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