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