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