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