878a08c40fffddd7b7d745271d4fad520827aae2
[releases.git] / ip6_tunnel.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *      IPv6 tunneling device
4  *      Linux INET6 implementation
5  *
6  *      Authors:
7  *      Ville Nuorvala          <vnuorval@tcs.hut.fi>
8  *      Yasuyuki Kozakai        <kozakai@linux-ipv6.org>
9  *
10  *      Based on:
11  *      linux/net/ipv6/sit.c and linux/net/ipv4/ipip.c
12  *
13  *      RFC 2473
14  */
15
16 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
17
18 #include <linux/module.h>
19 #include <linux/capability.h>
20 #include <linux/errno.h>
21 #include <linux/types.h>
22 #include <linux/sockios.h>
23 #include <linux/icmp.h>
24 #include <linux/if.h>
25 #include <linux/in.h>
26 #include <linux/ip.h>
27 #include <linux/net.h>
28 #include <linux/in6.h>
29 #include <linux/netdevice.h>
30 #include <linux/if_arp.h>
31 #include <linux/icmpv6.h>
32 #include <linux/init.h>
33 #include <linux/route.h>
34 #include <linux/rtnetlink.h>
35 #include <linux/netfilter_ipv6.h>
36 #include <linux/slab.h>
37 #include <linux/hash.h>
38 #include <linux/etherdevice.h>
39
40 #include <linux/uaccess.h>
41 #include <linux/atomic.h>
42
43 #include <net/icmp.h>
44 #include <net/ip.h>
45 #include <net/ip_tunnels.h>
46 #include <net/ipv6.h>
47 #include <net/ip6_route.h>
48 #include <net/addrconf.h>
49 #include <net/ip6_tunnel.h>
50 #include <net/xfrm.h>
51 #include <net/dsfield.h>
52 #include <net/inet_ecn.h>
53 #include <net/net_namespace.h>
54 #include <net/netns/generic.h>
55 #include <net/dst_metadata.h>
56
57 MODULE_AUTHOR("Ville Nuorvala");
58 MODULE_DESCRIPTION("IPv6 tunneling device");
59 MODULE_LICENSE("GPL");
60 MODULE_ALIAS_RTNL_LINK("ip6tnl");
61 MODULE_ALIAS_NETDEV("ip6tnl0");
62
63 #define IP6_TUNNEL_HASH_SIZE_SHIFT  5
64 #define IP6_TUNNEL_HASH_SIZE (1 << IP6_TUNNEL_HASH_SIZE_SHIFT)
65
66 static bool log_ecn_error = true;
67 module_param(log_ecn_error, bool, 0644);
68 MODULE_PARM_DESC(log_ecn_error, "Log packets received with corrupted ECN");
69
70 static u32 HASH(const struct in6_addr *addr1, const struct in6_addr *addr2)
71 {
72         u32 hash = ipv6_addr_hash(addr1) ^ ipv6_addr_hash(addr2);
73
74         return hash_32(hash, IP6_TUNNEL_HASH_SIZE_SHIFT);
75 }
76
77 static int ip6_tnl_dev_init(struct net_device *dev);
78 static void ip6_tnl_dev_setup(struct net_device *dev);
79 static struct rtnl_link_ops ip6_link_ops __read_mostly;
80
81 static unsigned int ip6_tnl_net_id __read_mostly;
82 struct ip6_tnl_net {
83         /* the IPv6 tunnel fallback device */
84         struct net_device *fb_tnl_dev;
85         /* lists for storing tunnels in use */
86         struct ip6_tnl __rcu *tnls_r_l[IP6_TUNNEL_HASH_SIZE];
87         struct ip6_tnl __rcu *tnls_wc[1];
88         struct ip6_tnl __rcu **tnls[2];
89         struct ip6_tnl __rcu *collect_md_tun;
90 };
91
92 static struct net_device_stats *ip6_get_stats(struct net_device *dev)
93 {
94         struct pcpu_sw_netstats tmp, sum = { 0 };
95         int i;
96
97         for_each_possible_cpu(i) {
98                 unsigned int start;
99                 const struct pcpu_sw_netstats *tstats =
100                                                    per_cpu_ptr(dev->tstats, i);
101
102                 do {
103                         start = u64_stats_fetch_begin_irq(&tstats->syncp);
104                         tmp.rx_packets = tstats->rx_packets;
105                         tmp.rx_bytes = tstats->rx_bytes;
106                         tmp.tx_packets = tstats->tx_packets;
107                         tmp.tx_bytes =  tstats->tx_bytes;
108                 } while (u64_stats_fetch_retry_irq(&tstats->syncp, start));
109
110                 sum.rx_packets += tmp.rx_packets;
111                 sum.rx_bytes   += tmp.rx_bytes;
112                 sum.tx_packets += tmp.tx_packets;
113                 sum.tx_bytes   += tmp.tx_bytes;
114         }
115         dev->stats.rx_packets = sum.rx_packets;
116         dev->stats.rx_bytes   = sum.rx_bytes;
117         dev->stats.tx_packets = sum.tx_packets;
118         dev->stats.tx_bytes   = sum.tx_bytes;
119         return &dev->stats;
120 }
121
122 /**
123  * ip6_tnl_lookup - fetch tunnel matching the end-point addresses
124  *   @remote: the address of the tunnel exit-point
125  *   @local: the address of the tunnel entry-point
126  *
127  * Return:
128  *   tunnel matching given end-points if found,
129  *   else fallback tunnel if its device is up,
130  *   else %NULL
131  **/
132
133 #define for_each_ip6_tunnel_rcu(start) \
134         for (t = rcu_dereference(start); t; t = rcu_dereference(t->next))
135
136 static struct ip6_tnl *
137 ip6_tnl_lookup(struct net *net, const struct in6_addr *remote, const struct in6_addr *local)
138 {
139         unsigned int hash = HASH(remote, local);
140         struct ip6_tnl *t;
141         struct ip6_tnl_net *ip6n = net_generic(net, ip6_tnl_net_id);
142         struct in6_addr any;
143
144         for_each_ip6_tunnel_rcu(ip6n->tnls_r_l[hash]) {
145                 if (ipv6_addr_equal(local, &t->parms.laddr) &&
146                     ipv6_addr_equal(remote, &t->parms.raddr) &&
147                     (t->dev->flags & IFF_UP))
148                         return t;
149         }
150
151         memset(&any, 0, sizeof(any));
152         hash = HASH(&any, local);
153         for_each_ip6_tunnel_rcu(ip6n->tnls_r_l[hash]) {
154                 if (ipv6_addr_equal(local, &t->parms.laddr) &&
155                     ipv6_addr_any(&t->parms.raddr) &&
156                     (t->dev->flags & IFF_UP))
157                         return t;
158         }
159
160         hash = HASH(remote, &any);
161         for_each_ip6_tunnel_rcu(ip6n->tnls_r_l[hash]) {
162                 if (ipv6_addr_equal(remote, &t->parms.raddr) &&
163                     ipv6_addr_any(&t->parms.laddr) &&
164                     (t->dev->flags & IFF_UP))
165                         return t;
166         }
167
168         t = rcu_dereference(ip6n->collect_md_tun);
169         if (t && t->dev->flags & IFF_UP)
170                 return t;
171
172         t = rcu_dereference(ip6n->tnls_wc[0]);
173         if (t && (t->dev->flags & IFF_UP))
174                 return t;
175
176         return NULL;
177 }
178
179 /**
180  * ip6_tnl_bucket - get head of list matching given tunnel parameters
181  *   @p: parameters containing tunnel end-points
182  *
183  * Description:
184  *   ip6_tnl_bucket() returns the head of the list matching the
185  *   &struct in6_addr entries laddr and raddr in @p.
186  *
187  * Return: head of IPv6 tunnel list
188  **/
189
190 static struct ip6_tnl __rcu **
191 ip6_tnl_bucket(struct ip6_tnl_net *ip6n, const struct __ip6_tnl_parm *p)
192 {
193         const struct in6_addr *remote = &p->raddr;
194         const struct in6_addr *local = &p->laddr;
195         unsigned int h = 0;
196         int prio = 0;
197
198         if (!ipv6_addr_any(remote) || !ipv6_addr_any(local)) {
199                 prio = 1;
200                 h = HASH(remote, local);
201         }
202         return &ip6n->tnls[prio][h];
203 }
204
205 /**
206  * ip6_tnl_link - add tunnel to hash table
207  *   @t: tunnel to be added
208  **/
209
210 static void
211 ip6_tnl_link(struct ip6_tnl_net *ip6n, struct ip6_tnl *t)
212 {
213         struct ip6_tnl __rcu **tp = ip6_tnl_bucket(ip6n, &t->parms);
214
215         if (t->parms.collect_md)
216                 rcu_assign_pointer(ip6n->collect_md_tun, t);
217         rcu_assign_pointer(t->next , rtnl_dereference(*tp));
218         rcu_assign_pointer(*tp, t);
219 }
220
221 /**
222  * ip6_tnl_unlink - remove tunnel from hash table
223  *   @t: tunnel to be removed
224  **/
225
226 static void
227 ip6_tnl_unlink(struct ip6_tnl_net *ip6n, struct ip6_tnl *t)
228 {
229         struct ip6_tnl __rcu **tp;
230         struct ip6_tnl *iter;
231
232         if (t->parms.collect_md)
233                 rcu_assign_pointer(ip6n->collect_md_tun, NULL);
234
235         for (tp = ip6_tnl_bucket(ip6n, &t->parms);
236              (iter = rtnl_dereference(*tp)) != NULL;
237              tp = &iter->next) {
238                 if (t == iter) {
239                         rcu_assign_pointer(*tp, t->next);
240                         break;
241                 }
242         }
243 }
244
245 static void ip6_dev_free(struct net_device *dev)
246 {
247         struct ip6_tnl *t = netdev_priv(dev);
248
249         gro_cells_destroy(&t->gro_cells);
250         dst_cache_destroy(&t->dst_cache);
251         free_percpu(dev->tstats);
252 }
253
254 static int ip6_tnl_create2(struct net_device *dev)
255 {
256         struct ip6_tnl *t = netdev_priv(dev);
257         struct net *net = dev_net(dev);
258         struct ip6_tnl_net *ip6n = net_generic(net, ip6_tnl_net_id);
259         int err;
260
261         t = netdev_priv(dev);
262
263         dev->rtnl_link_ops = &ip6_link_ops;
264         err = register_netdevice(dev);
265         if (err < 0)
266                 goto out;
267
268         strcpy(t->parms.name, dev->name);
269
270         ip6_tnl_link(ip6n, t);
271         return 0;
272
273 out:
274         return err;
275 }
276
277 /**
278  * ip6_tnl_create - create a new tunnel
279  *   @p: tunnel parameters
280  *   @pt: pointer to new tunnel
281  *
282  * Description:
283  *   Create tunnel matching given parameters.
284  *
285  * Return:
286  *   created tunnel or error pointer
287  **/
288
289 static struct ip6_tnl *ip6_tnl_create(struct net *net, struct __ip6_tnl_parm *p)
290 {
291         struct net_device *dev;
292         struct ip6_tnl *t;
293         char name[IFNAMSIZ];
294         int err = -E2BIG;
295
296         if (p->name[0]) {
297                 if (!dev_valid_name(p->name))
298                         goto failed;
299                 strlcpy(name, p->name, IFNAMSIZ);
300         } else {
301                 sprintf(name, "ip6tnl%%d");
302         }
303         err = -ENOMEM;
304         dev = alloc_netdev(sizeof(*t), name, NET_NAME_UNKNOWN,
305                            ip6_tnl_dev_setup);
306         if (!dev)
307                 goto failed;
308
309         dev_net_set(dev, net);
310
311         t = netdev_priv(dev);
312         t->parms = *p;
313         t->net = dev_net(dev);
314         err = ip6_tnl_create2(dev);
315         if (err < 0)
316                 goto failed_free;
317
318         return t;
319
320 failed_free:
321         free_netdev(dev);
322 failed:
323         return ERR_PTR(err);
324 }
325
326 /**
327  * ip6_tnl_locate - find or create tunnel matching given parameters
328  *   @p: tunnel parameters
329  *   @create: != 0 if allowed to create new tunnel if no match found
330  *
331  * Description:
332  *   ip6_tnl_locate() first tries to locate an existing tunnel
333  *   based on @parms. If this is unsuccessful, but @create is set a new
334  *   tunnel device is created and registered for use.
335  *
336  * Return:
337  *   matching tunnel or error pointer
338  **/
339
340 static struct ip6_tnl *ip6_tnl_locate(struct net *net,
341                 struct __ip6_tnl_parm *p, int create)
342 {
343         const struct in6_addr *remote = &p->raddr;
344         const struct in6_addr *local = &p->laddr;
345         struct ip6_tnl __rcu **tp;
346         struct ip6_tnl *t;
347         struct ip6_tnl_net *ip6n = net_generic(net, ip6_tnl_net_id);
348
349         for (tp = ip6_tnl_bucket(ip6n, p);
350              (t = rtnl_dereference(*tp)) != NULL;
351              tp = &t->next) {
352                 if (ipv6_addr_equal(local, &t->parms.laddr) &&
353                     ipv6_addr_equal(remote, &t->parms.raddr)) {
354                         if (create)
355                                 return ERR_PTR(-EEXIST);
356
357                         return t;
358                 }
359         }
360         if (!create)
361                 return ERR_PTR(-ENODEV);
362         return ip6_tnl_create(net, p);
363 }
364
365 /**
366  * ip6_tnl_dev_uninit - tunnel device uninitializer
367  *   @dev: the device to be destroyed
368  *
369  * Description:
370  *   ip6_tnl_dev_uninit() removes tunnel from its list
371  **/
372
373 static void
374 ip6_tnl_dev_uninit(struct net_device *dev)
375 {
376         struct ip6_tnl *t = netdev_priv(dev);
377         struct net *net = t->net;
378         struct ip6_tnl_net *ip6n = net_generic(net, ip6_tnl_net_id);
379
380         if (dev == ip6n->fb_tnl_dev)
381                 RCU_INIT_POINTER(ip6n->tnls_wc[0], NULL);
382         else
383                 ip6_tnl_unlink(ip6n, t);
384         dst_cache_reset(&t->dst_cache);
385         dev_put(dev);
386 }
387
388 /**
389  * parse_tvl_tnl_enc_lim - handle encapsulation limit option
390  *   @skb: received socket buffer
391  *
392  * Return:
393  *   0 if none was found,
394  *   else index to encapsulation limit
395  **/
396
397 __u16 ip6_tnl_parse_tlv_enc_lim(struct sk_buff *skb, __u8 *raw)
398 {
399         const struct ipv6hdr *ipv6h = (const struct ipv6hdr *)raw;
400         unsigned int nhoff = raw - skb->data;
401         unsigned int off = nhoff + sizeof(*ipv6h);
402         u8 next, nexthdr = ipv6h->nexthdr;
403
404         while (ipv6_ext_hdr(nexthdr) && nexthdr != NEXTHDR_NONE) {
405                 struct ipv6_opt_hdr *hdr;
406                 u16 optlen;
407
408                 if (!pskb_may_pull(skb, off + sizeof(*hdr)))
409                         break;
410
411                 hdr = (struct ipv6_opt_hdr *)(skb->data + off);
412                 if (nexthdr == NEXTHDR_FRAGMENT) {
413                         struct frag_hdr *frag_hdr = (struct frag_hdr *) hdr;
414                         if (frag_hdr->frag_off)
415                                 break;
416                         optlen = 8;
417                 } else if (nexthdr == NEXTHDR_AUTH) {
418                         optlen = ipv6_authlen(hdr);
419                 } else {
420                         optlen = ipv6_optlen(hdr);
421                 }
422                 /* cache hdr->nexthdr, since pskb_may_pull() might
423                  * invalidate hdr
424                  */
425                 next = hdr->nexthdr;
426                 if (nexthdr == NEXTHDR_DEST) {
427                         u16 i = 2;
428
429                         /* Remember : hdr is no longer valid at this point. */
430                         if (!pskb_may_pull(skb, off + optlen))
431                                 break;
432
433                         while (1) {
434                                 struct ipv6_tlv_tnl_enc_lim *tel;
435
436                                 /* No more room for encapsulation limit */
437                                 if (i + sizeof(*tel) > optlen)
438                                         break;
439
440                                 tel = (struct ipv6_tlv_tnl_enc_lim *)(skb->data + off + i);
441                                 /* return index of option if found and valid */
442                                 if (tel->type == IPV6_TLV_TNL_ENCAP_LIMIT &&
443                                     tel->length == 1)
444                                         return i + off - nhoff;
445                                 /* else jump to next option */
446                                 if (tel->type)
447                                         i += tel->length + 2;
448                                 else
449                                         i++;
450                         }
451                 }
452                 nexthdr = next;
453                 off += optlen;
454         }
455         return 0;
456 }
457 EXPORT_SYMBOL(ip6_tnl_parse_tlv_enc_lim);
458
459 /**
460  * ip6_tnl_err - tunnel error handler
461  *
462  * Description:
463  *   ip6_tnl_err() should handle errors in the tunnel according
464  *   to the specifications in RFC 2473.
465  **/
466
467 static int
468 ip6_tnl_err(struct sk_buff *skb, __u8 ipproto, struct inet6_skb_parm *opt,
469             u8 *type, u8 *code, int *msg, __u32 *info, int offset)
470 {
471         const struct ipv6hdr *ipv6h = (const struct ipv6hdr *)skb->data;
472         struct net *net = dev_net(skb->dev);
473         u8 rel_type = ICMPV6_DEST_UNREACH;
474         u8 rel_code = ICMPV6_ADDR_UNREACH;
475         __u32 rel_info = 0;
476         struct ip6_tnl *t;
477         int err = -ENOENT;
478         int rel_msg = 0;
479         u8 tproto;
480         __u16 len;
481
482         /* If the packet doesn't contain the original IPv6 header we are
483            in trouble since we might need the source address for further
484            processing of the error. */
485
486         rcu_read_lock();
487         t = ip6_tnl_lookup(dev_net(skb->dev), &ipv6h->daddr, &ipv6h->saddr);
488         if (!t)
489                 goto out;
490
491         tproto = READ_ONCE(t->parms.proto);
492         if (tproto != ipproto && tproto != 0)
493                 goto out;
494
495         err = 0;
496
497         switch (*type) {
498                 struct ipv6_tlv_tnl_enc_lim *tel;
499                 __u32 mtu, teli;
500         case ICMPV6_DEST_UNREACH:
501                 net_dbg_ratelimited("%s: Path to destination invalid or inactive!\n",
502                                     t->parms.name);
503                 rel_msg = 1;
504                 break;
505         case ICMPV6_TIME_EXCEED:
506                 if ((*code) == ICMPV6_EXC_HOPLIMIT) {
507                         net_dbg_ratelimited("%s: Too small hop limit or routing loop in tunnel!\n",
508                                             t->parms.name);
509                         rel_msg = 1;
510                 }
511                 break;
512         case ICMPV6_PARAMPROB:
513                 teli = 0;
514                 if ((*code) == ICMPV6_HDR_FIELD)
515                         teli = ip6_tnl_parse_tlv_enc_lim(skb, skb->data);
516
517                 if (teli && teli == *info - 2) {
518                         tel = (struct ipv6_tlv_tnl_enc_lim *) &skb->data[teli];
519                         if (tel->encap_limit == 0) {
520                                 net_dbg_ratelimited("%s: Too small encapsulation limit or routing loop in tunnel!\n",
521                                                     t->parms.name);
522                                 rel_msg = 1;
523                         }
524                 } else {
525                         net_dbg_ratelimited("%s: Recipient unable to parse tunneled packet!\n",
526                                             t->parms.name);
527                 }
528                 break;
529         case ICMPV6_PKT_TOOBIG:
530                 ip6_update_pmtu(skb, net, htonl(*info), 0, 0,
531                                 sock_net_uid(net, NULL));
532                 mtu = *info - offset;
533                 if (mtu < IPV6_MIN_MTU)
534                         mtu = IPV6_MIN_MTU;
535                 len = sizeof(*ipv6h) + ntohs(ipv6h->payload_len);
536                 if (len > mtu) {
537                         rel_type = ICMPV6_PKT_TOOBIG;
538                         rel_code = 0;
539                         rel_info = mtu;
540                         rel_msg = 1;
541                 }
542                 break;
543         case NDISC_REDIRECT:
544                 ip6_redirect(skb, net, skb->dev->ifindex, 0,
545                              sock_net_uid(net, NULL));
546                 break;
547         }
548
549         *type = rel_type;
550         *code = rel_code;
551         *info = rel_info;
552         *msg = rel_msg;
553
554 out:
555         rcu_read_unlock();
556         return err;
557 }
558
559 static int
560 ip4ip6_err(struct sk_buff *skb, struct inet6_skb_parm *opt,
561            u8 type, u8 code, int offset, __be32 info)
562 {
563         __u32 rel_info = ntohl(info);
564         const struct iphdr *eiph;
565         struct sk_buff *skb2;
566         int err, rel_msg = 0;
567         u8 rel_type = type;
568         u8 rel_code = code;
569         struct rtable *rt;
570         struct flowi4 fl4;
571
572         err = ip6_tnl_err(skb, IPPROTO_IPIP, opt, &rel_type, &rel_code,
573                           &rel_msg, &rel_info, offset);
574         if (err < 0)
575                 return err;
576
577         if (rel_msg == 0)
578                 return 0;
579
580         switch (rel_type) {
581         case ICMPV6_DEST_UNREACH:
582                 if (rel_code != ICMPV6_ADDR_UNREACH)
583                         return 0;
584                 rel_type = ICMP_DEST_UNREACH;
585                 rel_code = ICMP_HOST_UNREACH;
586                 break;
587         case ICMPV6_PKT_TOOBIG:
588                 if (rel_code != 0)
589                         return 0;
590                 rel_type = ICMP_DEST_UNREACH;
591                 rel_code = ICMP_FRAG_NEEDED;
592                 break;
593         default:
594                 return 0;
595         }
596
597         if (!pskb_may_pull(skb, offset + sizeof(struct iphdr)))
598                 return 0;
599
600         skb2 = skb_clone(skb, GFP_ATOMIC);
601         if (!skb2)
602                 return 0;
603
604         skb_dst_drop(skb2);
605
606         skb_pull(skb2, offset);
607         skb_reset_network_header(skb2);
608         eiph = ip_hdr(skb2);
609
610         /* Try to guess incoming interface */
611         rt = ip_route_output_ports(dev_net(skb->dev), &fl4, NULL, eiph->saddr,
612                                    0, 0, 0, IPPROTO_IPIP, RT_TOS(eiph->tos), 0);
613         if (IS_ERR(rt))
614                 goto out;
615
616         skb2->dev = rt->dst.dev;
617         ip_rt_put(rt);
618
619         /* route "incoming" packet */
620         if (rt->rt_flags & RTCF_LOCAL) {
621                 rt = ip_route_output_ports(dev_net(skb->dev), &fl4, NULL,
622                                            eiph->daddr, eiph->saddr, 0, 0,
623                                            IPPROTO_IPIP, RT_TOS(eiph->tos), 0);
624                 if (IS_ERR(rt) || rt->dst.dev->type != ARPHRD_TUNNEL6) {
625                         if (!IS_ERR(rt))
626                                 ip_rt_put(rt);
627                         goto out;
628                 }
629                 skb_dst_set(skb2, &rt->dst);
630         } else {
631                 if (ip_route_input(skb2, eiph->daddr, eiph->saddr, eiph->tos,
632                                    skb2->dev) ||
633                     skb_dst(skb2)->dev->type != ARPHRD_TUNNEL6)
634                         goto out;
635         }
636
637         /* change mtu on this route */
638         if (rel_type == ICMP_DEST_UNREACH && rel_code == ICMP_FRAG_NEEDED) {
639                 if (rel_info > dst_mtu(skb_dst(skb2)))
640                         goto out;
641
642                 skb_dst_update_pmtu_no_confirm(skb2, rel_info);
643         }
644
645         icmp_send(skb2, rel_type, rel_code, htonl(rel_info));
646
647 out:
648         kfree_skb(skb2);
649         return 0;
650 }
651
652 static int
653 ip6ip6_err(struct sk_buff *skb, struct inet6_skb_parm *opt,
654            u8 type, u8 code, int offset, __be32 info)
655 {
656         __u32 rel_info = ntohl(info);
657         int err, rel_msg = 0;
658         u8 rel_type = type;
659         u8 rel_code = code;
660
661         err = ip6_tnl_err(skb, IPPROTO_IPV6, opt, &rel_type, &rel_code,
662                           &rel_msg, &rel_info, offset);
663         if (err < 0)
664                 return err;
665
666         if (rel_msg && pskb_may_pull(skb, offset + sizeof(struct ipv6hdr))) {
667                 struct rt6_info *rt;
668                 struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC);
669
670                 if (!skb2)
671                         return 0;
672
673                 skb_dst_drop(skb2);
674                 skb_pull(skb2, offset);
675                 skb_reset_network_header(skb2);
676
677                 /* Try to guess incoming interface */
678                 rt = rt6_lookup(dev_net(skb->dev), &ipv6_hdr(skb2)->saddr,
679                                 NULL, 0, skb2, 0);
680
681                 if (rt && rt->dst.dev)
682                         skb2->dev = rt->dst.dev;
683
684                 icmpv6_send(skb2, rel_type, rel_code, rel_info);
685
686                 ip6_rt_put(rt);
687
688                 kfree_skb(skb2);
689         }
690
691         return 0;
692 }
693
694 static int ip4ip6_dscp_ecn_decapsulate(const struct ip6_tnl *t,
695                                        const struct ipv6hdr *ipv6h,
696                                        struct sk_buff *skb)
697 {
698         __u8 dsfield = ipv6_get_dsfield(ipv6h) & ~INET_ECN_MASK;
699
700         if (t->parms.flags & IP6_TNL_F_RCV_DSCP_COPY)
701                 ipv4_change_dsfield(ip_hdr(skb), INET_ECN_MASK, dsfield);
702
703         return IP6_ECN_decapsulate(ipv6h, skb);
704 }
705
706 static int ip6ip6_dscp_ecn_decapsulate(const struct ip6_tnl *t,
707                                        const struct ipv6hdr *ipv6h,
708                                        struct sk_buff *skb)
709 {
710         if (t->parms.flags & IP6_TNL_F_RCV_DSCP_COPY)
711                 ipv6_copy_dscp(ipv6_get_dsfield(ipv6h), ipv6_hdr(skb));
712
713         return IP6_ECN_decapsulate(ipv6h, skb);
714 }
715
716 __u32 ip6_tnl_get_cap(struct ip6_tnl *t,
717                              const struct in6_addr *laddr,
718                              const struct in6_addr *raddr)
719 {
720         struct __ip6_tnl_parm *p = &t->parms;
721         int ltype = ipv6_addr_type(laddr);
722         int rtype = ipv6_addr_type(raddr);
723         __u32 flags = 0;
724
725         if (ltype == IPV6_ADDR_ANY || rtype == IPV6_ADDR_ANY) {
726                 flags = IP6_TNL_F_CAP_PER_PACKET;
727         } else if (ltype & (IPV6_ADDR_UNICAST|IPV6_ADDR_MULTICAST) &&
728                    rtype & (IPV6_ADDR_UNICAST|IPV6_ADDR_MULTICAST) &&
729                    !((ltype|rtype) & IPV6_ADDR_LOOPBACK) &&
730                    (!((ltype|rtype) & IPV6_ADDR_LINKLOCAL) || p->link)) {
731                 if (ltype&IPV6_ADDR_UNICAST)
732                         flags |= IP6_TNL_F_CAP_XMIT;
733                 if (rtype&IPV6_ADDR_UNICAST)
734                         flags |= IP6_TNL_F_CAP_RCV;
735         }
736         return flags;
737 }
738 EXPORT_SYMBOL(ip6_tnl_get_cap);
739
740 /* called with rcu_read_lock() */
741 int ip6_tnl_rcv_ctl(struct ip6_tnl *t,
742                                   const struct in6_addr *laddr,
743                                   const struct in6_addr *raddr)
744 {
745         struct __ip6_tnl_parm *p = &t->parms;
746         int ret = 0;
747         struct net *net = t->net;
748
749         if ((p->flags & IP6_TNL_F_CAP_RCV) ||
750             ((p->flags & IP6_TNL_F_CAP_PER_PACKET) &&
751              (ip6_tnl_get_cap(t, laddr, raddr) & IP6_TNL_F_CAP_RCV))) {
752                 struct net_device *ldev = NULL;
753
754                 if (p->link)
755                         ldev = dev_get_by_index_rcu(net, p->link);
756
757                 if ((ipv6_addr_is_multicast(laddr) ||
758                      likely(ipv6_chk_addr_and_flags(net, laddr, ldev, false,
759                                                     0, IFA_F_TENTATIVE))) &&
760                     ((p->flags & IP6_TNL_F_ALLOW_LOCAL_REMOTE) ||
761                      likely(!ipv6_chk_addr_and_flags(net, raddr, ldev, true,
762                                                      0, IFA_F_TENTATIVE))))
763                         ret = 1;
764         }
765         return ret;
766 }
767 EXPORT_SYMBOL_GPL(ip6_tnl_rcv_ctl);
768
769 static int __ip6_tnl_rcv(struct ip6_tnl *tunnel, struct sk_buff *skb,
770                          const struct tnl_ptk_info *tpi,
771                          struct metadata_dst *tun_dst,
772                          int (*dscp_ecn_decapsulate)(const struct ip6_tnl *t,
773                                                 const struct ipv6hdr *ipv6h,
774                                                 struct sk_buff *skb),
775                          bool log_ecn_err)
776 {
777         struct pcpu_sw_netstats *tstats;
778         const struct ipv6hdr *ipv6h = ipv6_hdr(skb);
779         int err;
780
781         if ((!(tpi->flags & TUNNEL_CSUM) &&
782              (tunnel->parms.i_flags & TUNNEL_CSUM)) ||
783             ((tpi->flags & TUNNEL_CSUM) &&
784              !(tunnel->parms.i_flags & TUNNEL_CSUM))) {
785                 tunnel->dev->stats.rx_crc_errors++;
786                 tunnel->dev->stats.rx_errors++;
787                 goto drop;
788         }
789
790         if (tunnel->parms.i_flags & TUNNEL_SEQ) {
791                 if (!(tpi->flags & TUNNEL_SEQ) ||
792                     (tunnel->i_seqno &&
793                      (s32)(ntohl(tpi->seq) - tunnel->i_seqno) < 0)) {
794                         tunnel->dev->stats.rx_fifo_errors++;
795                         tunnel->dev->stats.rx_errors++;
796                         goto drop;
797                 }
798                 tunnel->i_seqno = ntohl(tpi->seq) + 1;
799         }
800
801         skb->protocol = tpi->proto;
802
803         /* Warning: All skb pointers will be invalidated! */
804         if (tunnel->dev->type == ARPHRD_ETHER) {
805                 if (!pskb_may_pull(skb, ETH_HLEN)) {
806                         tunnel->dev->stats.rx_length_errors++;
807                         tunnel->dev->stats.rx_errors++;
808                         goto drop;
809                 }
810
811                 ipv6h = ipv6_hdr(skb);
812                 skb->protocol = eth_type_trans(skb, tunnel->dev);
813                 skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
814         } else {
815                 skb->dev = tunnel->dev;
816         }
817
818         skb_reset_network_header(skb);
819         memset(skb->cb, 0, sizeof(struct inet6_skb_parm));
820
821         __skb_tunnel_rx(skb, tunnel->dev, tunnel->net);
822
823         err = dscp_ecn_decapsulate(tunnel, ipv6h, skb);
824         if (unlikely(err)) {
825                 if (log_ecn_err)
826                         net_info_ratelimited("non-ECT from %pI6 with DS=%#x\n",
827                                              &ipv6h->saddr,
828                                              ipv6_get_dsfield(ipv6h));
829                 if (err > 1) {
830                         ++tunnel->dev->stats.rx_frame_errors;
831                         ++tunnel->dev->stats.rx_errors;
832                         goto drop;
833                 }
834         }
835
836         tstats = this_cpu_ptr(tunnel->dev->tstats);
837         u64_stats_update_begin(&tstats->syncp);
838         tstats->rx_packets++;
839         tstats->rx_bytes += skb->len;
840         u64_stats_update_end(&tstats->syncp);
841
842         skb_scrub_packet(skb, !net_eq(tunnel->net, dev_net(tunnel->dev)));
843
844         if (tun_dst)
845                 skb_dst_set(skb, (struct dst_entry *)tun_dst);
846
847         gro_cells_receive(&tunnel->gro_cells, skb);
848         return 0;
849
850 drop:
851         if (tun_dst)
852                 dst_release((struct dst_entry *)tun_dst);
853         kfree_skb(skb);
854         return 0;
855 }
856
857 int ip6_tnl_rcv(struct ip6_tnl *t, struct sk_buff *skb,
858                 const struct tnl_ptk_info *tpi,
859                 struct metadata_dst *tun_dst,
860                 bool log_ecn_err)
861 {
862         int (*dscp_ecn_decapsulate)(const struct ip6_tnl *t,
863                                     const struct ipv6hdr *ipv6h,
864                                     struct sk_buff *skb);
865
866         dscp_ecn_decapsulate = ip6ip6_dscp_ecn_decapsulate;
867         if (tpi->proto == htons(ETH_P_IP))
868                 dscp_ecn_decapsulate = ip4ip6_dscp_ecn_decapsulate;
869
870         return __ip6_tnl_rcv(t, skb, tpi, tun_dst, dscp_ecn_decapsulate,
871                              log_ecn_err);
872 }
873 EXPORT_SYMBOL(ip6_tnl_rcv);
874
875 static const struct tnl_ptk_info tpi_v6 = {
876         /* no tunnel info required for ipxip6. */
877         .proto = htons(ETH_P_IPV6),
878 };
879
880 static const struct tnl_ptk_info tpi_v4 = {
881         /* no tunnel info required for ipxip6. */
882         .proto = htons(ETH_P_IP),
883 };
884
885 static int ipxip6_rcv(struct sk_buff *skb, u8 ipproto,
886                       const struct tnl_ptk_info *tpi,
887                       int (*dscp_ecn_decapsulate)(const struct ip6_tnl *t,
888                                                   const struct ipv6hdr *ipv6h,
889                                                   struct sk_buff *skb))
890 {
891         struct ip6_tnl *t;
892         const struct ipv6hdr *ipv6h = ipv6_hdr(skb);
893         struct metadata_dst *tun_dst = NULL;
894         int ret = -1;
895
896         rcu_read_lock();
897         t = ip6_tnl_lookup(dev_net(skb->dev), &ipv6h->saddr, &ipv6h->daddr);
898
899         if (t) {
900                 u8 tproto = READ_ONCE(t->parms.proto);
901
902                 if (tproto != ipproto && tproto != 0)
903                         goto drop;
904                 if (!xfrm6_policy_check(NULL, XFRM_POLICY_IN, skb))
905                         goto drop;
906                 ipv6h = ipv6_hdr(skb);
907                 if (!ip6_tnl_rcv_ctl(t, &ipv6h->daddr, &ipv6h->saddr))
908                         goto drop;
909                 if (iptunnel_pull_header(skb, 0, tpi->proto, false))
910                         goto drop;
911                 if (t->parms.collect_md) {
912                         tun_dst = ipv6_tun_rx_dst(skb, 0, 0, 0);
913                         if (!tun_dst)
914                                 goto drop;
915                 }
916                 ret = __ip6_tnl_rcv(t, skb, tpi, tun_dst, dscp_ecn_decapsulate,
917                                     log_ecn_error);
918         }
919
920         rcu_read_unlock();
921
922         return ret;
923
924 drop:
925         rcu_read_unlock();
926         kfree_skb(skb);
927         return 0;
928 }
929
930 static int ip4ip6_rcv(struct sk_buff *skb)
931 {
932         return ipxip6_rcv(skb, IPPROTO_IPIP, &tpi_v4,
933                           ip4ip6_dscp_ecn_decapsulate);
934 }
935
936 static int ip6ip6_rcv(struct sk_buff *skb)
937 {
938         return ipxip6_rcv(skb, IPPROTO_IPV6, &tpi_v6,
939                           ip6ip6_dscp_ecn_decapsulate);
940 }
941
942 struct ipv6_tel_txoption {
943         struct ipv6_txoptions ops;
944         __u8 dst_opt[8];
945 };
946
947 static void init_tel_txopt(struct ipv6_tel_txoption *opt, __u8 encap_limit)
948 {
949         memset(opt, 0, sizeof(struct ipv6_tel_txoption));
950
951         opt->dst_opt[2] = IPV6_TLV_TNL_ENCAP_LIMIT;
952         opt->dst_opt[3] = 1;
953         opt->dst_opt[4] = encap_limit;
954         opt->dst_opt[5] = IPV6_TLV_PADN;
955         opt->dst_opt[6] = 1;
956
957         opt->ops.dst1opt = (struct ipv6_opt_hdr *) opt->dst_opt;
958         opt->ops.opt_nflen = 8;
959 }
960
961 /**
962  * ip6_tnl_addr_conflict - compare packet addresses to tunnel's own
963  *   @t: the outgoing tunnel device
964  *   @hdr: IPv6 header from the incoming packet
965  *
966  * Description:
967  *   Avoid trivial tunneling loop by checking that tunnel exit-point
968  *   doesn't match source of incoming packet.
969  *
970  * Return:
971  *   1 if conflict,
972  *   0 else
973  **/
974
975 static inline bool
976 ip6_tnl_addr_conflict(const struct ip6_tnl *t, const struct ipv6hdr *hdr)
977 {
978         return ipv6_addr_equal(&t->parms.raddr, &hdr->saddr);
979 }
980
981 int ip6_tnl_xmit_ctl(struct ip6_tnl *t,
982                      const struct in6_addr *laddr,
983                      const struct in6_addr *raddr)
984 {
985         struct __ip6_tnl_parm *p = &t->parms;
986         int ret = 0;
987         struct net *net = t->net;
988
989         if (t->parms.collect_md)
990                 return 1;
991
992         if ((p->flags & IP6_TNL_F_CAP_XMIT) ||
993             ((p->flags & IP6_TNL_F_CAP_PER_PACKET) &&
994              (ip6_tnl_get_cap(t, laddr, raddr) & IP6_TNL_F_CAP_XMIT))) {
995                 struct net_device *ldev = NULL;
996
997                 rcu_read_lock();
998                 if (p->link)
999                         ldev = dev_get_by_index_rcu(net, p->link);
1000
1001                 if (unlikely(!ipv6_chk_addr_and_flags(net, laddr, ldev, false,
1002                                                       0, IFA_F_TENTATIVE)))
1003                         pr_warn_ratelimited("%s xmit: Local address not yet configured!\n",
1004                                             p->name);
1005                 else if (!(p->flags & IP6_TNL_F_ALLOW_LOCAL_REMOTE) &&
1006                          !ipv6_addr_is_multicast(raddr) &&
1007                          unlikely(ipv6_chk_addr_and_flags(net, raddr, ldev,
1008                                                           true, 0, IFA_F_TENTATIVE)))
1009                         pr_warn_ratelimited("%s xmit: Routing loop! Remote address found on this node!\n",
1010                                             p->name);
1011                 else
1012                         ret = 1;
1013                 rcu_read_unlock();
1014         }
1015         return ret;
1016 }
1017 EXPORT_SYMBOL_GPL(ip6_tnl_xmit_ctl);
1018
1019 /**
1020  * ip6_tnl_xmit - encapsulate packet and send
1021  *   @skb: the outgoing socket buffer
1022  *   @dev: the outgoing tunnel device
1023  *   @dsfield: dscp code for outer header
1024  *   @fl6: flow of tunneled packet
1025  *   @encap_limit: encapsulation limit
1026  *   @pmtu: Path MTU is stored if packet is too big
1027  *   @proto: next header value
1028  *
1029  * Description:
1030  *   Build new header and do some sanity checks on the packet before sending
1031  *   it.
1032  *
1033  * Return:
1034  *   0 on success
1035  *   -1 fail
1036  *   %-EMSGSIZE message too big. return mtu in this case.
1037  **/
1038
1039 int ip6_tnl_xmit(struct sk_buff *skb, struct net_device *dev, __u8 dsfield,
1040                  struct flowi6 *fl6, int encap_limit, __u32 *pmtu,
1041                  __u8 proto)
1042 {
1043         struct ip6_tnl *t = netdev_priv(dev);
1044         struct net *net = t->net;
1045         struct net_device_stats *stats = &t->dev->stats;
1046         struct ipv6hdr *ipv6h;
1047         struct ipv6_tel_txoption opt;
1048         struct dst_entry *dst = NULL, *ndst = NULL;
1049         struct net_device *tdev;
1050         int mtu;
1051         unsigned int eth_hlen = t->dev->type == ARPHRD_ETHER ? ETH_HLEN : 0;
1052         unsigned int psh_hlen = sizeof(struct ipv6hdr) + t->encap_hlen;
1053         unsigned int max_headroom = psh_hlen;
1054         bool use_cache = false;
1055         u8 hop_limit;
1056         int err = -1;
1057
1058         if (t->parms.collect_md) {
1059                 hop_limit = skb_tunnel_info(skb)->key.ttl;
1060                 goto route_lookup;
1061         } else {
1062                 hop_limit = t->parms.hop_limit;
1063         }
1064
1065         /* NBMA tunnel */
1066         if (ipv6_addr_any(&t->parms.raddr)) {
1067                 if (skb->protocol == htons(ETH_P_IPV6)) {
1068                         struct in6_addr *addr6;
1069                         struct neighbour *neigh;
1070                         int addr_type;
1071
1072                         if (!skb_dst(skb))
1073                                 goto tx_err_link_failure;
1074
1075                         neigh = dst_neigh_lookup(skb_dst(skb),
1076                                                  &ipv6_hdr(skb)->daddr);
1077                         if (!neigh)
1078                                 goto tx_err_link_failure;
1079
1080                         addr6 = (struct in6_addr *)&neigh->primary_key;
1081                         addr_type = ipv6_addr_type(addr6);
1082
1083                         if (addr_type == IPV6_ADDR_ANY)
1084                                 addr6 = &ipv6_hdr(skb)->daddr;
1085
1086                         memcpy(&fl6->daddr, addr6, sizeof(fl6->daddr));
1087                         neigh_release(neigh);
1088                 }
1089         } else if (t->parms.proto != 0 && !(t->parms.flags &
1090                                             (IP6_TNL_F_USE_ORIG_TCLASS |
1091                                              IP6_TNL_F_USE_ORIG_FWMARK))) {
1092                 /* enable the cache only if neither the outer protocol nor the
1093                  * routing decision depends on the current inner header value
1094                  */
1095                 use_cache = true;
1096         }
1097
1098         if (use_cache)
1099                 dst = dst_cache_get(&t->dst_cache);
1100
1101         if (!ip6_tnl_xmit_ctl(t, &fl6->saddr, &fl6->daddr))
1102                 goto tx_err_link_failure;
1103
1104         if (!dst) {
1105 route_lookup:
1106                 /* add dsfield to flowlabel for route lookup */
1107                 fl6->flowlabel = ip6_make_flowinfo(dsfield, fl6->flowlabel);
1108
1109                 dst = ip6_route_output(net, NULL, fl6);
1110
1111                 if (dst->error)
1112                         goto tx_err_link_failure;
1113                 dst = xfrm_lookup(net, dst, flowi6_to_flowi(fl6), NULL, 0);
1114                 if (IS_ERR(dst)) {
1115                         err = PTR_ERR(dst);
1116                         dst = NULL;
1117                         goto tx_err_link_failure;
1118                 }
1119                 if (t->parms.collect_md && ipv6_addr_any(&fl6->saddr) &&
1120                     ipv6_dev_get_saddr(net, ip6_dst_idev(dst)->dev,
1121                                        &fl6->daddr, 0, &fl6->saddr))
1122                         goto tx_err_link_failure;
1123                 ndst = dst;
1124         }
1125
1126         tdev = dst->dev;
1127
1128         if (tdev == dev) {
1129                 stats->collisions++;
1130                 net_warn_ratelimited("%s: Local routing loop detected!\n",
1131                                      t->parms.name);
1132                 goto tx_err_dst_release;
1133         }
1134         mtu = dst_mtu(dst) - eth_hlen - psh_hlen - t->tun_hlen;
1135         if (encap_limit >= 0) {
1136                 max_headroom += 8;
1137                 mtu -= 8;
1138         }
1139         mtu = max(mtu, skb->protocol == htons(ETH_P_IPV6) ?
1140                        IPV6_MIN_MTU : IPV4_MIN_MTU);
1141
1142         skb_dst_update_pmtu_no_confirm(skb, mtu);
1143         if (skb->len - t->tun_hlen - eth_hlen > mtu && !skb_is_gso(skb)) {
1144                 *pmtu = mtu;
1145                 err = -EMSGSIZE;
1146                 goto tx_err_dst_release;
1147         }
1148
1149         if (t->err_count > 0) {
1150                 if (time_before(jiffies,
1151                                 t->err_time + IP6TUNNEL_ERR_TIMEO)) {
1152                         t->err_count--;
1153
1154                         dst_link_failure(skb);
1155                 } else {
1156                         t->err_count = 0;
1157                 }
1158         }
1159
1160         skb_scrub_packet(skb, !net_eq(t->net, dev_net(dev)));
1161
1162         /*
1163          * Okay, now see if we can stuff it in the buffer as-is.
1164          */
1165         max_headroom += LL_RESERVED_SPACE(tdev);
1166
1167         if (skb_headroom(skb) < max_headroom || skb_shared(skb) ||
1168             (skb_cloned(skb) && !skb_clone_writable(skb, 0))) {
1169                 struct sk_buff *new_skb;
1170
1171                 new_skb = skb_realloc_headroom(skb, max_headroom);
1172                 if (!new_skb)
1173                         goto tx_err_dst_release;
1174
1175                 if (skb->sk)
1176                         skb_set_owner_w(new_skb, skb->sk);
1177                 consume_skb(skb);
1178                 skb = new_skb;
1179         }
1180
1181         if (t->parms.collect_md) {
1182                 if (t->encap.type != TUNNEL_ENCAP_NONE)
1183                         goto tx_err_dst_release;
1184         } else {
1185                 if (use_cache && ndst)
1186                         dst_cache_set_ip6(&t->dst_cache, ndst, &fl6->saddr);
1187         }
1188         skb_dst_set(skb, dst);
1189
1190         if (hop_limit == 0) {
1191                 if (skb->protocol == htons(ETH_P_IP))
1192                         hop_limit = ip_hdr(skb)->ttl;
1193                 else if (skb->protocol == htons(ETH_P_IPV6))
1194                         hop_limit = ipv6_hdr(skb)->hop_limit;
1195                 else
1196                         hop_limit = ip6_dst_hoplimit(dst);
1197         }
1198
1199         /* Calculate max headroom for all the headers and adjust
1200          * needed_headroom if necessary.
1201          */
1202         max_headroom = LL_RESERVED_SPACE(dst->dev) + sizeof(struct ipv6hdr)
1203                         + dst->header_len + t->hlen;
1204         if (max_headroom > dev->needed_headroom)
1205                 dev->needed_headroom = max_headroom;
1206
1207         err = ip6_tnl_encap(skb, t, &proto, fl6);
1208         if (err)
1209                 return err;
1210
1211         if (encap_limit >= 0) {
1212                 init_tel_txopt(&opt, encap_limit);
1213                 ipv6_push_frag_opts(skb, &opt.ops, &proto);
1214         }
1215
1216         skb_push(skb, sizeof(struct ipv6hdr));
1217         skb_reset_network_header(skb);
1218         ipv6h = ipv6_hdr(skb);
1219         ip6_flow_hdr(ipv6h, dsfield,
1220                      ip6_make_flowlabel(net, skb, fl6->flowlabel, true, fl6));
1221         ipv6h->hop_limit = hop_limit;
1222         ipv6h->nexthdr = proto;
1223         ipv6h->saddr = fl6->saddr;
1224         ipv6h->daddr = fl6->daddr;
1225         ip6tunnel_xmit(NULL, skb, dev);
1226         return 0;
1227 tx_err_link_failure:
1228         stats->tx_carrier_errors++;
1229         dst_link_failure(skb);
1230 tx_err_dst_release:
1231         dst_release(dst);
1232         return err;
1233 }
1234 EXPORT_SYMBOL(ip6_tnl_xmit);
1235
1236 static inline int
1237 ip4ip6_tnl_xmit(struct sk_buff *skb, struct net_device *dev)
1238 {
1239         struct ip6_tnl *t = netdev_priv(dev);
1240         const struct iphdr  *iph;
1241         int encap_limit = -1;
1242         struct flowi6 fl6;
1243         __u8 dsfield;
1244         __u32 mtu;
1245         u8 tproto;
1246         int err;
1247
1248         iph = ip_hdr(skb);
1249         memset(&(IPCB(skb)->opt), 0, sizeof(IPCB(skb)->opt));
1250
1251         tproto = READ_ONCE(t->parms.proto);
1252         if (tproto != IPPROTO_IPIP && tproto != 0)
1253                 return -1;
1254
1255         if (t->parms.collect_md) {
1256                 struct ip_tunnel_info *tun_info;
1257                 const struct ip_tunnel_key *key;
1258
1259                 tun_info = skb_tunnel_info(skb);
1260                 if (unlikely(!tun_info || !(tun_info->mode & IP_TUNNEL_INFO_TX) ||
1261                              ip_tunnel_info_af(tun_info) != AF_INET6))
1262                         return -1;
1263                 key = &tun_info->key;
1264                 memset(&fl6, 0, sizeof(fl6));
1265                 fl6.flowi6_proto = IPPROTO_IPIP;
1266                 fl6.saddr = key->u.ipv6.src;
1267                 fl6.daddr = key->u.ipv6.dst;
1268                 fl6.flowlabel = key->label;
1269                 dsfield =  key->tos;
1270         } else {
1271                 if (!(t->parms.flags & IP6_TNL_F_IGN_ENCAP_LIMIT))
1272                         encap_limit = t->parms.encap_limit;
1273
1274                 memcpy(&fl6, &t->fl.u.ip6, sizeof(fl6));
1275                 fl6.flowi6_proto = IPPROTO_IPIP;
1276
1277                 if (t->parms.flags & IP6_TNL_F_USE_ORIG_TCLASS)
1278                         dsfield = ipv4_get_dsfield(iph);
1279                 else
1280                         dsfield = ip6_tclass(t->parms.flowinfo);
1281                 if (t->parms.flags & IP6_TNL_F_USE_ORIG_FWMARK)
1282                         fl6.flowi6_mark = skb->mark;
1283                 else
1284                         fl6.flowi6_mark = t->parms.fwmark;
1285         }
1286
1287         fl6.flowi6_uid = sock_net_uid(dev_net(dev), NULL);
1288         dsfield = INET_ECN_encapsulate(dsfield, ipv4_get_dsfield(iph));
1289
1290         if (iptunnel_handle_offloads(skb, SKB_GSO_IPXIP6))
1291                 return -1;
1292
1293         skb_set_inner_ipproto(skb, IPPROTO_IPIP);
1294
1295         err = ip6_tnl_xmit(skb, dev, dsfield, &fl6, encap_limit, &mtu,
1296                            IPPROTO_IPIP);
1297         if (err != 0) {
1298                 /* XXX: send ICMP error even if DF is not set. */
1299                 if (err == -EMSGSIZE)
1300                         icmp_send(skb, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED,
1301                                   htonl(mtu));
1302                 return -1;
1303         }
1304
1305         return 0;
1306 }
1307
1308 static inline int
1309 ip6ip6_tnl_xmit(struct sk_buff *skb, struct net_device *dev)
1310 {
1311         struct ip6_tnl *t = netdev_priv(dev);
1312         struct ipv6hdr *ipv6h;
1313         int encap_limit = -1;
1314         __u16 offset;
1315         struct flowi6 fl6;
1316         __u8 dsfield;
1317         __u32 mtu;
1318         u8 tproto;
1319         int err;
1320
1321         ipv6h = ipv6_hdr(skb);
1322         tproto = READ_ONCE(t->parms.proto);
1323         if ((tproto != IPPROTO_IPV6 && tproto != 0) ||
1324             ip6_tnl_addr_conflict(t, ipv6h))
1325                 return -1;
1326
1327         if (t->parms.collect_md) {
1328                 struct ip_tunnel_info *tun_info;
1329                 const struct ip_tunnel_key *key;
1330
1331                 tun_info = skb_tunnel_info(skb);
1332                 if (unlikely(!tun_info || !(tun_info->mode & IP_TUNNEL_INFO_TX) ||
1333                              ip_tunnel_info_af(tun_info) != AF_INET6))
1334                         return -1;
1335                 key = &tun_info->key;
1336                 memset(&fl6, 0, sizeof(fl6));
1337                 fl6.flowi6_proto = IPPROTO_IPV6;
1338                 fl6.saddr = key->u.ipv6.src;
1339                 fl6.daddr = key->u.ipv6.dst;
1340                 fl6.flowlabel = key->label;
1341                 dsfield = key->tos;
1342         } else {
1343                 offset = ip6_tnl_parse_tlv_enc_lim(skb, skb_network_header(skb));
1344                 /* ip6_tnl_parse_tlv_enc_lim() might have reallocated skb->head */
1345                 ipv6h = ipv6_hdr(skb);
1346                 if (offset > 0) {
1347                         struct ipv6_tlv_tnl_enc_lim *tel;
1348
1349                         tel = (void *)&skb_network_header(skb)[offset];
1350                         if (tel->encap_limit == 0) {
1351                                 icmpv6_send(skb, ICMPV6_PARAMPROB,
1352                                             ICMPV6_HDR_FIELD, offset + 2);
1353                                 return -1;
1354                         }
1355                         encap_limit = tel->encap_limit - 1;
1356                 } else if (!(t->parms.flags & IP6_TNL_F_IGN_ENCAP_LIMIT)) {
1357                         encap_limit = t->parms.encap_limit;
1358                 }
1359
1360                 memcpy(&fl6, &t->fl.u.ip6, sizeof(fl6));
1361                 fl6.flowi6_proto = IPPROTO_IPV6;
1362
1363                 if (t->parms.flags & IP6_TNL_F_USE_ORIG_TCLASS)
1364                         dsfield = ipv6_get_dsfield(ipv6h);
1365                 else
1366                         dsfield = ip6_tclass(t->parms.flowinfo);
1367                 if (t->parms.flags & IP6_TNL_F_USE_ORIG_FLOWLABEL)
1368                         fl6.flowlabel |= ip6_flowlabel(ipv6h);
1369                 if (t->parms.flags & IP6_TNL_F_USE_ORIG_FWMARK)
1370                         fl6.flowi6_mark = skb->mark;
1371                 else
1372                         fl6.flowi6_mark = t->parms.fwmark;
1373         }
1374
1375         fl6.flowi6_uid = sock_net_uid(dev_net(dev), NULL);
1376         dsfield = INET_ECN_encapsulate(dsfield, ipv6_get_dsfield(ipv6h));
1377
1378         if (iptunnel_handle_offloads(skb, SKB_GSO_IPXIP6))
1379                 return -1;
1380
1381         skb_set_inner_ipproto(skb, IPPROTO_IPV6);
1382
1383         err = ip6_tnl_xmit(skb, dev, dsfield, &fl6, encap_limit, &mtu,
1384                            IPPROTO_IPV6);
1385         if (err != 0) {
1386                 if (err == -EMSGSIZE)
1387                         icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
1388                 return -1;
1389         }
1390
1391         return 0;
1392 }
1393
1394 static netdev_tx_t
1395 ip6_tnl_start_xmit(struct sk_buff *skb, struct net_device *dev)
1396 {
1397         struct ip6_tnl *t = netdev_priv(dev);
1398         struct net_device_stats *stats = &t->dev->stats;
1399         int ret;
1400
1401         if (!pskb_inet_may_pull(skb))
1402                 goto tx_err;
1403
1404         switch (skb->protocol) {
1405         case htons(ETH_P_IP):
1406                 ret = ip4ip6_tnl_xmit(skb, dev);
1407                 break;
1408         case htons(ETH_P_IPV6):
1409                 ret = ip6ip6_tnl_xmit(skb, dev);
1410                 break;
1411         default:
1412                 goto tx_err;
1413         }
1414
1415         if (ret < 0)
1416                 goto tx_err;
1417
1418         return NETDEV_TX_OK;
1419
1420 tx_err:
1421         stats->tx_errors++;
1422         stats->tx_dropped++;
1423         kfree_skb(skb);
1424         return NETDEV_TX_OK;
1425 }
1426
1427 static void ip6_tnl_link_config(struct ip6_tnl *t)
1428 {
1429         struct net_device *dev = t->dev;
1430         struct __ip6_tnl_parm *p = &t->parms;
1431         struct flowi6 *fl6 = &t->fl.u.ip6;
1432         int t_hlen;
1433
1434         memcpy(dev->dev_addr, &p->laddr, sizeof(struct in6_addr));
1435         memcpy(dev->broadcast, &p->raddr, sizeof(struct in6_addr));
1436
1437         /* Set up flowi template */
1438         fl6->saddr = p->laddr;
1439         fl6->daddr = p->raddr;
1440         fl6->flowi6_oif = p->link;
1441         fl6->flowlabel = 0;
1442
1443         if (!(p->flags&IP6_TNL_F_USE_ORIG_TCLASS))
1444                 fl6->flowlabel |= IPV6_TCLASS_MASK & p->flowinfo;
1445         if (!(p->flags&IP6_TNL_F_USE_ORIG_FLOWLABEL))
1446                 fl6->flowlabel |= IPV6_FLOWLABEL_MASK & p->flowinfo;
1447
1448         p->flags &= ~(IP6_TNL_F_CAP_XMIT|IP6_TNL_F_CAP_RCV|IP6_TNL_F_CAP_PER_PACKET);
1449         p->flags |= ip6_tnl_get_cap(t, &p->laddr, &p->raddr);
1450
1451         if (p->flags&IP6_TNL_F_CAP_XMIT && p->flags&IP6_TNL_F_CAP_RCV)
1452                 dev->flags |= IFF_POINTOPOINT;
1453         else
1454                 dev->flags &= ~IFF_POINTOPOINT;
1455
1456         t->tun_hlen = 0;
1457         t->hlen = t->encap_hlen + t->tun_hlen;
1458         t_hlen = t->hlen + sizeof(struct ipv6hdr);
1459
1460         if (p->flags & IP6_TNL_F_CAP_XMIT) {
1461                 int strict = (ipv6_addr_type(&p->raddr) &
1462                               (IPV6_ADDR_MULTICAST|IPV6_ADDR_LINKLOCAL));
1463
1464                 struct rt6_info *rt = rt6_lookup(t->net,
1465                                                  &p->raddr, &p->laddr,
1466                                                  p->link, NULL, strict);
1467
1468                 if (!rt)
1469                         return;
1470
1471                 if (rt->dst.dev) {
1472                         dev->hard_header_len = rt->dst.dev->hard_header_len +
1473                                 t_hlen;
1474
1475                         dev->mtu = rt->dst.dev->mtu - t_hlen;
1476                         if (!(t->parms.flags & IP6_TNL_F_IGN_ENCAP_LIMIT))
1477                                 dev->mtu -= 8;
1478
1479                         if (dev->mtu < IPV6_MIN_MTU)
1480                                 dev->mtu = IPV6_MIN_MTU;
1481                 }
1482                 ip6_rt_put(rt);
1483         }
1484 }
1485
1486 /**
1487  * ip6_tnl_change - update the tunnel parameters
1488  *   @t: tunnel to be changed
1489  *   @p: tunnel configuration parameters
1490  *
1491  * Description:
1492  *   ip6_tnl_change() updates the tunnel parameters
1493  **/
1494
1495 static int
1496 ip6_tnl_change(struct ip6_tnl *t, const struct __ip6_tnl_parm *p)
1497 {
1498         t->parms.laddr = p->laddr;
1499         t->parms.raddr = p->raddr;
1500         t->parms.flags = p->flags;
1501         t->parms.hop_limit = p->hop_limit;
1502         t->parms.encap_limit = p->encap_limit;
1503         t->parms.flowinfo = p->flowinfo;
1504         t->parms.link = p->link;
1505         t->parms.proto = p->proto;
1506         t->parms.fwmark = p->fwmark;
1507         dst_cache_reset(&t->dst_cache);
1508         ip6_tnl_link_config(t);
1509         return 0;
1510 }
1511
1512 static int ip6_tnl_update(struct ip6_tnl *t, struct __ip6_tnl_parm *p)
1513 {
1514         struct net *net = t->net;
1515         struct ip6_tnl_net *ip6n = net_generic(net, ip6_tnl_net_id);
1516         int err;
1517
1518         ip6_tnl_unlink(ip6n, t);
1519         synchronize_net();
1520         err = ip6_tnl_change(t, p);
1521         ip6_tnl_link(ip6n, t);
1522         netdev_state_change(t->dev);
1523         return err;
1524 }
1525
1526 static int ip6_tnl0_update(struct ip6_tnl *t, struct __ip6_tnl_parm *p)
1527 {
1528         /* for default tnl0 device allow to change only the proto */
1529         t->parms.proto = p->proto;
1530         netdev_state_change(t->dev);
1531         return 0;
1532 }
1533
1534 static void
1535 ip6_tnl_parm_from_user(struct __ip6_tnl_parm *p, const struct ip6_tnl_parm *u)
1536 {
1537         p->laddr = u->laddr;
1538         p->raddr = u->raddr;
1539         p->flags = u->flags;
1540         p->hop_limit = u->hop_limit;
1541         p->encap_limit = u->encap_limit;
1542         p->flowinfo = u->flowinfo;
1543         p->link = u->link;
1544         p->proto = u->proto;
1545         memcpy(p->name, u->name, sizeof(u->name));
1546 }
1547
1548 static void
1549 ip6_tnl_parm_to_user(struct ip6_tnl_parm *u, const struct __ip6_tnl_parm *p)
1550 {
1551         u->laddr = p->laddr;
1552         u->raddr = p->raddr;
1553         u->flags = p->flags;
1554         u->hop_limit = p->hop_limit;
1555         u->encap_limit = p->encap_limit;
1556         u->flowinfo = p->flowinfo;
1557         u->link = p->link;
1558         u->proto = p->proto;
1559         memcpy(u->name, p->name, sizeof(u->name));
1560 }
1561
1562 /**
1563  * ip6_tnl_ioctl - configure ipv6 tunnels from userspace
1564  *   @dev: virtual device associated with tunnel
1565  *   @ifr: parameters passed from userspace
1566  *   @cmd: command to be performed
1567  *
1568  * Description:
1569  *   ip6_tnl_ioctl() is used for managing IPv6 tunnels
1570  *   from userspace.
1571  *
1572  *   The possible commands are the following:
1573  *     %SIOCGETTUNNEL: get tunnel parameters for device
1574  *     %SIOCADDTUNNEL: add tunnel matching given tunnel parameters
1575  *     %SIOCCHGTUNNEL: change tunnel parameters to those given
1576  *     %SIOCDELTUNNEL: delete tunnel
1577  *
1578  *   The fallback device "ip6tnl0", created during module
1579  *   initialization, can be used for creating other tunnel devices.
1580  *
1581  * Return:
1582  *   0 on success,
1583  *   %-EFAULT if unable to copy data to or from userspace,
1584  *   %-EPERM if current process hasn't %CAP_NET_ADMIN set
1585  *   %-EINVAL if passed tunnel parameters are invalid,
1586  *   %-EEXIST if changing a tunnel's parameters would cause a conflict
1587  *   %-ENODEV if attempting to change or delete a nonexisting device
1588  **/
1589
1590 static int
1591 ip6_tnl_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
1592 {
1593         int err = 0;
1594         struct ip6_tnl_parm p;
1595         struct __ip6_tnl_parm p1;
1596         struct ip6_tnl *t = netdev_priv(dev);
1597         struct net *net = t->net;
1598         struct ip6_tnl_net *ip6n = net_generic(net, ip6_tnl_net_id);
1599
1600         memset(&p1, 0, sizeof(p1));
1601
1602         switch (cmd) {
1603         case SIOCGETTUNNEL:
1604                 if (dev == ip6n->fb_tnl_dev) {
1605                         if (copy_from_user(&p, ifr->ifr_ifru.ifru_data, sizeof(p))) {
1606                                 err = -EFAULT;
1607                                 break;
1608                         }
1609                         ip6_tnl_parm_from_user(&p1, &p);
1610                         t = ip6_tnl_locate(net, &p1, 0);
1611                         if (IS_ERR(t))
1612                                 t = netdev_priv(dev);
1613                 } else {
1614                         memset(&p, 0, sizeof(p));
1615                 }
1616                 ip6_tnl_parm_to_user(&p, &t->parms);
1617                 if (copy_to_user(ifr->ifr_ifru.ifru_data, &p, sizeof(p))) {
1618                         err = -EFAULT;
1619                 }
1620                 break;
1621         case SIOCADDTUNNEL:
1622         case SIOCCHGTUNNEL:
1623                 err = -EPERM;
1624                 if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
1625                         break;
1626                 err = -EFAULT;
1627                 if (copy_from_user(&p, ifr->ifr_ifru.ifru_data, sizeof(p)))
1628                         break;
1629                 err = -EINVAL;
1630                 if (p.proto != IPPROTO_IPV6 && p.proto != IPPROTO_IPIP &&
1631                     p.proto != 0)
1632                         break;
1633                 ip6_tnl_parm_from_user(&p1, &p);
1634                 t = ip6_tnl_locate(net, &p1, cmd == SIOCADDTUNNEL);
1635                 if (cmd == SIOCCHGTUNNEL) {
1636                         if (!IS_ERR(t)) {
1637                                 if (t->dev != dev) {
1638                                         err = -EEXIST;
1639                                         break;
1640                                 }
1641                         } else
1642                                 t = netdev_priv(dev);
1643                         if (dev == ip6n->fb_tnl_dev)
1644                                 err = ip6_tnl0_update(t, &p1);
1645                         else
1646                                 err = ip6_tnl_update(t, &p1);
1647                 }
1648                 if (!IS_ERR(t)) {
1649                         err = 0;
1650                         ip6_tnl_parm_to_user(&p, &t->parms);
1651                         if (copy_to_user(ifr->ifr_ifru.ifru_data, &p, sizeof(p)))
1652                                 err = -EFAULT;
1653
1654                 } else {
1655                         err = PTR_ERR(t);
1656                 }
1657                 break;
1658         case SIOCDELTUNNEL:
1659                 err = -EPERM;
1660                 if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
1661                         break;
1662
1663                 if (dev == ip6n->fb_tnl_dev) {
1664                         err = -EFAULT;
1665                         if (copy_from_user(&p, ifr->ifr_ifru.ifru_data, sizeof(p)))
1666                                 break;
1667                         err = -ENOENT;
1668                         ip6_tnl_parm_from_user(&p1, &p);
1669                         t = ip6_tnl_locate(net, &p1, 0);
1670                         if (IS_ERR(t))
1671                                 break;
1672                         err = -EPERM;
1673                         if (t->dev == ip6n->fb_tnl_dev)
1674                                 break;
1675                         dev = t->dev;
1676                 }
1677                 err = 0;
1678                 unregister_netdevice(dev);
1679                 break;
1680         default:
1681                 err = -EINVAL;
1682         }
1683         return err;
1684 }
1685
1686 /**
1687  * ip6_tnl_change_mtu - change mtu manually for tunnel device
1688  *   @dev: virtual device associated with tunnel
1689  *   @new_mtu: the new mtu
1690  *
1691  * Return:
1692  *   0 on success,
1693  *   %-EINVAL if mtu too small
1694  **/
1695
1696 int ip6_tnl_change_mtu(struct net_device *dev, int new_mtu)
1697 {
1698         struct ip6_tnl *tnl = netdev_priv(dev);
1699
1700         if (tnl->parms.proto == IPPROTO_IPV6) {
1701                 if (new_mtu < IPV6_MIN_MTU)
1702                         return -EINVAL;
1703         } else {
1704                 if (new_mtu < ETH_MIN_MTU)
1705                         return -EINVAL;
1706         }
1707         if (tnl->parms.proto == IPPROTO_IPV6 || tnl->parms.proto == 0) {
1708                 if (new_mtu > IP6_MAX_MTU - dev->hard_header_len)
1709                         return -EINVAL;
1710         } else {
1711                 if (new_mtu > IP_MAX_MTU - dev->hard_header_len)
1712                         return -EINVAL;
1713         }
1714         dev->mtu = new_mtu;
1715         return 0;
1716 }
1717 EXPORT_SYMBOL(ip6_tnl_change_mtu);
1718
1719 int ip6_tnl_get_iflink(const struct net_device *dev)
1720 {
1721         struct ip6_tnl *t = netdev_priv(dev);
1722
1723         return t->parms.link;
1724 }
1725 EXPORT_SYMBOL(ip6_tnl_get_iflink);
1726
1727 int ip6_tnl_encap_add_ops(const struct ip6_tnl_encap_ops *ops,
1728                           unsigned int num)
1729 {
1730         if (num >= MAX_IPTUN_ENCAP_OPS)
1731                 return -ERANGE;
1732
1733         return !cmpxchg((const struct ip6_tnl_encap_ops **)
1734                         &ip6tun_encaps[num],
1735                         NULL, ops) ? 0 : -1;
1736 }
1737 EXPORT_SYMBOL(ip6_tnl_encap_add_ops);
1738
1739 int ip6_tnl_encap_del_ops(const struct ip6_tnl_encap_ops *ops,
1740                           unsigned int num)
1741 {
1742         int ret;
1743
1744         if (num >= MAX_IPTUN_ENCAP_OPS)
1745                 return -ERANGE;
1746
1747         ret = (cmpxchg((const struct ip6_tnl_encap_ops **)
1748                        &ip6tun_encaps[num],
1749                        ops, NULL) == ops) ? 0 : -1;
1750
1751         synchronize_net();
1752
1753         return ret;
1754 }
1755 EXPORT_SYMBOL(ip6_tnl_encap_del_ops);
1756
1757 int ip6_tnl_encap_setup(struct ip6_tnl *t,
1758                         struct ip_tunnel_encap *ipencap)
1759 {
1760         int hlen;
1761
1762         memset(&t->encap, 0, sizeof(t->encap));
1763
1764         hlen = ip6_encap_hlen(ipencap);
1765         if (hlen < 0)
1766                 return hlen;
1767
1768         t->encap.type = ipencap->type;
1769         t->encap.sport = ipencap->sport;
1770         t->encap.dport = ipencap->dport;
1771         t->encap.flags = ipencap->flags;
1772
1773         t->encap_hlen = hlen;
1774         t->hlen = t->encap_hlen + t->tun_hlen;
1775
1776         return 0;
1777 }
1778 EXPORT_SYMBOL_GPL(ip6_tnl_encap_setup);
1779
1780 static const struct net_device_ops ip6_tnl_netdev_ops = {
1781         .ndo_init       = ip6_tnl_dev_init,
1782         .ndo_uninit     = ip6_tnl_dev_uninit,
1783         .ndo_start_xmit = ip6_tnl_start_xmit,
1784         .ndo_do_ioctl   = ip6_tnl_ioctl,
1785         .ndo_change_mtu = ip6_tnl_change_mtu,
1786         .ndo_get_stats  = ip6_get_stats,
1787         .ndo_get_iflink = ip6_tnl_get_iflink,
1788 };
1789
1790 #define IPXIPX_FEATURES (NETIF_F_SG |           \
1791                          NETIF_F_FRAGLIST |     \
1792                          NETIF_F_HIGHDMA |      \
1793                          NETIF_F_GSO_SOFTWARE | \
1794                          NETIF_F_HW_CSUM)
1795
1796 /**
1797  * ip6_tnl_dev_setup - setup virtual tunnel device
1798  *   @dev: virtual device associated with tunnel
1799  *
1800  * Description:
1801  *   Initialize function pointers and device parameters
1802  **/
1803
1804 static void ip6_tnl_dev_setup(struct net_device *dev)
1805 {
1806         dev->netdev_ops = &ip6_tnl_netdev_ops;
1807         dev->needs_free_netdev = true;
1808         dev->priv_destructor = ip6_dev_free;
1809
1810         dev->type = ARPHRD_TUNNEL6;
1811         dev->flags |= IFF_NOARP;
1812         dev->addr_len = sizeof(struct in6_addr);
1813         dev->features |= NETIF_F_LLTX;
1814         netif_keep_dst(dev);
1815
1816         dev->features           |= IPXIPX_FEATURES;
1817         dev->hw_features        |= IPXIPX_FEATURES;
1818
1819         /* This perm addr will be used as interface identifier by IPv6 */
1820         dev->addr_assign_type = NET_ADDR_RANDOM;
1821         eth_random_addr(dev->perm_addr);
1822 }
1823
1824
1825 /**
1826  * ip6_tnl_dev_init_gen - general initializer for all tunnel devices
1827  *   @dev: virtual device associated with tunnel
1828  **/
1829
1830 static inline int
1831 ip6_tnl_dev_init_gen(struct net_device *dev)
1832 {
1833         struct ip6_tnl *t = netdev_priv(dev);
1834         int ret;
1835         int t_hlen;
1836
1837         t->dev = dev;
1838         t->net = dev_net(dev);
1839         dev->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats);
1840         if (!dev->tstats)
1841                 return -ENOMEM;
1842
1843         ret = dst_cache_init(&t->dst_cache, GFP_KERNEL);
1844         if (ret)
1845                 goto free_stats;
1846
1847         ret = gro_cells_init(&t->gro_cells, dev);
1848         if (ret)
1849                 goto destroy_dst;
1850
1851         t->tun_hlen = 0;
1852         t->hlen = t->encap_hlen + t->tun_hlen;
1853         t_hlen = t->hlen + sizeof(struct ipv6hdr);
1854
1855         dev->type = ARPHRD_TUNNEL6;
1856         dev->hard_header_len = LL_MAX_HEADER + t_hlen;
1857         dev->mtu = ETH_DATA_LEN - t_hlen;
1858         if (!(t->parms.flags & IP6_TNL_F_IGN_ENCAP_LIMIT))
1859                 dev->mtu -= 8;
1860         dev->min_mtu = ETH_MIN_MTU;
1861         dev->max_mtu = IP6_MAX_MTU - dev->hard_header_len;
1862
1863         dev_hold(dev);
1864         return 0;
1865
1866 destroy_dst:
1867         dst_cache_destroy(&t->dst_cache);
1868 free_stats:
1869         free_percpu(dev->tstats);
1870         dev->tstats = NULL;
1871
1872         return ret;
1873 }
1874
1875 /**
1876  * ip6_tnl_dev_init - initializer for all non fallback tunnel devices
1877  *   @dev: virtual device associated with tunnel
1878  **/
1879
1880 static int ip6_tnl_dev_init(struct net_device *dev)
1881 {
1882         struct ip6_tnl *t = netdev_priv(dev);
1883         int err = ip6_tnl_dev_init_gen(dev);
1884
1885         if (err)
1886                 return err;
1887         ip6_tnl_link_config(t);
1888         if (t->parms.collect_md)
1889                 netif_keep_dst(dev);
1890         return 0;
1891 }
1892
1893 /**
1894  * ip6_fb_tnl_dev_init - initializer for fallback tunnel device
1895  *   @dev: fallback device
1896  *
1897  * Return: 0
1898  **/
1899
1900 static int __net_init ip6_fb_tnl_dev_init(struct net_device *dev)
1901 {
1902         struct ip6_tnl *t = netdev_priv(dev);
1903         struct net *net = dev_net(dev);
1904         struct ip6_tnl_net *ip6n = net_generic(net, ip6_tnl_net_id);
1905
1906         t->parms.proto = IPPROTO_IPV6;
1907
1908         rcu_assign_pointer(ip6n->tnls_wc[0], t);
1909         return 0;
1910 }
1911
1912 static int ip6_tnl_validate(struct nlattr *tb[], struct nlattr *data[],
1913                             struct netlink_ext_ack *extack)
1914 {
1915         u8 proto;
1916
1917         if (!data || !data[IFLA_IPTUN_PROTO])
1918                 return 0;
1919
1920         proto = nla_get_u8(data[IFLA_IPTUN_PROTO]);
1921         if (proto != IPPROTO_IPV6 &&
1922             proto != IPPROTO_IPIP &&
1923             proto != 0)
1924                 return -EINVAL;
1925
1926         return 0;
1927 }
1928
1929 static void ip6_tnl_netlink_parms(struct nlattr *data[],
1930                                   struct __ip6_tnl_parm *parms)
1931 {
1932         memset(parms, 0, sizeof(*parms));
1933
1934         if (!data)
1935                 return;
1936
1937         if (data[IFLA_IPTUN_LINK])
1938                 parms->link = nla_get_u32(data[IFLA_IPTUN_LINK]);
1939
1940         if (data[IFLA_IPTUN_LOCAL])
1941                 parms->laddr = nla_get_in6_addr(data[IFLA_IPTUN_LOCAL]);
1942
1943         if (data[IFLA_IPTUN_REMOTE])
1944                 parms->raddr = nla_get_in6_addr(data[IFLA_IPTUN_REMOTE]);
1945
1946         if (data[IFLA_IPTUN_TTL])
1947                 parms->hop_limit = nla_get_u8(data[IFLA_IPTUN_TTL]);
1948
1949         if (data[IFLA_IPTUN_ENCAP_LIMIT])
1950                 parms->encap_limit = nla_get_u8(data[IFLA_IPTUN_ENCAP_LIMIT]);
1951
1952         if (data[IFLA_IPTUN_FLOWINFO])
1953                 parms->flowinfo = nla_get_be32(data[IFLA_IPTUN_FLOWINFO]);
1954
1955         if (data[IFLA_IPTUN_FLAGS])
1956                 parms->flags = nla_get_u32(data[IFLA_IPTUN_FLAGS]);
1957
1958         if (data[IFLA_IPTUN_PROTO])
1959                 parms->proto = nla_get_u8(data[IFLA_IPTUN_PROTO]);
1960
1961         if (data[IFLA_IPTUN_COLLECT_METADATA])
1962                 parms->collect_md = true;
1963
1964         if (data[IFLA_IPTUN_FWMARK])
1965                 parms->fwmark = nla_get_u32(data[IFLA_IPTUN_FWMARK]);
1966 }
1967
1968 static bool ip6_tnl_netlink_encap_parms(struct nlattr *data[],
1969                                         struct ip_tunnel_encap *ipencap)
1970 {
1971         bool ret = false;
1972
1973         memset(ipencap, 0, sizeof(*ipencap));
1974
1975         if (!data)
1976                 return ret;
1977
1978         if (data[IFLA_IPTUN_ENCAP_TYPE]) {
1979                 ret = true;
1980                 ipencap->type = nla_get_u16(data[IFLA_IPTUN_ENCAP_TYPE]);
1981         }
1982
1983         if (data[IFLA_IPTUN_ENCAP_FLAGS]) {
1984                 ret = true;
1985                 ipencap->flags = nla_get_u16(data[IFLA_IPTUN_ENCAP_FLAGS]);
1986         }
1987
1988         if (data[IFLA_IPTUN_ENCAP_SPORT]) {
1989                 ret = true;
1990                 ipencap->sport = nla_get_be16(data[IFLA_IPTUN_ENCAP_SPORT]);
1991         }
1992
1993         if (data[IFLA_IPTUN_ENCAP_DPORT]) {
1994                 ret = true;
1995                 ipencap->dport = nla_get_be16(data[IFLA_IPTUN_ENCAP_DPORT]);
1996         }
1997
1998         return ret;
1999 }
2000
2001 static int ip6_tnl_newlink(struct net *src_net, struct net_device *dev,
2002                            struct nlattr *tb[], struct nlattr *data[],
2003                            struct netlink_ext_ack *extack)
2004 {
2005         struct net *net = dev_net(dev);
2006         struct ip6_tnl_net *ip6n = net_generic(net, ip6_tnl_net_id);
2007         struct ip_tunnel_encap ipencap;
2008         struct ip6_tnl *nt, *t;
2009         int err;
2010
2011         nt = netdev_priv(dev);
2012
2013         if (ip6_tnl_netlink_encap_parms(data, &ipencap)) {
2014                 err = ip6_tnl_encap_setup(nt, &ipencap);
2015                 if (err < 0)
2016                         return err;
2017         }
2018
2019         ip6_tnl_netlink_parms(data, &nt->parms);
2020
2021         if (nt->parms.collect_md) {
2022                 if (rtnl_dereference(ip6n->collect_md_tun))
2023                         return -EEXIST;
2024         } else {
2025                 t = ip6_tnl_locate(net, &nt->parms, 0);
2026                 if (!IS_ERR(t))
2027                         return -EEXIST;
2028         }
2029
2030         err = ip6_tnl_create2(dev);
2031         if (!err && tb[IFLA_MTU])
2032                 ip6_tnl_change_mtu(dev, nla_get_u32(tb[IFLA_MTU]));
2033
2034         return err;
2035 }
2036
2037 static int ip6_tnl_changelink(struct net_device *dev, struct nlattr *tb[],
2038                               struct nlattr *data[],
2039                               struct netlink_ext_ack *extack)
2040 {
2041         struct ip6_tnl *t = netdev_priv(dev);
2042         struct __ip6_tnl_parm p;
2043         struct net *net = t->net;
2044         struct ip6_tnl_net *ip6n = net_generic(net, ip6_tnl_net_id);
2045         struct ip_tunnel_encap ipencap;
2046
2047         if (dev == ip6n->fb_tnl_dev)
2048                 return -EINVAL;
2049
2050         if (ip6_tnl_netlink_encap_parms(data, &ipencap)) {
2051                 int err = ip6_tnl_encap_setup(t, &ipencap);
2052
2053                 if (err < 0)
2054                         return err;
2055         }
2056         ip6_tnl_netlink_parms(data, &p);
2057         if (p.collect_md)
2058                 return -EINVAL;
2059
2060         t = ip6_tnl_locate(net, &p, 0);
2061         if (!IS_ERR(t)) {
2062                 if (t->dev != dev)
2063                         return -EEXIST;
2064         } else
2065                 t = netdev_priv(dev);
2066
2067         return ip6_tnl_update(t, &p);
2068 }
2069
2070 static void ip6_tnl_dellink(struct net_device *dev, struct list_head *head)
2071 {
2072         struct net *net = dev_net(dev);
2073         struct ip6_tnl_net *ip6n = net_generic(net, ip6_tnl_net_id);
2074
2075         if (dev != ip6n->fb_tnl_dev)
2076                 unregister_netdevice_queue(dev, head);
2077 }
2078
2079 static size_t ip6_tnl_get_size(const struct net_device *dev)
2080 {
2081         return
2082                 /* IFLA_IPTUN_LINK */
2083                 nla_total_size(4) +
2084                 /* IFLA_IPTUN_LOCAL */
2085                 nla_total_size(sizeof(struct in6_addr)) +
2086                 /* IFLA_IPTUN_REMOTE */
2087                 nla_total_size(sizeof(struct in6_addr)) +
2088                 /* IFLA_IPTUN_TTL */
2089                 nla_total_size(1) +
2090                 /* IFLA_IPTUN_ENCAP_LIMIT */
2091                 nla_total_size(1) +
2092                 /* IFLA_IPTUN_FLOWINFO */
2093                 nla_total_size(4) +
2094                 /* IFLA_IPTUN_FLAGS */
2095                 nla_total_size(4) +
2096                 /* IFLA_IPTUN_PROTO */
2097                 nla_total_size(1) +
2098                 /* IFLA_IPTUN_ENCAP_TYPE */
2099                 nla_total_size(2) +
2100                 /* IFLA_IPTUN_ENCAP_FLAGS */
2101                 nla_total_size(2) +
2102                 /* IFLA_IPTUN_ENCAP_SPORT */
2103                 nla_total_size(2) +
2104                 /* IFLA_IPTUN_ENCAP_DPORT */
2105                 nla_total_size(2) +
2106                 /* IFLA_IPTUN_COLLECT_METADATA */
2107                 nla_total_size(0) +
2108                 /* IFLA_IPTUN_FWMARK */
2109                 nla_total_size(4) +
2110                 0;
2111 }
2112
2113 static int ip6_tnl_fill_info(struct sk_buff *skb, const struct net_device *dev)
2114 {
2115         struct ip6_tnl *tunnel = netdev_priv(dev);
2116         struct __ip6_tnl_parm *parm = &tunnel->parms;
2117
2118         if (nla_put_u32(skb, IFLA_IPTUN_LINK, parm->link) ||
2119             nla_put_in6_addr(skb, IFLA_IPTUN_LOCAL, &parm->laddr) ||
2120             nla_put_in6_addr(skb, IFLA_IPTUN_REMOTE, &parm->raddr) ||
2121             nla_put_u8(skb, IFLA_IPTUN_TTL, parm->hop_limit) ||
2122             nla_put_u8(skb, IFLA_IPTUN_ENCAP_LIMIT, parm->encap_limit) ||
2123             nla_put_be32(skb, IFLA_IPTUN_FLOWINFO, parm->flowinfo) ||
2124             nla_put_u32(skb, IFLA_IPTUN_FLAGS, parm->flags) ||
2125             nla_put_u8(skb, IFLA_IPTUN_PROTO, parm->proto) ||
2126             nla_put_u32(skb, IFLA_IPTUN_FWMARK, parm->fwmark))
2127                 goto nla_put_failure;
2128
2129         if (nla_put_u16(skb, IFLA_IPTUN_ENCAP_TYPE, tunnel->encap.type) ||
2130             nla_put_be16(skb, IFLA_IPTUN_ENCAP_SPORT, tunnel->encap.sport) ||
2131             nla_put_be16(skb, IFLA_IPTUN_ENCAP_DPORT, tunnel->encap.dport) ||
2132             nla_put_u16(skb, IFLA_IPTUN_ENCAP_FLAGS, tunnel->encap.flags))
2133                 goto nla_put_failure;
2134
2135         if (parm->collect_md)
2136                 if (nla_put_flag(skb, IFLA_IPTUN_COLLECT_METADATA))
2137                         goto nla_put_failure;
2138
2139         return 0;
2140
2141 nla_put_failure:
2142         return -EMSGSIZE;
2143 }
2144
2145 struct net *ip6_tnl_get_link_net(const struct net_device *dev)
2146 {
2147         struct ip6_tnl *tunnel = netdev_priv(dev);
2148
2149         return tunnel->net;
2150 }
2151 EXPORT_SYMBOL(ip6_tnl_get_link_net);
2152
2153 static const struct nla_policy ip6_tnl_policy[IFLA_IPTUN_MAX + 1] = {
2154         [IFLA_IPTUN_LINK]               = { .type = NLA_U32 },
2155         [IFLA_IPTUN_LOCAL]              = { .len = sizeof(struct in6_addr) },
2156         [IFLA_IPTUN_REMOTE]             = { .len = sizeof(struct in6_addr) },
2157         [IFLA_IPTUN_TTL]                = { .type = NLA_U8 },
2158         [IFLA_IPTUN_ENCAP_LIMIT]        = { .type = NLA_U8 },
2159         [IFLA_IPTUN_FLOWINFO]           = { .type = NLA_U32 },
2160         [IFLA_IPTUN_FLAGS]              = { .type = NLA_U32 },
2161         [IFLA_IPTUN_PROTO]              = { .type = NLA_U8 },
2162         [IFLA_IPTUN_ENCAP_TYPE]         = { .type = NLA_U16 },
2163         [IFLA_IPTUN_ENCAP_FLAGS]        = { .type = NLA_U16 },
2164         [IFLA_IPTUN_ENCAP_SPORT]        = { .type = NLA_U16 },
2165         [IFLA_IPTUN_ENCAP_DPORT]        = { .type = NLA_U16 },
2166         [IFLA_IPTUN_COLLECT_METADATA]   = { .type = NLA_FLAG },
2167         [IFLA_IPTUN_FWMARK]             = { .type = NLA_U32 },
2168 };
2169
2170 static struct rtnl_link_ops ip6_link_ops __read_mostly = {
2171         .kind           = "ip6tnl",
2172         .maxtype        = IFLA_IPTUN_MAX,
2173         .policy         = ip6_tnl_policy,
2174         .priv_size      = sizeof(struct ip6_tnl),
2175         .setup          = ip6_tnl_dev_setup,
2176         .validate       = ip6_tnl_validate,
2177         .newlink        = ip6_tnl_newlink,
2178         .changelink     = ip6_tnl_changelink,
2179         .dellink        = ip6_tnl_dellink,
2180         .get_size       = ip6_tnl_get_size,
2181         .fill_info      = ip6_tnl_fill_info,
2182         .get_link_net   = ip6_tnl_get_link_net,
2183 };
2184
2185 static struct xfrm6_tunnel ip4ip6_handler __read_mostly = {
2186         .handler        = ip4ip6_rcv,
2187         .err_handler    = ip4ip6_err,
2188         .priority       =       1,
2189 };
2190
2191 static struct xfrm6_tunnel ip6ip6_handler __read_mostly = {
2192         .handler        = ip6ip6_rcv,
2193         .err_handler    = ip6ip6_err,
2194         .priority       =       1,
2195 };
2196
2197 static void __net_exit ip6_tnl_destroy_tunnels(struct net *net, struct list_head *list)
2198 {
2199         struct ip6_tnl_net *ip6n = net_generic(net, ip6_tnl_net_id);
2200         struct net_device *dev, *aux;
2201         int h;
2202         struct ip6_tnl *t;
2203
2204         for_each_netdev_safe(net, dev, aux)
2205                 if (dev->rtnl_link_ops == &ip6_link_ops)
2206                         unregister_netdevice_queue(dev, list);
2207
2208         for (h = 0; h < IP6_TUNNEL_HASH_SIZE; h++) {
2209                 t = rtnl_dereference(ip6n->tnls_r_l[h]);
2210                 while (t) {
2211                         /* If dev is in the same netns, it has already
2212                          * been added to the list by the previous loop.
2213                          */
2214                         if (!net_eq(dev_net(t->dev), net))
2215                                 unregister_netdevice_queue(t->dev, list);
2216                         t = rtnl_dereference(t->next);
2217                 }
2218         }
2219
2220         t = rtnl_dereference(ip6n->tnls_wc[0]);
2221         while (t) {
2222                 /* If dev is in the same netns, it has already
2223                  * been added to the list by the previous loop.
2224                  */
2225                 if (!net_eq(dev_net(t->dev), net))
2226                         unregister_netdevice_queue(t->dev, list);
2227                 t = rtnl_dereference(t->next);
2228         }
2229 }
2230
2231 static int __net_init ip6_tnl_init_net(struct net *net)
2232 {
2233         struct ip6_tnl_net *ip6n = net_generic(net, ip6_tnl_net_id);
2234         struct ip6_tnl *t = NULL;
2235         int err;
2236
2237         ip6n->tnls[0] = ip6n->tnls_wc;
2238         ip6n->tnls[1] = ip6n->tnls_r_l;
2239
2240         if (!net_has_fallback_tunnels(net))
2241                 return 0;
2242         err = -ENOMEM;
2243         ip6n->fb_tnl_dev = alloc_netdev(sizeof(struct ip6_tnl), "ip6tnl0",
2244                                         NET_NAME_UNKNOWN, ip6_tnl_dev_setup);
2245
2246         if (!ip6n->fb_tnl_dev)
2247                 goto err_alloc_dev;
2248         dev_net_set(ip6n->fb_tnl_dev, net);
2249         ip6n->fb_tnl_dev->rtnl_link_ops = &ip6_link_ops;
2250         /* FB netdevice is special: we have one, and only one per netns.
2251          * Allowing to move it to another netns is clearly unsafe.
2252          */
2253         ip6n->fb_tnl_dev->features |= NETIF_F_NETNS_LOCAL;
2254
2255         err = ip6_fb_tnl_dev_init(ip6n->fb_tnl_dev);
2256         if (err < 0)
2257                 goto err_register;
2258
2259         err = register_netdev(ip6n->fb_tnl_dev);
2260         if (err < 0)
2261                 goto err_register;
2262
2263         t = netdev_priv(ip6n->fb_tnl_dev);
2264
2265         strcpy(t->parms.name, ip6n->fb_tnl_dev->name);
2266         return 0;
2267
2268 err_register:
2269         free_netdev(ip6n->fb_tnl_dev);
2270 err_alloc_dev:
2271         return err;
2272 }
2273
2274 static void __net_exit ip6_tnl_exit_batch_net(struct list_head *net_list)
2275 {
2276         struct net *net;
2277         LIST_HEAD(list);
2278
2279         rtnl_lock();
2280         list_for_each_entry(net, net_list, exit_list)
2281                 ip6_tnl_destroy_tunnels(net, &list);
2282         unregister_netdevice_many(&list);
2283         rtnl_unlock();
2284 }
2285
2286 static struct pernet_operations ip6_tnl_net_ops = {
2287         .init = ip6_tnl_init_net,
2288         .exit_batch = ip6_tnl_exit_batch_net,
2289         .id   = &ip6_tnl_net_id,
2290         .size = sizeof(struct ip6_tnl_net),
2291 };
2292
2293 /**
2294  * ip6_tunnel_init - register protocol and reserve needed resources
2295  *
2296  * Return: 0 on success
2297  **/
2298
2299 static int __init ip6_tunnel_init(void)
2300 {
2301         int  err;
2302
2303         if (!ipv6_mod_enabled())
2304                 return -EOPNOTSUPP;
2305
2306         err = register_pernet_device(&ip6_tnl_net_ops);
2307         if (err < 0)
2308                 goto out_pernet;
2309
2310         err = xfrm6_tunnel_register(&ip4ip6_handler, AF_INET);
2311         if (err < 0) {
2312                 pr_err("%s: can't register ip4ip6\n", __func__);
2313                 goto out_ip4ip6;
2314         }
2315
2316         err = xfrm6_tunnel_register(&ip6ip6_handler, AF_INET6);
2317         if (err < 0) {
2318                 pr_err("%s: can't register ip6ip6\n", __func__);
2319                 goto out_ip6ip6;
2320         }
2321         err = rtnl_link_register(&ip6_link_ops);
2322         if (err < 0)
2323                 goto rtnl_link_failed;
2324
2325         return 0;
2326
2327 rtnl_link_failed:
2328         xfrm6_tunnel_deregister(&ip6ip6_handler, AF_INET6);
2329 out_ip6ip6:
2330         xfrm6_tunnel_deregister(&ip4ip6_handler, AF_INET);
2331 out_ip4ip6:
2332         unregister_pernet_device(&ip6_tnl_net_ops);
2333 out_pernet:
2334         return err;
2335 }
2336
2337 /**
2338  * ip6_tunnel_cleanup - free resources and unregister protocol
2339  **/
2340
2341 static void __exit ip6_tunnel_cleanup(void)
2342 {
2343         rtnl_link_unregister(&ip6_link_ops);
2344         if (xfrm6_tunnel_deregister(&ip4ip6_handler, AF_INET))
2345                 pr_info("%s: can't deregister ip4ip6\n", __func__);
2346
2347         if (xfrm6_tunnel_deregister(&ip6ip6_handler, AF_INET6))
2348                 pr_info("%s: can't deregister ip6ip6\n", __func__);
2349
2350         unregister_pernet_device(&ip6_tnl_net_ops);
2351 }
2352
2353 module_init(ip6_tunnel_init);
2354 module_exit(ip6_tunnel_cleanup);