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