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