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