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