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