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