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