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