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