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