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