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