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