ovs-ofctl: Adding support for table ID.
[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 "dynamic-string.h"
31 #include "fail-open.h"
32 #include "in-band.h"
33 #include "mac-learning.h"
34 #include "netdev.h"
35 #include "netflow.h"
36 #include "ofp-print.h"
37 #include "ofp-util.h"
38 #include "ofproto-sflow.h"
39 #include "ofpbuf.h"
40 #include "openflow/nicira-ext.h"
41 #include "openflow/openflow.h"
42 #include "openvswitch/xflow.h"
43 #include "packets.h"
44 #include "pinsched.h"
45 #include "pktbuf.h"
46 #include "poll-loop.h"
47 #include "port-array.h"
48 #include "rconn.h"
49 #include "shash.h"
50 #include "status.h"
51 #include "stp.h"
52 #include "stream-ssl.h"
53 #include "svec.h"
54 #include "tag.h"
55 #include "timeval.h"
56 #include "unixctl.h"
57 #include "vconn.h"
58 #include "vlog.h"
59 #include "wdp.h"
60 #include "xfif.h"
61 #include "xtoxll.h"
62
63 VLOG_DEFINE_THIS_MODULE(ofproto)
64
65 #include "sflow_api.h"
66
67 struct ofproto_rule {
68     uint64_t flow_cookie;       /* Controller-issued identifier. 
69                                    (Kept in network-byte order.) */
70     bool send_flow_removed;     /* Send a flow removed message? */
71     tag_type tags;              /* Tags (set only by hooks). */
72 };
73
74 static struct ofproto_rule *
75 ofproto_rule_cast(const struct wdp_rule *wdp_rule)
76 {
77     return wdp_rule->client_data;
78 }
79
80 static void
81 ofproto_rule_init(struct wdp_rule *wdp_rule)
82 {
83     wdp_rule->client_data = xzalloc(sizeof(struct ofproto_rule));
84 }
85
86
87 static inline bool
88 rule_is_hidden(const struct wdp_rule *rule)
89 {
90     /* Rules with priority higher than UINT16_MAX are set up by ofproto itself
91      * (e.g. by in-band control) and are intentionally hidden from the
92      * controller. */
93     if (rule->cr.flow.priority > UINT16_MAX) {
94         return true;
95     }
96
97     return false;
98 }
99
100 static void delete_flow(struct ofproto *, struct wdp_rule *, uint8_t reason);
101
102 /* ofproto supports two kinds of OpenFlow connections:
103  *
104  *   - "Controller connections": Connections to ordinary OpenFlow controllers.
105  *     ofproto maintains persistent connections to these controllers and by
106  *     default sends them asynchronous messages such as packet-ins.
107  *
108  *   - "Transient connections", e.g. from ovs-ofctl.  When these connections
109  *     drop, it is the other side's responsibility to reconnect them if
110  *     necessary.  ofproto does not send them asynchronous messages by default.
111  */
112 enum ofconn_type {
113     OFCONN_CONTROLLER,          /* An OpenFlow controller. */
114     OFCONN_TRANSIENT            /* A transient connection. */
115 };
116
117 /* An OpenFlow connection. */
118 struct ofconn {
119     struct ofproto *ofproto;    /* The ofproto that owns this connection. */
120     struct list node;           /* In struct ofproto's "all_conns" list. */
121     struct rconn *rconn;        /* OpenFlow connection. */
122     enum ofconn_type type;      /* Type. */
123     bool flow_mod_table_id;     /* NXT_FLOW_MOD_TABLE_ID enabled? */
124
125     /* OFPT_PACKET_IN related data. */
126     struct rconn_packet_counter *packet_in_counter; /* # queued on 'rconn'. */
127     struct pinsched *schedulers[2]; /* Indexed by reason code; see below. */
128     struct pktbuf *pktbuf;         /* OpenFlow packet buffers. */
129     int miss_send_len;             /* Bytes to send of buffered packets. */
130
131     /* Number of OpenFlow messages queued on 'rconn' as replies to OpenFlow
132      * requests, and the maximum number before we stop reading OpenFlow
133      * requests.  */
134 #define OFCONN_REPLY_MAX 100
135     struct rconn_packet_counter *reply_counter;
136
137     /* type == OFCONN_CONTROLLER only. */
138     enum nx_role role;           /* Role. */
139     struct hmap_node hmap_node;  /* In struct ofproto's "controllers" map. */
140     struct discovery *discovery; /* Controller discovery object, if enabled. */
141     struct status_category *ss;  /* Switch status category. */
142     enum ofproto_band band;      /* In-band or out-of-band? */
143 };
144
145 /* We use OFPR_NO_MATCH and OFPR_ACTION as indexes into struct ofconn's
146  * "schedulers" array.  Their values are 0 and 1, and their meanings and values
147  * coincide with WDP_CHAN_MISS and WDP_CHAN_ACTION, so this is convenient.  In
148  * case anything ever changes, check their values here.  */
149 #define N_SCHEDULERS 2
150 BUILD_ASSERT_DECL(OFPR_NO_MATCH == 0);
151 BUILD_ASSERT_DECL(OFPR_NO_MATCH == WDP_CHAN_MISS);
152 BUILD_ASSERT_DECL(OFPR_ACTION == 1);
153 BUILD_ASSERT_DECL(OFPR_ACTION == WDP_CHAN_ACTION);
154
155 static struct ofconn *ofconn_create(struct ofproto *, struct rconn *,
156                                     enum ofconn_type);
157 static void ofconn_destroy(struct ofconn *);
158 static void ofconn_run(struct ofconn *, struct ofproto *);
159 static void ofconn_wait(struct ofconn *);
160 static bool ofconn_receives_async_msgs(const struct ofconn *);
161 static char *ofconn_make_name(const struct ofproto *, const char *target);
162
163 static void queue_tx(struct ofpbuf *msg, const struct ofconn *ofconn,
164                      struct rconn_packet_counter *counter);
165
166 static void send_packet_in(struct ofproto *, struct wdp_packet *);
167 static void do_send_packet_in(struct wdp_packet *, void *ofconn);
168
169 struct ofproto {
170     /* Settings. */
171     uint64_t datapath_id;       /* Datapath ID. */
172     uint64_t fallback_dpid;     /* Datapath ID if no better choice found. */
173     char *mfr_desc;             /* Manufacturer. */
174     char *hw_desc;              /* Hardware. */
175     char *sw_desc;              /* Software version. */
176     char *serial_desc;          /* Serial number. */
177     char *dp_desc;              /* Datapath description. */
178
179     /* Datapath. */
180     struct wdp *wdp;
181     uint32_t max_ports;
182
183     /* Configuration. */
184     struct switch_status *switch_status;
185     struct fail_open *fail_open;
186     struct netflow *netflow;
187     struct ofproto_sflow *sflow;
188     bool tun_id_from_cookie;    /* NXT_TUN_ID_FROM_COOKIE enabled? */
189
190     /* In-band control. */
191     struct in_band *in_band;
192     long long int next_in_band_update;
193     struct sockaddr_in *extra_in_band_remotes;
194     size_t n_extra_remotes;
195
196     /* OpenFlow connections. */
197     struct hmap controllers;   /* Controller "struct ofconn"s. */
198     struct list all_conns;     /* Contains "struct ofconn"s. */
199     struct pvconn **listeners;
200     size_t n_listeners;
201     struct pvconn **snoops;
202     size_t n_snoops;
203 };
204
205 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
206
207 static uint64_t pick_datapath_id(const struct ofproto *);
208 static uint64_t pick_fallback_dpid(void);
209
210 static void handle_wdp_packet(struct ofproto *, struct wdp_packet *);
211
212 static void handle_openflow(struct ofconn *, struct ofproto *,
213                             struct ofpbuf *);
214
215 int
216 ofproto_create(const char *datapath, const char *datapath_type,
217                const struct ofhooks *ofhooks, void *aux,
218                struct ofproto **ofprotop)
219 {
220     struct wdp_stats stats;
221     struct ofproto *p;
222     struct wdp *wdp;
223     int error;
224
225     *ofprotop = NULL;
226
227     /* Connect to datapath and start listening for messages. */
228     error = wdp_open(datapath, datapath_type, &wdp);
229     if (error) {
230         VLOG_ERR("failed to open datapath %s: %s", datapath, strerror(error));
231         return error;
232     }
233     error = wdp_get_wdp_stats(wdp, &stats);
234     if (error) {
235         VLOG_ERR("failed to obtain stats for datapath %s: %s",
236                  datapath, strerror(error));
237         wdp_close(wdp);
238         return error;
239     }
240     error = wdp_recv_set_mask(wdp, ((1 << WDP_CHAN_MISS)
241                                     | (1 << WDP_CHAN_ACTION)
242                                     | (1 << WDP_CHAN_SFLOW)));
243     if (error) {
244         VLOG_ERR("failed to listen on datapath %s: %s",
245                  datapath, strerror(error));
246         wdp_close(wdp);
247         return error;
248     }
249     wdp_flow_flush(wdp);
250     wdp_recv_purge(wdp);
251     wdp_set_ofhooks(wdp, ofhooks, aux);
252
253     /* Initialize settings. */
254     p = xzalloc(sizeof *p);
255     p->fallback_dpid = pick_fallback_dpid();
256     p->datapath_id = p->fallback_dpid;
257     p->mfr_desc = xstrdup(DEFAULT_MFR_DESC);
258     p->hw_desc = xstrdup(DEFAULT_HW_DESC);
259     p->sw_desc = xstrdup(DEFAULT_SW_DESC);
260     p->serial_desc = xstrdup(DEFAULT_SERIAL_DESC);
261     p->dp_desc = xstrdup(DEFAULT_DP_DESC);
262
263     /* Initialize datapath. */
264     p->wdp = wdp;
265     p->max_ports = stats.max_ports;
266
267     /* Initialize submodules. */
268     p->switch_status = switch_status_create(p);
269     p->in_band = NULL;
270     p->fail_open = NULL;
271     p->netflow = NULL;
272     p->sflow = NULL;
273
274     /* Initialize OpenFlow connections. */
275     list_init(&p->all_conns);
276     hmap_init(&p->controllers);
277     p->listeners = NULL;
278     p->n_listeners = 0;
279     p->snoops = NULL;
280     p->n_snoops = 0;
281
282     /* Pick final datapath ID. */
283     p->datapath_id = pick_datapath_id(p);
284     VLOG_INFO("using datapath ID %016"PRIx64, p->datapath_id);
285
286     *ofprotop = p;
287     return 0;
288 }
289
290 void
291 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
292 {
293     uint64_t old_dpid = p->datapath_id;
294     p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
295     if (p->datapath_id != old_dpid) {
296         VLOG_INFO("datapath ID changed to %016"PRIx64, p->datapath_id);
297
298         /* Force all active connections to reconnect, since there is no way to
299          * notify a controller that the datapath ID has changed. */
300         ofproto_reconnect_controllers(p);
301     }
302 }
303
304 static bool
305 is_discovery_controller(const struct ofproto_controller *c)
306 {
307     return !strcmp(c->target, "discover");
308 }
309
310 static bool
311 is_in_band_controller(const struct ofproto_controller *c)
312 {
313     return is_discovery_controller(c) || c->band == OFPROTO_IN_BAND;
314 }
315
316 /* Creates a new controller in 'ofproto'.  Some of the settings are initially
317  * drawn from 'c', but update_controller() needs to be called later to finish
318  * the new ofconn's configuration. */
319 static void
320 add_controller(struct ofproto *ofproto, const struct ofproto_controller *c)
321 {
322     struct discovery *discovery;
323     struct ofconn *ofconn;
324
325     if (is_discovery_controller(c)) {
326         int error = discovery_create(c->accept_re, c->update_resolv_conf,
327                                      ofproto->wdp, ofproto->switch_status,
328                                      &discovery);
329         if (error) {
330             return;
331         }
332     } else {
333         discovery = NULL;
334     }
335
336     ofconn = ofconn_create(ofproto, rconn_create(5, 8), OFCONN_CONTROLLER);
337     ofconn->pktbuf = pktbuf_create();
338     ofconn->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
339     if (discovery) {
340         ofconn->discovery = discovery;
341     } else {
342         char *name = ofconn_make_name(ofproto, c->target);
343         rconn_connect(ofconn->rconn, c->target, name);
344         free(name);
345     }
346     hmap_insert(&ofproto->controllers, &ofconn->hmap_node,
347                 hash_string(c->target, 0));
348 }
349
350 /* Reconfigures 'ofconn' to match 'c'.  This function cannot update an ofconn's
351  * target or turn discovery on or off (these are done by creating new ofconns
352  * and deleting old ones), but it can update the rest of an ofconn's
353  * settings. */
354 static void
355 update_controller(struct ofconn *ofconn, const struct ofproto_controller *c)
356 {
357     struct ofproto *ofproto = ofconn->ofproto;
358     int probe_interval;
359     int i;
360
361     ofconn->band = (is_in_band_controller(c)
362                     ? OFPROTO_IN_BAND : OFPROTO_OUT_OF_BAND);
363
364     rconn_set_max_backoff(ofconn->rconn, c->max_backoff);
365
366     probe_interval = c->probe_interval ? MAX(c->probe_interval, 5) : 0;
367     rconn_set_probe_interval(ofconn->rconn, probe_interval);
368
369     if (ofconn->discovery) {
370         discovery_set_update_resolv_conf(ofconn->discovery,
371                                          c->update_resolv_conf);
372         discovery_set_accept_controller_re(ofconn->discovery, c->accept_re);
373     }
374
375     for (i = 0; i < N_SCHEDULERS; i++) {
376         struct pinsched **s = &ofconn->schedulers[i];
377
378         if (c->rate_limit > 0) {
379             if (!*s) {
380                 *s = pinsched_create(c->rate_limit, c->burst_limit,
381                                      ofproto->switch_status);
382             } else {
383                 pinsched_set_limits(*s, c->rate_limit, c->burst_limit);
384             }
385         } else {
386             pinsched_destroy(*s);
387             *s = NULL;
388         }
389     }
390 }
391
392 static const char *
393 ofconn_get_target(const struct ofconn *ofconn)
394 {
395     return ofconn->discovery ? "discover" : rconn_get_target(ofconn->rconn);
396 }
397
398 static struct ofconn *
399 find_controller_by_target(struct ofproto *ofproto, const char *target)
400 {
401     struct ofconn *ofconn;
402
403     HMAP_FOR_EACH_WITH_HASH (ofconn, struct ofconn, hmap_node,
404                              hash_string(target, 0), &ofproto->controllers) {
405         if (!strcmp(ofconn_get_target(ofconn), target)) {
406             return ofconn;
407         }
408     }
409     return NULL;
410 }
411
412 static void
413 update_in_band_remotes(struct ofproto *ofproto)
414 {
415     const struct ofconn *ofconn;
416     struct sockaddr_in *addrs;
417     size_t max_addrs, n_addrs;
418     bool discovery;
419     size_t i;
420
421     /* Allocate enough memory for as many remotes as we could possibly have. */
422     max_addrs = ofproto->n_extra_remotes + hmap_count(&ofproto->controllers);
423     addrs = xmalloc(max_addrs * sizeof *addrs);
424     n_addrs = 0;
425
426     /* Add all the remotes. */
427     discovery = false;
428     HMAP_FOR_EACH (ofconn, struct ofconn, hmap_node, &ofproto->controllers) {
429         struct sockaddr_in *sin = &addrs[n_addrs];
430
431         if (ofconn->band == OFPROTO_OUT_OF_BAND) {
432             continue;
433         }
434
435         sin->sin_addr.s_addr = rconn_get_remote_ip(ofconn->rconn);
436         if (sin->sin_addr.s_addr) {
437             sin->sin_port = rconn_get_remote_port(ofconn->rconn);
438             n_addrs++;
439         }
440         if (ofconn->discovery) {
441             discovery = true;
442         }
443     }
444     for (i = 0; i < ofproto->n_extra_remotes; i++) {
445         addrs[n_addrs++] = ofproto->extra_in_band_remotes[i];
446     }
447
448     /* Create or update or destroy in-band.
449      *
450      * Ordinarily we only enable in-band if there's at least one remote
451      * address, but discovery needs the in-band rules for DHCP to be installed
452      * even before we know any remote addresses. */
453     if (n_addrs || discovery) {
454         if (!ofproto->in_band) {
455             in_band_create(ofproto, ofproto->wdp, ofproto->switch_status,
456                            &ofproto->in_band);
457         }
458         if (ofproto->in_band) {
459             in_band_set_remotes(ofproto->in_band, addrs, n_addrs);
460         }
461         ofproto->next_in_band_update = time_msec() + 1000;
462     } else {
463         in_band_destroy(ofproto->in_band);
464         ofproto->in_band = NULL;
465     }
466
467     /* Clean up. */
468     free(addrs);
469 }
470
471 void
472 ofproto_set_controllers(struct ofproto *p,
473                         const struct ofproto_controller *controllers,
474                         size_t n_controllers)
475 {
476     struct shash new_controllers;
477     enum ofproto_fail_mode fail_mode;
478     struct ofconn *ofconn, *next;
479     bool ss_exists;
480     size_t i;
481
482     shash_init(&new_controllers);
483     for (i = 0; i < n_controllers; i++) {
484         const struct ofproto_controller *c = &controllers[i];
485
486         shash_add_once(&new_controllers, c->target, &controllers[i]);
487         if (!find_controller_by_target(p, c->target)) {
488             add_controller(p, c);
489         }
490     }
491
492     fail_mode = OFPROTO_FAIL_STANDALONE;
493     ss_exists = false;
494     HMAP_FOR_EACH_SAFE (ofconn, next, struct ofconn, hmap_node,
495                         &p->controllers) {
496         struct ofproto_controller *c;
497
498         c = shash_find_data(&new_controllers, ofconn_get_target(ofconn));
499         if (!c) {
500             ofconn_destroy(ofconn);
501         } else {
502             update_controller(ofconn, c);
503             if (ofconn->ss) {
504                 ss_exists = true;
505             }
506             if (c->fail == OFPROTO_FAIL_SECURE) {
507                 fail_mode = OFPROTO_FAIL_SECURE;
508             }
509         }
510     }
511     shash_destroy(&new_controllers);
512
513     update_in_band_remotes(p);
514
515     if (!hmap_is_empty(&p->controllers)
516         && fail_mode == OFPROTO_FAIL_STANDALONE) {
517         struct rconn **rconns;
518         size_t n;
519
520         if (!p->fail_open) {
521             p->fail_open = fail_open_create(p, p->switch_status);
522         }
523
524         n = 0;
525         rconns = xmalloc(hmap_count(&p->controllers) * sizeof *rconns);
526         HMAP_FOR_EACH (ofconn, struct ofconn, hmap_node, &p->controllers) {
527             rconns[n++] = ofconn->rconn;
528         }
529
530         fail_open_set_controllers(p->fail_open, rconns, n);
531         /* p->fail_open takes ownership of 'rconns'. */
532     } else {
533         fail_open_destroy(p->fail_open);
534         p->fail_open = NULL;
535     }
536
537     if (!hmap_is_empty(&p->controllers) && !ss_exists) {
538         ofconn = CONTAINER_OF(hmap_first(&p->controllers),
539                               struct ofconn, hmap_node);
540         ofconn->ss = switch_status_register(p->switch_status, "remote",
541                                             rconn_status_cb, ofconn->rconn);
542     }
543 }
544
545 /* Drops the connections between 'ofproto' and all of its controllers, forcing
546  * them to reconnect. */
547 void
548 ofproto_reconnect_controllers(struct ofproto *ofproto)
549 {
550     struct ofconn *ofconn;
551
552     LIST_FOR_EACH (ofconn, struct ofconn, node, &ofproto->all_conns) {
553         rconn_reconnect(ofconn->rconn);
554     }
555 }
556
557 static bool
558 any_extras_changed(const struct ofproto *ofproto,
559                    const struct sockaddr_in *extras, size_t n)
560 {
561     size_t i;
562
563     if (n != ofproto->n_extra_remotes) {
564         return true;
565     }
566
567     for (i = 0; i < n; i++) {
568         const struct sockaddr_in *old = &ofproto->extra_in_band_remotes[i];
569         const struct sockaddr_in *new = &extras[i];
570
571         if (old->sin_addr.s_addr != new->sin_addr.s_addr ||
572             old->sin_port != new->sin_port) {
573             return true;
574         }
575     }
576
577     return false;
578 }
579
580 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
581  * in-band control should guarantee access, in the same way that in-band
582  * control guarantees access to OpenFlow controllers. */
583 void
584 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
585                                   const struct sockaddr_in *extras, size_t n)
586 {
587     if (!any_extras_changed(ofproto, extras, n)) {
588         return;
589     }
590
591     free(ofproto->extra_in_band_remotes);
592     ofproto->n_extra_remotes = n;
593     ofproto->extra_in_band_remotes = xmemdup(extras, n * sizeof *extras);
594
595     update_in_band_remotes(ofproto);
596 }
597
598 void
599 ofproto_set_desc(struct ofproto *p,
600                  const char *mfr_desc, const char *hw_desc,
601                  const char *sw_desc, const char *serial_desc,
602                  const char *dp_desc)
603 {
604     struct ofp_desc_stats *ods;
605
606     if (mfr_desc) {
607         if (strlen(mfr_desc) >= sizeof ods->mfr_desc) {
608             VLOG_WARN("truncating mfr_desc, must be less than %zu characters",
609                     sizeof ods->mfr_desc);
610         }
611         free(p->mfr_desc);
612         p->mfr_desc = xstrdup(mfr_desc);
613     }
614     if (hw_desc) {
615         if (strlen(hw_desc) >= sizeof ods->hw_desc) {
616             VLOG_WARN("truncating hw_desc, must be less than %zu characters",
617                     sizeof ods->hw_desc);
618         }
619         free(p->hw_desc);
620         p->hw_desc = xstrdup(hw_desc);
621     }
622     if (sw_desc) {
623         if (strlen(sw_desc) >= sizeof ods->sw_desc) {
624             VLOG_WARN("truncating sw_desc, must be less than %zu characters",
625                     sizeof ods->sw_desc);
626         }
627         free(p->sw_desc);
628         p->sw_desc = xstrdup(sw_desc);
629     }
630     if (serial_desc) {
631         if (strlen(serial_desc) >= sizeof ods->serial_num) {
632             VLOG_WARN("truncating serial_desc, must be less than %zu "
633                     "characters",
634                     sizeof ods->serial_num);
635         }
636         free(p->serial_desc);
637         p->serial_desc = xstrdup(serial_desc);
638     }
639     if (dp_desc) {
640         if (strlen(dp_desc) >= sizeof ods->dp_desc) {
641             VLOG_WARN("truncating dp_desc, must be less than %zu characters",
642                     sizeof ods->dp_desc);
643         }
644         free(p->dp_desc);
645         p->dp_desc = xstrdup(dp_desc);
646     }
647 }
648
649 static int
650 set_pvconns(struct pvconn ***pvconnsp, size_t *n_pvconnsp,
651             const struct svec *svec)
652 {
653     struct pvconn **pvconns = *pvconnsp;
654     size_t n_pvconns = *n_pvconnsp;
655     int retval = 0;
656     size_t i;
657
658     for (i = 0; i < n_pvconns; i++) {
659         pvconn_close(pvconns[i]);
660     }
661     free(pvconns);
662
663     pvconns = xmalloc(svec->n * sizeof *pvconns);
664     n_pvconns = 0;
665     for (i = 0; i < svec->n; i++) {
666         const char *name = svec->names[i];
667         struct pvconn *pvconn;
668         int error;
669
670         error = pvconn_open(name, &pvconn);
671         if (!error) {
672             pvconns[n_pvconns++] = pvconn;
673         } else {
674             VLOG_ERR("failed to listen on %s: %s", name, strerror(error));
675             if (!retval) {
676                 retval = error;
677             }
678         }
679     }
680
681     *pvconnsp = pvconns;
682     *n_pvconnsp = n_pvconns;
683
684     return retval;
685 }
686
687 int
688 ofproto_set_listeners(struct ofproto *ofproto, const struct svec *listeners)
689 {
690     return set_pvconns(&ofproto->listeners, &ofproto->n_listeners, listeners);
691 }
692
693 int
694 ofproto_set_snoops(struct ofproto *ofproto, const struct svec *snoops)
695 {
696     return set_pvconns(&ofproto->snoops, &ofproto->n_snoops, snoops);
697 }
698
699 int
700 ofproto_set_netflow(struct ofproto *ofproto,
701                     const struct netflow_options *nf_options)
702 {
703     if (nf_options && nf_options->collectors.n) {
704         if (!ofproto->netflow) {
705             ofproto->netflow = netflow_create();
706         }
707         return netflow_set_options(ofproto->netflow, nf_options);
708     } else {
709         netflow_destroy(ofproto->netflow);
710         ofproto->netflow = NULL;
711         return 0;
712     }
713 }
714
715 void
716 ofproto_set_sflow(struct ofproto *ofproto,
717                   const struct ofproto_sflow_options *oso)
718 {
719     struct ofproto_sflow *os = ofproto->sflow;
720     if (oso) {
721         if (!os) {
722             os = ofproto->sflow = ofproto_sflow_create(ofproto->wdp);
723             /* XXX ofport */
724         }
725         ofproto_sflow_set_options(os, oso);
726     } else {
727         ofproto_sflow_destroy(os);
728         ofproto->sflow = NULL;
729     }
730 }
731
732 int
733 ofproto_set_stp(struct ofproto *ofproto OVS_UNUSED, bool enable_stp)
734 {
735     /* XXX */
736     if (enable_stp) {
737         VLOG_WARN("STP is not yet implemented");
738         return EINVAL;
739     } else {
740         return 0;
741     }
742 }
743
744 uint64_t
745 ofproto_get_datapath_id(const struct ofproto *ofproto)
746 {
747     return ofproto->datapath_id;
748 }
749
750 bool
751 ofproto_has_controller(const struct ofproto *ofproto)
752 {
753     return !hmap_is_empty(&ofproto->controllers);
754 }
755
756 void
757 ofproto_get_listeners(const struct ofproto *ofproto, struct svec *listeners)
758 {
759     size_t i;
760
761     for (i = 0; i < ofproto->n_listeners; i++) {
762         svec_add(listeners, pvconn_get_name(ofproto->listeners[i]));
763     }
764 }
765
766 void
767 ofproto_get_snoops(const struct ofproto *ofproto, struct svec *snoops)
768 {
769     size_t i;
770
771     for (i = 0; i < ofproto->n_snoops; i++) {
772         svec_add(snoops, pvconn_get_name(ofproto->snoops[i]));
773     }
774 }
775
776 void
777 ofproto_destroy(struct ofproto *p)
778 {
779     struct ofconn *ofconn, *next_ofconn;
780     size_t i;
781
782     if (!p) {
783         return;
784     }
785
786     /* Destroy fail-open and in-band early, since they touch the classifier. */
787     fail_open_destroy(p->fail_open);
788     p->fail_open = NULL;
789
790     in_band_destroy(p->in_band);
791     p->in_band = NULL;
792     free(p->extra_in_band_remotes);
793
794     ofproto_flush_flows(p);
795
796     LIST_FOR_EACH_SAFE (ofconn, next_ofconn, struct ofconn, node,
797                         &p->all_conns) {
798         ofconn_destroy(ofconn);
799     }
800     hmap_destroy(&p->controllers);
801
802     wdp_close(p->wdp);
803
804     switch_status_destroy(p->switch_status);
805     netflow_destroy(p->netflow);
806     ofproto_sflow_destroy(p->sflow);
807
808     for (i = 0; i < p->n_listeners; i++) {
809         pvconn_close(p->listeners[i]);
810     }
811     free(p->listeners);
812
813     for (i = 0; i < p->n_snoops; i++) {
814         pvconn_close(p->snoops[i]);
815     }
816     free(p->snoops);
817
818     free(p->mfr_desc);
819     free(p->hw_desc);
820     free(p->sw_desc);
821     free(p->serial_desc);
822     free(p->dp_desc);
823
824     free(p);
825 }
826
827 int
828 ofproto_run(struct ofproto *p)
829 {
830     int error = ofproto_run1(p);
831     if (!error) {
832         error = ofproto_run2(p, false);
833     }
834     return error;
835 }
836
837 /* Returns a "preference level" for snooping 'ofconn'.  A higher return value
838  * means that 'ofconn' is more interesting for monitoring than a lower return
839  * value. */
840 static int
841 snoop_preference(const struct ofconn *ofconn)
842 {
843     switch (ofconn->role) {
844     case NX_ROLE_MASTER:
845         return 3;
846     case NX_ROLE_OTHER:
847         return 2;
848     case NX_ROLE_SLAVE:
849         return 1;
850     default:
851         /* Shouldn't happen. */
852         return 0;
853     }
854 }
855
856 /* One of ofproto's "snoop" pvconns has accepted a new connection on 'vconn'.
857  * Connects this vconn to a controller. */
858 static void
859 add_snooper(struct ofproto *ofproto, struct vconn *vconn)
860 {
861     struct ofconn *ofconn, *best;
862
863     /* Pick a controller for monitoring. */
864     best = NULL;
865     LIST_FOR_EACH (ofconn, struct ofconn, node, &ofproto->all_conns) {
866         if (ofconn->type == OFCONN_CONTROLLER
867             && (!best || snoop_preference(ofconn) > snoop_preference(best))) {
868             best = ofconn;
869         }
870     }
871
872     if (best) {
873         rconn_add_monitor(best->rconn, vconn);
874     } else {
875         VLOG_INFO_RL(&rl, "no controller connection to snoop");
876         vconn_close(vconn);
877     }
878 }
879
880 static void
881 ofproto_port_poll_cb(const struct ofp_phy_port *opp, uint8_t reason,
882                      void *ofproto_)
883 {
884     /* XXX Should limit the number of queued port status change messages. */
885     struct ofproto *ofproto = ofproto_;
886     struct ofconn *ofconn;
887
888     LIST_FOR_EACH (ofconn, struct ofconn, node, &ofproto->all_conns) {
889         struct ofp_port_status *ops;
890         struct ofpbuf *b;
891
892         if (!ofconn_receives_async_msgs(ofconn)) {
893             continue;
894         }
895
896         ops = make_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, 0, &b);
897         ops->reason = reason;
898         ops->desc = *opp;
899         hton_ofp_phy_port(&ops->desc);
900         queue_tx(b, ofconn, NULL);
901     }
902 }
903
904 int
905 ofproto_run1(struct ofproto *p)
906 {
907     struct ofconn *ofconn, *next_ofconn;
908     int i;
909
910     for (i = 0; i < 50; i++) {
911         struct wdp_packet packet;
912         int error;
913
914         error = wdp_recv(p->wdp, &packet);
915         if (error) {
916             if (error == ENODEV) {
917                 /* Someone destroyed the datapath behind our back.  The caller
918                  * better destroy us and give up, because we're just going to
919                  * spin from here on out. */
920                 static struct vlog_rate_limit rl2 = VLOG_RATE_LIMIT_INIT(1, 5);
921                 VLOG_ERR_RL(&rl2, "%s: datapath was destroyed externally",
922                             wdp_name(p->wdp));
923                 return ENODEV;
924             }
925             break;
926         }
927
928         handle_wdp_packet(p, xmemdup(&packet, sizeof packet));
929     }
930
931     wdp_port_poll(p->wdp, ofproto_port_poll_cb, p);
932
933     if (p->in_band) {
934         if (time_msec() >= p->next_in_band_update) {
935             update_in_band_remotes(p);
936         }
937         in_band_run(p->in_band);
938     }
939
940     LIST_FOR_EACH_SAFE (ofconn, next_ofconn, struct ofconn, node,
941                         &p->all_conns) {
942         ofconn_run(ofconn, p);
943     }
944
945     /* Fail-open maintenance.  Do this after processing the ofconns since
946      * fail-open checks the status of the controller rconn. */
947     if (p->fail_open) {
948         fail_open_run(p->fail_open);
949     }
950
951     for (i = 0; i < p->n_listeners; i++) {
952         struct vconn *vconn;
953         int retval;
954
955         retval = pvconn_accept(p->listeners[i], OFP_VERSION, &vconn);
956         if (!retval) {
957             struct rconn *rconn;
958             char *name;
959
960             rconn = rconn_create(60, 0);
961             name = ofconn_make_name(p, vconn_get_name(vconn));
962             rconn_connect_unreliably(rconn, vconn, name);
963             free(name);
964
965             ofconn_create(p, rconn, OFCONN_TRANSIENT);
966         } else if (retval != EAGAIN) {
967             VLOG_WARN_RL(&rl, "accept failed (%s)", strerror(retval));
968         }
969     }
970
971     for (i = 0; i < p->n_snoops; i++) {
972         struct vconn *vconn;
973         int retval;
974
975         retval = pvconn_accept(p->snoops[i], OFP_VERSION, &vconn);
976         if (!retval) {
977             add_snooper(p, vconn);
978         } else if (retval != EAGAIN) {
979             VLOG_WARN_RL(&rl, "accept failed (%s)", strerror(retval));
980         }
981     }
982
983     if (p->netflow) {
984         netflow_run(p->netflow);
985     }
986     if (p->sflow) {
987         ofproto_sflow_run(p->sflow);
988     }
989
990     return 0;
991 }
992
993 int
994 ofproto_run2(struct ofproto *p OVS_UNUSED, bool revalidate_all OVS_UNUSED)
995 {
996     return 0;
997 }
998
999 void
1000 ofproto_wait(struct ofproto *p)
1001 {
1002     struct ofconn *ofconn;
1003     size_t i;
1004
1005     wdp_recv_wait(p->wdp);
1006     wdp_port_poll_wait(p->wdp);
1007     LIST_FOR_EACH (ofconn, struct ofconn, node, &p->all_conns) {
1008         ofconn_wait(ofconn);
1009     }
1010     if (p->in_band) {
1011         poll_timer_wait_until(p->next_in_band_update);
1012         in_band_wait(p->in_band);
1013     }
1014     if (p->fail_open) {
1015         fail_open_wait(p->fail_open);
1016     }
1017     if (p->sflow) {
1018         ofproto_sflow_wait(p->sflow);
1019     }
1020     for (i = 0; i < p->n_listeners; i++) {
1021         pvconn_wait(p->listeners[i]);
1022     }
1023     for (i = 0; i < p->n_snoops; i++) {
1024         pvconn_wait(p->snoops[i]);
1025     }
1026 }
1027
1028 void
1029 ofproto_revalidate(struct ofproto *ofproto, tag_type tag)
1030 {
1031     wdp_revalidate(ofproto->wdp, tag);
1032 }
1033
1034 void
1035 ofproto_revalidate_all(struct ofproto *ofproto)
1036 {
1037     wdp_revalidate_all(ofproto->wdp);
1038 }
1039
1040 bool
1041 ofproto_is_alive(const struct ofproto *p)
1042 {
1043     return !hmap_is_empty(&p->controllers);
1044 }
1045
1046 int
1047 ofproto_send_packet(struct ofproto *p, const flow_t *flow,
1048                     const union ofp_action *actions, size_t n_actions,
1049                     const struct ofpbuf *packet)
1050 {
1051     /* XXX Should we translate the wdp_execute() errno value into an OpenFlow
1052      * error code? */
1053     wdp_execute(p->wdp, flow->in_port, actions, n_actions, packet);
1054     return 0;
1055 }
1056
1057 /* Intended for used by ofproto clients and ofproto submodules to add flows to
1058  * the flow table. */
1059 void
1060 ofproto_add_flow(struct ofproto *p, const flow_t *flow,
1061                  const union ofp_action *actions, size_t n_actions,
1062                  int idle_timeout)
1063 {
1064     struct wdp_flow_put put;
1065     struct wdp_rule *rule;
1066
1067     put.flags = WDP_PUT_CREATE | WDP_PUT_MODIFY | WDP_PUT_ALL;
1068     put.flow = flow;
1069     put.actions = actions;
1070     put.n_actions = n_actions;
1071     put.idle_timeout = idle_timeout;
1072     put.hard_timeout = 0;
1073     put.ofp_table_id = 0xff;
1074
1075     if (!wdp_flow_put(p->wdp, &put, NULL, &rule)) {
1076         ofproto_rule_init(rule);
1077     }
1078 }
1079
1080 /* Intended for used by ofproto clients and ofproto submodules to delete flows
1081  * that they earlier added to the flow table. */
1082 void
1083 ofproto_delete_flow(struct ofproto *ofproto, const flow_t *flow)
1084 {
1085     struct wdp_rule *rule = wdp_flow_get(ofproto->wdp, flow, UINT_MAX);
1086     if (rule) {
1087         delete_flow(ofproto, rule, OFPRR_DELETE);
1088     }
1089 }
1090
1091 void
1092 ofproto_flush_flows(struct ofproto *ofproto)
1093 {
1094     COVERAGE_INC(ofproto_flush);
1095     wdp_flow_flush(ofproto->wdp);
1096     if (ofproto->in_band) {
1097         in_band_flushed(ofproto->in_band);
1098     }
1099     if (ofproto->fail_open) {
1100         fail_open_flushed(ofproto->fail_open);
1101     }
1102 }
1103 \f
1104 static struct ofconn *
1105 ofconn_create(struct ofproto *p, struct rconn *rconn, enum ofconn_type type)
1106 {
1107     struct ofconn *ofconn = xzalloc(sizeof *ofconn);
1108     ofconn->ofproto = p;
1109     list_push_back(&p->all_conns, &ofconn->node);
1110     ofconn->rconn = rconn;
1111     ofconn->type = type;
1112     ofconn->role = NX_ROLE_OTHER;
1113     ofconn->packet_in_counter = rconn_packet_counter_create ();
1114     ofconn->pktbuf = NULL;
1115     ofconn->miss_send_len = 0;
1116     ofconn->reply_counter = rconn_packet_counter_create ();
1117     return ofconn;
1118 }
1119
1120 static void
1121 ofconn_destroy(struct ofconn *ofconn)
1122 {
1123     if (ofconn->type == OFCONN_CONTROLLER) {
1124         hmap_remove(&ofconn->ofproto->controllers, &ofconn->hmap_node);
1125     }
1126     discovery_destroy(ofconn->discovery);
1127
1128     list_remove(&ofconn->node);
1129     switch_status_unregister(ofconn->ss);
1130     rconn_destroy(ofconn->rconn);
1131     rconn_packet_counter_destroy(ofconn->packet_in_counter);
1132     rconn_packet_counter_destroy(ofconn->reply_counter);
1133     pktbuf_destroy(ofconn->pktbuf);
1134     free(ofconn);
1135 }
1136
1137 static void
1138 ofconn_run(struct ofconn *ofconn, struct ofproto *p)
1139 {
1140     int iteration;
1141     size_t i;
1142
1143     if (ofconn->discovery) {
1144         char *controller_name;
1145         if (rconn_is_connectivity_questionable(ofconn->rconn)) {
1146             discovery_question_connectivity(ofconn->discovery);
1147         }
1148         if (discovery_run(ofconn->discovery, &controller_name)) {
1149             if (controller_name) {
1150                 char *ofconn_name = ofconn_make_name(p, controller_name);
1151                 rconn_connect(ofconn->rconn, controller_name, ofconn_name);
1152                 free(ofconn_name);
1153             } else {
1154                 rconn_disconnect(ofconn->rconn);
1155             }
1156         }
1157     }
1158
1159     for (i = 0; i < N_SCHEDULERS; i++) {
1160         pinsched_run(ofconn->schedulers[i], do_send_packet_in, ofconn);
1161     }
1162
1163     rconn_run(ofconn->rconn);
1164
1165     if (rconn_packet_counter_read (ofconn->reply_counter) < OFCONN_REPLY_MAX) {
1166         /* Limit the number of iterations to prevent other tasks from
1167          * starving. */
1168         for (iteration = 0; iteration < 50; iteration++) {
1169             struct ofpbuf *of_msg = rconn_recv(ofconn->rconn);
1170             if (!of_msg) {
1171                 break;
1172             }
1173             if (p->fail_open) {
1174                 fail_open_maybe_recover(p->fail_open);
1175             }
1176             handle_openflow(ofconn, p, of_msg);
1177             ofpbuf_delete(of_msg);
1178         }
1179     }
1180
1181     if (!ofconn->discovery && !rconn_is_alive(ofconn->rconn)) {
1182         ofconn_destroy(ofconn);
1183     }
1184 }
1185
1186 static void
1187 ofconn_wait(struct ofconn *ofconn)
1188 {
1189     int i;
1190
1191     if (ofconn->discovery) {
1192         discovery_wait(ofconn->discovery);
1193     }
1194     for (i = 0; i < N_SCHEDULERS; i++) {
1195         pinsched_wait(ofconn->schedulers[i]);
1196     }
1197     rconn_run_wait(ofconn->rconn);
1198     if (rconn_packet_counter_read (ofconn->reply_counter) < OFCONN_REPLY_MAX) {
1199         rconn_recv_wait(ofconn->rconn);
1200     } else {
1201         COVERAGE_INC(ofproto_ofconn_stuck);
1202     }
1203 }
1204
1205 /* Returns true if 'ofconn' should receive asynchronous messages. */
1206 static bool
1207 ofconn_receives_async_msgs(const struct ofconn *ofconn)
1208 {
1209     if (ofconn->type == OFCONN_CONTROLLER) {
1210         /* Ordinary controllers always get asynchronous messages unless they
1211          * have configured themselves as "slaves".  */
1212         return ofconn->role != NX_ROLE_SLAVE;
1213     } else {
1214         /* Transient connections don't get asynchronous messages unless they
1215          * have explicitly asked for them by setting a nonzero miss send
1216          * length. */
1217         return ofconn->miss_send_len > 0;
1218     }
1219 }
1220
1221 /* Returns a human-readable name for an OpenFlow connection between 'ofproto'
1222  * and 'target', suitable for use in log messages for identifying the
1223  * connection.
1224  *
1225  * The name is dynamically allocated.  The caller should free it (with free())
1226  * when it is no longer needed. */
1227 static char *
1228 ofconn_make_name(const struct ofproto *ofproto, const char *target)
1229 {
1230     return xasprintf("%s<->%s", wdp_base_name(ofproto->wdp), target);
1231 }
1232 \f
1233 static bool
1234 rule_has_out_port(const struct wdp_rule *rule, uint16_t out_port)
1235 {
1236     const union ofp_action *oa;
1237     struct actions_iterator i;
1238
1239     if (out_port == htons(OFPP_NONE)) {
1240         return true;
1241     }
1242     for (oa = actions_first(&i, rule->actions, rule->n_actions); oa;
1243          oa = actions_next(&i)) {
1244         if (action_outputs_to_port(oa, out_port)) {
1245             return true;
1246         }
1247     }
1248     return false;
1249 }
1250 \f
1251 static void
1252 queue_tx(struct ofpbuf *msg, const struct ofconn *ofconn,
1253          struct rconn_packet_counter *counter)
1254 {
1255     update_openflow_length(msg);
1256     if (rconn_send(ofconn->rconn, msg, counter)) {
1257         ofpbuf_delete(msg);
1258     }
1259 }
1260
1261 static void
1262 send_error(const struct ofconn *ofconn, const struct ofp_header *oh,
1263            int error, const void *data, size_t len)
1264 {
1265     struct ofpbuf *buf;
1266     struct ofp_error_msg *oem;
1267
1268     if (!(error >> 16)) {
1269         VLOG_WARN_RL(&rl, "not sending bad error code %d to controller",
1270                      error);
1271         return;
1272     }
1273
1274     COVERAGE_INC(ofproto_error);
1275     oem = make_openflow_xid(len + sizeof *oem, OFPT_ERROR,
1276                             oh ? oh->xid : 0, &buf);
1277     oem->type = htons((unsigned int) error >> 16);
1278     oem->code = htons(error & 0xffff);
1279     memcpy(oem->data, data, len);
1280     queue_tx(buf, ofconn, ofconn->reply_counter);
1281 }
1282
1283 static void
1284 send_error_oh(const struct ofconn *ofconn, const struct ofp_header *oh,
1285               int error)
1286 {
1287     size_t oh_length = ntohs(oh->length);
1288     send_error(ofconn, oh, error, oh, MIN(oh_length, 64));
1289 }
1290
1291 static int
1292 handle_echo_request(struct ofconn *ofconn, struct ofp_header *oh)
1293 {
1294     struct ofp_header *rq = oh;
1295     queue_tx(make_echo_reply(rq), ofconn, ofconn->reply_counter);
1296     return 0;
1297 }
1298
1299 static int
1300 handle_features_request(struct ofproto *p, struct ofconn *ofconn,
1301                         struct ofp_header *oh)
1302 {
1303     struct ofpbuf *features;
1304     int error;
1305
1306     error = wdp_get_features(p->wdp, &features);
1307     if (!error) {
1308         struct ofp_switch_features *osf = features->data;
1309
1310         update_openflow_length(features);
1311         osf->header.version = OFP_VERSION;
1312         osf->header.type = OFPT_FEATURES_REPLY;
1313         osf->header.xid = oh->xid;
1314
1315         osf->datapath_id = htonll(p->datapath_id);
1316         osf->n_buffers = htonl(pktbuf_capacity());
1317         memset(osf->pad, 0, sizeof osf->pad);
1318
1319         /* Turn on capabilities implemented by ofproto. */
1320         osf->capabilities |= htonl(OFPC_FLOW_STATS | OFPC_TABLE_STATS |
1321                                    OFPC_PORT_STATS);
1322
1323         queue_tx(features, ofconn, ofconn->reply_counter);
1324     }
1325     return error;
1326 }
1327
1328 static int
1329 handle_get_config_request(struct ofproto *p, struct ofconn *ofconn,
1330                           struct ofp_header *oh)
1331 {
1332     struct ofpbuf *buf;
1333     struct ofp_switch_config *osc;
1334     uint16_t flags;
1335     bool drop_frags;
1336
1337     /* Figure out flags. */
1338     wdp_get_drop_frags(p->wdp, &drop_frags);
1339     flags = drop_frags ? OFPC_FRAG_DROP : OFPC_FRAG_NORMAL;
1340
1341     /* Send reply. */
1342     osc = make_openflow_xid(sizeof *osc, OFPT_GET_CONFIG_REPLY, oh->xid, &buf);
1343     osc->flags = htons(flags);
1344     osc->miss_send_len = htons(ofconn->miss_send_len);
1345     queue_tx(buf, ofconn, ofconn->reply_counter);
1346
1347     return 0;
1348 }
1349
1350 static int
1351 handle_set_config(struct ofproto *p, struct ofconn *ofconn,
1352                   struct ofp_switch_config *osc)
1353 {
1354     uint16_t flags;
1355     int error;
1356
1357     error = check_ofp_message(&osc->header, OFPT_SET_CONFIG, sizeof *osc);
1358     if (error) {
1359         return error;
1360     }
1361     flags = ntohs(osc->flags);
1362
1363     if (ofconn->type == OFCONN_CONTROLLER && ofconn->role != NX_ROLE_SLAVE) {
1364         switch (flags & OFPC_FRAG_MASK) {
1365         case OFPC_FRAG_NORMAL:
1366             wdp_set_drop_frags(p->wdp, false);
1367             break;
1368         case OFPC_FRAG_DROP:
1369             wdp_set_drop_frags(p->wdp, true);
1370             break;
1371         default:
1372             VLOG_WARN_RL(&rl, "requested bad fragment mode (flags=%"PRIx16")",
1373                          osc->flags);
1374             break;
1375         }
1376     }
1377
1378     ofconn->miss_send_len = ntohs(osc->miss_send_len);
1379
1380     return 0;
1381 }
1382
1383 /* Checks whether 'ofconn' is a slave controller.  If so, returns an OpenFlow
1384  * error message code (composed with ofp_mkerr()) for the caller to propagate
1385  * upward.  Otherwise, returns 0.
1386  *
1387  * 'oh' is used to make log messages more informative. */
1388 static int
1389 reject_slave_controller(struct ofconn *ofconn, const struct ofp_header *oh)
1390 {
1391     if (ofconn->type == OFCONN_CONTROLLER && ofconn->role == NX_ROLE_SLAVE) {
1392         static struct vlog_rate_limit perm_rl = VLOG_RATE_LIMIT_INIT(1, 5);
1393         char *type_name;
1394
1395         type_name = ofp_message_type_to_string(oh->type);
1396         VLOG_WARN_RL(&perm_rl, "rejecting %s message from slave controller",
1397                      type_name);
1398         free(type_name);
1399
1400         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
1401     } else {
1402         return 0;
1403     }
1404 }
1405
1406 static int
1407 handle_packet_out(struct ofproto *p, struct ofconn *ofconn,
1408                   struct ofp_header *oh)
1409 {
1410     struct ofp_packet_out *opo;
1411     struct ofpbuf payload, *buffer;
1412     struct ofp_action_header *actions;
1413     int n_actions;
1414     uint16_t in_port;
1415     flow_t flow;
1416     int error;
1417
1418     error = reject_slave_controller(ofconn, oh);
1419     if (error) {
1420         return error;
1421     }
1422
1423     error = check_ofp_packet_out(oh, &payload, &n_actions, p->max_ports);
1424     if (error) {
1425         return error;
1426     }
1427     opo = (struct ofp_packet_out *) oh;
1428     actions = opo->actions;
1429
1430     COVERAGE_INC(ofproto_packet_out);
1431     if (opo->buffer_id != htonl(UINT32_MAX)) {
1432         error = pktbuf_retrieve(ofconn->pktbuf, ntohl(opo->buffer_id),
1433                                 &buffer, &in_port);
1434         if (error || !buffer) {
1435             return error;
1436         }
1437         payload = *buffer;
1438     } else {
1439         buffer = NULL;
1440     }
1441
1442     flow_extract(&payload, 0, ntohs(opo->in_port), &flow);
1443     wdp_execute(p->wdp, flow.in_port, (const union ofp_action *) actions,
1444                 n_actions, &payload);
1445     ofpbuf_delete(buffer);
1446
1447     return 0;
1448 }
1449
1450 static int
1451 handle_port_mod(struct ofproto *p, struct ofconn *ofconn,
1452                 struct ofp_header *oh)
1453 {
1454     const struct ofp_port_mod *opm;
1455     struct wdp_port port;
1456     int error;
1457
1458     error = reject_slave_controller(ofconn, oh);
1459     if (error) {
1460         return error;
1461     }
1462     error = check_ofp_message(oh, OFPT_PORT_MOD, sizeof *opm);
1463     if (error) {
1464         return error;
1465     }
1466     opm = (struct ofp_port_mod *) oh;
1467
1468     if (wdp_port_query_by_number(p->wdp, ntohs(opm->port_no), &port)) {
1469         error = ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_PORT);
1470     } else if (memcmp(port.opp.hw_addr, opm->hw_addr, OFP_ETH_ALEN)) {
1471         error = ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_HW_ADDR);
1472     } else {
1473         uint32_t mask, new_config;
1474
1475         mask = ntohl(opm->mask) & (OFPPC_PORT_DOWN | OFPPC_NO_STP
1476                                    | OFPPC_NO_RECV | OFPPC_NO_RECV_STP
1477                                    | OFPPC_NO_FLOOD | OFPPC_NO_FWD
1478                                    | OFPPC_NO_PACKET_IN);
1479         new_config = (port.opp.config & ~mask) | (ntohl(opm->config) & mask);
1480         if (new_config != port.opp.config) {
1481             error = wdp_port_set_config(p->wdp, ntohs(opm->port_no),
1482                                         new_config);
1483         }
1484         if (opm->advertise) {
1485             netdev_set_advertisements(port.netdev, ntohl(opm->advertise));
1486         }
1487     }
1488     wdp_port_free(&port);
1489
1490     return error;
1491 }
1492
1493 static struct ofpbuf *
1494 make_stats_reply(uint32_t xid, uint16_t type, size_t body_len)
1495 {
1496     struct ofp_stats_reply *osr;
1497     struct ofpbuf *msg;
1498
1499     msg = ofpbuf_new(MIN(sizeof *osr + body_len, UINT16_MAX));
1500     osr = put_openflow_xid(sizeof *osr, OFPT_STATS_REPLY, xid, msg);
1501     osr->type = type;
1502     osr->flags = htons(0);
1503     return msg;
1504 }
1505
1506 static struct ofpbuf *
1507 start_stats_reply(const struct ofp_stats_request *request, size_t body_len)
1508 {
1509     return make_stats_reply(request->header.xid, request->type, body_len);
1510 }
1511
1512 static void *
1513 append_stats_reply(size_t nbytes, struct ofconn *ofconn, struct ofpbuf **msgp)
1514 {
1515     struct ofpbuf *msg = *msgp;
1516     assert(nbytes <= UINT16_MAX - sizeof(struct ofp_stats_reply));
1517     if (nbytes + msg->size > UINT16_MAX) {
1518         struct ofp_stats_reply *reply = msg->data;
1519         reply->flags = htons(OFPSF_REPLY_MORE);
1520         *msgp = make_stats_reply(reply->header.xid, reply->type, nbytes);
1521         queue_tx(msg, ofconn, ofconn->reply_counter);
1522     }
1523     return ofpbuf_put_uninit(*msgp, nbytes);
1524 }
1525
1526 static int
1527 handle_desc_stats_request(struct ofproto *p, struct ofconn *ofconn,
1528                            struct ofp_stats_request *request)
1529 {
1530     struct ofp_desc_stats *ods;
1531     struct ofpbuf *msg;
1532
1533     msg = start_stats_reply(request, sizeof *ods);
1534     ods = append_stats_reply(sizeof *ods, ofconn, &msg);
1535     memset(ods, 0, sizeof *ods);
1536     ovs_strlcpy(ods->mfr_desc, p->mfr_desc, sizeof ods->mfr_desc);
1537     ovs_strlcpy(ods->hw_desc, p->hw_desc, sizeof ods->hw_desc);
1538     ovs_strlcpy(ods->sw_desc, p->sw_desc, sizeof ods->sw_desc);
1539     ovs_strlcpy(ods->serial_num, p->serial_desc, sizeof ods->serial_num);
1540     ovs_strlcpy(ods->dp_desc, p->dp_desc, sizeof ods->dp_desc);
1541     queue_tx(msg, ofconn, ofconn->reply_counter);
1542
1543     return 0;
1544 }
1545
1546 static int
1547 handle_table_stats_request(struct ofproto *p, struct ofconn *ofconn,
1548                            struct ofp_stats_request *request)
1549 {
1550     struct ofpbuf *msg;
1551     int error;
1552
1553     msg = start_stats_reply(request, sizeof(struct ofp_table_stats) * 3);
1554     error = wdp_get_table_stats(p->wdp, msg);
1555     if (!error) {
1556         queue_tx(msg, ofconn, ofconn->reply_counter);
1557     } else {
1558         ofpbuf_delete(msg);
1559     }
1560     return error;
1561 }
1562
1563 static void
1564 append_port_stat(struct wdp_port *port, struct ofconn *ofconn,
1565                  struct ofpbuf **msgp)
1566 {
1567     struct netdev_stats stats;
1568     struct ofp_port_stats *ops;
1569
1570     /* Intentionally ignore return value, since errors will set 
1571      * 'stats' to all-1s, which is correct for OpenFlow, and 
1572      * netdev_get_stats() will log errors. */
1573     netdev_get_stats(port->netdev, &stats);
1574
1575     ops = append_stats_reply(sizeof *ops, ofconn, msgp);
1576     ops->port_no = htons(port->opp.port_no);
1577     memset(ops->pad, 0, sizeof ops->pad);
1578     ops->rx_packets = htonll(stats.rx_packets);
1579     ops->tx_packets = htonll(stats.tx_packets);
1580     ops->rx_bytes = htonll(stats.rx_bytes);
1581     ops->tx_bytes = htonll(stats.tx_bytes);
1582     ops->rx_dropped = htonll(stats.rx_dropped);
1583     ops->tx_dropped = htonll(stats.tx_dropped);
1584     ops->rx_errors = htonll(stats.rx_errors);
1585     ops->tx_errors = htonll(stats.tx_errors);
1586     ops->rx_frame_err = htonll(stats.rx_frame_errors);
1587     ops->rx_over_err = htonll(stats.rx_over_errors);
1588     ops->rx_crc_err = htonll(stats.rx_crc_errors);
1589     ops->collisions = htonll(stats.collisions);
1590 }
1591
1592 static int
1593 handle_port_stats_request(struct ofproto *p, struct ofconn *ofconn,
1594                           struct ofp_stats_request *osr,
1595                           size_t arg_size)
1596 {
1597     struct ofp_port_stats_request *psr;
1598     struct ofp_port_stats *ops;
1599     struct ofpbuf *msg;
1600
1601     if (arg_size != sizeof *psr) {
1602         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1603     }
1604     psr = (struct ofp_port_stats_request *) osr->body;
1605
1606     msg = start_stats_reply(osr, sizeof *ops * 16);
1607     if (psr->port_no != htons(OFPP_NONE)) {
1608         struct wdp_port port;
1609
1610         if (!wdp_port_query_by_number(p->wdp, ntohs(psr->port_no), &port)) {
1611             append_port_stat(&port, ofconn, &msg);
1612             wdp_port_free(&port);
1613         }
1614     } else {
1615         struct wdp_port *ports;
1616         size_t n_ports;
1617         size_t i;
1618
1619         wdp_port_list(p->wdp, &ports, &n_ports);
1620         for (i = 0; i < n_ports; i++) {
1621             append_port_stat(&ports[i], ofconn, &msg);
1622         }
1623         wdp_port_array_free(ports, n_ports);
1624     }
1625
1626     queue_tx(msg, ofconn, ofconn->reply_counter);
1627     return 0;
1628 }
1629
1630 struct flow_stats_cbdata {
1631     struct ofproto *ofproto;
1632     struct ofconn *ofconn;
1633     uint16_t out_port;
1634     struct ofpbuf *msg;
1635 };
1636
1637 /* Obtains statistic counters for 'rule' within 'p' and stores them into
1638  * '*packet_countp' and '*byte_countp'.  If 'rule' is a wildcarded rule, the
1639  * returned statistic include statistics for all of 'rule''s subrules. */
1640 static void
1641 query_stats(struct ofproto *p, struct wdp_rule *rule,
1642             uint64_t *packet_countp, uint64_t *byte_countp)
1643 {
1644     struct wdp_flow_stats stats;
1645
1646     if (!wdp_flow_get_stats(p->wdp, rule, &stats)) {
1647         *packet_countp = stats.n_packets;
1648         *byte_countp = stats.n_bytes;
1649     } else {
1650         *packet_countp = 0;
1651         *byte_countp = 0;
1652     }
1653 }
1654
1655 static void
1656 flow_stats_cb(struct wdp_rule *rule, void *cbdata_)
1657 {
1658     struct flow_stats_cbdata *cbdata = cbdata_;
1659     struct ofp_flow_stats *ofs;
1660     uint64_t packet_count, byte_count;
1661     size_t act_len, len;
1662     long long int tdiff = time_msec() - rule->created;
1663     uint32_t sec = tdiff / 1000;
1664     uint32_t msec = tdiff - (sec * 1000);
1665
1666     if (rule_is_hidden(rule)
1667         || !rule_has_out_port(rule, cbdata->out_port)) {
1668         return;
1669     }
1670
1671     act_len = sizeof *rule->actions * rule->n_actions;
1672     len = offsetof(struct ofp_flow_stats, actions) + act_len;
1673
1674     query_stats(cbdata->ofproto, rule, &packet_count, &byte_count);
1675
1676     ofs = append_stats_reply(len, cbdata->ofconn, &cbdata->msg);
1677     ofs->length = htons(len);
1678     ofs->table_id = rule->ofp_table_id;
1679     ofs->pad = 0;
1680     flow_to_match(&rule->cr.flow, cbdata->ofproto->tun_id_from_cookie,
1681                   &ofs->match);
1682     ofs->duration_sec = htonl(sec);
1683     ofs->duration_nsec = htonl(msec * 1000000);
1684     ofs->cookie = ofproto_rule_cast(rule)->flow_cookie;
1685     ofs->priority = htons(rule->cr.flow.priority);
1686     ofs->idle_timeout = htons(rule->idle_timeout);
1687     ofs->hard_timeout = htons(rule->hard_timeout);
1688     memset(ofs->pad2, 0, sizeof ofs->pad2);
1689     ofs->packet_count = htonll(packet_count);
1690     ofs->byte_count = htonll(byte_count);
1691     memcpy(ofs->actions, rule->actions, act_len);
1692 }
1693
1694 static unsigned int
1695 table_id_to_include(uint8_t table_id)
1696 {
1697     return (table_id == 0xff ? UINT_MAX
1698             : table_id < 32 ? 1u << table_id
1699             : 0);
1700 }
1701
1702 static unsigned int
1703 flow_mod_table_id(const struct ofconn *ofconn, const struct ofp_flow_mod *ofm)
1704 {
1705     return ofconn->flow_mod_table_id ? ntohs(ofm->command) >> 8 : 0xff;
1706 }
1707
1708 static int
1709 handle_flow_stats_request(struct ofproto *p, struct ofconn *ofconn,
1710                           const struct ofp_stats_request *osr,
1711                           size_t arg_size)
1712 {
1713     struct ofp_flow_stats_request *fsr;
1714     struct flow_stats_cbdata cbdata;
1715     flow_t target;
1716
1717     if (arg_size != sizeof *fsr) {
1718         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1719     }
1720     fsr = (struct ofp_flow_stats_request *) osr->body;
1721
1722     COVERAGE_INC(ofproto_flows_req);
1723     cbdata.ofproto = p;
1724     cbdata.ofconn = ofconn;
1725     cbdata.out_port = fsr->out_port;
1726     cbdata.msg = start_stats_reply(osr, 1024);
1727     flow_from_match(&fsr->match, 0, false, 0, &target);
1728     wdp_flow_for_each_match(p->wdp, &target, 
1729                             table_id_to_include(fsr->table_id),
1730                             flow_stats_cb, &cbdata);
1731     queue_tx(cbdata.msg, ofconn, ofconn->reply_counter);
1732     return 0;
1733 }
1734
1735 struct flow_stats_ds_cbdata {
1736     struct ofproto *ofproto;
1737     struct ds *results;
1738 };
1739
1740 static void
1741 flow_stats_ds_cb(struct wdp_rule *rule, void *cbdata_)
1742 {
1743     struct flow_stats_ds_cbdata *cbdata = cbdata_;
1744     struct ds *results = cbdata->results;
1745     struct ofp_match match;
1746     uint64_t packet_count, byte_count;
1747     size_t act_len = sizeof *rule->actions * rule->n_actions;
1748
1749     query_stats(cbdata->ofproto, rule, &packet_count, &byte_count);
1750     flow_to_match(&rule->cr.flow, cbdata->ofproto->tun_id_from_cookie,
1751                   &match);
1752
1753     ds_put_format(results, "duration=%llds, ",
1754                   (time_msec() - rule->created) / 1000);
1755     ds_put_format(results, "priority=%u, ", rule->cr.flow.priority);
1756     ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
1757     ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
1758     ofp_print_match(results, &match, true);
1759     ofp_print_actions(results, &rule->actions->header, act_len);
1760     ds_put_cstr(results, "\n");
1761 }
1762
1763 /* Adds a pretty-printed description of all flows to 'results', including 
1764  * those marked hidden by secchan (e.g., by in-band control). */
1765 void
1766 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
1767 {
1768     struct flow_stats_ds_cbdata cbdata;
1769     struct ofp_match match;
1770     flow_t target;
1771
1772     memset(&match, 0, sizeof match);
1773     match.wildcards = htonl(OVSFW_ALL);
1774
1775     cbdata.ofproto = p;
1776     cbdata.results = results;
1777
1778     flow_from_match(&match, 0, false, 0, &target);
1779     wdp_flow_for_each_match(p->wdp, &target, UINT_MAX,
1780                             flow_stats_ds_cb, &cbdata);
1781 }
1782
1783 struct aggregate_stats_cbdata {
1784     struct ofproto *ofproto;
1785     uint16_t out_port;
1786     uint64_t packet_count;
1787     uint64_t byte_count;
1788     uint32_t n_flows;
1789 };
1790
1791 static void
1792 aggregate_stats_cb(struct wdp_rule *rule, void *cbdata_)
1793 {
1794     struct aggregate_stats_cbdata *cbdata = cbdata_;
1795     uint64_t packet_count, byte_count;
1796
1797     if (rule_is_hidden(rule) || !rule_has_out_port(rule, cbdata->out_port)) {
1798         return;
1799     }
1800
1801     query_stats(cbdata->ofproto, rule, &packet_count, &byte_count);
1802
1803     cbdata->packet_count += packet_count;
1804     cbdata->byte_count += byte_count;
1805     cbdata->n_flows++;
1806 }
1807
1808 static int
1809 handle_aggregate_stats_request(struct ofproto *p, struct ofconn *ofconn,
1810                                const struct ofp_stats_request *osr,
1811                                size_t arg_size)
1812 {
1813     struct ofp_aggregate_stats_request *asr;
1814     struct ofp_aggregate_stats_reply *reply;
1815     struct aggregate_stats_cbdata cbdata;
1816     struct ofpbuf *msg;
1817     flow_t target;
1818
1819     if (arg_size != sizeof *asr) {
1820         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1821     }
1822     asr = (struct ofp_aggregate_stats_request *) osr->body;
1823
1824     COVERAGE_INC(ofproto_agg_request);
1825     cbdata.ofproto = p;
1826     cbdata.out_port = asr->out_port;
1827     cbdata.packet_count = 0;
1828     cbdata.byte_count = 0;
1829     cbdata.n_flows = 0;
1830     flow_from_match(&asr->match, 0, false, 0, &target);
1831     wdp_flow_for_each_match(p->wdp, &target,
1832                             table_id_to_include(asr->table_id),
1833                             aggregate_stats_cb, &cbdata);
1834
1835     msg = start_stats_reply(osr, sizeof *reply);
1836     reply = append_stats_reply(sizeof *reply, ofconn, &msg);
1837     reply->flow_count = htonl(cbdata.n_flows);
1838     reply->packet_count = htonll(cbdata.packet_count);
1839     reply->byte_count = htonll(cbdata.byte_count);
1840     queue_tx(msg, ofconn, ofconn->reply_counter);
1841     return 0;
1842 }
1843
1844 struct queue_stats_cbdata {
1845     struct ofconn *ofconn;
1846     struct ofpbuf *msg;
1847     uint16_t port_no;
1848 };
1849
1850 static void
1851 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
1852                 const struct netdev_queue_stats *stats)
1853 {
1854     struct ofp_queue_stats *reply;
1855
1856     reply = append_stats_reply(sizeof *reply, cbdata->ofconn, &cbdata->msg);
1857     reply->port_no = htons(cbdata->port_no);
1858     memset(reply->pad, 0, sizeof reply->pad);
1859     reply->queue_id = htonl(queue_id);
1860     reply->tx_bytes = htonll(stats->tx_bytes);
1861     reply->tx_packets = htonll(stats->tx_packets);
1862     reply->tx_errors = htonll(stats->tx_errors);
1863 }
1864
1865 static void
1866 handle_queue_stats_dump_cb(uint32_t queue_id,
1867                            struct netdev_queue_stats *stats,
1868                            void *cbdata_)
1869 {
1870     struct queue_stats_cbdata *cbdata = cbdata_;
1871
1872     put_queue_stats(cbdata, queue_id, stats);
1873 }
1874
1875 static void
1876 handle_queue_stats_for_port(struct wdp_port *port, uint32_t queue_id,
1877                             struct queue_stats_cbdata *cbdata)
1878 {
1879     cbdata->port_no = port->opp.port_no;
1880     if (queue_id == OFPQ_ALL) {
1881         netdev_dump_queue_stats(port->netdev,
1882                                 handle_queue_stats_dump_cb, cbdata);
1883     } else {
1884         struct netdev_queue_stats stats;
1885
1886         netdev_get_queue_stats(port->netdev, queue_id, &stats);
1887         put_queue_stats(cbdata, queue_id, &stats);
1888     }
1889 }
1890
1891 static int
1892 handle_queue_stats_request(struct ofproto *ofproto, struct ofconn *ofconn,
1893                            const struct ofp_stats_request *osr,
1894                            size_t arg_size)
1895 {
1896     struct ofp_queue_stats_request *qsr;
1897     struct queue_stats_cbdata cbdata;
1898     unsigned int port_no;
1899     uint32_t queue_id;
1900
1901     if (arg_size != sizeof *qsr) {
1902         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1903     }
1904     qsr = (struct ofp_queue_stats_request *) osr->body;
1905
1906     COVERAGE_INC(ofproto_queue_req);
1907
1908     cbdata.ofconn = ofconn;
1909     cbdata.msg = start_stats_reply(osr, 128);
1910
1911     port_no = ntohs(qsr->port_no);
1912     queue_id = ntohl(qsr->queue_id);
1913     if (port_no == OFPP_ALL) {
1914         struct wdp_port *ports;
1915         size_t n_ports, i;
1916
1917         wdp_port_list(ofproto->wdp, &ports, &n_ports);
1918         /* XXX deal with wdp_port_list() errors */
1919         for (i = 0; i < n_ports; i++) {
1920             handle_queue_stats_for_port(&ports[i], queue_id, &cbdata);
1921         }
1922         wdp_port_array_free(ports, n_ports);
1923     } else if (port_no < ofproto->max_ports) {
1924         struct wdp_port port;
1925         int error;
1926
1927         error = wdp_port_query_by_number(ofproto->wdp, port_no, &port);
1928         if (!error) {
1929             handle_queue_stats_for_port(&port, queue_id, &cbdata);
1930         } else {
1931             /* XXX deal with wdp_port_query_by_number() errors */
1932         }
1933         wdp_port_free(&port);
1934     } else {
1935         ofpbuf_delete(cbdata.msg);
1936         return ofp_mkerr(OFPET_QUEUE_OP_FAILED, OFPQOFC_BAD_PORT);
1937     }
1938     queue_tx(cbdata.msg, ofconn, ofconn->reply_counter);
1939
1940     return 0;
1941 }
1942
1943 static int
1944 handle_stats_request(struct ofproto *p, struct ofconn *ofconn,
1945                      struct ofp_header *oh)
1946 {
1947     struct ofp_stats_request *osr;
1948     size_t arg_size;
1949     int error;
1950
1951     error = check_ofp_message_array(oh, OFPT_STATS_REQUEST, sizeof *osr,
1952                                     1, &arg_size);
1953     if (error) {
1954         return error;
1955     }
1956     osr = (struct ofp_stats_request *) oh;
1957
1958     switch (ntohs(osr->type)) {
1959     case OFPST_DESC:
1960         return handle_desc_stats_request(p, ofconn, osr);
1961
1962     case OFPST_FLOW:
1963         return handle_flow_stats_request(p, ofconn, osr, arg_size);
1964
1965     case OFPST_AGGREGATE:
1966         return handle_aggregate_stats_request(p, ofconn, osr, arg_size);
1967
1968     case OFPST_TABLE:
1969         return handle_table_stats_request(p, ofconn, osr);
1970
1971     case OFPST_PORT:
1972         return handle_port_stats_request(p, ofconn, osr, arg_size);
1973
1974     case OFPST_QUEUE:
1975         return handle_queue_stats_request(p, ofconn, osr, arg_size);
1976
1977     case OFPST_VENDOR:
1978         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_VENDOR);
1979
1980     default:
1981         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT);
1982     }
1983 }
1984
1985 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
1986  * in which no matching flow already exists in the flow table.
1987  *
1988  * Adds the flow specified by 'ofm', which is followed by 'n_actions'
1989  * ofp_actions, to 'p''s flow table.  Returns 0 on success or an OpenFlow error
1990  * code as encoded by ofp_mkerr() on failure.
1991  *
1992  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
1993  * if any. */
1994 static int
1995 add_flow(struct ofproto *p, struct ofconn *ofconn,
1996          const struct ofp_flow_mod *ofm, size_t n_actions)
1997 {
1998     struct wdp_rule *rule;
1999     struct wdp_flow_put put;
2000     struct ofpbuf *packet;
2001     uint16_t in_port;
2002     flow_t flow;
2003     int error;
2004
2005     flow_from_match(&ofm->match, ntohs(ofm->priority), p->tun_id_from_cookie,
2006                     ofm->cookie, &flow);
2007     if (ofm->flags & htons(OFPFF_CHECK_OVERLAP)
2008         && wdp_flow_overlaps(p->wdp, &flow)) {
2009         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_OVERLAP);
2010     }
2011
2012     put.flags = WDP_PUT_CREATE | WDP_PUT_MODIFY | WDP_PUT_ALL;
2013     put.flow = &flow;
2014     put.actions = (const union ofp_action *) ofm->actions;
2015     put.n_actions = n_actions;
2016     put.idle_timeout = ntohs(ofm->idle_timeout);
2017     put.hard_timeout = ntohs(ofm->hard_timeout);
2018     put.ofp_table_id = flow_mod_table_id(ofconn, ofm);
2019     error = wdp_flow_put(p->wdp, &put, NULL, &rule);
2020     if (error) {
2021         /* XXX wdp_flow_put should return OpenFlow error code. */
2022         return error;
2023     }
2024     ofproto_rule_init(rule);
2025
2026     if (ofm->buffer_id != htonl(UINT32_MAX)) {
2027         error = pktbuf_retrieve(ofconn->pktbuf, ntohl(ofm->buffer_id),
2028                                 &packet, &in_port);
2029         if (!error) {
2030             wdp_flow_inject(p->wdp, rule, in_port, packet);
2031             ofpbuf_delete(packet);
2032         }
2033     }
2034
2035     return 0;
2036 }
2037
2038 static struct wdp_rule *
2039 find_flow_strict(struct ofproto *p, const struct ofconn *ofconn,
2040                  const struct ofp_flow_mod *ofm)
2041 {
2042     uint8_t table_id;
2043     flow_t flow;
2044
2045     flow_from_match(&ofm->match, ntohs(ofm->priority),
2046                     p->tun_id_from_cookie, ofm->cookie, &flow);
2047     table_id = flow_mod_table_id(ofconn, ofm);
2048     return wdp_flow_get(p->wdp, &flow, table_id_to_include(table_id));
2049 }
2050
2051 static int
2052 send_buffered_packet(struct ofproto *ofproto, struct ofconn *ofconn,
2053                      struct wdp_rule *rule, const struct ofp_flow_mod *ofm)
2054 {
2055     struct ofpbuf *packet;
2056     uint16_t in_port;
2057     int error;
2058
2059     if (ofm->buffer_id == htonl(UINT32_MAX)) {
2060         return 0;
2061     }
2062
2063     error = pktbuf_retrieve(ofconn->pktbuf, ntohl(ofm->buffer_id),
2064                             &packet, &in_port);
2065     if (error) {
2066         return error;
2067     }
2068
2069     wdp_flow_inject(ofproto->wdp, rule, in_port, packet);
2070     ofpbuf_delete(packet);
2071
2072     return 0;
2073 }
2074 \f
2075 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
2076
2077 struct modify_flows_cbdata {
2078     struct ofproto *ofproto;
2079     const struct ofp_flow_mod *ofm;
2080     size_t n_actions;
2081     struct wdp_rule *match;
2082 };
2083
2084 static int modify_flow(struct ofproto *, const struct ofp_flow_mod *,
2085                        size_t n_actions, struct wdp_rule *);
2086 static void modify_flows_cb(struct wdp_rule *, void *cbdata_);
2087
2088 /* Implements OFPFC_ADD and OFPFC_MODIFY.  Returns 0 on success or an OpenFlow
2089  * error code as encoded by ofp_mkerr() on failure.
2090  *
2091  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
2092  * if any. */
2093 static int
2094 modify_flows_loose(struct ofproto *p, struct ofconn *ofconn,
2095                    const struct ofp_flow_mod *ofm, size_t n_actions)
2096 {
2097     struct modify_flows_cbdata cbdata;
2098     uint8_t table_id;
2099     flow_t target;
2100
2101     cbdata.ofproto = p;
2102     cbdata.ofm = ofm;
2103     cbdata.n_actions = n_actions;
2104     cbdata.match = NULL;
2105
2106     flow_from_match(&ofm->match, 0, p->tun_id_from_cookie, ofm->cookie,
2107                     &target);
2108
2109     table_id = flow_mod_table_id(ofconn, ofm);
2110     wdp_flow_for_each_match(p->wdp, &target, table_id_to_include(table_id),
2111                             modify_flows_cb, &cbdata);
2112     if (cbdata.match) {
2113         /* This credits the packet to whichever flow happened to match last.
2114          * That's weird.  Maybe we should do a lookup for the flow that
2115          * actually matches the packet?  Who knows. */
2116         send_buffered_packet(p, ofconn, cbdata.match, ofm);
2117         return 0;
2118     } else {
2119         return add_flow(p, ofconn, ofm, n_actions);
2120     }
2121 }
2122
2123 /* Implements OFPFC_MODIFY_STRICT.  Returns 0 on success or an OpenFlow error
2124  * code as encoded by ofp_mkerr() on failure.
2125  *
2126  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
2127  * if any. */
2128 static int
2129 modify_flow_strict(struct ofproto *p, struct ofconn *ofconn,
2130                    struct ofp_flow_mod *ofm, size_t n_actions)
2131 {
2132     struct wdp_rule *rule = find_flow_strict(p, ofconn, ofm);
2133     if (rule && !rule_is_hidden(rule)) {
2134         modify_flow(p, ofm, n_actions, rule);
2135         return send_buffered_packet(p, ofconn, rule, ofm);
2136     } else {
2137         return add_flow(p, ofconn, ofm, n_actions);
2138     }
2139 }
2140
2141 /* Callback for modify_flows_loose(). */
2142 static void
2143 modify_flows_cb(struct wdp_rule *rule, void *cbdata_)
2144 {
2145     struct modify_flows_cbdata *cbdata = cbdata_;
2146
2147     if (!rule_is_hidden(rule)) {
2148         cbdata->match = rule;
2149         modify_flow(cbdata->ofproto, cbdata->ofm, cbdata->n_actions, rule);
2150     }
2151 }
2152
2153 /* Implements core of OFPFC_MODIFY and OFPFC_MODIFY_STRICT where 'rule' has
2154  * been identified as a flow in 'p''s flow table to be modified, by changing
2155  * the rule's actions to match those in 'ofm' (which is followed by 'n_actions'
2156  * ofp_action[] structures). */
2157 static int
2158 modify_flow(struct ofproto *p, const struct ofp_flow_mod *ofm,
2159             size_t n_actions, struct wdp_rule *rule)
2160 {
2161     const struct ofp_action_header *actions = ofm->actions;
2162     struct ofproto_rule *ofproto_rule = ofproto_rule_cast(rule);
2163     struct wdp_flow_put put;
2164
2165     ofproto_rule->flow_cookie = ofm->cookie;
2166
2167     /* If the actions are the same, do nothing. */
2168     if (n_actions == rule->n_actions
2169         && !memcmp(ofm->actions, rule->actions, sizeof *actions * n_actions))
2170     {
2171         return 0;
2172     }
2173
2174     put.flags = WDP_PUT_MODIFY | WDP_PUT_ACTIONS;
2175     put.flow = &rule->cr.flow;
2176     put.actions = (const union ofp_action *) actions;
2177     put.n_actions = n_actions;
2178     put.idle_timeout = put.hard_timeout = 0;
2179     put.ofp_table_id = rule->ofp_table_id;
2180     return wdp_flow_put(p->wdp, &put, NULL, NULL);
2181 }
2182 \f
2183 /* OFPFC_DELETE implementation. */
2184
2185 struct delete_flows_cbdata {
2186     struct ofproto *ofproto;
2187     uint16_t out_port;
2188 };
2189
2190 static void delete_flows_cb(struct wdp_rule *, void *cbdata_);
2191 static void delete_flow_core(struct ofproto *, struct wdp_rule *,
2192                              uint16_t out_port);
2193
2194 /* Implements OFPFC_DELETE. */
2195 static void
2196 delete_flows_loose(struct ofproto *p, const struct ofconn *ofconn,
2197                    const struct ofp_flow_mod *ofm)
2198 {
2199     struct delete_flows_cbdata cbdata;
2200     uint8_t table_id;
2201     flow_t target;
2202
2203     cbdata.ofproto = p;
2204     cbdata.out_port = ofm->out_port;
2205
2206     flow_from_match(&ofm->match, 0, p->tun_id_from_cookie, ofm->cookie,
2207                     &target);
2208     table_id = flow_mod_table_id(ofconn, ofm);
2209
2210     wdp_flow_for_each_match(p->wdp, &target, table_id_to_include(table_id),
2211                             delete_flows_cb, &cbdata);
2212 }
2213
2214 /* Implements OFPFC_DELETE_STRICT. */
2215 static void
2216 delete_flow_strict(struct ofproto *p, const struct ofconn *ofconn,
2217                    struct ofp_flow_mod *ofm)
2218 {
2219     struct wdp_rule *rule = find_flow_strict(p, ofconn, ofm);
2220     if (rule) {
2221         delete_flow_core(p, rule, ofm->out_port);
2222     }
2223 }
2224
2225 /* Callback for delete_flows_loose(). */
2226 static void
2227 delete_flows_cb(struct wdp_rule *rule, void *cbdata_)
2228 {
2229     struct delete_flows_cbdata *cbdata = cbdata_;
2230
2231     delete_flow_core(cbdata->ofproto, rule, cbdata->out_port);
2232 }
2233
2234 /* Implements core of OFPFC_DELETE and OFPFC_DELETE_STRICT where 'rule' has
2235  * been identified as a flow to delete from 'p''s flow table, by deleting the
2236  * flow and sending out a OFPT_FLOW_REMOVED message to any interested
2237  * controller.
2238  *
2239  * Will not delete 'rule' if it is hidden.  Will delete 'rule' only if
2240  * 'out_port' is htons(OFPP_NONE) or if 'rule' actually outputs to the
2241  * specified 'out_port'. */
2242 static void
2243 delete_flow_core(struct ofproto *p, struct wdp_rule *rule, uint16_t out_port)
2244 {
2245     if (rule_is_hidden(rule)) {
2246         return;
2247     }
2248
2249     if (out_port != htons(OFPP_NONE) && !rule_has_out_port(rule, out_port)) {
2250         return;
2251     }
2252
2253     delete_flow(p, rule, OFPRR_DELETE);
2254 }
2255 \f
2256 static int
2257 handle_flow_mod(struct ofproto *p, struct ofconn *ofconn,
2258                 struct ofp_flow_mod *ofm)
2259 {
2260     struct ofp_match orig_match;
2261     size_t n_actions;
2262     int error;
2263
2264     error = reject_slave_controller(ofconn, &ofm->header);
2265     if (error) {
2266         return error;
2267     }
2268     error = check_ofp_message_array(&ofm->header, OFPT_FLOW_MOD, sizeof *ofm,
2269                                     sizeof *ofm->actions, &n_actions);
2270     if (error) {
2271         return error;
2272     }
2273
2274     /* We do not support the emergency flow cache.  It will hopefully
2275      * get dropped from OpenFlow in the near future. */
2276     if (ofm->flags & htons(OFPFF_EMERG)) {
2277         /* There isn't a good fit for an error code, so just state that the
2278          * flow table is full. */
2279         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_ALL_TABLES_FULL);
2280     }
2281
2282     /* Normalize ofp->match.  If normalization actually changes anything, then
2283      * log the differences. */
2284     ofm->match.pad1[0] = ofm->match.pad2[0] = 0;
2285     orig_match = ofm->match;
2286     normalize_match(&ofm->match);
2287     if (memcmp(&ofm->match, &orig_match, sizeof orig_match)) {
2288         static struct vlog_rate_limit normal_rl = VLOG_RATE_LIMIT_INIT(1, 1);
2289         if (!VLOG_DROP_INFO(&normal_rl)) {
2290             char *old = ofp_match_to_literal_string(&orig_match);
2291             char *new = ofp_match_to_literal_string(&ofm->match);
2292             VLOG_INFO("%s: normalization changed ofp_match, details:",
2293                       rconn_get_name(ofconn->rconn));
2294             VLOG_INFO(" pre: %s", old);
2295             VLOG_INFO("post: %s", new);
2296             free(old);
2297             free(new);
2298         }
2299     }
2300
2301     if (!ofm->match.wildcards) {
2302         ofm->priority = htons(UINT16_MAX);
2303     }
2304
2305     error = validate_actions((const union ofp_action *) ofm->actions,
2306                              n_actions, p->max_ports);
2307     if (error) {
2308         return error;
2309     }
2310
2311     if (!ofconn->flow_mod_table_id && ofm->command & htons(0xff00)) {
2312         static struct vlog_rate_limit table_id_rl = VLOG_RATE_LIMIT_INIT(1, 1);
2313         VLOG_WARN_RL(&table_id_rl, "%s: flow_mod table_id feature must be "
2314                      "enabled with NXT_FLOW_MOD_TABLE_ID",
2315                      rconn_get_name(ofconn->rconn));
2316         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_BAD_COMMAND);
2317     }
2318
2319     switch (ntohs(ofm->command) & 0xff) {
2320     case OFPFC_ADD:
2321         return modify_flows_loose(p, ofconn, ofm, n_actions);
2322
2323     case OFPFC_MODIFY:
2324         return modify_flow_strict(p, ofconn, ofm, n_actions);
2325
2326     case OFPFC_MODIFY_STRICT:
2327         return modify_flow_strict(p, ofconn, ofm, n_actions);
2328
2329     case OFPFC_DELETE:
2330         delete_flows_loose(p, ofconn, ofm);
2331         return 0;
2332
2333     case OFPFC_DELETE_STRICT:
2334         delete_flow_strict(p, ofconn, ofm);
2335         return 0;
2336
2337     default:
2338         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_BAD_COMMAND);
2339     }
2340 }
2341
2342 static int
2343 handle_tun_id_from_cookie(struct ofproto *p, struct nxt_tun_id_cookie *msg)
2344 {
2345     int error;
2346
2347     error = check_ofp_message(&msg->header, OFPT_VENDOR, sizeof *msg);
2348     if (error) {
2349         return error;
2350     }
2351
2352     p->tun_id_from_cookie = !!msg->set;
2353     return 0;
2354 }
2355
2356 static int
2357 handle_flow_mod_table_id(struct ofconn *ofconn,
2358                          struct nxt_flow_mod_table_id *msg)
2359 {
2360     int error;
2361
2362     error = check_ofp_message(&msg->header, OFPT_VENDOR, sizeof *msg);
2363     if (error) {
2364         return error;
2365     }
2366
2367     ofconn->flow_mod_table_id = !!msg->set;
2368     return 0;
2369 }
2370
2371 static int
2372 handle_role_request(struct ofproto *ofproto,
2373                     struct ofconn *ofconn, struct nicira_header *msg)
2374 {
2375     struct nx_role_request *nrr;
2376     struct nx_role_request *reply;
2377     struct ofpbuf *buf;
2378     uint32_t role;
2379
2380     if (ntohs(msg->header.length) != sizeof *nrr) {
2381         VLOG_WARN_RL(&rl, "received role request of length %u (expected %zu)",
2382                      ntohs(msg->header.length), sizeof *nrr);
2383         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
2384     }
2385     nrr = (struct nx_role_request *) msg;
2386
2387     if (ofconn->type != OFCONN_CONTROLLER) {
2388         VLOG_WARN_RL(&rl, "ignoring role request on non-controller "
2389                      "connection");
2390         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
2391     }
2392
2393     role = ntohl(nrr->role);
2394     if (role != NX_ROLE_OTHER && role != NX_ROLE_MASTER
2395         && role != NX_ROLE_SLAVE) {
2396         VLOG_WARN_RL(&rl, "received request for unknown role %"PRIu32, role);
2397
2398         /* There's no good error code for this. */
2399         return ofp_mkerr(OFPET_BAD_REQUEST, -1);
2400     }
2401
2402     if (role == NX_ROLE_MASTER) {
2403         struct ofconn *other;
2404
2405         HMAP_FOR_EACH (other, struct ofconn, hmap_node,
2406                        &ofproto->controllers) {
2407             if (other->role == NX_ROLE_MASTER) {
2408                 other->role = NX_ROLE_SLAVE;
2409             }
2410         }
2411     }
2412     ofconn->role = role;
2413
2414     reply = make_openflow_xid(sizeof *reply, OFPT_VENDOR, msg->header.xid,
2415                               &buf);
2416     reply->nxh.vendor = htonl(NX_VENDOR_ID);
2417     reply->nxh.subtype = htonl(NXT_ROLE_REPLY);
2418     reply->role = htonl(role);
2419     queue_tx(buf, ofconn, ofconn->reply_counter);
2420
2421     return 0;
2422 }
2423
2424 static int
2425 handle_vendor(struct ofproto *p, struct ofconn *ofconn, void *msg)
2426 {
2427     struct ofp_vendor_header *ovh = msg;
2428     struct nicira_header *nh;
2429
2430     if (ntohs(ovh->header.length) < sizeof(struct ofp_vendor_header)) {
2431         VLOG_WARN_RL(&rl, "received vendor message of length %u "
2432                           "(expected at least %zu)",
2433                    ntohs(ovh->header.length), sizeof(struct ofp_vendor_header));
2434         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
2435     }
2436     if (ovh->vendor != htonl(NX_VENDOR_ID)) {
2437         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_VENDOR);
2438     }
2439     if (ntohs(ovh->header.length) < sizeof(struct nicira_header)) {
2440         VLOG_WARN_RL(&rl, "received Nicira vendor message of length %u "
2441                           "(expected at least %zu)",
2442                      ntohs(ovh->header.length), sizeof(struct nicira_header));
2443         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
2444     }
2445
2446     nh = msg;
2447     switch (ntohl(nh->subtype)) {
2448     case NXT_STATUS_REQUEST:
2449         return switch_status_handle_request(p->switch_status, ofconn->rconn,
2450                                             msg);
2451
2452     case NXT_TUN_ID_FROM_COOKIE:
2453         return handle_tun_id_from_cookie(p, msg);
2454
2455     case NXT_FLOW_MOD_TABLE_ID:
2456         return handle_flow_mod_table_id(ofconn, msg);
2457
2458     case NXT_ROLE_REQUEST:
2459         return handle_role_request(p, ofconn, msg);
2460     }
2461
2462     return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE);
2463 }
2464
2465 static int
2466 handle_barrier_request(struct ofconn *ofconn, struct ofp_header *oh)
2467 {
2468     struct ofp_header *ob;
2469     struct ofpbuf *buf;
2470
2471     /* Currently, everything executes synchronously, so we can just
2472      * immediately send the barrier reply. */
2473     ob = make_openflow_xid(sizeof *ob, OFPT_BARRIER_REPLY, oh->xid, &buf);
2474     queue_tx(buf, ofconn, ofconn->reply_counter);
2475     return 0;
2476 }
2477
2478 static void
2479 handle_openflow(struct ofconn *ofconn, struct ofproto *p,
2480                 struct ofpbuf *ofp_msg)
2481 {
2482     struct ofp_header *oh = ofp_msg->data;
2483     int error;
2484
2485     COVERAGE_INC(ofproto_recv_openflow);
2486     switch (oh->type) {
2487     case OFPT_ECHO_REQUEST:
2488         error = handle_echo_request(ofconn, oh);
2489         break;
2490
2491     case OFPT_ECHO_REPLY:
2492         error = 0;
2493         break;
2494
2495     case OFPT_FEATURES_REQUEST:
2496         error = handle_features_request(p, ofconn, oh);
2497         break;
2498
2499     case OFPT_GET_CONFIG_REQUEST:
2500         error = handle_get_config_request(p, ofconn, oh);
2501         break;
2502
2503     case OFPT_SET_CONFIG:
2504         error = handle_set_config(p, ofconn, ofp_msg->data);
2505         break;
2506
2507     case OFPT_PACKET_OUT:
2508         error = handle_packet_out(p, ofconn, ofp_msg->data);
2509         break;
2510
2511     case OFPT_PORT_MOD:
2512         error = handle_port_mod(p, ofconn, oh);
2513         break;
2514
2515     case OFPT_FLOW_MOD:
2516         error = handle_flow_mod(p, ofconn, ofp_msg->data);
2517         break;
2518
2519     case OFPT_STATS_REQUEST:
2520         error = handle_stats_request(p, ofconn, oh);
2521         break;
2522
2523     case OFPT_VENDOR:
2524         error = handle_vendor(p, ofconn, ofp_msg->data);
2525         break;
2526
2527     case OFPT_BARRIER_REQUEST:
2528         error = handle_barrier_request(ofconn, oh);
2529         break;
2530
2531     default:
2532         if (VLOG_IS_WARN_ENABLED()) {
2533             char *s = ofp_to_string(oh, ntohs(oh->length), 2);
2534             VLOG_DBG_RL(&rl, "OpenFlow message ignored: %s", s);
2535             free(s);
2536         }
2537         error = ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
2538         break;
2539     }
2540
2541     if (error) {
2542         send_error_oh(ofconn, ofp_msg->data, error);
2543     }
2544 }
2545 \f
2546 static void
2547 handle_flow_miss(struct ofproto *p, struct wdp_packet *packet)
2548 {
2549     struct wdp_rule *rule;
2550     flow_t flow;
2551
2552     flow_extract(packet->payload, packet->tun_id, packet->in_port, &flow);
2553     rule = wdp_flow_match(p->wdp, &flow);
2554     if (!rule) {
2555         /* Don't send a packet-in if OFPPC_NO_PACKET_IN asserted. */
2556         struct wdp_port port;
2557
2558         if (!wdp_port_query_by_number(p->wdp, packet->in_port, &port)) {
2559             bool no_packet_in = (port.opp.config & OFPPC_NO_PACKET_IN) != 0;
2560             wdp_port_free(&port);
2561             if (no_packet_in) {
2562                 COVERAGE_INC(ofproto_no_packet_in);
2563                 wdp_packet_destroy(packet);
2564                 return;
2565             }
2566         } else {
2567             VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16,
2568                          packet->in_port);
2569         }
2570
2571         COVERAGE_INC(ofproto_packet_in);
2572         send_packet_in(p, packet);
2573         return;
2574     }
2575
2576     wdp_flow_inject(p->wdp, rule, packet->in_port, packet->payload);
2577
2578     if (rule->cr.flow.priority == FAIL_OPEN_PRIORITY) {
2579         /*
2580          * Extra-special case for fail-open mode.
2581          *
2582          * We are in fail-open mode and the packet matched the fail-open rule,
2583          * but we are connected to a controller too.  We should send the packet
2584          * up to the controller in the hope that it will try to set up a flow
2585          * and thereby allow us to exit fail-open.
2586          *
2587          * See the top-level comment in fail-open.c for more information.
2588          */
2589         send_packet_in(p, packet);
2590     } else {
2591         wdp_packet_destroy(packet);
2592     }
2593 }
2594
2595 static void
2596 handle_wdp_packet(struct ofproto *p, struct wdp_packet *packet)
2597 {
2598     switch (packet->channel) {
2599     case WDP_CHAN_ACTION:
2600         COVERAGE_INC(ofproto_ctlr_action);
2601         send_packet_in(p, packet);
2602         break;
2603
2604     case WDP_CHAN_SFLOW:
2605         /* XXX */
2606         wdp_packet_destroy(packet);
2607         break;
2608
2609     case WDP_CHAN_MISS:
2610         handle_flow_miss(p, packet);
2611         break;
2612
2613     case WDP_N_CHANS:
2614     default:
2615         wdp_packet_destroy(packet);
2616         VLOG_WARN_RL(&rl, "received message on unexpected channel %d",
2617                      (int) packet->channel);
2618         break;
2619     }
2620 }
2621 \f
2622 static struct ofpbuf *
2623 compose_flow_removed(struct ofproto *p, const struct wdp_rule *rule,
2624                      uint8_t reason)
2625 {
2626     long long int tdiff = time_msec() - rule->created;
2627     uint32_t sec = tdiff / 1000;
2628     uint32_t msec = tdiff - (sec * 1000);
2629     struct ofp_flow_removed *ofr;
2630     struct ofpbuf *buf;
2631
2632     ofr = make_openflow(sizeof *ofr, OFPT_FLOW_REMOVED, &buf);
2633     flow_to_match(&rule->cr.flow, p->tun_id_from_cookie, &ofr->match);
2634     ofr->cookie = ofproto_rule_cast(rule)->flow_cookie;
2635     ofr->priority = htons(rule->cr.flow.priority);
2636     ofr->reason = reason;
2637     ofr->duration_sec = htonl(sec);
2638     ofr->duration_nsec = htonl(msec * 1000000);
2639     ofr->idle_timeout = htons(rule->idle_timeout);
2640
2641     return buf;
2642 }
2643
2644 static void
2645 delete_flow(struct ofproto *p, struct wdp_rule *rule, uint8_t reason)
2646 {
2647     /* We limit the maximum number of queued flow expirations it by accounting
2648      * them under the counter for replies.  That works because preventing
2649      * OpenFlow requests from being processed also prevents new flows from
2650      * being added (and expiring).  (It also prevents processing OpenFlow
2651      * requests that would not add new flows, so it is imperfect.) */
2652
2653     struct ofproto_rule *ofproto_rule = ofproto_rule_cast(rule);
2654     struct wdp_flow_stats stats;
2655     struct ofpbuf *buf;
2656
2657     if (ofproto_rule->send_flow_removed) {
2658         /* Compose most of the ofp_flow_removed before 'rule' is destroyed. */
2659         buf = compose_flow_removed(p, rule, reason);
2660     } else {
2661         buf = NULL;
2662     }
2663
2664     if (wdp_flow_delete(p->wdp, rule, &stats)) {
2665         return;
2666     }
2667
2668     if (buf) {
2669         struct ofp_flow_removed *ofr;
2670         struct ofconn *prev = NULL;
2671         struct ofconn *ofconn;
2672
2673         /* Compose the parts of the ofp_flow_removed that require stats. */
2674         ofr = buf->data;
2675         ofr->packet_count = htonll(stats.n_packets);
2676         ofr->byte_count = htonll(stats.n_bytes);
2677
2678         LIST_FOR_EACH (ofconn, struct ofconn, node, &p->all_conns) {
2679             if (rconn_is_connected(ofconn->rconn)) {
2680                 if (prev) {
2681                     queue_tx(ofpbuf_clone(buf), prev, prev->reply_counter);
2682                 }
2683                 prev = ofconn;
2684             }
2685         }
2686         if (prev) {
2687             queue_tx(buf, prev, prev->reply_counter);
2688         } else {
2689             ofpbuf_delete(buf);
2690         }
2691     }
2692     free(ofproto_rule);
2693 }
2694
2695 /* pinsched callback for sending 'packet' on 'ofconn'. */
2696 static void
2697 do_send_packet_in(struct wdp_packet *packet, void *ofconn_)
2698 {
2699     struct ofconn *ofconn = ofconn_;
2700
2701     rconn_send_with_limit(ofconn->rconn, packet->payload,
2702                           ofconn->packet_in_counter, 100);
2703     packet->payload = NULL;
2704     wdp_packet_destroy(packet);
2705 }
2706
2707 /* Takes 'packet', which has been converted with do_convert_to_packet_in(), and
2708  * finalizes its content for sending on 'ofconn', and passes it to 'ofconn''s
2709  * packet scheduler for sending.
2710  *
2711  * 'max_len' specifies the maximum number of bytes of the packet to send on
2712  * 'ofconn' (INT_MAX specifies no limit).
2713  *
2714  * If 'clone' is true, the caller retains ownership of 'packet'.  Otherwise,
2715  * ownership is transferred to this function. */
2716 static void
2717 schedule_packet_in(struct ofconn *ofconn, struct wdp_packet *packet,
2718                    int max_len, bool clone)
2719 {
2720     struct ofproto *ofproto = ofconn->ofproto;
2721     struct ofp_packet_in *opi = packet->payload->data;
2722     int send_len, trim_size;
2723     uint32_t buffer_id;
2724
2725     /* Get buffer. */
2726     if (opi->reason == OFPR_ACTION) {
2727         buffer_id = UINT32_MAX;
2728     } else if (ofproto->fail_open && fail_open_is_active(ofproto->fail_open)) {
2729         buffer_id = pktbuf_get_null();
2730     } else if (!ofconn->pktbuf) {
2731         buffer_id = UINT32_MAX;
2732     } else {
2733         struct ofpbuf payload;
2734         payload.data = opi->data;
2735         payload.size = (packet->payload->size
2736                         - offsetof(struct ofp_packet_in, data));
2737         buffer_id = pktbuf_save(ofconn->pktbuf, &payload, packet->in_port);
2738     }
2739
2740     /* Figure out how much of the packet to send. */
2741     send_len = ntohs(opi->total_len);
2742     if (buffer_id != UINT32_MAX) {
2743         send_len = MIN(send_len, ofconn->miss_send_len);
2744     }
2745     send_len = MIN(send_len, max_len);
2746
2747     /* Adjust packet length and clone if necessary. */
2748     trim_size = offsetof(struct ofp_packet_in, data) + send_len;
2749     if (clone) {
2750         packet = wdp_packet_clone(packet, trim_size);
2751         opi = packet->payload->data;
2752     } else {
2753         packet->payload->size = trim_size;
2754     }
2755
2756     /* Update packet headers. */
2757     opi->buffer_id = htonl(buffer_id);
2758     update_openflow_length(packet->payload);
2759
2760     /* Hand over to packet scheduler.  It might immediately call into
2761      * do_send_packet_in() or it might buffer it for a while (until a later
2762      * call to pinsched_run()). */
2763     pinsched_send(ofconn->schedulers[opi->reason], packet->in_port,
2764                   packet, do_send_packet_in, ofconn);
2765 }
2766
2767 /* Converts 'packet->payload' to a struct ofp_packet_in.  It must have
2768  * sufficient headroom to do so (e.g. as returned by xfif_recv()).
2769  *
2770  * The conversion is not complete: the caller still needs to trim any unneeded
2771  * payload off the end of the buffer, set the length in the OpenFlow header,
2772  * and set buffer_id.  Those require us to know the controller settings and so
2773  * must be done on a per-controller basis.
2774  *
2775  * Returns the maximum number of bytes of the packet that should be sent to
2776  * the controller (INT_MAX if no limit). */
2777 static int
2778 do_convert_to_packet_in(struct wdp_packet *packet)
2779 {
2780     uint16_t total_len = packet->payload->size;
2781     struct ofp_packet_in *opi;
2782
2783     /* Repurpose packet buffer by overwriting header. */
2784     opi = ofpbuf_push_zeros(packet->payload,
2785                             offsetof(struct ofp_packet_in, data));
2786     opi->header.version = OFP_VERSION;
2787     opi->header.type = OFPT_PACKET_IN;
2788     opi->total_len = htons(total_len);
2789     opi->in_port = htons(packet->in_port);
2790     if (packet->channel == WDP_CHAN_MISS) {
2791         opi->reason = OFPR_NO_MATCH;
2792         return INT_MAX;
2793     } else {
2794         opi->reason = OFPR_ACTION;
2795         return packet->send_len;
2796     }
2797 }
2798
2799 /* Given 'packet' with channel WDP_CHAN_ACTION or WDP_CHAN_MISS, sends an
2800  * OFPT_PACKET_IN message to each OpenFlow controller as necessary according to
2801  * their individual configurations.
2802  *
2803  * 'packet->payload' must have sufficient headroom to convert it into a struct
2804  * ofp_packet_in (e.g. as returned by dpif_recv()).
2805  *
2806  * Takes ownership of 'packet'. */
2807 static void
2808 send_packet_in(struct ofproto *ofproto, struct wdp_packet *packet)
2809 {
2810     struct ofconn *ofconn, *prev;
2811     int max_len;
2812
2813     max_len = do_convert_to_packet_in(packet);
2814
2815     prev = NULL;
2816     LIST_FOR_EACH (ofconn, struct ofconn, node, &ofproto->all_conns) {
2817         if (ofconn_receives_async_msgs(ofconn)) {
2818             if (prev) {
2819                 schedule_packet_in(prev, packet, max_len, true);
2820             }
2821             prev = ofconn;
2822         }
2823     }
2824     if (prev) {
2825         schedule_packet_in(prev, packet, max_len, false);
2826     } else {
2827         wdp_packet_destroy(packet);
2828     }
2829 }
2830
2831 static uint64_t
2832 pick_datapath_id(const struct ofproto *ofproto)
2833 {
2834     struct wdp_port port;
2835
2836     if (!wdp_port_query_by_number(ofproto->wdp, OFPP_LOCAL, &port)) {
2837         uint8_t ea[ETH_ADDR_LEN];
2838         int error;
2839
2840         error = netdev_get_etheraddr(port.netdev, ea);
2841         if (!error) {
2842             wdp_port_free(&port);
2843             return eth_addr_to_uint64(ea);
2844         }
2845         VLOG_WARN("could not get MAC address for %s (%s)",
2846                   netdev_get_name(port.netdev), strerror(error));
2847         wdp_port_free(&port);
2848     }
2849
2850     return ofproto->fallback_dpid;
2851 }
2852
2853 static uint64_t
2854 pick_fallback_dpid(void)
2855 {
2856     uint8_t ea[ETH_ADDR_LEN];
2857     eth_addr_nicira_random(ea);
2858     return eth_addr_to_uint64(ea);
2859 }