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