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