ofproto: Consistently use netdev's name instead of ofp_phy_port name.
[sliver-openvswitch.git] / ofproto / ofproto.c
1 /*
2  * Copyright (c) 2009, 2010, 2011 Nicira Networks.
3  * Copyright (c) 2010 Jean Tourrilhes - HP-Labs.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at:
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #include <config.h>
19 #include "ofproto.h"
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <sys/socket.h>
23 #include <net/if.h>
24 #include <netinet/in.h>
25 #include <stdbool.h>
26 #include <stdlib.h>
27 #include "byte-order.h"
28 #include "cfm.h"
29 #include "classifier.h"
30 #include "connmgr.h"
31 #include "coverage.h"
32 #include "dpif.h"
33 #include "dynamic-string.h"
34 #include "fail-open.h"
35 #include "hash.h"
36 #include "hmap.h"
37 #include "in-band.h"
38 #include "mac-learning.h"
39 #include "multipath.h"
40 #include "netdev.h"
41 #include "netflow.h"
42 #include "netlink.h"
43 #include "nx-match.h"
44 #include "odp-util.h"
45 #include "ofp-print.h"
46 #include "ofp-util.h"
47 #include "ofproto-sflow.h"
48 #include "ofpbuf.h"
49 #include "openflow/nicira-ext.h"
50 #include "openflow/openflow.h"
51 #include "openvswitch/datapath-protocol.h"
52 #include "packets.h"
53 #include "pinsched.h"
54 #include "pktbuf.h"
55 #include "poll-loop.h"
56 #include "rconn.h"
57 #include "shash.h"
58 #include "sset.h"
59 #include "stream-ssl.h"
60 #include "tag.h"
61 #include "timer.h"
62 #include "timeval.h"
63 #include "unaligned.h"
64 #include "unixctl.h"
65 #include "vconn.h"
66 #include "vlog.h"
67
68 VLOG_DEFINE_THIS_MODULE(ofproto);
69
70 COVERAGE_DEFINE(facet_changed_rule);
71 COVERAGE_DEFINE(facet_revalidate);
72 COVERAGE_DEFINE(odp_overflow);
73 COVERAGE_DEFINE(ofproto_agg_request);
74 COVERAGE_DEFINE(ofproto_costly_flags);
75 COVERAGE_DEFINE(ofproto_ctlr_action);
76 COVERAGE_DEFINE(ofproto_del_rule);
77 COVERAGE_DEFINE(ofproto_error);
78 COVERAGE_DEFINE(ofproto_expiration);
79 COVERAGE_DEFINE(ofproto_expired);
80 COVERAGE_DEFINE(ofproto_flows_req);
81 COVERAGE_DEFINE(ofproto_flush);
82 COVERAGE_DEFINE(ofproto_invalidated);
83 COVERAGE_DEFINE(ofproto_no_packet_in);
84 COVERAGE_DEFINE(ofproto_ofp2odp);
85 COVERAGE_DEFINE(ofproto_packet_in);
86 COVERAGE_DEFINE(ofproto_packet_out);
87 COVERAGE_DEFINE(ofproto_queue_req);
88 COVERAGE_DEFINE(ofproto_recv_openflow);
89 COVERAGE_DEFINE(ofproto_reinit_ports);
90 COVERAGE_DEFINE(ofproto_unexpected_rule);
91 COVERAGE_DEFINE(ofproto_uninstallable);
92 COVERAGE_DEFINE(ofproto_update_port);
93
94 /* Maximum depth of flow table recursion (due to NXAST_RESUBMIT actions) in a
95  * flow translation. */
96 #define MAX_RESUBMIT_RECURSION 16
97
98 struct rule;
99
100 struct ofport {
101     struct hmap_node hmap_node; /* In struct ofproto's "ports" hmap. */
102     struct netdev *netdev;
103     struct ofp_phy_port opp;    /* In host byte order. */
104     uint16_t odp_port;
105     struct cfm *cfm;            /* Connectivity Fault Management, if any. */
106 };
107
108 static void ofport_free(struct ofport *);
109 static void ofport_run(struct ofproto *, struct ofport *);
110 static void ofport_wait(struct ofport *);
111
112 struct action_xlate_ctx {
113 /* action_xlate_ctx_init() initializes these members. */
114
115     /* The ofproto. */
116     struct ofproto *ofproto;
117
118     /* Flow to which the OpenFlow actions apply.  xlate_actions() will modify
119      * this flow when actions change header fields. */
120     struct flow flow;
121
122     /* The packet corresponding to 'flow', or a null pointer if we are
123      * revalidating without a packet to refer to. */
124     const struct ofpbuf *packet;
125
126     /* If nonnull, called just before executing a resubmit action.
127      *
128      * This is normally null so the client has to set it manually after
129      * calling action_xlate_ctx_init(). */
130     void (*resubmit_hook)(struct action_xlate_ctx *, struct rule *);
131
132     /* If true, the speciality of 'flow' should be checked before executing
133      * its actions.  If special_cb returns false on 'flow' rendered
134      * uninstallable and no actions will be executed. */
135     bool check_special;
136
137 /* xlate_actions() initializes and uses these members.  The client might want
138  * to look at them after it returns. */
139
140     struct ofpbuf *odp_actions; /* Datapath actions. */
141     tag_type tags;              /* Tags associated with OFPP_NORMAL actions. */
142     bool may_set_up_flow;       /* True ordinarily; false if the actions must
143                                  * be reassessed for every packet. */
144     uint16_t nf_output_iface;   /* Output interface index for NetFlow. */
145
146 /* xlate_actions() initializes and uses these members, but the client has no
147  * reason to look at them. */
148
149     int recurse;                /* Recursion level, via xlate_table_action. */
150     int last_pop_priority;      /* Offset in 'odp_actions' just past most
151                                  * recent ODP_ACTION_ATTR_SET_PRIORITY. */
152 };
153
154 static void action_xlate_ctx_init(struct action_xlate_ctx *,
155                                   struct ofproto *, const struct flow *,
156                                   const struct ofpbuf *);
157 static struct ofpbuf *xlate_actions(struct action_xlate_ctx *,
158                                     const union ofp_action *in, size_t n_in);
159
160 /* An OpenFlow flow. */
161 struct rule {
162     long long int used;         /* Time last used; time created if not used. */
163     long long int created;      /* Creation time. */
164
165     /* These statistics:
166      *
167      *   - Do include packets and bytes from facets that have been deleted or
168      *     whose own statistics have been folded into the rule.
169      *
170      *   - Do include packets and bytes sent "by hand" that were accounted to
171      *     the rule without any facet being involved (this is a rare corner
172      *     case in rule_execute()).
173      *
174      *   - Do not include packet or bytes that can be obtained from any facet's
175      *     packet_count or byte_count member or that can be obtained from the
176      *     datapath by, e.g., dpif_flow_get() for any facet.
177      */
178     uint64_t packet_count;       /* Number of packets received. */
179     uint64_t byte_count;         /* Number of bytes received. */
180
181     ovs_be64 flow_cookie;        /* Controller-issued identifier. */
182
183     struct cls_rule cr;          /* In owning ofproto's classifier. */
184     uint16_t idle_timeout;       /* In seconds from time of last use. */
185     uint16_t hard_timeout;       /* In seconds from time of creation. */
186     bool send_flow_removed;      /* Send a flow removed message? */
187     int n_actions;               /* Number of elements in actions[]. */
188     union ofp_action *actions;   /* OpenFlow actions. */
189     struct list facets;          /* List of "struct facet"s. */
190 };
191
192 static struct rule *rule_from_cls_rule(const struct cls_rule *);
193 static bool rule_is_hidden(const struct rule *);
194
195 static struct rule *rule_create(const struct cls_rule *,
196                                 const union ofp_action *, size_t n_actions,
197                                 uint16_t idle_timeout, uint16_t hard_timeout,
198                                 ovs_be64 flow_cookie, bool send_flow_removed);
199 static void rule_destroy(struct ofproto *, struct rule *);
200 static void rule_free(struct rule *);
201
202 static struct rule *rule_lookup(struct ofproto *, const struct flow *);
203 static void rule_insert(struct ofproto *, struct rule *);
204 static void rule_remove(struct ofproto *, struct rule *);
205
206 static void rule_send_removed(struct ofproto *, struct rule *, uint8_t reason);
207 static void rule_get_stats(const struct rule *, uint64_t *packets,
208                            uint64_t *bytes);
209
210 /* An exact-match instantiation of an OpenFlow flow. */
211 struct facet {
212     long long int used;         /* Time last used; time created if not used. */
213
214     /* These statistics:
215      *
216      *   - Do include packets and bytes sent "by hand", e.g. with
217      *     dpif_execute().
218      *
219      *   - Do include packets and bytes that were obtained from the datapath
220      *     when a flow was deleted (e.g. dpif_flow_del()) or when its
221      *     statistics were reset (e.g. dpif_flow_put() with
222      *     DPIF_FP_ZERO_STATS).
223      *
224      *   - Do not include any packets or bytes that can currently be obtained
225      *     from the datapath by, e.g., dpif_flow_get().
226      */
227     uint64_t packet_count;       /* Number of packets received. */
228     uint64_t byte_count;         /* Number of bytes received. */
229
230     uint64_t dp_packet_count;    /* Last known packet count in the datapath. */
231     uint64_t dp_byte_count;      /* Last known byte count in the datapath. */
232
233     uint64_t rs_packet_count;    /* Packets pushed to resubmit children. */
234     uint64_t rs_byte_count;      /* Bytes pushed to resubmit children. */
235     long long int rs_used;       /* Used time pushed to resubmit children. */
236
237     /* Number of bytes passed to account_cb.  This may include bytes that can
238      * currently obtained from the datapath (thus, it can be greater than
239      * byte_count). */
240     uint64_t accounted_bytes;
241
242     struct hmap_node hmap_node;  /* In owning ofproto's 'facets' hmap. */
243     struct list list_node;       /* In owning rule's 'facets' list. */
244     struct rule *rule;           /* Owning rule. */
245     struct flow flow;            /* Exact-match flow. */
246     bool installed;              /* Installed in datapath? */
247     bool may_install;            /* True ordinarily; false if actions must
248                                   * be reassessed for every packet. */
249     size_t actions_len;          /* Number of bytes in actions[]. */
250     struct nlattr *actions;      /* Datapath actions. */
251     tag_type tags;               /* Tags (set only by hooks). */
252     struct netflow_flow nf_flow; /* Per-flow NetFlow tracking data. */
253 };
254
255 static struct facet *facet_create(struct ofproto *, struct rule *,
256                                   const struct flow *,
257                                   const struct ofpbuf *packet);
258 static void facet_remove(struct ofproto *, struct facet *);
259 static void facet_free(struct facet *);
260
261 static struct facet *facet_lookup_valid(struct ofproto *, const struct flow *);
262 static bool facet_revalidate(struct ofproto *, struct facet *);
263
264 static void facet_install(struct ofproto *, struct facet *, bool zero_stats);
265 static void facet_uninstall(struct ofproto *, struct facet *);
266 static void facet_flush_stats(struct ofproto *, struct facet *);
267
268 static void facet_make_actions(struct ofproto *, struct facet *,
269                                const struct ofpbuf *packet);
270 static void facet_update_stats(struct ofproto *, struct facet *,
271                                const struct dpif_flow_stats *);
272 static void facet_push_stats(struct ofproto *, struct facet *);
273
274 static void send_packet_in(struct ofproto *, struct dpif_upcall *,
275                            const struct flow *, bool clone);
276
277 struct ofproto {
278     /* Settings. */
279     uint64_t datapath_id;       /* Datapath ID. */
280     uint64_t fallback_dpid;     /* Datapath ID if no better choice found. */
281     char *mfr_desc;             /* Manufacturer. */
282     char *hw_desc;              /* Hardware. */
283     char *sw_desc;              /* Software version. */
284     char *serial_desc;          /* Serial number. */
285     char *dp_desc;              /* Datapath description. */
286
287     /* Datapath. */
288     struct dpif *dpif;
289     struct netdev_monitor *netdev_monitor;
290     struct hmap ports;          /* Contains "struct ofport"s. */
291     struct shash port_by_name;
292     uint32_t max_ports;
293
294     /* Configuration. */
295     struct netflow *netflow;
296     struct ofproto_sflow *sflow;
297
298     /* Flow table. */
299     struct classifier cls;
300     struct timer next_expiration;
301
302     /* Facets. */
303     struct hmap facets;
304     bool need_revalidate;
305     struct tag_set revalidate_set;
306
307     /* OpenFlow connections. */
308     struct connmgr *connmgr;
309
310     /* Hooks for ovs-vswitchd. */
311     const struct ofhooks *ofhooks;
312     void *aux;
313
314     /* Used by default ofhooks. */
315     struct mac_learning *ml;
316 };
317
318 /* Map from dpif name to struct ofproto, for use by unixctl commands. */
319 static struct shash all_ofprotos = SHASH_INITIALIZER(&all_ofprotos);
320
321 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
322
323 static const struct ofhooks default_ofhooks;
324
325 static uint64_t pick_datapath_id(const struct ofproto *);
326 static uint64_t pick_fallback_dpid(void);
327
328 static void ofproto_flush_flows__(struct ofproto *);
329 static int ofproto_expire(struct ofproto *);
330 static void flow_push_stats(struct ofproto *, const struct rule *,
331                             struct flow *, uint64_t packets, uint64_t bytes,
332                             long long int used);
333
334 static void handle_upcall(struct ofproto *, struct dpif_upcall *);
335
336 static void handle_openflow(struct ofconn *, struct ofpbuf *);
337
338 static struct ofport *get_port(const struct ofproto *, uint16_t odp_port);
339 static void update_port(struct ofproto *, const char *devname);
340 static int init_ports(struct ofproto *);
341 static void reinit_ports(struct ofproto *);
342
343 static void ofproto_unixctl_init(void);
344
345 int
346 ofproto_create(const char *datapath, const char *datapath_type,
347                const struct ofhooks *ofhooks, void *aux,
348                struct ofproto **ofprotop)
349 {
350     char local_name[IF_NAMESIZE];
351     struct ofproto *p;
352     struct dpif *dpif;
353     int error;
354
355     *ofprotop = NULL;
356
357     ofproto_unixctl_init();
358
359     /* Connect to datapath and start listening for messages. */
360     error = dpif_open(datapath, datapath_type, &dpif);
361     if (error) {
362         VLOG_ERR("failed to open datapath %s: %s", datapath, strerror(error));
363         return error;
364     }
365     error = dpif_recv_set_mask(dpif,
366                                ((1u << DPIF_UC_MISS) |
367                                 (1u << DPIF_UC_ACTION) |
368                                 (1u << DPIF_UC_SAMPLE)));
369     if (error) {
370         VLOG_ERR("failed to listen on datapath %s: %s",
371                  datapath, strerror(error));
372         dpif_close(dpif);
373         return error;
374     }
375     dpif_flow_flush(dpif);
376     dpif_recv_purge(dpif);
377
378     error = dpif_port_get_name(dpif, ODPP_LOCAL,
379                                local_name, sizeof local_name);
380     if (error) {
381         VLOG_ERR("%s: cannot get name of datapath local port (%s)",
382                  datapath, strerror(error));
383         return error;
384     }
385
386     /* Initialize settings. */
387     p = xzalloc(sizeof *p);
388     p->fallback_dpid = pick_fallback_dpid();
389     p->datapath_id = p->fallback_dpid;
390     p->mfr_desc = xstrdup(DEFAULT_MFR_DESC);
391     p->hw_desc = xstrdup(DEFAULT_HW_DESC);
392     p->sw_desc = xstrdup(DEFAULT_SW_DESC);
393     p->serial_desc = xstrdup(DEFAULT_SERIAL_DESC);
394     p->dp_desc = xstrdup(DEFAULT_DP_DESC);
395
396     /* Initialize datapath. */
397     p->dpif = dpif;
398     p->netdev_monitor = netdev_monitor_create();
399     hmap_init(&p->ports);
400     shash_init(&p->port_by_name);
401     p->max_ports = dpif_get_max_ports(dpif);
402
403     /* Initialize submodules. */
404     p->netflow = NULL;
405     p->sflow = NULL;
406
407     /* Initialize flow table. */
408     classifier_init(&p->cls);
409     timer_set_duration(&p->next_expiration, 1000);
410
411     /* Initialize facet table. */
412     hmap_init(&p->facets);
413     p->need_revalidate = false;
414     tag_set_init(&p->revalidate_set);
415
416     /* Initialize hooks. */
417     if (ofhooks) {
418         p->ofhooks = ofhooks;
419         p->aux = aux;
420         p->ml = NULL;
421     } else {
422         p->ofhooks = &default_ofhooks;
423         p->aux = p;
424         p->ml = mac_learning_create();
425     }
426
427     /* Pick final datapath ID. */
428     p->datapath_id = pick_datapath_id(p);
429     VLOG_INFO("using datapath ID %016"PRIx64, p->datapath_id);
430
431     shash_add_once(&all_ofprotos, dpif_name(p->dpif), p);
432
433     /* Initialize OpenFlow connections. */
434     p->connmgr = connmgr_create(p, datapath, local_name);
435
436     *ofprotop = p;
437     return 0;
438 }
439
440 void
441 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
442 {
443     uint64_t old_dpid = p->datapath_id;
444     p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
445     if (p->datapath_id != old_dpid) {
446         VLOG_INFO("datapath ID changed to %016"PRIx64, p->datapath_id);
447
448         /* Force all active connections to reconnect, since there is no way to
449          * notify a controller that the datapath ID has changed. */
450         ofproto_reconnect_controllers(p);
451     }
452 }
453
454 void
455 ofproto_set_controllers(struct ofproto *p,
456                         const struct ofproto_controller *controllers,
457                         size_t n_controllers)
458 {
459     connmgr_set_controllers(p->connmgr, controllers, n_controllers);
460 }
461
462 void
463 ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
464 {
465     connmgr_set_fail_mode(p->connmgr, fail_mode);
466 }
467
468 /* Drops the connections between 'ofproto' and all of its controllers, forcing
469  * them to reconnect. */
470 void
471 ofproto_reconnect_controllers(struct ofproto *ofproto)
472 {
473     connmgr_reconnect(ofproto->connmgr);
474 }
475
476 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
477  * in-band control should guarantee access, in the same way that in-band
478  * control guarantees access to OpenFlow controllers. */
479 void
480 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
481                                   const struct sockaddr_in *extras, size_t n)
482 {
483     connmgr_set_extra_in_band_remotes(ofproto->connmgr, extras, n);
484 }
485
486 /* Sets the OpenFlow queue used by flows set up by in-band control on
487  * 'ofproto' to 'queue_id'.  If 'queue_id' is negative, then in-band control
488  * flows will use the default queue. */
489 void
490 ofproto_set_in_band_queue(struct ofproto *ofproto, int queue_id)
491 {
492     connmgr_set_in_band_queue(ofproto->connmgr, queue_id);
493 }
494
495 void
496 ofproto_set_desc(struct ofproto *p,
497                  const char *mfr_desc, const char *hw_desc,
498                  const char *sw_desc, const char *serial_desc,
499                  const char *dp_desc)
500 {
501     struct ofp_desc_stats *ods;
502
503     if (mfr_desc) {
504         if (strlen(mfr_desc) >= sizeof ods->mfr_desc) {
505             VLOG_WARN("truncating mfr_desc, must be less than %zu characters",
506                     sizeof ods->mfr_desc);
507         }
508         free(p->mfr_desc);
509         p->mfr_desc = xstrdup(mfr_desc);
510     }
511     if (hw_desc) {
512         if (strlen(hw_desc) >= sizeof ods->hw_desc) {
513             VLOG_WARN("truncating hw_desc, must be less than %zu characters",
514                     sizeof ods->hw_desc);
515         }
516         free(p->hw_desc);
517         p->hw_desc = xstrdup(hw_desc);
518     }
519     if (sw_desc) {
520         if (strlen(sw_desc) >= sizeof ods->sw_desc) {
521             VLOG_WARN("truncating sw_desc, must be less than %zu characters",
522                     sizeof ods->sw_desc);
523         }
524         free(p->sw_desc);
525         p->sw_desc = xstrdup(sw_desc);
526     }
527     if (serial_desc) {
528         if (strlen(serial_desc) >= sizeof ods->serial_num) {
529             VLOG_WARN("truncating serial_desc, must be less than %zu "
530                     "characters",
531                     sizeof ods->serial_num);
532         }
533         free(p->serial_desc);
534         p->serial_desc = xstrdup(serial_desc);
535     }
536     if (dp_desc) {
537         if (strlen(dp_desc) >= sizeof ods->dp_desc) {
538             VLOG_WARN("truncating dp_desc, must be less than %zu characters",
539                     sizeof ods->dp_desc);
540         }
541         free(p->dp_desc);
542         p->dp_desc = xstrdup(dp_desc);
543     }
544 }
545
546 int
547 ofproto_set_snoops(struct ofproto *ofproto, const struct sset *snoops)
548 {
549     return connmgr_set_snoops(ofproto->connmgr, snoops);
550 }
551
552 int
553 ofproto_set_netflow(struct ofproto *ofproto,
554                     const struct netflow_options *nf_options)
555 {
556     if (nf_options && !sset_is_empty(&nf_options->collectors)) {
557         if (!ofproto->netflow) {
558             ofproto->netflow = netflow_create();
559         }
560         return netflow_set_options(ofproto->netflow, nf_options);
561     } else {
562         netflow_destroy(ofproto->netflow);
563         ofproto->netflow = NULL;
564         return 0;
565     }
566 }
567
568 void
569 ofproto_set_sflow(struct ofproto *ofproto,
570                   const struct ofproto_sflow_options *oso)
571 {
572     struct ofproto_sflow *os = ofproto->sflow;
573     if (oso) {
574         if (!os) {
575             struct ofport *ofport;
576
577             os = ofproto->sflow = ofproto_sflow_create(ofproto->dpif);
578             HMAP_FOR_EACH (ofport, hmap_node, &ofproto->ports) {
579                 ofproto_sflow_add_port(os, ofport->odp_port,
580                                        netdev_get_name(ofport->netdev));
581             }
582         }
583         ofproto_sflow_set_options(os, oso);
584     } else {
585         ofproto_sflow_destroy(os);
586         ofproto->sflow = NULL;
587     }
588 }
589 \f
590 /* Connectivity Fault Management configuration. */
591
592 /* Clears the CFM configuration from 'port_no' on 'ofproto'. */
593 void
594 ofproto_iface_clear_cfm(struct ofproto *ofproto, uint32_t port_no)
595 {
596     struct ofport *ofport = get_port(ofproto, port_no);
597     if (ofport && ofport->cfm){
598         cfm_destroy(ofport->cfm);
599         ofport->cfm = NULL;
600     }
601 }
602
603 /* Configures connectivity fault management on 'port_no' in 'ofproto'.  Takes
604  * basic configuration from the configuration members in 'cfm', and the set of
605  * remote maintenance points from the 'n_remote_mps' elements in 'remote_mps'.
606  * Ignores the statistics members of 'cfm'.
607  *
608  * This function has no effect if 'ofproto' does not have a port 'port_no'. */
609 void
610 ofproto_iface_set_cfm(struct ofproto *ofproto, uint32_t port_no,
611                       const struct cfm *cfm,
612                       const uint16_t *remote_mps, size_t n_remote_mps)
613 {
614     struct ofport *ofport;
615
616     ofport = get_port(ofproto, port_no);
617     if (!ofport) {
618         VLOG_WARN("%s: cannot configure CFM on nonexistent port %"PRIu32,
619                   dpif_name(ofproto->dpif), port_no);
620         return;
621     }
622
623     if (!ofport->cfm) {
624         ofport->cfm = cfm_create();
625     }
626
627     ofport->cfm->mpid = cfm->mpid;
628     ofport->cfm->interval = cfm->interval;
629     memcpy(ofport->cfm->maid, cfm->maid, CCM_MAID_LEN);
630
631     cfm_update_remote_mps(ofport->cfm, remote_mps, n_remote_mps);
632
633     if (!cfm_configure(ofport->cfm)) {
634         VLOG_WARN("%s: CFM configuration on port %"PRIu32" (%s) failed",
635                   dpif_name(ofproto->dpif), port_no,
636                   netdev_get_name(ofport->netdev));
637         cfm_destroy(ofport->cfm);
638         ofport->cfm = NULL;
639     }
640 }
641
642 /* Returns the connectivity fault management object associated with 'port_no'
643  * within 'ofproto', or a null pointer if 'ofproto' does not have a port
644  * 'port_no' or if that port does not have CFM configured.  The caller must not
645  * modify or destroy the returned object. */
646 const struct cfm *
647 ofproto_iface_get_cfm(struct ofproto *ofproto, uint32_t port_no)
648 {
649     struct ofport *ofport = get_port(ofproto, port_no);
650     return ofport ? ofport->cfm : NULL;
651 }
652 \f
653 uint64_t
654 ofproto_get_datapath_id(const struct ofproto *ofproto)
655 {
656     return ofproto->datapath_id;
657 }
658
659 bool
660 ofproto_has_primary_controller(const struct ofproto *ofproto)
661 {
662     return connmgr_has_controllers(ofproto->connmgr);
663 }
664
665 enum ofproto_fail_mode
666 ofproto_get_fail_mode(const struct ofproto *p)
667 {
668     return connmgr_get_fail_mode(p->connmgr);
669 }
670
671 bool
672 ofproto_has_snoops(const struct ofproto *ofproto)
673 {
674     return connmgr_has_snoops(ofproto->connmgr);
675 }
676
677 void
678 ofproto_get_snoops(const struct ofproto *ofproto, struct sset *snoops)
679 {
680     connmgr_get_snoops(ofproto->connmgr, snoops);
681 }
682
683 void
684 ofproto_destroy(struct ofproto *p)
685 {
686     struct ofport *ofport, *next_ofport;
687
688     if (!p) {
689         return;
690     }
691
692     shash_find_and_delete(&all_ofprotos, dpif_name(p->dpif));
693
694     ofproto_flush_flows__(p);
695     connmgr_destroy(p->connmgr);
696     classifier_destroy(&p->cls);
697     hmap_destroy(&p->facets);
698
699     dpif_close(p->dpif);
700     netdev_monitor_destroy(p->netdev_monitor);
701     HMAP_FOR_EACH_SAFE (ofport, next_ofport, hmap_node, &p->ports) {
702         hmap_remove(&p->ports, &ofport->hmap_node);
703         ofport_free(ofport);
704     }
705     shash_destroy(&p->port_by_name);
706
707     netflow_destroy(p->netflow);
708     ofproto_sflow_destroy(p->sflow);
709
710     mac_learning_destroy(p->ml);
711
712     free(p->mfr_desc);
713     free(p->hw_desc);
714     free(p->sw_desc);
715     free(p->serial_desc);
716     free(p->dp_desc);
717
718     hmap_destroy(&p->ports);
719
720     free(p);
721 }
722
723 int
724 ofproto_run(struct ofproto *p)
725 {
726     int error = ofproto_run1(p);
727     if (!error) {
728         error = ofproto_run2(p, false);
729     }
730     return error;
731 }
732
733 static void
734 process_port_change(struct ofproto *ofproto, int error, char *devname)
735 {
736     if (error == ENOBUFS) {
737         reinit_ports(ofproto);
738     } else if (!error) {
739         update_port(ofproto, devname);
740         free(devname);
741     }
742 }
743
744 int
745 ofproto_run1(struct ofproto *p)
746 {
747     struct ofport *ofport;
748     char *devname;
749     int error;
750     int i;
751
752     if (shash_is_empty(&p->port_by_name)) {
753         init_ports(p);
754     }
755
756     for (i = 0; i < 50; i++) {
757         struct dpif_upcall packet;
758
759         error = dpif_recv(p->dpif, &packet);
760         if (error) {
761             if (error == ENODEV) {
762                 /* Someone destroyed the datapath behind our back.  The caller
763                  * better destroy us and give up, because we're just going to
764                  * spin from here on out. */
765                 static struct vlog_rate_limit rl2 = VLOG_RATE_LIMIT_INIT(1, 5);
766                 VLOG_ERR_RL(&rl2, "%s: datapath was destroyed externally",
767                             dpif_name(p->dpif));
768                 return ENODEV;
769             }
770             break;
771         }
772
773         handle_upcall(p, &packet);
774     }
775
776     while ((error = dpif_port_poll(p->dpif, &devname)) != EAGAIN) {
777         process_port_change(p, error, devname);
778     }
779     while ((error = netdev_monitor_poll(p->netdev_monitor,
780                                         &devname)) != EAGAIN) {
781         process_port_change(p, error, devname);
782     }
783
784     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
785         ofport_run(p, ofport);
786     }
787
788     connmgr_run(p->connmgr, handle_openflow);
789
790     if (timer_expired(&p->next_expiration)) {
791         int delay = ofproto_expire(p);
792         timer_set_duration(&p->next_expiration, delay);
793         COVERAGE_INC(ofproto_expiration);
794     }
795
796     if (p->netflow) {
797         netflow_run(p->netflow);
798     }
799     if (p->sflow) {
800         ofproto_sflow_run(p->sflow);
801     }
802
803     return 0;
804 }
805
806 int
807 ofproto_run2(struct ofproto *p, bool revalidate_all)
808 {
809     /* Figure out what we need to revalidate now, if anything. */
810     struct tag_set revalidate_set = p->revalidate_set;
811     if (p->need_revalidate) {
812         revalidate_all = true;
813     }
814
815     /* Clear the revalidation flags. */
816     tag_set_init(&p->revalidate_set);
817     p->need_revalidate = false;
818
819     /* Now revalidate if there's anything to do. */
820     if (revalidate_all || !tag_set_is_empty(&revalidate_set)) {
821         struct facet *facet, *next;
822
823         HMAP_FOR_EACH_SAFE (facet, next, hmap_node, &p->facets) {
824             if (revalidate_all
825                 || tag_set_intersects(&revalidate_set, facet->tags)) {
826                 facet_revalidate(p, facet);
827             }
828         }
829     }
830
831     return 0;
832 }
833
834 void
835 ofproto_wait(struct ofproto *p)
836 {
837     struct ofport *ofport;
838
839     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
840         ofport_wait(ofport);
841     }
842     dpif_recv_wait(p->dpif);
843     dpif_port_poll_wait(p->dpif);
844     netdev_monitor_poll_wait(p->netdev_monitor);
845     if (p->sflow) {
846         ofproto_sflow_wait(p->sflow);
847     }
848     if (!tag_set_is_empty(&p->revalidate_set)) {
849         poll_immediate_wake();
850     }
851     if (p->need_revalidate) {
852         /* Shouldn't happen, but if it does just go around again. */
853         VLOG_DBG_RL(&rl, "need revalidate in ofproto_wait_cb()");
854         poll_immediate_wake();
855     } else {
856         timer_wait(&p->next_expiration);
857     }
858     connmgr_wait(p->connmgr);
859 }
860
861 void
862 ofproto_revalidate(struct ofproto *ofproto, tag_type tag)
863 {
864     tag_set_add(&ofproto->revalidate_set, tag);
865 }
866
867 struct tag_set *
868 ofproto_get_revalidate_set(struct ofproto *ofproto)
869 {
870     return &ofproto->revalidate_set;
871 }
872
873 bool
874 ofproto_is_alive(const struct ofproto *p)
875 {
876     return connmgr_has_controllers(p->connmgr);
877 }
878
879 void
880 ofproto_get_ofproto_controller_info(const struct ofproto *ofproto,
881                                     struct shash *info)
882 {
883     connmgr_get_controller_info(ofproto->connmgr, info);
884 }
885
886 void
887 ofproto_free_ofproto_controller_info(struct shash *info)
888 {
889     struct shash_node *node;
890
891     SHASH_FOR_EACH (node, info) {
892         struct ofproto_controller_info *cinfo = node->data;
893         while (cinfo->pairs.n) {
894             free((char *) cinfo->pairs.values[--cinfo->pairs.n]);
895         }
896         free(cinfo);
897     }
898     shash_destroy(info);
899 }
900
901 /* Deletes port number 'odp_port' from the datapath for 'ofproto'.
902  *
903  * This is almost the same as calling dpif_port_del() directly on the
904  * datapath, but it also makes 'ofproto' close its open netdev for the port
905  * (if any).  This makes it possible to create a new netdev of a different
906  * type under the same name, which otherwise the netdev library would refuse
907  * to do because of the conflict.  (The netdev would eventually get closed on
908  * the next trip through ofproto_run(), but this interface is more direct.)
909  *
910  * Returns 0 if successful, otherwise a positive errno. */
911 int
912 ofproto_port_del(struct ofproto *ofproto, uint16_t odp_port)
913 {
914     struct ofport *ofport = get_port(ofproto, odp_port);
915     const char *name = ofport ? netdev_get_name(ofport->netdev) : "<unknown>";
916     int error;
917
918     error = dpif_port_del(ofproto->dpif, odp_port);
919     if (error) {
920         VLOG_ERR("%s: failed to remove port %"PRIu16" (%s) interface (%s)",
921                  dpif_name(ofproto->dpif), odp_port, name, strerror(error));
922     } else if (ofport) {
923         /* 'name' is the netdev's name and update_port() is going to close the
924          * netdev.  Just in case update_port() refers to 'name' after it
925          * destroys 'ofport', make a copy of it around the update_port()
926          * call. */
927         char *devname = xstrdup(name);
928         update_port(ofproto, devname);
929         free(devname);
930     }
931     return error;
932 }
933
934 /* Checks if 'ofproto' thinks 'odp_port' should be included in floods.  Returns
935  * true if 'odp_port' exists and should be included, false otherwise. */
936 bool
937 ofproto_port_is_floodable(struct ofproto *ofproto, uint16_t odp_port)
938 {
939     struct ofport *ofport = get_port(ofproto, odp_port);
940     return ofport && !(ofport->opp.config & OFPPC_NO_FLOOD);
941 }
942
943 /* Sends 'packet' out of port 'port_no' within 'p'.  If 'vlan_tci' is zero the
944  * packet will not have any 802.1Q hader; if it is nonzero, then the packet
945  * will be sent with the VLAN TCI specified by 'vlan_tci & ~VLAN_CFI'.
946  *
947  * Returns 0 if successful, otherwise a positive errno value. */
948 int
949 ofproto_send_packet(struct ofproto *ofproto,
950                     uint32_t port_no, uint16_t vlan_tci,
951                     const struct ofpbuf *packet)
952 {
953     struct ofpbuf odp_actions;
954     int error;
955
956     ofpbuf_init(&odp_actions, 32);
957     if (vlan_tci != 0) {
958         nl_msg_put_u32(&odp_actions, ODP_ACTION_ATTR_SET_DL_TCI,
959                        ntohs(vlan_tci & ~VLAN_CFI));
960     }
961     nl_msg_put_u32(&odp_actions, ODP_ACTION_ATTR_OUTPUT, port_no);
962     error = dpif_execute(ofproto->dpif, odp_actions.data, odp_actions.size,
963                          packet);
964     ofpbuf_uninit(&odp_actions);
965
966     if (error) {
967         VLOG_WARN_RL(&rl, "%s: failed to send packet on port %"PRIu32" (%s)",
968                      dpif_name(ofproto->dpif), port_no, strerror(error));
969     }
970     return error;
971 }
972
973 /* Adds a flow to the OpenFlow flow table in 'p' that matches 'cls_rule' and
974  * performs the 'n_actions' actions in 'actions'.  The new flow will not
975  * timeout.
976  *
977  * If cls_rule->priority is in the range of priorities supported by OpenFlow
978  * (0...65535, inclusive) then the flow will be visible to OpenFlow
979  * controllers; otherwise, it will be hidden.
980  *
981  * The caller retains ownership of 'cls_rule' and 'actions'. */
982 void
983 ofproto_add_flow(struct ofproto *p, const struct cls_rule *cls_rule,
984                  const union ofp_action *actions, size_t n_actions)
985 {
986     struct rule *rule;
987     rule = rule_create(cls_rule, actions, n_actions, 0, 0, 0, false);
988     rule_insert(p, rule);
989 }
990
991 void
992 ofproto_delete_flow(struct ofproto *ofproto, const struct cls_rule *target)
993 {
994     struct rule *rule;
995
996     rule = rule_from_cls_rule(classifier_find_rule_exactly(&ofproto->cls,
997                                                            target));
998     if (rule) {
999         rule_remove(ofproto, rule);
1000     }
1001 }
1002
1003 static void
1004 ofproto_flush_flows__(struct ofproto *ofproto)
1005 {
1006     struct facet *facet, *next_facet;
1007     struct rule *rule, *next_rule;
1008     struct cls_cursor cursor;
1009
1010     COVERAGE_INC(ofproto_flush);
1011
1012     HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
1013         /* Mark the facet as not installed so that facet_remove() doesn't
1014          * bother trying to uninstall it.  There is no point in uninstalling it
1015          * individually since we are about to blow away all the facets with
1016          * dpif_flow_flush(). */
1017         facet->installed = false;
1018         facet->dp_packet_count = 0;
1019         facet->dp_byte_count = 0;
1020         facet_remove(ofproto, facet);
1021     }
1022
1023     cls_cursor_init(&cursor, &ofproto->cls, NULL);
1024     CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
1025         rule_remove(ofproto, rule);
1026     }
1027
1028     dpif_flow_flush(ofproto->dpif);
1029 }
1030
1031 void
1032 ofproto_flush_flows(struct ofproto *ofproto)
1033 {
1034     ofproto_flush_flows__(ofproto);
1035     connmgr_flushed(ofproto->connmgr);
1036 }
1037 \f
1038 static void
1039 reinit_ports(struct ofproto *p)
1040 {
1041     struct dpif_port_dump dump;
1042     struct sset devnames;
1043     struct ofport *ofport;
1044     struct dpif_port dpif_port;
1045     const char *devname;
1046
1047     COVERAGE_INC(ofproto_reinit_ports);
1048
1049     sset_init(&devnames);
1050     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1051         sset_add(&devnames, netdev_get_name(ofport->netdev));
1052     }
1053     DPIF_PORT_FOR_EACH (&dpif_port, &dump, p->dpif) {
1054         sset_add(&devnames, dpif_port.name);
1055     }
1056
1057     SSET_FOR_EACH (devname, &devnames) {
1058         update_port(p, devname);
1059     }
1060     sset_destroy(&devnames);
1061 }
1062
1063 static struct ofport *
1064 make_ofport(const struct dpif_port *dpif_port)
1065 {
1066     struct netdev_options netdev_options;
1067     enum netdev_flags flags;
1068     struct ofport *ofport;
1069     struct netdev *netdev;
1070     int error;
1071
1072     memset(&netdev_options, 0, sizeof netdev_options);
1073     netdev_options.name = dpif_port->name;
1074     netdev_options.type = dpif_port->type;
1075     netdev_options.ethertype = NETDEV_ETH_TYPE_NONE;
1076
1077     error = netdev_open(&netdev_options, &netdev);
1078     if (error) {
1079         VLOG_WARN_RL(&rl, "ignoring port %s (%"PRIu16") because netdev %s "
1080                      "cannot be opened (%s)",
1081                      dpif_port->name, dpif_port->port_no,
1082                      dpif_port->name, strerror(error));
1083         return NULL;
1084     }
1085
1086     ofport = xzalloc(sizeof *ofport);
1087     ofport->netdev = netdev;
1088     ofport->odp_port = dpif_port->port_no;
1089     ofport->opp.port_no = odp_port_to_ofp_port(dpif_port->port_no);
1090     netdev_get_etheraddr(netdev, ofport->opp.hw_addr);
1091     ovs_strlcpy(ofport->opp.name, dpif_port->name, sizeof ofport->opp.name);
1092
1093     netdev_get_flags(netdev, &flags);
1094     ofport->opp.config = flags & NETDEV_UP ? 0 : OFPPC_PORT_DOWN;
1095
1096     ofport->opp.state = netdev_get_carrier(netdev) ? 0 : OFPPS_LINK_DOWN;
1097
1098     netdev_get_features(netdev,
1099                         &ofport->opp.curr, &ofport->opp.advertised,
1100                         &ofport->opp.supported, &ofport->opp.peer);
1101     return ofport;
1102 }
1103
1104 static bool
1105 ofport_conflicts(const struct ofproto *p, const struct dpif_port *dpif_port)
1106 {
1107     if (get_port(p, dpif_port->port_no)) {
1108         VLOG_WARN_RL(&rl, "ignoring duplicate port %"PRIu16" in datapath",
1109                      dpif_port->port_no);
1110         return true;
1111     } else if (shash_find(&p->port_by_name, dpif_port->name)) {
1112         VLOG_WARN_RL(&rl, "ignoring duplicate device %s in datapath",
1113                      dpif_port->name);
1114         return true;
1115     } else {
1116         return false;
1117     }
1118 }
1119
1120 static int
1121 ofport_equal(const struct ofport *a_, const struct ofport *b_)
1122 {
1123     const struct ofp_phy_port *a = &a_->opp;
1124     const struct ofp_phy_port *b = &b_->opp;
1125
1126     BUILD_ASSERT_DECL(sizeof *a == 48); /* Detect ofp_phy_port changes. */
1127     return (a->port_no == b->port_no
1128             && !memcmp(a->hw_addr, b->hw_addr, sizeof a->hw_addr)
1129             && !strcmp(a->name, b->name)
1130             && a->state == b->state
1131             && a->config == b->config
1132             && a->curr == b->curr
1133             && a->advertised == b->advertised
1134             && a->supported == b->supported
1135             && a->peer == b->peer);
1136 }
1137
1138 static void
1139 ofport_install(struct ofproto *p, struct ofport *ofport)
1140 {
1141     const char *netdev_name = netdev_get_name(ofport->netdev);
1142
1143     netdev_monitor_add(p->netdev_monitor, ofport->netdev);
1144     hmap_insert(&p->ports, &ofport->hmap_node, hash_int(ofport->odp_port, 0));
1145     shash_add(&p->port_by_name, netdev_name, ofport);
1146     if (p->sflow) {
1147         ofproto_sflow_add_port(p->sflow, ofport->odp_port, netdev_name);
1148     }
1149 }
1150
1151 static void
1152 ofport_remove(struct ofproto *p, struct ofport *ofport)
1153 {
1154     netdev_monitor_remove(p->netdev_monitor, ofport->netdev);
1155     hmap_remove(&p->ports, &ofport->hmap_node);
1156     shash_delete(&p->port_by_name,
1157                  shash_find(&p->port_by_name,
1158                             netdev_get_name(ofport->netdev)));
1159     if (p->sflow) {
1160         ofproto_sflow_del_port(p->sflow, ofport->odp_port);
1161     }
1162 }
1163
1164 static void
1165 ofport_run(struct ofproto *ofproto, struct ofport *ofport)
1166 {
1167     if (ofport->cfm) {
1168         cfm_run(ofport->cfm);
1169
1170         if (cfm_should_send_ccm(ofport->cfm)) {
1171             struct ofpbuf packet;
1172             struct ccm *ccm;
1173
1174             ofpbuf_init(&packet, 0);
1175             ccm = compose_packet(&packet, eth_addr_ccm, ofport->opp.hw_addr,
1176                                  ETH_TYPE_CFM,  sizeof *ccm);
1177             cfm_compose_ccm(ofport->cfm, ccm);
1178             ofproto_send_packet(ofproto, ofport->odp_port, 0, &packet);
1179             ofpbuf_uninit(&packet);
1180         }
1181     }
1182 }
1183
1184 static void
1185 ofport_wait(struct ofport *ofport)
1186 {
1187     if (ofport->cfm) {
1188         cfm_wait(ofport->cfm);
1189     }
1190 }
1191
1192 static void
1193 ofport_free(struct ofport *ofport)
1194 {
1195     if (ofport) {
1196         cfm_destroy(ofport->cfm);
1197         netdev_close(ofport->netdev);
1198         free(ofport);
1199     }
1200 }
1201
1202 static struct ofport *
1203 get_port(const struct ofproto *ofproto, uint16_t odp_port)
1204 {
1205     struct ofport *port;
1206
1207     HMAP_FOR_EACH_IN_BUCKET (port, hmap_node,
1208                              hash_int(odp_port, 0), &ofproto->ports) {
1209         if (port->odp_port == odp_port) {
1210             return port;
1211         }
1212     }
1213     return NULL;
1214 }
1215
1216 static void
1217 update_port(struct ofproto *p, const char *devname)
1218 {
1219     struct dpif_port dpif_port;
1220     struct ofport *old_ofport;
1221     struct ofport *new_ofport;
1222     int error;
1223
1224     COVERAGE_INC(ofproto_update_port);
1225
1226     /* Query the datapath for port information. */
1227     error = dpif_port_query_by_name(p->dpif, devname, &dpif_port);
1228
1229     /* Find the old ofport. */
1230     old_ofport = shash_find_data(&p->port_by_name, devname);
1231     if (!error) {
1232         if (!old_ofport) {
1233             /* There's no port named 'devname' but there might be a port with
1234              * the same port number.  This could happen if a port is deleted
1235              * and then a new one added in its place very quickly, or if a port
1236              * is renamed.  In the former case we want to send an OFPPR_DELETE
1237              * and an OFPPR_ADD, and in the latter case we want to send a
1238              * single OFPPR_MODIFY.  We can distinguish the cases by comparing
1239              * the old port's ifindex against the new port, or perhaps less
1240              * reliably but more portably by comparing the old port's MAC
1241              * against the new port's MAC.  However, this code isn't that smart
1242              * and always sends an OFPPR_MODIFY (XXX). */
1243             old_ofport = get_port(p, dpif_port.port_no);
1244         }
1245     } else if (error != ENOENT && error != ENODEV) {
1246         VLOG_WARN_RL(&rl, "dpif_port_query_by_name returned unexpected error "
1247                      "%s", strerror(error));
1248         goto exit;
1249     }
1250
1251     /* Create a new ofport. */
1252     new_ofport = !error ? make_ofport(&dpif_port) : NULL;
1253
1254     /* Eliminate a few pathological cases. */
1255     if (!old_ofport && !new_ofport) {
1256         goto exit;
1257     } else if (old_ofport && new_ofport) {
1258         /* Most of the 'config' bits are OpenFlow soft state, but
1259          * OFPPC_PORT_DOWN is maintained by the kernel.  So transfer the
1260          * OpenFlow bits from old_ofport.  (make_ofport() only sets
1261          * OFPPC_PORT_DOWN and leaves the other bits 0.)  */
1262         new_ofport->opp.config |= old_ofport->opp.config & ~OFPPC_PORT_DOWN;
1263
1264         if (ofport_equal(old_ofport, new_ofport)) {
1265             /* False alarm--no change. */
1266             ofport_free(new_ofport);
1267             goto exit;
1268         }
1269     }
1270
1271     /* Now deal with the normal cases. */
1272     if (old_ofport) {
1273         ofport_remove(p, old_ofport);
1274     }
1275     if (new_ofport) {
1276         ofport_install(p, new_ofport);
1277     }
1278     connmgr_send_port_status(p->connmgr,
1279                              new_ofport ? &new_ofport->opp : &old_ofport->opp,
1280                              (!old_ofport ? OFPPR_ADD
1281                               : !new_ofport ? OFPPR_DELETE
1282                               : OFPPR_MODIFY));
1283     ofport_free(old_ofport);
1284
1285 exit:
1286     dpif_port_destroy(&dpif_port);
1287 }
1288
1289 static int
1290 init_ports(struct ofproto *p)
1291 {
1292     struct dpif_port_dump dump;
1293     struct dpif_port dpif_port;
1294
1295     DPIF_PORT_FOR_EACH (&dpif_port, &dump, p->dpif) {
1296         if (!ofport_conflicts(p, &dpif_port)) {
1297             struct ofport *ofport = make_ofport(&dpif_port);
1298             if (ofport) {
1299                 ofport_install(p, ofport);
1300             }
1301         }
1302     }
1303
1304     return 0;
1305 }
1306 \f
1307 /* Returns true if 'rule' should be hidden from the controller.
1308  *
1309  * Rules with priority higher than UINT16_MAX are set up by ofproto itself
1310  * (e.g. by in-band control) and are intentionally hidden from the
1311  * controller. */
1312 static bool
1313 rule_is_hidden(const struct rule *rule)
1314 {
1315     return rule->cr.priority > UINT16_MAX;
1316 }
1317
1318 /* Creates and returns a new rule initialized as specified.
1319  *
1320  * The caller is responsible for inserting the rule into the classifier (with
1321  * rule_insert()). */
1322 static struct rule *
1323 rule_create(const struct cls_rule *cls_rule,
1324             const union ofp_action *actions, size_t n_actions,
1325             uint16_t idle_timeout, uint16_t hard_timeout,
1326             ovs_be64 flow_cookie, bool send_flow_removed)
1327 {
1328     struct rule *rule = xzalloc(sizeof *rule);
1329     rule->cr = *cls_rule;
1330     rule->idle_timeout = idle_timeout;
1331     rule->hard_timeout = hard_timeout;
1332     rule->flow_cookie = flow_cookie;
1333     rule->used = rule->created = time_msec();
1334     rule->send_flow_removed = send_flow_removed;
1335     list_init(&rule->facets);
1336     if (n_actions > 0) {
1337         rule->n_actions = n_actions;
1338         rule->actions = xmemdup(actions, n_actions * sizeof *actions);
1339     }
1340
1341     return rule;
1342 }
1343
1344 static struct rule *
1345 rule_from_cls_rule(const struct cls_rule *cls_rule)
1346 {
1347     return cls_rule ? CONTAINER_OF(cls_rule, struct rule, cr) : NULL;
1348 }
1349
1350 static void
1351 rule_free(struct rule *rule)
1352 {
1353     free(rule->actions);
1354     free(rule);
1355 }
1356
1357 /* Destroys 'rule' and iterates through all of its facets and revalidates them,
1358  * destroying any that no longer has a rule (which is probably all of them).
1359  *
1360  * The caller must have already removed 'rule' from the classifier. */
1361 static void
1362 rule_destroy(struct ofproto *ofproto, struct rule *rule)
1363 {
1364     struct facet *facet, *next_facet;
1365     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
1366         facet_revalidate(ofproto, facet);
1367     }
1368     rule_free(rule);
1369 }
1370
1371 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
1372  * that outputs to 'out_port' (output to OFPP_FLOOD and OFPP_ALL doesn't
1373  * count). */
1374 static bool
1375 rule_has_out_port(const struct rule *rule, ovs_be16 out_port)
1376 {
1377     const union ofp_action *oa;
1378     struct actions_iterator i;
1379
1380     if (out_port == htons(OFPP_NONE)) {
1381         return true;
1382     }
1383     for (oa = actions_first(&i, rule->actions, rule->n_actions); oa;
1384          oa = actions_next(&i)) {
1385         if (action_outputs_to_port(oa, out_port)) {
1386             return true;
1387         }
1388     }
1389     return false;
1390 }
1391
1392 /* Executes, within 'ofproto', the 'n_actions' actions in 'actions' on
1393  * 'packet', which arrived on 'in_port'.
1394  *
1395  * Takes ownership of 'packet'. */
1396 static bool
1397 execute_odp_actions(struct ofproto *ofproto, const struct flow *flow,
1398                     const struct nlattr *odp_actions, size_t actions_len,
1399                     struct ofpbuf *packet)
1400 {
1401     if (actions_len == NLA_ALIGN(NLA_HDRLEN + sizeof(uint64_t))
1402         && odp_actions->nla_type == ODP_ACTION_ATTR_CONTROLLER) {
1403         /* As an optimization, avoid a round-trip from userspace to kernel to
1404          * userspace.  This also avoids possibly filling up kernel packet
1405          * buffers along the way. */
1406         struct dpif_upcall upcall;
1407
1408         upcall.type = DPIF_UC_ACTION;
1409         upcall.packet = packet;
1410         upcall.key = NULL;
1411         upcall.key_len = 0;
1412         upcall.userdata = nl_attr_get_u64(odp_actions);
1413         upcall.sample_pool = 0;
1414         upcall.actions = NULL;
1415         upcall.actions_len = 0;
1416
1417         send_packet_in(ofproto, &upcall, flow, false);
1418
1419         return true;
1420     } else {
1421         int error;
1422
1423         error = dpif_execute(ofproto->dpif, odp_actions, actions_len, packet);
1424         ofpbuf_delete(packet);
1425         return !error;
1426     }
1427 }
1428
1429 /* Executes the actions indicated by 'facet' on 'packet' and credits 'facet''s
1430  * statistics appropriately.  'packet' must have at least sizeof(struct
1431  * ofp_packet_in) bytes of headroom.
1432  *
1433  * For correct results, 'packet' must actually be in 'facet''s flow; that is,
1434  * applying flow_extract() to 'packet' would yield the same flow as
1435  * 'facet->flow'.
1436  *
1437  * 'facet' must have accurately composed ODP actions; that is, it must not be
1438  * in need of revalidation.
1439  *
1440  * Takes ownership of 'packet'. */
1441 static void
1442 facet_execute(struct ofproto *ofproto, struct facet *facet,
1443               struct ofpbuf *packet)
1444 {
1445     struct dpif_flow_stats stats;
1446
1447     assert(ofpbuf_headroom(packet) >= sizeof(struct ofp_packet_in));
1448
1449     flow_extract_stats(&facet->flow, packet, &stats);
1450     stats.used = time_msec();
1451     if (execute_odp_actions(ofproto, &facet->flow,
1452                             facet->actions, facet->actions_len, packet)) {
1453         facet_update_stats(ofproto, facet, &stats);
1454     }
1455 }
1456
1457 /* Executes the actions indicated by 'rule' on 'packet' and credits 'rule''s
1458  * statistics (or the statistics for one of its facets) appropriately.
1459  * 'packet' must have at least sizeof(struct ofp_packet_in) bytes of headroom.
1460  *
1461  * 'packet' doesn't necessarily have to match 'rule'.  'rule' will be credited
1462  * with statistics for 'packet' either way.
1463  *
1464  * Takes ownership of 'packet'. */
1465 static void
1466 rule_execute(struct ofproto *ofproto, struct rule *rule, uint16_t in_port,
1467              struct ofpbuf *packet)
1468 {
1469     struct action_xlate_ctx ctx;
1470     struct ofpbuf *odp_actions;
1471     struct facet *facet;
1472     struct flow flow;
1473     size_t size;
1474
1475     assert(ofpbuf_headroom(packet) >= sizeof(struct ofp_packet_in));
1476
1477     flow_extract(packet, 0, in_port, &flow);
1478
1479     /* First look for a related facet.  If we find one, account it to that. */
1480     facet = facet_lookup_valid(ofproto, &flow);
1481     if (facet && facet->rule == rule) {
1482         facet_execute(ofproto, facet, packet);
1483         return;
1484     }
1485
1486     /* Otherwise, if 'rule' is in fact the correct rule for 'packet', then
1487      * create a new facet for it and use that. */
1488     if (rule_lookup(ofproto, &flow) == rule) {
1489         facet = facet_create(ofproto, rule, &flow, packet);
1490         facet_execute(ofproto, facet, packet);
1491         facet_install(ofproto, facet, true);
1492         return;
1493     }
1494
1495     /* We can't account anything to a facet.  If we were to try, then that
1496      * facet would have a non-matching rule, busting our invariants. */
1497     action_xlate_ctx_init(&ctx, ofproto, &flow, packet);
1498     odp_actions = xlate_actions(&ctx, rule->actions, rule->n_actions);
1499     size = packet->size;
1500     if (execute_odp_actions(ofproto, &flow, odp_actions->data,
1501                             odp_actions->size, packet)) {
1502         rule->used = time_msec();
1503         rule->packet_count++;
1504         rule->byte_count += size;
1505         flow_push_stats(ofproto, rule, &flow, 1, size, rule->used);
1506     }
1507     ofpbuf_delete(odp_actions);
1508 }
1509
1510 /* Inserts 'rule' into 'p''s flow table. */
1511 static void
1512 rule_insert(struct ofproto *p, struct rule *rule)
1513 {
1514     struct rule *displaced_rule;
1515
1516     displaced_rule = rule_from_cls_rule(classifier_insert(&p->cls, &rule->cr));
1517     if (displaced_rule) {
1518         rule_destroy(p, displaced_rule);
1519     }
1520     p->need_revalidate = true;
1521 }
1522
1523 /* Creates and returns a new facet within 'ofproto' owned by 'rule', given a
1524  * 'flow' and an example 'packet' within that flow.
1525  *
1526  * The caller must already have determined that no facet with an identical
1527  * 'flow' exists in 'ofproto' and that 'flow' is the best match for 'rule' in
1528  * 'ofproto''s classifier table. */
1529 static struct facet *
1530 facet_create(struct ofproto *ofproto, struct rule *rule,
1531              const struct flow *flow, const struct ofpbuf *packet)
1532 {
1533     struct facet *facet;
1534
1535     facet = xzalloc(sizeof *facet);
1536     facet->used = time_msec();
1537     hmap_insert(&ofproto->facets, &facet->hmap_node, flow_hash(flow, 0));
1538     list_push_back(&rule->facets, &facet->list_node);
1539     facet->rule = rule;
1540     facet->flow = *flow;
1541     netflow_flow_init(&facet->nf_flow);
1542     netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, facet->used);
1543
1544     facet_make_actions(ofproto, facet, packet);
1545
1546     return facet;
1547 }
1548
1549 static void
1550 facet_free(struct facet *facet)
1551 {
1552     free(facet->actions);
1553     free(facet);
1554 }
1555
1556 /* Remove 'rule' from 'ofproto' and free up the associated memory:
1557  *
1558  *   - Removes 'rule' from the classifier.
1559  *
1560  *   - If 'rule' has facets, revalidates them (and possibly uninstalls and
1561  *     destroys them), via rule_destroy().
1562  */
1563 static void
1564 rule_remove(struct ofproto *ofproto, struct rule *rule)
1565 {
1566     COVERAGE_INC(ofproto_del_rule);
1567     ofproto->need_revalidate = true;
1568     classifier_remove(&ofproto->cls, &rule->cr);
1569     rule_destroy(ofproto, rule);
1570 }
1571
1572 /* Remove 'facet' from 'ofproto' and free up the associated memory:
1573  *
1574  *   - If 'facet' was installed in the datapath, uninstalls it and updates its
1575  *     rule's statistics, via facet_uninstall().
1576  *
1577  *   - Removes 'facet' from its rule and from ofproto->facets.
1578  */
1579 static void
1580 facet_remove(struct ofproto *ofproto, struct facet *facet)
1581 {
1582     facet_uninstall(ofproto, facet);
1583     facet_flush_stats(ofproto, facet);
1584     hmap_remove(&ofproto->facets, &facet->hmap_node);
1585     list_remove(&facet->list_node);
1586     facet_free(facet);
1587 }
1588
1589 /* Composes the ODP actions for 'facet' based on its rule's actions. */
1590 static void
1591 facet_make_actions(struct ofproto *p, struct facet *facet,
1592                    const struct ofpbuf *packet)
1593 {
1594     const struct rule *rule = facet->rule;
1595     struct ofpbuf *odp_actions;
1596     struct action_xlate_ctx ctx;
1597
1598     action_xlate_ctx_init(&ctx, p, &facet->flow, packet);
1599     odp_actions = xlate_actions(&ctx, rule->actions, rule->n_actions);
1600     facet->tags = ctx.tags;
1601     facet->may_install = ctx.may_set_up_flow;
1602     facet->nf_flow.output_iface = ctx.nf_output_iface;
1603
1604     if (facet->actions_len != odp_actions->size
1605         || memcmp(facet->actions, odp_actions->data, odp_actions->size)) {
1606         free(facet->actions);
1607         facet->actions_len = odp_actions->size;
1608         facet->actions = xmemdup(odp_actions->data, odp_actions->size);
1609     }
1610
1611     ofpbuf_delete(odp_actions);
1612 }
1613
1614 static int
1615 facet_put__(struct ofproto *ofproto, struct facet *facet,
1616             const struct nlattr *actions, size_t actions_len,
1617             struct dpif_flow_stats *stats)
1618 {
1619     struct odputil_keybuf keybuf;
1620     enum dpif_flow_put_flags flags;
1621     struct ofpbuf key;
1622
1623     flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
1624     if (stats) {
1625         flags |= DPIF_FP_ZERO_STATS;
1626         facet->dp_packet_count = 0;
1627         facet->dp_byte_count = 0;
1628     }
1629
1630     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
1631     odp_flow_key_from_flow(&key, &facet->flow);
1632
1633     return dpif_flow_put(ofproto->dpif, flags, key.data, key.size,
1634                          actions, actions_len, stats);
1635 }
1636
1637 /* If 'facet' is installable, inserts or re-inserts it into 'p''s datapath.  If
1638  * 'zero_stats' is true, clears any existing statistics from the datapath for
1639  * 'facet'. */
1640 static void
1641 facet_install(struct ofproto *p, struct facet *facet, bool zero_stats)
1642 {
1643     struct dpif_flow_stats stats;
1644
1645     if (facet->may_install
1646         && !facet_put__(p, facet, facet->actions, facet->actions_len,
1647                         zero_stats ? &stats : NULL)) {
1648         facet->installed = true;
1649     }
1650 }
1651
1652 /* Ensures that the bytes in 'facet', plus 'extra_bytes', have been passed up
1653  * to the accounting hook function in the ofhooks structure. */
1654 static void
1655 facet_account(struct ofproto *ofproto,
1656               struct facet *facet, uint64_t extra_bytes)
1657 {
1658     uint64_t total_bytes = facet->byte_count + extra_bytes;
1659
1660     if (ofproto->ofhooks->account_flow_cb
1661         && total_bytes > facet->accounted_bytes)
1662     {
1663         ofproto->ofhooks->account_flow_cb(
1664             &facet->flow, facet->tags, facet->actions, facet->actions_len,
1665             total_bytes - facet->accounted_bytes, ofproto->aux);
1666         facet->accounted_bytes = total_bytes;
1667     }
1668 }
1669
1670 /* If 'rule' is installed in the datapath, uninstalls it. */
1671 static void
1672 facet_uninstall(struct ofproto *p, struct facet *facet)
1673 {
1674     if (facet->installed) {
1675         struct odputil_keybuf keybuf;
1676         struct dpif_flow_stats stats;
1677         struct ofpbuf key;
1678
1679         ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
1680         odp_flow_key_from_flow(&key, &facet->flow);
1681
1682         if (!dpif_flow_del(p->dpif, key.data, key.size, &stats)) {
1683             facet_update_stats(p, facet, &stats);
1684         }
1685         facet->installed = false;
1686         facet->dp_packet_count = 0;
1687         facet->dp_byte_count = 0;
1688     } else {
1689         assert(facet->dp_packet_count == 0);
1690         assert(facet->dp_byte_count == 0);
1691     }
1692 }
1693
1694 /* Returns true if the only action for 'facet' is to send to the controller.
1695  * (We don't report NetFlow expiration messages for such facets because they
1696  * are just part of the control logic for the network, not real traffic). */
1697 static bool
1698 facet_is_controller_flow(struct facet *facet)
1699 {
1700     return (facet
1701             && facet->rule->n_actions == 1
1702             && action_outputs_to_port(&facet->rule->actions[0],
1703                                       htons(OFPP_CONTROLLER)));
1704 }
1705
1706 /* Folds all of 'facet''s statistics into its rule.  Also updates the
1707  * accounting ofhook and emits a NetFlow expiration if appropriate.  All of
1708  * 'facet''s statistics in the datapath should have been zeroed and folded into
1709  * its packet and byte counts before this function is called. */
1710 static void
1711 facet_flush_stats(struct ofproto *ofproto, struct facet *facet)
1712 {
1713     assert(!facet->dp_byte_count);
1714     assert(!facet->dp_packet_count);
1715
1716     facet_push_stats(ofproto, facet);
1717     facet_account(ofproto, facet, 0);
1718
1719     if (ofproto->netflow && !facet_is_controller_flow(facet)) {
1720         struct ofexpired expired;
1721         expired.flow = facet->flow;
1722         expired.packet_count = facet->packet_count;
1723         expired.byte_count = facet->byte_count;
1724         expired.used = facet->used;
1725         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
1726     }
1727
1728     facet->rule->packet_count += facet->packet_count;
1729     facet->rule->byte_count += facet->byte_count;
1730
1731     /* Reset counters to prevent double counting if 'facet' ever gets
1732      * reinstalled. */
1733     facet->packet_count = 0;
1734     facet->byte_count = 0;
1735     facet->rs_packet_count = 0;
1736     facet->rs_byte_count = 0;
1737     facet->accounted_bytes = 0;
1738
1739     netflow_flow_clear(&facet->nf_flow);
1740 }
1741
1742 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
1743  * Returns it if found, otherwise a null pointer.
1744  *
1745  * The returned facet might need revalidation; use facet_lookup_valid()
1746  * instead if that is important. */
1747 static struct facet *
1748 facet_find(struct ofproto *ofproto, const struct flow *flow)
1749 {
1750     struct facet *facet;
1751
1752     HMAP_FOR_EACH_WITH_HASH (facet, hmap_node, flow_hash(flow, 0),
1753                              &ofproto->facets) {
1754         if (flow_equal(flow, &facet->flow)) {
1755             return facet;
1756         }
1757     }
1758
1759     return NULL;
1760 }
1761
1762 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
1763  * Returns it if found, otherwise a null pointer.
1764  *
1765  * The returned facet is guaranteed to be valid. */
1766 static struct facet *
1767 facet_lookup_valid(struct ofproto *ofproto, const struct flow *flow)
1768 {
1769     struct facet *facet = facet_find(ofproto, flow);
1770
1771     /* The facet we found might not be valid, since we could be in need of
1772      * revalidation.  If it is not valid, don't return it. */
1773     if (facet
1774         && ofproto->need_revalidate
1775         && !facet_revalidate(ofproto, facet)) {
1776         COVERAGE_INC(ofproto_invalidated);
1777         return NULL;
1778     }
1779
1780     return facet;
1781 }
1782
1783 /* Re-searches 'ofproto''s classifier for a rule matching 'facet':
1784  *
1785  *   - If the rule found is different from 'facet''s current rule, moves
1786  *     'facet' to the new rule and recompiles its actions.
1787  *
1788  *   - If the rule found is the same as 'facet''s current rule, leaves 'facet'
1789  *     where it is and recompiles its actions anyway.
1790  *
1791  *   - If there is none, destroys 'facet'.
1792  *
1793  * Returns true if 'facet' still exists, false if it has been destroyed. */
1794 static bool
1795 facet_revalidate(struct ofproto *ofproto, struct facet *facet)
1796 {
1797     struct action_xlate_ctx ctx;
1798     struct ofpbuf *odp_actions;
1799     struct rule *new_rule;
1800     bool actions_changed;
1801
1802     COVERAGE_INC(facet_revalidate);
1803
1804     /* Determine the new rule. */
1805     new_rule = rule_lookup(ofproto, &facet->flow);
1806     if (!new_rule) {
1807         /* No new rule, so delete the facet. */
1808         facet_remove(ofproto, facet);
1809         return false;
1810     }
1811
1812     /* Calculate new ODP actions.
1813      *
1814      * We do not modify any 'facet' state yet, because we might need to, e.g.,
1815      * emit a NetFlow expiration and, if so, we need to have the old state
1816      * around to properly compose it. */
1817     action_xlate_ctx_init(&ctx, ofproto, &facet->flow, NULL);
1818     odp_actions = xlate_actions(&ctx, new_rule->actions, new_rule->n_actions);
1819     actions_changed = (facet->actions_len != odp_actions->size
1820                        || memcmp(facet->actions, odp_actions->data,
1821                                  facet->actions_len));
1822
1823     /* If the ODP actions changed or the installability changed, then we need
1824      * to talk to the datapath. */
1825     if (actions_changed || ctx.may_set_up_flow != facet->installed) {
1826         if (ctx.may_set_up_flow) {
1827             struct dpif_flow_stats stats;
1828
1829             facet_put__(ofproto, facet,
1830                         odp_actions->data, odp_actions->size, &stats);
1831             facet_update_stats(ofproto, facet, &stats);
1832         } else {
1833             facet_uninstall(ofproto, facet);
1834         }
1835
1836         /* The datapath flow is gone or has zeroed stats, so push stats out of
1837          * 'facet' into 'rule'. */
1838         facet_flush_stats(ofproto, facet);
1839     }
1840
1841     /* Update 'facet' now that we've taken care of all the old state. */
1842     facet->tags = ctx.tags;
1843     facet->nf_flow.output_iface = ctx.nf_output_iface;
1844     facet->may_install = ctx.may_set_up_flow;
1845     if (actions_changed) {
1846         free(facet->actions);
1847         facet->actions_len = odp_actions->size;
1848         facet->actions = xmemdup(odp_actions->data, odp_actions->size);
1849     }
1850     if (facet->rule != new_rule) {
1851         COVERAGE_INC(facet_changed_rule);
1852         list_remove(&facet->list_node);
1853         list_push_back(&new_rule->facets, &facet->list_node);
1854         facet->rule = new_rule;
1855         facet->used = new_rule->created;
1856         facet->rs_used = facet->used;
1857     }
1858
1859     ofpbuf_delete(odp_actions);
1860
1861     return true;
1862 }
1863 \f
1864 static void
1865 send_error_oh(const struct ofconn *ofconn, const struct ofp_header *oh,
1866               int error)
1867 {
1868     struct ofpbuf *buf = ofputil_encode_error_msg(error, oh);
1869     if (buf) {
1870         COVERAGE_INC(ofproto_error);
1871         ofconn_send_reply(ofconn, buf);
1872     }
1873 }
1874
1875 static int
1876 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
1877 {
1878     ofconn_send_reply(ofconn, make_echo_reply(oh));
1879     return 0;
1880 }
1881
1882 static int
1883 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
1884 {
1885     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
1886     struct ofp_switch_features *osf;
1887     struct ofpbuf *buf;
1888     struct ofport *port;
1889
1890     osf = make_openflow_xid(sizeof *osf, OFPT_FEATURES_REPLY, oh->xid, &buf);
1891     osf->datapath_id = htonll(ofproto->datapath_id);
1892     osf->n_buffers = htonl(pktbuf_capacity());
1893     osf->n_tables = 2;
1894     osf->capabilities = htonl(OFPC_FLOW_STATS | OFPC_TABLE_STATS |
1895                               OFPC_PORT_STATS | OFPC_ARP_MATCH_IP);
1896     osf->actions = htonl((1u << OFPAT_OUTPUT) |
1897                          (1u << OFPAT_SET_VLAN_VID) |
1898                          (1u << OFPAT_SET_VLAN_PCP) |
1899                          (1u << OFPAT_STRIP_VLAN) |
1900                          (1u << OFPAT_SET_DL_SRC) |
1901                          (1u << OFPAT_SET_DL_DST) |
1902                          (1u << OFPAT_SET_NW_SRC) |
1903                          (1u << OFPAT_SET_NW_DST) |
1904                          (1u << OFPAT_SET_NW_TOS) |
1905                          (1u << OFPAT_SET_TP_SRC) |
1906                          (1u << OFPAT_SET_TP_DST) |
1907                          (1u << OFPAT_ENQUEUE));
1908
1909     HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
1910         hton_ofp_phy_port(ofpbuf_put(buf, &port->opp, sizeof port->opp));
1911     }
1912
1913     ofconn_send_reply(ofconn, buf);
1914     return 0;
1915 }
1916
1917 static int
1918 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
1919 {
1920     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
1921     struct ofpbuf *buf;
1922     struct ofp_switch_config *osc;
1923     uint16_t flags;
1924     bool drop_frags;
1925
1926     /* Figure out flags. */
1927     dpif_get_drop_frags(ofproto->dpif, &drop_frags);
1928     flags = drop_frags ? OFPC_FRAG_DROP : OFPC_FRAG_NORMAL;
1929
1930     /* Send reply. */
1931     osc = make_openflow_xid(sizeof *osc, OFPT_GET_CONFIG_REPLY, oh->xid, &buf);
1932     osc->flags = htons(flags);
1933     osc->miss_send_len = htons(ofconn_get_miss_send_len(ofconn));
1934     ofconn_send_reply(ofconn, buf);
1935
1936     return 0;
1937 }
1938
1939 static int
1940 handle_set_config(struct ofconn *ofconn, const struct ofp_switch_config *osc)
1941 {
1942     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
1943     uint16_t flags = ntohs(osc->flags);
1944
1945     if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
1946         && ofconn_get_role(ofconn) != NX_ROLE_SLAVE) {
1947         switch (flags & OFPC_FRAG_MASK) {
1948         case OFPC_FRAG_NORMAL:
1949             dpif_set_drop_frags(ofproto->dpif, false);
1950             break;
1951         case OFPC_FRAG_DROP:
1952             dpif_set_drop_frags(ofproto->dpif, true);
1953             break;
1954         default:
1955             VLOG_WARN_RL(&rl, "requested bad fragment mode (flags=%"PRIx16")",
1956                          osc->flags);
1957             break;
1958         }
1959     }
1960
1961     ofconn_set_miss_send_len(ofconn, ntohs(osc->miss_send_len));
1962
1963     return 0;
1964 }
1965
1966 static void do_xlate_actions(const union ofp_action *in, size_t n_in,
1967                              struct action_xlate_ctx *ctx);
1968
1969 static void
1970 add_output_action(struct action_xlate_ctx *ctx, uint16_t port)
1971 {
1972     const struct ofport *ofport = get_port(ctx->ofproto, port);
1973
1974     if (ofport) {
1975         if (ofport->opp.config & OFPPC_NO_FWD) {
1976             /* Forwarding disabled on port. */
1977             return;
1978         }
1979     } else {
1980         /*
1981          * We don't have an ofport record for this port, but it doesn't hurt to
1982          * allow forwarding to it anyhow.  Maybe such a port will appear later
1983          * and we're pre-populating the flow table.
1984          */
1985     }
1986
1987     nl_msg_put_u32(ctx->odp_actions, ODP_ACTION_ATTR_OUTPUT, port);
1988     ctx->nf_output_iface = port;
1989 }
1990
1991 static struct rule *
1992 rule_lookup(struct ofproto *ofproto, const struct flow *flow)
1993 {
1994     return rule_from_cls_rule(classifier_lookup(&ofproto->cls, flow));
1995 }
1996
1997 static void
1998 xlate_table_action(struct action_xlate_ctx *ctx, uint16_t in_port)
1999 {
2000     if (ctx->recurse < MAX_RESUBMIT_RECURSION) {
2001         uint16_t old_in_port;
2002         struct rule *rule;
2003
2004         /* Look up a flow with 'in_port' as the input port.  Then restore the
2005          * original input port (otherwise OFPP_NORMAL and OFPP_IN_PORT will
2006          * have surprising behavior). */
2007         old_in_port = ctx->flow.in_port;
2008         ctx->flow.in_port = in_port;
2009         rule = rule_lookup(ctx->ofproto, &ctx->flow);
2010         ctx->flow.in_port = old_in_port;
2011
2012         if (ctx->resubmit_hook) {
2013             ctx->resubmit_hook(ctx, rule);
2014         }
2015
2016         if (rule) {
2017             ctx->recurse++;
2018             do_xlate_actions(rule->actions, rule->n_actions, ctx);
2019             ctx->recurse--;
2020         }
2021     } else {
2022         static struct vlog_rate_limit recurse_rl = VLOG_RATE_LIMIT_INIT(1, 1);
2023
2024         VLOG_ERR_RL(&recurse_rl, "NXAST_RESUBMIT recursed over %d times",
2025                     MAX_RESUBMIT_RECURSION);
2026     }
2027 }
2028
2029 static void
2030 flood_packets(struct ofproto *ofproto, uint16_t odp_in_port, uint32_t mask,
2031               uint16_t *nf_output_iface, struct ofpbuf *odp_actions)
2032 {
2033     struct ofport *ofport;
2034
2035     HMAP_FOR_EACH (ofport, hmap_node, &ofproto->ports) {
2036         uint16_t odp_port = ofport->odp_port;
2037         if (odp_port != odp_in_port && !(ofport->opp.config & mask)) {
2038             nl_msg_put_u32(odp_actions, ODP_ACTION_ATTR_OUTPUT, odp_port);
2039         }
2040     }
2041     *nf_output_iface = NF_OUT_FLOOD;
2042 }
2043
2044 static void
2045 xlate_output_action__(struct action_xlate_ctx *ctx,
2046                       uint16_t port, uint16_t max_len)
2047 {
2048     uint16_t odp_port;
2049     uint16_t prev_nf_output_iface = ctx->nf_output_iface;
2050
2051     ctx->nf_output_iface = NF_OUT_DROP;
2052
2053     switch (port) {
2054     case OFPP_IN_PORT:
2055         add_output_action(ctx, ctx->flow.in_port);
2056         break;
2057     case OFPP_TABLE:
2058         xlate_table_action(ctx, ctx->flow.in_port);
2059         break;
2060     case OFPP_NORMAL:
2061         if (!ctx->ofproto->ofhooks->normal_cb(&ctx->flow, ctx->packet,
2062                                               ctx->odp_actions, &ctx->tags,
2063                                               &ctx->nf_output_iface,
2064                                               ctx->ofproto->aux)) {
2065             COVERAGE_INC(ofproto_uninstallable);
2066             ctx->may_set_up_flow = false;
2067         }
2068         break;
2069     case OFPP_FLOOD:
2070         flood_packets(ctx->ofproto, ctx->flow.in_port, OFPPC_NO_FLOOD,
2071                       &ctx->nf_output_iface, ctx->odp_actions);
2072         break;
2073     case OFPP_ALL:
2074         flood_packets(ctx->ofproto, ctx->flow.in_port, 0,
2075                       &ctx->nf_output_iface, ctx->odp_actions);
2076         break;
2077     case OFPP_CONTROLLER:
2078         nl_msg_put_u64(ctx->odp_actions, ODP_ACTION_ATTR_CONTROLLER, max_len);
2079         break;
2080     case OFPP_LOCAL:
2081         add_output_action(ctx, ODPP_LOCAL);
2082         break;
2083     default:
2084         odp_port = ofp_port_to_odp_port(port);
2085         if (odp_port != ctx->flow.in_port) {
2086             add_output_action(ctx, odp_port);
2087         }
2088         break;
2089     }
2090
2091     if (prev_nf_output_iface == NF_OUT_FLOOD) {
2092         ctx->nf_output_iface = NF_OUT_FLOOD;
2093     } else if (ctx->nf_output_iface == NF_OUT_DROP) {
2094         ctx->nf_output_iface = prev_nf_output_iface;
2095     } else if (prev_nf_output_iface != NF_OUT_DROP &&
2096                ctx->nf_output_iface != NF_OUT_FLOOD) {
2097         ctx->nf_output_iface = NF_OUT_MULTI;
2098     }
2099 }
2100
2101 static void
2102 xlate_output_action(struct action_xlate_ctx *ctx,
2103                     const struct ofp_action_output *oao)
2104 {
2105     xlate_output_action__(ctx, ntohs(oao->port), ntohs(oao->max_len));
2106 }
2107
2108 /* If the final ODP action in 'ctx' is "pop priority", drop it, as an
2109  * optimization, because we're going to add another action that sets the
2110  * priority immediately after, or because there are no actions following the
2111  * pop.  */
2112 static void
2113 remove_pop_action(struct action_xlate_ctx *ctx)
2114 {
2115     if (ctx->odp_actions->size == ctx->last_pop_priority) {
2116         ctx->odp_actions->size -= NLA_ALIGN(NLA_HDRLEN);
2117         ctx->last_pop_priority = -1;
2118     }
2119 }
2120
2121 static void
2122 add_pop_action(struct action_xlate_ctx *ctx)
2123 {
2124     if (ctx->odp_actions->size != ctx->last_pop_priority) {
2125         nl_msg_put_flag(ctx->odp_actions, ODP_ACTION_ATTR_POP_PRIORITY);
2126         ctx->last_pop_priority = ctx->odp_actions->size;
2127     }
2128 }
2129
2130 static void
2131 xlate_enqueue_action(struct action_xlate_ctx *ctx,
2132                      const struct ofp_action_enqueue *oae)
2133 {
2134     uint16_t ofp_port, odp_port;
2135     uint32_t priority;
2136     int error;
2137
2138     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(oae->queue_id),
2139                                    &priority);
2140     if (error) {
2141         /* Fall back to ordinary output action. */
2142         xlate_output_action__(ctx, ntohs(oae->port), 0);
2143         return;
2144     }
2145
2146     /* Figure out ODP output port. */
2147     ofp_port = ntohs(oae->port);
2148     if (ofp_port != OFPP_IN_PORT) {
2149         odp_port = ofp_port_to_odp_port(ofp_port);
2150     } else {
2151         odp_port = ctx->flow.in_port;
2152     }
2153
2154     /* Add ODP actions. */
2155     remove_pop_action(ctx);
2156     nl_msg_put_u32(ctx->odp_actions, ODP_ACTION_ATTR_SET_PRIORITY, priority);
2157     add_output_action(ctx, odp_port);
2158     add_pop_action(ctx);
2159
2160     /* Update NetFlow output port. */
2161     if (ctx->nf_output_iface == NF_OUT_DROP) {
2162         ctx->nf_output_iface = odp_port;
2163     } else if (ctx->nf_output_iface != NF_OUT_FLOOD) {
2164         ctx->nf_output_iface = NF_OUT_MULTI;
2165     }
2166 }
2167
2168 static void
2169 xlate_set_queue_action(struct action_xlate_ctx *ctx,
2170                        const struct nx_action_set_queue *nasq)
2171 {
2172     uint32_t priority;
2173     int error;
2174
2175     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(nasq->queue_id),
2176                                    &priority);
2177     if (error) {
2178         /* Couldn't translate queue to a priority, so ignore.  A warning
2179          * has already been logged. */
2180         return;
2181     }
2182
2183     remove_pop_action(ctx);
2184     nl_msg_put_u32(ctx->odp_actions, ODP_ACTION_ATTR_SET_PRIORITY, priority);
2185 }
2186
2187 static void
2188 xlate_set_dl_tci(struct action_xlate_ctx *ctx)
2189 {
2190     ovs_be16 tci = ctx->flow.vlan_tci;
2191     if (!(tci & htons(VLAN_CFI))) {
2192         nl_msg_put_flag(ctx->odp_actions, ODP_ACTION_ATTR_STRIP_VLAN);
2193     } else {
2194         nl_msg_put_be16(ctx->odp_actions, ODP_ACTION_ATTR_SET_DL_TCI,
2195                         tci & ~htons(VLAN_CFI));
2196     }
2197 }
2198
2199 struct xlate_reg_state {
2200     ovs_be16 vlan_tci;
2201     ovs_be64 tun_id;
2202 };
2203
2204 static void
2205 save_reg_state(const struct action_xlate_ctx *ctx,
2206                struct xlate_reg_state *state)
2207 {
2208     state->vlan_tci = ctx->flow.vlan_tci;
2209     state->tun_id = ctx->flow.tun_id;
2210 }
2211
2212 static void
2213 update_reg_state(struct action_xlate_ctx *ctx,
2214                  const struct xlate_reg_state *state)
2215 {
2216     if (ctx->flow.vlan_tci != state->vlan_tci) {
2217         xlate_set_dl_tci(ctx);
2218     }
2219     if (ctx->flow.tun_id != state->tun_id) {
2220         nl_msg_put_be64(ctx->odp_actions,
2221                         ODP_ACTION_ATTR_SET_TUNNEL, ctx->flow.tun_id);
2222     }
2223 }
2224
2225 static void
2226 xlate_nicira_action(struct action_xlate_ctx *ctx,
2227                     const struct nx_action_header *nah)
2228 {
2229     const struct nx_action_resubmit *nar;
2230     const struct nx_action_set_tunnel *nast;
2231     const struct nx_action_set_queue *nasq;
2232     const struct nx_action_multipath *nam;
2233     enum nx_action_subtype subtype = ntohs(nah->subtype);
2234     struct xlate_reg_state state;
2235     ovs_be64 tun_id;
2236
2237     assert(nah->vendor == htonl(NX_VENDOR_ID));
2238     switch (subtype) {
2239     case NXAST_RESUBMIT:
2240         nar = (const struct nx_action_resubmit *) nah;
2241         xlate_table_action(ctx, ofp_port_to_odp_port(ntohs(nar->in_port)));
2242         break;
2243
2244     case NXAST_SET_TUNNEL:
2245         nast = (const struct nx_action_set_tunnel *) nah;
2246         tun_id = htonll(ntohl(nast->tun_id));
2247         nl_msg_put_be64(ctx->odp_actions, ODP_ACTION_ATTR_SET_TUNNEL, tun_id);
2248         ctx->flow.tun_id = tun_id;
2249         break;
2250
2251     case NXAST_DROP_SPOOFED_ARP:
2252         if (ctx->flow.dl_type == htons(ETH_TYPE_ARP)) {
2253             nl_msg_put_flag(ctx->odp_actions,
2254                             ODP_ACTION_ATTR_DROP_SPOOFED_ARP);
2255         }
2256         break;
2257
2258     case NXAST_SET_QUEUE:
2259         nasq = (const struct nx_action_set_queue *) nah;
2260         xlate_set_queue_action(ctx, nasq);
2261         break;
2262
2263     case NXAST_POP_QUEUE:
2264         add_pop_action(ctx);
2265         break;
2266
2267     case NXAST_REG_MOVE:
2268         save_reg_state(ctx, &state);
2269         nxm_execute_reg_move((const struct nx_action_reg_move *) nah,
2270                              &ctx->flow);
2271         update_reg_state(ctx, &state);
2272         break;
2273
2274     case NXAST_REG_LOAD:
2275         save_reg_state(ctx, &state);
2276         nxm_execute_reg_load((const struct nx_action_reg_load *) nah,
2277                              &ctx->flow);
2278         update_reg_state(ctx, &state);
2279         break;
2280
2281     case NXAST_NOTE:
2282         /* Nothing to do. */
2283         break;
2284
2285     case NXAST_SET_TUNNEL64:
2286         tun_id = ((const struct nx_action_set_tunnel64 *) nah)->tun_id;
2287         nl_msg_put_be64(ctx->odp_actions, ODP_ACTION_ATTR_SET_TUNNEL, tun_id);
2288         ctx->flow.tun_id = tun_id;
2289         break;
2290
2291     case NXAST_MULTIPATH:
2292         nam = (const struct nx_action_multipath *) nah;
2293         multipath_execute(nam, &ctx->flow);
2294         break;
2295
2296     /* If you add a new action here that modifies flow data, don't forget to
2297      * update the flow key in ctx->flow at the same time. */
2298
2299     case NXAST_SNAT__OBSOLETE:
2300     default:
2301         VLOG_DBG_RL(&rl, "unknown Nicira action type %d", (int) subtype);
2302         break;
2303     }
2304 }
2305
2306 static void
2307 do_xlate_actions(const union ofp_action *in, size_t n_in,
2308                  struct action_xlate_ctx *ctx)
2309 {
2310     struct actions_iterator iter;
2311     const union ofp_action *ia;
2312     const struct ofport *port;
2313
2314     port = get_port(ctx->ofproto, ctx->flow.in_port);
2315     if (port && port->opp.config & (OFPPC_NO_RECV | OFPPC_NO_RECV_STP) &&
2316         port->opp.config & (eth_addr_equals(ctx->flow.dl_dst, eth_addr_stp)
2317                             ? OFPPC_NO_RECV_STP : OFPPC_NO_RECV)) {
2318         /* Drop this flow. */
2319         return;
2320     }
2321
2322     for (ia = actions_first(&iter, in, n_in); ia; ia = actions_next(&iter)) {
2323         enum ofp_action_type type = ntohs(ia->type);
2324         const struct ofp_action_dl_addr *oada;
2325
2326         switch (type) {
2327         case OFPAT_OUTPUT:
2328             xlate_output_action(ctx, &ia->output);
2329             break;
2330
2331         case OFPAT_SET_VLAN_VID:
2332             ctx->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
2333             ctx->flow.vlan_tci |= ia->vlan_vid.vlan_vid | htons(VLAN_CFI);
2334             xlate_set_dl_tci(ctx);
2335             break;
2336
2337         case OFPAT_SET_VLAN_PCP:
2338             ctx->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
2339             ctx->flow.vlan_tci |= htons(
2340                 (ia->vlan_pcp.vlan_pcp << VLAN_PCP_SHIFT) | VLAN_CFI);
2341             xlate_set_dl_tci(ctx);
2342             break;
2343
2344         case OFPAT_STRIP_VLAN:
2345             ctx->flow.vlan_tci = htons(0);
2346             xlate_set_dl_tci(ctx);
2347             break;
2348
2349         case OFPAT_SET_DL_SRC:
2350             oada = ((struct ofp_action_dl_addr *) ia);
2351             nl_msg_put_unspec(ctx->odp_actions, ODP_ACTION_ATTR_SET_DL_SRC,
2352                               oada->dl_addr, ETH_ADDR_LEN);
2353             memcpy(ctx->flow.dl_src, oada->dl_addr, ETH_ADDR_LEN);
2354             break;
2355
2356         case OFPAT_SET_DL_DST:
2357             oada = ((struct ofp_action_dl_addr *) ia);
2358             nl_msg_put_unspec(ctx->odp_actions, ODP_ACTION_ATTR_SET_DL_DST,
2359                               oada->dl_addr, ETH_ADDR_LEN);
2360             memcpy(ctx->flow.dl_dst, oada->dl_addr, ETH_ADDR_LEN);
2361             break;
2362
2363         case OFPAT_SET_NW_SRC:
2364             nl_msg_put_be32(ctx->odp_actions, ODP_ACTION_ATTR_SET_NW_SRC,
2365                             ia->nw_addr.nw_addr);
2366             ctx->flow.nw_src = ia->nw_addr.nw_addr;
2367             break;
2368
2369         case OFPAT_SET_NW_DST:
2370             nl_msg_put_be32(ctx->odp_actions, ODP_ACTION_ATTR_SET_NW_DST,
2371                             ia->nw_addr.nw_addr);
2372             ctx->flow.nw_dst = ia->nw_addr.nw_addr;
2373             break;
2374
2375         case OFPAT_SET_NW_TOS:
2376             nl_msg_put_u8(ctx->odp_actions, ODP_ACTION_ATTR_SET_NW_TOS,
2377                           ia->nw_tos.nw_tos);
2378             ctx->flow.nw_tos = ia->nw_tos.nw_tos;
2379             break;
2380
2381         case OFPAT_SET_TP_SRC:
2382             nl_msg_put_be16(ctx->odp_actions, ODP_ACTION_ATTR_SET_TP_SRC,
2383                             ia->tp_port.tp_port);
2384             ctx->flow.tp_src = ia->tp_port.tp_port;
2385             break;
2386
2387         case OFPAT_SET_TP_DST:
2388             nl_msg_put_be16(ctx->odp_actions, ODP_ACTION_ATTR_SET_TP_DST,
2389                             ia->tp_port.tp_port);
2390             ctx->flow.tp_dst = ia->tp_port.tp_port;
2391             break;
2392
2393         case OFPAT_VENDOR:
2394             xlate_nicira_action(ctx, (const struct nx_action_header *) ia);
2395             break;
2396
2397         case OFPAT_ENQUEUE:
2398             xlate_enqueue_action(ctx, (const struct ofp_action_enqueue *) ia);
2399             break;
2400
2401         default:
2402             VLOG_DBG_RL(&rl, "unknown action type %d", (int) type);
2403             break;
2404         }
2405     }
2406 }
2407
2408 static void
2409 action_xlate_ctx_init(struct action_xlate_ctx *ctx,
2410                       struct ofproto *ofproto, const struct flow *flow,
2411                       const struct ofpbuf *packet)
2412 {
2413     ctx->ofproto = ofproto;
2414     ctx->flow = *flow;
2415     ctx->packet = packet;
2416     ctx->resubmit_hook = NULL;
2417     ctx->check_special = true;
2418 }
2419
2420 static void
2421 ofproto_process_cfm(struct ofproto *ofproto, const struct flow *flow,
2422                     const struct ofpbuf *packet)
2423 {
2424     struct ofport *ofport;
2425
2426     ofport = get_port(ofproto, flow->in_port);
2427     if (ofport && ofport->cfm) {
2428         cfm_process_heartbeat(ofport->cfm, packet);
2429     }
2430 }
2431
2432 static struct ofpbuf *
2433 xlate_actions(struct action_xlate_ctx *ctx,
2434               const union ofp_action *in, size_t n_in)
2435 {
2436     COVERAGE_INC(ofproto_ofp2odp);
2437
2438     ctx->odp_actions = ofpbuf_new(512);
2439     ctx->tags = 0;
2440     ctx->may_set_up_flow = true;
2441     ctx->nf_output_iface = NF_OUT_DROP;
2442     ctx->recurse = 0;
2443     ctx->last_pop_priority = -1;
2444
2445     if (ctx->check_special && cfm_should_process_flow(&ctx->flow)) {
2446         if (ctx->packet) {
2447             ofproto_process_cfm(ctx->ofproto, &ctx->flow, ctx->packet);
2448         }
2449         ctx->may_set_up_flow = false;
2450     } else if (ctx->check_special
2451                && ctx->ofproto->ofhooks->special_cb
2452                && !ctx->ofproto->ofhooks->special_cb(&ctx->flow, ctx->packet,
2453                                                      ctx->ofproto->aux)) {
2454         ctx->may_set_up_flow = false;
2455     } else {
2456         do_xlate_actions(in, n_in, ctx);
2457     }
2458
2459     remove_pop_action(ctx);
2460
2461     /* Check with in-band control to see if we're allowed to set up this
2462      * flow. */
2463     if (!connmgr_may_set_up_flow(ctx->ofproto->connmgr, &ctx->flow,
2464                                  ctx->odp_actions->data,
2465                                  ctx->odp_actions->size)) {
2466         ctx->may_set_up_flow = false;
2467     }
2468
2469     return ctx->odp_actions;
2470 }
2471
2472 /* Checks whether 'ofconn' is a slave controller.  If so, returns an OpenFlow
2473  * error message code (composed with ofp_mkerr()) for the caller to propagate
2474  * upward.  Otherwise, returns 0.
2475  *
2476  * The log message mentions 'msg_type'. */
2477 static int
2478 reject_slave_controller(struct ofconn *ofconn, const const char *msg_type)
2479 {
2480     if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
2481         && ofconn_get_role(ofconn) == NX_ROLE_SLAVE) {
2482         static struct vlog_rate_limit perm_rl = VLOG_RATE_LIMIT_INIT(1, 5);
2483         VLOG_WARN_RL(&perm_rl, "rejecting %s message from slave controller",
2484                      msg_type);
2485
2486         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
2487     } else {
2488         return 0;
2489     }
2490 }
2491
2492 static int
2493 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
2494 {
2495     struct ofproto *p = ofconn_get_ofproto(ofconn);
2496     struct ofp_packet_out *opo;
2497     struct ofpbuf payload, *buffer;
2498     union ofp_action *ofp_actions;
2499     struct action_xlate_ctx ctx;
2500     struct ofpbuf *odp_actions;
2501     struct ofpbuf request;
2502     struct flow flow;
2503     size_t n_ofp_actions;
2504     uint16_t in_port;
2505     int error;
2506
2507     COVERAGE_INC(ofproto_packet_out);
2508
2509     error = reject_slave_controller(ofconn, "OFPT_PACKET_OUT");
2510     if (error) {
2511         return error;
2512     }
2513
2514     /* Get ofp_packet_out. */
2515     ofpbuf_use_const(&request, oh, ntohs(oh->length));
2516     opo = ofpbuf_pull(&request, offsetof(struct ofp_packet_out, actions));
2517
2518     /* Get actions. */
2519     error = ofputil_pull_actions(&request, ntohs(opo->actions_len),
2520                                  &ofp_actions, &n_ofp_actions);
2521     if (error) {
2522         return error;
2523     }
2524
2525     /* Get payload. */
2526     if (opo->buffer_id != htonl(UINT32_MAX)) {
2527         error = ofconn_pktbuf_retrieve(ofconn, ntohl(opo->buffer_id),
2528                                        &buffer, &in_port);
2529         if (error || !buffer) {
2530             return error;
2531         }
2532         payload = *buffer;
2533     } else {
2534         payload = request;
2535         buffer = NULL;
2536     }
2537
2538     /* Extract flow, check actions. */
2539     flow_extract(&payload, 0, ofp_port_to_odp_port(ntohs(opo->in_port)),
2540                  &flow);
2541     error = validate_actions(ofp_actions, n_ofp_actions, &flow, p->max_ports);
2542     if (error) {
2543         goto exit;
2544     }
2545
2546     /* Send. */
2547     action_xlate_ctx_init(&ctx, p, &flow, &payload);
2548     odp_actions = xlate_actions(&ctx, ofp_actions, n_ofp_actions);
2549     dpif_execute(p->dpif, odp_actions->data, odp_actions->size, &payload);
2550     ofpbuf_delete(odp_actions);
2551
2552 exit:
2553     ofpbuf_delete(buffer);
2554     return 0;
2555 }
2556
2557 static void
2558 update_port_config(struct ofproto *p, struct ofport *port,
2559                    uint32_t config, uint32_t mask)
2560 {
2561     mask &= config ^ port->opp.config;
2562     if (mask & OFPPC_PORT_DOWN) {
2563         if (config & OFPPC_PORT_DOWN) {
2564             netdev_turn_flags_off(port->netdev, NETDEV_UP, true);
2565         } else {
2566             netdev_turn_flags_on(port->netdev, NETDEV_UP, true);
2567         }
2568     }
2569 #define REVALIDATE_BITS (OFPPC_NO_RECV | OFPPC_NO_RECV_STP |    \
2570                          OFPPC_NO_FWD | OFPPC_NO_FLOOD)
2571     if (mask & REVALIDATE_BITS) {
2572         COVERAGE_INC(ofproto_costly_flags);
2573         port->opp.config ^= mask & REVALIDATE_BITS;
2574         p->need_revalidate = true;
2575     }
2576 #undef REVALIDATE_BITS
2577     if (mask & OFPPC_NO_PACKET_IN) {
2578         port->opp.config ^= OFPPC_NO_PACKET_IN;
2579     }
2580 }
2581
2582 static int
2583 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
2584 {
2585     struct ofproto *p = ofconn_get_ofproto(ofconn);
2586     const struct ofp_port_mod *opm = (const struct ofp_port_mod *) oh;
2587     struct ofport *port;
2588     int error;
2589
2590     error = reject_slave_controller(ofconn, "OFPT_PORT_MOD");
2591     if (error) {
2592         return error;
2593     }
2594
2595     port = get_port(p, ofp_port_to_odp_port(ntohs(opm->port_no)));
2596     if (!port) {
2597         return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_PORT);
2598     } else if (memcmp(port->opp.hw_addr, opm->hw_addr, OFP_ETH_ALEN)) {
2599         return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_HW_ADDR);
2600     } else {
2601         update_port_config(p, port, ntohl(opm->config), ntohl(opm->mask));
2602         if (opm->advertise) {
2603             netdev_set_advertisements(port->netdev, ntohl(opm->advertise));
2604         }
2605     }
2606     return 0;
2607 }
2608
2609 static struct ofpbuf *
2610 make_ofp_stats_reply(ovs_be32 xid, ovs_be16 type, size_t body_len)
2611 {
2612     struct ofp_stats_reply *osr;
2613     struct ofpbuf *msg;
2614
2615     msg = ofpbuf_new(MIN(sizeof *osr + body_len, UINT16_MAX));
2616     osr = put_openflow_xid(sizeof *osr, OFPT_STATS_REPLY, xid, msg);
2617     osr->type = type;
2618     osr->flags = htons(0);
2619     return msg;
2620 }
2621
2622 static struct ofpbuf *
2623 start_ofp_stats_reply(const struct ofp_header *request, size_t body_len)
2624 {
2625     const struct ofp_stats_request *osr
2626         = (const struct ofp_stats_request *) request;
2627     return make_ofp_stats_reply(osr->header.xid, osr->type, body_len);
2628 }
2629
2630 static void *
2631 append_ofp_stats_reply(size_t nbytes, struct ofconn *ofconn,
2632                        struct ofpbuf **msgp)
2633 {
2634     struct ofpbuf *msg = *msgp;
2635     assert(nbytes <= UINT16_MAX - sizeof(struct ofp_stats_reply));
2636     if (nbytes + msg->size > UINT16_MAX) {
2637         struct ofp_stats_reply *reply = msg->data;
2638         reply->flags = htons(OFPSF_REPLY_MORE);
2639         *msgp = make_ofp_stats_reply(reply->header.xid, reply->type, nbytes);
2640         ofconn_send_reply(ofconn, msg);
2641     }
2642     return ofpbuf_put_uninit(*msgp, nbytes);
2643 }
2644
2645 static struct ofpbuf *
2646 make_nxstats_reply(ovs_be32 xid, ovs_be32 subtype, size_t body_len)
2647 {
2648     struct nicira_stats_msg *nsm;
2649     struct ofpbuf *msg;
2650
2651     msg = ofpbuf_new(MIN(sizeof *nsm + body_len, UINT16_MAX));
2652     nsm = put_openflow_xid(sizeof *nsm, OFPT_STATS_REPLY, xid, msg);
2653     nsm->type = htons(OFPST_VENDOR);
2654     nsm->flags = htons(0);
2655     nsm->vendor = htonl(NX_VENDOR_ID);
2656     nsm->subtype = subtype;
2657     return msg;
2658 }
2659
2660 static struct ofpbuf *
2661 start_nxstats_reply(const struct nicira_stats_msg *request, size_t body_len)
2662 {
2663     return make_nxstats_reply(request->header.xid, request->subtype, body_len);
2664 }
2665
2666 static void
2667 append_nxstats_reply(size_t nbytes, struct ofconn *ofconn,
2668                      struct ofpbuf **msgp)
2669 {
2670     struct ofpbuf *msg = *msgp;
2671     assert(nbytes <= UINT16_MAX - sizeof(struct nicira_stats_msg));
2672     if (nbytes + msg->size > UINT16_MAX) {
2673         struct nicira_stats_msg *reply = msg->data;
2674         reply->flags = htons(OFPSF_REPLY_MORE);
2675         *msgp = make_nxstats_reply(reply->header.xid, reply->subtype, nbytes);
2676         ofconn_send_reply(ofconn, msg);
2677     }
2678     ofpbuf_prealloc_tailroom(*msgp, nbytes);
2679 }
2680
2681 static int
2682 handle_desc_stats_request(struct ofconn *ofconn,
2683                           const struct ofp_header *request)
2684 {
2685     struct ofproto *p = ofconn_get_ofproto(ofconn);
2686     struct ofp_desc_stats *ods;
2687     struct ofpbuf *msg;
2688
2689     msg = start_ofp_stats_reply(request, sizeof *ods);
2690     ods = append_ofp_stats_reply(sizeof *ods, ofconn, &msg);
2691     memset(ods, 0, sizeof *ods);
2692     ovs_strlcpy(ods->mfr_desc, p->mfr_desc, sizeof ods->mfr_desc);
2693     ovs_strlcpy(ods->hw_desc, p->hw_desc, sizeof ods->hw_desc);
2694     ovs_strlcpy(ods->sw_desc, p->sw_desc, sizeof ods->sw_desc);
2695     ovs_strlcpy(ods->serial_num, p->serial_desc, sizeof ods->serial_num);
2696     ovs_strlcpy(ods->dp_desc, p->dp_desc, sizeof ods->dp_desc);
2697     ofconn_send_reply(ofconn, msg);
2698
2699     return 0;
2700 }
2701
2702 static int
2703 handle_table_stats_request(struct ofconn *ofconn,
2704                            const struct ofp_header *request)
2705 {
2706     struct ofproto *p = ofconn_get_ofproto(ofconn);
2707     struct ofp_table_stats *ots;
2708     struct ofpbuf *msg;
2709
2710     msg = start_ofp_stats_reply(request, sizeof *ots * 2);
2711
2712     /* Classifier table. */
2713     ots = append_ofp_stats_reply(sizeof *ots, ofconn, &msg);
2714     memset(ots, 0, sizeof *ots);
2715     strcpy(ots->name, "classifier");
2716     ots->wildcards = (ofconn_get_flow_format(ofconn) == NXFF_OPENFLOW10
2717                       ? htonl(OFPFW_ALL) : htonl(OVSFW_ALL));
2718     ots->max_entries = htonl(1024 * 1024); /* An arbitrary big number. */
2719     ots->active_count = htonl(classifier_count(&p->cls));
2720     put_32aligned_be64(&ots->lookup_count, htonll(0));  /* XXX */
2721     put_32aligned_be64(&ots->matched_count, htonll(0)); /* XXX */
2722
2723     ofconn_send_reply(ofconn, msg);
2724     return 0;
2725 }
2726
2727 static void
2728 append_port_stat(struct ofport *port, struct ofconn *ofconn,
2729                  struct ofpbuf **msgp)
2730 {
2731     struct netdev_stats stats;
2732     struct ofp_port_stats *ops;
2733
2734     /* Intentionally ignore return value, since errors will set
2735      * 'stats' to all-1s, which is correct for OpenFlow, and
2736      * netdev_get_stats() will log errors. */
2737     netdev_get_stats(port->netdev, &stats);
2738
2739     ops = append_ofp_stats_reply(sizeof *ops, ofconn, msgp);
2740     ops->port_no = htons(port->opp.port_no);
2741     memset(ops->pad, 0, sizeof ops->pad);
2742     put_32aligned_be64(&ops->rx_packets, htonll(stats.rx_packets));
2743     put_32aligned_be64(&ops->tx_packets, htonll(stats.tx_packets));
2744     put_32aligned_be64(&ops->rx_bytes, htonll(stats.rx_bytes));
2745     put_32aligned_be64(&ops->tx_bytes, htonll(stats.tx_bytes));
2746     put_32aligned_be64(&ops->rx_dropped, htonll(stats.rx_dropped));
2747     put_32aligned_be64(&ops->tx_dropped, htonll(stats.tx_dropped));
2748     put_32aligned_be64(&ops->rx_errors, htonll(stats.rx_errors));
2749     put_32aligned_be64(&ops->tx_errors, htonll(stats.tx_errors));
2750     put_32aligned_be64(&ops->rx_frame_err, htonll(stats.rx_frame_errors));
2751     put_32aligned_be64(&ops->rx_over_err, htonll(stats.rx_over_errors));
2752     put_32aligned_be64(&ops->rx_crc_err, htonll(stats.rx_crc_errors));
2753     put_32aligned_be64(&ops->collisions, htonll(stats.collisions));
2754 }
2755
2756 static int
2757 handle_port_stats_request(struct ofconn *ofconn, const struct ofp_header *oh)
2758 {
2759     struct ofproto *p = ofconn_get_ofproto(ofconn);
2760     const struct ofp_port_stats_request *psr = ofputil_stats_body(oh);
2761     struct ofp_port_stats *ops;
2762     struct ofpbuf *msg;
2763     struct ofport *port;
2764
2765     msg = start_ofp_stats_reply(oh, sizeof *ops * 16);
2766     if (psr->port_no != htons(OFPP_NONE)) {
2767         port = get_port(p, ofp_port_to_odp_port(ntohs(psr->port_no)));
2768         if (port) {
2769             append_port_stat(port, ofconn, &msg);
2770         }
2771     } else {
2772         HMAP_FOR_EACH (port, hmap_node, &p->ports) {
2773             append_port_stat(port, ofconn, &msg);
2774         }
2775     }
2776
2777     ofconn_send_reply(ofconn, msg);
2778     return 0;
2779 }
2780
2781 static void
2782 calc_flow_duration__(long long int start, uint32_t *sec, uint32_t *nsec)
2783 {
2784     long long int msecs = time_msec() - start;
2785     *sec = msecs / 1000;
2786     *nsec = (msecs % 1000) * (1000 * 1000);
2787 }
2788
2789 static void
2790 calc_flow_duration(long long int start, ovs_be32 *sec_be, ovs_be32 *nsec_be)
2791 {
2792     uint32_t sec, nsec;
2793
2794     calc_flow_duration__(start, &sec, &nsec);
2795     *sec_be = htonl(sec);
2796     *nsec_be = htonl(nsec);
2797 }
2798
2799 static void
2800 put_ofp_flow_stats(struct ofconn *ofconn, struct rule *rule,
2801                    ovs_be16 out_port, struct ofpbuf **replyp)
2802 {
2803     struct ofp_flow_stats *ofs;
2804     uint64_t packet_count, byte_count;
2805     ovs_be64 cookie;
2806     size_t act_len, len;
2807
2808     if (rule_is_hidden(rule) || !rule_has_out_port(rule, out_port)) {
2809         return;
2810     }
2811
2812     act_len = sizeof *rule->actions * rule->n_actions;
2813     len = offsetof(struct ofp_flow_stats, actions) + act_len;
2814
2815     rule_get_stats(rule, &packet_count, &byte_count);
2816
2817     ofs = append_ofp_stats_reply(len, ofconn, replyp);
2818     ofs->length = htons(len);
2819     ofs->table_id = 0;
2820     ofs->pad = 0;
2821     ofputil_cls_rule_to_match(&rule->cr, ofconn_get_flow_format(ofconn),
2822                               &ofs->match, rule->flow_cookie, &cookie);
2823     put_32aligned_be64(&ofs->cookie, cookie);
2824     calc_flow_duration(rule->created, &ofs->duration_sec, &ofs->duration_nsec);
2825     ofs->priority = htons(rule->cr.priority);
2826     ofs->idle_timeout = htons(rule->idle_timeout);
2827     ofs->hard_timeout = htons(rule->hard_timeout);
2828     memset(ofs->pad2, 0, sizeof ofs->pad2);
2829     put_32aligned_be64(&ofs->packet_count, htonll(packet_count));
2830     put_32aligned_be64(&ofs->byte_count, htonll(byte_count));
2831     if (rule->n_actions > 0) {
2832         memcpy(ofs->actions, rule->actions, act_len);
2833     }
2834 }
2835
2836 static bool
2837 is_valid_table(uint8_t table_id)
2838 {
2839     if (table_id == 0 || table_id == 0xff) {
2840         return true;
2841     } else {
2842         /* It would probably be better to reply with an error but there doesn't
2843          * seem to be any appropriate value, so that might just be
2844          * confusing. */
2845         VLOG_WARN_RL(&rl, "controller asked for invalid table %"PRIu8,
2846                      table_id);
2847         return false;
2848     }
2849 }
2850
2851 static int
2852 handle_flow_stats_request(struct ofconn *ofconn, const struct ofp_header *oh)
2853 {
2854     const struct ofp_flow_stats_request *fsr = ofputil_stats_body(oh);
2855     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2856     struct ofpbuf *reply;
2857
2858     COVERAGE_INC(ofproto_flows_req);
2859     reply = start_ofp_stats_reply(oh, 1024);
2860     if (is_valid_table(fsr->table_id)) {
2861         struct cls_cursor cursor;
2862         struct cls_rule target;
2863         struct rule *rule;
2864
2865         ofputil_cls_rule_from_match(&fsr->match, 0, NXFF_OPENFLOW10, 0,
2866                                     &target);
2867         cls_cursor_init(&cursor, &ofproto->cls, &target);
2868         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
2869             put_ofp_flow_stats(ofconn, rule, fsr->out_port, &reply);
2870         }
2871     }
2872     ofconn_send_reply(ofconn, reply);
2873
2874     return 0;
2875 }
2876
2877 static void
2878 put_nx_flow_stats(struct ofconn *ofconn, struct rule *rule,
2879                   ovs_be16 out_port, struct ofpbuf **replyp)
2880 {
2881     struct nx_flow_stats *nfs;
2882     uint64_t packet_count, byte_count;
2883     size_t act_len, start_len;
2884     struct ofpbuf *reply;
2885
2886     if (rule_is_hidden(rule) || !rule_has_out_port(rule, out_port)) {
2887         return;
2888     }
2889
2890     rule_get_stats(rule, &packet_count, &byte_count);
2891
2892     act_len = sizeof *rule->actions * rule->n_actions;
2893
2894     append_nxstats_reply(sizeof *nfs + NXM_MAX_LEN + act_len, ofconn, replyp);
2895     start_len = (*replyp)->size;
2896     reply = *replyp;
2897
2898     nfs = ofpbuf_put_uninit(reply, sizeof *nfs);
2899     nfs->table_id = 0;
2900     nfs->pad = 0;
2901     calc_flow_duration(rule->created, &nfs->duration_sec, &nfs->duration_nsec);
2902     nfs->cookie = rule->flow_cookie;
2903     nfs->priority = htons(rule->cr.priority);
2904     nfs->idle_timeout = htons(rule->idle_timeout);
2905     nfs->hard_timeout = htons(rule->hard_timeout);
2906     nfs->match_len = htons(nx_put_match(reply, &rule->cr));
2907     memset(nfs->pad2, 0, sizeof nfs->pad2);
2908     nfs->packet_count = htonll(packet_count);
2909     nfs->byte_count = htonll(byte_count);
2910     if (rule->n_actions > 0) {
2911         ofpbuf_put(reply, rule->actions, act_len);
2912     }
2913     nfs->length = htons(reply->size - start_len);
2914 }
2915
2916 static int
2917 handle_nxst_flow(struct ofconn *ofconn, const struct ofp_header *oh)
2918 {
2919     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2920     struct nx_flow_stats_request *nfsr;
2921     struct cls_rule target;
2922     struct ofpbuf *reply;
2923     struct ofpbuf b;
2924     int error;
2925
2926     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2927
2928     /* Dissect the message. */
2929     nfsr = ofpbuf_pull(&b, sizeof *nfsr);
2930     error = nx_pull_match(&b, ntohs(nfsr->match_len), 0, &target);
2931     if (error) {
2932         return error;
2933     }
2934     if (b.size) {
2935         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
2936     }
2937
2938     COVERAGE_INC(ofproto_flows_req);
2939     reply = start_nxstats_reply(&nfsr->nsm, 1024);
2940     if (is_valid_table(nfsr->table_id)) {
2941         struct cls_cursor cursor;
2942         struct rule *rule;
2943
2944         cls_cursor_init(&cursor, &ofproto->cls, &target);
2945         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
2946             put_nx_flow_stats(ofconn, rule, nfsr->out_port, &reply);
2947         }
2948     }
2949     ofconn_send_reply(ofconn, reply);
2950
2951     return 0;
2952 }
2953
2954 static void
2955 flow_stats_ds(struct rule *rule, struct ds *results)
2956 {
2957     uint64_t packet_count, byte_count;
2958     size_t act_len = sizeof *rule->actions * rule->n_actions;
2959
2960     rule_get_stats(rule, &packet_count, &byte_count);
2961
2962     ds_put_format(results, "duration=%llds, ",
2963                   (time_msec() - rule->created) / 1000);
2964     ds_put_format(results, "idle=%.3fs, ", (time_msec() - rule->used) / 1000.0);
2965     ds_put_format(results, "priority=%u, ", rule->cr.priority);
2966     ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
2967     ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
2968     cls_rule_format(&rule->cr, results);
2969     ds_put_char(results, ',');
2970     if (act_len > 0) {
2971         ofp_print_actions(results, &rule->actions->header, act_len);
2972     } else {
2973         ds_put_cstr(results, "drop");
2974     }
2975     ds_put_cstr(results, "\n");
2976 }
2977
2978 /* Adds a pretty-printed description of all flows to 'results', including
2979  * hidden flows (e.g., set up by in-band control). */
2980 void
2981 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
2982 {
2983     struct cls_cursor cursor;
2984     struct rule *rule;
2985
2986     cls_cursor_init(&cursor, &p->cls, NULL);
2987     CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
2988         flow_stats_ds(rule, results);
2989     }
2990 }
2991
2992 static void
2993 query_aggregate_stats(struct ofproto *ofproto, struct cls_rule *target,
2994                       ovs_be16 out_port, uint8_t table_id,
2995                       struct ofp_aggregate_stats_reply *oasr)
2996 {
2997     uint64_t total_packets = 0;
2998     uint64_t total_bytes = 0;
2999     int n_flows = 0;
3000
3001     COVERAGE_INC(ofproto_agg_request);
3002
3003     if (is_valid_table(table_id)) {
3004         struct cls_cursor cursor;
3005         struct rule *rule;
3006
3007         cls_cursor_init(&cursor, &ofproto->cls, target);
3008         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3009             if (!rule_is_hidden(rule) && rule_has_out_port(rule, out_port)) {
3010                 uint64_t packet_count;
3011                 uint64_t byte_count;
3012
3013                 rule_get_stats(rule, &packet_count, &byte_count);
3014
3015                 total_packets += packet_count;
3016                 total_bytes += byte_count;
3017                 n_flows++;
3018             }
3019         }
3020     }
3021
3022     oasr->flow_count = htonl(n_flows);
3023     put_32aligned_be64(&oasr->packet_count, htonll(total_packets));
3024     put_32aligned_be64(&oasr->byte_count, htonll(total_bytes));
3025     memset(oasr->pad, 0, sizeof oasr->pad);
3026 }
3027
3028 static int
3029 handle_aggregate_stats_request(struct ofconn *ofconn,
3030                                const struct ofp_header *oh)
3031 {
3032     const struct ofp_aggregate_stats_request *request = ofputil_stats_body(oh);
3033     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3034     struct ofp_aggregate_stats_reply *reply;
3035     struct cls_rule target;
3036     struct ofpbuf *msg;
3037
3038     ofputil_cls_rule_from_match(&request->match, 0, NXFF_OPENFLOW10, 0,
3039                                 &target);
3040
3041     msg = start_ofp_stats_reply(oh, sizeof *reply);
3042     reply = append_ofp_stats_reply(sizeof *reply, ofconn, &msg);
3043     query_aggregate_stats(ofproto, &target, request->out_port,
3044                           request->table_id, reply);
3045     ofconn_send_reply(ofconn, msg);
3046     return 0;
3047 }
3048
3049 static int
3050 handle_nxst_aggregate(struct ofconn *ofconn, const struct ofp_header *oh)
3051 {
3052     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3053     struct nx_aggregate_stats_request *request;
3054     struct ofp_aggregate_stats_reply *reply;
3055     struct cls_rule target;
3056     struct ofpbuf b;
3057     struct ofpbuf *buf;
3058     int error;
3059
3060     ofpbuf_use_const(&b, oh, ntohs(oh->length));
3061
3062     /* Dissect the message. */
3063     request = ofpbuf_pull(&b, sizeof *request);
3064     error = nx_pull_match(&b, ntohs(request->match_len), 0, &target);
3065     if (error) {
3066         return error;
3067     }
3068     if (b.size) {
3069         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3070     }
3071
3072     /* Reply. */
3073     COVERAGE_INC(ofproto_flows_req);
3074     buf = start_nxstats_reply(&request->nsm, sizeof *reply);
3075     reply = ofpbuf_put_uninit(buf, sizeof *reply);
3076     query_aggregate_stats(ofproto, &target, request->out_port,
3077                           request->table_id, reply);
3078     ofconn_send_reply(ofconn, buf);
3079
3080     return 0;
3081 }
3082
3083 struct queue_stats_cbdata {
3084     struct ofconn *ofconn;
3085     struct ofport *ofport;
3086     struct ofpbuf *msg;
3087 };
3088
3089 static void
3090 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
3091                 const struct netdev_queue_stats *stats)
3092 {
3093     struct ofp_queue_stats *reply;
3094
3095     reply = append_ofp_stats_reply(sizeof *reply, cbdata->ofconn, &cbdata->msg);
3096     reply->port_no = htons(cbdata->ofport->opp.port_no);
3097     memset(reply->pad, 0, sizeof reply->pad);
3098     reply->queue_id = htonl(queue_id);
3099     put_32aligned_be64(&reply->tx_bytes, htonll(stats->tx_bytes));
3100     put_32aligned_be64(&reply->tx_packets, htonll(stats->tx_packets));
3101     put_32aligned_be64(&reply->tx_errors, htonll(stats->tx_errors));
3102 }
3103
3104 static void
3105 handle_queue_stats_dump_cb(uint32_t queue_id,
3106                            struct netdev_queue_stats *stats,
3107                            void *cbdata_)
3108 {
3109     struct queue_stats_cbdata *cbdata = cbdata_;
3110
3111     put_queue_stats(cbdata, queue_id, stats);
3112 }
3113
3114 static void
3115 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
3116                             struct queue_stats_cbdata *cbdata)
3117 {
3118     cbdata->ofport = port;
3119     if (queue_id == OFPQ_ALL) {
3120         netdev_dump_queue_stats(port->netdev,
3121                                 handle_queue_stats_dump_cb, cbdata);
3122     } else {
3123         struct netdev_queue_stats stats;
3124
3125         if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
3126             put_queue_stats(cbdata, queue_id, &stats);
3127         }
3128     }
3129 }
3130
3131 static int
3132 handle_queue_stats_request(struct ofconn *ofconn, const struct ofp_header *oh)
3133 {
3134     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3135     const struct ofp_queue_stats_request *qsr;
3136     struct queue_stats_cbdata cbdata;
3137     struct ofport *port;
3138     unsigned int port_no;
3139     uint32_t queue_id;
3140
3141     qsr = ofputil_stats_body(oh);
3142     if (!qsr) {
3143         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3144     }
3145
3146     COVERAGE_INC(ofproto_queue_req);
3147
3148     cbdata.ofconn = ofconn;
3149     cbdata.msg = start_ofp_stats_reply(oh, 128);
3150
3151     port_no = ntohs(qsr->port_no);
3152     queue_id = ntohl(qsr->queue_id);
3153     if (port_no == OFPP_ALL) {
3154         HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3155             handle_queue_stats_for_port(port, queue_id, &cbdata);
3156         }
3157     } else if (port_no < ofproto->max_ports) {
3158         port = get_port(ofproto, ofp_port_to_odp_port(port_no));
3159         if (port) {
3160             handle_queue_stats_for_port(port, queue_id, &cbdata);
3161         }
3162     } else {
3163         ofpbuf_delete(cbdata.msg);
3164         return ofp_mkerr(OFPET_QUEUE_OP_FAILED, OFPQOFC_BAD_PORT);
3165     }
3166     ofconn_send_reply(ofconn, cbdata.msg);
3167
3168     return 0;
3169 }
3170
3171 /* Updates 'facet''s used time.  Caller is responsible for calling
3172  * facet_push_stats() to update the flows which 'facet' resubmits into. */
3173 static void
3174 facet_update_time(struct ofproto *ofproto, struct facet *facet,
3175                   long long int used)
3176 {
3177     if (used > facet->used) {
3178         facet->used = used;
3179         if (used > facet->rule->used) {
3180             facet->rule->used = used;
3181         }
3182         netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, used);
3183     }
3184 }
3185
3186 /* Folds the statistics from 'stats' into the counters in 'facet'.
3187  *
3188  * Because of the meaning of a facet's counters, it only makes sense to do this
3189  * if 'stats' are not tracked in the datapath, that is, if 'stats' represents a
3190  * packet that was sent by hand or if it represents statistics that have been
3191  * cleared out of the datapath. */
3192 static void
3193 facet_update_stats(struct ofproto *ofproto, struct facet *facet,
3194                    const struct dpif_flow_stats *stats)
3195 {
3196     if (stats->n_packets || stats->used > facet->used) {
3197         facet_update_time(ofproto, facet, stats->used);
3198         facet->packet_count += stats->n_packets;
3199         facet->byte_count += stats->n_bytes;
3200         facet_push_stats(ofproto, facet);
3201         netflow_flow_update_flags(&facet->nf_flow, stats->tcp_flags);
3202     }
3203 }
3204
3205 static void
3206 facet_push_stats(struct ofproto *ofproto, struct facet *facet)
3207 {
3208     uint64_t rs_packets, rs_bytes;
3209
3210     assert(facet->packet_count >= facet->rs_packet_count);
3211     assert(facet->byte_count >= facet->rs_byte_count);
3212     assert(facet->used >= facet->rs_used);
3213
3214     rs_packets = facet->packet_count - facet->rs_packet_count;
3215     rs_bytes = facet->byte_count - facet->rs_byte_count;
3216
3217     if (rs_packets || rs_bytes || facet->used > facet->rs_used) {
3218         facet->rs_packet_count = facet->packet_count;
3219         facet->rs_byte_count = facet->byte_count;
3220         facet->rs_used = facet->used;
3221
3222         flow_push_stats(ofproto, facet->rule, &facet->flow,
3223                         rs_packets, rs_bytes, facet->used);
3224     }
3225 }
3226
3227 struct ofproto_push {
3228     struct action_xlate_ctx ctx;
3229     uint64_t packets;
3230     uint64_t bytes;
3231     long long int used;
3232 };
3233
3234 static void
3235 push_resubmit(struct action_xlate_ctx *ctx, struct rule *rule)
3236 {
3237     struct ofproto_push *push = CONTAINER_OF(ctx, struct ofproto_push, ctx);
3238
3239     if (rule) {
3240         rule->packet_count += push->packets;
3241         rule->byte_count += push->bytes;
3242         rule->used = MAX(push->used, rule->used);
3243     }
3244 }
3245
3246 /* Pushes flow statistics to the rules which 'flow' resubmits into given
3247  * 'rule''s actions. */
3248 static void
3249 flow_push_stats(struct ofproto *ofproto, const struct rule *rule,
3250                 struct flow *flow, uint64_t packets, uint64_t bytes,
3251                 long long int used)
3252 {
3253     struct ofproto_push push;
3254
3255     push.packets = packets;
3256     push.bytes = bytes;
3257     push.used = used;
3258
3259     action_xlate_ctx_init(&push.ctx, ofproto, flow, NULL);
3260     push.ctx.resubmit_hook = push_resubmit;
3261     ofpbuf_delete(xlate_actions(&push.ctx, rule->actions, rule->n_actions));
3262 }
3263
3264 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
3265  * in which no matching flow already exists in the flow table.
3266  *
3267  * Adds the flow specified by 'ofm', which is followed by 'n_actions'
3268  * ofp_actions, to the ofproto's flow table.  Returns 0 on success or an
3269  * OpenFlow error code as encoded by ofp_mkerr() on failure.
3270  *
3271  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3272  * if any. */
3273 static int
3274 add_flow(struct ofconn *ofconn, struct flow_mod *fm)
3275 {
3276     struct ofproto *p = ofconn_get_ofproto(ofconn);
3277     struct ofpbuf *packet;
3278     struct rule *rule;
3279     uint16_t in_port;
3280     int error;
3281
3282     if (fm->flags & OFPFF_CHECK_OVERLAP
3283         && classifier_rule_overlaps(&p->cls, &fm->cr)) {
3284         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_OVERLAP);
3285     }
3286
3287     error = 0;
3288     if (fm->buffer_id != UINT32_MAX) {
3289         error = ofconn_pktbuf_retrieve(ofconn, fm->buffer_id,
3290                                        &packet, &in_port);
3291     } else {
3292         packet = NULL;
3293         in_port = UINT16_MAX;
3294     }
3295
3296     rule = rule_create(&fm->cr, fm->actions, fm->n_actions,
3297                        fm->idle_timeout, fm->hard_timeout, fm->cookie,
3298                        fm->flags & OFPFF_SEND_FLOW_REM);
3299     rule_insert(p, rule);
3300     if (packet) {
3301         rule_execute(p, rule, in_port, packet);
3302     }
3303     return error;
3304 }
3305
3306 static struct rule *
3307 find_flow_strict(struct ofproto *p, const struct flow_mod *fm)
3308 {
3309     return rule_from_cls_rule(classifier_find_rule_exactly(&p->cls, &fm->cr));
3310 }
3311
3312 static int
3313 send_buffered_packet(struct ofconn *ofconn,
3314                      struct rule *rule, uint32_t buffer_id)
3315 {
3316     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3317     struct ofpbuf *packet;
3318     uint16_t in_port;
3319     int error;
3320
3321     if (buffer_id == UINT32_MAX) {
3322         return 0;
3323     }
3324
3325     error = ofconn_pktbuf_retrieve(ofconn, buffer_id, &packet, &in_port);
3326     if (error) {
3327         return error;
3328     }
3329
3330     rule_execute(ofproto, rule, in_port, packet);
3331
3332     return 0;
3333 }
3334 \f
3335 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
3336
3337 struct modify_flows_cbdata {
3338     struct ofproto *ofproto;
3339     const struct flow_mod *fm;
3340     struct rule *match;
3341 };
3342
3343 static int modify_flow(struct ofproto *, const struct flow_mod *,
3344                        struct rule *);
3345
3346 /* Implements OFPFC_MODIFY.  Returns 0 on success or an OpenFlow error code as
3347  * encoded by ofp_mkerr() on failure.
3348  *
3349  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3350  * if any. */
3351 static int
3352 modify_flows_loose(struct ofconn *ofconn, struct flow_mod *fm)
3353 {
3354     struct ofproto *p = ofconn_get_ofproto(ofconn);
3355     struct rule *match = NULL;
3356     struct cls_cursor cursor;
3357     struct rule *rule;
3358
3359     cls_cursor_init(&cursor, &p->cls, &fm->cr);
3360     CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3361         if (!rule_is_hidden(rule)) {
3362             match = rule;
3363             modify_flow(p, fm, rule);
3364         }
3365     }
3366
3367     if (match) {
3368         /* This credits the packet to whichever flow happened to match last.
3369          * That's weird.  Maybe we should do a lookup for the flow that
3370          * actually matches the packet?  Who knows. */
3371         send_buffered_packet(ofconn, match, fm->buffer_id);
3372         return 0;
3373     } else {
3374         return add_flow(ofconn, fm);
3375     }
3376 }
3377
3378 /* Implements OFPFC_MODIFY_STRICT.  Returns 0 on success or an OpenFlow error
3379  * code as encoded by ofp_mkerr() on failure.
3380  *
3381  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3382  * if any. */
3383 static int
3384 modify_flow_strict(struct ofconn *ofconn, struct flow_mod *fm)
3385 {
3386     struct ofproto *p = ofconn_get_ofproto(ofconn);
3387     struct rule *rule = find_flow_strict(p, fm);
3388     if (rule && !rule_is_hidden(rule)) {
3389         modify_flow(p, fm, rule);
3390         return send_buffered_packet(ofconn, rule, fm->buffer_id);
3391     } else {
3392         return add_flow(ofconn, fm);
3393     }
3394 }
3395
3396 /* Implements core of OFPFC_MODIFY and OFPFC_MODIFY_STRICT where 'rule' has
3397  * been identified as a flow in 'p''s flow table to be modified, by changing
3398  * the rule's actions to match those in 'ofm' (which is followed by 'n_actions'
3399  * ofp_action[] structures). */
3400 static int
3401 modify_flow(struct ofproto *p, const struct flow_mod *fm, struct rule *rule)
3402 {
3403     size_t actions_len = fm->n_actions * sizeof *rule->actions;
3404
3405     rule->flow_cookie = fm->cookie;
3406
3407     /* If the actions are the same, do nothing. */
3408     if (fm->n_actions == rule->n_actions
3409         && (!fm->n_actions
3410             || !memcmp(fm->actions, rule->actions, actions_len))) {
3411         return 0;
3412     }
3413
3414     /* Replace actions. */
3415     free(rule->actions);
3416     rule->actions = fm->n_actions ? xmemdup(fm->actions, actions_len) : NULL;
3417     rule->n_actions = fm->n_actions;
3418
3419     p->need_revalidate = true;
3420
3421     return 0;
3422 }
3423 \f
3424 /* OFPFC_DELETE implementation. */
3425
3426 static void delete_flow(struct ofproto *, struct rule *, ovs_be16 out_port);
3427
3428 /* Implements OFPFC_DELETE. */
3429 static void
3430 delete_flows_loose(struct ofproto *p, const struct flow_mod *fm)
3431 {
3432     struct rule *rule, *next_rule;
3433     struct cls_cursor cursor;
3434
3435     cls_cursor_init(&cursor, &p->cls, &fm->cr);
3436     CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
3437         delete_flow(p, rule, htons(fm->out_port));
3438     }
3439 }
3440
3441 /* Implements OFPFC_DELETE_STRICT. */
3442 static void
3443 delete_flow_strict(struct ofproto *p, struct flow_mod *fm)
3444 {
3445     struct rule *rule = find_flow_strict(p, fm);
3446     if (rule) {
3447         delete_flow(p, rule, htons(fm->out_port));
3448     }
3449 }
3450
3451 /* Implements core of OFPFC_DELETE and OFPFC_DELETE_STRICT where 'rule' has
3452  * been identified as a flow to delete from 'p''s flow table, by deleting the
3453  * flow and sending out a OFPT_FLOW_REMOVED message to any interested
3454  * controller.
3455  *
3456  * Will not delete 'rule' if it is hidden.  Will delete 'rule' only if
3457  * 'out_port' is htons(OFPP_NONE) or if 'rule' actually outputs to the
3458  * specified 'out_port'. */
3459 static void
3460 delete_flow(struct ofproto *p, struct rule *rule, ovs_be16 out_port)
3461 {
3462     if (rule_is_hidden(rule)) {
3463         return;
3464     }
3465
3466     if (out_port != htons(OFPP_NONE) && !rule_has_out_port(rule, out_port)) {
3467         return;
3468     }
3469
3470     rule_send_removed(p, rule, OFPRR_DELETE);
3471     rule_remove(p, rule);
3472 }
3473 \f
3474 static int
3475 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
3476 {
3477     struct ofproto *p = ofconn_get_ofproto(ofconn);
3478     struct flow_mod fm;
3479     int error;
3480
3481     error = reject_slave_controller(ofconn, "flow_mod");
3482     if (error) {
3483         return error;
3484     }
3485
3486     error = ofputil_decode_flow_mod(&fm, oh, ofconn_get_flow_format(ofconn));
3487     if (error) {
3488         return error;
3489     }
3490
3491     /* We do not support the emergency flow cache.  It will hopefully get
3492      * dropped from OpenFlow in the near future. */
3493     if (fm.flags & OFPFF_EMERG) {
3494         /* There isn't a good fit for an error code, so just state that the
3495          * flow table is full. */
3496         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_ALL_TABLES_FULL);
3497     }
3498
3499     error = validate_actions(fm.actions, fm.n_actions,
3500                              &fm.cr.flow, p->max_ports);
3501     if (error) {
3502         return error;
3503     }
3504
3505     switch (fm.command) {
3506     case OFPFC_ADD:
3507         return add_flow(ofconn, &fm);
3508
3509     case OFPFC_MODIFY:
3510         return modify_flows_loose(ofconn, &fm);
3511
3512     case OFPFC_MODIFY_STRICT:
3513         return modify_flow_strict(ofconn, &fm);
3514
3515     case OFPFC_DELETE:
3516         delete_flows_loose(p, &fm);
3517         return 0;
3518
3519     case OFPFC_DELETE_STRICT:
3520         delete_flow_strict(p, &fm);
3521         return 0;
3522
3523     default:
3524         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_BAD_COMMAND);
3525     }
3526 }
3527
3528 static int
3529 handle_tun_id_from_cookie(struct ofconn *ofconn, const struct ofp_header *oh)
3530 {
3531     const struct nxt_tun_id_cookie *msg
3532         = (const struct nxt_tun_id_cookie *) oh;
3533     enum nx_flow_format flow_format;
3534
3535     flow_format = msg->set ? NXFF_TUN_ID_FROM_COOKIE : NXFF_OPENFLOW10;
3536     ofconn_set_flow_format(ofconn, flow_format);
3537
3538     return 0;
3539 }
3540
3541 static int
3542 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
3543 {
3544     struct nx_role_request *nrr = (struct nx_role_request *) oh;
3545     struct nx_role_request *reply;
3546     struct ofpbuf *buf;
3547     uint32_t role;
3548
3549     if (ofconn_get_type(ofconn) != OFCONN_PRIMARY) {
3550         VLOG_WARN_RL(&rl, "ignoring role request on service connection");
3551         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
3552     }
3553
3554     role = ntohl(nrr->role);
3555     if (role != NX_ROLE_OTHER && role != NX_ROLE_MASTER
3556         && role != NX_ROLE_SLAVE) {
3557         VLOG_WARN_RL(&rl, "received request for unknown role %"PRIu32, role);
3558
3559         /* There's no good error code for this. */
3560         return ofp_mkerr(OFPET_BAD_REQUEST, -1);
3561     }
3562
3563     ofconn_set_role(ofconn, role);
3564
3565     reply = make_nxmsg_xid(sizeof *reply, NXT_ROLE_REPLY, oh->xid, &buf);
3566     reply->role = htonl(role);
3567     ofconn_send_reply(ofconn, buf);
3568
3569     return 0;
3570 }
3571
3572 static int
3573 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
3574 {
3575     const struct nxt_set_flow_format *msg
3576         = (const struct nxt_set_flow_format *) oh;
3577     uint32_t format;
3578
3579     format = ntohl(msg->format);
3580     if (format == NXFF_OPENFLOW10
3581         || format == NXFF_TUN_ID_FROM_COOKIE
3582         || format == NXFF_NXM) {
3583         ofconn_set_flow_format(ofconn, format);
3584         return 0;
3585     } else {
3586         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
3587     }
3588 }
3589
3590 static int
3591 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
3592 {
3593     struct ofp_header *ob;
3594     struct ofpbuf *buf;
3595
3596     /* Currently, everything executes synchronously, so we can just
3597      * immediately send the barrier reply. */
3598     ob = make_openflow_xid(sizeof *ob, OFPT_BARRIER_REPLY, oh->xid, &buf);
3599     ofconn_send_reply(ofconn, buf);
3600     return 0;
3601 }
3602
3603 static int
3604 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
3605 {
3606     const struct ofp_header *oh = msg->data;
3607     const struct ofputil_msg_type *type;
3608     int error;
3609
3610     error = ofputil_decode_msg_type(oh, &type);
3611     if (error) {
3612         return error;
3613     }
3614
3615     switch (ofputil_msg_type_code(type)) {
3616         /* OpenFlow requests. */
3617     case OFPUTIL_OFPT_ECHO_REQUEST:
3618         return handle_echo_request(ofconn, oh);
3619
3620     case OFPUTIL_OFPT_FEATURES_REQUEST:
3621         return handle_features_request(ofconn, oh);
3622
3623     case OFPUTIL_OFPT_GET_CONFIG_REQUEST:
3624         return handle_get_config_request(ofconn, oh);
3625
3626     case OFPUTIL_OFPT_SET_CONFIG:
3627         return handle_set_config(ofconn, msg->data);
3628
3629     case OFPUTIL_OFPT_PACKET_OUT:
3630         return handle_packet_out(ofconn, oh);
3631
3632     case OFPUTIL_OFPT_PORT_MOD:
3633         return handle_port_mod(ofconn, oh);
3634
3635     case OFPUTIL_OFPT_FLOW_MOD:
3636         return handle_flow_mod(ofconn, oh);
3637
3638     case OFPUTIL_OFPT_BARRIER_REQUEST:
3639         return handle_barrier_request(ofconn, oh);
3640
3641         /* OpenFlow replies. */
3642     case OFPUTIL_OFPT_ECHO_REPLY:
3643         return 0;
3644
3645         /* Nicira extension requests. */
3646     case OFPUTIL_NXT_TUN_ID_FROM_COOKIE:
3647         return handle_tun_id_from_cookie(ofconn, oh);
3648
3649     case OFPUTIL_NXT_ROLE_REQUEST:
3650         return handle_role_request(ofconn, oh);
3651
3652     case OFPUTIL_NXT_SET_FLOW_FORMAT:
3653         return handle_nxt_set_flow_format(ofconn, oh);
3654
3655     case OFPUTIL_NXT_FLOW_MOD:
3656         return handle_flow_mod(ofconn, oh);
3657
3658         /* OpenFlow statistics requests. */
3659     case OFPUTIL_OFPST_DESC_REQUEST:
3660         return handle_desc_stats_request(ofconn, oh);
3661
3662     case OFPUTIL_OFPST_FLOW_REQUEST:
3663         return handle_flow_stats_request(ofconn, oh);
3664
3665     case OFPUTIL_OFPST_AGGREGATE_REQUEST:
3666         return handle_aggregate_stats_request(ofconn, oh);
3667
3668     case OFPUTIL_OFPST_TABLE_REQUEST:
3669         return handle_table_stats_request(ofconn, oh);
3670
3671     case OFPUTIL_OFPST_PORT_REQUEST:
3672         return handle_port_stats_request(ofconn, oh);
3673
3674     case OFPUTIL_OFPST_QUEUE_REQUEST:
3675         return handle_queue_stats_request(ofconn, oh);
3676
3677         /* Nicira extension statistics requests. */
3678     case OFPUTIL_NXST_FLOW_REQUEST:
3679         return handle_nxst_flow(ofconn, oh);
3680
3681     case OFPUTIL_NXST_AGGREGATE_REQUEST:
3682         return handle_nxst_aggregate(ofconn, oh);
3683
3684     case OFPUTIL_INVALID:
3685     case OFPUTIL_OFPT_HELLO:
3686     case OFPUTIL_OFPT_ERROR:
3687     case OFPUTIL_OFPT_FEATURES_REPLY:
3688     case OFPUTIL_OFPT_GET_CONFIG_REPLY:
3689     case OFPUTIL_OFPT_PACKET_IN:
3690     case OFPUTIL_OFPT_FLOW_REMOVED:
3691     case OFPUTIL_OFPT_PORT_STATUS:
3692     case OFPUTIL_OFPT_BARRIER_REPLY:
3693     case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REQUEST:
3694     case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REPLY:
3695     case OFPUTIL_OFPST_DESC_REPLY:
3696     case OFPUTIL_OFPST_FLOW_REPLY:
3697     case OFPUTIL_OFPST_QUEUE_REPLY:
3698     case OFPUTIL_OFPST_PORT_REPLY:
3699     case OFPUTIL_OFPST_TABLE_REPLY:
3700     case OFPUTIL_OFPST_AGGREGATE_REPLY:
3701     case OFPUTIL_NXT_ROLE_REPLY:
3702     case OFPUTIL_NXT_FLOW_REMOVED:
3703     case OFPUTIL_NXST_FLOW_REPLY:
3704     case OFPUTIL_NXST_AGGREGATE_REPLY:
3705     default:
3706         if (VLOG_IS_WARN_ENABLED()) {
3707             char *s = ofp_to_string(oh, ntohs(oh->length), 2);
3708             VLOG_DBG_RL(&rl, "OpenFlow message ignored: %s", s);
3709             free(s);
3710         }
3711         if (oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY) {
3712             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT);
3713         } else {
3714             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
3715         }
3716     }
3717 }
3718
3719 static void
3720 handle_openflow(struct ofconn *ofconn, struct ofpbuf *ofp_msg)
3721 {
3722     int error = handle_openflow__(ofconn, ofp_msg);
3723     if (error) {
3724         send_error_oh(ofconn, ofp_msg->data, error);
3725     }
3726     COVERAGE_INC(ofproto_recv_openflow);
3727 }
3728 \f
3729 static void
3730 handle_miss_upcall(struct ofproto *p, struct dpif_upcall *upcall)
3731 {
3732     struct facet *facet;
3733     struct flow flow;
3734
3735     /* Obtain in_port and tun_id, at least. */
3736     odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
3737
3738     /* Set header pointers in 'flow'. */
3739     flow_extract(upcall->packet, flow.tun_id, flow.in_port, &flow);
3740
3741     if (cfm_should_process_flow(&flow)) {
3742         ofproto_process_cfm(p, &flow, upcall->packet);
3743         ofpbuf_delete(upcall->packet);
3744         return;
3745     } else if (p->ofhooks->special_cb
3746                && !p->ofhooks->special_cb(&flow, upcall->packet, p->aux)) {
3747         ofpbuf_delete(upcall->packet);
3748         return;
3749     }
3750
3751     /* Check with in-band control to see if this packet should be sent
3752      * to the local port regardless of the flow table. */
3753     if (connmgr_msg_in_hook(p->connmgr, &flow, upcall->packet)) {
3754         ofproto_send_packet(p, ODPP_LOCAL, 0, upcall->packet);
3755     }
3756
3757     facet = facet_lookup_valid(p, &flow);
3758     if (!facet) {
3759         struct rule *rule = rule_lookup(p, &flow);
3760         if (!rule) {
3761             /* Don't send a packet-in if OFPPC_NO_PACKET_IN asserted. */
3762             struct ofport *port = get_port(p, flow.in_port);
3763             if (port) {
3764                 if (port->opp.config & OFPPC_NO_PACKET_IN) {
3765                     COVERAGE_INC(ofproto_no_packet_in);
3766                     /* XXX install 'drop' flow entry */
3767                     ofpbuf_delete(upcall->packet);
3768                     return;
3769                 }
3770             } else {
3771                 VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16,
3772                              flow.in_port);
3773             }
3774
3775             COVERAGE_INC(ofproto_packet_in);
3776             send_packet_in(p, upcall, &flow, false);
3777             return;
3778         }
3779
3780         facet = facet_create(p, rule, &flow, upcall->packet);
3781     } else if (!facet->may_install) {
3782         /* The facet is not installable, that is, we need to process every
3783          * packet, so process the current packet's actions into 'facet'. */
3784         facet_make_actions(p, facet, upcall->packet);
3785     }
3786
3787     if (facet->rule->cr.priority == FAIL_OPEN_PRIORITY) {
3788         /*
3789          * Extra-special case for fail-open mode.
3790          *
3791          * We are in fail-open mode and the packet matched the fail-open rule,
3792          * but we are connected to a controller too.  We should send the packet
3793          * up to the controller in the hope that it will try to set up a flow
3794          * and thereby allow us to exit fail-open.
3795          *
3796          * See the top-level comment in fail-open.c for more information.
3797          */
3798         send_packet_in(p, upcall, &flow, true);
3799     }
3800
3801     facet_execute(p, facet, upcall->packet);
3802     facet_install(p, facet, false);
3803 }
3804
3805 static void
3806 handle_upcall(struct ofproto *p, struct dpif_upcall *upcall)
3807 {
3808     struct flow flow;
3809
3810     switch (upcall->type) {
3811     case DPIF_UC_ACTION:
3812         COVERAGE_INC(ofproto_ctlr_action);
3813         odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
3814         send_packet_in(p, upcall, &flow, false);
3815         break;
3816
3817     case DPIF_UC_SAMPLE:
3818         if (p->sflow) {
3819             odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
3820             ofproto_sflow_received(p->sflow, upcall, &flow);
3821         }
3822         ofpbuf_delete(upcall->packet);
3823         break;
3824
3825     case DPIF_UC_MISS:
3826         handle_miss_upcall(p, upcall);
3827         break;
3828
3829     case DPIF_N_UC_TYPES:
3830     default:
3831         VLOG_WARN_RL(&rl, "upcall has unexpected type %"PRIu32, upcall->type);
3832         break;
3833     }
3834 }
3835 \f
3836 /* Flow expiration. */
3837
3838 static int ofproto_dp_max_idle(const struct ofproto *);
3839 static void ofproto_update_stats(struct ofproto *);
3840 static void rule_expire(struct ofproto *, struct rule *);
3841 static void ofproto_expire_facets(struct ofproto *, int dp_max_idle);
3842
3843 /* This function is called periodically by ofproto_run().  Its job is to
3844  * collect updates for the flows that have been installed into the datapath,
3845  * most importantly when they last were used, and then use that information to
3846  * expire flows that have not been used recently.
3847  *
3848  * Returns the number of milliseconds after which it should be called again. */
3849 static int
3850 ofproto_expire(struct ofproto *ofproto)
3851 {
3852     struct rule *rule, *next_rule;
3853     struct cls_cursor cursor;
3854     int dp_max_idle;
3855
3856     /* Update stats for each flow in the datapath. */
3857     ofproto_update_stats(ofproto);
3858
3859     /* Expire facets that have been idle too long. */
3860     dp_max_idle = ofproto_dp_max_idle(ofproto);
3861     ofproto_expire_facets(ofproto, dp_max_idle);
3862
3863     /* Expire OpenFlow flows whose idle_timeout or hard_timeout has passed. */
3864     cls_cursor_init(&cursor, &ofproto->cls, NULL);
3865     CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
3866         rule_expire(ofproto, rule);
3867     }
3868
3869     /* Let the hook know that we're at a stable point: all outstanding data
3870      * in existing flows has been accounted to the account_cb.  Thus, the
3871      * hook can now reasonably do operations that depend on having accurate
3872      * flow volume accounting (currently, that's just bond rebalancing). */
3873     if (ofproto->ofhooks->account_checkpoint_cb) {
3874         ofproto->ofhooks->account_checkpoint_cb(ofproto->aux);
3875     }
3876
3877     return MIN(dp_max_idle, 1000);
3878 }
3879
3880 /* Update 'packet_count', 'byte_count', and 'used' members of installed facets.
3881  *
3882  * This function also pushes statistics updates to rules which each facet
3883  * resubmits into.  Generally these statistics will be accurate.  However, if a
3884  * facet changes the rule it resubmits into at some time in between
3885  * ofproto_update_stats() runs, it is possible that statistics accrued to the
3886  * old rule will be incorrectly attributed to the new rule.  This could be
3887  * avoided by calling ofproto_update_stats() whenever rules are created or
3888  * deleted.  However, the performance impact of making so many calls to the
3889  * datapath do not justify the benefit of having perfectly accurate statistics.
3890  */
3891 static void
3892 ofproto_update_stats(struct ofproto *p)
3893 {
3894     const struct dpif_flow_stats *stats;
3895     struct dpif_flow_dump dump;
3896     const struct nlattr *key;
3897     size_t key_len;
3898
3899     dpif_flow_dump_start(&dump, p->dpif);
3900     while (dpif_flow_dump_next(&dump, &key, &key_len, NULL, NULL, &stats)) {
3901         struct facet *facet;
3902         struct flow flow;
3903
3904         if (odp_flow_key_to_flow(key, key_len, &flow)) {
3905             struct ds s;
3906
3907             ds_init(&s);
3908             odp_flow_key_format(key, key_len, &s);
3909             VLOG_WARN_RL(&rl, "failed to convert ODP flow key to flow: %s",
3910                          ds_cstr(&s));
3911             ds_destroy(&s);
3912
3913             continue;
3914         }
3915         facet = facet_find(p, &flow);
3916
3917         if (facet && facet->installed) {
3918
3919             if (stats->n_packets >= facet->dp_packet_count) {
3920                 facet->packet_count += stats->n_packets - facet->dp_packet_count;
3921             } else {
3922                 VLOG_WARN_RL(&rl, "unexpected packet count from the datapath");
3923             }
3924
3925             if (stats->n_bytes >= facet->dp_byte_count) {
3926                 facet->byte_count += stats->n_bytes - facet->dp_byte_count;
3927             } else {
3928                 VLOG_WARN_RL(&rl, "unexpected byte count from datapath");
3929             }
3930
3931             facet->dp_packet_count = stats->n_packets;
3932             facet->dp_byte_count = stats->n_bytes;
3933
3934             facet_update_time(p, facet, stats->used);
3935             facet_account(p, facet, stats->n_bytes);
3936             facet_push_stats(p, facet);
3937         } else {
3938             /* There's a flow in the datapath that we know nothing about.
3939              * Delete it. */
3940             COVERAGE_INC(ofproto_unexpected_rule);
3941             dpif_flow_del(p->dpif, key, key_len, NULL);
3942         }
3943     }
3944     dpif_flow_dump_done(&dump);
3945 }
3946
3947 /* Calculates and returns the number of milliseconds of idle time after which
3948  * facets should expire from the datapath and we should fold their statistics
3949  * into their parent rules in userspace. */
3950 static int
3951 ofproto_dp_max_idle(const struct ofproto *ofproto)
3952 {
3953     /*
3954      * Idle time histogram.
3955      *
3956      * Most of the time a switch has a relatively small number of facets.  When
3957      * this is the case we might as well keep statistics for all of them in
3958      * userspace and to cache them in the kernel datapath for performance as
3959      * well.
3960      *
3961      * As the number of facets increases, the memory required to maintain
3962      * statistics about them in userspace and in the kernel becomes
3963      * significant.  However, with a large number of facets it is likely that
3964      * only a few of them are "heavy hitters" that consume a large amount of
3965      * bandwidth.  At this point, only heavy hitters are worth caching in the
3966      * kernel and maintaining in userspaces; other facets we can discard.
3967      *
3968      * The technique used to compute the idle time is to build a histogram with
3969      * N_BUCKETS buckets whose width is BUCKET_WIDTH msecs each.  Each facet
3970      * that is installed in the kernel gets dropped in the appropriate bucket.
3971      * After the histogram has been built, we compute the cutoff so that only
3972      * the most-recently-used 1% of facets (but at least 1000 flows) are kept
3973      * cached.  At least the most-recently-used bucket of facets is kept, so
3974      * actually an arbitrary number of facets can be kept in any given
3975      * expiration run (though the next run will delete most of those unless
3976      * they receive additional data).
3977      *
3978      * This requires a second pass through the facets, in addition to the pass
3979      * made by ofproto_update_stats(), because the former function never looks
3980      * at uninstallable facets.
3981      */
3982     enum { BUCKET_WIDTH = ROUND_UP(100, TIME_UPDATE_INTERVAL) };
3983     enum { N_BUCKETS = 5000 / BUCKET_WIDTH };
3984     int buckets[N_BUCKETS] = { 0 };
3985     struct facet *facet;
3986     int total, bucket;
3987     long long int now;
3988     int i;
3989
3990     total = hmap_count(&ofproto->facets);
3991     if (total <= 1000) {
3992         return N_BUCKETS * BUCKET_WIDTH;
3993     }
3994
3995     /* Build histogram. */
3996     now = time_msec();
3997     HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
3998         long long int idle = now - facet->used;
3999         int bucket = (idle <= 0 ? 0
4000                       : idle >= BUCKET_WIDTH * N_BUCKETS ? N_BUCKETS - 1
4001                       : (unsigned int) idle / BUCKET_WIDTH);
4002         buckets[bucket]++;
4003     }
4004
4005     /* Find the first bucket whose flows should be expired. */
4006     for (bucket = 0; bucket < N_BUCKETS; bucket++) {
4007         if (buckets[bucket]) {
4008             int subtotal = 0;
4009             do {
4010                 subtotal += buckets[bucket++];
4011             } while (bucket < N_BUCKETS && subtotal < MAX(1000, total / 100));
4012             break;
4013         }
4014     }
4015
4016     if (VLOG_IS_DBG_ENABLED()) {
4017         struct ds s;
4018
4019         ds_init(&s);
4020         ds_put_cstr(&s, "keep");
4021         for (i = 0; i < N_BUCKETS; i++) {
4022             if (i == bucket) {
4023                 ds_put_cstr(&s, ", drop");
4024             }
4025             if (buckets[i]) {
4026                 ds_put_format(&s, " %d:%d", i * BUCKET_WIDTH, buckets[i]);
4027             }
4028         }
4029         VLOG_INFO("%s: %s (msec:count)",
4030                   dpif_name(ofproto->dpif), ds_cstr(&s));
4031         ds_destroy(&s);
4032     }
4033
4034     return bucket * BUCKET_WIDTH;
4035 }
4036
4037 static void
4038 facet_active_timeout(struct ofproto *ofproto, struct facet *facet)
4039 {
4040     if (ofproto->netflow && !facet_is_controller_flow(facet) &&
4041         netflow_active_timeout_expired(ofproto->netflow, &facet->nf_flow)) {
4042         struct ofexpired expired;
4043
4044         if (facet->installed) {
4045             struct dpif_flow_stats stats;
4046
4047             facet_put__(ofproto, facet, facet->actions, facet->actions_len,
4048                         &stats);
4049             facet_update_stats(ofproto, facet, &stats);
4050         }
4051
4052         expired.flow = facet->flow;
4053         expired.packet_count = facet->packet_count;
4054         expired.byte_count = facet->byte_count;
4055         expired.used = facet->used;
4056         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
4057     }
4058 }
4059
4060 static void
4061 ofproto_expire_facets(struct ofproto *ofproto, int dp_max_idle)
4062 {
4063     long long int cutoff = time_msec() - dp_max_idle;
4064     struct facet *facet, *next_facet;
4065
4066     HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
4067         facet_active_timeout(ofproto, facet);
4068         if (facet->used < cutoff) {
4069             facet_remove(ofproto, facet);
4070         }
4071     }
4072 }
4073
4074 /* If 'rule' is an OpenFlow rule, that has expired according to OpenFlow rules,
4075  * then delete it entirely. */
4076 static void
4077 rule_expire(struct ofproto *ofproto, struct rule *rule)
4078 {
4079     struct facet *facet, *next_facet;
4080     long long int now;
4081     uint8_t reason;
4082
4083     /* Has 'rule' expired? */
4084     now = time_msec();
4085     if (rule->hard_timeout
4086         && now > rule->created + rule->hard_timeout * 1000) {
4087         reason = OFPRR_HARD_TIMEOUT;
4088     } else if (rule->idle_timeout && list_is_empty(&rule->facets)
4089                && now >rule->used + rule->idle_timeout * 1000) {
4090         reason = OFPRR_IDLE_TIMEOUT;
4091     } else {
4092         return;
4093     }
4094
4095     COVERAGE_INC(ofproto_expired);
4096
4097     /* Update stats.  (This is a no-op if the rule expired due to an idle
4098      * timeout, because that only happens when the rule has no facets left.) */
4099     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
4100         facet_remove(ofproto, facet);
4101     }
4102
4103     /* Get rid of the rule. */
4104     if (!rule_is_hidden(rule)) {
4105         rule_send_removed(ofproto, rule, reason);
4106     }
4107     rule_remove(ofproto, rule);
4108 }
4109 \f
4110 static void
4111 rule_send_removed(struct ofproto *p, struct rule *rule, uint8_t reason)
4112 {
4113     struct ofputil_flow_removed fr;
4114
4115     if (!rule->send_flow_removed) {
4116         return;
4117     }
4118
4119     fr.rule = rule->cr;
4120     fr.cookie = rule->flow_cookie;
4121     fr.reason = reason;
4122     calc_flow_duration__(rule->created, &fr.duration_sec, &fr.duration_nsec);
4123     fr.idle_timeout = rule->idle_timeout;
4124     fr.packet_count = rule->packet_count;
4125     fr.byte_count = rule->byte_count;
4126
4127     connmgr_send_flow_removed(p->connmgr, &fr);
4128 }
4129
4130 /* Obtains statistics for 'rule' and stores them in '*packets' and '*bytes'.
4131  * The returned statistics include statistics for all of 'rule''s facets. */
4132 static void
4133 rule_get_stats(const struct rule *rule, uint64_t *packets, uint64_t *bytes)
4134 {
4135     uint64_t p, b;
4136     struct facet *facet;
4137
4138     /* Start from historical data for 'rule' itself that are no longer tracked
4139      * in facets.  This counts, for example, facets that have expired. */
4140     p = rule->packet_count;
4141     b = rule->byte_count;
4142
4143     /* Add any statistics that are tracked by facets.  This includes
4144      * statistical data recently updated by ofproto_update_stats() as well as
4145      * stats for packets that were executed "by hand" via dpif_execute(). */
4146     LIST_FOR_EACH (facet, list_node, &rule->facets) {
4147         p += facet->packet_count;
4148         b += facet->byte_count;
4149     }
4150
4151     *packets = p;
4152     *bytes = b;
4153 }
4154
4155 /* Given 'upcall', of type DPIF_UC_ACTION or DPIF_UC_MISS, sends an
4156  * OFPT_PACKET_IN message to each OpenFlow controller as necessary according to
4157  * their individual configurations.
4158  *
4159  * If 'clone' is true, the caller retains ownership of 'upcall->packet'.
4160  * Otherwise, ownership is transferred to this function. */
4161 static void
4162 send_packet_in(struct ofproto *ofproto, struct dpif_upcall *upcall,
4163                const struct flow *flow, bool clone)
4164 {
4165     struct ofputil_packet_in pin;
4166
4167     pin.packet = upcall->packet;
4168     pin.in_port = odp_port_to_ofp_port(flow->in_port);
4169     pin.reason = upcall->type == DPIF_UC_MISS ? OFPR_NO_MATCH : OFPR_ACTION;
4170     pin.buffer_id = 0;          /* not yet known */
4171     pin.send_len = upcall->userdata;
4172     connmgr_send_packet_in(ofproto->connmgr, upcall, flow,
4173                            clone ? NULL : upcall->packet);
4174 }
4175
4176 static uint64_t
4177 pick_datapath_id(const struct ofproto *ofproto)
4178 {
4179     const struct ofport *port;
4180
4181     port = get_port(ofproto, ODPP_LOCAL);
4182     if (port) {
4183         uint8_t ea[ETH_ADDR_LEN];
4184         int error;
4185
4186         error = netdev_get_etheraddr(port->netdev, ea);
4187         if (!error) {
4188             return eth_addr_to_uint64(ea);
4189         }
4190         VLOG_WARN("could not get MAC address for %s (%s)",
4191                   netdev_get_name(port->netdev), strerror(error));
4192     }
4193     return ofproto->fallback_dpid;
4194 }
4195
4196 static uint64_t
4197 pick_fallback_dpid(void)
4198 {
4199     uint8_t ea[ETH_ADDR_LEN];
4200     eth_addr_nicira_random(ea);
4201     return eth_addr_to_uint64(ea);
4202 }
4203 \f
4204 static void
4205 ofproto_unixctl_list(struct unixctl_conn *conn, const char *arg OVS_UNUSED,
4206                      void *aux OVS_UNUSED)
4207 {
4208     const struct shash_node *node;
4209     struct ds results;
4210
4211     ds_init(&results);
4212     SHASH_FOR_EACH (node, &all_ofprotos) {
4213         ds_put_format(&results, "%s\n", node->name);
4214     }
4215     unixctl_command_reply(conn, 200, ds_cstr(&results));
4216     ds_destroy(&results);
4217 }
4218
4219 struct ofproto_trace {
4220     struct action_xlate_ctx ctx;
4221     struct flow flow;
4222     struct ds *result;
4223 };
4224
4225 static void
4226 trace_format_rule(struct ds *result, int level, const struct rule *rule)
4227 {
4228     ds_put_char_multiple(result, '\t', level);
4229     if (!rule) {
4230         ds_put_cstr(result, "No match\n");
4231         return;
4232     }
4233
4234     ds_put_format(result, "Rule: cookie=%#"PRIx64" ",
4235                   ntohll(rule->flow_cookie));
4236     cls_rule_format(&rule->cr, result);
4237     ds_put_char(result, '\n');
4238
4239     ds_put_char_multiple(result, '\t', level);
4240     ds_put_cstr(result, "OpenFlow ");
4241     ofp_print_actions(result, (const struct ofp_action_header *) rule->actions,
4242                       rule->n_actions * sizeof *rule->actions);
4243     ds_put_char(result, '\n');
4244 }
4245
4246 static void
4247 trace_format_flow(struct ds *result, int level, const char *title,
4248                  struct ofproto_trace *trace)
4249 {
4250     ds_put_char_multiple(result, '\t', level);
4251     ds_put_format(result, "%s: ", title);
4252     if (flow_equal(&trace->ctx.flow, &trace->flow)) {
4253         ds_put_cstr(result, "unchanged");
4254     } else {
4255         flow_format(result, &trace->ctx.flow);
4256         trace->flow = trace->ctx.flow;
4257     }
4258     ds_put_char(result, '\n');
4259 }
4260
4261 static void
4262 trace_resubmit(struct action_xlate_ctx *ctx, struct rule *rule)
4263 {
4264     struct ofproto_trace *trace = CONTAINER_OF(ctx, struct ofproto_trace, ctx);
4265     struct ds *result = trace->result;
4266
4267     ds_put_char(result, '\n');
4268     trace_format_flow(result, ctx->recurse + 1, "Resubmitted flow", trace);
4269     trace_format_rule(result, ctx->recurse + 1, rule);
4270 }
4271
4272 static void
4273 ofproto_unixctl_trace(struct unixctl_conn *conn, const char *args_,
4274                       void *aux OVS_UNUSED)
4275 {
4276     char *dpname, *in_port_s, *tun_id_s, *packet_s;
4277     char *args = xstrdup(args_);
4278     char *save_ptr = NULL;
4279     struct ofproto *ofproto;
4280     struct ofpbuf packet;
4281     struct rule *rule;
4282     struct ds result;
4283     struct flow flow;
4284     uint16_t in_port;
4285     ovs_be64 tun_id;
4286     char *s;
4287
4288     ofpbuf_init(&packet, strlen(args) / 2);
4289     ds_init(&result);
4290
4291     dpname = strtok_r(args, " ", &save_ptr);
4292     tun_id_s = strtok_r(NULL, " ", &save_ptr);
4293     in_port_s = strtok_r(NULL, " ", &save_ptr);
4294     packet_s = strtok_r(NULL, "", &save_ptr); /* Get entire rest of line. */
4295     if (!dpname || !in_port_s || !packet_s) {
4296         unixctl_command_reply(conn, 501, "Bad command syntax");
4297         goto exit;
4298     }
4299
4300     ofproto = shash_find_data(&all_ofprotos, dpname);
4301     if (!ofproto) {
4302         unixctl_command_reply(conn, 501, "Unknown ofproto (use ofproto/list "
4303                               "for help)");
4304         goto exit;
4305     }
4306
4307     tun_id = htonll(strtoull(tun_id_s, NULL, 0));
4308     in_port = ofp_port_to_odp_port(atoi(in_port_s));
4309
4310     packet_s = ofpbuf_put_hex(&packet, packet_s, NULL);
4311     packet_s += strspn(packet_s, " ");
4312     if (*packet_s != '\0') {
4313         unixctl_command_reply(conn, 501, "Trailing garbage in command");
4314         goto exit;
4315     }
4316     if (packet.size < ETH_HEADER_LEN) {
4317         unixctl_command_reply(conn, 501, "Packet data too short for Ethernet");
4318         goto exit;
4319     }
4320
4321     ds_put_cstr(&result, "Packet: ");
4322     s = ofp_packet_to_string(packet.data, packet.size, packet.size);
4323     ds_put_cstr(&result, s);
4324     free(s);
4325
4326     flow_extract(&packet, tun_id, in_port, &flow);
4327     ds_put_cstr(&result, "Flow: ");
4328     flow_format(&result, &flow);
4329     ds_put_char(&result, '\n');
4330
4331     rule = rule_lookup(ofproto, &flow);
4332     trace_format_rule(&result, 0, rule);
4333     if (rule) {
4334         struct ofproto_trace trace;
4335         struct ofpbuf *odp_actions;
4336
4337         trace.result = &result;
4338         trace.flow = flow;
4339         action_xlate_ctx_init(&trace.ctx, ofproto, &flow, &packet);
4340         trace.ctx.resubmit_hook = trace_resubmit;
4341         odp_actions = xlate_actions(&trace.ctx,
4342                                     rule->actions, rule->n_actions);
4343
4344         ds_put_char(&result, '\n');
4345         trace_format_flow(&result, 0, "Final flow", &trace);
4346         ds_put_cstr(&result, "Datapath actions: ");
4347         format_odp_actions(&result, odp_actions->data, odp_actions->size);
4348         ofpbuf_delete(odp_actions);
4349     }
4350
4351     unixctl_command_reply(conn, 200, ds_cstr(&result));
4352
4353 exit:
4354     ds_destroy(&result);
4355     ofpbuf_uninit(&packet);
4356     free(args);
4357 }
4358
4359 static void
4360 ofproto_unixctl_init(void)
4361 {
4362     static bool registered;
4363     if (registered) {
4364         return;
4365     }
4366     registered = true;
4367
4368     unixctl_command_register("ofproto/list", ofproto_unixctl_list, NULL);
4369     unixctl_command_register("ofproto/trace", ofproto_unixctl_trace, NULL);
4370 }
4371 \f
4372 static bool
4373 default_normal_ofhook_cb(const struct flow *flow, const struct ofpbuf *packet,
4374                          struct ofpbuf *odp_actions, tag_type *tags,
4375                          uint16_t *nf_output_iface, void *ofproto_)
4376 {
4377     struct ofproto *ofproto = ofproto_;
4378     struct mac_entry *dst_mac;
4379
4380     /* Drop frames for reserved multicast addresses. */
4381     if (eth_addr_is_reserved(flow->dl_dst)) {
4382         return true;
4383     }
4384
4385     /* Learn source MAC (but don't try to learn from revalidation). */
4386     if (packet != NULL
4387         && mac_learning_may_learn(ofproto->ml, flow->dl_src, 0)) {
4388         struct mac_entry *src_mac;
4389
4390         src_mac = mac_learning_insert(ofproto->ml, flow->dl_src, 0);
4391         if (mac_entry_is_new(src_mac) || src_mac->port.i != flow->in_port) {
4392             /* The log messages here could actually be useful in debugging,
4393              * so keep the rate limit relatively high. */
4394             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
4395             VLOG_DBG_RL(&rl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
4396                         ETH_ADDR_ARGS(flow->dl_src), flow->in_port);
4397
4398             ofproto_revalidate(ofproto,
4399                                mac_learning_changed(ofproto->ml, src_mac));
4400             src_mac->port.i = flow->in_port;
4401         }
4402     }
4403
4404     /* Determine output port. */
4405     dst_mac = mac_learning_lookup(ofproto->ml, flow->dl_dst, 0, tags);
4406     if (!dst_mac) {
4407         flood_packets(ofproto, flow->in_port, OFPPC_NO_FLOOD,
4408                       nf_output_iface, odp_actions);
4409     } else {
4410         int out_port = dst_mac->port.i;
4411         if (out_port != flow->in_port) {
4412             nl_msg_put_u32(odp_actions, ODP_ACTION_ATTR_OUTPUT, out_port);
4413             *nf_output_iface = out_port;
4414         } else {
4415             /* Drop. */
4416         }
4417     }
4418
4419     return true;
4420 }
4421
4422 static const struct ofhooks default_ofhooks = {
4423     default_normal_ofhook_cb,
4424     NULL,
4425     NULL,
4426     NULL
4427 };