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