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