xref: /openbmc/linux/net/ipv4/ip_output.c (revision 9ad685db)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * INET		An implementation of the TCP/IP protocol suite for the LINUX
4  *		operating system.  INET is implemented using the  BSD Socket
5  *		interface as the means of communication with the user level.
6  *
7  *		The Internet Protocol (IP) output module.
8  *
9  * Authors:	Ross Biro
10  *		Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
11  *		Donald Becker, <becker@super.org>
12  *		Alan Cox, <Alan.Cox@linux.org>
13  *		Richard Underwood
14  *		Stefan Becker, <stefanb@yello.ping.de>
15  *		Jorge Cwik, <jorge@laser.satlink.net>
16  *		Arnt Gulbrandsen, <agulbra@nvg.unit.no>
17  *		Hirokazu Takahashi, <taka@valinux.co.jp>
18  *
19  *	See ip_input.c for original log
20  *
21  *	Fixes:
22  *		Alan Cox	:	Missing nonblock feature in ip_build_xmit.
23  *		Mike Kilburn	:	htons() missing in ip_build_xmit.
24  *		Bradford Johnson:	Fix faulty handling of some frames when
25  *					no route is found.
26  *		Alexander Demenshin:	Missing sk/skb free in ip_queue_xmit
27  *					(in case if packet not accepted by
28  *					output firewall rules)
29  *		Mike McLagan	:	Routing by source
30  *		Alexey Kuznetsov:	use new route cache
31  *		Andi Kleen:		Fix broken PMTU recovery and remove
32  *					some redundant tests.
33  *	Vitaly E. Lavrov	:	Transparent proxy revived after year coma.
34  *		Andi Kleen	: 	Replace ip_reply with ip_send_reply.
35  *		Andi Kleen	:	Split fast and slow ip_build_xmit path
36  *					for decreased register pressure on x86
37  *					and more readability.
38  *		Marc Boucher	:	When call_out_firewall returns FW_QUEUE,
39  *					silently drop skb instead of failing with -EPERM.
40  *		Detlev Wengorz	:	Copy protocol for fragments.
41  *		Hirokazu Takahashi:	HW checksumming for outgoing UDP
42  *					datagrams.
43  *		Hirokazu Takahashi:	sendfile() on UDP works now.
44  */
45 
46 #include <linux/uaccess.h>
47 #include <linux/module.h>
48 #include <linux/types.h>
49 #include <linux/kernel.h>
50 #include <linux/mm.h>
51 #include <linux/string.h>
52 #include <linux/errno.h>
53 #include <linux/highmem.h>
54 #include <linux/slab.h>
55 
56 #include <linux/socket.h>
57 #include <linux/sockios.h>
58 #include <linux/in.h>
59 #include <linux/inet.h>
60 #include <linux/netdevice.h>
61 #include <linux/etherdevice.h>
62 #include <linux/proc_fs.h>
63 #include <linux/stat.h>
64 #include <linux/init.h>
65 
66 #include <net/snmp.h>
67 #include <net/ip.h>
68 #include <net/protocol.h>
69 #include <net/route.h>
70 #include <net/xfrm.h>
71 #include <linux/skbuff.h>
72 #include <net/sock.h>
73 #include <net/arp.h>
74 #include <net/icmp.h>
75 #include <net/checksum.h>
76 #include <net/inetpeer.h>
77 #include <net/inet_ecn.h>
78 #include <net/lwtunnel.h>
79 #include <linux/bpf-cgroup.h>
80 #include <linux/igmp.h>
81 #include <linux/netfilter_ipv4.h>
82 #include <linux/netfilter_bridge.h>
83 #include <linux/netlink.h>
84 #include <linux/tcp.h>
85 
86 static int
87 ip_fragment(struct net *net, struct sock *sk, struct sk_buff *skb,
88 	    unsigned int mtu,
89 	    int (*output)(struct net *, struct sock *, struct sk_buff *));
90 
91 /* Generate a checksum for an outgoing IP datagram. */
92 void ip_send_check(struct iphdr *iph)
93 {
94 	iph->check = 0;
95 	iph->check = ip_fast_csum((unsigned char *)iph, iph->ihl);
96 }
97 EXPORT_SYMBOL(ip_send_check);
98 
99 int __ip_local_out(struct net *net, struct sock *sk, struct sk_buff *skb)
100 {
101 	struct iphdr *iph = ip_hdr(skb);
102 
103 	iph_set_totlen(iph, skb->len);
104 	ip_send_check(iph);
105 
106 	/* if egress device is enslaved to an L3 master device pass the
107 	 * skb to its handler for processing
108 	 */
109 	skb = l3mdev_ip_out(sk, skb);
110 	if (unlikely(!skb))
111 		return 0;
112 
113 	skb->protocol = htons(ETH_P_IP);
114 
115 	return nf_hook(NFPROTO_IPV4, NF_INET_LOCAL_OUT,
116 		       net, sk, skb, NULL, skb_dst(skb)->dev,
117 		       dst_output);
118 }
119 
120 int ip_local_out(struct net *net, struct sock *sk, struct sk_buff *skb)
121 {
122 	int err;
123 
124 	err = __ip_local_out(net, sk, skb);
125 	if (likely(err == 1))
126 		err = dst_output(net, sk, skb);
127 
128 	return err;
129 }
130 EXPORT_SYMBOL_GPL(ip_local_out);
131 
132 static inline int ip_select_ttl(const struct inet_sock *inet,
133 				const struct dst_entry *dst)
134 {
135 	int ttl = inet->uc_ttl;
136 
137 	if (ttl < 0)
138 		ttl = ip4_dst_hoplimit(dst);
139 	return ttl;
140 }
141 
142 /*
143  *		Add an ip header to a skbuff and send it out.
144  *
145  */
146 int ip_build_and_send_pkt(struct sk_buff *skb, const struct sock *sk,
147 			  __be32 saddr, __be32 daddr, struct ip_options_rcu *opt,
148 			  u8 tos)
149 {
150 	const struct inet_sock *inet = inet_sk(sk);
151 	struct rtable *rt = skb_rtable(skb);
152 	struct net *net = sock_net(sk);
153 	struct iphdr *iph;
154 
155 	/* Build the IP header. */
156 	skb_push(skb, sizeof(struct iphdr) + (opt ? opt->opt.optlen : 0));
157 	skb_reset_network_header(skb);
158 	iph = ip_hdr(skb);
159 	iph->version  = 4;
160 	iph->ihl      = 5;
161 	iph->tos      = tos;
162 	iph->ttl      = ip_select_ttl(inet, &rt->dst);
163 	iph->daddr    = (opt && opt->opt.srr ? opt->opt.faddr : daddr);
164 	iph->saddr    = saddr;
165 	iph->protocol = sk->sk_protocol;
166 	/* Do not bother generating IPID for small packets (eg SYNACK) */
167 	if (skb->len <= IPV4_MIN_MTU || ip_dont_fragment(sk, &rt->dst)) {
168 		iph->frag_off = htons(IP_DF);
169 		iph->id = 0;
170 	} else {
171 		iph->frag_off = 0;
172 		/* TCP packets here are SYNACK with fat IPv4/TCP options.
173 		 * Avoid using the hashed IP ident generator.
174 		 */
175 		if (sk->sk_protocol == IPPROTO_TCP)
176 			iph->id = (__force __be16)get_random_u16();
177 		else
178 			__ip_select_ident(net, iph, 1);
179 	}
180 
181 	if (opt && opt->opt.optlen) {
182 		iph->ihl += opt->opt.optlen>>2;
183 		ip_options_build(skb, &opt->opt, daddr, rt);
184 	}
185 
186 	skb->priority = sk->sk_priority;
187 	if (!skb->mark)
188 		skb->mark = sk->sk_mark;
189 
190 	/* Send it out. */
191 	return ip_local_out(net, skb->sk, skb);
192 }
193 EXPORT_SYMBOL_GPL(ip_build_and_send_pkt);
194 
195 static int ip_finish_output2(struct net *net, struct sock *sk, struct sk_buff *skb)
196 {
197 	struct dst_entry *dst = skb_dst(skb);
198 	struct rtable *rt = (struct rtable *)dst;
199 	struct net_device *dev = dst->dev;
200 	unsigned int hh_len = LL_RESERVED_SPACE(dev);
201 	struct neighbour *neigh;
202 	bool is_v6gw = false;
203 
204 	if (rt->rt_type == RTN_MULTICAST) {
205 		IP_UPD_PO_STATS(net, IPSTATS_MIB_OUTMCAST, skb->len);
206 	} else if (rt->rt_type == RTN_BROADCAST)
207 		IP_UPD_PO_STATS(net, IPSTATS_MIB_OUTBCAST, skb->len);
208 
209 	if (unlikely(skb_headroom(skb) < hh_len && dev->header_ops)) {
210 		skb = skb_expand_head(skb, hh_len);
211 		if (!skb)
212 			return -ENOMEM;
213 	}
214 
215 	if (lwtunnel_xmit_redirect(dst->lwtstate)) {
216 		int res = lwtunnel_xmit(skb);
217 
218 		if (res < 0 || res == LWTUNNEL_XMIT_DONE)
219 			return res;
220 	}
221 
222 	rcu_read_lock();
223 	neigh = ip_neigh_for_gw(rt, skb, &is_v6gw);
224 	if (!IS_ERR(neigh)) {
225 		int res;
226 
227 		sock_confirm_neigh(skb, neigh);
228 		/* if crossing protocols, can not use the cached header */
229 		res = neigh_output(neigh, skb, is_v6gw);
230 		rcu_read_unlock();
231 		return res;
232 	}
233 	rcu_read_unlock();
234 
235 	net_dbg_ratelimited("%s: No header cache and no neighbour!\n",
236 			    __func__);
237 	kfree_skb_reason(skb, SKB_DROP_REASON_NEIGH_CREATEFAIL);
238 	return -EINVAL;
239 }
240 
241 static int ip_finish_output_gso(struct net *net, struct sock *sk,
242 				struct sk_buff *skb, unsigned int mtu)
243 {
244 	struct sk_buff *segs, *nskb;
245 	netdev_features_t features;
246 	int ret = 0;
247 
248 	/* common case: seglen is <= mtu
249 	 */
250 	if (skb_gso_validate_network_len(skb, mtu))
251 		return ip_finish_output2(net, sk, skb);
252 
253 	/* Slowpath -  GSO segment length exceeds the egress MTU.
254 	 *
255 	 * This can happen in several cases:
256 	 *  - Forwarding of a TCP GRO skb, when DF flag is not set.
257 	 *  - Forwarding of an skb that arrived on a virtualization interface
258 	 *    (virtio-net/vhost/tap) with TSO/GSO size set by other network
259 	 *    stack.
260 	 *  - Local GSO skb transmitted on an NETIF_F_TSO tunnel stacked over an
261 	 *    interface with a smaller MTU.
262 	 *  - Arriving GRO skb (or GSO skb in a virtualized environment) that is
263 	 *    bridged to a NETIF_F_TSO tunnel stacked over an interface with an
264 	 *    insufficient MTU.
265 	 */
266 	features = netif_skb_features(skb);
267 	BUILD_BUG_ON(sizeof(*IPCB(skb)) > SKB_GSO_CB_OFFSET);
268 	segs = skb_gso_segment(skb, features & ~NETIF_F_GSO_MASK);
269 	if (IS_ERR_OR_NULL(segs)) {
270 		kfree_skb(skb);
271 		return -ENOMEM;
272 	}
273 
274 	consume_skb(skb);
275 
276 	skb_list_walk_safe(segs, segs, nskb) {
277 		int err;
278 
279 		skb_mark_not_on_list(segs);
280 		err = ip_fragment(net, sk, segs, mtu, ip_finish_output2);
281 
282 		if (err && ret == 0)
283 			ret = err;
284 	}
285 
286 	return ret;
287 }
288 
289 static int __ip_finish_output(struct net *net, struct sock *sk, struct sk_buff *skb)
290 {
291 	unsigned int mtu;
292 
293 #if defined(CONFIG_NETFILTER) && defined(CONFIG_XFRM)
294 	/* Policy lookup after SNAT yielded a new policy */
295 	if (skb_dst(skb)->xfrm) {
296 		IPCB(skb)->flags |= IPSKB_REROUTED;
297 		return dst_output(net, sk, skb);
298 	}
299 #endif
300 	mtu = ip_skb_dst_mtu(sk, skb);
301 	if (skb_is_gso(skb))
302 		return ip_finish_output_gso(net, sk, skb, mtu);
303 
304 	if (skb->len > mtu || IPCB(skb)->frag_max_size)
305 		return ip_fragment(net, sk, skb, mtu, ip_finish_output2);
306 
307 	return ip_finish_output2(net, sk, skb);
308 }
309 
310 static int ip_finish_output(struct net *net, struct sock *sk, struct sk_buff *skb)
311 {
312 	int ret;
313 
314 	ret = BPF_CGROUP_RUN_PROG_INET_EGRESS(sk, skb);
315 	switch (ret) {
316 	case NET_XMIT_SUCCESS:
317 		return __ip_finish_output(net, sk, skb);
318 	case NET_XMIT_CN:
319 		return __ip_finish_output(net, sk, skb) ? : ret;
320 	default:
321 		kfree_skb_reason(skb, SKB_DROP_REASON_BPF_CGROUP_EGRESS);
322 		return ret;
323 	}
324 }
325 
326 static int ip_mc_finish_output(struct net *net, struct sock *sk,
327 			       struct sk_buff *skb)
328 {
329 	struct rtable *new_rt;
330 	bool do_cn = false;
331 	int ret, err;
332 
333 	ret = BPF_CGROUP_RUN_PROG_INET_EGRESS(sk, skb);
334 	switch (ret) {
335 	case NET_XMIT_CN:
336 		do_cn = true;
337 		fallthrough;
338 	case NET_XMIT_SUCCESS:
339 		break;
340 	default:
341 		kfree_skb_reason(skb, SKB_DROP_REASON_BPF_CGROUP_EGRESS);
342 		return ret;
343 	}
344 
345 	/* Reset rt_iif so that inet_iif() will return skb->skb_iif. Setting
346 	 * this to non-zero causes ipi_ifindex in in_pktinfo to be overwritten,
347 	 * see ipv4_pktinfo_prepare().
348 	 */
349 	new_rt = rt_dst_clone(net->loopback_dev, skb_rtable(skb));
350 	if (new_rt) {
351 		new_rt->rt_iif = 0;
352 		skb_dst_drop(skb);
353 		skb_dst_set(skb, &new_rt->dst);
354 	}
355 
356 	err = dev_loopback_xmit(net, sk, skb);
357 	return (do_cn && err) ? ret : err;
358 }
359 
360 int ip_mc_output(struct net *net, struct sock *sk, struct sk_buff *skb)
361 {
362 	struct rtable *rt = skb_rtable(skb);
363 	struct net_device *dev = rt->dst.dev;
364 
365 	/*
366 	 *	If the indicated interface is up and running, send the packet.
367 	 */
368 	IP_UPD_PO_STATS(net, IPSTATS_MIB_OUT, skb->len);
369 
370 	skb->dev = dev;
371 	skb->protocol = htons(ETH_P_IP);
372 
373 	/*
374 	 *	Multicasts are looped back for other local users
375 	 */
376 
377 	if (rt->rt_flags&RTCF_MULTICAST) {
378 		if (sk_mc_loop(sk)
379 #ifdef CONFIG_IP_MROUTE
380 		/* Small optimization: do not loopback not local frames,
381 		   which returned after forwarding; they will be  dropped
382 		   by ip_mr_input in any case.
383 		   Note, that local frames are looped back to be delivered
384 		   to local recipients.
385 
386 		   This check is duplicated in ip_mr_input at the moment.
387 		 */
388 		    &&
389 		    ((rt->rt_flags & RTCF_LOCAL) ||
390 		     !(IPCB(skb)->flags & IPSKB_FORWARDED))
391 #endif
392 		   ) {
393 			struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC);
394 			if (newskb)
395 				NF_HOOK(NFPROTO_IPV4, NF_INET_POST_ROUTING,
396 					net, sk, newskb, NULL, newskb->dev,
397 					ip_mc_finish_output);
398 		}
399 
400 		/* Multicasts with ttl 0 must not go beyond the host */
401 
402 		if (ip_hdr(skb)->ttl == 0) {
403 			kfree_skb(skb);
404 			return 0;
405 		}
406 	}
407 
408 	if (rt->rt_flags&RTCF_BROADCAST) {
409 		struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC);
410 		if (newskb)
411 			NF_HOOK(NFPROTO_IPV4, NF_INET_POST_ROUTING,
412 				net, sk, newskb, NULL, newskb->dev,
413 				ip_mc_finish_output);
414 	}
415 
416 	return NF_HOOK_COND(NFPROTO_IPV4, NF_INET_POST_ROUTING,
417 			    net, sk, skb, NULL, skb->dev,
418 			    ip_finish_output,
419 			    !(IPCB(skb)->flags & IPSKB_REROUTED));
420 }
421 
422 int ip_output(struct net *net, struct sock *sk, struct sk_buff *skb)
423 {
424 	struct net_device *dev = skb_dst(skb)->dev, *indev = skb->dev;
425 
426 	IP_UPD_PO_STATS(net, IPSTATS_MIB_OUT, skb->len);
427 
428 	skb->dev = dev;
429 	skb->protocol = htons(ETH_P_IP);
430 
431 	return NF_HOOK_COND(NFPROTO_IPV4, NF_INET_POST_ROUTING,
432 			    net, sk, skb, indev, dev,
433 			    ip_finish_output,
434 			    !(IPCB(skb)->flags & IPSKB_REROUTED));
435 }
436 EXPORT_SYMBOL(ip_output);
437 
438 /*
439  * copy saddr and daddr, possibly using 64bit load/stores
440  * Equivalent to :
441  *   iph->saddr = fl4->saddr;
442  *   iph->daddr = fl4->daddr;
443  */
444 static void ip_copy_addrs(struct iphdr *iph, const struct flowi4 *fl4)
445 {
446 	BUILD_BUG_ON(offsetof(typeof(*fl4), daddr) !=
447 		     offsetof(typeof(*fl4), saddr) + sizeof(fl4->saddr));
448 
449 	iph->saddr = fl4->saddr;
450 	iph->daddr = fl4->daddr;
451 }
452 
453 /* Note: skb->sk can be different from sk, in case of tunnels */
454 int __ip_queue_xmit(struct sock *sk, struct sk_buff *skb, struct flowi *fl,
455 		    __u8 tos)
456 {
457 	struct inet_sock *inet = inet_sk(sk);
458 	struct net *net = sock_net(sk);
459 	struct ip_options_rcu *inet_opt;
460 	struct flowi4 *fl4;
461 	struct rtable *rt;
462 	struct iphdr *iph;
463 	int res;
464 
465 	/* Skip all of this if the packet is already routed,
466 	 * f.e. by something like SCTP.
467 	 */
468 	rcu_read_lock();
469 	inet_opt = rcu_dereference(inet->inet_opt);
470 	fl4 = &fl->u.ip4;
471 	rt = skb_rtable(skb);
472 	if (rt)
473 		goto packet_routed;
474 
475 	/* Make sure we can route this packet. */
476 	rt = (struct rtable *)__sk_dst_check(sk, 0);
477 	if (!rt) {
478 		__be32 daddr;
479 
480 		/* Use correct destination address if we have options. */
481 		daddr = inet->inet_daddr;
482 		if (inet_opt && inet_opt->opt.srr)
483 			daddr = inet_opt->opt.faddr;
484 
485 		/* If this fails, retransmit mechanism of transport layer will
486 		 * keep trying until route appears or the connection times
487 		 * itself out.
488 		 */
489 		rt = ip_route_output_ports(net, fl4, sk,
490 					   daddr, inet->inet_saddr,
491 					   inet->inet_dport,
492 					   inet->inet_sport,
493 					   sk->sk_protocol,
494 					   RT_CONN_FLAGS_TOS(sk, tos),
495 					   sk->sk_bound_dev_if);
496 		if (IS_ERR(rt))
497 			goto no_route;
498 		sk_setup_caps(sk, &rt->dst);
499 	}
500 	skb_dst_set_noref(skb, &rt->dst);
501 
502 packet_routed:
503 	if (inet_opt && inet_opt->opt.is_strictroute && rt->rt_uses_gateway)
504 		goto no_route;
505 
506 	/* OK, we know where to send it, allocate and build IP header. */
507 	skb_push(skb, sizeof(struct iphdr) + (inet_opt ? inet_opt->opt.optlen : 0));
508 	skb_reset_network_header(skb);
509 	iph = ip_hdr(skb);
510 	*((__be16 *)iph) = htons((4 << 12) | (5 << 8) | (tos & 0xff));
511 	if (ip_dont_fragment(sk, &rt->dst) && !skb->ignore_df)
512 		iph->frag_off = htons(IP_DF);
513 	else
514 		iph->frag_off = 0;
515 	iph->ttl      = ip_select_ttl(inet, &rt->dst);
516 	iph->protocol = sk->sk_protocol;
517 	ip_copy_addrs(iph, fl4);
518 
519 	/* Transport layer set skb->h.foo itself. */
520 
521 	if (inet_opt && inet_opt->opt.optlen) {
522 		iph->ihl += inet_opt->opt.optlen >> 2;
523 		ip_options_build(skb, &inet_opt->opt, inet->inet_daddr, rt);
524 	}
525 
526 	ip_select_ident_segs(net, skb, sk,
527 			     skb_shinfo(skb)->gso_segs ?: 1);
528 
529 	/* TODO : should we use skb->sk here instead of sk ? */
530 	skb->priority = sk->sk_priority;
531 	skb->mark = sk->sk_mark;
532 
533 	res = ip_local_out(net, sk, skb);
534 	rcu_read_unlock();
535 	return res;
536 
537 no_route:
538 	rcu_read_unlock();
539 	IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
540 	kfree_skb_reason(skb, SKB_DROP_REASON_IP_OUTNOROUTES);
541 	return -EHOSTUNREACH;
542 }
543 EXPORT_SYMBOL(__ip_queue_xmit);
544 
545 int ip_queue_xmit(struct sock *sk, struct sk_buff *skb, struct flowi *fl)
546 {
547 	return __ip_queue_xmit(sk, skb, fl, inet_sk(sk)->tos);
548 }
549 EXPORT_SYMBOL(ip_queue_xmit);
550 
551 static void ip_copy_metadata(struct sk_buff *to, struct sk_buff *from)
552 {
553 	to->pkt_type = from->pkt_type;
554 	to->priority = from->priority;
555 	to->protocol = from->protocol;
556 	to->skb_iif = from->skb_iif;
557 	skb_dst_drop(to);
558 	skb_dst_copy(to, from);
559 	to->dev = from->dev;
560 	to->mark = from->mark;
561 
562 	skb_copy_hash(to, from);
563 
564 #ifdef CONFIG_NET_SCHED
565 	to->tc_index = from->tc_index;
566 #endif
567 	nf_copy(to, from);
568 	skb_ext_copy(to, from);
569 #if IS_ENABLED(CONFIG_IP_VS)
570 	to->ipvs_property = from->ipvs_property;
571 #endif
572 	skb_copy_secmark(to, from);
573 }
574 
575 static int ip_fragment(struct net *net, struct sock *sk, struct sk_buff *skb,
576 		       unsigned int mtu,
577 		       int (*output)(struct net *, struct sock *, struct sk_buff *))
578 {
579 	struct iphdr *iph = ip_hdr(skb);
580 
581 	if ((iph->frag_off & htons(IP_DF)) == 0)
582 		return ip_do_fragment(net, sk, skb, output);
583 
584 	if (unlikely(!skb->ignore_df ||
585 		     (IPCB(skb)->frag_max_size &&
586 		      IPCB(skb)->frag_max_size > mtu))) {
587 		IP_INC_STATS(net, IPSTATS_MIB_FRAGFAILS);
588 		icmp_send(skb, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED,
589 			  htonl(mtu));
590 		kfree_skb(skb);
591 		return -EMSGSIZE;
592 	}
593 
594 	return ip_do_fragment(net, sk, skb, output);
595 }
596 
597 void ip_fraglist_init(struct sk_buff *skb, struct iphdr *iph,
598 		      unsigned int hlen, struct ip_fraglist_iter *iter)
599 {
600 	unsigned int first_len = skb_pagelen(skb);
601 
602 	iter->frag = skb_shinfo(skb)->frag_list;
603 	skb_frag_list_init(skb);
604 
605 	iter->offset = 0;
606 	iter->iph = iph;
607 	iter->hlen = hlen;
608 
609 	skb->data_len = first_len - skb_headlen(skb);
610 	skb->len = first_len;
611 	iph->tot_len = htons(first_len);
612 	iph->frag_off = htons(IP_MF);
613 	ip_send_check(iph);
614 }
615 EXPORT_SYMBOL(ip_fraglist_init);
616 
617 void ip_fraglist_prepare(struct sk_buff *skb, struct ip_fraglist_iter *iter)
618 {
619 	unsigned int hlen = iter->hlen;
620 	struct iphdr *iph = iter->iph;
621 	struct sk_buff *frag;
622 
623 	frag = iter->frag;
624 	frag->ip_summed = CHECKSUM_NONE;
625 	skb_reset_transport_header(frag);
626 	__skb_push(frag, hlen);
627 	skb_reset_network_header(frag);
628 	memcpy(skb_network_header(frag), iph, hlen);
629 	iter->iph = ip_hdr(frag);
630 	iph = iter->iph;
631 	iph->tot_len = htons(frag->len);
632 	ip_copy_metadata(frag, skb);
633 	iter->offset += skb->len - hlen;
634 	iph->frag_off = htons(iter->offset >> 3);
635 	if (frag->next)
636 		iph->frag_off |= htons(IP_MF);
637 	/* Ready, complete checksum */
638 	ip_send_check(iph);
639 }
640 EXPORT_SYMBOL(ip_fraglist_prepare);
641 
642 void ip_frag_init(struct sk_buff *skb, unsigned int hlen,
643 		  unsigned int ll_rs, unsigned int mtu, bool DF,
644 		  struct ip_frag_state *state)
645 {
646 	struct iphdr *iph = ip_hdr(skb);
647 
648 	state->DF = DF;
649 	state->hlen = hlen;
650 	state->ll_rs = ll_rs;
651 	state->mtu = mtu;
652 
653 	state->left = skb->len - hlen;	/* Space per frame */
654 	state->ptr = hlen;		/* Where to start from */
655 
656 	state->offset = (ntohs(iph->frag_off) & IP_OFFSET) << 3;
657 	state->not_last_frag = iph->frag_off & htons(IP_MF);
658 }
659 EXPORT_SYMBOL(ip_frag_init);
660 
661 static void ip_frag_ipcb(struct sk_buff *from, struct sk_buff *to,
662 			 bool first_frag)
663 {
664 	/* Copy the flags to each fragment. */
665 	IPCB(to)->flags = IPCB(from)->flags;
666 
667 	/* ANK: dirty, but effective trick. Upgrade options only if
668 	 * the segment to be fragmented was THE FIRST (otherwise,
669 	 * options are already fixed) and make it ONCE
670 	 * on the initial skb, so that all the following fragments
671 	 * will inherit fixed options.
672 	 */
673 	if (first_frag)
674 		ip_options_fragment(from);
675 }
676 
677 struct sk_buff *ip_frag_next(struct sk_buff *skb, struct ip_frag_state *state)
678 {
679 	unsigned int len = state->left;
680 	struct sk_buff *skb2;
681 	struct iphdr *iph;
682 
683 	/* IF: it doesn't fit, use 'mtu' - the data space left */
684 	if (len > state->mtu)
685 		len = state->mtu;
686 	/* IF: we are not sending up to and including the packet end
687 	   then align the next start on an eight byte boundary */
688 	if (len < state->left)	{
689 		len &= ~7;
690 	}
691 
692 	/* Allocate buffer */
693 	skb2 = alloc_skb(len + state->hlen + state->ll_rs, GFP_ATOMIC);
694 	if (!skb2)
695 		return ERR_PTR(-ENOMEM);
696 
697 	/*
698 	 *	Set up data on packet
699 	 */
700 
701 	ip_copy_metadata(skb2, skb);
702 	skb_reserve(skb2, state->ll_rs);
703 	skb_put(skb2, len + state->hlen);
704 	skb_reset_network_header(skb2);
705 	skb2->transport_header = skb2->network_header + state->hlen;
706 
707 	/*
708 	 *	Charge the memory for the fragment to any owner
709 	 *	it might possess
710 	 */
711 
712 	if (skb->sk)
713 		skb_set_owner_w(skb2, skb->sk);
714 
715 	/*
716 	 *	Copy the packet header into the new buffer.
717 	 */
718 
719 	skb_copy_from_linear_data(skb, skb_network_header(skb2), state->hlen);
720 
721 	/*
722 	 *	Copy a block of the IP datagram.
723 	 */
724 	if (skb_copy_bits(skb, state->ptr, skb_transport_header(skb2), len))
725 		BUG();
726 	state->left -= len;
727 
728 	/*
729 	 *	Fill in the new header fields.
730 	 */
731 	iph = ip_hdr(skb2);
732 	iph->frag_off = htons((state->offset >> 3));
733 	if (state->DF)
734 		iph->frag_off |= htons(IP_DF);
735 
736 	/*
737 	 *	Added AC : If we are fragmenting a fragment that's not the
738 	 *		   last fragment then keep MF on each bit
739 	 */
740 	if (state->left > 0 || state->not_last_frag)
741 		iph->frag_off |= htons(IP_MF);
742 	state->ptr += len;
743 	state->offset += len;
744 
745 	iph->tot_len = htons(len + state->hlen);
746 
747 	ip_send_check(iph);
748 
749 	return skb2;
750 }
751 EXPORT_SYMBOL(ip_frag_next);
752 
753 /*
754  *	This IP datagram is too large to be sent in one piece.  Break it up into
755  *	smaller pieces (each of size equal to IP header plus
756  *	a block of the data of the original IP data part) that will yet fit in a
757  *	single device frame, and queue such a frame for sending.
758  */
759 
760 int ip_do_fragment(struct net *net, struct sock *sk, struct sk_buff *skb,
761 		   int (*output)(struct net *, struct sock *, struct sk_buff *))
762 {
763 	struct iphdr *iph;
764 	struct sk_buff *skb2;
765 	bool mono_delivery_time = skb->mono_delivery_time;
766 	struct rtable *rt = skb_rtable(skb);
767 	unsigned int mtu, hlen, ll_rs;
768 	struct ip_fraglist_iter iter;
769 	ktime_t tstamp = skb->tstamp;
770 	struct ip_frag_state state;
771 	int err = 0;
772 
773 	/* for offloaded checksums cleanup checksum before fragmentation */
774 	if (skb->ip_summed == CHECKSUM_PARTIAL &&
775 	    (err = skb_checksum_help(skb)))
776 		goto fail;
777 
778 	/*
779 	 *	Point into the IP datagram header.
780 	 */
781 
782 	iph = ip_hdr(skb);
783 
784 	mtu = ip_skb_dst_mtu(sk, skb);
785 	if (IPCB(skb)->frag_max_size && IPCB(skb)->frag_max_size < mtu)
786 		mtu = IPCB(skb)->frag_max_size;
787 
788 	/*
789 	 *	Setup starting values.
790 	 */
791 
792 	hlen = iph->ihl * 4;
793 	mtu = mtu - hlen;	/* Size of data space */
794 	IPCB(skb)->flags |= IPSKB_FRAG_COMPLETE;
795 	ll_rs = LL_RESERVED_SPACE(rt->dst.dev);
796 
797 	/* When frag_list is given, use it. First, check its validity:
798 	 * some transformers could create wrong frag_list or break existing
799 	 * one, it is not prohibited. In this case fall back to copying.
800 	 *
801 	 * LATER: this step can be merged to real generation of fragments,
802 	 * we can switch to copy when see the first bad fragment.
803 	 */
804 	if (skb_has_frag_list(skb)) {
805 		struct sk_buff *frag, *frag2;
806 		unsigned int first_len = skb_pagelen(skb);
807 
808 		if (first_len - hlen > mtu ||
809 		    ((first_len - hlen) & 7) ||
810 		    ip_is_fragment(iph) ||
811 		    skb_cloned(skb) ||
812 		    skb_headroom(skb) < ll_rs)
813 			goto slow_path;
814 
815 		skb_walk_frags(skb, frag) {
816 			/* Correct geometry. */
817 			if (frag->len > mtu ||
818 			    ((frag->len & 7) && frag->next) ||
819 			    skb_headroom(frag) < hlen + ll_rs)
820 				goto slow_path_clean;
821 
822 			/* Partially cloned skb? */
823 			if (skb_shared(frag))
824 				goto slow_path_clean;
825 
826 			BUG_ON(frag->sk);
827 			if (skb->sk) {
828 				frag->sk = skb->sk;
829 				frag->destructor = sock_wfree;
830 			}
831 			skb->truesize -= frag->truesize;
832 		}
833 
834 		/* Everything is OK. Generate! */
835 		ip_fraglist_init(skb, iph, hlen, &iter);
836 
837 		for (;;) {
838 			/* Prepare header of the next frame,
839 			 * before previous one went down. */
840 			if (iter.frag) {
841 				bool first_frag = (iter.offset == 0);
842 
843 				IPCB(iter.frag)->flags = IPCB(skb)->flags;
844 				ip_fraglist_prepare(skb, &iter);
845 				if (first_frag && IPCB(skb)->opt.optlen) {
846 					/* ipcb->opt is not populated for frags
847 					 * coming from __ip_make_skb(),
848 					 * ip_options_fragment() needs optlen
849 					 */
850 					IPCB(iter.frag)->opt.optlen =
851 						IPCB(skb)->opt.optlen;
852 					ip_options_fragment(iter.frag);
853 					ip_send_check(iter.iph);
854 				}
855 			}
856 
857 			skb_set_delivery_time(skb, tstamp, mono_delivery_time);
858 			err = output(net, sk, skb);
859 
860 			if (!err)
861 				IP_INC_STATS(net, IPSTATS_MIB_FRAGCREATES);
862 			if (err || !iter.frag)
863 				break;
864 
865 			skb = ip_fraglist_next(&iter);
866 		}
867 
868 		if (err == 0) {
869 			IP_INC_STATS(net, IPSTATS_MIB_FRAGOKS);
870 			return 0;
871 		}
872 
873 		kfree_skb_list(iter.frag);
874 
875 		IP_INC_STATS(net, IPSTATS_MIB_FRAGFAILS);
876 		return err;
877 
878 slow_path_clean:
879 		skb_walk_frags(skb, frag2) {
880 			if (frag2 == frag)
881 				break;
882 			frag2->sk = NULL;
883 			frag2->destructor = NULL;
884 			skb->truesize += frag2->truesize;
885 		}
886 	}
887 
888 slow_path:
889 	/*
890 	 *	Fragment the datagram.
891 	 */
892 
893 	ip_frag_init(skb, hlen, ll_rs, mtu, IPCB(skb)->flags & IPSKB_FRAG_PMTU,
894 		     &state);
895 
896 	/*
897 	 *	Keep copying data until we run out.
898 	 */
899 
900 	while (state.left > 0) {
901 		bool first_frag = (state.offset == 0);
902 
903 		skb2 = ip_frag_next(skb, &state);
904 		if (IS_ERR(skb2)) {
905 			err = PTR_ERR(skb2);
906 			goto fail;
907 		}
908 		ip_frag_ipcb(skb, skb2, first_frag);
909 
910 		/*
911 		 *	Put this fragment into the sending queue.
912 		 */
913 		skb_set_delivery_time(skb2, tstamp, mono_delivery_time);
914 		err = output(net, sk, skb2);
915 		if (err)
916 			goto fail;
917 
918 		IP_INC_STATS(net, IPSTATS_MIB_FRAGCREATES);
919 	}
920 	consume_skb(skb);
921 	IP_INC_STATS(net, IPSTATS_MIB_FRAGOKS);
922 	return err;
923 
924 fail:
925 	kfree_skb(skb);
926 	IP_INC_STATS(net, IPSTATS_MIB_FRAGFAILS);
927 	return err;
928 }
929 EXPORT_SYMBOL(ip_do_fragment);
930 
931 int
932 ip_generic_getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb)
933 {
934 	struct msghdr *msg = from;
935 
936 	if (skb->ip_summed == CHECKSUM_PARTIAL) {
937 		if (!copy_from_iter_full(to, len, &msg->msg_iter))
938 			return -EFAULT;
939 	} else {
940 		__wsum csum = 0;
941 		if (!csum_and_copy_from_iter_full(to, len, &csum, &msg->msg_iter))
942 			return -EFAULT;
943 		skb->csum = csum_block_add(skb->csum, csum, odd);
944 	}
945 	return 0;
946 }
947 EXPORT_SYMBOL(ip_generic_getfrag);
948 
949 static inline __wsum
950 csum_page(struct page *page, int offset, int copy)
951 {
952 	char *kaddr;
953 	__wsum csum;
954 	kaddr = kmap(page);
955 	csum = csum_partial(kaddr + offset, copy, 0);
956 	kunmap(page);
957 	return csum;
958 }
959 
960 static int __ip_append_data(struct sock *sk,
961 			    struct flowi4 *fl4,
962 			    struct sk_buff_head *queue,
963 			    struct inet_cork *cork,
964 			    struct page_frag *pfrag,
965 			    int getfrag(void *from, char *to, int offset,
966 					int len, int odd, struct sk_buff *skb),
967 			    void *from, int length, int transhdrlen,
968 			    unsigned int flags)
969 {
970 	struct inet_sock *inet = inet_sk(sk);
971 	struct ubuf_info *uarg = NULL;
972 	struct sk_buff *skb;
973 	struct ip_options *opt = cork->opt;
974 	int hh_len;
975 	int exthdrlen;
976 	int mtu;
977 	int copy;
978 	int err;
979 	int offset = 0;
980 	bool zc = false;
981 	unsigned int maxfraglen, fragheaderlen, maxnonfragsize;
982 	int csummode = CHECKSUM_NONE;
983 	struct rtable *rt = (struct rtable *)cork->dst;
984 	unsigned int wmem_alloc_delta = 0;
985 	bool paged, extra_uref = false;
986 	u32 tskey = 0;
987 
988 	skb = skb_peek_tail(queue);
989 
990 	exthdrlen = !skb ? rt->dst.header_len : 0;
991 	mtu = cork->gso_size ? IP_MAX_MTU : cork->fragsize;
992 	paged = !!cork->gso_size;
993 
994 	if (cork->tx_flags & SKBTX_ANY_TSTAMP &&
995 	    sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)
996 		tskey = atomic_inc_return(&sk->sk_tskey) - 1;
997 
998 	hh_len = LL_RESERVED_SPACE(rt->dst.dev);
999 
1000 	fragheaderlen = sizeof(struct iphdr) + (opt ? opt->optlen : 0);
1001 	maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen;
1002 	maxnonfragsize = ip_sk_ignore_df(sk) ? IP_MAX_MTU : mtu;
1003 
1004 	if (cork->length + length > maxnonfragsize - fragheaderlen) {
1005 		ip_local_error(sk, EMSGSIZE, fl4->daddr, inet->inet_dport,
1006 			       mtu - (opt ? opt->optlen : 0));
1007 		return -EMSGSIZE;
1008 	}
1009 
1010 	/*
1011 	 * transhdrlen > 0 means that this is the first fragment and we wish
1012 	 * it won't be fragmented in the future.
1013 	 */
1014 	if (transhdrlen &&
1015 	    length + fragheaderlen <= mtu &&
1016 	    rt->dst.dev->features & (NETIF_F_HW_CSUM | NETIF_F_IP_CSUM) &&
1017 	    (!(flags & MSG_MORE) || cork->gso_size) &&
1018 	    (!exthdrlen || (rt->dst.dev->features & NETIF_F_HW_ESP_TX_CSUM)))
1019 		csummode = CHECKSUM_PARTIAL;
1020 
1021 	if ((flags & MSG_ZEROCOPY) && length) {
1022 		struct msghdr *msg = from;
1023 
1024 		if (getfrag == ip_generic_getfrag && msg->msg_ubuf) {
1025 			if (skb_zcopy(skb) && msg->msg_ubuf != skb_zcopy(skb))
1026 				return -EINVAL;
1027 
1028 			/* Leave uarg NULL if can't zerocopy, callers should
1029 			 * be able to handle it.
1030 			 */
1031 			if ((rt->dst.dev->features & NETIF_F_SG) &&
1032 			    csummode == CHECKSUM_PARTIAL) {
1033 				paged = true;
1034 				zc = true;
1035 				uarg = msg->msg_ubuf;
1036 			}
1037 		} else if (sock_flag(sk, SOCK_ZEROCOPY)) {
1038 			uarg = msg_zerocopy_realloc(sk, length, skb_zcopy(skb));
1039 			if (!uarg)
1040 				return -ENOBUFS;
1041 			extra_uref = !skb_zcopy(skb);	/* only ref on new uarg */
1042 			if (rt->dst.dev->features & NETIF_F_SG &&
1043 			    csummode == CHECKSUM_PARTIAL) {
1044 				paged = true;
1045 				zc = true;
1046 			} else {
1047 				uarg_to_msgzc(uarg)->zerocopy = 0;
1048 				skb_zcopy_set(skb, uarg, &extra_uref);
1049 			}
1050 		}
1051 	}
1052 
1053 	cork->length += length;
1054 
1055 	/* So, what's going on in the loop below?
1056 	 *
1057 	 * We use calculated fragment length to generate chained skb,
1058 	 * each of segments is IP fragment ready for sending to network after
1059 	 * adding appropriate IP header.
1060 	 */
1061 
1062 	if (!skb)
1063 		goto alloc_new_skb;
1064 
1065 	while (length > 0) {
1066 		/* Check if the remaining data fits into current packet. */
1067 		copy = mtu - skb->len;
1068 		if (copy < length)
1069 			copy = maxfraglen - skb->len;
1070 		if (copy <= 0) {
1071 			char *data;
1072 			unsigned int datalen;
1073 			unsigned int fraglen;
1074 			unsigned int fraggap;
1075 			unsigned int alloclen, alloc_extra;
1076 			unsigned int pagedlen;
1077 			struct sk_buff *skb_prev;
1078 alloc_new_skb:
1079 			skb_prev = skb;
1080 			if (skb_prev)
1081 				fraggap = skb_prev->len - maxfraglen;
1082 			else
1083 				fraggap = 0;
1084 
1085 			/*
1086 			 * If remaining data exceeds the mtu,
1087 			 * we know we need more fragment(s).
1088 			 */
1089 			datalen = length + fraggap;
1090 			if (datalen > mtu - fragheaderlen)
1091 				datalen = maxfraglen - fragheaderlen;
1092 			fraglen = datalen + fragheaderlen;
1093 			pagedlen = 0;
1094 
1095 			alloc_extra = hh_len + 15;
1096 			alloc_extra += exthdrlen;
1097 
1098 			/* The last fragment gets additional space at tail.
1099 			 * Note, with MSG_MORE we overallocate on fragments,
1100 			 * because we have no idea what fragment will be
1101 			 * the last.
1102 			 */
1103 			if (datalen == length + fraggap)
1104 				alloc_extra += rt->dst.trailer_len;
1105 
1106 			if ((flags & MSG_MORE) &&
1107 			    !(rt->dst.dev->features&NETIF_F_SG))
1108 				alloclen = mtu;
1109 			else if (!paged &&
1110 				 (fraglen + alloc_extra < SKB_MAX_ALLOC ||
1111 				  !(rt->dst.dev->features & NETIF_F_SG)))
1112 				alloclen = fraglen;
1113 			else {
1114 				alloclen = fragheaderlen + transhdrlen;
1115 				pagedlen = datalen - transhdrlen;
1116 			}
1117 
1118 			alloclen += alloc_extra;
1119 
1120 			if (transhdrlen) {
1121 				skb = sock_alloc_send_skb(sk, alloclen,
1122 						(flags & MSG_DONTWAIT), &err);
1123 			} else {
1124 				skb = NULL;
1125 				if (refcount_read(&sk->sk_wmem_alloc) + wmem_alloc_delta <=
1126 				    2 * sk->sk_sndbuf)
1127 					skb = alloc_skb(alloclen,
1128 							sk->sk_allocation);
1129 				if (unlikely(!skb))
1130 					err = -ENOBUFS;
1131 			}
1132 			if (!skb)
1133 				goto error;
1134 
1135 			/*
1136 			 *	Fill in the control structures
1137 			 */
1138 			skb->ip_summed = csummode;
1139 			skb->csum = 0;
1140 			skb_reserve(skb, hh_len);
1141 
1142 			/*
1143 			 *	Find where to start putting bytes.
1144 			 */
1145 			data = skb_put(skb, fraglen + exthdrlen - pagedlen);
1146 			skb_set_network_header(skb, exthdrlen);
1147 			skb->transport_header = (skb->network_header +
1148 						 fragheaderlen);
1149 			data += fragheaderlen + exthdrlen;
1150 
1151 			if (fraggap) {
1152 				skb->csum = skb_copy_and_csum_bits(
1153 					skb_prev, maxfraglen,
1154 					data + transhdrlen, fraggap);
1155 				skb_prev->csum = csum_sub(skb_prev->csum,
1156 							  skb->csum);
1157 				data += fraggap;
1158 				pskb_trim_unique(skb_prev, maxfraglen);
1159 			}
1160 
1161 			copy = datalen - transhdrlen - fraggap - pagedlen;
1162 			if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) {
1163 				err = -EFAULT;
1164 				kfree_skb(skb);
1165 				goto error;
1166 			}
1167 
1168 			offset += copy;
1169 			length -= copy + transhdrlen;
1170 			transhdrlen = 0;
1171 			exthdrlen = 0;
1172 			csummode = CHECKSUM_NONE;
1173 
1174 			/* only the initial fragment is time stamped */
1175 			skb_shinfo(skb)->tx_flags = cork->tx_flags;
1176 			cork->tx_flags = 0;
1177 			skb_shinfo(skb)->tskey = tskey;
1178 			tskey = 0;
1179 			skb_zcopy_set(skb, uarg, &extra_uref);
1180 
1181 			if ((flags & MSG_CONFIRM) && !skb_prev)
1182 				skb_set_dst_pending_confirm(skb, 1);
1183 
1184 			/*
1185 			 * Put the packet on the pending queue.
1186 			 */
1187 			if (!skb->destructor) {
1188 				skb->destructor = sock_wfree;
1189 				skb->sk = sk;
1190 				wmem_alloc_delta += skb->truesize;
1191 			}
1192 			__skb_queue_tail(queue, skb);
1193 			continue;
1194 		}
1195 
1196 		if (copy > length)
1197 			copy = length;
1198 
1199 		if (!(rt->dst.dev->features&NETIF_F_SG) &&
1200 		    skb_tailroom(skb) >= copy) {
1201 			unsigned int off;
1202 
1203 			off = skb->len;
1204 			if (getfrag(from, skb_put(skb, copy),
1205 					offset, copy, off, skb) < 0) {
1206 				__skb_trim(skb, off);
1207 				err = -EFAULT;
1208 				goto error;
1209 			}
1210 		} else if (!zc) {
1211 			int i = skb_shinfo(skb)->nr_frags;
1212 
1213 			err = -ENOMEM;
1214 			if (!sk_page_frag_refill(sk, pfrag))
1215 				goto error;
1216 
1217 			skb_zcopy_downgrade_managed(skb);
1218 			if (!skb_can_coalesce(skb, i, pfrag->page,
1219 					      pfrag->offset)) {
1220 				err = -EMSGSIZE;
1221 				if (i == MAX_SKB_FRAGS)
1222 					goto error;
1223 
1224 				__skb_fill_page_desc(skb, i, pfrag->page,
1225 						     pfrag->offset, 0);
1226 				skb_shinfo(skb)->nr_frags = ++i;
1227 				get_page(pfrag->page);
1228 			}
1229 			copy = min_t(int, copy, pfrag->size - pfrag->offset);
1230 			if (getfrag(from,
1231 				    page_address(pfrag->page) + pfrag->offset,
1232 				    offset, copy, skb->len, skb) < 0)
1233 				goto error_efault;
1234 
1235 			pfrag->offset += copy;
1236 			skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
1237 			skb_len_add(skb, copy);
1238 			wmem_alloc_delta += copy;
1239 		} else {
1240 			err = skb_zerocopy_iter_dgram(skb, from, copy);
1241 			if (err < 0)
1242 				goto error;
1243 		}
1244 		offset += copy;
1245 		length -= copy;
1246 	}
1247 
1248 	if (wmem_alloc_delta)
1249 		refcount_add(wmem_alloc_delta, &sk->sk_wmem_alloc);
1250 	return 0;
1251 
1252 error_efault:
1253 	err = -EFAULT;
1254 error:
1255 	net_zcopy_put_abort(uarg, extra_uref);
1256 	cork->length -= length;
1257 	IP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTDISCARDS);
1258 	refcount_add(wmem_alloc_delta, &sk->sk_wmem_alloc);
1259 	return err;
1260 }
1261 
1262 static int ip_setup_cork(struct sock *sk, struct inet_cork *cork,
1263 			 struct ipcm_cookie *ipc, struct rtable **rtp)
1264 {
1265 	struct ip_options_rcu *opt;
1266 	struct rtable *rt;
1267 
1268 	rt = *rtp;
1269 	if (unlikely(!rt))
1270 		return -EFAULT;
1271 
1272 	/*
1273 	 * setup for corking.
1274 	 */
1275 	opt = ipc->opt;
1276 	if (opt) {
1277 		if (!cork->opt) {
1278 			cork->opt = kmalloc(sizeof(struct ip_options) + 40,
1279 					    sk->sk_allocation);
1280 			if (unlikely(!cork->opt))
1281 				return -ENOBUFS;
1282 		}
1283 		memcpy(cork->opt, &opt->opt, sizeof(struct ip_options) + opt->opt.optlen);
1284 		cork->flags |= IPCORK_OPT;
1285 		cork->addr = ipc->addr;
1286 	}
1287 
1288 	cork->fragsize = ip_sk_use_pmtu(sk) ?
1289 			 dst_mtu(&rt->dst) : READ_ONCE(rt->dst.dev->mtu);
1290 
1291 	if (!inetdev_valid_mtu(cork->fragsize))
1292 		return -ENETUNREACH;
1293 
1294 	cork->gso_size = ipc->gso_size;
1295 
1296 	cork->dst = &rt->dst;
1297 	/* We stole this route, caller should not release it. */
1298 	*rtp = NULL;
1299 
1300 	cork->length = 0;
1301 	cork->ttl = ipc->ttl;
1302 	cork->tos = ipc->tos;
1303 	cork->mark = ipc->sockc.mark;
1304 	cork->priority = ipc->priority;
1305 	cork->transmit_time = ipc->sockc.transmit_time;
1306 	cork->tx_flags = 0;
1307 	sock_tx_timestamp(sk, ipc->sockc.tsflags, &cork->tx_flags);
1308 
1309 	return 0;
1310 }
1311 
1312 /*
1313  *	ip_append_data() and ip_append_page() can make one large IP datagram
1314  *	from many pieces of data. Each pieces will be holded on the socket
1315  *	until ip_push_pending_frames() is called. Each piece can be a page
1316  *	or non-page data.
1317  *
1318  *	Not only UDP, other transport protocols - e.g. raw sockets - can use
1319  *	this interface potentially.
1320  *
1321  *	LATER: length must be adjusted by pad at tail, when it is required.
1322  */
1323 int ip_append_data(struct sock *sk, struct flowi4 *fl4,
1324 		   int getfrag(void *from, char *to, int offset, int len,
1325 			       int odd, struct sk_buff *skb),
1326 		   void *from, int length, int transhdrlen,
1327 		   struct ipcm_cookie *ipc, struct rtable **rtp,
1328 		   unsigned int flags)
1329 {
1330 	struct inet_sock *inet = inet_sk(sk);
1331 	int err;
1332 
1333 	if (flags&MSG_PROBE)
1334 		return 0;
1335 
1336 	if (skb_queue_empty(&sk->sk_write_queue)) {
1337 		err = ip_setup_cork(sk, &inet->cork.base, ipc, rtp);
1338 		if (err)
1339 			return err;
1340 	} else {
1341 		transhdrlen = 0;
1342 	}
1343 
1344 	return __ip_append_data(sk, fl4, &sk->sk_write_queue, &inet->cork.base,
1345 				sk_page_frag(sk), getfrag,
1346 				from, length, transhdrlen, flags);
1347 }
1348 
1349 ssize_t	ip_append_page(struct sock *sk, struct flowi4 *fl4, struct page *page,
1350 		       int offset, size_t size, int flags)
1351 {
1352 	struct inet_sock *inet = inet_sk(sk);
1353 	struct sk_buff *skb;
1354 	struct rtable *rt;
1355 	struct ip_options *opt = NULL;
1356 	struct inet_cork *cork;
1357 	int hh_len;
1358 	int mtu;
1359 	int len;
1360 	int err;
1361 	unsigned int maxfraglen, fragheaderlen, fraggap, maxnonfragsize;
1362 
1363 	if (inet->hdrincl)
1364 		return -EPERM;
1365 
1366 	if (flags&MSG_PROBE)
1367 		return 0;
1368 
1369 	if (skb_queue_empty(&sk->sk_write_queue))
1370 		return -EINVAL;
1371 
1372 	cork = &inet->cork.base;
1373 	rt = (struct rtable *)cork->dst;
1374 	if (cork->flags & IPCORK_OPT)
1375 		opt = cork->opt;
1376 
1377 	if (!(rt->dst.dev->features & NETIF_F_SG))
1378 		return -EOPNOTSUPP;
1379 
1380 	hh_len = LL_RESERVED_SPACE(rt->dst.dev);
1381 	mtu = cork->gso_size ? IP_MAX_MTU : cork->fragsize;
1382 
1383 	fragheaderlen = sizeof(struct iphdr) + (opt ? opt->optlen : 0);
1384 	maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen;
1385 	maxnonfragsize = ip_sk_ignore_df(sk) ? 0xFFFF : mtu;
1386 
1387 	if (cork->length + size > maxnonfragsize - fragheaderlen) {
1388 		ip_local_error(sk, EMSGSIZE, fl4->daddr, inet->inet_dport,
1389 			       mtu - (opt ? opt->optlen : 0));
1390 		return -EMSGSIZE;
1391 	}
1392 
1393 	skb = skb_peek_tail(&sk->sk_write_queue);
1394 	if (!skb)
1395 		return -EINVAL;
1396 
1397 	cork->length += size;
1398 
1399 	while (size > 0) {
1400 		/* Check if the remaining data fits into current packet. */
1401 		len = mtu - skb->len;
1402 		if (len < size)
1403 			len = maxfraglen - skb->len;
1404 
1405 		if (len <= 0) {
1406 			struct sk_buff *skb_prev;
1407 			int alloclen;
1408 
1409 			skb_prev = skb;
1410 			fraggap = skb_prev->len - maxfraglen;
1411 
1412 			alloclen = fragheaderlen + hh_len + fraggap + 15;
1413 			skb = sock_wmalloc(sk, alloclen, 1, sk->sk_allocation);
1414 			if (unlikely(!skb)) {
1415 				err = -ENOBUFS;
1416 				goto error;
1417 			}
1418 
1419 			/*
1420 			 *	Fill in the control structures
1421 			 */
1422 			skb->ip_summed = CHECKSUM_NONE;
1423 			skb->csum = 0;
1424 			skb_reserve(skb, hh_len);
1425 
1426 			/*
1427 			 *	Find where to start putting bytes.
1428 			 */
1429 			skb_put(skb, fragheaderlen + fraggap);
1430 			skb_reset_network_header(skb);
1431 			skb->transport_header = (skb->network_header +
1432 						 fragheaderlen);
1433 			if (fraggap) {
1434 				skb->csum = skb_copy_and_csum_bits(skb_prev,
1435 								   maxfraglen,
1436 						    skb_transport_header(skb),
1437 								   fraggap);
1438 				skb_prev->csum = csum_sub(skb_prev->csum,
1439 							  skb->csum);
1440 				pskb_trim_unique(skb_prev, maxfraglen);
1441 			}
1442 
1443 			/*
1444 			 * Put the packet on the pending queue.
1445 			 */
1446 			__skb_queue_tail(&sk->sk_write_queue, skb);
1447 			continue;
1448 		}
1449 
1450 		if (len > size)
1451 			len = size;
1452 
1453 		if (skb_append_pagefrags(skb, page, offset, len)) {
1454 			err = -EMSGSIZE;
1455 			goto error;
1456 		}
1457 
1458 		if (skb->ip_summed == CHECKSUM_NONE) {
1459 			__wsum csum;
1460 			csum = csum_page(page, offset, len);
1461 			skb->csum = csum_block_add(skb->csum, csum, skb->len);
1462 		}
1463 
1464 		skb_len_add(skb, len);
1465 		refcount_add(len, &sk->sk_wmem_alloc);
1466 		offset += len;
1467 		size -= len;
1468 	}
1469 	return 0;
1470 
1471 error:
1472 	cork->length -= size;
1473 	IP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTDISCARDS);
1474 	return err;
1475 }
1476 
1477 static void ip_cork_release(struct inet_cork *cork)
1478 {
1479 	cork->flags &= ~IPCORK_OPT;
1480 	kfree(cork->opt);
1481 	cork->opt = NULL;
1482 	dst_release(cork->dst);
1483 	cork->dst = NULL;
1484 }
1485 
1486 /*
1487  *	Combined all pending IP fragments on the socket as one IP datagram
1488  *	and push them out.
1489  */
1490 struct sk_buff *__ip_make_skb(struct sock *sk,
1491 			      struct flowi4 *fl4,
1492 			      struct sk_buff_head *queue,
1493 			      struct inet_cork *cork)
1494 {
1495 	struct sk_buff *skb, *tmp_skb;
1496 	struct sk_buff **tail_skb;
1497 	struct inet_sock *inet = inet_sk(sk);
1498 	struct net *net = sock_net(sk);
1499 	struct ip_options *opt = NULL;
1500 	struct rtable *rt = (struct rtable *)cork->dst;
1501 	struct iphdr *iph;
1502 	__be16 df = 0;
1503 	__u8 ttl;
1504 
1505 	skb = __skb_dequeue(queue);
1506 	if (!skb)
1507 		goto out;
1508 	tail_skb = &(skb_shinfo(skb)->frag_list);
1509 
1510 	/* move skb->data to ip header from ext header */
1511 	if (skb->data < skb_network_header(skb))
1512 		__skb_pull(skb, skb_network_offset(skb));
1513 	while ((tmp_skb = __skb_dequeue(queue)) != NULL) {
1514 		__skb_pull(tmp_skb, skb_network_header_len(skb));
1515 		*tail_skb = tmp_skb;
1516 		tail_skb = &(tmp_skb->next);
1517 		skb->len += tmp_skb->len;
1518 		skb->data_len += tmp_skb->len;
1519 		skb->truesize += tmp_skb->truesize;
1520 		tmp_skb->destructor = NULL;
1521 		tmp_skb->sk = NULL;
1522 	}
1523 
1524 	/* Unless user demanded real pmtu discovery (IP_PMTUDISC_DO), we allow
1525 	 * to fragment the frame generated here. No matter, what transforms
1526 	 * how transforms change size of the packet, it will come out.
1527 	 */
1528 	skb->ignore_df = ip_sk_ignore_df(sk);
1529 
1530 	/* DF bit is set when we want to see DF on outgoing frames.
1531 	 * If ignore_df is set too, we still allow to fragment this frame
1532 	 * locally. */
1533 	if (inet->pmtudisc == IP_PMTUDISC_DO ||
1534 	    inet->pmtudisc == IP_PMTUDISC_PROBE ||
1535 	    (skb->len <= dst_mtu(&rt->dst) &&
1536 	     ip_dont_fragment(sk, &rt->dst)))
1537 		df = htons(IP_DF);
1538 
1539 	if (cork->flags & IPCORK_OPT)
1540 		opt = cork->opt;
1541 
1542 	if (cork->ttl != 0)
1543 		ttl = cork->ttl;
1544 	else if (rt->rt_type == RTN_MULTICAST)
1545 		ttl = inet->mc_ttl;
1546 	else
1547 		ttl = ip_select_ttl(inet, &rt->dst);
1548 
1549 	iph = ip_hdr(skb);
1550 	iph->version = 4;
1551 	iph->ihl = 5;
1552 	iph->tos = (cork->tos != -1) ? cork->tos : inet->tos;
1553 	iph->frag_off = df;
1554 	iph->ttl = ttl;
1555 	iph->protocol = sk->sk_protocol;
1556 	ip_copy_addrs(iph, fl4);
1557 	ip_select_ident(net, skb, sk);
1558 
1559 	if (opt) {
1560 		iph->ihl += opt->optlen >> 2;
1561 		ip_options_build(skb, opt, cork->addr, rt);
1562 	}
1563 
1564 	skb->priority = (cork->tos != -1) ? cork->priority: sk->sk_priority;
1565 	skb->mark = cork->mark;
1566 	skb->tstamp = cork->transmit_time;
1567 	/*
1568 	 * Steal rt from cork.dst to avoid a pair of atomic_inc/atomic_dec
1569 	 * on dst refcount
1570 	 */
1571 	cork->dst = NULL;
1572 	skb_dst_set(skb, &rt->dst);
1573 
1574 	if (iph->protocol == IPPROTO_ICMP) {
1575 		u8 icmp_type;
1576 
1577 		/* For such sockets, transhdrlen is zero when do ip_append_data(),
1578 		 * so icmphdr does not in skb linear region and can not get icmp_type
1579 		 * by icmp_hdr(skb)->type.
1580 		 */
1581 		if (sk->sk_type == SOCK_RAW && !inet_sk(sk)->hdrincl)
1582 			icmp_type = fl4->fl4_icmp_type;
1583 		else
1584 			icmp_type = icmp_hdr(skb)->type;
1585 		icmp_out_count(net, icmp_type);
1586 	}
1587 
1588 	ip_cork_release(cork);
1589 out:
1590 	return skb;
1591 }
1592 
1593 int ip_send_skb(struct net *net, struct sk_buff *skb)
1594 {
1595 	int err;
1596 
1597 	err = ip_local_out(net, skb->sk, skb);
1598 	if (err) {
1599 		if (err > 0)
1600 			err = net_xmit_errno(err);
1601 		if (err)
1602 			IP_INC_STATS(net, IPSTATS_MIB_OUTDISCARDS);
1603 	}
1604 
1605 	return err;
1606 }
1607 
1608 int ip_push_pending_frames(struct sock *sk, struct flowi4 *fl4)
1609 {
1610 	struct sk_buff *skb;
1611 
1612 	skb = ip_finish_skb(sk, fl4);
1613 	if (!skb)
1614 		return 0;
1615 
1616 	/* Netfilter gets whole the not fragmented skb. */
1617 	return ip_send_skb(sock_net(sk), skb);
1618 }
1619 
1620 /*
1621  *	Throw away all pending data on the socket.
1622  */
1623 static void __ip_flush_pending_frames(struct sock *sk,
1624 				      struct sk_buff_head *queue,
1625 				      struct inet_cork *cork)
1626 {
1627 	struct sk_buff *skb;
1628 
1629 	while ((skb = __skb_dequeue_tail(queue)) != NULL)
1630 		kfree_skb(skb);
1631 
1632 	ip_cork_release(cork);
1633 }
1634 
1635 void ip_flush_pending_frames(struct sock *sk)
1636 {
1637 	__ip_flush_pending_frames(sk, &sk->sk_write_queue, &inet_sk(sk)->cork.base);
1638 }
1639 
1640 struct sk_buff *ip_make_skb(struct sock *sk,
1641 			    struct flowi4 *fl4,
1642 			    int getfrag(void *from, char *to, int offset,
1643 					int len, int odd, struct sk_buff *skb),
1644 			    void *from, int length, int transhdrlen,
1645 			    struct ipcm_cookie *ipc, struct rtable **rtp,
1646 			    struct inet_cork *cork, unsigned int flags)
1647 {
1648 	struct sk_buff_head queue;
1649 	int err;
1650 
1651 	if (flags & MSG_PROBE)
1652 		return NULL;
1653 
1654 	__skb_queue_head_init(&queue);
1655 
1656 	cork->flags = 0;
1657 	cork->addr = 0;
1658 	cork->opt = NULL;
1659 	err = ip_setup_cork(sk, cork, ipc, rtp);
1660 	if (err)
1661 		return ERR_PTR(err);
1662 
1663 	err = __ip_append_data(sk, fl4, &queue, cork,
1664 			       &current->task_frag, getfrag,
1665 			       from, length, transhdrlen, flags);
1666 	if (err) {
1667 		__ip_flush_pending_frames(sk, &queue, cork);
1668 		return ERR_PTR(err);
1669 	}
1670 
1671 	return __ip_make_skb(sk, fl4, &queue, cork);
1672 }
1673 
1674 /*
1675  *	Fetch data from kernel space and fill in checksum if needed.
1676  */
1677 static int ip_reply_glue_bits(void *dptr, char *to, int offset,
1678 			      int len, int odd, struct sk_buff *skb)
1679 {
1680 	__wsum csum;
1681 
1682 	csum = csum_partial_copy_nocheck(dptr+offset, to, len);
1683 	skb->csum = csum_block_add(skb->csum, csum, odd);
1684 	return 0;
1685 }
1686 
1687 /*
1688  *	Generic function to send a packet as reply to another packet.
1689  *	Used to send some TCP resets/acks so far.
1690  */
1691 void ip_send_unicast_reply(struct sock *sk, struct sk_buff *skb,
1692 			   const struct ip_options *sopt,
1693 			   __be32 daddr, __be32 saddr,
1694 			   const struct ip_reply_arg *arg,
1695 			   unsigned int len, u64 transmit_time)
1696 {
1697 	struct ip_options_data replyopts;
1698 	struct ipcm_cookie ipc;
1699 	struct flowi4 fl4;
1700 	struct rtable *rt = skb_rtable(skb);
1701 	struct net *net = sock_net(sk);
1702 	struct sk_buff *nskb;
1703 	int err;
1704 	int oif;
1705 
1706 	if (__ip_options_echo(net, &replyopts.opt.opt, skb, sopt))
1707 		return;
1708 
1709 	ipcm_init(&ipc);
1710 	ipc.addr = daddr;
1711 	ipc.sockc.transmit_time = transmit_time;
1712 
1713 	if (replyopts.opt.opt.optlen) {
1714 		ipc.opt = &replyopts.opt;
1715 
1716 		if (replyopts.opt.opt.srr)
1717 			daddr = replyopts.opt.opt.faddr;
1718 	}
1719 
1720 	oif = arg->bound_dev_if;
1721 	if (!oif && netif_index_is_l3_master(net, skb->skb_iif))
1722 		oif = skb->skb_iif;
1723 
1724 	flowi4_init_output(&fl4, oif,
1725 			   IP4_REPLY_MARK(net, skb->mark) ?: sk->sk_mark,
1726 			   RT_TOS(arg->tos),
1727 			   RT_SCOPE_UNIVERSE, ip_hdr(skb)->protocol,
1728 			   ip_reply_arg_flowi_flags(arg),
1729 			   daddr, saddr,
1730 			   tcp_hdr(skb)->source, tcp_hdr(skb)->dest,
1731 			   arg->uid);
1732 	security_skb_classify_flow(skb, flowi4_to_flowi_common(&fl4));
1733 	rt = ip_route_output_flow(net, &fl4, sk);
1734 	if (IS_ERR(rt))
1735 		return;
1736 
1737 	inet_sk(sk)->tos = arg->tos & ~INET_ECN_MASK;
1738 
1739 	sk->sk_protocol = ip_hdr(skb)->protocol;
1740 	sk->sk_bound_dev_if = arg->bound_dev_if;
1741 	sk->sk_sndbuf = READ_ONCE(sysctl_wmem_default);
1742 	ipc.sockc.mark = fl4.flowi4_mark;
1743 	err = ip_append_data(sk, &fl4, ip_reply_glue_bits, arg->iov->iov_base,
1744 			     len, 0, &ipc, &rt, MSG_DONTWAIT);
1745 	if (unlikely(err)) {
1746 		ip_flush_pending_frames(sk);
1747 		goto out;
1748 	}
1749 
1750 	nskb = skb_peek(&sk->sk_write_queue);
1751 	if (nskb) {
1752 		if (arg->csumoffset >= 0)
1753 			*((__sum16 *)skb_transport_header(nskb) +
1754 			  arg->csumoffset) = csum_fold(csum_add(nskb->csum,
1755 								arg->csum));
1756 		nskb->ip_summed = CHECKSUM_NONE;
1757 		nskb->mono_delivery_time = !!transmit_time;
1758 		ip_push_pending_frames(sk, &fl4);
1759 	}
1760 out:
1761 	ip_rt_put(rt);
1762 }
1763 
1764 void __init ip_init(void)
1765 {
1766 	ip_rt_init();
1767 	inet_initpeers();
1768 
1769 #if defined(CONFIG_IP_MULTICAST)
1770 	igmp_mc_init();
1771 #endif
1772 }
1773