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