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