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