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