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