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