bfd: Optimize BFD for Megaflows.
[sliver-openvswitch.git] / lib / bfd.c
1 /* Copyright (c) 2013 Nicira, Inc.
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License. */
14
15 #include <config.h>
16 #include "bfd.h"
17
18 #include <arpa/inet.h>
19 #include <netinet/ip.h>
20
21 #include "byte-order.h"
22 #include "csum.h"
23 #include "dpif.h"
24 #include "dynamic-string.h"
25 #include "flow.h"
26 #include "hash.h"
27 #include "hmap.h"
28 #include "list.h"
29 #include "netlink.h"
30 #include "odp-util.h"
31 #include "ofpbuf.h"
32 #include "ovs-thread.h"
33 #include "openvswitch/types.h"
34 #include "packets.h"
35 #include "poll-loop.h"
36 #include "random.h"
37 #include "smap.h"
38 #include "timeval.h"
39 #include "unixctl.h"
40 #include "util.h"
41 #include "vlog.h"
42
43 VLOG_DEFINE_THIS_MODULE(bfd);
44
45 /* XXX Finish BFD.
46  *
47  * The goal of this module is to replace CFM with something both more flexible
48  * and standards compliant.  In service of this goal, the following needs to be
49  * done.
50  *
51  * - Compliance
52  *   * Implement Demand mode.
53  *   * Go through the RFC line by line and verify we comply.
54  *   * Test against a hardware implementation.  Preferably a popular one.
55  *   * Delete BFD packets with nw_ttl != 255 in the datapath to prevent DOS
56  *     attacks.
57  *
58  * - Unit tests.
59  *
60  * - Set TOS/PCP on the outer tunnel header when encapped.
61  *
62  * - Sending BFD messages should be in its own thread/process.
63  *
64  * - Scale testing.  How does it operate when there are large number of bfd
65  *   sessions?  Do we ever have random flaps?  What's the CPU utilization?
66  *
67  * - Rely on data traffic for liveness by using BFD demand mode.
68  *   If we're receiving traffic on a port, we can safely assume it's up (modulo
69  *   unidrectional failures).  BFD has a demand mode in which it can stay quiet
70  *   unless it feels the need to check the status of the port.  Using this, we
71  *   can implement a strategy in which BFD only sends control messages on dark
72  *   interfaces.
73  *
74  * - Depending on how one interprets the spec, it appears that a BFD session
75  *   can never change bfd.LocalDiag to "No Diagnostic".  We should verify that
76  *   this is what hardware implementations actually do.  Seems like "No
77  *   Diagnostic" should be set once a BFD session state goes UP. */
78
79 #define BFD_VERSION 1
80
81 enum flags {
82     FLAG_MULTIPOINT = 1 << 0,
83     FLAG_DEMAND = 1 << 1,
84     FLAG_AUTH = 1 << 2,
85     FLAG_CTL = 1 << 3,
86     FLAG_FINAL = 1 << 4,
87     FLAG_POLL = 1 << 5
88 };
89
90 enum state {
91     STATE_ADMIN_DOWN = 0 << 6,
92     STATE_DOWN = 1 << 6,
93     STATE_INIT = 2 << 6,
94     STATE_UP = 3 << 6
95 };
96
97 enum diag {
98     DIAG_NONE = 0,                /* No Diagnostic. */
99     DIAG_EXPIRED = 1,             /* Control Detection Time Expired. */
100     DIAG_ECHO_FAILED = 2,         /* Echo Function Failed. */
101     DIAG_RMT_DOWN = 3,            /* Neighbor Signaled Session Down. */
102     DIAG_FWD_RESET = 4,           /* Forwarding Plane Reset. */
103     DIAG_PATH_DOWN = 5,           /* Path Down. */
104     DIAG_CPATH_DOWN = 6,          /* Concatenated Path Down. */
105     DIAG_ADMIN_DOWN = 7,          /* Administratively Down. */
106     DIAG_RCPATH_DOWN = 8          /* Reverse Concatenated Path Down. */
107 };
108
109 /* RFC 5880 Section 4.1
110  *  0                   1                   2                   3
111  *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
112  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
113  * |Vers |  Diag   |Sta|P|F|C|A|D|M|  Detect Mult  |    Length     |
114  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
115  * |                       My Discriminator                        |
116  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
117  * |                      Your Discriminator                       |
118  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
119  * |                    Desired Min TX Interval                    |
120  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
121  * |                   Required Min RX Interval                    |
122  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
123  * |                 Required Min Echo RX Interval                 |
124  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
125 struct msg {
126     uint8_t vers_diag;    /* Version and diagnostic. */
127     uint8_t flags;        /* 2bit State field followed by flags. */
128     uint8_t mult;         /* Fault detection multiplier. */
129     uint8_t length;       /* Length of this BFD message. */
130     ovs_be32 my_disc;     /* My discriminator. */
131     ovs_be32 your_disc;   /* Your discriminator. */
132     ovs_be32 min_tx;      /* Desired minimum tx interval. */
133     ovs_be32 min_rx;      /* Required minimum rx interval. */
134     ovs_be32 min_rx_echo; /* Required minimum echo rx interval. */
135 };
136 BUILD_ASSERT_DECL(BFD_PACKET_LEN == sizeof(struct msg));
137
138 #define DIAG_MASK 0x1f
139 #define VERS_SHIFT 5
140 #define STATE_MASK 0xC0
141 #define FLAGS_MASK 0x3f
142
143 struct bfd {
144     struct hmap_node node;        /* In 'all_bfds'. */
145     uint32_t disc;                /* bfd.LocalDiscr. Key in 'all_bfds' hmap. */
146
147     char *name;                   /* Name used for logging. */
148
149     bool cpath_down;              /* Concatenated Path Down. */
150     uint8_t mult;                 /* bfd.DetectMult. */
151
152     enum state state;             /* bfd.SessionState. */
153     enum state rmt_state;         /* bfd.RemoteSessionState. */
154
155     enum diag diag;               /* bfd.LocalDiag. */
156     enum diag rmt_diag;           /* Remote diagnostic. */
157
158     enum flags flags;             /* Flags sent on messages. */
159     enum flags rmt_flags;         /* Flags last received. */
160
161     uint32_t rmt_disc;            /* bfd.RemoteDiscr. */
162
163     uint8_t eth_dst[ETH_ADDR_LEN];/* Ethernet destination address. */
164     bool eth_dst_set;             /* 'eth_dst' set through database. */
165
166     uint16_t udp_src;             /* UDP source port. */
167
168     /* All timers in milliseconds. */
169     long long int rmt_min_rx;     /* bfd.RemoteMinRxInterval. */
170     long long int rmt_min_tx;     /* Remote minimum TX interval. */
171
172     long long int cfg_min_tx;     /* Configured minimum TX rate. */
173     long long int cfg_min_rx;     /* Configured required minimum RX rate. */
174     long long int poll_min_tx;    /* Min TX negotating in a poll sequence. */
175     long long int poll_min_rx;    /* Min RX negotating in a poll sequence. */
176     long long int min_tx;         /* bfd.DesiredMinTxInterval. */
177     long long int min_rx;         /* bfd.RequiredMinRxInterval. */
178
179     long long int last_tx;        /* Last TX time. */
180     long long int next_tx;        /* Next TX time. */
181     long long int detect_time;    /* RFC 5880 6.8.4 Detection time. */
182
183     int forwarding_override;      /* Manual override of 'forwarding' status. */
184
185     atomic_bool check_tnl_key;    /* Verify tunnel key of inbound packets? */
186     atomic_int ref_cnt;
187 };
188
189 static struct ovs_mutex mutex = OVS_MUTEX_INITIALIZER;
190 static struct hmap all_bfds__ = HMAP_INITIALIZER(&all_bfds__);
191 static struct hmap *const all_bfds OVS_GUARDED_BY(mutex) = &all_bfds__;
192
193 static bool bfd_forwarding__(const struct bfd *) OVS_REQ_WRLOCK(mutex);
194 static bool bfd_in_poll(const struct bfd *) OVS_REQ_WRLOCK(&mutex);
195 static void bfd_poll(struct bfd *bfd) OVS_REQ_WRLOCK(&mutex);
196 static const char *bfd_diag_str(enum diag) OVS_REQ_WRLOCK(&mutex);
197 static const char *bfd_state_str(enum state) OVS_REQ_WRLOCK(&mutex);
198 static long long int bfd_min_tx(const struct bfd *) OVS_REQ_WRLOCK(&mutex);
199 static long long int bfd_tx_interval(const struct bfd *)
200     OVS_REQ_WRLOCK(&mutex);
201 static long long int bfd_rx_interval(const struct bfd *)
202     OVS_REQ_WRLOCK(&mutex);
203 static void bfd_set_next_tx(struct bfd *) OVS_REQ_WRLOCK(&mutex);
204 static void bfd_set_state(struct bfd *, enum state, enum diag)
205     OVS_REQ_WRLOCK(&mutex);
206 static uint32_t generate_discriminator(void) OVS_REQ_WRLOCK(&mutex);
207 static void bfd_put_details(struct ds *, const struct bfd *)
208     OVS_REQ_WRLOCK(&mutex);
209 static void bfd_unixctl_show(struct unixctl_conn *, int argc,
210                              const char *argv[], void *aux OVS_UNUSED);
211 static void bfd_unixctl_set_forwarding_override(struct unixctl_conn *,
212                                                 int argc, const char *argv[],
213                                                 void *aux OVS_UNUSED);
214 static void log_msg(enum vlog_level, const struct msg *, const char *message,
215                     const struct bfd *) OVS_REQ_WRLOCK(&mutex);
216
217 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(20, 20);
218
219 /* Returns true if the interface on which 'bfd' is running may be used to
220  * forward traffic according to the BFD session state. */
221 bool
222 bfd_forwarding(const struct bfd *bfd) OVS_EXCLUDED(mutex)
223 {
224     bool ret;
225
226     ovs_mutex_lock(&mutex);
227     ret = bfd_forwarding__(bfd);
228     ovs_mutex_unlock(&mutex);
229     return ret;
230 }
231
232 /* Returns a 'smap' of key value pairs representing the status of 'bfd'
233  * intended for the OVS database. */
234 void
235 bfd_get_status(const struct bfd *bfd, struct smap *smap)
236     OVS_EXCLUDED(mutex)
237 {
238     ovs_mutex_lock(&mutex);
239     smap_add(smap, "forwarding", bfd_forwarding__(bfd)? "true" : "false");
240     smap_add(smap, "state", bfd_state_str(bfd->state));
241     smap_add(smap, "diagnostic", bfd_diag_str(bfd->diag));
242
243     if (bfd->state != STATE_DOWN) {
244         smap_add(smap, "remote_state", bfd_state_str(bfd->rmt_state));
245         smap_add(smap, "remote_diagnostic", bfd_diag_str(bfd->rmt_diag));
246     }
247     ovs_mutex_unlock(&mutex);
248 }
249
250 /* Initializes, destroys, or reconfigures the BFD session 'bfd' (named 'name'),
251  * according to the database configuration contained in 'cfg'.  Takes ownership
252  * of 'bfd', which may be NULL.  Returns a BFD object which may be used as a
253  * handle for the session, or NULL if BFD is not enabled according to 'cfg'.
254  * Also returns NULL if cfg is NULL. */
255 struct bfd *
256 bfd_configure(struct bfd *bfd, const char *name, const struct smap *cfg)
257     OVS_EXCLUDED(mutex)
258 {
259     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
260     static atomic_uint16_t udp_src = ATOMIC_VAR_INIT(0);
261
262     long long int min_tx, min_rx;
263     bool cpath_down;
264     const char *hwaddr;
265     uint8_t ea[ETH_ADDR_LEN];
266
267     if (ovsthread_once_start(&once)) {
268         unixctl_command_register("bfd/show", "[interface]", 0, 1,
269                                  bfd_unixctl_show, NULL);
270         unixctl_command_register("bfd/set-forwarding",
271                                  "[interface] normal|false|true", 1, 2,
272                                  bfd_unixctl_set_forwarding_override, NULL);
273         ovsthread_once_done(&once);
274     }
275
276     if (!cfg || !smap_get_bool(cfg, "enable", false)) {
277         bfd_unref(bfd);
278         return NULL;
279     }
280
281     ovs_mutex_lock(&mutex);
282     if (!bfd) {
283         bfd = xzalloc(sizeof *bfd);
284         bfd->name = xstrdup(name);
285         bfd->forwarding_override = -1;
286         bfd->disc = generate_discriminator();
287         hmap_insert(all_bfds, &bfd->node, bfd->disc);
288
289         bfd->diag = DIAG_NONE;
290         bfd->min_tx = 1000;
291         bfd->mult = 3;
292         atomic_init(&bfd->ref_cnt, 1);
293
294         /* RFC 5881 section 4
295          * The source port MUST be in the range 49152 through 65535.  The same
296          * UDP source port number MUST be used for all BFD Control packets
297          * associated with a particular session.  The source port number SHOULD
298          * be unique among all BFD sessions on the system. */
299         atomic_add(&udp_src, 1, &bfd->udp_src);
300         bfd->udp_src = (bfd->udp_src % 16384) + 49152;
301
302         bfd_set_state(bfd, STATE_DOWN, DIAG_NONE);
303
304         memcpy(bfd->eth_dst, eth_addr_bfd, ETH_ADDR_LEN);
305     }
306
307     atomic_store(&bfd->check_tnl_key,
308                  smap_get_bool(cfg, "check_tnl_key", false));
309     min_tx = smap_get_int(cfg, "min_tx", 100);
310     min_tx = MAX(min_tx, 100);
311     if (bfd->cfg_min_tx != min_tx) {
312         bfd->cfg_min_tx = min_tx;
313         if (bfd->state != STATE_UP
314             || (!bfd_in_poll(bfd) && bfd->cfg_min_tx < bfd->min_tx)) {
315             bfd->min_tx = bfd->cfg_min_tx;
316         }
317         bfd_poll(bfd);
318     }
319
320     min_rx = smap_get_int(cfg, "min_rx", 1000);
321     min_rx = MAX(min_rx, 100);
322     if (bfd->cfg_min_rx != min_rx) {
323         bfd->cfg_min_rx = min_rx;
324         if (bfd->state != STATE_UP
325             || (!bfd_in_poll(bfd) && bfd->cfg_min_rx > bfd->min_rx)) {
326             bfd->min_rx = bfd->cfg_min_rx;
327         }
328         bfd_poll(bfd);
329     }
330
331     cpath_down = smap_get_bool(cfg, "cpath_down", false);
332     if (bfd->cpath_down != cpath_down) {
333         bfd->cpath_down = cpath_down;
334         if (bfd->diag == DIAG_NONE || bfd->diag == DIAG_CPATH_DOWN) {
335             bfd_set_state(bfd, bfd->state, DIAG_NONE);
336         }
337         bfd_poll(bfd);
338     }
339
340     hwaddr = smap_get(cfg, "bfd_dst_mac");
341     if (hwaddr && eth_addr_from_string(hwaddr, ea) && !eth_addr_is_zero(ea)) {
342         memcpy(bfd->eth_dst, ea, ETH_ADDR_LEN);
343         bfd->eth_dst_set = true;
344     } else if (bfd->eth_dst_set) {
345         memcpy(bfd->eth_dst, eth_addr_bfd, ETH_ADDR_LEN);
346         bfd->eth_dst_set = false;
347     }
348
349     ovs_mutex_unlock(&mutex);
350     return bfd;
351 }
352
353 struct bfd *
354 bfd_ref(const struct bfd *bfd_)
355 {
356     struct bfd *bfd = CONST_CAST(struct bfd *, bfd_);
357     if (bfd) {
358         int orig;
359         atomic_add(&bfd->ref_cnt, 1, &orig);
360         ovs_assert(orig > 0);
361     }
362     return bfd;
363 }
364
365 void
366 bfd_unref(struct bfd *bfd) OVS_EXCLUDED(mutex)
367 {
368     if (bfd) {
369         int orig;
370
371         atomic_sub(&bfd->ref_cnt, 1, &orig);
372         ovs_assert(orig > 0);
373         if (orig == 1) {
374             ovs_mutex_lock(&mutex);
375             hmap_remove(all_bfds, &bfd->node);
376             free(bfd->name);
377             free(bfd);
378             ovs_mutex_unlock(&mutex);
379         }
380     }
381 }
382
383 void
384 bfd_wait(const struct bfd *bfd) OVS_EXCLUDED(mutex)
385 {
386     ovs_mutex_lock(&mutex);
387     if (bfd->flags & FLAG_FINAL) {
388         poll_immediate_wake();
389     }
390
391     poll_timer_wait_until(bfd->next_tx);
392     if (bfd->state > STATE_DOWN) {
393         poll_timer_wait_until(bfd->detect_time);
394     }
395     ovs_mutex_unlock(&mutex);
396 }
397
398 void
399 bfd_run(struct bfd *bfd) OVS_EXCLUDED(mutex)
400 {
401     ovs_mutex_lock(&mutex);
402     if (bfd->state > STATE_DOWN && time_msec() >= bfd->detect_time) {
403         bfd_set_state(bfd, STATE_DOWN, DIAG_EXPIRED);
404     }
405
406     if (bfd->min_tx != bfd->cfg_min_tx || bfd->min_rx != bfd->cfg_min_rx) {
407         bfd_poll(bfd);
408     }
409     ovs_mutex_unlock(&mutex);
410 }
411
412 bool
413 bfd_should_send_packet(const struct bfd *bfd) OVS_EXCLUDED(mutex)
414 {
415     bool ret;
416     ovs_mutex_lock(&mutex);
417     ret = bfd->flags & FLAG_FINAL || time_msec() >= bfd->next_tx;
418     ovs_mutex_unlock(&mutex);
419     return ret;
420 }
421
422 void
423 bfd_put_packet(struct bfd *bfd, struct ofpbuf *p,
424                uint8_t eth_src[ETH_ADDR_LEN]) OVS_EXCLUDED(mutex)
425 {
426     long long int min_tx, min_rx;
427     struct udp_header *udp;
428     struct eth_header *eth;
429     struct ip_header *ip;
430     struct msg *msg;
431
432     ovs_mutex_lock(&mutex);
433     if (bfd->next_tx) {
434         long long int delay = time_msec() - bfd->next_tx;
435         long long int interval = bfd_tx_interval(bfd);
436         if (delay > interval * 3 / 2) {
437             VLOG_INFO("%s: long delay of %lldms (expected %lldms) sending BFD"
438                       " control message", bfd->name, delay, interval);
439         }
440     }
441
442     /* RFC 5880 Section 6.5
443      * A BFD Control packet MUST NOT have both the Poll (P) and Final (F) bits
444      * set. */
445     ovs_assert(!(bfd->flags & FLAG_POLL) || !(bfd->flags & FLAG_FINAL));
446
447     ofpbuf_reserve(p, 2); /* Properly align after the ethernet header. */
448     eth = ofpbuf_put_uninit(p, sizeof *eth);
449     memcpy(eth->eth_src, eth_src, ETH_ADDR_LEN);
450     memcpy(eth->eth_dst, bfd->eth_dst, ETH_ADDR_LEN);
451     eth->eth_type = htons(ETH_TYPE_IP);
452
453     ip = ofpbuf_put_zeros(p, sizeof *ip);
454     ip->ip_ihl_ver = IP_IHL_VER(5, 4);
455     ip->ip_tot_len = htons(sizeof *ip + sizeof *udp + sizeof *msg);
456     ip->ip_ttl = MAXTTL;
457     ip->ip_tos = IPTOS_LOWDELAY | IPTOS_THROUGHPUT;
458     ip->ip_proto = IPPROTO_UDP;
459     ip->ip_src = htonl(0xA9FE0100); /* 169.254.1.0 Link Local. */
460     ip->ip_dst = htonl(0xA9FE0101); /* 169.254.1.1 Link Local. */
461     ip->ip_csum = csum(ip, sizeof *ip);
462
463     udp = ofpbuf_put_zeros(p, sizeof *udp);
464     udp->udp_src = htons(bfd->udp_src);
465     udp->udp_dst = htons(BFD_DEST_PORT);
466     udp->udp_len = htons(sizeof *udp + sizeof *msg);
467
468     msg = ofpbuf_put_uninit(p, sizeof *msg);
469     msg->vers_diag = (BFD_VERSION << 5) | bfd->diag;
470     msg->flags = (bfd->state & STATE_MASK) | bfd->flags;
471
472     msg->mult = bfd->mult;
473     msg->length = BFD_PACKET_LEN;
474     msg->my_disc = htonl(bfd->disc);
475     msg->your_disc = htonl(bfd->rmt_disc);
476     msg->min_rx_echo = htonl(0);
477
478     if (bfd_in_poll(bfd)) {
479         min_tx = bfd->poll_min_tx;
480         min_rx = bfd->poll_min_rx;
481     } else {
482         min_tx = bfd_min_tx(bfd);
483         min_rx = bfd->min_rx;
484     }
485
486     msg->min_tx = htonl(min_tx * 1000);
487     msg->min_rx = htonl(min_rx * 1000);
488
489     bfd->flags &= ~FLAG_FINAL;
490
491     log_msg(VLL_DBG, msg, "Sending BFD Message", bfd);
492
493     bfd->last_tx = time_msec();
494     bfd_set_next_tx(bfd);
495     ovs_mutex_unlock(&mutex);
496 }
497
498 bool
499 bfd_should_process_flow(const struct bfd *bfd, const struct flow *flow,
500                         struct flow_wildcards *wc)
501 {
502     bool check_tnl_key;
503     memset(&wc->masks.dl_dst, 0xff, sizeof wc->masks.dl_dst);
504     if (bfd->eth_dst_set && memcmp(bfd->eth_dst, flow->dl_dst, ETH_ADDR_LEN)) {
505         return false;
506     }
507
508     memset(&wc->masks.nw_proto, 0xff, sizeof wc->masks.nw_proto);
509     memset(&wc->masks.tp_dst, 0xff, sizeof wc->masks.tp_dst);
510
511     atomic_read(&bfd->check_tnl_key, &check_tnl_key);
512     if (check_tnl_key) {
513         memset(&wc->masks.tunnel.tun_id, 0xff, sizeof wc->masks.tunnel.tun_id);
514     }
515     return (flow->dl_type == htons(ETH_TYPE_IP)
516             && flow->nw_proto == IPPROTO_UDP
517             && flow->tp_dst == htons(BFD_DEST_PORT)
518             && (check_tnl_key || flow->tunnel.tun_id == htonll(0)));
519 }
520
521 void
522 bfd_process_packet(struct bfd *bfd, const struct flow *flow,
523                    const struct ofpbuf *p) OVS_EXCLUDED(mutex)
524 {
525     uint32_t rmt_min_rx, pkt_your_disc;
526     enum state rmt_state;
527     enum flags flags;
528     uint8_t version;
529     struct msg *msg;
530
531     /* This function is designed to follow section RFC 5880 6.8.6 closely. */
532
533     ovs_mutex_lock(&mutex);
534     if (flow->nw_ttl != 255) {
535         /* XXX Should drop in the kernel to prevent DOS. */
536         goto out;
537     }
538
539     msg = ofpbuf_at(p, (uint8_t *)p->l7 - (uint8_t *)p->data, BFD_PACKET_LEN);
540     if (!msg) {
541         VLOG_INFO_RL(&rl, "%s: Received unparseable BFD control message.",
542                      bfd->name);
543         goto out;
544     }
545
546     /* RFC 5880 Section 6.8.6
547      * If the Length field is greater than the payload of the encapsulating
548      * protocol, the packet MUST be discarded.
549      *
550      * Note that we make this check implicity.  Above we use ofpbuf_at() to
551      * ensure that there are at least BFD_PACKET_LEN bytes in the payload of
552      * the encapsulating protocol.  Below we require msg->length to be exactly
553      * BFD_PACKET_LEN bytes. */
554
555     flags = msg->flags & FLAGS_MASK;
556     rmt_state = msg->flags & STATE_MASK;
557     version = msg->vers_diag >> VERS_SHIFT;
558
559     log_msg(VLL_DBG, msg, "Received BFD control message", bfd);
560
561     if (version != BFD_VERSION) {
562         log_msg(VLL_WARN, msg, "Incorrect version", bfd);
563         goto out;
564     }
565
566     /* Technically this should happen after the length check. We don't support
567      * authentication however, so it's simpler to do the check first. */
568     if (flags & FLAG_AUTH) {
569         log_msg(VLL_WARN, msg, "Authenticated control message with"
570                    " authentication disabled", bfd);
571         goto out;
572     }
573
574     if (msg->length != BFD_PACKET_LEN) {
575         log_msg(VLL_WARN, msg, "Unexpected length", bfd);
576         if (msg->length < BFD_PACKET_LEN) {
577             goto out;
578         }
579     }
580
581     if (!msg->mult) {
582         log_msg(VLL_WARN, msg, "Zero multiplier", bfd);
583         goto out;
584     }
585
586     if (flags & FLAG_MULTIPOINT) {
587         log_msg(VLL_WARN, msg, "Unsupported multipoint flag", bfd);
588         goto out;
589     }
590
591     if (!msg->my_disc) {
592         log_msg(VLL_WARN, msg, "NULL my_disc", bfd);
593         goto out;
594     }
595
596     pkt_your_disc = ntohl(msg->your_disc);
597     if (pkt_your_disc) {
598         /* Technically, we should use the your discriminator field to figure
599          * out which 'struct bfd' this packet is destined towards.  That way a
600          * bfd session could migrate from one interface to another
601          * transparently.  This doesn't fit in with the OVS structure very
602          * well, so in this respect, we are not compliant. */
603        if (pkt_your_disc != bfd->disc) {
604            log_msg(VLL_WARN, msg, "Incorrect your_disc", bfd);
605            goto out;
606        }
607     } else if (rmt_state > STATE_DOWN) {
608         log_msg(VLL_WARN, msg, "Null your_disc", bfd);
609         goto out;
610     }
611
612     bfd->rmt_disc = ntohl(msg->my_disc);
613     bfd->rmt_state = rmt_state;
614     bfd->rmt_flags = flags;
615     bfd->rmt_diag = msg->vers_diag & DIAG_MASK;
616
617     if (flags & FLAG_FINAL && bfd_in_poll(bfd)) {
618         bfd->min_tx = bfd->poll_min_tx;
619         bfd->min_rx = bfd->poll_min_rx;
620         bfd->flags &= ~FLAG_POLL;
621         log_msg(VLL_INFO, msg, "Poll sequence terminated", bfd);
622     }
623
624     if (flags & FLAG_POLL) {
625         /* RFC 5880 Section 6.5
626          * When the other system receives a Poll, it immediately transmits a
627          * BFD Control packet with the Final (F) bit set, independent of any
628          * periodic BFD Control packets it may be sending
629          * (see section 6.8.7). */
630         bfd->flags &= ~FLAG_POLL;
631         bfd->flags |= FLAG_FINAL;
632     }
633
634     rmt_min_rx = MAX(ntohl(msg->min_rx) / 1000, 1);
635     if (bfd->rmt_min_rx != rmt_min_rx) {
636         bfd->rmt_min_rx = rmt_min_rx;
637         bfd_set_next_tx(bfd);
638         log_msg(VLL_INFO, msg, "New remote min_rx", bfd);
639     }
640
641     bfd->rmt_min_tx = MAX(ntohl(msg->min_tx) / 1000, 1);
642     bfd->detect_time = bfd_rx_interval(bfd) * bfd->mult + time_msec();
643
644     if (bfd->state == STATE_ADMIN_DOWN) {
645         VLOG_DBG_RL(&rl, "Administratively down, dropping control message.");
646         goto out;
647     }
648
649     if (rmt_state == STATE_ADMIN_DOWN) {
650         if (bfd->state != STATE_DOWN) {
651             bfd_set_state(bfd, STATE_DOWN, DIAG_RMT_DOWN);
652         }
653     } else {
654         switch (bfd->state) {
655         case STATE_DOWN:
656             if (rmt_state == STATE_DOWN) {
657                 bfd_set_state(bfd, STATE_INIT, bfd->diag);
658             } else if (rmt_state == STATE_INIT) {
659                 bfd_set_state(bfd, STATE_UP, bfd->diag);
660             }
661             break;
662         case STATE_INIT:
663             if (rmt_state > STATE_DOWN) {
664                 bfd_set_state(bfd, STATE_UP, bfd->diag);
665             }
666             break;
667         case STATE_UP:
668             if (rmt_state <= STATE_DOWN) {
669                 bfd_set_state(bfd, STATE_DOWN, DIAG_RMT_DOWN);
670                 log_msg(VLL_INFO, msg, "Remote signaled STATE_DOWN", bfd);
671             }
672             break;
673         case STATE_ADMIN_DOWN:
674         default:
675             NOT_REACHED();
676         }
677     }
678     /* XXX: RFC 5880 Section 6.8.6 Demand mode related calculations here. */
679
680 out:
681     ovs_mutex_unlock(&mutex);
682 }
683 \f
684 static bool
685 bfd_forwarding__(const struct bfd *bfd) OVS_REQ_WRLOCK(mutex)
686 {
687     if (bfd->forwarding_override != -1) {
688         return bfd->forwarding_override == 1;
689     }
690
691     return bfd->state == STATE_UP
692         && bfd->rmt_diag != DIAG_PATH_DOWN
693         && bfd->rmt_diag != DIAG_CPATH_DOWN
694         && bfd->rmt_diag != DIAG_RCPATH_DOWN;
695 }
696
697 /* Helpers. */
698 static bool
699 bfd_in_poll(const struct bfd *bfd) OVS_REQ_WRLOCK(mutex)
700 {
701     return (bfd->flags & FLAG_POLL) != 0;
702 }
703
704 static void
705 bfd_poll(struct bfd *bfd) OVS_REQ_WRLOCK(mutex)
706 {
707     if (bfd->state > STATE_DOWN && !bfd_in_poll(bfd)
708         && !(bfd->flags & FLAG_FINAL)) {
709         bfd->poll_min_tx = bfd->cfg_min_tx;
710         bfd->poll_min_rx = bfd->cfg_min_rx;
711         bfd->flags |= FLAG_POLL;
712         bfd->next_tx = 0;
713         VLOG_INFO_RL(&rl, "%s: Initiating poll sequence", bfd->name);
714     }
715 }
716
717 static long long int
718 bfd_min_tx(const struct bfd *bfd) OVS_REQ_WRLOCK(mutex)
719 {
720     /* RFC 5880 Section 6.8.3
721      * When bfd.SessionState is not Up, the system MUST set
722      * bfd.DesiredMinTxInterval to a value of not less than one second
723      * (1,000,000 microseconds).  This is intended to ensure that the
724      * bandwidth consumed by BFD sessions that are not Up is negligible,
725      * particularly in the case where a neighbor may not be running BFD. */
726     return (bfd->state == STATE_UP ? bfd->min_tx : MAX(bfd->min_tx, 1000));
727 }
728
729 static long long int
730 bfd_tx_interval(const struct bfd *bfd) OVS_REQ_WRLOCK(mutex)
731 {
732     long long int interval = bfd_min_tx(bfd);
733     return MAX(interval, bfd->rmt_min_rx);
734 }
735
736 static long long int
737 bfd_rx_interval(const struct bfd *bfd) OVS_REQ_WRLOCK(mutex)
738 {
739     return MAX(bfd->min_rx, bfd->rmt_min_tx);
740 }
741
742 static void
743 bfd_set_next_tx(struct bfd *bfd) OVS_REQ_WRLOCK(mutex)
744 {
745     long long int interval = bfd_tx_interval(bfd);
746     interval -= interval * random_range(26) / 100;
747     bfd->next_tx = bfd->last_tx + interval;
748 }
749
750 static const char *
751 bfd_flag_str(enum flags flags)
752 {
753     struct ds ds = DS_EMPTY_INITIALIZER;
754     static char flag_str[128];
755
756     if (!flags) {
757         return "none";
758     }
759
760     if (flags & FLAG_MULTIPOINT) {
761         ds_put_cstr(&ds, "multipoint ");
762     }
763
764     if (flags & FLAG_DEMAND) {
765         ds_put_cstr(&ds, "demand ");
766     }
767
768     if (flags & FLAG_AUTH) {
769         ds_put_cstr(&ds, "auth ");
770     }
771
772     if (flags & FLAG_CTL) {
773         ds_put_cstr(&ds, "ctl ");
774     }
775
776     if (flags & FLAG_FINAL) {
777         ds_put_cstr(&ds, "final ");
778     }
779
780     if (flags & FLAG_POLL) {
781         ds_put_cstr(&ds, "poll ");
782     }
783
784     ovs_strlcpy(flag_str, ds_cstr(&ds), sizeof flag_str);
785     ds_destroy(&ds);
786     return flag_str;
787 }
788
789 static const char *
790 bfd_state_str(enum state state)
791 {
792     switch (state) {
793     case STATE_ADMIN_DOWN: return "admin_down";
794     case STATE_DOWN: return "down";
795     case STATE_INIT: return "init";
796     case STATE_UP: return "up";
797     default: return "invalid";
798     }
799 }
800
801 static const char *
802 bfd_diag_str(enum diag diag) {
803     switch (diag) {
804     case DIAG_NONE: return "No Diagnostic";
805     case DIAG_EXPIRED: return "Control Detection Time Expired";
806     case DIAG_ECHO_FAILED: return "Echo Function Failed";
807     case DIAG_RMT_DOWN: return "Neighbor Signaled Session Down";
808     case DIAG_FWD_RESET: return "Forwarding Plane Reset";
809     case DIAG_PATH_DOWN: return "Path Down";
810     case DIAG_CPATH_DOWN: return "Concatenated Path Down";
811     case DIAG_ADMIN_DOWN: return "Administratively Down";
812     case DIAG_RCPATH_DOWN: return "Reverse Concatenated Path Down";
813     default: return "Invalid Diagnostic";
814     }
815 };
816
817 static void
818 log_msg(enum vlog_level level, const struct msg *p, const char *message,
819         const struct bfd *bfd) OVS_REQ_WRLOCK(mutex)
820 {
821     struct ds ds = DS_EMPTY_INITIALIZER;
822
823     if (vlog_should_drop(THIS_MODULE, level, &rl)) {
824         return;
825     }
826
827     ds_put_format(&ds,
828                   "%s: %s."
829                   "\n\tvers:%"PRIu8" diag:\"%s\" state:%s mult:%"PRIu8
830                   " length:%"PRIu8
831                   "\n\tflags: %s"
832                   "\n\tmy_disc:0x%"PRIx32" your_disc:0x%"PRIx32
833                   "\n\tmin_tx:%"PRIu32"us (%"PRIu32"ms)"
834                   "\n\tmin_rx:%"PRIu32"us (%"PRIu32"ms)"
835                   "\n\tmin_rx_echo:%"PRIu32"us (%"PRIu32"ms)",
836                   bfd->name, message, p->vers_diag >> VERS_SHIFT,
837                   bfd_diag_str(p->vers_diag & DIAG_MASK),
838                   bfd_state_str(p->flags & STATE_MASK),
839                   p->mult, p->length, bfd_flag_str(p->flags & FLAGS_MASK),
840                   ntohl(p->my_disc), ntohl(p->your_disc),
841                   ntohl(p->min_tx), ntohl(p->min_tx) / 1000,
842                   ntohl(p->min_rx), ntohl(p->min_rx) / 1000,
843                   ntohl(p->min_rx_echo), ntohl(p->min_rx_echo) / 1000);
844     bfd_put_details(&ds, bfd);
845     VLOG(level, "%s", ds_cstr(&ds));
846     ds_destroy(&ds);
847 }
848
849 static void
850 bfd_set_state(struct bfd *bfd, enum state state, enum diag diag)
851     OVS_REQ_WRLOCK(mutex)
852 {
853     if (diag == DIAG_NONE && bfd->cpath_down) {
854         diag = DIAG_CPATH_DOWN;
855     }
856
857     if (bfd->state != state || bfd->diag != diag) {
858         if (!VLOG_DROP_INFO(&rl)) {
859             struct ds ds = DS_EMPTY_INITIALIZER;
860
861             ds_put_format(&ds, "%s: BFD state change: %s->%s"
862                           " \"%s\"->\"%s\".\n",
863                           bfd->name, bfd_state_str(bfd->state),
864                           bfd_state_str(state), bfd_diag_str(bfd->diag),
865                           bfd_diag_str(diag));
866             bfd_put_details(&ds, bfd);
867             VLOG_INFO("%s", ds_cstr(&ds));
868             ds_destroy(&ds);
869         }
870
871         bfd->state = state;
872         bfd->diag = diag;
873
874         if (bfd->state <= STATE_DOWN) {
875             bfd->rmt_state = STATE_DOWN;
876             bfd->rmt_diag = DIAG_NONE;
877             bfd->rmt_min_rx = 1;
878             bfd->rmt_flags = 0;
879             bfd->rmt_disc = 0;
880             bfd->rmt_min_tx = 0;
881         }
882     }
883 }
884
885 static uint32_t
886 generate_discriminator(void)
887 {
888     uint32_t disc = 0;
889
890     /* RFC 5880 Section 6.8.1
891      * It SHOULD be set to a random (but still unique) value to improve
892      * security.  The value is otherwise outside the scope of this
893      * specification. */
894
895     while (!disc) {
896         struct bfd *bfd;
897
898         /* 'disc' is by definition random, so there's no reason to waste time
899          * hashing it. */
900         disc = random_uint32();
901         HMAP_FOR_EACH_IN_BUCKET (bfd, node, disc, all_bfds) {
902             if (bfd->disc == disc) {
903                 disc = 0;
904                 break;
905             }
906         }
907     }
908
909     return disc;
910 }
911
912 static struct bfd *
913 bfd_find_by_name(const char *name) OVS_REQ_WRLOCK(mutex)
914 {
915     struct bfd *bfd;
916
917     HMAP_FOR_EACH (bfd, node, all_bfds) {
918         if (!strcmp(bfd->name, name)) {
919             return bfd;
920         }
921     }
922     return NULL;
923 }
924
925 static void
926 bfd_put_details(struct ds *ds, const struct bfd *bfd) OVS_REQ_WRLOCK(mutex)
927 {
928     ds_put_format(ds, "\tForwarding: %s\n",
929                   bfd_forwarding__(bfd) ? "true" : "false");
930     ds_put_format(ds, "\tDetect Multiplier: %d\n", bfd->mult);
931     ds_put_format(ds, "\tConcatenated Path Down: %s\n",
932                   bfd->cpath_down ? "true" : "false");
933     ds_put_format(ds, "\tTX Interval: Approx %lldms\n", bfd_tx_interval(bfd));
934     ds_put_format(ds, "\tRX Interval: Approx %lldms\n", bfd_rx_interval(bfd));
935     ds_put_format(ds, "\tDetect Time: now %+lldms\n",
936                   time_msec() - bfd->detect_time);
937     ds_put_format(ds, "\tNext TX Time: now %+lldms\n",
938                   time_msec() - bfd->next_tx);
939     ds_put_format(ds, "\tLast TX Time: now %+lldms\n",
940                   time_msec() - bfd->last_tx);
941
942     ds_put_cstr(ds, "\n");
943
944     ds_put_format(ds, "\tLocal Flags: %s\n", bfd_flag_str(bfd->flags));
945     ds_put_format(ds, "\tLocal Session State: %s\n",
946                   bfd_state_str(bfd->state));
947     ds_put_format(ds, "\tLocal Diagnostic: %s\n", bfd_diag_str(bfd->diag));
948     ds_put_format(ds, "\tLocal Discriminator: 0x%"PRIx32"\n", bfd->disc);
949     ds_put_format(ds, "\tLocal Minimum TX Interval: %lldms\n",
950                   bfd_min_tx(bfd));
951     ds_put_format(ds, "\tLocal Minimum RX Interval: %lldms\n", bfd->min_rx);
952
953     ds_put_cstr(ds, "\n");
954
955     ds_put_format(ds, "\tRemote Flags: %s\n", bfd_flag_str(bfd->rmt_flags));
956     ds_put_format(ds, "\tRemote Session State: %s\n",
957                   bfd_state_str(bfd->rmt_state));
958     ds_put_format(ds, "\tRemote Diagnostic: %s\n",
959                   bfd_diag_str(bfd->rmt_diag));
960     ds_put_format(ds, "\tRemote Discriminator: 0x%"PRIx32"\n", bfd->rmt_disc);
961     ds_put_format(ds, "\tRemote Minimum TX Interval: %lldms\n",
962                   bfd->rmt_min_tx);
963     ds_put_format(ds, "\tRemote Minimum RX Interval: %lldms\n",
964                   bfd->rmt_min_rx);
965 }
966
967 static void
968 bfd_unixctl_show(struct unixctl_conn *conn, int argc, const char *argv[],
969                  void *aux OVS_UNUSED) OVS_EXCLUDED(mutex)
970 {
971     struct ds ds = DS_EMPTY_INITIALIZER;
972     struct bfd *bfd;
973
974     ovs_mutex_lock(&mutex);
975     if (argc > 1) {
976         bfd = bfd_find_by_name(argv[1]);
977         if (!bfd) {
978             unixctl_command_reply_error(conn, "no such bfd object");
979             goto out;
980         }
981         bfd_put_details(&ds, bfd);
982     } else {
983         HMAP_FOR_EACH (bfd, node, all_bfds) {
984             ds_put_format(&ds, "---- %s ----\n", bfd->name);
985             bfd_put_details(&ds, bfd);
986         }
987     }
988     unixctl_command_reply(conn, ds_cstr(&ds));
989     ds_destroy(&ds);
990
991 out:
992     ovs_mutex_unlock(&mutex);
993 }
994
995
996 static void
997 bfd_unixctl_set_forwarding_override(struct unixctl_conn *conn, int argc,
998                                     const char *argv[], void *aux OVS_UNUSED)
999     OVS_EXCLUDED(mutex)
1000 {
1001     const char *forward_str = argv[argc - 1];
1002     int forwarding_override;
1003     struct bfd *bfd;
1004
1005     ovs_mutex_lock(&mutex);
1006     if (!strcasecmp("true", forward_str)) {
1007         forwarding_override = 1;
1008     } else if (!strcasecmp("false", forward_str)) {
1009         forwarding_override = 0;
1010     } else if (!strcasecmp("normal", forward_str)) {
1011         forwarding_override = -1;
1012     } else {
1013         unixctl_command_reply_error(conn, "unknown fault string");
1014         goto out;
1015     }
1016
1017     if (argc > 2) {
1018         bfd = bfd_find_by_name(argv[1]);
1019         if (!bfd) {
1020             unixctl_command_reply_error(conn, "no such BFD object");
1021             goto out;
1022         }
1023         bfd->forwarding_override = forwarding_override;
1024     } else {
1025         HMAP_FOR_EACH (bfd, node, all_bfds) {
1026             bfd->forwarding_override = forwarding_override;
1027         }
1028     }
1029
1030     unixctl_command_reply(conn, "OK");
1031
1032 out:
1033     ovs_mutex_unlock(&mutex);
1034 }