ofproto-sflow: Maintain table of ports even when clearing configuration.
[sliver-openvswitch.git] / ofproto / ofproto.c
1 /*
2  * Copyright (c) 2009, 2010 Nicira Networks.
3  * Copyright (c) 2010 Jean Tourrilhes - HP-Labs.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at:
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #include <config.h>
19 #include "ofproto.h"
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <net/if.h>
23 #include <netinet/in.h>
24 #include <stdbool.h>
25 #include <stdlib.h>
26 #include "classifier.h"
27 #include "coverage.h"
28 #include "discovery.h"
29 #include "dpif.h"
30 #include "dynamic-string.h"
31 #include "fail-open.h"
32 #include "in-band.h"
33 #include "mac-learning.h"
34 #include "netdev.h"
35 #include "netflow.h"
36 #include "odp-util.h"
37 #include "ofp-print.h"
38 #include "ofproto-sflow.h"
39 #include "ofpbuf.h"
40 #include "openflow/nicira-ext.h"
41 #include "openflow/openflow.h"
42 #include "openvswitch/datapath-protocol.h"
43 #include "packets.h"
44 #include "pinsched.h"
45 #include "pktbuf.h"
46 #include "poll-loop.h"
47 #include "port-array.h"
48 #include "rconn.h"
49 #include "shash.h"
50 #include "status.h"
51 #include "stp.h"
52 #include "stream-ssl.h"
53 #include "svec.h"
54 #include "tag.h"
55 #include "timeval.h"
56 #include "unixctl.h"
57 #include "vconn.h"
58 #include "xtoxll.h"
59
60 #define THIS_MODULE VLM_ofproto
61 #include "vlog.h"
62
63 #include "sflow_api.h"
64
65 enum {
66     TABLEID_HASH = 0,
67     TABLEID_CLASSIFIER = 1
68 };
69
70 struct ofport {
71     struct netdev *netdev;
72     struct ofp_phy_port opp;    /* In host byte order. */
73 };
74
75 static void ofport_free(struct ofport *);
76 static void hton_ofp_phy_port(struct ofp_phy_port *);
77
78 static int xlate_actions(const union ofp_action *in, size_t n_in,
79                          const flow_t *flow, struct ofproto *ofproto,
80                          const struct ofpbuf *packet,
81                          struct odp_actions *out, tag_type *tags,
82                          bool *may_set_up_flow, uint16_t *nf_output_iface);
83
84 struct rule {
85     struct cls_rule cr;
86
87     uint64_t flow_cookie;       /* Controller-issued identifier. 
88                                    (Kept in network-byte order.) */
89     uint16_t idle_timeout;      /* In seconds from time of last use. */
90     uint16_t hard_timeout;      /* In seconds from time of creation. */
91     bool send_flow_removed;     /* Send a flow removed message? */
92     long long int used;         /* Last-used time (0 if never used). */
93     long long int created;      /* Creation time. */
94     uint64_t packet_count;      /* Number of packets received. */
95     uint64_t byte_count;        /* Number of bytes received. */
96     uint64_t accounted_bytes;   /* Number of bytes passed to account_cb. */
97     tag_type tags;              /* Tags (set only by hooks). */
98     struct netflow_flow nf_flow; /* Per-flow NetFlow tracking data. */
99
100     /* If 'super' is non-NULL, this rule is a subrule, that is, it is an
101      * exact-match rule (having cr.wc.wildcards of 0) generated from the
102      * wildcard rule 'super'.  In this case, 'list' is an element of the
103      * super-rule's list.
104      *
105      * If 'super' is NULL, this rule is a super-rule, and 'list' is the head of
106      * a list of subrules.  A super-rule with no wildcards (where
107      * cr.wc.wildcards is 0) will never have any subrules. */
108     struct rule *super;
109     struct list list;
110
111     /* OpenFlow actions.
112      *
113      * 'n_actions' is the number of elements in the 'actions' array.  A single
114      * action may take up more more than one element's worth of space.
115      *
116      * A subrule has no actions (it uses the super-rule's actions). */
117     int n_actions;
118     union ofp_action *actions;
119
120     /* Datapath actions.
121      *
122      * A super-rule with wildcard fields never has ODP actions (since the
123      * datapath only supports exact-match flows). */
124     bool installed;             /* Installed in datapath? */
125     bool may_install;           /* True ordinarily; false if actions must
126                                  * be reassessed for every packet. */
127     int n_odp_actions;
128     union odp_action *odp_actions;
129 };
130
131 static inline bool
132 rule_is_hidden(const struct rule *rule)
133 {
134     /* Subrules are merely an implementation detail, so hide them from the
135      * controller. */
136     if (rule->super != NULL) {
137         return true;
138     }
139
140     /* Rules with priority higher than UINT16_MAX are set up by ofproto itself
141      * (e.g. by in-band control) and are intentionally hidden from the
142      * controller. */
143     if (rule->cr.priority > UINT16_MAX) {
144         return true;
145     }
146
147     return false;
148 }
149
150 static struct rule *rule_create(struct ofproto *, struct rule *super,
151                                 const union ofp_action *, size_t n_actions,
152                                 uint16_t idle_timeout, uint16_t hard_timeout,
153                                 uint64_t flow_cookie, bool send_flow_removed);
154 static void rule_free(struct rule *);
155 static void rule_destroy(struct ofproto *, struct rule *);
156 static struct rule *rule_from_cls_rule(const struct cls_rule *);
157 static void rule_insert(struct ofproto *, struct rule *,
158                         struct ofpbuf *packet, uint16_t in_port);
159 static void rule_remove(struct ofproto *, struct rule *);
160 static bool rule_make_actions(struct ofproto *, struct rule *,
161                               const struct ofpbuf *packet);
162 static void rule_install(struct ofproto *, struct rule *,
163                          struct rule *displaced_rule);
164 static void rule_uninstall(struct ofproto *, struct rule *);
165 static void rule_post_uninstall(struct ofproto *, struct rule *);
166 static void send_flow_removed(struct ofproto *p, struct rule *rule,
167                               long long int now, uint8_t reason);
168
169 /* ofproto supports two kinds of OpenFlow connections:
170  *
171  *   - "Controller connections": Connections to ordinary OpenFlow controllers.
172  *     ofproto maintains persistent connections to these controllers and by
173  *     default sends them asynchronous messages such as packet-ins.
174  *
175  *   - "Transient connections", e.g. from ovs-ofctl.  When these connections
176  *     drop, it is the other side's responsibility to reconnect them if
177  *     necessary.  ofproto does not send them asynchronous messages by default.
178  */
179 enum ofconn_type {
180     OFCONN_CONTROLLER,          /* An OpenFlow controller. */
181     OFCONN_TRANSIENT            /* A transient connection. */
182 };
183
184 /* An OpenFlow connection. */
185 struct ofconn {
186     struct ofproto *ofproto;    /* The ofproto that owns this connection. */
187     struct list node;           /* In struct ofproto's "all_conns" list. */
188     struct rconn *rconn;        /* OpenFlow connection. */
189     enum ofconn_type type;      /* Type. */
190
191     /* OFPT_PACKET_IN related data. */
192     struct rconn_packet_counter *packet_in_counter; /* # queued on 'rconn'. */
193     struct pinsched *schedulers[2]; /* Indexed by reason code; see below. */
194     struct pktbuf *pktbuf;         /* OpenFlow packet buffers. */
195     int miss_send_len;             /* Bytes to send of buffered packets. */
196
197     /* Number of OpenFlow messages queued on 'rconn' as replies to OpenFlow
198      * requests, and the maximum number before we stop reading OpenFlow
199      * requests.  */
200 #define OFCONN_REPLY_MAX 100
201     struct rconn_packet_counter *reply_counter;
202
203     /* type == OFCONN_CONTROLLER only. */
204     enum nx_role role;           /* Role. */
205     struct hmap_node hmap_node;  /* In struct ofproto's "controllers" map. */
206     struct discovery *discovery; /* Controller discovery object, if enabled. */
207     struct status_category *ss;  /* Switch status category. */
208     enum ofproto_band band;      /* In-band or out-of-band? */
209 };
210
211 /* We use OFPR_NO_MATCH and OFPR_ACTION as indexes into struct ofconn's
212  * "schedulers" array.  Their values are 0 and 1, and their meanings and values
213  * coincide with _ODPL_MISS_NR and _ODPL_ACTION_NR, so this is convenient.  In
214  * case anything ever changes, check their values here.  */
215 #define N_SCHEDULERS 2
216 BUILD_ASSERT_DECL(OFPR_NO_MATCH == 0);
217 BUILD_ASSERT_DECL(OFPR_NO_MATCH == _ODPL_MISS_NR);
218 BUILD_ASSERT_DECL(OFPR_ACTION == 1);
219 BUILD_ASSERT_DECL(OFPR_ACTION == _ODPL_ACTION_NR);
220
221 static struct ofconn *ofconn_create(struct ofproto *, struct rconn *,
222                                     enum ofconn_type);
223 static void ofconn_destroy(struct ofconn *);
224 static void ofconn_run(struct ofconn *, struct ofproto *);
225 static void ofconn_wait(struct ofconn *);
226 static bool ofconn_receives_async_msgs(const struct ofconn *);
227
228 static void queue_tx(struct ofpbuf *msg, const struct ofconn *ofconn,
229                      struct rconn_packet_counter *counter);
230
231 static void send_packet_in(struct ofproto *, struct ofpbuf *odp_msg);
232 static void do_send_packet_in(struct ofpbuf *odp_msg, void *ofconn);
233
234 struct ofproto {
235     /* Settings. */
236     uint64_t datapath_id;       /* Datapath ID. */
237     uint64_t fallback_dpid;     /* Datapath ID if no better choice found. */
238     char *mfr_desc;             /* Manufacturer. */
239     char *hw_desc;              /* Hardware. */
240     char *sw_desc;              /* Software version. */
241     char *serial_desc;          /* Serial number. */
242     char *dp_desc;              /* Datapath description. */
243
244     /* Datapath. */
245     struct dpif *dpif;
246     struct netdev_monitor *netdev_monitor;
247     struct port_array ports;    /* Index is ODP port nr; ofport->opp.port_no is
248                                  * OFP port nr. */
249     struct shash port_by_name;
250     uint32_t max_ports;
251
252     /* Configuration. */
253     struct switch_status *switch_status;
254     struct fail_open *fail_open;
255     struct netflow *netflow;
256     struct ofproto_sflow *sflow;
257
258     /* In-band control. */
259     struct in_band *in_band;
260     long long int next_in_band_update;
261     struct sockaddr_in *extra_in_band_remotes;
262     size_t n_extra_remotes;
263
264     /* Flow table. */
265     struct classifier cls;
266     bool need_revalidate;
267     long long int next_expiration;
268     struct tag_set revalidate_set;
269     bool tun_id_from_cookie;
270
271     /* OpenFlow connections. */
272     struct hmap controllers;   /* Controller "struct ofconn"s. */
273     struct list all_conns;     /* Contains "struct ofconn"s. */
274     struct pvconn **listeners;
275     size_t n_listeners;
276     struct pvconn **snoops;
277     size_t n_snoops;
278
279     /* Hooks for ovs-vswitchd. */
280     const struct ofhooks *ofhooks;
281     void *aux;
282
283     /* Used by default ofhooks. */
284     struct mac_learning *ml;
285 };
286
287 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
288
289 static const struct ofhooks default_ofhooks;
290
291 static uint64_t pick_datapath_id(const struct ofproto *);
292 static uint64_t pick_fallback_dpid(void);
293
294 static void update_used(struct ofproto *);
295 static void update_stats(struct ofproto *, struct rule *,
296                          const struct odp_flow_stats *);
297 static void expire_rule(struct cls_rule *, void *ofproto);
298 static void active_timeout(struct ofproto *ofproto, struct rule *rule);
299 static bool revalidate_rule(struct ofproto *p, struct rule *rule);
300 static void revalidate_cb(struct cls_rule *rule_, void *p_);
301
302 static void handle_odp_msg(struct ofproto *, struct ofpbuf *);
303
304 static void handle_openflow(struct ofconn *, struct ofproto *,
305                             struct ofpbuf *);
306
307 static void refresh_port_groups(struct ofproto *);
308
309 static void update_port(struct ofproto *, const char *devname);
310 static int init_ports(struct ofproto *);
311 static void reinit_ports(struct ofproto *);
312
313 int
314 ofproto_create(const char *datapath, const char *datapath_type,
315                const struct ofhooks *ofhooks, void *aux,
316                struct ofproto **ofprotop)
317 {
318     struct odp_stats stats;
319     struct ofproto *p;
320     struct dpif *dpif;
321     int error;
322
323     *ofprotop = NULL;
324
325     /* Connect to datapath and start listening for messages. */
326     error = dpif_open(datapath, datapath_type, &dpif);
327     if (error) {
328         VLOG_ERR("failed to open datapath %s: %s", datapath, strerror(error));
329         return error;
330     }
331     error = dpif_get_dp_stats(dpif, &stats);
332     if (error) {
333         VLOG_ERR("failed to obtain stats for datapath %s: %s",
334                  datapath, strerror(error));
335         dpif_close(dpif);
336         return error;
337     }
338     error = dpif_recv_set_mask(dpif, ODPL_MISS | ODPL_ACTION | ODPL_SFLOW);
339     if (error) {
340         VLOG_ERR("failed to listen on datapath %s: %s",
341                  datapath, strerror(error));
342         dpif_close(dpif);
343         return error;
344     }
345     dpif_flow_flush(dpif);
346     dpif_recv_purge(dpif);
347
348     /* Initialize settings. */
349     p = xzalloc(sizeof *p);
350     p->fallback_dpid = pick_fallback_dpid();
351     p->datapath_id = p->fallback_dpid;
352     p->mfr_desc = xstrdup(DEFAULT_MFR_DESC);
353     p->hw_desc = xstrdup(DEFAULT_HW_DESC);
354     p->sw_desc = xstrdup(DEFAULT_SW_DESC);
355     p->serial_desc = xstrdup(DEFAULT_SERIAL_DESC);
356     p->dp_desc = xstrdup(DEFAULT_DP_DESC);
357
358     /* Initialize datapath. */
359     p->dpif = dpif;
360     p->netdev_monitor = netdev_monitor_create();
361     port_array_init(&p->ports);
362     shash_init(&p->port_by_name);
363     p->max_ports = stats.max_ports;
364
365     /* Initialize submodules. */
366     p->switch_status = switch_status_create(p);
367     p->in_band = NULL;
368     p->fail_open = NULL;
369     p->netflow = NULL;
370     p->sflow = NULL;
371
372     /* Initialize flow table. */
373     classifier_init(&p->cls);
374     p->need_revalidate = false;
375     p->next_expiration = time_msec() + 1000;
376     tag_set_init(&p->revalidate_set);
377
378     /* Initialize OpenFlow connections. */
379     list_init(&p->all_conns);
380     hmap_init(&p->controllers);
381     p->listeners = NULL;
382     p->n_listeners = 0;
383     p->snoops = NULL;
384     p->n_snoops = 0;
385
386     /* Initialize hooks. */
387     if (ofhooks) {
388         p->ofhooks = ofhooks;
389         p->aux = aux;
390         p->ml = NULL;
391     } else {
392         p->ofhooks = &default_ofhooks;
393         p->aux = p;
394         p->ml = mac_learning_create();
395     }
396
397     /* Pick final datapath ID. */
398     p->datapath_id = pick_datapath_id(p);
399     VLOG_INFO("using datapath ID %016"PRIx64, p->datapath_id);
400
401     *ofprotop = p;
402     return 0;
403 }
404
405 void
406 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
407 {
408     uint64_t old_dpid = p->datapath_id;
409     p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
410     if (p->datapath_id != old_dpid) {
411         struct ofconn *ofconn;
412
413         VLOG_INFO("datapath ID changed to %016"PRIx64, p->datapath_id);
414
415         /* Force all active connections to reconnect, since there is no way to
416          * notify a controller that the datapath ID has changed. */
417         LIST_FOR_EACH (ofconn, struct ofconn, node, &p->all_conns) {
418             rconn_reconnect(ofconn->rconn);
419         }
420     }
421 }
422
423 static bool
424 is_discovery_controller(const struct ofproto_controller *c)
425 {
426     return !strcmp(c->target, "discover");
427 }
428
429 static bool
430 is_in_band_controller(const struct ofproto_controller *c)
431 {
432     return is_discovery_controller(c) || c->band == OFPROTO_IN_BAND;
433 }
434
435 /* Creates a new controller in 'ofproto'.  Some of the settings are initially
436  * drawn from 'c', but update_controller() needs to be called later to finish
437  * the new ofconn's configuration. */
438 static void
439 add_controller(struct ofproto *ofproto, const struct ofproto_controller *c)
440 {
441     struct discovery *discovery;
442     struct ofconn *ofconn;
443
444     if (is_discovery_controller(c)) {
445         int error = discovery_create(c->accept_re, c->update_resolv_conf,
446                                      ofproto->dpif, ofproto->switch_status,
447                                      &discovery);
448         if (error) {
449             return;
450         }
451     } else {
452         discovery = NULL;
453     }
454
455     ofconn = ofconn_create(ofproto, rconn_create(5, 8), OFCONN_CONTROLLER);
456     ofconn->pktbuf = pktbuf_create();
457     ofconn->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
458     if (discovery) {
459         ofconn->discovery = discovery;
460     } else {
461         rconn_connect(ofconn->rconn, c->target);
462     }
463     hmap_insert(&ofproto->controllers, &ofconn->hmap_node,
464                 hash_string(c->target, 0));
465 }
466
467 /* Reconfigures 'ofconn' to match 'c'.  This function cannot update an ofconn's
468  * target or turn discovery on or off (these are done by creating new ofconns
469  * and deleting old ones), but it can update the rest of an ofconn's
470  * settings. */
471 static void
472 update_controller(struct ofconn *ofconn, const struct ofproto_controller *c)
473 {
474     struct ofproto *ofproto = ofconn->ofproto;
475     int probe_interval;
476     int i;
477
478     ofconn->band = (is_in_band_controller(c)
479                     ? OFPROTO_IN_BAND : OFPROTO_OUT_OF_BAND);
480
481     rconn_set_max_backoff(ofconn->rconn, c->max_backoff);
482
483     probe_interval = c->probe_interval ? MAX(c->probe_interval, 5) : 0;
484     rconn_set_probe_interval(ofconn->rconn, probe_interval);
485
486     if (ofconn->discovery) {
487         discovery_set_update_resolv_conf(ofconn->discovery,
488                                          c->update_resolv_conf);
489         discovery_set_accept_controller_re(ofconn->discovery, c->accept_re);
490     }
491
492     for (i = 0; i < N_SCHEDULERS; i++) {
493         struct pinsched **s = &ofconn->schedulers[i];
494
495         if (c->rate_limit > 0) {
496             if (!*s) {
497                 *s = pinsched_create(c->rate_limit, c->burst_limit,
498                                      ofproto->switch_status);
499             } else {
500                 pinsched_set_limits(*s, c->rate_limit, c->burst_limit);
501             }
502         } else {
503             pinsched_destroy(*s);
504             *s = NULL;
505         }
506     }
507 }
508
509 static const char *
510 ofconn_get_target(const struct ofconn *ofconn)
511 {
512     return ofconn->discovery ? "discover" : rconn_get_name(ofconn->rconn);
513 }
514
515 static struct ofconn *
516 find_controller_by_target(struct ofproto *ofproto, const char *target)
517 {
518     struct ofconn *ofconn;
519
520     HMAP_FOR_EACH_WITH_HASH (ofconn, struct ofconn, hmap_node,
521                              hash_string(target, 0), &ofproto->controllers) {
522         if (!strcmp(ofconn_get_target(ofconn), target)) {
523             return ofconn;
524         }
525     }
526     return NULL;
527 }
528
529 static void
530 update_in_band_remotes(struct ofproto *ofproto)
531 {
532     const struct ofconn *ofconn;
533     struct sockaddr_in *addrs;
534     size_t max_addrs, n_addrs;
535     bool discovery;
536     size_t i;
537
538     /* Allocate enough memory for as many remotes as we could possibly have. */
539     max_addrs = ofproto->n_extra_remotes + hmap_count(&ofproto->controllers);
540     addrs = xmalloc(max_addrs * sizeof *addrs);
541     n_addrs = 0;
542
543     /* Add all the remotes. */
544     discovery = false;
545     HMAP_FOR_EACH (ofconn, struct ofconn, hmap_node, &ofproto->controllers) {
546         struct sockaddr_in *sin = &addrs[n_addrs];
547
548         sin->sin_addr.s_addr = rconn_get_remote_ip(ofconn->rconn);
549         if (sin->sin_addr.s_addr) {
550             sin->sin_port = rconn_get_remote_port(ofconn->rconn);
551             n_addrs++;
552         }
553         if (ofconn->discovery) {
554             discovery = true;
555         }
556     }
557     for (i = 0; i < ofproto->n_extra_remotes; i++) {
558         addrs[n_addrs++] = ofproto->extra_in_band_remotes[i];
559     }
560
561     /* Create or update or destroy in-band.
562      *
563      * Ordinarily we only enable in-band if there's at least one remote
564      * address, but discovery needs the in-band rules for DHCP to be installed
565      * even before we know any remote addresses. */
566     if (n_addrs || discovery) {
567         if (!ofproto->in_band) {
568             in_band_create(ofproto, ofproto->dpif, ofproto->switch_status,
569                            &ofproto->in_band);
570         }
571         in_band_set_remotes(ofproto->in_band, addrs, n_addrs);
572         ofproto->next_in_band_update = time_msec() + 1000;
573     } else {
574         in_band_destroy(ofproto->in_band);
575         ofproto->in_band = NULL;
576     }
577
578     /* Clean up. */
579     free(addrs);
580 }
581
582 void
583 ofproto_set_controllers(struct ofproto *p,
584                         const struct ofproto_controller *controllers,
585                         size_t n_controllers)
586 {
587     struct shash new_controllers;
588     enum ofproto_fail_mode fail_mode;
589     struct ofconn *ofconn, *next;
590     bool ss_exists;
591     size_t i;
592
593     shash_init(&new_controllers);
594     for (i = 0; i < n_controllers; i++) {
595         const struct ofproto_controller *c = &controllers[i];
596
597         shash_add_once(&new_controllers, c->target, &controllers[i]);
598         if (!find_controller_by_target(p, c->target)) {
599             add_controller(p, c);
600         }
601     }
602
603     fail_mode = OFPROTO_FAIL_STANDALONE;
604     ss_exists = false;
605     HMAP_FOR_EACH_SAFE (ofconn, next, struct ofconn, hmap_node,
606                         &p->controllers) {
607         struct ofproto_controller *c;
608
609         c = shash_find_data(&new_controllers, ofconn_get_target(ofconn));
610         if (!c) {
611             ofconn_destroy(ofconn);
612         } else {
613             update_controller(ofconn, c);
614             if (ofconn->ss) {
615                 ss_exists = true;
616             }
617             if (c->fail == OFPROTO_FAIL_SECURE) {
618                 fail_mode = OFPROTO_FAIL_SECURE;
619             }
620         }
621     }
622     shash_destroy(&new_controllers);
623
624     update_in_band_remotes(p);
625
626     if (!hmap_is_empty(&p->controllers)
627         && fail_mode == OFPROTO_FAIL_STANDALONE) {
628         struct rconn **rconns;
629         size_t n;
630
631         if (!p->fail_open) {
632             p->fail_open = fail_open_create(p, p->switch_status);
633         }
634
635         n = 0;
636         rconns = xmalloc(hmap_count(&p->controllers) * sizeof *rconns);
637         HMAP_FOR_EACH (ofconn, struct ofconn, hmap_node, &p->controllers) {
638             rconns[n++] = ofconn->rconn;
639         }
640
641         fail_open_set_controllers(p->fail_open, rconns, n);
642         /* p->fail_open takes ownership of 'rconns'. */
643     } else {
644         fail_open_destroy(p->fail_open);
645         p->fail_open = NULL;
646     }
647
648     if (!hmap_is_empty(&p->controllers) && !ss_exists) {
649         ofconn = CONTAINER_OF(hmap_first(&p->controllers),
650                               struct ofconn, hmap_node);
651         ofconn->ss = switch_status_register(p->switch_status, "remote",
652                                             rconn_status_cb, ofconn->rconn);
653     }
654 }
655
656 static bool
657 any_extras_changed(const struct ofproto *ofproto,
658                    const struct sockaddr_in *extras, size_t n)
659 {
660     size_t i;
661
662     if (n != ofproto->n_extra_remotes) {
663         return true;
664     }
665
666     for (i = 0; i < n; i++) {
667         const struct sockaddr_in *old = &ofproto->extra_in_band_remotes[i];
668         const struct sockaddr_in *new = &extras[i];
669
670         if (old->sin_addr.s_addr != new->sin_addr.s_addr ||
671             old->sin_port != new->sin_port) {
672             return true;
673         }
674     }
675
676     return false;
677 }
678
679 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
680  * in-band control should guarantee access, in the same way that in-band
681  * control guarantees access to OpenFlow controllers. */
682 void
683 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
684                                   const struct sockaddr_in *extras, size_t n)
685 {
686     if (!any_extras_changed(ofproto, extras, n)) {
687         return;
688     }
689
690     free(ofproto->extra_in_band_remotes);
691     ofproto->n_extra_remotes = n;
692     ofproto->extra_in_band_remotes = xmemdup(extras, n * sizeof *extras);
693
694     update_in_band_remotes(ofproto);
695 }
696
697 void
698 ofproto_set_desc(struct ofproto *p,
699                  const char *mfr_desc, const char *hw_desc,
700                  const char *sw_desc, const char *serial_desc,
701                  const char *dp_desc)
702 {
703     struct ofp_desc_stats *ods;
704
705     if (mfr_desc) {
706         if (strlen(mfr_desc) >= sizeof ods->mfr_desc) {
707             VLOG_WARN("truncating mfr_desc, must be less than %zu characters",
708                     sizeof ods->mfr_desc);
709         }
710         free(p->mfr_desc);
711         p->mfr_desc = xstrdup(mfr_desc);
712     }
713     if (hw_desc) {
714         if (strlen(hw_desc) >= sizeof ods->hw_desc) {
715             VLOG_WARN("truncating hw_desc, must be less than %zu characters",
716                     sizeof ods->hw_desc);
717         }
718         free(p->hw_desc);
719         p->hw_desc = xstrdup(hw_desc);
720     }
721     if (sw_desc) {
722         if (strlen(sw_desc) >= sizeof ods->sw_desc) {
723             VLOG_WARN("truncating sw_desc, must be less than %zu characters",
724                     sizeof ods->sw_desc);
725         }
726         free(p->sw_desc);
727         p->sw_desc = xstrdup(sw_desc);
728     }
729     if (serial_desc) {
730         if (strlen(serial_desc) >= sizeof ods->serial_num) {
731             VLOG_WARN("truncating serial_desc, must be less than %zu "
732                     "characters",
733                     sizeof ods->serial_num);
734         }
735         free(p->serial_desc);
736         p->serial_desc = xstrdup(serial_desc);
737     }
738     if (dp_desc) {
739         if (strlen(dp_desc) >= sizeof ods->dp_desc) {
740             VLOG_WARN("truncating dp_desc, must be less than %zu characters",
741                     sizeof ods->dp_desc);
742         }
743         free(p->dp_desc);
744         p->dp_desc = xstrdup(dp_desc);
745     }
746 }
747
748 static int
749 set_pvconns(struct pvconn ***pvconnsp, size_t *n_pvconnsp,
750             const struct svec *svec)
751 {
752     struct pvconn **pvconns = *pvconnsp;
753     size_t n_pvconns = *n_pvconnsp;
754     int retval = 0;
755     size_t i;
756
757     for (i = 0; i < n_pvconns; i++) {
758         pvconn_close(pvconns[i]);
759     }
760     free(pvconns);
761
762     pvconns = xmalloc(svec->n * sizeof *pvconns);
763     n_pvconns = 0;
764     for (i = 0; i < svec->n; i++) {
765         const char *name = svec->names[i];
766         struct pvconn *pvconn;
767         int error;
768
769         error = pvconn_open(name, &pvconn);
770         if (!error) {
771             pvconns[n_pvconns++] = pvconn;
772         } else {
773             VLOG_ERR("failed to listen on %s: %s", name, strerror(error));
774             if (!retval) {
775                 retval = error;
776             }
777         }
778     }
779
780     *pvconnsp = pvconns;
781     *n_pvconnsp = n_pvconns;
782
783     return retval;
784 }
785
786 int
787 ofproto_set_listeners(struct ofproto *ofproto, const struct svec *listeners)
788 {
789     return set_pvconns(&ofproto->listeners, &ofproto->n_listeners, listeners);
790 }
791
792 int
793 ofproto_set_snoops(struct ofproto *ofproto, const struct svec *snoops)
794 {
795     return set_pvconns(&ofproto->snoops, &ofproto->n_snoops, snoops);
796 }
797
798 int
799 ofproto_set_netflow(struct ofproto *ofproto,
800                     const struct netflow_options *nf_options)
801 {
802     if (nf_options && nf_options->collectors.n) {
803         if (!ofproto->netflow) {
804             ofproto->netflow = netflow_create();
805         }
806         return netflow_set_options(ofproto->netflow, nf_options);
807     } else {
808         netflow_destroy(ofproto->netflow);
809         ofproto->netflow = NULL;
810         return 0;
811     }
812 }
813
814 void
815 ofproto_set_sflow(struct ofproto *ofproto,
816                   const struct ofproto_sflow_options *oso)
817 {
818     struct ofproto_sflow *os = ofproto->sflow;
819     if (oso) {
820         if (!os) {
821             struct ofport *ofport;
822             unsigned int odp_port;
823
824             os = ofproto->sflow = ofproto_sflow_create(ofproto->dpif);
825             refresh_port_groups(ofproto);
826             PORT_ARRAY_FOR_EACH (ofport, &ofproto->ports, odp_port) {
827                 ofproto_sflow_add_port(os, odp_port,
828                                        netdev_get_name(ofport->netdev));
829             }
830         }
831         ofproto_sflow_set_options(os, oso);
832     } else {
833         ofproto_sflow_destroy(os);
834         ofproto->sflow = NULL;
835     }
836 }
837
838 int
839 ofproto_set_stp(struct ofproto *ofproto OVS_UNUSED, bool enable_stp)
840 {
841     /* XXX */
842     if (enable_stp) {
843         VLOG_WARN("STP is not yet implemented");
844         return EINVAL;
845     } else {
846         return 0;
847     }
848 }
849
850 uint64_t
851 ofproto_get_datapath_id(const struct ofproto *ofproto)
852 {
853     return ofproto->datapath_id;
854 }
855
856 bool
857 ofproto_has_controller(const struct ofproto *ofproto)
858 {
859     return !hmap_is_empty(&ofproto->controllers);
860 }
861
862 void
863 ofproto_get_listeners(const struct ofproto *ofproto, struct svec *listeners)
864 {
865     size_t i;
866
867     for (i = 0; i < ofproto->n_listeners; i++) {
868         svec_add(listeners, pvconn_get_name(ofproto->listeners[i]));
869     }
870 }
871
872 void
873 ofproto_get_snoops(const struct ofproto *ofproto, struct svec *snoops)
874 {
875     size_t i;
876
877     for (i = 0; i < ofproto->n_snoops; i++) {
878         svec_add(snoops, pvconn_get_name(ofproto->snoops[i]));
879     }
880 }
881
882 void
883 ofproto_destroy(struct ofproto *p)
884 {
885     struct ofconn *ofconn, *next_ofconn;
886     struct ofport *ofport;
887     unsigned int port_no;
888     size_t i;
889
890     if (!p) {
891         return;
892     }
893
894     /* Destroy fail-open and in-band early, since they touch the classifier. */
895     fail_open_destroy(p->fail_open);
896     p->fail_open = NULL;
897
898     in_band_destroy(p->in_band);
899     p->in_band = NULL;
900     free(p->extra_in_band_remotes);
901
902     ofproto_flush_flows(p);
903     classifier_destroy(&p->cls);
904
905     LIST_FOR_EACH_SAFE (ofconn, next_ofconn, struct ofconn, node,
906                         &p->all_conns) {
907         ofconn_destroy(ofconn);
908     }
909     hmap_destroy(&p->controllers);
910
911     dpif_close(p->dpif);
912     netdev_monitor_destroy(p->netdev_monitor);
913     PORT_ARRAY_FOR_EACH (ofport, &p->ports, port_no) {
914         ofport_free(ofport);
915     }
916     shash_destroy(&p->port_by_name);
917
918     switch_status_destroy(p->switch_status);
919     netflow_destroy(p->netflow);
920     ofproto_sflow_destroy(p->sflow);
921
922     for (i = 0; i < p->n_listeners; i++) {
923         pvconn_close(p->listeners[i]);
924     }
925     free(p->listeners);
926
927     for (i = 0; i < p->n_snoops; i++) {
928         pvconn_close(p->snoops[i]);
929     }
930     free(p->snoops);
931
932     mac_learning_destroy(p->ml);
933
934     free(p->mfr_desc);
935     free(p->hw_desc);
936     free(p->sw_desc);
937     free(p->serial_desc);
938     free(p->dp_desc);
939
940     port_array_destroy(&p->ports);
941
942     free(p);
943 }
944
945 int
946 ofproto_run(struct ofproto *p)
947 {
948     int error = ofproto_run1(p);
949     if (!error) {
950         error = ofproto_run2(p, false);
951     }
952     return error;
953 }
954
955 static void
956 process_port_change(struct ofproto *ofproto, int error, char *devname)
957 {
958     if (error == ENOBUFS) {
959         reinit_ports(ofproto);
960     } else if (!error) {
961         update_port(ofproto, devname);
962         free(devname);
963     }
964 }
965
966 /* One of ofproto's "snoop" pvconns has accepted a new connection on 'vconn'.
967  * Connects this vconn to a controller. */
968 static void
969 add_snooper(struct ofproto *ofproto, struct vconn *vconn)
970 {
971     struct ofconn *ofconn;
972
973     /* Arbitrarily pick the first controller in the list for monitoring.  We
974      * could do something smarter or more flexible later, if it ever proves
975      * useful. */
976     LIST_FOR_EACH (ofconn, struct ofconn, node, &ofproto->all_conns) {
977         if (ofconn->type == OFCONN_CONTROLLER) {
978             rconn_add_monitor(ofconn->rconn, vconn);
979             return;
980         }
981
982     }
983     VLOG_INFO_RL(&rl, "no controller connection to monitor");
984     vconn_close(vconn);
985 }
986
987 int
988 ofproto_run1(struct ofproto *p)
989 {
990     struct ofconn *ofconn, *next_ofconn;
991     char *devname;
992     int error;
993     int i;
994
995     if (shash_is_empty(&p->port_by_name)) {
996         init_ports(p);
997     }
998
999     for (i = 0; i < 50; i++) {
1000         struct ofpbuf *buf;
1001         int error;
1002
1003         error = dpif_recv(p->dpif, &buf);
1004         if (error) {
1005             if (error == ENODEV) {
1006                 /* Someone destroyed the datapath behind our back.  The caller
1007                  * better destroy us and give up, because we're just going to
1008                  * spin from here on out. */
1009                 static struct vlog_rate_limit rl2 = VLOG_RATE_LIMIT_INIT(1, 5);
1010                 VLOG_ERR_RL(&rl2, "%s: datapath was destroyed externally",
1011                             dpif_name(p->dpif));
1012                 return ENODEV;
1013             }
1014             break;
1015         }
1016
1017         handle_odp_msg(p, buf);
1018     }
1019
1020     while ((error = dpif_port_poll(p->dpif, &devname)) != EAGAIN) {
1021         process_port_change(p, error, devname);
1022     }
1023     while ((error = netdev_monitor_poll(p->netdev_monitor,
1024                                         &devname)) != EAGAIN) {
1025         process_port_change(p, error, devname);
1026     }
1027
1028     if (p->in_band) {
1029         if (time_msec() >= p->next_in_band_update) {
1030             update_in_band_remotes(p);
1031         }
1032         in_band_run(p->in_band);
1033     }
1034
1035     LIST_FOR_EACH_SAFE (ofconn, next_ofconn, struct ofconn, node,
1036                         &p->all_conns) {
1037         ofconn_run(ofconn, p);
1038     }
1039
1040     /* Fail-open maintenance.  Do this after processing the ofconns since
1041      * fail-open checks the status of the controller rconn. */
1042     if (p->fail_open) {
1043         fail_open_run(p->fail_open);
1044     }
1045
1046     for (i = 0; i < p->n_listeners; i++) {
1047         struct vconn *vconn;
1048         int retval;
1049
1050         retval = pvconn_accept(p->listeners[i], OFP_VERSION, &vconn);
1051         if (!retval) {
1052             ofconn_create(p, rconn_new_from_vconn("passive", vconn),
1053                           OFCONN_TRANSIENT);
1054         } else if (retval != EAGAIN) {
1055             VLOG_WARN_RL(&rl, "accept failed (%s)", strerror(retval));
1056         }
1057     }
1058
1059     for (i = 0; i < p->n_snoops; i++) {
1060         struct vconn *vconn;
1061         int retval;
1062
1063         retval = pvconn_accept(p->snoops[i], OFP_VERSION, &vconn);
1064         if (!retval) {
1065             add_snooper(p, vconn);
1066         } else if (retval != EAGAIN) {
1067             VLOG_WARN_RL(&rl, "accept failed (%s)", strerror(retval));
1068         }
1069     }
1070
1071     if (time_msec() >= p->next_expiration) {
1072         COVERAGE_INC(ofproto_expiration);
1073         p->next_expiration = time_msec() + 1000;
1074         update_used(p);
1075
1076         classifier_for_each(&p->cls, CLS_INC_ALL, expire_rule, p);
1077
1078         /* Let the hook know that we're at a stable point: all outstanding data
1079          * in existing flows has been accounted to the account_cb.  Thus, the
1080          * hook can now reasonably do operations that depend on having accurate
1081          * flow volume accounting (currently, that's just bond rebalancing). */
1082         if (p->ofhooks->account_checkpoint_cb) {
1083             p->ofhooks->account_checkpoint_cb(p->aux);
1084         }
1085     }
1086
1087     if (p->netflow) {
1088         netflow_run(p->netflow);
1089     }
1090     if (p->sflow) {
1091         ofproto_sflow_run(p->sflow);
1092     }
1093
1094     return 0;
1095 }
1096
1097 struct revalidate_cbdata {
1098     struct ofproto *ofproto;
1099     bool revalidate_all;        /* Revalidate all exact-match rules? */
1100     bool revalidate_subrules;   /* Revalidate all exact-match subrules? */
1101     struct tag_set revalidate_set; /* Set of tags to revalidate. */
1102 };
1103
1104 int
1105 ofproto_run2(struct ofproto *p, bool revalidate_all)
1106 {
1107     if (p->need_revalidate || revalidate_all
1108         || !tag_set_is_empty(&p->revalidate_set)) {
1109         struct revalidate_cbdata cbdata;
1110         cbdata.ofproto = p;
1111         cbdata.revalidate_all = revalidate_all;
1112         cbdata.revalidate_subrules = p->need_revalidate;
1113         cbdata.revalidate_set = p->revalidate_set;
1114         tag_set_init(&p->revalidate_set);
1115         COVERAGE_INC(ofproto_revalidate);
1116         classifier_for_each(&p->cls, CLS_INC_EXACT, revalidate_cb, &cbdata);
1117         p->need_revalidate = false;
1118     }
1119
1120     return 0;
1121 }
1122
1123 void
1124 ofproto_wait(struct ofproto *p)
1125 {
1126     struct ofconn *ofconn;
1127     size_t i;
1128
1129     dpif_recv_wait(p->dpif);
1130     dpif_port_poll_wait(p->dpif);
1131     netdev_monitor_poll_wait(p->netdev_monitor);
1132     LIST_FOR_EACH (ofconn, struct ofconn, node, &p->all_conns) {
1133         ofconn_wait(ofconn);
1134     }
1135     if (p->in_band) {
1136         poll_timer_wait(p->next_in_band_update - time_msec());
1137         in_band_wait(p->in_band);
1138     }
1139     if (p->fail_open) {
1140         fail_open_wait(p->fail_open);
1141     }
1142     if (p->sflow) {
1143         ofproto_sflow_wait(p->sflow);
1144     }
1145     if (!tag_set_is_empty(&p->revalidate_set)) {
1146         poll_immediate_wake();
1147     }
1148     if (p->need_revalidate) {
1149         /* Shouldn't happen, but if it does just go around again. */
1150         VLOG_DBG_RL(&rl, "need revalidate in ofproto_wait_cb()");
1151         poll_immediate_wake();
1152     } else if (p->next_expiration != LLONG_MAX) {
1153         poll_timer_wait(p->next_expiration - time_msec());
1154     }
1155     for (i = 0; i < p->n_listeners; i++) {
1156         pvconn_wait(p->listeners[i]);
1157     }
1158     for (i = 0; i < p->n_snoops; i++) {
1159         pvconn_wait(p->snoops[i]);
1160     }
1161 }
1162
1163 void
1164 ofproto_revalidate(struct ofproto *ofproto, tag_type tag)
1165 {
1166     tag_set_add(&ofproto->revalidate_set, tag);
1167 }
1168
1169 struct tag_set *
1170 ofproto_get_revalidate_set(struct ofproto *ofproto)
1171 {
1172     return &ofproto->revalidate_set;
1173 }
1174
1175 bool
1176 ofproto_is_alive(const struct ofproto *p)
1177 {
1178     return !hmap_is_empty(&p->controllers);
1179 }
1180
1181 int
1182 ofproto_send_packet(struct ofproto *p, const flow_t *flow,
1183                     const union ofp_action *actions, size_t n_actions,
1184                     const struct ofpbuf *packet)
1185 {
1186     struct odp_actions odp_actions;
1187     int error;
1188
1189     error = xlate_actions(actions, n_actions, flow, p, packet, &odp_actions,
1190                           NULL, NULL, NULL);
1191     if (error) {
1192         return error;
1193     }
1194
1195     /* XXX Should we translate the dpif_execute() errno value into an OpenFlow
1196      * error code? */
1197     dpif_execute(p->dpif, flow->in_port, odp_actions.actions,
1198                  odp_actions.n_actions, packet);
1199     return 0;
1200 }
1201
1202 void
1203 ofproto_add_flow(struct ofproto *p,
1204                  const flow_t *flow, uint32_t wildcards, unsigned int priority,
1205                  const union ofp_action *actions, size_t n_actions,
1206                  int idle_timeout)
1207 {
1208     struct rule *rule;
1209     rule = rule_create(p, NULL, actions, n_actions,
1210                        idle_timeout >= 0 ? idle_timeout : 5 /* XXX */, 
1211                        0, 0, false);
1212     cls_rule_from_flow(flow, wildcards, priority, &rule->cr);
1213     rule_insert(p, rule, NULL, 0);
1214 }
1215
1216 void
1217 ofproto_delete_flow(struct ofproto *ofproto, const flow_t *flow,
1218                     uint32_t wildcards, unsigned int priority)
1219 {
1220     struct rule *rule;
1221
1222     rule = rule_from_cls_rule(classifier_find_rule_exactly(&ofproto->cls,
1223                                                            flow, wildcards,
1224                                                            priority));
1225     if (rule) {
1226         rule_remove(ofproto, rule);
1227     }
1228 }
1229
1230 static void
1231 destroy_rule(struct cls_rule *rule_, void *ofproto_)
1232 {
1233     struct rule *rule = rule_from_cls_rule(rule_);
1234     struct ofproto *ofproto = ofproto_;
1235
1236     /* Mark the flow as not installed, even though it might really be
1237      * installed, so that rule_remove() doesn't bother trying to uninstall it.
1238      * There is no point in uninstalling it individually since we are about to
1239      * blow away all the flows with dpif_flow_flush(). */
1240     rule->installed = false;
1241
1242     rule_remove(ofproto, rule);
1243 }
1244
1245 void
1246 ofproto_flush_flows(struct ofproto *ofproto)
1247 {
1248     COVERAGE_INC(ofproto_flush);
1249     classifier_for_each(&ofproto->cls, CLS_INC_ALL, destroy_rule, ofproto);
1250     dpif_flow_flush(ofproto->dpif);
1251     if (ofproto->in_band) {
1252         in_band_flushed(ofproto->in_band);
1253     }
1254     if (ofproto->fail_open) {
1255         fail_open_flushed(ofproto->fail_open);
1256     }
1257 }
1258 \f
1259 static void
1260 reinit_ports(struct ofproto *p)
1261 {
1262     struct svec devnames;
1263     struct ofport *ofport;
1264     unsigned int port_no;
1265     struct odp_port *odp_ports;
1266     size_t n_odp_ports;
1267     size_t i;
1268
1269     svec_init(&devnames);
1270     PORT_ARRAY_FOR_EACH (ofport, &p->ports, port_no) {
1271         svec_add (&devnames, (char *) ofport->opp.name);
1272     }
1273     dpif_port_list(p->dpif, &odp_ports, &n_odp_ports);
1274     for (i = 0; i < n_odp_ports; i++) {
1275         svec_add (&devnames, odp_ports[i].devname);
1276     }
1277     free(odp_ports);
1278
1279     svec_sort_unique(&devnames);
1280     for (i = 0; i < devnames.n; i++) {
1281         update_port(p, devnames.names[i]);
1282     }
1283     svec_destroy(&devnames);
1284 }
1285
1286 static size_t
1287 refresh_port_group(struct ofproto *p, unsigned int group)
1288 {
1289     uint16_t *ports;
1290     size_t n_ports;
1291     struct ofport *port;
1292     unsigned int port_no;
1293
1294     assert(group == DP_GROUP_ALL || group == DP_GROUP_FLOOD);
1295
1296     ports = xmalloc(port_array_count(&p->ports) * sizeof *ports);
1297     n_ports = 0;
1298     PORT_ARRAY_FOR_EACH (port, &p->ports, port_no) {
1299         if (group == DP_GROUP_ALL || !(port->opp.config & OFPPC_NO_FLOOD)) {
1300             ports[n_ports++] = port_no;
1301         }
1302     }
1303     dpif_port_group_set(p->dpif, group, ports, n_ports);
1304     free(ports);
1305
1306     return n_ports;
1307 }
1308
1309 static void
1310 refresh_port_groups(struct ofproto *p)
1311 {
1312     size_t n_flood = refresh_port_group(p, DP_GROUP_FLOOD);
1313     size_t n_all = refresh_port_group(p, DP_GROUP_ALL);
1314     if (p->sflow) {
1315         ofproto_sflow_set_group_sizes(p->sflow, n_flood, n_all);
1316     }
1317 }
1318
1319 static struct ofport *
1320 make_ofport(const struct odp_port *odp_port)
1321 {
1322     struct netdev_options netdev_options;
1323     enum netdev_flags flags;
1324     struct ofport *ofport;
1325     struct netdev *netdev;
1326     bool carrier;
1327     int error;
1328
1329     memset(&netdev_options, 0, sizeof netdev_options);
1330     netdev_options.name = odp_port->devname;
1331     netdev_options.ethertype = NETDEV_ETH_TYPE_NONE;
1332     netdev_options.may_open = true;
1333
1334     error = netdev_open(&netdev_options, &netdev);
1335     if (error) {
1336         VLOG_WARN_RL(&rl, "ignoring port %s (%"PRIu16") because netdev %s "
1337                      "cannot be opened (%s)",
1338                      odp_port->devname, odp_port->port,
1339                      odp_port->devname, strerror(error));
1340         return NULL;
1341     }
1342
1343     ofport = xmalloc(sizeof *ofport);
1344     ofport->netdev = netdev;
1345     ofport->opp.port_no = odp_port_to_ofp_port(odp_port->port);
1346     netdev_get_etheraddr(netdev, ofport->opp.hw_addr);
1347     memcpy(ofport->opp.name, odp_port->devname,
1348            MIN(sizeof ofport->opp.name, sizeof odp_port->devname));
1349     ofport->opp.name[sizeof ofport->opp.name - 1] = '\0';
1350
1351     netdev_get_flags(netdev, &flags);
1352     ofport->opp.config = flags & NETDEV_UP ? 0 : OFPPC_PORT_DOWN;
1353
1354     netdev_get_carrier(netdev, &carrier);
1355     ofport->opp.state = carrier ? 0 : OFPPS_LINK_DOWN;
1356
1357     netdev_get_features(netdev,
1358                         &ofport->opp.curr, &ofport->opp.advertised,
1359                         &ofport->opp.supported, &ofport->opp.peer);
1360     return ofport;
1361 }
1362
1363 static bool
1364 ofport_conflicts(const struct ofproto *p, const struct odp_port *odp_port)
1365 {
1366     if (port_array_get(&p->ports, odp_port->port)) {
1367         VLOG_WARN_RL(&rl, "ignoring duplicate port %"PRIu16" in datapath",
1368                      odp_port->port);
1369         return true;
1370     } else if (shash_find(&p->port_by_name, odp_port->devname)) {
1371         VLOG_WARN_RL(&rl, "ignoring duplicate device %s in datapath",
1372                      odp_port->devname);
1373         return true;
1374     } else {
1375         return false;
1376     }
1377 }
1378
1379 static int
1380 ofport_equal(const struct ofport *a_, const struct ofport *b_)
1381 {
1382     const struct ofp_phy_port *a = &a_->opp;
1383     const struct ofp_phy_port *b = &b_->opp;
1384
1385     BUILD_ASSERT_DECL(sizeof *a == 48); /* Detect ofp_phy_port changes. */
1386     return (a->port_no == b->port_no
1387             && !memcmp(a->hw_addr, b->hw_addr, sizeof a->hw_addr)
1388             && !strcmp((char *) a->name, (char *) b->name)
1389             && a->state == b->state
1390             && a->config == b->config
1391             && a->curr == b->curr
1392             && a->advertised == b->advertised
1393             && a->supported == b->supported
1394             && a->peer == b->peer);
1395 }
1396
1397 static void
1398 send_port_status(struct ofproto *p, const struct ofport *ofport,
1399                  uint8_t reason)
1400 {
1401     /* XXX Should limit the number of queued port status change messages. */
1402     struct ofconn *ofconn;
1403     LIST_FOR_EACH (ofconn, struct ofconn, node, &p->all_conns) {
1404         struct ofp_port_status *ops;
1405         struct ofpbuf *b;
1406
1407         if (!ofconn_receives_async_msgs(ofconn)) {
1408             continue;
1409         }
1410
1411         ops = make_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, 0, &b);
1412         ops->reason = reason;
1413         ops->desc = ofport->opp;
1414         hton_ofp_phy_port(&ops->desc);
1415         queue_tx(b, ofconn, NULL);
1416     }
1417     if (p->ofhooks->port_changed_cb) {
1418         p->ofhooks->port_changed_cb(reason, &ofport->opp, p->aux);
1419     }
1420 }
1421
1422 static void
1423 ofport_install(struct ofproto *p, struct ofport *ofport)
1424 {
1425     uint16_t odp_port = ofp_port_to_odp_port(ofport->opp.port_no);
1426     const char *netdev_name = (const char *) ofport->opp.name;
1427
1428     netdev_monitor_add(p->netdev_monitor, ofport->netdev);
1429     port_array_set(&p->ports, odp_port, ofport);
1430     shash_add(&p->port_by_name, netdev_name, ofport);
1431     if (p->sflow) {
1432         ofproto_sflow_add_port(p->sflow, odp_port, netdev_name);
1433     }
1434 }
1435
1436 static void
1437 ofport_remove(struct ofproto *p, struct ofport *ofport)
1438 {
1439     uint16_t odp_port = ofp_port_to_odp_port(ofport->opp.port_no);
1440
1441     netdev_monitor_remove(p->netdev_monitor, ofport->netdev);
1442     port_array_set(&p->ports, odp_port, NULL);
1443     shash_delete(&p->port_by_name,
1444                  shash_find(&p->port_by_name, (char *) ofport->opp.name));
1445     if (p->sflow) {
1446         ofproto_sflow_del_port(p->sflow, odp_port);
1447     }
1448 }
1449
1450 static void
1451 ofport_free(struct ofport *ofport)
1452 {
1453     if (ofport) {
1454         netdev_close(ofport->netdev);
1455         free(ofport);
1456     }
1457 }
1458
1459 static void
1460 update_port(struct ofproto *p, const char *devname)
1461 {
1462     struct odp_port odp_port;
1463     struct ofport *old_ofport;
1464     struct ofport *new_ofport;
1465     int error;
1466
1467     COVERAGE_INC(ofproto_update_port);
1468
1469     /* Query the datapath for port information. */
1470     error = dpif_port_query_by_name(p->dpif, devname, &odp_port);
1471
1472     /* Find the old ofport. */
1473     old_ofport = shash_find_data(&p->port_by_name, devname);
1474     if (!error) {
1475         if (!old_ofport) {
1476             /* There's no port named 'devname' but there might be a port with
1477              * the same port number.  This could happen if a port is deleted
1478              * and then a new one added in its place very quickly, or if a port
1479              * is renamed.  In the former case we want to send an OFPPR_DELETE
1480              * and an OFPPR_ADD, and in the latter case we want to send a
1481              * single OFPPR_MODIFY.  We can distinguish the cases by comparing
1482              * the old port's ifindex against the new port, or perhaps less
1483              * reliably but more portably by comparing the old port's MAC
1484              * against the new port's MAC.  However, this code isn't that smart
1485              * and always sends an OFPPR_MODIFY (XXX). */
1486             old_ofport = port_array_get(&p->ports, odp_port.port);
1487         }
1488     } else if (error != ENOENT && error != ENODEV) {
1489         VLOG_WARN_RL(&rl, "dpif_port_query_by_name returned unexpected error "
1490                      "%s", strerror(error));
1491         return;
1492     }
1493
1494     /* Create a new ofport. */
1495     new_ofport = !error ? make_ofport(&odp_port) : NULL;
1496
1497     /* Eliminate a few pathological cases. */
1498     if (!old_ofport && !new_ofport) {
1499         return;
1500     } else if (old_ofport && new_ofport) {
1501         /* Most of the 'config' bits are OpenFlow soft state, but
1502          * OFPPC_PORT_DOWN is maintained the kernel.  So transfer the OpenFlow
1503          * bits from old_ofport.  (make_ofport() only sets OFPPC_PORT_DOWN and
1504          * leaves the other bits 0.)  */
1505         new_ofport->opp.config |= old_ofport->opp.config & ~OFPPC_PORT_DOWN;
1506
1507         if (ofport_equal(old_ofport, new_ofport)) {
1508             /* False alarm--no change. */
1509             ofport_free(new_ofport);
1510             return;
1511         }
1512     }
1513
1514     /* Now deal with the normal cases. */
1515     if (old_ofport) {
1516         ofport_remove(p, old_ofport);
1517     }
1518     if (new_ofport) {
1519         ofport_install(p, new_ofport);
1520     }
1521     send_port_status(p, new_ofport ? new_ofport : old_ofport,
1522                      (!old_ofport ? OFPPR_ADD
1523                       : !new_ofport ? OFPPR_DELETE
1524                       : OFPPR_MODIFY));
1525     ofport_free(old_ofport);
1526
1527     /* Update port groups. */
1528     refresh_port_groups(p);
1529 }
1530
1531 static int
1532 init_ports(struct ofproto *p)
1533 {
1534     struct odp_port *ports;
1535     size_t n_ports;
1536     size_t i;
1537     int error;
1538
1539     error = dpif_port_list(p->dpif, &ports, &n_ports);
1540     if (error) {
1541         return error;
1542     }
1543
1544     for (i = 0; i < n_ports; i++) {
1545         const struct odp_port *odp_port = &ports[i];
1546         if (!ofport_conflicts(p, odp_port)) {
1547             struct ofport *ofport = make_ofport(odp_port);
1548             if (ofport) {
1549                 ofport_install(p, ofport);
1550             }
1551         }
1552     }
1553     free(ports);
1554     refresh_port_groups(p);
1555     return 0;
1556 }
1557 \f
1558 static struct ofconn *
1559 ofconn_create(struct ofproto *p, struct rconn *rconn, enum ofconn_type type)
1560 {
1561     struct ofconn *ofconn = xzalloc(sizeof *ofconn);
1562     ofconn->ofproto = p;
1563     list_push_back(&p->all_conns, &ofconn->node);
1564     ofconn->rconn = rconn;
1565     ofconn->type = type;
1566     ofconn->role = NX_ROLE_OTHER;
1567     ofconn->packet_in_counter = rconn_packet_counter_create ();
1568     ofconn->pktbuf = NULL;
1569     ofconn->miss_send_len = 0;
1570     ofconn->reply_counter = rconn_packet_counter_create ();
1571     return ofconn;
1572 }
1573
1574 static void
1575 ofconn_destroy(struct ofconn *ofconn)
1576 {
1577     if (ofconn->type == OFCONN_CONTROLLER) {
1578         hmap_remove(&ofconn->ofproto->controllers, &ofconn->hmap_node);
1579     }
1580     discovery_destroy(ofconn->discovery);
1581
1582     list_remove(&ofconn->node);
1583     switch_status_unregister(ofconn->ss);
1584     rconn_destroy(ofconn->rconn);
1585     rconn_packet_counter_destroy(ofconn->packet_in_counter);
1586     rconn_packet_counter_destroy(ofconn->reply_counter);
1587     pktbuf_destroy(ofconn->pktbuf);
1588     free(ofconn);
1589 }
1590
1591 static void
1592 ofconn_run(struct ofconn *ofconn, struct ofproto *p)
1593 {
1594     int iteration;
1595     size_t i;
1596
1597     if (ofconn->discovery) {
1598         char *controller_name;
1599         if (rconn_is_connectivity_questionable(ofconn->rconn)) {
1600             discovery_question_connectivity(ofconn->discovery);
1601         }
1602         if (discovery_run(ofconn->discovery, &controller_name)) {
1603             if (controller_name) {
1604                 rconn_connect(ofconn->rconn, controller_name);
1605             } else {
1606                 rconn_disconnect(ofconn->rconn);
1607             }
1608         }
1609     }
1610
1611     for (i = 0; i < N_SCHEDULERS; i++) {
1612         pinsched_run(ofconn->schedulers[i], do_send_packet_in, ofconn);
1613     }
1614
1615     rconn_run(ofconn->rconn);
1616
1617     if (rconn_packet_counter_read (ofconn->reply_counter) < OFCONN_REPLY_MAX) {
1618         /* Limit the number of iterations to prevent other tasks from
1619          * starving. */
1620         for (iteration = 0; iteration < 50; iteration++) {
1621             struct ofpbuf *of_msg = rconn_recv(ofconn->rconn);
1622             if (!of_msg) {
1623                 break;
1624             }
1625             if (p->fail_open) {
1626                 fail_open_maybe_recover(p->fail_open);
1627             }
1628             handle_openflow(ofconn, p, of_msg);
1629             ofpbuf_delete(of_msg);
1630         }
1631     }
1632
1633     if (!ofconn->discovery && !rconn_is_alive(ofconn->rconn)) {
1634         ofconn_destroy(ofconn);
1635     }
1636 }
1637
1638 static void
1639 ofconn_wait(struct ofconn *ofconn)
1640 {
1641     int i;
1642
1643     if (ofconn->discovery) {
1644         discovery_wait(ofconn->discovery);
1645     }
1646     for (i = 0; i < N_SCHEDULERS; i++) {
1647         pinsched_wait(ofconn->schedulers[i]);
1648     }
1649     rconn_run_wait(ofconn->rconn);
1650     if (rconn_packet_counter_read (ofconn->reply_counter) < OFCONN_REPLY_MAX) {
1651         rconn_recv_wait(ofconn->rconn);
1652     } else {
1653         COVERAGE_INC(ofproto_ofconn_stuck);
1654     }
1655 }
1656
1657 /* Returns true if 'ofconn' should receive asynchronous messages. */
1658 static bool
1659 ofconn_receives_async_msgs(const struct ofconn *ofconn)
1660 {
1661     if (ofconn->type == OFCONN_CONTROLLER) {
1662         /* Ordinary controllers always get asynchronous messages unless they
1663          * have configured themselves as "slaves".  */
1664         return ofconn->role != NX_ROLE_SLAVE;
1665     } else {
1666         /* Transient connections don't get asynchronous messages unless they
1667          * have explicitly asked for them by setting a nonzero miss send
1668          * length. */
1669         return ofconn->miss_send_len > 0;
1670     }
1671 }
1672 \f
1673 /* Caller is responsible for initializing the 'cr' member of the returned
1674  * rule. */
1675 static struct rule *
1676 rule_create(struct ofproto *ofproto, struct rule *super,
1677             const union ofp_action *actions, size_t n_actions,
1678             uint16_t idle_timeout, uint16_t hard_timeout,
1679             uint64_t flow_cookie, bool send_flow_removed)
1680 {
1681     struct rule *rule = xzalloc(sizeof *rule);
1682     rule->idle_timeout = idle_timeout;
1683     rule->hard_timeout = hard_timeout;
1684     rule->flow_cookie = flow_cookie;
1685     rule->used = rule->created = time_msec();
1686     rule->send_flow_removed = send_flow_removed;
1687     rule->super = super;
1688     if (super) {
1689         list_push_back(&super->list, &rule->list);
1690     } else {
1691         list_init(&rule->list);
1692     }
1693     rule->n_actions = n_actions;
1694     rule->actions = xmemdup(actions, n_actions * sizeof *actions);
1695     netflow_flow_clear(&rule->nf_flow);
1696     netflow_flow_update_time(ofproto->netflow, &rule->nf_flow, rule->created);
1697
1698     return rule;
1699 }
1700
1701 static struct rule *
1702 rule_from_cls_rule(const struct cls_rule *cls_rule)
1703 {
1704     return cls_rule ? CONTAINER_OF(cls_rule, struct rule, cr) : NULL;
1705 }
1706
1707 static void
1708 rule_free(struct rule *rule)
1709 {
1710     free(rule->actions);
1711     free(rule->odp_actions);
1712     free(rule);
1713 }
1714
1715 /* Destroys 'rule'.  If 'rule' is a subrule, also removes it from its
1716  * super-rule's list of subrules.  If 'rule' is a super-rule, also iterates
1717  * through all of its subrules and revalidates them, destroying any that no
1718  * longer has a super-rule (which is probably all of them).
1719  *
1720  * Before calling this function, the caller must make have removed 'rule' from
1721  * the classifier.  If 'rule' is an exact-match rule, the caller is also
1722  * responsible for ensuring that it has been uninstalled from the datapath. */
1723 static void
1724 rule_destroy(struct ofproto *ofproto, struct rule *rule)
1725 {
1726     if (!rule->super) {
1727         struct rule *subrule, *next;
1728         LIST_FOR_EACH_SAFE (subrule, next, struct rule, list, &rule->list) {
1729             revalidate_rule(ofproto, subrule);
1730         }
1731     } else {
1732         list_remove(&rule->list);
1733     }
1734     rule_free(rule);
1735 }
1736
1737 static bool
1738 rule_has_out_port(const struct rule *rule, uint16_t out_port)
1739 {
1740     const union ofp_action *oa;
1741     struct actions_iterator i;
1742
1743     if (out_port == htons(OFPP_NONE)) {
1744         return true;
1745     }
1746     for (oa = actions_first(&i, rule->actions, rule->n_actions); oa;
1747          oa = actions_next(&i)) {
1748         if (oa->type == htons(OFPAT_OUTPUT) && oa->output.port == out_port) {
1749             return true;
1750         }
1751     }
1752     return false;
1753 }
1754
1755 /* Executes the actions indicated by 'rule' on 'packet', which is in flow
1756  * 'flow' and is considered to have arrived on ODP port 'in_port'.
1757  *
1758  * The flow that 'packet' actually contains does not need to actually match
1759  * 'rule'; the actions in 'rule' will be applied to it either way.  Likewise,
1760  * the packet and byte counters for 'rule' will be credited for the packet sent
1761  * out whether or not the packet actually matches 'rule'.
1762  *
1763  * If 'rule' is an exact-match rule and 'flow' actually equals the rule's flow,
1764  * the caller must already have accurately composed ODP actions for it given
1765  * 'packet' using rule_make_actions().  If 'rule' is a wildcard rule, or if
1766  * 'rule' is an exact-match rule but 'flow' is not the rule's flow, then this
1767  * function will compose a set of ODP actions based on 'rule''s OpenFlow
1768  * actions and apply them to 'packet'. */
1769 static void
1770 rule_execute(struct ofproto *ofproto, struct rule *rule,
1771              struct ofpbuf *packet, const flow_t *flow)
1772 {
1773     const union odp_action *actions;
1774     size_t n_actions;
1775     struct odp_actions a;
1776
1777     /* Grab or compose the ODP actions.
1778      *
1779      * The special case for an exact-match 'rule' where 'flow' is not the
1780      * rule's flow is important to avoid, e.g., sending a packet out its input
1781      * port simply because the ODP actions were composed for the wrong
1782      * scenario. */
1783     if (rule->cr.wc.wildcards || !flow_equal(flow, &rule->cr.flow)) {
1784         struct rule *super = rule->super ? rule->super : rule;
1785         if (xlate_actions(super->actions, super->n_actions, flow, ofproto,
1786                           packet, &a, NULL, 0, NULL)) {
1787             return;
1788         }
1789         actions = a.actions;
1790         n_actions = a.n_actions;
1791     } else {
1792         actions = rule->odp_actions;
1793         n_actions = rule->n_odp_actions;
1794     }
1795
1796     /* Execute the ODP actions. */
1797     if (!dpif_execute(ofproto->dpif, flow->in_port,
1798                       actions, n_actions, packet)) {
1799         struct odp_flow_stats stats;
1800         flow_extract_stats(flow, packet, &stats);
1801         update_stats(ofproto, rule, &stats);
1802         rule->used = time_msec();
1803         netflow_flow_update_time(ofproto->netflow, &rule->nf_flow, rule->used);
1804     }
1805 }
1806
1807 static void
1808 rule_insert(struct ofproto *p, struct rule *rule, struct ofpbuf *packet,
1809             uint16_t in_port)
1810 {
1811     struct rule *displaced_rule;
1812
1813     /* Insert the rule in the classifier. */
1814     displaced_rule = rule_from_cls_rule(classifier_insert(&p->cls, &rule->cr));
1815     if (!rule->cr.wc.wildcards) {
1816         rule_make_actions(p, rule, packet);
1817     }
1818
1819     /* Send the packet and credit it to the rule. */
1820     if (packet) {
1821         flow_t flow;
1822         flow_extract(packet, 0, in_port, &flow);
1823         rule_execute(p, rule, packet, &flow);
1824     }
1825
1826     /* Install the rule in the datapath only after sending the packet, to
1827      * avoid packet reordering.  */
1828     if (rule->cr.wc.wildcards) {
1829         COVERAGE_INC(ofproto_add_wc_flow);
1830         p->need_revalidate = true;
1831     } else {
1832         rule_install(p, rule, displaced_rule);
1833     }
1834
1835     /* Free the rule that was displaced, if any. */
1836     if (displaced_rule) {
1837         rule_destroy(p, displaced_rule);
1838     }
1839 }
1840
1841 static struct rule *
1842 rule_create_subrule(struct ofproto *ofproto, struct rule *rule,
1843                     const flow_t *flow)
1844 {
1845     struct rule *subrule = rule_create(ofproto, rule, NULL, 0,
1846                                        rule->idle_timeout, rule->hard_timeout,
1847                                        0, false);
1848     COVERAGE_INC(ofproto_subrule_create);
1849     cls_rule_from_flow(flow, 0, (rule->cr.priority <= UINT16_MAX ? UINT16_MAX
1850                         : rule->cr.priority), &subrule->cr);
1851     classifier_insert_exact(&ofproto->cls, &subrule->cr);
1852
1853     return subrule;
1854 }
1855
1856 static void
1857 rule_remove(struct ofproto *ofproto, struct rule *rule)
1858 {
1859     if (rule->cr.wc.wildcards) {
1860         COVERAGE_INC(ofproto_del_wc_flow);
1861         ofproto->need_revalidate = true;
1862     } else {
1863         rule_uninstall(ofproto, rule);
1864     }
1865     classifier_remove(&ofproto->cls, &rule->cr);
1866     rule_destroy(ofproto, rule);
1867 }
1868
1869 /* Returns true if the actions changed, false otherwise. */
1870 static bool
1871 rule_make_actions(struct ofproto *p, struct rule *rule,
1872                   const struct ofpbuf *packet)
1873 {
1874     const struct rule *super;
1875     struct odp_actions a;
1876     size_t actions_len;
1877
1878     assert(!rule->cr.wc.wildcards);
1879
1880     super = rule->super ? rule->super : rule;
1881     rule->tags = 0;
1882     xlate_actions(super->actions, super->n_actions, &rule->cr.flow, p,
1883                   packet, &a, &rule->tags, &rule->may_install,
1884                   &rule->nf_flow.output_iface);
1885
1886     actions_len = a.n_actions * sizeof *a.actions;
1887     if (rule->n_odp_actions != a.n_actions
1888         || memcmp(rule->odp_actions, a.actions, actions_len)) {
1889         COVERAGE_INC(ofproto_odp_unchanged);
1890         free(rule->odp_actions);
1891         rule->n_odp_actions = a.n_actions;
1892         rule->odp_actions = xmemdup(a.actions, actions_len);
1893         return true;
1894     } else {
1895         return false;
1896     }
1897 }
1898
1899 static int
1900 do_put_flow(struct ofproto *ofproto, struct rule *rule, int flags,
1901             struct odp_flow_put *put)
1902 {
1903     memset(&put->flow.stats, 0, sizeof put->flow.stats);
1904     put->flow.key = rule->cr.flow;
1905     put->flow.actions = rule->odp_actions;
1906     put->flow.n_actions = rule->n_odp_actions;
1907     put->flow.flags = 0;
1908     put->flags = flags;
1909     return dpif_flow_put(ofproto->dpif, put);
1910 }
1911
1912 static void
1913 rule_install(struct ofproto *p, struct rule *rule, struct rule *displaced_rule)
1914 {
1915     assert(!rule->cr.wc.wildcards);
1916
1917     if (rule->may_install) {
1918         struct odp_flow_put put;
1919         if (!do_put_flow(p, rule,
1920                          ODPPF_CREATE | ODPPF_MODIFY | ODPPF_ZERO_STATS,
1921                          &put)) {
1922             rule->installed = true;
1923             if (displaced_rule) {
1924                 update_stats(p, displaced_rule, &put.flow.stats);
1925                 rule_post_uninstall(p, displaced_rule);
1926             }
1927         }
1928     } else if (displaced_rule) {
1929         rule_uninstall(p, displaced_rule);
1930     }
1931 }
1932
1933 static void
1934 rule_reinstall(struct ofproto *ofproto, struct rule *rule)
1935 {
1936     if (rule->installed) {
1937         struct odp_flow_put put;
1938         COVERAGE_INC(ofproto_dp_missed);
1939         do_put_flow(ofproto, rule, ODPPF_CREATE | ODPPF_MODIFY, &put);
1940     } else {
1941         rule_install(ofproto, rule, NULL);
1942     }
1943 }
1944
1945 static void
1946 rule_update_actions(struct ofproto *ofproto, struct rule *rule)
1947 {
1948     bool actions_changed;
1949     uint16_t new_out_iface, old_out_iface;
1950
1951     old_out_iface = rule->nf_flow.output_iface;
1952     actions_changed = rule_make_actions(ofproto, rule, NULL);
1953
1954     if (rule->may_install) {
1955         if (rule->installed) {
1956             if (actions_changed) {
1957                 struct odp_flow_put put;
1958                 do_put_flow(ofproto, rule, ODPPF_CREATE | ODPPF_MODIFY
1959                                            | ODPPF_ZERO_STATS, &put);
1960                 update_stats(ofproto, rule, &put.flow.stats);
1961
1962                 /* Temporarily set the old output iface so that NetFlow
1963                  * messages have the correct output interface for the old
1964                  * stats. */
1965                 new_out_iface = rule->nf_flow.output_iface;
1966                 rule->nf_flow.output_iface = old_out_iface;
1967                 rule_post_uninstall(ofproto, rule);
1968                 rule->nf_flow.output_iface = new_out_iface;
1969             }
1970         } else {
1971             rule_install(ofproto, rule, NULL);
1972         }
1973     } else {
1974         rule_uninstall(ofproto, rule);
1975     }
1976 }
1977
1978 static void
1979 rule_account(struct ofproto *ofproto, struct rule *rule, uint64_t extra_bytes)
1980 {
1981     uint64_t total_bytes = rule->byte_count + extra_bytes;
1982
1983     if (ofproto->ofhooks->account_flow_cb
1984         && total_bytes > rule->accounted_bytes)
1985     {
1986         ofproto->ofhooks->account_flow_cb(
1987             &rule->cr.flow, rule->odp_actions, rule->n_odp_actions,
1988             total_bytes - rule->accounted_bytes, ofproto->aux);
1989         rule->accounted_bytes = total_bytes;
1990     }
1991 }
1992
1993 static void
1994 rule_uninstall(struct ofproto *p, struct rule *rule)
1995 {
1996     assert(!rule->cr.wc.wildcards);
1997     if (rule->installed) {
1998         struct odp_flow odp_flow;
1999
2000         odp_flow.key = rule->cr.flow;
2001         odp_flow.actions = NULL;
2002         odp_flow.n_actions = 0;
2003         odp_flow.flags = 0;
2004         if (!dpif_flow_del(p->dpif, &odp_flow)) {
2005             update_stats(p, rule, &odp_flow.stats);
2006         }
2007         rule->installed = false;
2008
2009         rule_post_uninstall(p, rule);
2010     }
2011 }
2012
2013 static bool
2014 is_controller_rule(struct rule *rule)
2015 {
2016     /* If the only action is send to the controller then don't report
2017      * NetFlow expiration messages since it is just part of the control
2018      * logic for the network and not real traffic. */
2019
2020     if (rule && rule->super) {
2021         struct rule *super = rule->super;
2022
2023         return super->n_actions == 1 &&
2024                super->actions[0].type == htons(OFPAT_OUTPUT) &&
2025                super->actions[0].output.port == htons(OFPP_CONTROLLER);
2026     }
2027
2028     return false;
2029 }
2030
2031 static void
2032 rule_post_uninstall(struct ofproto *ofproto, struct rule *rule)
2033 {
2034     struct rule *super = rule->super;
2035
2036     rule_account(ofproto, rule, 0);
2037
2038     if (ofproto->netflow && !is_controller_rule(rule)) {
2039         struct ofexpired expired;
2040         expired.flow = rule->cr.flow;
2041         expired.packet_count = rule->packet_count;
2042         expired.byte_count = rule->byte_count;
2043         expired.used = rule->used;
2044         netflow_expire(ofproto->netflow, &rule->nf_flow, &expired);
2045     }
2046     if (super) {
2047         super->packet_count += rule->packet_count;
2048         super->byte_count += rule->byte_count;
2049
2050         /* Reset counters to prevent double counting if the rule ever gets
2051          * reinstalled. */
2052         rule->packet_count = 0;
2053         rule->byte_count = 0;
2054         rule->accounted_bytes = 0;
2055
2056         netflow_flow_clear(&rule->nf_flow);
2057     }
2058 }
2059 \f
2060 static void
2061 queue_tx(struct ofpbuf *msg, const struct ofconn *ofconn,
2062          struct rconn_packet_counter *counter)
2063 {
2064     update_openflow_length(msg);
2065     if (rconn_send(ofconn->rconn, msg, counter)) {
2066         ofpbuf_delete(msg);
2067     }
2068 }
2069
2070 static void
2071 send_error(const struct ofconn *ofconn, const struct ofp_header *oh,
2072            int error, const void *data, size_t len)
2073 {
2074     struct ofpbuf *buf;
2075     struct ofp_error_msg *oem;
2076
2077     if (!(error >> 16)) {
2078         VLOG_WARN_RL(&rl, "not sending bad error code %d to controller",
2079                      error);
2080         return;
2081     }
2082
2083     COVERAGE_INC(ofproto_error);
2084     oem = make_openflow_xid(len + sizeof *oem, OFPT_ERROR,
2085                             oh ? oh->xid : 0, &buf);
2086     oem->type = htons((unsigned int) error >> 16);
2087     oem->code = htons(error & 0xffff);
2088     memcpy(oem->data, data, len);
2089     queue_tx(buf, ofconn, ofconn->reply_counter);
2090 }
2091
2092 static void
2093 send_error_oh(const struct ofconn *ofconn, const struct ofp_header *oh,
2094               int error)
2095 {
2096     size_t oh_length = ntohs(oh->length);
2097     send_error(ofconn, oh, error, oh, MIN(oh_length, 64));
2098 }
2099
2100 static void
2101 hton_ofp_phy_port(struct ofp_phy_port *opp)
2102 {
2103     opp->port_no = htons(opp->port_no);
2104     opp->config = htonl(opp->config);
2105     opp->state = htonl(opp->state);
2106     opp->curr = htonl(opp->curr);
2107     opp->advertised = htonl(opp->advertised);
2108     opp->supported = htonl(opp->supported);
2109     opp->peer = htonl(opp->peer);
2110 }
2111
2112 static int
2113 handle_echo_request(struct ofconn *ofconn, struct ofp_header *oh)
2114 {
2115     struct ofp_header *rq = oh;
2116     queue_tx(make_echo_reply(rq), ofconn, ofconn->reply_counter);
2117     return 0;
2118 }
2119
2120 static int
2121 handle_features_request(struct ofproto *p, struct ofconn *ofconn,
2122                         struct ofp_header *oh)
2123 {
2124     struct ofp_switch_features *osf;
2125     struct ofpbuf *buf;
2126     unsigned int port_no;
2127     struct ofport *port;
2128
2129     osf = make_openflow_xid(sizeof *osf, OFPT_FEATURES_REPLY, oh->xid, &buf);
2130     osf->datapath_id = htonll(p->datapath_id);
2131     osf->n_buffers = htonl(pktbuf_capacity());
2132     osf->n_tables = 2;
2133     osf->capabilities = htonl(OFPC_FLOW_STATS | OFPC_TABLE_STATS |
2134                               OFPC_PORT_STATS | OFPC_ARP_MATCH_IP);
2135     osf->actions = htonl((1u << OFPAT_OUTPUT) |
2136                          (1u << OFPAT_SET_VLAN_VID) |
2137                          (1u << OFPAT_SET_VLAN_PCP) |
2138                          (1u << OFPAT_STRIP_VLAN) |
2139                          (1u << OFPAT_SET_DL_SRC) |
2140                          (1u << OFPAT_SET_DL_DST) |
2141                          (1u << OFPAT_SET_NW_SRC) |
2142                          (1u << OFPAT_SET_NW_DST) |
2143                          (1u << OFPAT_SET_NW_TOS) |
2144                          (1u << OFPAT_SET_TP_SRC) |
2145                          (1u << OFPAT_SET_TP_DST));
2146
2147     PORT_ARRAY_FOR_EACH (port, &p->ports, port_no) {
2148         hton_ofp_phy_port(ofpbuf_put(buf, &port->opp, sizeof port->opp));
2149     }
2150
2151     queue_tx(buf, ofconn, ofconn->reply_counter);
2152     return 0;
2153 }
2154
2155 static int
2156 handle_get_config_request(struct ofproto *p, struct ofconn *ofconn,
2157                           struct ofp_header *oh)
2158 {
2159     struct ofpbuf *buf;
2160     struct ofp_switch_config *osc;
2161     uint16_t flags;
2162     bool drop_frags;
2163
2164     /* Figure out flags. */
2165     dpif_get_drop_frags(p->dpif, &drop_frags);
2166     flags = drop_frags ? OFPC_FRAG_DROP : OFPC_FRAG_NORMAL;
2167
2168     /* Send reply. */
2169     osc = make_openflow_xid(sizeof *osc, OFPT_GET_CONFIG_REPLY, oh->xid, &buf);
2170     osc->flags = htons(flags);
2171     osc->miss_send_len = htons(ofconn->miss_send_len);
2172     queue_tx(buf, ofconn, ofconn->reply_counter);
2173
2174     return 0;
2175 }
2176
2177 static int
2178 handle_set_config(struct ofproto *p, struct ofconn *ofconn,
2179                   struct ofp_switch_config *osc)
2180 {
2181     uint16_t flags;
2182     int error;
2183
2184     error = check_ofp_message(&osc->header, OFPT_SET_CONFIG, sizeof *osc);
2185     if (error) {
2186         return error;
2187     }
2188     flags = ntohs(osc->flags);
2189
2190     if (ofconn->type == OFCONN_CONTROLLER && ofconn->role != NX_ROLE_SLAVE) {
2191         switch (flags & OFPC_FRAG_MASK) {
2192         case OFPC_FRAG_NORMAL:
2193             dpif_set_drop_frags(p->dpif, false);
2194             break;
2195         case OFPC_FRAG_DROP:
2196             dpif_set_drop_frags(p->dpif, true);
2197             break;
2198         default:
2199             VLOG_WARN_RL(&rl, "requested bad fragment mode (flags=%"PRIx16")",
2200                          osc->flags);
2201             break;
2202         }
2203     }
2204
2205     ofconn->miss_send_len = ntohs(osc->miss_send_len);
2206
2207     return 0;
2208 }
2209
2210 static void
2211 add_output_group_action(struct odp_actions *actions, uint16_t group,
2212                         uint16_t *nf_output_iface)
2213 {
2214     odp_actions_add(actions, ODPAT_OUTPUT_GROUP)->output_group.group = group;
2215
2216     if (group == DP_GROUP_ALL || group == DP_GROUP_FLOOD) {
2217         *nf_output_iface = NF_OUT_FLOOD;
2218     }
2219 }
2220
2221 static void
2222 add_controller_action(struct odp_actions *actions,
2223                       const struct ofp_action_output *oao)
2224 {
2225     union odp_action *a = odp_actions_add(actions, ODPAT_CONTROLLER);
2226     a->controller.arg = ntohs(oao->max_len);
2227 }
2228
2229 struct action_xlate_ctx {
2230     /* Input. */
2231     flow_t flow;                /* Flow to which these actions correspond. */
2232     int recurse;                /* Recursion level, via xlate_table_action. */
2233     struct ofproto *ofproto;
2234     const struct ofpbuf *packet; /* The packet corresponding to 'flow', or a
2235                                   * null pointer if we are revalidating
2236                                   * without a packet to refer to. */
2237
2238     /* Output. */
2239     struct odp_actions *out;    /* Datapath actions. */
2240     tag_type *tags;             /* Tags associated with OFPP_NORMAL actions. */
2241     bool may_set_up_flow;       /* True ordinarily; false if the actions must
2242                                  * be reassessed for every packet. */
2243     uint16_t nf_output_iface;   /* Output interface index for NetFlow. */
2244 };
2245
2246 static void do_xlate_actions(const union ofp_action *in, size_t n_in,
2247                              struct action_xlate_ctx *ctx);
2248
2249 static void
2250 add_output_action(struct action_xlate_ctx *ctx, uint16_t port)
2251 {
2252     const struct ofport *ofport = port_array_get(&ctx->ofproto->ports, port);
2253
2254     if (ofport) {
2255         if (ofport->opp.config & OFPPC_NO_FWD) {
2256             /* Forwarding disabled on port. */
2257             return;
2258         }
2259     } else {
2260         /*
2261          * We don't have an ofport record for this port, but it doesn't hurt to
2262          * allow forwarding to it anyhow.  Maybe such a port will appear later
2263          * and we're pre-populating the flow table.
2264          */
2265     }
2266
2267     odp_actions_add(ctx->out, ODPAT_OUTPUT)->output.port = port;
2268     ctx->nf_output_iface = port;
2269 }
2270
2271 static struct rule *
2272 lookup_valid_rule(struct ofproto *ofproto, const flow_t *flow)
2273 {
2274     struct rule *rule;
2275     rule = rule_from_cls_rule(classifier_lookup(&ofproto->cls, flow));
2276
2277     /* The rule we found might not be valid, since we could be in need of
2278      * revalidation.  If it is not valid, don't return it. */
2279     if (rule
2280         && rule->super
2281         && ofproto->need_revalidate
2282         && !revalidate_rule(ofproto, rule)) {
2283         COVERAGE_INC(ofproto_invalidated);
2284         return NULL;
2285     }
2286
2287     return rule;
2288 }
2289
2290 static void
2291 xlate_table_action(struct action_xlate_ctx *ctx, uint16_t in_port)
2292 {
2293     if (!ctx->recurse) {
2294         uint16_t old_in_port;
2295         struct rule *rule;
2296
2297         /* Look up a flow with 'in_port' as the input port.  Then restore the
2298          * original input port (otherwise OFPP_NORMAL and OFPP_IN_PORT will
2299          * have surprising behavior). */
2300         old_in_port = ctx->flow.in_port;
2301         ctx->flow.in_port = in_port;
2302         rule = lookup_valid_rule(ctx->ofproto, &ctx->flow);
2303         ctx->flow.in_port = old_in_port;
2304
2305         if (rule) {
2306             if (rule->super) {
2307                 rule = rule->super;
2308             }
2309
2310             ctx->recurse++;
2311             do_xlate_actions(rule->actions, rule->n_actions, ctx);
2312             ctx->recurse--;
2313         }
2314     }
2315 }
2316
2317 static void
2318 xlate_output_action(struct action_xlate_ctx *ctx,
2319                     const struct ofp_action_output *oao)
2320 {
2321     uint16_t odp_port;
2322     uint16_t prev_nf_output_iface = ctx->nf_output_iface;
2323
2324     ctx->nf_output_iface = NF_OUT_DROP;
2325
2326     switch (ntohs(oao->port)) {
2327     case OFPP_IN_PORT:
2328         add_output_action(ctx, ctx->flow.in_port);
2329         break;
2330     case OFPP_TABLE:
2331         xlate_table_action(ctx, ctx->flow.in_port);
2332         break;
2333     case OFPP_NORMAL:
2334         if (!ctx->ofproto->ofhooks->normal_cb(&ctx->flow, ctx->packet,
2335                                               ctx->out, ctx->tags,
2336                                               &ctx->nf_output_iface,
2337                                               ctx->ofproto->aux)) {
2338             COVERAGE_INC(ofproto_uninstallable);
2339             ctx->may_set_up_flow = false;
2340         }
2341         break;
2342     case OFPP_FLOOD:
2343         add_output_group_action(ctx->out, DP_GROUP_FLOOD,
2344                                 &ctx->nf_output_iface);
2345         break;
2346     case OFPP_ALL:
2347         add_output_group_action(ctx->out, DP_GROUP_ALL, &ctx->nf_output_iface);
2348         break;
2349     case OFPP_CONTROLLER:
2350         add_controller_action(ctx->out, oao);
2351         break;
2352     case OFPP_LOCAL:
2353         add_output_action(ctx, ODPP_LOCAL);
2354         break;
2355     default:
2356         odp_port = ofp_port_to_odp_port(ntohs(oao->port));
2357         if (odp_port != ctx->flow.in_port) {
2358             add_output_action(ctx, odp_port);
2359         }
2360         break;
2361     }
2362
2363     if (prev_nf_output_iface == NF_OUT_FLOOD) {
2364         ctx->nf_output_iface = NF_OUT_FLOOD;
2365     } else if (ctx->nf_output_iface == NF_OUT_DROP) {
2366         ctx->nf_output_iface = prev_nf_output_iface;
2367     } else if (prev_nf_output_iface != NF_OUT_DROP &&
2368                ctx->nf_output_iface != NF_OUT_FLOOD) {
2369         ctx->nf_output_iface = NF_OUT_MULTI;
2370     }
2371 }
2372
2373 static void
2374 xlate_nicira_action(struct action_xlate_ctx *ctx,
2375                     const struct nx_action_header *nah)
2376 {
2377     const struct nx_action_resubmit *nar;
2378     const struct nx_action_set_tunnel *nast;
2379     union odp_action *oa;
2380     int subtype = ntohs(nah->subtype);
2381
2382     assert(nah->vendor == htonl(NX_VENDOR_ID));
2383     switch (subtype) {
2384     case NXAST_RESUBMIT:
2385         nar = (const struct nx_action_resubmit *) nah;
2386         xlate_table_action(ctx, ofp_port_to_odp_port(ntohs(nar->in_port)));
2387         break;
2388
2389     case NXAST_SET_TUNNEL:
2390         nast = (const struct nx_action_set_tunnel *) nah;
2391         oa = odp_actions_add(ctx->out, ODPAT_SET_TUNNEL);
2392         ctx->flow.tun_id = oa->tunnel.tun_id = nast->tun_id;
2393         break;
2394
2395     /* If you add a new action here that modifies flow data, don't forget to
2396      * update the flow key in ctx->flow in the same key. */
2397
2398     default:
2399         VLOG_DBG_RL(&rl, "unknown Nicira action type %"PRIu16, subtype);
2400         break;
2401     }
2402 }
2403
2404 static void
2405 do_xlate_actions(const union ofp_action *in, size_t n_in,
2406                  struct action_xlate_ctx *ctx)
2407 {
2408     struct actions_iterator iter;
2409     const union ofp_action *ia;
2410     const struct ofport *port;
2411
2412     port = port_array_get(&ctx->ofproto->ports, ctx->flow.in_port);
2413     if (port && port->opp.config & (OFPPC_NO_RECV | OFPPC_NO_RECV_STP) &&
2414         port->opp.config & (eth_addr_equals(ctx->flow.dl_dst, stp_eth_addr)
2415                             ? OFPPC_NO_RECV_STP : OFPPC_NO_RECV)) {
2416         /* Drop this flow. */
2417         return;
2418     }
2419
2420     for (ia = actions_first(&iter, in, n_in); ia; ia = actions_next(&iter)) {
2421         uint16_t type = ntohs(ia->type);
2422         union odp_action *oa;
2423
2424         switch (type) {
2425         case OFPAT_OUTPUT:
2426             xlate_output_action(ctx, &ia->output);
2427             break;
2428
2429         case OFPAT_SET_VLAN_VID:
2430             oa = odp_actions_add(ctx->out, ODPAT_SET_VLAN_VID);
2431             ctx->flow.dl_vlan = oa->vlan_vid.vlan_vid = ia->vlan_vid.vlan_vid;
2432             break;
2433
2434         case OFPAT_SET_VLAN_PCP:
2435             oa = odp_actions_add(ctx->out, ODPAT_SET_VLAN_PCP);
2436             ctx->flow.dl_vlan_pcp = oa->vlan_pcp.vlan_pcp = ia->vlan_pcp.vlan_pcp;
2437             break;
2438
2439         case OFPAT_STRIP_VLAN:
2440             odp_actions_add(ctx->out, ODPAT_STRIP_VLAN);
2441             ctx->flow.dl_vlan = OFP_VLAN_NONE;
2442             ctx->flow.dl_vlan_pcp = 0;
2443             break;
2444
2445         case OFPAT_SET_DL_SRC:
2446             oa = odp_actions_add(ctx->out, ODPAT_SET_DL_SRC);
2447             memcpy(oa->dl_addr.dl_addr,
2448                    ((struct ofp_action_dl_addr *) ia)->dl_addr, ETH_ADDR_LEN);
2449             memcpy(ctx->flow.dl_src,
2450                    ((struct ofp_action_dl_addr *) ia)->dl_addr, ETH_ADDR_LEN);
2451             break;
2452
2453         case OFPAT_SET_DL_DST:
2454             oa = odp_actions_add(ctx->out, ODPAT_SET_DL_DST);
2455             memcpy(oa->dl_addr.dl_addr,
2456                    ((struct ofp_action_dl_addr *) ia)->dl_addr, ETH_ADDR_LEN);
2457             memcpy(ctx->flow.dl_dst,
2458                    ((struct ofp_action_dl_addr *) ia)->dl_addr, ETH_ADDR_LEN);
2459             break;
2460
2461         case OFPAT_SET_NW_SRC:
2462             oa = odp_actions_add(ctx->out, ODPAT_SET_NW_SRC);
2463             ctx->flow.nw_src = oa->nw_addr.nw_addr = ia->nw_addr.nw_addr;
2464             break;
2465
2466         case OFPAT_SET_NW_DST:
2467             oa = odp_actions_add(ctx->out, ODPAT_SET_NW_DST);
2468             ctx->flow.nw_dst = oa->nw_addr.nw_addr = ia->nw_addr.nw_addr;
2469             break;
2470
2471         case OFPAT_SET_NW_TOS:
2472             oa = odp_actions_add(ctx->out, ODPAT_SET_NW_TOS);
2473             ctx->flow.nw_tos = oa->nw_tos.nw_tos = ia->nw_tos.nw_tos;
2474             break;
2475
2476         case OFPAT_SET_TP_SRC:
2477             oa = odp_actions_add(ctx->out, ODPAT_SET_TP_SRC);
2478             ctx->flow.tp_src = oa->tp_port.tp_port = ia->tp_port.tp_port;
2479             break;
2480
2481         case OFPAT_SET_TP_DST:
2482             oa = odp_actions_add(ctx->out, ODPAT_SET_TP_DST);
2483             ctx->flow.tp_dst = oa->tp_port.tp_port = ia->tp_port.tp_port;
2484             break;
2485
2486         case OFPAT_VENDOR:
2487             xlate_nicira_action(ctx, (const struct nx_action_header *) ia);
2488             break;
2489
2490         default:
2491             VLOG_DBG_RL(&rl, "unknown action type %"PRIu16, type);
2492             break;
2493         }
2494     }
2495 }
2496
2497 static int
2498 xlate_actions(const union ofp_action *in, size_t n_in,
2499               const flow_t *flow, struct ofproto *ofproto,
2500               const struct ofpbuf *packet,
2501               struct odp_actions *out, tag_type *tags, bool *may_set_up_flow,
2502               uint16_t *nf_output_iface)
2503 {
2504     tag_type no_tags = 0;
2505     struct action_xlate_ctx ctx;
2506     COVERAGE_INC(ofproto_ofp2odp);
2507     odp_actions_init(out);
2508     ctx.flow = *flow;
2509     ctx.recurse = 0;
2510     ctx.ofproto = ofproto;
2511     ctx.packet = packet;
2512     ctx.out = out;
2513     ctx.tags = tags ? tags : &no_tags;
2514     ctx.may_set_up_flow = true;
2515     ctx.nf_output_iface = NF_OUT_DROP;
2516     do_xlate_actions(in, n_in, &ctx);
2517
2518     /* Check with in-band control to see if we're allowed to set up this
2519      * flow. */
2520     if (!in_band_rule_check(ofproto->in_band, flow, out)) {
2521         ctx.may_set_up_flow = false;
2522     }
2523
2524     if (may_set_up_flow) {
2525         *may_set_up_flow = ctx.may_set_up_flow;
2526     }
2527     if (nf_output_iface) {
2528         *nf_output_iface = ctx.nf_output_iface;
2529     }
2530     if (odp_actions_overflow(out)) {
2531         odp_actions_init(out);
2532         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_TOO_MANY);
2533     }
2534     return 0;
2535 }
2536
2537 /* Checks whether 'ofconn' is a slave controller.  If so, returns an OpenFlow
2538  * error message code (composed with ofp_mkerr()) for the caller to propagate
2539  * upward.  Otherwise, returns 0.
2540  *
2541  * 'oh' is used to make log messages more informative. */
2542 static int
2543 reject_slave_controller(struct ofconn *ofconn, const struct ofp_header *oh)
2544 {
2545     if (ofconn->type == OFCONN_CONTROLLER && ofconn->role == NX_ROLE_SLAVE) {
2546         static struct vlog_rate_limit perm_rl = VLOG_RATE_LIMIT_INIT(1, 5);
2547         char *type_name;
2548
2549         type_name = ofp_message_type_to_string(oh->type);
2550         VLOG_WARN_RL(&perm_rl, "rejecting %s message from slave controller",
2551                      type_name);
2552         free(type_name);
2553
2554         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
2555     } else {
2556         return 0;
2557     }
2558 }
2559
2560 static int
2561 handle_packet_out(struct ofproto *p, struct ofconn *ofconn,
2562                   struct ofp_header *oh)
2563 {
2564     struct ofp_packet_out *opo;
2565     struct ofpbuf payload, *buffer;
2566     struct odp_actions actions;
2567     int n_actions;
2568     uint16_t in_port;
2569     flow_t flow;
2570     int error;
2571
2572     error = reject_slave_controller(ofconn, oh);
2573     if (error) {
2574         return error;
2575     }
2576
2577     error = check_ofp_packet_out(oh, &payload, &n_actions, p->max_ports);
2578     if (error) {
2579         return error;
2580     }
2581     opo = (struct ofp_packet_out *) oh;
2582
2583     COVERAGE_INC(ofproto_packet_out);
2584     if (opo->buffer_id != htonl(UINT32_MAX)) {
2585         error = pktbuf_retrieve(ofconn->pktbuf, ntohl(opo->buffer_id),
2586                                 &buffer, &in_port);
2587         if (error || !buffer) {
2588             return error;
2589         }
2590         payload = *buffer;
2591     } else {
2592         buffer = NULL;
2593     }
2594
2595     flow_extract(&payload, 0, ofp_port_to_odp_port(ntohs(opo->in_port)), &flow);
2596     error = xlate_actions((const union ofp_action *) opo->actions, n_actions,
2597                           &flow, p, &payload, &actions, NULL, NULL, NULL);
2598     if (error) {
2599         return error;
2600     }
2601
2602     dpif_execute(p->dpif, flow.in_port, actions.actions, actions.n_actions,
2603                  &payload);
2604     ofpbuf_delete(buffer);
2605
2606     return 0;
2607 }
2608
2609 static void
2610 update_port_config(struct ofproto *p, struct ofport *port,
2611                    uint32_t config, uint32_t mask)
2612 {
2613     mask &= config ^ port->opp.config;
2614     if (mask & OFPPC_PORT_DOWN) {
2615         if (config & OFPPC_PORT_DOWN) {
2616             netdev_turn_flags_off(port->netdev, NETDEV_UP, true);
2617         } else {
2618             netdev_turn_flags_on(port->netdev, NETDEV_UP, true);
2619         }
2620     }
2621 #define REVALIDATE_BITS (OFPPC_NO_RECV | OFPPC_NO_RECV_STP | OFPPC_NO_FWD)
2622     if (mask & REVALIDATE_BITS) {
2623         COVERAGE_INC(ofproto_costly_flags);
2624         port->opp.config ^= mask & REVALIDATE_BITS;
2625         p->need_revalidate = true;
2626     }
2627 #undef REVALIDATE_BITS
2628     if (mask & OFPPC_NO_FLOOD) {
2629         port->opp.config ^= OFPPC_NO_FLOOD;
2630         refresh_port_groups(p);
2631     }
2632     if (mask & OFPPC_NO_PACKET_IN) {
2633         port->opp.config ^= OFPPC_NO_PACKET_IN;
2634     }
2635 }
2636
2637 static int
2638 handle_port_mod(struct ofproto *p, struct ofconn *ofconn,
2639                 struct ofp_header *oh)
2640 {
2641     const struct ofp_port_mod *opm;
2642     struct ofport *port;
2643     int error;
2644
2645     error = reject_slave_controller(ofconn, oh);
2646     if (error) {
2647         return error;
2648     }
2649     error = check_ofp_message(oh, OFPT_PORT_MOD, sizeof *opm);
2650     if (error) {
2651         return error;
2652     }
2653     opm = (struct ofp_port_mod *) oh;
2654
2655     port = port_array_get(&p->ports,
2656                           ofp_port_to_odp_port(ntohs(opm->port_no)));
2657     if (!port) {
2658         return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_PORT);
2659     } else if (memcmp(port->opp.hw_addr, opm->hw_addr, OFP_ETH_ALEN)) {
2660         return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_HW_ADDR);
2661     } else {
2662         update_port_config(p, port, ntohl(opm->config), ntohl(opm->mask));
2663         if (opm->advertise) {
2664             netdev_set_advertisements(port->netdev, ntohl(opm->advertise));
2665         }
2666     }
2667     return 0;
2668 }
2669
2670 static struct ofpbuf *
2671 make_stats_reply(uint32_t xid, uint16_t type, size_t body_len)
2672 {
2673     struct ofp_stats_reply *osr;
2674     struct ofpbuf *msg;
2675
2676     msg = ofpbuf_new(MIN(sizeof *osr + body_len, UINT16_MAX));
2677     osr = put_openflow_xid(sizeof *osr, OFPT_STATS_REPLY, xid, msg);
2678     osr->type = type;
2679     osr->flags = htons(0);
2680     return msg;
2681 }
2682
2683 static struct ofpbuf *
2684 start_stats_reply(const struct ofp_stats_request *request, size_t body_len)
2685 {
2686     return make_stats_reply(request->header.xid, request->type, body_len);
2687 }
2688
2689 static void *
2690 append_stats_reply(size_t nbytes, struct ofconn *ofconn, struct ofpbuf **msgp)
2691 {
2692     struct ofpbuf *msg = *msgp;
2693     assert(nbytes <= UINT16_MAX - sizeof(struct ofp_stats_reply));
2694     if (nbytes + msg->size > UINT16_MAX) {
2695         struct ofp_stats_reply *reply = msg->data;
2696         reply->flags = htons(OFPSF_REPLY_MORE);
2697         *msgp = make_stats_reply(reply->header.xid, reply->type, nbytes);
2698         queue_tx(msg, ofconn, ofconn->reply_counter);
2699     }
2700     return ofpbuf_put_uninit(*msgp, nbytes);
2701 }
2702
2703 static int
2704 handle_desc_stats_request(struct ofproto *p, struct ofconn *ofconn,
2705                            struct ofp_stats_request *request)
2706 {
2707     struct ofp_desc_stats *ods;
2708     struct ofpbuf *msg;
2709
2710     msg = start_stats_reply(request, sizeof *ods);
2711     ods = append_stats_reply(sizeof *ods, ofconn, &msg);
2712     memset(ods, 0, sizeof *ods);
2713     ovs_strlcpy(ods->mfr_desc, p->mfr_desc, sizeof ods->mfr_desc);
2714     ovs_strlcpy(ods->hw_desc, p->hw_desc, sizeof ods->hw_desc);
2715     ovs_strlcpy(ods->sw_desc, p->sw_desc, sizeof ods->sw_desc);
2716     ovs_strlcpy(ods->serial_num, p->serial_desc, sizeof ods->serial_num);
2717     ovs_strlcpy(ods->dp_desc, p->dp_desc, sizeof ods->dp_desc);
2718     queue_tx(msg, ofconn, ofconn->reply_counter);
2719
2720     return 0;
2721 }
2722
2723 static void
2724 count_subrules(struct cls_rule *cls_rule, void *n_subrules_)
2725 {
2726     struct rule *rule = rule_from_cls_rule(cls_rule);
2727     int *n_subrules = n_subrules_;
2728
2729     if (rule->super) {
2730         (*n_subrules)++;
2731     }
2732 }
2733
2734 static int
2735 handle_table_stats_request(struct ofproto *p, struct ofconn *ofconn,
2736                            struct ofp_stats_request *request)
2737 {
2738     struct ofp_table_stats *ots;
2739     struct ofpbuf *msg;
2740     struct odp_stats dpstats;
2741     int n_exact, n_subrules, n_wild;
2742
2743     msg = start_stats_reply(request, sizeof *ots * 2);
2744
2745     /* Count rules of various kinds. */
2746     n_subrules = 0;
2747     classifier_for_each(&p->cls, CLS_INC_EXACT, count_subrules, &n_subrules);
2748     n_exact = classifier_count_exact(&p->cls) - n_subrules;
2749     n_wild = classifier_count(&p->cls) - classifier_count_exact(&p->cls);
2750
2751     /* Hash table. */
2752     dpif_get_dp_stats(p->dpif, &dpstats);
2753     ots = append_stats_reply(sizeof *ots, ofconn, &msg);
2754     memset(ots, 0, sizeof *ots);
2755     ots->table_id = TABLEID_HASH;
2756     strcpy(ots->name, "hash");
2757     ots->wildcards = htonl(0);
2758     ots->max_entries = htonl(dpstats.max_capacity);
2759     ots->active_count = htonl(n_exact);
2760     ots->lookup_count = htonll(dpstats.n_frags + dpstats.n_hit +
2761                                dpstats.n_missed);
2762     ots->matched_count = htonll(dpstats.n_hit); /* XXX */
2763
2764     /* Classifier table. */
2765     ots = append_stats_reply(sizeof *ots, ofconn, &msg);
2766     memset(ots, 0, sizeof *ots);
2767     ots->table_id = TABLEID_CLASSIFIER;
2768     strcpy(ots->name, "classifier");
2769     ots->wildcards = p->tun_id_from_cookie ? htonl(OVSFW_ALL)
2770                                            : htonl(OFPFW_ALL);
2771     ots->max_entries = htonl(65536);
2772     ots->active_count = htonl(n_wild);
2773     ots->lookup_count = htonll(0);              /* XXX */
2774     ots->matched_count = htonll(0);             /* XXX */
2775
2776     queue_tx(msg, ofconn, ofconn->reply_counter);
2777     return 0;
2778 }
2779
2780 static void
2781 append_port_stat(struct ofport *port, uint16_t port_no, struct ofconn *ofconn, 
2782                  struct ofpbuf **msgp)
2783 {
2784     struct netdev_stats stats;
2785     struct ofp_port_stats *ops;
2786
2787     /* Intentionally ignore return value, since errors will set 
2788      * 'stats' to all-1s, which is correct for OpenFlow, and 
2789      * netdev_get_stats() will log errors. */
2790     netdev_get_stats(port->netdev, &stats);
2791
2792     ops = append_stats_reply(sizeof *ops, ofconn, msgp);
2793     ops->port_no = htons(odp_port_to_ofp_port(port_no));
2794     memset(ops->pad, 0, sizeof ops->pad);
2795     ops->rx_packets = htonll(stats.rx_packets);
2796     ops->tx_packets = htonll(stats.tx_packets);
2797     ops->rx_bytes = htonll(stats.rx_bytes);
2798     ops->tx_bytes = htonll(stats.tx_bytes);
2799     ops->rx_dropped = htonll(stats.rx_dropped);
2800     ops->tx_dropped = htonll(stats.tx_dropped);
2801     ops->rx_errors = htonll(stats.rx_errors);
2802     ops->tx_errors = htonll(stats.tx_errors);
2803     ops->rx_frame_err = htonll(stats.rx_frame_errors);
2804     ops->rx_over_err = htonll(stats.rx_over_errors);
2805     ops->rx_crc_err = htonll(stats.rx_crc_errors);
2806     ops->collisions = htonll(stats.collisions);
2807 }
2808
2809 static int
2810 handle_port_stats_request(struct ofproto *p, struct ofconn *ofconn,
2811                           struct ofp_stats_request *osr,
2812                           size_t arg_size)
2813 {
2814     struct ofp_port_stats_request *psr;
2815     struct ofp_port_stats *ops;
2816     struct ofpbuf *msg;
2817     struct ofport *port;
2818     unsigned int port_no;
2819
2820     if (arg_size != sizeof *psr) {
2821         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
2822     }
2823     psr = (struct ofp_port_stats_request *) osr->body;
2824
2825     msg = start_stats_reply(osr, sizeof *ops * 16);
2826     if (psr->port_no != htons(OFPP_NONE)) {
2827         port = port_array_get(&p->ports, 
2828                 ofp_port_to_odp_port(ntohs(psr->port_no)));
2829         if (port) {
2830             append_port_stat(port, ntohs(psr->port_no), ofconn, &msg);
2831         }
2832     } else {
2833         PORT_ARRAY_FOR_EACH (port, &p->ports, port_no) {
2834             append_port_stat(port, port_no, ofconn, &msg);
2835         }
2836     }
2837
2838     queue_tx(msg, ofconn, ofconn->reply_counter);
2839     return 0;
2840 }
2841
2842 struct flow_stats_cbdata {
2843     struct ofproto *ofproto;
2844     struct ofconn *ofconn;
2845     uint16_t out_port;
2846     struct ofpbuf *msg;
2847 };
2848
2849 /* Obtains statistic counters for 'rule' within 'p' and stores them into
2850  * '*packet_countp' and '*byte_countp'.  If 'rule' is a wildcarded rule, the
2851  * returned statistic include statistics for all of 'rule''s subrules. */
2852 static void
2853 query_stats(struct ofproto *p, struct rule *rule,
2854             uint64_t *packet_countp, uint64_t *byte_countp)
2855 {
2856     uint64_t packet_count, byte_count;
2857     struct rule *subrule;
2858     struct odp_flow *odp_flows;
2859     size_t n_odp_flows;
2860
2861     /* Start from historical data for 'rule' itself that are no longer tracked
2862      * by the datapath.  This counts, for example, subrules that have
2863      * expired. */
2864     packet_count = rule->packet_count;
2865     byte_count = rule->byte_count;
2866
2867     /* Prepare to ask the datapath for statistics on 'rule', or if it is
2868      * wildcarded then on all of its subrules.
2869      *
2870      * Also, add any statistics that are not tracked by the datapath for each
2871      * subrule.  This includes, for example, statistics for packets that were
2872      * executed "by hand" by ofproto via dpif_execute() but must be accounted
2873      * to a flow. */
2874     n_odp_flows = rule->cr.wc.wildcards ? list_size(&rule->list) : 1;
2875     odp_flows = xzalloc(n_odp_flows * sizeof *odp_flows);
2876     if (rule->cr.wc.wildcards) {
2877         size_t i = 0;
2878         LIST_FOR_EACH (subrule, struct rule, list, &rule->list) {
2879             odp_flows[i++].key = subrule->cr.flow;
2880             packet_count += subrule->packet_count;
2881             byte_count += subrule->byte_count;
2882         }
2883     } else {
2884         odp_flows[0].key = rule->cr.flow;
2885     }
2886
2887     /* Fetch up-to-date statistics from the datapath and add them in. */
2888     if (!dpif_flow_get_multiple(p->dpif, odp_flows, n_odp_flows)) {
2889         size_t i;
2890         for (i = 0; i < n_odp_flows; i++) {
2891             struct odp_flow *odp_flow = &odp_flows[i];
2892             packet_count += odp_flow->stats.n_packets;
2893             byte_count += odp_flow->stats.n_bytes;
2894         }
2895     }
2896     free(odp_flows);
2897
2898     /* Return the stats to the caller. */
2899     *packet_countp = packet_count;
2900     *byte_countp = byte_count;
2901 }
2902
2903 static void
2904 flow_stats_cb(struct cls_rule *rule_, void *cbdata_)
2905 {
2906     struct rule *rule = rule_from_cls_rule(rule_);
2907     struct flow_stats_cbdata *cbdata = cbdata_;
2908     struct ofp_flow_stats *ofs;
2909     uint64_t packet_count, byte_count;
2910     size_t act_len, len;
2911     long long int tdiff = time_msec() - rule->created;
2912     uint32_t sec = tdiff / 1000;
2913     uint32_t msec = tdiff - (sec * 1000);
2914
2915     if (rule_is_hidden(rule) || !rule_has_out_port(rule, cbdata->out_port)) {
2916         return;
2917     }
2918
2919     act_len = sizeof *rule->actions * rule->n_actions;
2920     len = offsetof(struct ofp_flow_stats, actions) + act_len;
2921
2922     query_stats(cbdata->ofproto, rule, &packet_count, &byte_count);
2923
2924     ofs = append_stats_reply(len, cbdata->ofconn, &cbdata->msg);
2925     ofs->length = htons(len);
2926     ofs->table_id = rule->cr.wc.wildcards ? TABLEID_CLASSIFIER : TABLEID_HASH;
2927     ofs->pad = 0;
2928     flow_to_match(&rule->cr.flow, rule->cr.wc.wildcards,
2929                   cbdata->ofproto->tun_id_from_cookie, &ofs->match);
2930     ofs->duration_sec = htonl(sec);
2931     ofs->duration_nsec = htonl(msec * 1000000);
2932     ofs->cookie = rule->flow_cookie;
2933     ofs->priority = htons(rule->cr.priority);
2934     ofs->idle_timeout = htons(rule->idle_timeout);
2935     ofs->hard_timeout = htons(rule->hard_timeout);
2936     memset(ofs->pad2, 0, sizeof ofs->pad2);
2937     ofs->packet_count = htonll(packet_count);
2938     ofs->byte_count = htonll(byte_count);
2939     memcpy(ofs->actions, rule->actions, act_len);
2940 }
2941
2942 static int
2943 table_id_to_include(uint8_t table_id)
2944 {
2945     return (table_id == TABLEID_HASH ? CLS_INC_EXACT
2946             : table_id == TABLEID_CLASSIFIER ? CLS_INC_WILD
2947             : table_id == 0xff ? CLS_INC_ALL
2948             : 0);
2949 }
2950
2951 static int
2952 handle_flow_stats_request(struct ofproto *p, struct ofconn *ofconn,
2953                           const struct ofp_stats_request *osr,
2954                           size_t arg_size)
2955 {
2956     struct ofp_flow_stats_request *fsr;
2957     struct flow_stats_cbdata cbdata;
2958     struct cls_rule target;
2959
2960     if (arg_size != sizeof *fsr) {
2961         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
2962     }
2963     fsr = (struct ofp_flow_stats_request *) osr->body;
2964
2965     COVERAGE_INC(ofproto_flows_req);
2966     cbdata.ofproto = p;
2967     cbdata.ofconn = ofconn;
2968     cbdata.out_port = fsr->out_port;
2969     cbdata.msg = start_stats_reply(osr, 1024);
2970     cls_rule_from_match(&fsr->match, 0, false, 0, &target);
2971     classifier_for_each_match(&p->cls, &target,
2972                               table_id_to_include(fsr->table_id),
2973                               flow_stats_cb, &cbdata);
2974     queue_tx(cbdata.msg, ofconn, ofconn->reply_counter);
2975     return 0;
2976 }
2977
2978 struct flow_stats_ds_cbdata {
2979     struct ofproto *ofproto;
2980     struct ds *results;
2981 };
2982
2983 static void
2984 flow_stats_ds_cb(struct cls_rule *rule_, void *cbdata_)
2985 {
2986     struct rule *rule = rule_from_cls_rule(rule_);
2987     struct flow_stats_ds_cbdata *cbdata = cbdata_;
2988     struct ds *results = cbdata->results;
2989     struct ofp_match match;
2990     uint64_t packet_count, byte_count;
2991     size_t act_len = sizeof *rule->actions * rule->n_actions;
2992
2993     /* Don't report on subrules. */
2994     if (rule->super != NULL) {
2995         return;
2996     }
2997
2998     query_stats(cbdata->ofproto, rule, &packet_count, &byte_count);
2999     flow_to_match(&rule->cr.flow, rule->cr.wc.wildcards,
3000                   cbdata->ofproto->tun_id_from_cookie, &match);
3001
3002     ds_put_format(results, "duration=%llds, ",
3003                   (time_msec() - rule->created) / 1000);
3004     ds_put_format(results, "priority=%u, ", rule->cr.priority);
3005     ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
3006     ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
3007     ofp_print_match(results, &match, true);
3008     ofp_print_actions(results, &rule->actions->header, act_len);
3009     ds_put_cstr(results, "\n");
3010 }
3011
3012 /* Adds a pretty-printed description of all flows to 'results', including 
3013  * those marked hidden by secchan (e.g., by in-band control). */
3014 void
3015 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
3016 {
3017     struct ofp_match match;
3018     struct cls_rule target;
3019     struct flow_stats_ds_cbdata cbdata;
3020
3021     memset(&match, 0, sizeof match);
3022     match.wildcards = htonl(OVSFW_ALL);
3023
3024     cbdata.ofproto = p;
3025     cbdata.results = results;
3026
3027     cls_rule_from_match(&match, 0, false, 0, &target);
3028     classifier_for_each_match(&p->cls, &target, CLS_INC_ALL,
3029                               flow_stats_ds_cb, &cbdata);
3030 }
3031
3032 struct aggregate_stats_cbdata {
3033     struct ofproto *ofproto;
3034     uint16_t out_port;
3035     uint64_t packet_count;
3036     uint64_t byte_count;
3037     uint32_t n_flows;
3038 };
3039
3040 static void
3041 aggregate_stats_cb(struct cls_rule *rule_, void *cbdata_)
3042 {
3043     struct rule *rule = rule_from_cls_rule(rule_);
3044     struct aggregate_stats_cbdata *cbdata = cbdata_;
3045     uint64_t packet_count, byte_count;
3046
3047     if (rule_is_hidden(rule) || !rule_has_out_port(rule, cbdata->out_port)) {
3048         return;
3049     }
3050
3051     query_stats(cbdata->ofproto, rule, &packet_count, &byte_count);
3052
3053     cbdata->packet_count += packet_count;
3054     cbdata->byte_count += byte_count;
3055     cbdata->n_flows++;
3056 }
3057
3058 static int
3059 handle_aggregate_stats_request(struct ofproto *p, struct ofconn *ofconn,
3060                                const struct ofp_stats_request *osr,
3061                                size_t arg_size)
3062 {
3063     struct ofp_aggregate_stats_request *asr;
3064     struct ofp_aggregate_stats_reply *reply;
3065     struct aggregate_stats_cbdata cbdata;
3066     struct cls_rule target;
3067     struct ofpbuf *msg;
3068
3069     if (arg_size != sizeof *asr) {
3070         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3071     }
3072     asr = (struct ofp_aggregate_stats_request *) osr->body;
3073
3074     COVERAGE_INC(ofproto_agg_request);
3075     cbdata.ofproto = p;
3076     cbdata.out_port = asr->out_port;
3077     cbdata.packet_count = 0;
3078     cbdata.byte_count = 0;
3079     cbdata.n_flows = 0;
3080     cls_rule_from_match(&asr->match, 0, false, 0, &target);
3081     classifier_for_each_match(&p->cls, &target,
3082                               table_id_to_include(asr->table_id),
3083                               aggregate_stats_cb, &cbdata);
3084
3085     msg = start_stats_reply(osr, sizeof *reply);
3086     reply = append_stats_reply(sizeof *reply, ofconn, &msg);
3087     reply->flow_count = htonl(cbdata.n_flows);
3088     reply->packet_count = htonll(cbdata.packet_count);
3089     reply->byte_count = htonll(cbdata.byte_count);
3090     queue_tx(msg, ofconn, ofconn->reply_counter);
3091     return 0;
3092 }
3093
3094 static int
3095 handle_stats_request(struct ofproto *p, struct ofconn *ofconn,
3096                      struct ofp_header *oh)
3097 {
3098     struct ofp_stats_request *osr;
3099     size_t arg_size;
3100     int error;
3101
3102     error = check_ofp_message_array(oh, OFPT_STATS_REQUEST, sizeof *osr,
3103                                     1, &arg_size);
3104     if (error) {
3105         return error;
3106     }
3107     osr = (struct ofp_stats_request *) oh;
3108
3109     switch (ntohs(osr->type)) {
3110     case OFPST_DESC:
3111         return handle_desc_stats_request(p, ofconn, osr);
3112
3113     case OFPST_FLOW:
3114         return handle_flow_stats_request(p, ofconn, osr, arg_size);
3115
3116     case OFPST_AGGREGATE:
3117         return handle_aggregate_stats_request(p, ofconn, osr, arg_size);
3118
3119     case OFPST_TABLE:
3120         return handle_table_stats_request(p, ofconn, osr);
3121
3122     case OFPST_PORT:
3123         return handle_port_stats_request(p, ofconn, osr, arg_size);
3124
3125     case OFPST_VENDOR:
3126         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_VENDOR);
3127
3128     default:
3129         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT);
3130     }
3131 }
3132
3133 static long long int
3134 msec_from_nsec(uint64_t sec, uint32_t nsec)
3135 {
3136     return !sec ? 0 : sec * 1000 + nsec / 1000000;
3137 }
3138
3139 static void
3140 update_time(struct ofproto *ofproto, struct rule *rule,
3141             const struct odp_flow_stats *stats)
3142 {
3143     long long int used = msec_from_nsec(stats->used_sec, stats->used_nsec);
3144     if (used > rule->used) {
3145         rule->used = used;
3146         if (rule->super && used > rule->super->used) {
3147             rule->super->used = used;
3148         }
3149         netflow_flow_update_time(ofproto->netflow, &rule->nf_flow, used);
3150     }
3151 }
3152
3153 static void
3154 update_stats(struct ofproto *ofproto, struct rule *rule,
3155              const struct odp_flow_stats *stats)
3156 {
3157     if (stats->n_packets) {
3158         update_time(ofproto, rule, stats);
3159         rule->packet_count += stats->n_packets;
3160         rule->byte_count += stats->n_bytes;
3161         netflow_flow_update_flags(&rule->nf_flow, stats->ip_tos,
3162                                   stats->tcp_flags);
3163     }
3164 }
3165
3166 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
3167  * in which no matching flow already exists in the flow table.
3168  *
3169  * Adds the flow specified by 'ofm', which is followed by 'n_actions'
3170  * ofp_actions, to 'p''s flow table.  Returns 0 on success or an OpenFlow error
3171  * code as encoded by ofp_mkerr() on failure.
3172  *
3173  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3174  * if any. */
3175 static int
3176 add_flow(struct ofproto *p, struct ofconn *ofconn,
3177          const struct ofp_flow_mod *ofm, size_t n_actions)
3178 {
3179     struct ofpbuf *packet;
3180     struct rule *rule;
3181     uint16_t in_port;
3182     int error;
3183
3184     if (ofm->flags & htons(OFPFF_CHECK_OVERLAP)) {
3185         flow_t flow;
3186         uint32_t wildcards;
3187
3188         flow_from_match(&ofm->match, p->tun_id_from_cookie, ofm->cookie,
3189                         &flow, &wildcards);
3190         if (classifier_rule_overlaps(&p->cls, &flow, wildcards,
3191                                      ntohs(ofm->priority))) {
3192             return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_OVERLAP);
3193         }
3194     }
3195
3196     rule = rule_create(p, NULL, (const union ofp_action *) ofm->actions,
3197                        n_actions, ntohs(ofm->idle_timeout),
3198                        ntohs(ofm->hard_timeout),  ofm->cookie,
3199                        ofm->flags & htons(OFPFF_SEND_FLOW_REM));
3200     cls_rule_from_match(&ofm->match, ntohs(ofm->priority),
3201                         p->tun_id_from_cookie, ofm->cookie, &rule->cr);
3202
3203     error = 0;
3204     if (ofm->buffer_id != htonl(UINT32_MAX)) {
3205         error = pktbuf_retrieve(ofconn->pktbuf, ntohl(ofm->buffer_id),
3206                                 &packet, &in_port);
3207     } else {
3208         packet = NULL;
3209         in_port = UINT16_MAX;
3210     }
3211
3212     rule_insert(p, rule, packet, in_port);
3213     ofpbuf_delete(packet);
3214     return error;
3215 }
3216
3217 static struct rule *
3218 find_flow_strict(struct ofproto *p, const struct ofp_flow_mod *ofm)
3219 {
3220     uint32_t wildcards;
3221     flow_t flow;
3222
3223     flow_from_match(&ofm->match, p->tun_id_from_cookie, ofm->cookie,
3224                     &flow, &wildcards);
3225     return rule_from_cls_rule(classifier_find_rule_exactly(
3226                                   &p->cls, &flow, wildcards,
3227                                   ntohs(ofm->priority)));
3228 }
3229
3230 static int
3231 send_buffered_packet(struct ofproto *ofproto, struct ofconn *ofconn,
3232                      struct rule *rule, const struct ofp_flow_mod *ofm)
3233 {
3234     struct ofpbuf *packet;
3235     uint16_t in_port;
3236     flow_t flow;
3237     int error;
3238
3239     if (ofm->buffer_id == htonl(UINT32_MAX)) {
3240         return 0;
3241     }
3242
3243     error = pktbuf_retrieve(ofconn->pktbuf, ntohl(ofm->buffer_id),
3244                             &packet, &in_port);
3245     if (error) {
3246         return error;
3247     }
3248
3249     flow_extract(packet, 0, in_port, &flow);
3250     rule_execute(ofproto, rule, packet, &flow);
3251     ofpbuf_delete(packet);
3252
3253     return 0;
3254 }
3255 \f
3256 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
3257
3258 struct modify_flows_cbdata {
3259     struct ofproto *ofproto;
3260     const struct ofp_flow_mod *ofm;
3261     size_t n_actions;
3262     struct rule *match;
3263 };
3264
3265 static int modify_flow(struct ofproto *, const struct ofp_flow_mod *,
3266                        size_t n_actions, struct rule *);
3267 static void modify_flows_cb(struct cls_rule *, void *cbdata_);
3268
3269 /* Implements OFPFC_MODIFY.  Returns 0 on success or an OpenFlow error code as
3270  * encoded by ofp_mkerr() on failure.
3271  *
3272  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3273  * if any. */
3274 static int
3275 modify_flows_loose(struct ofproto *p, struct ofconn *ofconn,
3276                    const struct ofp_flow_mod *ofm, size_t n_actions)
3277 {
3278     struct modify_flows_cbdata cbdata;
3279     struct cls_rule target;
3280
3281     cbdata.ofproto = p;
3282     cbdata.ofm = ofm;
3283     cbdata.n_actions = n_actions;
3284     cbdata.match = NULL;
3285
3286     cls_rule_from_match(&ofm->match, 0, p->tun_id_from_cookie, ofm->cookie,
3287                         &target);
3288
3289     classifier_for_each_match(&p->cls, &target, CLS_INC_ALL,
3290                               modify_flows_cb, &cbdata);
3291     if (cbdata.match) {
3292         /* This credits the packet to whichever flow happened to happened to
3293          * match last.  That's weird.  Maybe we should do a lookup for the
3294          * flow that actually matches the packet?  Who knows. */
3295         send_buffered_packet(p, ofconn, cbdata.match, ofm);
3296         return 0;
3297     } else {
3298         return add_flow(p, ofconn, ofm, n_actions);
3299     }
3300 }
3301
3302 /* Implements OFPFC_MODIFY_STRICT.  Returns 0 on success or an OpenFlow error
3303  * code as encoded by ofp_mkerr() on failure.
3304  *
3305  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3306  * if any. */
3307 static int
3308 modify_flow_strict(struct ofproto *p, struct ofconn *ofconn,
3309                    struct ofp_flow_mod *ofm, size_t n_actions)
3310 {
3311     struct rule *rule = find_flow_strict(p, ofm);
3312     if (rule && !rule_is_hidden(rule)) {
3313         modify_flow(p, ofm, n_actions, rule);
3314         return send_buffered_packet(p, ofconn, rule, ofm);
3315     } else {
3316         return add_flow(p, ofconn, ofm, n_actions);
3317     }
3318 }
3319
3320 /* Callback for modify_flows_loose(). */
3321 static void
3322 modify_flows_cb(struct cls_rule *rule_, void *cbdata_)
3323 {
3324     struct rule *rule = rule_from_cls_rule(rule_);
3325     struct modify_flows_cbdata *cbdata = cbdata_;
3326
3327     if (!rule_is_hidden(rule)) {
3328         cbdata->match = rule;
3329         modify_flow(cbdata->ofproto, cbdata->ofm, cbdata->n_actions, rule);
3330     }
3331 }
3332
3333 /* Implements core of OFPFC_MODIFY and OFPFC_MODIFY_STRICT where 'rule' has
3334  * been identified as a flow in 'p''s flow table to be modified, by changing
3335  * the rule's actions to match those in 'ofm' (which is followed by 'n_actions'
3336  * ofp_action[] structures). */
3337 static int
3338 modify_flow(struct ofproto *p, const struct ofp_flow_mod *ofm,
3339             size_t n_actions, struct rule *rule)
3340 {
3341     size_t actions_len = n_actions * sizeof *rule->actions;
3342
3343     rule->flow_cookie = ofm->cookie;
3344
3345     /* If the actions are the same, do nothing. */
3346     if (n_actions == rule->n_actions
3347         && !memcmp(ofm->actions, rule->actions, actions_len))
3348     {
3349         return 0;
3350     }
3351
3352     /* Replace actions. */
3353     free(rule->actions);
3354     rule->actions = xmemdup(ofm->actions, actions_len);
3355     rule->n_actions = n_actions;
3356
3357     /* Make sure that the datapath gets updated properly. */
3358     if (rule->cr.wc.wildcards) {
3359         COVERAGE_INC(ofproto_mod_wc_flow);
3360         p->need_revalidate = true;
3361     } else {
3362         rule_update_actions(p, rule);
3363     }
3364
3365     return 0;
3366 }
3367 \f
3368 /* OFPFC_DELETE implementation. */
3369
3370 struct delete_flows_cbdata {
3371     struct ofproto *ofproto;
3372     uint16_t out_port;
3373 };
3374
3375 static void delete_flows_cb(struct cls_rule *, void *cbdata_);
3376 static void delete_flow(struct ofproto *, struct rule *, uint16_t out_port);
3377
3378 /* Implements OFPFC_DELETE. */
3379 static void
3380 delete_flows_loose(struct ofproto *p, const struct ofp_flow_mod *ofm)
3381 {
3382     struct delete_flows_cbdata cbdata;
3383     struct cls_rule target;
3384
3385     cbdata.ofproto = p;
3386     cbdata.out_port = ofm->out_port;
3387
3388     cls_rule_from_match(&ofm->match, 0, p->tun_id_from_cookie, ofm->cookie,
3389                         &target);
3390
3391     classifier_for_each_match(&p->cls, &target, CLS_INC_ALL,
3392                               delete_flows_cb, &cbdata);
3393 }
3394
3395 /* Implements OFPFC_DELETE_STRICT. */
3396 static void
3397 delete_flow_strict(struct ofproto *p, struct ofp_flow_mod *ofm)
3398 {
3399     struct rule *rule = find_flow_strict(p, ofm);
3400     if (rule) {
3401         delete_flow(p, rule, ofm->out_port);
3402     }
3403 }
3404
3405 /* Callback for delete_flows_loose(). */
3406 static void
3407 delete_flows_cb(struct cls_rule *rule_, void *cbdata_)
3408 {
3409     struct rule *rule = rule_from_cls_rule(rule_);
3410     struct delete_flows_cbdata *cbdata = cbdata_;
3411
3412     delete_flow(cbdata->ofproto, rule, cbdata->out_port);
3413 }
3414
3415 /* Implements core of OFPFC_DELETE and OFPFC_DELETE_STRICT where 'rule' has
3416  * been identified as a flow to delete from 'p''s flow table, by deleting the
3417  * flow and sending out a OFPT_FLOW_REMOVED message to any interested
3418  * controller.
3419  *
3420  * Will not delete 'rule' if it is hidden.  Will delete 'rule' only if
3421  * 'out_port' is htons(OFPP_NONE) or if 'rule' actually outputs to the
3422  * specified 'out_port'. */
3423 static void
3424 delete_flow(struct ofproto *p, struct rule *rule, uint16_t out_port)
3425 {
3426     if (rule_is_hidden(rule)) {
3427         return;
3428     }
3429
3430     if (out_port != htons(OFPP_NONE) && !rule_has_out_port(rule, out_port)) {
3431         return;
3432     }
3433
3434     send_flow_removed(p, rule, time_msec(), OFPRR_DELETE);
3435     rule_remove(p, rule);
3436 }
3437 \f
3438 static int
3439 handle_flow_mod(struct ofproto *p, struct ofconn *ofconn,
3440                 struct ofp_flow_mod *ofm)
3441 {
3442     size_t n_actions;
3443     int error;
3444
3445     error = reject_slave_controller(ofconn, &ofm->header);
3446     if (error) {
3447         return error;
3448     }
3449     error = check_ofp_message_array(&ofm->header, OFPT_FLOW_MOD, sizeof *ofm,
3450                                     sizeof *ofm->actions, &n_actions);
3451     if (error) {
3452         return error;
3453     }
3454
3455     /* We do not support the emergency flow cache.  It will hopefully
3456      * get dropped from OpenFlow in the near future. */
3457     if (ofm->flags & htons(OFPFF_EMERG)) {
3458         /* There isn't a good fit for an error code, so just state that the
3459          * flow table is full. */
3460         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_ALL_TABLES_FULL);
3461     }
3462
3463     normalize_match(&ofm->match);
3464     if (!ofm->match.wildcards) {
3465         ofm->priority = htons(UINT16_MAX);
3466     }
3467
3468     error = validate_actions((const union ofp_action *) ofm->actions,
3469                              n_actions, p->max_ports);
3470     if (error) {
3471         return error;
3472     }
3473
3474     switch (ntohs(ofm->command)) {
3475     case OFPFC_ADD:
3476         return add_flow(p, ofconn, ofm, n_actions);
3477
3478     case OFPFC_MODIFY:
3479         return modify_flows_loose(p, ofconn, ofm, n_actions);
3480
3481     case OFPFC_MODIFY_STRICT:
3482         return modify_flow_strict(p, ofconn, ofm, n_actions);
3483
3484     case OFPFC_DELETE:
3485         delete_flows_loose(p, ofm);
3486         return 0;
3487
3488     case OFPFC_DELETE_STRICT:
3489         delete_flow_strict(p, ofm);
3490         return 0;
3491
3492     default:
3493         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_BAD_COMMAND);
3494     }
3495 }
3496
3497 static int
3498 handle_tun_id_from_cookie(struct ofproto *p, struct nxt_tun_id_cookie *msg)
3499 {
3500     int error;
3501
3502     error = check_ofp_message(&msg->header, OFPT_VENDOR, sizeof *msg);
3503     if (error) {
3504         return error;
3505     }
3506
3507     p->tun_id_from_cookie = !!msg->set;
3508     return 0;
3509 }
3510
3511 static int
3512 handle_role_request(struct ofproto *ofproto,
3513                     struct ofconn *ofconn, struct nicira_header *msg)
3514 {
3515     struct nx_role_request *nrr;
3516     struct nx_role_request *reply;
3517     struct ofpbuf *buf;
3518     uint32_t role;
3519
3520     if (ntohs(msg->header.length) != sizeof *nrr) {
3521         VLOG_WARN_RL(&rl, "received role request of length %zu (expected %zu)",
3522                      ntohs(msg->header.length), sizeof *nrr);
3523         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3524     }
3525     nrr = (struct nx_role_request *) msg;
3526
3527     if (ofconn->type != OFCONN_CONTROLLER) {
3528         VLOG_WARN_RL(&rl, "ignoring role request on non-controller "
3529                      "connection");
3530         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
3531     }
3532
3533     role = ntohl(nrr->role);
3534     if (role != NX_ROLE_OTHER && role != NX_ROLE_MASTER
3535         && role != NX_ROLE_SLAVE) {
3536         VLOG_WARN_RL(&rl, "received request for unknown role %"PRIu32, role);
3537
3538         /* There's no good error code for this. */
3539         return ofp_mkerr(OFPET_BAD_REQUEST, -1);
3540     }
3541
3542     if (role == NX_ROLE_MASTER) {
3543         struct ofconn *other;
3544
3545         HMAP_FOR_EACH (other, struct ofconn, hmap_node,
3546                        &ofproto->controllers) {
3547             if (other->role == NX_ROLE_MASTER) {
3548                 other->role = NX_ROLE_SLAVE;
3549             }
3550         }
3551     }
3552     ofconn->role = role;
3553
3554     reply = make_openflow_xid(sizeof *reply, OFPT_VENDOR, msg->header.xid,
3555                               &buf);
3556     reply->nxh.vendor = htonl(NX_VENDOR_ID);
3557     reply->nxh.subtype = htonl(NXT_ROLE_REPLY);
3558     reply->role = htonl(role);
3559     queue_tx(buf, ofconn, ofconn->reply_counter);
3560
3561     return 0;
3562 }
3563
3564 static int
3565 handle_vendor(struct ofproto *p, struct ofconn *ofconn, void *msg)
3566 {
3567     struct ofp_vendor_header *ovh = msg;
3568     struct nicira_header *nh;
3569
3570     if (ntohs(ovh->header.length) < sizeof(struct ofp_vendor_header)) {
3571         VLOG_WARN_RL(&rl, "received vendor message of length %zu "
3572                           "(expected at least %zu)",
3573                    ntohs(ovh->header.length), sizeof(struct ofp_vendor_header));
3574         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3575     }
3576     if (ovh->vendor != htonl(NX_VENDOR_ID)) {
3577         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_VENDOR);
3578     }
3579     if (ntohs(ovh->header.length) < sizeof(struct nicira_header)) {
3580         VLOG_WARN_RL(&rl, "received Nicira vendor message of length %zu "
3581                           "(expected at least %zu)",
3582                      ntohs(ovh->header.length), sizeof(struct nicira_header));
3583         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3584     }
3585
3586     nh = msg;
3587     switch (ntohl(nh->subtype)) {
3588     case NXT_STATUS_REQUEST:
3589         return switch_status_handle_request(p->switch_status, ofconn->rconn,
3590                                             msg);
3591
3592     case NXT_TUN_ID_FROM_COOKIE:
3593         return handle_tun_id_from_cookie(p, msg);
3594
3595     case NXT_ROLE_REQUEST:
3596         return handle_role_request(p, ofconn, msg);
3597     }
3598
3599     return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE);
3600 }
3601
3602 static int
3603 handle_barrier_request(struct ofconn *ofconn, struct ofp_header *oh)
3604 {
3605     struct ofp_header *ob;
3606     struct ofpbuf *buf;
3607
3608     /* Currently, everything executes synchronously, so we can just
3609      * immediately send the barrier reply. */
3610     ob = make_openflow_xid(sizeof *ob, OFPT_BARRIER_REPLY, oh->xid, &buf);
3611     queue_tx(buf, ofconn, ofconn->reply_counter);
3612     return 0;
3613 }
3614
3615 static void
3616 handle_openflow(struct ofconn *ofconn, struct ofproto *p,
3617                 struct ofpbuf *ofp_msg)
3618 {
3619     struct ofp_header *oh = ofp_msg->data;
3620     int error;
3621
3622     COVERAGE_INC(ofproto_recv_openflow);
3623     switch (oh->type) {
3624     case OFPT_ECHO_REQUEST:
3625         error = handle_echo_request(ofconn, oh);
3626         break;
3627
3628     case OFPT_ECHO_REPLY:
3629         error = 0;
3630         break;
3631
3632     case OFPT_FEATURES_REQUEST:
3633         error = handle_features_request(p, ofconn, oh);
3634         break;
3635
3636     case OFPT_GET_CONFIG_REQUEST:
3637         error = handle_get_config_request(p, ofconn, oh);
3638         break;
3639
3640     case OFPT_SET_CONFIG:
3641         error = handle_set_config(p, ofconn, ofp_msg->data);
3642         break;
3643
3644     case OFPT_PACKET_OUT:
3645         error = handle_packet_out(p, ofconn, ofp_msg->data);
3646         break;
3647
3648     case OFPT_PORT_MOD:
3649         error = handle_port_mod(p, ofconn, oh);
3650         break;
3651
3652     case OFPT_FLOW_MOD:
3653         error = handle_flow_mod(p, ofconn, ofp_msg->data);
3654         break;
3655
3656     case OFPT_STATS_REQUEST:
3657         error = handle_stats_request(p, ofconn, oh);
3658         break;
3659
3660     case OFPT_VENDOR:
3661         error = handle_vendor(p, ofconn, ofp_msg->data);
3662         break;
3663
3664     case OFPT_BARRIER_REQUEST:
3665         error = handle_barrier_request(ofconn, oh);
3666         break;
3667
3668     default:
3669         if (VLOG_IS_WARN_ENABLED()) {
3670             char *s = ofp_to_string(oh, ntohs(oh->length), 2);
3671             VLOG_DBG_RL(&rl, "OpenFlow message ignored: %s", s);
3672             free(s);
3673         }
3674         error = ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
3675         break;
3676     }
3677
3678     if (error) {
3679         send_error_oh(ofconn, ofp_msg->data, error);
3680     }
3681 }
3682 \f
3683 static void
3684 handle_odp_miss_msg(struct ofproto *p, struct ofpbuf *packet)
3685 {
3686     struct odp_msg *msg = packet->data;
3687     struct rule *rule;
3688     struct ofpbuf payload;
3689     flow_t flow;
3690
3691     payload.data = msg + 1;
3692     payload.size = msg->length - sizeof *msg;
3693     flow_extract(&payload, msg->arg, msg->port, &flow);
3694
3695     /* Check with in-band control to see if this packet should be sent
3696      * to the local port regardless of the flow table. */
3697     if (in_band_msg_in_hook(p->in_band, &flow, &payload)) {
3698         union odp_action action;
3699
3700         memset(&action, 0, sizeof(action));
3701         action.output.type = ODPAT_OUTPUT;
3702         action.output.port = ODPP_LOCAL;
3703         dpif_execute(p->dpif, flow.in_port, &action, 1, &payload);
3704     }
3705
3706     rule = lookup_valid_rule(p, &flow);
3707     if (!rule) {
3708         /* Don't send a packet-in if OFPPC_NO_PACKET_IN asserted. */
3709         struct ofport *port = port_array_get(&p->ports, msg->port);
3710         if (port) {
3711             if (port->opp.config & OFPPC_NO_PACKET_IN) {
3712                 COVERAGE_INC(ofproto_no_packet_in);
3713                 /* XXX install 'drop' flow entry */
3714                 ofpbuf_delete(packet);
3715                 return;
3716             }
3717         } else {
3718             VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16, msg->port);
3719         }
3720
3721         COVERAGE_INC(ofproto_packet_in);
3722         send_packet_in(p, packet);
3723         return;
3724     }
3725
3726     if (rule->cr.wc.wildcards) {
3727         rule = rule_create_subrule(p, rule, &flow);
3728         rule_make_actions(p, rule, packet);
3729     } else {
3730         if (!rule->may_install) {
3731             /* The rule is not installable, that is, we need to process every
3732              * packet, so process the current packet and set its actions into
3733              * 'subrule'. */
3734             rule_make_actions(p, rule, packet);
3735         } else {
3736             /* XXX revalidate rule if it needs it */
3737         }
3738     }
3739
3740     rule_execute(p, rule, &payload, &flow);
3741     rule_reinstall(p, rule);
3742
3743     if (rule->super && rule->super->cr.priority == FAIL_OPEN_PRIORITY) {
3744         /*
3745          * Extra-special case for fail-open mode.
3746          *
3747          * We are in fail-open mode and the packet matched the fail-open rule,
3748          * but we are connected to a controller too.  We should send the packet
3749          * up to the controller in the hope that it will try to set up a flow
3750          * and thereby allow us to exit fail-open.
3751          *
3752          * See the top-level comment in fail-open.c for more information.
3753          */
3754         send_packet_in(p, packet);
3755     } else {
3756         ofpbuf_delete(packet);
3757     }
3758 }
3759
3760 static void
3761 handle_odp_msg(struct ofproto *p, struct ofpbuf *packet)
3762 {
3763     struct odp_msg *msg = packet->data;
3764
3765     switch (msg->type) {
3766     case _ODPL_ACTION_NR:
3767         COVERAGE_INC(ofproto_ctlr_action);
3768         send_packet_in(p, packet);
3769         break;
3770
3771     case _ODPL_SFLOW_NR:
3772         if (p->sflow) {
3773             ofproto_sflow_received(p->sflow, msg);
3774         }
3775         ofpbuf_delete(packet);
3776         break;
3777
3778     case _ODPL_MISS_NR:
3779         handle_odp_miss_msg(p, packet);
3780         break;
3781
3782     default:
3783         VLOG_WARN_RL(&rl, "received ODP message of unexpected type %"PRIu32,
3784                      msg->type);
3785         break;
3786     }
3787 }
3788 \f
3789 static void
3790 revalidate_cb(struct cls_rule *sub_, void *cbdata_)
3791 {
3792     struct rule *sub = rule_from_cls_rule(sub_);
3793     struct revalidate_cbdata *cbdata = cbdata_;
3794
3795     if (cbdata->revalidate_all
3796         || (cbdata->revalidate_subrules && sub->super)
3797         || (tag_set_intersects(&cbdata->revalidate_set, sub->tags))) {
3798         revalidate_rule(cbdata->ofproto, sub);
3799     }
3800 }
3801
3802 static bool
3803 revalidate_rule(struct ofproto *p, struct rule *rule)
3804 {
3805     const flow_t *flow = &rule->cr.flow;
3806
3807     COVERAGE_INC(ofproto_revalidate_rule);
3808     if (rule->super) {
3809         struct rule *super;
3810         super = rule_from_cls_rule(classifier_lookup_wild(&p->cls, flow));
3811         if (!super) {
3812             rule_remove(p, rule);
3813             return false;
3814         } else if (super != rule->super) {
3815             COVERAGE_INC(ofproto_revalidate_moved);
3816             list_remove(&rule->list);
3817             list_push_back(&super->list, &rule->list);
3818             rule->super = super;
3819             rule->hard_timeout = super->hard_timeout;
3820             rule->idle_timeout = super->idle_timeout;
3821             rule->created = super->created;
3822             rule->used = 0;
3823         }
3824     }
3825
3826     rule_update_actions(p, rule);
3827     return true;
3828 }
3829
3830 static struct ofpbuf *
3831 compose_flow_removed(struct ofproto *p, const struct rule *rule,
3832                      long long int now, uint8_t reason)
3833 {
3834     struct ofp_flow_removed *ofr;
3835     struct ofpbuf *buf;
3836     long long int tdiff = now - rule->created;
3837     uint32_t sec = tdiff / 1000;
3838     uint32_t msec = tdiff - (sec * 1000);
3839
3840     ofr = make_openflow(sizeof *ofr, OFPT_FLOW_REMOVED, &buf);
3841     flow_to_match(&rule->cr.flow, rule->cr.wc.wildcards, p->tun_id_from_cookie,
3842                   &ofr->match);
3843     ofr->cookie = rule->flow_cookie;
3844     ofr->priority = htons(rule->cr.priority);
3845     ofr->reason = reason;
3846     ofr->duration_sec = htonl(sec);
3847     ofr->duration_nsec = htonl(msec * 1000000);
3848     ofr->idle_timeout = htons(rule->idle_timeout);
3849     ofr->packet_count = htonll(rule->packet_count);
3850     ofr->byte_count = htonll(rule->byte_count);
3851
3852     return buf;
3853 }
3854
3855 static void
3856 uninstall_idle_flow(struct ofproto *ofproto, struct rule *rule)
3857 {
3858     assert(rule->installed);
3859     assert(!rule->cr.wc.wildcards);
3860
3861     if (rule->super) {
3862         rule_remove(ofproto, rule);
3863     } else {
3864         rule_uninstall(ofproto, rule);
3865     }
3866 }
3867
3868 static void
3869 send_flow_removed(struct ofproto *p, struct rule *rule,
3870                   long long int now, uint8_t reason)
3871 {
3872     struct ofconn *ofconn;
3873     struct ofconn *prev;
3874     struct ofpbuf *buf = NULL;
3875
3876     /* We limit the maximum number of queued flow expirations it by accounting
3877      * them under the counter for replies.  That works because preventing
3878      * OpenFlow requests from being processed also prevents new flows from
3879      * being added (and expiring).  (It also prevents processing OpenFlow
3880      * requests that would not add new flows, so it is imperfect.) */
3881
3882     prev = NULL;
3883     LIST_FOR_EACH (ofconn, struct ofconn, node, &p->all_conns) {
3884         if (rule->send_flow_removed && rconn_is_connected(ofconn->rconn)
3885             && ofconn_receives_async_msgs(ofconn)) {
3886             if (prev) {
3887                 queue_tx(ofpbuf_clone(buf), prev, prev->reply_counter);
3888             } else {
3889                 buf = compose_flow_removed(p, rule, now, reason);
3890             }
3891             prev = ofconn;
3892         }
3893     }
3894     if (prev) {
3895         queue_tx(buf, prev, prev->reply_counter);
3896     }
3897 }
3898
3899
3900 static void
3901 expire_rule(struct cls_rule *cls_rule, void *p_)
3902 {
3903     struct ofproto *p = p_;
3904     struct rule *rule = rule_from_cls_rule(cls_rule);
3905     long long int hard_expire, idle_expire, expire, now;
3906
3907     hard_expire = (rule->hard_timeout
3908                    ? rule->created + rule->hard_timeout * 1000
3909                    : LLONG_MAX);
3910     idle_expire = (rule->idle_timeout
3911                    && (rule->super || list_is_empty(&rule->list))
3912                    ? rule->used + rule->idle_timeout * 1000
3913                    : LLONG_MAX);
3914     expire = MIN(hard_expire, idle_expire);
3915
3916     now = time_msec();
3917     if (now < expire) {
3918         if (rule->installed && now >= rule->used + 5000) {
3919             uninstall_idle_flow(p, rule);
3920         } else if (!rule->cr.wc.wildcards) {
3921             active_timeout(p, rule);
3922         }
3923
3924         return;
3925     }
3926
3927     COVERAGE_INC(ofproto_expired);
3928
3929     /* Update stats.  This code will be a no-op if the rule expired
3930      * due to an idle timeout. */
3931     if (rule->cr.wc.wildcards) {
3932         struct rule *subrule, *next;
3933         LIST_FOR_EACH_SAFE (subrule, next, struct rule, list, &rule->list) {
3934             rule_remove(p, subrule);
3935         }
3936     } else {
3937         rule_uninstall(p, rule);
3938     }
3939
3940     if (!rule_is_hidden(rule)) {
3941         send_flow_removed(p, rule, now,
3942                           (now >= hard_expire
3943                            ? OFPRR_HARD_TIMEOUT : OFPRR_IDLE_TIMEOUT));
3944     }
3945     rule_remove(p, rule);
3946 }
3947
3948 static void
3949 active_timeout(struct ofproto *ofproto, struct rule *rule)
3950 {
3951     if (ofproto->netflow && !is_controller_rule(rule) &&
3952         netflow_active_timeout_expired(ofproto->netflow, &rule->nf_flow)) {
3953         struct ofexpired expired;
3954         struct odp_flow odp_flow;
3955
3956         /* Get updated flow stats. */
3957         memset(&odp_flow, 0, sizeof odp_flow);
3958         if (rule->installed) {
3959             odp_flow.key = rule->cr.flow;
3960             odp_flow.flags = ODPFF_ZERO_TCP_FLAGS;
3961             dpif_flow_get(ofproto->dpif, &odp_flow);
3962
3963             if (odp_flow.stats.n_packets) {
3964                 update_time(ofproto, rule, &odp_flow.stats);
3965                 netflow_flow_update_flags(&rule->nf_flow, odp_flow.stats.ip_tos,
3966                                           odp_flow.stats.tcp_flags);
3967             }
3968         }
3969
3970         expired.flow = rule->cr.flow;
3971         expired.packet_count = rule->packet_count +
3972                                odp_flow.stats.n_packets;
3973         expired.byte_count = rule->byte_count + odp_flow.stats.n_bytes;
3974         expired.used = rule->used;
3975
3976         netflow_expire(ofproto->netflow, &rule->nf_flow, &expired);
3977
3978         /* Schedule us to send the accumulated records once we have
3979          * collected all of them. */
3980         poll_immediate_wake();
3981     }
3982 }
3983
3984 static void
3985 update_used(struct ofproto *p)
3986 {
3987     struct odp_flow *flows;
3988     size_t n_flows;
3989     size_t i;
3990     int error;
3991
3992     error = dpif_flow_list_all(p->dpif, &flows, &n_flows);
3993     if (error) {
3994         return;
3995     }
3996
3997     for (i = 0; i < n_flows; i++) {
3998         struct odp_flow *f = &flows[i];
3999         struct rule *rule;
4000
4001         rule = rule_from_cls_rule(
4002             classifier_find_rule_exactly(&p->cls, &f->key, 0, UINT16_MAX));
4003         if (!rule || !rule->installed) {
4004             COVERAGE_INC(ofproto_unexpected_rule);
4005             dpif_flow_del(p->dpif, f);
4006             continue;
4007         }
4008
4009         update_time(p, rule, &f->stats);
4010         rule_account(p, rule, f->stats.n_bytes);
4011     }
4012     free(flows);
4013 }
4014
4015 /* pinsched callback for sending 'packet' on 'ofconn'. */
4016 static void
4017 do_send_packet_in(struct ofpbuf *packet, void *ofconn_)
4018 {
4019     struct ofconn *ofconn = ofconn_;
4020
4021     rconn_send_with_limit(ofconn->rconn, packet,
4022                           ofconn->packet_in_counter, 100);
4023 }
4024
4025 /* Takes 'packet', which has been converted with do_convert_to_packet_in(), and
4026  * finalizes its content for sending on 'ofconn', and passes it to 'ofconn''s
4027  * packet scheduler for sending.
4028  *
4029  * 'max_len' specifies the maximum number of bytes of the packet to send on
4030  * 'ofconn' (INT_MAX specifies no limit).
4031  *
4032  * If 'clone' is true, the caller retains ownership of 'packet'.  Otherwise,
4033  * ownership is transferred to this function. */
4034 static void
4035 schedule_packet_in(struct ofconn *ofconn, struct ofpbuf *packet, int max_len,
4036                    bool clone)
4037 {
4038     struct ofproto *ofproto = ofconn->ofproto;
4039     struct ofp_packet_in *opi = packet->data;
4040     uint16_t in_port = ofp_port_to_odp_port(ntohs(opi->in_port));
4041     int send_len, trim_size;
4042     uint32_t buffer_id;
4043
4044     /* Get buffer. */
4045     if (opi->reason == OFPR_ACTION) {
4046         buffer_id = UINT32_MAX;
4047     } else if (ofproto->fail_open && fail_open_is_active(ofproto->fail_open)) {
4048         buffer_id = pktbuf_get_null();
4049     } else if (!ofconn->pktbuf) {
4050         buffer_id = UINT32_MAX;
4051     } else {
4052         struct ofpbuf payload;
4053         payload.data = opi->data;
4054         payload.size = packet->size - offsetof(struct ofp_packet_in, data);
4055         buffer_id = pktbuf_save(ofconn->pktbuf, &payload, in_port);
4056     }
4057
4058     /* Figure out how much of the packet to send. */
4059     send_len = ntohs(opi->total_len);
4060     if (buffer_id != UINT32_MAX) {
4061         send_len = MIN(send_len, ofconn->miss_send_len);
4062     }
4063     send_len = MIN(send_len, max_len);
4064
4065     /* Adjust packet length and clone if necessary. */
4066     trim_size = offsetof(struct ofp_packet_in, data) + send_len;
4067     if (clone) {
4068         packet = ofpbuf_clone_data(packet->data, trim_size);
4069         opi = packet->data;
4070     } else {
4071         packet->size = trim_size;
4072     }
4073
4074     /* Update packet headers. */
4075     opi->buffer_id = htonl(buffer_id);
4076     update_openflow_length(packet);
4077
4078     /* Hand over to packet scheduler.  It might immediately call into
4079      * do_send_packet_in() or it might buffer it for a while (until a later
4080      * call to pinsched_run()). */
4081     pinsched_send(ofconn->schedulers[opi->reason], in_port,
4082                   packet, do_send_packet_in, ofconn);
4083 }
4084
4085 /* Replace struct odp_msg header in 'packet' by equivalent struct
4086  * ofp_packet_in.  The odp_msg must have sufficient headroom to do so (e.g. as
4087  * returned by dpif_recv()).
4088  *
4089  * The conversion is not complete: the caller still needs to trim any unneeded
4090  * payload off the end of the buffer, set the length in the OpenFlow header,
4091  * and set buffer_id.  Those require us to know the controller settings and so
4092  * must be done on a per-controller basis.
4093  *
4094  * Returns the maximum number of bytes of the packet that should be sent to
4095  * the controller (INT_MAX if no limit). */
4096 static int
4097 do_convert_to_packet_in(struct ofpbuf *packet)
4098 {
4099     struct odp_msg *msg = packet->data;
4100     struct ofp_packet_in *opi;
4101     uint8_t reason;
4102     uint16_t total_len;
4103     uint16_t in_port;
4104     int max_len;
4105
4106     /* Extract relevant header fields */
4107     if (msg->type == _ODPL_ACTION_NR) {
4108         reason = OFPR_ACTION;
4109         max_len = msg->arg;
4110     } else {
4111         reason = OFPR_NO_MATCH;
4112         max_len = INT_MAX;
4113     }
4114     total_len = msg->length - sizeof *msg;
4115     in_port = odp_port_to_ofp_port(msg->port);
4116
4117     /* Repurpose packet buffer by overwriting header. */
4118     ofpbuf_pull(packet, sizeof(struct odp_msg));
4119     opi = ofpbuf_push_zeros(packet, offsetof(struct ofp_packet_in, data));
4120     opi->header.version = OFP_VERSION;
4121     opi->header.type = OFPT_PACKET_IN;
4122     opi->total_len = htons(total_len);
4123     opi->in_port = htons(in_port);
4124     opi->reason = reason;
4125
4126     return max_len;
4127 }
4128
4129 /* Given 'packet' containing an odp_msg of type _ODPL_ACTION_NR or
4130  * _ODPL_MISS_NR, sends an OFPT_PACKET_IN message to each OpenFlow controller
4131  * as necessary according to their individual configurations.
4132  *
4133  * 'packet' must have sufficient headroom to convert it into a struct
4134  * ofp_packet_in (e.g. as returned by dpif_recv()).
4135  *
4136  * Takes ownership of 'packet'. */
4137 static void
4138 send_packet_in(struct ofproto *ofproto, struct ofpbuf *packet)
4139 {
4140     struct ofconn *ofconn, *prev;
4141     int max_len;
4142
4143     max_len = do_convert_to_packet_in(packet);
4144
4145     prev = NULL;
4146     LIST_FOR_EACH (ofconn, struct ofconn, node, &ofproto->all_conns) {
4147         if (ofconn_receives_async_msgs(ofconn)) {
4148             if (prev) {
4149                 schedule_packet_in(prev, packet, max_len, true);
4150             }
4151             prev = ofconn;
4152         }
4153     }
4154     if (prev) {
4155         schedule_packet_in(prev, packet, max_len, false);
4156     } else {
4157         ofpbuf_delete(packet);
4158     }
4159 }
4160
4161 static uint64_t
4162 pick_datapath_id(const struct ofproto *ofproto)
4163 {
4164     const struct ofport *port;
4165
4166     port = port_array_get(&ofproto->ports, ODPP_LOCAL);
4167     if (port) {
4168         uint8_t ea[ETH_ADDR_LEN];
4169         int error;
4170
4171         error = netdev_get_etheraddr(port->netdev, ea);
4172         if (!error) {
4173             return eth_addr_to_uint64(ea);
4174         }
4175         VLOG_WARN("could not get MAC address for %s (%s)",
4176                   netdev_get_name(port->netdev), strerror(error));
4177     }
4178     return ofproto->fallback_dpid;
4179 }
4180
4181 static uint64_t
4182 pick_fallback_dpid(void)
4183 {
4184     uint8_t ea[ETH_ADDR_LEN];
4185     eth_addr_nicira_random(ea);
4186     return eth_addr_to_uint64(ea);
4187 }
4188 \f
4189 static bool
4190 default_normal_ofhook_cb(const flow_t *flow, const struct ofpbuf *packet,
4191                          struct odp_actions *actions, tag_type *tags,
4192                          uint16_t *nf_output_iface, void *ofproto_)
4193 {
4194     struct ofproto *ofproto = ofproto_;
4195     int out_port;
4196
4197     /* Drop frames for reserved multicast addresses. */
4198     if (eth_addr_is_reserved(flow->dl_dst)) {
4199         return true;
4200     }
4201
4202     /* Learn source MAC (but don't try to learn from revalidation). */
4203     if (packet != NULL) {
4204         tag_type rev_tag = mac_learning_learn(ofproto->ml, flow->dl_src,
4205                                               0, flow->in_port);
4206         if (rev_tag) {
4207             /* The log messages here could actually be useful in debugging,
4208              * so keep the rate limit relatively high. */
4209             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
4210             VLOG_DBG_RL(&rl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
4211                         ETH_ADDR_ARGS(flow->dl_src), flow->in_port);
4212             ofproto_revalidate(ofproto, rev_tag);
4213         }
4214     }
4215
4216     /* Determine output port. */
4217     out_port = mac_learning_lookup_tag(ofproto->ml, flow->dl_dst, 0, tags);
4218     if (out_port < 0) {
4219         add_output_group_action(actions, DP_GROUP_FLOOD, nf_output_iface);
4220     } else if (out_port != flow->in_port) {
4221         odp_actions_add(actions, ODPAT_OUTPUT)->output.port = out_port;
4222         *nf_output_iface = out_port;
4223     } else {
4224         /* Drop. */
4225     }
4226
4227     return true;
4228 }
4229
4230 static const struct ofhooks default_ofhooks = {
4231     NULL,
4232     default_normal_ofhook_cb,
4233     NULL,
4234     NULL
4235 };