rconn: Fix segfault when the idle timeout races with connection failure.
[sliver-openvswitch.git] / lib / rconn.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  *
4  * We are making the OpenFlow specification and associated documentation
5  * (Software) available for public use and benefit with the expectation
6  * that others will use, modify and enhance the Software and contribute
7  * those enhancements back to the community. However, since we would
8  * like to make the Software available for broadest use, with as few
9  * restrictions as possible permission is hereby granted, free of
10  * charge, to any person obtaining a copy of this Software to deal in
11  * the Software under the copyrights without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  *
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27  * SOFTWARE.
28  *
29  * The name and trademarks of copyright holder(s) may NOT be used in
30  * advertising or publicity pertaining to the Software or any
31  * derivatives without specific, written prior permission.
32  */
33
34 #include <config.h>
35 #include "rconn.h"
36 #include <assert.h>
37 #include <errno.h>
38 #include <limits.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include "ofpbuf.h"
42 #include "openflow/openflow.h"
43 #include "poll-loop.h"
44 #include "sat-math.h"
45 #include "timeval.h"
46 #include "util.h"
47 #include "vconn.h"
48
49 #define THIS_MODULE VLM_rconn
50 #include "vlog.h"
51
52 #define STATES                                  \
53     STATE(VOID, 1 << 0)                         \
54     STATE(BACKOFF, 1 << 1)                      \
55     STATE(CONNECTING, 1 << 2)                   \
56     STATE(ACTIVE, 1 << 3)                       \
57     STATE(IDLE, 1 << 4)
58 enum state {
59 #define STATE(NAME, VALUE) S_##NAME = VALUE,
60     STATES
61 #undef STATE
62 };
63
64 static const char *
65 state_name(enum state state)
66 {
67     switch (state) {
68 #define STATE(NAME, VALUE) case S_##NAME: return #NAME;
69         STATES
70 #undef STATE
71     }
72     return "***ERROR***";
73 }
74
75 /* A reliable connection to an OpenFlow switch or controller.
76  *
77  * See the large comment in rconn.h for more information. */
78 struct rconn {
79     enum state state;
80     time_t state_entered;
81
82     struct vconn *vconn;
83     char *name;
84     bool reliable;
85
86     struct ofp_queue txq;
87
88     int backoff;
89     int max_backoff;
90     time_t backoff_deadline;
91     time_t last_received;
92     time_t last_connected;
93     unsigned int packets_sent;
94
95     /* In S_ACTIVE and S_IDLE, probably_admitted reports whether we believe
96      * that the peer has made a (positive) admission control decision on our
97      * connection.  If we have not yet been (probably) admitted, then the
98      * connection does not reset the timer used for deciding whether the switch
99      * should go into fail-open mode.
100      *
101      * last_admitted reports the last time we believe such a positive admission
102      * control decision was made. */
103     bool probably_admitted;
104     time_t last_admitted;
105
106     /* These values are simply for statistics reporting, not used directly by
107      * anything internal to the rconn (or the secchan for that matter). */
108     unsigned int packets_received;
109     unsigned int n_attempted_connections, n_successful_connections;
110     time_t creation_time;
111     unsigned long int total_time_connected;
112
113     /* If we can't connect to the peer, it could be for any number of reasons.
114      * Usually, one would assume it is because the peer is not running or
115      * because the network is partitioned.  But it could also be because the
116      * network topology has changed, in which case the upper layer will need to
117      * reassess it (in particular, obtain a new IP address via DHCP and find
118      * the new location of the controller).  We set this flag when we suspect
119      * that this could be the case. */
120     bool questionable_connectivity;
121     time_t last_questioned;
122
123     /* Throughout this file, "probe" is shorthand for "inactivity probe".
124      * When nothing has been received from the peer for a while, we send out
125      * an echo request as an inactivity probe packet.  We should receive back
126      * a response. */
127     int probe_interval;         /* Secs of inactivity before sending probe. */
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
135 static unsigned int elapsed_in_this_state(const struct rconn *);
136 static unsigned int timeout(const struct rconn *);
137 static bool timed_out(const struct rconn *);
138 static void state_transition(struct rconn *, enum state);
139 static int try_send(struct rconn *);
140 static int reconnect(struct rconn *);
141 static void disconnect(struct rconn *, int error);
142 static void flush_queue(struct rconn *);
143 static void question_connectivity(struct rconn *);
144 static void copy_to_monitor(struct rconn *, const struct ofpbuf *);
145 static bool is_connected_state(enum state);
146 static bool is_admitted_msg(const struct ofpbuf *);
147
148 /* Creates a new rconn, connects it (reliably) to 'name', and returns it. */
149 struct rconn *
150 rconn_new(const char *name, int inactivity_probe_interval, int max_backoff)
151 {
152     struct rconn *rc = rconn_create(inactivity_probe_interval, max_backoff);
153     rconn_connect(rc, name);
154     return rc;
155 }
156
157 /* Creates a new rconn, connects it (unreliably) to 'vconn', and returns it. */
158 struct rconn *
159 rconn_new_from_vconn(const char *name, struct vconn *vconn) 
160 {
161     struct rconn *rc = rconn_create(60, 0);
162     rconn_connect_unreliably(rc, name, vconn);
163     return rc;
164 }
165
166 /* Creates and returns a new rconn.
167  *
168  * 'probe_interval' is a number of seconds.  If the interval passes once
169  * without an OpenFlow message being received from the peer, the rconn sends
170  * out an "echo request" message.  If the interval passes again without a
171  * message being received, the rconn disconnects and re-connects to the peer.
172  * Setting 'probe_interval' to 0 disables this behavior.
173  *
174  * 'max_backoff' is the maximum number of seconds between attempts to connect
175  * to the peer.  The actual interval starts at 1 second and doubles on each
176  * failure until it reaches 'max_backoff'.  If 0 is specified, the default of
177  * 60 seconds is used. */
178 struct rconn *
179 rconn_create(int probe_interval, int max_backoff)
180 {
181     struct rconn *rc = xcalloc(1, sizeof *rc);
182
183     rc->state = S_VOID;
184     rc->state_entered = time_now();
185
186     rc->vconn = NULL;
187     rc->name = xstrdup("void");
188     rc->reliable = false;
189
190     queue_init(&rc->txq);
191
192     rc->backoff = 0;
193     rc->max_backoff = max_backoff ? max_backoff : 60;
194     rc->backoff_deadline = TIME_MIN;
195     rc->last_received = time_now();
196     rc->last_connected = time_now();
197
198     rc->packets_sent = 0;
199
200     rc->probably_admitted = false;
201     rc->last_admitted = time_now();
202
203     rc->packets_received = 0;
204     rc->n_attempted_connections = 0;
205     rc->n_successful_connections = 0;
206     rc->creation_time = time_now();
207     rc->total_time_connected = 0;
208
209     rc->questionable_connectivity = false;
210     rc->last_questioned = time_now();
211
212     rc->probe_interval = probe_interval ? MAX(5, probe_interval) : 0;
213
214     rc->n_monitors = 0;
215
216     return rc;
217 }
218
219 int
220 rconn_connect(struct rconn *rc, const char *name)
221 {
222     rconn_disconnect(rc);
223     free(rc->name);
224     rc->name = xstrdup(name);
225     rc->reliable = true;
226     return reconnect(rc);
227 }
228
229 void
230 rconn_connect_unreliably(struct rconn *rc,
231                          const char *name, struct vconn *vconn)
232 {
233     assert(vconn != NULL);
234     rconn_disconnect(rc);
235     free(rc->name);
236     rc->name = xstrdup(name);
237     rc->reliable = false;
238     rc->vconn = vconn;
239     rc->last_connected = time_now();
240     state_transition(rc, S_ACTIVE);
241 }
242
243 void
244 rconn_disconnect(struct rconn *rc)
245 {
246     if (rc->state != S_VOID) {
247         if (rc->vconn) {
248             vconn_close(rc->vconn);
249             rc->vconn = NULL;
250         }
251         free(rc->name);
252         rc->name = xstrdup("void");
253         rc->reliable = false;
254
255         rc->backoff = 0;
256         rc->backoff_deadline = TIME_MIN;
257
258         state_transition(rc, S_VOID);
259     }
260 }
261
262 /* Disconnects 'rc' and frees the underlying storage. */
263 void
264 rconn_destroy(struct rconn *rc)
265 {
266     if (rc) {
267         size_t i;
268
269         free(rc->name);
270         vconn_close(rc->vconn);
271         flush_queue(rc);
272         queue_destroy(&rc->txq);
273         for (i = 0; i < rc->n_monitors; i++) {
274             vconn_close(rc->monitors[i]);
275         }
276         free(rc);
277     }
278 }
279
280 static unsigned int
281 timeout_VOID(const struct rconn *rc)
282 {
283     return UINT_MAX;
284 }
285
286 static void
287 run_VOID(struct rconn *rc)
288 {
289     /* Nothing to do. */
290 }
291
292 static int
293 reconnect(struct rconn *rc)
294 {
295     int retval;
296
297     VLOG_WARN("%s: connecting...", rc->name);
298     rc->n_attempted_connections++;
299     retval = vconn_open(rc->name, OFP_VERSION, &rc->vconn);
300     if (!retval) {
301         rc->backoff_deadline = time_now() + rc->backoff;
302         state_transition(rc, S_CONNECTING);
303     } else {
304         VLOG_WARN("%s: connection failed (%s)", rc->name, strerror(retval));
305         rc->backoff_deadline = TIME_MAX; /* Prevent resetting backoff. */
306         disconnect(rc, 0);
307     }
308     return retval;
309 }
310
311 static unsigned int
312 timeout_BACKOFF(const struct rconn *rc)
313 {
314     return rc->backoff;
315 }
316
317 static void
318 run_BACKOFF(struct rconn *rc)
319 {
320     if (timed_out(rc)) {
321         reconnect(rc);
322     }
323 }
324
325 static unsigned int
326 timeout_CONNECTING(const struct rconn *rc)
327 {
328     return MAX(1, rc->backoff);
329 }
330
331 static void
332 run_CONNECTING(struct rconn *rc)
333 {
334     int retval = vconn_connect(rc->vconn);
335     if (!retval) {
336         VLOG_WARN("%s: connected", rc->name);
337         rc->n_successful_connections++;
338         state_transition(rc, S_ACTIVE);
339         rc->last_connected = rc->state_entered;
340     } else if (retval != EAGAIN) {
341         VLOG_WARN("%s: connection failed (%s)", rc->name, strerror(retval));
342         disconnect(rc, retval);
343     } else if (timed_out(rc)) {
344         VLOG_WARN("%s: connection timed out", rc->name);
345         rc->backoff_deadline = TIME_MAX; /* Prevent resetting backoff. */
346         disconnect(rc, 0);
347     }
348 }
349
350 static void
351 do_tx_work(struct rconn *rc)
352 {
353     if (!rc->txq.n) {
354         return;
355     }
356     while (rc->txq.n > 0) {
357         int error = try_send(rc);
358         if (error) {
359             break;
360         }
361     }
362     if (!rc->txq.n) {
363         poll_immediate_wake();
364     }
365 }
366
367 static unsigned int
368 timeout_ACTIVE(const struct rconn *rc)
369 {
370     if (rc->probe_interval) {
371         unsigned int base = MAX(rc->last_received, rc->state_entered);
372         unsigned int arg = base + rc->probe_interval - rc->state_entered;
373         return arg;
374     }
375     return UINT_MAX;
376 }
377
378 static void
379 run_ACTIVE(struct rconn *rc)
380 {
381     if (timed_out(rc)) {
382         unsigned int base = MAX(rc->last_received, rc->state_entered);
383         VLOG_DBG("%s: idle %u seconds, sending inactivity probe",
384                  rc->name, (unsigned int) (time_now() - base));
385
386         /* Ordering is important here: rconn_send() can transition to BACKOFF,
387          * and we don't want to transition back to IDLE if so, because then we
388          * can end up queuing a packet with vconn == NULL and then *boom*. */
389         state_transition(rc, S_IDLE);
390         rconn_send(rc, make_echo_request(), NULL);
391         return;
392     }
393
394     do_tx_work(rc);
395 }
396
397 static unsigned int
398 timeout_IDLE(const struct rconn *rc)
399 {
400     return rc->probe_interval;
401 }
402
403 static void
404 run_IDLE(struct rconn *rc)
405 {
406     if (timed_out(rc)) {
407         question_connectivity(rc);
408         VLOG_ERR("%s: no response to inactivity probe after %u "
409                  "seconds, disconnecting",
410                  rc->name, elapsed_in_this_state(rc));
411         disconnect(rc, 0);
412     } else {
413         do_tx_work(rc);
414     }
415 }
416
417 /* Performs whatever activities are necessary to maintain 'rc': if 'rc' is
418  * disconnected, attempts to (re)connect, backing off as necessary; if 'rc' is
419  * connected, attempts to send packets in the send queue, if any. */
420 void
421 rconn_run(struct rconn *rc)
422 {
423     int old_state;
424     do {
425         old_state = rc->state;
426         switch (rc->state) {
427 #define STATE(NAME, VALUE) case S_##NAME: run_##NAME(rc); break;
428             STATES
429 #undef STATE
430         default:
431             NOT_REACHED();
432         }
433     } while (rc->state != old_state);
434 }
435
436 /* Causes the next call to poll_block() to wake up when rconn_run() should be
437  * called on 'rc'. */
438 void
439 rconn_run_wait(struct rconn *rc)
440 {
441     unsigned int timeo = timeout(rc);
442     if (timeo != UINT_MAX) {
443         unsigned int expires = sat_add(rc->state_entered, timeo);
444         unsigned int remaining = sat_sub(expires, time_now());
445         poll_timer_wait(sat_mul(remaining, 1000));
446     }
447
448     if ((rc->state & (S_ACTIVE | S_IDLE)) && rc->txq.n) {
449         vconn_wait(rc->vconn, WAIT_SEND);
450     }
451 }
452
453 /* Attempts to receive a packet from 'rc'.  If successful, returns the packet;
454  * otherwise, returns a null pointer.  The caller is responsible for freeing
455  * the packet (with ofpbuf_delete()). */
456 struct ofpbuf *
457 rconn_recv(struct rconn *rc)
458 {
459     if (rc->state & (S_ACTIVE | S_IDLE)) {
460         struct ofpbuf *buffer;
461         int error = vconn_recv(rc->vconn, &buffer);
462         if (!error) {
463             copy_to_monitor(rc, buffer);
464             if (is_admitted_msg(buffer)
465                 || time_now() - rc->last_connected >= 30) {
466                 rc->probably_admitted = true;
467                 rc->last_admitted = time_now();
468             }
469             rc->last_received = time_now();
470             rc->packets_received++;
471             if (rc->state == S_IDLE) {
472                 state_transition(rc, S_ACTIVE);
473             }
474             return buffer;
475         } else if (error != EAGAIN) {
476             disconnect(rc, error);
477         }
478     }
479     return NULL;
480 }
481
482 /* Causes the next call to poll_block() to wake up when a packet may be ready
483  * to be received by vconn_recv() on 'rc'.  */
484 void
485 rconn_recv_wait(struct rconn *rc)
486 {
487     if (rc->vconn) {
488         vconn_wait(rc->vconn, WAIT_RECV);
489     }
490 }
491
492 /* Sends 'b' on 'rc'.  Returns 0 if successful (in which case 'b' is
493  * destroyed), or ENOTCONN if 'rc' is not currently connected (in which case
494  * the caller retains ownership of 'b').
495  *
496  * If 'n_queued' is non-null, then '*n_queued' will be incremented while the
497  * packet is in flight, then decremented when it has been sent (or discarded
498  * due to disconnection).  Because 'b' may be sent (or discarded) before this
499  * function returns, the caller may not be able to observe any change in
500  * '*n_queued'.
501  *
502  * There is no rconn_send_wait() function: an rconn has a send queue that it
503  * takes care of sending if you call rconn_run(), which will have the side
504  * effect of waking up poll_block(). */
505 int
506 rconn_send(struct rconn *rc, struct ofpbuf *b, int *n_queued)
507 {
508     if (rconn_is_connected(rc)) {
509         copy_to_monitor(rc, b);
510         b->private = n_queued;
511         if (n_queued) {
512             ++*n_queued;
513         }
514         queue_push_tail(&rc->txq, b);
515         if (rc->txq.n == 1) {
516             try_send(rc);
517         }
518         return 0;
519     } else {
520         return ENOTCONN;
521     }
522 }
523
524 /* Sends 'b' on 'rc'.  Increments '*n_queued' while the packet is in flight; it
525  * will be decremented when it has been sent (or discarded due to
526  * disconnection).  Returns 0 if successful, EAGAIN if '*n_queued' is already
527  * at least as large as 'queue_limit', or ENOTCONN if 'rc' is not currently
528  * connected.  Regardless of return value, 'b' is destroyed.
529  *
530  * Because 'b' may be sent (or discarded) before this function returns, the
531  * caller may not be able to observe any change in '*n_queued'.
532  *
533  * There is no rconn_send_wait() function: an rconn has a send queue that it
534  * takes care of sending if you call rconn_run(), which will have the side
535  * effect of waking up poll_block(). */
536 int
537 rconn_send_with_limit(struct rconn *rc, struct ofpbuf *b,
538                       int *n_queued, int queue_limit)
539 {
540     int retval;
541     retval = *n_queued >= queue_limit ? EAGAIN : rconn_send(rc, b, n_queued);
542     if (retval) {
543         ofpbuf_delete(b);
544     }
545     return retval;
546 }
547
548 /* Returns the total number of packets successfully sent on the underlying
549  * vconn.  A packet is not counted as sent while it is still queued in the
550  * rconn, only when it has been successfuly passed to the vconn.  */
551 unsigned int
552 rconn_packets_sent(const struct rconn *rc)
553 {
554     return rc->packets_sent;
555 }
556
557 /* Adds 'vconn' to 'rc' as a monitoring connection, to which all messages sent
558  * and received on 'rconn' will be copied.  'rc' takes ownership of 'vconn'. */
559 void
560 rconn_add_monitor(struct rconn *rc, struct vconn *vconn)
561 {
562     if (rc->n_monitors < ARRAY_SIZE(rc->monitors)) {
563         VLOG_WARN("new monitor connection from %s", vconn_get_name(vconn));
564         rc->monitors[rc->n_monitors++] = vconn;
565     } else {
566         VLOG_DBG("too many monitor connections, discarding %s",
567                  vconn_get_name(vconn));
568         vconn_close(vconn);
569     }
570 }
571
572 /* Returns 'rc''s name (the 'name' argument passed to rconn_new()). */
573 const char *
574 rconn_get_name(const struct rconn *rc)
575 {
576     return rc->name;
577 }
578
579 /* Returns true if 'rconn' is connected or in the process of reconnecting,
580  * false if 'rconn' is disconnected and will not reconnect on its own. */
581 bool
582 rconn_is_alive(const struct rconn *rconn)
583 {
584     return rconn->state != S_VOID;
585 }
586
587 /* Returns true if 'rconn' is connected, false otherwise. */
588 bool
589 rconn_is_connected(const struct rconn *rconn)
590 {
591     return is_connected_state(rconn->state);
592 }
593
594 /* Returns 0 if 'rconn' is connected.  Otherwise, if 'rconn' is in a "failure
595  * mode" (that is, it is not connected), returns the number of seconds that it
596  * has been in failure mode, ignoring any times that it connected but the
597  * controller's admission control policy caused it to be quickly
598  * disconnected. */
599 int
600 rconn_failure_duration(const struct rconn *rconn)
601 {
602     return rconn_is_connected(rconn) ? 0 : time_now() - rconn->last_admitted;
603 }
604
605 /* Returns the IP address of the peer, or 0 if the peer is not connected over
606  * an IP-based protocol or if its IP address is not known. */
607 uint32_t
608 rconn_get_ip(const struct rconn *rconn) 
609 {
610     return rconn->vconn ? vconn_get_ip(rconn->vconn) : 0;
611 }
612
613 /* If 'rconn' can't connect to the peer, it could be for any number of reasons.
614  * Usually, one would assume it is because the peer is not running or because
615  * the network is partitioned.  But it could also be because the network
616  * topology has changed, in which case the upper layer will need to reassess it
617  * (in particular, obtain a new IP address via DHCP and find the new location
618  * of the controller).  When this appears that this might be the case, this
619  * function returns true.  It also clears the questionability flag and prevents
620  * it from being set again for some time. */
621 bool
622 rconn_is_connectivity_questionable(struct rconn *rconn)
623 {
624     bool questionable = rconn->questionable_connectivity;
625     rconn->questionable_connectivity = false;
626     return questionable;
627 }
628
629 /* Returns the total number of packets successfully received by the underlying
630  * vconn.  */
631 unsigned int
632 rconn_packets_received(const struct rconn *rc)
633 {
634     return rc->packets_received;
635 }
636
637 /* Returns a string representing the internal state of 'rc'.  The caller must
638  * not modify or free the string. */
639 const char *
640 rconn_get_state(const struct rconn *rc)
641 {
642     return state_name(rc->state);
643 }
644
645 /* Returns the number of connection attempts made by 'rc', including any
646  * ongoing attempt that has not yet succeeded or failed. */
647 unsigned int
648 rconn_get_attempted_connections(const struct rconn *rc)
649 {
650     return rc->n_attempted_connections;
651 }
652
653 /* Returns the number of successful connection attempts made by 'rc'. */
654 unsigned int
655 rconn_get_successful_connections(const struct rconn *rc)
656 {
657     return rc->n_successful_connections;
658 }
659
660 /* Returns the time at which the last successful connection was made by
661  * 'rc'. */
662 time_t
663 rconn_get_last_connection(const struct rconn *rc)
664 {
665     return rc->last_connected;
666 }
667
668 /* Returns the time at which 'rc' was created. */
669 time_t
670 rconn_get_creation_time(const struct rconn *rc)
671 {
672     return rc->creation_time;
673 }
674
675 /* Returns the approximate number of seconds that 'rc' has been connected. */
676 unsigned long int
677 rconn_get_total_time_connected(const struct rconn *rc)
678 {
679     return (rc->total_time_connected
680             + (rconn_is_connected(rc) ? elapsed_in_this_state(rc) : 0));
681 }
682
683 /* Returns the current amount of backoff, in seconds.  This is the amount of
684  * time after which the rconn will transition from BACKOFF to CONNECTING. */
685 int
686 rconn_get_backoff(const struct rconn *rc)
687 {
688     return rc->backoff;
689 }
690
691 /* Returns the number of seconds spent in this state so far. */
692 unsigned int
693 rconn_get_state_elapsed(const struct rconn *rc)
694 {
695     return elapsed_in_this_state(rc);
696 }
697 \f
698 /* Tries to send a packet from 'rc''s send buffer.  Returns 0 if successful,
699  * otherwise a positive errno value. */
700 static int
701 try_send(struct rconn *rc)
702 {
703     int retval = 0;
704     struct ofpbuf *next = rc->txq.head->next;
705     int *n_queued = rc->txq.head->private;
706     retval = vconn_send(rc->vconn, rc->txq.head);
707     if (retval) {
708         if (retval != EAGAIN) {
709             disconnect(rc, retval);
710         }
711         return retval;
712     }
713     rc->packets_sent++;
714     if (n_queued) {
715         --*n_queued;
716     }
717     queue_advance_head(&rc->txq, next);
718     return 0;
719 }
720
721 /* Disconnects 'rc'.  'error' is used only for logging purposes.  If it is
722  * nonzero, then it should be EOF to indicate the connection was closed by the
723  * peer in a normal fashion or a positive errno value. */
724 static void
725 disconnect(struct rconn *rc, int error)
726 {
727     if (rc->reliable) {
728         time_t now = time_now();
729
730         if (rc->state & (S_CONNECTING | S_ACTIVE | S_IDLE)) {
731             if (error > 0) {
732                 VLOG_WARN("%s: connection dropped (%s)",
733                           rc->name, strerror(error));
734             } else if (error == EOF) {
735                 if (rc->reliable) {
736                     VLOG_WARN("%s: connection closed by peer", rc->name);
737                 }
738             } else {
739                 VLOG_WARN("%s: connection dropped", rc->name);
740             }
741             vconn_close(rc->vconn);
742             rc->vconn = NULL;
743             flush_queue(rc);
744         }
745
746         if (now >= rc->backoff_deadline) {
747             rc->backoff = 1;
748         } else {
749             rc->backoff = MIN(rc->max_backoff, MAX(1, 2 * rc->backoff));
750             VLOG_WARN("%s: waiting %d seconds before reconnect\n",
751                       rc->name, rc->backoff);
752         }
753         rc->backoff_deadline = now + rc->backoff;
754         state_transition(rc, S_BACKOFF);
755         if (now - rc->last_connected > 60) {
756             question_connectivity(rc);
757         }
758     } else {
759         rconn_disconnect(rc);
760     }
761 }
762
763 /* Drops all the packets from 'rc''s send queue and decrements their queue
764  * counts. */
765 static void
766 flush_queue(struct rconn *rc)
767 {
768     if (!rc->txq.n) {
769         return;
770     }
771     while (rc->txq.n > 0) {
772         struct ofpbuf *b = queue_pop_head(&rc->txq);
773         int *n_queued = b->private;
774         if (n_queued) {
775             --*n_queued;
776         }
777         ofpbuf_delete(b);
778     }
779     poll_immediate_wake();
780 }
781
782 static unsigned int
783 elapsed_in_this_state(const struct rconn *rc)
784 {
785     return time_now() - rc->state_entered;
786 }
787
788 static unsigned int
789 timeout(const struct rconn *rc)
790 {
791     switch (rc->state) {
792 #define STATE(NAME, VALUE) case S_##NAME: return timeout_##NAME(rc);
793         STATES
794 #undef STATE
795     default:
796         NOT_REACHED();
797     }
798 }
799
800 static bool
801 timed_out(const struct rconn *rc)
802 {
803     return time_now() >= sat_add(rc->state_entered, timeout(rc));
804 }
805
806 static void
807 state_transition(struct rconn *rc, enum state state)
808 {
809     if (is_connected_state(state) && !is_connected_state(rc->state)) {
810         rc->probably_admitted = false;
811     }
812     if (rconn_is_connected(rc)) {
813         rc->total_time_connected += elapsed_in_this_state(rc);
814     }
815     VLOG_DBG("%s: entering %s", rc->name, state_name(state));
816     rc->state = state;
817     rc->state_entered = time_now();
818 }
819
820 static void
821 question_connectivity(struct rconn *rc) 
822 {
823     time_t now = time_now();
824     if (now - rc->last_questioned > 60) {
825         rc->questionable_connectivity = true;
826         rc->last_questioned = now;
827     }
828 }
829
830 static void
831 copy_to_monitor(struct rconn *rc, const struct ofpbuf *b)
832 {
833     struct ofpbuf *clone = NULL;
834     int retval;
835     size_t i;
836
837     for (i = 0; i < rc->n_monitors; ) {
838         struct vconn *vconn = rc->monitors[i];
839
840         if (!clone) {
841             clone = ofpbuf_clone(b);
842         }
843         retval = vconn_send(vconn, clone);
844         if (!retval) {
845             clone = NULL;
846         } else if (retval != EAGAIN) {
847             VLOG_DBG("%s: closing monitor connection to %s: %s",
848                      rconn_get_name(rc), vconn_get_name(vconn),
849                      strerror(retval));
850             rc->monitors[i] = rc->monitors[--rc->n_monitors];
851             continue;
852         }
853         i++;
854     }
855     ofpbuf_delete(clone);
856 }
857
858 static bool
859 is_connected_state(enum state state) 
860 {
861     return (state & (S_ACTIVE | S_IDLE)) != 0;
862 }
863
864 static bool
865 is_admitted_msg(const struct ofpbuf *b)
866 {
867     struct ofp_header *oh = b->data;
868     uint8_t type = oh->type;
869     return !(type < 32
870              && (1u << type) & ((1u << OFPT_HELLO) |
871                                 (1u << OFPT_ERROR) |
872                                 (1u << OFPT_ECHO_REQUEST) |
873                                 (1u << OFPT_ECHO_REPLY) |
874                                 (1u << OFPT_VENDOR) |
875                                 (1u << OFPT_FEATURES_REQUEST) |
876                                 (1u << OFPT_FEATURES_REPLY) |
877                                 (1u << OFPT_GET_CONFIG_REQUEST) |
878                                 (1u << OFPT_GET_CONFIG_REPLY) |
879                                 (1u << OFPT_SET_CONFIG)));
880 }