connmgr: Move controller_id from ofputil_packet_in to ofproto_packet_in.
[sliver-openvswitch.git] / ofproto / connmgr.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013 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 "fail-open.h"
26 #include "in-band.h"
27 #include "odp-util.h"
28 #include "ofp-actions.h"
29 #include "ofp-msgs.h"
30 #include "ofp-util.h"
31 #include "ofpbuf.h"
32 #include "ofproto-provider.h"
33 #include "pinsched.h"
34 #include "poll-loop.h"
35 #include "pktbuf.h"
36 #include "rconn.h"
37 #include "shash.h"
38 #include "simap.h"
39 #include "stream.h"
40 #include "timeval.h"
41 #include "vconn.h"
42 #include "vlog.h"
43
44 VLOG_DEFINE_THIS_MODULE(connmgr);
45 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
46
47 /* An OpenFlow connection.
48  *
49  *
50  * Thread-safety
51  * =============
52  *
53  * 'ofproto_mutex' must be held whenever an ofconn is created or destroyed or,
54  * more or less equivalently, whenever an ofconn is added to or removed from a
55  * connmgr.  'ofproto_mutex' doesn't protect the data inside the ofconn, except
56  * as specifically noted below. */
57 struct ofconn {
58 /* Configuration that persists from one connection to the next. */
59
60     struct list node;           /* In struct connmgr's "all_conns" list. */
61     struct hmap_node hmap_node; /* In struct connmgr's "controllers" map. */
62
63     struct connmgr *connmgr;    /* Connection's manager. */
64     struct rconn *rconn;        /* OpenFlow connection. */
65     enum ofconn_type type;      /* Type. */
66     enum ofproto_band band;     /* In-band or out-of-band? */
67     bool enable_async_msgs;     /* Initially enable async messages? */
68
69 /* State that should be cleared from one connection to the next. */
70
71     /* OpenFlow state. */
72     enum ofp12_controller_role role;           /* Role. */
73     enum ofputil_protocol protocol; /* Current protocol variant. */
74     enum nx_packet_in_format packet_in_format; /* OFPT_PACKET_IN format. */
75
76     /* Asynchronous flow table operation support. */
77     struct list opgroups;       /* Contains pending "ofopgroups", if any. */
78     struct ofpbuf *blocked;     /* Postponed OpenFlow message, if any. */
79     bool retry;                 /* True if 'blocked' is ready to try again. */
80
81     /* OFPT_PACKET_IN related data. */
82     struct rconn_packet_counter *packet_in_counter; /* # queued on 'rconn'. */
83 #define N_SCHEDULERS 2
84     struct pinsched *schedulers[N_SCHEDULERS];
85     struct pktbuf *pktbuf;         /* OpenFlow packet buffers. */
86     int miss_send_len;             /* Bytes to send of buffered packets. */
87     uint16_t controller_id;     /* Connection controller ID. */
88
89     /* Number of OpenFlow messages queued on 'rconn' as replies to OpenFlow
90      * requests, and the maximum number before we stop reading OpenFlow
91      * requests.  */
92 #define OFCONN_REPLY_MAX 100
93     struct rconn_packet_counter *reply_counter;
94
95     /* Asynchronous message configuration in each possible roles.
96      *
97      * A 1-bit enables sending an asynchronous message for one possible reason
98      * that the message might be generated, a 0-bit disables it. */
99     uint32_t master_async_config[OAM_N_TYPES]; /* master, other */
100     uint32_t slave_async_config[OAM_N_TYPES];  /* slave */
101
102 /* Flow monitors (e.g. NXST_FLOW_MONITOR). */
103
104     /* Configuration.  Contains "struct ofmonitor"s. */
105     struct hmap monitors OVS_GUARDED_BY(ofproto_mutex);
106
107     /* Flow control.
108      *
109      * When too many flow monitor notifications back up in the transmit buffer,
110      * we pause the transmission of further notifications.  These members track
111      * the flow control state.
112      *
113      * When notifications are flowing, 'monitor_paused' is 0.  When
114      * notifications are paused, 'monitor_paused' is the value of
115      * 'monitor_seqno' at the point we paused.
116      *
117      * 'monitor_counter' counts the OpenFlow messages and bytes currently in
118      * flight.  This value growing too large triggers pausing. */
119     uint64_t monitor_paused OVS_GUARDED_BY(ofproto_mutex);
120     struct rconn_packet_counter *monitor_counter OVS_GUARDED_BY(ofproto_mutex);
121
122     /* State of monitors for a single ongoing flow_mod.
123      *
124      * 'updates' is a list of "struct ofpbuf"s that contain
125      * NXST_FLOW_MONITOR_REPLY messages representing the changes made by the
126      * current flow_mod.
127      *
128      * When 'updates' is nonempty, 'sent_abbrev_update' is true if 'updates'
129      * contains an update event of type NXFME_ABBREV and false otherwise.. */
130     struct list updates OVS_GUARDED_BY(ofproto_mutex);
131     bool sent_abbrev_update OVS_GUARDED_BY(ofproto_mutex);
132 };
133
134 static struct ofconn *ofconn_create(struct connmgr *, struct rconn *,
135                                     enum ofconn_type, bool enable_async_msgs)
136     OVS_REQUIRES(ofproto_mutex);
137 static void ofconn_destroy(struct ofconn *) OVS_REQUIRES(ofproto_mutex);
138 static void ofconn_flush(struct ofconn *) OVS_REQUIRES(ofproto_mutex);
139
140 static void ofconn_reconfigure(struct ofconn *,
141                                const struct ofproto_controller *);
142
143 static void ofconn_run(struct ofconn *,
144                        bool (*handle_openflow)(struct ofconn *,
145                                                const struct ofpbuf *ofp_msg));
146 static void ofconn_wait(struct ofconn *, bool handling_openflow);
147
148 static const char *ofconn_get_target(const struct ofconn *);
149 static char *ofconn_make_name(const struct connmgr *, const char *target);
150
151 static void ofconn_set_rate_limit(struct ofconn *, int rate, int burst);
152
153 static void ofconn_send(const struct ofconn *, struct ofpbuf *,
154                         struct rconn_packet_counter *);
155
156 static void do_send_packet_in(struct ofpbuf *, void *ofconn_);
157
158 /* A listener for incoming OpenFlow "service" connections. */
159 struct ofservice {
160     struct hmap_node node;      /* In struct connmgr's "services" hmap. */
161     struct pvconn *pvconn;      /* OpenFlow connection listener. */
162
163     /* These are not used by ofservice directly.  They are settings for
164      * accepted "struct ofconn"s from the pvconn. */
165     int probe_interval;         /* Max idle time before probing, in seconds. */
166     int rate_limit;             /* Max packet-in rate in packets per second. */
167     int burst_limit;            /* Limit on accumulating packet credits. */
168     bool enable_async_msgs;     /* Initially enable async messages? */
169     uint8_t dscp;               /* DSCP Value for controller connection */
170     uint32_t allowed_versions;  /* OpenFlow protocol versions that may
171                                  * be negotiated for a session. */
172 };
173
174 static void ofservice_reconfigure(struct ofservice *,
175                                   const struct ofproto_controller *);
176 static int ofservice_create(struct connmgr *mgr, const char *target,
177                             uint32_t allowed_versions, uint8_t dscp);
178 static void ofservice_destroy(struct connmgr *, struct ofservice *);
179 static struct ofservice *ofservice_lookup(struct connmgr *,
180                                           const char *target);
181
182 /* Connection manager for an OpenFlow switch. */
183 struct connmgr {
184     struct ofproto *ofproto;
185     char *name;
186     char *local_port_name;
187
188     /* OpenFlow connections. */
189     struct hmap controllers;   /* Controller "struct ofconn"s. */
190     struct list all_conns;     /* Contains "struct ofconn"s. */
191     uint64_t master_election_id; /* monotonically increasing sequence number
192                                   * for master election */
193     bool master_election_id_defined;
194
195     /* OpenFlow listeners. */
196     struct hmap services;       /* Contains "struct ofservice"s. */
197     struct pvconn **snoops;
198     size_t n_snoops;
199
200     /* Fail open. */
201     struct fail_open *fail_open;
202     enum ofproto_fail_mode fail_mode;
203
204     /* In-band control. */
205     struct in_band *in_band;
206     struct sockaddr_in *extra_in_band_remotes;
207     size_t n_extra_remotes;
208     int in_band_queue;
209 };
210
211 static void update_in_band_remotes(struct connmgr *);
212 static void add_snooper(struct connmgr *, struct vconn *);
213 static void ofmonitor_run(struct connmgr *);
214 static void ofmonitor_wait(struct connmgr *);
215
216 /* Creates and returns a new connection manager owned by 'ofproto'.  'name' is
217  * a name for the ofproto suitable for using in log messages.
218  * 'local_port_name' is the name of the local port (OFPP_LOCAL) within
219  * 'ofproto'. */
220 struct connmgr *
221 connmgr_create(struct ofproto *ofproto,
222                const char *name, const char *local_port_name)
223 {
224     struct connmgr *mgr;
225
226     mgr = xmalloc(sizeof *mgr);
227     mgr->ofproto = ofproto;
228     mgr->name = xstrdup(name);
229     mgr->local_port_name = xstrdup(local_port_name);
230
231     hmap_init(&mgr->controllers);
232     list_init(&mgr->all_conns);
233     mgr->master_election_id = 0;
234     mgr->master_election_id_defined = false;
235
236     hmap_init(&mgr->services);
237     mgr->snoops = NULL;
238     mgr->n_snoops = 0;
239
240     mgr->fail_open = NULL;
241     mgr->fail_mode = OFPROTO_FAIL_SECURE;
242
243     mgr->in_band = NULL;
244     mgr->extra_in_band_remotes = NULL;
245     mgr->n_extra_remotes = 0;
246     mgr->in_band_queue = -1;
247
248     return mgr;
249 }
250
251 /* Frees 'mgr' and all of its resources. */
252 void
253 connmgr_destroy(struct connmgr *mgr)
254 {
255     struct ofservice *ofservice, *next_ofservice;
256     struct ofconn *ofconn, *next_ofconn;
257     size_t i;
258
259     if (!mgr) {
260         return;
261     }
262
263     ovs_mutex_lock(&ofproto_mutex);
264     LIST_FOR_EACH_SAFE (ofconn, next_ofconn, node, &mgr->all_conns) {
265         ofconn_destroy(ofconn);
266     }
267     ovs_mutex_unlock(&ofproto_mutex);
268
269     hmap_destroy(&mgr->controllers);
270
271     HMAP_FOR_EACH_SAFE (ofservice, next_ofservice, node, &mgr->services) {
272         ofservice_destroy(mgr, ofservice);
273     }
274     hmap_destroy(&mgr->services);
275
276     for (i = 0; i < mgr->n_snoops; i++) {
277         pvconn_close(mgr->snoops[i]);
278     }
279     free(mgr->snoops);
280
281     fail_open_destroy(mgr->fail_open);
282     mgr->fail_open = NULL;
283
284     in_band_destroy(mgr->in_band);
285     mgr->in_band = NULL;
286     free(mgr->extra_in_band_remotes);
287     free(mgr->name);
288     free(mgr->local_port_name);
289
290     free(mgr);
291 }
292
293 /* Does all of the periodic maintenance required by 'mgr'.
294  *
295  * If 'handle_openflow' is nonnull, calls 'handle_openflow' for each message
296  * received on an OpenFlow connection, passing along the OpenFlow connection
297  * itself and the message that was sent.  If 'handle_openflow' returns true,
298  * the message is considered to be fully processed.  If 'handle_openflow'
299  * returns false, the message is considered not to have been processed at all;
300  * it will be stored and re-presented to 'handle_openflow' following the next
301  * call to connmgr_retry().  'handle_openflow' must not modify or free the
302  * message.
303  *
304  * If 'handle_openflow' is NULL, no OpenFlow messages will be processed and
305  * other activities that could affect the flow table (in-band processing,
306  * fail-open processing) are suppressed too. */
307 void
308 connmgr_run(struct connmgr *mgr,
309             bool (*handle_openflow)(struct ofconn *,
310                                     const struct ofpbuf *ofp_msg))
311     OVS_EXCLUDED(ofproto_mutex)
312 {
313     struct ofconn *ofconn, *next_ofconn;
314     struct ofservice *ofservice;
315     size_t i;
316
317     if (handle_openflow && mgr->in_band) {
318         if (!in_band_run(mgr->in_band)) {
319             in_band_destroy(mgr->in_band);
320             mgr->in_band = NULL;
321         }
322     }
323
324     LIST_FOR_EACH_SAFE (ofconn, next_ofconn, node, &mgr->all_conns) {
325         ofconn_run(ofconn, handle_openflow);
326     }
327     ofmonitor_run(mgr);
328
329     /* Fail-open maintenance.  Do this after processing the ofconns since
330      * fail-open checks the status of the controller rconn. */
331     if (handle_openflow && mgr->fail_open) {
332         fail_open_run(mgr->fail_open);
333     }
334
335     HMAP_FOR_EACH (ofservice, node, &mgr->services) {
336         struct vconn *vconn;
337         int retval;
338
339         retval = pvconn_accept(ofservice->pvconn, &vconn);
340         if (!retval) {
341             struct rconn *rconn;
342             char *name;
343
344             /* Passing default value for creation of the rconn */
345             rconn = rconn_create(ofservice->probe_interval, 0, ofservice->dscp,
346                                  vconn_get_allowed_versions(vconn));
347             name = ofconn_make_name(mgr, vconn_get_name(vconn));
348             rconn_connect_unreliably(rconn, vconn, name);
349             free(name);
350
351             ovs_mutex_lock(&ofproto_mutex);
352             ofconn = ofconn_create(mgr, rconn, OFCONN_SERVICE,
353                                    ofservice->enable_async_msgs);
354             ovs_mutex_unlock(&ofproto_mutex);
355
356             ofconn_set_rate_limit(ofconn, ofservice->rate_limit,
357                                   ofservice->burst_limit);
358         } else if (retval != EAGAIN) {
359             VLOG_WARN_RL(&rl, "accept failed (%s)", ovs_strerror(retval));
360         }
361     }
362
363     for (i = 0; i < mgr->n_snoops; i++) {
364         struct vconn *vconn;
365         int retval;
366
367         retval = pvconn_accept(mgr->snoops[i], &vconn);
368         if (!retval) {
369             add_snooper(mgr, vconn);
370         } else if (retval != EAGAIN) {
371             VLOG_WARN_RL(&rl, "accept failed (%s)", ovs_strerror(retval));
372         }
373     }
374 }
375
376 /* Causes the poll loop to wake up when connmgr_run() needs to run.
377  *
378  * If 'handling_openflow' is true, arriving OpenFlow messages and other
379  * activities that affect the flow table will wake up the poll loop.  If
380  * 'handling_openflow' is false, they will not. */
381 void
382 connmgr_wait(struct connmgr *mgr, bool handling_openflow)
383 {
384     struct ofservice *ofservice;
385     struct ofconn *ofconn;
386     size_t i;
387
388     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
389         ofconn_wait(ofconn, handling_openflow);
390     }
391     ofmonitor_wait(mgr);
392     if (handling_openflow && mgr->in_band) {
393         in_band_wait(mgr->in_band);
394     }
395     if (handling_openflow && mgr->fail_open) {
396         fail_open_wait(mgr->fail_open);
397     }
398     HMAP_FOR_EACH (ofservice, node, &mgr->services) {
399         pvconn_wait(ofservice->pvconn);
400     }
401     for (i = 0; i < mgr->n_snoops; i++) {
402         pvconn_wait(mgr->snoops[i]);
403     }
404 }
405
406 /* Adds some memory usage statistics for 'mgr' into 'usage', for use with
407  * memory_report(). */
408 void
409 connmgr_get_memory_usage(const struct connmgr *mgr, struct simap *usage)
410 {
411     const struct ofconn *ofconn;
412     unsigned int packets = 0;
413     unsigned int ofconns = 0;
414
415     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
416         int i;
417
418         ofconns++;
419
420         packets += rconn_count_txqlen(ofconn->rconn);
421         for (i = 0; i < N_SCHEDULERS; i++) {
422             packets += pinsched_count_txqlen(ofconn->schedulers[i]);
423         }
424         packets += pktbuf_count_packets(ofconn->pktbuf);
425     }
426     simap_increase(usage, "ofconns", ofconns);
427     simap_increase(usage, "packets", packets);
428 }
429
430 /* Returns the ofproto that owns 'ofconn''s connmgr. */
431 struct ofproto *
432 ofconn_get_ofproto(const struct ofconn *ofconn)
433 {
434     return ofconn->connmgr->ofproto;
435 }
436
437 /* If processing of OpenFlow messages was blocked on any 'mgr' ofconns by
438  * returning false to the 'handle_openflow' callback to connmgr_run(), this
439  * re-enables them. */
440 void
441 connmgr_retry(struct connmgr *mgr)
442 {
443     struct ofconn *ofconn;
444
445     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
446         ofconn->retry = true;
447     }
448 }
449 \f
450 /* OpenFlow configuration. */
451
452 static void add_controller(struct connmgr *, const char *target, uint8_t dscp,
453                            uint32_t allowed_versions)
454     OVS_REQUIRES(ofproto_mutex);
455 static struct ofconn *find_controller_by_target(struct connmgr *,
456                                                 const char *target);
457 static void update_fail_open(struct connmgr *);
458 static int set_pvconns(struct pvconn ***pvconnsp, size_t *n_pvconnsp,
459                        const struct sset *);
460
461 /* Returns true if 'mgr' has any configured primary controllers.
462  *
463  * Service controllers do not count, but configured primary controllers do
464  * count whether or not they are currently connected. */
465 bool
466 connmgr_has_controllers(const struct connmgr *mgr)
467 {
468     return !hmap_is_empty(&mgr->controllers);
469 }
470
471 /* Initializes 'info' and populates it with information about each configured
472  * primary controller.  The keys in 'info' are the controllers' targets; the
473  * data values are corresponding "struct ofproto_controller_info".
474  *
475  * The caller owns 'info' and everything in it and should free it when it is no
476  * longer needed. */
477 void
478 connmgr_get_controller_info(struct connmgr *mgr, struct shash *info)
479 {
480     const struct ofconn *ofconn;
481
482     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
483         const struct rconn *rconn = ofconn->rconn;
484         const char *target = rconn_get_target(rconn);
485
486         if (!shash_find(info, target)) {
487             struct ofproto_controller_info *cinfo = xmalloc(sizeof *cinfo);
488             time_t now = time_now();
489             time_t last_connection = rconn_get_last_connection(rconn);
490             time_t last_disconnect = rconn_get_last_disconnect(rconn);
491             int last_error = rconn_get_last_error(rconn);
492
493             shash_add(info, target, cinfo);
494
495             cinfo->is_connected = rconn_is_connected(rconn);
496             cinfo->role = ofconn->role;
497
498             cinfo->pairs.n = 0;
499
500             if (last_error) {
501                 cinfo->pairs.keys[cinfo->pairs.n] = "last_error";
502                 cinfo->pairs.values[cinfo->pairs.n++]
503                     = xstrdup(ovs_retval_to_string(last_error));
504             }
505
506             cinfo->pairs.keys[cinfo->pairs.n] = "state";
507             cinfo->pairs.values[cinfo->pairs.n++]
508                 = xstrdup(rconn_get_state(rconn));
509
510             if (last_connection != TIME_MIN) {
511                 cinfo->pairs.keys[cinfo->pairs.n] = "sec_since_connect";
512                 cinfo->pairs.values[cinfo->pairs.n++]
513                     = xasprintf("%ld", (long int) (now - last_connection));
514             }
515
516             if (last_disconnect != TIME_MIN) {
517                 cinfo->pairs.keys[cinfo->pairs.n] = "sec_since_disconnect";
518                 cinfo->pairs.values[cinfo->pairs.n++]
519                     = xasprintf("%ld", (long int) (now - last_disconnect));
520             }
521         }
522     }
523 }
524
525 void
526 connmgr_free_controller_info(struct shash *info)
527 {
528     struct shash_node *node;
529
530     SHASH_FOR_EACH (node, info) {
531         struct ofproto_controller_info *cinfo = node->data;
532         while (cinfo->pairs.n) {
533             free(CONST_CAST(char *, cinfo->pairs.values[--cinfo->pairs.n]));
534         }
535         free(cinfo);
536     }
537     shash_destroy(info);
538 }
539
540 /* Changes 'mgr''s set of controllers to the 'n_controllers' controllers in
541  * 'controllers'. */
542 void
543 connmgr_set_controllers(struct connmgr *mgr,
544                         const struct ofproto_controller *controllers,
545                         size_t n_controllers, uint32_t allowed_versions)
546     OVS_EXCLUDED(ofproto_mutex)
547 {
548     bool had_controllers = connmgr_has_controllers(mgr);
549     struct shash new_controllers;
550     struct ofconn *ofconn, *next_ofconn;
551     struct ofservice *ofservice, *next_ofservice;
552     size_t i;
553
554     /* Required to add and remove ofconns.  This could probably be narrowed to
555      * cover a smaller amount of code, if that yielded some benefit. */
556     ovs_mutex_lock(&ofproto_mutex);
557
558     /* Create newly configured controllers and services.
559      * Create a name to ofproto_controller mapping in 'new_controllers'. */
560     shash_init(&new_controllers);
561     for (i = 0; i < n_controllers; i++) {
562         const struct ofproto_controller *c = &controllers[i];
563
564         if (!vconn_verify_name(c->target)) {
565             bool add = false;
566             ofconn = find_controller_by_target(mgr, c->target);
567             if (!ofconn) {
568                 VLOG_INFO("%s: added primary controller \"%s\"",
569                           mgr->name, c->target);
570                 add = true;
571             } else if (rconn_get_allowed_versions(ofconn->rconn) !=
572                        allowed_versions) {
573                 VLOG_INFO("%s: re-added primary controller \"%s\"",
574                           mgr->name, c->target);
575                 add = true;
576                 ofconn_destroy(ofconn);
577             }
578             if (add) {
579                 add_controller(mgr, c->target, c->dscp, allowed_versions);
580             }
581         } else if (!pvconn_verify_name(c->target)) {
582             bool add = false;
583             ofservice = ofservice_lookup(mgr, c->target);
584             if (!ofservice) {
585                 VLOG_INFO("%s: added service controller \"%s\"",
586                           mgr->name, c->target);
587                 add = true;
588             } else if (ofservice->allowed_versions != allowed_versions) {
589                 VLOG_INFO("%s: re-added service controller \"%s\"",
590                           mgr->name, c->target);
591                 ofservice_destroy(mgr, ofservice);
592                 add = true;
593             }
594             if (add) {
595                 ofservice_create(mgr, c->target, allowed_versions, c->dscp);
596             }
597         } else {
598             VLOG_WARN_RL(&rl, "%s: unsupported controller \"%s\"",
599                          mgr->name, c->target);
600             continue;
601         }
602
603         shash_add_once(&new_controllers, c->target, &controllers[i]);
604     }
605
606     /* Delete controllers that are no longer configured.
607      * Update configuration of all now-existing controllers. */
608     HMAP_FOR_EACH_SAFE (ofconn, next_ofconn, hmap_node, &mgr->controllers) {
609         const char *target = ofconn_get_target(ofconn);
610         struct ofproto_controller *c;
611
612         c = shash_find_data(&new_controllers, target);
613         if (!c) {
614             VLOG_INFO("%s: removed primary controller \"%s\"",
615                       mgr->name, target);
616             ofconn_destroy(ofconn);
617         } else {
618             ofconn_reconfigure(ofconn, c);
619         }
620     }
621
622     /* Delete services that are no longer configured.
623      * Update configuration of all now-existing services. */
624     HMAP_FOR_EACH_SAFE (ofservice, next_ofservice, node, &mgr->services) {
625         const char *target = pvconn_get_name(ofservice->pvconn);
626         struct ofproto_controller *c;
627
628         c = shash_find_data(&new_controllers, target);
629         if (!c) {
630             VLOG_INFO("%s: removed service controller \"%s\"",
631                       mgr->name, target);
632             ofservice_destroy(mgr, ofservice);
633         } else {
634             ofservice_reconfigure(ofservice, c);
635         }
636     }
637
638     shash_destroy(&new_controllers);
639
640     update_in_band_remotes(mgr);
641     update_fail_open(mgr);
642     if (had_controllers != connmgr_has_controllers(mgr)) {
643         ofproto_flush_flows(mgr->ofproto);
644     }
645     ovs_mutex_unlock(&ofproto_mutex);
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         struct sockaddr_in *sin = &addrs[n_addrs];
737         const char *target = rconn_get_target(ofconn->rconn);
738
739         if (ofconn->band == OFPROTO_OUT_OF_BAND) {
740             continue;
741         }
742
743         if (stream_parse_target_with_default_port(target,
744                                                   OFP_OLD_PORT,
745                                                   sin)) {
746             n_addrs++;
747         }
748     }
749     for (i = 0; i < mgr->n_extra_remotes; i++) {
750         addrs[n_addrs++] = mgr->extra_in_band_remotes[i];
751     }
752
753     /* Create or update or destroy in-band. */
754     if (n_addrs) {
755         if (!mgr->in_band) {
756             in_band_create(mgr->ofproto, mgr->local_port_name, &mgr->in_band);
757         }
758         in_band_set_queue(mgr->in_band, mgr->in_band_queue);
759     } else {
760         /* in_band_run() needs a chance to delete any existing in-band flows.
761          * We will destroy mgr->in_band after it's done with that. */
762     }
763     if (mgr->in_band) {
764         in_band_set_remotes(mgr->in_band, addrs, n_addrs);
765     }
766
767     /* Clean up. */
768     free(addrs);
769 }
770
771 static void
772 update_fail_open(struct connmgr *mgr)
773 {
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 /* Changes 'ofconn''s role to 'role'.  If 'role' is OFPCR12_ROLE_MASTER then
916  * any existing master is demoted to a slave. */
917 void
918 ofconn_set_role(struct ofconn *ofconn, enum ofp12_controller_role role)
919 {
920     if (role == OFPCR12_ROLE_MASTER) {
921         struct ofconn *other;
922
923         HMAP_FOR_EACH (other, hmap_node, &ofconn->connmgr->controllers) {
924             if (other->role == OFPCR12_ROLE_MASTER) {
925                 other->role = OFPCR12_ROLE_SLAVE;
926             }
927         }
928     }
929     ofconn->role = role;
930 }
931
932 void
933 ofconn_set_invalid_ttl_to_controller(struct ofconn *ofconn, bool enable)
934 {
935     uint32_t bit = 1u << OFPR_INVALID_TTL;
936     if (enable) {
937         ofconn->master_async_config[OAM_PACKET_IN] |= bit;
938     } else {
939         ofconn->master_async_config[OAM_PACKET_IN] &= ~bit;
940     }
941 }
942
943 bool
944 ofconn_get_invalid_ttl_to_controller(struct ofconn *ofconn)
945 {
946     uint32_t bit = 1u << OFPR_INVALID_TTL;
947     return (ofconn->master_async_config[OAM_PACKET_IN] & bit) != 0;
948 }
949
950 /* Returns the currently configured protocol for 'ofconn', one of OFPUTIL_P_*.
951  *
952  * Returns OFPUTIL_P_NONE, which is not a valid protocol, if 'ofconn' hasn't
953  * completed version negotiation.  This can't happen if at least one OpenFlow
954  * message, other than OFPT_HELLO, has been received on the connection (such as
955  * in ofproto.c's message handling code), since version negotiation is a
956  * prerequisite for starting to receive messages.  This means that
957  * OFPUTIL_P_NONE is a special case that most callers need not worry about. */
958 enum ofputil_protocol
959 ofconn_get_protocol(const struct ofconn *ofconn)
960 {
961     if (ofconn->protocol == OFPUTIL_P_NONE &&
962         rconn_is_connected(ofconn->rconn)) {
963         int version = rconn_get_version(ofconn->rconn);
964         if (version > 0) {
965             ofconn_set_protocol(CONST_CAST(struct ofconn *, ofconn),
966                                 ofputil_protocol_from_ofp_version(version));
967         }
968     }
969
970     return ofconn->protocol;
971 }
972
973 /* Sets the protocol for 'ofconn' to 'protocol' (one of OFPUTIL_P_*).
974  *
975  * (This doesn't actually send anything to accomplish this.  Presumably the
976  * caller already did that.) */
977 void
978 ofconn_set_protocol(struct ofconn *ofconn, enum ofputil_protocol protocol)
979 {
980     ofconn->protocol = protocol;
981 }
982
983 /* Returns the currently configured packet in format for 'ofconn', one of
984  * NXPIF_*.
985  *
986  * The default, if no other format has been set, is NXPIF_OPENFLOW10. */
987 enum nx_packet_in_format
988 ofconn_get_packet_in_format(struct ofconn *ofconn)
989 {
990     return ofconn->packet_in_format;
991 }
992
993 /* Sets the packet in format for 'ofconn' to 'packet_in_format' (one of
994  * NXPIF_*). */
995 void
996 ofconn_set_packet_in_format(struct ofconn *ofconn,
997                             enum nx_packet_in_format packet_in_format)
998 {
999     ofconn->packet_in_format = packet_in_format;
1000 }
1001
1002 /* Sets the controller connection ID for 'ofconn' to 'controller_id'.
1003  *
1004  * The connection controller ID is used for OFPP_CONTROLLER and
1005  * NXAST_CONTROLLER actions.  See "struct nx_action_controller" for details. */
1006 void
1007 ofconn_set_controller_id(struct ofconn *ofconn, uint16_t controller_id)
1008 {
1009     ofconn->controller_id = controller_id;
1010 }
1011
1012 /* Returns the default miss send length for 'ofconn'. */
1013 int
1014 ofconn_get_miss_send_len(const struct ofconn *ofconn)
1015 {
1016     return ofconn->miss_send_len;
1017 }
1018
1019 /* Sets the default miss send length for 'ofconn' to 'miss_send_len'. */
1020 void
1021 ofconn_set_miss_send_len(struct ofconn *ofconn, int miss_send_len)
1022 {
1023     ofconn->miss_send_len = miss_send_len;
1024 }
1025
1026 void
1027 ofconn_set_async_config(struct ofconn *ofconn,
1028                         const uint32_t master_masks[OAM_N_TYPES],
1029                         const uint32_t slave_masks[OAM_N_TYPES])
1030 {
1031     size_t size = sizeof ofconn->master_async_config;
1032     memcpy(ofconn->master_async_config, master_masks, size);
1033     memcpy(ofconn->slave_async_config, slave_masks, size);
1034 }
1035
1036 void
1037 ofconn_get_async_config(struct ofconn *ofconn,
1038                         uint32_t *master_masks, uint32_t *slave_masks)
1039 {
1040     size_t size = sizeof ofconn->master_async_config;
1041     memcpy(master_masks, ofconn->master_async_config, size);
1042     memcpy(slave_masks, ofconn->slave_async_config, size);
1043 }
1044
1045 /* Sends 'msg' on 'ofconn', accounting it as a reply.  (If there is a
1046  * sufficient number of OpenFlow replies in-flight on a single ofconn, then the
1047  * connmgr will stop accepting new OpenFlow requests on that ofconn until the
1048  * controller has accepted some of the replies.) */
1049 void
1050 ofconn_send_reply(const struct ofconn *ofconn, struct ofpbuf *msg)
1051 {
1052     ofconn_send(ofconn, msg, ofconn->reply_counter);
1053 }
1054
1055 /* Sends each of the messages in list 'replies' on 'ofconn' in order,
1056  * accounting them as replies. */
1057 void
1058 ofconn_send_replies(const struct ofconn *ofconn, struct list *replies)
1059 {
1060     struct ofpbuf *reply, *next;
1061
1062     LIST_FOR_EACH_SAFE (reply, next, list_node, replies) {
1063         list_remove(&reply->list_node);
1064         ofconn_send_reply(ofconn, reply);
1065     }
1066 }
1067
1068 /* Sends 'error' on 'ofconn', as a reply to 'request'.  Only at most the
1069  * first 64 bytes of 'request' are used. */
1070 void
1071 ofconn_send_error(const struct ofconn *ofconn,
1072                   const struct ofp_header *request, enum ofperr error)
1073 {
1074     static struct vlog_rate_limit err_rl = VLOG_RATE_LIMIT_INIT(10, 10);
1075     struct ofpbuf *reply;
1076
1077     reply = ofperr_encode_reply(error, request);
1078     if (!VLOG_DROP_INFO(&err_rl)) {
1079         const char *type_name;
1080         size_t request_len;
1081         enum ofpraw raw;
1082
1083         request_len = ntohs(request->length);
1084         type_name = (!ofpraw_decode_partial(&raw, request,
1085                                             MIN(64, request_len))
1086                      ? ofpraw_get_name(raw)
1087                      : "invalid");
1088
1089         VLOG_INFO("%s: sending %s error reply to %s message",
1090                   rconn_get_name(ofconn->rconn), ofperr_to_string(error),
1091                   type_name);
1092     }
1093     ofconn_send_reply(ofconn, reply);
1094 }
1095
1096 /* Same as pktbuf_retrieve(), using the pktbuf owned by 'ofconn'. */
1097 enum ofperr
1098 ofconn_pktbuf_retrieve(struct ofconn *ofconn, uint32_t id,
1099                        struct ofpbuf **bufferp, ofp_port_t *in_port)
1100 {
1101     return pktbuf_retrieve(ofconn->pktbuf, id, bufferp, in_port);
1102 }
1103
1104 /* Returns true if 'ofconn' has any pending opgroups. */
1105 bool
1106 ofconn_has_pending_opgroups(const struct ofconn *ofconn)
1107 {
1108     return !list_is_empty(&ofconn->opgroups);
1109 }
1110
1111 /* Adds 'ofconn_node' to 'ofconn''s list of pending opgroups.
1112  *
1113  * If 'ofconn' is destroyed or its connection drops, then 'ofconn' will remove
1114  * 'ofconn_node' from the list and re-initialize it with list_init().  The
1115  * client may, therefore, use list_is_empty(ofconn_node) to determine whether
1116  * 'ofconn_node' is still associated with an active ofconn.
1117  *
1118  * The client may also remove ofconn_node from the list itself, with
1119  * list_remove(). */
1120 void
1121 ofconn_add_opgroup(struct ofconn *ofconn, struct list *ofconn_node)
1122 {
1123     list_push_back(&ofconn->opgroups, ofconn_node);
1124 }
1125 \f
1126 /* Private ofconn functions. */
1127
1128 static const char *
1129 ofconn_get_target(const struct ofconn *ofconn)
1130 {
1131     return rconn_get_target(ofconn->rconn);
1132 }
1133
1134 static struct ofconn *
1135 ofconn_create(struct connmgr *mgr, struct rconn *rconn, enum ofconn_type type,
1136               bool enable_async_msgs)
1137 {
1138     struct ofconn *ofconn;
1139
1140     ofconn = xzalloc(sizeof *ofconn);
1141     ofconn->connmgr = mgr;
1142     list_push_back(&mgr->all_conns, &ofconn->node);
1143     ofconn->rconn = rconn;
1144     ofconn->type = type;
1145     ofconn->enable_async_msgs = enable_async_msgs;
1146
1147     list_init(&ofconn->opgroups);
1148
1149     hmap_init(&ofconn->monitors);
1150     list_init(&ofconn->updates);
1151
1152     ofconn_flush(ofconn);
1153
1154     return ofconn;
1155 }
1156
1157 /* Clears all of the state in 'ofconn' that should not persist from one
1158  * connection to the next. */
1159 static void
1160 ofconn_flush(struct ofconn *ofconn)
1161     OVS_REQUIRES(ofproto_mutex)
1162 {
1163     struct ofmonitor *monitor, *next_monitor;
1164     int i;
1165
1166     ofconn->role = OFPCR12_ROLE_EQUAL;
1167     ofconn_set_protocol(ofconn, OFPUTIL_P_NONE);
1168     ofconn->packet_in_format = NXPIF_OPENFLOW10;
1169
1170     /* Disassociate 'ofconn' from all of the ofopgroups that it initiated that
1171      * have not yet completed.  (Those ofopgroups will still run to completion
1172      * in the usual way, but any errors that they run into will not be reported
1173      * on any OpenFlow channel.)
1174      *
1175      * Also discard any blocked operation on 'ofconn'. */
1176     while (!list_is_empty(&ofconn->opgroups)) {
1177         list_init(list_pop_front(&ofconn->opgroups));
1178     }
1179     ofpbuf_delete(ofconn->blocked);
1180     ofconn->blocked = NULL;
1181
1182     rconn_packet_counter_destroy(ofconn->packet_in_counter);
1183     ofconn->packet_in_counter = rconn_packet_counter_create();
1184     for (i = 0; i < N_SCHEDULERS; i++) {
1185         if (ofconn->schedulers[i]) {
1186             int rate, burst;
1187
1188             pinsched_get_limits(ofconn->schedulers[i], &rate, &burst);
1189             pinsched_destroy(ofconn->schedulers[i]);
1190             ofconn->schedulers[i] = pinsched_create(rate, burst);
1191         }
1192     }
1193     if (ofconn->pktbuf) {
1194         pktbuf_destroy(ofconn->pktbuf);
1195         ofconn->pktbuf = pktbuf_create();
1196     }
1197     ofconn->miss_send_len = (ofconn->type == OFCONN_PRIMARY
1198                              ? OFP_DEFAULT_MISS_SEND_LEN
1199                              : 0);
1200     ofconn->controller_id = 0;
1201
1202     rconn_packet_counter_destroy(ofconn->reply_counter);
1203     ofconn->reply_counter = rconn_packet_counter_create();
1204
1205     if (ofconn->enable_async_msgs) {
1206         uint32_t *master = ofconn->master_async_config;
1207         uint32_t *slave = ofconn->slave_async_config;
1208
1209         /* "master" and "other" roles get all asynchronous messages by default,
1210          * except that the controller needs to enable nonstandard "packet-in"
1211          * reasons itself. */
1212         master[OAM_PACKET_IN] = (1u << OFPR_NO_MATCH) | (1u << OFPR_ACTION);
1213         master[OAM_PORT_STATUS] = ((1u << OFPPR_ADD)
1214                                    | (1u << OFPPR_DELETE)
1215                                    | (1u << OFPPR_MODIFY));
1216         master[OAM_FLOW_REMOVED] = ((1u << OFPRR_IDLE_TIMEOUT)
1217                                     | (1u << OFPRR_HARD_TIMEOUT)
1218                                     | (1u << OFPRR_DELETE));
1219
1220         /* "slave" role gets port status updates by default. */
1221         slave[OAM_PACKET_IN] = 0;
1222         slave[OAM_PORT_STATUS] = ((1u << OFPPR_ADD)
1223                                   | (1u << OFPPR_DELETE)
1224                                   | (1u << OFPPR_MODIFY));
1225         slave[OAM_FLOW_REMOVED] = 0;
1226     } else {
1227         memset(ofconn->master_async_config, 0,
1228                sizeof ofconn->master_async_config);
1229         memset(ofconn->slave_async_config, 0,
1230                sizeof ofconn->slave_async_config);
1231     }
1232
1233     HMAP_FOR_EACH_SAFE (monitor, next_monitor, ofconn_node,
1234                         &ofconn->monitors) {
1235         ofmonitor_destroy(monitor);
1236     }
1237     rconn_packet_counter_destroy(ofconn->monitor_counter);
1238     ofconn->monitor_counter = rconn_packet_counter_create();
1239     ofpbuf_list_delete(&ofconn->updates); /* ...but it should be empty. */
1240 }
1241
1242 static void
1243 ofconn_destroy(struct ofconn *ofconn)
1244     OVS_REQUIRES(ofproto_mutex)
1245 {
1246     ofconn_flush(ofconn);
1247
1248     if (ofconn->type == OFCONN_PRIMARY) {
1249         hmap_remove(&ofconn->connmgr->controllers, &ofconn->hmap_node);
1250     }
1251
1252     hmap_destroy(&ofconn->monitors);
1253     list_remove(&ofconn->node);
1254     rconn_destroy(ofconn->rconn);
1255     rconn_packet_counter_destroy(ofconn->packet_in_counter);
1256     rconn_packet_counter_destroy(ofconn->reply_counter);
1257     pktbuf_destroy(ofconn->pktbuf);
1258     rconn_packet_counter_destroy(ofconn->monitor_counter);
1259     free(ofconn);
1260 }
1261
1262 /* Reconfigures 'ofconn' to match 'c'.  'ofconn' and 'c' must have the same
1263  * target. */
1264 static void
1265 ofconn_reconfigure(struct ofconn *ofconn, const struct ofproto_controller *c)
1266 {
1267     int probe_interval;
1268
1269     ofconn->band = c->band;
1270     ofconn->enable_async_msgs = c->enable_async_msgs;
1271
1272     rconn_set_max_backoff(ofconn->rconn, c->max_backoff);
1273
1274     probe_interval = c->probe_interval ? MAX(c->probe_interval, 5) : 0;
1275     rconn_set_probe_interval(ofconn->rconn, probe_interval);
1276
1277     ofconn_set_rate_limit(ofconn, c->rate_limit, c->burst_limit);
1278
1279     /* If dscp value changed reconnect. */
1280     if (c->dscp != rconn_get_dscp(ofconn->rconn)) {
1281         rconn_set_dscp(ofconn->rconn, c->dscp);
1282         rconn_reconnect(ofconn->rconn);
1283     }
1284 }
1285
1286 /* Returns true if it makes sense for 'ofconn' to receive and process OpenFlow
1287  * messages. */
1288 static bool
1289 ofconn_may_recv(const struct ofconn *ofconn)
1290 {
1291     int count = rconn_packet_counter_n_packets(ofconn->reply_counter);
1292     return (!ofconn->blocked || ofconn->retry) && count < OFCONN_REPLY_MAX;
1293 }
1294
1295 static void
1296 ofconn_run(struct ofconn *ofconn,
1297            bool (*handle_openflow)(struct ofconn *,
1298                                    const struct ofpbuf *ofp_msg))
1299 {
1300     struct connmgr *mgr = ofconn->connmgr;
1301     size_t i;
1302
1303     for (i = 0; i < N_SCHEDULERS; i++) {
1304         pinsched_run(ofconn->schedulers[i], do_send_packet_in, ofconn);
1305     }
1306
1307     rconn_run(ofconn->rconn);
1308
1309     if (handle_openflow) {
1310         /* Limit the number of iterations to avoid starving other tasks. */
1311         for (i = 0; i < 50 && ofconn_may_recv(ofconn); i++) {
1312             struct ofpbuf *of_msg;
1313
1314             of_msg = (ofconn->blocked
1315                       ? ofconn->blocked
1316                       : rconn_recv(ofconn->rconn));
1317             if (!of_msg) {
1318                 break;
1319             }
1320             if (mgr->fail_open) {
1321                 fail_open_maybe_recover(mgr->fail_open);
1322             }
1323
1324             if (handle_openflow(ofconn, of_msg)) {
1325                 ofpbuf_delete(of_msg);
1326                 ofconn->blocked = NULL;
1327             } else {
1328                 ofconn->blocked = of_msg;
1329                 ofconn->retry = false;
1330             }
1331         }
1332     }
1333
1334     ovs_mutex_lock(&ofproto_mutex);
1335     if (!rconn_is_alive(ofconn->rconn)) {
1336         ofconn_destroy(ofconn);
1337     } else if (!rconn_is_connected(ofconn->rconn)) {
1338         ofconn_flush(ofconn);
1339     }
1340     ovs_mutex_unlock(&ofproto_mutex);
1341 }
1342
1343 static void
1344 ofconn_wait(struct ofconn *ofconn, bool handling_openflow)
1345 {
1346     int i;
1347
1348     for (i = 0; i < N_SCHEDULERS; i++) {
1349         pinsched_wait(ofconn->schedulers[i]);
1350     }
1351     rconn_run_wait(ofconn->rconn);
1352     if (handling_openflow && ofconn_may_recv(ofconn)) {
1353         rconn_recv_wait(ofconn->rconn);
1354     }
1355 }
1356
1357 /* Returns true if 'ofconn' should receive asynchronous messages of the given
1358  * OAM_* 'type' and 'reason', which should be a OFPR_* value for OAM_PACKET_IN,
1359  * a OFPPR_* value for OAM_PORT_STATUS, or an OFPRR_* value for
1360  * OAM_FLOW_REMOVED.  Returns false if the message should not be sent on
1361  * 'ofconn'. */
1362 static bool
1363 ofconn_receives_async_msg(const struct ofconn *ofconn,
1364                           enum ofconn_async_msg_type type,
1365                           unsigned int reason)
1366 {
1367     const uint32_t *async_config;
1368
1369     ovs_assert(reason < 32);
1370     ovs_assert((unsigned int) type < OAM_N_TYPES);
1371
1372     if (ofconn_get_protocol(ofconn) == OFPUTIL_P_NONE
1373         || !rconn_is_connected(ofconn->rconn)) {
1374         return false;
1375     }
1376
1377     /* Keep the following code in sync with the documentation in the
1378      * "Asynchronous Messages" section in DESIGN. */
1379
1380     if (ofconn->type == OFCONN_SERVICE && !ofconn->miss_send_len) {
1381         /* Service connections don't get asynchronous messages unless they have
1382          * explicitly asked for them by setting a nonzero miss send length. */
1383         return false;
1384     }
1385
1386     async_config = (ofconn->role == OFPCR12_ROLE_SLAVE
1387                     ? ofconn->slave_async_config
1388                     : ofconn->master_async_config);
1389     if (!(async_config[type] & (1u << reason))) {
1390         return false;
1391     }
1392
1393     return true;
1394 }
1395
1396 /* Returns a human-readable name for an OpenFlow connection between 'mgr' and
1397  * 'target', suitable for use in log messages for identifying the connection.
1398  *
1399  * The name is dynamically allocated.  The caller should free it (with free())
1400  * when it is no longer needed. */
1401 static char *
1402 ofconn_make_name(const struct connmgr *mgr, const char *target)
1403 {
1404     return xasprintf("%s<->%s", mgr->name, target);
1405 }
1406
1407 static void
1408 ofconn_set_rate_limit(struct ofconn *ofconn, int rate, int burst)
1409 {
1410     int i;
1411
1412     for (i = 0; i < N_SCHEDULERS; i++) {
1413         struct pinsched **s = &ofconn->schedulers[i];
1414
1415         if (rate > 0) {
1416             if (!*s) {
1417                 *s = pinsched_create(rate, burst);
1418             } else {
1419                 pinsched_set_limits(*s, rate, burst);
1420             }
1421         } else {
1422             pinsched_destroy(*s);
1423             *s = NULL;
1424         }
1425     }
1426 }
1427
1428 static void
1429 ofconn_send(const struct ofconn *ofconn, struct ofpbuf *msg,
1430             struct rconn_packet_counter *counter)
1431 {
1432     ofpmsg_update_length(msg);
1433     rconn_send(ofconn->rconn, msg, counter);
1434 }
1435 \f
1436 /* Sending asynchronous messages. */
1437
1438 static void schedule_packet_in(struct ofconn *, struct ofproto_packet_in);
1439
1440 /* Sends an OFPT_PORT_STATUS message with 'opp' and 'reason' to appropriate
1441  * controllers managed by 'mgr'. */
1442 void
1443 connmgr_send_port_status(struct connmgr *mgr,
1444                          const struct ofputil_phy_port *pp, uint8_t reason)
1445 {
1446     /* XXX Should limit the number of queued port status change messages. */
1447     struct ofputil_port_status ps;
1448     struct ofconn *ofconn;
1449
1450     ps.reason = reason;
1451     ps.desc = *pp;
1452     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
1453         if (ofconn_receives_async_msg(ofconn, OAM_PORT_STATUS, reason)) {
1454             struct ofpbuf *msg;
1455
1456             msg = ofputil_encode_port_status(&ps, ofconn_get_protocol(ofconn));
1457             ofconn_send(ofconn, msg, NULL);
1458         }
1459     }
1460 }
1461
1462 /* Sends an OFPT_FLOW_REMOVED or NXT_FLOW_REMOVED message based on 'fr' to
1463  * appropriate controllers managed by 'mgr'. */
1464 void
1465 connmgr_send_flow_removed(struct connmgr *mgr,
1466                           const struct ofputil_flow_removed *fr)
1467 {
1468     struct ofconn *ofconn;
1469
1470     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
1471         if (ofconn_receives_async_msg(ofconn, OAM_FLOW_REMOVED, fr->reason)) {
1472             struct ofpbuf *msg;
1473
1474             /* Account flow expirations as replies to OpenFlow requests.  That
1475              * works because preventing OpenFlow requests from being processed
1476              * also prevents new flows from being added (and expiring).  (It
1477              * also prevents processing OpenFlow requests that would not add
1478              * new flows, so it is imperfect.) */
1479             msg = ofputil_encode_flow_removed(fr, ofconn_get_protocol(ofconn));
1480             ofconn_send_reply(ofconn, msg);
1481         }
1482     }
1483 }
1484
1485 /* Given 'pin', sends an OFPT_PACKET_IN message to each OpenFlow controller as
1486  * necessary according to their individual configurations.
1487  *
1488  * The caller doesn't need to fill in pin->buffer_id or pin->total_len. */
1489 void
1490 connmgr_send_packet_in(struct connmgr *mgr,
1491                        const struct ofproto_packet_in *pin)
1492 {
1493     struct ofconn *ofconn;
1494
1495     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
1496         if (ofconn_receives_async_msg(ofconn, OAM_PACKET_IN, pin->up.reason)
1497             && ofconn->controller_id == pin->controller_id) {
1498             schedule_packet_in(ofconn, *pin);
1499         }
1500     }
1501 }
1502
1503 /* pinsched callback for sending 'ofp_packet_in' on 'ofconn'. */
1504 static void
1505 do_send_packet_in(struct ofpbuf *ofp_packet_in, void *ofconn_)
1506 {
1507     struct ofconn *ofconn = ofconn_;
1508
1509     rconn_send_with_limit(ofconn->rconn, ofp_packet_in,
1510                           ofconn->packet_in_counter, 100);
1511 }
1512
1513 /* Takes 'pin', composes an OpenFlow packet-in message from it, and passes it
1514  * to 'ofconn''s packet scheduler for sending. */
1515 static void
1516 schedule_packet_in(struct ofconn *ofconn, struct ofproto_packet_in pin)
1517 {
1518     struct connmgr *mgr = ofconn->connmgr;
1519     uint16_t controller_max_len;
1520
1521     pin.up.total_len = pin.up.packet_len;
1522
1523     if (pin.up.reason == OFPR_ACTION) {
1524         controller_max_len = pin.up.send_len;  /* max_len */
1525     } else {
1526         controller_max_len = ofconn->miss_send_len;
1527     }
1528
1529     /* Get OpenFlow buffer_id.
1530      * For OpenFlow 1.2+, OFPCML_NO_BUFFER (== UINT16_MAX) specifies
1531      * unbuffered.  This behaviour doesn't violate prior versions, too. */
1532     if (controller_max_len == UINT16_MAX) {
1533         pin.up.buffer_id = UINT32_MAX;
1534     } else if (mgr->fail_open && fail_open_is_active(mgr->fail_open)) {
1535         pin.up.buffer_id = pktbuf_get_null();
1536     } else if (!ofconn->pktbuf) {
1537         pin.up.buffer_id = UINT32_MAX;
1538     } else {
1539         pin.up.buffer_id = pktbuf_save(ofconn->pktbuf,
1540                                        pin.up.packet, pin.up.packet_len,
1541                                        pin.up.fmd.in_port);
1542     }
1543
1544     /* Figure out how much of the packet to send.
1545      * If not buffered, send the entire packet.  Otherwise, depending on
1546      * the reason of packet-in, send what requested by the controller. */
1547     if (pin.up.buffer_id == UINT32_MAX) {
1548         pin.up.send_len = pin.up.packet_len;
1549     } else {
1550         pin.up.send_len = MIN(pin.up.packet_len, controller_max_len);
1551     }
1552
1553     /* Make OFPT_PACKET_IN and hand over to packet scheduler.  It might
1554      * immediately call into do_send_packet_in() or it might buffer it for a
1555      * while (until a later call to pinsched_run()). */
1556     pinsched_send(ofconn->schedulers[pin.up.reason == OFPR_NO_MATCH ? 0 : 1],
1557                   pin.up.fmd.in_port,
1558                   ofputil_encode_packet_in(&pin.up,
1559                                            ofconn_get_protocol(ofconn),
1560                                            ofconn->packet_in_format),
1561                   do_send_packet_in, ofconn);
1562 }
1563 \f
1564 /* Fail-open settings. */
1565
1566 /* Returns the failure handling mode (OFPROTO_FAIL_SECURE or
1567  * OFPROTO_FAIL_STANDALONE) for 'mgr'. */
1568 enum ofproto_fail_mode
1569 connmgr_get_fail_mode(const struct connmgr *mgr)
1570 {
1571     return mgr->fail_mode;
1572 }
1573
1574 /* Sets the failure handling mode for 'mgr' to 'fail_mode' (either
1575  * OFPROTO_FAIL_SECURE or OFPROTO_FAIL_STANDALONE). */
1576 void
1577 connmgr_set_fail_mode(struct connmgr *mgr, enum ofproto_fail_mode fail_mode)
1578 {
1579     if (mgr->fail_mode != fail_mode) {
1580         mgr->fail_mode = fail_mode;
1581         update_fail_open(mgr);
1582         if (!connmgr_has_controllers(mgr)) {
1583             ofproto_flush_flows(mgr->ofproto);
1584         }
1585     }
1586 }
1587 \f
1588 /* Fail-open implementation. */
1589
1590 /* Returns the longest probe interval among the primary controllers configured
1591  * on 'mgr'.  Returns 0 if there are no primary controllers. */
1592 int
1593 connmgr_get_max_probe_interval(const struct connmgr *mgr)
1594 {
1595     const struct ofconn *ofconn;
1596     int max_probe_interval;
1597
1598     max_probe_interval = 0;
1599     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
1600         int probe_interval = rconn_get_probe_interval(ofconn->rconn);
1601         max_probe_interval = MAX(max_probe_interval, probe_interval);
1602     }
1603     return max_probe_interval;
1604 }
1605
1606 /* Returns the number of seconds for which all of 'mgr's primary controllers
1607  * have been disconnected.  Returns 0 if 'mgr' has no primary controllers. */
1608 int
1609 connmgr_failure_duration(const struct connmgr *mgr)
1610 {
1611     const struct ofconn *ofconn;
1612     int min_failure_duration;
1613
1614     if (!connmgr_has_controllers(mgr)) {
1615         return 0;
1616     }
1617
1618     min_failure_duration = INT_MAX;
1619     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
1620         int failure_duration = rconn_failure_duration(ofconn->rconn);
1621         min_failure_duration = MIN(min_failure_duration, failure_duration);
1622     }
1623     return min_failure_duration;
1624 }
1625
1626 /* Returns true if at least one primary controller is connected (regardless of
1627  * whether those controllers are believed to have authenticated and accepted
1628  * this switch), false if none of them are connected. */
1629 bool
1630 connmgr_is_any_controller_connected(const struct connmgr *mgr)
1631 {
1632     const struct ofconn *ofconn;
1633
1634     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
1635         if (rconn_is_connected(ofconn->rconn)) {
1636             return true;
1637         }
1638     }
1639     return false;
1640 }
1641
1642 /* Returns true if at least one primary controller is believed to have
1643  * authenticated and accepted this switch, false otherwise. */
1644 bool
1645 connmgr_is_any_controller_admitted(const struct connmgr *mgr)
1646 {
1647     const struct ofconn *ofconn;
1648
1649     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
1650         if (rconn_is_admitted(ofconn->rconn)) {
1651             return true;
1652         }
1653     }
1654     return false;
1655 }
1656 \f
1657 /* In-band configuration. */
1658
1659 static bool any_extras_changed(const struct connmgr *,
1660                                const struct sockaddr_in *extras, size_t n);
1661
1662 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'mgr''s
1663  * in-band control should guarantee access, in the same way that in-band
1664  * control guarantees access to OpenFlow controllers. */
1665 void
1666 connmgr_set_extra_in_band_remotes(struct connmgr *mgr,
1667                                   const struct sockaddr_in *extras, size_t n)
1668 {
1669     if (!any_extras_changed(mgr, extras, n)) {
1670         return;
1671     }
1672
1673     free(mgr->extra_in_band_remotes);
1674     mgr->n_extra_remotes = n;
1675     mgr->extra_in_band_remotes = xmemdup(extras, n * sizeof *extras);
1676
1677     update_in_band_remotes(mgr);
1678 }
1679
1680 /* Sets the OpenFlow queue used by flows set up by in-band control on
1681  * 'mgr' to 'queue_id'.  If 'queue_id' is negative, then in-band control
1682  * flows will use the default queue. */
1683 void
1684 connmgr_set_in_band_queue(struct connmgr *mgr, int queue_id)
1685 {
1686     if (queue_id != mgr->in_band_queue) {
1687         mgr->in_band_queue = queue_id;
1688         update_in_band_remotes(mgr);
1689     }
1690 }
1691
1692 static bool
1693 any_extras_changed(const struct connmgr *mgr,
1694                    const struct sockaddr_in *extras, size_t n)
1695 {
1696     size_t i;
1697
1698     if (n != mgr->n_extra_remotes) {
1699         return true;
1700     }
1701
1702     for (i = 0; i < n; i++) {
1703         const struct sockaddr_in *old = &mgr->extra_in_band_remotes[i];
1704         const struct sockaddr_in *new = &extras[i];
1705
1706         if (old->sin_addr.s_addr != new->sin_addr.s_addr ||
1707             old->sin_port != new->sin_port) {
1708             return true;
1709         }
1710     }
1711
1712     return false;
1713 }
1714 \f
1715 /* In-band implementation. */
1716
1717 bool
1718 connmgr_has_in_band(struct connmgr *mgr)
1719 {
1720     return mgr->in_band != NULL;
1721 }
1722 \f
1723 /* Fail-open and in-band implementation. */
1724
1725 /* Called by 'ofproto' after all flows have been flushed, to allow fail-open
1726  * and standalone mode to re-create their flows.
1727  *
1728  * In-band control has more sophisticated code that manages flows itself. */
1729 void
1730 connmgr_flushed(struct connmgr *mgr)
1731     OVS_EXCLUDED(ofproto_mutex)
1732 {
1733     if (mgr->fail_open) {
1734         fail_open_flushed(mgr->fail_open);
1735     }
1736
1737     /* If there are no controllers and we're in standalone mode, set up a flow
1738      * that matches every packet and directs them to OFPP_NORMAL (which goes to
1739      * us).  Otherwise, the switch is in secure mode and we won't pass any
1740      * traffic until a controller has been defined and it tells us to do so. */
1741     if (!connmgr_has_controllers(mgr)
1742         && mgr->fail_mode == OFPROTO_FAIL_STANDALONE) {
1743         struct ofpbuf ofpacts;
1744         struct match match;
1745
1746         ofpbuf_init(&ofpacts, OFPACT_OUTPUT_SIZE);
1747         ofpact_put_OUTPUT(&ofpacts)->port = OFPP_NORMAL;
1748         ofpact_pad(&ofpacts);
1749
1750         match_init_catchall(&match);
1751         ofproto_add_flow(mgr->ofproto, &match, 0, ofpacts.data, ofpacts.size);
1752
1753         ofpbuf_uninit(&ofpacts);
1754     }
1755 }
1756 \f
1757 /* Creates a new ofservice for 'target' in 'mgr'.  Returns 0 if successful,
1758  * otherwise a positive errno value.
1759  *
1760  * ofservice_reconfigure() must be called to fully configure the new
1761  * ofservice. */
1762 static int
1763 ofservice_create(struct connmgr *mgr, const char *target,
1764                  uint32_t allowed_versions, uint8_t dscp)
1765 {
1766     struct ofservice *ofservice;
1767     struct pvconn *pvconn;
1768     int error;
1769
1770     error = pvconn_open(target, allowed_versions, dscp, &pvconn);
1771     if (error) {
1772         return error;
1773     }
1774
1775     ofservice = xzalloc(sizeof *ofservice);
1776     hmap_insert(&mgr->services, &ofservice->node, hash_string(target, 0));
1777     ofservice->pvconn = pvconn;
1778     ofservice->allowed_versions = allowed_versions;
1779
1780     return 0;
1781 }
1782
1783 static void
1784 ofservice_destroy(struct connmgr *mgr, struct ofservice *ofservice)
1785 {
1786     hmap_remove(&mgr->services, &ofservice->node);
1787     pvconn_close(ofservice->pvconn);
1788     free(ofservice);
1789 }
1790
1791 static void
1792 ofservice_reconfigure(struct ofservice *ofservice,
1793                       const struct ofproto_controller *c)
1794 {
1795     ofservice->probe_interval = c->probe_interval;
1796     ofservice->rate_limit = c->rate_limit;
1797     ofservice->burst_limit = c->burst_limit;
1798     ofservice->enable_async_msgs = c->enable_async_msgs;
1799     ofservice->dscp = c->dscp;
1800 }
1801
1802 /* Finds and returns the ofservice within 'mgr' that has the given
1803  * 'target', or a null pointer if none exists. */
1804 static struct ofservice *
1805 ofservice_lookup(struct connmgr *mgr, const char *target)
1806 {
1807     struct ofservice *ofservice;
1808
1809     HMAP_FOR_EACH_WITH_HASH (ofservice, node, hash_string(target, 0),
1810                              &mgr->services) {
1811         if (!strcmp(pvconn_get_name(ofservice->pvconn), target)) {
1812             return ofservice;
1813         }
1814     }
1815     return NULL;
1816 }
1817 \f
1818 /* Flow monitors (NXST_FLOW_MONITOR). */
1819
1820 /* A counter incremented when something significant happens to an OpenFlow
1821  * rule.
1822  *
1823  *     - When a rule is added, its 'add_seqno' and 'modify_seqno' are set to
1824  *       the current value (which is then incremented).
1825  *
1826  *     - When a rule is modified, its 'modify_seqno' is set to the current
1827  *       value (which is then incremented).
1828  *
1829  * Thus, by comparing an old value of monitor_seqno against a rule's
1830  * 'add_seqno', one can tell whether the rule was added before or after the old
1831  * value was read, and similarly for 'modify_seqno'.
1832  *
1833  * 32 bits should normally be sufficient (and would be nice, to save space in
1834  * each rule) but then we'd have to have some special cases for wraparound.
1835  *
1836  * We initialize monitor_seqno to 1 to allow 0 to be used as an invalid
1837  * value. */
1838 static uint64_t monitor_seqno = 1;
1839
1840 COVERAGE_DEFINE(ofmonitor_pause);
1841 COVERAGE_DEFINE(ofmonitor_resume);
1842
1843 enum ofperr
1844 ofmonitor_create(const struct ofputil_flow_monitor_request *request,
1845                  struct ofconn *ofconn, struct ofmonitor **monitorp)
1846     OVS_REQUIRES(ofproto_mutex)
1847 {
1848     struct ofmonitor *m;
1849
1850     *monitorp = NULL;
1851
1852     m = ofmonitor_lookup(ofconn, request->id);
1853     if (m) {
1854         return OFPERR_NXBRC_FM_DUPLICATE_ID;
1855     }
1856
1857     m = xmalloc(sizeof *m);
1858     m->ofconn = ofconn;
1859     hmap_insert(&ofconn->monitors, &m->ofconn_node, hash_int(request->id, 0));
1860     m->id = request->id;
1861     m->flags = request->flags;
1862     m->out_port = request->out_port;
1863     m->table_id = request->table_id;
1864     minimatch_init(&m->match, &request->match);
1865
1866     *monitorp = m;
1867     return 0;
1868 }
1869
1870 struct ofmonitor *
1871 ofmonitor_lookup(struct ofconn *ofconn, uint32_t id)
1872     OVS_REQUIRES(ofproto_mutex)
1873 {
1874     struct ofmonitor *m;
1875
1876     HMAP_FOR_EACH_IN_BUCKET (m, ofconn_node, hash_int(id, 0),
1877                              &ofconn->monitors) {
1878         if (m->id == id) {
1879             return m;
1880         }
1881     }
1882     return NULL;
1883 }
1884
1885 void
1886 ofmonitor_destroy(struct ofmonitor *m)
1887     OVS_REQUIRES(ofproto_mutex)
1888 {
1889     if (m) {
1890         minimatch_destroy(&m->match);
1891         hmap_remove(&m->ofconn->monitors, &m->ofconn_node);
1892         free(m);
1893     }
1894 }
1895
1896 void
1897 ofmonitor_report(struct connmgr *mgr, struct rule *rule,
1898                  enum nx_flow_update_event event,
1899                  enum ofp_flow_removed_reason reason,
1900                  const struct ofconn *abbrev_ofconn, ovs_be32 abbrev_xid)
1901     OVS_REQUIRES(ofproto_mutex)
1902 {
1903     enum nx_flow_monitor_flags update;
1904     struct ofconn *ofconn;
1905
1906     switch (event) {
1907     case NXFME_ADDED:
1908         update = NXFMF_ADD;
1909         rule->add_seqno = rule->modify_seqno = monitor_seqno++;
1910         break;
1911
1912     case NXFME_DELETED:
1913         update = NXFMF_DELETE;
1914         break;
1915
1916     case NXFME_MODIFIED:
1917         update = NXFMF_MODIFY;
1918         rule->modify_seqno = monitor_seqno++;
1919         break;
1920
1921     default:
1922     case NXFME_ABBREV:
1923         NOT_REACHED();
1924     }
1925
1926     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
1927         enum nx_flow_monitor_flags flags = 0;
1928         struct ofmonitor *m;
1929
1930         if (ofconn->monitor_paused) {
1931             /* Only send NXFME_DELETED notifications for flows that were added
1932              * before we paused. */
1933             if (event != NXFME_DELETED
1934                 || rule->add_seqno > ofconn->monitor_paused) {
1935                 continue;
1936             }
1937         }
1938
1939         HMAP_FOR_EACH (m, ofconn_node, &ofconn->monitors) {
1940             if (m->flags & update
1941                 && (m->table_id == 0xff || m->table_id == rule->table_id)
1942                 && ofoperation_has_out_port(rule->pending, m->out_port)
1943                 && cls_rule_is_loose_match(&rule->cr, &m->match)) {
1944                 flags |= m->flags;
1945             }
1946         }
1947
1948         if (flags) {
1949             if (list_is_empty(&ofconn->updates)) {
1950                 ofputil_start_flow_update(&ofconn->updates);
1951                 ofconn->sent_abbrev_update = false;
1952             }
1953
1954             if (ofconn != abbrev_ofconn || ofconn->monitor_paused) {
1955                 struct ofputil_flow_update fu;
1956                 struct match match;
1957
1958                 fu.event = event;
1959                 fu.reason = event == NXFME_DELETED ? reason : 0;
1960                 fu.table_id = rule->table_id;
1961                 fu.cookie = rule->flow_cookie;
1962                 minimatch_expand(&rule->cr.match, &match);
1963                 fu.match = &match;
1964                 fu.priority = rule->cr.priority;
1965
1966                 ovs_mutex_lock(&rule->mutex);
1967                 fu.idle_timeout = rule->idle_timeout;
1968                 fu.hard_timeout = rule->hard_timeout;
1969                 ovs_mutex_unlock(&rule->mutex);
1970
1971                 if (flags & NXFMF_ACTIONS) {
1972                     fu.ofpacts = rule->actions->ofpacts;
1973                     fu.ofpacts_len = rule->actions->ofpacts_len;
1974                 } else {
1975                     fu.ofpacts = NULL;
1976                     fu.ofpacts_len = 0;
1977                 }
1978                 ofputil_append_flow_update(&fu, &ofconn->updates);
1979             } else if (!ofconn->sent_abbrev_update) {
1980                 struct ofputil_flow_update fu;
1981
1982                 fu.event = NXFME_ABBREV;
1983                 fu.xid = abbrev_xid;
1984                 ofputil_append_flow_update(&fu, &ofconn->updates);
1985
1986                 ofconn->sent_abbrev_update = true;
1987             }
1988         }
1989     }
1990 }
1991
1992 void
1993 ofmonitor_flush(struct connmgr *mgr)
1994     OVS_REQUIRES(ofproto_mutex)
1995 {
1996     struct ofconn *ofconn;
1997
1998     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
1999         struct ofpbuf *msg, *next;
2000
2001         LIST_FOR_EACH_SAFE (msg, next, list_node, &ofconn->updates) {
2002             unsigned int n_bytes;
2003
2004             list_remove(&msg->list_node);
2005             ofconn_send(ofconn, msg, ofconn->monitor_counter);
2006             n_bytes = rconn_packet_counter_n_bytes(ofconn->monitor_counter);
2007             if (!ofconn->monitor_paused && n_bytes > 128 * 1024) {
2008                 struct ofpbuf *pause;
2009
2010                 COVERAGE_INC(ofmonitor_pause);
2011                 ofconn->monitor_paused = monitor_seqno++;
2012                 pause = ofpraw_alloc_xid(OFPRAW_NXT_FLOW_MONITOR_PAUSED,
2013                                          OFP10_VERSION, htonl(0), 0);
2014                 ofconn_send(ofconn, pause, ofconn->monitor_counter);
2015             }
2016         }
2017     }
2018 }
2019
2020 static void
2021 ofmonitor_resume(struct ofconn *ofconn)
2022     OVS_REQUIRES(ofproto_mutex)
2023 {
2024     struct rule_collection rules;
2025     struct ofpbuf *resumed;
2026     struct ofmonitor *m;
2027     struct list msgs;
2028
2029     rule_collection_init(&rules);
2030     HMAP_FOR_EACH (m, ofconn_node, &ofconn->monitors) {
2031         ofmonitor_collect_resume_rules(m, ofconn->monitor_paused, &rules);
2032     }
2033
2034     list_init(&msgs);
2035     ofmonitor_compose_refresh_updates(&rules, &msgs);
2036
2037     resumed = ofpraw_alloc_xid(OFPRAW_NXT_FLOW_MONITOR_RESUMED, OFP10_VERSION,
2038                                htonl(0), 0);
2039     list_push_back(&msgs, &resumed->list_node);
2040     ofconn_send_replies(ofconn, &msgs);
2041
2042     ofconn->monitor_paused = 0;
2043 }
2044
2045 static bool
2046 ofmonitor_may_resume(const struct ofconn *ofconn)
2047     OVS_REQUIRES(ofproto_mutex)
2048 {
2049     return (ofconn->monitor_paused != 0
2050             && !rconn_packet_counter_n_packets(ofconn->monitor_counter));
2051 }
2052
2053 static void
2054 ofmonitor_run(struct connmgr *mgr)
2055 {
2056     struct ofconn *ofconn;
2057
2058     ovs_mutex_lock(&ofproto_mutex);
2059     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
2060         if (ofmonitor_may_resume(ofconn)) {
2061             COVERAGE_INC(ofmonitor_resume);
2062             ofmonitor_resume(ofconn);
2063         }
2064     }
2065     ovs_mutex_unlock(&ofproto_mutex);
2066 }
2067
2068 static void
2069 ofmonitor_wait(struct connmgr *mgr)
2070 {
2071     struct ofconn *ofconn;
2072
2073     ovs_mutex_lock(&ofproto_mutex);
2074     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
2075         if (ofmonitor_may_resume(ofconn)) {
2076             poll_immediate_wake();
2077         }
2078     }
2079     ovs_mutex_unlock(&ofproto_mutex);
2080 }