Replace most uses of assert by ovs_assert.
[sliver-openvswitch.git] / lib / rconn.c
1 /*
2  * Copyright (c) 2008, 2009, 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 "rconn.h"
19 #include <errno.h>
20 #include <limits.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include "coverage.h"
24 #include "ofp-msgs.h"
25 #include "ofp-util.h"
26 #include "ofpbuf.h"
27 #include "openflow/openflow.h"
28 #include "poll-loop.h"
29 #include "sat-math.h"
30 #include "timeval.h"
31 #include "util.h"
32 #include "vconn.h"
33 #include "vlog.h"
34
35 VLOG_DEFINE_THIS_MODULE(rconn);
36
37 COVERAGE_DEFINE(rconn_discarded);
38 COVERAGE_DEFINE(rconn_overflow);
39 COVERAGE_DEFINE(rconn_queued);
40 COVERAGE_DEFINE(rconn_sent);
41
42 #define STATES                                  \
43     STATE(VOID, 1 << 0)                         \
44     STATE(BACKOFF, 1 << 1)                      \
45     STATE(CONNECTING, 1 << 2)                   \
46     STATE(ACTIVE, 1 << 3)                       \
47     STATE(IDLE, 1 << 4)
48 enum state {
49 #define STATE(NAME, VALUE) S_##NAME = VALUE,
50     STATES
51 #undef STATE
52 };
53
54 static const char *
55 state_name(enum state state)
56 {
57     switch (state) {
58 #define STATE(NAME, VALUE) case S_##NAME: return #NAME;
59         STATES
60 #undef STATE
61     }
62     return "***ERROR***";
63 }
64
65 /* A reliable connection to an OpenFlow switch or controller.
66  *
67  * See the large comment in rconn.h for more information. */
68 struct rconn {
69     enum state state;
70     time_t state_entered;
71
72     struct vconn *vconn;
73     char *name;                 /* Human-readable descriptive name. */
74     char *target;               /* vconn name, passed to vconn_open(). */
75     bool reliable;
76
77     struct list txq;            /* Contains "struct ofpbuf"s. */
78
79     int backoff;
80     int max_backoff;
81     time_t backoff_deadline;
82     time_t last_connected;
83     time_t last_disconnected;
84     unsigned int packets_sent;
85     unsigned int seqno;
86     int last_error;
87
88     /* In S_ACTIVE and S_IDLE, probably_admitted reports whether we believe
89      * that the peer has made a (positive) admission control decision on our
90      * connection.  If we have not yet been (probably) admitted, then the
91      * connection does not reset the timer used for deciding whether the switch
92      * should go into fail-open mode.
93      *
94      * last_admitted reports the last time we believe such a positive admission
95      * control decision was made. */
96     bool probably_admitted;
97     time_t last_admitted;
98
99     /* These values are simply for statistics reporting, not used directly by
100      * anything internal to the rconn (or ofproto for that matter). */
101     unsigned int packets_received;
102     unsigned int n_attempted_connections, n_successful_connections;
103     time_t creation_time;
104     unsigned long int total_time_connected;
105
106     /* Throughout this file, "probe" is shorthand for "inactivity probe".  When
107      * no activity has been observed from the peer for a while, we send out an
108      * echo request as an inactivity probe packet.  We should receive back a
109      * response.
110      *
111      * "Activity" is defined as either receiving an OpenFlow message from the
112      * peer or successfully sending a message that had been in 'txq'. */
113     int probe_interval;         /* Secs of inactivity before sending probe. */
114     time_t last_activity;       /* Last time we saw some activity. */
115
116     /* When we create a vconn we obtain these values, to save them past the end
117      * of the vconn's lifetime.  Otherwise, in-band control will only allow
118      * traffic when a vconn is actually open, but it is nice to allow ARP to
119      * complete even between connection attempts, and it is also polite to
120      * allow traffic from other switches to go through to the controller
121      * whether or not we are connected.
122      *
123      * We don't cache the local port, because that changes from one connection
124      * attempt to the next. */
125     ovs_be32 local_ip, remote_ip;
126     ovs_be16 remote_port;
127     uint8_t dscp;
128
129     /* Messages sent or received are copied to the monitor connections. */
130 #define MAX_MONITORS 8
131     struct vconn *monitors[8];
132     size_t n_monitors;
133
134     uint32_t allowed_versions;
135 };
136
137 uint32_t rconn_get_allowed_versions(const struct rconn *rconn)
138 {
139     return rconn->allowed_versions;
140 }
141
142 static unsigned int elapsed_in_this_state(const struct rconn *);
143 static unsigned int timeout(const struct rconn *);
144 static bool timed_out(const struct rconn *);
145 static void state_transition(struct rconn *, enum state);
146 static void rconn_set_target__(struct rconn *,
147                                const char *target, const char *name);
148 static int try_send(struct rconn *);
149 static void reconnect(struct rconn *);
150 static void report_error(struct rconn *, int error);
151 static void disconnect(struct rconn *, int error);
152 static void flush_queue(struct rconn *);
153 static void copy_to_monitor(struct rconn *, const struct ofpbuf *);
154 static bool is_connected_state(enum state);
155 static bool is_admitted_msg(const struct ofpbuf *);
156 static bool rconn_logging_connection_attempts__(const struct rconn *);
157
158 /* Creates and returns a new rconn.
159  *
160  * 'probe_interval' is a number of seconds.  If the interval passes once
161  * without an OpenFlow message being received from the peer, the rconn sends
162  * out an "echo request" message.  If the interval passes again without a
163  * message being received, the rconn disconnects and re-connects to the peer.
164  * Setting 'probe_interval' to 0 disables this behavior.
165  *
166  * 'max_backoff' is the maximum number of seconds between attempts to connect
167  * to the peer.  The actual interval starts at 1 second and doubles on each
168  * failure until it reaches 'max_backoff'.  If 0 is specified, the default of
169  * 8 seconds is used.
170  *
171  * The new rconn is initially unconnected.  Use rconn_connect() or
172  * rconn_connect_unreliably() to connect it.
173  *
174  * Connections made by the rconn will automatically negotiate an OpenFlow
175  * protocol version acceptable to both peers on the connection.  The version
176  * negotiated will be one of those in the 'allowed_versions' bitmap: version
177  * 'x' is allowed if allowed_versions & (1 << x) is nonzero.  (The underlying
178  * vconn will treat an 'allowed_versions' of 0 as OFPUTIL_DEFAULT_VERSIONS.)
179  */
180 struct rconn *
181 rconn_create(int probe_interval, int max_backoff, uint8_t dscp,
182              uint32_t allowed_versions)
183 {
184     struct rconn *rc = xzalloc(sizeof *rc);
185
186     rc->state = S_VOID;
187     rc->state_entered = time_now();
188
189     rc->vconn = NULL;
190     rc->name = xstrdup("void");
191     rc->target = xstrdup("void");
192     rc->reliable = false;
193
194     list_init(&rc->txq);
195
196     rc->backoff = 0;
197     rc->max_backoff = max_backoff ? max_backoff : 8;
198     rc->backoff_deadline = TIME_MIN;
199     rc->last_connected = TIME_MIN;
200     rc->last_disconnected = TIME_MIN;
201     rc->seqno = 0;
202
203     rc->packets_sent = 0;
204
205     rc->probably_admitted = false;
206     rc->last_admitted = time_now();
207
208     rc->packets_received = 0;
209     rc->n_attempted_connections = 0;
210     rc->n_successful_connections = 0;
211     rc->creation_time = time_now();
212     rc->total_time_connected = 0;
213
214     rc->last_activity = time_now();
215
216     rconn_set_probe_interval(rc, probe_interval);
217     rconn_set_dscp(rc, dscp);
218
219     rc->n_monitors = 0;
220     rc->allowed_versions = allowed_versions;
221
222     return rc;
223 }
224
225 void
226 rconn_set_max_backoff(struct rconn *rc, int max_backoff)
227 {
228     rc->max_backoff = MAX(1, max_backoff);
229     if (rc->state == S_BACKOFF && rc->backoff > max_backoff) {
230         rc->backoff = max_backoff;
231         if (rc->backoff_deadline > time_now() + max_backoff) {
232             rc->backoff_deadline = time_now() + max_backoff;
233         }
234     }
235 }
236
237 int
238 rconn_get_max_backoff(const struct rconn *rc)
239 {
240     return rc->max_backoff;
241 }
242
243 void
244 rconn_set_dscp(struct rconn *rc, uint8_t dscp)
245 {
246     rc->dscp = dscp;
247 }
248
249 uint8_t
250 rconn_get_dscp(const struct rconn *rc)
251 {
252     return rc->dscp;
253 }
254
255 void
256 rconn_set_probe_interval(struct rconn *rc, int probe_interval)
257 {
258     rc->probe_interval = probe_interval ? MAX(5, probe_interval) : 0;
259 }
260
261 int
262 rconn_get_probe_interval(const struct rconn *rc)
263 {
264     return rc->probe_interval;
265 }
266
267 /* Drops any existing connection on 'rc', then sets up 'rc' to connect to
268  * 'target' and reconnect as needed.  'target' should be a remote OpenFlow
269  * target in a form acceptable to vconn_open().
270  *
271  * If 'name' is nonnull, then it is used in log messages in place of 'target'.
272  * It should presumably give more information to a human reader than 'target',
273  * but it need not be acceptable to vconn_open(). */
274 void
275 rconn_connect(struct rconn *rc, const char *target, const char *name)
276 {
277     rconn_disconnect(rc);
278     rconn_set_target__(rc, target, name);
279     rc->reliable = true;
280     reconnect(rc);
281 }
282
283 /* Drops any existing connection on 'rc', then configures 'rc' to use
284  * 'vconn'.  If the connection on 'vconn' drops, 'rc' will not reconnect on it
285  * own.
286  *
287  * By default, the target obtained from vconn_get_name(vconn) is used in log
288  * messages.  If 'name' is nonnull, then it is used instead.  It should
289  * presumably give more information to a human reader than the target, but it
290  * need not be acceptable to vconn_open(). */
291 void
292 rconn_connect_unreliably(struct rconn *rc,
293                          struct vconn *vconn, const char *name)
294 {
295     ovs_assert(vconn != NULL);
296     rconn_disconnect(rc);
297     rconn_set_target__(rc, vconn_get_name(vconn), name);
298     rc->reliable = false;
299     rc->vconn = vconn;
300     rc->last_connected = time_now();
301     state_transition(rc, S_ACTIVE);
302 }
303
304 /* If 'rc' is connected, forces it to drop the connection and reconnect. */
305 void
306 rconn_reconnect(struct rconn *rc)
307 {
308     if (rc->state & (S_ACTIVE | S_IDLE)) {
309         VLOG_INFO("%s: disconnecting", rc->name);
310         disconnect(rc, 0);
311     }
312 }
313
314 void
315 rconn_disconnect(struct rconn *rc)
316 {
317     if (rc->state != S_VOID) {
318         if (rc->vconn) {
319             vconn_close(rc->vconn);
320             rc->vconn = NULL;
321         }
322         rconn_set_target__(rc, "void", NULL);
323         rc->reliable = false;
324
325         rc->backoff = 0;
326         rc->backoff_deadline = TIME_MIN;
327
328         state_transition(rc, S_VOID);
329     }
330 }
331
332 /* Disconnects 'rc' and frees the underlying storage. */
333 void
334 rconn_destroy(struct rconn *rc)
335 {
336     if (rc) {
337         size_t i;
338
339         free(rc->name);
340         free(rc->target);
341         vconn_close(rc->vconn);
342         flush_queue(rc);
343         ofpbuf_list_delete(&rc->txq);
344         for (i = 0; i < rc->n_monitors; i++) {
345             vconn_close(rc->monitors[i]);
346         }
347         free(rc);
348     }
349 }
350
351 static unsigned int
352 timeout_VOID(const struct rconn *rc OVS_UNUSED)
353 {
354     return UINT_MAX;
355 }
356
357 static void
358 run_VOID(struct rconn *rc OVS_UNUSED)
359 {
360     /* Nothing to do. */
361 }
362
363 static void
364 reconnect(struct rconn *rc)
365 {
366     int retval;
367
368     if (rconn_logging_connection_attempts__(rc)) {
369         VLOG_INFO("%s: connecting...", rc->name);
370     }
371     rc->n_attempted_connections++;
372     retval = vconn_open(rc->target, rc->allowed_versions, rc->dscp,
373                         &rc->vconn);
374     if (!retval) {
375         rc->remote_ip = vconn_get_remote_ip(rc->vconn);
376         rc->local_ip = vconn_get_local_ip(rc->vconn);
377         rc->remote_port = vconn_get_remote_port(rc->vconn);
378         rc->backoff_deadline = time_now() + rc->backoff;
379         state_transition(rc, S_CONNECTING);
380     } else {
381         VLOG_WARN("%s: connection failed (%s)", rc->name, strerror(retval));
382         rc->backoff_deadline = TIME_MAX; /* Prevent resetting backoff. */
383         disconnect(rc, retval);
384     }
385 }
386
387 static unsigned int
388 timeout_BACKOFF(const struct rconn *rc)
389 {
390     return rc->backoff;
391 }
392
393 static void
394 run_BACKOFF(struct rconn *rc)
395 {
396     if (timed_out(rc)) {
397         reconnect(rc);
398     }
399 }
400
401 static unsigned int
402 timeout_CONNECTING(const struct rconn *rc)
403 {
404     return MAX(1, rc->backoff);
405 }
406
407 static void
408 run_CONNECTING(struct rconn *rc)
409 {
410     int retval = vconn_connect(rc->vconn);
411     if (!retval) {
412         VLOG_INFO("%s: connected", rc->name);
413         rc->n_successful_connections++;
414         state_transition(rc, S_ACTIVE);
415         rc->last_connected = rc->state_entered;
416     } else if (retval != EAGAIN) {
417         if (rconn_logging_connection_attempts__(rc)) {
418             VLOG_INFO("%s: connection failed (%s)",
419                       rc->name, strerror(retval));
420         }
421         disconnect(rc, retval);
422     } else if (timed_out(rc)) {
423         if (rconn_logging_connection_attempts__(rc)) {
424             VLOG_INFO("%s: connection timed out", rc->name);
425         }
426         rc->backoff_deadline = TIME_MAX; /* Prevent resetting backoff. */
427         disconnect(rc, ETIMEDOUT);
428     }
429 }
430
431 static void
432 do_tx_work(struct rconn *rc)
433 {
434     if (list_is_empty(&rc->txq)) {
435         return;
436     }
437     while (!list_is_empty(&rc->txq)) {
438         int error = try_send(rc);
439         if (error) {
440             break;
441         }
442         rc->last_activity = time_now();
443     }
444     if (list_is_empty(&rc->txq)) {
445         poll_immediate_wake();
446     }
447 }
448
449 static unsigned int
450 timeout_ACTIVE(const struct rconn *rc)
451 {
452     if (rc->probe_interval) {
453         unsigned int base = MAX(rc->last_activity, rc->state_entered);
454         unsigned int arg = base + rc->probe_interval - rc->state_entered;
455         return arg;
456     }
457     return UINT_MAX;
458 }
459
460 static void
461 run_ACTIVE(struct rconn *rc)
462 {
463     if (timed_out(rc)) {
464         unsigned int base = MAX(rc->last_activity, rc->state_entered);
465         int version;
466
467         VLOG_DBG("%s: idle %u seconds, sending inactivity probe",
468                  rc->name, (unsigned int) (time_now() - base));
469
470         version = rconn_get_version(rc);
471         ovs_assert(version >= 0 && version <= 0xff);
472
473         /* Ordering is important here: rconn_send() can transition to BACKOFF,
474          * and we don't want to transition back to IDLE if so, because then we
475          * can end up queuing a packet with vconn == NULL and then *boom*. */
476         state_transition(rc, S_IDLE);
477         rconn_send(rc, make_echo_request(version), NULL);
478         return;
479     }
480
481     do_tx_work(rc);
482 }
483
484 static unsigned int
485 timeout_IDLE(const struct rconn *rc)
486 {
487     return rc->probe_interval;
488 }
489
490 static void
491 run_IDLE(struct rconn *rc)
492 {
493     if (timed_out(rc)) {
494         VLOG_ERR("%s: no response to inactivity probe after %u "
495                  "seconds, disconnecting",
496                  rc->name, elapsed_in_this_state(rc));
497         disconnect(rc, ETIMEDOUT);
498     } else {
499         do_tx_work(rc);
500     }
501 }
502
503 /* Performs whatever activities are necessary to maintain 'rc': if 'rc' is
504  * disconnected, attempts to (re)connect, backing off as necessary; if 'rc' is
505  * connected, attempts to send packets in the send queue, if any. */
506 void
507 rconn_run(struct rconn *rc)
508 {
509     int old_state;
510     size_t i;
511
512     if (rc->vconn) {
513         vconn_run(rc->vconn);
514     }
515     for (i = 0; i < rc->n_monitors; i++) {
516         vconn_run(rc->monitors[i]);
517     }
518
519     do {
520         old_state = rc->state;
521         switch (rc->state) {
522 #define STATE(NAME, VALUE) case S_##NAME: run_##NAME(rc); break;
523             STATES
524 #undef STATE
525         default:
526             NOT_REACHED();
527         }
528     } while (rc->state != old_state);
529 }
530
531 /* Causes the next call to poll_block() to wake up when rconn_run() should be
532  * called on 'rc'. */
533 void
534 rconn_run_wait(struct rconn *rc)
535 {
536     unsigned int timeo;
537     size_t i;
538
539     if (rc->vconn) {
540         vconn_run_wait(rc->vconn);
541         if ((rc->state & (S_ACTIVE | S_IDLE)) && !list_is_empty(&rc->txq)) {
542             vconn_wait(rc->vconn, WAIT_SEND);
543         }
544     }
545     for (i = 0; i < rc->n_monitors; i++) {
546         vconn_run_wait(rc->monitors[i]);
547     }
548
549     timeo = timeout(rc);
550     if (timeo != UINT_MAX) {
551         long long int expires = sat_add(rc->state_entered, timeo);
552         poll_timer_wait_until(expires * 1000);
553     }
554 }
555
556 /* Attempts to receive a packet from 'rc'.  If successful, returns the packet;
557  * otherwise, returns a null pointer.  The caller is responsible for freeing
558  * the packet (with ofpbuf_delete()). */
559 struct ofpbuf *
560 rconn_recv(struct rconn *rc)
561 {
562     if (rc->state & (S_ACTIVE | S_IDLE)) {
563         struct ofpbuf *buffer;
564         int error = vconn_recv(rc->vconn, &buffer);
565         if (!error) {
566             copy_to_monitor(rc, buffer);
567             if (rc->probably_admitted || is_admitted_msg(buffer)
568                 || time_now() - rc->last_connected >= 30) {
569                 rc->probably_admitted = true;
570                 rc->last_admitted = time_now();
571             }
572             rc->last_activity = time_now();
573             rc->packets_received++;
574             if (rc->state == S_IDLE) {
575                 state_transition(rc, S_ACTIVE);
576             }
577             return buffer;
578         } else if (error != EAGAIN) {
579             report_error(rc, error);
580             disconnect(rc, error);
581         }
582     }
583     return NULL;
584 }
585
586 /* Causes the next call to poll_block() to wake up when a packet may be ready
587  * to be received by vconn_recv() on 'rc'.  */
588 void
589 rconn_recv_wait(struct rconn *rc)
590 {
591     if (rc->vconn) {
592         vconn_wait(rc->vconn, WAIT_RECV);
593     }
594 }
595
596 /* Sends 'b' on 'rc'.  Returns 0 if successful, or ENOTCONN if 'rc' is not
597  * currently connected.  Takes ownership of 'b'.
598  *
599  * If 'counter' is non-null, then 'counter' will be incremented while the
600  * packet is in flight, then decremented when it has been sent (or discarded
601  * due to disconnection).  Because 'b' may be sent (or discarded) before this
602  * function returns, the caller may not be able to observe any change in
603  * 'counter'.
604  *
605  * There is no rconn_send_wait() function: an rconn has a send queue that it
606  * takes care of sending if you call rconn_run(), which will have the side
607  * effect of waking up poll_block(). */
608 int
609 rconn_send(struct rconn *rc, struct ofpbuf *b,
610            struct rconn_packet_counter *counter)
611 {
612     if (rconn_is_connected(rc)) {
613         COVERAGE_INC(rconn_queued);
614         copy_to_monitor(rc, b);
615         b->private_p = counter;
616         if (counter) {
617             rconn_packet_counter_inc(counter, b->size);
618         }
619         list_push_back(&rc->txq, &b->list_node);
620
621         /* If the queue was empty before we added 'b', try to send some
622          * packets.  (But if the queue had packets in it, it's because the
623          * vconn is backlogged and there's no point in stuffing more into it
624          * now.  We'll get back to that in rconn_run().) */
625         if (rc->txq.next == &b->list_node) {
626             try_send(rc);
627         }
628         return 0;
629     } else {
630         ofpbuf_delete(b);
631         return ENOTCONN;
632     }
633 }
634
635 /* Sends 'b' on 'rc'.  Increments 'counter' while the packet is in flight; it
636  * will be decremented when it has been sent (or discarded due to
637  * disconnection).  Returns 0 if successful, EAGAIN if 'counter->n' is already
638  * at least as large as 'queue_limit', or ENOTCONN if 'rc' is not currently
639  * connected.  Regardless of return value, 'b' is destroyed.
640  *
641  * Because 'b' may be sent (or discarded) before this function returns, the
642  * caller may not be able to observe any change in 'counter'.
643  *
644  * There is no rconn_send_wait() function: an rconn has a send queue that it
645  * takes care of sending if you call rconn_run(), which will have the side
646  * effect of waking up poll_block(). */
647 int
648 rconn_send_with_limit(struct rconn *rc, struct ofpbuf *b,
649                       struct rconn_packet_counter *counter, int queue_limit)
650 {
651     if (counter->n_packets < queue_limit) {
652         return rconn_send(rc, b, counter);
653     } else {
654         COVERAGE_INC(rconn_overflow);
655         ofpbuf_delete(b);
656         return EAGAIN;
657     }
658 }
659
660 /* Returns the total number of packets successfully sent on the underlying
661  * vconn.  A packet is not counted as sent while it is still queued in the
662  * rconn, only when it has been successfuly passed to the vconn.  */
663 unsigned int
664 rconn_packets_sent(const struct rconn *rc)
665 {
666     return rc->packets_sent;
667 }
668
669 /* Adds 'vconn' to 'rc' as a monitoring connection, to which all messages sent
670  * and received on 'rconn' will be copied.  'rc' takes ownership of 'vconn'. */
671 void
672 rconn_add_monitor(struct rconn *rc, struct vconn *vconn)
673 {
674     if (rc->n_monitors < ARRAY_SIZE(rc->monitors)) {
675         int version = vconn_get_version(rc->vconn);
676
677         /* Override the allowed versions of the snoop vconn so that
678          * only the version of the controller connection is allowed.
679          * This is because the snoop will see the same messages as the
680          * controller */
681         vconn_set_allowed_versions(vconn, 1u << version);
682
683         VLOG_INFO("new monitor connection from %s", vconn_get_name(vconn));
684         rc->monitors[rc->n_monitors++] = vconn;
685     } else {
686         VLOG_DBG("too many monitor connections, discarding %s",
687                  vconn_get_name(vconn));
688         vconn_close(vconn);
689     }
690 }
691
692 /* Returns 'rc''s name.  This is a name for human consumption, appropriate for
693  * use in log messages.  It is not necessarily a name that may be passed
694  * directly to, e.g., vconn_open(). */
695 const char *
696 rconn_get_name(const struct rconn *rc)
697 {
698     return rc->name;
699 }
700
701 /* Sets 'rc''s name to 'new_name'. */
702 void
703 rconn_set_name(struct rconn *rc, const char *new_name)
704 {
705     free(rc->name);
706     rc->name = xstrdup(new_name);
707 }
708
709 /* Returns 'rc''s target.  This is intended to be a string that may be passed
710  * directly to, e.g., vconn_open(). */
711 const char *
712 rconn_get_target(const struct rconn *rc)
713 {
714     return rc->target;
715 }
716
717 /* Returns true if 'rconn' is connected or in the process of reconnecting,
718  * false if 'rconn' is disconnected and will not reconnect on its own. */
719 bool
720 rconn_is_alive(const struct rconn *rconn)
721 {
722     return rconn->state != S_VOID;
723 }
724
725 /* Returns true if 'rconn' is connected, false otherwise. */
726 bool
727 rconn_is_connected(const struct rconn *rconn)
728 {
729     return is_connected_state(rconn->state);
730 }
731
732 /* Returns true if 'rconn' is connected and thought to have been accepted by
733  * the peer's admission-control policy. */
734 bool
735 rconn_is_admitted(const struct rconn *rconn)
736 {
737     return (rconn_is_connected(rconn)
738             && rconn->last_admitted >= rconn->last_connected);
739 }
740
741 /* Returns 0 if 'rconn' is currently connected and considered to have been
742  * accepted by the peer's admission-control policy, otherwise the number of
743  * seconds since 'rconn' was last in such a state. */
744 int
745 rconn_failure_duration(const struct rconn *rconn)
746 {
747     return rconn_is_admitted(rconn) ? 0 : time_now() - rconn->last_admitted;
748 }
749
750 /* Returns the IP address of the peer, or 0 if the peer's IP address is not
751  * known. */
752 ovs_be32
753 rconn_get_remote_ip(const struct rconn *rconn)
754 {
755     return rconn->remote_ip;
756 }
757
758 /* Returns the transport port of the peer, or 0 if the peer's port is not
759  * known. */
760 ovs_be16
761 rconn_get_remote_port(const struct rconn *rconn)
762 {
763     return rconn->remote_port;
764 }
765
766 /* Returns the IP address used to connect to the peer, or 0 if the
767  * connection is not an IP-based protocol or if its IP address is not
768  * known. */
769 ovs_be32
770 rconn_get_local_ip(const struct rconn *rconn)
771 {
772     return rconn->local_ip;
773 }
774
775 /* Returns the transport port used to connect to the peer, or 0 if the
776  * connection does not contain a port or if the port is not known. */
777 ovs_be16
778 rconn_get_local_port(const struct rconn *rconn)
779 {
780     return rconn->vconn ? vconn_get_local_port(rconn->vconn) : 0;
781 }
782
783 /* Returns the OpenFlow version negotiated with the peer, or -1 if there is
784  * currently no connection or if version negotiation is not yet complete. */
785 int
786 rconn_get_version(const struct rconn *rconn)
787 {
788     return rconn->vconn ? vconn_get_version(rconn->vconn) : -1;
789 }
790
791 /* Returns the total number of packets successfully received by the underlying
792  * vconn.  */
793 unsigned int
794 rconn_packets_received(const struct rconn *rc)
795 {
796     return rc->packets_received;
797 }
798
799 /* Returns a string representing the internal state of 'rc'.  The caller must
800  * not modify or free the string. */
801 const char *
802 rconn_get_state(const struct rconn *rc)
803 {
804     return state_name(rc->state);
805 }
806
807 /* Returns the time at which the last successful connection was made by
808  * 'rc'. Returns TIME_MIN if never connected. */
809 time_t
810 rconn_get_last_connection(const struct rconn *rc)
811 {
812     return rc->last_connected;
813 }
814
815 /* Returns the time at which 'rc' was last disconnected. Returns TIME_MIN
816  * if never disconnected. */
817 time_t
818 rconn_get_last_disconnect(const struct rconn *rc)
819 {
820     return rc->last_disconnected;
821 }
822
823 /* Returns 'rc''s current connection sequence number, a number that changes
824  * every time that 'rconn' connects or disconnects. */
825 unsigned int
826 rconn_get_connection_seqno(const struct rconn *rc)
827 {
828     return rc->seqno;
829 }
830
831 /* Returns a value that explains why 'rc' last disconnected:
832  *
833  *   - 0 means that the last disconnection was caused by a call to
834  *     rconn_disconnect(), or that 'rc' is new and has not yet completed its
835  *     initial connection or connection attempt.
836  *
837  *   - EOF means that the connection was closed in the normal way by the peer.
838  *
839  *   - A positive integer is an errno value that represents the error.
840  */
841 int
842 rconn_get_last_error(const struct rconn *rc)
843 {
844     return rc->last_error;
845 }
846
847 /* Returns the number of messages queued for transmission on 'rc'. */
848 unsigned int
849 rconn_count_txqlen(const struct rconn *rc)
850 {
851     return list_size(&rc->txq);
852 }
853 \f
854 struct rconn_packet_counter *
855 rconn_packet_counter_create(void)
856 {
857     struct rconn_packet_counter *c = xzalloc(sizeof *c);
858     c->ref_cnt = 1;
859     return c;
860 }
861
862 void
863 rconn_packet_counter_destroy(struct rconn_packet_counter *c)
864 {
865     if (c) {
866         ovs_assert(c->ref_cnt > 0);
867         if (!--c->ref_cnt && !c->n_packets) {
868             free(c);
869         }
870     }
871 }
872
873 void
874 rconn_packet_counter_inc(struct rconn_packet_counter *c, unsigned int n_bytes)
875 {
876     c->n_packets++;
877     c->n_bytes += n_bytes;
878 }
879
880 void
881 rconn_packet_counter_dec(struct rconn_packet_counter *c, unsigned int n_bytes)
882 {
883     ovs_assert(c->n_packets > 0);
884     ovs_assert(c->n_bytes >= n_bytes);
885
886     c->n_bytes -= n_bytes;
887     c->n_packets--;
888     if (!c->n_packets) {
889         ovs_assert(!c->n_bytes);
890         if (!c->ref_cnt) {
891             free(c);
892         }
893     }
894 }
895 \f
896 /* Set rc->target and rc->name to 'target' and 'name', respectively.  If 'name'
897  * is null, 'target' is used.
898  *
899  * Also, clear out the cached IP address and port information, since changing
900  * the target also likely changes these values. */
901 static void
902 rconn_set_target__(struct rconn *rc, const char *target, const char *name)
903 {
904     free(rc->name);
905     rc->name = xstrdup(name ? name : target);
906     free(rc->target);
907     rc->target = xstrdup(target);
908     rc->local_ip = 0;
909     rc->remote_ip = 0;
910     rc->remote_port = 0;
911 }
912
913 /* Tries to send a packet from 'rc''s send buffer.  Returns 0 if successful,
914  * otherwise a positive errno value. */
915 static int
916 try_send(struct rconn *rc)
917 {
918     struct ofpbuf *msg = ofpbuf_from_list(rc->txq.next);
919     unsigned int n_bytes = msg->size;
920     struct rconn_packet_counter *counter = msg->private_p;
921     int retval;
922
923     /* Eagerly remove 'msg' from the txq.  We can't remove it from the list
924      * after sending, if sending is successful, because it is then owned by the
925      * vconn, which might have freed it already. */
926     list_remove(&msg->list_node);
927
928     retval = vconn_send(rc->vconn, msg);
929     if (retval) {
930         list_push_front(&rc->txq, &msg->list_node);
931         if (retval != EAGAIN) {
932             report_error(rc, retval);
933             disconnect(rc, retval);
934         }
935         return retval;
936     }
937     COVERAGE_INC(rconn_sent);
938     rc->packets_sent++;
939     if (counter) {
940         rconn_packet_counter_dec(counter, n_bytes);
941     }
942     return 0;
943 }
944
945 /* Reports that 'error' caused 'rc' to disconnect.  'error' may be a positive
946  * errno value, or it may be EOF to indicate that the connection was closed
947  * normally. */
948 static void
949 report_error(struct rconn *rc, int error)
950 {
951     if (error == EOF) {
952         /* If 'rc' isn't reliable, then we don't really expect this connection
953          * to last forever anyway (probably it's a connection that we received
954          * via accept()), so use DBG level to avoid cluttering the logs. */
955         enum vlog_level level = rc->reliable ? VLL_INFO : VLL_DBG;
956         VLOG(level, "%s: connection closed by peer", rc->name);
957     } else {
958         VLOG_WARN("%s: connection dropped (%s)", rc->name, strerror(error));
959     }
960 }
961
962 /* Disconnects 'rc' and records 'error' as the error that caused 'rc''s last
963  * disconnection:
964  *
965  *   - 0 means that this disconnection is due to a request by 'rc''s client,
966  *     not due to any kind of network error.
967  *
968  *   - EOF means that the connection was closed in the normal way by the peer.
969  *
970  *   - A positive integer is an errno value that represents the error.
971  */
972 static void
973 disconnect(struct rconn *rc, int error)
974 {
975     rc->last_error = error;
976     if (rc->reliable) {
977         time_t now = time_now();
978
979         if (rc->state & (S_CONNECTING | S_ACTIVE | S_IDLE)) {
980             rc->last_disconnected = now;
981             vconn_close(rc->vconn);
982             rc->vconn = NULL;
983             flush_queue(rc);
984         }
985
986         if (now >= rc->backoff_deadline) {
987             rc->backoff = 1;
988         } else if (rc->backoff < rc->max_backoff / 2) {
989             rc->backoff = MAX(1, 2 * rc->backoff);
990             VLOG_INFO("%s: waiting %d seconds before reconnect",
991                       rc->name, rc->backoff);
992         } else {
993             if (rconn_logging_connection_attempts__(rc)) {
994                 VLOG_INFO("%s: continuing to retry connections in the "
995                           "background but suppressing further logging",
996                           rc->name);
997             }
998             rc->backoff = rc->max_backoff;
999         }
1000         rc->backoff_deadline = now + rc->backoff;
1001         state_transition(rc, S_BACKOFF);
1002     } else {
1003         rc->last_disconnected = time_now();
1004         rconn_disconnect(rc);
1005     }
1006 }
1007
1008 /* Drops all the packets from 'rc''s send queue and decrements their queue
1009  * counts. */
1010 static void
1011 flush_queue(struct rconn *rc)
1012 {
1013     if (list_is_empty(&rc->txq)) {
1014         return;
1015     }
1016     while (!list_is_empty(&rc->txq)) {
1017         struct ofpbuf *b = ofpbuf_from_list(list_pop_front(&rc->txq));
1018         struct rconn_packet_counter *counter = b->private_p;
1019         if (counter) {
1020             rconn_packet_counter_dec(counter, b->size);
1021         }
1022         COVERAGE_INC(rconn_discarded);
1023         ofpbuf_delete(b);
1024     }
1025     poll_immediate_wake();
1026 }
1027
1028 static unsigned int
1029 elapsed_in_this_state(const struct rconn *rc)
1030 {
1031     return time_now() - rc->state_entered;
1032 }
1033
1034 static unsigned int
1035 timeout(const struct rconn *rc)
1036 {
1037     switch (rc->state) {
1038 #define STATE(NAME, VALUE) case S_##NAME: return timeout_##NAME(rc);
1039         STATES
1040 #undef STATE
1041     default:
1042         NOT_REACHED();
1043     }
1044 }
1045
1046 static bool
1047 timed_out(const struct rconn *rc)
1048 {
1049     return time_now() >= sat_add(rc->state_entered, timeout(rc));
1050 }
1051
1052 static void
1053 state_transition(struct rconn *rc, enum state state)
1054 {
1055     rc->seqno += (rc->state == S_ACTIVE) != (state == S_ACTIVE);
1056     if (is_connected_state(state) && !is_connected_state(rc->state)) {
1057         rc->probably_admitted = false;
1058     }
1059     if (rconn_is_connected(rc)) {
1060         rc->total_time_connected += elapsed_in_this_state(rc);
1061     }
1062     VLOG_DBG("%s: entering %s", rc->name, state_name(state));
1063     rc->state = state;
1064     rc->state_entered = time_now();
1065 }
1066
1067 static void
1068 copy_to_monitor(struct rconn *rc, const struct ofpbuf *b)
1069 {
1070     struct ofpbuf *clone = NULL;
1071     int retval;
1072     size_t i;
1073
1074     for (i = 0; i < rc->n_monitors; ) {
1075         struct vconn *vconn = rc->monitors[i];
1076
1077         if (!clone) {
1078             clone = ofpbuf_clone(b);
1079         }
1080         retval = vconn_send(vconn, clone);
1081         if (!retval) {
1082             clone = NULL;
1083         } else if (retval != EAGAIN) {
1084             VLOG_DBG("%s: closing monitor connection to %s: %s",
1085                      rconn_get_name(rc), vconn_get_name(vconn),
1086                      strerror(retval));
1087             rc->monitors[i] = rc->monitors[--rc->n_monitors];
1088             continue;
1089         }
1090         i++;
1091     }
1092     ofpbuf_delete(clone);
1093 }
1094
1095 static bool
1096 is_connected_state(enum state state)
1097 {
1098     return (state & (S_ACTIVE | S_IDLE)) != 0;
1099 }
1100
1101 static bool
1102 is_admitted_msg(const struct ofpbuf *b)
1103 {
1104     enum ofptype type;
1105     enum ofperr error;
1106
1107     error = ofptype_decode(&type, b->data);
1108     if (error) {
1109         return false;
1110     }
1111
1112     switch (type) {
1113     case OFPTYPE_HELLO:
1114     case OFPTYPE_ERROR:
1115     case OFPTYPE_ECHO_REQUEST:
1116     case OFPTYPE_ECHO_REPLY:
1117     case OFPTYPE_FEATURES_REQUEST:
1118     case OFPTYPE_FEATURES_REPLY:
1119     case OFPTYPE_GET_CONFIG_REQUEST:
1120     case OFPTYPE_GET_CONFIG_REPLY:
1121     case OFPTYPE_SET_CONFIG:
1122         /* FIXME: Change the following once they are implemented: */
1123     case OFPTYPE_QUEUE_GET_CONFIG_REQUEST:
1124     case OFPTYPE_QUEUE_GET_CONFIG_REPLY:
1125     case OFPTYPE_GET_ASYNC_REQUEST:
1126     case OFPTYPE_GET_ASYNC_REPLY:
1127     case OFPTYPE_METER_MOD:
1128     case OFPTYPE_GROUP_REQUEST:
1129     case OFPTYPE_GROUP_REPLY:
1130     case OFPTYPE_GROUP_DESC_REQUEST:
1131     case OFPTYPE_GROUP_DESC_REPLY:
1132     case OFPTYPE_GROUP_FEATURES_REQUEST:
1133     case OFPTYPE_GROUP_FEATURES_REPLY:
1134     case OFPTYPE_METER_REQUEST:
1135     case OFPTYPE_METER_REPLY:
1136     case OFPTYPE_METER_CONFIG_REQUEST:
1137     case OFPTYPE_METER_CONFIG_REPLY:
1138     case OFPTYPE_METER_FEATURES_REQUEST:
1139     case OFPTYPE_METER_FEATURES_REPLY:
1140     case OFPTYPE_TABLE_FEATURES_REQUEST:
1141     case OFPTYPE_TABLE_FEATURES_REPLY:
1142         return false;
1143
1144     case OFPTYPE_PACKET_IN:
1145     case OFPTYPE_FLOW_REMOVED:
1146     case OFPTYPE_PORT_STATUS:
1147     case OFPTYPE_PACKET_OUT:
1148     case OFPTYPE_FLOW_MOD:
1149     case OFPTYPE_PORT_MOD:
1150     case OFPTYPE_BARRIER_REQUEST:
1151     case OFPTYPE_BARRIER_REPLY:
1152     case OFPTYPE_DESC_STATS_REQUEST:
1153     case OFPTYPE_DESC_STATS_REPLY:
1154     case OFPTYPE_FLOW_STATS_REQUEST:
1155     case OFPTYPE_FLOW_STATS_REPLY:
1156     case OFPTYPE_AGGREGATE_STATS_REQUEST:
1157     case OFPTYPE_AGGREGATE_STATS_REPLY:
1158     case OFPTYPE_TABLE_STATS_REQUEST:
1159     case OFPTYPE_TABLE_STATS_REPLY:
1160     case OFPTYPE_PORT_STATS_REQUEST:
1161     case OFPTYPE_PORT_STATS_REPLY:
1162     case OFPTYPE_QUEUE_STATS_REQUEST:
1163     case OFPTYPE_QUEUE_STATS_REPLY:
1164     case OFPTYPE_PORT_DESC_STATS_REQUEST:
1165     case OFPTYPE_PORT_DESC_STATS_REPLY:
1166     case OFPTYPE_ROLE_REQUEST:
1167     case OFPTYPE_ROLE_REPLY:
1168     case OFPTYPE_SET_FLOW_FORMAT:
1169     case OFPTYPE_FLOW_MOD_TABLE_ID:
1170     case OFPTYPE_SET_PACKET_IN_FORMAT:
1171     case OFPTYPE_FLOW_AGE:
1172     case OFPTYPE_SET_ASYNC_CONFIG:
1173     case OFPTYPE_SET_CONTROLLER_ID:
1174     case OFPTYPE_FLOW_MONITOR_STATS_REQUEST:
1175     case OFPTYPE_FLOW_MONITOR_STATS_REPLY:
1176     case OFPTYPE_FLOW_MONITOR_CANCEL:
1177     case OFPTYPE_FLOW_MONITOR_PAUSED:
1178     case OFPTYPE_FLOW_MONITOR_RESUMED:
1179     default:
1180         return true;
1181     }
1182 }
1183
1184 /* Returns true if 'rc' is currently logging information about connection
1185  * attempts, false if logging should be suppressed because 'rc' hasn't
1186  * successuflly connected in too long. */
1187 static bool
1188 rconn_logging_connection_attempts__(const struct rconn *rc)
1189 {
1190     return rc->backoff < rc->max_backoff;
1191 }