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