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