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