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