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