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