447d7f09b88e999a7307662465eda593c40bcd98
[sliver-openvswitch.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_NW_TOS) |
1857                          (1u << OFPAT_SET_TP_SRC) |
1858                          (1u << OFPAT_SET_TP_DST));
1859
1860     PORT_ARRAY_FOR_EACH (port, &p->ports, port_no) {
1861         hton_ofp_phy_port(ofpbuf_put(buf, &port->opp, sizeof port->opp));
1862     }
1863
1864     queue_tx(buf, ofconn, ofconn->reply_counter);
1865     return 0;
1866 }
1867
1868 static int
1869 handle_get_config_request(struct ofproto *p, struct ofconn *ofconn,
1870                           struct ofp_header *oh)
1871 {
1872     struct ofpbuf *buf;
1873     struct ofp_switch_config *osc;
1874     uint16_t flags;
1875     bool drop_frags;
1876
1877     /* Figure out flags. */
1878     dpif_get_drop_frags(p->dpif, &drop_frags);
1879     flags = drop_frags ? OFPC_FRAG_DROP : OFPC_FRAG_NORMAL;
1880     if (ofconn->send_flow_exp) {
1881         flags |= OFPC_SEND_FLOW_EXP;
1882     }
1883
1884     /* Send reply. */
1885     osc = make_openflow_xid(sizeof *osc, OFPT_GET_CONFIG_REPLY, oh->xid, &buf);
1886     osc->flags = htons(flags);
1887     osc->miss_send_len = htons(ofconn->miss_send_len);
1888     queue_tx(buf, ofconn, ofconn->reply_counter);
1889
1890     return 0;
1891 }
1892
1893 static int
1894 handle_set_config(struct ofproto *p, struct ofconn *ofconn,
1895                   struct ofp_switch_config *osc)
1896 {
1897     uint16_t flags;
1898     int error;
1899
1900     error = check_ofp_message(&osc->header, OFPT_SET_CONFIG, sizeof *osc);
1901     if (error) {
1902         return error;
1903     }
1904     flags = ntohs(osc->flags);
1905
1906     ofconn->send_flow_exp = (flags & OFPC_SEND_FLOW_EXP) != 0;
1907
1908     if (ofconn == p->controller) {
1909         switch (flags & OFPC_FRAG_MASK) {
1910         case OFPC_FRAG_NORMAL:
1911             dpif_set_drop_frags(p->dpif, false);
1912             break;
1913         case OFPC_FRAG_DROP:
1914             dpif_set_drop_frags(p->dpif, true);
1915             break;
1916         default:
1917             VLOG_WARN_RL(&rl, "requested bad fragment mode (flags=%"PRIx16")",
1918                          osc->flags);
1919             break;
1920         }
1921     }
1922
1923     if ((ntohs(osc->miss_send_len) != 0) != (ofconn->miss_send_len != 0)) {
1924         if (ntohs(osc->miss_send_len) != 0) {
1925             ofconn->pktbuf = pktbuf_create();
1926         } else {
1927             pktbuf_destroy(ofconn->pktbuf);
1928         }
1929     }
1930
1931     ofconn->miss_send_len = ntohs(osc->miss_send_len);
1932
1933     return 0;
1934 }
1935
1936 static void
1937 add_output_group_action(struct odp_actions *actions, uint16_t group,
1938                         uint16_t *nf_output_iface)
1939 {
1940     odp_actions_add(actions, ODPAT_OUTPUT_GROUP)->output_group.group = group;
1941
1942     if (group == DP_GROUP_ALL || group == DP_GROUP_FLOOD) {
1943         *nf_output_iface = NF_OUT_FLOOD;
1944     }
1945 }
1946
1947 static void
1948 add_controller_action(struct odp_actions *actions,
1949                       const struct ofp_action_output *oao)
1950 {
1951     union odp_action *a = odp_actions_add(actions, ODPAT_CONTROLLER);
1952     a->controller.arg = oao->max_len ? ntohs(oao->max_len) : UINT32_MAX;
1953 }
1954
1955 struct action_xlate_ctx {
1956     /* Input. */
1957     const flow_t *flow;         /* Flow to which these actions correspond. */
1958     int recurse;                /* Recursion level, via xlate_table_action. */
1959     struct ofproto *ofproto;
1960     const struct ofpbuf *packet; /* The packet corresponding to 'flow', or a
1961                                   * null pointer if we are revalidating
1962                                   * without a packet to refer to. */
1963
1964     /* Output. */
1965     struct odp_actions *out;    /* Datapath actions. */
1966     tag_type *tags;             /* Tags associated with OFPP_NORMAL actions. */
1967     bool may_set_up_flow;       /* True ordinarily; false if the actions must
1968                                  * be reassessed for every packet. */
1969     uint16_t nf_output_iface;   /* Output interface index for NetFlow. */
1970 };
1971
1972 static void do_xlate_actions(const union ofp_action *in, size_t n_in,
1973                              struct action_xlate_ctx *ctx);
1974
1975 static void
1976 add_output_action(struct action_xlate_ctx *ctx, uint16_t port)
1977 {
1978     const struct ofport *ofport = port_array_get(&ctx->ofproto->ports, port);
1979
1980     if (ofport) {
1981         if (ofport->opp.config & OFPPC_NO_FWD) {
1982             /* Forwarding disabled on port. */
1983             return;
1984         }
1985     } else {
1986         /*
1987          * We don't have an ofport record for this port, but it doesn't hurt to
1988          * allow forwarding to it anyhow.  Maybe such a port will appear later
1989          * and we're pre-populating the flow table.
1990          */
1991     }
1992
1993     odp_actions_add(ctx->out, ODPAT_OUTPUT)->output.port = port;
1994     ctx->nf_output_iface = port;
1995 }
1996
1997 static struct rule *
1998 lookup_valid_rule(struct ofproto *ofproto, const flow_t *flow)
1999 {
2000     struct rule *rule;
2001     rule = rule_from_cls_rule(classifier_lookup(&ofproto->cls, flow));
2002
2003     /* The rule we found might not be valid, since we could be in need of
2004      * revalidation.  If it is not valid, don't return it. */
2005     if (rule
2006         && rule->super
2007         && ofproto->need_revalidate
2008         && !revalidate_rule(ofproto, rule)) {
2009         COVERAGE_INC(ofproto_invalidated);
2010         return NULL;
2011     }
2012
2013     return rule;
2014 }
2015
2016 static void
2017 xlate_table_action(struct action_xlate_ctx *ctx, uint16_t in_port)
2018 {
2019     if (!ctx->recurse) {
2020         struct rule *rule;
2021         flow_t flow;
2022
2023         flow = *ctx->flow;
2024         flow.in_port = in_port;
2025
2026         rule = lookup_valid_rule(ctx->ofproto, &flow);
2027         if (rule) {
2028             if (rule->super) {
2029                 rule = rule->super;
2030             }
2031
2032             ctx->recurse++;
2033             do_xlate_actions(rule->actions, rule->n_actions, ctx);
2034             ctx->recurse--;
2035         }
2036     }
2037 }
2038
2039 static void
2040 xlate_output_action(struct action_xlate_ctx *ctx,
2041                     const struct ofp_action_output *oao)
2042 {
2043     uint16_t odp_port;
2044     uint16_t prev_nf_output_iface = ctx->nf_output_iface;
2045
2046     ctx->nf_output_iface = NF_OUT_DROP;
2047
2048     switch (ntohs(oao->port)) {
2049     case OFPP_IN_PORT:
2050         add_output_action(ctx, ctx->flow->in_port);
2051         break;
2052     case OFPP_TABLE:
2053         xlate_table_action(ctx, ctx->flow->in_port);
2054         break;
2055     case OFPP_NORMAL:
2056         if (!ctx->ofproto->ofhooks->normal_cb(ctx->flow, ctx->packet,
2057                                               ctx->out, ctx->tags,
2058                                               &ctx->nf_output_iface,
2059                                               ctx->ofproto->aux)) {
2060             COVERAGE_INC(ofproto_uninstallable);
2061             ctx->may_set_up_flow = false;
2062         }
2063         break;
2064     case OFPP_FLOOD:
2065         add_output_group_action(ctx->out, DP_GROUP_FLOOD,
2066                                 &ctx->nf_output_iface);
2067         break;
2068     case OFPP_ALL:
2069         add_output_group_action(ctx->out, DP_GROUP_ALL, &ctx->nf_output_iface);
2070         break;
2071     case OFPP_CONTROLLER:
2072         add_controller_action(ctx->out, oao);
2073         break;
2074     case OFPP_LOCAL:
2075         add_output_action(ctx, ODPP_LOCAL);
2076         break;
2077     default:
2078         odp_port = ofp_port_to_odp_port(ntohs(oao->port));
2079         if (odp_port != ctx->flow->in_port) {
2080             add_output_action(ctx, odp_port);
2081         }
2082         break;
2083     }
2084
2085     if (prev_nf_output_iface == NF_OUT_FLOOD) {
2086         ctx->nf_output_iface = NF_OUT_FLOOD;
2087     } else if (ctx->nf_output_iface == NF_OUT_DROP) {
2088         ctx->nf_output_iface = prev_nf_output_iface;
2089     } else if (prev_nf_output_iface != NF_OUT_DROP &&
2090                ctx->nf_output_iface != NF_OUT_FLOOD) {
2091         ctx->nf_output_iface = NF_OUT_MULTI;
2092     }
2093 }
2094
2095 static void
2096 xlate_nicira_action(struct action_xlate_ctx *ctx,
2097                     const struct nx_action_header *nah)
2098 {
2099     const struct nx_action_resubmit *nar;
2100     int subtype = ntohs(nah->subtype);
2101
2102     assert(nah->vendor == htonl(NX_VENDOR_ID));
2103     switch (subtype) {
2104     case NXAST_RESUBMIT:
2105         nar = (const struct nx_action_resubmit *) nah;
2106         xlate_table_action(ctx, ofp_port_to_odp_port(ntohs(nar->in_port)));
2107         break;
2108
2109     default:
2110         VLOG_DBG_RL(&rl, "unknown Nicira action type %"PRIu16, subtype);
2111         break;
2112     }
2113 }
2114
2115 static void
2116 do_xlate_actions(const union ofp_action *in, size_t n_in,
2117                  struct action_xlate_ctx *ctx)
2118 {
2119     struct actions_iterator iter;
2120     const union ofp_action *ia;
2121     const struct ofport *port;
2122
2123     port = port_array_get(&ctx->ofproto->ports, ctx->flow->in_port);
2124     if (port && port->opp.config & (OFPPC_NO_RECV | OFPPC_NO_RECV_STP) &&
2125         port->opp.config & (eth_addr_equals(ctx->flow->dl_dst, stp_eth_addr)
2126                             ? OFPPC_NO_RECV_STP : OFPPC_NO_RECV)) {
2127         /* Drop this flow. */
2128         return;
2129     }
2130
2131     for (ia = actions_first(&iter, in, n_in); ia; ia = actions_next(&iter)) {
2132         uint16_t type = ntohs(ia->type);
2133         union odp_action *oa;
2134
2135         switch (type) {
2136         case OFPAT_OUTPUT:
2137             xlate_output_action(ctx, &ia->output);
2138             break;
2139
2140         case OFPAT_SET_VLAN_VID:
2141             oa = odp_actions_add(ctx->out, ODPAT_SET_VLAN_VID);
2142             oa->vlan_vid.vlan_vid = ia->vlan_vid.vlan_vid;
2143             break;
2144
2145         case OFPAT_SET_VLAN_PCP:
2146             oa = odp_actions_add(ctx->out, ODPAT_SET_VLAN_PCP);
2147             oa->vlan_pcp.vlan_pcp = ia->vlan_pcp.vlan_pcp;
2148             break;
2149
2150         case OFPAT_STRIP_VLAN:
2151             odp_actions_add(ctx->out, ODPAT_STRIP_VLAN);
2152             break;
2153
2154         case OFPAT_SET_DL_SRC:
2155             oa = odp_actions_add(ctx->out, ODPAT_SET_DL_SRC);
2156             memcpy(oa->dl_addr.dl_addr,
2157                    ((struct ofp_action_dl_addr *) ia)->dl_addr, ETH_ADDR_LEN);
2158             break;
2159
2160         case OFPAT_SET_DL_DST:
2161             oa = odp_actions_add(ctx->out, ODPAT_SET_DL_DST);
2162             memcpy(oa->dl_addr.dl_addr,
2163                    ((struct ofp_action_dl_addr *) ia)->dl_addr, ETH_ADDR_LEN);
2164             break;
2165
2166         case OFPAT_SET_NW_SRC:
2167             oa = odp_actions_add(ctx->out, ODPAT_SET_NW_SRC);
2168             oa->nw_addr.nw_addr = ia->nw_addr.nw_addr;
2169             break;
2170
2171         case OFPAT_SET_NW_DST:
2172             oa = odp_actions_add(ctx->out, ODPAT_SET_NW_DST);
2173             oa->nw_addr.nw_addr = ia->nw_addr.nw_addr;
2174
2175         case OFPAT_SET_NW_TOS:
2176             oa = odp_actions_add(ctx->out, ODPAT_SET_NW_TOS);
2177             oa->nw_tos.nw_tos = ia->nw_tos.nw_tos;
2178             break;
2179
2180         case OFPAT_SET_TP_SRC:
2181             oa = odp_actions_add(ctx->out, ODPAT_SET_TP_SRC);
2182             oa->tp_port.tp_port = ia->tp_port.tp_port;
2183             break;
2184
2185         case OFPAT_SET_TP_DST:
2186             oa = odp_actions_add(ctx->out, ODPAT_SET_TP_DST);
2187             oa->tp_port.tp_port = ia->tp_port.tp_port;
2188             break;
2189
2190         case OFPAT_VENDOR:
2191             xlate_nicira_action(ctx, (const struct nx_action_header *) ia);
2192             break;
2193
2194         default:
2195             VLOG_DBG_RL(&rl, "unknown action type %"PRIu16, type);
2196             break;
2197         }
2198     }
2199 }
2200
2201 static int
2202 xlate_actions(const union ofp_action *in, size_t n_in,
2203               const flow_t *flow, struct ofproto *ofproto,
2204               const struct ofpbuf *packet,
2205               struct odp_actions *out, tag_type *tags, bool *may_set_up_flow,
2206               uint16_t *nf_output_iface)
2207 {
2208     tag_type no_tags = 0;
2209     struct action_xlate_ctx ctx;
2210     COVERAGE_INC(ofproto_ofp2odp);
2211     odp_actions_init(out);
2212     ctx.flow = flow;
2213     ctx.recurse = 0;
2214     ctx.ofproto = ofproto;
2215     ctx.packet = packet;
2216     ctx.out = out;
2217     ctx.tags = tags ? tags : &no_tags;
2218     ctx.may_set_up_flow = true;
2219     ctx.nf_output_iface = NF_OUT_DROP;
2220     do_xlate_actions(in, n_in, &ctx);
2221
2222     /* Check with in-band control to see if we're allowed to set up this
2223      * flow. */
2224     if (!in_band_rule_check(ofproto->in_band, flow, out)) {
2225         ctx.may_set_up_flow = false;
2226     }
2227
2228     if (may_set_up_flow) {
2229         *may_set_up_flow = ctx.may_set_up_flow;
2230     }
2231     if (nf_output_iface) {
2232         *nf_output_iface = ctx.nf_output_iface;
2233     }
2234     if (odp_actions_overflow(out)) {
2235         odp_actions_init(out);
2236         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_TOO_MANY);
2237     }
2238     return 0;
2239 }
2240
2241 static int
2242 handle_packet_out(struct ofproto *p, struct ofconn *ofconn,
2243                   struct ofp_header *oh)
2244 {
2245     struct ofp_packet_out *opo;
2246     struct ofpbuf payload, *buffer;
2247     struct odp_actions actions;
2248     int n_actions;
2249     uint16_t in_port;
2250     flow_t flow;
2251     int error;
2252
2253     error = check_ofp_packet_out(oh, &payload, &n_actions, p->max_ports);
2254     if (error) {
2255         return error;
2256     }
2257     opo = (struct ofp_packet_out *) oh;
2258
2259     COVERAGE_INC(ofproto_packet_out);
2260     if (opo->buffer_id != htonl(UINT32_MAX)) {
2261         error = pktbuf_retrieve(ofconn->pktbuf, ntohl(opo->buffer_id),
2262                                 &buffer, &in_port);
2263         if (error || !buffer) {
2264             return error;
2265         }
2266         payload = *buffer;
2267     } else {
2268         buffer = NULL;
2269     }
2270
2271     flow_extract(&payload, ofp_port_to_odp_port(ntohs(opo->in_port)), &flow);
2272     error = xlate_actions((const union ofp_action *) opo->actions, n_actions,
2273                           &flow, p, &payload, &actions, NULL, NULL, NULL);
2274     if (error) {
2275         return error;
2276     }
2277
2278     dpif_execute(p->dpif, flow.in_port, actions.actions, actions.n_actions,
2279                  &payload);
2280     ofpbuf_delete(buffer);
2281
2282     return 0;
2283 }
2284
2285 static void
2286 update_port_config(struct ofproto *p, struct ofport *port,
2287                    uint32_t config, uint32_t mask)
2288 {
2289     mask &= config ^ port->opp.config;
2290     if (mask & OFPPC_PORT_DOWN) {
2291         if (config & OFPPC_PORT_DOWN) {
2292             netdev_turn_flags_off(port->netdev, NETDEV_UP, true);
2293         } else {
2294             netdev_turn_flags_on(port->netdev, NETDEV_UP, true);
2295         }
2296     }
2297 #define REVALIDATE_BITS (OFPPC_NO_RECV | OFPPC_NO_RECV_STP | OFPPC_NO_FWD)
2298     if (mask & REVALIDATE_BITS) {
2299         COVERAGE_INC(ofproto_costly_flags);
2300         port->opp.config ^= mask & REVALIDATE_BITS;
2301         p->need_revalidate = true;
2302     }
2303 #undef REVALIDATE_BITS
2304     if (mask & OFPPC_NO_FLOOD) {
2305         port->opp.config ^= OFPPC_NO_FLOOD;
2306         refresh_port_groups(p);
2307     }
2308     if (mask & OFPPC_NO_PACKET_IN) {
2309         port->opp.config ^= OFPPC_NO_PACKET_IN;
2310     }
2311 }
2312
2313 static int
2314 handle_port_mod(struct ofproto *p, struct ofp_header *oh)
2315 {
2316     const struct ofp_port_mod *opm;
2317     struct ofport *port;
2318     int error;
2319
2320     error = check_ofp_message(oh, OFPT_PORT_MOD, sizeof *opm);
2321     if (error) {
2322         return error;
2323     }
2324     opm = (struct ofp_port_mod *) oh;
2325
2326     port = port_array_get(&p->ports,
2327                           ofp_port_to_odp_port(ntohs(opm->port_no)));
2328     if (!port) {
2329         return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_PORT);
2330     } else if (memcmp(port->opp.hw_addr, opm->hw_addr, OFP_ETH_ALEN)) {
2331         return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_HW_ADDR);
2332     } else {
2333         update_port_config(p, port, ntohl(opm->config), ntohl(opm->mask));
2334         if (opm->advertise) {
2335             netdev_set_advertisements(port->netdev, ntohl(opm->advertise));
2336         }
2337     }
2338     return 0;
2339 }
2340
2341 static struct ofpbuf *
2342 make_stats_reply(uint32_t xid, uint16_t type, size_t body_len)
2343 {
2344     struct ofp_stats_reply *osr;
2345     struct ofpbuf *msg;
2346
2347     msg = ofpbuf_new(MIN(sizeof *osr + body_len, UINT16_MAX));
2348     osr = put_openflow_xid(sizeof *osr, OFPT_STATS_REPLY, xid, msg);
2349     osr->type = type;
2350     osr->flags = htons(0);
2351     return msg;
2352 }
2353
2354 static struct ofpbuf *
2355 start_stats_reply(const struct ofp_stats_request *request, size_t body_len)
2356 {
2357     return make_stats_reply(request->header.xid, request->type, body_len);
2358 }
2359
2360 static void *
2361 append_stats_reply(size_t nbytes, struct ofconn *ofconn, struct ofpbuf **msgp)
2362 {
2363     struct ofpbuf *msg = *msgp;
2364     assert(nbytes <= UINT16_MAX - sizeof(struct ofp_stats_reply));
2365     if (nbytes + msg->size > UINT16_MAX) {
2366         struct ofp_stats_reply *reply = msg->data;
2367         reply->flags = htons(OFPSF_REPLY_MORE);
2368         *msgp = make_stats_reply(reply->header.xid, reply->type, nbytes);
2369         queue_tx(msg, ofconn, ofconn->reply_counter);
2370     }
2371     return ofpbuf_put_uninit(*msgp, nbytes);
2372 }
2373
2374 static int
2375 handle_desc_stats_request(struct ofproto *p, struct ofconn *ofconn,
2376                            struct ofp_stats_request *request)
2377 {
2378     struct ofp_desc_stats *ods;
2379     struct ofpbuf *msg;
2380
2381     msg = start_stats_reply(request, sizeof *ods);
2382     ods = append_stats_reply(sizeof *ods, ofconn, &msg);
2383     strncpy(ods->mfr_desc, p->manufacturer, sizeof ods->mfr_desc);
2384     strncpy(ods->hw_desc, p->hardware, sizeof ods->hw_desc);
2385     strncpy(ods->sw_desc, p->software, sizeof ods->sw_desc);
2386     strncpy(ods->serial_num, p->serial, sizeof ods->serial_num);
2387     queue_tx(msg, ofconn, ofconn->reply_counter);
2388
2389     return 0;
2390 }
2391
2392 static void
2393 count_subrules(struct cls_rule *cls_rule, void *n_subrules_)
2394 {
2395     struct rule *rule = rule_from_cls_rule(cls_rule);
2396     int *n_subrules = n_subrules_;
2397
2398     if (rule->super) {
2399         (*n_subrules)++;
2400     }
2401 }
2402
2403 static int
2404 handle_table_stats_request(struct ofproto *p, struct ofconn *ofconn,
2405                            struct ofp_stats_request *request)
2406 {
2407     struct ofp_table_stats *ots;
2408     struct ofpbuf *msg;
2409     struct odp_stats dpstats;
2410     int n_exact, n_subrules, n_wild;
2411
2412     msg = start_stats_reply(request, sizeof *ots * 2);
2413
2414     /* Count rules of various kinds. */
2415     n_subrules = 0;
2416     classifier_for_each(&p->cls, CLS_INC_EXACT, count_subrules, &n_subrules);
2417     n_exact = classifier_count_exact(&p->cls) - n_subrules;
2418     n_wild = classifier_count(&p->cls) - classifier_count_exact(&p->cls);
2419
2420     /* Hash table. */
2421     dpif_get_dp_stats(p->dpif, &dpstats);
2422     ots = append_stats_reply(sizeof *ots, ofconn, &msg);
2423     memset(ots, 0, sizeof *ots);
2424     ots->table_id = TABLEID_HASH;
2425     strcpy(ots->name, "hash");
2426     ots->wildcards = htonl(0);
2427     ots->max_entries = htonl(dpstats.max_capacity);
2428     ots->active_count = htonl(n_exact);
2429     ots->lookup_count = htonll(dpstats.n_frags + dpstats.n_hit +
2430                                dpstats.n_missed);
2431     ots->matched_count = htonll(dpstats.n_hit); /* XXX */
2432
2433     /* Classifier table. */
2434     ots = append_stats_reply(sizeof *ots, ofconn, &msg);
2435     memset(ots, 0, sizeof *ots);
2436     ots->table_id = TABLEID_CLASSIFIER;
2437     strcpy(ots->name, "classifier");
2438     ots->wildcards = htonl(OFPFW_ALL);
2439     ots->max_entries = htonl(65536);
2440     ots->active_count = htonl(n_wild);
2441     ots->lookup_count = htonll(0);              /* XXX */
2442     ots->matched_count = htonll(0);             /* XXX */
2443
2444     queue_tx(msg, ofconn, ofconn->reply_counter);
2445     return 0;
2446 }
2447
2448 static int
2449 handle_port_stats_request(struct ofproto *p, struct ofconn *ofconn,
2450                           struct ofp_stats_request *request)
2451 {
2452     struct ofp_port_stats *ops;
2453     struct ofpbuf *msg;
2454     struct ofport *port;
2455     unsigned int port_no;
2456
2457     msg = start_stats_reply(request, sizeof *ops * 16);
2458     PORT_ARRAY_FOR_EACH (port, &p->ports, port_no) {
2459         struct netdev_stats stats;
2460
2461         /* Intentionally ignore return value, since errors will set 'stats' to
2462          * all-1s, which is correct for OpenFlow, and netdev_get_stats() will
2463          * log errors. */
2464         netdev_get_stats(port->netdev, &stats);
2465
2466         ops = append_stats_reply(sizeof *ops, ofconn, &msg);
2467         ops->port_no = htons(odp_port_to_ofp_port(port_no));
2468         memset(ops->pad, 0, sizeof ops->pad);
2469         ops->rx_packets = htonll(stats.rx_packets);
2470         ops->tx_packets = htonll(stats.tx_packets);
2471         ops->rx_bytes = htonll(stats.rx_bytes);
2472         ops->tx_bytes = htonll(stats.tx_bytes);
2473         ops->rx_dropped = htonll(stats.rx_dropped);
2474         ops->tx_dropped = htonll(stats.tx_dropped);
2475         ops->rx_errors = htonll(stats.rx_errors);
2476         ops->tx_errors = htonll(stats.tx_errors);
2477         ops->rx_frame_err = htonll(stats.rx_frame_errors);
2478         ops->rx_over_err = htonll(stats.rx_over_errors);
2479         ops->rx_crc_err = htonll(stats.rx_crc_errors);
2480         ops->collisions = htonll(stats.collisions);
2481     }
2482
2483     queue_tx(msg, ofconn, ofconn->reply_counter);
2484     return 0;
2485 }
2486
2487 struct flow_stats_cbdata {
2488     struct ofproto *ofproto;
2489     struct ofconn *ofconn;
2490     uint16_t out_port;
2491     struct ofpbuf *msg;
2492 };
2493
2494 static void
2495 query_stats(struct ofproto *p, struct rule *rule,
2496             uint64_t *packet_countp, uint64_t *byte_countp)
2497 {
2498     uint64_t packet_count, byte_count;
2499     struct rule *subrule;
2500     struct odp_flow *odp_flows;
2501     size_t n_odp_flows;
2502
2503     packet_count = rule->packet_count;
2504     byte_count = rule->byte_count;
2505
2506     n_odp_flows = rule->cr.wc.wildcards ? list_size(&rule->list) : 1;
2507     odp_flows = xzalloc(n_odp_flows * sizeof *odp_flows);
2508     if (rule->cr.wc.wildcards) {
2509         size_t i = 0;
2510         LIST_FOR_EACH (subrule, struct rule, list, &rule->list) {
2511             odp_flows[i++].key = subrule->cr.flow;
2512             packet_count += subrule->packet_count;
2513             byte_count += subrule->byte_count;
2514         }
2515     } else {
2516         odp_flows[0].key = rule->cr.flow;
2517     }
2518
2519     packet_count = rule->packet_count;
2520     byte_count = rule->byte_count;
2521     if (!dpif_flow_get_multiple(p->dpif, odp_flows, n_odp_flows)) {
2522         size_t i;
2523         for (i = 0; i < n_odp_flows; i++) {
2524             struct odp_flow *odp_flow = &odp_flows[i];
2525             packet_count += odp_flow->stats.n_packets;
2526             byte_count += odp_flow->stats.n_bytes;
2527         }
2528     }
2529     free(odp_flows);
2530
2531     *packet_countp = packet_count;
2532     *byte_countp = byte_count;
2533 }
2534
2535 static void
2536 flow_stats_cb(struct cls_rule *rule_, void *cbdata_)
2537 {
2538     struct rule *rule = rule_from_cls_rule(rule_);
2539     struct flow_stats_cbdata *cbdata = cbdata_;
2540     struct ofp_flow_stats *ofs;
2541     uint64_t packet_count, byte_count;
2542     size_t act_len, len;
2543
2544     if (rule_is_hidden(rule) || !rule_has_out_port(rule, cbdata->out_port)) {
2545         return;
2546     }
2547
2548     act_len = sizeof *rule->actions * rule->n_actions;
2549     len = offsetof(struct ofp_flow_stats, actions) + act_len;
2550
2551     query_stats(cbdata->ofproto, rule, &packet_count, &byte_count);
2552
2553     ofs = append_stats_reply(len, cbdata->ofconn, &cbdata->msg);
2554     ofs->length = htons(len);
2555     ofs->table_id = rule->cr.wc.wildcards ? TABLEID_CLASSIFIER : TABLEID_HASH;
2556     ofs->pad = 0;
2557     flow_to_match(&rule->cr.flow, rule->cr.wc.wildcards, &ofs->match);
2558     ofs->duration = htonl((time_msec() - rule->created) / 1000);
2559     ofs->priority = htons(rule->cr.priority);
2560     ofs->idle_timeout = htons(rule->idle_timeout);
2561     ofs->hard_timeout = htons(rule->hard_timeout);
2562     ofs->pad2 = 0;
2563     ofs->packet_count = htonll(packet_count);
2564     ofs->byte_count = htonll(byte_count);
2565     memcpy(ofs->actions, rule->actions, act_len);
2566 }
2567
2568 static int
2569 table_id_to_include(uint8_t table_id)
2570 {
2571     return (table_id == TABLEID_HASH ? CLS_INC_EXACT
2572             : table_id == TABLEID_CLASSIFIER ? CLS_INC_WILD
2573             : table_id == 0xff ? CLS_INC_ALL
2574             : 0);
2575 }
2576
2577 static int
2578 handle_flow_stats_request(struct ofproto *p, struct ofconn *ofconn,
2579                           const struct ofp_stats_request *osr,
2580                           size_t arg_size)
2581 {
2582     struct ofp_flow_stats_request *fsr;
2583     struct flow_stats_cbdata cbdata;
2584     struct cls_rule target;
2585
2586     if (arg_size != sizeof *fsr) {
2587         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
2588     }
2589     fsr = (struct ofp_flow_stats_request *) osr->body;
2590
2591     COVERAGE_INC(ofproto_flows_req);
2592     cbdata.ofproto = p;
2593     cbdata.ofconn = ofconn;
2594     cbdata.out_port = fsr->out_port;
2595     cbdata.msg = start_stats_reply(osr, 1024);
2596     cls_rule_from_match(&target, &fsr->match, 0);
2597     classifier_for_each_match(&p->cls, &target,
2598                               table_id_to_include(fsr->table_id),
2599                               flow_stats_cb, &cbdata);
2600     queue_tx(cbdata.msg, ofconn, ofconn->reply_counter);
2601     return 0;
2602 }
2603
2604 struct flow_stats_ds_cbdata {
2605     struct ofproto *ofproto;
2606     struct ds *results;
2607 };
2608
2609 static void
2610 flow_stats_ds_cb(struct cls_rule *rule_, void *cbdata_)
2611 {
2612     struct rule *rule = rule_from_cls_rule(rule_);
2613     struct flow_stats_ds_cbdata *cbdata = cbdata_;
2614     struct ds *results = cbdata->results;
2615     struct ofp_match match;
2616     uint64_t packet_count, byte_count;
2617     size_t act_len = sizeof *rule->actions * rule->n_actions;
2618
2619     /* Don't report on subrules. */
2620     if (rule->super != NULL) {
2621         return;
2622     }
2623
2624     query_stats(cbdata->ofproto, rule, &packet_count, &byte_count);
2625     flow_to_ovs_match(&rule->cr.flow, rule->cr.wc.wildcards, &match);
2626
2627     ds_put_format(results, "duration=%llds, ",
2628                   (time_msec() - rule->created) / 1000);
2629     ds_put_format(results, "priority=%u, ", rule->cr.priority);
2630     ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
2631     ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
2632     ofp_print_match(results, &match, true);
2633     ofp_print_actions(results, &rule->actions->header, act_len);
2634     ds_put_cstr(results, "\n");
2635 }
2636
2637 /* Adds a pretty-printed description of all flows to 'results', including 
2638  * those marked hidden by secchan (e.g., by in-band control). */
2639 void
2640 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
2641 {
2642     struct ofp_match match;
2643     struct cls_rule target;
2644     struct flow_stats_ds_cbdata cbdata;
2645
2646     memset(&match, 0, sizeof match);
2647     match.wildcards = htonl(OFPFW_ALL);
2648
2649     cbdata.ofproto = p;
2650     cbdata.results = results;
2651
2652     cls_rule_from_match(&target, &match, 0);
2653     classifier_for_each_match(&p->cls, &target, CLS_INC_ALL,
2654                               flow_stats_ds_cb, &cbdata);
2655 }
2656
2657 struct aggregate_stats_cbdata {
2658     struct ofproto *ofproto;
2659     uint16_t out_port;
2660     uint64_t packet_count;
2661     uint64_t byte_count;
2662     uint32_t n_flows;
2663 };
2664
2665 static void
2666 aggregate_stats_cb(struct cls_rule *rule_, void *cbdata_)
2667 {
2668     struct rule *rule = rule_from_cls_rule(rule_);
2669     struct aggregate_stats_cbdata *cbdata = cbdata_;
2670     uint64_t packet_count, byte_count;
2671
2672     if (rule_is_hidden(rule) || !rule_has_out_port(rule, cbdata->out_port)) {
2673         return;
2674     }
2675
2676     query_stats(cbdata->ofproto, rule, &packet_count, &byte_count);
2677
2678     cbdata->packet_count += packet_count;
2679     cbdata->byte_count += byte_count;
2680     cbdata->n_flows++;
2681 }
2682
2683 static int
2684 handle_aggregate_stats_request(struct ofproto *p, struct ofconn *ofconn,
2685                                const struct ofp_stats_request *osr,
2686                                size_t arg_size)
2687 {
2688     struct ofp_aggregate_stats_request *asr;
2689     struct ofp_aggregate_stats_reply *reply;
2690     struct aggregate_stats_cbdata cbdata;
2691     struct cls_rule target;
2692     struct ofpbuf *msg;
2693
2694     if (arg_size != sizeof *asr) {
2695         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
2696     }
2697     asr = (struct ofp_aggregate_stats_request *) osr->body;
2698
2699     COVERAGE_INC(ofproto_agg_request);
2700     cbdata.ofproto = p;
2701     cbdata.out_port = asr->out_port;
2702     cbdata.packet_count = 0;
2703     cbdata.byte_count = 0;
2704     cbdata.n_flows = 0;
2705     cls_rule_from_match(&target, &asr->match, 0);
2706     classifier_for_each_match(&p->cls, &target,
2707                               table_id_to_include(asr->table_id),
2708                               aggregate_stats_cb, &cbdata);
2709
2710     msg = start_stats_reply(osr, sizeof *reply);
2711     reply = append_stats_reply(sizeof *reply, ofconn, &msg);
2712     reply->flow_count = htonl(cbdata.n_flows);
2713     reply->packet_count = htonll(cbdata.packet_count);
2714     reply->byte_count = htonll(cbdata.byte_count);
2715     queue_tx(msg, ofconn, ofconn->reply_counter);
2716     return 0;
2717 }
2718
2719 static int
2720 handle_stats_request(struct ofproto *p, struct ofconn *ofconn,
2721                      struct ofp_header *oh)
2722 {
2723     struct ofp_stats_request *osr;
2724     size_t arg_size;
2725     int error;
2726
2727     error = check_ofp_message_array(oh, OFPT_STATS_REQUEST, sizeof *osr,
2728                                     1, &arg_size);
2729     if (error) {
2730         return error;
2731     }
2732     osr = (struct ofp_stats_request *) oh;
2733
2734     switch (ntohs(osr->type)) {
2735     case OFPST_DESC:
2736         return handle_desc_stats_request(p, ofconn, osr);
2737
2738     case OFPST_FLOW:
2739         return handle_flow_stats_request(p, ofconn, osr, arg_size);
2740
2741     case OFPST_AGGREGATE:
2742         return handle_aggregate_stats_request(p, ofconn, osr, arg_size);
2743
2744     case OFPST_TABLE:
2745         return handle_table_stats_request(p, ofconn, osr);
2746
2747     case OFPST_PORT:
2748         return handle_port_stats_request(p, ofconn, osr);
2749
2750     case OFPST_VENDOR:
2751         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_VENDOR);
2752
2753     default:
2754         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT);
2755     }
2756 }
2757
2758 static long long int
2759 msec_from_nsec(uint64_t sec, uint32_t nsec)
2760 {
2761     return !sec ? 0 : sec * 1000 + nsec / 1000000;
2762 }
2763
2764 static void
2765 update_time(struct ofproto *ofproto, struct rule *rule,
2766             const struct odp_flow_stats *stats)
2767 {
2768     long long int used = msec_from_nsec(stats->used_sec, stats->used_nsec);
2769     if (used > rule->used) {
2770         rule->used = used;
2771         if (rule->super && used > rule->super->used) {
2772             rule->super->used = used;
2773         }
2774         netflow_flow_update_time(ofproto->netflow, &rule->nf_flow, used);
2775     }
2776 }
2777
2778 static void
2779 update_stats(struct ofproto *ofproto, struct rule *rule,
2780              const struct odp_flow_stats *stats)
2781 {
2782     if (stats->n_packets) {
2783         update_time(ofproto, rule, stats);
2784         rule->packet_count += stats->n_packets;
2785         rule->byte_count += stats->n_bytes;
2786         netflow_flow_update_flags(&rule->nf_flow, stats->ip_tos,
2787                                   stats->tcp_flags);
2788     }
2789 }
2790
2791 static int
2792 add_flow(struct ofproto *p, struct ofconn *ofconn,
2793          struct ofp_flow_mod *ofm, size_t n_actions)
2794 {
2795     struct ofpbuf *packet;
2796     struct rule *rule;
2797     uint16_t in_port;
2798     int error;
2799
2800     rule = rule_create(p, NULL, (const union ofp_action *) ofm->actions,
2801                        n_actions, ntohs(ofm->idle_timeout),
2802                        ntohs(ofm->hard_timeout));
2803     cls_rule_from_match(&rule->cr, &ofm->match, ntohs(ofm->priority));
2804
2805     error = 0;
2806     if (ofm->buffer_id != htonl(UINT32_MAX)) {
2807         error = pktbuf_retrieve(ofconn->pktbuf, ntohl(ofm->buffer_id),
2808                                 &packet, &in_port);
2809     } else {
2810         packet = NULL;
2811         in_port = UINT16_MAX;
2812     }
2813
2814     rule_insert(p, rule, packet, in_port);
2815     ofpbuf_delete(packet);
2816     return error;
2817 }
2818
2819 static int
2820 modify_flow(struct ofproto *p, const struct ofp_flow_mod *ofm,
2821             size_t n_actions, uint16_t command, struct rule *rule)
2822 {
2823     if (rule_is_hidden(rule)) {
2824         return 0;
2825     }
2826
2827     if (command == OFPFC_DELETE) {
2828         rule_remove(p, rule);
2829     } else {
2830         size_t actions_len = n_actions * sizeof *rule->actions;
2831
2832         if (n_actions == rule->n_actions
2833             && !memcmp(ofm->actions, rule->actions, actions_len))
2834         {
2835             return 0;
2836         }
2837
2838         free(rule->actions);
2839         rule->actions = xmemdup(ofm->actions, actions_len);
2840         rule->n_actions = n_actions;
2841
2842         if (rule->cr.wc.wildcards) {
2843             COVERAGE_INC(ofproto_mod_wc_flow);
2844             p->need_revalidate = true;
2845         } else {
2846             rule_update_actions(p, rule);
2847         }
2848     }
2849
2850     return 0;
2851 }
2852
2853 static int
2854 modify_flows_strict(struct ofproto *p, const struct ofp_flow_mod *ofm,
2855                     size_t n_actions, uint16_t command)
2856 {
2857     struct rule *rule;
2858     uint32_t wildcards;
2859     flow_t flow;
2860
2861     flow_from_match(&flow, &wildcards, &ofm->match);
2862     rule = rule_from_cls_rule(classifier_find_rule_exactly(
2863                                   &p->cls, &flow, wildcards,
2864                                   ntohs(ofm->priority)));
2865
2866     if (rule) {
2867         if (command == OFPFC_DELETE
2868             && ofm->out_port != htons(OFPP_NONE)
2869             && !rule_has_out_port(rule, ofm->out_port)) {
2870             return 0;
2871         }
2872
2873         modify_flow(p, ofm, n_actions, command, rule);
2874     }
2875     return 0;
2876 }
2877
2878 struct modify_flows_cbdata {
2879     struct ofproto *ofproto;
2880     const struct ofp_flow_mod *ofm;
2881     uint16_t out_port;
2882     size_t n_actions;
2883     uint16_t command;
2884 };
2885
2886 static void
2887 modify_flows_cb(struct cls_rule *rule_, void *cbdata_)
2888 {
2889     struct rule *rule = rule_from_cls_rule(rule_);
2890     struct modify_flows_cbdata *cbdata = cbdata_;
2891
2892     if (cbdata->out_port != htons(OFPP_NONE)
2893         && !rule_has_out_port(rule, cbdata->out_port)) {
2894         return;
2895     }
2896
2897     modify_flow(cbdata->ofproto, cbdata->ofm, cbdata->n_actions,
2898                 cbdata->command, rule);
2899 }
2900
2901 static int
2902 modify_flows_loose(struct ofproto *p, const struct ofp_flow_mod *ofm,
2903                    size_t n_actions, uint16_t command)
2904 {
2905     struct modify_flows_cbdata cbdata;
2906     struct cls_rule target;
2907
2908     cbdata.ofproto = p;
2909     cbdata.ofm = ofm;
2910     cbdata.out_port = (command == OFPFC_DELETE ? ofm->out_port
2911                        : htons(OFPP_NONE));
2912     cbdata.n_actions = n_actions;
2913     cbdata.command = command;
2914
2915     cls_rule_from_match(&target, &ofm->match, 0);
2916
2917     classifier_for_each_match(&p->cls, &target, CLS_INC_ALL,
2918                               modify_flows_cb, &cbdata);
2919     return 0;
2920 }
2921
2922 static int
2923 handle_flow_mod(struct ofproto *p, struct ofconn *ofconn,
2924                 struct ofp_flow_mod *ofm)
2925 {
2926     size_t n_actions;
2927     int error;
2928
2929     error = check_ofp_message_array(&ofm->header, OFPT_FLOW_MOD, sizeof *ofm,
2930                                     sizeof *ofm->actions, &n_actions);
2931     if (error) {
2932         return error;
2933     }
2934
2935     normalize_match(&ofm->match);
2936     if (!ofm->match.wildcards) {
2937         ofm->priority = htons(UINT16_MAX);
2938     }
2939
2940     error = validate_actions((const union ofp_action *) ofm->actions,
2941                              n_actions, p->max_ports);
2942     if (error) {
2943         return error;
2944     }
2945
2946     switch (ntohs(ofm->command)) {
2947     case OFPFC_ADD:
2948         return add_flow(p, ofconn, ofm, n_actions);
2949
2950     case OFPFC_MODIFY:
2951         return modify_flows_loose(p, ofm, n_actions, OFPFC_MODIFY);
2952
2953     case OFPFC_MODIFY_STRICT:
2954         return modify_flows_strict(p, ofm, n_actions, OFPFC_MODIFY);
2955
2956     case OFPFC_DELETE:
2957         return modify_flows_loose(p, ofm, n_actions, OFPFC_DELETE);
2958
2959     case OFPFC_DELETE_STRICT:
2960         return modify_flows_strict(p, ofm, n_actions, OFPFC_DELETE);
2961
2962     default:
2963         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_BAD_COMMAND);
2964     }
2965 }
2966
2967 static int
2968 handle_vendor(struct ofproto *p, struct ofconn *ofconn, void *msg)
2969 {
2970     struct ofp_vendor_header *ovh = msg;
2971     struct nicira_header *nh;
2972
2973     if (ntohs(ovh->header.length) < sizeof(struct ofp_vendor_header)) {
2974         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
2975     }
2976     if (ovh->vendor != htonl(NX_VENDOR_ID)) {
2977         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_VENDOR);
2978     }
2979     if (ntohs(ovh->header.length) < sizeof(struct nicira_header)) {
2980         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
2981     }
2982
2983     nh = msg;
2984     switch (ntohl(nh->subtype)) {
2985     case NXT_STATUS_REQUEST:
2986         return switch_status_handle_request(p->switch_status, ofconn->rconn,
2987                                             msg);
2988     }
2989
2990     return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE);
2991 }
2992
2993 static void
2994 handle_openflow(struct ofconn *ofconn, struct ofproto *p,
2995                 struct ofpbuf *ofp_msg)
2996 {
2997     struct ofp_header *oh = ofp_msg->data;
2998     int error;
2999
3000     COVERAGE_INC(ofproto_recv_openflow);
3001     switch (oh->type) {
3002     case OFPT_ECHO_REQUEST:
3003         error = handle_echo_request(ofconn, oh);
3004         break;
3005
3006     case OFPT_ECHO_REPLY:
3007         error = 0;
3008         break;
3009
3010     case OFPT_FEATURES_REQUEST:
3011         error = handle_features_request(p, ofconn, oh);
3012         break;
3013
3014     case OFPT_GET_CONFIG_REQUEST:
3015         error = handle_get_config_request(p, ofconn, oh);
3016         break;
3017
3018     case OFPT_SET_CONFIG:
3019         error = handle_set_config(p, ofconn, ofp_msg->data);
3020         break;
3021
3022     case OFPT_PACKET_OUT:
3023         error = handle_packet_out(p, ofconn, ofp_msg->data);
3024         break;
3025
3026     case OFPT_PORT_MOD:
3027         error = handle_port_mod(p, oh);
3028         break;
3029
3030     case OFPT_FLOW_MOD:
3031         error = handle_flow_mod(p, ofconn, ofp_msg->data);
3032         break;
3033
3034     case OFPT_STATS_REQUEST:
3035         error = handle_stats_request(p, ofconn, oh);
3036         break;
3037
3038     case OFPT_VENDOR:
3039         error = handle_vendor(p, ofconn, ofp_msg->data);
3040         break;
3041
3042     default:
3043         if (VLOG_IS_WARN_ENABLED()) {
3044             char *s = ofp_to_string(oh, ntohs(oh->length), 2);
3045             VLOG_DBG_RL(&rl, "OpenFlow message ignored: %s", s);
3046             free(s);
3047         }
3048         error = ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
3049         break;
3050     }
3051
3052     if (error) {
3053         send_error_oh(ofconn, ofp_msg->data, error);
3054     }
3055 }
3056 \f
3057 static void
3058 handle_odp_miss_msg(struct ofproto *p, struct ofpbuf *packet)
3059 {
3060     struct odp_msg *msg = packet->data;
3061     uint16_t in_port = odp_port_to_ofp_port(msg->port);
3062     struct rule *rule;
3063     struct ofpbuf payload;
3064     flow_t flow;
3065
3066     payload.data = msg + 1;
3067     payload.size = msg->length - sizeof *msg;
3068     flow_extract(&payload, msg->port, &flow);
3069
3070     /* Check with in-band control to see if this packet should be sent
3071      * to the local port regardless of the flow table. */
3072     if (in_band_msg_in_hook(p->in_band, &flow, &payload)) {
3073         union odp_action action;
3074
3075         memset(&action, 0, sizeof(action));
3076         action.output.type = ODPAT_OUTPUT;
3077         action.output.port = ODPP_LOCAL;
3078         dpif_execute(p->dpif, flow.in_port, &action, 1, &payload);
3079     }
3080
3081     rule = lookup_valid_rule(p, &flow);
3082     if (!rule) {
3083         /* Don't send a packet-in if OFPPC_NO_PACKET_IN asserted. */
3084         struct ofport *port = port_array_get(&p->ports, msg->port);
3085         if (port) {
3086             if (port->opp.config & OFPPC_NO_PACKET_IN) {
3087                 COVERAGE_INC(ofproto_no_packet_in);
3088                 /* XXX install 'drop' flow entry */
3089                 ofpbuf_delete(packet);
3090                 return;
3091             }
3092         } else {
3093             VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16, msg->port);
3094         }
3095
3096         COVERAGE_INC(ofproto_packet_in);
3097         pinsched_send(p->miss_sched, in_port, packet, send_packet_in_miss, p);
3098         return;
3099     }
3100
3101     if (rule->cr.wc.wildcards) {
3102         rule = rule_create_subrule(p, rule, &flow);
3103         rule_make_actions(p, rule, packet);
3104     } else {
3105         if (!rule->may_install) {
3106             /* The rule is not installable, that is, we need to process every
3107              * packet, so process the current packet and set its actions into
3108              * 'subrule'. */
3109             rule_make_actions(p, rule, packet);
3110         } else {
3111             /* XXX revalidate rule if it needs it */
3112         }
3113     }
3114
3115     rule_execute(p, rule, &payload, &flow);
3116     rule_reinstall(p, rule);
3117
3118     if (rule->super && rule->super->cr.priority == FAIL_OPEN_PRIORITY
3119         && rconn_is_connected(p->controller->rconn)) {
3120         /*
3121          * Extra-special case for fail-open mode.
3122          *
3123          * We are in fail-open mode and the packet matched the fail-open rule,
3124          * but we are connected to a controller too.  We should send the packet
3125          * up to the controller in the hope that it will try to set up a flow
3126          * and thereby allow us to exit fail-open.
3127          *
3128          * See the top-level comment in fail-open.c for more information.
3129          */
3130         pinsched_send(p->miss_sched, in_port, packet, send_packet_in_miss, p);
3131     } else {
3132         ofpbuf_delete(packet);
3133     }
3134 }
3135
3136 static void
3137 handle_odp_msg(struct ofproto *p, struct ofpbuf *packet)
3138 {
3139     struct odp_msg *msg = packet->data;
3140
3141     switch (msg->type) {
3142     case _ODPL_ACTION_NR:
3143         COVERAGE_INC(ofproto_ctlr_action);
3144         pinsched_send(p->action_sched, odp_port_to_ofp_port(msg->port), packet,
3145                       send_packet_in_action, p);
3146         break;
3147
3148     case _ODPL_SFLOW_NR:
3149         if (p->sflow) {
3150             ofproto_sflow_received(p->sflow, msg);
3151         }
3152         ofpbuf_delete(packet);
3153         break;
3154
3155     case _ODPL_MISS_NR:
3156         handle_odp_miss_msg(p, packet);
3157         break;
3158
3159     default:
3160         VLOG_WARN_RL(&rl, "received ODP message of unexpected type %"PRIu32,
3161                      msg->type);
3162         break;
3163     }
3164 }
3165 \f
3166 static void
3167 revalidate_cb(struct cls_rule *sub_, void *cbdata_)
3168 {
3169     struct rule *sub = rule_from_cls_rule(sub_);
3170     struct revalidate_cbdata *cbdata = cbdata_;
3171
3172     if (cbdata->revalidate_all
3173         || (cbdata->revalidate_subrules && sub->super)
3174         || (tag_set_intersects(&cbdata->revalidate_set, sub->tags))) {
3175         revalidate_rule(cbdata->ofproto, sub);
3176     }
3177 }
3178
3179 static bool
3180 revalidate_rule(struct ofproto *p, struct rule *rule)
3181 {
3182     const flow_t *flow = &rule->cr.flow;
3183
3184     COVERAGE_INC(ofproto_revalidate_rule);
3185     if (rule->super) {
3186         struct rule *super;
3187         super = rule_from_cls_rule(classifier_lookup_wild(&p->cls, flow));
3188         if (!super) {
3189             rule_remove(p, rule);
3190             return false;
3191         } else if (super != rule->super) {
3192             COVERAGE_INC(ofproto_revalidate_moved);
3193             list_remove(&rule->list);
3194             list_push_back(&super->list, &rule->list);
3195             rule->super = super;
3196             rule->hard_timeout = super->hard_timeout;
3197             rule->idle_timeout = super->idle_timeout;
3198             rule->created = super->created;
3199             rule->used = 0;
3200         }
3201     }
3202
3203     rule_update_actions(p, rule);
3204     return true;
3205 }
3206
3207 static struct ofpbuf *
3208 compose_flow_exp(const struct rule *rule, long long int now, uint8_t reason)
3209 {
3210     struct ofp_flow_expired *ofe;
3211     struct ofpbuf *buf;
3212
3213     ofe = make_openflow(sizeof *ofe, OFPT_FLOW_EXPIRED, &buf);
3214     flow_to_match(&rule->cr.flow, rule->cr.wc.wildcards, &ofe->match);
3215     ofe->priority = htons(rule->cr.priority);
3216     ofe->reason = reason;
3217     ofe->duration = htonl((now - rule->created) / 1000);
3218     ofe->packet_count = htonll(rule->packet_count);
3219     ofe->byte_count = htonll(rule->byte_count);
3220
3221     return buf;
3222 }
3223
3224 static void
3225 send_flow_exp(struct ofproto *p, struct rule *rule,
3226               long long int now, uint8_t reason)
3227 {
3228     struct ofconn *ofconn;
3229     struct ofconn *prev;
3230     struct ofpbuf *buf = NULL;
3231
3232     /* We limit the maximum number of queued flow expirations it by accounting
3233      * them under the counter for replies.  That works because preventing
3234      * OpenFlow requests from being processed also prevents new flows from
3235      * being added (and expiring).  (It also prevents processing OpenFlow
3236      * requests that would not add new flows, so it is imperfect.) */
3237
3238     prev = NULL;
3239     LIST_FOR_EACH (ofconn, struct ofconn, node, &p->all_conns) {
3240         if (ofconn->send_flow_exp && rconn_is_connected(ofconn->rconn)) {
3241             if (prev) {
3242                 queue_tx(ofpbuf_clone(buf), prev, prev->reply_counter);
3243             } else {
3244                 buf = compose_flow_exp(rule, now, reason);
3245             }
3246             prev = ofconn;
3247         }
3248     }
3249     if (prev) {
3250         queue_tx(buf, prev, prev->reply_counter);
3251     }
3252 }
3253
3254 static void
3255 uninstall_idle_flow(struct ofproto *ofproto, struct rule *rule)
3256 {
3257     assert(rule->installed);
3258     assert(!rule->cr.wc.wildcards);
3259
3260     if (rule->super) {
3261         rule_remove(ofproto, rule);
3262     } else {
3263         rule_uninstall(ofproto, rule);
3264     }
3265 }
3266
3267 static void
3268 expire_rule(struct cls_rule *cls_rule, void *p_)
3269 {
3270     struct ofproto *p = p_;
3271     struct rule *rule = rule_from_cls_rule(cls_rule);
3272     long long int hard_expire, idle_expire, expire, now;
3273
3274     hard_expire = (rule->hard_timeout
3275                    ? rule->created + rule->hard_timeout * 1000
3276                    : LLONG_MAX);
3277     idle_expire = (rule->idle_timeout
3278                    && (rule->super || list_is_empty(&rule->list))
3279                    ? rule->used + rule->idle_timeout * 1000
3280                    : LLONG_MAX);
3281     expire = MIN(hard_expire, idle_expire);
3282
3283     now = time_msec();
3284     if (now < expire) {
3285         if (rule->installed && now >= rule->used + 5000) {
3286             uninstall_idle_flow(p, rule);
3287         } else if (!rule->cr.wc.wildcards) {
3288             active_timeout(p, rule);
3289         }
3290
3291         return;
3292     }
3293
3294     COVERAGE_INC(ofproto_expired);
3295
3296     /* Update stats.  This code will be a no-op if the rule expired
3297      * due to an idle timeout. */
3298     if (rule->cr.wc.wildcards) {
3299         struct rule *subrule, *next;
3300         LIST_FOR_EACH_SAFE (subrule, next, struct rule, list, &rule->list) {
3301             rule_remove(p, subrule);
3302         }
3303     } else {
3304         rule_uninstall(p, rule);
3305     }
3306
3307     if (!rule_is_hidden(rule)) {
3308         send_flow_exp(p, rule, now,
3309                       (now >= hard_expire
3310                        ? OFPER_HARD_TIMEOUT : OFPER_IDLE_TIMEOUT));
3311     }
3312     rule_remove(p, rule);
3313 }
3314
3315 static void
3316 active_timeout(struct ofproto *ofproto, struct rule *rule)
3317 {
3318     if (ofproto->netflow && !is_controller_rule(rule) &&
3319         netflow_active_timeout_expired(ofproto->netflow, &rule->nf_flow)) {
3320         struct ofexpired expired;
3321         struct odp_flow odp_flow;
3322
3323         /* Get updated flow stats. */
3324         memset(&odp_flow, 0, sizeof odp_flow);
3325         if (rule->installed) {
3326             odp_flow.key = rule->cr.flow;
3327             odp_flow.flags = ODPFF_ZERO_TCP_FLAGS;
3328             dpif_flow_get(ofproto->dpif, &odp_flow);
3329
3330             if (odp_flow.stats.n_packets) {
3331                 update_time(ofproto, rule, &odp_flow.stats);
3332                 netflow_flow_update_flags(&rule->nf_flow, odp_flow.stats.ip_tos,
3333                                           odp_flow.stats.tcp_flags);
3334             }
3335         }
3336
3337         expired.flow = rule->cr.flow;
3338         expired.packet_count = rule->packet_count +
3339                                odp_flow.stats.n_packets;
3340         expired.byte_count = rule->byte_count + odp_flow.stats.n_bytes;
3341         expired.used = rule->used;
3342
3343         netflow_expire(ofproto->netflow, &rule->nf_flow, &expired);
3344
3345         /* Schedule us to send the accumulated records once we have
3346          * collected all of them. */
3347         poll_immediate_wake();
3348     }
3349 }
3350
3351 static void
3352 update_used(struct ofproto *p)
3353 {
3354     struct odp_flow *flows;
3355     size_t n_flows;
3356     size_t i;
3357     int error;
3358
3359     error = dpif_flow_list_all(p->dpif, &flows, &n_flows);
3360     if (error) {
3361         return;
3362     }
3363
3364     for (i = 0; i < n_flows; i++) {
3365         struct odp_flow *f = &flows[i];
3366         struct rule *rule;
3367
3368         rule = rule_from_cls_rule(
3369             classifier_find_rule_exactly(&p->cls, &f->key, 0, UINT16_MAX));
3370         if (!rule || !rule->installed) {
3371             COVERAGE_INC(ofproto_unexpected_rule);
3372             dpif_flow_del(p->dpif, f);
3373             continue;
3374         }
3375
3376         update_time(p, rule, &f->stats);
3377         rule_account(p, rule, f->stats.n_bytes);
3378     }
3379     free(flows);
3380 }
3381
3382 static void
3383 do_send_packet_in(struct ofconn *ofconn, uint32_t buffer_id,
3384                   const struct ofpbuf *packet, int send_len)
3385 {
3386     struct odp_msg *msg = packet->data;
3387     struct ofpbuf payload;
3388     struct ofpbuf *opi;
3389     uint8_t reason;
3390
3391     /* Extract packet payload from 'msg'. */
3392     payload.data = msg + 1;
3393     payload.size = msg->length - sizeof *msg;
3394
3395     /* Construct ofp_packet_in message. */
3396     reason = msg->type == _ODPL_ACTION_NR ? OFPR_ACTION : OFPR_NO_MATCH;
3397     opi = make_packet_in(buffer_id, odp_port_to_ofp_port(msg->port), reason,
3398                          &payload, send_len);
3399
3400     /* Send. */
3401     rconn_send_with_limit(ofconn->rconn, opi, ofconn->packet_in_counter, 100);
3402 }
3403
3404 static void
3405 send_packet_in_action(struct ofpbuf *packet, void *p_)
3406 {
3407     struct ofproto *p = p_;
3408     struct ofconn *ofconn;
3409     struct odp_msg *msg;
3410
3411     msg = packet->data;
3412     LIST_FOR_EACH (ofconn, struct ofconn, node, &p->all_conns) {
3413         if (ofconn == p->controller || ofconn->miss_send_len) {
3414             do_send_packet_in(ofconn, UINT32_MAX, packet, msg->arg);
3415         }
3416     }
3417     ofpbuf_delete(packet);
3418 }
3419
3420 static void
3421 send_packet_in_miss(struct ofpbuf *packet, void *p_)
3422 {
3423     struct ofproto *p = p_;
3424     bool in_fail_open = p->fail_open && fail_open_is_active(p->fail_open);
3425     struct ofconn *ofconn;
3426     struct ofpbuf payload;
3427     struct odp_msg *msg;
3428
3429     msg = packet->data;
3430     payload.data = msg + 1;
3431     payload.size = msg->length - sizeof *msg;
3432     LIST_FOR_EACH (ofconn, struct ofconn, node, &p->all_conns) {
3433         if (ofconn->miss_send_len) {
3434             struct pktbuf *pb = ofconn->pktbuf;
3435             uint32_t buffer_id = (in_fail_open
3436                                   ? pktbuf_get_null()
3437                                   : pktbuf_save(pb, &payload, msg->port));
3438             int send_len = (buffer_id != UINT32_MAX ? ofconn->miss_send_len
3439                             : UINT32_MAX);
3440             do_send_packet_in(ofconn, buffer_id, packet, send_len);
3441         }
3442     }
3443     ofpbuf_delete(packet);
3444 }
3445
3446 static uint64_t
3447 pick_datapath_id(const struct ofproto *ofproto)
3448 {
3449     const struct ofport *port;
3450
3451     port = port_array_get(&ofproto->ports, ODPP_LOCAL);
3452     if (port) {
3453         uint8_t ea[ETH_ADDR_LEN];
3454         int error;
3455
3456         error = netdev_get_etheraddr(port->netdev, ea);
3457         if (!error) {
3458             return eth_addr_to_uint64(ea);
3459         }
3460         VLOG_WARN("could not get MAC address for %s (%s)",
3461                   netdev_get_name(port->netdev), strerror(error));
3462     }
3463     return ofproto->fallback_dpid;
3464 }
3465
3466 static uint64_t
3467 pick_fallback_dpid(void)
3468 {
3469     uint8_t ea[ETH_ADDR_LEN];
3470     eth_addr_nicira_random(ea);
3471     return eth_addr_to_uint64(ea);
3472 }
3473 \f
3474 static bool
3475 default_normal_ofhook_cb(const flow_t *flow, const struct ofpbuf *packet,
3476                          struct odp_actions *actions, tag_type *tags,
3477                          uint16_t *nf_output_iface, void *ofproto_)
3478 {
3479     struct ofproto *ofproto = ofproto_;
3480     int out_port;
3481
3482     /* Drop frames for reserved multicast addresses. */
3483     if (eth_addr_is_reserved(flow->dl_dst)) {
3484         return true;
3485     }
3486
3487     /* Learn source MAC (but don't try to learn from revalidation). */
3488     if (packet != NULL) {
3489         tag_type rev_tag = mac_learning_learn(ofproto->ml, flow->dl_src,
3490                                               0, flow->in_port);
3491         if (rev_tag) {
3492             /* The log messages here could actually be useful in debugging,
3493              * so keep the rate limit relatively high. */
3494             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
3495             VLOG_DBG_RL(&rl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
3496                         ETH_ADDR_ARGS(flow->dl_src), flow->in_port);
3497             ofproto_revalidate(ofproto, rev_tag);
3498         }
3499     }
3500
3501     /* Determine output port. */
3502     out_port = mac_learning_lookup_tag(ofproto->ml, flow->dl_dst, 0, tags);
3503     if (out_port < 0) {
3504         add_output_group_action(actions, DP_GROUP_FLOOD, nf_output_iface);
3505     } else if (out_port != flow->in_port) {
3506         odp_actions_add(actions, ODPAT_OUTPUT)->output.port = out_port;
3507         *nf_output_iface = out_port;
3508     } else {
3509         /* Drop. */
3510     }
3511
3512     return true;
3513 }
3514
3515 static const struct ofhooks default_ofhooks = {
3516     NULL,
3517     default_normal_ofhook_cb,
3518     NULL,
3519     NULL
3520 };