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