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