rconn: New function rconn_get_last_error().
[cascardo/ovs.git] / lib / rconn.c
1 /*
2  * Copyright (c) 2008, 2009, 2010 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 "rconn.h"
19 #include <assert.h>
20 #include <errno.h>
21 #include <limits.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include "coverage.h"
25 #include "ofpbuf.h"
26 #include "openflow/openflow.h"
27 #include "poll-loop.h"
28 #include "sat-math.h"
29 #include "timeval.h"
30 #include "util.h"
31 #include "vconn.h"
32
33 #define THIS_MODULE VLM_rconn
34 #include "vlog.h"
35
36 #define STATES                                  \
37     STATE(VOID, 1 << 0)                         \
38     STATE(BACKOFF, 1 << 1)                      \
39     STATE(CONNECTING, 1 << 2)                   \
40     STATE(ACTIVE, 1 << 3)                       \
41     STATE(IDLE, 1 << 4)
42 enum state {
43 #define STATE(NAME, VALUE) S_##NAME = VALUE,
44     STATES
45 #undef STATE
46 };
47
48 static const char *
49 state_name(enum state state)
50 {
51     switch (state) {
52 #define STATE(NAME, VALUE) case S_##NAME: return #NAME;
53         STATES
54 #undef STATE
55     }
56     return "***ERROR***";
57 }
58
59 /* A reliable connection to an OpenFlow switch or controller.
60  *
61  * See the large comment in rconn.h for more information. */
62 struct rconn {
63     enum state state;
64     time_t state_entered;
65
66     struct vconn *vconn;
67     char *name;
68     bool reliable;
69
70     struct ovs_queue txq;
71
72     int backoff;
73     int max_backoff;
74     time_t backoff_deadline;
75     time_t last_received;
76     time_t last_connected;
77     unsigned int packets_sent;
78     unsigned int seqno;
79     int last_error;
80
81     /* In S_ACTIVE and S_IDLE, probably_admitted reports whether we believe
82      * that the peer has made a (positive) admission control decision on our
83      * connection.  If we have not yet been (probably) admitted, then the
84      * connection does not reset the timer used for deciding whether the switch
85      * should go into fail-open mode.
86      *
87      * last_admitted reports the last time we believe such a positive admission
88      * control decision was made. */
89     bool probably_admitted;
90     time_t last_admitted;
91
92     /* These values are simply for statistics reporting, not used directly by
93      * anything internal to the rconn (or ofproto for that matter). */
94     unsigned int packets_received;
95     unsigned int n_attempted_connections, n_successful_connections;
96     time_t creation_time;
97     unsigned long int total_time_connected;
98
99     /* If we can't connect to the peer, it could be for any number of reasons.
100      * Usually, one would assume it is because the peer is not running or
101      * because the network is partitioned.  But it could also be because the
102      * network topology has changed, in which case the upper layer will need to
103      * reassess it (in particular, obtain a new IP address via DHCP and find
104      * the new location of the controller).  We set this flag when we suspect
105      * that this could be the case. */
106     bool questionable_connectivity;
107     time_t last_questioned;
108
109     /* Throughout this file, "probe" is shorthand for "inactivity probe".
110      * When nothing has been received from the peer for a while, we send out
111      * an echo request as an inactivity probe packet.  We should receive back
112      * a response. */
113     int probe_interval;         /* Secs of inactivity before sending probe. */
114
115     /* When we create a vconn we obtain these values, to save them past the end
116      * of the vconn's lifetime.  Otherwise, in-band control will only allow
117      * traffic when a vconn is actually open, but it is nice to allow ARP to
118      * complete even between connection attempts, and it is also polite to
119      * allow traffic from other switches to go through to the controller
120      * whether or not we are connected.
121      *
122      * We don't cache the local port, because that changes from one connection
123      * attempt to the next. */
124     uint32_t local_ip, remote_ip;
125     uint16_t remote_port;
126
127     /* Messages sent or received are copied to the monitor connections. */
128 #define MAX_MONITORS 8
129     struct vconn *monitors[8];
130     size_t n_monitors;
131 };
132
133 static unsigned int elapsed_in_this_state(const struct rconn *);
134 static unsigned int timeout(const struct rconn *);
135 static bool timed_out(const struct rconn *);
136 static void state_transition(struct rconn *, enum state);
137 static void set_vconn_name(struct rconn *, const char *name);
138 static int try_send(struct rconn *);
139 static int reconnect(struct rconn *);
140 static void report_error(struct rconn *, int error);
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  * 8 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 : 8;
194     rc->backoff_deadline = TIME_MIN;
195     rc->last_received = time_now();
196     rc->last_connected = time_now();
197     rc->seqno = 0;
198
199     rc->packets_sent = 0;
200
201     rc->probably_admitted = false;
202     rc->last_admitted = time_now();
203
204     rc->packets_received = 0;
205     rc->n_attempted_connections = 0;
206     rc->n_successful_connections = 0;
207     rc->creation_time = time_now();
208     rc->total_time_connected = 0;
209
210     rc->questionable_connectivity = false;
211     rc->last_questioned = time_now();
212
213     rconn_set_probe_interval(rc, probe_interval);
214
215     rc->n_monitors = 0;
216
217     return rc;
218 }
219
220 void
221 rconn_set_max_backoff(struct rconn *rc, int max_backoff)
222 {
223     rc->max_backoff = MAX(1, max_backoff);
224     if (rc->state == S_BACKOFF && rc->backoff > max_backoff) {
225         rc->backoff = max_backoff;
226         if (rc->backoff_deadline > time_now() + max_backoff) {
227             rc->backoff_deadline = time_now() + max_backoff;
228         }
229     }
230 }
231
232 int
233 rconn_get_max_backoff(const struct rconn *rc)
234 {
235     return rc->max_backoff;
236 }
237
238 void
239 rconn_set_probe_interval(struct rconn *rc, int probe_interval)
240 {
241     rc->probe_interval = probe_interval ? MAX(5, probe_interval) : 0;
242 }
243
244 int
245 rconn_get_probe_interval(const struct rconn *rc)
246 {
247     return rc->probe_interval;
248 }
249
250 int
251 rconn_connect(struct rconn *rc, const char *name)
252 {
253     rconn_disconnect(rc);
254     set_vconn_name(rc, name);
255     rc->reliable = true;
256     return reconnect(rc);
257 }
258
259 void
260 rconn_connect_unreliably(struct rconn *rc,
261                          const char *name, struct vconn *vconn)
262 {
263     assert(vconn != NULL);
264     rconn_disconnect(rc);
265     set_vconn_name(rc, name);
266     rc->reliable = false;
267     rc->vconn = vconn;
268     rc->last_connected = time_now();
269     state_transition(rc, S_ACTIVE);
270 }
271
272 /* If 'rc' is connected, forces it to drop the connection and reconnect. */
273 void
274 rconn_reconnect(struct rconn *rc)
275 {
276     if (rc->state & (S_ACTIVE | S_IDLE)) {
277         VLOG_INFO("%s: disconnecting", rc->name);
278         disconnect(rc, 0);
279     }
280 }
281
282 void
283 rconn_disconnect(struct rconn *rc)
284 {
285     if (rc->state != S_VOID) {
286         if (rc->vconn) {
287             vconn_close(rc->vconn);
288             rc->vconn = NULL;
289         }
290         set_vconn_name(rc, "void");
291         rc->reliable = false;
292
293         rc->backoff = 0;
294         rc->backoff_deadline = TIME_MIN;
295
296         state_transition(rc, S_VOID);
297     }
298 }
299
300 /* Disconnects 'rc' and frees the underlying storage. */
301 void
302 rconn_destroy(struct rconn *rc)
303 {
304     if (rc) {
305         size_t i;
306
307         free(rc->name);
308         vconn_close(rc->vconn);
309         flush_queue(rc);
310         queue_destroy(&rc->txq);
311         for (i = 0; i < rc->n_monitors; i++) {
312             vconn_close(rc->monitors[i]);
313         }
314         free(rc);
315     }
316 }
317
318 static unsigned int
319 timeout_VOID(const struct rconn *rc OVS_UNUSED)
320 {
321     return UINT_MAX;
322 }
323
324 static void
325 run_VOID(struct rconn *rc OVS_UNUSED)
326 {
327     /* Nothing to do. */
328 }
329
330 static int
331 reconnect(struct rconn *rc)
332 {
333     int retval;
334
335     VLOG_INFO("%s: connecting...", rc->name);
336     rc->n_attempted_connections++;
337     retval = vconn_open(rc->name, OFP_VERSION, &rc->vconn);
338     if (!retval) {
339         rc->remote_ip = vconn_get_remote_ip(rc->vconn);
340         rc->local_ip = vconn_get_local_ip(rc->vconn);
341         rc->remote_port = vconn_get_remote_port(rc->vconn);
342         rc->backoff_deadline = time_now() + rc->backoff;
343         state_transition(rc, S_CONNECTING);
344     } else {
345         VLOG_WARN("%s: connection failed (%s)", rc->name, strerror(retval));
346         rc->backoff_deadline = TIME_MAX; /* Prevent resetting backoff. */
347         disconnect(rc, retval);
348     }
349     return retval;
350 }
351
352 static unsigned int
353 timeout_BACKOFF(const struct rconn *rc)
354 {
355     return rc->backoff;
356 }
357
358 static void
359 run_BACKOFF(struct rconn *rc)
360 {
361     if (timed_out(rc)) {
362         reconnect(rc);
363     }
364 }
365
366 static unsigned int
367 timeout_CONNECTING(const struct rconn *rc)
368 {
369     return MAX(1, rc->backoff);
370 }
371
372 static void
373 run_CONNECTING(struct rconn *rc)
374 {
375     int retval = vconn_connect(rc->vconn);
376     if (!retval) {
377         VLOG_INFO("%s: connected", rc->name);
378         rc->n_successful_connections++;
379         state_transition(rc, S_ACTIVE);
380         rc->last_connected = rc->state_entered;
381     } else if (retval != EAGAIN) {
382         VLOG_INFO("%s: connection failed (%s)", rc->name, strerror(retval));
383         disconnect(rc, retval);
384     } else if (timed_out(rc)) {
385         VLOG_INFO("%s: connection timed out", rc->name);
386         rc->backoff_deadline = TIME_MAX; /* Prevent resetting backoff. */
387         disconnect(rc, ETIMEDOUT);
388     }
389 }
390
391 static void
392 do_tx_work(struct rconn *rc)
393 {
394     if (!rc->txq.n) {
395         return;
396     }
397     while (rc->txq.n > 0) {
398         int error = try_send(rc);
399         if (error) {
400             break;
401         }
402     }
403     if (!rc->txq.n) {
404         poll_immediate_wake();
405     }
406 }
407
408 static unsigned int
409 timeout_ACTIVE(const struct rconn *rc)
410 {
411     if (rc->probe_interval) {
412         unsigned int base = MAX(rc->last_received, rc->state_entered);
413         unsigned int arg = base + rc->probe_interval - rc->state_entered;
414         return arg;
415     }
416     return UINT_MAX;
417 }
418
419 static void
420 run_ACTIVE(struct rconn *rc)
421 {
422     if (timed_out(rc)) {
423         unsigned int base = MAX(rc->last_received, rc->state_entered);
424         VLOG_DBG("%s: idle %u seconds, sending inactivity probe",
425                  rc->name, (unsigned int) (time_now() - base));
426
427         /* Ordering is important here: rconn_send() can transition to BACKOFF,
428          * and we don't want to transition back to IDLE if so, because then we
429          * can end up queuing a packet with vconn == NULL and then *boom*. */
430         state_transition(rc, S_IDLE);
431         rconn_send(rc, make_echo_request(), NULL);
432         return;
433     }
434
435     do_tx_work(rc);
436 }
437
438 static unsigned int
439 timeout_IDLE(const struct rconn *rc)
440 {
441     return rc->probe_interval;
442 }
443
444 static void
445 run_IDLE(struct rconn *rc)
446 {
447     if (timed_out(rc)) {
448         question_connectivity(rc);
449         VLOG_ERR("%s: no response to inactivity probe after %u "
450                  "seconds, disconnecting",
451                  rc->name, elapsed_in_this_state(rc));
452         disconnect(rc, ETIMEDOUT);
453     } else {
454         do_tx_work(rc);
455     }
456 }
457
458 /* Performs whatever activities are necessary to maintain 'rc': if 'rc' is
459  * disconnected, attempts to (re)connect, backing off as necessary; if 'rc' is
460  * connected, attempts to send packets in the send queue, if any. */
461 void
462 rconn_run(struct rconn *rc)
463 {
464     int old_state;
465     do {
466         old_state = rc->state;
467         switch (rc->state) {
468 #define STATE(NAME, VALUE) case S_##NAME: run_##NAME(rc); break;
469             STATES
470 #undef STATE
471         default:
472             NOT_REACHED();
473         }
474     } while (rc->state != old_state);
475 }
476
477 /* Causes the next call to poll_block() to wake up when rconn_run() should be
478  * called on 'rc'. */
479 void
480 rconn_run_wait(struct rconn *rc)
481 {
482     unsigned int timeo = timeout(rc);
483     if (timeo != UINT_MAX) {
484         unsigned int expires = sat_add(rc->state_entered, timeo);
485         unsigned int remaining = sat_sub(expires, time_now());
486         poll_timer_wait(sat_mul(remaining, 1000));
487     }
488
489     if ((rc->state & (S_ACTIVE | S_IDLE)) && rc->txq.n) {
490         vconn_wait(rc->vconn, WAIT_SEND);
491     }
492 }
493
494 /* Attempts to receive a packet from 'rc'.  If successful, returns the packet;
495  * otherwise, returns a null pointer.  The caller is responsible for freeing
496  * the packet (with ofpbuf_delete()). */
497 struct ofpbuf *
498 rconn_recv(struct rconn *rc)
499 {
500     if (rc->state & (S_ACTIVE | S_IDLE)) {
501         struct ofpbuf *buffer;
502         int error = vconn_recv(rc->vconn, &buffer);
503         if (!error) {
504             copy_to_monitor(rc, buffer);
505             if (rc->probably_admitted || is_admitted_msg(buffer)
506                 || time_now() - rc->last_connected >= 30) {
507                 rc->probably_admitted = true;
508                 rc->last_admitted = time_now();
509             }
510             rc->last_received = time_now();
511             rc->packets_received++;
512             if (rc->state == S_IDLE) {
513                 state_transition(rc, S_ACTIVE);
514             }
515             return buffer;
516         } else if (error != EAGAIN) {
517             report_error(rc, error);
518             disconnect(rc, error);
519         }
520     }
521     return NULL;
522 }
523
524 /* Causes the next call to poll_block() to wake up when a packet may be ready
525  * to be received by vconn_recv() on 'rc'.  */
526 void
527 rconn_recv_wait(struct rconn *rc)
528 {
529     if (rc->vconn) {
530         vconn_wait(rc->vconn, WAIT_RECV);
531     }
532 }
533
534 /* Sends 'b' on 'rc'.  Returns 0 if successful (in which case 'b' is
535  * destroyed), or ENOTCONN if 'rc' is not currently connected (in which case
536  * the caller retains ownership of 'b').
537  *
538  * If 'counter' is non-null, then 'counter' will be incremented while the
539  * packet is in flight, then decremented when it has been sent (or discarded
540  * due to disconnection).  Because 'b' may be sent (or discarded) before this
541  * function returns, the caller may not be able to observe any change in
542  * 'counter'.
543  *
544  * There is no rconn_send_wait() function: an rconn has a send queue that it
545  * takes care of sending if you call rconn_run(), which will have the side
546  * effect of waking up poll_block(). */
547 int
548 rconn_send(struct rconn *rc, struct ofpbuf *b,
549            struct rconn_packet_counter *counter)
550 {
551     if (rconn_is_connected(rc)) {
552         COVERAGE_INC(rconn_queued);
553         copy_to_monitor(rc, b);
554         b->private_p = counter;
555         if (counter) {
556             rconn_packet_counter_inc(counter);
557         }
558         queue_push_tail(&rc->txq, b);
559
560         /* If the queue was empty before we added 'b', try to send some
561          * packets.  (But if the queue had packets in it, it's because the
562          * vconn is backlogged and there's no point in stuffing more into it
563          * now.  We'll get back to that in rconn_run().) */
564         if (rc->txq.n == 1) {
565             try_send(rc);
566         }
567         return 0;
568     } else {
569         return ENOTCONN;
570     }
571 }
572
573 /* Sends 'b' on 'rc'.  Increments 'counter' while the packet is in flight; it
574  * will be decremented when it has been sent (or discarded due to
575  * disconnection).  Returns 0 if successful, EAGAIN if 'counter->n' is already
576  * at least as large as 'queue_limit', or ENOTCONN if 'rc' is not currently
577  * connected.  Regardless of return value, 'b' is destroyed.
578  *
579  * Because 'b' may be sent (or discarded) before this function returns, the
580  * caller may not be able to observe any change in 'counter'.
581  *
582  * There is no rconn_send_wait() function: an rconn has a send queue that it
583  * takes care of sending if you call rconn_run(), which will have the side
584  * effect of waking up poll_block(). */
585 int
586 rconn_send_with_limit(struct rconn *rc, struct ofpbuf *b,
587                       struct rconn_packet_counter *counter, int queue_limit)
588 {
589     int retval;
590     retval = counter->n >= queue_limit ? EAGAIN : rconn_send(rc, b, counter);
591     if (retval) {
592         COVERAGE_INC(rconn_overflow);
593         ofpbuf_delete(b);
594     }
595     return retval;
596 }
597
598 /* Returns the total number of packets successfully sent on the underlying
599  * vconn.  A packet is not counted as sent while it is still queued in the
600  * rconn, only when it has been successfuly passed to the vconn.  */
601 unsigned int
602 rconn_packets_sent(const struct rconn *rc)
603 {
604     return rc->packets_sent;
605 }
606
607 /* Adds 'vconn' to 'rc' as a monitoring connection, to which all messages sent
608  * and received on 'rconn' will be copied.  'rc' takes ownership of 'vconn'. */
609 void
610 rconn_add_monitor(struct rconn *rc, struct vconn *vconn)
611 {
612     if (rc->n_monitors < ARRAY_SIZE(rc->monitors)) {
613         VLOG_INFO("new monitor connection from %s", vconn_get_name(vconn));
614         rc->monitors[rc->n_monitors++] = vconn;
615     } else {
616         VLOG_DBG("too many monitor connections, discarding %s",
617                  vconn_get_name(vconn));
618         vconn_close(vconn);
619     }
620 }
621
622 /* Returns 'rc''s name (the 'name' argument passed to rconn_new()). */
623 const char *
624 rconn_get_name(const struct rconn *rc)
625 {
626     return rc->name;
627 }
628
629 /* Returns true if 'rconn' is connected or in the process of reconnecting,
630  * false if 'rconn' is disconnected and will not reconnect on its own. */
631 bool
632 rconn_is_alive(const struct rconn *rconn)
633 {
634     return rconn->state != S_VOID;
635 }
636
637 /* Returns true if 'rconn' is connected, false otherwise. */
638 bool
639 rconn_is_connected(const struct rconn *rconn)
640 {
641     return is_connected_state(rconn->state);
642 }
643
644 /* Returns true if 'rconn' is connected and thought to have been accepted by
645  * the peer's admission-control policy. */
646 bool
647 rconn_is_admitted(const struct rconn *rconn)
648 {
649     return (rconn_is_connected(rconn)
650             && rconn->last_admitted >= rconn->last_connected);
651 }
652
653 /* Returns 0 if 'rconn' is currently connected and considered to have been
654  * accepted by the peer's admission-control policy, otherwise the number of
655  * seconds since 'rconn' was last in such a state. */
656 int
657 rconn_failure_duration(const struct rconn *rconn)
658 {
659     return rconn_is_admitted(rconn) ? 0 : time_now() - rconn->last_admitted;
660 }
661
662 /* Returns the IP address of the peer, or 0 if the peer's IP address is not
663  * known. */
664 uint32_t
665 rconn_get_remote_ip(const struct rconn *rconn) 
666 {
667     return rconn->remote_ip;
668 }
669
670 /* Returns the transport port of the peer, or 0 if the peer's port is not
671  * known. */
672 uint16_t
673 rconn_get_remote_port(const struct rconn *rconn) 
674 {
675     return rconn->remote_port;
676 }
677
678 /* Returns the IP address used to connect to the peer, or 0 if the
679  * connection is not an IP-based protocol or if its IP address is not 
680  * known. */
681 uint32_t
682 rconn_get_local_ip(const struct rconn *rconn) 
683 {
684     return rconn->local_ip;
685 }
686
687 /* Returns the transport port used to connect to the peer, or 0 if the
688  * connection does not contain a port or if the port is not known. */
689 uint16_t
690 rconn_get_local_port(const struct rconn *rconn) 
691 {
692     return rconn->vconn ? vconn_get_local_port(rconn->vconn) : 0;
693 }
694
695 /* If 'rconn' can't connect to the peer, it could be for any number of reasons.
696  * Usually, one would assume it is because the peer is not running or because
697  * the network is partitioned.  But it could also be because the network
698  * topology has changed, in which case the upper layer will need to reassess it
699  * (in particular, obtain a new IP address via DHCP and find the new location
700  * of the controller).  When this appears that this might be the case, this
701  * function returns true.  It also clears the questionability flag and prevents
702  * it from being set again for some time. */
703 bool
704 rconn_is_connectivity_questionable(struct rconn *rconn)
705 {
706     bool questionable = rconn->questionable_connectivity;
707     rconn->questionable_connectivity = false;
708     return questionable;
709 }
710
711 /* Returns the total number of packets successfully received by the underlying
712  * vconn.  */
713 unsigned int
714 rconn_packets_received(const struct rconn *rc)
715 {
716     return rc->packets_received;
717 }
718
719 /* Returns a string representing the internal state of 'rc'.  The caller must
720  * not modify or free the string. */
721 const char *
722 rconn_get_state(const struct rconn *rc)
723 {
724     return state_name(rc->state);
725 }
726
727 /* Returns the number of connection attempts made by 'rc', including any
728  * ongoing attempt that has not yet succeeded or failed. */
729 unsigned int
730 rconn_get_attempted_connections(const struct rconn *rc)
731 {
732     return rc->n_attempted_connections;
733 }
734
735 /* Returns the number of successful connection attempts made by 'rc'. */
736 unsigned int
737 rconn_get_successful_connections(const struct rconn *rc)
738 {
739     return rc->n_successful_connections;
740 }
741
742 /* Returns the time at which the last successful connection was made by
743  * 'rc'. */
744 time_t
745 rconn_get_last_connection(const struct rconn *rc)
746 {
747     return rc->last_connected;
748 }
749
750 /* Returns the time at which the last OpenFlow message was received by 'rc'.
751  * If no packets have been received on 'rc', returns the time at which 'rc'
752  * was created. */
753 time_t
754 rconn_get_last_received(const struct rconn *rc)
755 {
756     return rc->last_received;
757 }
758
759 /* Returns the time at which 'rc' was created. */
760 time_t
761 rconn_get_creation_time(const struct rconn *rc)
762 {
763     return rc->creation_time;
764 }
765
766 /* Returns the approximate number of seconds that 'rc' has been connected. */
767 unsigned long int
768 rconn_get_total_time_connected(const struct rconn *rc)
769 {
770     return (rc->total_time_connected
771             + (rconn_is_connected(rc) ? elapsed_in_this_state(rc) : 0));
772 }
773
774 /* Returns the current amount of backoff, in seconds.  This is the amount of
775  * time after which the rconn will transition from BACKOFF to CONNECTING. */
776 int
777 rconn_get_backoff(const struct rconn *rc)
778 {
779     return rc->backoff;
780 }
781
782 /* Returns the number of seconds spent in this state so far. */
783 unsigned int
784 rconn_get_state_elapsed(const struct rconn *rc)
785 {
786     return elapsed_in_this_state(rc);
787 }
788
789 /* Returns 'rc''s current connection sequence number, a number that changes
790  * every time that 'rconn' connects or disconnects. */
791 unsigned int
792 rconn_get_connection_seqno(const struct rconn *rc)
793 {
794     return rc->seqno;
795 }
796
797 /* Returns a value that explains why 'rc' last disconnected:
798  *
799  *   - 0 means that the last disconnection was caused by a call to
800  *     rconn_disconnect(), or that 'rc' is new and has not yet completed its
801  *     initial connection or connection attempt.
802  *
803  *   - EOF means that the connection was closed in the normal way by the peer.
804  *
805  *   - A positive integer is an errno value that represents the error.
806  */
807 int
808 rconn_get_last_error(const struct rconn *rc)
809 {
810     return rc->last_error;
811 }
812 \f
813 struct rconn_packet_counter *
814 rconn_packet_counter_create(void)
815 {
816     struct rconn_packet_counter *c = xmalloc(sizeof *c);
817     c->n = 0;
818     c->ref_cnt = 1;
819     return c;
820 }
821
822 void
823 rconn_packet_counter_destroy(struct rconn_packet_counter *c)
824 {
825     if (c) {
826         assert(c->ref_cnt > 0);
827         if (!--c->ref_cnt && !c->n) {
828             free(c);
829         }
830     }
831 }
832
833 void
834 rconn_packet_counter_inc(struct rconn_packet_counter *c)
835 {
836     c->n++;
837 }
838
839 void
840 rconn_packet_counter_dec(struct rconn_packet_counter *c)
841 {
842     assert(c->n > 0);
843     if (!--c->n && !c->ref_cnt) {
844         free(c);
845     }
846 }
847 \f
848 /* Set the name of the remote vconn to 'name' and clear out the cached IP
849  * address and port information, since changing the name also likely changes
850  * these values. */
851 static void
852 set_vconn_name(struct rconn *rc, const char *name)
853 {
854     free(rc->name);
855     rc->name = xstrdup(name);
856     rc->local_ip = 0;
857     rc->remote_ip = 0;
858     rc->remote_port = 0;
859 }
860
861 /* Tries to send a packet from 'rc''s send buffer.  Returns 0 if successful,
862  * otherwise a positive errno value. */
863 static int
864 try_send(struct rconn *rc)
865 {
866     int retval = 0;
867     struct ofpbuf *next = rc->txq.head->next;
868     struct rconn_packet_counter *counter = rc->txq.head->private_p;
869     retval = vconn_send(rc->vconn, rc->txq.head);
870     if (retval) {
871         if (retval != EAGAIN) {
872             report_error(rc, retval);
873             disconnect(rc, retval);
874         }
875         return retval;
876     }
877     COVERAGE_INC(rconn_sent);
878     rc->packets_sent++;
879     if (counter) {
880         rconn_packet_counter_dec(counter);
881     }
882     queue_advance_head(&rc->txq, next);
883     return 0;
884 }
885
886 /* Reports that 'error' caused 'rc' to disconnect.  'error' may be a positive
887  * errno value, or it may be EOF to indicate that the connection was closed
888  * normally. */
889 static void
890 report_error(struct rconn *rc, int error)
891 {
892     if (error == EOF) {
893         /* If 'rc' isn't reliable, then we don't really expect this connection
894          * to last forever anyway (probably it's a connection that we received
895          * via accept()), so use DBG level to avoid cluttering the logs. */
896         enum vlog_level level = rc->reliable ? VLL_INFO : VLL_DBG;
897         VLOG(level, "%s: connection closed by peer", rc->name);
898     } else {
899         VLOG_WARN("%s: connection dropped (%s)", rc->name, strerror(error));
900     }
901 }
902
903 /* Disconnects 'rc' and records 'error' as the error that caused 'rc''s last
904  * disconnection:
905  *
906  *   - 0 means that this disconnection is due to a request by 'rc''s client,
907  *     not due to any kind of network error.
908  *
909  *   - EOF means that the connection was closed in the normal way by the peer.
910  *
911  *   - A positive integer is an errno value that represents the error.
912  */
913 static void
914 disconnect(struct rconn *rc, int error)
915 {
916     rc->last_error = error;
917     if (rc->reliable) {
918         time_t now = time_now();
919
920         if (rc->state & (S_CONNECTING | S_ACTIVE | S_IDLE)) {
921             vconn_close(rc->vconn);
922             rc->vconn = NULL;
923             flush_queue(rc);
924         }
925
926         if (now >= rc->backoff_deadline) {
927             rc->backoff = 1;
928         } else {
929             rc->backoff = MIN(rc->max_backoff, MAX(1, 2 * rc->backoff));
930             VLOG_INFO("%s: waiting %d seconds before reconnect\n",
931                       rc->name, rc->backoff);
932         }
933         rc->backoff_deadline = now + rc->backoff;
934         state_transition(rc, S_BACKOFF);
935         if (now - rc->last_connected > 60) {
936             question_connectivity(rc);
937         }
938     } else {
939         rconn_disconnect(rc);
940     }
941 }
942
943 /* Drops all the packets from 'rc''s send queue and decrements their queue
944  * counts. */
945 static void
946 flush_queue(struct rconn *rc)
947 {
948     if (!rc->txq.n) {
949         return;
950     }
951     while (rc->txq.n > 0) {
952         struct ofpbuf *b = queue_pop_head(&rc->txq);
953         struct rconn_packet_counter *counter = b->private_p;
954         if (counter) {
955             rconn_packet_counter_dec(counter);
956         }
957         COVERAGE_INC(rconn_discarded);
958         ofpbuf_delete(b);
959     }
960     poll_immediate_wake();
961 }
962
963 static unsigned int
964 elapsed_in_this_state(const struct rconn *rc)
965 {
966     return time_now() - rc->state_entered;
967 }
968
969 static unsigned int
970 timeout(const struct rconn *rc)
971 {
972     switch (rc->state) {
973 #define STATE(NAME, VALUE) case S_##NAME: return timeout_##NAME(rc);
974         STATES
975 #undef STATE
976     default:
977         NOT_REACHED();
978     }
979 }
980
981 static bool
982 timed_out(const struct rconn *rc)
983 {
984     return time_now() >= sat_add(rc->state_entered, timeout(rc));
985 }
986
987 static void
988 state_transition(struct rconn *rc, enum state state)
989 {
990     rc->seqno += (rc->state == S_ACTIVE) != (state == S_ACTIVE);
991     if (is_connected_state(state) && !is_connected_state(rc->state)) {
992         rc->probably_admitted = false;
993     }
994     if (rconn_is_connected(rc)) {
995         rc->total_time_connected += elapsed_in_this_state(rc);
996     }
997     VLOG_DBG("%s: entering %s", rc->name, state_name(state));
998     rc->state = state;
999     rc->state_entered = time_now();
1000 }
1001
1002 static void
1003 question_connectivity(struct rconn *rc) 
1004 {
1005     time_t now = time_now();
1006     if (now - rc->last_questioned > 60) {
1007         rc->questionable_connectivity = true;
1008         rc->last_questioned = now;
1009     }
1010 }
1011
1012 static void
1013 copy_to_monitor(struct rconn *rc, const struct ofpbuf *b)
1014 {
1015     struct ofpbuf *clone = NULL;
1016     int retval;
1017     size_t i;
1018
1019     for (i = 0; i < rc->n_monitors; ) {
1020         struct vconn *vconn = rc->monitors[i];
1021
1022         if (!clone) {
1023             clone = ofpbuf_clone(b);
1024         }
1025         retval = vconn_send(vconn, clone);
1026         if (!retval) {
1027             clone = NULL;
1028         } else if (retval != EAGAIN) {
1029             VLOG_DBG("%s: closing monitor connection to %s: %s",
1030                      rconn_get_name(rc), vconn_get_name(vconn),
1031                      strerror(retval));
1032             rc->monitors[i] = rc->monitors[--rc->n_monitors];
1033             continue;
1034         }
1035         i++;
1036     }
1037     ofpbuf_delete(clone);
1038 }
1039
1040 static bool
1041 is_connected_state(enum state state) 
1042 {
1043     return (state & (S_ACTIVE | S_IDLE)) != 0;
1044 }
1045
1046 static bool
1047 is_admitted_msg(const struct ofpbuf *b)
1048 {
1049     struct ofp_header *oh = b->data;
1050     uint8_t type = oh->type;
1051     return !(type < 32
1052              && (1u << type) & ((1u << OFPT_HELLO) |
1053                                 (1u << OFPT_ERROR) |
1054                                 (1u << OFPT_ECHO_REQUEST) |
1055                                 (1u << OFPT_ECHO_REPLY) |
1056                                 (1u << OFPT_VENDOR) |
1057                                 (1u << OFPT_FEATURES_REQUEST) |
1058                                 (1u << OFPT_FEATURES_REPLY) |
1059                                 (1u << OFPT_GET_CONFIG_REQUEST) |
1060                                 (1u << OFPT_GET_CONFIG_REPLY) |
1061                                 (1u << OFPT_SET_CONFIG)));
1062 }