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