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