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