5861627b6acfd2de57edef30b4ed50cc1cc16244
[cascardo/ovs.git] / ofproto / connmgr.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014 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 "dynamic-string.h"
26 #include "fail-open.h"
27 #include "in-band.h"
28 #include "odp-util.h"
29 #include "ofp-actions.h"
30 #include "ofp-msgs.h"
31 #include "ofp-util.h"
32 #include "ofpbuf.h"
33 #include "ofproto-provider.h"
34 #include "pinsched.h"
35 #include "poll-loop.h"
36 #include "pktbuf.h"
37 #include "rconn.h"
38 #include "shash.h"
39 #include "simap.h"
40 #include "stream.h"
41 #include "timeval.h"
42 #include "vconn.h"
43 #include "vlog.h"
44
45 #include "bundles.h"
46
47 VLOG_DEFINE_THIS_MODULE(connmgr);
48 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
49
50 /* An OpenFlow connection.
51  *
52  *
53  * Thread-safety
54  * =============
55  *
56  * 'ofproto_mutex' must be held whenever an ofconn is created or destroyed or,
57  * more or less equivalently, whenever an ofconn is added to or removed from a
58  * connmgr.  'ofproto_mutex' doesn't protect the data inside the ofconn, except
59  * as specifically noted below. */
60 struct ofconn {
61 /* Configuration that persists from one connection to the next. */
62
63     struct list node;           /* In struct connmgr's "all_conns" list. */
64     struct hmap_node hmap_node; /* In struct connmgr's "controllers" map. */
65
66     struct connmgr *connmgr;    /* Connection's manager. */
67     struct rconn *rconn;        /* OpenFlow connection. */
68     enum ofconn_type type;      /* Type. */
69     enum ofproto_band band;     /* In-band or out-of-band? */
70     bool enable_async_msgs;     /* Initially enable async messages? */
71
72 /* State that should be cleared from one connection to the next. */
73
74     /* OpenFlow state. */
75     enum ofp12_controller_role role;           /* Role. */
76     enum ofputil_protocol protocol; /* Current protocol variant. */
77     enum nx_packet_in_format packet_in_format; /* OFPT_PACKET_IN format. */
78
79     /* Asynchronous flow table operation support. */
80     struct list opgroups;       /* Contains pending "ofopgroups", if any. */
81     struct ofpbuf *blocked;     /* Postponed OpenFlow message, if any. */
82     bool retry;                 /* True if 'blocked' is ready to try again. */
83
84     /* OFPT_PACKET_IN related data. */
85     struct rconn_packet_counter *packet_in_counter; /* # queued on 'rconn'. */
86 #define N_SCHEDULERS 2
87     struct pinsched *schedulers[N_SCHEDULERS];
88     struct pktbuf *pktbuf;         /* OpenFlow packet buffers. */
89     int miss_send_len;             /* Bytes to send of buffered packets. */
90     uint16_t controller_id;     /* Connection controller ID. */
91
92     /* Number of OpenFlow messages queued on 'rconn' as replies to OpenFlow
93      * requests, and the maximum number before we stop reading OpenFlow
94      * requests.  */
95 #define OFCONN_REPLY_MAX 100
96     struct rconn_packet_counter *reply_counter;
97
98     /* Asynchronous message configuration in each possible roles.
99      *
100      * A 1-bit enables sending an asynchronous message for one possible reason
101      * that the message might be generated, a 0-bit disables it. */
102     uint32_t master_async_config[OAM_N_TYPES]; /* master, other */
103     uint32_t slave_async_config[OAM_N_TYPES];  /* slave */
104
105     /* Flow table operation logging. */
106     int n_add, n_delete, n_modify; /* Number of unreported ops of each kind. */
107     long long int first_op, last_op; /* Range of times for unreported ops. */
108     long long int next_op_report;    /* Time to report ops, or LLONG_MAX. */
109     long long int op_backoff;        /* Earliest time to report ops again. */
110
111 /* Flow monitors (e.g. NXST_FLOW_MONITOR). */
112
113     /* Configuration.  Contains "struct ofmonitor"s. */
114     struct hmap monitors OVS_GUARDED_BY(ofproto_mutex);
115
116     /* Flow control.
117      *
118      * When too many flow monitor notifications back up in the transmit buffer,
119      * we pause the transmission of further notifications.  These members track
120      * the flow control state.
121      *
122      * When notifications are flowing, 'monitor_paused' is 0.  When
123      * notifications are paused, 'monitor_paused' is the value of
124      * 'monitor_seqno' at the point we paused.
125      *
126      * 'monitor_counter' counts the OpenFlow messages and bytes currently in
127      * flight.  This value growing too large triggers pausing. */
128     uint64_t monitor_paused OVS_GUARDED_BY(ofproto_mutex);
129     struct rconn_packet_counter *monitor_counter OVS_GUARDED_BY(ofproto_mutex);
130
131     /* State of monitors for a single ongoing flow_mod.
132      *
133      * 'updates' is a list of "struct ofpbuf"s that contain
134      * NXST_FLOW_MONITOR_REPLY messages representing the changes made by the
135      * current flow_mod.
136      *
137      * When 'updates' is nonempty, 'sent_abbrev_update' is true if 'updates'
138      * contains an update event of type NXFME_ABBREV and false otherwise.. */
139     struct list updates OVS_GUARDED_BY(ofproto_mutex);
140     bool sent_abbrev_update OVS_GUARDED_BY(ofproto_mutex);
141
142     /* Active bundles. Contains "struct ofp_bundle"s. */
143     struct hmap bundles;
144 };
145
146 static struct ofconn *ofconn_create(struct connmgr *, struct rconn *,
147                                     enum ofconn_type, bool enable_async_msgs)
148     OVS_REQUIRES(ofproto_mutex);
149 static void ofconn_destroy(struct ofconn *) OVS_REQUIRES(ofproto_mutex);
150 static void ofconn_flush(struct ofconn *) OVS_REQUIRES(ofproto_mutex);
151
152 static void ofconn_reconfigure(struct ofconn *,
153                                const struct ofproto_controller *);
154
155 static void ofconn_run(struct ofconn *,
156                        bool (*handle_openflow)(struct ofconn *,
157                                                const struct ofpbuf *ofp_msg));
158 static void ofconn_wait(struct ofconn *, bool handling_openflow);
159
160 static void ofconn_log_flow_mods(struct ofconn *);
161
162 static const char *ofconn_get_target(const struct ofconn *);
163 static char *ofconn_make_name(const struct connmgr *, const char *target);
164
165 static void ofconn_set_rate_limit(struct ofconn *, int rate, int burst);
166
167 static void ofconn_send(const struct ofconn *, struct ofpbuf *,
168                         struct rconn_packet_counter *);
169
170 static void do_send_packet_ins(struct ofconn *, struct list *txq);
171
172 /* A listener for incoming OpenFlow "service" connections. */
173 struct ofservice {
174     struct hmap_node node;      /* In struct connmgr's "services" hmap. */
175     struct pvconn *pvconn;      /* OpenFlow connection listener. */
176
177     /* These are not used by ofservice directly.  They are settings for
178      * accepted "struct ofconn"s from the pvconn. */
179     int probe_interval;         /* Max idle time before probing, in seconds. */
180     int rate_limit;             /* Max packet-in rate in packets per second. */
181     int burst_limit;            /* Limit on accumulating packet credits. */
182     bool enable_async_msgs;     /* Initially enable async messages? */
183     uint8_t dscp;               /* DSCP Value for controller connection */
184     uint32_t allowed_versions;  /* OpenFlow protocol versions that may
185                                  * be negotiated for a session. */
186 };
187
188 static void ofservice_reconfigure(struct ofservice *,
189                                   const struct ofproto_controller *);
190 static int ofservice_create(struct connmgr *mgr, const char *target,
191                             uint32_t allowed_versions, uint8_t dscp);
192 static void ofservice_destroy(struct connmgr *, struct ofservice *);
193 static struct ofservice *ofservice_lookup(struct connmgr *,
194                                           const char *target);
195
196 /* Connection manager for an OpenFlow switch. */
197 struct connmgr {
198     struct ofproto *ofproto;
199     char *name;
200     char *local_port_name;
201
202     /* OpenFlow connections. */
203     struct hmap controllers;   /* All OFCONN_PRIMARY controllers. */
204     struct list all_conns;     /* All controllers. */
205     uint64_t master_election_id; /* monotonically increasing sequence number
206                                   * for master election */
207     bool master_election_id_defined;
208
209     /* OpenFlow listeners. */
210     struct hmap services;       /* Contains "struct ofservice"s. */
211     struct pvconn **snoops;
212     size_t n_snoops;
213
214     /* Fail open. */
215     struct fail_open *fail_open;
216     enum ofproto_fail_mode fail_mode;
217
218     /* In-band control. */
219     struct in_band *in_band;
220     struct sockaddr_in *extra_in_band_remotes;
221     size_t n_extra_remotes;
222     int in_band_queue;
223 };
224
225 static void update_in_band_remotes(struct connmgr *);
226 static void add_snooper(struct connmgr *, struct vconn *);
227 static void ofmonitor_run(struct connmgr *);
228 static void ofmonitor_wait(struct connmgr *);
229
230 /* Creates and returns a new connection manager owned by 'ofproto'.  'name' is
231  * a name for the ofproto suitable for using in log messages.
232  * 'local_port_name' is the name of the local port (OFPP_LOCAL) within
233  * 'ofproto'. */
234 struct connmgr *
235 connmgr_create(struct ofproto *ofproto,
236                const char *name, const char *local_port_name)
237 {
238     struct connmgr *mgr;
239
240     mgr = xmalloc(sizeof *mgr);
241     mgr->ofproto = ofproto;
242     mgr->name = xstrdup(name);
243     mgr->local_port_name = xstrdup(local_port_name);
244
245     hmap_init(&mgr->controllers);
246     list_init(&mgr->all_conns);
247     mgr->master_election_id = 0;
248     mgr->master_election_id_defined = false;
249
250     hmap_init(&mgr->services);
251     mgr->snoops = NULL;
252     mgr->n_snoops = 0;
253
254     mgr->fail_open = NULL;
255     mgr->fail_mode = OFPROTO_FAIL_SECURE;
256
257     mgr->in_band = NULL;
258     mgr->extra_in_band_remotes = NULL;
259     mgr->n_extra_remotes = 0;
260     mgr->in_band_queue = -1;
261
262     return mgr;
263 }
264
265 /* Frees 'mgr' and all of its resources. */
266 void
267 connmgr_destroy(struct connmgr *mgr)
268 {
269     struct ofservice *ofservice, *next_ofservice;
270     struct ofconn *ofconn, *next_ofconn;
271     size_t i;
272
273     if (!mgr) {
274         return;
275     }
276
277     ovs_mutex_lock(&ofproto_mutex);
278     LIST_FOR_EACH_SAFE (ofconn, next_ofconn, node, &mgr->all_conns) {
279         ofconn_destroy(ofconn);
280     }
281     ovs_mutex_unlock(&ofproto_mutex);
282
283     hmap_destroy(&mgr->controllers);
284
285     HMAP_FOR_EACH_SAFE (ofservice, next_ofservice, node, &mgr->services) {
286         ofservice_destroy(mgr, ofservice);
287     }
288     hmap_destroy(&mgr->services);
289
290     for (i = 0; i < mgr->n_snoops; i++) {
291         pvconn_close(mgr->snoops[i]);
292     }
293     free(mgr->snoops);
294
295     fail_open_destroy(mgr->fail_open);
296     mgr->fail_open = NULL;
297
298     in_band_destroy(mgr->in_band);
299     mgr->in_band = NULL;
300     free(mgr->extra_in_band_remotes);
301     free(mgr->name);
302     free(mgr->local_port_name);
303
304     free(mgr);
305 }
306
307 /* Does all of the periodic maintenance required by 'mgr'.
308  *
309  * If 'handle_openflow' is nonnull, calls 'handle_openflow' for each message
310  * received on an OpenFlow connection, passing along the OpenFlow connection
311  * itself and the message that was sent.  If 'handle_openflow' returns true,
312  * the message is considered to be fully processed.  If 'handle_openflow'
313  * returns false, the message is considered not to have been processed at all;
314  * it will be stored and re-presented to 'handle_openflow' following the next
315  * call to connmgr_retry().  'handle_openflow' must not modify or free the
316  * message.
317  *
318  * If 'handle_openflow' is NULL, no OpenFlow messages will be processed and
319  * other activities that could affect the flow table (in-band processing,
320  * fail-open processing) are suppressed too. */
321 void
322 connmgr_run(struct connmgr *mgr,
323             bool (*handle_openflow)(struct ofconn *,
324                                     const struct ofpbuf *ofp_msg))
325     OVS_EXCLUDED(ofproto_mutex)
326 {
327     struct ofconn *ofconn, *next_ofconn;
328     struct ofservice *ofservice;
329     size_t i;
330
331     if (handle_openflow && mgr->in_band) {
332         if (!in_band_run(mgr->in_band)) {
333             in_band_destroy(mgr->in_band);
334             mgr->in_band = NULL;
335         }
336     }
337
338     LIST_FOR_EACH_SAFE (ofconn, next_ofconn, node, &mgr->all_conns) {
339         ofconn_run(ofconn, handle_openflow);
340     }
341     ofmonitor_run(mgr);
342
343     /* Fail-open maintenance.  Do this after processing the ofconns since
344      * fail-open checks the status of the controller rconn. */
345     if (handle_openflow && mgr->fail_open) {
346         fail_open_run(mgr->fail_open);
347     }
348
349     HMAP_FOR_EACH (ofservice, node, &mgr->services) {
350         struct vconn *vconn;
351         int retval;
352
353         retval = pvconn_accept(ofservice->pvconn, &vconn);
354         if (!retval) {
355             struct rconn *rconn;
356             char *name;
357
358             /* Passing default value for creation of the rconn */
359             rconn = rconn_create(ofservice->probe_interval, 0, ofservice->dscp,
360                                  vconn_get_allowed_versions(vconn));
361             name = ofconn_make_name(mgr, vconn_get_name(vconn));
362             rconn_connect_unreliably(rconn, vconn, name);
363             free(name);
364
365             ovs_mutex_lock(&ofproto_mutex);
366             ofconn = ofconn_create(mgr, rconn, OFCONN_SERVICE,
367                                    ofservice->enable_async_msgs);
368             ovs_mutex_unlock(&ofproto_mutex);
369
370             ofconn_set_rate_limit(ofconn, ofservice->rate_limit,
371                                   ofservice->burst_limit);
372         } else if (retval != EAGAIN) {
373             VLOG_WARN_RL(&rl, "accept failed (%s)", ovs_strerror(retval));
374         }
375     }
376
377     for (i = 0; i < mgr->n_snoops; i++) {
378         struct vconn *vconn;
379         int retval;
380
381         retval = pvconn_accept(mgr->snoops[i], &vconn);
382         if (!retval) {
383             add_snooper(mgr, vconn);
384         } else if (retval != EAGAIN) {
385             VLOG_WARN_RL(&rl, "accept failed (%s)", ovs_strerror(retval));
386         }
387     }
388 }
389
390 /* Causes the poll loop to wake up when connmgr_run() needs to run.
391  *
392  * If 'handling_openflow' is true, arriving OpenFlow messages and other
393  * activities that affect the flow table will wake up the poll loop.  If
394  * 'handling_openflow' is false, they will not. */
395 void
396 connmgr_wait(struct connmgr *mgr, bool handling_openflow)
397 {
398     struct ofservice *ofservice;
399     struct ofconn *ofconn;
400     size_t i;
401
402     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
403         ofconn_wait(ofconn, handling_openflow);
404     }
405     ofmonitor_wait(mgr);
406     if (handling_openflow && mgr->in_band) {
407         in_band_wait(mgr->in_band);
408     }
409     if (handling_openflow && mgr->fail_open) {
410         fail_open_wait(mgr->fail_open);
411     }
412     HMAP_FOR_EACH (ofservice, node, &mgr->services) {
413         pvconn_wait(ofservice->pvconn);
414     }
415     for (i = 0; i < mgr->n_snoops; i++) {
416         pvconn_wait(mgr->snoops[i]);
417     }
418 }
419
420 /* Adds some memory usage statistics for 'mgr' into 'usage', for use with
421  * memory_report(). */
422 void
423 connmgr_get_memory_usage(const struct connmgr *mgr, struct simap *usage)
424 {
425     const struct ofconn *ofconn;
426     unsigned int packets = 0;
427     unsigned int ofconns = 0;
428
429     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
430         int i;
431
432         ofconns++;
433
434         packets += rconn_count_txqlen(ofconn->rconn);
435         for (i = 0; i < N_SCHEDULERS; i++) {
436             packets += pinsched_count_txqlen(ofconn->schedulers[i]);
437         }
438         packets += pktbuf_count_packets(ofconn->pktbuf);
439     }
440     simap_increase(usage, "ofconns", ofconns);
441     simap_increase(usage, "packets", packets);
442 }
443
444 /* Returns the ofproto that owns 'ofconn''s connmgr. */
445 struct ofproto *
446 ofconn_get_ofproto(const struct ofconn *ofconn)
447 {
448     return ofconn->connmgr->ofproto;
449 }
450
451 /* If processing of OpenFlow messages was blocked on any 'mgr' ofconns by
452  * returning false to the 'handle_openflow' callback to connmgr_run(), this
453  * re-enables them. */
454 void
455 connmgr_retry(struct connmgr *mgr)
456 {
457     struct ofconn *ofconn;
458
459     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
460         ofconn->retry = true;
461     }
462 }
463 \f
464 /* OpenFlow configuration. */
465
466 static void add_controller(struct connmgr *, const char *target, uint8_t dscp,
467                            uint32_t allowed_versions)
468     OVS_REQUIRES(ofproto_mutex);
469 static struct ofconn *find_controller_by_target(struct connmgr *,
470                                                 const char *target);
471 static void update_fail_open(struct connmgr *) OVS_EXCLUDED(ofproto_mutex);
472 static int set_pvconns(struct pvconn ***pvconnsp, size_t *n_pvconnsp,
473                        const struct sset *);
474
475 /* Returns true if 'mgr' has any configured primary controllers.
476  *
477  * Service controllers do not count, but configured primary controllers do
478  * count whether or not they are currently connected. */
479 bool
480 connmgr_has_controllers(const struct connmgr *mgr)
481 {
482     return !hmap_is_empty(&mgr->controllers);
483 }
484
485 /* Initializes 'info' and populates it with information about each configured
486  * primary controller.  The keys in 'info' are the controllers' targets; the
487  * data values are corresponding "struct ofproto_controller_info".
488  *
489  * The caller owns 'info' and everything in it and should free it when it is no
490  * longer needed. */
491 void
492 connmgr_get_controller_info(struct connmgr *mgr, struct shash *info)
493 {
494     const struct ofconn *ofconn;
495
496     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
497         const struct rconn *rconn = ofconn->rconn;
498         const char *target = rconn_get_target(rconn);
499
500         if (!shash_find(info, target)) {
501             struct ofproto_controller_info *cinfo = xmalloc(sizeof *cinfo);
502             time_t now = time_now();
503             time_t last_connection = rconn_get_last_connection(rconn);
504             time_t last_disconnect = rconn_get_last_disconnect(rconn);
505             int last_error = rconn_get_last_error(rconn);
506
507             shash_add(info, target, cinfo);
508
509             cinfo->is_connected = rconn_is_connected(rconn);
510             cinfo->role = ofconn->role;
511
512             cinfo->pairs.n = 0;
513
514             if (last_error) {
515                 cinfo->pairs.keys[cinfo->pairs.n] = "last_error";
516                 cinfo->pairs.values[cinfo->pairs.n++]
517                     = xstrdup(ovs_retval_to_string(last_error));
518             }
519
520             cinfo->pairs.keys[cinfo->pairs.n] = "state";
521             cinfo->pairs.values[cinfo->pairs.n++]
522                 = xstrdup(rconn_get_state(rconn));
523
524             if (last_connection != TIME_MIN) {
525                 cinfo->pairs.keys[cinfo->pairs.n] = "sec_since_connect";
526                 cinfo->pairs.values[cinfo->pairs.n++]
527                     = xasprintf("%ld", (long int) (now - last_connection));
528             }
529
530             if (last_disconnect != TIME_MIN) {
531                 cinfo->pairs.keys[cinfo->pairs.n] = "sec_since_disconnect";
532                 cinfo->pairs.values[cinfo->pairs.n++]
533                     = xasprintf("%ld", (long int) (now - last_disconnect));
534             }
535         }
536     }
537 }
538
539 void
540 connmgr_free_controller_info(struct shash *info)
541 {
542     struct shash_node *node;
543
544     SHASH_FOR_EACH (node, info) {
545         struct ofproto_controller_info *cinfo = node->data;
546         while (cinfo->pairs.n) {
547             free(CONST_CAST(char *, cinfo->pairs.values[--cinfo->pairs.n]));
548         }
549         free(cinfo);
550     }
551     shash_destroy(info);
552 }
553
554 /* Changes 'mgr''s set of controllers to the 'n_controllers' controllers in
555  * 'controllers'. */
556 void
557 connmgr_set_controllers(struct connmgr *mgr,
558                         const struct ofproto_controller *controllers,
559                         size_t n_controllers, uint32_t allowed_versions)
560     OVS_EXCLUDED(ofproto_mutex)
561 {
562     bool had_controllers = connmgr_has_controllers(mgr);
563     struct shash new_controllers;
564     struct ofconn *ofconn, *next_ofconn;
565     struct ofservice *ofservice, *next_ofservice;
566     size_t i;
567
568     /* Required to add and remove ofconns.  This could probably be narrowed to
569      * cover a smaller amount of code, if that yielded some benefit. */
570     ovs_mutex_lock(&ofproto_mutex);
571
572     /* Create newly configured controllers and services.
573      * Create a name to ofproto_controller mapping in 'new_controllers'. */
574     shash_init(&new_controllers);
575     for (i = 0; i < n_controllers; i++) {
576         const struct ofproto_controller *c = &controllers[i];
577
578         if (!vconn_verify_name(c->target)) {
579             bool add = false;
580             ofconn = find_controller_by_target(mgr, c->target);
581             if (!ofconn) {
582                 VLOG_INFO("%s: added primary controller \"%s\"",
583                           mgr->name, c->target);
584                 add = true;
585             } else if (rconn_get_allowed_versions(ofconn->rconn) !=
586                        allowed_versions) {
587                 VLOG_INFO("%s: re-added primary controller \"%s\"",
588                           mgr->name, c->target);
589                 add = true;
590                 ofconn_destroy(ofconn);
591             }
592             if (add) {
593                 add_controller(mgr, c->target, c->dscp, allowed_versions);
594             }
595         } else if (!pvconn_verify_name(c->target)) {
596             bool add = false;
597             ofservice = ofservice_lookup(mgr, c->target);
598             if (!ofservice) {
599                 VLOG_INFO("%s: added service controller \"%s\"",
600                           mgr->name, c->target);
601                 add = true;
602             } else if (ofservice->allowed_versions != allowed_versions) {
603                 VLOG_INFO("%s: re-added service controller \"%s\"",
604                           mgr->name, c->target);
605                 ofservice_destroy(mgr, ofservice);
606                 add = true;
607             }
608             if (add) {
609                 ofservice_create(mgr, c->target, allowed_versions, c->dscp);
610             }
611         } else {
612             VLOG_WARN_RL(&rl, "%s: unsupported controller \"%s\"",
613                          mgr->name, c->target);
614             continue;
615         }
616
617         shash_add_once(&new_controllers, c->target, &controllers[i]);
618     }
619
620     /* Delete controllers that are no longer configured.
621      * Update configuration of all now-existing controllers. */
622     HMAP_FOR_EACH_SAFE (ofconn, next_ofconn, hmap_node, &mgr->controllers) {
623         const char *target = ofconn_get_target(ofconn);
624         struct ofproto_controller *c;
625
626         c = shash_find_data(&new_controllers, target);
627         if (!c) {
628             VLOG_INFO("%s: removed primary controller \"%s\"",
629                       mgr->name, target);
630             ofconn_destroy(ofconn);
631         } else {
632             ofconn_reconfigure(ofconn, c);
633         }
634     }
635
636     /* Delete services that are no longer configured.
637      * Update configuration of all now-existing services. */
638     HMAP_FOR_EACH_SAFE (ofservice, next_ofservice, node, &mgr->services) {
639         const char *target = pvconn_get_name(ofservice->pvconn);
640         struct ofproto_controller *c;
641
642         c = shash_find_data(&new_controllers, target);
643         if (!c) {
644             VLOG_INFO("%s: removed service controller \"%s\"",
645                       mgr->name, target);
646             ofservice_destroy(mgr, ofservice);
647         } else {
648             ofservice_reconfigure(ofservice, c);
649         }
650     }
651
652     shash_destroy(&new_controllers);
653
654     ovs_mutex_unlock(&ofproto_mutex);
655
656     update_in_band_remotes(mgr);
657     update_fail_open(mgr);
658     if (had_controllers != connmgr_has_controllers(mgr)) {
659         ofproto_flush_flows(mgr->ofproto);
660     }
661 }
662
663 /* Drops the connections between 'mgr' and all of its primary and secondary
664  * controllers, forcing them to reconnect. */
665 void
666 connmgr_reconnect(const struct connmgr *mgr)
667 {
668     struct ofconn *ofconn;
669
670     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
671         rconn_reconnect(ofconn->rconn);
672     }
673 }
674
675 /* Sets the "snoops" for 'mgr' to the pvconn targets listed in 'snoops'.
676  *
677  * A "snoop" is a pvconn to which every OpenFlow message to or from the most
678  * important controller on 'mgr' is mirrored. */
679 int
680 connmgr_set_snoops(struct connmgr *mgr, const struct sset *snoops)
681 {
682     return set_pvconns(&mgr->snoops, &mgr->n_snoops, snoops);
683 }
684
685 /* Adds each of the snoops currently configured on 'mgr' to 'snoops'. */
686 void
687 connmgr_get_snoops(const struct connmgr *mgr, struct sset *snoops)
688 {
689     size_t i;
690
691     for (i = 0; i < mgr->n_snoops; i++) {
692         sset_add(snoops, pvconn_get_name(mgr->snoops[i]));
693     }
694 }
695
696 /* Returns true if 'mgr' has at least one snoop, false if it has none. */
697 bool
698 connmgr_has_snoops(const struct connmgr *mgr)
699 {
700     return mgr->n_snoops > 0;
701 }
702
703 /* Creates a new controller for 'target' in 'mgr'.  update_controller() needs
704  * to be called later to finish the new ofconn's configuration. */
705 static void
706 add_controller(struct connmgr *mgr, const char *target, uint8_t dscp,
707                uint32_t allowed_versions)
708     OVS_REQUIRES(ofproto_mutex)
709 {
710     char *name = ofconn_make_name(mgr, target);
711     struct ofconn *ofconn;
712
713     ofconn = ofconn_create(mgr, rconn_create(5, 8, dscp, allowed_versions),
714                            OFCONN_PRIMARY, true);
715     ofconn->pktbuf = pktbuf_create();
716     rconn_connect(ofconn->rconn, target, name);
717     hmap_insert(&mgr->controllers, &ofconn->hmap_node, hash_string(target, 0));
718
719     free(name);
720 }
721
722 static struct ofconn *
723 find_controller_by_target(struct connmgr *mgr, const char *target)
724 {
725     struct ofconn *ofconn;
726
727     HMAP_FOR_EACH_WITH_HASH (ofconn, hmap_node,
728                              hash_string(target, 0), &mgr->controllers) {
729         if (!strcmp(ofconn_get_target(ofconn), target)) {
730             return ofconn;
731         }
732     }
733     return NULL;
734 }
735
736 static void
737 update_in_band_remotes(struct connmgr *mgr)
738 {
739     struct sockaddr_in *addrs;
740     size_t max_addrs, n_addrs;
741     struct ofconn *ofconn;
742     size_t i;
743
744     /* Allocate enough memory for as many remotes as we could possibly have. */
745     max_addrs = mgr->n_extra_remotes + hmap_count(&mgr->controllers);
746     addrs = xmalloc(max_addrs * sizeof *addrs);
747     n_addrs = 0;
748
749     /* Add all the remotes. */
750     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
751         const char *target = rconn_get_target(ofconn->rconn);
752         struct sockaddr_storage ss;
753
754         if (ofconn->band == OFPROTO_IN_BAND
755             && stream_parse_target_with_default_port(target, OFP_OLD_PORT, &ss)
756             && ss.ss_family == AF_INET) {
757             addrs[n_addrs++] = *(struct sockaddr_in *) &ss;
758         }
759     }
760     for (i = 0; i < mgr->n_extra_remotes; i++) {
761         addrs[n_addrs++] = mgr->extra_in_band_remotes[i];
762     }
763
764     /* Create or update or destroy in-band. */
765     if (n_addrs) {
766         if (!mgr->in_band) {
767             in_band_create(mgr->ofproto, mgr->local_port_name, &mgr->in_band);
768         }
769         in_band_set_queue(mgr->in_band, mgr->in_band_queue);
770     } else {
771         /* in_band_run() needs a chance to delete any existing in-band flows.
772          * We will destroy mgr->in_band after it's done with that. */
773     }
774     if (mgr->in_band) {
775         in_band_set_remotes(mgr->in_band, addrs, n_addrs);
776     }
777
778     /* Clean up. */
779     free(addrs);
780 }
781
782 static void
783 update_fail_open(struct connmgr *mgr)
784     OVS_EXCLUDED(ofproto_mutex)
785 {
786     if (connmgr_has_controllers(mgr)
787         && mgr->fail_mode == OFPROTO_FAIL_STANDALONE) {
788         if (!mgr->fail_open) {
789             mgr->fail_open = fail_open_create(mgr->ofproto, mgr);
790         }
791     } else {
792         fail_open_destroy(mgr->fail_open);
793         mgr->fail_open = NULL;
794     }
795 }
796
797 static int
798 set_pvconns(struct pvconn ***pvconnsp, size_t *n_pvconnsp,
799             const struct sset *sset)
800 {
801     struct pvconn **pvconns = *pvconnsp;
802     size_t n_pvconns = *n_pvconnsp;
803     const char *name;
804     int retval = 0;
805     size_t i;
806
807     for (i = 0; i < n_pvconns; i++) {
808         pvconn_close(pvconns[i]);
809     }
810     free(pvconns);
811
812     pvconns = xmalloc(sset_count(sset) * sizeof *pvconns);
813     n_pvconns = 0;
814     SSET_FOR_EACH (name, sset) {
815         struct pvconn *pvconn;
816         int error;
817         error = pvconn_open(name, 0, 0, &pvconn);
818         if (!error) {
819             pvconns[n_pvconns++] = pvconn;
820         } else {
821             VLOG_ERR("failed to listen on %s: %s", name, ovs_strerror(error));
822             if (!retval) {
823                 retval = error;
824             }
825         }
826     }
827
828     *pvconnsp = pvconns;
829     *n_pvconnsp = n_pvconns;
830
831     return retval;
832 }
833
834 /* Returns a "preference level" for snooping 'ofconn'.  A higher return value
835  * means that 'ofconn' is more interesting for monitoring than a lower return
836  * value. */
837 static int
838 snoop_preference(const struct ofconn *ofconn)
839 {
840     switch (ofconn->role) {
841     case OFPCR12_ROLE_MASTER:
842         return 3;
843     case OFPCR12_ROLE_EQUAL:
844         return 2;
845     case OFPCR12_ROLE_SLAVE:
846         return 1;
847     case OFPCR12_ROLE_NOCHANGE:
848     default:
849         /* Shouldn't happen. */
850         return 0;
851     }
852 }
853
854 /* One of 'mgr''s "snoop" pvconns has accepted a new connection on 'vconn'.
855  * Connects this vconn to a controller. */
856 static void
857 add_snooper(struct connmgr *mgr, struct vconn *vconn)
858 {
859     struct ofconn *ofconn, *best;
860
861     /* Pick a controller for monitoring. */
862     best = NULL;
863     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
864         if (ofconn->type == OFCONN_PRIMARY
865             && (!best || snoop_preference(ofconn) > snoop_preference(best))) {
866             best = ofconn;
867         }
868     }
869
870     if (best) {
871         rconn_add_monitor(best->rconn, vconn);
872     } else {
873         VLOG_INFO_RL(&rl, "no controller connection to snoop");
874         vconn_close(vconn);
875     }
876 }
877 \f
878 /* Public ofconn functions. */
879
880 /* Returns the connection type, either OFCONN_PRIMARY or OFCONN_SERVICE. */
881 enum ofconn_type
882 ofconn_get_type(const struct ofconn *ofconn)
883 {
884     return ofconn->type;
885 }
886
887 /* If a master election id is defined, stores it into '*idp' and returns
888  * true.  Otherwise, stores UINT64_MAX into '*idp' and returns false. */
889 bool
890 ofconn_get_master_election_id(const struct ofconn *ofconn, uint64_t *idp)
891 {
892     *idp = (ofconn->connmgr->master_election_id_defined
893             ? ofconn->connmgr->master_election_id
894             : UINT64_MAX);
895     return ofconn->connmgr->master_election_id_defined;
896 }
897
898 /* Sets the master election id.
899  *
900  * Returns true if successful, false if the id is stale
901  */
902 bool
903 ofconn_set_master_election_id(struct ofconn *ofconn, uint64_t id)
904 {
905     if (ofconn->connmgr->master_election_id_defined
906         &&
907         /* Unsigned difference interpreted as a two's complement signed
908          * value */
909         (int64_t)(id - ofconn->connmgr->master_election_id) < 0) {
910         return false;
911     }
912     ofconn->connmgr->master_election_id = id;
913     ofconn->connmgr->master_election_id_defined = true;
914
915     return true;
916 }
917
918 /* Returns the role configured for 'ofconn'.
919  *
920  * The default role, if no other role has been set, is OFPCR12_ROLE_EQUAL. */
921 enum ofp12_controller_role
922 ofconn_get_role(const struct ofconn *ofconn)
923 {
924     return ofconn->role;
925 }
926
927 void
928 ofconn_send_role_status(struct ofconn *ofconn, uint32_t role, uint8_t reason)
929 {
930     struct ofputil_role_status status;
931     struct ofpbuf *buf;
932
933     status.reason = reason;
934     status.role = role;
935     ofconn_get_master_election_id(ofconn, &status.generation_id);
936
937     buf = ofputil_encode_role_status(&status, ofconn_get_protocol(ofconn));
938     if (buf) {
939         ofconn_send(ofconn, buf, NULL);
940     }
941 }
942
943 /* Changes 'ofconn''s role to 'role'.  If 'role' is OFPCR12_ROLE_MASTER then
944  * any existing master is demoted to a slave. */
945 void
946 ofconn_set_role(struct ofconn *ofconn, enum ofp12_controller_role role)
947 {
948     if (role != ofconn->role && role == OFPCR12_ROLE_MASTER) {
949         struct ofconn *other;
950
951         LIST_FOR_EACH (other, node, &ofconn->connmgr->all_conns) {
952             if (other->role == OFPCR12_ROLE_MASTER) {
953                 other->role = OFPCR12_ROLE_SLAVE;
954                 ofconn_send_role_status(other, OFPCR12_ROLE_SLAVE, OFPCRR_MASTER_REQUEST);
955             }
956         }
957     }
958     ofconn->role = role;
959 }
960
961 void
962 ofconn_set_invalid_ttl_to_controller(struct ofconn *ofconn, bool enable)
963 {
964     uint32_t bit = 1u << OFPR_INVALID_TTL;
965     if (enable) {
966         ofconn->master_async_config[OAM_PACKET_IN] |= bit;
967     } else {
968         ofconn->master_async_config[OAM_PACKET_IN] &= ~bit;
969     }
970 }
971
972 bool
973 ofconn_get_invalid_ttl_to_controller(struct ofconn *ofconn)
974 {
975     uint32_t bit = 1u << OFPR_INVALID_TTL;
976     return (ofconn->master_async_config[OAM_PACKET_IN] & bit) != 0;
977 }
978
979 /* Returns the currently configured protocol for 'ofconn', one of OFPUTIL_P_*.
980  *
981  * Returns OFPUTIL_P_NONE, which is not a valid protocol, if 'ofconn' hasn't
982  * completed version negotiation.  This can't happen if at least one OpenFlow
983  * message, other than OFPT_HELLO, has been received on the connection (such as
984  * in ofproto.c's message handling code), since version negotiation is a
985  * prerequisite for starting to receive messages.  This means that
986  * OFPUTIL_P_NONE is a special case that most callers need not worry about. */
987 enum ofputil_protocol
988 ofconn_get_protocol(const struct ofconn *ofconn)
989 {
990     if (ofconn->protocol == OFPUTIL_P_NONE &&
991         rconn_is_connected(ofconn->rconn)) {
992         int version = rconn_get_version(ofconn->rconn);
993         if (version > 0) {
994             ofconn_set_protocol(CONST_CAST(struct ofconn *, ofconn),
995                                 ofputil_protocol_from_ofp_version(version));
996         }
997     }
998
999     return ofconn->protocol;
1000 }
1001
1002 /* Sets the protocol for 'ofconn' to 'protocol' (one of OFPUTIL_P_*).
1003  *
1004  * (This doesn't actually send anything to accomplish this.  Presumably the
1005  * caller already did that.) */
1006 void
1007 ofconn_set_protocol(struct ofconn *ofconn, enum ofputil_protocol protocol)
1008 {
1009     ofconn->protocol = protocol;
1010 }
1011
1012 /* Returns the currently configured packet in format for 'ofconn', one of
1013  * NXPIF_*.
1014  *
1015  * The default, if no other format has been set, is NXPIF_OPENFLOW10. */
1016 enum nx_packet_in_format
1017 ofconn_get_packet_in_format(struct ofconn *ofconn)
1018 {
1019     return ofconn->packet_in_format;
1020 }
1021
1022 /* Sets the packet in format for 'ofconn' to 'packet_in_format' (one of
1023  * NXPIF_*). */
1024 void
1025 ofconn_set_packet_in_format(struct ofconn *ofconn,
1026                             enum nx_packet_in_format packet_in_format)
1027 {
1028     ofconn->packet_in_format = packet_in_format;
1029 }
1030
1031 /* Sets the controller connection ID for 'ofconn' to 'controller_id'.
1032  *
1033  * The connection controller ID is used for OFPP_CONTROLLER and
1034  * NXAST_CONTROLLER actions.  See "struct nx_action_controller" for details. */
1035 void
1036 ofconn_set_controller_id(struct ofconn *ofconn, uint16_t controller_id)
1037 {
1038     ofconn->controller_id = controller_id;
1039 }
1040
1041 /* Returns the default miss send length for 'ofconn'. */
1042 int
1043 ofconn_get_miss_send_len(const struct ofconn *ofconn)
1044 {
1045     return ofconn->miss_send_len;
1046 }
1047
1048 /* Sets the default miss send length for 'ofconn' to 'miss_send_len'. */
1049 void
1050 ofconn_set_miss_send_len(struct ofconn *ofconn, int miss_send_len)
1051 {
1052     ofconn->miss_send_len = miss_send_len;
1053 }
1054
1055 void
1056 ofconn_set_async_config(struct ofconn *ofconn,
1057                         const uint32_t master_masks[OAM_N_TYPES],
1058                         const uint32_t slave_masks[OAM_N_TYPES])
1059 {
1060     size_t size = sizeof ofconn->master_async_config;
1061     memcpy(ofconn->master_async_config, master_masks, size);
1062     memcpy(ofconn->slave_async_config, slave_masks, size);
1063 }
1064
1065 void
1066 ofconn_get_async_config(struct ofconn *ofconn,
1067                         uint32_t *master_masks, uint32_t *slave_masks)
1068 {
1069     size_t size = sizeof ofconn->master_async_config;
1070     memcpy(master_masks, ofconn->master_async_config, size);
1071     memcpy(slave_masks, ofconn->slave_async_config, size);
1072 }
1073
1074 /* Sends 'msg' on 'ofconn', accounting it as a reply.  (If there is a
1075  * sufficient number of OpenFlow replies in-flight on a single ofconn, then the
1076  * connmgr will stop accepting new OpenFlow requests on that ofconn until the
1077  * controller has accepted some of the replies.) */
1078 void
1079 ofconn_send_reply(const struct ofconn *ofconn, struct ofpbuf *msg)
1080 {
1081     ofconn_send(ofconn, msg, ofconn->reply_counter);
1082 }
1083
1084 /* Sends each of the messages in list 'replies' on 'ofconn' in order,
1085  * accounting them as replies. */
1086 void
1087 ofconn_send_replies(const struct ofconn *ofconn, struct list *replies)
1088 {
1089     struct ofpbuf *reply, *next;
1090
1091     LIST_FOR_EACH_SAFE (reply, next, list_node, replies) {
1092         list_remove(&reply->list_node);
1093         ofconn_send_reply(ofconn, reply);
1094     }
1095 }
1096
1097 /* Sends 'error' on 'ofconn', as a reply to 'request'.  Only at most the
1098  * first 64 bytes of 'request' are used. */
1099 void
1100 ofconn_send_error(const struct ofconn *ofconn,
1101                   const struct ofp_header *request, enum ofperr error)
1102 {
1103     static struct vlog_rate_limit err_rl = VLOG_RATE_LIMIT_INIT(10, 10);
1104     struct ofpbuf *reply;
1105
1106     reply = ofperr_encode_reply(error, request);
1107     if (!VLOG_DROP_INFO(&err_rl)) {
1108         const char *type_name;
1109         size_t request_len;
1110         enum ofpraw raw;
1111
1112         request_len = ntohs(request->length);
1113         type_name = (!ofpraw_decode_partial(&raw, request,
1114                                             MIN(64, request_len))
1115                      ? ofpraw_get_name(raw)
1116                      : "invalid");
1117
1118         VLOG_INFO("%s: sending %s error reply to %s message",
1119                   rconn_get_name(ofconn->rconn), ofperr_to_string(error),
1120                   type_name);
1121     }
1122     ofconn_send_reply(ofconn, reply);
1123 }
1124
1125 /* Same as pktbuf_retrieve(), using the pktbuf owned by 'ofconn'. */
1126 enum ofperr
1127 ofconn_pktbuf_retrieve(struct ofconn *ofconn, uint32_t id,
1128                        struct ofpbuf **bufferp, ofp_port_t *in_port)
1129 {
1130     return pktbuf_retrieve(ofconn->pktbuf, id, bufferp, in_port);
1131 }
1132
1133 /* Reports that a flow_mod operation of the type specified by 'command' was
1134  * successfully executed by 'ofconn', so that the connmgr can log it. */
1135 void
1136 ofconn_report_flow_mod(struct ofconn *ofconn,
1137                        enum ofp_flow_mod_command command)
1138 {
1139     long long int now;
1140
1141     switch (command) {
1142     case OFPFC_ADD:
1143         ofconn->n_add++;
1144         break;
1145
1146     case OFPFC_MODIFY:
1147     case OFPFC_MODIFY_STRICT:
1148         ofconn->n_modify++;
1149         break;
1150
1151     case OFPFC_DELETE:
1152     case OFPFC_DELETE_STRICT:
1153         ofconn->n_delete++;
1154         break;
1155     }
1156
1157     now = time_msec();
1158     if (ofconn->next_op_report == LLONG_MAX) {
1159         ofconn->first_op = now;
1160         ofconn->next_op_report = MAX(now + 10 * 1000, ofconn->op_backoff);
1161         ofconn->op_backoff = ofconn->next_op_report + 60 * 1000;
1162     }
1163     ofconn->last_op = now;
1164 }
1165
1166 /* Returns true if 'ofconn' has any pending opgroups. */
1167 bool
1168 ofconn_has_pending_opgroups(const struct ofconn *ofconn)
1169 {
1170     return !list_is_empty(&ofconn->opgroups);
1171 }
1172
1173 /* Adds 'ofconn_node' to 'ofconn''s list of pending opgroups.
1174  *
1175  * If 'ofconn' is destroyed or its connection drops, then 'ofconn' will remove
1176  * 'ofconn_node' from the list and re-initialize it with list_init().  The
1177  * client may, therefore, use list_is_empty(ofconn_node) to determine whether
1178  * 'ofconn_node' is still associated with an active ofconn.
1179  *
1180  * The client may also remove ofconn_node from the list itself, with
1181  * list_remove(). */
1182 void
1183 ofconn_add_opgroup(struct ofconn *ofconn, struct list *ofconn_node)
1184 {
1185     list_push_back(&ofconn->opgroups, ofconn_node);
1186 }
1187
1188 struct hmap *
1189 ofconn_get_bundles(struct ofconn *ofconn)
1190 {
1191     return &ofconn->bundles;
1192 }
1193
1194 \f
1195 /* Private ofconn functions. */
1196
1197 static const char *
1198 ofconn_get_target(const struct ofconn *ofconn)
1199 {
1200     return rconn_get_target(ofconn->rconn);
1201 }
1202
1203 static struct ofconn *
1204 ofconn_create(struct connmgr *mgr, struct rconn *rconn, enum ofconn_type type,
1205               bool enable_async_msgs)
1206 {
1207     struct ofconn *ofconn;
1208
1209     ofconn = xzalloc(sizeof *ofconn);
1210     ofconn->connmgr = mgr;
1211     list_push_back(&mgr->all_conns, &ofconn->node);
1212     ofconn->rconn = rconn;
1213     ofconn->type = type;
1214     ofconn->enable_async_msgs = enable_async_msgs;
1215
1216     list_init(&ofconn->opgroups);
1217
1218     hmap_init(&ofconn->monitors);
1219     list_init(&ofconn->updates);
1220
1221     hmap_init(&ofconn->bundles);
1222
1223     ofconn_flush(ofconn);
1224
1225     return ofconn;
1226 }
1227
1228 /* Clears all of the state in 'ofconn' that should not persist from one
1229  * connection to the next. */
1230 static void
1231 ofconn_flush(struct ofconn *ofconn)
1232     OVS_REQUIRES(ofproto_mutex)
1233 {
1234     struct ofmonitor *monitor, *next_monitor;
1235     int i;
1236
1237     ofconn_log_flow_mods(ofconn);
1238
1239     ofconn->role = OFPCR12_ROLE_EQUAL;
1240     ofconn_set_protocol(ofconn, OFPUTIL_P_NONE);
1241     ofconn->packet_in_format = NXPIF_OPENFLOW10;
1242
1243     /* Disassociate 'ofconn' from all of the ofopgroups that it initiated that
1244      * have not yet completed.  (Those ofopgroups will still run to completion
1245      * in the usual way, but any errors that they run into will not be reported
1246      * on any OpenFlow channel.)
1247      *
1248      * Also discard any blocked operation on 'ofconn'. */
1249     while (!list_is_empty(&ofconn->opgroups)) {
1250         list_init(list_pop_front(&ofconn->opgroups));
1251     }
1252     ofpbuf_delete(ofconn->blocked);
1253     ofconn->blocked = NULL;
1254
1255     rconn_packet_counter_destroy(ofconn->packet_in_counter);
1256     ofconn->packet_in_counter = rconn_packet_counter_create();
1257     for (i = 0; i < N_SCHEDULERS; i++) {
1258         if (ofconn->schedulers[i]) {
1259             int rate, burst;
1260
1261             pinsched_get_limits(ofconn->schedulers[i], &rate, &burst);
1262             pinsched_destroy(ofconn->schedulers[i]);
1263             ofconn->schedulers[i] = pinsched_create(rate, burst);
1264         }
1265     }
1266     if (ofconn->pktbuf) {
1267         pktbuf_destroy(ofconn->pktbuf);
1268         ofconn->pktbuf = pktbuf_create();
1269     }
1270     ofconn->miss_send_len = (ofconn->type == OFCONN_PRIMARY
1271                              ? OFP_DEFAULT_MISS_SEND_LEN
1272                              : 0);
1273     ofconn->controller_id = 0;
1274
1275     rconn_packet_counter_destroy(ofconn->reply_counter);
1276     ofconn->reply_counter = rconn_packet_counter_create();
1277
1278     if (ofconn->enable_async_msgs) {
1279         uint32_t *master = ofconn->master_async_config;
1280         uint32_t *slave = ofconn->slave_async_config;
1281
1282         /* "master" and "other" roles get all asynchronous messages by default,
1283          * except that the controller needs to enable nonstandard "packet-in"
1284          * reasons itself. */
1285         master[OAM_PACKET_IN] = (1u << OFPR_NO_MATCH) | (1u << OFPR_ACTION);
1286         master[OAM_PORT_STATUS] = ((1u << OFPPR_ADD)
1287                                    | (1u << OFPPR_DELETE)
1288                                    | (1u << OFPPR_MODIFY));
1289         master[OAM_FLOW_REMOVED] = ((1u << OFPRR_IDLE_TIMEOUT)
1290                                     | (1u << OFPRR_HARD_TIMEOUT)
1291                                     | (1u << OFPRR_DELETE));
1292
1293         /* "slave" role gets port status updates by default. */
1294         slave[OAM_PACKET_IN] = 0;
1295         slave[OAM_PORT_STATUS] = ((1u << OFPPR_ADD)
1296                                   | (1u << OFPPR_DELETE)
1297                                   | (1u << OFPPR_MODIFY));
1298         slave[OAM_FLOW_REMOVED] = 0;
1299     } else {
1300         memset(ofconn->master_async_config, 0,
1301                sizeof ofconn->master_async_config);
1302         memset(ofconn->slave_async_config, 0,
1303                sizeof ofconn->slave_async_config);
1304     }
1305
1306     ofconn->n_add = ofconn->n_delete = ofconn->n_modify = 0;
1307     ofconn->first_op = ofconn->last_op = LLONG_MIN;
1308     ofconn->next_op_report = LLONG_MAX;
1309     ofconn->op_backoff = LLONG_MIN;
1310
1311     HMAP_FOR_EACH_SAFE (monitor, next_monitor, ofconn_node,
1312                         &ofconn->monitors) {
1313         ofmonitor_destroy(monitor);
1314     }
1315     rconn_packet_counter_destroy(ofconn->monitor_counter);
1316     ofconn->monitor_counter = rconn_packet_counter_create();
1317     ofpbuf_list_delete(&ofconn->updates); /* ...but it should be empty. */
1318 }
1319
1320 static void
1321 ofconn_destroy(struct ofconn *ofconn)
1322     OVS_REQUIRES(ofproto_mutex)
1323 {
1324     ofconn_flush(ofconn);
1325
1326     if (ofconn->type == OFCONN_PRIMARY) {
1327         hmap_remove(&ofconn->connmgr->controllers, &ofconn->hmap_node);
1328     }
1329
1330     ofp_bundle_remove_all(ofconn);
1331
1332     hmap_destroy(&ofconn->monitors);
1333     list_remove(&ofconn->node);
1334     rconn_destroy(ofconn->rconn);
1335     rconn_packet_counter_destroy(ofconn->packet_in_counter);
1336     rconn_packet_counter_destroy(ofconn->reply_counter);
1337     pktbuf_destroy(ofconn->pktbuf);
1338     rconn_packet_counter_destroy(ofconn->monitor_counter);
1339     free(ofconn);
1340 }
1341
1342 /* Reconfigures 'ofconn' to match 'c'.  'ofconn' and 'c' must have the same
1343  * target. */
1344 static void
1345 ofconn_reconfigure(struct ofconn *ofconn, const struct ofproto_controller *c)
1346 {
1347     int probe_interval;
1348
1349     ofconn->band = c->band;
1350     ofconn->enable_async_msgs = c->enable_async_msgs;
1351
1352     rconn_set_max_backoff(ofconn->rconn, c->max_backoff);
1353
1354     probe_interval = c->probe_interval ? MAX(c->probe_interval, 5) : 0;
1355     rconn_set_probe_interval(ofconn->rconn, probe_interval);
1356
1357     ofconn_set_rate_limit(ofconn, c->rate_limit, c->burst_limit);
1358
1359     /* If dscp value changed reconnect. */
1360     if (c->dscp != rconn_get_dscp(ofconn->rconn)) {
1361         rconn_set_dscp(ofconn->rconn, c->dscp);
1362         rconn_reconnect(ofconn->rconn);
1363     }
1364 }
1365
1366 /* Returns true if it makes sense for 'ofconn' to receive and process OpenFlow
1367  * messages. */
1368 static bool
1369 ofconn_may_recv(const struct ofconn *ofconn)
1370 {
1371     int count = rconn_packet_counter_n_packets(ofconn->reply_counter);
1372     return (!ofconn->blocked || ofconn->retry) && count < OFCONN_REPLY_MAX;
1373 }
1374
1375 static void
1376 ofconn_run(struct ofconn *ofconn,
1377            bool (*handle_openflow)(struct ofconn *,
1378                                    const struct ofpbuf *ofp_msg))
1379 {
1380     struct connmgr *mgr = ofconn->connmgr;
1381     size_t i;
1382
1383     for (i = 0; i < N_SCHEDULERS; i++) {
1384         struct list txq;
1385
1386         pinsched_run(ofconn->schedulers[i], &txq);
1387         do_send_packet_ins(ofconn, &txq);
1388     }
1389
1390     rconn_run(ofconn->rconn);
1391
1392     if (handle_openflow) {
1393         /* Limit the number of iterations to avoid starving other tasks. */
1394         for (i = 0; i < 50 && ofconn_may_recv(ofconn); i++) {
1395             struct ofpbuf *of_msg;
1396
1397             of_msg = (ofconn->blocked
1398                       ? ofconn->blocked
1399                       : rconn_recv(ofconn->rconn));
1400             if (!of_msg) {
1401                 break;
1402             }
1403             if (mgr->fail_open) {
1404                 fail_open_maybe_recover(mgr->fail_open);
1405             }
1406
1407             if (handle_openflow(ofconn, of_msg)) {
1408                 ofpbuf_delete(of_msg);
1409                 ofconn->blocked = NULL;
1410             } else {
1411                 ofconn->blocked = of_msg;
1412                 ofconn->retry = false;
1413             }
1414         }
1415     }
1416
1417
1418     if (time_msec() >= ofconn->next_op_report) {
1419         ofconn_log_flow_mods(ofconn);
1420     }
1421
1422     ovs_mutex_lock(&ofproto_mutex);
1423     if (!rconn_is_alive(ofconn->rconn)) {
1424         ofconn_destroy(ofconn);
1425     } else if (!rconn_is_connected(ofconn->rconn)) {
1426         ofconn_flush(ofconn);
1427     }
1428     ovs_mutex_unlock(&ofproto_mutex);
1429 }
1430
1431 static void
1432 ofconn_wait(struct ofconn *ofconn, bool handling_openflow)
1433 {
1434     int i;
1435
1436     for (i = 0; i < N_SCHEDULERS; i++) {
1437         pinsched_wait(ofconn->schedulers[i]);
1438     }
1439     rconn_run_wait(ofconn->rconn);
1440     if (handling_openflow && ofconn_may_recv(ofconn)) {
1441         rconn_recv_wait(ofconn->rconn);
1442     }
1443     if (ofconn->next_op_report != LLONG_MAX) {
1444         poll_timer_wait_until(ofconn->next_op_report);
1445     }
1446 }
1447
1448 static void
1449 ofconn_log_flow_mods(struct ofconn *ofconn)
1450 {
1451     int n_flow_mods = ofconn->n_add + ofconn->n_delete + ofconn->n_modify;
1452     if (n_flow_mods) {
1453         long long int ago = (time_msec() - ofconn->first_op) / 1000;
1454         long long int interval = (ofconn->last_op - ofconn->first_op) / 1000;
1455         struct ds s;
1456
1457         ds_init(&s);
1458         ds_put_format(&s, "%d flow_mods ", n_flow_mods);
1459         if (interval == ago) {
1460             ds_put_format(&s, "in the last %lld s", ago);
1461         } else if (interval) {
1462             ds_put_format(&s, "in the %lld s starting %lld s ago",
1463                           interval, ago);
1464         } else {
1465             ds_put_format(&s, "%lld s ago", ago);
1466         }
1467
1468         ds_put_cstr(&s, " (");
1469         if (ofconn->n_add) {
1470             ds_put_format(&s, "%d adds, ", ofconn->n_add);
1471         }
1472         if (ofconn->n_delete) {
1473             ds_put_format(&s, "%d deletes, ", ofconn->n_delete);
1474         }
1475         if (ofconn->n_modify) {
1476             ds_put_format(&s, "%d modifications, ", ofconn->n_modify);
1477         }
1478         s.length -= 2;
1479         ds_put_char(&s, ')');
1480
1481         VLOG_INFO("%s: %s", rconn_get_name(ofconn->rconn), ds_cstr(&s));
1482         ds_destroy(&s);
1483
1484         ofconn->n_add = ofconn->n_delete = ofconn->n_modify = 0;
1485     }
1486     ofconn->next_op_report = LLONG_MAX;
1487 }
1488
1489 /* Returns true if 'ofconn' should receive asynchronous messages of the given
1490  * OAM_* 'type' and 'reason', which should be a OFPR_* value for OAM_PACKET_IN,
1491  * a OFPPR_* value for OAM_PORT_STATUS, or an OFPRR_* value for
1492  * OAM_FLOW_REMOVED.  Returns false if the message should not be sent on
1493  * 'ofconn'. */
1494 static bool
1495 ofconn_receives_async_msg(const struct ofconn *ofconn,
1496                           enum ofconn_async_msg_type type,
1497                           unsigned int reason)
1498 {
1499     const uint32_t *async_config;
1500
1501     ovs_assert(reason < 32);
1502     ovs_assert((unsigned int) type < OAM_N_TYPES);
1503
1504     if (ofconn_get_protocol(ofconn) == OFPUTIL_P_NONE
1505         || !rconn_is_connected(ofconn->rconn)) {
1506         return false;
1507     }
1508
1509     /* Keep the following code in sync with the documentation in the
1510      * "Asynchronous Messages" section in DESIGN. */
1511
1512     if (ofconn->type == OFCONN_SERVICE && !ofconn->miss_send_len) {
1513         /* Service connections don't get asynchronous messages unless they have
1514          * explicitly asked for them by setting a nonzero miss send length. */
1515         return false;
1516     }
1517
1518     async_config = (ofconn->role == OFPCR12_ROLE_SLAVE
1519                     ? ofconn->slave_async_config
1520                     : ofconn->master_async_config);
1521     if (!(async_config[type] & (1u << reason))) {
1522         return false;
1523     }
1524
1525     return true;
1526 }
1527
1528 /* The default "table-miss" behaviour for OpenFlow1.3+ is to drop the
1529  * packet rather than to send the packet to the controller.
1530  *
1531  * This function returns false to indicate the packet should be dropped if
1532  * the controller action was the result of the default table-miss behaviour
1533  * and the controller is using OpenFlow1.3+.
1534  *
1535  * Otherwise true is returned to indicate the packet should be forwarded to
1536  * the controller */
1537 static bool
1538 ofconn_wants_packet_in_on_miss(struct ofconn *ofconn,
1539                                const struct ofproto_packet_in *pin)
1540 {
1541     if (pin->miss_type == OFPROTO_PACKET_IN_MISS_WITHOUT_FLOW) {
1542         enum ofputil_protocol protocol = ofconn_get_protocol(ofconn);
1543
1544         if (protocol != OFPUTIL_P_NONE
1545             && ofputil_protocol_to_ofp_version(protocol) >= OFP13_VERSION) {
1546             enum ofproto_table_config config;
1547
1548             config = ofproto_table_get_config(ofconn->connmgr->ofproto,
1549                                               pin->up.table_id);
1550             if (config == OFPROTO_TABLE_MISS_DEFAULT) {
1551                 return false;
1552             }
1553         }
1554     }
1555     return true;
1556 }
1557
1558 /* The default "table-miss" behaviour for OpenFlow1.3+ is to drop the
1559  * packet rather than to send the packet to the controller.
1560  *
1561  * This function returns true to indicate that a packet_in message
1562  * for a "table-miss" should be sent to at least one controller.
1563  * That is there is at least one controller with controller_id 0
1564  * which connected using an OpenFlow version earlier than OpenFlow1.3.
1565  *
1566  * False otherwise.
1567  *
1568  * This logic assumes that "table-miss" packet_in messages
1569  * are always sent to controller_id 0. */
1570 bool
1571 connmgr_wants_packet_in_on_miss(struct connmgr *mgr)
1572 {
1573     struct ofconn *ofconn;
1574
1575     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
1576         enum ofputil_protocol protocol = ofconn_get_protocol(ofconn);
1577
1578         if (ofconn->controller_id == 0 &&
1579             (protocol == OFPUTIL_P_NONE ||
1580              ofputil_protocol_to_ofp_version(protocol) < OFP13_VERSION)) {
1581             return true;
1582         }
1583     }
1584     return false;
1585 }
1586
1587 /* Returns a human-readable name for an OpenFlow connection between 'mgr' and
1588  * 'target', suitable for use in log messages for identifying the connection.
1589  *
1590  * The name is dynamically allocated.  The caller should free it (with free())
1591  * when it is no longer needed. */
1592 static char *
1593 ofconn_make_name(const struct connmgr *mgr, const char *target)
1594 {
1595     return xasprintf("%s<->%s", mgr->name, target);
1596 }
1597
1598 static void
1599 ofconn_set_rate_limit(struct ofconn *ofconn, int rate, int burst)
1600 {
1601     int i;
1602
1603     for (i = 0; i < N_SCHEDULERS; i++) {
1604         struct pinsched **s = &ofconn->schedulers[i];
1605
1606         if (rate > 0) {
1607             if (!*s) {
1608                 *s = pinsched_create(rate, burst);
1609             } else {
1610                 pinsched_set_limits(*s, rate, burst);
1611             }
1612         } else {
1613             pinsched_destroy(*s);
1614             *s = NULL;
1615         }
1616     }
1617 }
1618
1619 static void
1620 ofconn_send(const struct ofconn *ofconn, struct ofpbuf *msg,
1621             struct rconn_packet_counter *counter)
1622 {
1623     ofpmsg_update_length(msg);
1624     rconn_send(ofconn->rconn, msg, counter);
1625 }
1626 \f
1627 /* Sending asynchronous messages. */
1628
1629 static void schedule_packet_in(struct ofconn *, struct ofproto_packet_in,
1630                                enum ofp_packet_in_reason wire_reason);
1631
1632 /* Sends an OFPT_PORT_STATUS message with 'opp' and 'reason' to appropriate
1633  * controllers managed by 'mgr'.  For messages caused by a controller
1634  * OFPT_PORT_MOD, specify 'source' as the controller connection that sent the
1635  * request; otherwise, specify 'source' as NULL. */
1636 void
1637 connmgr_send_port_status(struct connmgr *mgr, struct ofconn *source,
1638                          const struct ofputil_phy_port *pp, uint8_t reason)
1639 {
1640     /* XXX Should limit the number of queued port status change messages. */
1641     struct ofputil_port_status ps;
1642     struct ofconn *ofconn;
1643
1644     ps.reason = reason;
1645     ps.desc = *pp;
1646     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
1647         if (ofconn_receives_async_msg(ofconn, OAM_PORT_STATUS, reason)) {
1648             struct ofpbuf *msg;
1649
1650             /* Before 1.5, OpenFlow specified that OFPT_PORT_MOD should not
1651              * generate OFPT_PORT_STATUS messages.  That requirement was a
1652              * relic of how OpenFlow originally supported a single controller,
1653              * so that one could expect the controller to already know the
1654              * changes it had made.
1655              *
1656              * EXT-338 changes OpenFlow 1.5 OFPT_PORT_MOD to send
1657              * OFPT_PORT_STATUS messages to every controller.  This is
1658              * obviously more useful in the multi-controller case.  We could
1659              * always implement it that way in OVS, but that would risk
1660              * confusing controllers that are intended for single-controller
1661              * use only.  (Imagine a controller that generates an OFPT_PORT_MOD
1662              * in response to any OFPT_PORT_STATUS!)
1663              *
1664              * So this compromises: for OpenFlow 1.4 and earlier, it generates
1665              * OFPT_PORT_STATUS for OFPT_PORT_MOD, but not back to the
1666              * originating controller.  In a single-controller environment, in
1667              * particular, this means that it will never generate
1668              * OFPT_PORT_STATUS for OFPT_PORT_MOD at all. */
1669             if (ofconn == source
1670                 && rconn_get_version(ofconn->rconn) < OFP15_VERSION) {
1671                 continue;
1672             }
1673
1674             msg = ofputil_encode_port_status(&ps, ofconn_get_protocol(ofconn));
1675             ofconn_send(ofconn, msg, NULL);
1676         }
1677     }
1678 }
1679
1680 /* Sends an OFPT_FLOW_REMOVED or NXT_FLOW_REMOVED message based on 'fr' to
1681  * appropriate controllers managed by 'mgr'. */
1682 void
1683 connmgr_send_flow_removed(struct connmgr *mgr,
1684                           const struct ofputil_flow_removed *fr)
1685 {
1686     struct ofconn *ofconn;
1687
1688     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
1689         if (ofconn_receives_async_msg(ofconn, OAM_FLOW_REMOVED, fr->reason)) {
1690             struct ofpbuf *msg;
1691
1692             /* Account flow expirations as replies to OpenFlow requests.  That
1693              * works because preventing OpenFlow requests from being processed
1694              * also prevents new flows from being added (and expiring).  (It
1695              * also prevents processing OpenFlow requests that would not add
1696              * new flows, so it is imperfect.) */
1697             msg = ofputil_encode_flow_removed(fr, ofconn_get_protocol(ofconn));
1698             ofconn_send_reply(ofconn, msg);
1699         }
1700     }
1701 }
1702
1703 /* Normally a send-to-controller action uses reason OFPR_ACTION.  However, in
1704  * OpenFlow 1.3 and later, packet_ins generated by a send-to-controller action
1705  * in a "table-miss" flow (one with priority 0 and completely wildcarded) are
1706  * sent as OFPR_NO_MATCH.  This function returns the reason that should
1707  * actually be sent on 'ofconn' for 'pin'. */
1708 static enum ofp_packet_in_reason
1709 wire_reason(struct ofconn *ofconn, const struct ofproto_packet_in *pin)
1710 {
1711     if (pin->miss_type == OFPROTO_PACKET_IN_MISS_FLOW
1712         && pin->up.reason == OFPR_ACTION) {
1713         enum ofputil_protocol protocol = ofconn_get_protocol(ofconn);
1714
1715         if (protocol != OFPUTIL_P_NONE
1716             && ofputil_protocol_to_ofp_version(protocol) >= OFP13_VERSION) {
1717             return OFPR_NO_MATCH;
1718         }
1719     }
1720     return pin->up.reason;
1721 }
1722
1723 /* Given 'pin', sends an OFPT_PACKET_IN message to each OpenFlow controller as
1724  * necessary according to their individual configurations.
1725  *
1726  * The caller doesn't need to fill in pin->buffer_id or pin->total_len. */
1727 void
1728 connmgr_send_packet_in(struct connmgr *mgr,
1729                        const struct ofproto_packet_in *pin)
1730 {
1731     struct ofconn *ofconn;
1732
1733     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
1734         enum ofp_packet_in_reason reason = wire_reason(ofconn, pin);
1735
1736         if (ofconn_wants_packet_in_on_miss(ofconn, pin)
1737             && ofconn_receives_async_msg(ofconn, OAM_PACKET_IN, pin->up.reason)
1738             && ofconn->controller_id == pin->controller_id) {
1739             schedule_packet_in(ofconn, *pin, reason);
1740         }
1741     }
1742 }
1743
1744 static void
1745 do_send_packet_ins(struct ofconn *ofconn, struct list *txq)
1746 {
1747     struct ofpbuf *pin, *next_pin;
1748
1749     LIST_FOR_EACH_SAFE (pin, next_pin, list_node, txq) {
1750         list_remove(&pin->list_node);
1751
1752         if (rconn_send_with_limit(ofconn->rconn, pin,
1753                                   ofconn->packet_in_counter, 100) == EAGAIN) {
1754             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
1755
1756             VLOG_INFO_RL(&rl, "%s: dropping packet-in due to queue overflow",
1757                          rconn_get_name(ofconn->rconn));
1758         }
1759     }
1760 }
1761
1762 /* Takes 'pin', composes an OpenFlow packet-in message from it, and passes it
1763  * to 'ofconn''s packet scheduler for sending. */
1764 static void
1765 schedule_packet_in(struct ofconn *ofconn, struct ofproto_packet_in pin,
1766                    enum ofp_packet_in_reason wire_reason)
1767 {
1768     struct connmgr *mgr = ofconn->connmgr;
1769     uint16_t controller_max_len;
1770     struct list txq;
1771
1772     pin.up.total_len = pin.up.packet_len;
1773
1774     pin.up.reason = wire_reason;
1775     if (pin.up.reason == OFPR_ACTION) {
1776         controller_max_len = pin.send_len;  /* max_len */
1777     } else {
1778         controller_max_len = ofconn->miss_send_len;
1779     }
1780
1781     /* Get OpenFlow buffer_id.
1782      * For OpenFlow 1.2+, OFPCML_NO_BUFFER (== UINT16_MAX) specifies
1783      * unbuffered.  This behaviour doesn't violate prior versions, too. */
1784     if (controller_max_len == UINT16_MAX) {
1785         pin.up.buffer_id = UINT32_MAX;
1786     } else if (mgr->fail_open && fail_open_is_active(mgr->fail_open)) {
1787         pin.up.buffer_id = pktbuf_get_null();
1788     } else if (!ofconn->pktbuf) {
1789         pin.up.buffer_id = UINT32_MAX;
1790     } else {
1791         pin.up.buffer_id = pktbuf_save(ofconn->pktbuf,
1792                                        pin.up.packet, pin.up.packet_len,
1793                                        pin.up.fmd.in_port);
1794     }
1795
1796     /* Figure out how much of the packet to send.
1797      * If not buffered, send the entire packet.  Otherwise, depending on
1798      * the reason of packet-in, send what requested by the controller. */
1799     if (pin.up.buffer_id != UINT32_MAX
1800         && controller_max_len < pin.up.packet_len) {
1801         pin.up.packet_len = controller_max_len;
1802     }
1803
1804     /* Make OFPT_PACKET_IN and hand over to packet scheduler. */
1805     pinsched_send(ofconn->schedulers[pin.up.reason == OFPR_NO_MATCH ? 0 : 1],
1806                   pin.up.fmd.in_port,
1807                   ofputil_encode_packet_in(&pin.up,
1808                                            ofconn_get_protocol(ofconn),
1809                                            ofconn->packet_in_format),
1810                   &txq);
1811     do_send_packet_ins(ofconn, &txq);
1812 }
1813 \f
1814 /* Fail-open settings. */
1815
1816 /* Returns the failure handling mode (OFPROTO_FAIL_SECURE or
1817  * OFPROTO_FAIL_STANDALONE) for 'mgr'. */
1818 enum ofproto_fail_mode
1819 connmgr_get_fail_mode(const struct connmgr *mgr)
1820 {
1821     return mgr->fail_mode;
1822 }
1823
1824 /* Sets the failure handling mode for 'mgr' to 'fail_mode' (either
1825  * OFPROTO_FAIL_SECURE or OFPROTO_FAIL_STANDALONE). */
1826 void
1827 connmgr_set_fail_mode(struct connmgr *mgr, enum ofproto_fail_mode fail_mode)
1828 {
1829     if (mgr->fail_mode != fail_mode) {
1830         mgr->fail_mode = fail_mode;
1831         update_fail_open(mgr);
1832         if (!connmgr_has_controllers(mgr)) {
1833             ofproto_flush_flows(mgr->ofproto);
1834         }
1835     }
1836 }
1837 \f
1838 /* Fail-open implementation. */
1839
1840 /* Returns the longest probe interval among the primary controllers configured
1841  * on 'mgr'.  Returns 0 if there are no primary controllers. */
1842 int
1843 connmgr_get_max_probe_interval(const struct connmgr *mgr)
1844 {
1845     const struct ofconn *ofconn;
1846     int max_probe_interval;
1847
1848     max_probe_interval = 0;
1849     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
1850         int probe_interval = rconn_get_probe_interval(ofconn->rconn);
1851         max_probe_interval = MAX(max_probe_interval, probe_interval);
1852     }
1853     return max_probe_interval;
1854 }
1855
1856 /* Returns the number of seconds for which all of 'mgr's primary controllers
1857  * have been disconnected.  Returns 0 if 'mgr' has no primary controllers. */
1858 int
1859 connmgr_failure_duration(const struct connmgr *mgr)
1860 {
1861     const struct ofconn *ofconn;
1862     int min_failure_duration;
1863
1864     if (!connmgr_has_controllers(mgr)) {
1865         return 0;
1866     }
1867
1868     min_failure_duration = INT_MAX;
1869     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
1870         int failure_duration = rconn_failure_duration(ofconn->rconn);
1871         min_failure_duration = MIN(min_failure_duration, failure_duration);
1872     }
1873     return min_failure_duration;
1874 }
1875
1876 /* Returns true if at least one primary controller is connected (regardless of
1877  * whether those controllers are believed to have authenticated and accepted
1878  * this switch), false if none of them are connected. */
1879 bool
1880 connmgr_is_any_controller_connected(const struct connmgr *mgr)
1881 {
1882     const struct ofconn *ofconn;
1883
1884     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
1885         if (rconn_is_connected(ofconn->rconn)) {
1886             return true;
1887         }
1888     }
1889     return false;
1890 }
1891
1892 /* Returns true if at least one primary controller is believed to have
1893  * authenticated and accepted this switch, false otherwise. */
1894 bool
1895 connmgr_is_any_controller_admitted(const struct connmgr *mgr)
1896 {
1897     const struct ofconn *ofconn;
1898
1899     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
1900         if (rconn_is_admitted(ofconn->rconn)) {
1901             return true;
1902         }
1903     }
1904     return false;
1905 }
1906 \f
1907 /* In-band configuration. */
1908
1909 static bool any_extras_changed(const struct connmgr *,
1910                                const struct sockaddr_in *extras, size_t n);
1911
1912 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'mgr''s
1913  * in-band control should guarantee access, in the same way that in-band
1914  * control guarantees access to OpenFlow controllers. */
1915 void
1916 connmgr_set_extra_in_band_remotes(struct connmgr *mgr,
1917                                   const struct sockaddr_in *extras, size_t n)
1918 {
1919     if (!any_extras_changed(mgr, extras, n)) {
1920         return;
1921     }
1922
1923     free(mgr->extra_in_band_remotes);
1924     mgr->n_extra_remotes = n;
1925     mgr->extra_in_band_remotes = xmemdup(extras, n * sizeof *extras);
1926
1927     update_in_band_remotes(mgr);
1928 }
1929
1930 /* Sets the OpenFlow queue used by flows set up by in-band control on
1931  * 'mgr' to 'queue_id'.  If 'queue_id' is negative, then in-band control
1932  * flows will use the default queue. */
1933 void
1934 connmgr_set_in_band_queue(struct connmgr *mgr, int queue_id)
1935 {
1936     if (queue_id != mgr->in_band_queue) {
1937         mgr->in_band_queue = queue_id;
1938         update_in_band_remotes(mgr);
1939     }
1940 }
1941
1942 static bool
1943 any_extras_changed(const struct connmgr *mgr,
1944                    const struct sockaddr_in *extras, size_t n)
1945 {
1946     size_t i;
1947
1948     if (n != mgr->n_extra_remotes) {
1949         return true;
1950     }
1951
1952     for (i = 0; i < n; i++) {
1953         const struct sockaddr_in *old = &mgr->extra_in_band_remotes[i];
1954         const struct sockaddr_in *new = &extras[i];
1955
1956         if (old->sin_addr.s_addr != new->sin_addr.s_addr ||
1957             old->sin_port != new->sin_port) {
1958             return true;
1959         }
1960     }
1961
1962     return false;
1963 }
1964 \f
1965 /* In-band implementation. */
1966
1967 bool
1968 connmgr_has_in_band(struct connmgr *mgr)
1969 {
1970     return mgr->in_band != NULL;
1971 }
1972 \f
1973 /* Fail-open and in-band implementation. */
1974
1975 /* Called by 'ofproto' after all flows have been flushed, to allow fail-open
1976  * and standalone mode to re-create their flows.
1977  *
1978  * In-band control has more sophisticated code that manages flows itself. */
1979 void
1980 connmgr_flushed(struct connmgr *mgr)
1981     OVS_EXCLUDED(ofproto_mutex)
1982 {
1983     if (mgr->fail_open) {
1984         fail_open_flushed(mgr->fail_open);
1985     }
1986
1987     /* If there are no controllers and we're in standalone mode, set up a flow
1988      * that matches every packet and directs them to OFPP_NORMAL (which goes to
1989      * us).  Otherwise, the switch is in secure mode and we won't pass any
1990      * traffic until a controller has been defined and it tells us to do so. */
1991     if (!connmgr_has_controllers(mgr)
1992         && mgr->fail_mode == OFPROTO_FAIL_STANDALONE) {
1993         struct ofpbuf ofpacts;
1994         struct match match;
1995
1996         ofpbuf_init(&ofpacts, OFPACT_OUTPUT_SIZE);
1997         ofpact_put_OUTPUT(&ofpacts)->port = OFPP_NORMAL;
1998         ofpact_pad(&ofpacts);
1999
2000         match_init_catchall(&match);
2001         ofproto_add_flow(mgr->ofproto, &match, 0, ofpbuf_data(&ofpacts),
2002                                                   ofpbuf_size(&ofpacts));
2003
2004         ofpbuf_uninit(&ofpacts);
2005     }
2006 }
2007 \f
2008 /* Creates a new ofservice for 'target' in 'mgr'.  Returns 0 if successful,
2009  * otherwise a positive errno value.
2010  *
2011  * ofservice_reconfigure() must be called to fully configure the new
2012  * ofservice. */
2013 static int
2014 ofservice_create(struct connmgr *mgr, const char *target,
2015                  uint32_t allowed_versions, uint8_t dscp)
2016 {
2017     struct ofservice *ofservice;
2018     struct pvconn *pvconn;
2019     int error;
2020
2021     error = pvconn_open(target, allowed_versions, dscp, &pvconn);
2022     if (error) {
2023         return error;
2024     }
2025
2026     ofservice = xzalloc(sizeof *ofservice);
2027     hmap_insert(&mgr->services, &ofservice->node, hash_string(target, 0));
2028     ofservice->pvconn = pvconn;
2029     ofservice->allowed_versions = allowed_versions;
2030
2031     return 0;
2032 }
2033
2034 static void
2035 ofservice_destroy(struct connmgr *mgr, struct ofservice *ofservice)
2036 {
2037     hmap_remove(&mgr->services, &ofservice->node);
2038     pvconn_close(ofservice->pvconn);
2039     free(ofservice);
2040 }
2041
2042 static void
2043 ofservice_reconfigure(struct ofservice *ofservice,
2044                       const struct ofproto_controller *c)
2045 {
2046     ofservice->probe_interval = c->probe_interval;
2047     ofservice->rate_limit = c->rate_limit;
2048     ofservice->burst_limit = c->burst_limit;
2049     ofservice->enable_async_msgs = c->enable_async_msgs;
2050     ofservice->dscp = c->dscp;
2051 }
2052
2053 /* Finds and returns the ofservice within 'mgr' that has the given
2054  * 'target', or a null pointer if none exists. */
2055 static struct ofservice *
2056 ofservice_lookup(struct connmgr *mgr, const char *target)
2057 {
2058     struct ofservice *ofservice;
2059
2060     HMAP_FOR_EACH_WITH_HASH (ofservice, node, hash_string(target, 0),
2061                              &mgr->services) {
2062         if (!strcmp(pvconn_get_name(ofservice->pvconn), target)) {
2063             return ofservice;
2064         }
2065     }
2066     return NULL;
2067 }
2068 \f
2069 /* Flow monitors (NXST_FLOW_MONITOR). */
2070
2071 /* A counter incremented when something significant happens to an OpenFlow
2072  * rule.
2073  *
2074  *     - When a rule is added, its 'add_seqno' and 'modify_seqno' are set to
2075  *       the current value (which is then incremented).
2076  *
2077  *     - When a rule is modified, its 'modify_seqno' is set to the current
2078  *       value (which is then incremented).
2079  *
2080  * Thus, by comparing an old value of monitor_seqno against a rule's
2081  * 'add_seqno', one can tell whether the rule was added before or after the old
2082  * value was read, and similarly for 'modify_seqno'.
2083  *
2084  * 32 bits should normally be sufficient (and would be nice, to save space in
2085  * each rule) but then we'd have to have some special cases for wraparound.
2086  *
2087  * We initialize monitor_seqno to 1 to allow 0 to be used as an invalid
2088  * value. */
2089 static uint64_t monitor_seqno = 1;
2090
2091 COVERAGE_DEFINE(ofmonitor_pause);
2092 COVERAGE_DEFINE(ofmonitor_resume);
2093
2094 enum ofperr
2095 ofmonitor_create(const struct ofputil_flow_monitor_request *request,
2096                  struct ofconn *ofconn, struct ofmonitor **monitorp)
2097     OVS_REQUIRES(ofproto_mutex)
2098 {
2099     struct ofmonitor *m;
2100
2101     *monitorp = NULL;
2102
2103     m = ofmonitor_lookup(ofconn, request->id);
2104     if (m) {
2105         return OFPERR_NXBRC_FM_DUPLICATE_ID;
2106     }
2107
2108     m = xmalloc(sizeof *m);
2109     m->ofconn = ofconn;
2110     hmap_insert(&ofconn->monitors, &m->ofconn_node, hash_int(request->id, 0));
2111     m->id = request->id;
2112     m->flags = request->flags;
2113     m->out_port = request->out_port;
2114     m->table_id = request->table_id;
2115     minimatch_init(&m->match, &request->match);
2116
2117     *monitorp = m;
2118     return 0;
2119 }
2120
2121 struct ofmonitor *
2122 ofmonitor_lookup(struct ofconn *ofconn, uint32_t id)
2123     OVS_REQUIRES(ofproto_mutex)
2124 {
2125     struct ofmonitor *m;
2126
2127     HMAP_FOR_EACH_IN_BUCKET (m, ofconn_node, hash_int(id, 0),
2128                              &ofconn->monitors) {
2129         if (m->id == id) {
2130             return m;
2131         }
2132     }
2133     return NULL;
2134 }
2135
2136 void
2137 ofmonitor_destroy(struct ofmonitor *m)
2138     OVS_REQUIRES(ofproto_mutex)
2139 {
2140     if (m) {
2141         minimatch_destroy(&m->match);
2142         hmap_remove(&m->ofconn->monitors, &m->ofconn_node);
2143         free(m);
2144     }
2145 }
2146
2147 void
2148 ofmonitor_report(struct connmgr *mgr, struct rule *rule,
2149                  enum nx_flow_update_event event,
2150                  enum ofp_flow_removed_reason reason,
2151                  const struct ofconn *abbrev_ofconn, ovs_be32 abbrev_xid)
2152     OVS_REQUIRES(ofproto_mutex)
2153 {
2154     enum nx_flow_monitor_flags update;
2155     struct ofconn *ofconn;
2156
2157     switch (event) {
2158     case NXFME_ADDED:
2159         update = NXFMF_ADD;
2160         rule->add_seqno = rule->modify_seqno = monitor_seqno++;
2161         break;
2162
2163     case NXFME_DELETED:
2164         update = NXFMF_DELETE;
2165         break;
2166
2167     case NXFME_MODIFIED:
2168         update = NXFMF_MODIFY;
2169         rule->modify_seqno = monitor_seqno++;
2170         break;
2171
2172     default:
2173     case NXFME_ABBREV:
2174         OVS_NOT_REACHED();
2175     }
2176
2177     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
2178         enum nx_flow_monitor_flags flags = 0;
2179         struct ofmonitor *m;
2180
2181         if (ofconn->monitor_paused) {
2182             /* Only send NXFME_DELETED notifications for flows that were added
2183              * before we paused. */
2184             if (event != NXFME_DELETED
2185                 || rule->add_seqno > ofconn->monitor_paused) {
2186                 continue;
2187             }
2188         }
2189
2190         HMAP_FOR_EACH (m, ofconn_node, &ofconn->monitors) {
2191             if (m->flags & update
2192                 && (m->table_id == 0xff || m->table_id == rule->table_id)
2193                 && ofoperation_has_out_port(rule->pending, m->out_port)
2194                 && cls_rule_is_loose_match(&rule->cr, &m->match)) {
2195                 flags |= m->flags;
2196             }
2197         }
2198
2199         if (flags) {
2200             if (list_is_empty(&ofconn->updates)) {
2201                 ofputil_start_flow_update(&ofconn->updates);
2202                 ofconn->sent_abbrev_update = false;
2203             }
2204
2205             if (ofconn != abbrev_ofconn || ofconn->monitor_paused) {
2206                 struct ofputil_flow_update fu;
2207                 struct match match;
2208
2209                 fu.event = event;
2210                 fu.reason = event == NXFME_DELETED ? reason : 0;
2211                 fu.table_id = rule->table_id;
2212                 fu.cookie = rule->flow_cookie;
2213                 minimatch_expand(&rule->cr.match, &match);
2214                 fu.match = &match;
2215                 fu.priority = rule->cr.priority;
2216
2217                 ovs_mutex_lock(&rule->mutex);
2218                 fu.idle_timeout = rule->idle_timeout;
2219                 fu.hard_timeout = rule->hard_timeout;
2220                 ovs_mutex_unlock(&rule->mutex);
2221
2222                 if (flags & NXFMF_ACTIONS) {
2223                     const struct rule_actions *actions = rule_get_actions(rule);
2224                     fu.ofpacts = actions->ofpacts;
2225                     fu.ofpacts_len = actions->ofpacts_len;
2226                 } else {
2227                     fu.ofpacts = NULL;
2228                     fu.ofpacts_len = 0;
2229                 }
2230                 ofputil_append_flow_update(&fu, &ofconn->updates);
2231             } else if (!ofconn->sent_abbrev_update) {
2232                 struct ofputil_flow_update fu;
2233
2234                 fu.event = NXFME_ABBREV;
2235                 fu.xid = abbrev_xid;
2236                 ofputil_append_flow_update(&fu, &ofconn->updates);
2237
2238                 ofconn->sent_abbrev_update = true;
2239             }
2240         }
2241     }
2242 }
2243
2244 void
2245 ofmonitor_flush(struct connmgr *mgr)
2246     OVS_REQUIRES(ofproto_mutex)
2247 {
2248     struct ofconn *ofconn;
2249
2250     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
2251         struct ofpbuf *msg, *next;
2252
2253         LIST_FOR_EACH_SAFE (msg, next, list_node, &ofconn->updates) {
2254             unsigned int n_bytes;
2255
2256             list_remove(&msg->list_node);
2257             ofconn_send(ofconn, msg, ofconn->monitor_counter);
2258             n_bytes = rconn_packet_counter_n_bytes(ofconn->monitor_counter);
2259             if (!ofconn->monitor_paused && n_bytes > 128 * 1024) {
2260                 struct ofpbuf *pause;
2261
2262                 COVERAGE_INC(ofmonitor_pause);
2263                 ofconn->monitor_paused = monitor_seqno++;
2264                 pause = ofpraw_alloc_xid(OFPRAW_NXT_FLOW_MONITOR_PAUSED,
2265                                          OFP10_VERSION, htonl(0), 0);
2266                 ofconn_send(ofconn, pause, ofconn->monitor_counter);
2267             }
2268         }
2269     }
2270 }
2271
2272 static void
2273 ofmonitor_resume(struct ofconn *ofconn)
2274     OVS_REQUIRES(ofproto_mutex)
2275 {
2276     struct rule_collection rules;
2277     struct ofpbuf *resumed;
2278     struct ofmonitor *m;
2279     struct list msgs;
2280
2281     rule_collection_init(&rules);
2282     HMAP_FOR_EACH (m, ofconn_node, &ofconn->monitors) {
2283         ofmonitor_collect_resume_rules(m, ofconn->monitor_paused, &rules);
2284     }
2285
2286     list_init(&msgs);
2287     ofmonitor_compose_refresh_updates(&rules, &msgs);
2288
2289     resumed = ofpraw_alloc_xid(OFPRAW_NXT_FLOW_MONITOR_RESUMED, OFP10_VERSION,
2290                                htonl(0), 0);
2291     list_push_back(&msgs, &resumed->list_node);
2292     ofconn_send_replies(ofconn, &msgs);
2293
2294     ofconn->monitor_paused = 0;
2295 }
2296
2297 static bool
2298 ofmonitor_may_resume(const struct ofconn *ofconn)
2299     OVS_REQUIRES(ofproto_mutex)
2300 {
2301     return (ofconn->monitor_paused != 0
2302             && !rconn_packet_counter_n_packets(ofconn->monitor_counter));
2303 }
2304
2305 static void
2306 ofmonitor_run(struct connmgr *mgr)
2307 {
2308     struct ofconn *ofconn;
2309
2310     ovs_mutex_lock(&ofproto_mutex);
2311     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
2312         if (ofmonitor_may_resume(ofconn)) {
2313             COVERAGE_INC(ofmonitor_resume);
2314             ofmonitor_resume(ofconn);
2315         }
2316     }
2317     ovs_mutex_unlock(&ofproto_mutex);
2318 }
2319
2320 static void
2321 ofmonitor_wait(struct connmgr *mgr)
2322 {
2323     struct ofconn *ofconn;
2324
2325     ovs_mutex_lock(&ofproto_mutex);
2326     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
2327         if (ofmonitor_may_resume(ofconn)) {
2328             poll_immediate_wake();
2329         }
2330     }
2331     ovs_mutex_unlock(&ofproto_mutex);
2332 }