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