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