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