xref: /linux/net/xfrm/xfrm_iptfs.c (revision dc33262be1fe43d0eb0b84fb58c6ed42e2f64a8c)
1 // SPDX-License-Identifier: GPL-2.0
2 /* xfrm_iptfs: IPTFS encapsulation support
3  *
4  * April 21 2022, Christian Hopps <chopps@labn.net>
5  *
6  * Copyright (c) 2022, LabN Consulting, L.L.C.
7  *
8  */
9 
10 #include <linux/kernel.h>
11 #include <linux/icmpv6.h>
12 #include <linux/skbuff_ref.h>
13 #include <net/gro.h>
14 #include <net/icmp.h>
15 #include <net/ip6_route.h>
16 #include <net/inet_ecn.h>
17 #include <net/xfrm.h>
18 
19 #include <crypto/aead.h>
20 
21 #include "xfrm_inout.h"
22 #include "trace_iptfs.h"
23 
24 /* IPTFS encap (header) values. */
25 #define IPTFS_SUBTYPE_BASIC 0
26 #define IPTFS_SUBTYPE_CC 1
27 
28 /* ----------------------------------------------- */
29 /* IP-TFS default SA values (tunnel egress/dir-in) */
30 /* ----------------------------------------------- */
31 
32 /**
33  * define IPTFS_DEFAULT_DROP_TIME_USECS - default drop time
34  *
35  * The default IPTFS drop time in microseconds. The drop time is the amount of
36  * time before a missing out-of-order IPTFS tunnel packet is considered lost.
37  * See also the reorder window.
38  *
39  * Default 1s.
40  */
41 #define IPTFS_DEFAULT_DROP_TIME_USECS 1000000
42 
43 /**
44  * define IPTFS_DEFAULT_REORDER_WINDOW - default reorder window size
45  *
46  * The default IPTFS reorder window size. The reorder window size dictates the
47  * maximum number of IPTFS tunnel packets in a sequence that may arrive out of
48  * order.
49  *
50  * Default 3. (tcp folks suggested)
51  */
52 #define IPTFS_DEFAULT_REORDER_WINDOW 3
53 
54 /* ------------------------------------------------ */
55 /* IPTFS default SA values (tunnel ingress/dir-out) */
56 /* ------------------------------------------------ */
57 
58 /**
59  * define IPTFS_DEFAULT_INIT_DELAY_USECS - default initial output delay
60  *
61  * The initial output delay is the amount of time prior to servicing the output
62  * queue after queueing the first packet on said queue. This applies anytime the
63  * output queue was previously empty.
64  *
65  * Default 0.
66  */
67 #define IPTFS_DEFAULT_INIT_DELAY_USECS 0
68 
69 /**
70  * define IPTFS_DEFAULT_MAX_QUEUE_SIZE - default max output queue size.
71  *
72  * The default IPTFS max output queue size in octets. The output queue is where
73  * received packets destined for output over an IPTFS tunnel are stored prior to
74  * being output in aggregated/fragmented form over the IPTFS tunnel.
75  *
76  * Default 1M.
77  */
78 #define IPTFS_DEFAULT_MAX_QUEUE_SIZE (1024 * 10240)
79 
80 /* Assumed: skb->head is cache aligned.
81  *
82  * L2 Header resv: Arrange for cacheline to start at skb->data - 16 to keep the
83  * to-be-pushed L2 header in the same cacheline as resulting `skb->data` (i.e.,
84  * the L3 header). If cacheline size is > 64 then skb->data + pushed L2 will all
85  * be in a single cacheline if we simply reserve 64 bytes.
86  *
87  * L3 Header resv: For L3+L2 headers (i.e., skb->data points at the IPTFS payload)
88  * we want `skb->data` to be cacheline aligned and all pushed L2L3 headers will
89  * be in their own cacheline[s]. 128 works for cachelins up to 128 bytes, for
90  * any larger cacheline sizes the pushed headers will simply share the cacheline
91  * with the start of the IPTFS payload (skb->data).
92  */
93 #define XFRM_IPTFS_MIN_L3HEADROOM 128
94 #define XFRM_IPTFS_MIN_L2HEADROOM (L1_CACHE_BYTES > 64 ? 64 : 64 + 16)
95 
96 /* Min to try to share outer iptfs skb data vs copying into new skb */
97 #define IPTFS_PKT_SHARE_MIN 129
98 
99 #define NSECS_IN_USEC 1000
100 
101 #define IPTFS_HRTIMER_MODE HRTIMER_MODE_REL_SOFT
102 
103 /**
104  * struct xfrm_iptfs_config - configuration for the IPTFS tunnel.
105  * @pkt_size: size of the outer IP packet. 0 to use interface and MTU discovery,
106  *	otherwise the user specified value.
107  * @max_queue_size: The maximum number of octets allowed to be queued to be sent
108  *	over the IPTFS SA. The queue size is measured as the size of all the
109  *	packets enqueued.
110  * @reorder_win_size: the number slots in the reorder window, thus the number of
111  *	packets that may arrive out of order.
112  * @dont_frag: true to inhibit fragmenting across IPTFS outer packets.
113  */
114 struct xfrm_iptfs_config {
115 	u32 pkt_size;	    /* outer_packet_size or 0 */
116 	u32 max_queue_size; /* octets */
117 	u16 reorder_win_size;
118 	u8 dont_frag : 1;
119 };
120 
121 struct skb_wseq {
122 	struct sk_buff *skb;
123 	u64 drop_time;
124 };
125 
126 /**
127  * struct xfrm_iptfs_data - mode specific xfrm state.
128  * @cfg: IPTFS tunnel config.
129  * @x: owning SA (xfrm_state).
130  * @queue: queued user packets to send.
131  * @queue_size: number of octets on queue (sum of packet sizes).
132  * @ecn_queue_size: octets above with ECN mark.
133  * @init_delay_ns: nanoseconds to wait to send initial IPTFS packet.
134  * @iptfs_timer: output timer.
135  * @iptfs_settime: time the output timer was set.
136  * @payload_mtu: max payload size.
137  * @w_seq_set: true after first seq received.
138  * @w_wantseq: waiting for this seq number as next to process (in order).
139  * @w_saved: the saved buf array (reorder window).
140  * @w_savedlen: the saved len (not size).
141  * @drop_lock: lock to protect reorder queue.
142  * @drop_timer: timer for considering next packet lost.
143  * @drop_time_ns: timer intervan in nanoseconds.
144  * @ra_newskb: new pkt being reassembled.
145  * @ra_wantseq: expected next sequence for reassembly.
146  * @ra_runt: last pkt bytes from very end of last skb.
147  * @ra_runtlen: size of ra_runt.
148  */
149 struct xfrm_iptfs_data {
150 	struct xfrm_iptfs_config cfg;
151 
152 	/* Ingress User Input */
153 	struct xfrm_state *x;	   /* owning state */
154 	struct sk_buff_head queue; /* output queue */
155 
156 	u32 queue_size;		    /* octets */
157 	u32 ecn_queue_size;	    /* octets above which ECN mark */
158 	u64 init_delay_ns;	    /* nanoseconds */
159 	struct hrtimer iptfs_timer; /* output timer */
160 	time64_t iptfs_settime;	    /* time timer was set */
161 	u32 payload_mtu;	    /* max payload size */
162 
163 	/* Tunnel input reordering */
164 	bool w_seq_set;		  /* true after first seq received */
165 	u64 w_wantseq;		  /* expected next sequence */
166 	struct skb_wseq *w_saved; /* the saved buf array */
167 	u32 w_savedlen;		  /* the saved len (not size) */
168 	spinlock_t drop_lock;
169 	struct hrtimer drop_timer;
170 	u64 drop_time_ns;
171 
172 	/* Tunnel input reassembly */
173 	struct sk_buff *ra_newskb; /* new pkt being reassembled */
174 	u64 ra_wantseq;		   /* expected next sequence */
175 	u8 ra_runt[6];		   /* last pkt bytes from last skb */
176 	u8 ra_runtlen;		   /* count of ra_runt */
177 };
178 
179 static u32 __iptfs_get_inner_mtu(struct xfrm_state *x, int outer_mtu);
180 static enum hrtimer_restart iptfs_delay_timer(struct hrtimer *me);
181 static enum hrtimer_restart iptfs_drop_timer(struct hrtimer *me);
182 
183 /* ================= */
184 /* Utility Functions */
185 /* ================= */
186 
187 #ifdef TRACEPOINTS_ENABLED
188 static u32 __trace_ip_proto(struct iphdr *iph)
189 {
190 	if (iph->version == 4)
191 		return iph->protocol;
192 	return ((struct ipv6hdr *)iph)->nexthdr;
193 }
194 
195 static u32 __trace_ip_proto_seq(struct iphdr *iph)
196 {
197 	void *nexthdr;
198 	u32 protocol = 0;
199 
200 	if (iph->version == 4) {
201 		nexthdr = (void *)(iph + 1);
202 		protocol = iph->protocol;
203 	} else if (iph->version == 6) {
204 		nexthdr = (void *)(((struct ipv6hdr *)(iph)) + 1);
205 		protocol = ((struct ipv6hdr *)(iph))->nexthdr;
206 	}
207 	switch (protocol) {
208 	case IPPROTO_ICMP:
209 		return ntohs(((struct icmphdr *)nexthdr)->un.echo.sequence);
210 	case IPPROTO_ICMPV6:
211 		return ntohs(((struct icmp6hdr *)nexthdr)->icmp6_sequence);
212 	case IPPROTO_TCP:
213 		return ntohl(((struct tcphdr *)nexthdr)->seq);
214 	case IPPROTO_UDP:
215 		return ntohs(((struct udphdr *)nexthdr)->source);
216 	default:
217 		return 0;
218 	}
219 }
220 #endif /*TRACEPOINTS_ENABLED*/
221 
222 static u64 __esp_seq(struct sk_buff *skb)
223 {
224 	u64 seq = ntohl(XFRM_SKB_CB(skb)->seq.input.low);
225 
226 	return seq | (u64)ntohl(XFRM_SKB_CB(skb)->seq.input.hi) << 32;
227 }
228 
229 /* ======================= */
230 /* IPTFS SK_BUFF Functions */
231 /* ======================= */
232 
233 /**
234  * iptfs_alloc_skb() - Allocate a new `skb`.
235  * @tpl: the skb to copy required meta-data from.
236  * @len: the linear length of the head data, zero is fine.
237  * @l3resv: true if skb reserve needs to support pushing L3 headers
238  *
239  * A new `skb` is allocated and required meta-data is copied from `tpl`, the
240  * head data is sized to `len` + reserved space set according to the @l3resv
241  * boolean.
242  *
243  * When @l3resv is false, resv is XFRM_IPTFS_MIN_L2HEADROOM which arranges for
244  * `skb->data - 16`  which is a good guess for good cache alignment (placing the
245  * to be pushed L2 header at the start of a cacheline.
246  *
247  * Otherwise, @l3resv is true and resv is set to the correct reserved space for
248  * dst->dev plus the calculated L3 overhead for the xfrm dst or
249  * XFRM_IPTFS_MIN_L3HEADROOM whichever is larger. This is then cache aligned so
250  * that all the headers will commonly fall in a cacheline when possible.
251  *
252  * l3resv=true is used on tunnel ingress (tx), because we need to reserve for
253  * the new IPTFS packet (i.e., L2+L3 headers). On tunnel egress (rx) the data
254  * being copied into the skb includes the user L3 headers already so we only
255  * need to reserve for L2.
256  *
257  * Return: the new skb or NULL.
258  */
259 static struct sk_buff *iptfs_alloc_skb(struct sk_buff *tpl, u32 len, bool l3resv)
260 {
261 	struct sk_buff *skb;
262 	u32 resv;
263 
264 	if (!l3resv) {
265 		resv = XFRM_IPTFS_MIN_L2HEADROOM;
266 	} else {
267 		struct dst_entry *dst = skb_dst(tpl);
268 
269 		resv = LL_RESERVED_SPACE(dst->dev) + dst->header_len;
270 		resv = max(resv, XFRM_IPTFS_MIN_L3HEADROOM);
271 		resv = L1_CACHE_ALIGN(resv);
272 	}
273 
274 	skb = alloc_skb(len + resv, GFP_ATOMIC | __GFP_NOWARN);
275 	if (!skb)
276 		return NULL;
277 
278 	skb_reserve(skb, resv);
279 
280 	if (!l3resv) {
281 		/* xfrm_input resume needs dev and xfrm ext from tunnel pkt */
282 		skb->dev = tpl->dev;
283 		__skb_ext_copy(skb, tpl);
284 	}
285 
286 	/* dropped by xfrm_input, used by xfrm_output */
287 	skb_dst_copy(skb, tpl);
288 
289 	return skb;
290 }
291 
292 /**
293  * iptfs_skb_head_to_frag() - initialize a skb_frag_t based on skb head data
294  * @skb: skb with the head data
295  * @frag: frag to initialize
296  */
297 static void iptfs_skb_head_to_frag(const struct sk_buff *skb, skb_frag_t *frag)
298 {
299 	struct page *page = virt_to_head_page(skb->data);
300 	unsigned char *addr = (unsigned char *)page_address(page);
301 
302 	skb_frag_fill_page_desc(frag, page, skb->data - addr, skb_headlen(skb));
303 }
304 
305 /**
306  * struct iptfs_skb_frag_walk - use to track a walk through fragments
307  * @fragi: current fragment index
308  * @past: length of data in fragments before @fragi
309  * @total: length of data in all fragments
310  * @nr_frags: number of fragments present in array
311  * @initial_offset: the value passed in to skb_prepare_frag_walk()
312  * @frags: the page fragments inc. room for head page
313  * @pp_recycle: copy of skb->pp_recycle
314  */
315 struct iptfs_skb_frag_walk {
316 	u32 fragi;
317 	u32 past;
318 	u32 total;
319 	u32 nr_frags;
320 	u32 initial_offset;
321 	skb_frag_t frags[MAX_SKB_FRAGS + 1];
322 	bool pp_recycle;
323 };
324 
325 /**
326  * iptfs_skb_prepare_frag_walk() - initialize a frag walk over an skb.
327  * @skb: the skb to walk.
328  * @initial_offset: start the walk @initial_offset into the skb.
329  * @walk: the walk to initialize
330  *
331  * Future calls to skb_add_frags() will expect the @offset value to be at
332  * least @initial_offset large.
333  */
334 static void iptfs_skb_prepare_frag_walk(struct sk_buff *skb, u32 initial_offset,
335 					struct iptfs_skb_frag_walk *walk)
336 {
337 	struct skb_shared_info *shinfo = skb_shinfo(skb);
338 	skb_frag_t *frag, *from;
339 	u32 i;
340 
341 	walk->initial_offset = initial_offset;
342 	walk->fragi = 0;
343 	walk->past = 0;
344 	walk->total = 0;
345 	walk->nr_frags = 0;
346 	walk->pp_recycle = skb->pp_recycle;
347 
348 	if (skb->head_frag) {
349 		if (initial_offset >= skb_headlen(skb)) {
350 			initial_offset -= skb_headlen(skb);
351 		} else {
352 			frag = &walk->frags[walk->nr_frags++];
353 			iptfs_skb_head_to_frag(skb, frag);
354 			frag->offset += initial_offset;
355 			frag->len -= initial_offset;
356 			walk->total += frag->len;
357 			initial_offset = 0;
358 		}
359 	} else {
360 		initial_offset -= skb_headlen(skb);
361 	}
362 
363 	for (i = 0; i < shinfo->nr_frags; i++) {
364 		from = &shinfo->frags[i];
365 		if (initial_offset >= from->len) {
366 			initial_offset -= from->len;
367 			continue;
368 		}
369 		frag = &walk->frags[walk->nr_frags++];
370 		*frag = *from;
371 		if (initial_offset) {
372 			frag->offset += initial_offset;
373 			frag->len -= initial_offset;
374 			initial_offset = 0;
375 		}
376 		walk->total += frag->len;
377 	}
378 }
379 
380 static u32 iptfs_skb_reset_frag_walk(struct iptfs_skb_frag_walk *walk,
381 				     u32 offset)
382 {
383 	/* Adjust offset to refer to internal walk values */
384 	offset -= walk->initial_offset;
385 
386 	/* Get to the correct fragment for offset */
387 	while (offset < walk->past) {
388 		walk->past -= walk->frags[--walk->fragi].len;
389 		if (offset >= walk->past)
390 			break;
391 	}
392 	while (offset >= walk->past + walk->frags[walk->fragi].len)
393 		walk->past += walk->frags[walk->fragi++].len;
394 
395 	/* offset now relative to this current frag */
396 	offset -= walk->past;
397 	return offset;
398 }
399 
400 /**
401  * iptfs_skb_can_add_frags() - check if ok to add frags from walk to skb
402  * @skb: skb to check for adding frags to
403  * @walk: the walk that will be used as source for frags.
404  * @offset: offset from beginning of original skb to start from.
405  * @len: amount of data to add frag references to in @skb.
406  *
407  * Return: true if ok to add frags.
408  */
409 static bool iptfs_skb_can_add_frags(const struct sk_buff *skb,
410 				    struct iptfs_skb_frag_walk *walk,
411 				    u32 offset, u32 len)
412 {
413 	struct skb_shared_info *shinfo = skb_shinfo(skb);
414 	u32 fragi, nr_frags, fraglen;
415 
416 	if (skb_has_frag_list(skb) || skb->pp_recycle != walk->pp_recycle)
417 		return false;
418 
419 	/* Reject an @offset that is at or beyond the end of the walk's data
420 	 * before calling iptfs_skb_reset_frag_walk(), whose fragment-advance
421 	 * loop is otherwise unbounded and would index past walk->frags[].
422 	 * This mirrors the guard already present in iptfs_skb_add_frags().
423 	 */
424 	if (!walk->nr_frags || offset >= walk->total + walk->initial_offset)
425 		return false;
426 
427 	/* Make offset relative to current frag after setting that */
428 	offset = iptfs_skb_reset_frag_walk(walk, offset);
429 
430 	/* Verify we have array space for the fragments we need to add */
431 	fragi = walk->fragi;
432 	nr_frags = shinfo->nr_frags;
433 	while (len && fragi < walk->nr_frags) {
434 		skb_frag_t *frag = &walk->frags[fragi];
435 
436 		fraglen = frag->len;
437 		if (offset) {
438 			fraglen -= offset;
439 			offset = 0;
440 		}
441 		if (++nr_frags > MAX_SKB_FRAGS)
442 			return false;
443 		if (len <= fraglen)
444 			return true;
445 		len -= fraglen;
446 		fragi++;
447 	}
448 	/* We may not copy all @len but what we have will fit. */
449 	return true;
450 }
451 
452 /**
453  * iptfs_skb_add_frags() - add a range of fragment references into an skb
454  * @skb: skb to add references into
455  * @walk: the walk to add referenced fragments from.
456  * @offset: offset from beginning of original skb to start from.
457  * @len: amount of data to add frag references to in @skb.
458  *
459  * iptfs_skb_can_add_frags() should be called before this function to verify
460  * that the destination @skb is compatible with the walk and has space in the
461  * array for the to be added frag references.
462  *
463  * Return: The number of bytes not added to @skb b/c we reached the end of the
464  * walk before adding all of @len.
465  */
466 static int iptfs_skb_add_frags(struct sk_buff *skb,
467 			       struct iptfs_skb_frag_walk *walk, u32 offset,
468 			       u32 len)
469 {
470 	struct skb_shared_info *shinfo = skb_shinfo(skb);
471 	u32 fraglen;
472 
473 	if (!walk->nr_frags || offset >= walk->total + walk->initial_offset)
474 		return len;
475 
476 	/* make offset relative to current frag after setting that */
477 	offset = iptfs_skb_reset_frag_walk(walk, offset);
478 
479 	while (len && walk->fragi < walk->nr_frags) {
480 		skb_frag_t *frag = &walk->frags[walk->fragi];
481 		skb_frag_t *tofrag = &shinfo->frags[shinfo->nr_frags];
482 
483 		*tofrag = *frag;
484 		if (offset) {
485 			tofrag->offset += offset;
486 			tofrag->len -= offset;
487 			offset = 0;
488 		}
489 		__skb_frag_ref(tofrag);
490 		shinfo->nr_frags++;
491 		shinfo->flags |= SKBFL_SHARED_FRAG;
492 
493 		/* see if we are done */
494 		fraglen = tofrag->len;
495 		if (len < fraglen) {
496 			tofrag->len = len;
497 			skb->len += len;
498 			skb->data_len += len;
499 			return 0;
500 		}
501 		/* advance to next source fragment */
502 		len -= fraglen;			/* careful, use dst bv_len */
503 		skb->len += fraglen;		/* careful, "   "    "     */
504 		skb->data_len += fraglen;	/* careful, "   "    "     */
505 		walk->past += frag->len;	/* careful, use src bv_len */
506 		walk->fragi++;
507 	}
508 	return len;
509 }
510 
511 /* ================================== */
512 /* IPTFS Trace Event Definitions      */
513 /* ================================== */
514 
515 #define CREATE_TRACE_POINTS
516 #include "trace_iptfs.h"
517 
518 /* ================================== */
519 /* IPTFS Receiving (egress) Functions */
520 /* ================================== */
521 
522 /**
523  * iptfs_pskb_add_frags() - Create and add frags into a new sk_buff.
524  * @tpl: template to create new skb from.
525  * @walk: The source for fragments to add.
526  * @off: The offset into @walk to add frags from, also used with @st and
527  *       @copy_len.
528  * @len: The length of data to add covering frags from @walk into @skb.
529  *       This must be <= @skblen.
530  * @st: The sequence state to copy from into the new head skb.
531  * @copy_len: Copy @copy_len bytes from @st at offset @off into the new skb
532  *            linear space.
533  *
534  * Create a new sk_buff `skb` using the template @tpl. Copy @copy_len bytes from
535  * @st into the new skb linear space, and then add shared fragments from the
536  * frag walk for the remaining @len of data (i.e., @len - @copy_len bytes).
537  *
538  * Return: The newly allocated sk_buff `skb` or NULL if an error occurs.
539  */
540 static struct sk_buff *
541 iptfs_pskb_add_frags(struct sk_buff *tpl, struct iptfs_skb_frag_walk *walk,
542 		     u32 off, u32 len, struct skb_seq_state *st, u32 copy_len)
543 {
544 	struct sk_buff *skb;
545 
546 	skb = iptfs_alloc_skb(tpl, copy_len, false);
547 	if (!skb)
548 		return NULL;
549 
550 	/* this should not normally be happening */
551 	if (!iptfs_skb_can_add_frags(skb, walk, off + copy_len,
552 				     len - copy_len)) {
553 		kfree_skb(skb);
554 		return NULL;
555 	}
556 
557 	if (copy_len &&
558 	    skb_copy_seq_read(st, off, skb_put(skb, copy_len), copy_len)) {
559 		XFRM_INC_STATS(dev_net(st->root_skb->dev),
560 			       LINUX_MIB_XFRMINERROR);
561 		kfree_skb(skb);
562 		return NULL;
563 	}
564 
565 	iptfs_skb_add_frags(skb, walk, off + copy_len, len - copy_len);
566 	return skb;
567 }
568 
569 /**
570  * iptfs_pskb_extract_seq() - Create and load data into a new sk_buff.
571  * @skblen: the total data size for `skb`.
572  * @st: The source for the rest of the data to copy into `skb`.
573  * @off: The offset into @st to copy data from.
574  * @len: The length of data to copy from @st into `skb`. This must be <=
575  *       @skblen.
576  *
577  * Create a new sk_buff `skb` with @skblen of packet data space. If non-zero,
578  * copy @rlen bytes of @runt into `skb`. Then using seq functions copy @len
579  * bytes from @st into `skb` starting from @off.
580  *
581  * It is an error for @len to be greater than the amount of data left in @st.
582  *
583  * Return: The newly allocated sk_buff `skb` or NULL if an error occurs.
584  */
585 static struct sk_buff *
586 iptfs_pskb_extract_seq(u32 skblen, struct skb_seq_state *st, u32 off, int len)
587 {
588 	struct sk_buff *skb = iptfs_alloc_skb(st->root_skb, skblen, false);
589 
590 	if (!skb)
591 		return NULL;
592 	if (skb_copy_seq_read(st, off, skb_put(skb, len), len)) {
593 		XFRM_INC_STATS(dev_net(st->root_skb->dev), LINUX_MIB_XFRMINERROR);
594 		kfree_skb(skb);
595 		return NULL;
596 	}
597 	return skb;
598 }
599 
600 /**
601  * iptfs_input_save_runt() - save data in xtfs runt space.
602  * @xtfs: xtfs state
603  * @seq: the current sequence
604  * @buf: packet data
605  * @len: length of packet data
606  *
607  * Save the small (`len`) start of a fragmented packet in `buf` in the xtfs data
608  * runt space.
609  */
610 static void iptfs_input_save_runt(struct xfrm_iptfs_data *xtfs, u64 seq,
611 				  u8 *buf, int len)
612 {
613 	memcpy(xtfs->ra_runt, buf, len);
614 
615 	xtfs->ra_runtlen = len;
616 	xtfs->ra_wantseq = seq + 1;
617 }
618 
619 /**
620  * __iptfs_iphlen() - return the v4/v6 header length using packet data.
621  * @data: pointer at octet with version nibble
622  *
623  * The version data has been checked to be valid (i.e., either 4 or 6).
624  *
625  * Return: the IP header size based on the IP version.
626  */
627 static u32 __iptfs_iphlen(u8 *data)
628 {
629 	struct iphdr *iph = (struct iphdr *)data;
630 
631 	if (iph->version == 0x4)
632 		return sizeof(*iph);
633 	return sizeof(struct ipv6hdr);
634 }
635 
636 /**
637  * __iptfs_iplen() - return the v4/v6 length using packet data.
638  * @data: pointer to ip (v4/v6) packet header
639  *
640  * Grab the IPv4 or IPv6 length value in the start of the inner packet header
641  * pointed to by `data`. Assumes data len is enough for the length field only.
642  *
643  * The version data has been checked to be valid (i.e., either 4 or 6).
644  *
645  * Return: the length value.
646  */
647 static u32 __iptfs_iplen(u8 *data)
648 {
649 	struct iphdr *iph = (struct iphdr *)data;
650 
651 	if (iph->version == 0x4)
652 		return ntohs(iph->tot_len);
653 	return ntohs(((struct ipv6hdr *)iph)->payload_len) +
654 		sizeof(struct ipv6hdr);
655 }
656 
657 /**
658  * iptfs_complete_inner_skb() - finish preparing the inner packet for gro recv.
659  * @x: xfrm state
660  * @skb: the inner packet
661  *
662  * Finish the standard xfrm processing on the inner packet prior to sending back
663  * through gro_cells_receive. We do this separately b/c we are building a list
664  * of packets in the hopes that one day a list will be taken by
665  * xfrm_input.
666  */
667 static void iptfs_complete_inner_skb(struct xfrm_state *x, struct sk_buff *skb)
668 {
669 	skb_reset_network_header(skb);
670 
671 	/* The packet is going back through gro_cells_receive no need to
672 	 * set this.
673 	 */
674 	skb_reset_transport_header(skb);
675 
676 	/* Packet already has checksum value set. */
677 	skb->ip_summed = CHECKSUM_NONE;
678 
679 	/* Our skb will contain the header data copied when this outer packet
680 	 * which contained the start of this inner packet. This is true
681 	 * when we allocate a new skb as well as when we reuse the existing skb.
682 	 */
683 	if (ip_hdr(skb)->version == 0x4) {
684 		struct iphdr *iph = ip_hdr(skb);
685 
686 		if (x->props.flags & XFRM_STATE_DECAP_DSCP)
687 			ipv4_copy_dscp(XFRM_MODE_SKB_CB(skb)->tos, iph);
688 		if (!(x->props.flags & XFRM_STATE_NOECN))
689 			if (INET_ECN_is_ce(XFRM_MODE_SKB_CB(skb)->tos))
690 				IP_ECN_set_ce(iph);
691 
692 		skb->protocol = htons(ETH_P_IP);
693 	} else {
694 		struct ipv6hdr *iph = ipv6_hdr(skb);
695 
696 		if (x->props.flags & XFRM_STATE_DECAP_DSCP)
697 			ipv6_copy_dscp(XFRM_MODE_SKB_CB(skb)->tos, iph);
698 		if (!(x->props.flags & XFRM_STATE_NOECN))
699 			if (INET_ECN_is_ce(XFRM_MODE_SKB_CB(skb)->tos))
700 				IP6_ECN_set_ce(skb, iph);
701 
702 		skb->protocol = htons(ETH_P_IPV6);
703 	}
704 }
705 
706 static void __iptfs_reassem_done(struct xfrm_iptfs_data *xtfs, bool free)
707 {
708 	assert_spin_locked(&xtfs->drop_lock);
709 
710 	/* We don't care if it works locking takes care of things */
711 	hrtimer_try_to_cancel(&xtfs->drop_timer);
712 	if (free)
713 		kfree_skb(xtfs->ra_newskb);
714 	xtfs->ra_newskb = NULL;
715 }
716 
717 /**
718  * iptfs_reassem_abort() - In-progress packet is aborted free the state.
719  * @xtfs: xtfs state
720  */
721 static void iptfs_reassem_abort(struct xfrm_iptfs_data *xtfs)
722 {
723 	__iptfs_reassem_done(xtfs, true);
724 }
725 
726 /**
727  * iptfs_reassem_done() - In-progress packet is complete, clear the state.
728  * @xtfs: xtfs state
729  */
730 static void iptfs_reassem_done(struct xfrm_iptfs_data *xtfs)
731 {
732 	__iptfs_reassem_done(xtfs, false);
733 }
734 
735 /**
736  * iptfs_reassem_cont() - Continue the reassembly of an inner packets.
737  * @xtfs: xtfs state
738  * @seq: sequence of current packet
739  * @st: seq read stat for current packet
740  * @skb: current packet
741  * @data: offset into sequential packet data
742  * @blkoff: packet blkoff value
743  * @list: list of skbs to enqueue completed packet on
744  *
745  * Process an IPTFS payload that has a non-zero `blkoff` or when we are
746  * expecting the continuation b/c we have a runt or in-progress packet.
747  *
748  * Return: the new data offset to continue processing from.
749  */
750 static u32 iptfs_reassem_cont(struct xfrm_iptfs_data *xtfs, u64 seq,
751 			      struct skb_seq_state *st, struct sk_buff *skb,
752 			      u32 data, u32 blkoff, struct list_head *list)
753 {
754 	struct iptfs_skb_frag_walk _fragwalk;
755 	struct iptfs_skb_frag_walk *fragwalk = NULL;
756 	struct sk_buff *newskb = xtfs->ra_newskb;
757 	u32 remaining = skb->len - data;
758 	u32 runtlen = xtfs->ra_runtlen;
759 	u32 copylen, fraglen, ipremain, iphlen, iphremain, rrem;
760 
761 	/* Handle packet fragment we aren't expecting */
762 	if (!runtlen && !xtfs->ra_newskb)
763 		return data + min(blkoff, remaining);
764 
765 	/* Important to remember that input to this function is an ordered
766 	 * packet stream (unless the user disabled the reorder window). Thus if
767 	 * we are waiting for, and expecting the next packet so we can continue
768 	 * assembly, a newer sequence number indicates older ones are not coming
769 	 * (or if they do should be ignored). Technically we can receive older
770 	 * ones when the reorder window is disabled; however, the user should
771 	 * have disabled fragmentation in this case, and regardless we don't
772 	 * deal with it.
773 	 *
774 	 * blkoff could be zero if the stream is messed up (or it's an all pad
775 	 * insertion) be careful to handle that case in each of the below
776 	 */
777 
778 	/* Too old case: This can happen when the reorder window is disabled so
779 	 * ordering isn't actually guaranteed.
780 	 */
781 	if (seq < xtfs->ra_wantseq)
782 		return data + remaining;
783 
784 	/* Too new case: We missed what we wanted cleanup. */
785 	if (seq > xtfs->ra_wantseq) {
786 		XFRM_INC_STATS(xs_net(xtfs->x), LINUX_MIB_XFRMINIPTFSERROR);
787 		goto abandon;
788 	}
789 
790 	if (blkoff == 0) {
791 		if ((*skb->data & 0xF0) != 0) {
792 			XFRM_INC_STATS(xs_net(xtfs->x),
793 				       LINUX_MIB_XFRMINIPTFSERROR);
794 			goto abandon;
795 		}
796 		/* Handle all pad case, advance expected sequence number.
797 		 * (RFC 9347 S2.2.3)
798 		 */
799 		xtfs->ra_wantseq++;
800 		/* will end parsing */
801 		return data + remaining;
802 	}
803 
804 	if (runtlen) {
805 		/* Regardless of what happens we're done with the runt */
806 		xtfs->ra_runtlen = 0;
807 
808 		/* The start of this inner packet was at the very end of the last
809 		 * iptfs payload which didn't include enough for the ip header
810 		 * length field. We must have *at least* that now.
811 		 */
812 		rrem = sizeof(xtfs->ra_runt) - runtlen;
813 		if (remaining < rrem || blkoff < rrem) {
814 			XFRM_INC_STATS(xs_net(xtfs->x),
815 				       LINUX_MIB_XFRMINIPTFSERROR);
816 			goto abandon;
817 		}
818 
819 		/* fill in the runt data */
820 		if (skb_copy_seq_read(st, data, &xtfs->ra_runt[runtlen],
821 				      rrem)) {
822 			XFRM_INC_STATS(xs_net(xtfs->x),
823 				       LINUX_MIB_XFRMINBUFFERERROR);
824 			goto abandon;
825 		}
826 
827 		/* We have enough data to get the ip length value now,
828 		 * allocate an in progress skb
829 		 */
830 		ipremain = __iptfs_iplen(xtfs->ra_runt);
831 		if (ipremain < __iptfs_iphlen(xtfs->ra_runt)) {
832 			/* length has to be at least the IP header size */
833 			XFRM_INC_STATS(xs_net(xtfs->x),
834 				       LINUX_MIB_XFRMINIPTFSERROR);
835 			goto abandon;
836 		}
837 
838 		/* For the runt case we don't attempt sharing currently. NOTE:
839 		 * Currently, this IPTFS implementation will not create runts.
840 		 */
841 
842 		newskb = iptfs_alloc_skb(skb, ipremain, false);
843 		if (!newskb) {
844 			XFRM_INC_STATS(xs_net(xtfs->x), LINUX_MIB_XFRMINERROR);
845 			goto abandon;
846 		}
847 		xtfs->ra_newskb = newskb;
848 
849 		/* Copy the runt data into the buffer, but leave data
850 		 * pointers the same as normal non-runt case. The extra `rrem`
851 		 * recopied bytes are basically cacheline free. Allows using
852 		 * same logic below to complete.
853 		 */
854 		memcpy(skb_put(newskb, runtlen), xtfs->ra_runt,
855 		       sizeof(xtfs->ra_runt));
856 	}
857 
858 	/* Continue reassembling the packet */
859 	ipremain = __iptfs_iplen(newskb->data);
860 	iphlen = __iptfs_iphlen(newskb->data);
861 
862 	ipremain -= newskb->len;
863 	if (blkoff < ipremain) {
864 		/* Corrupt data, we don't have enough to complete the packet */
865 		XFRM_INC_STATS(xs_net(xtfs->x), LINUX_MIB_XFRMINIPTFSERROR);
866 		goto abandon;
867 	}
868 
869 	/* We want the IP header in linear space */
870 	if (newskb->len < iphlen) {
871 		iphremain = iphlen - newskb->len;
872 		if (blkoff < iphremain) {
873 			XFRM_INC_STATS(xs_net(xtfs->x),
874 				       LINUX_MIB_XFRMINIPTFSERROR);
875 			goto abandon;
876 		}
877 		fraglen = min(blkoff, remaining);
878 		copylen = min(fraglen, iphremain);
879 		if (skb_copy_seq_read(st, data, skb_put(newskb, copylen),
880 				      copylen)) {
881 			XFRM_INC_STATS(xs_net(xtfs->x),
882 				       LINUX_MIB_XFRMINBUFFERERROR);
883 			goto abandon;
884 		}
885 		/* this is a silly condition that might occur anyway */
886 		if (copylen < iphremain) {
887 			xtfs->ra_wantseq++;
888 			return data + fraglen;
889 		}
890 		/* update data and things derived from it */
891 		data += copylen;
892 		blkoff -= copylen;
893 		remaining -= copylen;
894 		ipremain -= copylen;
895 	}
896 
897 	fraglen = min(blkoff, remaining);
898 	copylen = min(fraglen, ipremain);
899 
900 	/* If we may have the opportunity to share prepare a fragwalk. */
901 	if (!skb_has_frag_list(skb) && !skb_has_frag_list(newskb) &&
902 	    (skb->head_frag || skb->len == skb->data_len) &&
903 	    skb->pp_recycle == newskb->pp_recycle) {
904 		fragwalk = &_fragwalk;
905 		iptfs_skb_prepare_frag_walk(skb, data, fragwalk);
906 	}
907 
908 	/* Try share then copy. */
909 	if (fragwalk &&
910 	    iptfs_skb_can_add_frags(newskb, fragwalk, data, copylen)) {
911 		iptfs_skb_add_frags(newskb, fragwalk, data, copylen);
912 	} else {
913 		if (skb_linearize(newskb)) {
914 			XFRM_INC_STATS(xs_net(xtfs->x),
915 				       LINUX_MIB_XFRMINBUFFERERROR);
916 			goto abandon;
917 		}
918 
919 		/* copy fragment data into newskb */
920 		if (skb_copy_seq_read(st, data, skb_put(newskb, copylen),
921 				      copylen)) {
922 			XFRM_INC_STATS(xs_net(xtfs->x),
923 				       LINUX_MIB_XFRMINBUFFERERROR);
924 			goto abandon;
925 		}
926 	}
927 
928 	if (copylen < ipremain) {
929 		xtfs->ra_wantseq++;
930 	} else {
931 		/* We are done with packet reassembly! */
932 		iptfs_reassem_done(xtfs);
933 		iptfs_complete_inner_skb(xtfs->x, newskb);
934 		list_add_tail(&newskb->list, list);
935 	}
936 
937 	/* will continue on to new data block or end */
938 	return data + fraglen;
939 
940 abandon:
941 	if (xtfs->ra_newskb) {
942 		iptfs_reassem_abort(xtfs);
943 	} else {
944 		xtfs->ra_runtlen = 0;
945 		xtfs->ra_wantseq = 0;
946 	}
947 	/* skip past fragment, maybe to end */
948 	return data + min(blkoff, remaining);
949 }
950 
951 static bool __input_process_payload(struct xfrm_state *x, u32 data,
952 				    struct skb_seq_state *skbseq,
953 				    struct list_head *sublist)
954 {
955 	u8 hbytes[sizeof(struct ipv6hdr)];
956 	struct iptfs_skb_frag_walk _fragwalk;
957 	struct iptfs_skb_frag_walk *fragwalk = NULL;
958 	struct sk_buff *defer, *first_skb, *next, *skb;
959 	const unsigned char *old_mac;
960 	struct xfrm_iptfs_data *xtfs;
961 	struct iphdr *iph;
962 	struct net *net;
963 	u32 first_iplen, iphlen, iplen, remaining, tail;
964 	u32 capturelen;
965 	u64 seq;
966 	bool first_skb_partial = false;
967 
968 	xtfs = x->mode_data;
969 	net = xs_net(x);
970 	skb = skbseq->root_skb;
971 	first_skb = NULL;
972 	defer = NULL;
973 
974 	seq = __esp_seq(skb);
975 
976 	/* Save the old mac header if set */
977 	old_mac = skb_mac_header_was_set(skb) ? skb_mac_header(skb) : NULL;
978 
979 	/* New packets */
980 
981 	tail = skb->len;
982 	while (data < tail) {
983 		__be16 protocol = 0;
984 
985 		/* Gather information on the next data block.
986 		 * `data` points to the start of the data block.
987 		 */
988 		remaining = tail - data;
989 
990 		/* try and copy enough bytes to read length from ipv4/ipv6 */
991 		iphlen = min_t(u32, remaining, 6);
992 		if (skb_copy_seq_read(skbseq, data, hbytes, iphlen)) {
993 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINBUFFERERROR);
994 			goto done;
995 		}
996 
997 		iph = (struct iphdr *)hbytes;
998 		if (iph->version == 0x4) {
999 			/* must have at least tot_len field present */
1000 			if (remaining < 4) {
1001 				/* save the bytes we have, advance data and exit */
1002 				iptfs_input_save_runt(xtfs, seq, hbytes,
1003 						      remaining);
1004 				data += remaining;
1005 				break;
1006 			}
1007 
1008 			iplen = be16_to_cpu(iph->tot_len);
1009 			iphlen = iph->ihl << 2;
1010 			if (iplen < iphlen || iphlen < sizeof(*iph)) {
1011 				XFRM_INC_STATS(net,
1012 					       LINUX_MIB_XFRMINHDRERROR);
1013 				goto done;
1014 			}
1015 			protocol = cpu_to_be16(ETH_P_IP);
1016 			XFRM_MODE_SKB_CB(skbseq->root_skb)->tos = iph->tos;
1017 		} else if (iph->version == 0x6) {
1018 			/* must have at least payload_len field present */
1019 			if (remaining < 6) {
1020 				/* save the bytes we have, advance data and exit */
1021 				iptfs_input_save_runt(xtfs, seq, hbytes,
1022 						      remaining);
1023 				data += remaining;
1024 				break;
1025 			}
1026 
1027 			iplen = be16_to_cpu(((struct ipv6hdr *)hbytes)->payload_len);
1028 			iplen += sizeof(struct ipv6hdr);
1029 			iphlen = sizeof(struct ipv6hdr);
1030 			protocol = cpu_to_be16(ETH_P_IPV6);
1031 			XFRM_MODE_SKB_CB(skbseq->root_skb)->tos =
1032 				ipv6_get_dsfield((struct ipv6hdr *)iph);
1033 		} else if (iph->version == 0x0) {
1034 			/* pad */
1035 			data = tail;
1036 			break;
1037 		} else {
1038 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINBUFFERERROR);
1039 			goto done;
1040 		}
1041 
1042 		if (unlikely(skbseq->stepped_offset)) {
1043 			/* We need to reset our seq read, it can't backup at
1044 			 * this point.
1045 			 */
1046 			struct sk_buff *save = skbseq->root_skb;
1047 
1048 			skb_abort_seq_read(skbseq);
1049 			skb_prepare_seq_read(save, data, tail, skbseq);
1050 		}
1051 
1052 		if (first_skb) {
1053 			skb = NULL;
1054 		} else {
1055 			first_skb = skb;
1056 			first_iplen = iplen;
1057 			fragwalk = NULL;
1058 
1059 			/* We are going to skip over `data` bytes to reach the
1060 			 * start of the IP header of `iphlen` len for `iplen`
1061 			 * inner packet.
1062 			 */
1063 
1064 			if (skb_has_frag_list(skb)) {
1065 				defer = skb;
1066 				skb = NULL;
1067 			} else if (data + iphlen <= skb_headlen(skb) &&
1068 				   /* make sure our header is 32-bit aligned? */
1069 				   /* ((uintptr_t)(skb->data + data) & 0x3) == 0 && */
1070 				   skb_tailroom(skb) + tail - data >= iplen) {
1071 				/* Reuse the received skb.
1072 				 *
1073 				 * We have enough headlen to pull past any
1074 				 * initial fragment data, leaving at least the
1075 				 * IP header in the linear buffer space.
1076 				 *
1077 				 * For linear buffer space we only require that
1078 				 * linear buffer space is large enough to
1079 				 * eventually hold the entire reassembled
1080 				 * packet (by including tailroom in the check).
1081 				 *
1082 				 * For non-linear tailroom is 0 and so we only
1083 				 * re-use if the entire packet is present
1084 				 * already.
1085 				 *
1086 				 * NOTE: there are many more options for
1087 				 * sharing, KISS for now. Also, this can produce
1088 				 * skb's with the IP header unaligned to 32
1089 				 * bits. If that ends up being a problem then a
1090 				 * check should be added to the conditional
1091 				 * above that the header lies on a 32-bit
1092 				 * boundary as well.
1093 				 */
1094 				skb_pull(skb, data);
1095 
1096 				/* our range just changed */
1097 				data = 0;
1098 				tail = skb->len;
1099 				remaining = skb->len;
1100 
1101 				skb->protocol = protocol;
1102 				skb_mac_header_rebuild(skb);
1103 				if (skb->mac_len)
1104 					eth_hdr(skb)->h_proto = skb->protocol;
1105 
1106 				/* all pointers could be changed now reset walk */
1107 				skb_abort_seq_read(skbseq);
1108 				skb_prepare_seq_read(skb, data, tail, skbseq);
1109 			} else if (skb->head_frag &&
1110 				   /* We have the IP header right now */
1111 				   remaining >= iphlen) {
1112 				fragwalk = &_fragwalk;
1113 				iptfs_skb_prepare_frag_walk(skb, data, fragwalk);
1114 				defer = skb;
1115 				skb = NULL;
1116 			} else {
1117 				/* We couldn't reuse the input skb so allocate a
1118 				 * new one.
1119 				 */
1120 				defer = skb;
1121 				skb = NULL;
1122 			}
1123 
1124 			/* Don't trim `first_skb` until the end as we are
1125 			 * walking that data now.
1126 			 */
1127 		}
1128 
1129 		capturelen = min(iplen, remaining);
1130 		if (!skb) {
1131 			if (!fragwalk ||
1132 			    /* Large enough to be worth sharing */
1133 			    iplen < IPTFS_PKT_SHARE_MIN ||
1134 			    /* Have IP header + some data to share. */
1135 			    capturelen <= iphlen ||
1136 			    /* Try creating skb and adding frags */
1137 			    !(skb = iptfs_pskb_add_frags(first_skb, fragwalk,
1138 							 data, capturelen,
1139 							 skbseq, iphlen))) {
1140 				skb = iptfs_pskb_extract_seq(iplen, skbseq, data, capturelen);
1141 			}
1142 			if (!skb) {
1143 				/* skip to next packet or done */
1144 				data += capturelen;
1145 				continue;
1146 			}
1147 
1148 			skb->protocol = protocol;
1149 			if (old_mac) {
1150 				/* rebuild the mac header */
1151 				skb_set_mac_header(skb, -first_skb->mac_len);
1152 				memcpy(skb_mac_header(skb), old_mac, first_skb->mac_len);
1153 				eth_hdr(skb)->h_proto = skb->protocol;
1154 			}
1155 		}
1156 
1157 		data += capturelen;
1158 
1159 		if (skb->len < iplen) {
1160 			/* Start reassembly */
1161 			spin_lock(&xtfs->drop_lock);
1162 
1163 			xtfs->ra_newskb = skb;
1164 			xtfs->ra_wantseq = seq + 1;
1165 			if (!hrtimer_is_queued(&xtfs->drop_timer)) {
1166 				/* softirq blocked lest the timer fire and interrupt us */
1167 				hrtimer_start(&xtfs->drop_timer,
1168 					      xtfs->drop_time_ns,
1169 					      IPTFS_HRTIMER_MODE);
1170 			}
1171 
1172 			spin_unlock(&xtfs->drop_lock);
1173 
1174 			first_skb_partial = (first_skb == skb);
1175 			break;
1176 		}
1177 
1178 		iptfs_complete_inner_skb(x, skb);
1179 		list_add_tail(&skb->list, sublist);
1180 	}
1181 
1182 	if (data != tail)
1183 		/* this should not happen from the above code */
1184 		XFRM_INC_STATS(net, LINUX_MIB_XFRMINIPTFSERROR);
1185 
1186 	if (first_skb && first_iplen && !defer && !first_skb_partial) {
1187 		/* first_skb is queued b/c !defer and not partial */
1188 		if (pskb_trim(first_skb, first_iplen)) {
1189 			/* error trimming */
1190 			list_del(&first_skb->list);
1191 			defer = first_skb;
1192 		}
1193 		first_skb->ip_summed = CHECKSUM_NONE;
1194 	}
1195 
1196 	/* Send the packets! */
1197 	list_for_each_entry_safe(skb, next, sublist, list) {
1198 		skb_list_del_init(skb);
1199 		if (xfrm_input(skb, 0, 0, -2))
1200 			kfree_skb(skb);
1201 	}
1202 done:
1203 	skb = skbseq->root_skb;
1204 	skb_abort_seq_read(skbseq);
1205 
1206 	if (defer) {
1207 		consume_skb(defer);
1208 	} else if (!first_skb) {
1209 		/* skb is the original passed in skb, but we didn't get far
1210 		 * enough to process it as the first_skb, if we had it would
1211 		 * either be save in ra_newskb, trimmed and sent on as an skb or
1212 		 * placed in defer to be freed.
1213 		 */
1214 		kfree_skb(skb);
1215 	}
1216 	return true;
1217 }
1218 
1219 /**
1220  * iptfs_input_ordered() - handle next in order IPTFS payload.
1221  * @x: xfrm state
1222  * @skb: current packet
1223  *
1224  * Process the IPTFS payload in `skb` and consume it afterwards.
1225  */
1226 static void iptfs_input_ordered(struct xfrm_state *x, struct sk_buff *skb)
1227 {
1228 	struct ip_iptfs_cc_hdr iptcch;
1229 	struct skb_seq_state skbseq;
1230 	struct list_head sublist; /* rename this it's just a list */
1231 	struct xfrm_iptfs_data *xtfs;
1232 	struct ip_iptfs_hdr *ipth;
1233 	struct net *net;
1234 	u32 blkoff, data, remaining;
1235 	bool consumed = false;
1236 	u64 seq;
1237 
1238 	xtfs = x->mode_data;
1239 	net = xs_net(x);
1240 
1241 	seq = __esp_seq(skb);
1242 
1243 	/* Large enough to hold both types of header */
1244 	ipth = (struct ip_iptfs_hdr *)&iptcch;
1245 
1246 	skb_prepare_seq_read(skb, 0, skb->len, &skbseq);
1247 
1248 	/* Get the IPTFS header and validate it */
1249 
1250 	if (skb_copy_seq_read(&skbseq, 0, ipth, sizeof(*ipth))) {
1251 		XFRM_INC_STATS(net, LINUX_MIB_XFRMINBUFFERERROR);
1252 		goto done;
1253 	}
1254 	data = sizeof(*ipth);
1255 
1256 	trace_iptfs_egress_recv(skb, xtfs, be16_to_cpu(ipth->block_offset));
1257 
1258 	/* Set data past the basic header */
1259 	if (ipth->subtype == IPTFS_SUBTYPE_CC) {
1260 		/* Copy the rest of the CC header */
1261 		remaining = sizeof(iptcch) - sizeof(*ipth);
1262 		if (skb_copy_seq_read(&skbseq, data, ipth + 1, remaining)) {
1263 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINBUFFERERROR);
1264 			goto done;
1265 		}
1266 		data += remaining;
1267 	} else if (ipth->subtype != IPTFS_SUBTYPE_BASIC) {
1268 		XFRM_INC_STATS(net, LINUX_MIB_XFRMINHDRERROR);
1269 		goto done;
1270 	}
1271 
1272 	if (ipth->flags != 0) {
1273 		XFRM_INC_STATS(net, LINUX_MIB_XFRMINHDRERROR);
1274 		goto done;
1275 	}
1276 
1277 	INIT_LIST_HEAD(&sublist);
1278 
1279 	/* Handle fragment at start of payload, and/or waiting reassembly. */
1280 
1281 	blkoff = ntohs(ipth->block_offset);
1282 	/* check before locking i.e., maybe */
1283 	if (blkoff || xtfs->ra_runtlen || xtfs->ra_newskb) {
1284 		spin_lock(&xtfs->drop_lock);
1285 
1286 		/* check again after lock */
1287 		if (blkoff || xtfs->ra_runtlen || xtfs->ra_newskb) {
1288 			data = iptfs_reassem_cont(xtfs, seq, &skbseq, skb, data,
1289 						  blkoff, &sublist);
1290 		}
1291 
1292 		spin_unlock(&xtfs->drop_lock);
1293 	}
1294 
1295 	/* New packets */
1296 	consumed = __input_process_payload(x, data, &skbseq, &sublist);
1297 done:
1298 	if (!consumed) {
1299 		skb = skbseq.root_skb;
1300 		skb_abort_seq_read(&skbseq);
1301 		kfree_skb(skb);
1302 	}
1303 }
1304 
1305 /* ------------------------------- */
1306 /* Input (Egress) Re-ordering Code */
1307 /* ------------------------------- */
1308 
1309 static void __vec_shift(struct xfrm_iptfs_data *xtfs, u32 shift)
1310 {
1311 	u32 savedlen = xtfs->w_savedlen;
1312 
1313 	if (shift > savedlen)
1314 		shift = savedlen;
1315 	if (shift != savedlen)
1316 		memcpy(xtfs->w_saved, xtfs->w_saved + shift,
1317 		       (savedlen - shift) * sizeof(*xtfs->w_saved));
1318 	memset(xtfs->w_saved + savedlen - shift, 0,
1319 	       shift * sizeof(*xtfs->w_saved));
1320 	xtfs->w_savedlen -= shift;
1321 }
1322 
1323 static void __reorder_past(struct xfrm_iptfs_data *xtfs, struct sk_buff *inskb,
1324 			   struct list_head *freelist)
1325 {
1326 	list_add_tail(&inskb->list, freelist);
1327 }
1328 
1329 static u32 __reorder_drop(struct xfrm_iptfs_data *xtfs, struct list_head *list)
1330 
1331 {
1332 	struct skb_wseq *s, *se;
1333 	const u32 savedlen = xtfs->w_savedlen;
1334 	time64_t now = ktime_get_raw_fast_ns();
1335 	u32 count = 0;
1336 	u32 scount = 0;
1337 
1338 	if (xtfs->w_saved[0].drop_time > now)
1339 		goto set_timer;
1340 
1341 	++xtfs->w_wantseq;
1342 
1343 	/* Keep flushing packets until we reach a drop time greater than now. */
1344 	s = xtfs->w_saved;
1345 	se = s + savedlen;
1346 	do {
1347 		/* Walking past empty slots until we reach a packet */
1348 		for (; s < se && !s->skb; s++) {
1349 			if (s->drop_time > now)
1350 				goto outerdone;
1351 		}
1352 		/* Sending packets until we hit another empty slot. */
1353 		for (; s < se && s->skb; scount++, s++)
1354 			list_add_tail(&s->skb->list, list);
1355 	} while (s < se);
1356 outerdone:
1357 
1358 	count = s - xtfs->w_saved;
1359 	if (count) {
1360 		xtfs->w_wantseq += count;
1361 
1362 		/* Shift handled slots plus final empty slot into slot 0. */
1363 		__vec_shift(xtfs, count);
1364 	}
1365 
1366 	if (xtfs->w_savedlen) {
1367 set_timer:
1368 		/* Drifting is OK */
1369 		hrtimer_start(&xtfs->drop_timer,
1370 			      xtfs->w_saved[0].drop_time - now,
1371 			      IPTFS_HRTIMER_MODE);
1372 	}
1373 	return scount;
1374 }
1375 
1376 static void __reorder_this(struct xfrm_iptfs_data *xtfs, struct sk_buff *inskb,
1377 			   struct list_head *list)
1378 {
1379 	struct skb_wseq *s, *se;
1380 	const u32 savedlen = xtfs->w_savedlen;
1381 	u32 count = 0;
1382 
1383 	/* Got what we wanted. */
1384 	list_add_tail(&inskb->list, list);
1385 	++xtfs->w_wantseq;
1386 	if (!savedlen)
1387 		return;
1388 
1389 	/* Flush remaining consecutive packets. */
1390 
1391 	/* Keep sending until we hit another missed pkt. */
1392 	for (s = xtfs->w_saved, se = s + savedlen; s < se && s->skb; s++)
1393 		list_add_tail(&s->skb->list, list);
1394 	count = s - xtfs->w_saved;
1395 	if (count)
1396 		xtfs->w_wantseq += count;
1397 
1398 	/* Shift handled slots plus final empty slot into slot 0. */
1399 	__vec_shift(xtfs, count + 1);
1400 }
1401 
1402 /* Set the slot's drop time and all the empty slots below it until reaching a
1403  * filled slot which will already be set.
1404  */
1405 static void iptfs_set_window_drop_times(struct xfrm_iptfs_data *xtfs, int index)
1406 {
1407 	const u32 savedlen = xtfs->w_savedlen;
1408 	struct skb_wseq *s = xtfs->w_saved;
1409 	time64_t drop_time;
1410 
1411 	assert_spin_locked(&xtfs->drop_lock);
1412 
1413 	if (savedlen > index + 1) {
1414 		/* we are below another, our drop time and the timer are already set */
1415 		return;
1416 	}
1417 	/* we are the most future so get a new drop time. */
1418 	drop_time = ktime_get_raw_fast_ns();
1419 	drop_time += xtfs->drop_time_ns;
1420 
1421 	/* Walk back through the array setting drop times as we go */
1422 	s[index].drop_time = drop_time;
1423 	while (index-- > 0 && !s[index].skb)
1424 		s[index].drop_time = drop_time;
1425 
1426 	/* If we walked all the way back, schedule the drop timer if needed */
1427 	if (index == -1 && !hrtimer_is_queued(&xtfs->drop_timer))
1428 		hrtimer_start(&xtfs->drop_timer, xtfs->drop_time_ns,
1429 			      IPTFS_HRTIMER_MODE);
1430 }
1431 
1432 static void __reorder_future_fits(struct xfrm_iptfs_data *xtfs,
1433 				  struct sk_buff *inskb,
1434 				  struct list_head *freelist)
1435 {
1436 	const u64 inseq = __esp_seq(inskb);
1437 	const u64 wantseq = xtfs->w_wantseq;
1438 	const u64 distance = inseq - wantseq;
1439 	const u32 savedlen = xtfs->w_savedlen;
1440 	const u32 index = distance - 1;
1441 
1442 	/* Handle future sequence number received which fits in the window.
1443 	 *
1444 	 * We know we don't have the seq we want so we won't be able to flush
1445 	 * anything.
1446 	 */
1447 
1448 	/* slot count is 4, saved size is 3 savedlen is 2
1449 	 *
1450 	 * "window boundary" is based on the fixed window size
1451 	 * distance is also slot number
1452 	 * index is an array index (i.e., - 1 of slot)
1453 	 * : : - implicit NULL after array len
1454 	 *
1455 	 *          +--------- used length (savedlen == 2)
1456 	 *          |   +----- array size (nslots - 1 == 3)
1457 	 *          |   |   + window boundary (nslots == 4)
1458 	 *          V   V | V
1459 	 *                |
1460 	 *  0   1   2   3 |   slot number
1461 	 * ---  0   1   2 |   array index
1462 	 *     [-] [b] : :|   array
1463 	 *
1464 	 * "2" "3" "4" *5*|   seq numbers
1465 	 *
1466 	 * We receive seq number 5
1467 	 * distance == 3 [inseq(5) - w_wantseq(2)]
1468 	 * index == 2 [distance(6) - 1]
1469 	 */
1470 
1471 	if (xtfs->w_saved[index].skb) {
1472 		/* a dup of a future */
1473 		list_add_tail(&inskb->list, freelist);
1474 		return;
1475 	}
1476 
1477 	xtfs->w_saved[index].skb = inskb;
1478 	xtfs->w_savedlen = max(savedlen, index + 1);
1479 	iptfs_set_window_drop_times(xtfs, index);
1480 }
1481 
1482 static void __reorder_future_shifts(struct xfrm_iptfs_data *xtfs,
1483 				    struct sk_buff *inskb,
1484 				    struct list_head *list)
1485 {
1486 	const u32 nslots = xtfs->cfg.reorder_win_size + 1;
1487 	const u64 inseq = __esp_seq(inskb);
1488 	u32 savedlen = xtfs->w_savedlen;
1489 	u64 wantseq = xtfs->w_wantseq;
1490 	struct skb_wseq *wnext;
1491 	struct sk_buff *slot0;
1492 	u32 beyond, shifting, slot;
1493 	u64 distance;
1494 
1495 	/* Handle future sequence number received.
1496 	 *
1497 	 * IMPORTANT: we are at least advancing w_wantseq (i.e., wantseq) by 1
1498 	 * b/c we are beyond the window boundary.
1499 	 *
1500 	 * We know we don't have the wantseq so that counts as a drop.
1501 	 */
1502 
1503 	/* example: slot count is 4, array size is 3 savedlen is 2, slot 0 is
1504 	 * the missing sequence number.
1505 	 *
1506 	 * the final slot at savedlen (index savedlen - 1) is always occupied.
1507 	 *
1508 	 * beyond is "beyond array size" not savedlen.
1509 	 *
1510 	 *          +--------- array length (savedlen == 2)
1511 	 *          |   +----- array size (nslots - 1 == 3)
1512 	 *          |   | +- window boundary (nslots == 4)
1513 	 *          V   V |
1514 	 *                |
1515 	 *  0   1   2   3 |   slot number
1516 	 * ---  0   1   2 |   array index
1517 	 *     [b] [c] : :|   array
1518 	 *                |
1519 	 * "2" "3" "4" "5"|*6*  seq numbers
1520 	 *
1521 	 * We receive seq number 6
1522 	 * distance == 4 [inseq(6) - w_wantseq(2)]
1523 	 * newslot == distance
1524 	 * index == 3 [distance(4) - 1]
1525 	 * beyond == 1 [newslot(4) - lastslot((nslots(4) - 1))]
1526 	 * shifting == 1 [min(savedlen(2), beyond(1)]
1527 	 * slot0_skb == [b], and should match w_wantseq
1528 	 *
1529 	 *                +--- window boundary (nslots == 4)
1530 	 *  0   1   2   3 | 4   slot number
1531 	 * ---  0   1   2 | 3   array index
1532 	 *     [b] : : : :|     array
1533 	 * "2" "3" "4" "5" *6*  seq numbers
1534 	 *
1535 	 * We receive seq number 6
1536 	 * distance == 4 [inseq(6) - w_wantseq(2)]
1537 	 * newslot == distance
1538 	 * index == 3 [distance(4) - 1]
1539 	 * beyond == 1 [newslot(4) - lastslot((nslots(4) - 1))]
1540 	 * shifting == 1 [min(savedlen(1), beyond(1)]
1541 	 * slot0_skb == [b] and should match w_wantseq
1542 	 *
1543 	 *                +-- window boundary (nslots == 4)
1544 	 *  0   1   2   3 | 4   5   6   slot number
1545 	 * ---  0   1   2 | 3   4   5   array index
1546 	 *     [-] [c] : :|             array
1547 	 * "2" "3" "4" "5" "6" "7" *8*  seq numbers
1548 	 *
1549 	 * savedlen = 2, beyond = 3
1550 	 * iter 1: slot0 == NULL, missed++, lastdrop = 2 (2+1-1), slot0 = [-]
1551 	 * iter 2: slot0 == NULL, missed++, lastdrop = 3 (2+2-1), slot0 = [c]
1552 	 * 2 < 3, extra = 1 (3-2), missed += extra, lastdrop = 4 (2+2+1-1)
1553 	 *
1554 	 * We receive seq number 8
1555 	 * distance == 6 [inseq(8) - w_wantseq(2)]
1556 	 * newslot == distance
1557 	 * index == 5 [distance(6) - 1]
1558 	 * beyond == 3 [newslot(6) - lastslot((nslots(4) - 1))]
1559 	 * shifting == 2 [min(savedlen(2), beyond(3)]
1560 	 *
1561 	 * slot0_skb == NULL changed from [b] when "savedlen < beyond" is true.
1562 	 */
1563 
1564 	/* Now send any packets that are being shifted out of saved, and account
1565 	 * for missing packets that are exiting the window as we shift it.
1566 	 */
1567 
1568 	distance = inseq - wantseq;
1569 	beyond = distance - (nslots - 1);
1570 
1571 	/* If savedlen > beyond we are shifting some, else all. */
1572 	shifting = min(savedlen, beyond);
1573 
1574 	/* slot0 is the buf that just shifted out and into slot0 */
1575 	slot0 = NULL;
1576 	wnext = xtfs->w_saved;
1577 	for (slot = 1; slot <= shifting; slot++, wnext++) {
1578 		/* handle what was in slot0 before we occupy it */
1579 		if (slot0)
1580 			list_add_tail(&slot0->list, list);
1581 		slot0 = wnext->skb;
1582 		wnext->skb = NULL;
1583 	}
1584 
1585 	/* slot0 is now either NULL (in which case it's what we now are waiting
1586 	 * for, or a buf in which case we need to handle it like we received it;
1587 	 * however, we may be advancing past that buffer as well..
1588 	 */
1589 
1590 	/* Handle case where we need to shift more than we had saved, slot0 will
1591 	 * be NULL iff savedlen is 0, otherwise slot0 will always be
1592 	 * non-NULL b/c we shifted the final element, which is always set if
1593 	 * there is any saved, into slot0.
1594 	 */
1595 	if (savedlen < beyond) {
1596 		if (savedlen != 0)
1597 			list_add_tail(&slot0->list, list);
1598 		slot0 = NULL;
1599 		/* slot0 has had an empty slot pushed into it */
1600 	}
1601 
1602 	/* Remove the entries */
1603 	__vec_shift(xtfs, beyond);
1604 
1605 	/* Advance want seq */
1606 	xtfs->w_wantseq += beyond;
1607 
1608 	/* Process drops here when implementing congestion control */
1609 
1610 	/* We've shifted. plug the packet in at the end. */
1611 	xtfs->w_savedlen = nslots - 1;
1612 	xtfs->w_saved[xtfs->w_savedlen - 1].skb = inskb;
1613 	iptfs_set_window_drop_times(xtfs, xtfs->w_savedlen - 1);
1614 
1615 	/* if we don't have a slot0 then we must wait for it */
1616 	if (!slot0)
1617 		return;
1618 
1619 	/* If slot0, seq must match new want seq */
1620 
1621 	/* slot0 is valid, treat like we received expected. */
1622 	__reorder_this(xtfs, slot0, list);
1623 }
1624 
1625 /* Receive a new packet into the reorder window. Return a list of ordered
1626  * packets from the window.
1627  */
1628 static void iptfs_input_reorder(struct xfrm_iptfs_data *xtfs,
1629 				struct sk_buff *inskb, struct list_head *list,
1630 				struct list_head *freelist)
1631 {
1632 	const u32 nslots = xtfs->cfg.reorder_win_size + 1;
1633 	u64 inseq = __esp_seq(inskb);
1634 	u64 wantseq;
1635 
1636 	assert_spin_locked(&xtfs->drop_lock);
1637 
1638 	if (unlikely(!xtfs->w_seq_set)) {
1639 		xtfs->w_seq_set = true;
1640 		xtfs->w_wantseq = inseq;
1641 	}
1642 	wantseq = xtfs->w_wantseq;
1643 
1644 	if (likely(inseq == wantseq))
1645 		__reorder_this(xtfs, inskb, list);
1646 	else if (inseq < wantseq)
1647 		__reorder_past(xtfs, inskb, freelist);
1648 	else if ((inseq - wantseq) < nslots)
1649 		__reorder_future_fits(xtfs, inskb, freelist);
1650 	else
1651 		__reorder_future_shifts(xtfs, inskb, list);
1652 }
1653 
1654 /**
1655  * iptfs_drop_timer() - Handle drop timer expiry.
1656  * @me: the timer
1657  *
1658  * This is similar to our input function.
1659  *
1660  * The drop timer is set when we start an in progress reassembly, and also when
1661  * we save a future packet in the window saved array.
1662  *
1663  * NOTE packets in the save window are always newer WRT drop times as
1664  * they get further in the future. i.e. for:
1665  *
1666  *    if slots (S0, S1, ... Sn) and `Dn` is the drop time for slot `Sn`,
1667  *    then D(n-1) <= D(n).
1668  *
1669  * So, regardless of why the timer is firing we can always discard any inprogress
1670  * fragment; either it's the reassembly timer, or slot 0 is going to be
1671  * dropped as S0 must have the most recent drop time, and slot 0 holds the
1672  * continuation fragment of the in progress packet.
1673  *
1674  * Returns HRTIMER_NORESTART.
1675  */
1676 static enum hrtimer_restart iptfs_drop_timer(struct hrtimer *me)
1677 {
1678 	struct sk_buff *skb, *next;
1679 	struct list_head list;
1680 	struct xfrm_iptfs_data *xtfs;
1681 	struct xfrm_state *x;
1682 	u32 count;
1683 
1684 	xtfs = container_of(me, typeof(*xtfs), drop_timer);
1685 	x = xtfs->x;
1686 
1687 	INIT_LIST_HEAD(&list);
1688 
1689 	spin_lock(&xtfs->drop_lock);
1690 
1691 	/* Drop any in progress packet */
1692 	skb = xtfs->ra_newskb;
1693 	xtfs->ra_newskb = NULL;
1694 
1695 	/* Now drop as many packets as we should from the reordering window
1696 	 * saved array
1697 	 */
1698 	count = xtfs->w_savedlen ? __reorder_drop(xtfs, &list) : 0;
1699 
1700 	spin_unlock(&xtfs->drop_lock);
1701 
1702 	if (skb)
1703 		kfree_skb_reason(skb, SKB_DROP_REASON_FRAG_REASM_TIMEOUT);
1704 
1705 	if (count) {
1706 		list_for_each_entry_safe(skb, next, &list, list) {
1707 			skb_list_del_init(skb);
1708 			iptfs_input_ordered(x, skb);
1709 		}
1710 	}
1711 
1712 	return HRTIMER_NORESTART;
1713 }
1714 
1715 /**
1716  * iptfs_input() - handle receipt of iptfs payload
1717  * @x: xfrm state
1718  * @skb: the packet
1719  *
1720  * We have an IPTFS payload order it if needed, then process newly in order
1721  * packets.
1722  *
1723  * Return: -EINPROGRESS to inform xfrm_input to stop processing the skb.
1724  */
1725 static int iptfs_input(struct xfrm_state *x, struct sk_buff *skb)
1726 {
1727 	struct list_head freelist, list;
1728 	struct xfrm_iptfs_data *xtfs = x->mode_data;
1729 	struct sk_buff *next;
1730 
1731 	/* Fast path for no reorder window. */
1732 	if (xtfs->cfg.reorder_win_size == 0) {
1733 		iptfs_input_ordered(x, skb);
1734 		goto done;
1735 	}
1736 
1737 	/* Fetch list of in-order packets from the reordering window as well as
1738 	 * a list of buffers we need to now free.
1739 	 */
1740 	INIT_LIST_HEAD(&list);
1741 	INIT_LIST_HEAD(&freelist);
1742 
1743 	spin_lock(&xtfs->drop_lock);
1744 	iptfs_input_reorder(xtfs, skb, &list, &freelist);
1745 	spin_unlock(&xtfs->drop_lock);
1746 
1747 	list_for_each_entry_safe(skb, next, &list, list) {
1748 		skb_list_del_init(skb);
1749 		iptfs_input_ordered(x, skb);
1750 	}
1751 
1752 	list_for_each_entry_safe(skb, next, &freelist, list) {
1753 		skb_list_del_init(skb);
1754 		kfree_skb(skb);
1755 	}
1756 done:
1757 	/* We always have dealt with the input SKB, either we are re-using it,
1758 	 * or we have freed it. Return EINPROGRESS so that xfrm_input stops
1759 	 * processing it.
1760 	 */
1761 	return -EINPROGRESS;
1762 }
1763 
1764 /* ================================= */
1765 /* IPTFS Sending (ingress) Functions */
1766 /* ================================= */
1767 
1768 /* ------------------------- */
1769 /* Enqueue to send functions */
1770 /* ------------------------- */
1771 
1772 /**
1773  * iptfs_enqueue() - enqueue packet if ok to send.
1774  * @xtfs: xtfs state
1775  * @skb: the packet
1776  *
1777  * Return: true if packet enqueued.
1778  */
1779 static bool iptfs_enqueue(struct xfrm_iptfs_data *xtfs, struct sk_buff *skb)
1780 {
1781 	u64 newsz = xtfs->queue_size + skb->len;
1782 	struct iphdr *iph;
1783 
1784 	assert_spin_locked(&xtfs->x->lock);
1785 
1786 	if (newsz > xtfs->cfg.max_queue_size)
1787 		return false;
1788 
1789 	/* Set ECN CE if we are above our ECN queue threshold */
1790 	if (newsz > xtfs->ecn_queue_size) {
1791 		iph = ip_hdr(skb);
1792 		if (iph->version == 4)
1793 			IP_ECN_set_ce(iph);
1794 		else if (iph->version == 6)
1795 			IP6_ECN_set_ce(skb, ipv6_hdr(skb));
1796 	}
1797 
1798 	__skb_queue_tail(&xtfs->queue, skb);
1799 	xtfs->queue_size += skb->len;
1800 	return true;
1801 }
1802 
1803 static int iptfs_get_cur_pmtu(struct xfrm_state *x, struct xfrm_iptfs_data *xtfs,
1804 			      struct sk_buff *skb)
1805 {
1806 	struct xfrm_dst *xdst = (struct xfrm_dst *)skb_dst(skb);
1807 	u32 payload_mtu = xtfs->payload_mtu;
1808 	u32 pmtu = __iptfs_get_inner_mtu(x, xdst->child_mtu_cached);
1809 
1810 	if (payload_mtu && payload_mtu < pmtu)
1811 		pmtu = payload_mtu;
1812 
1813 	return pmtu;
1814 }
1815 
1816 static int iptfs_is_too_big(struct sock *sk, struct sk_buff *skb, u32 pmtu)
1817 {
1818 	if (skb->len <= pmtu)
1819 		return 0;
1820 
1821 	/* We only send ICMP too big if the user has configured us as
1822 	 * dont-fragment.
1823 	 */
1824 	if (skb->dev)
1825 		XFRM_INC_STATS(dev_net(skb->dev), LINUX_MIB_XFRMOUTERROR);
1826 
1827 	if (sk)
1828 		xfrm_local_error(skb, pmtu);
1829 	else if (ip_hdr(skb)->version == 4)
1830 		icmp_send(skb, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED, htonl(pmtu));
1831 	else
1832 		icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, pmtu);
1833 
1834 	return 1;
1835 }
1836 
1837 /* IPv4/IPv6 packet ingress to IPTFS tunnel, arrange to send in IPTFS payload
1838  * (i.e., aggregating or fragmenting as appropriate).
1839  * This is set in dst->output for an SA.
1840  */
1841 static int iptfs_output_collect(struct net *net, struct sock *sk, struct sk_buff *skb)
1842 {
1843 	struct dst_entry *dst = skb_dst(skb);
1844 	struct xfrm_state *x = dst->xfrm;
1845 	struct xfrm_iptfs_data *xtfs = x->mode_data;
1846 	struct sk_buff *segs, *nskb;
1847 	u32 pmtu = 0;
1848 	bool ok = true;
1849 	bool was_gso;
1850 
1851 	/* We have hooked into dst_entry->output which means we have skipped the
1852 	 * protocol specific netfilter (see xfrm4_output, xfrm6_output).
1853 	 * when our timer runs we will end up calling xfrm_output directly on
1854 	 * the encapsulated traffic.
1855 	 *
1856 	 * For both cases this is the NF_INET_POST_ROUTING hook which allows
1857 	 * changing the skb->dst entry which then may not be xfrm based anymore
1858 	 * in which case a REROUTED flag is set. and dst_output is called.
1859 	 *
1860 	 * For IPv6 we are also skipping fragmentation handling for local
1861 	 * sockets, which may or may not be good depending on our tunnel DF
1862 	 * setting. Normally with fragmentation supported we want to skip this
1863 	 * fragmentation.
1864 	 */
1865 
1866 	if (xtfs->cfg.dont_frag)
1867 		pmtu = iptfs_get_cur_pmtu(x, xtfs, skb);
1868 
1869 	/* Break apart GSO skbs. If the queue is nearing full then we want the
1870 	 * accounting and queuing to be based on the individual packets not on the
1871 	 * aggregate GSO buffer.
1872 	 */
1873 	was_gso = skb_is_gso(skb);
1874 	if (!was_gso) {
1875 		segs = skb;
1876 	} else {
1877 		segs = skb_gso_segment(skb, 0);
1878 		if (IS_ERR_OR_NULL(segs)) {
1879 			XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTERROR);
1880 			kfree_skb(skb);
1881 			if (IS_ERR(segs))
1882 				return PTR_ERR(segs);
1883 			return -EINVAL;
1884 		}
1885 		consume_skb(skb);
1886 		skb = NULL;
1887 	}
1888 
1889 	/* We can be running on multiple cores and from the network softirq or
1890 	 * from user context depending on where the packet is coming from.
1891 	 */
1892 	spin_lock_bh(&x->lock);
1893 
1894 	skb_list_walk_safe(segs, skb, nskb) {
1895 		skb_mark_not_on_list(skb);
1896 
1897 		/* Once we drop due to no queue space we continue to drop the
1898 		 * rest of the packets from that GRO.
1899 		 */
1900 		if (!ok) {
1901 nospace:
1902 			trace_iptfs_no_queue_space(skb, xtfs, pmtu, was_gso);
1903 			XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOQSPACE);
1904 			kfree_skb_reason(skb, SKB_DROP_REASON_FULL_RING);
1905 			continue;
1906 		}
1907 
1908 		/* If the user indicated no iptfs fragmenting check before
1909 		 * enqueue.
1910 		 */
1911 		if (xtfs->cfg.dont_frag && iptfs_is_too_big(sk, skb, pmtu)) {
1912 			trace_iptfs_too_big(skb, xtfs, pmtu, was_gso);
1913 			kfree_skb_reason(skb, SKB_DROP_REASON_PKT_TOO_BIG);
1914 			continue;
1915 		}
1916 
1917 		/* Enqueue to send in tunnel */
1918 		ok = iptfs_enqueue(xtfs, skb);
1919 		if (!ok)
1920 			goto nospace;
1921 
1922 		trace_iptfs_enqueue(skb, xtfs, pmtu, was_gso);
1923 	}
1924 
1925 	/* Start a delay timer if we don't have one yet */
1926 	if (!hrtimer_is_queued(&xtfs->iptfs_timer)) {
1927 		hrtimer_start(&xtfs->iptfs_timer, xtfs->init_delay_ns, IPTFS_HRTIMER_MODE);
1928 		xtfs->iptfs_settime = ktime_get_raw_fast_ns();
1929 		trace_iptfs_timer_start(xtfs, xtfs->init_delay_ns);
1930 	}
1931 
1932 	spin_unlock_bh(&x->lock);
1933 	return 0;
1934 }
1935 
1936 /* -------------------------- */
1937 /* Dequeue and send functions */
1938 /* -------------------------- */
1939 
1940 static void iptfs_output_prepare_skb(struct sk_buff *skb, u32 blkoff)
1941 {
1942 	struct ip_iptfs_hdr *h;
1943 	size_t hsz = sizeof(*h);
1944 
1945 	/* now reset values to be pointing at the rest of the packets */
1946 	h = skb_push(skb, hsz);
1947 	memset(h, 0, hsz);
1948 	if (blkoff)
1949 		h->block_offset = htons(blkoff);
1950 
1951 	/* network_header current points at the inner IP packet
1952 	 * move it to the iptfs header
1953 	 */
1954 	skb->transport_header = skb->network_header;
1955 	skb->network_header -= hsz;
1956 
1957 	IPCB(skb)->flags |= IPSKB_XFRM_TUNNEL_SIZE;
1958 }
1959 
1960 /**
1961  * iptfs_copy_create_frag() - create an inner fragment skb.
1962  * @st: The source packet data.
1963  * @offset: offset in @st of the new fragment data.
1964  * @copy_len: the amount of data to copy from @st.
1965  *
1966  * Create a new skb holding a single IPTFS inner packet fragment. @copy_len must
1967  * not be greater than the max fragment size.
1968  *
1969  * Return: the new fragment skb or an ERR_PTR().
1970  */
1971 static struct sk_buff *iptfs_copy_create_frag(struct skb_seq_state *st, u32 offset, u32 copy_len)
1972 {
1973 	struct sk_buff *src = st->root_skb;
1974 	struct sk_buff *skb;
1975 	int err;
1976 
1977 	skb = iptfs_alloc_skb(src, copy_len, true);
1978 	if (!skb)
1979 		return ERR_PTR(-ENOMEM);
1980 
1981 	/* Now copy `copy_len` data from src */
1982 	err = skb_copy_seq_read(st, offset, skb_put(skb, copy_len), copy_len);
1983 	if (err) {
1984 		kfree_skb(skb);
1985 		return ERR_PTR(err);
1986 	}
1987 
1988 	return skb;
1989 }
1990 
1991 /**
1992  * iptfs_copy_create_frags() - create and send N-1 fragments of a larger skb.
1993  * @skbp: the source packet skb (IN), skb holding the last fragment in
1994  *        the fragment stream (OUT).
1995  * @xtfs: IPTFS SA state.
1996  * @mtu: the max IPTFS fragment size.
1997  *
1998  * This function is responsible for fragmenting a larger inner packet into a
1999  * sequence of IPTFS payload packets. The last fragment is returned rather than
2000  * being sent so that the caller can append more inner packets (aggregation) if
2001  * there is room.
2002  *
2003  * Return: 0 on success or a negative error code on failure
2004  */
2005 static int iptfs_copy_create_frags(struct sk_buff **skbp, struct xfrm_iptfs_data *xtfs, u32 mtu)
2006 {
2007 	struct skb_seq_state skbseq;
2008 	struct list_head sublist;
2009 	struct sk_buff *skb = *skbp;
2010 	struct sk_buff *nskb = *skbp;
2011 	u32 copy_len, offset;
2012 	u32 to_copy = skb->len - mtu;
2013 	u32 blkoff = 0;
2014 	int err = 0;
2015 
2016 	INIT_LIST_HEAD(&sublist);
2017 
2018 	skb_prepare_seq_read(skb, 0, skb->len, &skbseq);
2019 
2020 	/* A trimmed `skb` will be sent as the first fragment, later. */
2021 	offset = mtu;
2022 	to_copy = skb->len - offset;
2023 	while (to_copy) {
2024 		/* Send all but last fragment to allow agg. append */
2025 		trace_iptfs_first_fragmenting(nskb, mtu, to_copy, NULL);
2026 		list_add_tail(&nskb->list, &sublist);
2027 
2028 		/* FUTURE: if the packet has an odd/non-aligning length we could
2029 		 * send less data in the penultimate fragment so that the last
2030 		 * fragment then ends on an aligned boundary.
2031 		 */
2032 		copy_len = min(to_copy, mtu);
2033 		nskb = iptfs_copy_create_frag(&skbseq, offset, copy_len);
2034 		if (IS_ERR(nskb)) {
2035 			XFRM_INC_STATS(xs_net(xtfs->x), LINUX_MIB_XFRMOUTERROR);
2036 			skb_abort_seq_read(&skbseq);
2037 			err = PTR_ERR(nskb);
2038 			nskb = NULL;
2039 			break;
2040 		}
2041 		iptfs_output_prepare_skb(nskb, to_copy);
2042 		offset += copy_len;
2043 		to_copy -= copy_len;
2044 		blkoff = to_copy;
2045 	}
2046 	skb_abort_seq_read(&skbseq);
2047 
2048 	/* return last fragment that will be unsent (or NULL) */
2049 	*skbp = nskb;
2050 	if (nskb)
2051 		trace_iptfs_first_final_fragment(nskb, mtu, blkoff, NULL);
2052 
2053 	/* trim the original skb to MTU */
2054 	if (!err)
2055 		err = pskb_trim(skb, mtu);
2056 
2057 	if (err) {
2058 		/* Free all frags. Don't bother sending a partial packet we will
2059 		 * never complete.
2060 		 */
2061 		kfree_skb(nskb);
2062 		list_for_each_entry_safe(skb, nskb, &sublist, list) {
2063 			skb_list_del_init(skb);
2064 			kfree_skb(skb);
2065 		}
2066 		return err;
2067 	}
2068 
2069 	/* prepare the initial fragment with an iptfs header */
2070 	iptfs_output_prepare_skb(skb, 0);
2071 
2072 	/* Send all but last fragment, if we fail to send a fragment then free
2073 	 * the rest -- no point in sending a packet that can't be reassembled.
2074 	 */
2075 	list_for_each_entry_safe(skb, nskb, &sublist, list) {
2076 		skb_list_del_init(skb);
2077 		if (!err)
2078 			err = xfrm_output(NULL, skb);
2079 		else
2080 			kfree_skb(skb);
2081 	}
2082 	if (err)
2083 		kfree_skb(*skbp);
2084 	return err;
2085 }
2086 
2087 /**
2088  * iptfs_first_skb() - handle the first dequeued inner packet for output
2089  * @skbp: the source packet skb (IN), skb holding the last fragment in
2090  *        the fragment stream (OUT).
2091  * @xtfs: IPTFS SA state.
2092  * @mtu: the max IPTFS fragment size.
2093  *
2094  * This function is responsible for fragmenting a larger inner packet into a
2095  * sequence of IPTFS payload packets.
2096  *
2097  * The last fragment is returned rather than being sent so that the caller can
2098  * append more inner packets (aggregation) if there is room.
2099  *
2100  * Return: 0 on success or a negative error code on failure
2101  */
2102 static int iptfs_first_skb(struct sk_buff **skbp, struct xfrm_iptfs_data *xtfs, u32 mtu)
2103 {
2104 	struct sk_buff *skb = *skbp;
2105 	int err;
2106 
2107 	/* Classic ESP skips the don't fragment ICMP error if DF is clear on
2108 	 * the inner packet or ignore_df is set. Otherwise it will send an ICMP
2109 	 * or local error if the inner packet won't fit it's MTU.
2110 	 *
2111 	 * With IPTFS we do not care about the inner packet DF bit. If the
2112 	 * tunnel is configured to "don't fragment" we error back if things
2113 	 * don't fit in our max packet size. Otherwise we iptfs-fragment as
2114 	 * normal.
2115 	 */
2116 
2117 	/* The opportunity for HW offload has ended */
2118 	if (skb->ip_summed == CHECKSUM_PARTIAL) {
2119 		err = skb_checksum_help(skb);
2120 		if (err)
2121 			return err;
2122 	}
2123 
2124 	/* We've split gso up before queuing */
2125 
2126 	trace_iptfs_first_dequeue(skb, mtu, 0, ip_hdr(skb));
2127 
2128 	/* Consider the buffer Tx'd and no longer owned */
2129 	skb_orphan(skb);
2130 
2131 	/* Simple case -- it fits. `mtu` accounted for all the overhead
2132 	 * including the basic IPTFS header.
2133 	 */
2134 	if (skb->len <= mtu) {
2135 		iptfs_output_prepare_skb(skb, 0);
2136 		return 0;
2137 	}
2138 
2139 	return iptfs_copy_create_frags(skbp, xtfs, mtu);
2140 }
2141 
2142 static struct sk_buff **iptfs_rehome_fraglist(struct sk_buff **nextp, struct sk_buff *child)
2143 {
2144 	u32 fllen = 0;
2145 
2146 	/* It might be possible to account for a frag list in addition to page
2147 	 * fragment if it's a valid state to be in. The page fragments size
2148 	 * should be kept as data_len so only the frag_list size is removed,
2149 	 * this must be done above as well.
2150 	 */
2151 	*nextp = skb_shinfo(child)->frag_list;
2152 	while (*nextp) {
2153 		fllen += (*nextp)->len;
2154 		nextp = &(*nextp)->next;
2155 	}
2156 	skb_frag_list_init(child);
2157 	child->len -= fllen;
2158 	child->data_len -= fllen;
2159 
2160 	return nextp;
2161 }
2162 
2163 static void iptfs_consume_frags(struct sk_buff *to, struct sk_buff *from)
2164 {
2165 	struct skb_shared_info *fromi = skb_shinfo(from);
2166 	struct skb_shared_info *toi = skb_shinfo(to);
2167 	unsigned int new_truesize;
2168 
2169 	/* If we have data in a head page, grab it */
2170 	if (!skb_headlen(from)) {
2171 		new_truesize = SKB_TRUESIZE(skb_end_offset(from));
2172 	} else {
2173 		iptfs_skb_head_to_frag(from, &toi->frags[toi->nr_frags]);
2174 		skb_frag_ref(to, toi->nr_frags++);
2175 		new_truesize = SKB_DATA_ALIGN(sizeof(struct sk_buff));
2176 	}
2177 
2178 	/* Move any other page fragments rather than copy */
2179 	memcpy(&toi->frags[toi->nr_frags], fromi->frags,
2180 	       sizeof(fromi->frags[0]) * fromi->nr_frags);
2181 	toi->nr_frags += fromi->nr_frags;
2182 	if (fromi->nr_frags)
2183 		toi->flags |= fromi->flags & SKBFL_SHARED_FRAG;
2184 	fromi->nr_frags = 0;
2185 	from->data_len = 0;
2186 	from->len = 0;
2187 	to->truesize += from->truesize - new_truesize;
2188 	from->truesize = new_truesize;
2189 
2190 	/* We are done with this SKB */
2191 	consume_skb(from);
2192 }
2193 
2194 static void iptfs_output_queued(struct xfrm_state *x, struct sk_buff_head *list)
2195 {
2196 	struct xfrm_iptfs_data *xtfs = x->mode_data;
2197 	struct sk_buff *skb, *skb2, **nextp;
2198 	struct skb_shared_info *shi, *shi2;
2199 
2200 	/* If we are fragmenting due to a large inner packet we will output all
2201 	 * the outer IPTFS packets required to contain the fragments of the
2202 	 * single large inner packet. These outer packets need to be sent
2203 	 * consecutively (ESP seq-wise). Since this output function is always
2204 	 * running from a timer we do not need a lock to provide this guarantee.
2205 	 * We will output our packets consecutively before the timer is allowed
2206 	 * to run again on some other CPU.
2207 	 */
2208 
2209 	while ((skb = __skb_dequeue(list))) {
2210 		u32 mtu = iptfs_get_cur_pmtu(x, xtfs, skb);
2211 		bool share_ok = true;
2212 		int remaining;
2213 
2214 		/* protocol comes to us cleared sometimes */
2215 		skb->protocol = x->outer_mode.family == AF_INET ? htons(ETH_P_IP) :
2216 								  htons(ETH_P_IPV6);
2217 
2218 		if (skb->len > mtu && xtfs->cfg.dont_frag) {
2219 			/* We handle this case before enqueueing so we are only
2220 			 * here b/c MTU changed after we enqueued before we
2221 			 * dequeued, just drop these.
2222 			 */
2223 			XFRM_INC_STATS(xs_net(x), LINUX_MIB_XFRMOUTERROR);
2224 
2225 			trace_iptfs_first_toobig(skb, mtu, 0, ip_hdr(skb));
2226 			kfree_skb_reason(skb, SKB_DROP_REASON_PKT_TOO_BIG);
2227 			continue;
2228 		}
2229 
2230 		/* Convert first inner packet into an outer IPTFS packet,
2231 		 * dealing with any fragmentation into multiple outer packets
2232 		 * if necessary.
2233 		 */
2234 		if (iptfs_first_skb(&skb, xtfs, mtu))
2235 			continue;
2236 
2237 		/* If fragmentation was required the returned skb is the last
2238 		 * IPTFS fragment in the chain, and it's IPTFS header blkoff has
2239 		 * been set just past the end of the fragment data.
2240 		 *
2241 		 * In either case the space remaining to send more inner packet
2242 		 * data is `mtu` - (skb->len - sizeof iptfs header). This is b/c
2243 		 * the `mtu` value has the basic IPTFS header len accounted for,
2244 		 * and we added that header to the skb so it is a part of
2245 		 * skb->len, thus we subtract it from the skb length.
2246 		 */
2247 		remaining = mtu - (skb->len - sizeof(struct ip_iptfs_hdr));
2248 
2249 		/* Re-home (un-nest) nested fragment lists. We need to do this
2250 		 * b/c we will simply be appending any following aggregated
2251 		 * inner packets using the frag list.
2252 		 */
2253 		shi = skb_shinfo(skb);
2254 		nextp = &shi->frag_list;
2255 		while (*nextp) {
2256 			if (skb_has_frag_list(*nextp))
2257 				nextp = iptfs_rehome_fraglist(&(*nextp)->next, *nextp);
2258 			else
2259 				nextp = &(*nextp)->next;
2260 		}
2261 
2262 		if (shi->frag_list || skb_cloned(skb) || skb_shared(skb))
2263 			share_ok = false;
2264 
2265 		/* See if we have enough space to simply append.
2266 		 *
2267 		 * NOTE: Maybe do not append if we will be mis-aligned,
2268 		 * SW-based endpoints will probably have to copy in this
2269 		 * case.
2270 		 */
2271 		while ((skb2 = skb_peek(list))) {
2272 			trace_iptfs_ingress_nth_peek(skb2, remaining);
2273 			if (skb2->len > remaining)
2274 				break;
2275 
2276 			__skb_unlink(skb2, list);
2277 
2278 			/* Consider the buffer Tx'd and no longer owned */
2279 			skb_orphan(skb);
2280 
2281 			/* If we don't have a cksum in the packet we need to add
2282 			 * one before encapsulation.
2283 			 */
2284 			if (skb2->ip_summed == CHECKSUM_PARTIAL) {
2285 				if (skb_checksum_help(skb2)) {
2286 					XFRM_INC_STATS(xs_net(x), LINUX_MIB_XFRMOUTERROR);
2287 					kfree_skb(skb2);
2288 					continue;
2289 				}
2290 			}
2291 
2292 			/* skb->pp_recycle is passed to __skb_flag_unref for all
2293 			 * frag pages so we can only share pages with skb's who
2294 			 * match ourselves.
2295 			 */
2296 			shi2 = skb_shinfo(skb2);
2297 			if (share_ok &&
2298 			    (shi2->frag_list ||
2299 			     (!skb2->head_frag && skb_headlen(skb)) ||
2300 			     skb->pp_recycle != skb2->pp_recycle ||
2301 			     skb_zcopy(skb2) ||
2302 			     (shi->nr_frags + shi2->nr_frags + 1 > MAX_SKB_FRAGS)))
2303 				share_ok = false;
2304 
2305 			/* Do accounting */
2306 			skb->data_len += skb2->len;
2307 			skb->len += skb2->len;
2308 			remaining -= skb2->len;
2309 
2310 			trace_iptfs_ingress_nth_add(skb2, share_ok);
2311 
2312 			if (share_ok) {
2313 				iptfs_consume_frags(skb, skb2);
2314 			} else {
2315 				/* Append to the frag_list */
2316 				*nextp = skb2;
2317 				nextp = &skb2->next;
2318 				if (skb_has_frag_list(skb2))
2319 					nextp = iptfs_rehome_fraglist(nextp,
2320 								      skb2);
2321 				skb->truesize += skb2->truesize;
2322 			}
2323 		}
2324 
2325 		xfrm_output(NULL, skb);
2326 	}
2327 }
2328 
2329 static enum hrtimer_restart iptfs_delay_timer(struct hrtimer *me)
2330 {
2331 	struct sk_buff_head list;
2332 	struct xfrm_iptfs_data *xtfs;
2333 	struct xfrm_state *x;
2334 	time64_t settime;
2335 
2336 	xtfs = container_of(me, typeof(*xtfs), iptfs_timer);
2337 	x = xtfs->x;
2338 
2339 	/* Process all the queued packets
2340 	 *
2341 	 * softirq execution order: timer > tasklet > hrtimer
2342 	 *
2343 	 * Network rx will have run before us giving one last chance to queue
2344 	 * ingress packets for us to process and transmit.
2345 	 */
2346 
2347 	spin_lock(&x->lock);
2348 	__skb_queue_head_init(&list);
2349 	skb_queue_splice_init(&xtfs->queue, &list);
2350 	xtfs->queue_size = 0;
2351 	settime = xtfs->iptfs_settime;
2352 	spin_unlock(&x->lock);
2353 
2354 	/* After the above unlock, packets can begin queuing again, and the
2355 	 * timer can be set again, from another CPU either in softirq or user
2356 	 * context (not from this one since we are running at softirq level
2357 	 * already).
2358 	 */
2359 
2360 	trace_iptfs_timer_expire(xtfs, (unsigned long long)(ktime_get_raw_fast_ns() - settime));
2361 
2362 	iptfs_output_queued(x, &list);
2363 
2364 	return HRTIMER_NORESTART;
2365 }
2366 
2367 /**
2368  * iptfs_encap_add_ipv4() - add outer encaps
2369  * @x: xfrm state
2370  * @skb: the packet
2371  *
2372  * This was originally taken from xfrm4_tunnel_encap_add. The reason for the
2373  * copy is that IP-TFS/AGGFRAG can have different functionality for how to set
2374  * the TOS/DSCP bits. Sets the protocol to a different value and doesn't do
2375  * anything with inner headers as they aren't pointing into a normal IP
2376  * singleton inner packet.
2377  *
2378  * Return: 0 on success or a negative error code on failure
2379  */
2380 static int iptfs_encap_add_ipv4(struct xfrm_state *x, struct sk_buff *skb)
2381 {
2382 	struct dst_entry *dst = skb_dst(skb);
2383 	struct iphdr *top_iph;
2384 
2385 	skb_reset_inner_network_header(skb);
2386 	skb_reset_inner_transport_header(skb);
2387 
2388 	skb_set_network_header(skb, -(x->props.header_len - x->props.enc_hdr_len));
2389 	skb->mac_header = skb->network_header + offsetof(struct iphdr, protocol);
2390 	skb->transport_header = skb->network_header + sizeof(*top_iph);
2391 
2392 	top_iph = ip_hdr(skb);
2393 	top_iph->ihl = 5;
2394 	top_iph->version = 4;
2395 	top_iph->protocol = IPPROTO_AGGFRAG;
2396 
2397 	/* As we have 0, fractional, 1 or N inner packets there's no obviously
2398 	 * correct DSCP mapping to inherit. ECN should be cleared per RFC9347
2399 	 * 3.1.
2400 	 */
2401 	top_iph->tos = 0;
2402 
2403 	top_iph->frag_off = htons(IP_DF);
2404 	top_iph->ttl = ip4_dst_hoplimit(xfrm_dst_child(dst));
2405 	top_iph->saddr = x->props.saddr.a4;
2406 	top_iph->daddr = x->id.daddr.a4;
2407 	ip_select_ident(dev_net(dst->dev), skb, NULL);
2408 
2409 	return 0;
2410 }
2411 
2412 #if IS_ENABLED(CONFIG_IPV6)
2413 /**
2414  * iptfs_encap_add_ipv6() - add outer encaps
2415  * @x: xfrm state
2416  * @skb: the packet
2417  *
2418  * This was originally taken from xfrm6_tunnel_encap_add. The reason for the
2419  * copy is that IP-TFS/AGGFRAG can have different functionality for how to set
2420  * the flow label and TOS/DSCP bits. It also sets the protocol to a different
2421  * value and doesn't do anything with inner headers as they aren't pointing into
2422  * a normal IP singleton inner packet.
2423  *
2424  * Return: 0 on success or a negative error code on failure
2425  */
2426 static int iptfs_encap_add_ipv6(struct xfrm_state *x, struct sk_buff *skb)
2427 {
2428 	struct dst_entry *dst = skb_dst(skb);
2429 	struct ipv6hdr *top_iph;
2430 	int dsfield;
2431 
2432 	skb_reset_inner_network_header(skb);
2433 	skb_reset_inner_transport_header(skb);
2434 
2435 	skb_set_network_header(skb, -x->props.header_len + x->props.enc_hdr_len);
2436 	skb->mac_header = skb->network_header + offsetof(struct ipv6hdr, nexthdr);
2437 	skb->transport_header = skb->network_header + sizeof(*top_iph);
2438 
2439 	top_iph = ipv6_hdr(skb);
2440 	top_iph->version = 6;
2441 	top_iph->priority = 0;
2442 	memset(top_iph->flow_lbl, 0, sizeof(top_iph->flow_lbl));
2443 	top_iph->nexthdr = IPPROTO_AGGFRAG;
2444 
2445 	/* As we have 0, fractional, 1 or N inner packets there's no obviously
2446 	 * correct DSCP mapping to inherit. ECN should be cleared per RFC9347
2447 	 * 3.1.
2448 	 */
2449 	dsfield = 0;
2450 	ipv6_change_dsfield(top_iph, 0, dsfield);
2451 
2452 	top_iph->hop_limit = ip6_dst_hoplimit(xfrm_dst_child(dst));
2453 	top_iph->saddr = *(struct in6_addr *)&x->props.saddr;
2454 	top_iph->daddr = *(struct in6_addr *)&x->id.daddr;
2455 
2456 	return 0;
2457 }
2458 #endif
2459 
2460 /**
2461  * iptfs_prepare_output() -  prepare the skb for output
2462  * @x: xfrm state
2463  * @skb: the packet
2464  *
2465  * Return: Error value, if 0 then skb values should be as follows:
2466  *    - transport_header should point at ESP header
2467  *    - network_header should point at Outer IP header
2468  *    - mac_header should point at protocol/nexthdr of the outer IP
2469  */
2470 static int iptfs_prepare_output(struct xfrm_state *x, struct sk_buff *skb)
2471 {
2472 	if (x->outer_mode.family == AF_INET)
2473 		return iptfs_encap_add_ipv4(x, skb);
2474 	if (x->outer_mode.family == AF_INET6) {
2475 #if IS_ENABLED(CONFIG_IPV6)
2476 		return iptfs_encap_add_ipv6(x, skb);
2477 #else
2478 		return -EAFNOSUPPORT;
2479 #endif
2480 	}
2481 	return -EOPNOTSUPP;
2482 }
2483 
2484 /* ========================== */
2485 /* State Management Functions */
2486 /* ========================== */
2487 
2488 /**
2489  * __iptfs_get_inner_mtu() - return inner MTU with no fragmentation.
2490  * @x: xfrm state.
2491  * @outer_mtu: the outer mtu
2492  *
2493  * Return: Correct MTU taking in to account the encap overhead.
2494  */
2495 static u32 __iptfs_get_inner_mtu(struct xfrm_state *x, int outer_mtu)
2496 {
2497 	struct crypto_aead *aead;
2498 	u32 blksize;
2499 
2500 	aead = x->data;
2501 	blksize = ALIGN(crypto_aead_blocksize(aead), 4);
2502 	return ((outer_mtu - x->props.header_len - crypto_aead_authsize(aead)) &
2503 		~(blksize - 1)) - 2;
2504 }
2505 
2506 /**
2507  * iptfs_get_inner_mtu() - return the inner MTU for an IPTFS xfrm.
2508  * @x: xfrm state.
2509  * @outer_mtu: Outer MTU for the encapsulated packet.
2510  *
2511  * Return: Correct MTU taking in to account the encap overhead.
2512  */
2513 static u32 iptfs_get_inner_mtu(struct xfrm_state *x, int outer_mtu)
2514 {
2515 	struct xfrm_iptfs_data *xtfs = x->mode_data;
2516 
2517 	/* If not dont-frag we have no MTU */
2518 	if (!xtfs->cfg.dont_frag)
2519 		return x->outer_mode.family == AF_INET ? IP_MAX_MTU : IP6_MAX_MTU;
2520 	return __iptfs_get_inner_mtu(x, outer_mtu);
2521 }
2522 
2523 /**
2524  * iptfs_user_init() - initialize the SA with IPTFS options from netlink.
2525  * @net: the net data
2526  * @x: xfrm state
2527  * @attrs: netlink attributes
2528  * @extack: extack return data
2529  *
2530  * Return: 0 on success or a negative error code on failure
2531  */
2532 static int iptfs_user_init(struct net *net, struct xfrm_state *x,
2533 			   struct nlattr **attrs,
2534 			   struct netlink_ext_ack *extack)
2535 {
2536 	struct xfrm_iptfs_data *xtfs = x->mode_data;
2537 	struct xfrm_iptfs_config *xc;
2538 	u64 q;
2539 
2540 	xc = &xtfs->cfg;
2541 	xc->max_queue_size = IPTFS_DEFAULT_MAX_QUEUE_SIZE;
2542 	xc->reorder_win_size = IPTFS_DEFAULT_REORDER_WINDOW;
2543 	xtfs->drop_time_ns = IPTFS_DEFAULT_DROP_TIME_USECS * NSECS_IN_USEC;
2544 	xtfs->init_delay_ns = IPTFS_DEFAULT_INIT_DELAY_USECS * NSECS_IN_USEC;
2545 
2546 	if (attrs[XFRMA_IPTFS_DONT_FRAG])
2547 		xc->dont_frag = true;
2548 	if (attrs[XFRMA_IPTFS_REORDER_WINDOW])
2549 		xc->reorder_win_size =
2550 			nla_get_u16(attrs[XFRMA_IPTFS_REORDER_WINDOW]);
2551 	/* saved array is for saving 1..N seq nums from wantseq */
2552 	if (xc->reorder_win_size) {
2553 		xtfs->w_saved = kzalloc_objs(*xtfs->w_saved,
2554 					     xc->reorder_win_size);
2555 		if (!xtfs->w_saved) {
2556 			NL_SET_ERR_MSG(extack, "Cannot alloc reorder window");
2557 			return -ENOMEM;
2558 		}
2559 	}
2560 	if (attrs[XFRMA_IPTFS_PKT_SIZE]) {
2561 		xc->pkt_size = nla_get_u32(attrs[XFRMA_IPTFS_PKT_SIZE]);
2562 		if (!xc->pkt_size) {
2563 			xtfs->payload_mtu = 0;
2564 		} else if (xc->pkt_size > x->props.header_len) {
2565 			xtfs->payload_mtu = xc->pkt_size - x->props.header_len;
2566 		} else {
2567 			NL_SET_ERR_MSG(extack,
2568 				       "Packet size must be 0 or greater than IPTFS/ESP header length");
2569 			return -EINVAL;
2570 		}
2571 	}
2572 	if (attrs[XFRMA_IPTFS_MAX_QSIZE])
2573 		xc->max_queue_size = nla_get_u32(attrs[XFRMA_IPTFS_MAX_QSIZE]);
2574 	if (attrs[XFRMA_IPTFS_DROP_TIME])
2575 		xtfs->drop_time_ns =
2576 			(u64)nla_get_u32(attrs[XFRMA_IPTFS_DROP_TIME]) *
2577 			NSECS_IN_USEC;
2578 	if (attrs[XFRMA_IPTFS_INIT_DELAY])
2579 		xtfs->init_delay_ns =
2580 			(u64)nla_get_u32(attrs[XFRMA_IPTFS_INIT_DELAY]) * NSECS_IN_USEC;
2581 
2582 	q = (u64)xc->max_queue_size * 95;
2583 	do_div(q, 100);
2584 	xtfs->ecn_queue_size = (u32)q;
2585 
2586 	return 0;
2587 }
2588 
2589 static unsigned int iptfs_sa_len(const struct xfrm_state *x)
2590 {
2591 	struct xfrm_iptfs_data *xtfs = x->mode_data;
2592 	struct xfrm_iptfs_config *xc = &xtfs->cfg;
2593 	unsigned int l = 0;
2594 
2595 	if (x->dir == XFRM_SA_DIR_IN) {
2596 		l += nla_total_size(sizeof(u32)); /* drop time usec */
2597 		l += nla_total_size(sizeof(xc->reorder_win_size));
2598 	} else {
2599 		if (xc->dont_frag)
2600 			l += nla_total_size(0);	  /* dont-frag flag */
2601 		l += nla_total_size(sizeof(u32)); /* init delay usec */
2602 		l += nla_total_size(sizeof(xc->max_queue_size));
2603 		l += nla_total_size(sizeof(xc->pkt_size));
2604 	}
2605 
2606 	return l;
2607 }
2608 
2609 static int iptfs_copy_to_user(struct xfrm_state *x, struct sk_buff *skb)
2610 {
2611 	struct xfrm_iptfs_data *xtfs = x->mode_data;
2612 	struct xfrm_iptfs_config *xc = &xtfs->cfg;
2613 	int ret = 0;
2614 	u64 q;
2615 
2616 	if (x->dir == XFRM_SA_DIR_IN) {
2617 		q = xtfs->drop_time_ns;
2618 		do_div(q, NSECS_IN_USEC);
2619 		ret = nla_put_u32(skb, XFRMA_IPTFS_DROP_TIME, q);
2620 		if (ret)
2621 			return ret;
2622 
2623 		ret = nla_put_u16(skb, XFRMA_IPTFS_REORDER_WINDOW,
2624 				  xc->reorder_win_size);
2625 	} else {
2626 		if (xc->dont_frag) {
2627 			ret = nla_put_flag(skb, XFRMA_IPTFS_DONT_FRAG);
2628 			if (ret)
2629 				return ret;
2630 		}
2631 
2632 		q = xtfs->init_delay_ns;
2633 		do_div(q, NSECS_IN_USEC);
2634 		ret = nla_put_u32(skb, XFRMA_IPTFS_INIT_DELAY, q);
2635 		if (ret)
2636 			return ret;
2637 
2638 		ret = nla_put_u32(skb, XFRMA_IPTFS_MAX_QSIZE, xc->max_queue_size);
2639 		if (ret)
2640 			return ret;
2641 
2642 		ret = nla_put_u32(skb, XFRMA_IPTFS_PKT_SIZE, xc->pkt_size);
2643 	}
2644 
2645 	return ret;
2646 }
2647 
2648 static void __iptfs_init_state(struct xfrm_state *x,
2649 			       struct xfrm_iptfs_data *xtfs)
2650 {
2651 	__skb_queue_head_init(&xtfs->queue);
2652 	hrtimer_setup(&xtfs->iptfs_timer, iptfs_delay_timer, CLOCK_MONOTONIC, IPTFS_HRTIMER_MODE);
2653 
2654 	spin_lock_init(&xtfs->drop_lock);
2655 	hrtimer_setup(&xtfs->drop_timer, iptfs_drop_timer, CLOCK_MONOTONIC, IPTFS_HRTIMER_MODE);
2656 
2657 	/* Modify type (esp) adjustment values */
2658 
2659 	if (x->props.family == AF_INET)
2660 		x->props.header_len += sizeof(struct iphdr) + sizeof(struct ip_iptfs_hdr);
2661 	else if (x->props.family == AF_INET6)
2662 		x->props.header_len += sizeof(struct ipv6hdr) + sizeof(struct ip_iptfs_hdr);
2663 	x->props.enc_hdr_len = sizeof(struct ip_iptfs_hdr);
2664 
2665 	/* Always keep a module reference when x->mode_data is set */
2666 	if (x->mode_data != xtfs)
2667 		__module_get(x->mode_cbs->owner);
2668 
2669 	x->mode_data = xtfs;
2670 	xtfs->x = x;
2671 }
2672 
2673 static int iptfs_clone_state(struct xfrm_state *x, struct xfrm_state *orig)
2674 {
2675 	struct skb_wseq *w_saved = NULL;
2676 	struct xfrm_iptfs_data *xtfs;
2677 
2678 	xtfs = kmemdup(orig->mode_data, sizeof(*xtfs), GFP_KERNEL);
2679 	if (!xtfs)
2680 		return -ENOMEM;
2681 
2682 	if (xtfs->cfg.reorder_win_size) {
2683 		w_saved = kzalloc_objs(*w_saved, xtfs->cfg.reorder_win_size);
2684 		if (!w_saved) {
2685 			kfree_sensitive(xtfs);
2686 			return -ENOMEM;
2687 		}
2688 	}
2689 	xtfs->w_saved = w_saved;
2690 
2691 	__skb_queue_head_init(&xtfs->queue);
2692 	xtfs->queue_size = 0;
2693 	hrtimer_setup(&xtfs->iptfs_timer, iptfs_delay_timer, CLOCK_MONOTONIC,
2694 		      IPTFS_HRTIMER_MODE);
2695 
2696 	spin_lock_init(&xtfs->drop_lock);
2697 	hrtimer_setup(&xtfs->drop_timer, iptfs_drop_timer, CLOCK_MONOTONIC,
2698 		      IPTFS_HRTIMER_MODE);
2699 
2700 	xtfs->w_seq_set = false;
2701 	xtfs->w_wantseq = 0;
2702 	xtfs->w_savedlen = 0;
2703 	xtfs->ra_newskb = NULL;
2704 	xtfs->ra_wantseq = 0;
2705 	xtfs->ra_runtlen = 0;
2706 
2707 	__module_get(x->mode_cbs->owner);
2708 	x->mode_data = xtfs;
2709 	xtfs->x = x;
2710 
2711 	return 0;
2712 }
2713 
2714 static int iptfs_init_state(struct xfrm_state *x)
2715 {
2716 	struct xfrm_iptfs_data *xtfs;
2717 
2718 	if (x->mode_data) {
2719 		/* We have arrived here from xfrm_state_clone() */
2720 		xtfs = x->mode_data;
2721 	} else {
2722 		xtfs = kzalloc_obj(*xtfs);
2723 		if (!xtfs)
2724 			return -ENOMEM;
2725 	}
2726 
2727 	__iptfs_init_state(x, xtfs);
2728 
2729 	return 0;
2730 }
2731 
2732 static void iptfs_destroy_state(struct xfrm_state *x)
2733 {
2734 	struct xfrm_iptfs_data *xtfs = x->mode_data;
2735 	struct sk_buff_head list;
2736 	struct skb_wseq *s, *se;
2737 	struct sk_buff *skb;
2738 
2739 	if (!xtfs)
2740 		return;
2741 
2742 	hrtimer_cancel(&xtfs->iptfs_timer);
2743 
2744 	spin_lock_bh(&xtfs->x->lock);
2745 	__skb_queue_head_init(&list);
2746 	skb_queue_splice_init(&xtfs->queue, &list);
2747 	spin_unlock_bh(&xtfs->x->lock);
2748 
2749 	while ((skb = __skb_dequeue(&list)))
2750 		kfree_skb(skb);
2751 
2752 	hrtimer_cancel(&xtfs->drop_timer);
2753 
2754 	if (xtfs->ra_newskb)
2755 		kfree_skb(xtfs->ra_newskb);
2756 
2757 	for (s = xtfs->w_saved, se = s + xtfs->w_savedlen; s < se; s++) {
2758 		if (s->skb)
2759 			kfree_skb(s->skb);
2760 	}
2761 
2762 	kfree_sensitive(xtfs->w_saved);
2763 	kfree_sensitive(xtfs);
2764 
2765 	module_put(x->mode_cbs->owner);
2766 }
2767 
2768 static const struct xfrm_mode_cbs iptfs_mode_cbs = {
2769 	.owner = THIS_MODULE,
2770 	.init_state = iptfs_init_state,
2771 	.clone_state = iptfs_clone_state,
2772 	.destroy_state = iptfs_destroy_state,
2773 	.user_init = iptfs_user_init,
2774 	.copy_to_user = iptfs_copy_to_user,
2775 	.sa_len = iptfs_sa_len,
2776 	.get_inner_mtu = iptfs_get_inner_mtu,
2777 	.input = iptfs_input,
2778 	.output = iptfs_output_collect,
2779 	.prepare_output = iptfs_prepare_output,
2780 };
2781 
2782 static int __init xfrm_iptfs_init(void)
2783 {
2784 	int err;
2785 
2786 	pr_info("xfrm_iptfs: IPsec IP-TFS tunnel mode module\n");
2787 
2788 	err = xfrm_register_mode_cbs(XFRM_MODE_IPTFS, &iptfs_mode_cbs);
2789 	if (err < 0)
2790 		pr_info("%s: can't register IP-TFS\n", __func__);
2791 
2792 	return err;
2793 }
2794 
2795 static void __exit xfrm_iptfs_fini(void)
2796 {
2797 	xfrm_unregister_mode_cbs(XFRM_MODE_IPTFS);
2798 }
2799 
2800 module_init(xfrm_iptfs_init);
2801 module_exit(xfrm_iptfs_fini);
2802 MODULE_LICENSE("GPL");
2803 MODULE_DESCRIPTION("IP-TFS support for xfrm ipsec tunnels");
2804