e0a097fcd3e5e0511fbbca2689224450bad113b9
[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;   /* Controller "struct ofconn"s. */
204     struct list all_conns;     /* Contains "struct ofconn"s. */
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
939     ofconn_send(ofconn, buf, NULL);
940 }
941
942 /* Changes 'ofconn''s role to 'role'.  If 'role' is OFPCR12_ROLE_MASTER then
943  * any existing master is demoted to a slave. */
944 void
945 ofconn_set_role(struct ofconn *ofconn, enum ofp12_controller_role role)
946 {
947     if (role != ofconn->role && role == OFPCR12_ROLE_MASTER) {
948         struct ofconn *other;
949
950         HMAP_FOR_EACH (other, hmap_node, &ofconn->connmgr->controllers) {
951             if (other->role == OFPCR12_ROLE_MASTER) {
952                 other->role = OFPCR12_ROLE_SLAVE;
953                 ofconn_send_role_status(other, OFPCR12_ROLE_SLAVE, OFPCRR_MASTER_REQUEST);
954             }
955         }
956     }
957     ofconn->role = role;
958 }
959
960 void
961 ofconn_set_invalid_ttl_to_controller(struct ofconn *ofconn, bool enable)
962 {
963     uint32_t bit = 1u << OFPR_INVALID_TTL;
964     if (enable) {
965         ofconn->master_async_config[OAM_PACKET_IN] |= bit;
966     } else {
967         ofconn->master_async_config[OAM_PACKET_IN] &= ~bit;
968     }
969 }
970
971 bool
972 ofconn_get_invalid_ttl_to_controller(struct ofconn *ofconn)
973 {
974     uint32_t bit = 1u << OFPR_INVALID_TTL;
975     return (ofconn->master_async_config[OAM_PACKET_IN] & bit) != 0;
976 }
977
978 /* Returns the currently configured protocol for 'ofconn', one of OFPUTIL_P_*.
979  *
980  * Returns OFPUTIL_P_NONE, which is not a valid protocol, if 'ofconn' hasn't
981  * completed version negotiation.  This can't happen if at least one OpenFlow
982  * message, other than OFPT_HELLO, has been received on the connection (such as
983  * in ofproto.c's message handling code), since version negotiation is a
984  * prerequisite for starting to receive messages.  This means that
985  * OFPUTIL_P_NONE is a special case that most callers need not worry about. */
986 enum ofputil_protocol
987 ofconn_get_protocol(const struct ofconn *ofconn)
988 {
989     if (ofconn->protocol == OFPUTIL_P_NONE &&
990         rconn_is_connected(ofconn->rconn)) {
991         int version = rconn_get_version(ofconn->rconn);
992         if (version > 0) {
993             ofconn_set_protocol(CONST_CAST(struct ofconn *, ofconn),
994                                 ofputil_protocol_from_ofp_version(version));
995         }
996     }
997
998     return ofconn->protocol;
999 }
1000
1001 /* Sets the protocol for 'ofconn' to 'protocol' (one of OFPUTIL_P_*).
1002  *
1003  * (This doesn't actually send anything to accomplish this.  Presumably the
1004  * caller already did that.) */
1005 void
1006 ofconn_set_protocol(struct ofconn *ofconn, enum ofputil_protocol protocol)
1007 {
1008     ofconn->protocol = protocol;
1009 }
1010
1011 /* Returns the currently configured packet in format for 'ofconn', one of
1012  * NXPIF_*.
1013  *
1014  * The default, if no other format has been set, is NXPIF_OPENFLOW10. */
1015 enum nx_packet_in_format
1016 ofconn_get_packet_in_format(struct ofconn *ofconn)
1017 {
1018     return ofconn->packet_in_format;
1019 }
1020
1021 /* Sets the packet in format for 'ofconn' to 'packet_in_format' (one of
1022  * NXPIF_*). */
1023 void
1024 ofconn_set_packet_in_format(struct ofconn *ofconn,
1025                             enum nx_packet_in_format packet_in_format)
1026 {
1027     ofconn->packet_in_format = packet_in_format;
1028 }
1029
1030 /* Sets the controller connection ID for 'ofconn' to 'controller_id'.
1031  *
1032  * The connection controller ID is used for OFPP_CONTROLLER and
1033  * NXAST_CONTROLLER actions.  See "struct nx_action_controller" for details. */
1034 void
1035 ofconn_set_controller_id(struct ofconn *ofconn, uint16_t controller_id)
1036 {
1037     ofconn->controller_id = controller_id;
1038 }
1039
1040 /* Returns the default miss send length for 'ofconn'. */
1041 int
1042 ofconn_get_miss_send_len(const struct ofconn *ofconn)
1043 {
1044     return ofconn->miss_send_len;
1045 }
1046
1047 /* Sets the default miss send length for 'ofconn' to 'miss_send_len'. */
1048 void
1049 ofconn_set_miss_send_len(struct ofconn *ofconn, int miss_send_len)
1050 {
1051     ofconn->miss_send_len = miss_send_len;
1052 }
1053
1054 void
1055 ofconn_set_async_config(struct ofconn *ofconn,
1056                         const uint32_t master_masks[OAM_N_TYPES],
1057                         const uint32_t slave_masks[OAM_N_TYPES])
1058 {
1059     size_t size = sizeof ofconn->master_async_config;
1060     memcpy(ofconn->master_async_config, master_masks, size);
1061     memcpy(ofconn->slave_async_config, slave_masks, size);
1062 }
1063
1064 void
1065 ofconn_get_async_config(struct ofconn *ofconn,
1066                         uint32_t *master_masks, uint32_t *slave_masks)
1067 {
1068     size_t size = sizeof ofconn->master_async_config;
1069     memcpy(master_masks, ofconn->master_async_config, size);
1070     memcpy(slave_masks, ofconn->slave_async_config, size);
1071 }
1072
1073 /* Sends 'msg' on 'ofconn', accounting it as a reply.  (If there is a
1074  * sufficient number of OpenFlow replies in-flight on a single ofconn, then the
1075  * connmgr will stop accepting new OpenFlow requests on that ofconn until the
1076  * controller has accepted some of the replies.) */
1077 void
1078 ofconn_send_reply(const struct ofconn *ofconn, struct ofpbuf *msg)
1079 {
1080     ofconn_send(ofconn, msg, ofconn->reply_counter);
1081 }
1082
1083 /* Sends each of the messages in list 'replies' on 'ofconn' in order,
1084  * accounting them as replies. */
1085 void
1086 ofconn_send_replies(const struct ofconn *ofconn, struct list *replies)
1087 {
1088     struct ofpbuf *reply, *next;
1089
1090     LIST_FOR_EACH_SAFE (reply, next, list_node, replies) {
1091         list_remove(&reply->list_node);
1092         ofconn_send_reply(ofconn, reply);
1093     }
1094 }
1095
1096 /* Sends 'error' on 'ofconn', as a reply to 'request'.  Only at most the
1097  * first 64 bytes of 'request' are used. */
1098 void
1099 ofconn_send_error(const struct ofconn *ofconn,
1100                   const struct ofp_header *request, enum ofperr error)
1101 {
1102     static struct vlog_rate_limit err_rl = VLOG_RATE_LIMIT_INIT(10, 10);
1103     struct ofpbuf *reply;
1104
1105     reply = ofperr_encode_reply(error, request);
1106     if (!VLOG_DROP_INFO(&err_rl)) {
1107         const char *type_name;
1108         size_t request_len;
1109         enum ofpraw raw;
1110
1111         request_len = ntohs(request->length);
1112         type_name = (!ofpraw_decode_partial(&raw, request,
1113                                             MIN(64, request_len))
1114                      ? ofpraw_get_name(raw)
1115                      : "invalid");
1116
1117         VLOG_INFO("%s: sending %s error reply to %s message",
1118                   rconn_get_name(ofconn->rconn), ofperr_to_string(error),
1119                   type_name);
1120     }
1121     ofconn_send_reply(ofconn, reply);
1122 }
1123
1124 /* Same as pktbuf_retrieve(), using the pktbuf owned by 'ofconn'. */
1125 enum ofperr
1126 ofconn_pktbuf_retrieve(struct ofconn *ofconn, uint32_t id,
1127                        struct ofpbuf **bufferp, ofp_port_t *in_port)
1128 {
1129     return pktbuf_retrieve(ofconn->pktbuf, id, bufferp, in_port);
1130 }
1131
1132 /* Reports that a flow_mod operation of the type specified by 'command' was
1133  * successfully executed by 'ofconn', so that the connmgr can log it. */
1134 void
1135 ofconn_report_flow_mod(struct ofconn *ofconn,
1136                        enum ofp_flow_mod_command command)
1137 {
1138     long long int now;
1139
1140     switch (command) {
1141     case OFPFC_ADD:
1142         ofconn->n_add++;
1143         break;
1144
1145     case OFPFC_MODIFY:
1146     case OFPFC_MODIFY_STRICT:
1147         ofconn->n_modify++;
1148         break;
1149
1150     case OFPFC_DELETE:
1151     case OFPFC_DELETE_STRICT:
1152         ofconn->n_delete++;
1153         break;
1154     }
1155
1156     now = time_msec();
1157     if (ofconn->next_op_report == LLONG_MAX) {
1158         ofconn->first_op = now;
1159         ofconn->next_op_report = MAX(now + 10 * 1000, ofconn->op_backoff);
1160         ofconn->op_backoff = ofconn->next_op_report + 60 * 1000;
1161     }
1162     ofconn->last_op = now;
1163 }
1164
1165 /* Returns true if 'ofconn' has any pending opgroups. */
1166 bool
1167 ofconn_has_pending_opgroups(const struct ofconn *ofconn)
1168 {
1169     return !list_is_empty(&ofconn->opgroups);
1170 }
1171
1172 /* Adds 'ofconn_node' to 'ofconn''s list of pending opgroups.
1173  *
1174  * If 'ofconn' is destroyed or its connection drops, then 'ofconn' will remove
1175  * 'ofconn_node' from the list and re-initialize it with list_init().  The
1176  * client may, therefore, use list_is_empty(ofconn_node) to determine whether
1177  * 'ofconn_node' is still associated with an active ofconn.
1178  *
1179  * The client may also remove ofconn_node from the list itself, with
1180  * list_remove(). */
1181 void
1182 ofconn_add_opgroup(struct ofconn *ofconn, struct list *ofconn_node)
1183 {
1184     list_push_back(&ofconn->opgroups, ofconn_node);
1185 }
1186
1187 struct hmap *
1188 ofconn_get_bundles(struct ofconn *ofconn)
1189 {
1190     return &ofconn->bundles;
1191 }
1192
1193 \f
1194 /* Private ofconn functions. */
1195
1196 static const char *
1197 ofconn_get_target(const struct ofconn *ofconn)
1198 {
1199     return rconn_get_target(ofconn->rconn);
1200 }
1201
1202 static struct ofconn *
1203 ofconn_create(struct connmgr *mgr, struct rconn *rconn, enum ofconn_type type,
1204               bool enable_async_msgs)
1205 {
1206     struct ofconn *ofconn;
1207
1208     ofconn = xzalloc(sizeof *ofconn);
1209     ofconn->connmgr = mgr;
1210     list_push_back(&mgr->all_conns, &ofconn->node);
1211     ofconn->rconn = rconn;
1212     ofconn->type = type;
1213     ofconn->enable_async_msgs = enable_async_msgs;
1214
1215     list_init(&ofconn->opgroups);
1216
1217     hmap_init(&ofconn->monitors);
1218     list_init(&ofconn->updates);
1219
1220     hmap_init(&ofconn->bundles);
1221
1222     ofconn_flush(ofconn);
1223
1224     return ofconn;
1225 }
1226
1227 /* Clears all of the state in 'ofconn' that should not persist from one
1228  * connection to the next. */
1229 static void
1230 ofconn_flush(struct ofconn *ofconn)
1231     OVS_REQUIRES(ofproto_mutex)
1232 {
1233     struct ofmonitor *monitor, *next_monitor;
1234     int i;
1235
1236     ofconn_log_flow_mods(ofconn);
1237
1238     ofconn->role = OFPCR12_ROLE_EQUAL;
1239     ofconn_set_protocol(ofconn, OFPUTIL_P_NONE);
1240     ofconn->packet_in_format = NXPIF_OPENFLOW10;
1241
1242     /* Disassociate 'ofconn' from all of the ofopgroups that it initiated that
1243      * have not yet completed.  (Those ofopgroups will still run to completion
1244      * in the usual way, but any errors that they run into will not be reported
1245      * on any OpenFlow channel.)
1246      *
1247      * Also discard any blocked operation on 'ofconn'. */
1248     while (!list_is_empty(&ofconn->opgroups)) {
1249         list_init(list_pop_front(&ofconn->opgroups));
1250     }
1251     ofpbuf_delete(ofconn->blocked);
1252     ofconn->blocked = NULL;
1253
1254     rconn_packet_counter_destroy(ofconn->packet_in_counter);
1255     ofconn->packet_in_counter = rconn_packet_counter_create();
1256     for (i = 0; i < N_SCHEDULERS; i++) {
1257         if (ofconn->schedulers[i]) {
1258             int rate, burst;
1259
1260             pinsched_get_limits(ofconn->schedulers[i], &rate, &burst);
1261             pinsched_destroy(ofconn->schedulers[i]);
1262             ofconn->schedulers[i] = pinsched_create(rate, burst);
1263         }
1264     }
1265     if (ofconn->pktbuf) {
1266         pktbuf_destroy(ofconn->pktbuf);
1267         ofconn->pktbuf = pktbuf_create();
1268     }
1269     ofconn->miss_send_len = (ofconn->type == OFCONN_PRIMARY
1270                              ? OFP_DEFAULT_MISS_SEND_LEN
1271                              : 0);
1272     ofconn->controller_id = 0;
1273
1274     rconn_packet_counter_destroy(ofconn->reply_counter);
1275     ofconn->reply_counter = rconn_packet_counter_create();
1276
1277     if (ofconn->enable_async_msgs) {
1278         uint32_t *master = ofconn->master_async_config;
1279         uint32_t *slave = ofconn->slave_async_config;
1280
1281         /* "master" and "other" roles get all asynchronous messages by default,
1282          * except that the controller needs to enable nonstandard "packet-in"
1283          * reasons itself. */
1284         master[OAM_PACKET_IN] = (1u << OFPR_NO_MATCH) | (1u << OFPR_ACTION);
1285         master[OAM_PORT_STATUS] = ((1u << OFPPR_ADD)
1286                                    | (1u << OFPPR_DELETE)
1287                                    | (1u << OFPPR_MODIFY));
1288         master[OAM_FLOW_REMOVED] = ((1u << OFPRR_IDLE_TIMEOUT)
1289                                     | (1u << OFPRR_HARD_TIMEOUT)
1290                                     | (1u << OFPRR_DELETE));
1291
1292         /* "slave" role gets port status updates by default. */
1293         slave[OAM_PACKET_IN] = 0;
1294         slave[OAM_PORT_STATUS] = ((1u << OFPPR_ADD)
1295                                   | (1u << OFPPR_DELETE)
1296                                   | (1u << OFPPR_MODIFY));
1297         slave[OAM_FLOW_REMOVED] = 0;
1298     } else {
1299         memset(ofconn->master_async_config, 0,
1300                sizeof ofconn->master_async_config);
1301         memset(ofconn->slave_async_config, 0,
1302                sizeof ofconn->slave_async_config);
1303     }
1304
1305     ofconn->n_add = ofconn->n_delete = ofconn->n_modify = 0;
1306     ofconn->first_op = ofconn->last_op = LLONG_MIN;
1307     ofconn->next_op_report = LLONG_MAX;
1308     ofconn->op_backoff = LLONG_MIN;
1309
1310     HMAP_FOR_EACH_SAFE (monitor, next_monitor, ofconn_node,
1311                         &ofconn->monitors) {
1312         ofmonitor_destroy(monitor);
1313     }
1314     rconn_packet_counter_destroy(ofconn->monitor_counter);
1315     ofconn->monitor_counter = rconn_packet_counter_create();
1316     ofpbuf_list_delete(&ofconn->updates); /* ...but it should be empty. */
1317 }
1318
1319 static void
1320 ofconn_destroy(struct ofconn *ofconn)
1321     OVS_REQUIRES(ofproto_mutex)
1322 {
1323     ofconn_flush(ofconn);
1324
1325     if (ofconn->type == OFCONN_PRIMARY) {
1326         hmap_remove(&ofconn->connmgr->controllers, &ofconn->hmap_node);
1327     }
1328
1329     ofp_bundle_remove_all(ofconn);
1330
1331     hmap_destroy(&ofconn->monitors);
1332     list_remove(&ofconn->node);
1333     rconn_destroy(ofconn->rconn);
1334     rconn_packet_counter_destroy(ofconn->packet_in_counter);
1335     rconn_packet_counter_destroy(ofconn->reply_counter);
1336     pktbuf_destroy(ofconn->pktbuf);
1337     rconn_packet_counter_destroy(ofconn->monitor_counter);
1338     free(ofconn);
1339 }
1340
1341 /* Reconfigures 'ofconn' to match 'c'.  'ofconn' and 'c' must have the same
1342  * target. */
1343 static void
1344 ofconn_reconfigure(struct ofconn *ofconn, const struct ofproto_controller *c)
1345 {
1346     int probe_interval;
1347
1348     ofconn->band = c->band;
1349     ofconn->enable_async_msgs = c->enable_async_msgs;
1350
1351     rconn_set_max_backoff(ofconn->rconn, c->max_backoff);
1352
1353     probe_interval = c->probe_interval ? MAX(c->probe_interval, 5) : 0;
1354     rconn_set_probe_interval(ofconn->rconn, probe_interval);
1355
1356     ofconn_set_rate_limit(ofconn, c->rate_limit, c->burst_limit);
1357
1358     /* If dscp value changed reconnect. */
1359     if (c->dscp != rconn_get_dscp(ofconn->rconn)) {
1360         rconn_set_dscp(ofconn->rconn, c->dscp);
1361         rconn_reconnect(ofconn->rconn);
1362     }
1363 }
1364
1365 /* Returns true if it makes sense for 'ofconn' to receive and process OpenFlow
1366  * messages. */
1367 static bool
1368 ofconn_may_recv(const struct ofconn *ofconn)
1369 {
1370     int count = rconn_packet_counter_n_packets(ofconn->reply_counter);
1371     return (!ofconn->blocked || ofconn->retry) && count < OFCONN_REPLY_MAX;
1372 }
1373
1374 static void
1375 ofconn_run(struct ofconn *ofconn,
1376            bool (*handle_openflow)(struct ofconn *,
1377                                    const struct ofpbuf *ofp_msg))
1378 {
1379     struct connmgr *mgr = ofconn->connmgr;
1380     size_t i;
1381
1382     for (i = 0; i < N_SCHEDULERS; i++) {
1383         struct list txq;
1384
1385         pinsched_run(ofconn->schedulers[i], &txq);
1386         do_send_packet_ins(ofconn, &txq);
1387     }
1388
1389     rconn_run(ofconn->rconn);
1390
1391     if (handle_openflow) {
1392         /* Limit the number of iterations to avoid starving other tasks. */
1393         for (i = 0; i < 50 && ofconn_may_recv(ofconn); i++) {
1394             struct ofpbuf *of_msg;
1395
1396             of_msg = (ofconn->blocked
1397                       ? ofconn->blocked
1398                       : rconn_recv(ofconn->rconn));
1399             if (!of_msg) {
1400                 break;
1401             }
1402             if (mgr->fail_open) {
1403                 fail_open_maybe_recover(mgr->fail_open);
1404             }
1405
1406             if (handle_openflow(ofconn, of_msg)) {
1407                 ofpbuf_delete(of_msg);
1408                 ofconn->blocked = NULL;
1409             } else {
1410                 ofconn->blocked = of_msg;
1411                 ofconn->retry = false;
1412             }
1413         }
1414     }
1415
1416
1417     if (time_msec() >= ofconn->next_op_report) {
1418         ofconn_log_flow_mods(ofconn);
1419     }
1420
1421     ovs_mutex_lock(&ofproto_mutex);
1422     if (!rconn_is_alive(ofconn->rconn)) {
1423         ofconn_destroy(ofconn);
1424     } else if (!rconn_is_connected(ofconn->rconn)) {
1425         ofconn_flush(ofconn);
1426     }
1427     ovs_mutex_unlock(&ofproto_mutex);
1428 }
1429
1430 static void
1431 ofconn_wait(struct ofconn *ofconn, bool handling_openflow)
1432 {
1433     int i;
1434
1435     for (i = 0; i < N_SCHEDULERS; i++) {
1436         pinsched_wait(ofconn->schedulers[i]);
1437     }
1438     rconn_run_wait(ofconn->rconn);
1439     if (handling_openflow && ofconn_may_recv(ofconn)) {
1440         rconn_recv_wait(ofconn->rconn);
1441     }
1442     if (ofconn->next_op_report != LLONG_MAX) {
1443         poll_timer_wait_until(ofconn->next_op_report);
1444     }
1445 }
1446
1447 static void
1448 ofconn_log_flow_mods(struct ofconn *ofconn)
1449 {
1450     int n_flow_mods = ofconn->n_add + ofconn->n_delete + ofconn->n_modify;
1451     if (n_flow_mods) {
1452         long long int ago = (time_msec() - ofconn->first_op) / 1000;
1453         long long int interval = (ofconn->last_op - ofconn->first_op) / 1000;
1454         struct ds s;
1455
1456         ds_init(&s);
1457         ds_put_format(&s, "%d flow_mods ", n_flow_mods);
1458         if (interval == ago) {
1459             ds_put_format(&s, "in the last %lld s", ago);
1460         } else if (interval) {
1461             ds_put_format(&s, "in the %lld s starting %lld s ago",
1462                           interval, ago);
1463         } else {
1464             ds_put_format(&s, "%lld s ago", ago);
1465         }
1466
1467         ds_put_cstr(&s, " (");
1468         if (ofconn->n_add) {
1469             ds_put_format(&s, "%d adds, ", ofconn->n_add);
1470         }
1471         if (ofconn->n_delete) {
1472             ds_put_format(&s, "%d deletes, ", ofconn->n_delete);
1473         }
1474         if (ofconn->n_modify) {
1475             ds_put_format(&s, "%d modifications, ", ofconn->n_modify);
1476         }
1477         s.length -= 2;
1478         ds_put_char(&s, ')');
1479
1480         VLOG_INFO("%s: %s", rconn_get_name(ofconn->rconn), ds_cstr(&s));
1481         ds_destroy(&s);
1482
1483         ofconn->n_add = ofconn->n_delete = ofconn->n_modify = 0;
1484     }
1485     ofconn->next_op_report = LLONG_MAX;
1486 }
1487
1488 /* Returns true if 'ofconn' should receive asynchronous messages of the given
1489  * OAM_* 'type' and 'reason', which should be a OFPR_* value for OAM_PACKET_IN,
1490  * a OFPPR_* value for OAM_PORT_STATUS, or an OFPRR_* value for
1491  * OAM_FLOW_REMOVED.  Returns false if the message should not be sent on
1492  * 'ofconn'. */
1493 static bool
1494 ofconn_receives_async_msg(const struct ofconn *ofconn,
1495                           enum ofconn_async_msg_type type,
1496                           unsigned int reason)
1497 {
1498     const uint32_t *async_config;
1499
1500     ovs_assert(reason < 32);
1501     ovs_assert((unsigned int) type < OAM_N_TYPES);
1502
1503     if (ofconn_get_protocol(ofconn) == OFPUTIL_P_NONE
1504         || !rconn_is_connected(ofconn->rconn)) {
1505         return false;
1506     }
1507
1508     /* Keep the following code in sync with the documentation in the
1509      * "Asynchronous Messages" section in DESIGN. */
1510
1511     if (ofconn->type == OFCONN_SERVICE && !ofconn->miss_send_len) {
1512         /* Service connections don't get asynchronous messages unless they have
1513          * explicitly asked for them by setting a nonzero miss send length. */
1514         return false;
1515     }
1516
1517     async_config = (ofconn->role == OFPCR12_ROLE_SLAVE
1518                     ? ofconn->slave_async_config
1519                     : ofconn->master_async_config);
1520     if (!(async_config[type] & (1u << reason))) {
1521         return false;
1522     }
1523
1524     return true;
1525 }
1526
1527 /* The default "table-miss" behaviour for OpenFlow1.3+ is to drop the
1528  * packet rather than to send the packet to the controller.
1529  *
1530  * This function returns false to indicate the packet should be dropped if
1531  * the controller action was the result of the default table-miss behaviour
1532  * and the controller is using OpenFlow1.3+.
1533  *
1534  * Otherwise true is returned to indicate the packet should be forwarded to
1535  * the controller */
1536 static bool
1537 ofconn_wants_packet_in_on_miss(struct ofconn *ofconn,
1538                                const struct ofproto_packet_in *pin)
1539 {
1540     if (pin->miss_type == OFPROTO_PACKET_IN_MISS_WITHOUT_FLOW) {
1541         enum ofputil_protocol protocol = ofconn_get_protocol(ofconn);
1542
1543         if (protocol != OFPUTIL_P_NONE
1544             && ofputil_protocol_to_ofp_version(protocol) >= OFP13_VERSION) {
1545             enum ofproto_table_config config;
1546
1547             config = ofproto_table_get_config(ofconn->connmgr->ofproto,
1548                                               pin->up.table_id);
1549             if (config == OFPROTO_TABLE_MISS_DEFAULT) {
1550                 return false;
1551             }
1552         }
1553     }
1554     return true;
1555 }
1556
1557 /* The default "table-miss" behaviour for OpenFlow1.3+ is to drop the
1558  * packet rather than to send the packet to the controller.
1559  *
1560  * This function returns false to indicate that a packet_in message
1561  * for a "table-miss" should be sent to at least one controller.
1562  * That is there is at least one controller with controller_id 0
1563  * which connected using an OpenFlow version earlier than OpenFlow1.3.
1564  *
1565  * False otherwise.
1566  *
1567  * This logic assumes that "table-miss" packet_in messages
1568  * are always sent to controller_id 0. */
1569 bool
1570 connmgr_wants_packet_in_on_miss(struct connmgr *mgr)
1571 {
1572     struct ofconn *ofconn;
1573
1574     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
1575         enum ofputil_protocol protocol = ofconn_get_protocol(ofconn);
1576
1577         if (ofconn->controller_id == 0 &&
1578             (protocol == OFPUTIL_P_NONE ||
1579              ofputil_protocol_to_ofp_version(protocol) < OFP13_VERSION)) {
1580             return true;
1581         }
1582     }
1583     return false;
1584 }
1585
1586 /* Returns a human-readable name for an OpenFlow connection between 'mgr' and
1587  * 'target', suitable for use in log messages for identifying the connection.
1588  *
1589  * The name is dynamically allocated.  The caller should free it (with free())
1590  * when it is no longer needed. */
1591 static char *
1592 ofconn_make_name(const struct connmgr *mgr, const char *target)
1593 {
1594     return xasprintf("%s<->%s", mgr->name, target);
1595 }
1596
1597 static void
1598 ofconn_set_rate_limit(struct ofconn *ofconn, int rate, int burst)
1599 {
1600     int i;
1601
1602     for (i = 0; i < N_SCHEDULERS; i++) {
1603         struct pinsched **s = &ofconn->schedulers[i];
1604
1605         if (rate > 0) {
1606             if (!*s) {
1607                 *s = pinsched_create(rate, burst);
1608             } else {
1609                 pinsched_set_limits(*s, rate, burst);
1610             }
1611         } else {
1612             pinsched_destroy(*s);
1613             *s = NULL;
1614         }
1615     }
1616 }
1617
1618 static void
1619 ofconn_send(const struct ofconn *ofconn, struct ofpbuf *msg,
1620             struct rconn_packet_counter *counter)
1621 {
1622     ofpmsg_update_length(msg);
1623     rconn_send(ofconn->rconn, msg, counter);
1624 }
1625 \f
1626 /* Sending asynchronous messages. */
1627
1628 static void schedule_packet_in(struct ofconn *, struct ofproto_packet_in,
1629                                enum ofp_packet_in_reason wire_reason);
1630
1631 /* Sends an OFPT_PORT_STATUS message with 'opp' and 'reason' to appropriate
1632  * controllers managed by 'mgr'.  For messages caused by a controller
1633  * OFPT_PORT_MOD, specify 'source' as the controller connection that sent the
1634  * request; otherwise, specify 'source' as NULL. */
1635 void
1636 connmgr_send_port_status(struct connmgr *mgr, struct ofconn *source,
1637                          const struct ofputil_phy_port *pp, uint8_t reason)
1638 {
1639     /* XXX Should limit the number of queued port status change messages. */
1640     struct ofputil_port_status ps;
1641     struct ofconn *ofconn;
1642
1643     ps.reason = reason;
1644     ps.desc = *pp;
1645     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
1646         if (ofconn_receives_async_msg(ofconn, OAM_PORT_STATUS, reason)) {
1647             struct ofpbuf *msg;
1648
1649             /* Before 1.5, OpenFlow specified that OFPT_PORT_MOD should not
1650              * generate OFPT_PORT_STATUS messages.  That requirement was a
1651              * relic of how OpenFlow originally supported a single controller,
1652              * so that one could expect the controller to already know the
1653              * changes it had made.
1654              *
1655              * EXT-338 changes OpenFlow 1.5 OFPT_PORT_MOD to send
1656              * OFPT_PORT_STATUS messages to every controller.  This is
1657              * obviously more useful in the multi-controller case.  We could
1658              * always implement it that way in OVS, but that would risk
1659              * confusing controllers that are intended for single-controller
1660              * use only.  (Imagine a controller that generates an OFPT_PORT_MOD
1661              * in response to any OFPT_PORT_STATUS!)
1662              *
1663              * So this compromises: for OpenFlow 1.4 and earlier, it generates
1664              * OFPT_PORT_STATUS for OFPT_PORT_MOD, but not back to the
1665              * originating controller.  In a single-controller environment, in
1666              * particular, this means that it will never generate
1667              * OFPT_PORT_STATUS for OFPT_PORT_MOD at all. */
1668             if (ofconn == source
1669                 && rconn_get_version(ofconn->rconn) < OFP15_VERSION) {
1670                 continue;
1671             }
1672
1673             msg = ofputil_encode_port_status(&ps, ofconn_get_protocol(ofconn));
1674             ofconn_send(ofconn, msg, NULL);
1675         }
1676     }
1677 }
1678
1679 /* Sends an OFPT_FLOW_REMOVED or NXT_FLOW_REMOVED message based on 'fr' to
1680  * appropriate controllers managed by 'mgr'. */
1681 void
1682 connmgr_send_flow_removed(struct connmgr *mgr,
1683                           const struct ofputil_flow_removed *fr)
1684 {
1685     struct ofconn *ofconn;
1686
1687     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
1688         if (ofconn_receives_async_msg(ofconn, OAM_FLOW_REMOVED, fr->reason)) {
1689             struct ofpbuf *msg;
1690
1691             /* Account flow expirations as replies to OpenFlow requests.  That
1692              * works because preventing OpenFlow requests from being processed
1693              * also prevents new flows from being added (and expiring).  (It
1694              * also prevents processing OpenFlow requests that would not add
1695              * new flows, so it is imperfect.) */
1696             msg = ofputil_encode_flow_removed(fr, ofconn_get_protocol(ofconn));
1697             ofconn_send_reply(ofconn, msg);
1698         }
1699     }
1700 }
1701
1702 /* Normally a send-to-controller action uses reason OFPR_ACTION.  However, in
1703  * OpenFlow 1.3 and later, packet_ins generated by a send-to-controller action
1704  * in a "table-miss" flow (one with priority 0 and completely wildcarded) are
1705  * sent as OFPR_NO_MATCH.  This function returns the reason that should
1706  * actually be sent on 'ofconn' for 'pin'. */
1707 static enum ofp_packet_in_reason
1708 wire_reason(struct ofconn *ofconn, const struct ofproto_packet_in *pin)
1709 {
1710     if (pin->miss_type == OFPROTO_PACKET_IN_MISS_FLOW
1711         && pin->up.reason == OFPR_ACTION) {
1712         enum ofputil_protocol protocol = ofconn_get_protocol(ofconn);
1713
1714         if (protocol != OFPUTIL_P_NONE
1715             && ofputil_protocol_to_ofp_version(protocol) >= OFP13_VERSION) {
1716             return OFPR_NO_MATCH;
1717         }
1718     }
1719     return pin->up.reason;
1720 }
1721
1722 /* Given 'pin', sends an OFPT_PACKET_IN message to each OpenFlow controller as
1723  * necessary according to their individual configurations.
1724  *
1725  * The caller doesn't need to fill in pin->buffer_id or pin->total_len. */
1726 void
1727 connmgr_send_packet_in(struct connmgr *mgr,
1728                        const struct ofproto_packet_in *pin)
1729 {
1730     struct ofconn *ofconn;
1731
1732     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
1733         enum ofp_packet_in_reason reason = wire_reason(ofconn, pin);
1734
1735         if (ofconn_wants_packet_in_on_miss(ofconn, pin)
1736             && ofconn_receives_async_msg(ofconn, OAM_PACKET_IN, pin->up.reason)
1737             && ofconn->controller_id == pin->controller_id) {
1738             schedule_packet_in(ofconn, *pin, reason);
1739         }
1740     }
1741 }
1742
1743 static void
1744 do_send_packet_ins(struct ofconn *ofconn, struct list *txq)
1745 {
1746     struct ofpbuf *pin, *next_pin;
1747
1748     LIST_FOR_EACH_SAFE (pin, next_pin, list_node, txq) {
1749         list_remove(&pin->list_node);
1750
1751         if (rconn_send_with_limit(ofconn->rconn, pin,
1752                                   ofconn->packet_in_counter, 100) == EAGAIN) {
1753             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
1754
1755             VLOG_INFO_RL(&rl, "%s: dropping packet-in due to queue overflow",
1756                          rconn_get_name(ofconn->rconn));
1757         }
1758     }
1759 }
1760
1761 /* Takes 'pin', composes an OpenFlow packet-in message from it, and passes it
1762  * to 'ofconn''s packet scheduler for sending. */
1763 static void
1764 schedule_packet_in(struct ofconn *ofconn, struct ofproto_packet_in pin,
1765                    enum ofp_packet_in_reason wire_reason)
1766 {
1767     struct connmgr *mgr = ofconn->connmgr;
1768     uint16_t controller_max_len;
1769     struct list txq;
1770
1771     pin.up.total_len = pin.up.packet_len;
1772
1773     pin.up.reason = wire_reason;
1774     if (pin.up.reason == OFPR_ACTION) {
1775         controller_max_len = pin.send_len;  /* max_len */
1776     } else {
1777         controller_max_len = ofconn->miss_send_len;
1778     }
1779
1780     /* Get OpenFlow buffer_id.
1781      * For OpenFlow 1.2+, OFPCML_NO_BUFFER (== UINT16_MAX) specifies
1782      * unbuffered.  This behaviour doesn't violate prior versions, too. */
1783     if (controller_max_len == UINT16_MAX) {
1784         pin.up.buffer_id = UINT32_MAX;
1785     } else if (mgr->fail_open && fail_open_is_active(mgr->fail_open)) {
1786         pin.up.buffer_id = pktbuf_get_null();
1787     } else if (!ofconn->pktbuf) {
1788         pin.up.buffer_id = UINT32_MAX;
1789     } else {
1790         pin.up.buffer_id = pktbuf_save(ofconn->pktbuf,
1791                                        pin.up.packet, pin.up.packet_len,
1792                                        pin.up.fmd.in_port);
1793     }
1794
1795     /* Figure out how much of the packet to send.
1796      * If not buffered, send the entire packet.  Otherwise, depending on
1797      * the reason of packet-in, send what requested by the controller. */
1798     if (pin.up.buffer_id != UINT32_MAX
1799         && controller_max_len < pin.up.packet_len) {
1800         pin.up.packet_len = controller_max_len;
1801     }
1802
1803     /* Make OFPT_PACKET_IN and hand over to packet scheduler. */
1804     pinsched_send(ofconn->schedulers[pin.up.reason == OFPR_NO_MATCH ? 0 : 1],
1805                   pin.up.fmd.in_port,
1806                   ofputil_encode_packet_in(&pin.up,
1807                                            ofconn_get_protocol(ofconn),
1808                                            ofconn->packet_in_format),
1809                   &txq);
1810     do_send_packet_ins(ofconn, &txq);
1811 }
1812 \f
1813 /* Fail-open settings. */
1814
1815 /* Returns the failure handling mode (OFPROTO_FAIL_SECURE or
1816  * OFPROTO_FAIL_STANDALONE) for 'mgr'. */
1817 enum ofproto_fail_mode
1818 connmgr_get_fail_mode(const struct connmgr *mgr)
1819 {
1820     return mgr->fail_mode;
1821 }
1822
1823 /* Sets the failure handling mode for 'mgr' to 'fail_mode' (either
1824  * OFPROTO_FAIL_SECURE or OFPROTO_FAIL_STANDALONE). */
1825 void
1826 connmgr_set_fail_mode(struct connmgr *mgr, enum ofproto_fail_mode fail_mode)
1827 {
1828     if (mgr->fail_mode != fail_mode) {
1829         mgr->fail_mode = fail_mode;
1830         update_fail_open(mgr);
1831         if (!connmgr_has_controllers(mgr)) {
1832             ofproto_flush_flows(mgr->ofproto);
1833         }
1834     }
1835 }
1836 \f
1837 /* Fail-open implementation. */
1838
1839 /* Returns the longest probe interval among the primary controllers configured
1840  * on 'mgr'.  Returns 0 if there are no primary controllers. */
1841 int
1842 connmgr_get_max_probe_interval(const struct connmgr *mgr)
1843 {
1844     const struct ofconn *ofconn;
1845     int max_probe_interval;
1846
1847     max_probe_interval = 0;
1848     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
1849         int probe_interval = rconn_get_probe_interval(ofconn->rconn);
1850         max_probe_interval = MAX(max_probe_interval, probe_interval);
1851     }
1852     return max_probe_interval;
1853 }
1854
1855 /* Returns the number of seconds for which all of 'mgr's primary controllers
1856  * have been disconnected.  Returns 0 if 'mgr' has no primary controllers. */
1857 int
1858 connmgr_failure_duration(const struct connmgr *mgr)
1859 {
1860     const struct ofconn *ofconn;
1861     int min_failure_duration;
1862
1863     if (!connmgr_has_controllers(mgr)) {
1864         return 0;
1865     }
1866
1867     min_failure_duration = INT_MAX;
1868     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
1869         int failure_duration = rconn_failure_duration(ofconn->rconn);
1870         min_failure_duration = MIN(min_failure_duration, failure_duration);
1871     }
1872     return min_failure_duration;
1873 }
1874
1875 /* Returns true if at least one primary controller is connected (regardless of
1876  * whether those controllers are believed to have authenticated and accepted
1877  * this switch), false if none of them are connected. */
1878 bool
1879 connmgr_is_any_controller_connected(const struct connmgr *mgr)
1880 {
1881     const struct ofconn *ofconn;
1882
1883     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
1884         if (rconn_is_connected(ofconn->rconn)) {
1885             return true;
1886         }
1887     }
1888     return false;
1889 }
1890
1891 /* Returns true if at least one primary controller is believed to have
1892  * authenticated and accepted this switch, false otherwise. */
1893 bool
1894 connmgr_is_any_controller_admitted(const struct connmgr *mgr)
1895 {
1896     const struct ofconn *ofconn;
1897
1898     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
1899         if (rconn_is_admitted(ofconn->rconn)) {
1900             return true;
1901         }
1902     }
1903     return false;
1904 }
1905 \f
1906 /* In-band configuration. */
1907
1908 static bool any_extras_changed(const struct connmgr *,
1909                                const struct sockaddr_in *extras, size_t n);
1910
1911 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'mgr''s
1912  * in-band control should guarantee access, in the same way that in-band
1913  * control guarantees access to OpenFlow controllers. */
1914 void
1915 connmgr_set_extra_in_band_remotes(struct connmgr *mgr,
1916                                   const struct sockaddr_in *extras, size_t n)
1917 {
1918     if (!any_extras_changed(mgr, extras, n)) {
1919         return;
1920     }
1921
1922     free(mgr->extra_in_band_remotes);
1923     mgr->n_extra_remotes = n;
1924     mgr->extra_in_band_remotes = xmemdup(extras, n * sizeof *extras);
1925
1926     update_in_band_remotes(mgr);
1927 }
1928
1929 /* Sets the OpenFlow queue used by flows set up by in-band control on
1930  * 'mgr' to 'queue_id'.  If 'queue_id' is negative, then in-band control
1931  * flows will use the default queue. */
1932 void
1933 connmgr_set_in_band_queue(struct connmgr *mgr, int queue_id)
1934 {
1935     if (queue_id != mgr->in_band_queue) {
1936         mgr->in_band_queue = queue_id;
1937         update_in_band_remotes(mgr);
1938     }
1939 }
1940
1941 static bool
1942 any_extras_changed(const struct connmgr *mgr,
1943                    const struct sockaddr_in *extras, size_t n)
1944 {
1945     size_t i;
1946
1947     if (n != mgr->n_extra_remotes) {
1948         return true;
1949     }
1950
1951     for (i = 0; i < n; i++) {
1952         const struct sockaddr_in *old = &mgr->extra_in_band_remotes[i];
1953         const struct sockaddr_in *new = &extras[i];
1954
1955         if (old->sin_addr.s_addr != new->sin_addr.s_addr ||
1956             old->sin_port != new->sin_port) {
1957             return true;
1958         }
1959     }
1960
1961     return false;
1962 }
1963 \f
1964 /* In-band implementation. */
1965
1966 bool
1967 connmgr_has_in_band(struct connmgr *mgr)
1968 {
1969     return mgr->in_band != NULL;
1970 }
1971 \f
1972 /* Fail-open and in-band implementation. */
1973
1974 /* Called by 'ofproto' after all flows have been flushed, to allow fail-open
1975  * and standalone mode to re-create their flows.
1976  *
1977  * In-band control has more sophisticated code that manages flows itself. */
1978 void
1979 connmgr_flushed(struct connmgr *mgr)
1980     OVS_EXCLUDED(ofproto_mutex)
1981 {
1982     if (mgr->fail_open) {
1983         fail_open_flushed(mgr->fail_open);
1984     }
1985
1986     /* If there are no controllers and we're in standalone mode, set up a flow
1987      * that matches every packet and directs them to OFPP_NORMAL (which goes to
1988      * us).  Otherwise, the switch is in secure mode and we won't pass any
1989      * traffic until a controller has been defined and it tells us to do so. */
1990     if (!connmgr_has_controllers(mgr)
1991         && mgr->fail_mode == OFPROTO_FAIL_STANDALONE) {
1992         struct ofpbuf ofpacts;
1993         struct match match;
1994
1995         ofpbuf_init(&ofpacts, OFPACT_OUTPUT_SIZE);
1996         ofpact_put_OUTPUT(&ofpacts)->port = OFPP_NORMAL;
1997         ofpact_pad(&ofpacts);
1998
1999         match_init_catchall(&match);
2000         ofproto_add_flow(mgr->ofproto, &match, 0, ofpbuf_data(&ofpacts),
2001                                                   ofpbuf_size(&ofpacts));
2002
2003         ofpbuf_uninit(&ofpacts);
2004     }
2005 }
2006 \f
2007 /* Creates a new ofservice for 'target' in 'mgr'.  Returns 0 if successful,
2008  * otherwise a positive errno value.
2009  *
2010  * ofservice_reconfigure() must be called to fully configure the new
2011  * ofservice. */
2012 static int
2013 ofservice_create(struct connmgr *mgr, const char *target,
2014                  uint32_t allowed_versions, uint8_t dscp)
2015 {
2016     struct ofservice *ofservice;
2017     struct pvconn *pvconn;
2018     int error;
2019
2020     error = pvconn_open(target, allowed_versions, dscp, &pvconn);
2021     if (error) {
2022         return error;
2023     }
2024
2025     ofservice = xzalloc(sizeof *ofservice);
2026     hmap_insert(&mgr->services, &ofservice->node, hash_string(target, 0));
2027     ofservice->pvconn = pvconn;
2028     ofservice->allowed_versions = allowed_versions;
2029
2030     return 0;
2031 }
2032
2033 static void
2034 ofservice_destroy(struct connmgr *mgr, struct ofservice *ofservice)
2035 {
2036     hmap_remove(&mgr->services, &ofservice->node);
2037     pvconn_close(ofservice->pvconn);
2038     free(ofservice);
2039 }
2040
2041 static void
2042 ofservice_reconfigure(struct ofservice *ofservice,
2043                       const struct ofproto_controller *c)
2044 {
2045     ofservice->probe_interval = c->probe_interval;
2046     ofservice->rate_limit = c->rate_limit;
2047     ofservice->burst_limit = c->burst_limit;
2048     ofservice->enable_async_msgs = c->enable_async_msgs;
2049     ofservice->dscp = c->dscp;
2050 }
2051
2052 /* Finds and returns the ofservice within 'mgr' that has the given
2053  * 'target', or a null pointer if none exists. */
2054 static struct ofservice *
2055 ofservice_lookup(struct connmgr *mgr, const char *target)
2056 {
2057     struct ofservice *ofservice;
2058
2059     HMAP_FOR_EACH_WITH_HASH (ofservice, node, hash_string(target, 0),
2060                              &mgr->services) {
2061         if (!strcmp(pvconn_get_name(ofservice->pvconn), target)) {
2062             return ofservice;
2063         }
2064     }
2065     return NULL;
2066 }
2067 \f
2068 /* Flow monitors (NXST_FLOW_MONITOR). */
2069
2070 /* A counter incremented when something significant happens to an OpenFlow
2071  * rule.
2072  *
2073  *     - When a rule is added, its 'add_seqno' and 'modify_seqno' are set to
2074  *       the current value (which is then incremented).
2075  *
2076  *     - When a rule is modified, its 'modify_seqno' is set to the current
2077  *       value (which is then incremented).
2078  *
2079  * Thus, by comparing an old value of monitor_seqno against a rule's
2080  * 'add_seqno', one can tell whether the rule was added before or after the old
2081  * value was read, and similarly for 'modify_seqno'.
2082  *
2083  * 32 bits should normally be sufficient (and would be nice, to save space in
2084  * each rule) but then we'd have to have some special cases for wraparound.
2085  *
2086  * We initialize monitor_seqno to 1 to allow 0 to be used as an invalid
2087  * value. */
2088 static uint64_t monitor_seqno = 1;
2089
2090 COVERAGE_DEFINE(ofmonitor_pause);
2091 COVERAGE_DEFINE(ofmonitor_resume);
2092
2093 enum ofperr
2094 ofmonitor_create(const struct ofputil_flow_monitor_request *request,
2095                  struct ofconn *ofconn, struct ofmonitor **monitorp)
2096     OVS_REQUIRES(ofproto_mutex)
2097 {
2098     struct ofmonitor *m;
2099
2100     *monitorp = NULL;
2101
2102     m = ofmonitor_lookup(ofconn, request->id);
2103     if (m) {
2104         return OFPERR_NXBRC_FM_DUPLICATE_ID;
2105     }
2106
2107     m = xmalloc(sizeof *m);
2108     m->ofconn = ofconn;
2109     hmap_insert(&ofconn->monitors, &m->ofconn_node, hash_int(request->id, 0));
2110     m->id = request->id;
2111     m->flags = request->flags;
2112     m->out_port = request->out_port;
2113     m->table_id = request->table_id;
2114     minimatch_init(&m->match, &request->match);
2115
2116     *monitorp = m;
2117     return 0;
2118 }
2119
2120 struct ofmonitor *
2121 ofmonitor_lookup(struct ofconn *ofconn, uint32_t id)
2122     OVS_REQUIRES(ofproto_mutex)
2123 {
2124     struct ofmonitor *m;
2125
2126     HMAP_FOR_EACH_IN_BUCKET (m, ofconn_node, hash_int(id, 0),
2127                              &ofconn->monitors) {
2128         if (m->id == id) {
2129             return m;
2130         }
2131     }
2132     return NULL;
2133 }
2134
2135 void
2136 ofmonitor_destroy(struct ofmonitor *m)
2137     OVS_REQUIRES(ofproto_mutex)
2138 {
2139     if (m) {
2140         minimatch_destroy(&m->match);
2141         hmap_remove(&m->ofconn->monitors, &m->ofconn_node);
2142         free(m);
2143     }
2144 }
2145
2146 void
2147 ofmonitor_report(struct connmgr *mgr, struct rule *rule,
2148                  enum nx_flow_update_event event,
2149                  enum ofp_flow_removed_reason reason,
2150                  const struct ofconn *abbrev_ofconn, ovs_be32 abbrev_xid)
2151     OVS_REQUIRES(ofproto_mutex)
2152 {
2153     enum nx_flow_monitor_flags update;
2154     struct ofconn *ofconn;
2155
2156     switch (event) {
2157     case NXFME_ADDED:
2158         update = NXFMF_ADD;
2159         rule->add_seqno = rule->modify_seqno = monitor_seqno++;
2160         break;
2161
2162     case NXFME_DELETED:
2163         update = NXFMF_DELETE;
2164         break;
2165
2166     case NXFME_MODIFIED:
2167         update = NXFMF_MODIFY;
2168         rule->modify_seqno = monitor_seqno++;
2169         break;
2170
2171     default:
2172     case NXFME_ABBREV:
2173         OVS_NOT_REACHED();
2174     }
2175
2176     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
2177         enum nx_flow_monitor_flags flags = 0;
2178         struct ofmonitor *m;
2179
2180         if (ofconn->monitor_paused) {
2181             /* Only send NXFME_DELETED notifications for flows that were added
2182              * before we paused. */
2183             if (event != NXFME_DELETED
2184                 || rule->add_seqno > ofconn->monitor_paused) {
2185                 continue;
2186             }
2187         }
2188
2189         HMAP_FOR_EACH (m, ofconn_node, &ofconn->monitors) {
2190             if (m->flags & update
2191                 && (m->table_id == 0xff || m->table_id == rule->table_id)
2192                 && ofoperation_has_out_port(rule->pending, m->out_port)
2193                 && cls_rule_is_loose_match(&rule->cr, &m->match)) {
2194                 flags |= m->flags;
2195             }
2196         }
2197
2198         if (flags) {
2199             if (list_is_empty(&ofconn->updates)) {
2200                 ofputil_start_flow_update(&ofconn->updates);
2201                 ofconn->sent_abbrev_update = false;
2202             }
2203
2204             if (ofconn != abbrev_ofconn || ofconn->monitor_paused) {
2205                 struct ofputil_flow_update fu;
2206                 struct match match;
2207
2208                 fu.event = event;
2209                 fu.reason = event == NXFME_DELETED ? reason : 0;
2210                 fu.table_id = rule->table_id;
2211                 fu.cookie = rule->flow_cookie;
2212                 minimatch_expand(&rule->cr.match, &match);
2213                 fu.match = &match;
2214                 fu.priority = rule->cr.priority;
2215
2216                 ovs_mutex_lock(&rule->mutex);
2217                 fu.idle_timeout = rule->idle_timeout;
2218                 fu.hard_timeout = rule->hard_timeout;
2219                 ovs_mutex_unlock(&rule->mutex);
2220
2221                 if (flags & NXFMF_ACTIONS) {
2222                     const struct rule_actions *actions = rule_get_actions(rule);
2223                     fu.ofpacts = actions->ofpacts;
2224                     fu.ofpacts_len = actions->ofpacts_len;
2225                 } else {
2226                     fu.ofpacts = NULL;
2227                     fu.ofpacts_len = 0;
2228                 }
2229                 ofputil_append_flow_update(&fu, &ofconn->updates);
2230             } else if (!ofconn->sent_abbrev_update) {
2231                 struct ofputil_flow_update fu;
2232
2233                 fu.event = NXFME_ABBREV;
2234                 fu.xid = abbrev_xid;
2235                 ofputil_append_flow_update(&fu, &ofconn->updates);
2236
2237                 ofconn->sent_abbrev_update = true;
2238             }
2239         }
2240     }
2241 }
2242
2243 void
2244 ofmonitor_flush(struct connmgr *mgr)
2245     OVS_REQUIRES(ofproto_mutex)
2246 {
2247     struct ofconn *ofconn;
2248
2249     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
2250         struct ofpbuf *msg, *next;
2251
2252         LIST_FOR_EACH_SAFE (msg, next, list_node, &ofconn->updates) {
2253             unsigned int n_bytes;
2254
2255             list_remove(&msg->list_node);
2256             ofconn_send(ofconn, msg, ofconn->monitor_counter);
2257             n_bytes = rconn_packet_counter_n_bytes(ofconn->monitor_counter);
2258             if (!ofconn->monitor_paused && n_bytes > 128 * 1024) {
2259                 struct ofpbuf *pause;
2260
2261                 COVERAGE_INC(ofmonitor_pause);
2262                 ofconn->monitor_paused = monitor_seqno++;
2263                 pause = ofpraw_alloc_xid(OFPRAW_NXT_FLOW_MONITOR_PAUSED,
2264                                          OFP10_VERSION, htonl(0), 0);
2265                 ofconn_send(ofconn, pause, ofconn->monitor_counter);
2266             }
2267         }
2268     }
2269 }
2270
2271 static void
2272 ofmonitor_resume(struct ofconn *ofconn)
2273     OVS_REQUIRES(ofproto_mutex)
2274 {
2275     struct rule_collection rules;
2276     struct ofpbuf *resumed;
2277     struct ofmonitor *m;
2278     struct list msgs;
2279
2280     rule_collection_init(&rules);
2281     HMAP_FOR_EACH (m, ofconn_node, &ofconn->monitors) {
2282         ofmonitor_collect_resume_rules(m, ofconn->monitor_paused, &rules);
2283     }
2284
2285     list_init(&msgs);
2286     ofmonitor_compose_refresh_updates(&rules, &msgs);
2287
2288     resumed = ofpraw_alloc_xid(OFPRAW_NXT_FLOW_MONITOR_RESUMED, OFP10_VERSION,
2289                                htonl(0), 0);
2290     list_push_back(&msgs, &resumed->list_node);
2291     ofconn_send_replies(ofconn, &msgs);
2292
2293     ofconn->monitor_paused = 0;
2294 }
2295
2296 static bool
2297 ofmonitor_may_resume(const struct ofconn *ofconn)
2298     OVS_REQUIRES(ofproto_mutex)
2299 {
2300     return (ofconn->monitor_paused != 0
2301             && !rconn_packet_counter_n_packets(ofconn->monitor_counter));
2302 }
2303
2304 static void
2305 ofmonitor_run(struct connmgr *mgr)
2306 {
2307     struct ofconn *ofconn;
2308
2309     ovs_mutex_lock(&ofproto_mutex);
2310     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
2311         if (ofmonitor_may_resume(ofconn)) {
2312             COVERAGE_INC(ofmonitor_resume);
2313             ofmonitor_resume(ofconn);
2314         }
2315     }
2316     ovs_mutex_unlock(&ofproto_mutex);
2317 }
2318
2319 static void
2320 ofmonitor_wait(struct connmgr *mgr)
2321 {
2322     struct ofconn *ofconn;
2323
2324     ovs_mutex_lock(&ofproto_mutex);
2325     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
2326         if (ofmonitor_may_resume(ofconn)) {
2327             poll_immediate_wake();
2328         }
2329     }
2330     ovs_mutex_unlock(&ofproto_mutex);
2331 }