openvswitch: Userspace tunneling.
[cascardo/ovs.git] / lib / netdev-vport.c
1 /*
2  * Copyright (c) 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include "netdev-vport.h"
20
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <sys/socket.h>
24 #include <net/if.h>
25 #include <sys/ioctl.h>
26
27 #include "byte-order.h"
28 #include "csum.h"
29 #include "daemon.h"
30 #include "dirs.h"
31 #include "dpif.h"
32 #include "dynamic-string.h"
33 #include "flow.h"
34 #include "hash.h"
35 #include "hmap.h"
36 #include "list.h"
37 #include "netdev-provider.h"
38 #include "odp-netlink.h"
39 #include "ofpbuf.h"
40 #include "ovs-router.h"
41 #include "packets.h"
42 #include "packet-dpif.h"
43 #include "poll-loop.h"
44 #include "route-table.h"
45 #include "shash.h"
46 #include "socket-util.h"
47 #include "vlog.h"
48 #include "unaligned.h"
49 #include "unixctl.h"
50 #include "util.h"
51
52 VLOG_DEFINE_THIS_MODULE(netdev_vport);
53 static struct vlog_rate_limit err_rl = VLOG_RATE_LIMIT_INIT(60, 5);
54
55 #define GENEVE_DST_PORT 6081
56 #define VXLAN_DST_PORT 4789
57 #define LISP_DST_PORT 4341
58
59 #define VXLAN_HLEN   (sizeof(struct eth_header) +         \
60                       sizeof(struct ip_header)  +         \
61                       sizeof(struct udp_header) +         \
62                       sizeof(struct vxlanhdr))
63
64 #define DEFAULT_TTL 64
65
66 struct netdev_vport {
67     struct netdev up;
68
69     /* Protects all members below. */
70     struct ovs_mutex mutex;
71
72     uint8_t etheraddr[ETH_ADDR_LEN];
73     struct netdev_stats stats;
74
75     /* Tunnels. */
76     struct netdev_tunnel_config tnl_cfg;
77     char egress_iface[IFNAMSIZ];
78     bool carrier_status;
79
80     /* Patch Ports. */
81     char *peer;
82 };
83
84 struct vport_class {
85     const char *dpif_port;
86     struct netdev_class netdev_class;
87 };
88
89 /* Last read of the route-table's change number. */
90 static uint64_t rt_change_seqno;
91
92 static int netdev_vport_construct(struct netdev *);
93 static int get_patch_config(const struct netdev *netdev, struct smap *args);
94 static int get_tunnel_config(const struct netdev *, struct smap *args);
95 static bool tunnel_check_status_change__(struct netdev_vport *);
96
97 static uint16_t tnl_udp_port_min = 32768;
98 static uint16_t tnl_udp_port_max = 61000;
99
100 static bool
101 is_vport_class(const struct netdev_class *class)
102 {
103     return class->construct == netdev_vport_construct;
104 }
105
106 bool
107 netdev_vport_is_vport_class(const struct netdev_class *class)
108 {
109     return is_vport_class(class);
110 }
111
112 static const struct vport_class *
113 vport_class_cast(const struct netdev_class *class)
114 {
115     ovs_assert(is_vport_class(class));
116     return CONTAINER_OF(class, struct vport_class, netdev_class);
117 }
118
119 static struct netdev_vport *
120 netdev_vport_cast(const struct netdev *netdev)
121 {
122     ovs_assert(is_vport_class(netdev_get_class(netdev)));
123     return CONTAINER_OF(netdev, struct netdev_vport, up);
124 }
125
126 static const struct netdev_tunnel_config *
127 get_netdev_tunnel_config(const struct netdev *netdev)
128 {
129     return &netdev_vport_cast(netdev)->tnl_cfg;
130 }
131
132 bool
133 netdev_vport_is_patch(const struct netdev *netdev)
134 {
135     const struct netdev_class *class = netdev_get_class(netdev);
136
137     return class->get_config == get_patch_config;
138 }
139
140 bool
141 netdev_vport_is_layer3(const struct netdev *dev)
142 {
143     const char *type = netdev_get_type(dev);
144
145     return (!strcmp("lisp", type));
146 }
147
148 static bool
149 netdev_vport_needs_dst_port(const struct netdev *dev)
150 {
151     const struct netdev_class *class = netdev_get_class(dev);
152     const char *type = netdev_get_type(dev);
153
154     return (class->get_config == get_tunnel_config &&
155             (!strcmp("geneve", type) || !strcmp("vxlan", type) ||
156              !strcmp("lisp", type)));
157 }
158
159 const char *
160 netdev_vport_class_get_dpif_port(const struct netdev_class *class)
161 {
162     return is_vport_class(class) ? vport_class_cast(class)->dpif_port : NULL;
163 }
164
165 const char *
166 netdev_vport_get_dpif_port(const struct netdev *netdev,
167                            char namebuf[], size_t bufsize)
168 {
169     const struct netdev_class *class = netdev_get_class(netdev);
170     const char *dpif_port = netdev_vport_class_get_dpif_port(class);
171
172     if (!dpif_port) {
173         return netdev_get_name(netdev);
174     }
175
176     if (netdev_vport_needs_dst_port(netdev)) {
177         const struct netdev_vport *vport = netdev_vport_cast(netdev);
178
179         /*
180          * Note: IFNAMSIZ is 16 bytes long. Implementations should choose
181          * a dpif port name that is short enough to fit including any
182          * port numbers but assert just in case.
183          */
184         BUILD_ASSERT(NETDEV_VPORT_NAME_BUFSIZE >= IFNAMSIZ);
185         ovs_assert(strlen(dpif_port) + 6 < IFNAMSIZ);
186         snprintf(namebuf, bufsize, "%s_%d", dpif_port,
187                  ntohs(vport->tnl_cfg.dst_port));
188         return namebuf;
189     } else {
190         return dpif_port;
191     }
192 }
193
194 char *
195 netdev_vport_get_dpif_port_strdup(const struct netdev *netdev)
196 {
197     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
198
199     return xstrdup(netdev_vport_get_dpif_port(netdev, namebuf,
200                                               sizeof namebuf));
201 }
202
203 /* Whenever the route-table change number is incremented,
204  * netdev_vport_route_changed() should be called to update
205  * the corresponding tunnel interface status. */
206 static void
207 netdev_vport_route_changed(void)
208 {
209     struct netdev **vports;
210     size_t i, n_vports;
211
212     vports = netdev_get_vports(&n_vports);
213     for (i = 0; i < n_vports; i++) {
214         struct netdev *netdev_ = vports[i];
215         struct netdev_vport *netdev = netdev_vport_cast(netdev_);
216
217         ovs_mutex_lock(&netdev->mutex);
218         /* Finds all tunnel vports. */
219         if (netdev->tnl_cfg.ip_dst) {
220             if (tunnel_check_status_change__(netdev)) {
221                 netdev_change_seq_changed(netdev_);
222             }
223         }
224         ovs_mutex_unlock(&netdev->mutex);
225
226         netdev_close(netdev_);
227     }
228
229     free(vports);
230 }
231
232 static struct netdev *
233 netdev_vport_alloc(void)
234 {
235     struct netdev_vport *netdev = xzalloc(sizeof *netdev);
236     return &netdev->up;
237 }
238
239 static int
240 netdev_vport_construct(struct netdev *netdev_)
241 {
242     struct netdev_vport *dev = netdev_vport_cast(netdev_);
243     const char *type = netdev_get_type(netdev_);
244
245     ovs_mutex_init(&dev->mutex);
246     eth_addr_random(dev->etheraddr);
247
248     /* Add a default destination port for tunnel ports if none specified. */
249     if (!strcmp(type, "geneve")) {
250         dev->tnl_cfg.dst_port = htons(GENEVE_DST_PORT);
251     } else if (!strcmp(type, "vxlan")) {
252         dev->tnl_cfg.dst_port = htons(VXLAN_DST_PORT);
253     } else if (!strcmp(type, "lisp")) {
254         dev->tnl_cfg.dst_port = htons(LISP_DST_PORT);
255     }
256
257     route_table_register();
258
259     return 0;
260 }
261
262 static void
263 netdev_vport_destruct(struct netdev *netdev_)
264 {
265     struct netdev_vport *netdev = netdev_vport_cast(netdev_);
266
267     route_table_unregister();
268     free(netdev->peer);
269     ovs_mutex_destroy(&netdev->mutex);
270 }
271
272 static void
273 netdev_vport_dealloc(struct netdev *netdev_)
274 {
275     struct netdev_vport *netdev = netdev_vport_cast(netdev_);
276     free(netdev);
277 }
278
279 static int
280 netdev_vport_set_etheraddr(struct netdev *netdev_,
281                            const uint8_t mac[ETH_ADDR_LEN])
282 {
283     struct netdev_vport *netdev = netdev_vport_cast(netdev_);
284
285     ovs_mutex_lock(&netdev->mutex);
286     memcpy(netdev->etheraddr, mac, ETH_ADDR_LEN);
287     ovs_mutex_unlock(&netdev->mutex);
288     netdev_change_seq_changed(netdev_);
289
290     return 0;
291 }
292
293 static int
294 netdev_vport_get_etheraddr(const struct netdev *netdev_,
295                            uint8_t mac[ETH_ADDR_LEN])
296 {
297     struct netdev_vport *netdev = netdev_vport_cast(netdev_);
298
299     ovs_mutex_lock(&netdev->mutex);
300     memcpy(mac, netdev->etheraddr, ETH_ADDR_LEN);
301     ovs_mutex_unlock(&netdev->mutex);
302
303     return 0;
304 }
305
306 /* Checks if the tunnel status has changed and returns a boolean.
307  * Updates the tunnel status if it has changed. */
308 static bool
309 tunnel_check_status_change__(struct netdev_vport *netdev)
310     OVS_REQUIRES(netdev->mutex)
311 {
312     char iface[IFNAMSIZ];
313     bool status = false;
314     ovs_be32 route;
315     ovs_be32 gw;
316
317     iface[0] = '\0';
318     route = netdev->tnl_cfg.ip_dst;
319     if (ovs_router_lookup(route, iface, &gw)) {
320         struct netdev *egress_netdev;
321
322         if (!netdev_open(iface, "system", &egress_netdev)) {
323             status = netdev_get_carrier(egress_netdev);
324             netdev_close(egress_netdev);
325         }
326     }
327
328     if (strcmp(netdev->egress_iface, iface)
329         || netdev->carrier_status != status) {
330         ovs_strlcpy(netdev->egress_iface, iface, IFNAMSIZ);
331         netdev->carrier_status = status;
332
333         return true;
334     }
335
336     return false;
337 }
338
339 static int
340 tunnel_get_status(const struct netdev *netdev_, struct smap *smap)
341 {
342     struct netdev_vport *netdev = netdev_vport_cast(netdev_);
343
344     if (netdev->egress_iface[0]) {
345         smap_add(smap, "tunnel_egress_iface", netdev->egress_iface);
346
347         smap_add(smap, "tunnel_egress_iface_carrier",
348                  netdev->carrier_status ? "up" : "down");
349     }
350
351     return 0;
352 }
353
354 static int
355 netdev_vport_update_flags(struct netdev *netdev OVS_UNUSED,
356                           enum netdev_flags off,
357                           enum netdev_flags on OVS_UNUSED,
358                           enum netdev_flags *old_flagsp)
359 {
360     if (off & (NETDEV_UP | NETDEV_PROMISC)) {
361         return EOPNOTSUPP;
362     }
363
364     *old_flagsp = NETDEV_UP | NETDEV_PROMISC;
365     return 0;
366 }
367
368 static void
369 netdev_vport_run(void)
370 {
371     uint64_t seq;
372
373     route_table_run();
374     seq = route_table_get_change_seq();
375     if (rt_change_seqno != seq) {
376         rt_change_seqno = seq;
377         netdev_vport_route_changed();
378     }
379 }
380
381 static void
382 netdev_vport_wait(void)
383 {
384     uint64_t seq;
385
386     route_table_wait();
387     seq = route_table_get_change_seq();
388     if (rt_change_seqno != seq) {
389         poll_immediate_wake();
390     }
391 }
392 \f
393 /* Code specific to tunnel types. */
394
395 static ovs_be64
396 parse_key(const struct smap *args, const char *name,
397           bool *present, bool *flow)
398 {
399     const char *s;
400
401     *present = false;
402     *flow = false;
403
404     s = smap_get(args, name);
405     if (!s) {
406         s = smap_get(args, "key");
407         if (!s) {
408             return 0;
409         }
410     }
411
412     *present = true;
413
414     if (!strcmp(s, "flow")) {
415         *flow = true;
416         return 0;
417     } else {
418         return htonll(strtoull(s, NULL, 0));
419     }
420 }
421
422 static int
423 set_tunnel_config(struct netdev *dev_, const struct smap *args)
424 {
425     struct netdev_vport *dev = netdev_vport_cast(dev_);
426     const char *name = netdev_get_name(dev_);
427     const char *type = netdev_get_type(dev_);
428     bool ipsec_mech_set, needs_dst_port, has_csum;
429     struct netdev_tunnel_config tnl_cfg;
430     struct smap_node *node;
431
432     has_csum = strstr(type, "gre");
433     ipsec_mech_set = false;
434     memset(&tnl_cfg, 0, sizeof tnl_cfg);
435
436     /* Add a default destination port for tunnel ports if none specified. */
437     if (!strcmp(type, "geneve")) {
438         tnl_cfg.dst_port = htons(GENEVE_DST_PORT);
439     }
440
441     if (!strcmp(type, "vxlan")) {
442         tnl_cfg.dst_port = htons(VXLAN_DST_PORT);
443     }
444
445     if (!strcmp(type, "lisp")) {
446         tnl_cfg.dst_port = htons(LISP_DST_PORT);
447     }
448
449     needs_dst_port = netdev_vport_needs_dst_port(dev_);
450     tnl_cfg.ipsec = strstr(type, "ipsec");
451     tnl_cfg.dont_fragment = true;
452
453     SMAP_FOR_EACH (node, args) {
454         if (!strcmp(node->key, "remote_ip")) {
455             struct in_addr in_addr;
456             if (!strcmp(node->value, "flow")) {
457                 tnl_cfg.ip_dst_flow = true;
458                 tnl_cfg.ip_dst = htonl(0);
459             } else if (lookup_ip(node->value, &in_addr)) {
460                 VLOG_WARN("%s: bad %s 'remote_ip'", name, type);
461             } else if (ip_is_multicast(in_addr.s_addr)) {
462                 VLOG_WARN("%s: multicast remote_ip="IP_FMT" not allowed",
463                           name, IP_ARGS(in_addr.s_addr));
464                 return EINVAL;
465             } else {
466                 tnl_cfg.ip_dst = in_addr.s_addr;
467             }
468         } else if (!strcmp(node->key, "local_ip")) {
469             struct in_addr in_addr;
470             if (!strcmp(node->value, "flow")) {
471                 tnl_cfg.ip_src_flow = true;
472                 tnl_cfg.ip_src = htonl(0);
473             } else if (lookup_ip(node->value, &in_addr)) {
474                 VLOG_WARN("%s: bad %s 'local_ip'", name, type);
475             } else {
476                 tnl_cfg.ip_src = in_addr.s_addr;
477             }
478         } else if (!strcmp(node->key, "tos")) {
479             if (!strcmp(node->value, "inherit")) {
480                 tnl_cfg.tos_inherit = true;
481             } else {
482                 char *endptr;
483                 int tos;
484                 tos = strtol(node->value, &endptr, 0);
485                 if (*endptr == '\0' && tos == (tos & IP_DSCP_MASK)) {
486                     tnl_cfg.tos = tos;
487                 } else {
488                     VLOG_WARN("%s: invalid TOS %s", name, node->value);
489                 }
490             }
491         } else if (!strcmp(node->key, "ttl")) {
492             if (!strcmp(node->value, "inherit")) {
493                 tnl_cfg.ttl_inherit = true;
494             } else {
495                 tnl_cfg.ttl = atoi(node->value);
496             }
497         } else if (!strcmp(node->key, "dst_port") && needs_dst_port) {
498             tnl_cfg.dst_port = htons(atoi(node->value));
499         } else if (!strcmp(node->key, "csum") && has_csum) {
500             if (!strcmp(node->value, "true")) {
501                 tnl_cfg.csum = true;
502             }
503         } else if (!strcmp(node->key, "df_default")) {
504             if (!strcmp(node->value, "false")) {
505                 tnl_cfg.dont_fragment = false;
506             }
507         } else if (!strcmp(node->key, "peer_cert") && tnl_cfg.ipsec) {
508             if (smap_get(args, "certificate")) {
509                 ipsec_mech_set = true;
510             } else {
511                 const char *use_ssl_cert;
512
513                 /* If the "use_ssl_cert" is true, then "certificate" and
514                  * "private_key" will be pulled from the SSL table.  The
515                  * use of this option is strongly discouraged, since it
516                  * will like be removed when multiple SSL configurations
517                  * are supported by OVS.
518                  */
519                 use_ssl_cert = smap_get(args, "use_ssl_cert");
520                 if (!use_ssl_cert || strcmp(use_ssl_cert, "true")) {
521                     VLOG_ERR("%s: 'peer_cert' requires 'certificate' argument",
522                              name);
523                     return EINVAL;
524                 }
525                 ipsec_mech_set = true;
526             }
527         } else if (!strcmp(node->key, "psk") && tnl_cfg.ipsec) {
528             ipsec_mech_set = true;
529         } else if (tnl_cfg.ipsec
530                 && (!strcmp(node->key, "certificate")
531                     || !strcmp(node->key, "private_key")
532                     || !strcmp(node->key, "use_ssl_cert"))) {
533             /* Ignore options not used by the netdev. */
534         } else if (!strcmp(node->key, "key") ||
535                    !strcmp(node->key, "in_key") ||
536                    !strcmp(node->key, "out_key")) {
537             /* Handled separately below. */
538         } else {
539             VLOG_WARN("%s: unknown %s argument '%s'", name, type, node->key);
540         }
541     }
542
543     if (tnl_cfg.ipsec) {
544         static struct ovs_mutex mutex = OVS_MUTEX_INITIALIZER;
545         static pid_t pid = 0;
546
547 #ifndef _WIN32
548         ovs_mutex_lock(&mutex);
549         if (pid <= 0) {
550             char *file_name = xasprintf("%s/%s", ovs_rundir(),
551                                         "ovs-monitor-ipsec.pid");
552             pid = read_pidfile(file_name);
553             free(file_name);
554         }
555         ovs_mutex_unlock(&mutex);
556 #endif
557
558         if (pid < 0) {
559             VLOG_ERR("%s: IPsec requires the ovs-monitor-ipsec daemon",
560                      name);
561             return EINVAL;
562         }
563
564         if (smap_get(args, "peer_cert") && smap_get(args, "psk")) {
565             VLOG_ERR("%s: cannot define both 'peer_cert' and 'psk'", name);
566             return EINVAL;
567         }
568
569         if (!ipsec_mech_set) {
570             VLOG_ERR("%s: IPsec requires an 'peer_cert' or psk' argument",
571                      name);
572             return EINVAL;
573         }
574     }
575
576     if (!tnl_cfg.ip_dst && !tnl_cfg.ip_dst_flow) {
577         VLOG_ERR("%s: %s type requires valid 'remote_ip' argument",
578                  name, type);
579         return EINVAL;
580     }
581     if (tnl_cfg.ip_src_flow && !tnl_cfg.ip_dst_flow) {
582         VLOG_ERR("%s: %s type requires 'remote_ip=flow' with 'local_ip=flow'",
583                  name, type);
584         return EINVAL;
585     }
586     if (!tnl_cfg.ttl) {
587         tnl_cfg.ttl = DEFAULT_TTL;
588     }
589
590     tnl_cfg.in_key = parse_key(args, "in_key",
591                                &tnl_cfg.in_key_present,
592                                &tnl_cfg.in_key_flow);
593
594     tnl_cfg.out_key = parse_key(args, "out_key",
595                                &tnl_cfg.out_key_present,
596                                &tnl_cfg.out_key_flow);
597
598     ovs_mutex_lock(&dev->mutex);
599     dev->tnl_cfg = tnl_cfg;
600     tunnel_check_status_change__(dev);
601     netdev_change_seq_changed(dev_);
602     ovs_mutex_unlock(&dev->mutex);
603
604     return 0;
605 }
606
607 static int
608 get_tunnel_config(const struct netdev *dev, struct smap *args)
609 {
610     struct netdev_vport *netdev = netdev_vport_cast(dev);
611     struct netdev_tunnel_config tnl_cfg;
612
613     ovs_mutex_lock(&netdev->mutex);
614     tnl_cfg = netdev->tnl_cfg;
615     ovs_mutex_unlock(&netdev->mutex);
616
617     if (tnl_cfg.ip_dst) {
618         smap_add_format(args, "remote_ip", IP_FMT, IP_ARGS(tnl_cfg.ip_dst));
619     } else if (tnl_cfg.ip_dst_flow) {
620         smap_add(args, "remote_ip", "flow");
621     }
622
623     if (tnl_cfg.ip_src) {
624         smap_add_format(args, "local_ip", IP_FMT, IP_ARGS(tnl_cfg.ip_src));
625     } else if (tnl_cfg.ip_src_flow) {
626         smap_add(args, "local_ip", "flow");
627     }
628
629     if (tnl_cfg.in_key_flow && tnl_cfg.out_key_flow) {
630         smap_add(args, "key", "flow");
631     } else if (tnl_cfg.in_key_present && tnl_cfg.out_key_present
632                && tnl_cfg.in_key == tnl_cfg.out_key) {
633         smap_add_format(args, "key", "%"PRIu64, ntohll(tnl_cfg.in_key));
634     } else {
635         if (tnl_cfg.in_key_flow) {
636             smap_add(args, "in_key", "flow");
637         } else if (tnl_cfg.in_key_present) {
638             smap_add_format(args, "in_key", "%"PRIu64,
639                             ntohll(tnl_cfg.in_key));
640         }
641
642         if (tnl_cfg.out_key_flow) {
643             smap_add(args, "out_key", "flow");
644         } else if (tnl_cfg.out_key_present) {
645             smap_add_format(args, "out_key", "%"PRIu64,
646                             ntohll(tnl_cfg.out_key));
647         }
648     }
649
650     if (tnl_cfg.ttl_inherit) {
651         smap_add(args, "ttl", "inherit");
652     } else if (tnl_cfg.ttl != DEFAULT_TTL) {
653         smap_add_format(args, "ttl", "%"PRIu8, tnl_cfg.ttl);
654     }
655
656     if (tnl_cfg.tos_inherit) {
657         smap_add(args, "tos", "inherit");
658     } else if (tnl_cfg.tos) {
659         smap_add_format(args, "tos", "0x%x", tnl_cfg.tos);
660     }
661
662     if (tnl_cfg.dst_port) {
663         uint16_t dst_port = ntohs(tnl_cfg.dst_port);
664         const char *type = netdev_get_type(dev);
665
666         if ((!strcmp("geneve", type) && dst_port != GENEVE_DST_PORT) ||
667             (!strcmp("vxlan", type) && dst_port != VXLAN_DST_PORT) ||
668             (!strcmp("lisp", type) && dst_port != LISP_DST_PORT)) {
669             smap_add_format(args, "dst_port", "%d", dst_port);
670         }
671     }
672
673     if (tnl_cfg.csum) {
674         smap_add(args, "csum", "true");
675     }
676
677     if (!tnl_cfg.dont_fragment) {
678         smap_add(args, "df_default", "false");
679     }
680
681     return 0;
682 }
683 \f
684 /* Code specific to patch ports. */
685
686 /* If 'netdev' is a patch port, returns the name of its peer as a malloc()'d
687  * string that the caller must free.
688  *
689  * If 'netdev' is not a patch port, returns NULL. */
690 char *
691 netdev_vport_patch_peer(const struct netdev *netdev_)
692 {
693     char *peer = NULL;
694
695     if (netdev_vport_is_patch(netdev_)) {
696         struct netdev_vport *netdev = netdev_vport_cast(netdev_);
697
698         ovs_mutex_lock(&netdev->mutex);
699         if (netdev->peer) {
700             peer = xstrdup(netdev->peer);
701         }
702         ovs_mutex_unlock(&netdev->mutex);
703     }
704
705     return peer;
706 }
707
708 void
709 netdev_vport_inc_rx(const struct netdev *netdev,
710                     const struct dpif_flow_stats *stats)
711 {
712     if (is_vport_class(netdev_get_class(netdev))) {
713         struct netdev_vport *dev = netdev_vport_cast(netdev);
714
715         ovs_mutex_lock(&dev->mutex);
716         dev->stats.rx_packets += stats->n_packets;
717         dev->stats.rx_bytes += stats->n_bytes;
718         ovs_mutex_unlock(&dev->mutex);
719     }
720 }
721
722 void
723 netdev_vport_inc_tx(const struct netdev *netdev,
724                     const struct dpif_flow_stats *stats)
725 {
726     if (is_vport_class(netdev_get_class(netdev))) {
727         struct netdev_vport *dev = netdev_vport_cast(netdev);
728
729         ovs_mutex_lock(&dev->mutex);
730         dev->stats.tx_packets += stats->n_packets;
731         dev->stats.tx_bytes += stats->n_bytes;
732         ovs_mutex_unlock(&dev->mutex);
733     }
734 }
735
736 static int
737 get_patch_config(const struct netdev *dev_, struct smap *args)
738 {
739     struct netdev_vport *dev = netdev_vport_cast(dev_);
740
741     ovs_mutex_lock(&dev->mutex);
742     if (dev->peer) {
743         smap_add(args, "peer", dev->peer);
744     }
745     ovs_mutex_unlock(&dev->mutex);
746
747     return 0;
748 }
749
750 static int
751 set_patch_config(struct netdev *dev_, const struct smap *args)
752 {
753     struct netdev_vport *dev = netdev_vport_cast(dev_);
754     const char *name = netdev_get_name(dev_);
755     const char *peer;
756
757     peer = smap_get(args, "peer");
758     if (!peer) {
759         VLOG_ERR("%s: patch type requires valid 'peer' argument", name);
760         return EINVAL;
761     }
762
763     if (smap_count(args) > 1) {
764         VLOG_ERR("%s: patch type takes only a 'peer' argument", name);
765         return EINVAL;
766     }
767
768     if (!strcmp(name, peer)) {
769         VLOG_ERR("%s: patch peer must not be self", name);
770         return EINVAL;
771     }
772
773     ovs_mutex_lock(&dev->mutex);
774     free(dev->peer);
775     dev->peer = xstrdup(peer);
776     netdev_change_seq_changed(dev_);
777     ovs_mutex_unlock(&dev->mutex);
778
779     return 0;
780 }
781
782 static int
783 get_stats(const struct netdev *netdev, struct netdev_stats *stats)
784 {
785     struct netdev_vport *dev = netdev_vport_cast(netdev);
786
787     ovs_mutex_lock(&dev->mutex);
788     *stats = dev->stats;
789     ovs_mutex_unlock(&dev->mutex);
790
791     return 0;
792 }
793
794 \f
795 /* Tunnel push pop ops. */
796
797 static struct ip_header *
798 ip_hdr(void *eth)
799 {
800     return (void *)((char *)eth + sizeof (struct eth_header));
801 }
802
803 static struct gre_base_hdr *
804 gre_hdr(struct ip_header *ip)
805 {
806      return (void *)((char *)ip + sizeof (struct ip_header));
807 }
808
809 static void *
810 ip_extract_tnl_md(struct ofpbuf *packet, struct flow_tnl *tnl)
811 {
812     struct ip_header *nh;
813     void *l4;
814
815     nh = ofpbuf_l3(packet);
816     l4 = ofpbuf_l4(packet);
817
818     if (!nh || !l4) {
819         return NULL;
820     }
821
822     tnl->ip_src = get_16aligned_be32(&nh->ip_src);
823     tnl->ip_dst = get_16aligned_be32(&nh->ip_dst);
824     tnl->ip_tos = nh->ip_tos;
825
826     return l4;
827 }
828
829 /* Pushes the 'size' bytes of 'header' into the headroom of 'packet',
830  * reallocating the packet if necessary.  'header' should contain an Ethernet
831  * header, followed by an IPv4 header (without options), and an L4 header.
832  *
833  * This function sets the IP header's ip_tot_len field (which should be zeroed
834  * as part of 'header') and puts its value into '*ip_tot_size' as well.  Also
835  * updates IP header checksum.
836  *
837  * Return pointer to the L4 header added to 'packet'. */
838 static void *
839 push_ip_header(struct ofpbuf *packet,
840                const void *header, int size, int *ip_tot_size)
841 {
842     struct eth_header *eth;
843     struct ip_header *ip;
844
845     eth = ofpbuf_push_uninit(packet, size);
846     *ip_tot_size = ofpbuf_size(packet) - sizeof (struct eth_header);
847
848     memcpy(eth, header, size);
849     ip = ip_hdr(eth);
850     ip->ip_tot_len = htons(*ip_tot_size);
851
852
853     ip->ip_csum = recalc_csum16(ip->ip_csum, 0, ip->ip_tot_len);
854
855     return ip + 1;
856 }
857
858 static int
859 gre_header_len(ovs_be16 flags)
860 {
861     int hlen = sizeof(struct eth_header) +
862                sizeof(struct ip_header) + 4;
863
864     if (flags & htons(GRE_CSUM)) {
865         hlen += 4;
866     }
867     if (flags & htons(GRE_KEY)) {
868         hlen += 4;
869     }
870     if (flags & htons(GRE_SEQ)) {
871         hlen += 4;
872     }
873     return hlen;
874 }
875
876 static int
877 parse_gre_header(struct ofpbuf *packet,
878                  struct flow_tnl *tnl)
879 {
880     const struct gre_base_hdr *greh;
881     ovs_16aligned_be32 *options;
882     int hlen;
883
884     greh = ip_extract_tnl_md(packet, tnl);
885     if (!greh) {
886         return -EINVAL;
887     }
888
889     if (greh->flags & ~(htons(GRE_CSUM | GRE_KEY | GRE_SEQ))) {
890         return -EINVAL;
891     }
892
893     hlen = gre_header_len(greh->flags);
894     if (hlen > ofpbuf_size(packet)) {
895         return -EINVAL;
896     }
897
898     options = (ovs_16aligned_be32 *)(greh + 1);
899     if (greh->flags & htons(GRE_CSUM)) {
900         ovs_be16 pkt_csum;
901
902         pkt_csum = csum(greh, ofpbuf_size(packet) -
903                               ((const unsigned char *)greh -
904                                (const unsigned char *)ofpbuf_l2(packet)));
905         if (pkt_csum) {
906             return -EINVAL;
907         }
908         tnl->flags = FLOW_TNL_F_CSUM;
909         options++;
910     }
911
912     if (greh->flags & htons(GRE_KEY)) {
913         tnl->tun_id = (OVS_FORCE ovs_be64) ((OVS_FORCE uint64_t)(get_16aligned_be32(options)) << 32);
914         tnl->flags |= FLOW_TNL_F_KEY;
915         options++;
916     }
917
918     if (greh->flags & htons(GRE_SEQ)) {
919         options++;
920     }
921
922     return hlen;
923 }
924
925 static void
926 reset_tnl_md(struct pkt_metadata *md)
927 {
928     memset(&md->tunnel, 0, sizeof(md->tunnel));
929 }
930
931 static void
932 gre_extract_md(struct dpif_packet *dpif_pkt)
933 {
934     struct ofpbuf *packet = &dpif_pkt->ofpbuf;
935     struct pkt_metadata *md = &dpif_pkt->md;
936     struct flow_tnl *tnl = &md->tunnel;
937     int hlen = sizeof(struct eth_header) +
938                sizeof(struct ip_header) + 4;
939
940     memset(md, 0, sizeof *md);
941     if (hlen > ofpbuf_size(packet)) {
942         return;
943     }
944
945     hlen = parse_gre_header(packet, tnl);
946     if (hlen < 0) {
947         reset_tnl_md(md);
948     }
949
950     ofpbuf_reset_packet(packet, hlen);
951 }
952
953 static int
954 netdev_gre_pop_header(struct netdev *netdev_ OVS_UNUSED,
955                       struct dpif_packet **pkt, int cnt)
956 {
957     int i;
958
959     for (i = 0; i < cnt; i++) {
960         gre_extract_md(pkt[i]);
961     }
962     return 0;
963 }
964
965 static void
966 netdev_gre_push_header__(struct ofpbuf *packet,
967                          const void *header, int size)
968 {
969     struct gre_base_hdr *greh;
970     int ip_tot_size;
971
972     greh = push_ip_header(packet, header, size,  &ip_tot_size);
973
974     if (greh->flags & htons(GRE_CSUM)) {
975         ovs_16aligned_be32 *options = (ovs_16aligned_be32 *) (greh + 1);
976
977         put_16aligned_be32(options,
978                            (OVS_FORCE ovs_be32) csum(greh, ip_tot_size - sizeof (struct ip_header)));
979     }
980 }
981
982 static int
983 netdev_gre_push_header(const struct netdev *netdev OVS_UNUSED,
984                        struct dpif_packet **packets, int cnt,
985                        const struct ovs_action_push_tnl *data)
986 {
987     int i;
988
989     for (i = 0; i < cnt; i++) {
990         netdev_gre_push_header__(&packets[i]->ofpbuf,
991                                    data->header, data->header_len);
992         packets[i]->md = PKT_METADATA_INITIALIZER(u32_to_odp(data->out_port));
993     }
994     return 0;
995 }
996
997
998 static int
999 netdev_gre_build_header(const struct netdev *netdev,
1000                         struct ovs_action_push_tnl *data)
1001 {
1002     struct netdev_vport *dev = netdev_vport_cast(netdev);
1003     struct netdev_tunnel_config *tnl_cfg;
1004     struct ip_header *ip;
1005     struct gre_base_hdr *greh;
1006     ovs_16aligned_be32 *options;
1007     int hlen;
1008
1009     /* XXX: RCUfy tnl_cfg. */
1010     ovs_mutex_lock(&dev->mutex);
1011     tnl_cfg = &dev->tnl_cfg;
1012
1013     ip = ip_hdr(data->header);
1014     ip->ip_proto = IPPROTO_GRE;
1015
1016     greh = gre_hdr(ip);
1017     greh->protocol = htons(ETH_TYPE_TEB);
1018     greh->flags = 0;
1019
1020     options = (ovs_16aligned_be32 *) (greh + 1);
1021     if (tnl_cfg->csum) {
1022         greh->flags |= htons(GRE_CSUM);
1023         put_16aligned_be32(options, 0);
1024         options++;
1025     }
1026
1027     if (tnl_cfg->out_key_present) {
1028         greh->flags |= htons(GRE_KEY);
1029         put_16aligned_be32(options, (OVS_FORCE ovs_be32)
1030                                     ((OVS_FORCE uint64_t) tnl_cfg->out_key >> 32));
1031         options++;
1032     }
1033
1034     ovs_mutex_unlock(&dev->mutex);
1035
1036     hlen = (uint8_t *) options - (uint8_t *) greh;
1037
1038     data->header_len = sizeof(struct eth_header) +
1039                        sizeof(struct ip_header)  + hlen;
1040     data->tnl_type = OVS_VPORT_TYPE_GRE;
1041     return 0;
1042 }
1043
1044 static void
1045 vxlan_extract_md(struct dpif_packet *dpif_pkt)
1046 {
1047     struct ofpbuf *packet = &dpif_pkt->ofpbuf;
1048     struct pkt_metadata *md = &dpif_pkt->md;
1049     struct flow_tnl *tnl = &md->tunnel;
1050     struct udp_header *udp;
1051     struct vxlanhdr *vxh;
1052
1053     memset(md, 0, sizeof *md);
1054     if (VXLAN_HLEN > ofpbuf_size(packet)) {
1055         return;
1056     }
1057
1058     udp = ip_extract_tnl_md(packet, tnl);
1059     if (!udp) {
1060         return;
1061     }
1062     vxh = (struct vxlanhdr *) (udp + 1);
1063
1064     if (get_16aligned_be32(&vxh->vx_flags) != htonl(VXLAN_FLAGS) ||
1065        (get_16aligned_be32(&vxh->vx_vni) & htonl(0xff))) {
1066         VLOG_WARN_RL(&err_rl, "invalid vxlan flags=%#x vni=%#x\n",
1067                      ntohl(get_16aligned_be32(&vxh->vx_flags)),
1068                      ntohl(get_16aligned_be32(&vxh->vx_vni)));
1069         reset_tnl_md(md);
1070         return;
1071     }
1072     tnl->tp_src = udp->udp_src;
1073     tnl->tp_dst = udp->udp_dst;
1074     tnl->tun_id = htonll(ntohl(get_16aligned_be32(&vxh->vx_vni)) >> 8);
1075
1076     ofpbuf_reset_packet(packet, VXLAN_HLEN);
1077 }
1078
1079 static int
1080 netdev_vxlan_pop_header(struct netdev *netdev_ OVS_UNUSED,
1081                         struct dpif_packet **pkt, int cnt)
1082 {
1083     int i;
1084
1085     for (i = 0; i < cnt; i++) {
1086         vxlan_extract_md(pkt[i]);
1087     }
1088     return 0;
1089 }
1090
1091 static int
1092 netdev_vxlan_build_header(const struct netdev *netdev,
1093                           struct ovs_action_push_tnl *data)
1094 {
1095     struct netdev_vport *dev = netdev_vport_cast(netdev);
1096     struct netdev_tunnel_config *tnl_cfg;
1097     struct ip_header *ip;
1098     struct udp_header *udp;
1099     struct vxlanhdr *vxh;
1100
1101     /* XXX: RCUfy tnl_cfg. */
1102     ovs_mutex_lock(&dev->mutex);
1103     tnl_cfg = &dev->tnl_cfg;
1104
1105     ip = ip_hdr(data->header);
1106     ip->ip_proto = IPPROTO_UDP;
1107
1108     udp = (struct udp_header *) (ip + 1);
1109     udp->udp_dst = tnl_cfg->dst_port;
1110
1111     vxh = (struct vxlanhdr *) (udp + 1);
1112     put_16aligned_be32(&vxh->vx_flags, htonl(VXLAN_FLAGS));
1113     put_16aligned_be32(&vxh->vx_vni, htonl(ntohll(tnl_cfg->out_key) << 8));
1114
1115     ovs_mutex_unlock(&dev->mutex);
1116     data->header_len = VXLAN_HLEN;
1117     data->tnl_type = OVS_VPORT_TYPE_VXLAN;
1118     return 0;
1119 }
1120
1121 static ovs_be16
1122 get_src_port(struct dpif_packet *packet)
1123 {
1124     uint32_t hash;
1125
1126     hash = dpif_packet_get_dp_hash(packet);
1127
1128     return htons((((uint64_t) hash * (tnl_udp_port_max - tnl_udp_port_min)) >> 32) +
1129                  tnl_udp_port_min);
1130 }
1131
1132 static void
1133 netdev_vxlan_push_header__(struct dpif_packet *packet,
1134                            const void *header, int size)
1135 {
1136     struct udp_header *udp;
1137     int ip_tot_size;
1138
1139     udp = push_ip_header(&packet->ofpbuf, header, size, &ip_tot_size);
1140
1141     /* set udp src port */
1142     udp->udp_src = get_src_port(packet);
1143     udp->udp_len = htons(ip_tot_size - sizeof (struct ip_header));
1144     /* udp_csum is zero */
1145 }
1146
1147 static int
1148 netdev_vxlan_push_header(const struct netdev *netdev OVS_UNUSED,
1149                          struct dpif_packet **packets, int cnt,
1150                          const struct ovs_action_push_tnl *data)
1151 {
1152     int i;
1153
1154     for (i = 0; i < cnt; i++) {
1155         netdev_vxlan_push_header__(packets[i],
1156                                    data->header, VXLAN_HLEN);
1157         packets[i]->md = PKT_METADATA_INITIALIZER(u32_to_odp(data->out_port));
1158     }
1159     return 0;
1160 }
1161
1162 static void
1163 netdev_vport_range(struct unixctl_conn *conn, int argc,
1164                    const char *argv[], void *aux OVS_UNUSED)
1165 {
1166     int val1, val2;
1167
1168     if (argc < 3) {
1169         struct ds ds = DS_EMPTY_INITIALIZER;
1170
1171         ds_put_format(&ds, "Tunnel UDP source port range: %"PRIu16"-%"PRIu16"\n",
1172                             tnl_udp_port_min, tnl_udp_port_max);
1173
1174         unixctl_command_reply(conn, ds_cstr(&ds));
1175         ds_destroy(&ds);
1176         return;
1177     }
1178
1179     if (argc != 3) {
1180         return;
1181     }
1182
1183     val1 = atoi(argv[1]);
1184     if (val1 <= 0 || val1 > UINT16_MAX) {
1185         unixctl_command_reply(conn, "Invalid min.");
1186         return;
1187     }
1188     val2 = atoi(argv[2]);
1189     if (val2 <= 0 || val2 > UINT16_MAX) {
1190         unixctl_command_reply(conn, "Invalid max.");
1191         return;
1192     }
1193
1194     if (val1 > val2) {
1195         tnl_udp_port_min = val2;
1196         tnl_udp_port_max = val1;
1197     } else {
1198         tnl_udp_port_min = val1;
1199         tnl_udp_port_max = val2;
1200     }
1201     seq_change(tnl_conf_seq);
1202
1203     unixctl_command_reply(conn, "OK");
1204 }
1205
1206 \f
1207 #define VPORT_FUNCTIONS(GET_CONFIG, SET_CONFIG,             \
1208                         GET_TUNNEL_CONFIG, GET_STATUS,      \
1209                         BUILD_HEADER,                       \
1210                         PUSH_HEADER, POP_HEADER)            \
1211     NULL,                                                   \
1212     netdev_vport_run,                                       \
1213     netdev_vport_wait,                                      \
1214                                                             \
1215     netdev_vport_alloc,                                     \
1216     netdev_vport_construct,                                 \
1217     netdev_vport_destruct,                                  \
1218     netdev_vport_dealloc,                                   \
1219     GET_CONFIG,                                             \
1220     SET_CONFIG,                                             \
1221     GET_TUNNEL_CONFIG,                                      \
1222     BUILD_HEADER,                                           \
1223     PUSH_HEADER,                                            \
1224     POP_HEADER,                                             \
1225     NULL,                       /* get_numa_id */           \
1226     NULL,                       /* set_multiq */            \
1227                                                             \
1228     NULL,                       /* send */                  \
1229     NULL,                       /* send_wait */             \
1230                                                             \
1231     netdev_vport_set_etheraddr,                             \
1232     netdev_vport_get_etheraddr,                             \
1233     NULL,                       /* get_mtu */               \
1234     NULL,                       /* set_mtu */               \
1235     NULL,                       /* get_ifindex */           \
1236     NULL,                       /* get_carrier */           \
1237     NULL,                       /* get_carrier_resets */    \
1238     NULL,                       /* get_miimon */            \
1239     get_stats,                                              \
1240                                                             \
1241     NULL,                       /* get_features */          \
1242     NULL,                       /* set_advertisements */    \
1243                                                             \
1244     NULL,                       /* set_policing */          \
1245     NULL,                       /* get_qos_types */         \
1246     NULL,                       /* get_qos_capabilities */  \
1247     NULL,                       /* get_qos */               \
1248     NULL,                       /* set_qos */               \
1249     NULL,                       /* get_queue */             \
1250     NULL,                       /* set_queue */             \
1251     NULL,                       /* delete_queue */          \
1252     NULL,                       /* get_queue_stats */       \
1253     NULL,                       /* queue_dump_start */      \
1254     NULL,                       /* queue_dump_next */       \
1255     NULL,                       /* queue_dump_done */       \
1256     NULL,                       /* dump_queue_stats */      \
1257                                                             \
1258     NULL,                       /* get_in4 */               \
1259     NULL,                       /* set_in4 */               \
1260     NULL,                       /* get_in6 */               \
1261     NULL,                       /* add_router */            \
1262     NULL,                       /* get_next_hop */          \
1263     GET_STATUS,                                             \
1264     NULL,                       /* arp_lookup */            \
1265                                                             \
1266     netdev_vport_update_flags,                              \
1267                                                             \
1268     NULL,                   /* rx_alloc */                  \
1269     NULL,                   /* rx_construct */              \
1270     NULL,                   /* rx_destruct */               \
1271     NULL,                   /* rx_dealloc */                \
1272     NULL,                   /* rx_recv */                   \
1273     NULL,                   /* rx_wait */                   \
1274     NULL,                   /* rx_drain */
1275
1276
1277 #define TUNNEL_CLASS(NAME, DPIF_PORT, BUILD_HEADER, PUSH_HEADER, POP_HEADER)   \
1278     { DPIF_PORT,                                                               \
1279         { NAME, VPORT_FUNCTIONS(get_tunnel_config,                             \
1280                                 set_tunnel_config,                             \
1281                                 get_netdev_tunnel_config,                      \
1282                                 tunnel_get_status,                             \
1283                                 BUILD_HEADER, PUSH_HEADER, POP_HEADER) }}
1284
1285 void
1286 netdev_vport_tunnel_register(void)
1287 {
1288     /* The name of the dpif_port should be short enough to accomodate adding
1289      * a port number to the end if one is necessary. */
1290     static const struct vport_class vport_classes[] = {
1291         TUNNEL_CLASS("geneve", "genev_sys", NULL, NULL, NULL),
1292         TUNNEL_CLASS("gre", "gre_sys", netdev_gre_build_header,
1293                                        netdev_gre_push_header,
1294                                        netdev_gre_pop_header),
1295         TUNNEL_CLASS("ipsec_gre", "gre_sys", NULL, NULL, NULL),
1296         TUNNEL_CLASS("gre64", "gre64_sys", NULL,  NULL, NULL),
1297         TUNNEL_CLASS("ipsec_gre64", "gre64_sys", NULL, NULL, NULL),
1298         TUNNEL_CLASS("vxlan", "vxlan_sys", netdev_vxlan_build_header,
1299                                            netdev_vxlan_push_header,
1300                                            netdev_vxlan_pop_header),
1301         TUNNEL_CLASS("lisp", "lisp_sys", NULL, NULL, NULL)
1302     };
1303     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
1304
1305     if (ovsthread_once_start(&once)) {
1306         int i;
1307
1308         for (i = 0; i < ARRAY_SIZE(vport_classes); i++) {
1309             netdev_register_provider(&vport_classes[i].netdev_class);
1310         }
1311
1312         unixctl_command_register("tnl/egress_port_range", "min max", 0, 2,
1313                                  netdev_vport_range, NULL);
1314
1315         ovsthread_once_done(&once);
1316     }
1317 }
1318
1319 void
1320 netdev_vport_patch_register(void)
1321 {
1322     static const struct vport_class patch_class =
1323         { NULL,
1324             { "patch", VPORT_FUNCTIONS(get_patch_config,
1325                                        set_patch_config,
1326                                        NULL,
1327                                        NULL, NULL, NULL, NULL) }};
1328     netdev_register_provider(&patch_class.netdev_class);
1329 }