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