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