unixctl: Implement quoting.
[sliver-openvswitch.git] / lib / cfm.c
1 /*
2  * Copyright (c) 2010, 2011 Nicira Networks.
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 <assert.h>
21 #include <stdint.h>
22 #include <stdlib.h>
23 #include <string.h>
24
25 #include "byte-order.h"
26 #include "dynamic-string.h"
27 #include "flow.h"
28 #include "hash.h"
29 #include "hmap.h"
30 #include "ofpbuf.h"
31 #include "packets.h"
32 #include "poll-loop.h"
33 #include "timer.h"
34 #include "timeval.h"
35 #include "unixctl.h"
36 #include "vlog.h"
37
38 VLOG_DEFINE_THIS_MODULE(cfm);
39
40 #define CFM_MAX_RMPS 256
41
42 /* Ethernet destination address of CCM packets. */
43 static const uint8_t eth_addr_ccm[6] = { 0x01, 0x80, 0xC2, 0x00, 0x00, 0x30 };
44 static const uint8_t eth_addr_ccm_x[6] = {
45     0x01, 0x23, 0x20, 0x00, 0x00, 0x30
46 };
47
48 #define ETH_TYPE_CFM 0x8902
49
50 /* A 'ccm' represents a Continuity Check Message from the 802.1ag
51  * specification.  Continuity Check Messages are broadcast periodically so that
52  * hosts can determine whom they have connectivity to.
53  *
54  * The minimum length of a CCM as specified by IEEE 802.1ag is 75 bytes.
55  * Previous versions of Open vSwitch generated 74-byte CCM messages, so we
56  * accept such messages too. */
57 #define CCM_LEN 75
58 #define CCM_ACCEPT_LEN 74
59 #define CCM_MAID_LEN 48
60 #define CCM_OPCODE 1 /* CFM message opcode meaning CCM. */
61 #define CCM_RDI_MASK 0x80
62 struct ccm {
63     uint8_t  mdlevel_version; /* MD Level and Version */
64     uint8_t  opcode;
65     uint8_t  flags;
66     uint8_t  tlv_offset;
67     ovs_be32 seq;
68     ovs_be16 mpid;
69     uint8_t  maid[CCM_MAID_LEN];
70
71     /* Defined by ITU-T Y.1731 should be zero */
72     ovs_be16 interval_ms_x;      /* Transmission interval in ms. */
73     ovs_be64 mpid64;             /* MPID in extended mode. */
74     uint8_t opdown;              /* Operationally down. */
75     uint8_t  zero[5];
76
77     /* TLV space. */
78     uint8_t end_tlv;
79 } __attribute__((packed));
80 BUILD_ASSERT_DECL(CCM_LEN == sizeof(struct ccm));
81
82 struct cfm {
83     char *name;                 /* Name of this CFM object. */
84     struct hmap_node hmap_node; /* Node in all_cfms list. */
85
86     uint64_t mpid;
87     bool extended;         /* Extended mode. */
88     bool fault;            /* Indicates connectivity fault. */
89     bool unexpected_recv;  /* Received an unexpected CCM. */
90     bool opup;             /* Operational State. */
91     bool remote_opup;      /* Remote Operational State. */
92
93     uint32_t seq;          /* The sequence number of our last CCM. */
94     uint8_t ccm_interval;  /* The CCM transmission interval. */
95     int ccm_interval_ms;   /* 'ccm_interval' in milliseconds. */
96     uint16_t ccm_vlan;     /* Vlan tag of CCM PDUs. */
97     uint8_t maid[CCM_MAID_LEN]; /* The MAID of this CFM. */
98
99     struct timer tx_timer;    /* Send CCM when expired. */
100     struct timer fault_timer; /* Check for faults when expired. */
101
102     struct hmap remote_mps;   /* Remote MPs. */
103
104     /* Result of cfm_get_remote_mpids(). Updated only during fault check to
105      * avoid flapping. */
106     uint64_t *rmps_array;     /* Cache of remote_mps. */
107     size_t rmps_array_len;    /* Number of rmps in 'rmps_array'. */
108 };
109
110 /* Remote MPs represent foreign network entities that are configured to have
111  * the same MAID as this CFM instance. */
112 struct remote_mp {
113     uint64_t mpid;         /* The Maintenance Point ID of this 'remote_mp'. */
114     struct hmap_node node; /* Node in 'remote_mps' map. */
115
116     bool recv;           /* CCM was received since last fault check. */
117     bool rdi;            /* Remote Defect Indicator. Indicates remote_mp isn't
118                             receiving CCMs that it's expecting to. */
119     bool opup;           /* Operational State. */
120 };
121
122 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
123 static struct hmap all_cfms = HMAP_INITIALIZER(&all_cfms);
124
125 static unixctl_cb_func cfm_unixctl_show;
126
127 static const uint8_t *
128 cfm_ccm_addr(const struct cfm *cfm)
129 {
130     return cfm->extended ? eth_addr_ccm_x : eth_addr_ccm;
131 }
132
133 static void
134 cfm_generate_maid(struct cfm *cfm)
135 {
136     const char *ovs_md_name = "ovs";
137     const char *ovs_ma_name = "ovs";
138     uint8_t *ma_p;
139     size_t md_len, ma_len;
140
141     memset(cfm->maid, 0, CCM_MAID_LEN);
142
143     md_len = strlen(ovs_md_name);
144     ma_len = strlen(ovs_ma_name);
145
146     assert(md_len && ma_len && md_len + ma_len + 4 <= CCM_MAID_LEN);
147
148     cfm->maid[0] = 4;                           /* MD name string format. */
149     cfm->maid[1] = md_len;                      /* MD name size. */
150     memcpy(&cfm->maid[2], ovs_md_name, md_len); /* MD name. */
151
152     ma_p = cfm->maid + 2 + md_len;
153     ma_p[0] = 2;                           /* MA name string format. */
154     ma_p[1] = ma_len;                      /* MA name size. */
155     memcpy(&ma_p[2], ovs_ma_name, ma_len); /* MA name. */
156 }
157
158 static int
159 ccm_interval_to_ms(uint8_t interval)
160 {
161     switch (interval) {
162     case 0:  NOT_REACHED(); /* Explicitly not supported by 802.1ag. */
163     case 1:  return 3;      /* Not recommended due to timer resolution. */
164     case 2:  return 10;     /* Not recommended due to timer resolution. */
165     case 3:  return 100;
166     case 4:  return 1000;
167     case 5:  return 10000;
168     case 6:  return 60000;
169     case 7:  return 600000;
170     default: NOT_REACHED(); /* Explicitly not supported by 802.1ag. */
171     }
172
173     NOT_REACHED();
174 }
175
176 static long long int
177 cfm_fault_interval(struct cfm *cfm)
178 {
179     /* According to the 802.1ag specification we should assume every other MP
180      * with the same MAID has the same transmission interval that we have.  If
181      * an MP has a different interval, cfm_process_heartbeat will register it
182      * as a fault (likely due to a configuration error).  Thus we can check all
183      * MPs at once making this quite a bit simpler.
184      *
185      * According to the specification we should check when (ccm_interval_ms *
186      * 3.5)ms have passed. */
187     return (cfm->ccm_interval_ms * 7) / 2;
188 }
189
190 static uint8_t
191 ms_to_ccm_interval(int interval_ms)
192 {
193     uint8_t i;
194
195     for (i = 7; i > 0; i--) {
196         if (ccm_interval_to_ms(i) <= interval_ms) {
197             return i;
198         }
199     }
200
201     return 1;
202 }
203
204 static uint32_t
205 hash_mpid(uint64_t mpid)
206 {
207     return hash_bytes(&mpid, sizeof mpid, 0);
208 }
209
210 static bool
211 cfm_is_valid_mpid(bool extended, uint64_t mpid)
212 {
213     /* 802.1ag specification requires MPIDs to be within the range [1, 8191].
214      * In extended mode we relax this requirement. */
215     return mpid >= 1 && (extended || mpid <= 8191);
216 }
217
218 static struct remote_mp *
219 lookup_remote_mp(const struct cfm *cfm, uint64_t mpid)
220 {
221     struct remote_mp *rmp;
222
223     HMAP_FOR_EACH_IN_BUCKET (rmp, node, hash_mpid(mpid), &cfm->remote_mps) {
224         if (rmp->mpid == mpid) {
225             return rmp;
226         }
227     }
228
229     return NULL;
230 }
231
232 void
233 cfm_init(void)
234 {
235     unixctl_command_register("cfm/show", "[interface]", 0, 1, cfm_unixctl_show,
236                              NULL);
237 }
238
239 /* Allocates a 'cfm' object called 'name'.  'cfm' should be initialized by
240  * cfm_configure() before use. */
241 struct cfm *
242 cfm_create(const char *name)
243 {
244     struct cfm *cfm;
245
246     cfm = xzalloc(sizeof *cfm);
247     cfm->name = xstrdup(name);
248     hmap_init(&cfm->remote_mps);
249     cfm_generate_maid(cfm);
250     hmap_insert(&all_cfms, &cfm->hmap_node, hash_string(cfm->name, 0));
251     cfm->remote_opup = true;
252     return cfm;
253 }
254
255 void
256 cfm_destroy(struct cfm *cfm)
257 {
258     struct remote_mp *rmp, *rmp_next;
259
260     if (!cfm) {
261         return;
262     }
263
264     HMAP_FOR_EACH_SAFE (rmp, rmp_next, node, &cfm->remote_mps) {
265         hmap_remove(&cfm->remote_mps, &rmp->node);
266         free(rmp);
267     }
268
269     hmap_destroy(&cfm->remote_mps);
270     hmap_remove(&all_cfms, &cfm->hmap_node);
271     free(cfm->rmps_array);
272     free(cfm->name);
273     free(cfm);
274 }
275
276 /* Should be run periodically to update fault statistics messages. */
277 void
278 cfm_run(struct cfm *cfm)
279 {
280     if (timer_expired(&cfm->fault_timer)) {
281         long long int interval = cfm_fault_interval(cfm);
282         struct remote_mp *rmp, *rmp_next;
283
284         cfm->fault = cfm->unexpected_recv;
285         cfm->unexpected_recv = false;
286
287         cfm->rmps_array_len = 0;
288         free(cfm->rmps_array);
289         cfm->rmps_array = xmalloc(hmap_count(&cfm->remote_mps) *
290                                   sizeof *cfm->rmps_array);
291
292         cfm->remote_opup = true;
293         HMAP_FOR_EACH_SAFE (rmp, rmp_next, node, &cfm->remote_mps) {
294
295             if (!rmp->recv) {
296                 VLOG_DBG("%s: no CCM from RMP %"PRIu64" in the last %lldms",
297                          cfm->name, rmp->mpid, interval);
298                 hmap_remove(&cfm->remote_mps, &rmp->node);
299                 free(rmp);
300             } else {
301                 rmp->recv = false;
302
303                 if (rmp->mpid == cfm->mpid) {
304                     VLOG_WARN_RL(&rl,"%s: received CCM with local MPID"
305                                  " %"PRIu64, cfm->name, rmp->mpid);
306                     cfm->fault = true;
307                 }
308
309                 if (rmp->rdi) {
310                     VLOG_DBG("%s: RDI bit flagged from RMP %"PRIu64, cfm->name,
311                              rmp->mpid);
312                     cfm->fault = true;
313                 }
314
315                 if (!rmp->opup) {
316                     cfm->remote_opup = rmp->opup;
317                 }
318
319                 cfm->rmps_array[cfm->rmps_array_len++] = rmp->mpid;
320             }
321         }
322
323         if (hmap_is_empty(&cfm->remote_mps)) {
324             cfm->fault = true;
325         }
326
327         timer_set_duration(&cfm->fault_timer, interval);
328     }
329 }
330
331 /* Should be run periodically to check if the CFM module has a CCM message it
332  * wishes to send. */
333 bool
334 cfm_should_send_ccm(struct cfm *cfm)
335 {
336     return timer_expired(&cfm->tx_timer);
337 }
338
339 /* Composes a CCM message into 'packet'.  Messages generated with this function
340  * should be sent whenever cfm_should_send_ccm() indicates. */
341 void
342 cfm_compose_ccm(struct cfm *cfm, struct ofpbuf *packet,
343                 uint8_t eth_src[ETH_ADDR_LEN])
344 {
345     struct ccm *ccm;
346
347     timer_set_duration(&cfm->tx_timer, cfm->ccm_interval_ms);
348     eth_compose(packet, cfm_ccm_addr(cfm), eth_src, ETH_TYPE_CFM, sizeof *ccm);
349
350     if (cfm->ccm_vlan) {
351         eth_push_vlan(packet, htons(cfm->ccm_vlan));
352     }
353
354     ccm = packet->l3;
355     ccm->mdlevel_version = 0;
356     ccm->opcode = CCM_OPCODE;
357     ccm->tlv_offset = 70;
358     ccm->seq = htonl(++cfm->seq);
359     ccm->flags = cfm->ccm_interval;
360     memcpy(ccm->maid, cfm->maid, sizeof ccm->maid);
361     memset(ccm->zero, 0, sizeof ccm->zero);
362     ccm->end_tlv = 0;
363
364     if (cfm->extended) {
365         ccm->mpid = htons(hash_mpid(cfm->mpid));
366         ccm->mpid64 = htonll(cfm->mpid);
367         ccm->opdown = !cfm->opup;
368     } else {
369         ccm->mpid = htons(cfm->mpid);
370         ccm->mpid64 = htonll(0);
371         ccm->opdown = 0;
372     }
373
374     if (cfm->ccm_interval == 0) {
375         assert(cfm->extended);
376         ccm->interval_ms_x = htons(cfm->ccm_interval_ms);
377     }
378
379     if (hmap_is_empty(&cfm->remote_mps)) {
380         ccm->flags |= CCM_RDI_MASK;
381     }
382 }
383
384 void
385 cfm_wait(struct cfm *cfm)
386 {
387     timer_wait(&cfm->tx_timer);
388     timer_wait(&cfm->fault_timer);
389 }
390
391 /* Configures 'cfm' with settings from 's'. */
392 bool
393 cfm_configure(struct cfm *cfm, const struct cfm_settings *s)
394 {
395     uint8_t interval;
396     int interval_ms;
397
398     if (!cfm_is_valid_mpid(s->extended, s->mpid) || s->interval <= 0) {
399         return false;
400     }
401
402     cfm->mpid = s->mpid;
403     cfm->extended = s->extended;
404     cfm->opup = s->opup;
405     interval = ms_to_ccm_interval(s->interval);
406     interval_ms = ccm_interval_to_ms(interval);
407
408     cfm->ccm_vlan = s->ccm_vlan & VLAN_VID_MASK;
409     if (cfm->extended && interval_ms != s->interval) {
410         interval = 0;
411         interval_ms = MIN(s->interval, UINT16_MAX);
412     }
413
414     if (interval != cfm->ccm_interval || interval_ms != cfm->ccm_interval_ms) {
415         cfm->ccm_interval = interval;
416         cfm->ccm_interval_ms = interval_ms;
417
418         timer_set_expired(&cfm->tx_timer);
419         timer_set_duration(&cfm->fault_timer, cfm_fault_interval(cfm));
420     }
421
422     return true;
423 }
424
425 /* Returns true if 'cfm' should process packets from 'flow'. */
426 bool
427 cfm_should_process_flow(const struct cfm *cfm, const struct flow *flow)
428 {
429     return (ntohs(flow->dl_type) == ETH_TYPE_CFM
430             && eth_addr_equals(flow->dl_dst, cfm_ccm_addr(cfm)));
431 }
432
433 /* Updates internal statistics relevant to packet 'p'.  Should be called on
434  * every packet whose flow returned true when passed to
435  * cfm_should_process_flow. */
436 void
437 cfm_process_heartbeat(struct cfm *cfm, const struct ofpbuf *p)
438 {
439     struct ccm *ccm;
440     struct eth_header *eth;
441
442     eth = p->l2;
443     ccm = ofpbuf_at(p, (uint8_t *)p->l3 - (uint8_t *)p->data, CCM_ACCEPT_LEN);
444
445     if (!ccm) {
446         VLOG_INFO_RL(&rl, "%s: Received an unparseable 802.1ag CCM heartbeat.",
447                      cfm->name);
448         return;
449     }
450
451     if (ccm->opcode != CCM_OPCODE) {
452         VLOG_INFO_RL(&rl, "%s: Received an unsupported 802.1ag message. "
453                      "(opcode %u)", cfm->name, ccm->opcode);
454         return;
455     }
456
457     /* According to the 802.1ag specification, reception of a CCM with an
458      * incorrect ccm_interval, unexpected MAID, or unexpected MPID should
459      * trigger a fault.  We ignore this requirement for several reasons.
460      *
461      * Faults can cause a controller or Open vSwitch to make potentially
462      * expensive changes to the network topology.  It seems prudent to trigger
463      * them judiciously, especially when CFM is used to check slave status of
464      * bonds. Furthermore, faults can be maliciously triggered by crafting
465      * invalid CCMs. */
466     if (memcmp(ccm->maid, cfm->maid, sizeof ccm->maid)) {
467         cfm->unexpected_recv = true;
468         VLOG_WARN_RL(&rl, "%s: Received unexpected remote MAID from MAC "
469                      ETH_ADDR_FMT, cfm->name, ETH_ADDR_ARGS(eth->eth_src));
470     } else {
471         uint8_t ccm_interval = ccm->flags & 0x7;
472         bool ccm_rdi = ccm->flags & CCM_RDI_MASK;
473         uint16_t ccm_interval_ms_x = ntohs(ccm->interval_ms_x);
474
475         struct remote_mp *rmp;
476         uint64_t ccm_mpid;
477         bool ccm_opdown;
478
479         if (cfm->extended) {
480             ccm_mpid = ntohll(ccm->mpid64);
481             ccm_opdown = ccm->opdown;
482         } else {
483             ccm_mpid = ntohs(ccm->mpid);
484             ccm_opdown = false;
485         }
486
487         if (ccm_interval != cfm->ccm_interval) {
488             VLOG_WARN_RL(&rl, "%s: received a CCM with an invalid interval"
489                          " (%"PRIu8") from RMP %"PRIu64, cfm->name,
490                          ccm_interval, ccm_mpid);
491         }
492
493         if (cfm->extended && ccm_interval == 0
494             && ccm_interval_ms_x != cfm->ccm_interval_ms) {
495             VLOG_WARN_RL(&rl, "%s: received a CCM with an invalid extended"
496                          " interval (%"PRIu16"ms) from RMP %"PRIu64, cfm->name,
497                          ccm_interval_ms_x, ccm_mpid);
498         }
499
500         rmp = lookup_remote_mp(cfm, ccm_mpid);
501         if (!rmp) {
502             if (hmap_count(&cfm->remote_mps) < CFM_MAX_RMPS) {
503                 rmp = xmalloc(sizeof *rmp);
504                 hmap_insert(&cfm->remote_mps, &rmp->node, hash_mpid(ccm_mpid));
505             } else {
506                 cfm->unexpected_recv = true;
507                 VLOG_WARN_RL(&rl,
508                              "%s: dropped CCM with MPID %"PRIu64" from MAC "
509                              ETH_ADDR_FMT, cfm->name, ccm_mpid,
510                              ETH_ADDR_ARGS(eth->eth_src));
511             }
512         }
513
514         if (rmp) {
515             rmp->mpid = ccm_mpid;
516             rmp->recv = true;
517             rmp->rdi = ccm_rdi;
518             rmp->opup = !ccm_opdown;
519         }
520
521         VLOG_DBG("%s: received CCM (seq %"PRIu32") (mpid %"PRIu64")"
522                  " (interval %"PRIu8") (RDI %s)", cfm->name, ntohl(ccm->seq),
523                  ccm_mpid, ccm_interval, ccm_rdi ? "true" : "false");
524     }
525 }
526
527 /* Gets the fault status of 'cfm'.  Returns true when 'cfm' has detected
528  * connectivity problems, false otherwise. */
529 bool
530 cfm_get_fault(const struct cfm *cfm)
531 {
532     return cfm->fault;
533 }
534
535 /* Gets the operational state of 'cfm'.  'cfm' is considered operationally down
536  * if it has received a CCM with the operationally down bit set from any of its
537  * remote maintenance points. Returns true if 'cfm' is operationally up. False
538  * otherwise. */
539 bool
540 cfm_get_opup(const struct cfm *cfm)
541 {
542     return cfm->remote_opup;
543 }
544
545 /* Populates 'rmps' with an array of remote maintenance points reachable by
546  * 'cfm'. The number of remote maintenance points is written to 'n_rmps'.
547  * 'cfm' retains ownership of the array written to 'rmps' */
548 void
549 cfm_get_remote_mpids(const struct cfm *cfm, const uint64_t **rmps,
550                      size_t *n_rmps)
551 {
552     *rmps = cfm->rmps_array;
553     *n_rmps = cfm->rmps_array_len;
554 }
555
556 static struct cfm *
557 cfm_find(const char *name)
558 {
559     struct cfm *cfm;
560
561     HMAP_FOR_EACH_WITH_HASH (cfm, hmap_node, hash_string(name, 0), &all_cfms) {
562         if (!strcmp(cfm->name, name)) {
563             return cfm;
564         }
565     }
566     return NULL;
567 }
568
569 static void
570 cfm_print_details(struct ds *ds, const struct cfm *cfm)
571 {
572     struct remote_mp *rmp;
573
574     ds_put_format(ds, "---- %s ----\n", cfm->name);
575     ds_put_format(ds, "MPID %"PRIu64":%s%s%s\n", cfm->mpid,
576                   cfm->extended ? " extended" : "",
577                   cfm->fault ? " fault" : "",
578                   cfm->unexpected_recv ? " unexpected_recv" : "");
579
580     ds_put_format(ds, "\topstate: %s\n", cfm->opup ? "up" : "down");
581     ds_put_format(ds, "\tremote_opstate: %s\n",
582                   cfm->remote_opup ? "up" : "down");
583     ds_put_format(ds, "\tinterval: %dms\n", cfm->ccm_interval_ms);
584     ds_put_format(ds, "\tnext CCM tx: %lldms\n",
585                   timer_msecs_until_expired(&cfm->tx_timer));
586     ds_put_format(ds, "\tnext fault check: %lldms\n",
587                   timer_msecs_until_expired(&cfm->fault_timer));
588
589     HMAP_FOR_EACH (rmp, node, &cfm->remote_mps) {
590         ds_put_format(ds, "Remote MPID %"PRIu64":%s\n",
591                       rmp->mpid,
592                       rmp->rdi ? " rdi" : "");
593         ds_put_format(ds, "\trecv since check: %s\n",
594                       rmp->recv ? "true" : "false");
595         ds_put_format(ds, "\topstate: %s\n", rmp->opup? "up" : "down");
596     }
597 }
598
599 static void
600 cfm_unixctl_show(struct unixctl_conn *conn, int argc, const char *argv[],
601                  void *aux OVS_UNUSED)
602 {
603     struct ds ds = DS_EMPTY_INITIALIZER;
604     const struct cfm *cfm;
605
606     if (argc > 1) {
607         cfm = cfm_find(argv[1]);
608         if (!cfm) {
609             unixctl_command_reply(conn, 501, "no such CFM object");
610             return;
611         }
612         cfm_print_details(&ds, cfm);
613     } else {
614         HMAP_FOR_EACH (cfm, hmap_node, &all_cfms) {
615             cfm_print_details(&ds, cfm);
616         }
617     }
618
619     unixctl_command_reply(conn, 200, ds_cstr(&ds));
620     ds_destroy(&ds);
621 }