xref: /linux-6.15/net/ipv6/ip6_output.c (revision da273b37)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *	IPv6 output functions
4  *	Linux INET6 implementation
5  *
6  *	Authors:
7  *	Pedro Roque		<[email protected]>
8  *
9  *	Based on linux/net/ipv4/ip_output.c
10  *
11  *	Changes:
12  *	A.N.Kuznetsov	:	airthmetics in fragmentation.
13  *				extension headers are implemented.
14  *				route changes now work.
15  *				ip6_forward does not confuse sniffers.
16  *				etc.
17  *
18  *      H. von Brand    :       Added missing #include <linux/string.h>
19  *	Imran Patel	:	frag id should be in NBO
20  *      Kazunori MIYAZAWA @USAGI
21  *			:       add ip6_append_data and related functions
22  *				for datagram xmit
23  */
24 
25 #include <linux/errno.h>
26 #include <linux/kernel.h>
27 #include <linux/string.h>
28 #include <linux/socket.h>
29 #include <linux/net.h>
30 #include <linux/netdevice.h>
31 #include <linux/if_arp.h>
32 #include <linux/in6.h>
33 #include <linux/tcp.h>
34 #include <linux/route.h>
35 #include <linux/module.h>
36 #include <linux/slab.h>
37 
38 #include <linux/bpf-cgroup.h>
39 #include <linux/netfilter.h>
40 #include <linux/netfilter_ipv6.h>
41 
42 #include <net/sock.h>
43 #include <net/snmp.h>
44 
45 #include <net/gso.h>
46 #include <net/ipv6.h>
47 #include <net/ndisc.h>
48 #include <net/protocol.h>
49 #include <net/ip6_route.h>
50 #include <net/addrconf.h>
51 #include <net/rawv6.h>
52 #include <net/icmp.h>
53 #include <net/xfrm.h>
54 #include <net/checksum.h>
55 #include <linux/mroute6.h>
56 #include <net/l3mdev.h>
57 #include <net/lwtunnel.h>
58 #include <net/ip_tunnels.h>
59 
60 static int ip6_finish_output2(struct net *net, struct sock *sk, struct sk_buff *skb)
61 {
62 	struct dst_entry *dst = skb_dst(skb);
63 	struct net_device *dev = dst->dev;
64 	struct inet6_dev *idev = ip6_dst_idev(dst);
65 	unsigned int hh_len = LL_RESERVED_SPACE(dev);
66 	const struct in6_addr *daddr, *nexthop;
67 	struct ipv6hdr *hdr;
68 	struct neighbour *neigh;
69 	int ret;
70 
71 	/* Be paranoid, rather than too clever. */
72 	if (unlikely(hh_len > skb_headroom(skb)) && dev->header_ops) {
73 		/* Make sure idev stays alive */
74 		rcu_read_lock();
75 		skb = skb_expand_head(skb, hh_len);
76 		if (!skb) {
77 			IP6_INC_STATS(net, idev, IPSTATS_MIB_OUTDISCARDS);
78 			rcu_read_unlock();
79 			return -ENOMEM;
80 		}
81 		rcu_read_unlock();
82 	}
83 
84 	hdr = ipv6_hdr(skb);
85 	daddr = &hdr->daddr;
86 	if (ipv6_addr_is_multicast(daddr)) {
87 		if (!(dev->flags & IFF_LOOPBACK) && sk_mc_loop(sk) &&
88 		    ((mroute6_is_socket(net, skb) &&
89 		     !(IP6CB(skb)->flags & IP6SKB_FORWARDED)) ||
90 		     ipv6_chk_mcast_addr(dev, daddr, &hdr->saddr))) {
91 			struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC);
92 
93 			/* Do not check for IFF_ALLMULTI; multicast routing
94 			   is not supported in any case.
95 			 */
96 			if (newskb)
97 				NF_HOOK(NFPROTO_IPV6, NF_INET_POST_ROUTING,
98 					net, sk, newskb, NULL, newskb->dev,
99 					dev_loopback_xmit);
100 
101 			if (hdr->hop_limit == 0) {
102 				IP6_INC_STATS(net, idev,
103 					      IPSTATS_MIB_OUTDISCARDS);
104 				kfree_skb(skb);
105 				return 0;
106 			}
107 		}
108 
109 		IP6_UPD_PO_STATS(net, idev, IPSTATS_MIB_OUTMCAST, skb->len);
110 		if (IPV6_ADDR_MC_SCOPE(daddr) <= IPV6_ADDR_SCOPE_NODELOCAL &&
111 		    !(dev->flags & IFF_LOOPBACK)) {
112 			kfree_skb(skb);
113 			return 0;
114 		}
115 	}
116 
117 	if (lwtunnel_xmit_redirect(dst->lwtstate)) {
118 		int res = lwtunnel_xmit(skb);
119 
120 		if (res != LWTUNNEL_XMIT_CONTINUE)
121 			return res;
122 	}
123 
124 	IP6_UPD_PO_STATS(net, idev, IPSTATS_MIB_OUT, skb->len);
125 
126 	rcu_read_lock();
127 	nexthop = rt6_nexthop(dst_rt6_info(dst), daddr);
128 	neigh = __ipv6_neigh_lookup_noref(dev, nexthop);
129 
130 	if (unlikely(IS_ERR_OR_NULL(neigh))) {
131 		if (unlikely(!neigh))
132 			neigh = __neigh_create(&nd_tbl, nexthop, dev, false);
133 		if (IS_ERR(neigh)) {
134 			rcu_read_unlock();
135 			IP6_INC_STATS(net, idev, IPSTATS_MIB_OUTNOROUTES);
136 			kfree_skb_reason(skb, SKB_DROP_REASON_NEIGH_CREATEFAIL);
137 			return -EINVAL;
138 		}
139 	}
140 	sock_confirm_neigh(skb, neigh);
141 	ret = neigh_output(neigh, skb, false);
142 	rcu_read_unlock();
143 	return ret;
144 }
145 
146 static int
147 ip6_finish_output_gso_slowpath_drop(struct net *net, struct sock *sk,
148 				    struct sk_buff *skb, unsigned int mtu)
149 {
150 	struct sk_buff *segs, *nskb;
151 	netdev_features_t features;
152 	int ret = 0;
153 
154 	/* Please see corresponding comment in ip_finish_output_gso
155 	 * describing the cases where GSO segment length exceeds the
156 	 * egress MTU.
157 	 */
158 	features = netif_skb_features(skb);
159 	segs = skb_gso_segment(skb, features & ~NETIF_F_GSO_MASK);
160 	if (IS_ERR_OR_NULL(segs)) {
161 		kfree_skb(skb);
162 		return -ENOMEM;
163 	}
164 
165 	consume_skb(skb);
166 
167 	skb_list_walk_safe(segs, segs, nskb) {
168 		int err;
169 
170 		skb_mark_not_on_list(segs);
171 		/* Last GSO segment can be smaller than gso_size (and MTU).
172 		 * Adding a fragment header would produce an "atomic fragment",
173 		 * which is considered harmful (RFC-8021). Avoid that.
174 		 */
175 		err = segs->len > mtu ?
176 			ip6_fragment(net, sk, segs, ip6_finish_output2) :
177 			ip6_finish_output2(net, sk, segs);
178 		if (err && ret == 0)
179 			ret = err;
180 	}
181 
182 	return ret;
183 }
184 
185 static int ip6_finish_output_gso(struct net *net, struct sock *sk,
186 				 struct sk_buff *skb, unsigned int mtu)
187 {
188 	if (!(IP6CB(skb)->flags & IP6SKB_FAKEJUMBO) &&
189 	    !skb_gso_validate_network_len(skb, mtu))
190 		return ip6_finish_output_gso_slowpath_drop(net, sk, skb, mtu);
191 
192 	return ip6_finish_output2(net, sk, skb);
193 }
194 
195 static int __ip6_finish_output(struct net *net, struct sock *sk, struct sk_buff *skb)
196 {
197 	unsigned int mtu;
198 
199 #if defined(CONFIG_NETFILTER) && defined(CONFIG_XFRM)
200 	/* Policy lookup after SNAT yielded a new policy */
201 	if (skb_dst(skb)->xfrm) {
202 		IP6CB(skb)->flags |= IP6SKB_REROUTED;
203 		return dst_output(net, sk, skb);
204 	}
205 #endif
206 
207 	mtu = ip6_skb_dst_mtu(skb);
208 	if (skb_is_gso(skb))
209 		return ip6_finish_output_gso(net, sk, skb, mtu);
210 
211 	if (skb->len > mtu ||
212 	    (IP6CB(skb)->frag_max_size && skb->len > IP6CB(skb)->frag_max_size))
213 		return ip6_fragment(net, sk, skb, ip6_finish_output2);
214 
215 	return ip6_finish_output2(net, sk, skb);
216 }
217 
218 static int ip6_finish_output(struct net *net, struct sock *sk, struct sk_buff *skb)
219 {
220 	int ret;
221 
222 	ret = BPF_CGROUP_RUN_PROG_INET_EGRESS(sk, skb);
223 	switch (ret) {
224 	case NET_XMIT_SUCCESS:
225 	case NET_XMIT_CN:
226 		return __ip6_finish_output(net, sk, skb) ? : ret;
227 	default:
228 		kfree_skb_reason(skb, SKB_DROP_REASON_BPF_CGROUP_EGRESS);
229 		return ret;
230 	}
231 }
232 
233 int ip6_output(struct net *net, struct sock *sk, struct sk_buff *skb)
234 {
235 	struct net_device *dev = skb_dst(skb)->dev, *indev = skb->dev;
236 	struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb));
237 
238 	skb->protocol = htons(ETH_P_IPV6);
239 	skb->dev = dev;
240 
241 	if (unlikely(!idev || READ_ONCE(idev->cnf.disable_ipv6))) {
242 		IP6_INC_STATS(net, idev, IPSTATS_MIB_OUTDISCARDS);
243 		kfree_skb_reason(skb, SKB_DROP_REASON_IPV6DISABLED);
244 		return 0;
245 	}
246 
247 	return NF_HOOK_COND(NFPROTO_IPV6, NF_INET_POST_ROUTING,
248 			    net, sk, skb, indev, dev,
249 			    ip6_finish_output,
250 			    !(IP6CB(skb)->flags & IP6SKB_REROUTED));
251 }
252 EXPORT_SYMBOL(ip6_output);
253 
254 bool ip6_autoflowlabel(struct net *net, const struct sock *sk)
255 {
256 	if (!inet6_test_bit(AUTOFLOWLABEL_SET, sk))
257 		return ip6_default_np_autolabel(net);
258 	return inet6_test_bit(AUTOFLOWLABEL, sk);
259 }
260 
261 /*
262  * xmit an sk_buff (used by TCP, SCTP and DCCP)
263  * Note : socket lock is not held for SYNACK packets, but might be modified
264  * by calls to skb_set_owner_w() and ipv6_local_error(),
265  * which are using proper atomic operations or spinlocks.
266  */
267 int ip6_xmit(const struct sock *sk, struct sk_buff *skb, struct flowi6 *fl6,
268 	     __u32 mark, struct ipv6_txoptions *opt, int tclass, u32 priority)
269 {
270 	struct net *net = sock_net(sk);
271 	const struct ipv6_pinfo *np = inet6_sk(sk);
272 	struct in6_addr *first_hop = &fl6->daddr;
273 	struct dst_entry *dst = skb_dst(skb);
274 	struct net_device *dev = dst->dev;
275 	struct inet6_dev *idev = ip6_dst_idev(dst);
276 	struct hop_jumbo_hdr *hop_jumbo;
277 	int hoplen = sizeof(*hop_jumbo);
278 	unsigned int head_room;
279 	struct ipv6hdr *hdr;
280 	u8  proto = fl6->flowi6_proto;
281 	int seg_len = skb->len;
282 	int hlimit = -1;
283 	u32 mtu;
284 
285 	head_room = sizeof(struct ipv6hdr) + hoplen + LL_RESERVED_SPACE(dev);
286 	if (opt)
287 		head_room += opt->opt_nflen + opt->opt_flen;
288 
289 	if (unlikely(head_room > skb_headroom(skb))) {
290 		skb = skb_expand_head(skb, head_room);
291 		if (!skb) {
292 			IP6_INC_STATS(net, idev, IPSTATS_MIB_OUTDISCARDS);
293 			return -ENOBUFS;
294 		}
295 	}
296 
297 	if (opt) {
298 		seg_len += opt->opt_nflen + opt->opt_flen;
299 
300 		if (opt->opt_flen)
301 			ipv6_push_frag_opts(skb, opt, &proto);
302 
303 		if (opt->opt_nflen)
304 			ipv6_push_nfrag_opts(skb, opt, &proto, &first_hop,
305 					     &fl6->saddr);
306 	}
307 
308 	if (unlikely(seg_len > IPV6_MAXPLEN)) {
309 		hop_jumbo = skb_push(skb, hoplen);
310 
311 		hop_jumbo->nexthdr = proto;
312 		hop_jumbo->hdrlen = 0;
313 		hop_jumbo->tlv_type = IPV6_TLV_JUMBO;
314 		hop_jumbo->tlv_len = 4;
315 		hop_jumbo->jumbo_payload_len = htonl(seg_len + hoplen);
316 
317 		proto = IPPROTO_HOPOPTS;
318 		seg_len = 0;
319 		IP6CB(skb)->flags |= IP6SKB_FAKEJUMBO;
320 	}
321 
322 	skb_push(skb, sizeof(struct ipv6hdr));
323 	skb_reset_network_header(skb);
324 	hdr = ipv6_hdr(skb);
325 
326 	/*
327 	 *	Fill in the IPv6 header
328 	 */
329 	if (np)
330 		hlimit = READ_ONCE(np->hop_limit);
331 	if (hlimit < 0)
332 		hlimit = ip6_dst_hoplimit(dst);
333 
334 	ip6_flow_hdr(hdr, tclass, ip6_make_flowlabel(net, skb, fl6->flowlabel,
335 				ip6_autoflowlabel(net, sk), fl6));
336 
337 	hdr->payload_len = htons(seg_len);
338 	hdr->nexthdr = proto;
339 	hdr->hop_limit = hlimit;
340 
341 	hdr->saddr = fl6->saddr;
342 	hdr->daddr = *first_hop;
343 
344 	skb->protocol = htons(ETH_P_IPV6);
345 	skb->priority = priority;
346 	skb->mark = mark;
347 
348 	mtu = dst_mtu(dst);
349 	if ((skb->len <= mtu) || skb->ignore_df || skb_is_gso(skb)) {
350 		IP6_INC_STATS(net, idev, IPSTATS_MIB_OUTREQUESTS);
351 
352 		/* if egress device is enslaved to an L3 master device pass the
353 		 * skb to its handler for processing
354 		 */
355 		skb = l3mdev_ip6_out((struct sock *)sk, skb);
356 		if (unlikely(!skb))
357 			return 0;
358 
359 		/* hooks should never assume socket lock is held.
360 		 * we promote our socket to non const
361 		 */
362 		return NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_OUT,
363 			       net, (struct sock *)sk, skb, NULL, dev,
364 			       dst_output);
365 	}
366 
367 	skb->dev = dev;
368 	/* ipv6_local_error() does not require socket lock,
369 	 * we promote our socket to non const
370 	 */
371 	ipv6_local_error((struct sock *)sk, EMSGSIZE, fl6, mtu);
372 
373 	IP6_INC_STATS(net, idev, IPSTATS_MIB_FRAGFAILS);
374 	kfree_skb(skb);
375 	return -EMSGSIZE;
376 }
377 EXPORT_SYMBOL(ip6_xmit);
378 
379 static int ip6_call_ra_chain(struct sk_buff *skb, int sel)
380 {
381 	struct ip6_ra_chain *ra;
382 	struct sock *last = NULL;
383 
384 	read_lock(&ip6_ra_lock);
385 	for (ra = ip6_ra_chain; ra; ra = ra->next) {
386 		struct sock *sk = ra->sk;
387 		if (sk && ra->sel == sel &&
388 		    (!sk->sk_bound_dev_if ||
389 		     sk->sk_bound_dev_if == skb->dev->ifindex)) {
390 
391 			if (inet6_test_bit(RTALERT_ISOLATE, sk) &&
392 			    !net_eq(sock_net(sk), dev_net(skb->dev))) {
393 				continue;
394 			}
395 			if (last) {
396 				struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC);
397 				if (skb2)
398 					rawv6_rcv(last, skb2);
399 			}
400 			last = sk;
401 		}
402 	}
403 
404 	if (last) {
405 		rawv6_rcv(last, skb);
406 		read_unlock(&ip6_ra_lock);
407 		return 1;
408 	}
409 	read_unlock(&ip6_ra_lock);
410 	return 0;
411 }
412 
413 static int ip6_forward_proxy_check(struct sk_buff *skb)
414 {
415 	struct ipv6hdr *hdr = ipv6_hdr(skb);
416 	u8 nexthdr = hdr->nexthdr;
417 	__be16 frag_off;
418 	int offset;
419 
420 	if (ipv6_ext_hdr(nexthdr)) {
421 		offset = ipv6_skip_exthdr(skb, sizeof(*hdr), &nexthdr, &frag_off);
422 		if (offset < 0)
423 			return 0;
424 	} else
425 		offset = sizeof(struct ipv6hdr);
426 
427 	if (nexthdr == IPPROTO_ICMPV6) {
428 		struct icmp6hdr *icmp6;
429 
430 		if (!pskb_may_pull(skb, (skb_network_header(skb) +
431 					 offset + 1 - skb->data)))
432 			return 0;
433 
434 		icmp6 = (struct icmp6hdr *)(skb_network_header(skb) + offset);
435 
436 		switch (icmp6->icmp6_type) {
437 		case NDISC_ROUTER_SOLICITATION:
438 		case NDISC_ROUTER_ADVERTISEMENT:
439 		case NDISC_NEIGHBOUR_SOLICITATION:
440 		case NDISC_NEIGHBOUR_ADVERTISEMENT:
441 		case NDISC_REDIRECT:
442 			/* For reaction involving unicast neighbor discovery
443 			 * message destined to the proxied address, pass it to
444 			 * input function.
445 			 */
446 			return 1;
447 		default:
448 			break;
449 		}
450 	}
451 
452 	/*
453 	 * The proxying router can't forward traffic sent to a link-local
454 	 * address, so signal the sender and discard the packet. This
455 	 * behavior is clarified by the MIPv6 specification.
456 	 */
457 	if (ipv6_addr_type(&hdr->daddr) & IPV6_ADDR_LINKLOCAL) {
458 		dst_link_failure(skb);
459 		return -1;
460 	}
461 
462 	return 0;
463 }
464 
465 static inline int ip6_forward_finish(struct net *net, struct sock *sk,
466 				     struct sk_buff *skb)
467 {
468 #ifdef CONFIG_NET_SWITCHDEV
469 	if (skb->offload_l3_fwd_mark) {
470 		consume_skb(skb);
471 		return 0;
472 	}
473 #endif
474 
475 	skb_clear_tstamp(skb);
476 	return dst_output(net, sk, skb);
477 }
478 
479 static bool ip6_pkt_too_big(const struct sk_buff *skb, unsigned int mtu)
480 {
481 	if (skb->len <= mtu)
482 		return false;
483 
484 	/* ipv6 conntrack defrag sets max_frag_size + ignore_df */
485 	if (IP6CB(skb)->frag_max_size && IP6CB(skb)->frag_max_size > mtu)
486 		return true;
487 
488 	if (skb->ignore_df)
489 		return false;
490 
491 	if (skb_is_gso(skb) && skb_gso_validate_network_len(skb, mtu))
492 		return false;
493 
494 	return true;
495 }
496 
497 int ip6_forward(struct sk_buff *skb)
498 {
499 	struct dst_entry *dst = skb_dst(skb);
500 	struct ipv6hdr *hdr = ipv6_hdr(skb);
501 	struct inet6_skb_parm *opt = IP6CB(skb);
502 	struct net *net = dev_net(dst->dev);
503 	struct inet6_dev *idev;
504 	SKB_DR(reason);
505 	u32 mtu;
506 
507 	idev = __in6_dev_get_safely(dev_get_by_index_rcu(net, IP6CB(skb)->iif));
508 	if (READ_ONCE(net->ipv6.devconf_all->forwarding) == 0)
509 		goto error;
510 
511 	if (skb->pkt_type != PACKET_HOST)
512 		goto drop;
513 
514 	if (unlikely(skb->sk))
515 		goto drop;
516 
517 	if (skb_warn_if_lro(skb))
518 		goto drop;
519 
520 	if (!READ_ONCE(net->ipv6.devconf_all->disable_policy) &&
521 	    (!idev || !READ_ONCE(idev->cnf.disable_policy)) &&
522 	    !xfrm6_policy_check(NULL, XFRM_POLICY_FWD, skb)) {
523 		__IP6_INC_STATS(net, idev, IPSTATS_MIB_INDISCARDS);
524 		goto drop;
525 	}
526 
527 	skb_forward_csum(skb);
528 
529 	/*
530 	 *	We DO NOT make any processing on
531 	 *	RA packets, pushing them to user level AS IS
532 	 *	without ane WARRANTY that application will be able
533 	 *	to interpret them. The reason is that we
534 	 *	cannot make anything clever here.
535 	 *
536 	 *	We are not end-node, so that if packet contains
537 	 *	AH/ESP, we cannot make anything.
538 	 *	Defragmentation also would be mistake, RA packets
539 	 *	cannot be fragmented, because there is no warranty
540 	 *	that different fragments will go along one path. --ANK
541 	 */
542 	if (unlikely(opt->flags & IP6SKB_ROUTERALERT)) {
543 		if (ip6_call_ra_chain(skb, ntohs(opt->ra)))
544 			return 0;
545 	}
546 
547 	/*
548 	 *	check and decrement ttl
549 	 */
550 	if (hdr->hop_limit <= 1) {
551 		icmpv6_send(skb, ICMPV6_TIME_EXCEED, ICMPV6_EXC_HOPLIMIT, 0);
552 		__IP6_INC_STATS(net, idev, IPSTATS_MIB_INHDRERRORS);
553 
554 		kfree_skb_reason(skb, SKB_DROP_REASON_IP_INHDR);
555 		return -ETIMEDOUT;
556 	}
557 
558 	/* XXX: idev->cnf.proxy_ndp? */
559 	if (READ_ONCE(net->ipv6.devconf_all->proxy_ndp) &&
560 	    pneigh_lookup(&nd_tbl, net, &hdr->daddr, skb->dev, 0)) {
561 		int proxied = ip6_forward_proxy_check(skb);
562 		if (proxied > 0) {
563 			/* It's tempting to decrease the hop limit
564 			 * here by 1, as we do at the end of the
565 			 * function too.
566 			 *
567 			 * But that would be incorrect, as proxying is
568 			 * not forwarding.  The ip6_input function
569 			 * will handle this packet locally, and it
570 			 * depends on the hop limit being unchanged.
571 			 *
572 			 * One example is the NDP hop limit, that
573 			 * always has to stay 255, but other would be
574 			 * similar checks around RA packets, where the
575 			 * user can even change the desired limit.
576 			 */
577 			return ip6_input(skb);
578 		} else if (proxied < 0) {
579 			__IP6_INC_STATS(net, idev, IPSTATS_MIB_INDISCARDS);
580 			goto drop;
581 		}
582 	}
583 
584 	if (!xfrm6_route_forward(skb)) {
585 		__IP6_INC_STATS(net, idev, IPSTATS_MIB_INDISCARDS);
586 		SKB_DR_SET(reason, XFRM_POLICY);
587 		goto drop;
588 	}
589 	dst = skb_dst(skb);
590 
591 	/* IPv6 specs say nothing about it, but it is clear that we cannot
592 	   send redirects to source routed frames.
593 	   We don't send redirects to frames decapsulated from IPsec.
594 	 */
595 	if (IP6CB(skb)->iif == dst->dev->ifindex &&
596 	    opt->srcrt == 0 && !skb_sec_path(skb)) {
597 		struct in6_addr *target = NULL;
598 		struct inet_peer *peer;
599 		struct rt6_info *rt;
600 
601 		/*
602 		 *	incoming and outgoing devices are the same
603 		 *	send a redirect.
604 		 */
605 
606 		rt = dst_rt6_info(dst);
607 		if (rt->rt6i_flags & RTF_GATEWAY)
608 			target = &rt->rt6i_gateway;
609 		else
610 			target = &hdr->daddr;
611 
612 		peer = inet_getpeer_v6(net->ipv6.peers, &hdr->daddr, 1);
613 
614 		/* Limit redirects both by destination (here)
615 		   and by source (inside ndisc_send_redirect)
616 		 */
617 		if (inet_peer_xrlim_allow(peer, 1*HZ))
618 			ndisc_send_redirect(skb, target);
619 		if (peer)
620 			inet_putpeer(peer);
621 	} else {
622 		int addrtype = ipv6_addr_type(&hdr->saddr);
623 
624 		/* This check is security critical. */
625 		if (addrtype == IPV6_ADDR_ANY ||
626 		    addrtype & (IPV6_ADDR_MULTICAST | IPV6_ADDR_LOOPBACK))
627 			goto error;
628 		if (addrtype & IPV6_ADDR_LINKLOCAL) {
629 			icmpv6_send(skb, ICMPV6_DEST_UNREACH,
630 				    ICMPV6_NOT_NEIGHBOUR, 0);
631 			goto error;
632 		}
633 	}
634 
635 	__IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTFORWDATAGRAMS);
636 
637 	mtu = ip6_dst_mtu_maybe_forward(dst, true);
638 	if (mtu < IPV6_MIN_MTU)
639 		mtu = IPV6_MIN_MTU;
640 
641 	if (ip6_pkt_too_big(skb, mtu)) {
642 		/* Again, force OUTPUT device used as source address */
643 		skb->dev = dst->dev;
644 		icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
645 		__IP6_INC_STATS(net, idev, IPSTATS_MIB_INTOOBIGERRORS);
646 		__IP6_INC_STATS(net, ip6_dst_idev(dst),
647 				IPSTATS_MIB_FRAGFAILS);
648 		kfree_skb_reason(skb, SKB_DROP_REASON_PKT_TOO_BIG);
649 		return -EMSGSIZE;
650 	}
651 
652 	if (skb_cow(skb, dst->dev->hard_header_len)) {
653 		__IP6_INC_STATS(net, ip6_dst_idev(dst),
654 				IPSTATS_MIB_OUTDISCARDS);
655 		goto drop;
656 	}
657 
658 	hdr = ipv6_hdr(skb);
659 
660 	/* Mangling hops number delayed to point after skb COW */
661 
662 	hdr->hop_limit--;
663 
664 	return NF_HOOK(NFPROTO_IPV6, NF_INET_FORWARD,
665 		       net, NULL, skb, skb->dev, dst->dev,
666 		       ip6_forward_finish);
667 
668 error:
669 	__IP6_INC_STATS(net, idev, IPSTATS_MIB_INADDRERRORS);
670 	SKB_DR_SET(reason, IP_INADDRERRORS);
671 drop:
672 	kfree_skb_reason(skb, reason);
673 	return -EINVAL;
674 }
675 
676 static void ip6_copy_metadata(struct sk_buff *to, struct sk_buff *from)
677 {
678 	to->pkt_type = from->pkt_type;
679 	to->priority = from->priority;
680 	to->protocol = from->protocol;
681 	skb_dst_drop(to);
682 	skb_dst_set(to, dst_clone(skb_dst(from)));
683 	to->dev = from->dev;
684 	to->mark = from->mark;
685 
686 	skb_copy_hash(to, from);
687 
688 #ifdef CONFIG_NET_SCHED
689 	to->tc_index = from->tc_index;
690 #endif
691 	nf_copy(to, from);
692 	skb_ext_copy(to, from);
693 	skb_copy_secmark(to, from);
694 }
695 
696 int ip6_fraglist_init(struct sk_buff *skb, unsigned int hlen, u8 *prevhdr,
697 		      u8 nexthdr, __be32 frag_id,
698 		      struct ip6_fraglist_iter *iter)
699 {
700 	unsigned int first_len;
701 	struct frag_hdr *fh;
702 
703 	/* BUILD HEADER */
704 	*prevhdr = NEXTHDR_FRAGMENT;
705 	iter->tmp_hdr = kmemdup(skb_network_header(skb), hlen, GFP_ATOMIC);
706 	if (!iter->tmp_hdr)
707 		return -ENOMEM;
708 
709 	iter->frag = skb_shinfo(skb)->frag_list;
710 	skb_frag_list_init(skb);
711 
712 	iter->offset = 0;
713 	iter->hlen = hlen;
714 	iter->frag_id = frag_id;
715 	iter->nexthdr = nexthdr;
716 
717 	__skb_pull(skb, hlen);
718 	fh = __skb_push(skb, sizeof(struct frag_hdr));
719 	__skb_push(skb, hlen);
720 	skb_reset_network_header(skb);
721 	memcpy(skb_network_header(skb), iter->tmp_hdr, hlen);
722 
723 	fh->nexthdr = nexthdr;
724 	fh->reserved = 0;
725 	fh->frag_off = htons(IP6_MF);
726 	fh->identification = frag_id;
727 
728 	first_len = skb_pagelen(skb);
729 	skb->data_len = first_len - skb_headlen(skb);
730 	skb->len = first_len;
731 	ipv6_hdr(skb)->payload_len = htons(first_len - sizeof(struct ipv6hdr));
732 
733 	return 0;
734 }
735 EXPORT_SYMBOL(ip6_fraglist_init);
736 
737 void ip6_fraglist_prepare(struct sk_buff *skb,
738 			  struct ip6_fraglist_iter *iter)
739 {
740 	struct sk_buff *frag = iter->frag;
741 	unsigned int hlen = iter->hlen;
742 	struct frag_hdr *fh;
743 
744 	frag->ip_summed = CHECKSUM_NONE;
745 	skb_reset_transport_header(frag);
746 	fh = __skb_push(frag, sizeof(struct frag_hdr));
747 	__skb_push(frag, hlen);
748 	skb_reset_network_header(frag);
749 	memcpy(skb_network_header(frag), iter->tmp_hdr, hlen);
750 	iter->offset += skb->len - hlen - sizeof(struct frag_hdr);
751 	fh->nexthdr = iter->nexthdr;
752 	fh->reserved = 0;
753 	fh->frag_off = htons(iter->offset);
754 	if (frag->next)
755 		fh->frag_off |= htons(IP6_MF);
756 	fh->identification = iter->frag_id;
757 	ipv6_hdr(frag)->payload_len = htons(frag->len - sizeof(struct ipv6hdr));
758 	ip6_copy_metadata(frag, skb);
759 }
760 EXPORT_SYMBOL(ip6_fraglist_prepare);
761 
762 void ip6_frag_init(struct sk_buff *skb, unsigned int hlen, unsigned int mtu,
763 		   unsigned short needed_tailroom, int hdr_room, u8 *prevhdr,
764 		   u8 nexthdr, __be32 frag_id, struct ip6_frag_state *state)
765 {
766 	state->prevhdr = prevhdr;
767 	state->nexthdr = nexthdr;
768 	state->frag_id = frag_id;
769 
770 	state->hlen = hlen;
771 	state->mtu = mtu;
772 
773 	state->left = skb->len - hlen;	/* Space per frame */
774 	state->ptr = hlen;		/* Where to start from */
775 
776 	state->hroom = hdr_room;
777 	state->troom = needed_tailroom;
778 
779 	state->offset = 0;
780 }
781 EXPORT_SYMBOL(ip6_frag_init);
782 
783 struct sk_buff *ip6_frag_next(struct sk_buff *skb, struct ip6_frag_state *state)
784 {
785 	u8 *prevhdr = state->prevhdr, *fragnexthdr_offset;
786 	struct sk_buff *frag;
787 	struct frag_hdr *fh;
788 	unsigned int len;
789 
790 	len = state->left;
791 	/* IF: it doesn't fit, use 'mtu' - the data space left */
792 	if (len > state->mtu)
793 		len = state->mtu;
794 	/* IF: we are not sending up to and including the packet end
795 	   then align the next start on an eight byte boundary */
796 	if (len < state->left)
797 		len &= ~7;
798 
799 	/* Allocate buffer */
800 	frag = alloc_skb(len + state->hlen + sizeof(struct frag_hdr) +
801 			 state->hroom + state->troom, GFP_ATOMIC);
802 	if (!frag)
803 		return ERR_PTR(-ENOMEM);
804 
805 	/*
806 	 *	Set up data on packet
807 	 */
808 
809 	ip6_copy_metadata(frag, skb);
810 	skb_reserve(frag, state->hroom);
811 	skb_put(frag, len + state->hlen + sizeof(struct frag_hdr));
812 	skb_reset_network_header(frag);
813 	fh = (struct frag_hdr *)(skb_network_header(frag) + state->hlen);
814 	frag->transport_header = (frag->network_header + state->hlen +
815 				  sizeof(struct frag_hdr));
816 
817 	/*
818 	 *	Charge the memory for the fragment to any owner
819 	 *	it might possess
820 	 */
821 	if (skb->sk)
822 		skb_set_owner_w(frag, skb->sk);
823 
824 	/*
825 	 *	Copy the packet header into the new buffer.
826 	 */
827 	skb_copy_from_linear_data(skb, skb_network_header(frag), state->hlen);
828 
829 	fragnexthdr_offset = skb_network_header(frag);
830 	fragnexthdr_offset += prevhdr - skb_network_header(skb);
831 	*fragnexthdr_offset = NEXTHDR_FRAGMENT;
832 
833 	/*
834 	 *	Build fragment header.
835 	 */
836 	fh->nexthdr = state->nexthdr;
837 	fh->reserved = 0;
838 	fh->identification = state->frag_id;
839 
840 	/*
841 	 *	Copy a block of the IP datagram.
842 	 */
843 	BUG_ON(skb_copy_bits(skb, state->ptr, skb_transport_header(frag),
844 			     len));
845 	state->left -= len;
846 
847 	fh->frag_off = htons(state->offset);
848 	if (state->left > 0)
849 		fh->frag_off |= htons(IP6_MF);
850 	ipv6_hdr(frag)->payload_len = htons(frag->len - sizeof(struct ipv6hdr));
851 
852 	state->ptr += len;
853 	state->offset += len;
854 
855 	return frag;
856 }
857 EXPORT_SYMBOL(ip6_frag_next);
858 
859 int ip6_fragment(struct net *net, struct sock *sk, struct sk_buff *skb,
860 		 int (*output)(struct net *, struct sock *, struct sk_buff *))
861 {
862 	struct sk_buff *frag;
863 	struct rt6_info *rt = dst_rt6_info(skb_dst(skb));
864 	struct ipv6_pinfo *np = skb->sk && !dev_recursion_level() ?
865 				inet6_sk(skb->sk) : NULL;
866 	u8 tstamp_type = skb->tstamp_type;
867 	struct ip6_frag_state state;
868 	unsigned int mtu, hlen, nexthdr_offset;
869 	ktime_t tstamp = skb->tstamp;
870 	int hroom, err = 0;
871 	__be32 frag_id;
872 	u8 *prevhdr, nexthdr = 0;
873 
874 	err = ip6_find_1stfragopt(skb, &prevhdr);
875 	if (err < 0)
876 		goto fail;
877 	hlen = err;
878 	nexthdr = *prevhdr;
879 	nexthdr_offset = prevhdr - skb_network_header(skb);
880 
881 	mtu = ip6_skb_dst_mtu(skb);
882 
883 	/* We must not fragment if the socket is set to force MTU discovery
884 	 * or if the skb it not generated by a local socket.
885 	 */
886 	if (unlikely(!skb->ignore_df && skb->len > mtu))
887 		goto fail_toobig;
888 
889 	if (IP6CB(skb)->frag_max_size) {
890 		if (IP6CB(skb)->frag_max_size > mtu)
891 			goto fail_toobig;
892 
893 		/* don't send fragments larger than what we received */
894 		mtu = IP6CB(skb)->frag_max_size;
895 		if (mtu < IPV6_MIN_MTU)
896 			mtu = IPV6_MIN_MTU;
897 	}
898 
899 	if (np) {
900 		u32 frag_size = READ_ONCE(np->frag_size);
901 
902 		if (frag_size && frag_size < mtu)
903 			mtu = frag_size;
904 	}
905 	if (mtu < hlen + sizeof(struct frag_hdr) + 8)
906 		goto fail_toobig;
907 	mtu -= hlen + sizeof(struct frag_hdr);
908 
909 	frag_id = ipv6_select_ident(net, &ipv6_hdr(skb)->daddr,
910 				    &ipv6_hdr(skb)->saddr);
911 
912 	if (skb->ip_summed == CHECKSUM_PARTIAL &&
913 	    (err = skb_checksum_help(skb)))
914 		goto fail;
915 
916 	prevhdr = skb_network_header(skb) + nexthdr_offset;
917 	hroom = LL_RESERVED_SPACE(rt->dst.dev);
918 	if (skb_has_frag_list(skb)) {
919 		unsigned int first_len = skb_pagelen(skb);
920 		struct ip6_fraglist_iter iter;
921 		struct sk_buff *frag2;
922 
923 		if (first_len - hlen > mtu ||
924 		    ((first_len - hlen) & 7) ||
925 		    skb_cloned(skb) ||
926 		    skb_headroom(skb) < (hroom + sizeof(struct frag_hdr)))
927 			goto slow_path;
928 
929 		skb_walk_frags(skb, frag) {
930 			/* Correct geometry. */
931 			if (frag->len > mtu ||
932 			    ((frag->len & 7) && frag->next) ||
933 			    skb_headroom(frag) < (hlen + hroom + sizeof(struct frag_hdr)))
934 				goto slow_path_clean;
935 
936 			/* Partially cloned skb? */
937 			if (skb_shared(frag))
938 				goto slow_path_clean;
939 
940 			BUG_ON(frag->sk);
941 			if (skb->sk) {
942 				frag->sk = skb->sk;
943 				frag->destructor = sock_wfree;
944 			}
945 			skb->truesize -= frag->truesize;
946 		}
947 
948 		err = ip6_fraglist_init(skb, hlen, prevhdr, nexthdr, frag_id,
949 					&iter);
950 		if (err < 0)
951 			goto fail;
952 
953 		/* We prevent @rt from being freed. */
954 		rcu_read_lock();
955 
956 		for (;;) {
957 			/* Prepare header of the next frame,
958 			 * before previous one went down. */
959 			if (iter.frag)
960 				ip6_fraglist_prepare(skb, &iter);
961 
962 			skb_set_delivery_time(skb, tstamp, tstamp_type);
963 			err = output(net, sk, skb);
964 			if (!err)
965 				IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
966 					      IPSTATS_MIB_FRAGCREATES);
967 
968 			if (err || !iter.frag)
969 				break;
970 
971 			skb = ip6_fraglist_next(&iter);
972 		}
973 
974 		kfree(iter.tmp_hdr);
975 
976 		if (err == 0) {
977 			IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
978 				      IPSTATS_MIB_FRAGOKS);
979 			rcu_read_unlock();
980 			return 0;
981 		}
982 
983 		kfree_skb_list(iter.frag);
984 
985 		IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
986 			      IPSTATS_MIB_FRAGFAILS);
987 		rcu_read_unlock();
988 		return err;
989 
990 slow_path_clean:
991 		skb_walk_frags(skb, frag2) {
992 			if (frag2 == frag)
993 				break;
994 			frag2->sk = NULL;
995 			frag2->destructor = NULL;
996 			skb->truesize += frag2->truesize;
997 		}
998 	}
999 
1000 slow_path:
1001 	/*
1002 	 *	Fragment the datagram.
1003 	 */
1004 
1005 	ip6_frag_init(skb, hlen, mtu, rt->dst.dev->needed_tailroom,
1006 		      LL_RESERVED_SPACE(rt->dst.dev), prevhdr, nexthdr, frag_id,
1007 		      &state);
1008 
1009 	/*
1010 	 *	Keep copying data until we run out.
1011 	 */
1012 
1013 	while (state.left > 0) {
1014 		frag = ip6_frag_next(skb, &state);
1015 		if (IS_ERR(frag)) {
1016 			err = PTR_ERR(frag);
1017 			goto fail;
1018 		}
1019 
1020 		/*
1021 		 *	Put this fragment into the sending queue.
1022 		 */
1023 		skb_set_delivery_time(frag, tstamp, tstamp_type);
1024 		err = output(net, sk, frag);
1025 		if (err)
1026 			goto fail;
1027 
1028 		IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
1029 			      IPSTATS_MIB_FRAGCREATES);
1030 	}
1031 	IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
1032 		      IPSTATS_MIB_FRAGOKS);
1033 	consume_skb(skb);
1034 	return err;
1035 
1036 fail_toobig:
1037 	icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
1038 	err = -EMSGSIZE;
1039 
1040 fail:
1041 	IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
1042 		      IPSTATS_MIB_FRAGFAILS);
1043 	kfree_skb(skb);
1044 	return err;
1045 }
1046 
1047 static inline int ip6_rt_check(const struct rt6key *rt_key,
1048 			       const struct in6_addr *fl_addr,
1049 			       const struct in6_addr *addr_cache)
1050 {
1051 	return (rt_key->plen != 128 || !ipv6_addr_equal(fl_addr, &rt_key->addr)) &&
1052 		(!addr_cache || !ipv6_addr_equal(fl_addr, addr_cache));
1053 }
1054 
1055 static struct dst_entry *ip6_sk_dst_check(struct sock *sk,
1056 					  struct dst_entry *dst,
1057 					  const struct flowi6 *fl6)
1058 {
1059 	struct ipv6_pinfo *np = inet6_sk(sk);
1060 	struct rt6_info *rt;
1061 
1062 	if (!dst)
1063 		goto out;
1064 
1065 	if (dst->ops->family != AF_INET6) {
1066 		dst_release(dst);
1067 		return NULL;
1068 	}
1069 
1070 	rt = dst_rt6_info(dst);
1071 	/* Yes, checking route validity in not connected
1072 	 * case is not very simple. Take into account,
1073 	 * that we do not support routing by source, TOS,
1074 	 * and MSG_DONTROUTE		--ANK (980726)
1075 	 *
1076 	 * 1. ip6_rt_check(): If route was host route,
1077 	 *    check that cached destination is current.
1078 	 *    If it is network route, we still may
1079 	 *    check its validity using saved pointer
1080 	 *    to the last used address: daddr_cache.
1081 	 *    We do not want to save whole address now,
1082 	 *    (because main consumer of this service
1083 	 *    is tcp, which has not this problem),
1084 	 *    so that the last trick works only on connected
1085 	 *    sockets.
1086 	 * 2. oif also should be the same.
1087 	 */
1088 	if (ip6_rt_check(&rt->rt6i_dst, &fl6->daddr, np->daddr_cache) ||
1089 #ifdef CONFIG_IPV6_SUBTREES
1090 	    ip6_rt_check(&rt->rt6i_src, &fl6->saddr, np->saddr_cache) ||
1091 #endif
1092 	   (fl6->flowi6_oif && fl6->flowi6_oif != dst->dev->ifindex)) {
1093 		dst_release(dst);
1094 		dst = NULL;
1095 	}
1096 
1097 out:
1098 	return dst;
1099 }
1100 
1101 static int ip6_dst_lookup_tail(struct net *net, const struct sock *sk,
1102 			       struct dst_entry **dst, struct flowi6 *fl6)
1103 {
1104 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
1105 	struct neighbour *n;
1106 	struct rt6_info *rt;
1107 #endif
1108 	int err;
1109 	int flags = 0;
1110 
1111 	/* The correct way to handle this would be to do
1112 	 * ip6_route_get_saddr, and then ip6_route_output; however,
1113 	 * the route-specific preferred source forces the
1114 	 * ip6_route_output call _before_ ip6_route_get_saddr.
1115 	 *
1116 	 * In source specific routing (no src=any default route),
1117 	 * ip6_route_output will fail given src=any saddr, though, so
1118 	 * that's why we try it again later.
1119 	 */
1120 	if (ipv6_addr_any(&fl6->saddr)) {
1121 		struct fib6_info *from;
1122 		struct rt6_info *rt;
1123 
1124 		*dst = ip6_route_output(net, sk, fl6);
1125 		rt = (*dst)->error ? NULL : dst_rt6_info(*dst);
1126 
1127 		rcu_read_lock();
1128 		from = rt ? rcu_dereference(rt->from) : NULL;
1129 		err = ip6_route_get_saddr(net, from, &fl6->daddr,
1130 					  sk ? READ_ONCE(inet6_sk(sk)->srcprefs) : 0,
1131 					  fl6->flowi6_l3mdev,
1132 					  &fl6->saddr);
1133 		rcu_read_unlock();
1134 
1135 		if (err)
1136 			goto out_err_release;
1137 
1138 		/* If we had an erroneous initial result, pretend it
1139 		 * never existed and let the SA-enabled version take
1140 		 * over.
1141 		 */
1142 		if ((*dst)->error) {
1143 			dst_release(*dst);
1144 			*dst = NULL;
1145 		}
1146 
1147 		if (fl6->flowi6_oif)
1148 			flags |= RT6_LOOKUP_F_IFACE;
1149 	}
1150 
1151 	if (!*dst)
1152 		*dst = ip6_route_output_flags(net, sk, fl6, flags);
1153 
1154 	err = (*dst)->error;
1155 	if (err)
1156 		goto out_err_release;
1157 
1158 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
1159 	/*
1160 	 * Here if the dst entry we've looked up
1161 	 * has a neighbour entry that is in the INCOMPLETE
1162 	 * state and the src address from the flow is
1163 	 * marked as OPTIMISTIC, we release the found
1164 	 * dst entry and replace it instead with the
1165 	 * dst entry of the nexthop router
1166 	 */
1167 	rt = dst_rt6_info(*dst);
1168 	rcu_read_lock();
1169 	n = __ipv6_neigh_lookup_noref(rt->dst.dev,
1170 				      rt6_nexthop(rt, &fl6->daddr));
1171 	err = n && !(READ_ONCE(n->nud_state) & NUD_VALID) ? -EINVAL : 0;
1172 	rcu_read_unlock();
1173 
1174 	if (err) {
1175 		struct inet6_ifaddr *ifp;
1176 		struct flowi6 fl_gw6;
1177 		int redirect;
1178 
1179 		ifp = ipv6_get_ifaddr(net, &fl6->saddr,
1180 				      (*dst)->dev, 1);
1181 
1182 		redirect = (ifp && ifp->flags & IFA_F_OPTIMISTIC);
1183 		if (ifp)
1184 			in6_ifa_put(ifp);
1185 
1186 		if (redirect) {
1187 			/*
1188 			 * We need to get the dst entry for the
1189 			 * default router instead
1190 			 */
1191 			dst_release(*dst);
1192 			memcpy(&fl_gw6, fl6, sizeof(struct flowi6));
1193 			memset(&fl_gw6.daddr, 0, sizeof(struct in6_addr));
1194 			*dst = ip6_route_output(net, sk, &fl_gw6);
1195 			err = (*dst)->error;
1196 			if (err)
1197 				goto out_err_release;
1198 		}
1199 	}
1200 #endif
1201 	if (ipv6_addr_v4mapped(&fl6->saddr) &&
1202 	    !(ipv6_addr_v4mapped(&fl6->daddr) || ipv6_addr_any(&fl6->daddr))) {
1203 		err = -EAFNOSUPPORT;
1204 		goto out_err_release;
1205 	}
1206 
1207 	return 0;
1208 
1209 out_err_release:
1210 	dst_release(*dst);
1211 	*dst = NULL;
1212 
1213 	if (err == -ENETUNREACH)
1214 		IP6_INC_STATS(net, NULL, IPSTATS_MIB_OUTNOROUTES);
1215 	return err;
1216 }
1217 
1218 /**
1219  *	ip6_dst_lookup - perform route lookup on flow
1220  *	@net: Network namespace to perform lookup in
1221  *	@sk: socket which provides route info
1222  *	@dst: pointer to dst_entry * for result
1223  *	@fl6: flow to lookup
1224  *
1225  *	This function performs a route lookup on the given flow.
1226  *
1227  *	It returns zero on success, or a standard errno code on error.
1228  */
1229 int ip6_dst_lookup(struct net *net, struct sock *sk, struct dst_entry **dst,
1230 		   struct flowi6 *fl6)
1231 {
1232 	*dst = NULL;
1233 	return ip6_dst_lookup_tail(net, sk, dst, fl6);
1234 }
1235 EXPORT_SYMBOL_GPL(ip6_dst_lookup);
1236 
1237 /**
1238  *	ip6_dst_lookup_flow - perform route lookup on flow with ipsec
1239  *	@net: Network namespace to perform lookup in
1240  *	@sk: socket which provides route info
1241  *	@fl6: flow to lookup
1242  *	@final_dst: final destination address for ipsec lookup
1243  *
1244  *	This function performs a route lookup on the given flow.
1245  *
1246  *	It returns a valid dst pointer on success, or a pointer encoded
1247  *	error code.
1248  */
1249 struct dst_entry *ip6_dst_lookup_flow(struct net *net, const struct sock *sk, struct flowi6 *fl6,
1250 				      const struct in6_addr *final_dst)
1251 {
1252 	struct dst_entry *dst = NULL;
1253 	int err;
1254 
1255 	err = ip6_dst_lookup_tail(net, sk, &dst, fl6);
1256 	if (err)
1257 		return ERR_PTR(err);
1258 	if (final_dst)
1259 		fl6->daddr = *final_dst;
1260 
1261 	return xfrm_lookup_route(net, dst, flowi6_to_flowi(fl6), sk, 0);
1262 }
1263 EXPORT_SYMBOL_GPL(ip6_dst_lookup_flow);
1264 
1265 /**
1266  *	ip6_sk_dst_lookup_flow - perform socket cached route lookup on flow
1267  *	@sk: socket which provides the dst cache and route info
1268  *	@fl6: flow to lookup
1269  *	@final_dst: final destination address for ipsec lookup
1270  *	@connected: whether @sk is connected or not
1271  *
1272  *	This function performs a route lookup on the given flow with the
1273  *	possibility of using the cached route in the socket if it is valid.
1274  *	It will take the socket dst lock when operating on the dst cache.
1275  *	As a result, this function can only be used in process context.
1276  *
1277  *	In addition, for a connected socket, cache the dst in the socket
1278  *	if the current cache is not valid.
1279  *
1280  *	It returns a valid dst pointer on success, or a pointer encoded
1281  *	error code.
1282  */
1283 struct dst_entry *ip6_sk_dst_lookup_flow(struct sock *sk, struct flowi6 *fl6,
1284 					 const struct in6_addr *final_dst,
1285 					 bool connected)
1286 {
1287 	struct dst_entry *dst = sk_dst_check(sk, inet6_sk(sk)->dst_cookie);
1288 
1289 	dst = ip6_sk_dst_check(sk, dst, fl6);
1290 	if (dst)
1291 		return dst;
1292 
1293 	dst = ip6_dst_lookup_flow(sock_net(sk), sk, fl6, final_dst);
1294 	if (connected && !IS_ERR(dst))
1295 		ip6_sk_dst_store_flow(sk, dst_clone(dst), fl6);
1296 
1297 	return dst;
1298 }
1299 EXPORT_SYMBOL_GPL(ip6_sk_dst_lookup_flow);
1300 
1301 static inline struct ipv6_opt_hdr *ip6_opt_dup(struct ipv6_opt_hdr *src,
1302 					       gfp_t gfp)
1303 {
1304 	return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL;
1305 }
1306 
1307 static inline struct ipv6_rt_hdr *ip6_rthdr_dup(struct ipv6_rt_hdr *src,
1308 						gfp_t gfp)
1309 {
1310 	return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL;
1311 }
1312 
1313 static void ip6_append_data_mtu(unsigned int *mtu,
1314 				int *maxfraglen,
1315 				unsigned int fragheaderlen,
1316 				struct sk_buff *skb,
1317 				struct rt6_info *rt,
1318 				unsigned int orig_mtu)
1319 {
1320 	if (!(rt->dst.flags & DST_XFRM_TUNNEL)) {
1321 		if (!skb) {
1322 			/* first fragment, reserve header_len */
1323 			*mtu = orig_mtu - rt->dst.header_len;
1324 
1325 		} else {
1326 			/*
1327 			 * this fragment is not first, the headers
1328 			 * space is regarded as data space.
1329 			 */
1330 			*mtu = orig_mtu;
1331 		}
1332 		*maxfraglen = ((*mtu - fragheaderlen) & ~7)
1333 			      + fragheaderlen - sizeof(struct frag_hdr);
1334 	}
1335 }
1336 
1337 static int ip6_setup_cork(struct sock *sk, struct inet_cork_full *cork,
1338 			  struct inet6_cork *v6_cork, struct ipcm6_cookie *ipc6,
1339 			  struct rt6_info *rt)
1340 {
1341 	struct ipv6_pinfo *np = inet6_sk(sk);
1342 	unsigned int mtu, frag_size;
1343 	struct ipv6_txoptions *nopt, *opt = ipc6->opt;
1344 
1345 	/* callers pass dst together with a reference, set it first so
1346 	 * ip6_cork_release() can put it down even in case of an error.
1347 	 */
1348 	cork->base.dst = &rt->dst;
1349 
1350 	/*
1351 	 * setup for corking
1352 	 */
1353 	if (opt) {
1354 		if (WARN_ON(v6_cork->opt))
1355 			return -EINVAL;
1356 
1357 		nopt = v6_cork->opt = kzalloc(sizeof(*opt), sk->sk_allocation);
1358 		if (unlikely(!nopt))
1359 			return -ENOBUFS;
1360 
1361 		nopt->tot_len = sizeof(*opt);
1362 		nopt->opt_flen = opt->opt_flen;
1363 		nopt->opt_nflen = opt->opt_nflen;
1364 
1365 		nopt->dst0opt = ip6_opt_dup(opt->dst0opt, sk->sk_allocation);
1366 		if (opt->dst0opt && !nopt->dst0opt)
1367 			return -ENOBUFS;
1368 
1369 		nopt->dst1opt = ip6_opt_dup(opt->dst1opt, sk->sk_allocation);
1370 		if (opt->dst1opt && !nopt->dst1opt)
1371 			return -ENOBUFS;
1372 
1373 		nopt->hopopt = ip6_opt_dup(opt->hopopt, sk->sk_allocation);
1374 		if (opt->hopopt && !nopt->hopopt)
1375 			return -ENOBUFS;
1376 
1377 		nopt->srcrt = ip6_rthdr_dup(opt->srcrt, sk->sk_allocation);
1378 		if (opt->srcrt && !nopt->srcrt)
1379 			return -ENOBUFS;
1380 
1381 		/* need source address above miyazawa*/
1382 	}
1383 	v6_cork->hop_limit = ipc6->hlimit;
1384 	v6_cork->tclass = ipc6->tclass;
1385 	if (rt->dst.flags & DST_XFRM_TUNNEL)
1386 		mtu = READ_ONCE(np->pmtudisc) >= IPV6_PMTUDISC_PROBE ?
1387 		      READ_ONCE(rt->dst.dev->mtu) : dst_mtu(&rt->dst);
1388 	else
1389 		mtu = READ_ONCE(np->pmtudisc) >= IPV6_PMTUDISC_PROBE ?
1390 			READ_ONCE(rt->dst.dev->mtu) : dst_mtu(xfrm_dst_path(&rt->dst));
1391 
1392 	frag_size = READ_ONCE(np->frag_size);
1393 	if (frag_size && frag_size < mtu)
1394 		mtu = frag_size;
1395 
1396 	cork->base.fragsize = mtu;
1397 	cork->base.gso_size = ipc6->gso_size;
1398 	cork->base.tx_flags = 0;
1399 	cork->base.mark = ipc6->sockc.mark;
1400 	sock_tx_timestamp(sk, ipc6->sockc.tsflags, &cork->base.tx_flags);
1401 
1402 	cork->base.length = 0;
1403 	cork->base.transmit_time = ipc6->sockc.transmit_time;
1404 
1405 	return 0;
1406 }
1407 
1408 static int __ip6_append_data(struct sock *sk,
1409 			     struct sk_buff_head *queue,
1410 			     struct inet_cork_full *cork_full,
1411 			     struct inet6_cork *v6_cork,
1412 			     struct page_frag *pfrag,
1413 			     int getfrag(void *from, char *to, int offset,
1414 					 int len, int odd, struct sk_buff *skb),
1415 			     void *from, size_t length, int transhdrlen,
1416 			     unsigned int flags, struct ipcm6_cookie *ipc6)
1417 {
1418 	struct sk_buff *skb, *skb_prev = NULL;
1419 	struct inet_cork *cork = &cork_full->base;
1420 	struct flowi6 *fl6 = &cork_full->fl.u.ip6;
1421 	unsigned int maxfraglen, fragheaderlen, mtu, orig_mtu, pmtu;
1422 	struct ubuf_info *uarg = NULL;
1423 	int exthdrlen = 0;
1424 	int dst_exthdrlen = 0;
1425 	int hh_len;
1426 	int copy;
1427 	int err;
1428 	int offset = 0;
1429 	bool zc = false;
1430 	u32 tskey = 0;
1431 	struct rt6_info *rt = dst_rt6_info(cork->dst);
1432 	bool paged, hold_tskey, extra_uref = false;
1433 	struct ipv6_txoptions *opt = v6_cork->opt;
1434 	int csummode = CHECKSUM_NONE;
1435 	unsigned int maxnonfragsize, headersize;
1436 	unsigned int wmem_alloc_delta = 0;
1437 
1438 	skb = skb_peek_tail(queue);
1439 	if (!skb) {
1440 		exthdrlen = opt ? opt->opt_flen : 0;
1441 		dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len;
1442 	}
1443 
1444 	paged = !!cork->gso_size;
1445 	mtu = cork->gso_size ? IP6_MAX_MTU : cork->fragsize;
1446 	orig_mtu = mtu;
1447 
1448 	hh_len = LL_RESERVED_SPACE(rt->dst.dev);
1449 
1450 	fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len +
1451 			(opt ? opt->opt_nflen : 0);
1452 
1453 	headersize = sizeof(struct ipv6hdr) +
1454 		     (opt ? opt->opt_flen + opt->opt_nflen : 0) +
1455 		     rt->rt6i_nfheader_len;
1456 
1457 	if (mtu <= fragheaderlen ||
1458 	    ((mtu - fragheaderlen) & ~7) + fragheaderlen <= sizeof(struct frag_hdr))
1459 		goto emsgsize;
1460 
1461 	maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen -
1462 		     sizeof(struct frag_hdr);
1463 
1464 	/* as per RFC 7112 section 5, the entire IPv6 Header Chain must fit
1465 	 * the first fragment
1466 	 */
1467 	if (headersize + transhdrlen > mtu)
1468 		goto emsgsize;
1469 
1470 	if (cork->length + length > mtu - headersize && ipc6->dontfrag &&
1471 	    (sk->sk_protocol == IPPROTO_UDP ||
1472 	     sk->sk_protocol == IPPROTO_ICMPV6 ||
1473 	     sk->sk_protocol == IPPROTO_RAW)) {
1474 		ipv6_local_rxpmtu(sk, fl6, mtu - headersize +
1475 				sizeof(struct ipv6hdr));
1476 		goto emsgsize;
1477 	}
1478 
1479 	if (ip6_sk_ignore_df(sk))
1480 		maxnonfragsize = sizeof(struct ipv6hdr) + IPV6_MAXPLEN;
1481 	else
1482 		maxnonfragsize = mtu;
1483 
1484 	if (cork->length + length > maxnonfragsize - headersize) {
1485 emsgsize:
1486 		pmtu = max_t(int, mtu - headersize + sizeof(struct ipv6hdr), 0);
1487 		ipv6_local_error(sk, EMSGSIZE, fl6, pmtu);
1488 		return -EMSGSIZE;
1489 	}
1490 
1491 	/* CHECKSUM_PARTIAL only with no extension headers and when
1492 	 * we are not going to fragment
1493 	 */
1494 	if (transhdrlen && sk->sk_protocol == IPPROTO_UDP &&
1495 	    headersize == sizeof(struct ipv6hdr) &&
1496 	    length <= mtu - headersize &&
1497 	    (!(flags & MSG_MORE) || cork->gso_size) &&
1498 	    rt->dst.dev->features & (NETIF_F_IPV6_CSUM | NETIF_F_HW_CSUM))
1499 		csummode = CHECKSUM_PARTIAL;
1500 
1501 	if ((flags & MSG_ZEROCOPY) && length) {
1502 		struct msghdr *msg = from;
1503 
1504 		if (getfrag == ip_generic_getfrag && msg->msg_ubuf) {
1505 			if (skb_zcopy(skb) && msg->msg_ubuf != skb_zcopy(skb))
1506 				return -EINVAL;
1507 
1508 			/* Leave uarg NULL if can't zerocopy, callers should
1509 			 * be able to handle it.
1510 			 */
1511 			if ((rt->dst.dev->features & NETIF_F_SG) &&
1512 			    csummode == CHECKSUM_PARTIAL) {
1513 				paged = true;
1514 				zc = true;
1515 				uarg = msg->msg_ubuf;
1516 			}
1517 		} else if (sock_flag(sk, SOCK_ZEROCOPY)) {
1518 			uarg = msg_zerocopy_realloc(sk, length, skb_zcopy(skb));
1519 			if (!uarg)
1520 				return -ENOBUFS;
1521 			extra_uref = !skb_zcopy(skb);	/* only ref on new uarg */
1522 			if (rt->dst.dev->features & NETIF_F_SG &&
1523 			    csummode == CHECKSUM_PARTIAL) {
1524 				paged = true;
1525 				zc = true;
1526 			} else {
1527 				uarg_to_msgzc(uarg)->zerocopy = 0;
1528 				skb_zcopy_set(skb, uarg, &extra_uref);
1529 			}
1530 		}
1531 	} else if ((flags & MSG_SPLICE_PAGES) && length) {
1532 		if (inet_test_bit(HDRINCL, sk))
1533 			return -EPERM;
1534 		if (rt->dst.dev->features & NETIF_F_SG &&
1535 		    getfrag == ip_generic_getfrag)
1536 			/* We need an empty buffer to attach stuff to */
1537 			paged = true;
1538 		else
1539 			flags &= ~MSG_SPLICE_PAGES;
1540 	}
1541 
1542 	hold_tskey = cork->tx_flags & SKBTX_ANY_TSTAMP &&
1543 		     READ_ONCE(sk->sk_tsflags) & SOF_TIMESTAMPING_OPT_ID;
1544 	if (hold_tskey)
1545 		tskey = atomic_inc_return(&sk->sk_tskey) - 1;
1546 
1547 	/*
1548 	 * Let's try using as much space as possible.
1549 	 * Use MTU if total length of the message fits into the MTU.
1550 	 * Otherwise, we need to reserve fragment header and
1551 	 * fragment alignment (= 8-15 octects, in total).
1552 	 *
1553 	 * Note that we may need to "move" the data from the tail
1554 	 * of the buffer to the new fragment when we split
1555 	 * the message.
1556 	 *
1557 	 * FIXME: It may be fragmented into multiple chunks
1558 	 *        at once if non-fragmentable extension headers
1559 	 *        are too large.
1560 	 * --yoshfuji
1561 	 */
1562 
1563 	cork->length += length;
1564 	if (!skb)
1565 		goto alloc_new_skb;
1566 
1567 	while (length > 0) {
1568 		/* Check if the remaining data fits into current packet. */
1569 		copy = (cork->length <= mtu ? mtu : maxfraglen) - skb->len;
1570 		if (copy < length)
1571 			copy = maxfraglen - skb->len;
1572 
1573 		if (copy <= 0) {
1574 			char *data;
1575 			unsigned int datalen;
1576 			unsigned int fraglen;
1577 			unsigned int fraggap;
1578 			unsigned int alloclen, alloc_extra;
1579 			unsigned int pagedlen;
1580 alloc_new_skb:
1581 			/* There's no room in the current skb */
1582 			if (skb)
1583 				fraggap = skb->len - maxfraglen;
1584 			else
1585 				fraggap = 0;
1586 			/* update mtu and maxfraglen if necessary */
1587 			if (!skb || !skb_prev)
1588 				ip6_append_data_mtu(&mtu, &maxfraglen,
1589 						    fragheaderlen, skb, rt,
1590 						    orig_mtu);
1591 
1592 			skb_prev = skb;
1593 
1594 			/*
1595 			 * If remaining data exceeds the mtu,
1596 			 * we know we need more fragment(s).
1597 			 */
1598 			datalen = length + fraggap;
1599 
1600 			if (datalen > (cork->length <= mtu ? mtu : maxfraglen) - fragheaderlen)
1601 				datalen = maxfraglen - fragheaderlen - rt->dst.trailer_len;
1602 			fraglen = datalen + fragheaderlen;
1603 			pagedlen = 0;
1604 
1605 			alloc_extra = hh_len;
1606 			alloc_extra += dst_exthdrlen;
1607 			alloc_extra += rt->dst.trailer_len;
1608 
1609 			/* We just reserve space for fragment header.
1610 			 * Note: this may be overallocation if the message
1611 			 * (without MSG_MORE) fits into the MTU.
1612 			 */
1613 			alloc_extra += sizeof(struct frag_hdr);
1614 
1615 			if ((flags & MSG_MORE) &&
1616 			    !(rt->dst.dev->features&NETIF_F_SG))
1617 				alloclen = mtu;
1618 			else if (!paged &&
1619 				 (fraglen + alloc_extra < SKB_MAX_ALLOC ||
1620 				  !(rt->dst.dev->features & NETIF_F_SG)))
1621 				alloclen = fraglen;
1622 			else {
1623 				alloclen = fragheaderlen + transhdrlen;
1624 				pagedlen = datalen - transhdrlen;
1625 			}
1626 			alloclen += alloc_extra;
1627 
1628 			if (datalen != length + fraggap) {
1629 				/*
1630 				 * this is not the last fragment, the trailer
1631 				 * space is regarded as data space.
1632 				 */
1633 				datalen += rt->dst.trailer_len;
1634 			}
1635 
1636 			fraglen = datalen + fragheaderlen;
1637 
1638 			copy = datalen - transhdrlen - fraggap - pagedlen;
1639 			/* [!] NOTE: copy may be negative if pagedlen>0
1640 			 * because then the equation may reduces to -fraggap.
1641 			 */
1642 			if (copy < 0 && !(flags & MSG_SPLICE_PAGES)) {
1643 				err = -EINVAL;
1644 				goto error;
1645 			}
1646 			if (transhdrlen) {
1647 				skb = sock_alloc_send_skb(sk, alloclen,
1648 						(flags & MSG_DONTWAIT), &err);
1649 			} else {
1650 				skb = NULL;
1651 				if (refcount_read(&sk->sk_wmem_alloc) + wmem_alloc_delta <=
1652 				    2 * sk->sk_sndbuf)
1653 					skb = alloc_skb(alloclen,
1654 							sk->sk_allocation);
1655 				if (unlikely(!skb))
1656 					err = -ENOBUFS;
1657 			}
1658 			if (!skb)
1659 				goto error;
1660 			/*
1661 			 *	Fill in the control structures
1662 			 */
1663 			skb->protocol = htons(ETH_P_IPV6);
1664 			skb->ip_summed = csummode;
1665 			skb->csum = 0;
1666 			/* reserve for fragmentation and ipsec header */
1667 			skb_reserve(skb, hh_len + sizeof(struct frag_hdr) +
1668 				    dst_exthdrlen);
1669 
1670 			/*
1671 			 *	Find where to start putting bytes
1672 			 */
1673 			data = skb_put(skb, fraglen - pagedlen);
1674 			skb_set_network_header(skb, exthdrlen);
1675 			data += fragheaderlen;
1676 			skb->transport_header = (skb->network_header +
1677 						 fragheaderlen);
1678 			if (fraggap) {
1679 				skb->csum = skb_copy_and_csum_bits(
1680 					skb_prev, maxfraglen,
1681 					data + transhdrlen, fraggap);
1682 				skb_prev->csum = csum_sub(skb_prev->csum,
1683 							  skb->csum);
1684 				data += fraggap;
1685 				pskb_trim_unique(skb_prev, maxfraglen);
1686 			}
1687 			if (copy > 0 &&
1688 			    getfrag(from, data + transhdrlen, offset,
1689 				    copy, fraggap, skb) < 0) {
1690 				err = -EFAULT;
1691 				kfree_skb(skb);
1692 				goto error;
1693 			} else if (flags & MSG_SPLICE_PAGES) {
1694 				copy = 0;
1695 			}
1696 
1697 			offset += copy;
1698 			length -= copy + transhdrlen;
1699 			transhdrlen = 0;
1700 			exthdrlen = 0;
1701 			dst_exthdrlen = 0;
1702 
1703 			/* Only the initial fragment is time stamped */
1704 			skb_shinfo(skb)->tx_flags = cork->tx_flags;
1705 			cork->tx_flags = 0;
1706 			skb_shinfo(skb)->tskey = tskey;
1707 			tskey = 0;
1708 			skb_zcopy_set(skb, uarg, &extra_uref);
1709 
1710 			if ((flags & MSG_CONFIRM) && !skb_prev)
1711 				skb_set_dst_pending_confirm(skb, 1);
1712 
1713 			/*
1714 			 * Put the packet on the pending queue
1715 			 */
1716 			if (!skb->destructor) {
1717 				skb->destructor = sock_wfree;
1718 				skb->sk = sk;
1719 				wmem_alloc_delta += skb->truesize;
1720 			}
1721 			__skb_queue_tail(queue, skb);
1722 			continue;
1723 		}
1724 
1725 		if (copy > length)
1726 			copy = length;
1727 
1728 		if (!(rt->dst.dev->features&NETIF_F_SG) &&
1729 		    skb_tailroom(skb) >= copy) {
1730 			unsigned int off;
1731 
1732 			off = skb->len;
1733 			if (getfrag(from, skb_put(skb, copy),
1734 						offset, copy, off, skb) < 0) {
1735 				__skb_trim(skb, off);
1736 				err = -EFAULT;
1737 				goto error;
1738 			}
1739 		} else if (flags & MSG_SPLICE_PAGES) {
1740 			struct msghdr *msg = from;
1741 
1742 			err = -EIO;
1743 			if (WARN_ON_ONCE(copy > msg->msg_iter.count))
1744 				goto error;
1745 
1746 			err = skb_splice_from_iter(skb, &msg->msg_iter, copy,
1747 						   sk->sk_allocation);
1748 			if (err < 0)
1749 				goto error;
1750 			copy = err;
1751 			wmem_alloc_delta += copy;
1752 		} else if (!zc) {
1753 			int i = skb_shinfo(skb)->nr_frags;
1754 
1755 			err = -ENOMEM;
1756 			if (!sk_page_frag_refill(sk, pfrag))
1757 				goto error;
1758 
1759 			skb_zcopy_downgrade_managed(skb);
1760 			if (!skb_can_coalesce(skb, i, pfrag->page,
1761 					      pfrag->offset)) {
1762 				err = -EMSGSIZE;
1763 				if (i == MAX_SKB_FRAGS)
1764 					goto error;
1765 
1766 				__skb_fill_page_desc(skb, i, pfrag->page,
1767 						     pfrag->offset, 0);
1768 				skb_shinfo(skb)->nr_frags = ++i;
1769 				get_page(pfrag->page);
1770 			}
1771 			copy = min_t(int, copy, pfrag->size - pfrag->offset);
1772 			if (getfrag(from,
1773 				    page_address(pfrag->page) + pfrag->offset,
1774 				    offset, copy, skb->len, skb) < 0)
1775 				goto error_efault;
1776 
1777 			pfrag->offset += copy;
1778 			skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
1779 			skb->len += copy;
1780 			skb->data_len += copy;
1781 			skb->truesize += copy;
1782 			wmem_alloc_delta += copy;
1783 		} else {
1784 			err = skb_zerocopy_iter_dgram(skb, from, copy);
1785 			if (err < 0)
1786 				goto error;
1787 		}
1788 		offset += copy;
1789 		length -= copy;
1790 	}
1791 
1792 	if (wmem_alloc_delta)
1793 		refcount_add(wmem_alloc_delta, &sk->sk_wmem_alloc);
1794 	return 0;
1795 
1796 error_efault:
1797 	err = -EFAULT;
1798 error:
1799 	net_zcopy_put_abort(uarg, extra_uref);
1800 	cork->length -= length;
1801 	IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS);
1802 	refcount_add(wmem_alloc_delta, &sk->sk_wmem_alloc);
1803 	if (hold_tskey)
1804 		atomic_dec(&sk->sk_tskey);
1805 	return err;
1806 }
1807 
1808 int ip6_append_data(struct sock *sk,
1809 		    int getfrag(void *from, char *to, int offset, int len,
1810 				int odd, struct sk_buff *skb),
1811 		    void *from, size_t length, int transhdrlen,
1812 		    struct ipcm6_cookie *ipc6, struct flowi6 *fl6,
1813 		    struct rt6_info *rt, unsigned int flags)
1814 {
1815 	struct inet_sock *inet = inet_sk(sk);
1816 	struct ipv6_pinfo *np = inet6_sk(sk);
1817 	int exthdrlen;
1818 	int err;
1819 
1820 	if (flags&MSG_PROBE)
1821 		return 0;
1822 	if (skb_queue_empty(&sk->sk_write_queue)) {
1823 		/*
1824 		 * setup for corking
1825 		 */
1826 		dst_hold(&rt->dst);
1827 		err = ip6_setup_cork(sk, &inet->cork, &np->cork,
1828 				     ipc6, rt);
1829 		if (err)
1830 			return err;
1831 
1832 		inet->cork.fl.u.ip6 = *fl6;
1833 		exthdrlen = (ipc6->opt ? ipc6->opt->opt_flen : 0);
1834 		length += exthdrlen;
1835 		transhdrlen += exthdrlen;
1836 	} else {
1837 		transhdrlen = 0;
1838 	}
1839 
1840 	return __ip6_append_data(sk, &sk->sk_write_queue, &inet->cork,
1841 				 &np->cork, sk_page_frag(sk), getfrag,
1842 				 from, length, transhdrlen, flags, ipc6);
1843 }
1844 EXPORT_SYMBOL_GPL(ip6_append_data);
1845 
1846 static void ip6_cork_steal_dst(struct sk_buff *skb, struct inet_cork_full *cork)
1847 {
1848 	struct dst_entry *dst = cork->base.dst;
1849 
1850 	cork->base.dst = NULL;
1851 	skb_dst_set(skb, dst);
1852 }
1853 
1854 static void ip6_cork_release(struct inet_cork_full *cork,
1855 			     struct inet6_cork *v6_cork)
1856 {
1857 	if (v6_cork->opt) {
1858 		struct ipv6_txoptions *opt = v6_cork->opt;
1859 
1860 		kfree(opt->dst0opt);
1861 		kfree(opt->dst1opt);
1862 		kfree(opt->hopopt);
1863 		kfree(opt->srcrt);
1864 		kfree(opt);
1865 		v6_cork->opt = NULL;
1866 	}
1867 
1868 	if (cork->base.dst) {
1869 		dst_release(cork->base.dst);
1870 		cork->base.dst = NULL;
1871 	}
1872 }
1873 
1874 struct sk_buff *__ip6_make_skb(struct sock *sk,
1875 			       struct sk_buff_head *queue,
1876 			       struct inet_cork_full *cork,
1877 			       struct inet6_cork *v6_cork)
1878 {
1879 	struct sk_buff *skb, *tmp_skb;
1880 	struct sk_buff **tail_skb;
1881 	struct in6_addr *final_dst;
1882 	struct net *net = sock_net(sk);
1883 	struct ipv6hdr *hdr;
1884 	struct ipv6_txoptions *opt = v6_cork->opt;
1885 	struct rt6_info *rt = dst_rt6_info(cork->base.dst);
1886 	struct flowi6 *fl6 = &cork->fl.u.ip6;
1887 	unsigned char proto = fl6->flowi6_proto;
1888 
1889 	skb = __skb_dequeue(queue);
1890 	if (!skb)
1891 		goto out;
1892 	tail_skb = &(skb_shinfo(skb)->frag_list);
1893 
1894 	/* move skb->data to ip header from ext header */
1895 	if (skb->data < skb_network_header(skb))
1896 		__skb_pull(skb, skb_network_offset(skb));
1897 	while ((tmp_skb = __skb_dequeue(queue)) != NULL) {
1898 		__skb_pull(tmp_skb, skb_network_header_len(skb));
1899 		*tail_skb = tmp_skb;
1900 		tail_skb = &(tmp_skb->next);
1901 		skb->len += tmp_skb->len;
1902 		skb->data_len += tmp_skb->len;
1903 		skb->truesize += tmp_skb->truesize;
1904 		tmp_skb->destructor = NULL;
1905 		tmp_skb->sk = NULL;
1906 	}
1907 
1908 	/* Allow local fragmentation. */
1909 	skb->ignore_df = ip6_sk_ignore_df(sk);
1910 	__skb_pull(skb, skb_network_header_len(skb));
1911 
1912 	final_dst = &fl6->daddr;
1913 	if (opt && opt->opt_flen)
1914 		ipv6_push_frag_opts(skb, opt, &proto);
1915 	if (opt && opt->opt_nflen)
1916 		ipv6_push_nfrag_opts(skb, opt, &proto, &final_dst, &fl6->saddr);
1917 
1918 	skb_push(skb, sizeof(struct ipv6hdr));
1919 	skb_reset_network_header(skb);
1920 	hdr = ipv6_hdr(skb);
1921 
1922 	ip6_flow_hdr(hdr, v6_cork->tclass,
1923 		     ip6_make_flowlabel(net, skb, fl6->flowlabel,
1924 					ip6_autoflowlabel(net, sk), fl6));
1925 	hdr->hop_limit = v6_cork->hop_limit;
1926 	hdr->nexthdr = proto;
1927 	hdr->saddr = fl6->saddr;
1928 	hdr->daddr = *final_dst;
1929 
1930 	skb->priority = READ_ONCE(sk->sk_priority);
1931 	skb->mark = cork->base.mark;
1932 	if (sk_is_tcp(sk))
1933 		skb_set_delivery_time(skb, cork->base.transmit_time, SKB_CLOCK_MONOTONIC);
1934 	else
1935 		skb_set_delivery_type_by_clockid(skb, cork->base.transmit_time, sk->sk_clockid);
1936 
1937 	ip6_cork_steal_dst(skb, cork);
1938 	IP6_INC_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUTREQUESTS);
1939 	if (proto == IPPROTO_ICMPV6) {
1940 		struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb));
1941 		u8 icmp6_type;
1942 
1943 		if (sk->sk_socket->type == SOCK_RAW &&
1944 		   !(fl6->flowi6_flags & FLOWI_FLAG_KNOWN_NH))
1945 			icmp6_type = fl6->fl6_icmp_type;
1946 		else
1947 			icmp6_type = icmp6_hdr(skb)->icmp6_type;
1948 		ICMP6MSGOUT_INC_STATS(net, idev, icmp6_type);
1949 		ICMP6_INC_STATS(net, idev, ICMP6_MIB_OUTMSGS);
1950 	}
1951 
1952 	ip6_cork_release(cork, v6_cork);
1953 out:
1954 	return skb;
1955 }
1956 
1957 int ip6_send_skb(struct sk_buff *skb)
1958 {
1959 	struct net *net = sock_net(skb->sk);
1960 	struct rt6_info *rt = dst_rt6_info(skb_dst(skb));
1961 	int err;
1962 
1963 	rcu_read_lock();
1964 	err = ip6_local_out(net, skb->sk, skb);
1965 	if (err) {
1966 		if (err > 0)
1967 			err = net_xmit_errno(err);
1968 		if (err)
1969 			IP6_INC_STATS(net, rt->rt6i_idev,
1970 				      IPSTATS_MIB_OUTDISCARDS);
1971 	}
1972 
1973 	rcu_read_unlock();
1974 	return err;
1975 }
1976 
1977 int ip6_push_pending_frames(struct sock *sk)
1978 {
1979 	struct sk_buff *skb;
1980 
1981 	skb = ip6_finish_skb(sk);
1982 	if (!skb)
1983 		return 0;
1984 
1985 	return ip6_send_skb(skb);
1986 }
1987 EXPORT_SYMBOL_GPL(ip6_push_pending_frames);
1988 
1989 static void __ip6_flush_pending_frames(struct sock *sk,
1990 				       struct sk_buff_head *queue,
1991 				       struct inet_cork_full *cork,
1992 				       struct inet6_cork *v6_cork)
1993 {
1994 	struct sk_buff *skb;
1995 
1996 	while ((skb = __skb_dequeue_tail(queue)) != NULL) {
1997 		if (skb_dst(skb))
1998 			IP6_INC_STATS(sock_net(sk), ip6_dst_idev(skb_dst(skb)),
1999 				      IPSTATS_MIB_OUTDISCARDS);
2000 		kfree_skb(skb);
2001 	}
2002 
2003 	ip6_cork_release(cork, v6_cork);
2004 }
2005 
2006 void ip6_flush_pending_frames(struct sock *sk)
2007 {
2008 	__ip6_flush_pending_frames(sk, &sk->sk_write_queue,
2009 				   &inet_sk(sk)->cork, &inet6_sk(sk)->cork);
2010 }
2011 EXPORT_SYMBOL_GPL(ip6_flush_pending_frames);
2012 
2013 struct sk_buff *ip6_make_skb(struct sock *sk,
2014 			     int getfrag(void *from, char *to, int offset,
2015 					 int len, int odd, struct sk_buff *skb),
2016 			     void *from, size_t length, int transhdrlen,
2017 			     struct ipcm6_cookie *ipc6, struct rt6_info *rt,
2018 			     unsigned int flags, struct inet_cork_full *cork)
2019 {
2020 	struct inet6_cork v6_cork;
2021 	struct sk_buff_head queue;
2022 	int exthdrlen = (ipc6->opt ? ipc6->opt->opt_flen : 0);
2023 	int err;
2024 
2025 	if (flags & MSG_PROBE) {
2026 		dst_release(&rt->dst);
2027 		return NULL;
2028 	}
2029 
2030 	__skb_queue_head_init(&queue);
2031 
2032 	cork->base.flags = 0;
2033 	cork->base.addr = 0;
2034 	cork->base.opt = NULL;
2035 	v6_cork.opt = NULL;
2036 	err = ip6_setup_cork(sk, cork, &v6_cork, ipc6, rt);
2037 	if (err) {
2038 		ip6_cork_release(cork, &v6_cork);
2039 		return ERR_PTR(err);
2040 	}
2041 	if (ipc6->dontfrag < 0)
2042 		ipc6->dontfrag = inet6_test_bit(DONTFRAG, sk);
2043 
2044 	err = __ip6_append_data(sk, &queue, cork, &v6_cork,
2045 				&current->task_frag, getfrag, from,
2046 				length + exthdrlen, transhdrlen + exthdrlen,
2047 				flags, ipc6);
2048 	if (err) {
2049 		__ip6_flush_pending_frames(sk, &queue, cork, &v6_cork);
2050 		return ERR_PTR(err);
2051 	}
2052 
2053 	return __ip6_make_skb(sk, &queue, cork, &v6_cork);
2054 }
2055