Merge branch 'mainstream'
[sliver-openvswitch.git] / lib / cfm.c
1 /*
2  * Copyright (c) 2010, 2011, 2012, 2013 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 #include "cfm.h"
19
20 #include <stdint.h>
21 #include <stdlib.h>
22 #include <string.h>
23
24 #include "byte-order.h"
25 #include "dynamic-string.h"
26 #include "flow.h"
27 #include "hash.h"
28 #include "hmap.h"
29 #include "netdev.h"
30 #include "ofpbuf.h"
31 #include "packets.h"
32 #include "poll-loop.h"
33 #include "random.h"
34 #include "timer.h"
35 #include "timeval.h"
36 #include "unixctl.h"
37 #include "vlog.h"
38
39 VLOG_DEFINE_THIS_MODULE(cfm);
40
41 #define CFM_MAX_RMPS 256
42
43 /* Ethernet destination address of CCM packets. */
44 static const uint8_t eth_addr_ccm[6] = { 0x01, 0x80, 0xC2, 0x00, 0x00, 0x30 };
45 static const uint8_t eth_addr_ccm_x[6] = {
46     0x01, 0x23, 0x20, 0x00, 0x00, 0x30
47 };
48
49 #define ETH_TYPE_CFM 0x8902
50
51 /* A 'ccm' represents a Continuity Check Message from the 802.1ag
52  * specification.  Continuity Check Messages are broadcast periodically so that
53  * hosts can determine whom they have connectivity to.
54  *
55  * The minimum length of a CCM as specified by IEEE 802.1ag is 75 bytes.
56  * Previous versions of Open vSwitch generated 74-byte CCM messages, so we
57  * accept such messages too. */
58 #define CCM_LEN 75
59 #define CCM_ACCEPT_LEN 74
60 #define CCM_MAID_LEN 48
61 #define CCM_OPCODE 1 /* CFM message opcode meaning CCM. */
62 #define CCM_RDI_MASK 0x80
63 #define CFM_HEALTH_INTERVAL 6
64
65 OVS_PACKED(
66 struct ccm {
67     uint8_t mdlevel_version; /* MD Level and Version */
68     uint8_t opcode;
69     uint8_t flags;
70     uint8_t tlv_offset;
71     ovs_be32 seq;
72     ovs_be16 mpid;
73     uint8_t maid[CCM_MAID_LEN];
74
75     /* Defined by ITU-T Y.1731 should be zero */
76     ovs_be16 interval_ms_x;      /* Transmission interval in ms. */
77     ovs_be64 mpid64;             /* MPID in extended mode. */
78     uint8_t opdown;              /* Operationally down. */
79     uint8_t zero[5];
80
81     /* TLV space. */
82     uint8_t end_tlv;
83 });
84 BUILD_ASSERT_DECL(CCM_LEN == sizeof(struct ccm));
85
86 struct cfm {
87     const char *name;           /* Name of this CFM object. */
88     struct hmap_node hmap_node; /* Node in all_cfms list. */
89
90     struct netdev *netdev;
91     uint64_t rx_packets;        /* Packets received by 'netdev'. */
92
93     uint64_t mpid;
94     bool demand;           /* Demand mode. */
95     bool booted;           /* A full fault interval has occurred. */
96     enum cfm_fault_reason fault;  /* Connectivity fault status. */
97     enum cfm_fault_reason recv_fault;  /* Bit mask of faults occurring on
98                                           receive. */
99     bool opup;             /* Operational State. */
100     bool remote_opup;      /* Remote Operational State. */
101
102     int fault_override;    /* Manual override of 'fault' status.
103                               Ignored if negative. */
104
105     uint32_t seq;          /* The sequence number of our last CCM. */
106     uint8_t ccm_interval;  /* The CCM transmission interval. */
107     int ccm_interval_ms;   /* 'ccm_interval' in milliseconds. */
108     uint16_t ccm_vlan;     /* Vlan tag of CCM PDUs.  CFM_RANDOM_VLAN if
109                               random. */
110     uint8_t ccm_pcp;       /* Priority of CCM PDUs. */
111     uint8_t maid[CCM_MAID_LEN]; /* The MAID of this CFM. */
112
113     struct timer tx_timer;    /* Send CCM when expired. */
114     struct timer fault_timer; /* Check for faults when expired. */
115
116     struct hmap remote_mps;   /* Remote MPs. */
117
118     /* Result of cfm_get_remote_mpids(). Updated only during fault check to
119      * avoid flapping. */
120     uint64_t *rmps_array;     /* Cache of remote_mps. */
121     size_t rmps_array_len;    /* Number of rmps in 'rmps_array'. */
122
123     int health;               /* Percentage of the number of CCM frames
124                                  received. */
125     int health_interval;      /* Number of fault_intervals since health was
126                                  recomputed. */
127     long long int last_tx;    /* Last CCM transmission time. */
128
129     atomic_bool check_tnl_key; /* Verify the tunnel key of inbound packets? */
130     atomic_bool extended;      /* Extended mode. */
131     atomic_int ref_cnt;
132
133     uint64_t flap_count;       /* Count the flaps since boot. */
134 };
135
136 /* Remote MPs represent foreign network entities that are configured to have
137  * the same MAID as this CFM instance. */
138 struct remote_mp {
139     uint64_t mpid;         /* The Maintenance Point ID of this 'remote_mp'. */
140     struct hmap_node node; /* Node in 'remote_mps' map. */
141
142     bool recv;           /* CCM was received since last fault check. */
143     bool opup;           /* Operational State. */
144     uint32_t seq;        /* Most recently received sequence number. */
145     uint8_t num_health_ccm; /* Number of received ccm frames every
146                                CFM_HEALTH_INTERVAL * 'fault_interval'. */
147     long long int last_rx; /* Last CCM reception time. */
148
149 };
150
151 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(20, 30);
152
153 static struct ovs_mutex mutex = OVS_MUTEX_INITIALIZER;
154 static struct hmap all_cfms__ = HMAP_INITIALIZER(&all_cfms__);
155 static struct hmap *const all_cfms OVS_GUARDED_BY(mutex) = &all_cfms__;
156
157 static unixctl_cb_func cfm_unixctl_show;
158 static unixctl_cb_func cfm_unixctl_set_fault;
159
160 static uint64_t
161 cfm_rx_packets(const struct cfm *cfm) OVS_REQUIRES(mutex)
162 {
163     struct netdev_stats stats;
164
165     if (!netdev_get_stats(cfm->netdev, &stats)) {
166         return stats.rx_packets;
167     } else {
168         return 0;
169     }
170 }
171
172 static const uint8_t *
173 cfm_ccm_addr(struct cfm *cfm)
174 {
175     bool extended;
176     atomic_read(&cfm->extended, &extended);
177     return extended ? eth_addr_ccm_x : eth_addr_ccm;
178 }
179
180 /* Returns the string representation of the given cfm_fault_reason 'reason'. */
181 const char *
182 cfm_fault_reason_to_str(int reason)
183 {
184     switch (reason) {
185 #define CFM_FAULT_REASON(NAME, STR) case CFM_FAULT_##NAME: return #STR;
186         CFM_FAULT_REASONS
187 #undef CFM_FAULT_REASON
188     default: return "<unknown>";
189     }
190 }
191
192 static void
193 ds_put_cfm_fault(struct ds *ds, int fault)
194 {
195     int i;
196
197     for (i = 0; i < CFM_FAULT_N_REASONS; i++) {
198         int reason = 1 << i;
199
200         if (fault & reason) {
201             ds_put_format(ds, "%s ", cfm_fault_reason_to_str(reason));
202         }
203     }
204
205     ds_chomp(ds, ' ');
206 }
207
208 static void
209 cfm_generate_maid(struct cfm *cfm) OVS_REQUIRES(mutex)
210 {
211     const char *ovs_md_name = "ovs";
212     const char *ovs_ma_name = "ovs";
213     uint8_t *ma_p;
214     size_t md_len, ma_len;
215
216     memset(cfm->maid, 0, CCM_MAID_LEN);
217
218     md_len = strlen(ovs_md_name);
219     ma_len = strlen(ovs_ma_name);
220
221     ovs_assert(md_len && ma_len && md_len + ma_len + 4 <= CCM_MAID_LEN);
222
223     cfm->maid[0] = 4;                           /* MD name string format. */
224     cfm->maid[1] = md_len;                      /* MD name size. */
225     memcpy(&cfm->maid[2], ovs_md_name, md_len); /* MD name. */
226
227     ma_p = cfm->maid + 2 + md_len;
228     ma_p[0] = 2;                           /* MA name string format. */
229     ma_p[1] = ma_len;                      /* MA name size. */
230     memcpy(&ma_p[2], ovs_ma_name, ma_len); /* MA name. */
231 }
232
233 static int
234 ccm_interval_to_ms(uint8_t interval)
235 {
236     switch (interval) {
237     case 0:  NOT_REACHED(); /* Explicitly not supported by 802.1ag. */
238     case 1:  return 3;      /* Not recommended due to timer resolution. */
239     case 2:  return 10;     /* Not recommended due to timer resolution. */
240     case 3:  return 100;
241     case 4:  return 1000;
242     case 5:  return 10000;
243     case 6:  return 60000;
244     case 7:  return 600000;
245     default: NOT_REACHED(); /* Explicitly not supported by 802.1ag. */
246     }
247
248     NOT_REACHED();
249 }
250
251 static long long int
252 cfm_fault_interval(struct cfm *cfm) OVS_REQUIRES(mutex)
253 {
254     /* According to the 802.1ag specification we should assume every other MP
255      * with the same MAID has the same transmission interval that we have.  If
256      * an MP has a different interval, cfm_process_heartbeat will register it
257      * as a fault (likely due to a configuration error).  Thus we can check all
258      * MPs at once making this quite a bit simpler.
259      *
260      * When cfm is not in demand mode, we check when (ccm_interval_ms * 3.5) ms
261      * have passed.  When cfm is in demand mode, we check when
262      * (MAX(ccm_interval_ms, 500) * 3.5) ms have passed.  This ensures that
263      * ovs-vswitchd has enough time to pull statistics from the datapath. */
264
265     return (MAX(cfm->ccm_interval_ms, cfm->demand ? 500 : cfm->ccm_interval_ms)
266             * 7) / 2;
267 }
268
269 static uint8_t
270 ms_to_ccm_interval(int interval_ms)
271 {
272     uint8_t i;
273
274     for (i = 7; i > 0; i--) {
275         if (ccm_interval_to_ms(i) <= interval_ms) {
276             return i;
277         }
278     }
279
280     return 1;
281 }
282
283 static uint32_t
284 hash_mpid(uint64_t mpid)
285 {
286     return hash_bytes(&mpid, sizeof mpid, 0);
287 }
288
289 static bool
290 cfm_is_valid_mpid(bool extended, uint64_t mpid)
291 {
292     /* 802.1ag specification requires MPIDs to be within the range [1, 8191].
293      * In extended mode we relax this requirement. */
294     return mpid >= 1 && (extended || mpid <= 8191);
295 }
296
297 static struct remote_mp *
298 lookup_remote_mp(const struct cfm *cfm, uint64_t mpid) OVS_REQUIRES(mutex)
299 {
300     struct remote_mp *rmp;
301
302     HMAP_FOR_EACH_IN_BUCKET (rmp, node, hash_mpid(mpid), &cfm->remote_mps) {
303         if (rmp->mpid == mpid) {
304             return rmp;
305         }
306     }
307
308     return NULL;
309 }
310
311 void
312 cfm_init(void)
313 {
314     unixctl_command_register("cfm/show", "[interface]", 0, 1, cfm_unixctl_show,
315                              NULL);
316     unixctl_command_register("cfm/set-fault", "[interface] normal|false|true",
317                              1, 2, cfm_unixctl_set_fault, NULL);
318 }
319
320 /* Allocates a 'cfm' object called 'name'.  'cfm' should be initialized by
321  * cfm_configure() before use. */
322 struct cfm *
323 cfm_create(const struct netdev *netdev) OVS_EXCLUDED(mutex)
324 {
325     struct cfm *cfm;
326
327     cfm = xzalloc(sizeof *cfm);
328     cfm->netdev = netdev_ref(netdev);
329     cfm->name = netdev_get_name(cfm->netdev);
330     hmap_init(&cfm->remote_mps);
331     cfm->remote_opup = true;
332     cfm->fault_override = -1;
333     cfm->health = -1;
334     cfm->last_tx = 0;
335     cfm->flap_count = 0;
336     atomic_init(&cfm->extended, false);
337     atomic_init(&cfm->check_tnl_key, false);
338     atomic_init(&cfm->ref_cnt, 1);
339
340     ovs_mutex_lock(&mutex);
341     cfm_generate_maid(cfm);
342     hmap_insert(all_cfms, &cfm->hmap_node, hash_string(cfm->name, 0));
343     ovs_mutex_unlock(&mutex);
344     return cfm;
345 }
346
347 void
348 cfm_unref(struct cfm *cfm) OVS_EXCLUDED(mutex)
349 {
350     struct remote_mp *rmp, *rmp_next;
351     int orig;
352
353     if (!cfm) {
354         return;
355     }
356
357     atomic_sub(&cfm->ref_cnt, 1, &orig);
358     ovs_assert(orig > 0);
359     if (orig != 1) {
360         return;
361     }
362
363     ovs_mutex_lock(&mutex);
364     hmap_remove(all_cfms, &cfm->hmap_node);
365     ovs_mutex_unlock(&mutex);
366
367     HMAP_FOR_EACH_SAFE (rmp, rmp_next, node, &cfm->remote_mps) {
368         hmap_remove(&cfm->remote_mps, &rmp->node);
369         free(rmp);
370     }
371
372     hmap_destroy(&cfm->remote_mps);
373     netdev_close(cfm->netdev);
374     free(cfm->rmps_array);
375     free(cfm);
376 }
377
378 struct cfm *
379 cfm_ref(const struct cfm *cfm_)
380 {
381     struct cfm *cfm = CONST_CAST(struct cfm *, cfm_);
382     if (cfm) {
383         int orig;
384         atomic_add(&cfm->ref_cnt, 1, &orig);
385         ovs_assert(orig > 0);
386     }
387     return cfm;
388 }
389
390 /* Should be run periodically to update fault statistics messages. */
391 void
392 cfm_run(struct cfm *cfm) OVS_EXCLUDED(mutex)
393 {
394     ovs_mutex_lock(&mutex);
395     if (timer_expired(&cfm->fault_timer)) {
396         long long int interval = cfm_fault_interval(cfm);
397         struct remote_mp *rmp, *rmp_next;
398         bool old_cfm_fault = cfm->fault;
399         bool demand_override;
400         bool rmp_set_opup = false;
401         bool rmp_set_opdown = false;
402
403         cfm->fault = cfm->recv_fault;
404         cfm->recv_fault = 0;
405
406         cfm->rmps_array_len = 0;
407         free(cfm->rmps_array);
408         cfm->rmps_array = xmalloc(hmap_count(&cfm->remote_mps) *
409                                   sizeof *cfm->rmps_array);
410
411         if (cfm->health_interval == CFM_HEALTH_INTERVAL) {
412             /* Calculate the cfm health of the interface.  If the number of
413              * remote_mpids of a cfm interface is > 1, the cfm health is
414              * undefined. If the number of remote_mpids is 1, the cfm health is
415              * the percentage of the ccm frames received in the
416              * (CFM_HEALTH_INTERVAL * 3.5)ms, else it is 0. */
417             if (hmap_count(&cfm->remote_mps) > 1) {
418                 cfm->health = -1;
419             } else if (hmap_is_empty(&cfm->remote_mps)) {
420                 cfm->health = 0;
421             } else {
422                 int exp_ccm_recvd;
423
424                 rmp = CONTAINER_OF(hmap_first(&cfm->remote_mps),
425                                    struct remote_mp, node);
426                 exp_ccm_recvd = (CFM_HEALTH_INTERVAL * 7) / 2;
427                 /* Calculate the percentage of healthy ccm frames received.
428                  * Since the 'fault_interval' is (3.5 * cfm_interval), and
429                  * 1 CCM packet must be received every cfm_interval,
430                  * the 'remote_mpid' health reports the percentage of
431                  * healthy CCM frames received every
432                  * 'CFM_HEALTH_INTERVAL'th 'fault_interval'. */
433                 cfm->health = (rmp->num_health_ccm * 100) / exp_ccm_recvd;
434                 cfm->health = MIN(cfm->health, 100);
435                 rmp->num_health_ccm = 0;
436                 ovs_assert(cfm->health >= 0 && cfm->health <= 100);
437             }
438             cfm->health_interval = 0;
439         }
440         cfm->health_interval++;
441
442         demand_override = false;
443         if (cfm->demand) {
444             uint64_t rx_packets = cfm_rx_packets(cfm);
445             demand_override = hmap_count(&cfm->remote_mps) == 1
446                 && rx_packets > cfm->rx_packets;
447             cfm->rx_packets = rx_packets;
448         }
449
450         HMAP_FOR_EACH_SAFE (rmp, rmp_next, node, &cfm->remote_mps) {
451             if (!rmp->recv) {
452                 VLOG_INFO("%s: Received no CCM from RMP %"PRIu64" in the last"
453                           " %lldms", cfm->name, rmp->mpid,
454                           time_msec() - rmp->last_rx);
455                 if (!demand_override) {
456                     hmap_remove(&cfm->remote_mps, &rmp->node);
457                     free(rmp);
458                 }
459             } else {
460                 rmp->recv = false;
461
462                 if (rmp->opup) {
463                     rmp_set_opup = true;
464                 } else {
465                     rmp_set_opdown = true;
466                 }
467
468                 cfm->rmps_array[cfm->rmps_array_len++] = rmp->mpid;
469             }
470         }
471
472         if (rmp_set_opdown) {
473             cfm->remote_opup = false;
474         }
475         else if (rmp_set_opup) {
476             cfm->remote_opup = true;
477         }
478
479         if (hmap_is_empty(&cfm->remote_mps)) {
480             cfm->fault |= CFM_FAULT_RECV;
481         }
482
483         if (old_cfm_fault != cfm->fault && !VLOG_DROP_INFO(&rl)) {
484             struct ds ds = DS_EMPTY_INITIALIZER;
485
486             ds_put_cstr(&ds, "from [");
487             ds_put_cfm_fault(&ds, old_cfm_fault);
488             ds_put_cstr(&ds, "] to [");
489             ds_put_cfm_fault(&ds, cfm->fault);
490             ds_put_char(&ds, ']');
491             VLOG_INFO("%s: CFM faults changed %s.", cfm->name, ds_cstr(&ds));
492             ds_destroy(&ds);
493
494             /* If there is a flap, increments the counter. */
495             if (old_cfm_fault == false || cfm->fault == false) {
496                 cfm->flap_count++;
497             }
498         }
499
500         cfm->booted = true;
501         timer_set_duration(&cfm->fault_timer, interval);
502         VLOG_DBG("%s: new fault interval", cfm->name);
503     }
504     ovs_mutex_unlock(&mutex);
505 }
506
507 /* Should be run periodically to check if the CFM module has a CCM message it
508  * wishes to send. */
509 bool
510 cfm_should_send_ccm(struct cfm *cfm) OVS_EXCLUDED(mutex)
511 {
512     bool ret;
513
514     ovs_mutex_lock(&mutex);
515     ret = timer_expired(&cfm->tx_timer);
516     ovs_mutex_unlock(&mutex);
517     return ret;
518 }
519
520 /* Composes a CCM message into 'packet'.  Messages generated with this function
521  * should be sent whenever cfm_should_send_ccm() indicates. */
522 void
523 cfm_compose_ccm(struct cfm *cfm, struct ofpbuf *packet,
524                 uint8_t eth_src[ETH_ADDR_LEN]) OVS_EXCLUDED(mutex)
525 {
526     uint16_t ccm_vlan;
527     struct ccm *ccm;
528     bool extended;
529
530     ovs_mutex_lock(&mutex);
531     timer_set_duration(&cfm->tx_timer, cfm->ccm_interval_ms);
532     eth_compose(packet, cfm_ccm_addr(cfm), eth_src, ETH_TYPE_CFM, sizeof *ccm);
533
534     ccm_vlan = (cfm->ccm_vlan != CFM_RANDOM_VLAN
535                 ? cfm->ccm_vlan
536                 : random_uint16());
537     ccm_vlan = ccm_vlan & VLAN_VID_MASK;
538
539     if (ccm_vlan || cfm->ccm_pcp) {
540         uint16_t tci = ccm_vlan | (cfm->ccm_pcp << VLAN_PCP_SHIFT);
541         eth_push_vlan(packet, htons(tci));
542     }
543
544     ccm = packet->l3;
545     ccm->mdlevel_version = 0;
546     ccm->opcode = CCM_OPCODE;
547     ccm->tlv_offset = 70;
548     ccm->seq = htonl(++cfm->seq);
549     ccm->flags = cfm->ccm_interval;
550     memcpy(ccm->maid, cfm->maid, sizeof ccm->maid);
551     memset(ccm->zero, 0, sizeof ccm->zero);
552     ccm->end_tlv = 0;
553
554     atomic_read(&cfm->extended, &extended);
555     if (extended) {
556         ccm->mpid = htons(hash_mpid(cfm->mpid));
557         ccm->mpid64 = htonll(cfm->mpid);
558         ccm->opdown = !cfm->opup;
559     } else {
560         ccm->mpid = htons(cfm->mpid);
561         ccm->mpid64 = htonll(0);
562         ccm->opdown = 0;
563     }
564
565     if (cfm->ccm_interval == 0) {
566         ovs_assert(extended);
567         ccm->interval_ms_x = htons(cfm->ccm_interval_ms);
568     } else {
569         ccm->interval_ms_x = htons(0);
570     }
571
572     if (cfm->booted && hmap_is_empty(&cfm->remote_mps)) {
573         ccm->flags |= CCM_RDI_MASK;
574     }
575
576     if (cfm->last_tx) {
577         long long int delay = time_msec() - cfm->last_tx;
578         if (delay > (cfm->ccm_interval_ms * 3 / 2)) {
579             VLOG_WARN("%s: long delay of %lldms (expected %dms) sending CCM"
580                       " seq %"PRIu32, cfm->name, delay, cfm->ccm_interval_ms,
581                       cfm->seq);
582         }
583     }
584     cfm->last_tx = time_msec();
585     ovs_mutex_unlock(&mutex);
586 }
587
588 void
589 cfm_wait(struct cfm *cfm) OVS_EXCLUDED(mutex)
590 {
591     poll_timer_wait_until(cfm_wake_time(cfm));
592 }
593
594
595 /* Returns the next cfm wakeup time. */
596 long long int
597 cfm_wake_time(struct cfm *cfm) OVS_EXCLUDED(mutex)
598 {
599     long long int retval;
600
601     if (!cfm) {
602         return LLONG_MAX;
603     }
604
605     ovs_mutex_lock(&mutex);
606     retval = MIN(cfm->tx_timer.t, cfm->fault_timer.t);
607     ovs_mutex_unlock(&mutex);
608     return retval;
609 }
610
611
612 /* Configures 'cfm' with settings from 's'. */
613 bool
614 cfm_configure(struct cfm *cfm, const struct cfm_settings *s)
615     OVS_EXCLUDED(mutex)
616 {
617     uint8_t interval;
618     int interval_ms;
619
620     if (!cfm_is_valid_mpid(s->extended, s->mpid) || s->interval <= 0) {
621         return false;
622     }
623
624     ovs_mutex_lock(&mutex);
625     cfm->mpid = s->mpid;
626     cfm->opup = s->opup;
627     interval = ms_to_ccm_interval(s->interval);
628     interval_ms = ccm_interval_to_ms(interval);
629
630     atomic_store(&cfm->check_tnl_key, s->check_tnl_key);
631     atomic_store(&cfm->extended, s->extended);
632
633     cfm->ccm_vlan = s->ccm_vlan;
634     cfm->ccm_pcp = s->ccm_pcp & (VLAN_PCP_MASK >> VLAN_PCP_SHIFT);
635     if (s->extended && interval_ms != s->interval) {
636         interval = 0;
637         interval_ms = MIN(s->interval, UINT16_MAX);
638     }
639
640     if (s->extended && s->demand) {
641         if (!cfm->demand) {
642             cfm->demand = true;
643             cfm->rx_packets = cfm_rx_packets(cfm);
644         }
645     } else {
646         cfm->demand = false;
647     }
648
649     if (interval != cfm->ccm_interval || interval_ms != cfm->ccm_interval_ms) {
650         cfm->ccm_interval = interval;
651         cfm->ccm_interval_ms = interval_ms;
652
653         timer_set_expired(&cfm->tx_timer);
654         timer_set_duration(&cfm->fault_timer, cfm_fault_interval(cfm));
655     }
656
657     ovs_mutex_unlock(&mutex);
658     return true;
659 }
660
661 /* Must be called when the netdev owned by 'cfm' should change. */
662 void
663 cfm_set_netdev(struct cfm *cfm, const struct netdev *netdev)
664     OVS_EXCLUDED(mutex)
665 {
666     ovs_mutex_lock(&mutex);
667     if (cfm->netdev != netdev) {
668         netdev_close(cfm->netdev);
669         cfm->netdev = netdev_ref(netdev);
670     }
671     ovs_mutex_unlock(&mutex);
672 }
673
674 /* Returns true if 'cfm' should process packets from 'flow'.  Sets
675  * fields in 'wc' that were used to make the determination. */
676 bool
677 cfm_should_process_flow(const struct cfm *cfm_, const struct flow *flow,
678                         struct flow_wildcards *wc)
679 {
680     struct cfm *cfm = CONST_CAST(struct cfm *, cfm_);
681     bool check_tnl_key;
682
683     atomic_read(&cfm->check_tnl_key, &check_tnl_key);
684     memset(&wc->masks.dl_dst, 0xff, sizeof wc->masks.dl_dst);
685     if (check_tnl_key) {
686         memset(&wc->masks.tunnel.tun_id, 0xff, sizeof wc->masks.tunnel.tun_id);
687     }
688     return (ntohs(flow->dl_type) == ETH_TYPE_CFM
689             && eth_addr_equals(flow->dl_dst, cfm_ccm_addr(cfm))
690             && (!check_tnl_key || flow->tunnel.tun_id == htonll(0)));
691 }
692
693 /* Updates internal statistics relevant to packet 'p'.  Should be called on
694  * every packet whose flow returned true when passed to
695  * cfm_should_process_flow. */
696 void
697 cfm_process_heartbeat(struct cfm *cfm, const struct ofpbuf *p)
698     OVS_EXCLUDED(mutex)
699 {
700     struct ccm *ccm;
701     struct eth_header *eth;
702
703     ovs_mutex_lock(&mutex);
704
705     eth = p->l2;
706     ccm = ofpbuf_at(p, (uint8_t *)p->l3 - (uint8_t *)p->data, CCM_ACCEPT_LEN);
707
708     if (!ccm) {
709         VLOG_INFO_RL(&rl, "%s: Received an unparseable 802.1ag CCM heartbeat.",
710                      cfm->name);
711         goto out;
712     }
713
714     if (ccm->opcode != CCM_OPCODE) {
715         VLOG_INFO_RL(&rl, "%s: Received an unsupported 802.1ag message. "
716                      "(opcode %u)", cfm->name, ccm->opcode);
717         goto out;
718     }
719
720     /* According to the 802.1ag specification, reception of a CCM with an
721      * incorrect ccm_interval, unexpected MAID, or unexpected MPID should
722      * trigger a fault.  We ignore this requirement for several reasons.
723      *
724      * Faults can cause a controller or Open vSwitch to make potentially
725      * expensive changes to the network topology.  It seems prudent to trigger
726      * them judiciously, especially when CFM is used to check slave status of
727      * bonds. Furthermore, faults can be maliciously triggered by crafting
728      * unexpected CCMs. */
729     if (memcmp(ccm->maid, cfm->maid, sizeof ccm->maid)) {
730         cfm->recv_fault |= CFM_FAULT_MAID;
731         VLOG_WARN_RL(&rl, "%s: Received unexpected remote MAID from MAC "
732                      ETH_ADDR_FMT, cfm->name, ETH_ADDR_ARGS(eth->eth_src));
733     } else {
734         uint8_t ccm_interval = ccm->flags & 0x7;
735         bool ccm_rdi = ccm->flags & CCM_RDI_MASK;
736         uint16_t ccm_interval_ms_x = ntohs(ccm->interval_ms_x);
737
738         struct remote_mp *rmp;
739         uint64_t ccm_mpid;
740         uint32_t ccm_seq;
741         bool ccm_opdown;
742         bool extended;
743         enum cfm_fault_reason cfm_fault = 0;
744
745         atomic_read(&cfm->extended, &extended);
746         if (extended) {
747             ccm_mpid = ntohll(ccm->mpid64);
748             ccm_opdown = ccm->opdown;
749         } else {
750             ccm_mpid = ntohs(ccm->mpid);
751             ccm_opdown = false;
752         }
753         ccm_seq = ntohl(ccm->seq);
754
755         if (ccm_interval != cfm->ccm_interval) {
756             VLOG_WARN_RL(&rl, "%s: received a CCM with an unexpected interval"
757                          " (%"PRIu8") from RMP %"PRIu64, cfm->name,
758                          ccm_interval, ccm_mpid);
759         }
760
761         if (extended && ccm_interval == 0
762             && ccm_interval_ms_x != cfm->ccm_interval_ms) {
763             VLOG_WARN_RL(&rl, "%s: received a CCM with an unexpected extended"
764                          " interval (%"PRIu16"ms) from RMP %"PRIu64, cfm->name,
765                          ccm_interval_ms_x, ccm_mpid);
766         }
767
768         rmp = lookup_remote_mp(cfm, ccm_mpid);
769         if (!rmp) {
770             if (hmap_count(&cfm->remote_mps) < CFM_MAX_RMPS) {
771                 rmp = xzalloc(sizeof *rmp);
772                 hmap_insert(&cfm->remote_mps, &rmp->node, hash_mpid(ccm_mpid));
773             } else {
774                 cfm_fault |= CFM_FAULT_OVERFLOW;
775                 VLOG_WARN_RL(&rl,
776                              "%s: dropped CCM with MPID %"PRIu64" from MAC "
777                              ETH_ADDR_FMT, cfm->name, ccm_mpid,
778                              ETH_ADDR_ARGS(eth->eth_src));
779             }
780         }
781
782         if (ccm_rdi) {
783             cfm_fault |= CFM_FAULT_RDI;
784             VLOG_DBG("%s: RDI bit flagged from RMP %"PRIu64, cfm->name,
785                      ccm_mpid);
786         }
787
788         VLOG_DBG("%s: received CCM (seq %"PRIu32") (mpid %"PRIu64")"
789                  " (interval %"PRIu8") (RDI %s)", cfm->name, ccm_seq,
790                  ccm_mpid, ccm_interval, ccm_rdi ? "true" : "false");
791
792         if (rmp) {
793             if (rmp->mpid == cfm->mpid) {
794                 cfm_fault |= CFM_FAULT_LOOPBACK;
795                 VLOG_WARN_RL(&rl,"%s: received CCM with local MPID"
796                              " %"PRIu64, cfm->name, rmp->mpid);
797             }
798
799             if (rmp->seq && ccm_seq != (rmp->seq + 1)) {
800                 VLOG_WARN_RL(&rl, "%s: (mpid %"PRIu64") detected sequence"
801                              " numbers which indicate possible connectivity"
802                              " problems (previous %"PRIu32") (current %"PRIu32
803                              ")", cfm->name, ccm_mpid, rmp->seq, ccm_seq);
804             }
805
806             rmp->mpid = ccm_mpid;
807             if (!cfm_fault) {
808                 rmp->num_health_ccm++;
809             }
810             rmp->recv = true;
811             cfm->recv_fault |= cfm_fault;
812             rmp->seq = ccm_seq;
813             rmp->opup = !ccm_opdown;
814             rmp->last_rx = time_msec();
815         }
816     }
817
818 out:
819     ovs_mutex_unlock(&mutex);
820 }
821
822 static int
823 cfm_get_fault__(const struct cfm *cfm) OVS_REQUIRES(mutex)
824 {
825     if (cfm->fault_override >= 0) {
826         return cfm->fault_override ? CFM_FAULT_OVERRIDE : 0;
827     }
828     return cfm->fault;
829 }
830
831 /* Gets the fault status of 'cfm'.  Returns a bit mask of 'cfm_fault_reason's
832  * indicating the cause of the connectivity fault, or zero if there is no
833  * fault. */
834 int
835 cfm_get_fault(const struct cfm *cfm) OVS_EXCLUDED(mutex)
836 {
837     int fault;
838
839     ovs_mutex_lock(&mutex);
840     fault = cfm_get_fault__(cfm);
841     ovs_mutex_unlock(&mutex);
842     return fault;
843 }
844
845 /* Gets the number of cfm fault flapping since start. */
846 uint64_t
847 cfm_get_flap_count(const struct cfm *cfm) OVS_EXCLUDED(mutex)
848 {
849     uint64_t flap_count;
850     ovs_mutex_lock(&mutex);
851     flap_count = cfm->flap_count;
852     ovs_mutex_unlock(&mutex);
853     return flap_count;
854 }
855
856 /* Gets the health of 'cfm'.  Returns an integer between 0 and 100 indicating
857  * the health of the link as a percentage of ccm frames received in
858  * CFM_HEALTH_INTERVAL * 'fault_interval' if there is only 1 remote_mpid,
859  * returns 0 if there are no remote_mpids, and returns -1 if there are more
860  * than 1 remote_mpids. */
861 int
862 cfm_get_health(const struct cfm *cfm) OVS_EXCLUDED(mutex)
863 {
864     int health;
865
866     ovs_mutex_lock(&mutex);
867     health = cfm->health;
868     ovs_mutex_unlock(&mutex);
869     return health;
870 }
871
872 /* Gets the operational state of 'cfm'.  'cfm' is considered operationally down
873  * if it has received a CCM with the operationally down bit set from any of its
874  * remote maintenance points. Returns 1 if 'cfm' is operationally up, 0 if
875  * 'cfm' is operationally down, or -1 if 'cfm' has no operational state
876  * (because it isn't in extended mode). */
877 int
878 cfm_get_opup(const struct cfm *cfm_) OVS_EXCLUDED(mutex)
879 {
880     struct cfm *cfm = CONST_CAST(struct cfm *, cfm_);
881     bool extended;
882     int opup;
883
884     ovs_mutex_lock(&mutex);
885     atomic_read(&cfm->extended, &extended);
886     opup = extended ? cfm->remote_opup : -1;
887     ovs_mutex_unlock(&mutex);
888
889     return opup;
890 }
891
892 /* Populates 'rmps' with an array of remote maintenance points reachable by
893  * 'cfm'. The number of remote maintenance points is written to 'n_rmps'.
894  * 'cfm' retains ownership of the array written to 'rmps' */
895 void
896 cfm_get_remote_mpids(const struct cfm *cfm, uint64_t **rmps, size_t *n_rmps)
897     OVS_EXCLUDED(mutex)
898 {
899     ovs_mutex_lock(&mutex);
900     *rmps = xmemdup(cfm->rmps_array, cfm->rmps_array_len * sizeof **rmps);
901     *n_rmps = cfm->rmps_array_len;
902     ovs_mutex_unlock(&mutex);
903 }
904
905 static struct cfm *
906 cfm_find(const char *name) OVS_REQUIRES(mutex)
907 {
908     struct cfm *cfm;
909
910     HMAP_FOR_EACH_WITH_HASH (cfm, hmap_node, hash_string(name, 0), all_cfms) {
911         if (!strcmp(cfm->name, name)) {
912             return cfm;
913         }
914     }
915     return NULL;
916 }
917
918 static void
919 cfm_print_details(struct ds *ds, struct cfm *cfm) OVS_REQUIRES(mutex)
920 {
921     struct remote_mp *rmp;
922     bool extended;
923     int fault;
924
925     atomic_read(&cfm->extended, &extended);
926
927     ds_put_format(ds, "---- %s ----\n", cfm->name);
928     ds_put_format(ds, "MPID %"PRIu64":%s%s\n", cfm->mpid,
929                   extended ? " extended" : "",
930                   cfm->fault_override >= 0 ? " fault_override" : "");
931
932     fault = cfm_get_fault__(cfm);
933     if (fault) {
934         ds_put_cstr(ds, "\tfault: ");
935         ds_put_cfm_fault(ds, fault);
936         ds_put_cstr(ds, "\n");
937     }
938
939     if (cfm->health == -1) {
940         ds_put_format(ds, "\taverage health: undefined\n");
941     } else {
942         ds_put_format(ds, "\taverage health: %d\n", cfm->health);
943     }
944     ds_put_format(ds, "\topstate: %s\n", cfm->opup ? "up" : "down");
945     ds_put_format(ds, "\tremote_opstate: %s\n",
946                   cfm->remote_opup ? "up" : "down");
947     ds_put_format(ds, "\tinterval: %dms\n", cfm->ccm_interval_ms);
948     ds_put_format(ds, "\tnext CCM tx: %lldms\n",
949                   timer_msecs_until_expired(&cfm->tx_timer));
950     ds_put_format(ds, "\tnext fault check: %lldms\n",
951                   timer_msecs_until_expired(&cfm->fault_timer));
952
953     HMAP_FOR_EACH (rmp, node, &cfm->remote_mps) {
954         ds_put_format(ds, "Remote MPID %"PRIu64"\n", rmp->mpid);
955         ds_put_format(ds, "\trecv since check: %s\n",
956                       rmp->recv ? "true" : "false");
957         ds_put_format(ds, "\topstate: %s\n", rmp->opup? "up" : "down");
958     }
959 }
960
961 static void
962 cfm_unixctl_show(struct unixctl_conn *conn, int argc, const char *argv[],
963                  void *aux OVS_UNUSED) OVS_EXCLUDED(mutex)
964 {
965     struct ds ds = DS_EMPTY_INITIALIZER;
966     struct cfm *cfm;
967
968     ovs_mutex_lock(&mutex);
969     if (argc > 1) {
970         cfm = cfm_find(argv[1]);
971         if (!cfm) {
972             unixctl_command_reply_error(conn, "no such CFM object");
973             goto out;
974         }
975         cfm_print_details(&ds, cfm);
976     } else {
977         HMAP_FOR_EACH (cfm, hmap_node, all_cfms) {
978             cfm_print_details(&ds, cfm);
979         }
980     }
981
982     unixctl_command_reply(conn, ds_cstr(&ds));
983     ds_destroy(&ds);
984 out:
985     ovs_mutex_unlock(&mutex);
986 }
987
988 static void
989 cfm_unixctl_set_fault(struct unixctl_conn *conn, int argc, const char *argv[],
990                       void *aux OVS_UNUSED) OVS_EXCLUDED(mutex)
991 {
992     const char *fault_str = argv[argc - 1];
993     int fault_override;
994     struct cfm *cfm;
995
996     ovs_mutex_lock(&mutex);
997     if (!strcasecmp("true", fault_str)) {
998         fault_override = 1;
999     } else if (!strcasecmp("false", fault_str)) {
1000         fault_override = 0;
1001     } else if (!strcasecmp("normal", fault_str)) {
1002         fault_override = -1;
1003     } else {
1004         unixctl_command_reply_error(conn, "unknown fault string");
1005         goto out;
1006     }
1007
1008     if (argc > 2) {
1009         cfm = cfm_find(argv[1]);
1010         if (!cfm) {
1011             unixctl_command_reply_error(conn, "no such CFM object");
1012             goto out;
1013         }
1014         cfm->fault_override = fault_override;
1015     } else {
1016         HMAP_FOR_EACH (cfm, hmap_node, all_cfms) {
1017             cfm->fault_override = fault_override;
1018         }
1019     }
1020
1021     unixctl_command_reply(conn, "OK");
1022
1023 out:
1024     ovs_mutex_unlock(&mutex);
1025 }