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