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