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