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