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