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