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