connmgr: Drop 'next_in_band_update' timer.
[sliver-openvswitch.git] / ofproto / connmgr.c
1 /*
2  * Copyright (c) 2009, 2010, 2011 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include "connmgr.h"
20
21 #include <errno.h>
22 #include <stdlib.h>
23
24 #include "coverage.h"
25 #include "fail-open.h"
26 #include "in-band.h"
27 #include "odp-util.h"
28 #include "ofp-util.h"
29 #include "ofpbuf.h"
30 #include "ofproto-provider.h"
31 #include "pinsched.h"
32 #include "poll-loop.h"
33 #include "pktbuf.h"
34 #include "rconn.h"
35 #include "shash.h"
36 #include "timeval.h"
37 #include "vconn.h"
38 #include "vlog.h"
39
40 VLOG_DEFINE_THIS_MODULE(connmgr);
41 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
42
43 /* An OpenFlow connection. */
44 struct ofconn {
45     struct connmgr *connmgr;    /* Connection's manager. */
46     struct list node;           /* In struct connmgr's "all_conns" list. */
47     struct rconn *rconn;        /* OpenFlow connection. */
48     enum ofconn_type type;      /* Type. */
49     enum nx_flow_format flow_format; /* Currently selected flow format. */
50     bool flow_mod_table_id;     /* NXT_FLOW_MOD_TABLE_ID enabled? */
51
52     /* Asynchronous flow table operation support. */
53     struct list opgroups;       /* Contains pending "ofopgroups", if any. */
54     struct ofpbuf *blocked;     /* Postponed OpenFlow message, if any. */
55     bool retry;                 /* True if 'blocked' is ready to try again. */
56
57     /* OFPT_PACKET_IN related data. */
58     struct rconn_packet_counter *packet_in_counter; /* # queued on 'rconn'. */
59 #define N_SCHEDULERS 2
60     struct pinsched *schedulers[N_SCHEDULERS];
61     struct pktbuf *pktbuf;         /* OpenFlow packet buffers. */
62     int miss_send_len;             /* Bytes to send of buffered packets. */
63
64     /* Number of OpenFlow messages queued on 'rconn' as replies to OpenFlow
65      * requests, and the maximum number before we stop reading OpenFlow
66      * requests.  */
67 #define OFCONN_REPLY_MAX 100
68     struct rconn_packet_counter *reply_counter;
69
70     /* type == OFCONN_PRIMARY only. */
71     enum nx_role role;           /* Role. */
72     struct hmap_node hmap_node;  /* In struct connmgr's "controllers" map. */
73     enum ofproto_band band;      /* In-band or out-of-band? */
74 };
75
76 static struct ofconn *ofconn_create(struct connmgr *, struct rconn *,
77                                     enum ofconn_type);
78 static void ofconn_destroy(struct ofconn *);
79
80 static void ofconn_reconfigure(struct ofconn *,
81                                const struct ofproto_controller *);
82
83 static void ofconn_run(struct ofconn *,
84                        bool (*handle_openflow)(struct ofconn *,
85                                                struct ofpbuf *ofp_msg));
86 static void ofconn_wait(struct ofconn *, bool handling_openflow);
87
88 static const char *ofconn_get_target(const struct ofconn *);
89 static char *ofconn_make_name(const struct connmgr *, const char *target);
90
91 static void ofconn_set_rate_limit(struct ofconn *, int rate, int burst);
92
93 static bool ofconn_receives_async_msgs(const struct ofconn *);
94
95 static void ofconn_send(const struct ofconn *, struct ofpbuf *,
96                         struct rconn_packet_counter *);
97
98 static void do_send_packet_in(struct ofpbuf *, void *ofconn_);
99
100 /* A listener for incoming OpenFlow "service" connections. */
101 struct ofservice {
102     struct hmap_node node;      /* In struct connmgr's "services" hmap. */
103     struct pvconn *pvconn;      /* OpenFlow connection listener. */
104
105     /* These are not used by ofservice directly.  They are settings for
106      * accepted "struct ofconn"s from the pvconn. */
107     int probe_interval;         /* Max idle time before probing, in seconds. */
108     int rate_limit;             /* Max packet-in rate in packets per second. */
109     int burst_limit;            /* Limit on accumulating packet credits. */
110 };
111
112 static void ofservice_reconfigure(struct ofservice *,
113                                   const struct ofproto_controller *);
114 static int ofservice_create(struct connmgr *, const char *target);
115 static void ofservice_destroy(struct connmgr *, struct ofservice *);
116 static struct ofservice *ofservice_lookup(struct connmgr *,
117                                           const char *target);
118
119 /* Connection manager for an OpenFlow switch. */
120 struct connmgr {
121     struct ofproto *ofproto;
122     char *name;
123     char *local_port_name;
124
125     /* OpenFlow connections. */
126     struct hmap controllers;   /* Controller "struct ofconn"s. */
127     struct list all_conns;     /* Contains "struct ofconn"s. */
128
129     /* OpenFlow listeners. */
130     struct hmap services;       /* Contains "struct ofservice"s. */
131     struct pvconn **snoops;
132     size_t n_snoops;
133
134     /* Fail open. */
135     struct fail_open *fail_open;
136     enum ofproto_fail_mode fail_mode;
137
138     /* In-band control. */
139     struct in_band *in_band;
140     struct sockaddr_in *extra_in_band_remotes;
141     size_t n_extra_remotes;
142     int in_band_queue;
143 };
144
145 static void update_in_band_remotes(struct connmgr *);
146 static void add_snooper(struct connmgr *, struct vconn *);
147
148 /* Creates and returns a new connection manager owned by 'ofproto'.  'name' is
149  * a name for the ofproto suitable for using in log messages.
150  * 'local_port_name' is the name of the local port (OFPP_LOCAL) within
151  * 'ofproto'. */
152 struct connmgr *
153 connmgr_create(struct ofproto *ofproto,
154                const char *name, const char *local_port_name)
155 {
156     struct connmgr *mgr;
157
158     mgr = xmalloc(sizeof *mgr);
159     mgr->ofproto = ofproto;
160     mgr->name = xstrdup(name);
161     mgr->local_port_name = xstrdup(local_port_name);
162
163     hmap_init(&mgr->controllers);
164     list_init(&mgr->all_conns);
165
166     hmap_init(&mgr->services);
167     mgr->snoops = NULL;
168     mgr->n_snoops = 0;
169
170     mgr->fail_open = NULL;
171     mgr->fail_mode = OFPROTO_FAIL_SECURE;
172
173     mgr->in_band = NULL;
174     mgr->extra_in_band_remotes = NULL;
175     mgr->n_extra_remotes = 0;
176     mgr->in_band_queue = -1;
177
178     return mgr;
179 }
180
181 /* Frees 'mgr' and all of its resources. */
182 void
183 connmgr_destroy(struct connmgr *mgr)
184 {
185     struct ofservice *ofservice, *next_ofservice;
186     struct ofconn *ofconn, *next_ofconn;
187     size_t i;
188
189     if (!mgr) {
190         return;
191     }
192
193     LIST_FOR_EACH_SAFE (ofconn, next_ofconn, node, &mgr->all_conns) {
194         ofconn_destroy(ofconn);
195     }
196     hmap_destroy(&mgr->controllers);
197
198     HMAP_FOR_EACH_SAFE (ofservice, next_ofservice, node, &mgr->services) {
199         ofservice_destroy(mgr, ofservice);
200     }
201     hmap_destroy(&mgr->services);
202
203     for (i = 0; i < mgr->n_snoops; i++) {
204         pvconn_close(mgr->snoops[i]);
205     }
206     free(mgr->snoops);
207
208     fail_open_destroy(mgr->fail_open);
209     mgr->fail_open = NULL;
210
211     in_band_destroy(mgr->in_band);
212     mgr->in_band = NULL;
213     free(mgr->extra_in_band_remotes);
214     free(mgr->name);
215     free(mgr->local_port_name);
216
217     free(mgr);
218 }
219
220 /* Does all of the periodic maintenance required by 'mgr'.
221  *
222  * If 'handle_openflow' is nonnull, calls 'handle_openflow' for each message
223  * received on an OpenFlow connection, passing along the OpenFlow connection
224  * itself and the message that was sent.  If 'handle_openflow' returns true,
225  * the message is considered to be fully processed.  If 'handle_openflow'
226  * returns false, the message is considered not to have been processed at all;
227  * it will be stored and re-presented to 'handle_openflow' following the next
228  * call to connmgr_retry().  'handle_openflow' must not modify or free the
229  * message.
230  *
231  * If 'handle_openflow' is NULL, no OpenFlow messages will be processed and
232  * other activities that could affect the flow table (in-band processing,
233  * fail-open processing) are suppressed too. */
234 void
235 connmgr_run(struct connmgr *mgr,
236             bool (*handle_openflow)(struct ofconn *, struct ofpbuf *ofp_msg))
237 {
238     struct ofconn *ofconn, *next_ofconn;
239     struct ofservice *ofservice;
240     size_t i;
241
242     if (handle_openflow && mgr->in_band) {
243         in_band_run(mgr->in_band);
244     }
245
246     LIST_FOR_EACH_SAFE (ofconn, next_ofconn, node, &mgr->all_conns) {
247         ofconn_run(ofconn, handle_openflow);
248     }
249
250     /* Fail-open maintenance.  Do this after processing the ofconns since
251      * fail-open checks the status of the controller rconn. */
252     if (handle_openflow && mgr->fail_open) {
253         fail_open_run(mgr->fail_open);
254     }
255
256     HMAP_FOR_EACH (ofservice, node, &mgr->services) {
257         struct vconn *vconn;
258         int retval;
259
260         retval = pvconn_accept(ofservice->pvconn, OFP_VERSION, &vconn);
261         if (!retval) {
262             struct rconn *rconn;
263             char *name;
264
265             rconn = rconn_create(ofservice->probe_interval, 0);
266             name = ofconn_make_name(mgr, vconn_get_name(vconn));
267             rconn_connect_unreliably(rconn, vconn, name);
268             free(name);
269
270             ofconn = ofconn_create(mgr, rconn, OFCONN_SERVICE);
271             ofconn_set_rate_limit(ofconn, ofservice->rate_limit,
272                                   ofservice->burst_limit);
273         } else if (retval != EAGAIN) {
274             VLOG_WARN_RL(&rl, "accept failed (%s)", strerror(retval));
275         }
276     }
277
278     for (i = 0; i < mgr->n_snoops; i++) {
279         struct vconn *vconn;
280         int retval;
281
282         retval = pvconn_accept(mgr->snoops[i], OFP_VERSION, &vconn);
283         if (!retval) {
284             add_snooper(mgr, vconn);
285         } else if (retval != EAGAIN) {
286             VLOG_WARN_RL(&rl, "accept failed (%s)", strerror(retval));
287         }
288     }
289 }
290
291 /* Causes the poll loop to wake up when connmgr_run() needs to run.
292  *
293  * If 'handling_openflow' is true, arriving OpenFlow messages and other
294  * activities that affect the flow table will wake up the poll loop.  If
295  * 'handling_openflow' is false, they will not. */
296 void
297 connmgr_wait(struct connmgr *mgr, bool handling_openflow)
298 {
299     struct ofservice *ofservice;
300     struct ofconn *ofconn;
301     size_t i;
302
303     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
304         ofconn_wait(ofconn, handling_openflow);
305     }
306     if (handling_openflow && mgr->in_band) {
307         in_band_wait(mgr->in_band);
308     }
309     if (handling_openflow && mgr->fail_open) {
310         fail_open_wait(mgr->fail_open);
311     }
312     HMAP_FOR_EACH (ofservice, node, &mgr->services) {
313         pvconn_wait(ofservice->pvconn);
314     }
315     for (i = 0; i < mgr->n_snoops; i++) {
316         pvconn_wait(mgr->snoops[i]);
317     }
318 }
319
320 /* Returns the ofproto that owns 'ofconn''s connmgr. */
321 struct ofproto *
322 ofconn_get_ofproto(const struct ofconn *ofconn)
323 {
324     return ofconn->connmgr->ofproto;
325 }
326
327 /* If processing of OpenFlow messages was blocked on any 'mgr' ofconns by
328  * returning false to the 'handle_openflow' callback to connmgr_run(), this
329  * re-enables them. */
330 void
331 connmgr_retry(struct connmgr *mgr)
332 {
333     struct ofconn *ofconn;
334
335     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
336         ofconn->retry = true;
337     }
338 }
339 \f
340 /* OpenFlow configuration. */
341
342 static void add_controller(struct connmgr *, const char *target);
343 static struct ofconn *find_controller_by_target(struct connmgr *,
344                                                 const char *target);
345 static void update_fail_open(struct connmgr *);
346 static int set_pvconns(struct pvconn ***pvconnsp, size_t *n_pvconnsp,
347                        const struct sset *);
348
349 /* Returns true if 'mgr' has any configured primary controllers.
350  *
351  * Service controllers do not count, but configured primary controllers do
352  * count whether or not they are currently connected. */
353 bool
354 connmgr_has_controllers(const struct connmgr *mgr)
355 {
356     return !hmap_is_empty(&mgr->controllers);
357 }
358
359 /* Initializes 'info' and populates it with information about each configured
360  * primary controller.  The keys in 'info' are the controllers' targets; the
361  * data values are corresponding "struct ofproto_controller_info".
362  *
363  * The caller owns 'info' and everything in it and should free it when it is no
364  * longer needed. */
365 void
366 connmgr_get_controller_info(struct connmgr *mgr, struct shash *info)
367 {
368     const struct ofconn *ofconn;
369
370     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
371         const struct rconn *rconn = ofconn->rconn;
372         const char *target = rconn_get_target(rconn);
373
374         if (!shash_find(info, target)) {
375             struct ofproto_controller_info *cinfo = xmalloc(sizeof *cinfo);
376             time_t now = time_now();
377             time_t last_connection = rconn_get_last_connection(rconn);
378             time_t last_disconnect = rconn_get_last_disconnect(rconn);
379             int last_error = rconn_get_last_error(rconn);
380
381             shash_add(info, target, cinfo);
382
383             cinfo->is_connected = rconn_is_connected(rconn);
384             cinfo->role = ofconn->role;
385
386             cinfo->pairs.n = 0;
387
388             if (last_error) {
389                 cinfo->pairs.keys[cinfo->pairs.n] = "last_error";
390                 cinfo->pairs.values[cinfo->pairs.n++]
391                     = xstrdup(ovs_retval_to_string(last_error));
392             }
393
394             cinfo->pairs.keys[cinfo->pairs.n] = "state";
395             cinfo->pairs.values[cinfo->pairs.n++]
396                 = xstrdup(rconn_get_state(rconn));
397
398             if (last_connection != TIME_MIN) {
399                 cinfo->pairs.keys[cinfo->pairs.n] = "sec_since_connect";
400                 cinfo->pairs.values[cinfo->pairs.n++]
401                     = xasprintf("%ld", (long int) (now - last_connection));
402             }
403
404             if (last_disconnect != TIME_MIN) {
405                 cinfo->pairs.keys[cinfo->pairs.n] = "sec_since_disconnect";
406                 cinfo->pairs.values[cinfo->pairs.n++]
407                     = xasprintf("%ld", (long int) (now - last_disconnect));
408             }
409         }
410     }
411 }
412
413 void
414 connmgr_free_controller_info(struct shash *info)
415 {
416     struct shash_node *node;
417
418     SHASH_FOR_EACH (node, info) {
419         struct ofproto_controller_info *cinfo = node->data;
420         while (cinfo->pairs.n) {
421             free((char *) cinfo->pairs.values[--cinfo->pairs.n]);
422         }
423         free(cinfo);
424     }
425     shash_destroy(info);
426 }
427
428 /* Changes 'mgr''s set of controllers to the 'n_controllers' controllers in
429  * 'controllers'. */
430 void
431 connmgr_set_controllers(struct connmgr *mgr,
432                         const struct ofproto_controller *controllers,
433                         size_t n_controllers)
434 {
435     bool had_controllers = connmgr_has_controllers(mgr);
436     struct shash new_controllers;
437     struct ofconn *ofconn, *next_ofconn;
438     struct ofservice *ofservice, *next_ofservice;
439     size_t i;
440
441     /* Create newly configured controllers and services.
442      * Create a name to ofproto_controller mapping in 'new_controllers'. */
443     shash_init(&new_controllers);
444     for (i = 0; i < n_controllers; i++) {
445         const struct ofproto_controller *c = &controllers[i];
446
447         if (!vconn_verify_name(c->target)) {
448             if (!find_controller_by_target(mgr, c->target)) {
449                 add_controller(mgr, c->target);
450             }
451         } else if (!pvconn_verify_name(c->target)) {
452             if (!ofservice_lookup(mgr, c->target)) {
453                 ofservice_create(mgr, c->target);
454             }
455         } else {
456             VLOG_WARN_RL(&rl, "%s: unsupported controller \"%s\"",
457                          mgr->name, c->target);
458             continue;
459         }
460
461         shash_add_once(&new_controllers, c->target, &controllers[i]);
462     }
463
464     /* Delete controllers that are no longer configured.
465      * Update configuration of all now-existing controllers. */
466     HMAP_FOR_EACH_SAFE (ofconn, next_ofconn, hmap_node, &mgr->controllers) {
467         struct ofproto_controller *c;
468
469         c = shash_find_data(&new_controllers, ofconn_get_target(ofconn));
470         if (!c) {
471             ofconn_destroy(ofconn);
472         } else {
473             ofconn_reconfigure(ofconn, c);
474         }
475     }
476
477     /* Delete services that are no longer configured.
478      * Update configuration of all now-existing services. */
479     HMAP_FOR_EACH_SAFE (ofservice, next_ofservice, node, &mgr->services) {
480         struct ofproto_controller *c;
481
482         c = shash_find_data(&new_controllers,
483                             pvconn_get_name(ofservice->pvconn));
484         if (!c) {
485             ofservice_destroy(mgr, ofservice);
486         } else {
487             ofservice_reconfigure(ofservice, c);
488         }
489     }
490
491     shash_destroy(&new_controllers);
492
493     update_in_band_remotes(mgr);
494     update_fail_open(mgr);
495     if (had_controllers != connmgr_has_controllers(mgr)) {
496         ofproto_flush_flows(mgr->ofproto);
497     }
498 }
499
500 /* Drops the connections between 'mgr' and all of its primary and secondary
501  * controllers, forcing them to reconnect. */
502 void
503 connmgr_reconnect(const struct connmgr *mgr)
504 {
505     struct ofconn *ofconn;
506
507     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
508         rconn_reconnect(ofconn->rconn);
509     }
510 }
511
512 /* Sets the "snoops" for 'mgr' to the pvconn targets listed in 'snoops'.
513  *
514  * A "snoop" is a pvconn to which every OpenFlow message to or from the most
515  * important controller on 'mgr' is mirrored. */
516 int
517 connmgr_set_snoops(struct connmgr *mgr, const struct sset *snoops)
518 {
519     return set_pvconns(&mgr->snoops, &mgr->n_snoops, snoops);
520 }
521
522 /* Adds each of the snoops currently configured on 'mgr' to 'snoops'. */
523 void
524 connmgr_get_snoops(const struct connmgr *mgr, struct sset *snoops)
525 {
526     size_t i;
527
528     for (i = 0; i < mgr->n_snoops; i++) {
529         sset_add(snoops, pvconn_get_name(mgr->snoops[i]));
530     }
531 }
532
533 /* Returns true if 'mgr' has at least one snoop, false if it has none. */
534 bool
535 connmgr_has_snoops(const struct connmgr *mgr)
536 {
537     return mgr->n_snoops > 0;
538 }
539
540 /* Creates a new controller for 'target' in 'mgr'.  update_controller() needs
541  * to be called later to finish the new ofconn's configuration. */
542 static void
543 add_controller(struct connmgr *mgr, const char *target)
544 {
545     char *name = ofconn_make_name(mgr, target);
546     struct ofconn *ofconn;
547
548     ofconn = ofconn_create(mgr, rconn_create(5, 8), OFCONN_PRIMARY);
549     ofconn->pktbuf = pktbuf_create();
550     ofconn->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
551     rconn_connect(ofconn->rconn, target, name);
552     hmap_insert(&mgr->controllers, &ofconn->hmap_node, hash_string(target, 0));
553
554     free(name);
555 }
556
557 static struct ofconn *
558 find_controller_by_target(struct connmgr *mgr, const char *target)
559 {
560     struct ofconn *ofconn;
561
562     HMAP_FOR_EACH_WITH_HASH (ofconn, hmap_node,
563                              hash_string(target, 0), &mgr->controllers) {
564         if (!strcmp(ofconn_get_target(ofconn), target)) {
565             return ofconn;
566         }
567     }
568     return NULL;
569 }
570
571 static void
572 update_in_band_remotes(struct connmgr *mgr)
573 {
574     struct sockaddr_in *addrs;
575     size_t max_addrs, n_addrs;
576     struct ofconn *ofconn;
577     size_t i;
578
579     /* Allocate enough memory for as many remotes as we could possibly have. */
580     max_addrs = mgr->n_extra_remotes + hmap_count(&mgr->controllers);
581     addrs = xmalloc(max_addrs * sizeof *addrs);
582     n_addrs = 0;
583
584     /* Add all the remotes. */
585     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
586         struct sockaddr_in *sin = &addrs[n_addrs];
587
588         if (ofconn->band == OFPROTO_OUT_OF_BAND) {
589             continue;
590         }
591
592         sin->sin_addr.s_addr = rconn_get_remote_ip(ofconn->rconn);
593         if (sin->sin_addr.s_addr) {
594             sin->sin_port = rconn_get_remote_port(ofconn->rconn);
595             n_addrs++;
596         }
597     }
598     for (i = 0; i < mgr->n_extra_remotes; i++) {
599         addrs[n_addrs++] = mgr->extra_in_band_remotes[i];
600     }
601
602     /* Create or update or destroy in-band. */
603     if (n_addrs) {
604         if (!mgr->in_band) {
605             in_band_create(mgr->ofproto, mgr->local_port_name, &mgr->in_band);
606         }
607         if (mgr->in_band) {
608             in_band_set_remotes(mgr->in_band, addrs, n_addrs);
609         }
610         in_band_set_queue(mgr->in_band, mgr->in_band_queue);
611     } else {
612         in_band_destroy(mgr->in_band);
613         mgr->in_band = NULL;
614     }
615
616     /* Clean up. */
617     free(addrs);
618 }
619
620 static void
621 update_fail_open(struct connmgr *mgr)
622 {
623     if (connmgr_has_controllers(mgr)
624         && mgr->fail_mode == OFPROTO_FAIL_STANDALONE) {
625         if (!mgr->fail_open) {
626             mgr->fail_open = fail_open_create(mgr->ofproto, mgr);
627         }
628     } else {
629         fail_open_destroy(mgr->fail_open);
630         mgr->fail_open = NULL;
631     }
632 }
633
634 static int
635 set_pvconns(struct pvconn ***pvconnsp, size_t *n_pvconnsp,
636             const struct sset *sset)
637 {
638     struct pvconn **pvconns = *pvconnsp;
639     size_t n_pvconns = *n_pvconnsp;
640     const char *name;
641     int retval = 0;
642     size_t i;
643
644     for (i = 0; i < n_pvconns; i++) {
645         pvconn_close(pvconns[i]);
646     }
647     free(pvconns);
648
649     pvconns = xmalloc(sset_count(sset) * sizeof *pvconns);
650     n_pvconns = 0;
651     SSET_FOR_EACH (name, sset) {
652         struct pvconn *pvconn;
653         int error;
654
655         error = pvconn_open(name, &pvconn);
656         if (!error) {
657             pvconns[n_pvconns++] = pvconn;
658         } else {
659             VLOG_ERR("failed to listen on %s: %s", name, strerror(error));
660             if (!retval) {
661                 retval = error;
662             }
663         }
664     }
665
666     *pvconnsp = pvconns;
667     *n_pvconnsp = n_pvconns;
668
669     return retval;
670 }
671
672 /* Returns a "preference level" for snooping 'ofconn'.  A higher return value
673  * means that 'ofconn' is more interesting for monitoring than a lower return
674  * value. */
675 static int
676 snoop_preference(const struct ofconn *ofconn)
677 {
678     switch (ofconn->role) {
679     case NX_ROLE_MASTER:
680         return 3;
681     case NX_ROLE_OTHER:
682         return 2;
683     case NX_ROLE_SLAVE:
684         return 1;
685     default:
686         /* Shouldn't happen. */
687         return 0;
688     }
689 }
690
691 /* One of 'mgr''s "snoop" pvconns has accepted a new connection on 'vconn'.
692  * Connects this vconn to a controller. */
693 static void
694 add_snooper(struct connmgr *mgr, struct vconn *vconn)
695 {
696     struct ofconn *ofconn, *best;
697
698     /* Pick a controller for monitoring. */
699     best = NULL;
700     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
701         if (ofconn->type == OFCONN_PRIMARY
702             && (!best || snoop_preference(ofconn) > snoop_preference(best))) {
703             best = ofconn;
704         }
705     }
706
707     if (best) {
708         rconn_add_monitor(best->rconn, vconn);
709     } else {
710         VLOG_INFO_RL(&rl, "no controller connection to snoop");
711         vconn_close(vconn);
712     }
713 }
714 \f
715 /* Public ofconn functions. */
716
717 /* Returns the connection type, either OFCONN_PRIMARY or OFCONN_SERVICE. */
718 enum ofconn_type
719 ofconn_get_type(const struct ofconn *ofconn)
720 {
721     return ofconn->type;
722 }
723
724 /* Returns the role configured for 'ofconn'.
725  *
726  * The default role, if no other role has been set, is NX_ROLE_OTHER. */
727 enum nx_role
728 ofconn_get_role(const struct ofconn *ofconn)
729 {
730     return ofconn->role;
731 }
732
733 /* Changes 'ofconn''s role to 'role'.  If 'role' is NX_ROLE_MASTER then any
734  * existing master is demoted to a slave. */
735 void
736 ofconn_set_role(struct ofconn *ofconn, enum nx_role role)
737 {
738     if (role == NX_ROLE_MASTER) {
739         struct ofconn *other;
740
741         HMAP_FOR_EACH (other, hmap_node, &ofconn->connmgr->controllers) {
742             if (other->role == NX_ROLE_MASTER) {
743                 other->role = NX_ROLE_SLAVE;
744             }
745         }
746     }
747     ofconn->role = role;
748 }
749
750 /* Returns the currently configured flow format for 'ofconn', one of NXFF_*.
751  *
752  * The default, if no other format has been set, is NXFF_OPENFLOW10. */
753 enum nx_flow_format
754 ofconn_get_flow_format(struct ofconn *ofconn)
755 {
756     return ofconn->flow_format;
757 }
758
759 /* Sets the flow format for 'ofconn' to 'flow_format' (one of NXFF_*). */
760 void
761 ofconn_set_flow_format(struct ofconn *ofconn, enum nx_flow_format flow_format)
762 {
763     ofconn->flow_format = flow_format;
764 }
765
766 /* Returns true if the NXT_FLOW_MOD_TABLE_ID extension is enabled, false
767  * otherwise.
768  *
769  * By default the extension is not enabled. */
770 bool
771 ofconn_get_flow_mod_table_id(const struct ofconn *ofconn)
772 {
773     return ofconn->flow_mod_table_id;
774 }
775
776 /* Enables or disables (according to 'enable') the NXT_FLOW_MOD_TABLE_ID
777  * extension on 'ofconn'. */
778 void
779 ofconn_set_flow_mod_table_id(struct ofconn *ofconn, bool enable)
780 {
781     ofconn->flow_mod_table_id = enable;
782 }
783
784 /* Returns the default miss send length for 'ofconn'. */
785 int
786 ofconn_get_miss_send_len(const struct ofconn *ofconn)
787 {
788     return ofconn->miss_send_len;
789 }
790
791 /* Sets the default miss send length for 'ofconn' to 'miss_send_len'. */
792 void
793 ofconn_set_miss_send_len(struct ofconn *ofconn, int miss_send_len)
794 {
795     ofconn->miss_send_len = miss_send_len;
796 }
797
798 /* Sends 'msg' on 'ofconn', accounting it as a reply.  (If there is a
799  * sufficient number of OpenFlow replies in-flight on a single ofconn, then the
800  * connmgr will stop accepting new OpenFlow requests on that ofconn until the
801  * controller has accepted some of the replies.) */
802 void
803 ofconn_send_reply(const struct ofconn *ofconn, struct ofpbuf *msg)
804 {
805     ofconn_send(ofconn, msg, ofconn->reply_counter);
806 }
807
808 /* Sends each of the messages in list 'replies' on 'ofconn' in order,
809  * accounting them as replies. */
810 void
811 ofconn_send_replies(const struct ofconn *ofconn, struct list *replies)
812 {
813     struct ofpbuf *reply, *next;
814
815     LIST_FOR_EACH_SAFE (reply, next, list_node, replies) {
816         list_remove(&reply->list_node);
817         ofconn_send_reply(ofconn, reply);
818     }
819 }
820
821 /* Sends 'error', which should be an OpenFlow error created with
822  * e.g. ofp_mkerr(), on 'ofconn', as a reply to 'request'.  Only at most the
823  * first 64 bytes of 'request' are used. */
824 void
825 ofconn_send_error(const struct ofconn *ofconn,
826                   const struct ofp_header *request, int error)
827 {
828     struct ofpbuf *msg = ofputil_encode_error_msg(error, request);
829     if (msg) {
830         ofconn_send_reply(ofconn, msg);
831     }
832 }
833
834 /* Same as pktbuf_retrieve(), using the pktbuf owned by 'ofconn'. */
835 int
836 ofconn_pktbuf_retrieve(struct ofconn *ofconn, uint32_t id,
837                        struct ofpbuf **bufferp, uint16_t *in_port)
838 {
839     return pktbuf_retrieve(ofconn->pktbuf, id, bufferp, in_port);
840 }
841
842 /* Returns true if 'ofconn' has any pending opgroups. */
843 bool
844 ofconn_has_pending_opgroups(const struct ofconn *ofconn)
845 {
846     return !list_is_empty(&ofconn->opgroups);
847 }
848
849 /* Returns the number of pending opgroups on 'ofconn'. */
850 size_t
851 ofconn_n_pending_opgroups(const struct ofconn *ofconn)
852 {
853     return list_size(&ofconn->opgroups);
854 }
855
856 /* Adds 'ofconn_node' to 'ofconn''s list of pending opgroups.
857  *
858  * If 'ofconn' is destroyed or its connection drops, then 'ofconn' will remove
859  * 'ofconn_node' from the list and re-initialize it with list_init().  The
860  * client may, therefore, use list_is_empty(ofconn_node) to determine whether
861  * 'ofconn_node' is still associated with an active ofconn.
862  *
863  * The client may also remove ofconn_node from the list itself, with
864  * list_remove(). */
865 void
866 ofconn_add_opgroup(struct ofconn *ofconn, struct list *ofconn_node)
867 {
868     list_push_back(&ofconn->opgroups, ofconn_node);
869 }
870 \f
871 /* Private ofconn functions. */
872
873 static const char *
874 ofconn_get_target(const struct ofconn *ofconn)
875 {
876     return rconn_get_target(ofconn->rconn);
877 }
878
879 static struct ofconn *
880 ofconn_create(struct connmgr *mgr, struct rconn *rconn, enum ofconn_type type)
881 {
882     struct ofconn *ofconn = xzalloc(sizeof *ofconn);
883     ofconn->connmgr = mgr;
884     list_push_back(&mgr->all_conns, &ofconn->node);
885     ofconn->rconn = rconn;
886     ofconn->type = type;
887     ofconn->flow_format = NXFF_OPENFLOW10;
888     ofconn->flow_mod_table_id = false;
889     list_init(&ofconn->opgroups);
890     ofconn->role = NX_ROLE_OTHER;
891     ofconn->packet_in_counter = rconn_packet_counter_create ();
892     ofconn->pktbuf = NULL;
893     ofconn->miss_send_len = 0;
894     ofconn->reply_counter = rconn_packet_counter_create ();
895     return ofconn;
896 }
897
898 /* Disassociates 'ofconn' from all of the ofopgroups that it initiated that
899  * have not yet completed.  (Those ofopgroups will still run to completion in
900  * the usual way, but any errors that they run into will not be reported on any
901  * OpenFlow channel.)
902  *
903  * Also discards any blocked operation on 'ofconn'. */
904 static void
905 ofconn_flush(struct ofconn *ofconn)
906 {
907     while (!list_is_empty(&ofconn->opgroups)) {
908         list_init(list_pop_front(&ofconn->opgroups));
909     }
910     ofpbuf_delete(ofconn->blocked);
911     ofconn->blocked = NULL;
912 }
913
914 static void
915 ofconn_destroy(struct ofconn *ofconn)
916 {
917     ofconn_flush(ofconn);
918
919     if (ofconn->type == OFCONN_PRIMARY) {
920         hmap_remove(&ofconn->connmgr->controllers, &ofconn->hmap_node);
921     }
922
923     list_remove(&ofconn->node);
924     rconn_destroy(ofconn->rconn);
925     rconn_packet_counter_destroy(ofconn->packet_in_counter);
926     rconn_packet_counter_destroy(ofconn->reply_counter);
927     pktbuf_destroy(ofconn->pktbuf);
928     free(ofconn);
929 }
930
931 /* Reconfigures 'ofconn' to match 'c'.  'ofconn' and 'c' must have the same
932  * target. */
933 static void
934 ofconn_reconfigure(struct ofconn *ofconn, const struct ofproto_controller *c)
935 {
936     int probe_interval;
937
938     ofconn->band = c->band;
939
940     rconn_set_max_backoff(ofconn->rconn, c->max_backoff);
941
942     probe_interval = c->probe_interval ? MAX(c->probe_interval, 5) : 0;
943     rconn_set_probe_interval(ofconn->rconn, probe_interval);
944
945     ofconn_set_rate_limit(ofconn, c->rate_limit, c->burst_limit);
946 }
947
948 /* Returns true if it makes sense for 'ofconn' to receive and process OpenFlow
949  * messages. */
950 static bool
951 ofconn_may_recv(const struct ofconn *ofconn)
952 {
953     int count = rconn_packet_counter_read (ofconn->reply_counter);
954     return (!ofconn->blocked || ofconn->retry) && count < OFCONN_REPLY_MAX;
955 }
956
957 static void
958 ofconn_run(struct ofconn *ofconn,
959            bool (*handle_openflow)(struct ofconn *, struct ofpbuf *ofp_msg))
960 {
961     struct connmgr *mgr = ofconn->connmgr;
962     size_t i;
963
964     for (i = 0; i < N_SCHEDULERS; i++) {
965         pinsched_run(ofconn->schedulers[i], do_send_packet_in, ofconn);
966     }
967
968     rconn_run(ofconn->rconn);
969
970     if (handle_openflow) {
971         /* Limit the number of iterations to avoid starving other tasks. */
972         for (i = 0; i < 50 && ofconn_may_recv(ofconn); i++) {
973             struct ofpbuf *of_msg;
974
975             of_msg = (ofconn->blocked
976                       ? ofconn->blocked
977                       : rconn_recv(ofconn->rconn));
978             if (!of_msg) {
979                 break;
980             }
981             if (mgr->fail_open) {
982                 fail_open_maybe_recover(mgr->fail_open);
983             }
984
985             if (handle_openflow(ofconn, of_msg)) {
986                 ofpbuf_delete(of_msg);
987                 ofconn->blocked = NULL;
988             } else {
989                 ofconn->blocked = of_msg;
990                 ofconn->retry = false;
991             }
992         }
993     }
994
995     if (!rconn_is_alive(ofconn->rconn)) {
996         ofconn_destroy(ofconn);
997     } else if (!rconn_is_connected(ofconn->rconn)) {
998         ofconn_flush(ofconn);
999     }
1000 }
1001
1002 static void
1003 ofconn_wait(struct ofconn *ofconn, bool handling_openflow)
1004 {
1005     int i;
1006
1007     for (i = 0; i < N_SCHEDULERS; i++) {
1008         pinsched_wait(ofconn->schedulers[i]);
1009     }
1010     rconn_run_wait(ofconn->rconn);
1011     if (handling_openflow && ofconn_may_recv(ofconn)) {
1012         rconn_recv_wait(ofconn->rconn);
1013     }
1014 }
1015
1016 /* Returns true if 'ofconn' should receive asynchronous messages. */
1017 static bool
1018 ofconn_receives_async_msgs(const struct ofconn *ofconn)
1019 {
1020     if (!rconn_is_connected(ofconn->rconn)) {
1021         return false;
1022     } else if (ofconn->type == OFCONN_PRIMARY) {
1023         /* Primary controllers always get asynchronous messages unless they
1024          * have configured themselves as "slaves".  */
1025         return ofconn->role != NX_ROLE_SLAVE;
1026     } else {
1027         /* Service connections don't get asynchronous messages unless they have
1028          * explicitly asked for them by setting a nonzero miss send length. */
1029         return ofconn->miss_send_len > 0;
1030     }
1031 }
1032
1033 /* Returns a human-readable name for an OpenFlow connection between 'mgr' and
1034  * 'target', suitable for use in log messages for identifying the connection.
1035  *
1036  * The name is dynamically allocated.  The caller should free it (with free())
1037  * when it is no longer needed. */
1038 static char *
1039 ofconn_make_name(const struct connmgr *mgr, const char *target)
1040 {
1041     return xasprintf("%s<->%s", mgr->name, target);
1042 }
1043
1044 static void
1045 ofconn_set_rate_limit(struct ofconn *ofconn, int rate, int burst)
1046 {
1047     int i;
1048
1049     for (i = 0; i < N_SCHEDULERS; i++) {
1050         struct pinsched **s = &ofconn->schedulers[i];
1051
1052         if (rate > 0) {
1053             if (!*s) {
1054                 *s = pinsched_create(rate, burst);
1055             } else {
1056                 pinsched_set_limits(*s, rate, burst);
1057             }
1058         } else {
1059             pinsched_destroy(*s);
1060             *s = NULL;
1061         }
1062     }
1063 }
1064
1065 static void
1066 ofconn_send(const struct ofconn *ofconn, struct ofpbuf *msg,
1067             struct rconn_packet_counter *counter)
1068 {
1069     update_openflow_length(msg);
1070     if (rconn_send(ofconn->rconn, msg, counter)) {
1071         ofpbuf_delete(msg);
1072     }
1073 }
1074 \f
1075 /* Sending asynchronous messages. */
1076
1077 static void schedule_packet_in(struct ofconn *, struct ofputil_packet_in,
1078                                const struct flow *, struct ofpbuf *rw_packet);
1079
1080 /* Sends an OFPT_PORT_STATUS message with 'opp' and 'reason' to appropriate
1081  * controllers managed by 'mgr'. */
1082 void
1083 connmgr_send_port_status(struct connmgr *mgr, const struct ofp_phy_port *opp,
1084                          uint8_t reason)
1085 {
1086     /* XXX Should limit the number of queued port status change messages. */
1087     struct ofconn *ofconn;
1088
1089     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
1090         struct ofp_port_status *ops;
1091         struct ofpbuf *b;
1092
1093         /* Primary controllers, even slaves, should always get port status
1094            updates.  Otherwise obey ofconn_receives_async_msgs(). */
1095         if (ofconn->type != OFCONN_PRIMARY
1096             && !ofconn_receives_async_msgs(ofconn)) {
1097             continue;
1098         }
1099
1100         ops = make_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, 0, &b);
1101         ops->reason = reason;
1102         ops->desc = *opp;
1103         ofconn_send(ofconn, b, NULL);
1104     }
1105 }
1106
1107 /* Sends an OFPT_FLOW_REMOVED or NXT_FLOW_REMOVED message based on 'fr' to
1108  * appropriate controllers managed by 'mgr'. */
1109 void
1110 connmgr_send_flow_removed(struct connmgr *mgr,
1111                           const struct ofputil_flow_removed *fr)
1112 {
1113     struct ofconn *ofconn;
1114
1115     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
1116         struct ofpbuf *msg;
1117
1118         if (!ofconn_receives_async_msgs(ofconn)) {
1119             continue;
1120         }
1121
1122         /* Account flow expirations as replies to OpenFlow requests.  That
1123          * works because preventing OpenFlow requests from being processed also
1124          * prevents new flows from being added (and expiring).  (It also
1125          * prevents processing OpenFlow requests that would not add new flows,
1126          * so it is imperfect.) */
1127         msg = ofputil_encode_flow_removed(fr, ofconn->flow_format);
1128         ofconn_send_reply(ofconn, msg);
1129     }
1130 }
1131
1132 /* Given 'pin', sends an OFPT_PACKET_IN message to each OpenFlow controller as
1133  * necessary according to their individual configurations.
1134  *
1135  * 'rw_packet' may be NULL.  Otherwise, 'rw_packet' must contain the same data
1136  * as pin->packet.  (rw_packet == pin->packet is also valid.)  Ownership of
1137  * 'rw_packet' is transferred to this function. */
1138 void
1139 connmgr_send_packet_in(struct connmgr *mgr,
1140                        const struct ofputil_packet_in *pin,
1141                        const struct flow *flow, struct ofpbuf *rw_packet)
1142 {
1143     struct ofconn *ofconn, *prev;
1144
1145     prev = NULL;
1146     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
1147         if (ofconn_receives_async_msgs(ofconn)) {
1148             if (prev) {
1149                 schedule_packet_in(prev, *pin, flow, NULL);
1150             }
1151             prev = ofconn;
1152         }
1153     }
1154     if (prev) {
1155         schedule_packet_in(prev, *pin, flow, rw_packet);
1156     } else {
1157         ofpbuf_delete(rw_packet);
1158     }
1159 }
1160
1161 /* pinsched callback for sending 'ofp_packet_in' on 'ofconn'. */
1162 static void
1163 do_send_packet_in(struct ofpbuf *ofp_packet_in, void *ofconn_)
1164 {
1165     struct ofconn *ofconn = ofconn_;
1166
1167     rconn_send_with_limit(ofconn->rconn, ofp_packet_in,
1168                           ofconn->packet_in_counter, 100);
1169 }
1170
1171 /* Takes 'pin', whose packet has the flow specified by 'flow', composes an
1172  * OpenFlow packet-in message from it, and passes it to 'ofconn''s packet
1173  * scheduler for sending.
1174  *
1175  * 'rw_packet' may be NULL.  Otherwise, 'rw_packet' must contain the same data
1176  * as pin->packet.  (rw_packet == pin->packet is also valid.)  Ownership of
1177  * 'rw_packet' is transferred to this function. */
1178 static void
1179 schedule_packet_in(struct ofconn *ofconn, struct ofputil_packet_in pin,
1180                    const struct flow *flow, struct ofpbuf *rw_packet)
1181 {
1182     struct connmgr *mgr = ofconn->connmgr;
1183
1184     /* Get OpenFlow buffer_id. */
1185     if (pin.reason == OFPR_ACTION) {
1186         pin.buffer_id = UINT32_MAX;
1187     } else if (mgr->fail_open && fail_open_is_active(mgr->fail_open)) {
1188         pin.buffer_id = pktbuf_get_null();
1189     } else if (!ofconn->pktbuf) {
1190         pin.buffer_id = UINT32_MAX;
1191     } else {
1192         pin.buffer_id = pktbuf_save(ofconn->pktbuf, pin.packet, flow->in_port);
1193     }
1194
1195     /* Figure out how much of the packet to send. */
1196     if (pin.reason == OFPR_NO_MATCH) {
1197         pin.send_len = pin.packet->size;
1198     } else {
1199         /* Caller should have initialized 'send_len' to 'max_len' specified in
1200          * struct ofp_action_output. */
1201     }
1202     if (pin.buffer_id != UINT32_MAX) {
1203         pin.send_len = MIN(pin.send_len, ofconn->miss_send_len);
1204     }
1205
1206     /* Make OFPT_PACKET_IN and hand over to packet scheduler.  It might
1207      * immediately call into do_send_packet_in() or it might buffer it for a
1208      * while (until a later call to pinsched_run()). */
1209     pinsched_send(ofconn->schedulers[pin.reason == OFPR_NO_MATCH ? 0 : 1],
1210                   flow->in_port, ofputil_encode_packet_in(&pin, rw_packet),
1211                   do_send_packet_in, ofconn);
1212 }
1213 \f
1214 /* Fail-open settings. */
1215
1216 /* Returns the failure handling mode (OFPROTO_FAIL_SECURE or
1217  * OFPROTO_FAIL_STANDALONE) for 'mgr'. */
1218 enum ofproto_fail_mode
1219 connmgr_get_fail_mode(const struct connmgr *mgr)
1220 {
1221     return mgr->fail_mode;
1222 }
1223
1224 /* Sets the failure handling mode for 'mgr' to 'fail_mode' (either
1225  * OFPROTO_FAIL_SECURE or OFPROTO_FAIL_STANDALONE). */
1226 void
1227 connmgr_set_fail_mode(struct connmgr *mgr, enum ofproto_fail_mode fail_mode)
1228 {
1229     if (mgr->fail_mode != fail_mode) {
1230         mgr->fail_mode = fail_mode;
1231         update_fail_open(mgr);
1232         if (!connmgr_has_controllers(mgr)) {
1233             ofproto_flush_flows(mgr->ofproto);
1234         }
1235     }
1236 }
1237 \f
1238 /* Fail-open implementation. */
1239
1240 /* Returns the longest probe interval among the primary controllers configured
1241  * on 'mgr'.  Returns 0 if there are no primary controllers. */
1242 int
1243 connmgr_get_max_probe_interval(const struct connmgr *mgr)
1244 {
1245     const struct ofconn *ofconn;
1246     int max_probe_interval;
1247
1248     max_probe_interval = 0;
1249     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
1250         int probe_interval = rconn_get_probe_interval(ofconn->rconn);
1251         max_probe_interval = MAX(max_probe_interval, probe_interval);
1252     }
1253     return max_probe_interval;
1254 }
1255
1256 /* Returns the number of seconds for which all of 'mgr's primary controllers
1257  * have been disconnected.  Returns 0 if 'mgr' has no primary controllers. */
1258 int
1259 connmgr_failure_duration(const struct connmgr *mgr)
1260 {
1261     const struct ofconn *ofconn;
1262     int min_failure_duration;
1263
1264     if (!connmgr_has_controllers(mgr)) {
1265         return 0;
1266     }
1267
1268     min_failure_duration = INT_MAX;
1269     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
1270         int failure_duration = rconn_failure_duration(ofconn->rconn);
1271         min_failure_duration = MIN(min_failure_duration, failure_duration);
1272     }
1273     return min_failure_duration;
1274 }
1275
1276 /* Returns true if at least one primary controller is connected (regardless of
1277  * whether those controllers are believed to have authenticated and accepted
1278  * this switch), false if none of them are connected. */
1279 bool
1280 connmgr_is_any_controller_connected(const struct connmgr *mgr)
1281 {
1282     const struct ofconn *ofconn;
1283
1284     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
1285         if (rconn_is_connected(ofconn->rconn)) {
1286             return true;
1287         }
1288     }
1289     return false;
1290 }
1291
1292 /* Returns true if at least one primary controller is believed to have
1293  * authenticated and accepted this switch, false otherwise. */
1294 bool
1295 connmgr_is_any_controller_admitted(const struct connmgr *mgr)
1296 {
1297     const struct ofconn *ofconn;
1298
1299     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
1300         if (rconn_is_admitted(ofconn->rconn)) {
1301             return true;
1302         }
1303     }
1304     return false;
1305 }
1306
1307 /* Sends 'packet' to each controller connected to 'mgr'.  Takes ownership of
1308  * 'packet'. */
1309 void
1310 connmgr_broadcast(struct connmgr *mgr, struct ofpbuf *packet)
1311 {
1312     struct ofconn *ofconn, *prev;
1313
1314     prev = NULL;
1315     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
1316         if (prev) {
1317             ofconn_send_reply(ofconn, ofpbuf_clone(packet));
1318         }
1319         if (rconn_is_connected(ofconn->rconn)) {
1320             prev = ofconn;
1321         }
1322     }
1323     if (prev) {
1324         ofconn_send_reply(prev, packet);
1325     } else {
1326         ofpbuf_delete(packet);
1327     }
1328 }
1329 \f
1330 /* In-band configuration. */
1331
1332 static bool any_extras_changed(const struct connmgr *,
1333                                const struct sockaddr_in *extras, size_t n);
1334
1335 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'mgr''s
1336  * in-band control should guarantee access, in the same way that in-band
1337  * control guarantees access to OpenFlow controllers. */
1338 void
1339 connmgr_set_extra_in_band_remotes(struct connmgr *mgr,
1340                                   const struct sockaddr_in *extras, size_t n)
1341 {
1342     if (!any_extras_changed(mgr, extras, n)) {
1343         return;
1344     }
1345
1346     free(mgr->extra_in_band_remotes);
1347     mgr->n_extra_remotes = n;
1348     mgr->extra_in_band_remotes = xmemdup(extras, n * sizeof *extras);
1349
1350     update_in_band_remotes(mgr);
1351 }
1352
1353 /* Sets the OpenFlow queue used by flows set up by in-band control on
1354  * 'mgr' to 'queue_id'.  If 'queue_id' is negative, then in-band control
1355  * flows will use the default queue. */
1356 void
1357 connmgr_set_in_band_queue(struct connmgr *mgr, int queue_id)
1358 {
1359     if (queue_id != mgr->in_band_queue) {
1360         mgr->in_band_queue = queue_id;
1361         update_in_band_remotes(mgr);
1362     }
1363 }
1364
1365 static bool
1366 any_extras_changed(const struct connmgr *mgr,
1367                    const struct sockaddr_in *extras, size_t n)
1368 {
1369     size_t i;
1370
1371     if (n != mgr->n_extra_remotes) {
1372         return true;
1373     }
1374
1375     for (i = 0; i < n; i++) {
1376         const struct sockaddr_in *old = &mgr->extra_in_band_remotes[i];
1377         const struct sockaddr_in *new = &extras[i];
1378
1379         if (old->sin_addr.s_addr != new->sin_addr.s_addr ||
1380             old->sin_port != new->sin_port) {
1381             return true;
1382         }
1383     }
1384
1385     return false;
1386 }
1387 \f
1388 /* In-band implementation. */
1389
1390 bool
1391 connmgr_msg_in_hook(struct connmgr *mgr, const struct flow *flow,
1392                     const struct ofpbuf *packet)
1393 {
1394     return mgr->in_band && in_band_msg_in_hook(mgr->in_band, flow, packet);
1395 }
1396
1397 bool
1398 connmgr_may_set_up_flow(struct connmgr *mgr, const struct flow *flow,
1399                         const struct nlattr *odp_actions,
1400                         size_t actions_len)
1401 {
1402     return !mgr->in_band || in_band_rule_check(flow, odp_actions, actions_len);
1403 }
1404 \f
1405 /* Fail-open and in-band implementation. */
1406
1407 /* Called by 'ofproto' after all flows have been flushed, to allow fail-open
1408  * and standalone mode to re-create their flows.
1409  *
1410  * In-band control has more sophisticated code that manages flows itself. */
1411 void
1412 connmgr_flushed(struct connmgr *mgr)
1413 {
1414     if (mgr->fail_open) {
1415         fail_open_flushed(mgr->fail_open);
1416     }
1417
1418     /* If there are no controllers and we're in standalone mode, set up a flow
1419      * that matches every packet and directs them to OFPP_NORMAL (which goes to
1420      * us).  Otherwise, the switch is in secure mode and we won't pass any
1421      * traffic until a controller has been defined and it tells us to do so. */
1422     if (!connmgr_has_controllers(mgr)
1423         && mgr->fail_mode == OFPROTO_FAIL_STANDALONE) {
1424         union ofp_action action;
1425         struct cls_rule rule;
1426
1427         memset(&action, 0, sizeof action);
1428         action.type = htons(OFPAT_OUTPUT);
1429         action.output.len = htons(sizeof action);
1430         action.output.port = htons(OFPP_NORMAL);
1431         cls_rule_init_catchall(&rule, 0);
1432         ofproto_add_flow(mgr->ofproto, &rule, &action, 1);
1433     }
1434 }
1435 \f
1436 /* Creates a new ofservice for 'target' in 'mgr'.  Returns 0 if successful,
1437  * otherwise a positive errno value.
1438  *
1439  * ofservice_reconfigure() must be called to fully configure the new
1440  * ofservice. */
1441 static int
1442 ofservice_create(struct connmgr *mgr, const char *target)
1443 {
1444     struct ofservice *ofservice;
1445     struct pvconn *pvconn;
1446     int error;
1447
1448     error = pvconn_open(target, &pvconn);
1449     if (error) {
1450         return error;
1451     }
1452
1453     ofservice = xzalloc(sizeof *ofservice);
1454     hmap_insert(&mgr->services, &ofservice->node, hash_string(target, 0));
1455     ofservice->pvconn = pvconn;
1456
1457     return 0;
1458 }
1459
1460 static void
1461 ofservice_destroy(struct connmgr *mgr, struct ofservice *ofservice)
1462 {
1463     hmap_remove(&mgr->services, &ofservice->node);
1464     pvconn_close(ofservice->pvconn);
1465     free(ofservice);
1466 }
1467
1468 static void
1469 ofservice_reconfigure(struct ofservice *ofservice,
1470                       const struct ofproto_controller *c)
1471 {
1472     ofservice->probe_interval = c->probe_interval;
1473     ofservice->rate_limit = c->rate_limit;
1474     ofservice->burst_limit = c->burst_limit;
1475 }
1476
1477 /* Finds and returns the ofservice within 'mgr' that has the given
1478  * 'target', or a null pointer if none exists. */
1479 static struct ofservice *
1480 ofservice_lookup(struct connmgr *mgr, const char *target)
1481 {
1482     struct ofservice *ofservice;
1483
1484     HMAP_FOR_EACH_WITH_HASH (ofservice, node, hash_string(target, 0),
1485                              &mgr->services) {
1486         if (!strcmp(pvconn_get_name(ofservice->pvconn), target)) {
1487             return ofservice;
1488         }
1489     }
1490     return NULL;
1491 }