1 // SPDX-License-Identifier: GPL-2.0-only
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.
7 * The Internet Protocol (IP) output module.
10 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
11 * Donald Becker, <becker@super.org>
12 * Alan Cox, <Alan.Cox@linux.org>
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>
19 * See ip_input.c for original log
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
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 readibility.
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
43 * Hirokazu Takahashi: sendfile() on UDP works now.
46 #include <linux/uaccess.h>
47 #include <linux/module.h>
48 #include <linux/types.h>
49 #include <linux/kernel.h>
51 #include <linux/string.h>
52 #include <linux/errno.h>
53 #include <linux/highmem.h>
54 #include <linux/slab.h>
56 #include <linux/socket.h>
57 #include <linux/sockios.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>
68 #include <net/protocol.h>
69 #include <net/route.h>
71 #include <linux/skbuff.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>
87 ip_fragment(struct net *net, struct sock *sk, struct sk_buff *skb,
89 int (*output)(struct net *, struct sock *, struct sk_buff *));
91 /* Generate a checksum for an outgoing IP datagram. */
92 void ip_send_check(struct iphdr *iph)
95 iph->check = ip_fast_csum((unsigned char *)iph, iph->ihl);
97 EXPORT_SYMBOL(ip_send_check);
99 int __ip_local_out(struct net *net, struct sock *sk, struct sk_buff *skb)
101 struct iphdr *iph = ip_hdr(skb);
103 iph->tot_len = htons(skb->len);
106 /* if egress device is enslaved to an L3 master device pass the
107 * skb to its handler for processing
109 skb = l3mdev_ip_out(sk, skb);
113 skb->protocol = htons(ETH_P_IP);
115 return nf_hook(NFPROTO_IPV4, NF_INET_LOCAL_OUT,
116 net, sk, skb, NULL, skb_dst(skb)->dev,
120 int ip_local_out(struct net *net, struct sock *sk, struct sk_buff *skb)
124 err = __ip_local_out(net, sk, skb);
125 if (likely(err == 1))
126 err = dst_output(net, sk, skb);
130 EXPORT_SYMBOL_GPL(ip_local_out);
132 static inline int ip_select_ttl(struct inet_sock *inet, struct dst_entry *dst)
134 int ttl = inet->uc_ttl;
137 ttl = ip4_dst_hoplimit(dst);
142 * Add an ip header to a skbuff and send it out.
145 int ip_build_and_send_pkt(struct sk_buff *skb, const struct sock *sk,
146 __be32 saddr, __be32 daddr, struct ip_options_rcu *opt)
148 struct inet_sock *inet = inet_sk(sk);
149 struct rtable *rt = skb_rtable(skb);
150 struct net *net = sock_net(sk);
153 /* Build the IP header. */
154 skb_push(skb, sizeof(struct iphdr) + (opt ? opt->opt.optlen : 0));
155 skb_reset_network_header(skb);
159 iph->tos = inet->tos;
160 iph->ttl = ip_select_ttl(inet, &rt->dst);
161 iph->daddr = (opt && opt->opt.srr ? opt->opt.faddr : daddr);
163 iph->protocol = sk->sk_protocol;
164 /* Do not bother generating IPID for small packets (eg SYNACK) */
165 if (skb->len <= IPV4_MIN_MTU || ip_dont_fragment(sk, &rt->dst)) {
166 iph->frag_off = htons(IP_DF);
170 /* TCP packets here are SYNACK with fat IPv4/TCP options.
171 * Avoid using the hashed IP ident generator.
173 if (sk->sk_protocol == IPPROTO_TCP)
174 iph->id = (__force __be16)prandom_u32();
176 __ip_select_ident(net, iph, 1);
179 if (opt && opt->opt.optlen) {
180 iph->ihl += opt->opt.optlen>>2;
181 ip_options_build(skb, &opt->opt, daddr, rt, 0);
184 skb->priority = sk->sk_priority;
186 skb->mark = sk->sk_mark;
189 return ip_local_out(net, skb->sk, skb);
191 EXPORT_SYMBOL_GPL(ip_build_and_send_pkt);
193 static int ip_finish_output2(struct net *net, struct sock *sk, struct sk_buff *skb)
195 struct dst_entry *dst = skb_dst(skb);
196 struct rtable *rt = (struct rtable *)dst;
197 struct net_device *dev = dst->dev;
198 unsigned int hh_len = LL_RESERVED_SPACE(dev);
199 struct neighbour *neigh;
200 bool is_v6gw = false;
202 if (rt->rt_type == RTN_MULTICAST) {
203 IP_UPD_PO_STATS(net, IPSTATS_MIB_OUTMCAST, skb->len);
204 } else if (rt->rt_type == RTN_BROADCAST)
205 IP_UPD_PO_STATS(net, IPSTATS_MIB_OUTBCAST, skb->len);
207 /* Be paranoid, rather than too clever. */
208 if (unlikely(skb_headroom(skb) < hh_len && dev->header_ops)) {
209 struct sk_buff *skb2;
211 skb2 = skb_realloc_headroom(skb, LL_RESERVED_SPACE(dev));
217 skb_set_owner_w(skb2, skb->sk);
222 if (lwtunnel_xmit_redirect(dst->lwtstate)) {
223 int res = lwtunnel_xmit(skb);
225 if (res != LWTUNNEL_XMIT_CONTINUE)
230 neigh = ip_neigh_for_gw(rt, skb, &is_v6gw);
231 if (!IS_ERR(neigh)) {
234 sock_confirm_neigh(skb, neigh);
235 /* if crossing protocols, can not use the cached header */
236 res = neigh_output(neigh, skb, is_v6gw);
237 rcu_read_unlock_bh();
240 rcu_read_unlock_bh();
242 net_dbg_ratelimited("%s: No header cache and no neighbour!\n",
248 static int ip_finish_output_gso(struct net *net, struct sock *sk,
249 struct sk_buff *skb, unsigned int mtu)
251 netdev_features_t features;
252 struct sk_buff *segs;
255 /* common case: seglen is <= mtu
257 if (skb_gso_validate_network_len(skb, mtu))
258 return ip_finish_output2(net, sk, skb);
260 /* Slowpath - GSO segment length exceeds the egress MTU.
262 * This can happen in several cases:
263 * - Forwarding of a TCP GRO skb, when DF flag is not set.
264 * - Forwarding of an skb that arrived on a virtualization interface
265 * (virtio-net/vhost/tap) with TSO/GSO size set by other network
267 * - Local GSO skb transmitted on an NETIF_F_TSO tunnel stacked over an
268 * interface with a smaller MTU.
269 * - Arriving GRO skb (or GSO skb in a virtualized environment) that is
270 * bridged to a NETIF_F_TSO tunnel stacked over an interface with an
273 features = netif_skb_features(skb);
274 BUILD_BUG_ON(sizeof(*IPCB(skb)) > SKB_SGO_CB_OFFSET);
275 segs = skb_gso_segment(skb, features & ~NETIF_F_GSO_MASK);
276 if (IS_ERR_OR_NULL(segs)) {
284 struct sk_buff *nskb = segs->next;
287 skb_mark_not_on_list(segs);
288 err = ip_fragment(net, sk, segs, mtu, ip_finish_output2);
298 static int __ip_finish_output(struct net *net, struct sock *sk, struct sk_buff *skb)
302 #if defined(CONFIG_NETFILTER) && defined(CONFIG_XFRM)
303 /* Policy lookup after SNAT yielded a new policy */
304 if (skb_dst(skb)->xfrm) {
305 IPCB(skb)->flags |= IPSKB_REROUTED;
306 return dst_output(net, sk, skb);
309 mtu = ip_skb_dst_mtu(sk, skb);
311 return ip_finish_output_gso(net, sk, skb, mtu);
313 if (skb->len > mtu || IPCB(skb)->frag_max_size)
314 return ip_fragment(net, sk, skb, mtu, ip_finish_output2);
316 return ip_finish_output2(net, sk, skb);
319 static int ip_finish_output(struct net *net, struct sock *sk, struct sk_buff *skb)
323 ret = BPF_CGROUP_RUN_PROG_INET_EGRESS(sk, skb);
325 case NET_XMIT_SUCCESS:
326 return __ip_finish_output(net, sk, skb);
328 return __ip_finish_output(net, sk, skb) ? : ret;
335 static int ip_mc_finish_output(struct net *net, struct sock *sk,
338 struct rtable *new_rt;
342 ret = BPF_CGROUP_RUN_PROG_INET_EGRESS(sk, skb);
347 case NET_XMIT_SUCCESS:
354 /* Reset rt_iif so that inet_iif() will return skb->skb_iif. Setting
355 * this to non-zero causes ipi_ifindex in in_pktinfo to be overwritten,
356 * see ipv4_pktinfo_prepare().
358 new_rt = rt_dst_clone(net->loopback_dev, skb_rtable(skb));
362 skb_dst_set(skb, &new_rt->dst);
365 err = dev_loopback_xmit(net, sk, skb);
366 return (do_cn && err) ? ret : err;
369 int ip_mc_output(struct net *net, struct sock *sk, struct sk_buff *skb)
371 struct rtable *rt = skb_rtable(skb);
372 struct net_device *dev = rt->dst.dev;
375 * If the indicated interface is up and running, send the packet.
377 IP_UPD_PO_STATS(net, IPSTATS_MIB_OUT, skb->len);
380 skb->protocol = htons(ETH_P_IP);
383 * Multicasts are looped back for other local users
386 if (rt->rt_flags&RTCF_MULTICAST) {
388 #ifdef CONFIG_IP_MROUTE
389 /* Small optimization: do not loopback not local frames,
390 which returned after forwarding; they will be dropped
391 by ip_mr_input in any case.
392 Note, that local frames are looped back to be delivered
395 This check is duplicated in ip_mr_input at the moment.
398 ((rt->rt_flags & RTCF_LOCAL) ||
399 !(IPCB(skb)->flags & IPSKB_FORWARDED))
402 struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC);
404 NF_HOOK(NFPROTO_IPV4, NF_INET_POST_ROUTING,
405 net, sk, newskb, NULL, newskb->dev,
406 ip_mc_finish_output);
409 /* Multicasts with ttl 0 must not go beyond the host */
411 if (ip_hdr(skb)->ttl == 0) {
417 if (rt->rt_flags&RTCF_BROADCAST) {
418 struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC);
420 NF_HOOK(NFPROTO_IPV4, NF_INET_POST_ROUTING,
421 net, sk, newskb, NULL, newskb->dev,
422 ip_mc_finish_output);
425 return NF_HOOK_COND(NFPROTO_IPV4, NF_INET_POST_ROUTING,
426 net, sk, skb, NULL, skb->dev,
428 !(IPCB(skb)->flags & IPSKB_REROUTED));
431 int ip_output(struct net *net, struct sock *sk, struct sk_buff *skb)
433 struct net_device *dev = skb_dst(skb)->dev;
435 IP_UPD_PO_STATS(net, IPSTATS_MIB_OUT, skb->len);
438 skb->protocol = htons(ETH_P_IP);
440 return NF_HOOK_COND(NFPROTO_IPV4, NF_INET_POST_ROUTING,
441 net, sk, skb, NULL, dev,
443 !(IPCB(skb)->flags & IPSKB_REROUTED));
447 * copy saddr and daddr, possibly using 64bit load/stores
449 * iph->saddr = fl4->saddr;
450 * iph->daddr = fl4->daddr;
452 static void ip_copy_addrs(struct iphdr *iph, const struct flowi4 *fl4)
454 BUILD_BUG_ON(offsetof(typeof(*fl4), daddr) !=
455 offsetof(typeof(*fl4), saddr) + sizeof(fl4->saddr));
457 iph->saddr = fl4->saddr;
458 iph->daddr = fl4->daddr;
461 /* Note: skb->sk can be different from sk, in case of tunnels */
462 int __ip_queue_xmit(struct sock *sk, struct sk_buff *skb, struct flowi *fl,
465 struct inet_sock *inet = inet_sk(sk);
466 struct net *net = sock_net(sk);
467 struct ip_options_rcu *inet_opt;
473 /* Skip all of this if the packet is already routed,
474 * f.e. by something like SCTP.
477 inet_opt = rcu_dereference(inet->inet_opt);
479 rt = skb_rtable(skb);
483 /* Make sure we can route this packet. */
484 rt = (struct rtable *)__sk_dst_check(sk, 0);
488 /* Use correct destination address if we have options. */
489 daddr = inet->inet_daddr;
490 if (inet_opt && inet_opt->opt.srr)
491 daddr = inet_opt->opt.faddr;
493 /* If this fails, retransmit mechanism of transport layer will
494 * keep trying until route appears or the connection times
497 rt = ip_route_output_ports(net, fl4, sk,
498 daddr, inet->inet_saddr,
502 RT_CONN_FLAGS_TOS(sk, tos),
503 sk->sk_bound_dev_if);
506 sk_setup_caps(sk, &rt->dst);
508 skb_dst_set_noref(skb, &rt->dst);
511 if (inet_opt && inet_opt->opt.is_strictroute && rt->rt_uses_gateway)
514 /* OK, we know where to send it, allocate and build IP header. */
515 skb_push(skb, sizeof(struct iphdr) + (inet_opt ? inet_opt->opt.optlen : 0));
516 skb_reset_network_header(skb);
518 *((__be16 *)iph) = htons((4 << 12) | (5 << 8) | (tos & 0xff));
519 if (ip_dont_fragment(sk, &rt->dst) && !skb->ignore_df)
520 iph->frag_off = htons(IP_DF);
523 iph->ttl = ip_select_ttl(inet, &rt->dst);
524 iph->protocol = sk->sk_protocol;
525 ip_copy_addrs(iph, fl4);
527 /* Transport layer set skb->h.foo itself. */
529 if (inet_opt && inet_opt->opt.optlen) {
530 iph->ihl += inet_opt->opt.optlen >> 2;
531 ip_options_build(skb, &inet_opt->opt, inet->inet_daddr, rt, 0);
534 ip_select_ident_segs(net, skb, sk,
535 skb_shinfo(skb)->gso_segs ?: 1);
537 /* TODO : should we use skb->sk here instead of sk ? */
538 skb->priority = sk->sk_priority;
539 skb->mark = sk->sk_mark;
541 res = ip_local_out(net, sk, skb);
547 IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
549 return -EHOSTUNREACH;
551 EXPORT_SYMBOL(__ip_queue_xmit);
553 static void ip_copy_metadata(struct sk_buff *to, struct sk_buff *from)
555 to->pkt_type = from->pkt_type;
556 to->priority = from->priority;
557 to->protocol = from->protocol;
558 to->skb_iif = from->skb_iif;
560 skb_dst_copy(to, from);
562 to->mark = from->mark;
564 skb_copy_hash(to, from);
566 #ifdef CONFIG_NET_SCHED
567 to->tc_index = from->tc_index;
570 skb_ext_copy(to, from);
571 #if IS_ENABLED(CONFIG_IP_VS)
572 to->ipvs_property = from->ipvs_property;
574 skb_copy_secmark(to, from);
577 static int ip_fragment(struct net *net, struct sock *sk, struct sk_buff *skb,
579 int (*output)(struct net *, struct sock *, struct sk_buff *))
581 struct iphdr *iph = ip_hdr(skb);
583 if ((iph->frag_off & htons(IP_DF)) == 0)
584 return ip_do_fragment(net, sk, skb, output);
586 if (unlikely(!skb->ignore_df ||
587 (IPCB(skb)->frag_max_size &&
588 IPCB(skb)->frag_max_size > mtu))) {
589 IP_INC_STATS(net, IPSTATS_MIB_FRAGFAILS);
590 icmp_send(skb, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED,
596 return ip_do_fragment(net, sk, skb, output);
599 void ip_fraglist_init(struct sk_buff *skb, struct iphdr *iph,
600 unsigned int hlen, struct ip_fraglist_iter *iter)
602 unsigned int first_len = skb_pagelen(skb);
604 iter->frag = skb_shinfo(skb)->frag_list;
605 skb_frag_list_init(skb);
611 skb->data_len = first_len - skb_headlen(skb);
612 skb->len = first_len;
613 iph->tot_len = htons(first_len);
614 iph->frag_off = htons(IP_MF);
617 EXPORT_SYMBOL(ip_fraglist_init);
619 static void ip_fraglist_ipcb_prepare(struct sk_buff *skb,
620 struct ip_fraglist_iter *iter)
622 struct sk_buff *to = iter->frag;
624 /* Copy the flags to each fragment. */
625 IPCB(to)->flags = IPCB(skb)->flags;
627 if (iter->offset == 0)
628 ip_options_fragment(to);
631 void ip_fraglist_prepare(struct sk_buff *skb, struct ip_fraglist_iter *iter)
633 unsigned int hlen = iter->hlen;
634 struct iphdr *iph = iter->iph;
635 struct sk_buff *frag;
638 frag->ip_summed = CHECKSUM_NONE;
639 skb_reset_transport_header(frag);
640 __skb_push(frag, hlen);
641 skb_reset_network_header(frag);
642 memcpy(skb_network_header(frag), iph, hlen);
643 iter->iph = ip_hdr(frag);
645 iph->tot_len = htons(frag->len);
646 ip_copy_metadata(frag, skb);
647 iter->offset += skb->len - hlen;
648 iph->frag_off = htons(iter->offset >> 3);
650 iph->frag_off |= htons(IP_MF);
651 /* Ready, complete checksum */
654 EXPORT_SYMBOL(ip_fraglist_prepare);
656 void ip_frag_init(struct sk_buff *skb, unsigned int hlen,
657 unsigned int ll_rs, unsigned int mtu, bool DF,
658 struct ip_frag_state *state)
660 struct iphdr *iph = ip_hdr(skb);
664 state->ll_rs = ll_rs;
667 state->left = skb->len - hlen; /* Space per frame */
668 state->ptr = hlen; /* Where to start from */
670 state->offset = (ntohs(iph->frag_off) & IP_OFFSET) << 3;
671 state->not_last_frag = iph->frag_off & htons(IP_MF);
673 EXPORT_SYMBOL(ip_frag_init);
675 static void ip_frag_ipcb(struct sk_buff *from, struct sk_buff *to,
676 bool first_frag, struct ip_frag_state *state)
678 /* Copy the flags to each fragment. */
679 IPCB(to)->flags = IPCB(from)->flags;
681 /* ANK: dirty, but effective trick. Upgrade options only if
682 * the segment to be fragmented was THE FIRST (otherwise,
683 * options are already fixed) and make it ONCE
684 * on the initial skb, so that all the following fragments
685 * will inherit fixed options.
688 ip_options_fragment(from);
691 struct sk_buff *ip_frag_next(struct sk_buff *skb, struct ip_frag_state *state)
693 unsigned int len = state->left;
694 struct sk_buff *skb2;
698 /* IF: it doesn't fit, use 'mtu' - the data space left */
699 if (len > state->mtu)
701 /* IF: we are not sending up to and including the packet end
702 then align the next start on an eight byte boundary */
703 if (len < state->left) {
707 /* Allocate buffer */
708 skb2 = alloc_skb(len + state->hlen + state->ll_rs, GFP_ATOMIC);
710 return ERR_PTR(-ENOMEM);
713 * Set up data on packet
716 ip_copy_metadata(skb2, skb);
717 skb_reserve(skb2, state->ll_rs);
718 skb_put(skb2, len + state->hlen);
719 skb_reset_network_header(skb2);
720 skb2->transport_header = skb2->network_header + state->hlen;
723 * Charge the memory for the fragment to any owner
728 skb_set_owner_w(skb2, skb->sk);
731 * Copy the packet header into the new buffer.
734 skb_copy_from_linear_data(skb, skb_network_header(skb2), state->hlen);
737 * Copy a block of the IP datagram.
739 if (skb_copy_bits(skb, state->ptr, skb_transport_header(skb2), len))
744 * Fill in the new header fields.
747 iph->frag_off = htons((state->offset >> 3));
749 iph->frag_off |= htons(IP_DF);
752 * Added AC : If we are fragmenting a fragment that's not the
753 * last fragment then keep MF on each bit
755 if (state->left > 0 || state->not_last_frag)
756 iph->frag_off |= htons(IP_MF);
758 state->offset += len;
760 iph->tot_len = htons(len + state->hlen);
766 EXPORT_SYMBOL(ip_frag_next);
769 * This IP datagram is too large to be sent in one piece. Break it up into
770 * smaller pieces (each of size equal to IP header plus
771 * a block of the data of the original IP data part) that will yet fit in a
772 * single device frame, and queue such a frame for sending.
775 int ip_do_fragment(struct net *net, struct sock *sk, struct sk_buff *skb,
776 int (*output)(struct net *, struct sock *, struct sk_buff *))
779 struct sk_buff *skb2;
780 struct rtable *rt = skb_rtable(skb);
781 unsigned int mtu, hlen, ll_rs;
782 struct ip_fraglist_iter iter;
783 ktime_t tstamp = skb->tstamp;
784 struct ip_frag_state state;
787 /* for offloaded checksums cleanup checksum before fragmentation */
788 if (skb->ip_summed == CHECKSUM_PARTIAL &&
789 (err = skb_checksum_help(skb)))
793 * Point into the IP datagram header.
798 mtu = ip_skb_dst_mtu(sk, skb);
799 if (IPCB(skb)->frag_max_size && IPCB(skb)->frag_max_size < mtu)
800 mtu = IPCB(skb)->frag_max_size;
803 * Setup starting values.
807 mtu = mtu - hlen; /* Size of data space */
808 IPCB(skb)->flags |= IPSKB_FRAG_COMPLETE;
809 ll_rs = LL_RESERVED_SPACE(rt->dst.dev);
811 /* When frag_list is given, use it. First, check its validity:
812 * some transformers could create wrong frag_list or break existing
813 * one, it is not prohibited. In this case fall back to copying.
815 * LATER: this step can be merged to real generation of fragments,
816 * we can switch to copy when see the first bad fragment.
818 if (skb_has_frag_list(skb)) {
819 struct sk_buff *frag, *frag2;
820 unsigned int first_len = skb_pagelen(skb);
822 if (first_len - hlen > mtu ||
823 ((first_len - hlen) & 7) ||
824 ip_is_fragment(iph) ||
826 skb_headroom(skb) < ll_rs)
829 skb_walk_frags(skb, frag) {
830 /* Correct geometry. */
831 if (frag->len > mtu ||
832 ((frag->len & 7) && frag->next) ||
833 skb_headroom(frag) < hlen + ll_rs)
834 goto slow_path_clean;
836 /* Partially cloned skb? */
837 if (skb_shared(frag))
838 goto slow_path_clean;
843 frag->destructor = sock_wfree;
845 skb->truesize -= frag->truesize;
848 /* Everything is OK. Generate! */
849 ip_fraglist_init(skb, iph, hlen, &iter);
852 /* Prepare header of the next frame,
853 * before previous one went down. */
855 ip_fraglist_ipcb_prepare(skb, &iter);
856 ip_fraglist_prepare(skb, &iter);
859 skb->tstamp = tstamp;
860 err = output(net, sk, skb);
863 IP_INC_STATS(net, IPSTATS_MIB_FRAGCREATES);
864 if (err || !iter.frag)
867 skb = ip_fraglist_next(&iter);
871 IP_INC_STATS(net, IPSTATS_MIB_FRAGOKS);
875 kfree_skb_list(iter.frag);
877 IP_INC_STATS(net, IPSTATS_MIB_FRAGFAILS);
881 skb_walk_frags(skb, frag2) {
885 frag2->destructor = NULL;
886 skb->truesize += frag2->truesize;
892 * Fragment the datagram.
895 ip_frag_init(skb, hlen, ll_rs, mtu, IPCB(skb)->flags & IPSKB_FRAG_PMTU,
899 * Keep copying data until we run out.
902 while (state.left > 0) {
903 bool first_frag = (state.offset == 0);
905 skb2 = ip_frag_next(skb, &state);
910 ip_frag_ipcb(skb, skb2, first_frag, &state);
913 * Put this fragment into the sending queue.
915 skb2->tstamp = tstamp;
916 err = output(net, sk, skb2);
920 IP_INC_STATS(net, IPSTATS_MIB_FRAGCREATES);
923 IP_INC_STATS(net, IPSTATS_MIB_FRAGOKS);
928 IP_INC_STATS(net, IPSTATS_MIB_FRAGFAILS);
931 EXPORT_SYMBOL(ip_do_fragment);
934 ip_generic_getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb)
936 struct msghdr *msg = from;
938 if (skb->ip_summed == CHECKSUM_PARTIAL) {
939 if (!copy_from_iter_full(to, len, &msg->msg_iter))
943 if (!csum_and_copy_from_iter_full(to, len, &csum, &msg->msg_iter))
945 skb->csum = csum_block_add(skb->csum, csum, odd);
949 EXPORT_SYMBOL(ip_generic_getfrag);
952 csum_page(struct page *page, int offset, int copy)
957 csum = csum_partial(kaddr + offset, copy, 0);
962 static int __ip_append_data(struct sock *sk,
964 struct sk_buff_head *queue,
965 struct inet_cork *cork,
966 struct page_frag *pfrag,
967 int getfrag(void *from, char *to, int offset,
968 int len, int odd, struct sk_buff *skb),
969 void *from, int length, int transhdrlen,
972 struct inet_sock *inet = inet_sk(sk);
973 struct ubuf_info *uarg = NULL;
976 struct ip_options *opt = cork->opt;
983 unsigned int maxfraglen, fragheaderlen, maxnonfragsize;
984 int csummode = CHECKSUM_NONE;
985 struct rtable *rt = (struct rtable *)cork->dst;
986 unsigned int wmem_alloc_delta = 0;
987 bool paged, extra_uref = false;
990 skb = skb_peek_tail(queue);
992 exthdrlen = !skb ? rt->dst.header_len : 0;
993 mtu = cork->gso_size ? IP_MAX_MTU : cork->fragsize;
994 paged = !!cork->gso_size;
996 if (cork->tx_flags & SKBTX_ANY_SW_TSTAMP &&
997 sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)
998 tskey = sk->sk_tskey++;
1000 hh_len = LL_RESERVED_SPACE(rt->dst.dev);
1002 fragheaderlen = sizeof(struct iphdr) + (opt ? opt->optlen : 0);
1003 maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen;
1004 maxnonfragsize = ip_sk_ignore_df(sk) ? 0xFFFF : mtu;
1006 if (cork->length + length > maxnonfragsize - fragheaderlen) {
1007 ip_local_error(sk, EMSGSIZE, fl4->daddr, inet->inet_dport,
1008 mtu - (opt ? opt->optlen : 0));
1013 * transhdrlen > 0 means that this is the first fragment and we wish
1014 * it won't be fragmented in the future.
1017 length + fragheaderlen <= mtu &&
1018 rt->dst.dev->features & (NETIF_F_HW_CSUM | NETIF_F_IP_CSUM) &&
1019 (!(flags & MSG_MORE) || cork->gso_size) &&
1020 (!exthdrlen || (rt->dst.dev->features & NETIF_F_HW_ESP_TX_CSUM)))
1021 csummode = CHECKSUM_PARTIAL;
1023 if (flags & MSG_ZEROCOPY && length && sock_flag(sk, SOCK_ZEROCOPY)) {
1024 uarg = sock_zerocopy_realloc(sk, length, skb_zcopy(skb));
1027 extra_uref = !skb_zcopy(skb); /* only ref on new uarg */
1028 if (rt->dst.dev->features & NETIF_F_SG &&
1029 csummode == CHECKSUM_PARTIAL) {
1033 skb_zcopy_set(skb, uarg, &extra_uref);
1037 cork->length += length;
1039 /* So, what's going on in the loop below?
1041 * We use calculated fragment length to generate chained skb,
1042 * each of segments is IP fragment ready for sending to network after
1043 * adding appropriate IP header.
1049 while (length > 0) {
1050 /* Check if the remaining data fits into current packet. */
1051 copy = mtu - skb->len;
1053 copy = maxfraglen - skb->len;
1056 unsigned int datalen;
1057 unsigned int fraglen;
1058 unsigned int fraggap;
1059 unsigned int alloclen, alloc_extra;
1060 unsigned int pagedlen;
1061 struct sk_buff *skb_prev;
1065 fraggap = skb_prev->len - maxfraglen;
1070 * If remaining data exceeds the mtu,
1071 * we know we need more fragment(s).
1073 datalen = length + fraggap;
1074 if (datalen > mtu - fragheaderlen)
1075 datalen = maxfraglen - fragheaderlen;
1076 fraglen = datalen + fragheaderlen;
1079 alloc_extra = hh_len + 15;
1080 alloc_extra += exthdrlen;
1082 /* The last fragment gets additional space at tail.
1083 * Note, with MSG_MORE we overallocate on fragments,
1084 * because we have no idea what fragment will be
1087 if (datalen == length + fraggap)
1088 alloc_extra += rt->dst.trailer_len;
1090 if ((flags & MSG_MORE) &&
1091 !(rt->dst.dev->features&NETIF_F_SG))
1094 (fraglen + alloc_extra < SKB_MAX_ALLOC ||
1095 !(rt->dst.dev->features & NETIF_F_SG)))
1098 alloclen = min_t(int, fraglen, MAX_HEADER);
1099 pagedlen = fraglen - alloclen;
1102 alloclen += alloc_extra;
1105 skb = sock_alloc_send_skb(sk, alloclen,
1106 (flags & MSG_DONTWAIT), &err);
1109 if (refcount_read(&sk->sk_wmem_alloc) + wmem_alloc_delta <=
1111 skb = alloc_skb(alloclen,
1120 * Fill in the control structures
1122 skb->ip_summed = csummode;
1124 skb_reserve(skb, hh_len);
1127 * Find where to start putting bytes.
1129 data = skb_put(skb, fraglen + exthdrlen - pagedlen);
1130 skb_set_network_header(skb, exthdrlen);
1131 skb->transport_header = (skb->network_header +
1133 data += fragheaderlen + exthdrlen;
1136 skb->csum = skb_copy_and_csum_bits(
1137 skb_prev, maxfraglen,
1138 data + transhdrlen, fraggap, 0);
1139 skb_prev->csum = csum_sub(skb_prev->csum,
1142 pskb_trim_unique(skb_prev, maxfraglen);
1145 copy = datalen - transhdrlen - fraggap - pagedlen;
1146 if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) {
1153 length -= copy + transhdrlen;
1156 csummode = CHECKSUM_NONE;
1158 /* only the initial fragment is time stamped */
1159 skb_shinfo(skb)->tx_flags = cork->tx_flags;
1161 skb_shinfo(skb)->tskey = tskey;
1163 skb_zcopy_set(skb, uarg, &extra_uref);
1165 if ((flags & MSG_CONFIRM) && !skb_prev)
1166 skb_set_dst_pending_confirm(skb, 1);
1169 * Put the packet on the pending queue.
1171 if (!skb->destructor) {
1172 skb->destructor = sock_wfree;
1174 wmem_alloc_delta += skb->truesize;
1176 __skb_queue_tail(queue, skb);
1183 if (!(rt->dst.dev->features&NETIF_F_SG) &&
1184 skb_tailroom(skb) >= copy) {
1188 if (getfrag(from, skb_put(skb, copy),
1189 offset, copy, off, skb) < 0) {
1190 __skb_trim(skb, off);
1194 } else if (!uarg || !uarg->zerocopy) {
1195 int i = skb_shinfo(skb)->nr_frags;
1198 if (!sk_page_frag_refill(sk, pfrag))
1201 if (!skb_can_coalesce(skb, i, pfrag->page,
1204 if (i == MAX_SKB_FRAGS)
1207 __skb_fill_page_desc(skb, i, pfrag->page,
1209 skb_shinfo(skb)->nr_frags = ++i;
1210 get_page(pfrag->page);
1212 copy = min_t(int, copy, pfrag->size - pfrag->offset);
1214 page_address(pfrag->page) + pfrag->offset,
1215 offset, copy, skb->len, skb) < 0)
1218 pfrag->offset += copy;
1219 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
1221 skb->data_len += copy;
1222 skb->truesize += copy;
1223 wmem_alloc_delta += copy;
1225 err = skb_zerocopy_iter_dgram(skb, from, copy);
1233 if (wmem_alloc_delta)
1234 refcount_add(wmem_alloc_delta, &sk->sk_wmem_alloc);
1241 sock_zerocopy_put_abort(uarg, extra_uref);
1242 cork->length -= length;
1243 IP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTDISCARDS);
1244 refcount_add(wmem_alloc_delta, &sk->sk_wmem_alloc);
1248 static int ip_setup_cork(struct sock *sk, struct inet_cork *cork,
1249 struct ipcm_cookie *ipc, struct rtable **rtp)
1251 struct ip_options_rcu *opt;
1259 * setup for corking.
1264 cork->opt = kmalloc(sizeof(struct ip_options) + 40,
1266 if (unlikely(!cork->opt))
1269 memcpy(cork->opt, &opt->opt, sizeof(struct ip_options) + opt->opt.optlen);
1270 cork->flags |= IPCORK_OPT;
1271 cork->addr = ipc->addr;
1274 cork->fragsize = ip_sk_use_pmtu(sk) ?
1275 dst_mtu(&rt->dst) : READ_ONCE(rt->dst.dev->mtu);
1277 if (!inetdev_valid_mtu(cork->fragsize))
1278 return -ENETUNREACH;
1280 cork->gso_size = ipc->gso_size;
1282 cork->dst = &rt->dst;
1283 /* We stole this route, caller should not release it. */
1287 cork->ttl = ipc->ttl;
1288 cork->tos = ipc->tos;
1289 cork->mark = ipc->sockc.mark;
1290 cork->priority = ipc->priority;
1291 cork->transmit_time = ipc->sockc.transmit_time;
1293 sock_tx_timestamp(sk, ipc->sockc.tsflags, &cork->tx_flags);
1299 * ip_append_data() and ip_append_page() can make one large IP datagram
1300 * from many pieces of data. Each pieces will be holded on the socket
1301 * until ip_push_pending_frames() is called. Each piece can be a page
1304 * Not only UDP, other transport protocols - e.g. raw sockets - can use
1305 * this interface potentially.
1307 * LATER: length must be adjusted by pad at tail, when it is required.
1309 int ip_append_data(struct sock *sk, struct flowi4 *fl4,
1310 int getfrag(void *from, char *to, int offset, int len,
1311 int odd, struct sk_buff *skb),
1312 void *from, int length, int transhdrlen,
1313 struct ipcm_cookie *ipc, struct rtable **rtp,
1316 struct inet_sock *inet = inet_sk(sk);
1319 if (flags&MSG_PROBE)
1322 if (skb_queue_empty(&sk->sk_write_queue)) {
1323 err = ip_setup_cork(sk, &inet->cork.base, ipc, rtp);
1330 return __ip_append_data(sk, fl4, &sk->sk_write_queue, &inet->cork.base,
1331 sk_page_frag(sk), getfrag,
1332 from, length, transhdrlen, flags);
1335 ssize_t ip_append_page(struct sock *sk, struct flowi4 *fl4, struct page *page,
1336 int offset, size_t size, int flags)
1338 struct inet_sock *inet = inet_sk(sk);
1339 struct sk_buff *skb;
1341 struct ip_options *opt = NULL;
1342 struct inet_cork *cork;
1347 unsigned int maxfraglen, fragheaderlen, fraggap, maxnonfragsize;
1352 if (flags&MSG_PROBE)
1355 if (skb_queue_empty(&sk->sk_write_queue))
1358 cork = &inet->cork.base;
1359 rt = (struct rtable *)cork->dst;
1360 if (cork->flags & IPCORK_OPT)
1363 if (!(rt->dst.dev->features&NETIF_F_SG))
1366 hh_len = LL_RESERVED_SPACE(rt->dst.dev);
1367 mtu = cork->gso_size ? IP_MAX_MTU : cork->fragsize;
1369 fragheaderlen = sizeof(struct iphdr) + (opt ? opt->optlen : 0);
1370 maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen;
1371 maxnonfragsize = ip_sk_ignore_df(sk) ? 0xFFFF : mtu;
1373 if (cork->length + size > maxnonfragsize - fragheaderlen) {
1374 ip_local_error(sk, EMSGSIZE, fl4->daddr, inet->inet_dport,
1375 mtu - (opt ? opt->optlen : 0));
1379 skb = skb_peek_tail(&sk->sk_write_queue);
1383 cork->length += size;
1386 /* Check if the remaining data fits into current packet. */
1387 len = mtu - skb->len;
1389 len = maxfraglen - skb->len;
1392 struct sk_buff *skb_prev;
1396 fraggap = skb_prev->len - maxfraglen;
1398 alloclen = fragheaderlen + hh_len + fraggap + 15;
1399 skb = sock_wmalloc(sk, alloclen, 1, sk->sk_allocation);
1400 if (unlikely(!skb)) {
1406 * Fill in the control structures
1408 skb->ip_summed = CHECKSUM_NONE;
1410 skb_reserve(skb, hh_len);
1413 * Find where to start putting bytes.
1415 skb_put(skb, fragheaderlen + fraggap);
1416 skb_reset_network_header(skb);
1417 skb->transport_header = (skb->network_header +
1420 skb->csum = skb_copy_and_csum_bits(skb_prev,
1422 skb_transport_header(skb),
1424 skb_prev->csum = csum_sub(skb_prev->csum,
1426 pskb_trim_unique(skb_prev, maxfraglen);
1430 * Put the packet on the pending queue.
1432 __skb_queue_tail(&sk->sk_write_queue, skb);
1439 if (skb_append_pagefrags(skb, page, offset, len)) {
1444 if (skb->ip_summed == CHECKSUM_NONE) {
1446 csum = csum_page(page, offset, len);
1447 skb->csum = csum_block_add(skb->csum, csum, skb->len);
1451 skb->data_len += len;
1452 skb->truesize += len;
1453 refcount_add(len, &sk->sk_wmem_alloc);
1460 cork->length -= size;
1461 IP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTDISCARDS);
1465 static void ip_cork_release(struct inet_cork *cork)
1467 cork->flags &= ~IPCORK_OPT;
1470 dst_release(cork->dst);
1475 * Combined all pending IP fragments on the socket as one IP datagram
1476 * and push them out.
1478 struct sk_buff *__ip_make_skb(struct sock *sk,
1480 struct sk_buff_head *queue,
1481 struct inet_cork *cork)
1483 struct sk_buff *skb, *tmp_skb;
1484 struct sk_buff **tail_skb;
1485 struct inet_sock *inet = inet_sk(sk);
1486 struct net *net = sock_net(sk);
1487 struct ip_options *opt = NULL;
1488 struct rtable *rt = (struct rtable *)cork->dst;
1493 skb = __skb_dequeue(queue);
1496 tail_skb = &(skb_shinfo(skb)->frag_list);
1498 /* move skb->data to ip header from ext header */
1499 if (skb->data < skb_network_header(skb))
1500 __skb_pull(skb, skb_network_offset(skb));
1501 while ((tmp_skb = __skb_dequeue(queue)) != NULL) {
1502 __skb_pull(tmp_skb, skb_network_header_len(skb));
1503 *tail_skb = tmp_skb;
1504 tail_skb = &(tmp_skb->next);
1505 skb->len += tmp_skb->len;
1506 skb->data_len += tmp_skb->len;
1507 skb->truesize += tmp_skb->truesize;
1508 tmp_skb->destructor = NULL;
1512 /* Unless user demanded real pmtu discovery (IP_PMTUDISC_DO), we allow
1513 * to fragment the frame generated here. No matter, what transforms
1514 * how transforms change size of the packet, it will come out.
1516 skb->ignore_df = ip_sk_ignore_df(sk);
1518 /* DF bit is set when we want to see DF on outgoing frames.
1519 * If ignore_df is set too, we still allow to fragment this frame
1521 if (inet->pmtudisc == IP_PMTUDISC_DO ||
1522 inet->pmtudisc == IP_PMTUDISC_PROBE ||
1523 (skb->len <= dst_mtu(&rt->dst) &&
1524 ip_dont_fragment(sk, &rt->dst)))
1527 if (cork->flags & IPCORK_OPT)
1532 else if (rt->rt_type == RTN_MULTICAST)
1535 ttl = ip_select_ttl(inet, &rt->dst);
1540 iph->tos = (cork->tos != -1) ? cork->tos : inet->tos;
1543 iph->protocol = sk->sk_protocol;
1544 ip_copy_addrs(iph, fl4);
1545 ip_select_ident(net, skb, sk);
1548 iph->ihl += opt->optlen>>2;
1549 ip_options_build(skb, opt, cork->addr, rt, 0);
1552 skb->priority = (cork->tos != -1) ? cork->priority: sk->sk_priority;
1553 skb->mark = cork->mark;
1554 skb->tstamp = cork->transmit_time;
1556 * Steal rt from cork.dst to avoid a pair of atomic_inc/atomic_dec
1560 skb_dst_set(skb, &rt->dst);
1562 if (iph->protocol == IPPROTO_ICMP) {
1565 /* For such sockets, transhdrlen is zero when do ip_append_data(),
1566 * so icmphdr does not in skb linear region and can not get icmp_type
1567 * by icmp_hdr(skb)->type.
1569 if (sk->sk_type == SOCK_RAW && !inet_sk(sk)->hdrincl)
1570 icmp_type = fl4->fl4_icmp_type;
1572 icmp_type = icmp_hdr(skb)->type;
1573 icmp_out_count(net, icmp_type);
1576 ip_cork_release(cork);
1581 int ip_send_skb(struct net *net, struct sk_buff *skb)
1585 err = ip_local_out(net, skb->sk, skb);
1588 err = net_xmit_errno(err);
1590 IP_INC_STATS(net, IPSTATS_MIB_OUTDISCARDS);
1596 int ip_push_pending_frames(struct sock *sk, struct flowi4 *fl4)
1598 struct sk_buff *skb;
1600 skb = ip_finish_skb(sk, fl4);
1604 /* Netfilter gets whole the not fragmented skb. */
1605 return ip_send_skb(sock_net(sk), skb);
1609 * Throw away all pending data on the socket.
1611 static void __ip_flush_pending_frames(struct sock *sk,
1612 struct sk_buff_head *queue,
1613 struct inet_cork *cork)
1615 struct sk_buff *skb;
1617 while ((skb = __skb_dequeue_tail(queue)) != NULL)
1620 ip_cork_release(cork);
1623 void ip_flush_pending_frames(struct sock *sk)
1625 __ip_flush_pending_frames(sk, &sk->sk_write_queue, &inet_sk(sk)->cork.base);
1628 struct sk_buff *ip_make_skb(struct sock *sk,
1630 int getfrag(void *from, char *to, int offset,
1631 int len, int odd, struct sk_buff *skb),
1632 void *from, int length, int transhdrlen,
1633 struct ipcm_cookie *ipc, struct rtable **rtp,
1634 struct inet_cork *cork, unsigned int flags)
1636 struct sk_buff_head queue;
1639 if (flags & MSG_PROBE)
1642 __skb_queue_head_init(&queue);
1647 err = ip_setup_cork(sk, cork, ipc, rtp);
1649 return ERR_PTR(err);
1651 err = __ip_append_data(sk, fl4, &queue, cork,
1652 ¤t->task_frag, getfrag,
1653 from, length, transhdrlen, flags);
1655 __ip_flush_pending_frames(sk, &queue, cork);
1656 return ERR_PTR(err);
1659 return __ip_make_skb(sk, fl4, &queue, cork);
1663 * Fetch data from kernel space and fill in checksum if needed.
1665 static int ip_reply_glue_bits(void *dptr, char *to, int offset,
1666 int len, int odd, struct sk_buff *skb)
1670 csum = csum_partial_copy_nocheck(dptr+offset, to, len, 0);
1671 skb->csum = csum_block_add(skb->csum, csum, odd);
1676 * Generic function to send a packet as reply to another packet.
1677 * Used to send some TCP resets/acks so far.
1679 void ip_send_unicast_reply(struct sock *sk, struct sk_buff *skb,
1680 const struct ip_options *sopt,
1681 __be32 daddr, __be32 saddr,
1682 const struct ip_reply_arg *arg,
1683 unsigned int len, u64 transmit_time)
1685 struct ip_options_data replyopts;
1686 struct ipcm_cookie ipc;
1688 struct rtable *rt = skb_rtable(skb);
1689 struct net *net = sock_net(sk);
1690 struct sk_buff *nskb;
1694 if (__ip_options_echo(net, &replyopts.opt.opt, skb, sopt))
1699 ipc.sockc.transmit_time = transmit_time;
1701 if (replyopts.opt.opt.optlen) {
1702 ipc.opt = &replyopts.opt;
1704 if (replyopts.opt.opt.srr)
1705 daddr = replyopts.opt.opt.faddr;
1708 oif = arg->bound_dev_if;
1709 if (!oif && netif_index_is_l3_master(net, skb->skb_iif))
1712 flowi4_init_output(&fl4, oif,
1713 IP4_REPLY_MARK(net, skb->mark) ?: sk->sk_mark,
1715 RT_SCOPE_UNIVERSE, ip_hdr(skb)->protocol,
1716 ip_reply_arg_flowi_flags(arg),
1718 tcp_hdr(skb)->source, tcp_hdr(skb)->dest,
1720 security_skb_classify_flow(skb, flowi4_to_flowi(&fl4));
1721 rt = ip_route_output_key(net, &fl4);
1725 inet_sk(sk)->tos = arg->tos & ~INET_ECN_MASK;
1727 sk->sk_protocol = ip_hdr(skb)->protocol;
1728 sk->sk_bound_dev_if = arg->bound_dev_if;
1729 sk->sk_sndbuf = sysctl_wmem_default;
1730 ipc.sockc.mark = fl4.flowi4_mark;
1731 err = ip_append_data(sk, &fl4, ip_reply_glue_bits, arg->iov->iov_base,
1732 len, 0, &ipc, &rt, MSG_DONTWAIT);
1733 if (unlikely(err)) {
1734 ip_flush_pending_frames(sk);
1738 nskb = skb_peek(&sk->sk_write_queue);
1740 if (arg->csumoffset >= 0)
1741 *((__sum16 *)skb_transport_header(nskb) +
1742 arg->csumoffset) = csum_fold(csum_add(nskb->csum,
1744 nskb->ip_summed = CHECKSUM_NONE;
1745 ip_push_pending_frames(sk, &fl4);
1751 void __init ip_init(void)
1756 #if defined(CONFIG_IP_MULTICAST)