ofproto: Add more thread safety annotations.
[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_ins(struct ofconn *, struct list *txq);
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 *) OVS_EXCLUDED(ofproto_mutex);
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     ovs_mutex_unlock(&ofproto_mutex);
641
642     update_in_band_remotes(mgr);
643     update_fail_open(mgr);
644     if (had_controllers != connmgr_has_controllers(mgr)) {
645         ofproto_flush_flows(mgr->ofproto);
646     }
647 }
648
649 /* Drops the connections between 'mgr' and all of its primary and secondary
650  * controllers, forcing them to reconnect. */
651 void
652 connmgr_reconnect(const struct connmgr *mgr)
653 {
654     struct ofconn *ofconn;
655
656     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
657         rconn_reconnect(ofconn->rconn);
658     }
659 }
660
661 /* Sets the "snoops" for 'mgr' to the pvconn targets listed in 'snoops'.
662  *
663  * A "snoop" is a pvconn to which every OpenFlow message to or from the most
664  * important controller on 'mgr' is mirrored. */
665 int
666 connmgr_set_snoops(struct connmgr *mgr, const struct sset *snoops)
667 {
668     return set_pvconns(&mgr->snoops, &mgr->n_snoops, snoops);
669 }
670
671 /* Adds each of the snoops currently configured on 'mgr' to 'snoops'. */
672 void
673 connmgr_get_snoops(const struct connmgr *mgr, struct sset *snoops)
674 {
675     size_t i;
676
677     for (i = 0; i < mgr->n_snoops; i++) {
678         sset_add(snoops, pvconn_get_name(mgr->snoops[i]));
679     }
680 }
681
682 /* Returns true if 'mgr' has at least one snoop, false if it has none. */
683 bool
684 connmgr_has_snoops(const struct connmgr *mgr)
685 {
686     return mgr->n_snoops > 0;
687 }
688
689 /* Creates a new controller for 'target' in 'mgr'.  update_controller() needs
690  * to be called later to finish the new ofconn's configuration. */
691 static void
692 add_controller(struct connmgr *mgr, const char *target, uint8_t dscp,
693                uint32_t allowed_versions)
694     OVS_REQUIRES(ofproto_mutex)
695 {
696     char *name = ofconn_make_name(mgr, target);
697     struct ofconn *ofconn;
698
699     ofconn = ofconn_create(mgr, rconn_create(5, 8, dscp, allowed_versions),
700                            OFCONN_PRIMARY, true);
701     ofconn->pktbuf = pktbuf_create();
702     rconn_connect(ofconn->rconn, target, name);
703     hmap_insert(&mgr->controllers, &ofconn->hmap_node, hash_string(target, 0));
704
705     free(name);
706 }
707
708 static struct ofconn *
709 find_controller_by_target(struct connmgr *mgr, const char *target)
710 {
711     struct ofconn *ofconn;
712
713     HMAP_FOR_EACH_WITH_HASH (ofconn, hmap_node,
714                              hash_string(target, 0), &mgr->controllers) {
715         if (!strcmp(ofconn_get_target(ofconn), target)) {
716             return ofconn;
717         }
718     }
719     return NULL;
720 }
721
722 static void
723 update_in_band_remotes(struct connmgr *mgr)
724 {
725     struct sockaddr_in *addrs;
726     size_t max_addrs, n_addrs;
727     struct ofconn *ofconn;
728     size_t i;
729
730     /* Allocate enough memory for as many remotes as we could possibly have. */
731     max_addrs = mgr->n_extra_remotes + hmap_count(&mgr->controllers);
732     addrs = xmalloc(max_addrs * sizeof *addrs);
733     n_addrs = 0;
734
735     /* Add all the remotes. */
736     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
737         struct sockaddr_in *sin = &addrs[n_addrs];
738         const char *target = rconn_get_target(ofconn->rconn);
739
740         if (ofconn->band == OFPROTO_OUT_OF_BAND) {
741             continue;
742         }
743
744         if (stream_parse_target_with_default_port(target,
745                                                   OFP_OLD_PORT,
746                                                   sin)) {
747             n_addrs++;
748         }
749     }
750     for (i = 0; i < mgr->n_extra_remotes; i++) {
751         addrs[n_addrs++] = mgr->extra_in_band_remotes[i];
752     }
753
754     /* Create or update or destroy in-band. */
755     if (n_addrs) {
756         if (!mgr->in_band) {
757             in_band_create(mgr->ofproto, mgr->local_port_name, &mgr->in_band);
758         }
759         in_band_set_queue(mgr->in_band, mgr->in_band_queue);
760     } else {
761         /* in_band_run() needs a chance to delete any existing in-band flows.
762          * We will destroy mgr->in_band after it's done with that. */
763     }
764     if (mgr->in_band) {
765         in_band_set_remotes(mgr->in_band, addrs, n_addrs);
766     }
767
768     /* Clean up. */
769     free(addrs);
770 }
771
772 static void
773 update_fail_open(struct connmgr *mgr)
774     OVS_EXCLUDED(ofproto_mutex)
775 {
776     if (connmgr_has_controllers(mgr)
777         && mgr->fail_mode == OFPROTO_FAIL_STANDALONE) {
778         if (!mgr->fail_open) {
779             mgr->fail_open = fail_open_create(mgr->ofproto, mgr);
780         }
781     } else {
782         fail_open_destroy(mgr->fail_open);
783         mgr->fail_open = NULL;
784     }
785 }
786
787 static int
788 set_pvconns(struct pvconn ***pvconnsp, size_t *n_pvconnsp,
789             const struct sset *sset)
790 {
791     struct pvconn **pvconns = *pvconnsp;
792     size_t n_pvconns = *n_pvconnsp;
793     const char *name;
794     int retval = 0;
795     size_t i;
796
797     for (i = 0; i < n_pvconns; i++) {
798         pvconn_close(pvconns[i]);
799     }
800     free(pvconns);
801
802     pvconns = xmalloc(sset_count(sset) * sizeof *pvconns);
803     n_pvconns = 0;
804     SSET_FOR_EACH (name, sset) {
805         struct pvconn *pvconn;
806         int error;
807         error = pvconn_open(name, 0, 0, &pvconn);
808         if (!error) {
809             pvconns[n_pvconns++] = pvconn;
810         } else {
811             VLOG_ERR("failed to listen on %s: %s", name, ovs_strerror(error));
812             if (!retval) {
813                 retval = error;
814             }
815         }
816     }
817
818     *pvconnsp = pvconns;
819     *n_pvconnsp = n_pvconns;
820
821     return retval;
822 }
823
824 /* Returns a "preference level" for snooping 'ofconn'.  A higher return value
825  * means that 'ofconn' is more interesting for monitoring than a lower return
826  * value. */
827 static int
828 snoop_preference(const struct ofconn *ofconn)
829 {
830     switch (ofconn->role) {
831     case OFPCR12_ROLE_MASTER:
832         return 3;
833     case OFPCR12_ROLE_EQUAL:
834         return 2;
835     case OFPCR12_ROLE_SLAVE:
836         return 1;
837     case OFPCR12_ROLE_NOCHANGE:
838     default:
839         /* Shouldn't happen. */
840         return 0;
841     }
842 }
843
844 /* One of 'mgr''s "snoop" pvconns has accepted a new connection on 'vconn'.
845  * Connects this vconn to a controller. */
846 static void
847 add_snooper(struct connmgr *mgr, struct vconn *vconn)
848 {
849     struct ofconn *ofconn, *best;
850
851     /* Pick a controller for monitoring. */
852     best = NULL;
853     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
854         if (ofconn->type == OFCONN_PRIMARY
855             && (!best || snoop_preference(ofconn) > snoop_preference(best))) {
856             best = ofconn;
857         }
858     }
859
860     if (best) {
861         rconn_add_monitor(best->rconn, vconn);
862     } else {
863         VLOG_INFO_RL(&rl, "no controller connection to snoop");
864         vconn_close(vconn);
865     }
866 }
867 \f
868 /* Public ofconn functions. */
869
870 /* Returns the connection type, either OFCONN_PRIMARY or OFCONN_SERVICE. */
871 enum ofconn_type
872 ofconn_get_type(const struct ofconn *ofconn)
873 {
874     return ofconn->type;
875 }
876
877 /* If a master election id is defined, stores it into '*idp' and returns
878  * true.  Otherwise, stores UINT64_MAX into '*idp' and returns false. */
879 bool
880 ofconn_get_master_election_id(const struct ofconn *ofconn, uint64_t *idp)
881 {
882     *idp = (ofconn->connmgr->master_election_id_defined
883             ? ofconn->connmgr->master_election_id
884             : UINT64_MAX);
885     return ofconn->connmgr->master_election_id_defined;
886 }
887
888 /* Sets the master election id.
889  *
890  * Returns true if successful, false if the id is stale
891  */
892 bool
893 ofconn_set_master_election_id(struct ofconn *ofconn, uint64_t id)
894 {
895     if (ofconn->connmgr->master_election_id_defined
896         &&
897         /* Unsigned difference interpreted as a two's complement signed
898          * value */
899         (int64_t)(id - ofconn->connmgr->master_election_id) < 0) {
900         return false;
901     }
902     ofconn->connmgr->master_election_id = id;
903     ofconn->connmgr->master_election_id_defined = true;
904
905     return true;
906 }
907
908 /* Returns the role configured for 'ofconn'.
909  *
910  * The default role, if no other role has been set, is OFPCR12_ROLE_EQUAL. */
911 enum ofp12_controller_role
912 ofconn_get_role(const struct ofconn *ofconn)
913 {
914     return ofconn->role;
915 }
916
917 void
918 ofconn_send_role_status(struct ofconn *ofconn, uint32_t role, uint8_t reason)
919 {
920     struct ofputil_role_status status;
921     struct ofpbuf *buf;
922
923     status.reason = reason;
924     status.role = role;
925     ofconn_get_master_election_id(ofconn, &status.generation_id);
926
927     buf = ofputil_encode_role_status(&status, ofconn_get_protocol(ofconn));
928
929     ofconn_send(ofconn, buf, NULL);
930 }
931
932 /* Changes 'ofconn''s role to 'role'.  If 'role' is OFPCR12_ROLE_MASTER then
933  * any existing master is demoted to a slave. */
934 void
935 ofconn_set_role(struct ofconn *ofconn, enum ofp12_controller_role role)
936 {
937     if (role != ofconn->role && role == OFPCR12_ROLE_MASTER) {
938         struct ofconn *other;
939
940         HMAP_FOR_EACH (other, hmap_node, &ofconn->connmgr->controllers) {
941             if (other->role == OFPCR12_ROLE_MASTER) {
942                 other->role = OFPCR12_ROLE_SLAVE;
943                 ofconn_send_role_status(other, OFPCR12_ROLE_SLAVE, OFPCRR_MASTER_REQUEST);
944             }
945         }
946     }
947     ofconn->role = role;
948 }
949
950 void
951 ofconn_set_invalid_ttl_to_controller(struct ofconn *ofconn, bool enable)
952 {
953     uint32_t bit = 1u << OFPR_INVALID_TTL;
954     if (enable) {
955         ofconn->master_async_config[OAM_PACKET_IN] |= bit;
956     } else {
957         ofconn->master_async_config[OAM_PACKET_IN] &= ~bit;
958     }
959 }
960
961 bool
962 ofconn_get_invalid_ttl_to_controller(struct ofconn *ofconn)
963 {
964     uint32_t bit = 1u << OFPR_INVALID_TTL;
965     return (ofconn->master_async_config[OAM_PACKET_IN] & bit) != 0;
966 }
967
968 /* Returns the currently configured protocol for 'ofconn', one of OFPUTIL_P_*.
969  *
970  * Returns OFPUTIL_P_NONE, which is not a valid protocol, if 'ofconn' hasn't
971  * completed version negotiation.  This can't happen if at least one OpenFlow
972  * message, other than OFPT_HELLO, has been received on the connection (such as
973  * in ofproto.c's message handling code), since version negotiation is a
974  * prerequisite for starting to receive messages.  This means that
975  * OFPUTIL_P_NONE is a special case that most callers need not worry about. */
976 enum ofputil_protocol
977 ofconn_get_protocol(const struct ofconn *ofconn)
978 {
979     if (ofconn->protocol == OFPUTIL_P_NONE &&
980         rconn_is_connected(ofconn->rconn)) {
981         int version = rconn_get_version(ofconn->rconn);
982         if (version > 0) {
983             ofconn_set_protocol(CONST_CAST(struct ofconn *, ofconn),
984                                 ofputil_protocol_from_ofp_version(version));
985         }
986     }
987
988     return ofconn->protocol;
989 }
990
991 /* Sets the protocol for 'ofconn' to 'protocol' (one of OFPUTIL_P_*).
992  *
993  * (This doesn't actually send anything to accomplish this.  Presumably the
994  * caller already did that.) */
995 void
996 ofconn_set_protocol(struct ofconn *ofconn, enum ofputil_protocol protocol)
997 {
998     ofconn->protocol = protocol;
999 }
1000
1001 /* Returns the currently configured packet in format for 'ofconn', one of
1002  * NXPIF_*.
1003  *
1004  * The default, if no other format has been set, is NXPIF_OPENFLOW10. */
1005 enum nx_packet_in_format
1006 ofconn_get_packet_in_format(struct ofconn *ofconn)
1007 {
1008     return ofconn->packet_in_format;
1009 }
1010
1011 /* Sets the packet in format for 'ofconn' to 'packet_in_format' (one of
1012  * NXPIF_*). */
1013 void
1014 ofconn_set_packet_in_format(struct ofconn *ofconn,
1015                             enum nx_packet_in_format packet_in_format)
1016 {
1017     ofconn->packet_in_format = packet_in_format;
1018 }
1019
1020 /* Sets the controller connection ID for 'ofconn' to 'controller_id'.
1021  *
1022  * The connection controller ID is used for OFPP_CONTROLLER and
1023  * NXAST_CONTROLLER actions.  See "struct nx_action_controller" for details. */
1024 void
1025 ofconn_set_controller_id(struct ofconn *ofconn, uint16_t controller_id)
1026 {
1027     ofconn->controller_id = controller_id;
1028 }
1029
1030 /* Returns the default miss send length for 'ofconn'. */
1031 int
1032 ofconn_get_miss_send_len(const struct ofconn *ofconn)
1033 {
1034     return ofconn->miss_send_len;
1035 }
1036
1037 /* Sets the default miss send length for 'ofconn' to 'miss_send_len'. */
1038 void
1039 ofconn_set_miss_send_len(struct ofconn *ofconn, int miss_send_len)
1040 {
1041     ofconn->miss_send_len = miss_send_len;
1042 }
1043
1044 void
1045 ofconn_set_async_config(struct ofconn *ofconn,
1046                         const uint32_t master_masks[OAM_N_TYPES],
1047                         const uint32_t slave_masks[OAM_N_TYPES])
1048 {
1049     size_t size = sizeof ofconn->master_async_config;
1050     memcpy(ofconn->master_async_config, master_masks, size);
1051     memcpy(ofconn->slave_async_config, slave_masks, size);
1052 }
1053
1054 void
1055 ofconn_get_async_config(struct ofconn *ofconn,
1056                         uint32_t *master_masks, uint32_t *slave_masks)
1057 {
1058     size_t size = sizeof ofconn->master_async_config;
1059     memcpy(master_masks, ofconn->master_async_config, size);
1060     memcpy(slave_masks, ofconn->slave_async_config, size);
1061 }
1062
1063 /* Sends 'msg' on 'ofconn', accounting it as a reply.  (If there is a
1064  * sufficient number of OpenFlow replies in-flight on a single ofconn, then the
1065  * connmgr will stop accepting new OpenFlow requests on that ofconn until the
1066  * controller has accepted some of the replies.) */
1067 void
1068 ofconn_send_reply(const struct ofconn *ofconn, struct ofpbuf *msg)
1069 {
1070     ofconn_send(ofconn, msg, ofconn->reply_counter);
1071 }
1072
1073 /* Sends each of the messages in list 'replies' on 'ofconn' in order,
1074  * accounting them as replies. */
1075 void
1076 ofconn_send_replies(const struct ofconn *ofconn, struct list *replies)
1077 {
1078     struct ofpbuf *reply, *next;
1079
1080     LIST_FOR_EACH_SAFE (reply, next, list_node, replies) {
1081         list_remove(&reply->list_node);
1082         ofconn_send_reply(ofconn, reply);
1083     }
1084 }
1085
1086 /* Sends 'error' on 'ofconn', as a reply to 'request'.  Only at most the
1087  * first 64 bytes of 'request' are used. */
1088 void
1089 ofconn_send_error(const struct ofconn *ofconn,
1090                   const struct ofp_header *request, enum ofperr error)
1091 {
1092     static struct vlog_rate_limit err_rl = VLOG_RATE_LIMIT_INIT(10, 10);
1093     struct ofpbuf *reply;
1094
1095     reply = ofperr_encode_reply(error, request);
1096     if (!VLOG_DROP_INFO(&err_rl)) {
1097         const char *type_name;
1098         size_t request_len;
1099         enum ofpraw raw;
1100
1101         request_len = ntohs(request->length);
1102         type_name = (!ofpraw_decode_partial(&raw, request,
1103                                             MIN(64, request_len))
1104                      ? ofpraw_get_name(raw)
1105                      : "invalid");
1106
1107         VLOG_INFO("%s: sending %s error reply to %s message",
1108                   rconn_get_name(ofconn->rconn), ofperr_to_string(error),
1109                   type_name);
1110     }
1111     ofconn_send_reply(ofconn, reply);
1112 }
1113
1114 /* Same as pktbuf_retrieve(), using the pktbuf owned by 'ofconn'. */
1115 enum ofperr
1116 ofconn_pktbuf_retrieve(struct ofconn *ofconn, uint32_t id,
1117                        struct ofpbuf **bufferp, ofp_port_t *in_port)
1118 {
1119     return pktbuf_retrieve(ofconn->pktbuf, id, bufferp, in_port);
1120 }
1121
1122 /* Returns true if 'ofconn' has any pending opgroups. */
1123 bool
1124 ofconn_has_pending_opgroups(const struct ofconn *ofconn)
1125 {
1126     return !list_is_empty(&ofconn->opgroups);
1127 }
1128
1129 /* Adds 'ofconn_node' to 'ofconn''s list of pending opgroups.
1130  *
1131  * If 'ofconn' is destroyed or its connection drops, then 'ofconn' will remove
1132  * 'ofconn_node' from the list and re-initialize it with list_init().  The
1133  * client may, therefore, use list_is_empty(ofconn_node) to determine whether
1134  * 'ofconn_node' is still associated with an active ofconn.
1135  *
1136  * The client may also remove ofconn_node from the list itself, with
1137  * list_remove(). */
1138 void
1139 ofconn_add_opgroup(struct ofconn *ofconn, struct list *ofconn_node)
1140 {
1141     list_push_back(&ofconn->opgroups, ofconn_node);
1142 }
1143 \f
1144 /* Private ofconn functions. */
1145
1146 static const char *
1147 ofconn_get_target(const struct ofconn *ofconn)
1148 {
1149     return rconn_get_target(ofconn->rconn);
1150 }
1151
1152 static struct ofconn *
1153 ofconn_create(struct connmgr *mgr, struct rconn *rconn, enum ofconn_type type,
1154               bool enable_async_msgs)
1155 {
1156     struct ofconn *ofconn;
1157
1158     ofconn = xzalloc(sizeof *ofconn);
1159     ofconn->connmgr = mgr;
1160     list_push_back(&mgr->all_conns, &ofconn->node);
1161     ofconn->rconn = rconn;
1162     ofconn->type = type;
1163     ofconn->enable_async_msgs = enable_async_msgs;
1164
1165     list_init(&ofconn->opgroups);
1166
1167     hmap_init(&ofconn->monitors);
1168     list_init(&ofconn->updates);
1169
1170     ofconn_flush(ofconn);
1171
1172     return ofconn;
1173 }
1174
1175 /* Clears all of the state in 'ofconn' that should not persist from one
1176  * connection to the next. */
1177 static void
1178 ofconn_flush(struct ofconn *ofconn)
1179     OVS_REQUIRES(ofproto_mutex)
1180 {
1181     struct ofmonitor *monitor, *next_monitor;
1182     int i;
1183
1184     ofconn->role = OFPCR12_ROLE_EQUAL;
1185     ofconn_set_protocol(ofconn, OFPUTIL_P_NONE);
1186     ofconn->packet_in_format = NXPIF_OPENFLOW10;
1187
1188     /* Disassociate 'ofconn' from all of the ofopgroups that it initiated that
1189      * have not yet completed.  (Those ofopgroups will still run to completion
1190      * in the usual way, but any errors that they run into will not be reported
1191      * on any OpenFlow channel.)
1192      *
1193      * Also discard any blocked operation on 'ofconn'. */
1194     while (!list_is_empty(&ofconn->opgroups)) {
1195         list_init(list_pop_front(&ofconn->opgroups));
1196     }
1197     ofpbuf_delete(ofconn->blocked);
1198     ofconn->blocked = NULL;
1199
1200     rconn_packet_counter_destroy(ofconn->packet_in_counter);
1201     ofconn->packet_in_counter = rconn_packet_counter_create();
1202     for (i = 0; i < N_SCHEDULERS; i++) {
1203         if (ofconn->schedulers[i]) {
1204             int rate, burst;
1205
1206             pinsched_get_limits(ofconn->schedulers[i], &rate, &burst);
1207             pinsched_destroy(ofconn->schedulers[i]);
1208             ofconn->schedulers[i] = pinsched_create(rate, burst);
1209         }
1210     }
1211     if (ofconn->pktbuf) {
1212         pktbuf_destroy(ofconn->pktbuf);
1213         ofconn->pktbuf = pktbuf_create();
1214     }
1215     ofconn->miss_send_len = (ofconn->type == OFCONN_PRIMARY
1216                              ? OFP_DEFAULT_MISS_SEND_LEN
1217                              : 0);
1218     ofconn->controller_id = 0;
1219
1220     rconn_packet_counter_destroy(ofconn->reply_counter);
1221     ofconn->reply_counter = rconn_packet_counter_create();
1222
1223     if (ofconn->enable_async_msgs) {
1224         uint32_t *master = ofconn->master_async_config;
1225         uint32_t *slave = ofconn->slave_async_config;
1226
1227         /* "master" and "other" roles get all asynchronous messages by default,
1228          * except that the controller needs to enable nonstandard "packet-in"
1229          * reasons itself. */
1230         master[OAM_PACKET_IN] = (1u << OFPR_NO_MATCH) | (1u << OFPR_ACTION);
1231         master[OAM_PORT_STATUS] = ((1u << OFPPR_ADD)
1232                                    | (1u << OFPPR_DELETE)
1233                                    | (1u << OFPPR_MODIFY));
1234         master[OAM_FLOW_REMOVED] = ((1u << OFPRR_IDLE_TIMEOUT)
1235                                     | (1u << OFPRR_HARD_TIMEOUT)
1236                                     | (1u << OFPRR_DELETE));
1237
1238         /* "slave" role gets port status updates by default. */
1239         slave[OAM_PACKET_IN] = 0;
1240         slave[OAM_PORT_STATUS] = ((1u << OFPPR_ADD)
1241                                   | (1u << OFPPR_DELETE)
1242                                   | (1u << OFPPR_MODIFY));
1243         slave[OAM_FLOW_REMOVED] = 0;
1244     } else {
1245         memset(ofconn->master_async_config, 0,
1246                sizeof ofconn->master_async_config);
1247         memset(ofconn->slave_async_config, 0,
1248                sizeof ofconn->slave_async_config);
1249     }
1250
1251     HMAP_FOR_EACH_SAFE (monitor, next_monitor, ofconn_node,
1252                         &ofconn->monitors) {
1253         ofmonitor_destroy(monitor);
1254     }
1255     rconn_packet_counter_destroy(ofconn->monitor_counter);
1256     ofconn->monitor_counter = rconn_packet_counter_create();
1257     ofpbuf_list_delete(&ofconn->updates); /* ...but it should be empty. */
1258 }
1259
1260 static void
1261 ofconn_destroy(struct ofconn *ofconn)
1262     OVS_REQUIRES(ofproto_mutex)
1263 {
1264     ofconn_flush(ofconn);
1265
1266     if (ofconn->type == OFCONN_PRIMARY) {
1267         hmap_remove(&ofconn->connmgr->controllers, &ofconn->hmap_node);
1268     }
1269
1270     hmap_destroy(&ofconn->monitors);
1271     list_remove(&ofconn->node);
1272     rconn_destroy(ofconn->rconn);
1273     rconn_packet_counter_destroy(ofconn->packet_in_counter);
1274     rconn_packet_counter_destroy(ofconn->reply_counter);
1275     pktbuf_destroy(ofconn->pktbuf);
1276     rconn_packet_counter_destroy(ofconn->monitor_counter);
1277     free(ofconn);
1278 }
1279
1280 /* Reconfigures 'ofconn' to match 'c'.  'ofconn' and 'c' must have the same
1281  * target. */
1282 static void
1283 ofconn_reconfigure(struct ofconn *ofconn, const struct ofproto_controller *c)
1284 {
1285     int probe_interval;
1286
1287     ofconn->band = c->band;
1288     ofconn->enable_async_msgs = c->enable_async_msgs;
1289
1290     rconn_set_max_backoff(ofconn->rconn, c->max_backoff);
1291
1292     probe_interval = c->probe_interval ? MAX(c->probe_interval, 5) : 0;
1293     rconn_set_probe_interval(ofconn->rconn, probe_interval);
1294
1295     ofconn_set_rate_limit(ofconn, c->rate_limit, c->burst_limit);
1296
1297     /* If dscp value changed reconnect. */
1298     if (c->dscp != rconn_get_dscp(ofconn->rconn)) {
1299         rconn_set_dscp(ofconn->rconn, c->dscp);
1300         rconn_reconnect(ofconn->rconn);
1301     }
1302 }
1303
1304 /* Returns true if it makes sense for 'ofconn' to receive and process OpenFlow
1305  * messages. */
1306 static bool
1307 ofconn_may_recv(const struct ofconn *ofconn)
1308 {
1309     int count = rconn_packet_counter_n_packets(ofconn->reply_counter);
1310     return (!ofconn->blocked || ofconn->retry) && count < OFCONN_REPLY_MAX;
1311 }
1312
1313 static void
1314 ofconn_run(struct ofconn *ofconn,
1315            bool (*handle_openflow)(struct ofconn *,
1316                                    const struct ofpbuf *ofp_msg))
1317 {
1318     struct connmgr *mgr = ofconn->connmgr;
1319     size_t i;
1320
1321     for (i = 0; i < N_SCHEDULERS; i++) {
1322         struct list txq;
1323
1324         pinsched_run(ofconn->schedulers[i], &txq);
1325         do_send_packet_ins(ofconn, &txq);
1326     }
1327
1328     rconn_run(ofconn->rconn);
1329
1330     if (handle_openflow) {
1331         /* Limit the number of iterations to avoid starving other tasks. */
1332         for (i = 0; i < 50 && ofconn_may_recv(ofconn); i++) {
1333             struct ofpbuf *of_msg;
1334
1335             of_msg = (ofconn->blocked
1336                       ? ofconn->blocked
1337                       : rconn_recv(ofconn->rconn));
1338             if (!of_msg) {
1339                 break;
1340             }
1341             if (mgr->fail_open) {
1342                 fail_open_maybe_recover(mgr->fail_open);
1343             }
1344
1345             if (handle_openflow(ofconn, of_msg)) {
1346                 ofpbuf_delete(of_msg);
1347                 ofconn->blocked = NULL;
1348             } else {
1349                 ofconn->blocked = of_msg;
1350                 ofconn->retry = false;
1351             }
1352         }
1353     }
1354
1355     ovs_mutex_lock(&ofproto_mutex);
1356     if (!rconn_is_alive(ofconn->rconn)) {
1357         ofconn_destroy(ofconn);
1358     } else if (!rconn_is_connected(ofconn->rconn)) {
1359         ofconn_flush(ofconn);
1360     }
1361     ovs_mutex_unlock(&ofproto_mutex);
1362 }
1363
1364 static void
1365 ofconn_wait(struct ofconn *ofconn, bool handling_openflow)
1366 {
1367     int i;
1368
1369     for (i = 0; i < N_SCHEDULERS; i++) {
1370         pinsched_wait(ofconn->schedulers[i]);
1371     }
1372     rconn_run_wait(ofconn->rconn);
1373     if (handling_openflow && ofconn_may_recv(ofconn)) {
1374         rconn_recv_wait(ofconn->rconn);
1375     }
1376 }
1377
1378 /* Returns true if 'ofconn' should receive asynchronous messages of the given
1379  * OAM_* 'type' and 'reason', which should be a OFPR_* value for OAM_PACKET_IN,
1380  * a OFPPR_* value for OAM_PORT_STATUS, or an OFPRR_* value for
1381  * OAM_FLOW_REMOVED.  Returns false if the message should not be sent on
1382  * 'ofconn'. */
1383 static bool
1384 ofconn_receives_async_msg(const struct ofconn *ofconn,
1385                           enum ofconn_async_msg_type type,
1386                           unsigned int reason)
1387 {
1388     const uint32_t *async_config;
1389
1390     ovs_assert(reason < 32);
1391     ovs_assert((unsigned int) type < OAM_N_TYPES);
1392
1393     if (ofconn_get_protocol(ofconn) == OFPUTIL_P_NONE
1394         || !rconn_is_connected(ofconn->rconn)) {
1395         return false;
1396     }
1397
1398     /* Keep the following code in sync with the documentation in the
1399      * "Asynchronous Messages" section in DESIGN. */
1400
1401     if (ofconn->type == OFCONN_SERVICE && !ofconn->miss_send_len) {
1402         /* Service connections don't get asynchronous messages unless they have
1403          * explicitly asked for them by setting a nonzero miss send length. */
1404         return false;
1405     }
1406
1407     async_config = (ofconn->role == OFPCR12_ROLE_SLAVE
1408                     ? ofconn->slave_async_config
1409                     : ofconn->master_async_config);
1410     if (!(async_config[type] & (1u << reason))) {
1411         return false;
1412     }
1413
1414     return true;
1415 }
1416
1417 /* Returns a human-readable name for an OpenFlow connection between 'mgr' and
1418  * 'target', suitable for use in log messages for identifying the connection.
1419  *
1420  * The name is dynamically allocated.  The caller should free it (with free())
1421  * when it is no longer needed. */
1422 static char *
1423 ofconn_make_name(const struct connmgr *mgr, const char *target)
1424 {
1425     return xasprintf("%s<->%s", mgr->name, target);
1426 }
1427
1428 static void
1429 ofconn_set_rate_limit(struct ofconn *ofconn, int rate, int burst)
1430 {
1431     int i;
1432
1433     for (i = 0; i < N_SCHEDULERS; i++) {
1434         struct pinsched **s = &ofconn->schedulers[i];
1435
1436         if (rate > 0) {
1437             if (!*s) {
1438                 *s = pinsched_create(rate, burst);
1439             } else {
1440                 pinsched_set_limits(*s, rate, burst);
1441             }
1442         } else {
1443             pinsched_destroy(*s);
1444             *s = NULL;
1445         }
1446     }
1447 }
1448
1449 static void
1450 ofconn_send(const struct ofconn *ofconn, struct ofpbuf *msg,
1451             struct rconn_packet_counter *counter)
1452 {
1453     ofpmsg_update_length(msg);
1454     rconn_send(ofconn->rconn, msg, counter);
1455 }
1456 \f
1457 /* Sending asynchronous messages. */
1458
1459 static void schedule_packet_in(struct ofconn *, struct ofproto_packet_in,
1460                                enum ofp_packet_in_reason wire_reason);
1461
1462 /* Sends an OFPT_PORT_STATUS message with 'opp' and 'reason' to appropriate
1463  * controllers managed by 'mgr'. */
1464 void
1465 connmgr_send_port_status(struct connmgr *mgr,
1466                          const struct ofputil_phy_port *pp, uint8_t reason)
1467 {
1468     /* XXX Should limit the number of queued port status change messages. */
1469     struct ofputil_port_status ps;
1470     struct ofconn *ofconn;
1471
1472     ps.reason = reason;
1473     ps.desc = *pp;
1474     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
1475         if (ofconn_receives_async_msg(ofconn, OAM_PORT_STATUS, reason)) {
1476             struct ofpbuf *msg;
1477
1478             msg = ofputil_encode_port_status(&ps, ofconn_get_protocol(ofconn));
1479             ofconn_send(ofconn, msg, NULL);
1480         }
1481     }
1482 }
1483
1484 /* Sends an OFPT_FLOW_REMOVED or NXT_FLOW_REMOVED message based on 'fr' to
1485  * appropriate controllers managed by 'mgr'. */
1486 void
1487 connmgr_send_flow_removed(struct connmgr *mgr,
1488                           const struct ofputil_flow_removed *fr)
1489 {
1490     struct ofconn *ofconn;
1491
1492     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
1493         if (ofconn_receives_async_msg(ofconn, OAM_FLOW_REMOVED, fr->reason)) {
1494             struct ofpbuf *msg;
1495
1496             /* Account flow expirations as replies to OpenFlow requests.  That
1497              * works because preventing OpenFlow requests from being processed
1498              * also prevents new flows from being added (and expiring).  (It
1499              * also prevents processing OpenFlow requests that would not add
1500              * new flows, so it is imperfect.) */
1501             msg = ofputil_encode_flow_removed(fr, ofconn_get_protocol(ofconn));
1502             ofconn_send_reply(ofconn, msg);
1503         }
1504     }
1505 }
1506
1507 /* Normally a send-to-controller action uses reason OFPR_ACTION.  However, in
1508  * OpenFlow 1.3 and later, packet_ins generated by a send-to-controller action
1509  * in a "table-miss" flow (one with priority 0 and completely wildcarded) are
1510  * sent as OFPR_NO_MATCH.  This function returns the reason that should
1511  * actually be sent on 'ofconn' for 'pin'. */
1512 static enum ofp_packet_in_reason
1513 wire_reason(struct ofconn *ofconn, const struct ofproto_packet_in *pin)
1514 {
1515     if (pin->generated_by_table_miss && pin->up.reason == OFPR_ACTION) {
1516         enum ofputil_protocol protocol = ofconn_get_protocol(ofconn);
1517
1518         if (protocol != OFPUTIL_P_NONE
1519             && ofputil_protocol_to_ofp_version(protocol) >= OFP13_VERSION) {
1520             return OFPR_NO_MATCH;
1521         }
1522     }
1523     return pin->up.reason;
1524 }
1525
1526 /* Given 'pin', sends an OFPT_PACKET_IN message to each OpenFlow controller as
1527  * necessary according to their individual configurations.
1528  *
1529  * The caller doesn't need to fill in pin->buffer_id or pin->total_len. */
1530 void
1531 connmgr_send_packet_in(struct connmgr *mgr,
1532                        const struct ofproto_packet_in *pin)
1533 {
1534     struct ofconn *ofconn;
1535
1536     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
1537         enum ofp_packet_in_reason reason = wire_reason(ofconn, pin);
1538
1539         if (ofconn_receives_async_msg(ofconn, OAM_PACKET_IN, reason)
1540             && ofconn->controller_id == pin->controller_id) {
1541             schedule_packet_in(ofconn, *pin, reason);
1542         }
1543     }
1544 }
1545
1546 static void
1547 do_send_packet_ins(struct ofconn *ofconn, struct list *txq)
1548 {
1549     struct ofpbuf *pin, *next_pin;
1550
1551     LIST_FOR_EACH_SAFE (pin, next_pin, list_node, txq) {
1552         list_remove(&pin->list_node);
1553
1554         if (rconn_send_with_limit(ofconn->rconn, pin,
1555                                   ofconn->packet_in_counter, 100) == EAGAIN) {
1556             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
1557
1558             VLOG_INFO_RL(&rl, "%s: dropping packet-in due to queue overflow",
1559                          rconn_get_name(ofconn->rconn));
1560         }
1561     }
1562 }
1563
1564 /* Takes 'pin', composes an OpenFlow packet-in message from it, and passes it
1565  * to 'ofconn''s packet scheduler for sending. */
1566 static void
1567 schedule_packet_in(struct ofconn *ofconn, struct ofproto_packet_in pin,
1568                    enum ofp_packet_in_reason wire_reason)
1569 {
1570     struct connmgr *mgr = ofconn->connmgr;
1571     uint16_t controller_max_len;
1572     struct list txq;
1573
1574     pin.up.total_len = pin.up.packet_len;
1575
1576     pin.up.reason = wire_reason;
1577     if (pin.up.reason == OFPR_ACTION) {
1578         controller_max_len = pin.send_len;  /* max_len */
1579     } else {
1580         controller_max_len = ofconn->miss_send_len;
1581     }
1582
1583     /* Get OpenFlow buffer_id.
1584      * For OpenFlow 1.2+, OFPCML_NO_BUFFER (== UINT16_MAX) specifies
1585      * unbuffered.  This behaviour doesn't violate prior versions, too. */
1586     if (controller_max_len == UINT16_MAX) {
1587         pin.up.buffer_id = UINT32_MAX;
1588     } else if (mgr->fail_open && fail_open_is_active(mgr->fail_open)) {
1589         pin.up.buffer_id = pktbuf_get_null();
1590     } else if (!ofconn->pktbuf) {
1591         pin.up.buffer_id = UINT32_MAX;
1592     } else {
1593         pin.up.buffer_id = pktbuf_save(ofconn->pktbuf,
1594                                        pin.up.packet, pin.up.packet_len,
1595                                        pin.up.fmd.in_port);
1596     }
1597
1598     /* Figure out how much of the packet to send.
1599      * If not buffered, send the entire packet.  Otherwise, depending on
1600      * the reason of packet-in, send what requested by the controller. */
1601     if (pin.up.buffer_id != UINT32_MAX
1602         && controller_max_len < pin.up.packet_len) {
1603         pin.up.packet_len = controller_max_len;
1604     }
1605
1606     /* Make OFPT_PACKET_IN and hand over to packet scheduler. */
1607     pinsched_send(ofconn->schedulers[pin.up.reason == OFPR_NO_MATCH ? 0 : 1],
1608                   pin.up.fmd.in_port,
1609                   ofputil_encode_packet_in(&pin.up,
1610                                            ofconn_get_protocol(ofconn),
1611                                            ofconn->packet_in_format),
1612                   &txq);
1613     do_send_packet_ins(ofconn, &txq);
1614 }
1615 \f
1616 /* Fail-open settings. */
1617
1618 /* Returns the failure handling mode (OFPROTO_FAIL_SECURE or
1619  * OFPROTO_FAIL_STANDALONE) for 'mgr'. */
1620 enum ofproto_fail_mode
1621 connmgr_get_fail_mode(const struct connmgr *mgr)
1622 {
1623     return mgr->fail_mode;
1624 }
1625
1626 /* Sets the failure handling mode for 'mgr' to 'fail_mode' (either
1627  * OFPROTO_FAIL_SECURE or OFPROTO_FAIL_STANDALONE). */
1628 void
1629 connmgr_set_fail_mode(struct connmgr *mgr, enum ofproto_fail_mode fail_mode)
1630 {
1631     if (mgr->fail_mode != fail_mode) {
1632         mgr->fail_mode = fail_mode;
1633         update_fail_open(mgr);
1634         if (!connmgr_has_controllers(mgr)) {
1635             ofproto_flush_flows(mgr->ofproto);
1636         }
1637     }
1638 }
1639 \f
1640 /* Fail-open implementation. */
1641
1642 /* Returns the longest probe interval among the primary controllers configured
1643  * on 'mgr'.  Returns 0 if there are no primary controllers. */
1644 int
1645 connmgr_get_max_probe_interval(const struct connmgr *mgr)
1646 {
1647     const struct ofconn *ofconn;
1648     int max_probe_interval;
1649
1650     max_probe_interval = 0;
1651     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
1652         int probe_interval = rconn_get_probe_interval(ofconn->rconn);
1653         max_probe_interval = MAX(max_probe_interval, probe_interval);
1654     }
1655     return max_probe_interval;
1656 }
1657
1658 /* Returns the number of seconds for which all of 'mgr's primary controllers
1659  * have been disconnected.  Returns 0 if 'mgr' has no primary controllers. */
1660 int
1661 connmgr_failure_duration(const struct connmgr *mgr)
1662 {
1663     const struct ofconn *ofconn;
1664     int min_failure_duration;
1665
1666     if (!connmgr_has_controllers(mgr)) {
1667         return 0;
1668     }
1669
1670     min_failure_duration = INT_MAX;
1671     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
1672         int failure_duration = rconn_failure_duration(ofconn->rconn);
1673         min_failure_duration = MIN(min_failure_duration, failure_duration);
1674     }
1675     return min_failure_duration;
1676 }
1677
1678 /* Returns true if at least one primary controller is connected (regardless of
1679  * whether those controllers are believed to have authenticated and accepted
1680  * this switch), false if none of them are connected. */
1681 bool
1682 connmgr_is_any_controller_connected(const struct connmgr *mgr)
1683 {
1684     const struct ofconn *ofconn;
1685
1686     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
1687         if (rconn_is_connected(ofconn->rconn)) {
1688             return true;
1689         }
1690     }
1691     return false;
1692 }
1693
1694 /* Returns true if at least one primary controller is believed to have
1695  * authenticated and accepted this switch, false otherwise. */
1696 bool
1697 connmgr_is_any_controller_admitted(const struct connmgr *mgr)
1698 {
1699     const struct ofconn *ofconn;
1700
1701     HMAP_FOR_EACH (ofconn, hmap_node, &mgr->controllers) {
1702         if (rconn_is_admitted(ofconn->rconn)) {
1703             return true;
1704         }
1705     }
1706     return false;
1707 }
1708 \f
1709 /* In-band configuration. */
1710
1711 static bool any_extras_changed(const struct connmgr *,
1712                                const struct sockaddr_in *extras, size_t n);
1713
1714 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'mgr''s
1715  * in-band control should guarantee access, in the same way that in-band
1716  * control guarantees access to OpenFlow controllers. */
1717 void
1718 connmgr_set_extra_in_band_remotes(struct connmgr *mgr,
1719                                   const struct sockaddr_in *extras, size_t n)
1720 {
1721     if (!any_extras_changed(mgr, extras, n)) {
1722         return;
1723     }
1724
1725     free(mgr->extra_in_band_remotes);
1726     mgr->n_extra_remotes = n;
1727     mgr->extra_in_band_remotes = xmemdup(extras, n * sizeof *extras);
1728
1729     update_in_band_remotes(mgr);
1730 }
1731
1732 /* Sets the OpenFlow queue used by flows set up by in-band control on
1733  * 'mgr' to 'queue_id'.  If 'queue_id' is negative, then in-band control
1734  * flows will use the default queue. */
1735 void
1736 connmgr_set_in_band_queue(struct connmgr *mgr, int queue_id)
1737 {
1738     if (queue_id != mgr->in_band_queue) {
1739         mgr->in_band_queue = queue_id;
1740         update_in_band_remotes(mgr);
1741     }
1742 }
1743
1744 static bool
1745 any_extras_changed(const struct connmgr *mgr,
1746                    const struct sockaddr_in *extras, size_t n)
1747 {
1748     size_t i;
1749
1750     if (n != mgr->n_extra_remotes) {
1751         return true;
1752     }
1753
1754     for (i = 0; i < n; i++) {
1755         const struct sockaddr_in *old = &mgr->extra_in_band_remotes[i];
1756         const struct sockaddr_in *new = &extras[i];
1757
1758         if (old->sin_addr.s_addr != new->sin_addr.s_addr ||
1759             old->sin_port != new->sin_port) {
1760             return true;
1761         }
1762     }
1763
1764     return false;
1765 }
1766 \f
1767 /* In-band implementation. */
1768
1769 bool
1770 connmgr_has_in_band(struct connmgr *mgr)
1771 {
1772     return mgr->in_band != NULL;
1773 }
1774 \f
1775 /* Fail-open and in-band implementation. */
1776
1777 /* Called by 'ofproto' after all flows have been flushed, to allow fail-open
1778  * and standalone mode to re-create their flows.
1779  *
1780  * In-band control has more sophisticated code that manages flows itself. */
1781 void
1782 connmgr_flushed(struct connmgr *mgr)
1783     OVS_EXCLUDED(ofproto_mutex)
1784 {
1785     if (mgr->fail_open) {
1786         fail_open_flushed(mgr->fail_open);
1787     }
1788
1789     /* If there are no controllers and we're in standalone mode, set up a flow
1790      * that matches every packet and directs them to OFPP_NORMAL (which goes to
1791      * us).  Otherwise, the switch is in secure mode and we won't pass any
1792      * traffic until a controller has been defined and it tells us to do so. */
1793     if (!connmgr_has_controllers(mgr)
1794         && mgr->fail_mode == OFPROTO_FAIL_STANDALONE) {
1795         struct ofpbuf ofpacts;
1796         struct match match;
1797
1798         ofpbuf_init(&ofpacts, OFPACT_OUTPUT_SIZE);
1799         ofpact_put_OUTPUT(&ofpacts)->port = OFPP_NORMAL;
1800         ofpact_pad(&ofpacts);
1801
1802         match_init_catchall(&match);
1803         ofproto_add_flow(mgr->ofproto, &match, 0, ofpacts.data, ofpacts.size);
1804
1805         ofpbuf_uninit(&ofpacts);
1806     }
1807 }
1808 \f
1809 /* Creates a new ofservice for 'target' in 'mgr'.  Returns 0 if successful,
1810  * otherwise a positive errno value.
1811  *
1812  * ofservice_reconfigure() must be called to fully configure the new
1813  * ofservice. */
1814 static int
1815 ofservice_create(struct connmgr *mgr, const char *target,
1816                  uint32_t allowed_versions, uint8_t dscp)
1817 {
1818     struct ofservice *ofservice;
1819     struct pvconn *pvconn;
1820     int error;
1821
1822     error = pvconn_open(target, allowed_versions, dscp, &pvconn);
1823     if (error) {
1824         return error;
1825     }
1826
1827     ofservice = xzalloc(sizeof *ofservice);
1828     hmap_insert(&mgr->services, &ofservice->node, hash_string(target, 0));
1829     ofservice->pvconn = pvconn;
1830     ofservice->allowed_versions = allowed_versions;
1831
1832     return 0;
1833 }
1834
1835 static void
1836 ofservice_destroy(struct connmgr *mgr, struct ofservice *ofservice)
1837 {
1838     hmap_remove(&mgr->services, &ofservice->node);
1839     pvconn_close(ofservice->pvconn);
1840     free(ofservice);
1841 }
1842
1843 static void
1844 ofservice_reconfigure(struct ofservice *ofservice,
1845                       const struct ofproto_controller *c)
1846 {
1847     ofservice->probe_interval = c->probe_interval;
1848     ofservice->rate_limit = c->rate_limit;
1849     ofservice->burst_limit = c->burst_limit;
1850     ofservice->enable_async_msgs = c->enable_async_msgs;
1851     ofservice->dscp = c->dscp;
1852 }
1853
1854 /* Finds and returns the ofservice within 'mgr' that has the given
1855  * 'target', or a null pointer if none exists. */
1856 static struct ofservice *
1857 ofservice_lookup(struct connmgr *mgr, const char *target)
1858 {
1859     struct ofservice *ofservice;
1860
1861     HMAP_FOR_EACH_WITH_HASH (ofservice, node, hash_string(target, 0),
1862                              &mgr->services) {
1863         if (!strcmp(pvconn_get_name(ofservice->pvconn), target)) {
1864             return ofservice;
1865         }
1866     }
1867     return NULL;
1868 }
1869 \f
1870 /* Flow monitors (NXST_FLOW_MONITOR). */
1871
1872 /* A counter incremented when something significant happens to an OpenFlow
1873  * rule.
1874  *
1875  *     - When a rule is added, its 'add_seqno' and 'modify_seqno' are set to
1876  *       the current value (which is then incremented).
1877  *
1878  *     - When a rule is modified, its 'modify_seqno' is set to the current
1879  *       value (which is then incremented).
1880  *
1881  * Thus, by comparing an old value of monitor_seqno against a rule's
1882  * 'add_seqno', one can tell whether the rule was added before or after the old
1883  * value was read, and similarly for 'modify_seqno'.
1884  *
1885  * 32 bits should normally be sufficient (and would be nice, to save space in
1886  * each rule) but then we'd have to have some special cases for wraparound.
1887  *
1888  * We initialize monitor_seqno to 1 to allow 0 to be used as an invalid
1889  * value. */
1890 static uint64_t monitor_seqno = 1;
1891
1892 COVERAGE_DEFINE(ofmonitor_pause);
1893 COVERAGE_DEFINE(ofmonitor_resume);
1894
1895 enum ofperr
1896 ofmonitor_create(const struct ofputil_flow_monitor_request *request,
1897                  struct ofconn *ofconn, struct ofmonitor **monitorp)
1898     OVS_REQUIRES(ofproto_mutex)
1899 {
1900     struct ofmonitor *m;
1901
1902     *monitorp = NULL;
1903
1904     m = ofmonitor_lookup(ofconn, request->id);
1905     if (m) {
1906         return OFPERR_NXBRC_FM_DUPLICATE_ID;
1907     }
1908
1909     m = xmalloc(sizeof *m);
1910     m->ofconn = ofconn;
1911     hmap_insert(&ofconn->monitors, &m->ofconn_node, hash_int(request->id, 0));
1912     m->id = request->id;
1913     m->flags = request->flags;
1914     m->out_port = request->out_port;
1915     m->table_id = request->table_id;
1916     minimatch_init(&m->match, &request->match);
1917
1918     *monitorp = m;
1919     return 0;
1920 }
1921
1922 struct ofmonitor *
1923 ofmonitor_lookup(struct ofconn *ofconn, uint32_t id)
1924     OVS_REQUIRES(ofproto_mutex)
1925 {
1926     struct ofmonitor *m;
1927
1928     HMAP_FOR_EACH_IN_BUCKET (m, ofconn_node, hash_int(id, 0),
1929                              &ofconn->monitors) {
1930         if (m->id == id) {
1931             return m;
1932         }
1933     }
1934     return NULL;
1935 }
1936
1937 void
1938 ofmonitor_destroy(struct ofmonitor *m)
1939     OVS_REQUIRES(ofproto_mutex)
1940 {
1941     if (m) {
1942         minimatch_destroy(&m->match);
1943         hmap_remove(&m->ofconn->monitors, &m->ofconn_node);
1944         free(m);
1945     }
1946 }
1947
1948 void
1949 ofmonitor_report(struct connmgr *mgr, struct rule *rule,
1950                  enum nx_flow_update_event event,
1951                  enum ofp_flow_removed_reason reason,
1952                  const struct ofconn *abbrev_ofconn, ovs_be32 abbrev_xid)
1953     OVS_REQUIRES(ofproto_mutex)
1954 {
1955     enum nx_flow_monitor_flags update;
1956     struct ofconn *ofconn;
1957
1958     switch (event) {
1959     case NXFME_ADDED:
1960         update = NXFMF_ADD;
1961         rule->add_seqno = rule->modify_seqno = monitor_seqno++;
1962         break;
1963
1964     case NXFME_DELETED:
1965         update = NXFMF_DELETE;
1966         break;
1967
1968     case NXFME_MODIFIED:
1969         update = NXFMF_MODIFY;
1970         rule->modify_seqno = monitor_seqno++;
1971         break;
1972
1973     default:
1974     case NXFME_ABBREV:
1975         OVS_NOT_REACHED();
1976     }
1977
1978     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
1979         enum nx_flow_monitor_flags flags = 0;
1980         struct ofmonitor *m;
1981
1982         if (ofconn->monitor_paused) {
1983             /* Only send NXFME_DELETED notifications for flows that were added
1984              * before we paused. */
1985             if (event != NXFME_DELETED
1986                 || rule->add_seqno > ofconn->monitor_paused) {
1987                 continue;
1988             }
1989         }
1990
1991         HMAP_FOR_EACH (m, ofconn_node, &ofconn->monitors) {
1992             if (m->flags & update
1993                 && (m->table_id == 0xff || m->table_id == rule->table_id)
1994                 && ofoperation_has_out_port(rule->pending, m->out_port)
1995                 && cls_rule_is_loose_match(&rule->cr, &m->match)) {
1996                 flags |= m->flags;
1997             }
1998         }
1999
2000         if (flags) {
2001             if (list_is_empty(&ofconn->updates)) {
2002                 ofputil_start_flow_update(&ofconn->updates);
2003                 ofconn->sent_abbrev_update = false;
2004             }
2005
2006             if (ofconn != abbrev_ofconn || ofconn->monitor_paused) {
2007                 struct ofputil_flow_update fu;
2008                 struct match match;
2009
2010                 fu.event = event;
2011                 fu.reason = event == NXFME_DELETED ? reason : 0;
2012                 fu.table_id = rule->table_id;
2013                 fu.cookie = rule->flow_cookie;
2014                 minimatch_expand(&rule->cr.match, &match);
2015                 fu.match = &match;
2016                 fu.priority = rule->cr.priority;
2017
2018                 ovs_mutex_lock(&rule->mutex);
2019                 fu.idle_timeout = rule->idle_timeout;
2020                 fu.hard_timeout = rule->hard_timeout;
2021                 ovs_mutex_unlock(&rule->mutex);
2022
2023                 if (flags & NXFMF_ACTIONS) {
2024                     fu.ofpacts = rule->actions->ofpacts;
2025                     fu.ofpacts_len = rule->actions->ofpacts_len;
2026                 } else {
2027                     fu.ofpacts = NULL;
2028                     fu.ofpacts_len = 0;
2029                 }
2030                 ofputil_append_flow_update(&fu, &ofconn->updates);
2031             } else if (!ofconn->sent_abbrev_update) {
2032                 struct ofputil_flow_update fu;
2033
2034                 fu.event = NXFME_ABBREV;
2035                 fu.xid = abbrev_xid;
2036                 ofputil_append_flow_update(&fu, &ofconn->updates);
2037
2038                 ofconn->sent_abbrev_update = true;
2039             }
2040         }
2041     }
2042 }
2043
2044 void
2045 ofmonitor_flush(struct connmgr *mgr)
2046     OVS_REQUIRES(ofproto_mutex)
2047 {
2048     struct ofconn *ofconn;
2049
2050     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
2051         struct ofpbuf *msg, *next;
2052
2053         LIST_FOR_EACH_SAFE (msg, next, list_node, &ofconn->updates) {
2054             unsigned int n_bytes;
2055
2056             list_remove(&msg->list_node);
2057             ofconn_send(ofconn, msg, ofconn->monitor_counter);
2058             n_bytes = rconn_packet_counter_n_bytes(ofconn->monitor_counter);
2059             if (!ofconn->monitor_paused && n_bytes > 128 * 1024) {
2060                 struct ofpbuf *pause;
2061
2062                 COVERAGE_INC(ofmonitor_pause);
2063                 ofconn->monitor_paused = monitor_seqno++;
2064                 pause = ofpraw_alloc_xid(OFPRAW_NXT_FLOW_MONITOR_PAUSED,
2065                                          OFP10_VERSION, htonl(0), 0);
2066                 ofconn_send(ofconn, pause, ofconn->monitor_counter);
2067             }
2068         }
2069     }
2070 }
2071
2072 static void
2073 ofmonitor_resume(struct ofconn *ofconn)
2074     OVS_REQUIRES(ofproto_mutex)
2075 {
2076     struct rule_collection rules;
2077     struct ofpbuf *resumed;
2078     struct ofmonitor *m;
2079     struct list msgs;
2080
2081     rule_collection_init(&rules);
2082     HMAP_FOR_EACH (m, ofconn_node, &ofconn->monitors) {
2083         ofmonitor_collect_resume_rules(m, ofconn->monitor_paused, &rules);
2084     }
2085
2086     list_init(&msgs);
2087     ofmonitor_compose_refresh_updates(&rules, &msgs);
2088
2089     resumed = ofpraw_alloc_xid(OFPRAW_NXT_FLOW_MONITOR_RESUMED, OFP10_VERSION,
2090                                htonl(0), 0);
2091     list_push_back(&msgs, &resumed->list_node);
2092     ofconn_send_replies(ofconn, &msgs);
2093
2094     ofconn->monitor_paused = 0;
2095 }
2096
2097 static bool
2098 ofmonitor_may_resume(const struct ofconn *ofconn)
2099     OVS_REQUIRES(ofproto_mutex)
2100 {
2101     return (ofconn->monitor_paused != 0
2102             && !rconn_packet_counter_n_packets(ofconn->monitor_counter));
2103 }
2104
2105 static void
2106 ofmonitor_run(struct connmgr *mgr)
2107 {
2108     struct ofconn *ofconn;
2109
2110     ovs_mutex_lock(&ofproto_mutex);
2111     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
2112         if (ofmonitor_may_resume(ofconn)) {
2113             COVERAGE_INC(ofmonitor_resume);
2114             ofmonitor_resume(ofconn);
2115         }
2116     }
2117     ovs_mutex_unlock(&ofproto_mutex);
2118 }
2119
2120 static void
2121 ofmonitor_wait(struct connmgr *mgr)
2122 {
2123     struct ofconn *ofconn;
2124
2125     ovs_mutex_lock(&ofproto_mutex);
2126     LIST_FOR_EACH (ofconn, node, &mgr->all_conns) {
2127         if (ofmonitor_may_resume(ofconn)) {
2128             poll_immediate_wake();
2129         }
2130     }
2131     ovs_mutex_unlock(&ofproto_mutex);
2132 }