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