Update primary code license to Apache 2.0.
[cascardo/ovs.git] / secchan / ofproto.c
1 /*
2  * Copyright (c) 2009 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "ofproto.h"
19 #include <errno.h>
20 #include <inttypes.h>
21 #include <net/if.h>
22 #include <netinet/in.h>
23 #include <stdbool.h>
24 #include <stdlib.h>
25 #include "classifier.h"
26 #include "coverage.h"
27 #include "discovery.h"
28 #include "dpif.h"
29 #include "executer.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 "odp-util.h"
36 #include "ofp-print.h"
37 #include "ofpbuf.h"
38 #include "openflow/nicira-ext.h"
39 #include "openflow/openflow.h"
40 #include "openflow/openflow-mgmt.h"
41 #include "openvswitch/datapath-protocol.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 "svec.h"
52 #include "tag.h"
53 #include "timeval.h"
54 #include "vconn.h"
55 #include "vconn-ssl.h"
56 #include "xtoxll.h"
57
58 #define THIS_MODULE VLM_ofproto
59 #include "vlog.h"
60
61 enum {
62     DP_GROUP_FLOOD = 0,
63     DP_GROUP_ALL = 1
64 };
65
66 enum {
67     TABLEID_HASH = 0,
68     TABLEID_CLASSIFIER = 1
69 };
70
71 struct ofport {
72     struct netdev *netdev;
73     struct ofp_phy_port opp;    /* In host byte order. */
74 };
75
76 static void ofport_free(struct ofport *);
77 static void hton_ofp_phy_port(struct ofp_phy_port *);
78
79 static int xlate_actions(const union ofp_action *in, size_t n_in,
80                          const flow_t *flow, struct ofproto *ofproto,
81                          const struct ofpbuf *packet,
82                          struct odp_actions *out, tag_type *tags,
83                          bool *may_setup_flow);
84
85 struct rule {
86     struct cls_rule cr;
87
88     uint16_t idle_timeout;      /* In seconds from time of last use. */
89     uint16_t hard_timeout;      /* In seconds from time of creation. */
90     long long int used;         /* Last-used time (0 if never used). */
91     long long int created;      /* Creation time. */
92     uint64_t packet_count;      /* Number of packets received. */
93     uint64_t byte_count;        /* Number of bytes received. */
94     uint64_t accounted_bytes;   /* Number of bytes passed to account_cb. */
95     uint8_t tcp_flags;          /* Bitwise-OR of all TCP flags seen. */
96     uint8_t ip_tos;             /* Last-seen IP type-of-service. */
97     tag_type tags;              /* Tags (set only by hooks). */
98
99     /* If 'super' is non-NULL, this rule is a subrule, that is, it is an
100      * exact-match rule (having cr.wc.wildcards of 0) generated from the
101      * wildcard rule 'super'.  In this case, 'list' is an element of the
102      * super-rule's list.
103      *
104      * If 'super' is NULL, this rule is a super-rule, and 'list' is the head of
105      * a list of subrules.  A super-rule with no wildcards (where
106      * cr.wc.wildcards is 0) will never have any subrules. */
107     struct rule *super;
108     struct list list;
109
110     /* OpenFlow actions.
111      *
112      * A subrule has no actions (it uses the super-rule's actions). */
113     int n_actions;
114     union ofp_action *actions;
115
116     /* Datapath actions.
117      *
118      * A super-rule with wildcard fields never has ODP actions (since the
119      * datapath only supports exact-match flows). */
120     bool installed;             /* Installed in datapath? */
121     bool may_install;           /* True ordinarily; false if actions must
122                                  * be reassessed for every packet. */
123     int n_odp_actions;
124     union odp_action *odp_actions;
125 };
126
127 static inline bool
128 rule_is_hidden(const struct rule *rule)
129 {
130     /* Subrules are merely an implementation detail, so hide them from the
131      * controller. */
132     if (rule->super != NULL) {
133         return true;
134     }
135
136     /* Rules with priority higher than UINT16_MAX are set up by secchan itself
137      * (e.g. by in-band control) and are intentionally hidden from the
138      * controller. */
139     if (rule->cr.priority > UINT16_MAX) {
140         return true;
141     }
142
143     return false;
144 }
145
146 static struct rule *rule_create(struct rule *super, const union ofp_action *,
147                                 size_t n_actions, uint16_t idle_timeout,
148                                 uint16_t hard_timeout);
149 static void rule_free(struct rule *);
150 static void rule_destroy(struct ofproto *, struct rule *);
151 static struct rule *rule_from_cls_rule(const struct cls_rule *);
152 static void rule_insert(struct ofproto *, struct rule *,
153                         struct ofpbuf *packet, uint16_t in_port);
154 static void rule_remove(struct ofproto *, struct rule *);
155 static bool rule_make_actions(struct ofproto *, struct rule *,
156                               const struct ofpbuf *packet);
157 static void rule_install(struct ofproto *, struct rule *,
158                          struct rule *displaced_rule);
159 static void rule_uninstall(struct ofproto *, struct rule *);
160 static void rule_post_uninstall(struct ofproto *, struct rule *);
161
162 struct ofconn {
163     struct list node;
164     struct rconn *rconn;
165     struct pktbuf *pktbuf;
166     bool send_flow_exp;
167     int miss_send_len;
168
169     struct rconn_packet_counter *packet_in_counter;
170
171     /* Number of OpenFlow messages queued as replies to OpenFlow requests, and
172      * the maximum number before we stop reading OpenFlow requests.  */
173 #define OFCONN_REPLY_MAX 100
174     struct rconn_packet_counter *reply_counter;
175 };
176
177 static struct ofconn *ofconn_create(struct ofproto *, struct rconn *);
178 static void ofconn_destroy(struct ofconn *, struct ofproto *);
179 static void ofconn_run(struct ofconn *, struct ofproto *);
180 static void ofconn_wait(struct ofconn *);
181 static void queue_tx(struct ofpbuf *msg, const struct ofconn *ofconn,
182                      struct rconn_packet_counter *counter);
183
184 struct ofproto {
185     /* Settings. */
186     uint64_t datapath_id;       /* Datapath ID. */
187     uint64_t fallback_dpid;     /* Datapath ID if no better choice found. */
188     uint64_t mgmt_id;           /* Management channel identifier. */
189     char *manufacturer;         /* Manufacturer. */
190     char *hardware;             /* Hardware. */
191     char *software;             /* Software version. */
192     char *serial;               /* Serial number. */
193
194     /* Datapath. */
195     struct dpif dpif;
196     struct dpifmon *dpifmon;
197     struct port_array ports;    /* Index is ODP port nr; ofport->opp.port_no is
198                                  * OFP port nr. */
199     struct shash port_by_name;
200     uint32_t max_ports;
201
202     /* Configuration. */
203     struct switch_status *switch_status;
204     struct status_category *ss_cat;
205     struct in_band *in_band;
206     struct discovery *discovery;
207     struct fail_open *fail_open;
208     struct pinsched *miss_sched, *action_sched;
209     struct executer *executer;
210     struct netflow *netflow;
211
212     /* Flow table. */
213     struct classifier cls;
214     bool need_revalidate;
215     long long int next_expiration;
216     struct tag_set revalidate_set;
217
218     /* OpenFlow connections. */
219     struct list all_conns;
220     struct ofconn *controller;
221     struct pvconn **listeners;
222     size_t n_listeners;
223     struct pvconn **snoops;
224     size_t n_snoops;
225
226     /* Hooks for ovs-vswitchd. */
227     const struct ofhooks *ofhooks;
228     void *aux;
229
230     /* Used by default ofhooks. */
231     struct mac_learning *ml;
232 };
233
234 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
235
236 static const struct ofhooks default_ofhooks;
237
238 static uint64_t pick_datapath_id(struct dpif *, uint64_t fallback_dpid);
239 static uint64_t pick_fallback_dpid(void);
240 static void send_packet_in_miss(struct ofpbuf *, void *ofproto);
241 static void send_packet_in_action(struct ofpbuf *, void *ofproto);
242 static void update_used(struct ofproto *);
243 static void update_stats(struct rule *, const struct odp_flow_stats *);
244 static void expire_rule(struct cls_rule *, void *ofproto);
245 static bool revalidate_rule(struct ofproto *p, struct rule *rule);
246 static void revalidate_cb(struct cls_rule *rule_, void *p_);
247
248 static void handle_odp_msg(struct ofproto *, struct ofpbuf *);
249
250 static void handle_openflow(struct ofconn *, struct ofproto *,
251                             struct ofpbuf *);
252
253 static void refresh_port_group(struct ofproto *, unsigned int group);
254 static void update_port(struct ofproto *, const char *devname);
255 static int init_ports(struct ofproto *);
256 static void reinit_ports(struct ofproto *);
257
258 int
259 ofproto_create(const char *datapath, const struct ofhooks *ofhooks, void *aux,
260                struct ofproto **ofprotop)
261 {
262     struct dpifmon *dpifmon;
263     struct odp_stats stats;
264     struct ofproto *p;
265     struct dpif dpif;
266     int error;
267
268     *ofprotop = NULL;
269
270     /* Connect to datapath and start listening for messages. */
271     error = dpif_open(datapath, &dpif);
272     if (error) {
273         VLOG_ERR("failed to open datapath %s: %s", datapath, strerror(error));
274         return error;
275     }
276     error = dpif_get_dp_stats(&dpif, &stats);
277     if (error) {
278         VLOG_ERR("failed to obtain stats for datapath %s: %s",
279                  datapath, strerror(error));
280         dpif_close(&dpif);
281         return error;
282     }
283     error = dpif_set_listen_mask(&dpif, ODPL_MISS | ODPL_ACTION);
284     if (error) {
285         VLOG_ERR("failed to listen on datapath %s: %s",
286                  datapath, strerror(error));
287         dpif_close(&dpif);
288         return error;
289     }
290     dpif_flow_flush(&dpif);
291     dpif_purge(&dpif);
292
293     /* Start monitoring datapath ports for status changes. */
294     error = dpifmon_create(datapath, &dpifmon);
295     if (error) {
296         VLOG_ERR("failed to starting monitoring datapath %s: %s",
297                  datapath, strerror(error));
298         dpif_close(&dpif);
299         return error;
300     }
301
302     /* Initialize settings. */
303     p = xcalloc(1, sizeof *p);
304     p->fallback_dpid = pick_fallback_dpid();
305     p->datapath_id = pick_datapath_id(&dpif, p->fallback_dpid);
306     VLOG_INFO("using datapath ID %012"PRIx64, p->datapath_id);
307     p->manufacturer = xstrdup("Nicira Networks, Inc.");
308     p->hardware = xstrdup("Reference Implementation");
309     p->software = xstrdup(VERSION BUILDNR);
310     p->serial = xstrdup("None");
311
312     /* Initialize datapath. */
313     p->dpif = dpif;
314     p->dpifmon = dpifmon;
315     port_array_init(&p->ports);
316     shash_init(&p->port_by_name);
317     p->max_ports = stats.max_ports;
318
319     /* Initialize submodules. */
320     p->switch_status = switch_status_create(p);
321     p->in_band = NULL;
322     p->discovery = NULL;
323     p->fail_open = NULL;
324     p->miss_sched = p->action_sched = NULL;
325     p->executer = NULL;
326     p->netflow = NULL;
327
328     /* Initialize flow table. */
329     classifier_init(&p->cls);
330     p->need_revalidate = false;
331     p->next_expiration = time_msec() + 1000;
332     tag_set_init(&p->revalidate_set);
333
334     /* Initialize OpenFlow connections. */
335     list_init(&p->all_conns);
336     p->controller = ofconn_create(p, rconn_create(15, 15));
337     p->controller->pktbuf = pktbuf_create();
338     p->controller->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
339     p->listeners = NULL;
340     p->n_listeners = 0;
341     p->snoops = NULL;
342     p->n_snoops = 0;
343
344     /* Initialize hooks. */
345     if (ofhooks) {
346         p->ofhooks = ofhooks;
347         p->aux = aux;
348         p->ml = NULL;
349     } else {
350         p->ofhooks = &default_ofhooks;
351         p->aux = p;
352         p->ml = mac_learning_create();
353     }
354
355     /* Register switch status category. */
356     p->ss_cat = switch_status_register(p->switch_status, "remote",
357                                        rconn_status_cb, p->controller->rconn);
358
359     /* Almost done... */
360     error = init_ports(p);
361     if (error) {
362         ofproto_destroy(p);
363         return error;
364     }
365
366     *ofprotop = p;
367     return 0;
368 }
369
370 void
371 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
372 {
373     uint64_t old_dpid = p->datapath_id;
374     p->datapath_id = (datapath_id
375                       ? datapath_id
376                       : pick_datapath_id(&p->dpif, p->fallback_dpid));
377     if (p->datapath_id != old_dpid) {
378         VLOG_INFO("datapath ID changed to %012"PRIx64, p->datapath_id);
379         rconn_reconnect(p->controller->rconn);
380     }
381 }
382
383 void
384 ofproto_set_mgmt_id(struct ofproto *p, uint64_t mgmt_id)
385 {
386     p->mgmt_id = mgmt_id;
387 }
388
389 void
390 ofproto_set_probe_interval(struct ofproto *p, int probe_interval)
391 {
392     probe_interval = probe_interval ? MAX(probe_interval, 5) : 0;
393     rconn_set_probe_interval(p->controller->rconn, probe_interval);
394     if (p->fail_open) {
395         int trigger_duration = probe_interval ? probe_interval * 3 : 15;
396         fail_open_set_trigger_duration(p->fail_open, trigger_duration);
397     }
398 }
399
400 void
401 ofproto_set_max_backoff(struct ofproto *p, int max_backoff)
402 {
403     rconn_set_max_backoff(p->controller->rconn, max_backoff);
404 }
405
406 void
407 ofproto_set_desc(struct ofproto *p,
408                  const char *manufacturer, const char *hardware,
409                  const char *software, const char *serial)
410 {
411     if (manufacturer) {
412         free(p->manufacturer);
413         p->manufacturer = xstrdup(manufacturer);
414     }
415     if (hardware) {
416         free(p->hardware);
417         p->hardware = xstrdup(hardware);
418     }
419     if (software) {
420         free(p->software);
421         p->software = xstrdup(software);
422     }
423     if (serial) {
424         free(p->serial);
425         p->serial = xstrdup(serial);
426     }
427 }
428
429 int
430 ofproto_set_in_band(struct ofproto *p, bool in_band)
431 {
432     if (in_band != (p->in_band != NULL)) {
433         if (in_band) {
434             return in_band_create(p, &p->dpif, p->switch_status,
435                                   p->controller->rconn, &p->in_band);
436         } else {
437             ofproto_set_discovery(p, false, NULL, true);
438             in_band_destroy(p->in_band);
439             p->in_band = NULL;
440         }
441         rconn_reconnect(p->controller->rconn);
442     }
443     return 0;
444 }
445
446 int
447 ofproto_set_discovery(struct ofproto *p, bool discovery,
448                       const char *re, bool update_resolv_conf)
449 {
450     if (discovery != (p->discovery != NULL)) {
451         if (discovery) {
452             int error = ofproto_set_in_band(p, true);
453             if (error) {
454                 return error;
455             }
456             error = discovery_create(re, update_resolv_conf,
457                                      &p->dpif, p->switch_status,
458                                      &p->discovery);
459             if (error) {
460                 return error;
461             }
462         } else {
463             discovery_destroy(p->discovery);
464             p->discovery = NULL;
465         }
466         rconn_disconnect(p->controller->rconn);
467     } else if (discovery) {
468         discovery_set_update_resolv_conf(p->discovery, update_resolv_conf);
469         return discovery_set_accept_controller_re(p->discovery, re);
470     }
471     return 0;
472 }
473
474 int
475 ofproto_set_controller(struct ofproto *ofproto, const char *controller)
476 {
477     if (ofproto->discovery) {
478         return EINVAL;
479     } else if (controller) {
480         if (strcmp(rconn_get_name(ofproto->controller->rconn), controller)) {
481             return rconn_connect(ofproto->controller->rconn, controller);
482         } else {
483             return 0;
484         }
485     } else {
486         rconn_disconnect(ofproto->controller->rconn);
487         return 0;
488     }
489 }
490
491 static int
492 set_pvconns(struct pvconn ***pvconnsp, size_t *n_pvconnsp,
493             const struct svec *svec)
494 {
495     struct pvconn **pvconns = *pvconnsp;
496     size_t n_pvconns = *n_pvconnsp;
497     int retval = 0;
498     size_t i;
499
500     for (i = 0; i < n_pvconns; i++) {
501         pvconn_close(pvconns[i]);
502     }
503     free(pvconns);
504
505     pvconns = xmalloc(svec->n * sizeof *pvconns);
506     n_pvconns = 0;
507     for (i = 0; i < svec->n; i++) {
508         const char *name = svec->names[i];
509         struct pvconn *pvconn;
510         int error;
511
512         error = pvconn_open(name, &pvconn);
513         if (!error) {
514             pvconns[n_pvconns++] = pvconn;
515         } else {
516             VLOG_ERR("failed to listen on %s: %s", name, strerror(error));
517             if (!retval) {
518                 retval = error;
519             }
520         }
521     }
522
523     *pvconnsp = pvconns;
524     *n_pvconnsp = n_pvconns;
525
526     return retval;
527 }
528
529 int
530 ofproto_set_listeners(struct ofproto *ofproto, const struct svec *listeners)
531 {
532     return set_pvconns(&ofproto->listeners, &ofproto->n_listeners, listeners);
533 }
534
535 int
536 ofproto_set_snoops(struct ofproto *ofproto, const struct svec *snoops)
537 {
538     return set_pvconns(&ofproto->snoops, &ofproto->n_snoops, snoops);
539 }
540
541 int
542 ofproto_set_netflow(struct ofproto *ofproto, const struct svec *collectors,
543         uint8_t engine_type, uint8_t engine_id, bool add_id_to_iface)
544 {
545     if (collectors && collectors->n) {
546         if (!ofproto->netflow) {
547             ofproto->netflow = netflow_create();
548         }
549         netflow_set_engine(ofproto->netflow, engine_type, engine_id, 
550                 add_id_to_iface);
551         return netflow_set_collectors(ofproto->netflow, collectors);
552     } else {
553         netflow_destroy(ofproto->netflow);
554         ofproto->netflow = NULL;
555         return 0;
556     }
557 }
558
559 void
560 ofproto_set_failure(struct ofproto *ofproto, bool fail_open)
561 {
562     if (fail_open) {
563         struct rconn *rconn = ofproto->controller->rconn;
564         int trigger_duration = rconn_get_probe_interval(rconn) * 3;
565         if (!ofproto->fail_open) {
566             ofproto->fail_open = fail_open_create(ofproto, trigger_duration,
567                                                   ofproto->switch_status,
568                                                   rconn);
569         } else {
570             fail_open_set_trigger_duration(ofproto->fail_open,
571                                            trigger_duration);
572         }
573     } else {
574         fail_open_destroy(ofproto->fail_open);
575         ofproto->fail_open = NULL;
576     }
577 }
578
579 void
580 ofproto_set_rate_limit(struct ofproto *ofproto,
581                        int rate_limit, int burst_limit)
582 {
583     if (rate_limit > 0) {
584         if (!ofproto->miss_sched) {
585             ofproto->miss_sched = pinsched_create(rate_limit, burst_limit,
586                                                   ofproto->switch_status);
587             ofproto->action_sched = pinsched_create(rate_limit, burst_limit,
588                                                     NULL);
589         } else {
590             pinsched_set_limits(ofproto->miss_sched, rate_limit, burst_limit);
591             pinsched_set_limits(ofproto->action_sched,
592                                 rate_limit, burst_limit);
593         }
594     } else {
595         pinsched_destroy(ofproto->miss_sched);
596         ofproto->miss_sched = NULL;
597         pinsched_destroy(ofproto->action_sched);
598         ofproto->action_sched = NULL;
599     }
600 }
601
602 int
603 ofproto_set_stp(struct ofproto *ofproto UNUSED, bool enable_stp)
604 {
605     /* XXX */
606     if (enable_stp) {
607         VLOG_WARN("STP is not yet implemented");
608         return EINVAL;
609     } else {
610         return 0;
611     }
612 }
613
614 int
615 ofproto_set_remote_execution(struct ofproto *ofproto, const char *command_acl,
616                              const char *command_dir)
617 {
618     if (command_acl) {
619         if (!ofproto->executer) {
620             return executer_create(command_acl, command_dir,
621                                    &ofproto->executer);
622         } else {
623             executer_set_acl(ofproto->executer, command_acl, command_dir);
624         }
625     } else {
626         executer_destroy(ofproto->executer);
627         ofproto->executer = NULL;
628     }
629     return 0;
630 }
631
632 uint64_t
633 ofproto_get_datapath_id(const struct ofproto *ofproto)
634 {
635     return ofproto->datapath_id;
636 }
637
638 int
639 ofproto_get_probe_interval(const struct ofproto *ofproto)
640 {
641     return rconn_get_probe_interval(ofproto->controller->rconn);
642 }
643
644 int
645 ofproto_get_max_backoff(const struct ofproto *ofproto)
646 {
647     return rconn_get_max_backoff(ofproto->controller->rconn);
648 }
649
650 bool
651 ofproto_get_in_band(const struct ofproto *ofproto)
652 {
653     return ofproto->in_band != NULL;
654 }
655
656 bool
657 ofproto_get_discovery(const struct ofproto *ofproto)
658 {
659     return ofproto->discovery != NULL;
660 }
661
662 const char *
663 ofproto_get_controller(const struct ofproto *ofproto)
664 {
665     return rconn_get_name(ofproto->controller->rconn);
666 }
667
668 void
669 ofproto_get_listeners(const struct ofproto *ofproto, struct svec *listeners)
670 {
671     size_t i;
672
673     for (i = 0; i < ofproto->n_listeners; i++) {
674         svec_add(listeners, pvconn_get_name(ofproto->listeners[i]));
675     }
676 }
677
678 void
679 ofproto_get_snoops(const struct ofproto *ofproto, struct svec *snoops)
680 {
681     size_t i;
682
683     for (i = 0; i < ofproto->n_snoops; i++) {
684         svec_add(snoops, pvconn_get_name(ofproto->snoops[i]));
685     }
686 }
687
688 void
689 ofproto_destroy(struct ofproto *p)
690 {
691     struct ofconn *ofconn, *next_ofconn;
692     struct ofport *ofport;
693     unsigned int port_no;
694     size_t i;
695
696     if (!p) {
697         return;
698     }
699
700     ofproto_flush_flows(p);
701     classifier_destroy(&p->cls);
702
703     LIST_FOR_EACH_SAFE (ofconn, next_ofconn, struct ofconn, node,
704                         &p->all_conns) {
705         ofconn_destroy(ofconn, p);
706     }
707
708     dpif_close(&p->dpif);
709     dpifmon_destroy(p->dpifmon);
710     PORT_ARRAY_FOR_EACH (ofport, &p->ports, port_no) {
711         ofport_free(ofport);
712     }
713     shash_destroy(&p->port_by_name);
714
715     switch_status_destroy(p->switch_status);
716     in_band_destroy(p->in_band);
717     discovery_destroy(p->discovery);
718     fail_open_destroy(p->fail_open);
719     pinsched_destroy(p->miss_sched);
720     pinsched_destroy(p->action_sched);
721     executer_destroy(p->executer);
722     netflow_destroy(p->netflow);
723
724     switch_status_unregister(p->ss_cat);
725
726     for (i = 0; i < p->n_listeners; i++) {
727         pvconn_close(p->listeners[i]);
728     }
729     free(p->listeners);
730
731     for (i = 0; i < p->n_snoops; i++) {
732         pvconn_close(p->snoops[i]);
733     }
734     free(p->snoops);
735
736     mac_learning_destroy(p->ml);
737
738     free(p);
739 }
740
741 int
742 ofproto_run(struct ofproto *p)
743 {
744     int error = ofproto_run1(p);
745     if (!error) {
746         error = ofproto_run2(p, false);
747     }
748     return error;
749 }
750
751 int
752 ofproto_run1(struct ofproto *p)
753 {
754     struct ofconn *ofconn, *next_ofconn;
755     char *devname;
756     int error;
757     int i;
758
759     for (i = 0; i < 50; i++) {
760         struct ofpbuf *buf;
761         int error;
762
763         error = dpif_recv(&p->dpif, &buf);
764         if (error) {
765             if (error == ENODEV) {
766                 /* Someone destroyed the datapath behind our back.  The caller
767                  * better destroy us and give up, because we're just going to
768                  * spin from here on out. */
769                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
770                 VLOG_ERR_RL(&rl, "dp%u: datapath was destroyed externally",
771                             dpif_id(&p->dpif));
772                 return ENODEV;
773             }
774             break;
775         }
776
777         handle_odp_msg(p, buf);
778     }
779
780     while ((error = dpifmon_poll(p->dpifmon, &devname)) != EAGAIN) {
781         if (error == ENOBUFS) {
782             reinit_ports(p);
783         } else if (!error) {
784             update_port(p, devname);
785             free(devname);
786         }
787     }
788
789     if (p->in_band) {
790         in_band_run(p->in_band);
791     }
792     if (p->discovery) {
793         char *controller_name;
794         if (rconn_is_connectivity_questionable(p->controller->rconn)) {
795             discovery_question_connectivity(p->discovery);
796         }
797         if (discovery_run(p->discovery, &controller_name)) {
798             if (controller_name) {
799                 rconn_connect(p->controller->rconn, controller_name);
800             } else {
801                 rconn_disconnect(p->controller->rconn);
802             }
803         }
804     }
805     if (p->fail_open) {
806         fail_open_run(p->fail_open);
807     }
808     pinsched_run(p->miss_sched, send_packet_in_miss, p);
809     pinsched_run(p->action_sched, send_packet_in_action, p);
810     if (p->executer) {
811         executer_run(p->executer);
812     }
813
814     LIST_FOR_EACH_SAFE (ofconn, next_ofconn, struct ofconn, node,
815                         &p->all_conns) {
816         ofconn_run(ofconn, p);
817     }
818
819     for (i = 0; i < p->n_listeners; i++) {
820         struct vconn *vconn;
821         int retval;
822
823         retval = pvconn_accept(p->listeners[i], OFP_VERSION, &vconn);
824         if (!retval) {
825             ofconn_create(p, rconn_new_from_vconn("passive", vconn));
826         } else if (retval != EAGAIN) {
827             VLOG_WARN_RL(&rl, "accept failed (%s)", strerror(retval));
828         }
829     }
830
831     for (i = 0; i < p->n_snoops; i++) {
832         struct vconn *vconn;
833         int retval;
834
835         retval = pvconn_accept(p->snoops[i], OFP_VERSION, &vconn);
836         if (!retval) {
837             rconn_add_monitor(p->controller->rconn, vconn);
838         } else if (retval != EAGAIN) {
839             VLOG_WARN_RL(&rl, "accept failed (%s)", strerror(retval));
840         }
841     }
842
843     if (time_msec() >= p->next_expiration) {
844         COVERAGE_INC(ofproto_expiration);
845         p->next_expiration = time_msec() + 1000;
846         update_used(p);
847
848         classifier_for_each(&p->cls, CLS_INC_ALL, expire_rule, p);
849
850         /* Let the hook know that we're at a stable point: all outstanding data
851          * in existing flows has been accounted to the account_cb.  Thus, the
852          * hook can now reasonably do operations that depend on having accurate
853          * flow volume accounting (currently, that's just bond rebalancing). */
854         if (p->ofhooks->account_checkpoint_cb) {
855             p->ofhooks->account_checkpoint_cb(p->aux);
856         }
857     }
858
859     if (p->netflow) {
860         netflow_run(p->netflow);
861     }
862
863     return 0;
864 }
865
866 struct revalidate_cbdata {
867     struct ofproto *ofproto;
868     bool revalidate_all;        /* Revalidate all exact-match rules? */
869     bool revalidate_subrules;   /* Revalidate all exact-match subrules? */
870     struct tag_set revalidate_set; /* Set of tags to revalidate. */
871 };
872
873 int
874 ofproto_run2(struct ofproto *p, bool revalidate_all)
875 {
876     if (p->need_revalidate || revalidate_all
877         || !tag_set_is_empty(&p->revalidate_set)) {
878         struct revalidate_cbdata cbdata;
879         cbdata.ofproto = p;
880         cbdata.revalidate_all = revalidate_all;
881         cbdata.revalidate_subrules = p->need_revalidate;
882         cbdata.revalidate_set = p->revalidate_set;
883         tag_set_init(&p->revalidate_set);
884         COVERAGE_INC(ofproto_revalidate);
885         classifier_for_each(&p->cls, CLS_INC_EXACT, revalidate_cb, &cbdata);
886         p->need_revalidate = false;
887     }
888
889     return 0;
890 }
891
892 void
893 ofproto_wait(struct ofproto *p)
894 {
895     struct ofconn *ofconn;
896     size_t i;
897
898     dpif_recv_wait(&p->dpif);
899     dpifmon_wait(p->dpifmon);
900     LIST_FOR_EACH (ofconn, struct ofconn, node, &p->all_conns) {
901         ofconn_wait(ofconn);
902     }
903     if (p->in_band) {
904         in_band_wait(p->in_band);
905     }
906     if (p->discovery) {
907         discovery_wait(p->discovery);
908     }
909     if (p->fail_open) {
910         fail_open_wait(p->fail_open);
911     }
912     pinsched_wait(p->miss_sched);
913     pinsched_wait(p->action_sched);
914     if (p->executer) {
915         executer_wait(p->executer);
916     }
917     if (!tag_set_is_empty(&p->revalidate_set)) {
918         poll_immediate_wake();
919     }
920     if (p->need_revalidate) {
921         /* Shouldn't happen, but if it does just go around again. */
922         VLOG_DBG_RL(&rl, "need revalidate in ofproto_wait_cb()");
923         poll_immediate_wake();
924     } else if (p->next_expiration != LLONG_MAX) {
925         poll_timer_wait(p->next_expiration - time_msec());
926     }
927     for (i = 0; i < p->n_listeners; i++) {
928         pvconn_wait(p->listeners[i]);
929     }
930     for (i = 0; i < p->n_snoops; i++) {
931         pvconn_wait(p->snoops[i]);
932     }
933 }
934
935 void
936 ofproto_revalidate(struct ofproto *ofproto, tag_type tag)
937 {
938     tag_set_add(&ofproto->revalidate_set, tag);
939 }
940
941 struct tag_set *
942 ofproto_get_revalidate_set(struct ofproto *ofproto)
943 {
944     return &ofproto->revalidate_set;
945 }
946
947 bool
948 ofproto_is_alive(const struct ofproto *p)
949 {
950     return p->discovery || rconn_is_alive(p->controller->rconn);
951 }
952
953 int
954 ofproto_send_packet(struct ofproto *p, const flow_t *flow,
955                     const union ofp_action *actions, size_t n_actions,
956                     const struct ofpbuf *packet)
957 {
958     struct odp_actions odp_actions;
959     int error;
960
961     error = xlate_actions(actions, n_actions, flow, p, packet, &odp_actions,
962                           NULL, NULL);
963     if (error) {
964         return error;
965     }
966
967     /* XXX Should we translate the dpif_execute() errno value into an OpenFlow
968      * error code? */
969     dpif_execute(&p->dpif, flow->in_port, odp_actions.actions,
970                  odp_actions.n_actions, packet);
971     return 0;
972 }
973
974 void
975 ofproto_add_flow(struct ofproto *p,
976                  const flow_t *flow, uint32_t wildcards, unsigned int priority,
977                  const union ofp_action *actions, size_t n_actions,
978                  int idle_timeout)
979 {
980     struct rule *rule;
981     rule = rule_create(NULL, actions, n_actions,
982                        idle_timeout >= 0 ? idle_timeout : 5 /* XXX */, 0);
983     cls_rule_from_flow(&rule->cr, flow, wildcards, priority);
984     rule_insert(p, rule, NULL, 0);
985 }
986
987 void
988 ofproto_delete_flow(struct ofproto *ofproto, const flow_t *flow,
989                     uint32_t wildcards, unsigned int priority)
990 {
991     struct rule *rule;
992
993     rule = rule_from_cls_rule(classifier_find_rule_exactly(&ofproto->cls,
994                                                            flow, wildcards,
995                                                            priority));
996     if (rule) {
997         rule_remove(ofproto, rule);
998     }
999 }
1000
1001 static void
1002 destroy_rule(struct cls_rule *rule_, void *ofproto_)
1003 {
1004     struct rule *rule = rule_from_cls_rule(rule_);
1005     struct ofproto *ofproto = ofproto_;
1006
1007     /* Mark the flow as not installed, even though it might really be
1008      * installed, so that rule_remove() doesn't bother trying to uninstall it.
1009      * There is no point in uninstalling it individually since we are about to
1010      * blow away all the flows with dpif_flow_flush(). */
1011     rule->installed = false;
1012
1013     rule_remove(ofproto, rule);
1014 }
1015
1016 void
1017 ofproto_flush_flows(struct ofproto *ofproto)
1018 {
1019     COVERAGE_INC(ofproto_flush);
1020     classifier_for_each(&ofproto->cls, CLS_INC_ALL, destroy_rule, ofproto);
1021     dpif_flow_flush(&ofproto->dpif);
1022     if (ofproto->in_band) {
1023         in_band_flushed(ofproto->in_band);
1024     }
1025     if (ofproto->fail_open) {
1026         fail_open_flushed(ofproto->fail_open);
1027     }
1028 }
1029 \f
1030 static void
1031 reinit_ports(struct ofproto *p)
1032 {
1033     struct svec devnames;
1034     struct ofport *ofport;
1035     unsigned int port_no;
1036     struct odp_port *odp_ports;
1037     size_t n_odp_ports;
1038     size_t i;
1039
1040     svec_init(&devnames);
1041     PORT_ARRAY_FOR_EACH (ofport, &p->ports, port_no) {
1042         svec_add (&devnames, (char *) ofport->opp.name);
1043     }
1044     dpif_port_list(&p->dpif, &odp_ports, &n_odp_ports);
1045     for (i = 0; i < n_odp_ports; i++) {
1046         svec_add (&devnames, odp_ports[i].devname);
1047     }
1048     free(odp_ports);
1049
1050     svec_sort_unique(&devnames);
1051     for (i = 0; i < devnames.n; i++) {
1052         update_port(p, devnames.names[i]);
1053     }
1054     svec_destroy(&devnames);
1055 }
1056
1057 static void
1058 refresh_port_group(struct ofproto *p, unsigned int group)
1059 {
1060     uint16_t *ports;
1061     size_t n_ports;
1062     struct ofport *port;
1063     unsigned int port_no;
1064
1065     assert(group == DP_GROUP_ALL || group == DP_GROUP_FLOOD);
1066
1067     ports = xmalloc(port_array_count(&p->ports) * sizeof *ports);
1068     n_ports = 0;
1069     PORT_ARRAY_FOR_EACH (port, &p->ports, port_no) {
1070         if (group == DP_GROUP_ALL || !(port->opp.config & OFPPC_NO_FLOOD)) {
1071             ports[n_ports++] = port_no;
1072         }
1073     }
1074     dpif_port_group_set(&p->dpif, group, ports, n_ports);
1075     free(ports);
1076 }
1077
1078 static void
1079 refresh_port_groups(struct ofproto *p)
1080 {
1081     refresh_port_group(p, DP_GROUP_FLOOD);
1082     refresh_port_group(p, DP_GROUP_ALL);
1083 }
1084
1085 static struct ofport *
1086 make_ofport(const struct odp_port *odp_port)
1087 {
1088     enum netdev_flags flags;
1089     struct ofport *ofport;
1090     struct netdev *netdev;
1091     bool carrier;
1092     int error;
1093
1094     error = netdev_open(odp_port->devname, NETDEV_ETH_TYPE_NONE, &netdev);
1095     if (error) {
1096         VLOG_WARN_RL(&rl, "ignoring port %s (%"PRIu16") because netdev %s "
1097                      "cannot be opened (%s)",
1098                      odp_port->devname, odp_port->port,
1099                      odp_port->devname, strerror(error));
1100         return NULL;
1101     }
1102
1103     ofport = xmalloc(sizeof *ofport);
1104     ofport->netdev = netdev;
1105     ofport->opp.port_no = odp_port_to_ofp_port(odp_port->port);
1106     memcpy(ofport->opp.hw_addr, netdev_get_etheraddr(netdev), ETH_ALEN);
1107     memcpy(ofport->opp.name, odp_port->devname,
1108            MIN(sizeof ofport->opp.name, sizeof odp_port->devname));
1109     ofport->opp.name[sizeof ofport->opp.name - 1] = '\0';
1110
1111     netdev_get_flags(netdev, &flags);
1112     ofport->opp.config = flags & NETDEV_UP ? 0 : OFPPC_PORT_DOWN;
1113
1114     netdev_get_carrier(netdev, &carrier);
1115     ofport->opp.state = carrier ? 0 : OFPPS_LINK_DOWN;
1116
1117     netdev_get_features(netdev,
1118                         &ofport->opp.curr, &ofport->opp.advertised,
1119                         &ofport->opp.supported, &ofport->opp.peer);
1120     return ofport;
1121 }
1122
1123 static bool
1124 ofport_conflicts(const struct ofproto *p, const struct odp_port *odp_port)
1125 {
1126     if (port_array_get(&p->ports, odp_port->port)) {
1127         VLOG_WARN_RL(&rl, "ignoring duplicate port %"PRIu16" in datapath",
1128                      odp_port->port);
1129         return true;
1130     } else if (shash_find(&p->port_by_name, odp_port->devname)) {
1131         VLOG_WARN_RL(&rl, "ignoring duplicate device %s in datapath",
1132                      odp_port->devname);
1133         return true;
1134     } else {
1135         return false;
1136     }
1137 }
1138
1139 static int
1140 ofport_equal(const struct ofport *a_, const struct ofport *b_)
1141 {
1142     const struct ofp_phy_port *a = &a_->opp;
1143     const struct ofp_phy_port *b = &b_->opp;
1144
1145     BUILD_ASSERT_DECL(sizeof *a == 48); /* Detect ofp_phy_port changes. */
1146     return (a->port_no == b->port_no
1147             && !memcmp(a->hw_addr, b->hw_addr, sizeof a->hw_addr)
1148             && !strcmp((char *) a->name, (char *) b->name)
1149             && a->state == b->state
1150             && a->config == b->config
1151             && a->curr == b->curr
1152             && a->advertised == b->advertised
1153             && a->supported == b->supported
1154             && a->peer == b->peer);
1155 }
1156
1157 static void
1158 send_port_status(struct ofproto *p, const struct ofport *ofport,
1159                  uint8_t reason)
1160 {
1161     /* XXX Should limit the number of queued port status change messages. */
1162     struct ofconn *ofconn;
1163     LIST_FOR_EACH (ofconn, struct ofconn, node, &p->all_conns) {
1164         struct ofp_port_status *ops;
1165         struct ofpbuf *b;
1166
1167         ops = make_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, 0, &b);
1168         ops->reason = reason;
1169         ops->desc = ofport->opp;
1170         hton_ofp_phy_port(&ops->desc);
1171         queue_tx(b, ofconn, NULL);
1172     }
1173     if (p->ofhooks->port_changed_cb) {
1174         p->ofhooks->port_changed_cb(reason, &ofport->opp, p->aux);
1175     }
1176 }
1177
1178 static void
1179 ofport_install(struct ofproto *p, struct ofport *ofport)
1180 {
1181     port_array_set(&p->ports, ofp_port_to_odp_port(ofport->opp.port_no),
1182                    ofport);
1183     shash_add(&p->port_by_name, (char *) ofport->opp.name, ofport);
1184 }
1185
1186 static void
1187 ofport_remove(struct ofproto *p, struct ofport *ofport)
1188 {
1189     port_array_set(&p->ports, ofp_port_to_odp_port(ofport->opp.port_no), NULL);
1190     shash_delete(&p->port_by_name,
1191                  shash_find(&p->port_by_name, (char *) ofport->opp.name));
1192 }
1193
1194 static void
1195 ofport_free(struct ofport *ofport)
1196 {
1197     if (ofport) {
1198         netdev_close(ofport->netdev);
1199         free(ofport);
1200     }
1201 }
1202
1203 static void
1204 update_port(struct ofproto *p, const char *devname)
1205 {
1206     struct odp_port odp_port;
1207     struct ofport *ofport;
1208     int error;
1209
1210     COVERAGE_INC(ofproto_update_port);
1211     ofport = shash_find_data(&p->port_by_name, devname);
1212     error = dpif_port_query_by_name(&p->dpif, devname, &odp_port);
1213     if (!error) {
1214         if (!ofport) {
1215             /* New port. */
1216             if (!ofport_conflicts(p, &odp_port)) {
1217                 ofport = make_ofport(&odp_port);
1218                 if (ofport) {
1219                     ofport_install(p, ofport);
1220                     send_port_status(p, ofport, OFPPR_ADD);
1221                 }
1222             }
1223         } else {
1224             /* Modified port. */
1225             struct ofport *new_ofport = make_ofport(&odp_port);
1226             if (!new_ofport) {
1227                 return;
1228             }
1229
1230             new_ofport->opp.config &= OFPPC_PORT_DOWN;
1231             new_ofport->opp.config |= ofport->opp.config & ~OFPPC_PORT_DOWN;
1232             if (ofport_equal(ofport, new_ofport)) {
1233                 /* False alarm--no change. */
1234                 ofport_free(new_ofport);
1235             } else {
1236                 ofport_remove(p, ofport);
1237                 ofport_install(p, new_ofport);
1238                 ofport_free(ofport);
1239                 send_port_status(p, new_ofport, OFPPR_MODIFY);
1240             }
1241         }
1242     } else if (error == ENOENT || error == ENODEV) {
1243         /* Deleted port. */
1244         if (ofport) {
1245             send_port_status(p, ofport, OFPPR_DELETE);
1246             ofport_remove(p, ofport);
1247             ofport_free(ofport);
1248         }
1249     } else {
1250         VLOG_WARN_RL(&rl, "dpif_port_query_by_name returned unexpected error "
1251                      "%s", strerror(error));
1252         return;
1253     }
1254     refresh_port_groups(p);
1255 }
1256
1257 static int
1258 init_ports(struct ofproto *p)
1259 {
1260     struct odp_port *ports;
1261     size_t n_ports;
1262     size_t i;
1263     int error;
1264
1265     error = dpif_port_list(&p->dpif, &ports, &n_ports);
1266     if (error) {
1267         return error;
1268     }
1269
1270     for (i = 0; i < n_ports; i++) {
1271         const struct odp_port *odp_port = &ports[i];
1272         if (!ofport_conflicts(p, odp_port)) {
1273             struct ofport *ofport = make_ofport(odp_port);
1274             if (ofport) {
1275                 ofport_install(p, ofport);
1276             }
1277         }
1278     }
1279     free(ports);
1280     refresh_port_groups(p);
1281     return 0;
1282 }
1283 \f
1284 static struct ofconn *
1285 ofconn_create(struct ofproto *p, struct rconn *rconn)
1286 {
1287     struct ofconn *ofconn = xmalloc(sizeof *ofconn);
1288     list_push_back(&p->all_conns, &ofconn->node);
1289     ofconn->rconn = rconn;
1290     ofconn->pktbuf = NULL;
1291     ofconn->send_flow_exp = false;
1292     ofconn->miss_send_len = 0;
1293     ofconn->packet_in_counter = rconn_packet_counter_create ();
1294     ofconn->reply_counter = rconn_packet_counter_create ();
1295     return ofconn;
1296 }
1297
1298 static void
1299 ofconn_destroy(struct ofconn *ofconn, struct ofproto *p)
1300 {
1301     if (p->executer) {
1302         executer_rconn_closing(p->executer, ofconn->rconn);
1303     }
1304
1305     list_remove(&ofconn->node);
1306     rconn_destroy(ofconn->rconn);
1307     rconn_packet_counter_destroy(ofconn->packet_in_counter);
1308     rconn_packet_counter_destroy(ofconn->reply_counter);
1309     pktbuf_destroy(ofconn->pktbuf);
1310     free(ofconn);
1311 }
1312
1313 static void
1314 ofconn_run(struct ofconn *ofconn, struct ofproto *p)
1315 {
1316     int iteration;
1317
1318     rconn_run(ofconn->rconn);
1319
1320     if (rconn_packet_counter_read (ofconn->reply_counter) < OFCONN_REPLY_MAX) {
1321         /* Limit the number of iterations to prevent other tasks from
1322          * starving. */
1323         for (iteration = 0; iteration < 50; iteration++) {
1324             struct ofpbuf *of_msg = rconn_recv(ofconn->rconn);
1325             if (!of_msg) {
1326                 break;
1327             }
1328             handle_openflow(ofconn, p, of_msg);
1329             ofpbuf_delete(of_msg);
1330         }
1331     }
1332
1333     if (ofconn != p->controller && !rconn_is_alive(ofconn->rconn)) {
1334         ofconn_destroy(ofconn, p);
1335     }
1336 }
1337
1338 static void
1339 ofconn_wait(struct ofconn *ofconn)
1340 {
1341     rconn_run_wait(ofconn->rconn);
1342     if (rconn_packet_counter_read (ofconn->reply_counter) < OFCONN_REPLY_MAX) {
1343         rconn_recv_wait(ofconn->rconn);
1344     } else {
1345         COVERAGE_INC(ofproto_ofconn_stuck);
1346     }
1347 }
1348 \f
1349 /* Caller is responsible for initializing the 'cr' member of the returned
1350  * rule. */
1351 static struct rule *
1352 rule_create(struct rule *super,
1353             const union ofp_action *actions, size_t n_actions,
1354             uint16_t idle_timeout, uint16_t hard_timeout)
1355 {
1356     struct rule *rule = xcalloc(1, sizeof *rule);
1357     rule->idle_timeout = idle_timeout;
1358     rule->hard_timeout = hard_timeout;
1359     rule->used = rule->created = time_msec();
1360     rule->super = super;
1361     if (super) {
1362         list_push_back(&super->list, &rule->list);
1363     } else {
1364         list_init(&rule->list);
1365     }
1366     rule->n_actions = n_actions;
1367     rule->actions = xmemdup(actions, n_actions * sizeof *actions);
1368     return rule;
1369 }
1370
1371 static struct rule *
1372 rule_from_cls_rule(const struct cls_rule *cls_rule)
1373 {
1374     return cls_rule ? CONTAINER_OF(cls_rule, struct rule, cr) : NULL;
1375 }
1376
1377 static void
1378 rule_free(struct rule *rule)
1379 {
1380     free(rule->actions);
1381     free(rule->odp_actions);
1382     free(rule);
1383 }
1384
1385 /* Destroys 'rule'.  If 'rule' is a subrule, also removes it from its
1386  * super-rule's list of subrules.  If 'rule' is a super-rule, also iterates
1387  * through all of its subrules and revalidates them, destroying any that no
1388  * longer has a super-rule (which is probably all of them).
1389  *
1390  * Before calling this function, the caller must make have removed 'rule' from
1391  * the classifier.  If 'rule' is an exact-match rule, the caller is also
1392  * responsible for ensuring that it has been uninstalled from the datapath. */
1393 static void
1394 rule_destroy(struct ofproto *ofproto, struct rule *rule)
1395 {
1396     if (!rule->super) {
1397         struct rule *subrule, *next;
1398         LIST_FOR_EACH_SAFE (subrule, next, struct rule, list, &rule->list) {
1399             revalidate_rule(ofproto, subrule);
1400         }
1401     } else {
1402         list_remove(&rule->list);
1403     }
1404     rule_free(rule);
1405 }
1406
1407 static bool
1408 rule_has_out_port(const struct rule *rule, uint16_t out_port)
1409 {
1410     const union ofp_action *oa;
1411     struct actions_iterator i;
1412
1413     if (out_port == htons(OFPP_NONE)) {
1414         return true;
1415     }
1416     for (oa = actions_first(&i, rule->actions, rule->n_actions); oa;
1417          oa = actions_next(&i)) {
1418         if (oa->type == htons(OFPAT_OUTPUT) && oa->output.port == out_port) {
1419             return true;
1420         }
1421     }
1422     return false;
1423 }
1424
1425 /* Executes the actions indicated by 'rule' on 'packet', which is in flow
1426  * 'flow' and is considered to have arrived on ODP port 'in_port'.
1427  *
1428  * The flow that 'packet' actually contains does not need to actually match
1429  * 'rule'; the actions in 'rule' will be applied to it either way.  Likewise,
1430  * the packet and byte counters for 'rule' will be credited for the packet sent
1431  * out whether or not the packet actually matches 'rule'.
1432  *
1433  * If 'rule' is an exact-match rule and 'flow' actually equals the rule's flow,
1434  * the caller must already have accurately composed ODP actions for it given
1435  * 'packet' using rule_make_actions().  If 'rule' is a wildcard rule, or if
1436  * 'rule' is an exact-match rule but 'flow' is not the rule's flow, then this
1437  * function will compose a set of ODP actions based on 'rule''s OpenFlow
1438  * actions and apply them to 'packet'. */
1439 static void
1440 rule_execute(struct ofproto *ofproto, struct rule *rule,
1441              struct ofpbuf *packet, const flow_t *flow)
1442 {
1443     const union odp_action *actions;
1444     size_t n_actions;
1445     struct odp_actions a;
1446
1447     /* Grab or compose the ODP actions.
1448      *
1449      * The special case for an exact-match 'rule' where 'flow' is not the
1450      * rule's flow is important to avoid, e.g., sending a packet out its input
1451      * port simply because the ODP actions were composed for the wrong
1452      * scenario. */
1453     if (rule->cr.wc.wildcards || !flow_equal(flow, &rule->cr.flow)) {
1454         struct rule *super = rule->super ? rule->super : rule;
1455         if (xlate_actions(super->actions, super->n_actions, flow, ofproto,
1456                           packet, &a, NULL, 0)) {
1457             return;
1458         }
1459         actions = a.actions;
1460         n_actions = a.n_actions;
1461     } else {
1462         actions = rule->odp_actions;
1463         n_actions = rule->n_odp_actions;
1464     }
1465
1466     /* Execute the ODP actions. */
1467     if (!dpif_execute(&ofproto->dpif, flow->in_port,
1468                       actions, n_actions, packet)) {
1469         struct odp_flow_stats stats;
1470         flow_extract_stats(flow, packet, &stats);
1471         update_stats(rule, &stats);
1472         rule->used = time_msec();
1473     }
1474 }
1475
1476 static void
1477 rule_insert(struct ofproto *p, struct rule *rule, struct ofpbuf *packet,
1478             uint16_t in_port)
1479 {
1480     struct rule *displaced_rule;
1481
1482     /* Insert the rule in the classifier. */
1483     displaced_rule = rule_from_cls_rule(classifier_insert(&p->cls, &rule->cr));
1484     if (!rule->cr.wc.wildcards) {
1485         rule_make_actions(p, rule, packet);
1486     }
1487
1488     /* Send the packet and credit it to the rule. */
1489     if (packet) {
1490         flow_t flow;
1491         flow_extract(packet, in_port, &flow);
1492         rule_execute(p, rule, packet, &flow);
1493     }
1494
1495     /* Install the rule in the datapath only after sending the packet, to
1496      * avoid packet reordering.  */
1497     if (rule->cr.wc.wildcards) {
1498         COVERAGE_INC(ofproto_add_wc_flow);
1499         p->need_revalidate = true;
1500     } else {
1501         rule_install(p, rule, displaced_rule);
1502     }
1503
1504     /* Free the rule that was displaced, if any. */
1505     if (displaced_rule) {
1506         rule_destroy(p, displaced_rule);
1507     }
1508 }
1509
1510 static struct rule *
1511 rule_create_subrule(struct ofproto *ofproto, struct rule *rule,
1512                     const flow_t *flow)
1513 {
1514     struct rule *subrule = rule_create(rule, NULL, 0,
1515                                        rule->idle_timeout, rule->hard_timeout);
1516     COVERAGE_INC(ofproto_subrule_create);
1517     cls_rule_from_flow(&subrule->cr, flow, 0,
1518                        (rule->cr.priority <= UINT16_MAX ? UINT16_MAX
1519                         : rule->cr.priority));
1520     classifier_insert_exact(&ofproto->cls, &subrule->cr);
1521
1522     return subrule;
1523 }
1524
1525 static void
1526 rule_remove(struct ofproto *ofproto, struct rule *rule)
1527 {
1528     if (rule->cr.wc.wildcards) {
1529         COVERAGE_INC(ofproto_del_wc_flow);
1530         ofproto->need_revalidate = true;
1531     } else {
1532         rule_uninstall(ofproto, rule);
1533     }
1534     classifier_remove(&ofproto->cls, &rule->cr);
1535     rule_destroy(ofproto, rule);
1536 }
1537
1538 /* Returns true if the actions changed, false otherwise. */
1539 static bool
1540 rule_make_actions(struct ofproto *p, struct rule *rule,
1541                   const struct ofpbuf *packet)
1542 {
1543     const struct rule *super;
1544     struct odp_actions a;
1545     size_t actions_len;
1546
1547     assert(!rule->cr.wc.wildcards);
1548
1549     super = rule->super ? rule->super : rule;
1550     rule->tags = 0;
1551     xlate_actions(super->actions, super->n_actions, &rule->cr.flow, p,
1552                   packet, &a, &rule->tags, &rule->may_install);
1553
1554     actions_len = a.n_actions * sizeof *a.actions;
1555     if (rule->n_odp_actions != a.n_actions
1556         || memcmp(rule->odp_actions, a.actions, actions_len)) {
1557         COVERAGE_INC(ofproto_odp_unchanged);
1558         free(rule->odp_actions);
1559         rule->n_odp_actions = a.n_actions;
1560         rule->odp_actions = xmemdup(a.actions, actions_len);
1561         return true;
1562     } else {
1563         return false;
1564     }
1565 }
1566
1567 static int
1568 do_put_flow(struct ofproto *ofproto, struct rule *rule, int flags,
1569             struct odp_flow_put *put)
1570 {
1571     memset(&put->flow.stats, 0, sizeof put->flow.stats);
1572     put->flow.key = rule->cr.flow;
1573     put->flow.actions = rule->odp_actions;
1574     put->flow.n_actions = rule->n_odp_actions;
1575     put->flags = flags;
1576     return dpif_flow_put(&ofproto->dpif, put);
1577 }
1578
1579 static void
1580 rule_install(struct ofproto *p, struct rule *rule, struct rule *displaced_rule)
1581 {
1582     assert(!rule->cr.wc.wildcards);
1583
1584     if (rule->may_install) {
1585         struct odp_flow_put put;
1586         if (!do_put_flow(p, rule,
1587                          ODPPF_CREATE | ODPPF_MODIFY | ODPPF_ZERO_STATS,
1588                          &put)) {
1589             rule->installed = true;
1590             if (displaced_rule) {
1591                 update_stats(rule, &put.flow.stats);
1592                 rule_post_uninstall(p, displaced_rule);
1593             }
1594         }
1595     } else if (displaced_rule) {
1596         rule_uninstall(p, displaced_rule);
1597     }
1598 }
1599
1600 static void
1601 rule_reinstall(struct ofproto *ofproto, struct rule *rule)
1602 {
1603     if (rule->installed) {
1604         struct odp_flow_put put;
1605         COVERAGE_INC(ofproto_dp_missed);
1606         do_put_flow(ofproto, rule, ODPPF_CREATE | ODPPF_MODIFY, &put);
1607     } else {
1608         rule_install(ofproto, rule, NULL);
1609     }
1610 }
1611
1612 static void
1613 rule_update_actions(struct ofproto *ofproto, struct rule *rule)
1614 {
1615     bool actions_changed = rule_make_actions(ofproto, rule, NULL);
1616     if (rule->may_install) {
1617         if (rule->installed) {
1618             if (actions_changed) {
1619                 /* XXX should really do rule_post_uninstall() for the *old* set
1620                  * of actions, and distinguish the old stats from the new. */
1621                 struct odp_flow_put put;
1622                 do_put_flow(ofproto, rule, ODPPF_CREATE | ODPPF_MODIFY, &put);
1623             }
1624         } else {
1625             rule_install(ofproto, rule, NULL);
1626         }
1627     } else {
1628         rule_uninstall(ofproto, rule);
1629     }
1630 }
1631
1632 static void
1633 rule_account(struct ofproto *ofproto, struct rule *rule, uint64_t extra_bytes)
1634 {
1635     uint64_t total_bytes = rule->byte_count + extra_bytes;
1636
1637     if (ofproto->ofhooks->account_flow_cb
1638         && total_bytes > rule->accounted_bytes)
1639     {
1640         ofproto->ofhooks->account_flow_cb(
1641             &rule->cr.flow, rule->odp_actions, rule->n_odp_actions,
1642             total_bytes - rule->accounted_bytes, ofproto->aux);
1643         rule->accounted_bytes = total_bytes;
1644     }
1645 }
1646
1647 static void
1648 rule_uninstall(struct ofproto *p, struct rule *rule)
1649 {
1650     assert(!rule->cr.wc.wildcards);
1651     if (rule->installed) {
1652         struct odp_flow odp_flow;
1653
1654         odp_flow.key = rule->cr.flow;
1655         odp_flow.actions = NULL;
1656         odp_flow.n_actions = 0;
1657         if (!dpif_flow_del(&p->dpif, &odp_flow)) {
1658             update_stats(rule, &odp_flow.stats);
1659         }
1660         rule->installed = false;
1661
1662         rule_post_uninstall(p, rule);
1663     }
1664 }
1665
1666 static void
1667 rule_post_uninstall(struct ofproto *ofproto, struct rule *rule)
1668 {
1669     struct rule *super = rule->super;
1670
1671     rule_account(ofproto, rule, 0);
1672     if (ofproto->netflow) {
1673         struct ofexpired expired;
1674         expired.flow = rule->cr.flow;
1675         expired.packet_count = rule->packet_count;
1676         expired.byte_count = rule->byte_count;
1677         expired.used = rule->used;
1678         expired.created = rule->created;
1679         expired.tcp_flags = rule->tcp_flags;
1680         expired.ip_tos = rule->ip_tos;
1681         netflow_expire(ofproto->netflow, &expired);
1682     }
1683     if (super) {
1684         super->packet_count += rule->packet_count;
1685         super->byte_count += rule->byte_count;
1686         super->tcp_flags |= rule->tcp_flags;
1687         if (rule->packet_count) {
1688             super->ip_tos = rule->ip_tos;
1689         }
1690     }
1691
1692     /* Reset counters to prevent double counting if the rule ever gets
1693      * reinstalled. */
1694     rule->packet_count = 0;
1695     rule->byte_count = 0;
1696     rule->accounted_bytes = 0;
1697     rule->tcp_flags = 0;
1698     rule->ip_tos = 0;
1699 }
1700 \f
1701 static void
1702 queue_tx(struct ofpbuf *msg, const struct ofconn *ofconn,
1703          struct rconn_packet_counter *counter)
1704 {
1705     update_openflow_length(msg);
1706     if (rconn_send(ofconn->rconn, msg, counter)) {
1707         ofpbuf_delete(msg);
1708     }
1709 }
1710
1711 static void
1712 send_error(const struct ofconn *ofconn, const struct ofp_header *oh,
1713            int error, const void *data, size_t len)
1714 {
1715     struct ofpbuf *buf;
1716     struct ofp_error_msg *oem;
1717
1718     if (!(error >> 16)) {
1719         VLOG_WARN_RL(&rl, "not sending bad error code %d to controller",
1720                      error);
1721         return;
1722     }
1723
1724     COVERAGE_INC(ofproto_error);
1725     oem = make_openflow_xid(len + sizeof *oem, OFPT_ERROR,
1726                             oh ? oh->xid : 0, &buf);
1727     oem->type = htons((unsigned int) error >> 16);
1728     oem->code = htons(error & 0xffff);
1729     memcpy(oem->data, data, len);
1730     queue_tx(buf, ofconn, ofconn->reply_counter);
1731 }
1732
1733 static void
1734 send_error_oh(const struct ofconn *ofconn, const struct ofp_header *oh,
1735               int error)
1736 {
1737     size_t oh_length = ntohs(oh->length);
1738     send_error(ofconn, oh, error, oh, MIN(oh_length, 64));
1739 }
1740
1741 static void
1742 hton_ofp_phy_port(struct ofp_phy_port *opp)
1743 {
1744     opp->port_no = htons(opp->port_no);
1745     opp->config = htonl(opp->config);
1746     opp->state = htonl(opp->state);
1747     opp->curr = htonl(opp->curr);
1748     opp->advertised = htonl(opp->advertised);
1749     opp->supported = htonl(opp->supported);
1750     opp->peer = htonl(opp->peer);
1751 }
1752
1753 static int
1754 handle_echo_request(struct ofconn *ofconn, struct ofp_header *oh)
1755 {
1756     struct ofp_header *rq = oh;
1757     queue_tx(make_echo_reply(rq), ofconn, ofconn->reply_counter);
1758     return 0;
1759 }
1760
1761 static int
1762 handle_features_request(struct ofproto *p, struct ofconn *ofconn,
1763                         struct ofp_header *oh)
1764 {
1765     struct ofp_switch_features *osf;
1766     struct ofpbuf *buf;
1767     unsigned int port_no;
1768     struct ofport *port;
1769
1770     osf = make_openflow_xid(sizeof *osf, OFPT_FEATURES_REPLY, oh->xid, &buf);
1771     osf->datapath_id = htonll(p->datapath_id);
1772     osf->n_buffers = htonl(pktbuf_capacity());
1773     osf->n_tables = 2;
1774     osf->capabilities = htonl(OFPC_FLOW_STATS | OFPC_TABLE_STATS |
1775                               OFPC_PORT_STATS | OFPC_MULTI_PHY_TX);
1776     osf->actions = htonl((1u << OFPAT_OUTPUT) |
1777                          (1u << OFPAT_SET_VLAN_VID) |
1778                          (1u << OFPAT_SET_VLAN_PCP) |
1779                          (1u << OFPAT_STRIP_VLAN) |
1780                          (1u << OFPAT_SET_DL_SRC) |
1781                          (1u << OFPAT_SET_DL_DST) |
1782                          (1u << OFPAT_SET_NW_SRC) |
1783                          (1u << OFPAT_SET_NW_DST) |
1784                          (1u << OFPAT_SET_TP_SRC) |
1785                          (1u << OFPAT_SET_TP_DST));
1786
1787     PORT_ARRAY_FOR_EACH (port, &p->ports, port_no) {
1788         hton_ofp_phy_port(ofpbuf_put(buf, &port->opp, sizeof port->opp));
1789     }
1790
1791     queue_tx(buf, ofconn, ofconn->reply_counter);
1792     return 0;
1793 }
1794
1795 static int
1796 handle_get_config_request(struct ofproto *p, struct ofconn *ofconn,
1797                           struct ofp_header *oh)
1798 {
1799     struct ofpbuf *buf;
1800     struct ofp_switch_config *osc;
1801     uint16_t flags;
1802     bool drop_frags;
1803
1804     /* Figure out flags. */
1805     dpif_get_drop_frags(&p->dpif, &drop_frags);
1806     flags = drop_frags ? OFPC_FRAG_DROP : OFPC_FRAG_NORMAL;
1807     if (ofconn->send_flow_exp) {
1808         flags |= OFPC_SEND_FLOW_EXP;
1809     }
1810
1811     /* Send reply. */
1812     osc = make_openflow_xid(sizeof *osc, OFPT_GET_CONFIG_REPLY, oh->xid, &buf);
1813     osc->flags = htons(flags);
1814     osc->miss_send_len = htons(ofconn->miss_send_len);
1815     queue_tx(buf, ofconn, ofconn->reply_counter);
1816
1817     return 0;
1818 }
1819
1820 static int
1821 handle_set_config(struct ofproto *p, struct ofconn *ofconn,
1822                   struct ofp_switch_config *osc)
1823 {
1824     uint16_t flags;
1825     int error;
1826
1827     error = check_ofp_message(&osc->header, OFPT_SET_CONFIG, sizeof *osc);
1828     if (error) {
1829         return error;
1830     }
1831     flags = ntohs(osc->flags);
1832
1833     ofconn->send_flow_exp = (flags & OFPC_SEND_FLOW_EXP) != 0;
1834
1835     if (ofconn == p->controller) {
1836         switch (flags & OFPC_FRAG_MASK) {
1837         case OFPC_FRAG_NORMAL:
1838             dpif_set_drop_frags(&p->dpif, false);
1839             break;
1840         case OFPC_FRAG_DROP:
1841             dpif_set_drop_frags(&p->dpif, true);
1842             break;
1843         default:
1844             VLOG_WARN_RL(&rl, "requested bad fragment mode (flags=%"PRIx16")",
1845                          osc->flags);
1846             break;
1847         }
1848     }
1849
1850     if ((ntohs(osc->miss_send_len) != 0) != (ofconn->miss_send_len != 0)) {
1851         if (ntohs(osc->miss_send_len) != 0) {
1852             ofconn->pktbuf = pktbuf_create();
1853         } else {
1854             pktbuf_destroy(ofconn->pktbuf);
1855         }
1856     }
1857
1858     ofconn->miss_send_len = ntohs(osc->miss_send_len);
1859
1860     return 0;
1861 }
1862
1863 static void
1864 add_output_group_action(struct odp_actions *actions, uint16_t group)
1865 {
1866     odp_actions_add(actions, ODPAT_OUTPUT_GROUP)->output_group.group = group;
1867 }
1868
1869 static void
1870 add_controller_action(struct odp_actions *actions,
1871                       const struct ofp_action_output *oao)
1872 {
1873     union odp_action *a = odp_actions_add(actions, ODPAT_CONTROLLER);
1874     a->controller.arg = oao->max_len ? ntohs(oao->max_len) : UINT32_MAX;
1875 }
1876
1877 struct action_xlate_ctx {
1878     /* Input. */
1879     const flow_t *flow;         /* Flow to which these actions correspond. */
1880     int recurse;                /* Recursion level, via xlate_table_action. */
1881     struct ofproto *ofproto;
1882     const struct ofpbuf *packet; /* The packet corresponding to 'flow', or a
1883                                   * null pointer if we are revalidating
1884                                   * without a packet to refer to. */
1885
1886     /* Output. */
1887     struct odp_actions *out;    /* Datapath actions. */
1888     tag_type *tags;             /* Tags associated with OFPP_NORMAL actions. */
1889     bool may_setup_flow;        /* True ordinarily; false if the actions must
1890                                  * be reassessed for every packet. */
1891 };
1892
1893 static void do_xlate_actions(const union ofp_action *in, size_t n_in,
1894                              struct action_xlate_ctx *ctx);
1895
1896 static void
1897 add_output_action(struct action_xlate_ctx *ctx, uint16_t port)
1898 {
1899     const struct ofport *ofport = port_array_get(&ctx->ofproto->ports, port);
1900     if (!ofport || !(ofport->opp.config & OFPPC_NO_FWD)) {
1901         odp_actions_add(ctx->out, ODPAT_OUTPUT)->output.port = port;
1902     }
1903 }
1904
1905 static struct rule *
1906 lookup_valid_rule(struct ofproto *ofproto, const flow_t *flow)
1907 {
1908     struct rule *rule;
1909     rule = rule_from_cls_rule(classifier_lookup(&ofproto->cls, flow));
1910
1911     /* The rule we found might not be valid, since we could be in need of
1912      * revalidation.  If it is not valid, don't return it. */
1913     if (rule
1914         && rule->super
1915         && ofproto->need_revalidate
1916         && !revalidate_rule(ofproto, rule)) {
1917         COVERAGE_INC(ofproto_invalidated);
1918         return NULL;
1919     }
1920
1921     return rule;
1922 }
1923
1924 static void
1925 xlate_table_action(struct action_xlate_ctx *ctx, uint16_t in_port)
1926 {
1927     if (!ctx->recurse) {
1928         struct rule *rule;
1929         flow_t flow;
1930
1931         flow = *ctx->flow;
1932         flow.in_port = in_port;
1933
1934         rule = lookup_valid_rule(ctx->ofproto, &flow);
1935         if (rule) {
1936             if (rule->super) {
1937                 rule = rule->super;
1938             }
1939
1940             ctx->recurse++;
1941             do_xlate_actions(rule->actions, rule->n_actions, ctx);
1942             ctx->recurse--;
1943         }
1944     }
1945 }
1946
1947 static void
1948 xlate_output_action(struct action_xlate_ctx *ctx,
1949                     const struct ofp_action_output *oao)
1950 {
1951     uint16_t odp_port;
1952
1953     switch (ntohs(oao->port)) {
1954     case OFPP_IN_PORT:
1955         add_output_action(ctx, ctx->flow->in_port);
1956         break;
1957     case OFPP_TABLE:
1958         xlate_table_action(ctx, ctx->flow->in_port);
1959         break;
1960     case OFPP_NORMAL:
1961         if (!ctx->ofproto->ofhooks->normal_cb(ctx->flow, ctx->packet,
1962                                               ctx->out, ctx->tags,
1963                                               ctx->ofproto->aux)) {
1964             COVERAGE_INC(ofproto_uninstallable);
1965             ctx->may_setup_flow = false;
1966         }
1967         break;
1968     case OFPP_FLOOD:
1969         add_output_group_action(ctx->out, DP_GROUP_FLOOD);
1970         break;
1971     case OFPP_ALL:
1972         add_output_group_action(ctx->out, DP_GROUP_ALL);
1973         break;
1974     case OFPP_CONTROLLER:
1975         add_controller_action(ctx->out, oao);
1976         break;
1977     case OFPP_LOCAL:
1978         add_output_action(ctx, ODPP_LOCAL);
1979         break;
1980     default:
1981         odp_port = ofp_port_to_odp_port(ntohs(oao->port));
1982         if (odp_port != ctx->flow->in_port) {
1983             add_output_action(ctx, odp_port);
1984         }
1985         break;
1986     }
1987 }
1988
1989 static void
1990 xlate_nicira_action(struct action_xlate_ctx *ctx,
1991                     const struct nx_action_header *nah)
1992 {
1993     const struct nx_action_resubmit *nar;
1994     int subtype = ntohs(nah->subtype);
1995
1996     assert(nah->vendor == htonl(NX_VENDOR_ID));
1997     switch (subtype) {
1998     case NXAST_RESUBMIT:
1999         nar = (const struct nx_action_resubmit *) nah;
2000         xlate_table_action(ctx, ofp_port_to_odp_port(ntohs(nar->in_port)));
2001         break;
2002
2003     default:
2004         VLOG_DBG_RL(&rl, "unknown Nicira action type %"PRIu16, subtype);
2005         break;
2006     }
2007 }
2008
2009 static void
2010 do_xlate_actions(const union ofp_action *in, size_t n_in,
2011                  struct action_xlate_ctx *ctx)
2012 {
2013     struct actions_iterator iter;
2014     const union ofp_action *ia;
2015     const struct ofport *port;
2016
2017     port = port_array_get(&ctx->ofproto->ports, ctx->flow->in_port);
2018     if (port && port->opp.config & (OFPPC_NO_RECV | OFPPC_NO_RECV_STP) &&
2019         port->opp.config & (eth_addr_equals(ctx->flow->dl_dst, stp_eth_addr)
2020                             ? OFPPC_NO_RECV_STP : OFPPC_NO_RECV)) {
2021         /* Drop this flow. */
2022         return;
2023     }
2024
2025     for (ia = actions_first(&iter, in, n_in); ia; ia = actions_next(&iter)) {
2026         uint16_t type = ntohs(ia->type);
2027         union odp_action *oa;
2028
2029         switch (type) {
2030         case OFPAT_OUTPUT:
2031             xlate_output_action(ctx, &ia->output);
2032             break;
2033
2034         case OFPAT_SET_VLAN_VID:
2035             oa = odp_actions_add(ctx->out, ODPAT_SET_VLAN_VID);
2036             oa->vlan_vid.vlan_vid = ia->vlan_vid.vlan_vid;
2037             break;
2038
2039         case OFPAT_SET_VLAN_PCP:
2040             oa = odp_actions_add(ctx->out, ODPAT_SET_VLAN_PCP);
2041             oa->vlan_pcp.vlan_pcp = ia->vlan_pcp.vlan_pcp;
2042             break;
2043
2044         case OFPAT_STRIP_VLAN:
2045             odp_actions_add(ctx->out, ODPAT_STRIP_VLAN);
2046             break;
2047
2048         case OFPAT_SET_DL_SRC:
2049             oa = odp_actions_add(ctx->out, ODPAT_SET_DL_SRC);
2050             memcpy(oa->dl_addr.dl_addr,
2051                    ((struct ofp_action_dl_addr *) ia)->dl_addr, ETH_ADDR_LEN);
2052             break;
2053
2054         case OFPAT_SET_DL_DST:
2055             oa = odp_actions_add(ctx->out, ODPAT_SET_DL_DST);
2056             memcpy(oa->dl_addr.dl_addr,
2057                    ((struct ofp_action_dl_addr *) ia)->dl_addr, ETH_ADDR_LEN);
2058             break;
2059
2060         case OFPAT_SET_NW_SRC:
2061             oa = odp_actions_add(ctx->out, ODPAT_SET_NW_SRC);
2062             oa->nw_addr.nw_addr = ia->nw_addr.nw_addr;
2063             break;
2064
2065         case OFPAT_SET_TP_SRC:
2066             oa = odp_actions_add(ctx->out, ODPAT_SET_TP_SRC);
2067             oa->tp_port.tp_port = ia->tp_port.tp_port;
2068             break;
2069
2070         case OFPAT_VENDOR:
2071             xlate_nicira_action(ctx, (const struct nx_action_header *) ia);
2072             break;
2073
2074         default:
2075             VLOG_DBG_RL(&rl, "unknown action type %"PRIu16, type);
2076             break;
2077         }
2078     }
2079 }
2080
2081 static int
2082 xlate_actions(const union ofp_action *in, size_t n_in,
2083               const flow_t *flow, struct ofproto *ofproto,
2084               const struct ofpbuf *packet,
2085               struct odp_actions *out, tag_type *tags, bool *may_setup_flow)
2086 {
2087     tag_type no_tags = 0;
2088     struct action_xlate_ctx ctx;
2089     COVERAGE_INC(ofproto_ofp2odp);
2090     odp_actions_init(out);
2091     ctx.flow = flow;
2092     ctx.recurse = 0;
2093     ctx.ofproto = ofproto;
2094     ctx.packet = packet;
2095     ctx.out = out;
2096     ctx.tags = tags ? tags : &no_tags;
2097     ctx.may_setup_flow = true;
2098     do_xlate_actions(in, n_in, &ctx);
2099     if (may_setup_flow) {
2100         *may_setup_flow = ctx.may_setup_flow;
2101     }
2102     if (odp_actions_overflow(out)) {
2103         odp_actions_init(out);
2104         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_TOO_MANY);
2105     }
2106     return 0;
2107 }
2108
2109 static int
2110 handle_packet_out(struct ofproto *p, struct ofconn *ofconn,
2111                   struct ofp_header *oh)
2112 {
2113     struct ofp_packet_out *opo;
2114     struct ofpbuf payload, *buffer;
2115     struct odp_actions actions;
2116     int n_actions;
2117     uint16_t in_port;
2118     flow_t flow;
2119     int error;
2120
2121     error = check_ofp_packet_out(oh, &payload, &n_actions, p->max_ports);
2122     if (error) {
2123         return error;
2124     }
2125     opo = (struct ofp_packet_out *) oh;
2126
2127     COVERAGE_INC(ofproto_packet_out);
2128     if (opo->buffer_id != htonl(UINT32_MAX)) {
2129         error = pktbuf_retrieve(ofconn->pktbuf, ntohl(opo->buffer_id),
2130                                 &buffer, &in_port);
2131         if (error) {
2132             return error;
2133         }
2134         payload = *buffer;
2135     } else {
2136         buffer = NULL;
2137     }
2138
2139     flow_extract(&payload, ofp_port_to_odp_port(ntohs(opo->in_port)), &flow);
2140     error = xlate_actions((const union ofp_action *) opo->actions, n_actions,
2141                           &flow, p, &payload, &actions, NULL, NULL);
2142     if (error) {
2143         return error;
2144     }
2145
2146     dpif_execute(&p->dpif, flow.in_port, actions.actions, actions.n_actions,
2147                  &payload);
2148     ofpbuf_delete(buffer);
2149
2150     return 0;
2151 }
2152
2153 static void
2154 update_port_config(struct ofproto *p, struct ofport *port,
2155                    uint32_t config, uint32_t mask)
2156 {
2157     mask &= config ^ port->opp.config;
2158     if (mask & OFPPC_PORT_DOWN) {
2159         if (config & OFPPC_PORT_DOWN) {
2160             netdev_turn_flags_off(port->netdev, NETDEV_UP, true);
2161         } else {
2162             netdev_turn_flags_on(port->netdev, NETDEV_UP, true);
2163         }
2164     }
2165 #define REVALIDATE_BITS (OFPPC_NO_RECV | OFPPC_NO_RECV_STP | OFPPC_NO_FWD)
2166     if (mask & REVALIDATE_BITS) {
2167         COVERAGE_INC(ofproto_costly_flags);
2168         port->opp.config ^= mask & REVALIDATE_BITS;
2169         p->need_revalidate = true;
2170     }
2171 #undef REVALIDATE_BITS
2172     if (mask & OFPPC_NO_FLOOD) {
2173         port->opp.config ^= OFPPC_NO_FLOOD;
2174         refresh_port_group(p, DP_GROUP_FLOOD);
2175     }
2176     if (mask & OFPPC_NO_PACKET_IN) {
2177         port->opp.config ^= OFPPC_NO_PACKET_IN;
2178     }
2179 }
2180
2181 static int
2182 handle_port_mod(struct ofproto *p, struct ofp_header *oh)
2183 {
2184     const struct ofp_port_mod *opm;
2185     struct ofport *port;
2186     int error;
2187
2188     error = check_ofp_message(oh, OFPT_PORT_MOD, sizeof *opm);
2189     if (error) {
2190         return error;
2191     }
2192     opm = (struct ofp_port_mod *) oh;
2193
2194     port = port_array_get(&p->ports,
2195                           ofp_port_to_odp_port(ntohs(opm->port_no)));
2196     if (!port) {
2197         return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_PORT);
2198     } else if (memcmp(port->opp.hw_addr, opm->hw_addr, OFP_ETH_ALEN)) {
2199         return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_HW_ADDR);
2200     } else {
2201         update_port_config(p, port, ntohl(opm->config), ntohl(opm->mask));
2202         if (opm->advertise) {
2203             netdev_set_advertisements(port->netdev, ntohl(opm->advertise));
2204         }
2205     }
2206     return 0;
2207 }
2208
2209 static struct ofpbuf *
2210 make_stats_reply(uint32_t xid, uint16_t type, size_t body_len)
2211 {
2212     struct ofp_stats_reply *osr;
2213     struct ofpbuf *msg;
2214
2215     msg = ofpbuf_new(MIN(sizeof *osr + body_len, UINT16_MAX));
2216     osr = put_openflow_xid(sizeof *osr, OFPT_STATS_REPLY, xid, msg);
2217     osr->type = type;
2218     osr->flags = htons(0);
2219     return msg;
2220 }
2221
2222 static struct ofpbuf *
2223 start_stats_reply(const struct ofp_stats_request *request, size_t body_len)
2224 {
2225     return make_stats_reply(request->header.xid, request->type, body_len);
2226 }
2227
2228 static void *
2229 append_stats_reply(size_t nbytes, struct ofconn *ofconn, struct ofpbuf **msgp)
2230 {
2231     struct ofpbuf *msg = *msgp;
2232     assert(nbytes <= UINT16_MAX - sizeof(struct ofp_stats_reply));
2233     if (nbytes + msg->size > UINT16_MAX) {
2234         struct ofp_stats_reply *reply = msg->data;
2235         reply->flags = htons(OFPSF_REPLY_MORE);
2236         *msgp = make_stats_reply(reply->header.xid, reply->type, nbytes);
2237         queue_tx(msg, ofconn, ofconn->reply_counter);
2238     }
2239     return ofpbuf_put_uninit(*msgp, nbytes);
2240 }
2241
2242 static int
2243 handle_desc_stats_request(struct ofproto *p, struct ofconn *ofconn,
2244                            struct ofp_stats_request *request)
2245 {
2246     struct ofp_desc_stats *ods;
2247     struct ofpbuf *msg;
2248
2249     msg = start_stats_reply(request, sizeof *ods);
2250     ods = append_stats_reply(sizeof *ods, ofconn, &msg);
2251     strncpy(ods->mfr_desc, p->manufacturer, sizeof ods->mfr_desc);
2252     strncpy(ods->hw_desc, p->hardware, sizeof ods->hw_desc);
2253     strncpy(ods->sw_desc, p->software, sizeof ods->sw_desc);
2254     strncpy(ods->serial_num, p->serial, sizeof ods->serial_num);
2255     queue_tx(msg, ofconn, ofconn->reply_counter);
2256
2257     return 0;
2258 }
2259
2260 static void
2261 count_subrules(struct cls_rule *cls_rule, void *n_subrules_)
2262 {
2263     struct rule *rule = rule_from_cls_rule(cls_rule);
2264     int *n_subrules = n_subrules_;
2265
2266     if (rule->super) {
2267         (*n_subrules)++;
2268     }
2269 }
2270
2271 static int
2272 handle_table_stats_request(struct ofproto *p, struct ofconn *ofconn,
2273                            struct ofp_stats_request *request)
2274 {
2275     struct ofp_table_stats *ots;
2276     struct ofpbuf *msg;
2277     struct odp_stats dpstats;
2278     int n_exact, n_subrules, n_wild;
2279
2280     msg = start_stats_reply(request, sizeof *ots * 2);
2281
2282     /* Count rules of various kinds. */
2283     n_subrules = 0;
2284     classifier_for_each(&p->cls, CLS_INC_EXACT, count_subrules, &n_subrules);
2285     n_exact = classifier_count_exact(&p->cls) - n_subrules;
2286     n_wild = classifier_count(&p->cls) - classifier_count_exact(&p->cls);
2287
2288     /* Hash table. */
2289     dpif_get_dp_stats(&p->dpif, &dpstats);
2290     ots = append_stats_reply(sizeof *ots, ofconn, &msg);
2291     memset(ots, 0, sizeof *ots);
2292     ots->table_id = TABLEID_HASH;
2293     strcpy(ots->name, "hash");
2294     ots->wildcards = htonl(0);
2295     ots->max_entries = htonl(dpstats.max_capacity);
2296     ots->active_count = htonl(n_exact);
2297     ots->lookup_count = htonll(dpstats.n_frags + dpstats.n_hit +
2298                                dpstats.n_missed);
2299     ots->matched_count = htonll(dpstats.n_hit); /* XXX */
2300
2301     /* Classifier table. */
2302     ots = append_stats_reply(sizeof *ots, ofconn, &msg);
2303     memset(ots, 0, sizeof *ots);
2304     ots->table_id = TABLEID_CLASSIFIER;
2305     strcpy(ots->name, "classifier");
2306     ots->wildcards = htonl(OFPFW_ALL);
2307     ots->max_entries = htonl(65536);
2308     ots->active_count = htonl(n_wild);
2309     ots->lookup_count = htonll(0);              /* XXX */
2310     ots->matched_count = htonll(0);             /* XXX */
2311
2312     queue_tx(msg, ofconn, ofconn->reply_counter);
2313     return 0;
2314 }
2315
2316 static int
2317 handle_port_stats_request(struct ofproto *p, struct ofconn *ofconn,
2318                           struct ofp_stats_request *request)
2319 {
2320     struct ofp_port_stats *ops;
2321     struct ofpbuf *msg;
2322     struct ofport *port;
2323     unsigned int port_no;
2324
2325     msg = start_stats_reply(request, sizeof *ops * 16);
2326     PORT_ARRAY_FOR_EACH (port, &p->ports, port_no) {
2327         struct netdev_stats stats;
2328
2329         /* Intentionally ignore return value, since errors will set 'stats' to
2330          * all-1s, which is correct for OpenFlow, and netdev_get_stats() will
2331          * log errors. */
2332         netdev_get_stats(port->netdev, &stats);
2333
2334         ops = append_stats_reply(sizeof *ops, ofconn, &msg);
2335         ops->port_no = htons(odp_port_to_ofp_port(port_no));
2336         memset(ops->pad, 0, sizeof ops->pad);
2337         ops->rx_packets = htonll(stats.rx_packets);
2338         ops->tx_packets = htonll(stats.tx_packets);
2339         ops->rx_bytes = htonll(stats.rx_bytes);
2340         ops->tx_bytes = htonll(stats.tx_bytes);
2341         ops->rx_dropped = htonll(stats.rx_dropped);
2342         ops->tx_dropped = htonll(stats.tx_dropped);
2343         ops->rx_errors = htonll(stats.rx_errors);
2344         ops->tx_errors = htonll(stats.tx_errors);
2345         ops->rx_frame_err = htonll(stats.rx_frame_errors);
2346         ops->rx_over_err = htonll(stats.rx_over_errors);
2347         ops->rx_crc_err = htonll(stats.rx_crc_errors);
2348         ops->collisions = htonll(stats.collisions);
2349     }
2350
2351     queue_tx(msg, ofconn, ofconn->reply_counter);
2352     return 0;
2353 }
2354
2355 struct flow_stats_cbdata {
2356     struct ofproto *ofproto;
2357     struct ofconn *ofconn;
2358     uint16_t out_port;
2359     struct ofpbuf *msg;
2360 };
2361
2362 static void
2363 query_stats(struct ofproto *p, struct rule *rule,
2364             uint64_t *packet_countp, uint64_t *byte_countp)
2365 {
2366     uint64_t packet_count, byte_count;
2367     struct rule *subrule;
2368     struct odp_flow *odp_flows;
2369     size_t n_odp_flows;
2370
2371     n_odp_flows = rule->cr.wc.wildcards ? list_size(&rule->list) : 1;
2372     odp_flows = xcalloc(1, n_odp_flows * sizeof *odp_flows);
2373     if (rule->cr.wc.wildcards) {
2374         size_t i = 0;
2375         LIST_FOR_EACH (subrule, struct rule, list, &rule->list) {
2376             odp_flows[i++].key = subrule->cr.flow;
2377         }
2378     } else {
2379         odp_flows[0].key = rule->cr.flow;
2380     }
2381
2382     packet_count = rule->packet_count;
2383     byte_count = rule->byte_count;
2384     if (!dpif_flow_get_multiple(&p->dpif, odp_flows, n_odp_flows)) {
2385         size_t i;
2386         for (i = 0; i < n_odp_flows; i++) {
2387             struct odp_flow *odp_flow = &odp_flows[i];
2388             packet_count += odp_flow->stats.n_packets;
2389             byte_count += odp_flow->stats.n_bytes;
2390         }
2391     }
2392     free(odp_flows);
2393
2394     *packet_countp = packet_count;
2395     *byte_countp = byte_count;
2396 }
2397
2398 static void
2399 flow_stats_cb(struct cls_rule *rule_, void *cbdata_)
2400 {
2401     struct rule *rule = rule_from_cls_rule(rule_);
2402     struct flow_stats_cbdata *cbdata = cbdata_;
2403     struct ofp_flow_stats *ofs;
2404     uint64_t packet_count, byte_count;
2405     size_t act_len, len;
2406
2407     if (rule_is_hidden(rule) || !rule_has_out_port(rule, cbdata->out_port)) {
2408         return;
2409     }
2410
2411     act_len = sizeof *rule->actions * rule->n_actions;
2412     len = offsetof(struct ofp_flow_stats, actions) + act_len;
2413
2414     query_stats(cbdata->ofproto, rule, &packet_count, &byte_count);
2415
2416     ofs = append_stats_reply(len, cbdata->ofconn, &cbdata->msg);
2417     ofs->length = htons(len);
2418     ofs->table_id = rule->cr.wc.wildcards ? TABLEID_CLASSIFIER : TABLEID_HASH;
2419     ofs->pad = 0;
2420     flow_to_match(&rule->cr.flow, rule->cr.wc.wildcards, &ofs->match);
2421     ofs->duration = htonl((time_msec() - rule->created) / 1000);
2422     ofs->priority = htons(rule->cr.priority);
2423     ofs->idle_timeout = htons(rule->idle_timeout);
2424     ofs->hard_timeout = htons(rule->hard_timeout);
2425     memset(ofs->pad2, 0, sizeof ofs->pad2);
2426     ofs->packet_count = htonll(packet_count);
2427     ofs->byte_count = htonll(byte_count);
2428     memcpy(ofs->actions, rule->actions, act_len);
2429 }
2430
2431 static int
2432 table_id_to_include(uint8_t table_id)
2433 {
2434     return (table_id == TABLEID_HASH ? CLS_INC_EXACT
2435             : table_id == TABLEID_CLASSIFIER ? CLS_INC_WILD
2436             : table_id == 0xff ? CLS_INC_ALL
2437             : 0);
2438 }
2439
2440 static int
2441 handle_flow_stats_request(struct ofproto *p, struct ofconn *ofconn,
2442                           const struct ofp_stats_request *osr,
2443                           size_t arg_size)
2444 {
2445     struct ofp_flow_stats_request *fsr;
2446     struct flow_stats_cbdata cbdata;
2447     struct cls_rule target;
2448
2449     if (arg_size != sizeof *fsr) {
2450         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
2451     }
2452     fsr = (struct ofp_flow_stats_request *) osr->body;
2453
2454     COVERAGE_INC(ofproto_flows_req);
2455     cbdata.ofproto = p;
2456     cbdata.ofconn = ofconn;
2457     cbdata.out_port = fsr->out_port;
2458     cbdata.msg = start_stats_reply(osr, 1024);
2459     cls_rule_from_match(&target, &fsr->match, 0);
2460     classifier_for_each_match(&p->cls, &target,
2461                               table_id_to_include(fsr->table_id),
2462                               flow_stats_cb, &cbdata);
2463     queue_tx(cbdata.msg, ofconn, ofconn->reply_counter);
2464     return 0;
2465 }
2466
2467 struct aggregate_stats_cbdata {
2468     struct ofproto *ofproto;
2469     uint16_t out_port;
2470     uint64_t packet_count;
2471     uint64_t byte_count;
2472     uint32_t n_flows;
2473 };
2474
2475 static void
2476 aggregate_stats_cb(struct cls_rule *rule_, void *cbdata_)
2477 {
2478     struct rule *rule = rule_from_cls_rule(rule_);
2479     struct aggregate_stats_cbdata *cbdata = cbdata_;
2480     uint64_t packet_count, byte_count;
2481
2482     if (rule_is_hidden(rule) || !rule_has_out_port(rule, cbdata->out_port)) {
2483         return;
2484     }
2485
2486     query_stats(cbdata->ofproto, rule, &packet_count, &byte_count);
2487
2488     cbdata->packet_count += packet_count;
2489     cbdata->byte_count += byte_count;
2490     cbdata->n_flows++;
2491 }
2492
2493 static int
2494 handle_aggregate_stats_request(struct ofproto *p, struct ofconn *ofconn,
2495                                const struct ofp_stats_request *osr,
2496                                size_t arg_size)
2497 {
2498     struct ofp_aggregate_stats_request *asr;
2499     struct ofp_aggregate_stats_reply *reply;
2500     struct aggregate_stats_cbdata cbdata;
2501     struct cls_rule target;
2502     struct ofpbuf *msg;
2503
2504     if (arg_size != sizeof *asr) {
2505         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
2506     }
2507     asr = (struct ofp_aggregate_stats_request *) osr->body;
2508
2509     COVERAGE_INC(ofproto_agg_request);
2510     cbdata.ofproto = p;
2511     cbdata.out_port = asr->out_port;
2512     cbdata.packet_count = 0;
2513     cbdata.byte_count = 0;
2514     cbdata.n_flows = 0;
2515     cls_rule_from_match(&target, &asr->match, 0);
2516     classifier_for_each_match(&p->cls, &target,
2517                               table_id_to_include(asr->table_id),
2518                               aggregate_stats_cb, &cbdata);
2519
2520     msg = start_stats_reply(osr, sizeof *reply);
2521     reply = append_stats_reply(sizeof *reply, ofconn, &msg);
2522     reply->flow_count = htonl(cbdata.n_flows);
2523     reply->packet_count = htonll(cbdata.packet_count);
2524     reply->byte_count = htonll(cbdata.byte_count);
2525     queue_tx(msg, ofconn, ofconn->reply_counter);
2526     return 0;
2527 }
2528
2529 static int
2530 handle_stats_request(struct ofproto *p, struct ofconn *ofconn,
2531                      struct ofp_header *oh)
2532 {
2533     struct ofp_stats_request *osr;
2534     size_t arg_size;
2535     int error;
2536
2537     error = check_ofp_message_array(oh, OFPT_STATS_REQUEST, sizeof *osr,
2538                                     1, &arg_size);
2539     if (error) {
2540         return error;
2541     }
2542     osr = (struct ofp_stats_request *) oh;
2543
2544     switch (ntohs(osr->type)) {
2545     case OFPST_DESC:
2546         return handle_desc_stats_request(p, ofconn, osr);
2547
2548     case OFPST_FLOW:
2549         return handle_flow_stats_request(p, ofconn, osr, arg_size);
2550
2551     case OFPST_AGGREGATE:
2552         return handle_aggregate_stats_request(p, ofconn, osr, arg_size);
2553
2554     case OFPST_TABLE:
2555         return handle_table_stats_request(p, ofconn, osr);
2556
2557     case OFPST_PORT:
2558         return handle_port_stats_request(p, ofconn, osr);
2559
2560     case OFPST_VENDOR:
2561         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_VENDOR);
2562
2563     default:
2564         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT);
2565     }
2566 }
2567
2568 static long long int
2569 msec_from_nsec(uint64_t sec, uint32_t nsec)
2570 {
2571     return !sec ? 0 : sec * 1000 + nsec / 1000000;
2572 }
2573
2574 static void
2575 update_time(struct rule *rule, const struct odp_flow_stats *stats)
2576 {
2577     long long int used = msec_from_nsec(stats->used_sec, stats->used_nsec);
2578     if (used > rule->used) {
2579         rule->used = used;
2580     }
2581 }
2582
2583 static void
2584 update_stats(struct rule *rule, const struct odp_flow_stats *stats)
2585 {
2586     update_time(rule, stats);
2587     rule->packet_count += stats->n_packets;
2588     rule->byte_count += stats->n_bytes;
2589     rule->tcp_flags |= stats->tcp_flags;
2590     if (stats->n_packets) {
2591         rule->ip_tos = stats->ip_tos;
2592     }
2593 }
2594
2595 static int
2596 add_flow(struct ofproto *p, struct ofconn *ofconn,
2597          struct ofp_flow_mod *ofm, size_t n_actions)
2598 {
2599     struct ofpbuf *packet;
2600     struct rule *rule;
2601     uint16_t in_port;
2602     int error;
2603
2604     rule = rule_create(NULL, (const union ofp_action *) ofm->actions,
2605                        n_actions, ntohs(ofm->idle_timeout),
2606                        ntohs(ofm->hard_timeout));
2607     cls_rule_from_match(&rule->cr, &ofm->match, ntohs(ofm->priority));
2608
2609     packet = NULL;
2610     error = 0;
2611     if (ofm->buffer_id != htonl(UINT32_MAX)) {
2612         error = pktbuf_retrieve(ofconn->pktbuf, ntohl(ofm->buffer_id),
2613                                 &packet, &in_port);
2614     }
2615
2616     rule_insert(p, rule, packet, in_port);
2617     ofpbuf_delete(packet);
2618     return error;
2619 }
2620
2621 static int
2622 modify_flow(struct ofproto *p, const struct ofp_flow_mod *ofm,
2623             size_t n_actions, uint16_t command, struct rule *rule)
2624 {
2625     if (rule_is_hidden(rule)) {
2626         return 0;
2627     }
2628
2629     if (command == OFPFC_DELETE) {
2630         rule_remove(p, rule);
2631     } else {
2632         size_t actions_len = n_actions * sizeof *rule->actions;
2633
2634         if (n_actions == rule->n_actions
2635             && !memcmp(ofm->actions, rule->actions, actions_len))
2636         {
2637             return 0;
2638         }
2639
2640         free(rule->actions);
2641         rule->actions = xmemdup(ofm->actions, actions_len);
2642         rule->n_actions = n_actions;
2643
2644         if (rule->cr.wc.wildcards) {
2645             COVERAGE_INC(ofproto_mod_wc_flow);
2646             p->need_revalidate = true;
2647         } else {
2648             rule_update_actions(p, rule);
2649         }
2650     }
2651
2652     return 0;
2653 }
2654
2655 static int
2656 modify_flows_strict(struct ofproto *p, const struct ofp_flow_mod *ofm,
2657                     size_t n_actions, uint16_t command)
2658 {
2659     struct rule *rule;
2660     uint32_t wildcards;
2661     flow_t flow;
2662
2663     flow_from_match(&flow, &wildcards, &ofm->match);
2664     rule = rule_from_cls_rule(classifier_find_rule_exactly(
2665                                   &p->cls, &flow, wildcards,
2666                                   ntohs(ofm->priority)));
2667
2668     if (rule) {
2669         if (command == OFPFC_DELETE
2670             && ofm->out_port != htons(OFPP_NONE)
2671             && !rule_has_out_port(rule, ofm->out_port)) {
2672             return 0;
2673         }
2674
2675         modify_flow(p, ofm, n_actions, command, rule);
2676     }
2677     return 0;
2678 }
2679
2680 struct modify_flows_cbdata {
2681     struct ofproto *ofproto;
2682     const struct ofp_flow_mod *ofm;
2683     uint16_t out_port;
2684     size_t n_actions;
2685     uint16_t command;
2686 };
2687
2688 static void
2689 modify_flows_cb(struct cls_rule *rule_, void *cbdata_)
2690 {
2691     struct rule *rule = rule_from_cls_rule(rule_);
2692     struct modify_flows_cbdata *cbdata = cbdata_;
2693
2694     if (cbdata->out_port != htons(OFPP_NONE)
2695         && !rule_has_out_port(rule, cbdata->out_port)) {
2696         return;
2697     }
2698
2699     modify_flow(cbdata->ofproto, cbdata->ofm, cbdata->n_actions,
2700                 cbdata->command, rule);
2701 }
2702
2703 static int
2704 modify_flows_loose(struct ofproto *p, const struct ofp_flow_mod *ofm,
2705                    size_t n_actions, uint16_t command)
2706 {
2707     struct modify_flows_cbdata cbdata;
2708     struct cls_rule target;
2709
2710     cbdata.ofproto = p;
2711     cbdata.ofm = ofm;
2712     cbdata.out_port = (command == OFPFC_DELETE ? ofm->out_port
2713                        : htons(OFPP_NONE));
2714     cbdata.n_actions = n_actions;
2715     cbdata.command = command;
2716
2717     cls_rule_from_match(&target, &ofm->match, 0);
2718
2719     classifier_for_each_match(&p->cls, &target, CLS_INC_ALL,
2720                               modify_flows_cb, &cbdata);
2721     return 0;
2722 }
2723
2724 static int
2725 handle_flow_mod(struct ofproto *p, struct ofconn *ofconn,
2726                 struct ofp_flow_mod *ofm)
2727 {
2728     size_t n_actions;
2729     int error;
2730
2731     error = check_ofp_message_array(&ofm->header, OFPT_FLOW_MOD, sizeof *ofm,
2732                                     sizeof *ofm->actions, &n_actions);
2733     if (error) {
2734         return error;
2735     }
2736
2737     normalize_match(&ofm->match);
2738     if (!ofm->match.wildcards) {
2739         ofm->priority = htons(UINT16_MAX);
2740     }
2741
2742     error = validate_actions((const union ofp_action *) ofm->actions,
2743                              n_actions, p->max_ports);
2744     if (error) {
2745         return error;
2746     }
2747
2748     switch (ntohs(ofm->command)) {
2749     case OFPFC_ADD:
2750         return add_flow(p, ofconn, ofm, n_actions);
2751
2752     case OFPFC_MODIFY:
2753         return modify_flows_loose(p, ofm, n_actions, OFPFC_MODIFY);
2754
2755     case OFPFC_MODIFY_STRICT:
2756         return modify_flows_strict(p, ofm, n_actions, OFPFC_MODIFY);
2757
2758     case OFPFC_DELETE:
2759         return modify_flows_loose(p, ofm, n_actions, OFPFC_DELETE);
2760
2761     case OFPFC_DELETE_STRICT:
2762         return modify_flows_strict(p, ofm, n_actions, OFPFC_DELETE);
2763
2764     default:
2765         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_BAD_COMMAND);
2766     }
2767 }
2768
2769 static void
2770 send_capability_reply(struct ofproto *p, struct ofconn *ofconn, uint32_t xid)
2771 {
2772     struct ofmp_capability_reply *ocr;
2773     struct ofpbuf *b;
2774     char capabilities[] = "com.nicira.mgmt.manager=false\n";
2775
2776     ocr = make_openflow_xid(sizeof(*ocr), OFPT_VENDOR, xid, &b);
2777     ocr->header.header.vendor = htonl(NX_VENDOR_ID);
2778     ocr->header.header.subtype = htonl(NXT_MGMT);
2779     ocr->header.type = htons(OFMPT_CAPABILITY_REPLY);
2780
2781     ocr->format = htonl(OFMPCOF_SIMPLE);
2782     ocr->mgmt_id = htonll(p->mgmt_id);
2783
2784     ofpbuf_put(b, capabilities, strlen(capabilities));
2785
2786     queue_tx(b, ofconn, ofconn->reply_counter);
2787 }
2788
2789 static int
2790 handle_ofmp(struct ofproto *p, struct ofconn *ofconn, 
2791             struct ofmp_header *ofmph)
2792 {
2793     size_t msg_len = ntohs(ofmph->header.header.length);
2794     if (msg_len < sizeof(*ofmph)) {
2795         VLOG_WARN_RL(&rl, "dropping short managment message: %d\n", msg_len);
2796         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
2797     }
2798
2799     if (ofmph->type == htons(OFMPT_CAPABILITY_REQUEST)) {
2800         struct ofmp_capability_request *ofmpcr;
2801
2802         if (msg_len < sizeof(struct ofmp_capability_request)) {
2803             VLOG_WARN_RL(&rl, "dropping short capability request: %d\n", 
2804                     msg_len);
2805             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
2806         }
2807
2808         ofmpcr = (struct ofmp_capability_request *)ofmph;
2809         if (ofmpcr->format != htonl(OFMPCAF_SIMPLE)) {
2810             /* xxx Find a better type than bad subtype */
2811             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE);
2812         }
2813
2814         send_capability_reply(p, ofconn, ofmph->header.header.xid);
2815         return 0;
2816     } else {
2817         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE);
2818     }
2819 }
2820
2821 static int
2822 handle_vendor(struct ofproto *p, struct ofconn *ofconn, void *msg)
2823 {
2824     struct ofp_vendor_header *ovh = msg;
2825     struct nicira_header *nh;
2826
2827     if (ntohs(ovh->header.length) < sizeof(struct ofp_vendor_header)) {
2828         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
2829     }
2830     if (ovh->vendor != htonl(NX_VENDOR_ID)) {
2831         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_VENDOR);
2832     }
2833     if (ntohs(ovh->header.length) < sizeof(struct nicira_header)) {
2834         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
2835     }
2836
2837     nh = msg;
2838     switch (ntohl(nh->subtype)) {
2839     case NXT_STATUS_REQUEST:
2840         return switch_status_handle_request(p->switch_status, ofconn->rconn,
2841                                             msg);
2842
2843     case NXT_ACT_SET_CONFIG:
2844         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE); /* XXX */
2845
2846     case NXT_ACT_GET_CONFIG:
2847         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE); /* XXX */
2848
2849     case NXT_COMMAND_REQUEST:
2850         if (p->executer) {
2851             return executer_handle_request(p->executer, ofconn->rconn, msg);
2852         }
2853         break;
2854
2855     case NXT_MGMT:
2856         return handle_ofmp(p, ofconn, msg);
2857     }
2858
2859     return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE);
2860 }
2861
2862 static void
2863 handle_openflow(struct ofconn *ofconn, struct ofproto *p,
2864                 struct ofpbuf *ofp_msg)
2865 {
2866     struct ofp_header *oh = ofp_msg->data;
2867     int error;
2868
2869     COVERAGE_INC(ofproto_recv_openflow);
2870     switch (oh->type) {
2871     case OFPT_ECHO_REQUEST:
2872         error = handle_echo_request(ofconn, oh);
2873         break;
2874
2875     case OFPT_ECHO_REPLY:
2876         error = 0;
2877         break;
2878
2879     case OFPT_FEATURES_REQUEST:
2880         error = handle_features_request(p, ofconn, oh);
2881         break;
2882
2883     case OFPT_GET_CONFIG_REQUEST:
2884         error = handle_get_config_request(p, ofconn, oh);
2885         break;
2886
2887     case OFPT_SET_CONFIG:
2888         error = handle_set_config(p, ofconn, ofp_msg->data);
2889         break;
2890
2891     case OFPT_PACKET_OUT:
2892         error = handle_packet_out(p, ofconn, ofp_msg->data);
2893         break;
2894
2895     case OFPT_PORT_MOD:
2896         error = handle_port_mod(p, oh);
2897         break;
2898
2899     case OFPT_FLOW_MOD:
2900         error = handle_flow_mod(p, ofconn, ofp_msg->data);
2901         break;
2902
2903     case OFPT_STATS_REQUEST:
2904         error = handle_stats_request(p, ofconn, oh);
2905         break;
2906
2907     case OFPT_VENDOR:
2908         error = handle_vendor(p, ofconn, ofp_msg->data);
2909         break;
2910
2911     default:
2912         if (VLOG_IS_WARN_ENABLED()) {
2913             char *s = ofp_to_string(oh, ntohs(oh->length), 2);
2914             VLOG_DBG_RL(&rl, "OpenFlow message ignored: %s", s);
2915             free(s);
2916         }
2917         error = ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
2918         break;
2919     }
2920
2921     if (error) {
2922         send_error_oh(ofconn, ofp_msg->data, error);
2923     }
2924 }
2925 \f
2926 static void
2927 handle_odp_msg(struct ofproto *p, struct ofpbuf *packet)
2928 {
2929     struct odp_msg *msg = packet->data;
2930     uint16_t in_port = odp_port_to_ofp_port(msg->port);
2931     struct rule *rule;
2932     struct ofpbuf payload;
2933     flow_t flow;
2934
2935     /* Handle controller actions. */
2936     if (msg->type == _ODPL_ACTION_NR) {
2937         COVERAGE_INC(ofproto_ctlr_action);
2938         pinsched_send(p->action_sched, in_port, packet,
2939                       send_packet_in_action, p);
2940         return;
2941     }
2942
2943     payload.data = msg + 1;
2944     payload.size = msg->length - sizeof *msg;
2945     flow_extract(&payload, msg->port, &flow);
2946
2947     rule = lookup_valid_rule(p, &flow);
2948     if (!rule) {
2949         /* Don't send a packet-in if OFPPC_NO_PACKET_IN asserted. */
2950         struct ofport *port = port_array_get(&p->ports, msg->port);
2951         if (port) {
2952             if (port->opp.config & OFPPC_NO_PACKET_IN) {
2953                 COVERAGE_INC(ofproto_no_packet_in);
2954                 /* XXX install 'drop' flow entry */
2955                 ofpbuf_delete(packet);
2956                 return;
2957             }
2958         } else {
2959             VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16, msg->port);
2960         }
2961
2962         COVERAGE_INC(ofproto_packet_in);
2963         pinsched_send(p->miss_sched, in_port, packet, send_packet_in_miss, p);
2964         return;
2965     }
2966
2967     if (rule->cr.wc.wildcards) {
2968         rule = rule_create_subrule(p, rule, &flow);
2969         rule_make_actions(p, rule, packet);
2970     } else {
2971         if (!rule->may_install) {
2972             /* The rule is not installable, that is, we need to process every
2973              * packet, so process the current packet and set its actions into
2974              * 'subrule'. */
2975             rule_make_actions(p, rule, packet);
2976         } else {
2977             /* XXX revalidate rule if it needs it */
2978         }
2979     }
2980
2981     rule_execute(p, rule, &payload, &flow);
2982     rule_reinstall(p, rule);
2983     ofpbuf_delete(packet);
2984 }
2985 \f
2986 static void
2987 revalidate_cb(struct cls_rule *sub_, void *cbdata_)
2988 {
2989     struct rule *sub = rule_from_cls_rule(sub_);
2990     struct revalidate_cbdata *cbdata = cbdata_;
2991
2992     if (cbdata->revalidate_all
2993         || (cbdata->revalidate_subrules && sub->super)
2994         || (tag_set_intersects(&cbdata->revalidate_set, sub->tags))) {
2995         revalidate_rule(cbdata->ofproto, sub);
2996     }
2997 }
2998
2999 static bool
3000 revalidate_rule(struct ofproto *p, struct rule *rule)
3001 {
3002     const flow_t *flow = &rule->cr.flow;
3003
3004     COVERAGE_INC(ofproto_revalidate_rule);
3005     if (rule->super) {
3006         struct rule *super;
3007         super = rule_from_cls_rule(classifier_lookup_wild(&p->cls, flow));
3008         if (!super) {
3009             rule_remove(p, rule);
3010             return false;
3011         } else if (super != rule->super) {
3012             COVERAGE_INC(ofproto_revalidate_moved);
3013             list_remove(&rule->list);
3014             list_push_back(&super->list, &rule->list);
3015             rule->super = super;
3016             rule->hard_timeout = super->hard_timeout;
3017             rule->idle_timeout = super->idle_timeout;
3018             rule->created = super->created;
3019             rule->used = 0;
3020         }
3021     }
3022
3023     rule_update_actions(p, rule);
3024     return true;
3025 }
3026
3027 static struct ofpbuf *
3028 compose_flow_exp(const struct rule *rule, long long int now, uint8_t reason)
3029 {
3030     struct ofp_flow_expired *ofe;
3031     struct ofpbuf *buf;
3032
3033     ofe = make_openflow(sizeof *ofe, OFPT_FLOW_EXPIRED, &buf);
3034     flow_to_match(&rule->cr.flow, rule->cr.wc.wildcards, &ofe->match);
3035     ofe->priority = htons(rule->cr.priority);
3036     ofe->reason = reason;
3037     ofe->duration = (now - rule->created) / 1000;
3038     ofe->packet_count = rule->packet_count;
3039     ofe->byte_count = rule->byte_count;
3040
3041     return buf;
3042 }
3043
3044 static void
3045 send_flow_exp(struct ofproto *p, struct rule *rule,
3046               long long int now, uint8_t reason)
3047 {
3048     struct ofconn *ofconn;
3049     struct ofconn *prev;
3050     struct ofpbuf *buf;
3051
3052     /* We limit the maximum number of queued flow expirations it by accounting
3053      * them under the counter for replies.  That works because preventing
3054      * OpenFlow requests from being processed also prevents new flows from
3055      * being added (and expiring).  (It also prevents processing OpenFlow
3056      * requests that would not add new flows, so it is imperfect.) */
3057
3058     prev = NULL;
3059     LIST_FOR_EACH (ofconn, struct ofconn, node, &p->all_conns) {
3060         if (ofconn->send_flow_exp && rconn_is_connected(ofconn->rconn)) {
3061             if (prev) {
3062                 queue_tx(ofpbuf_clone(buf), prev, ofconn->reply_counter);
3063             } else {
3064                 buf = compose_flow_exp(rule, now, reason);
3065             }
3066             prev = ofconn;
3067         }
3068     }
3069     if (prev) {
3070         queue_tx(buf, prev, ofconn->reply_counter);
3071     }
3072 }
3073
3074 static void
3075 uninstall_idle_flow(struct ofproto *ofproto, struct rule *rule)
3076 {
3077     assert(rule->installed);
3078     assert(!rule->cr.wc.wildcards);
3079
3080     if (rule->super) {
3081         rule_remove(ofproto, rule);
3082     } else {
3083         rule_uninstall(ofproto, rule);
3084     }
3085 }
3086
3087 static void
3088 expire_rule(struct cls_rule *cls_rule, void *p_)
3089 {
3090     struct ofproto *p = p_;
3091     struct rule *rule = rule_from_cls_rule(cls_rule);
3092     long long int hard_expire, idle_expire, expire, now;
3093
3094     hard_expire = (rule->hard_timeout
3095                    ? rule->created + rule->hard_timeout * 1000
3096                    : LLONG_MAX);
3097     idle_expire = (rule->idle_timeout
3098                    && (rule->super || list_is_empty(&rule->list))
3099                    ? rule->used + rule->idle_timeout * 1000
3100                    : LLONG_MAX);
3101     expire = MIN(hard_expire, idle_expire);
3102     if (expire == LLONG_MAX) {
3103         if (rule->installed && time_msec() >= rule->used + 5000) {
3104             uninstall_idle_flow(p, rule);
3105         }
3106         return;
3107     }
3108
3109     now = time_msec();
3110     if (now < expire) {
3111         if (rule->installed && now >= rule->used + 5000) {
3112             uninstall_idle_flow(p, rule);
3113         }
3114         return;
3115     }
3116
3117     COVERAGE_INC(ofproto_expired);
3118     if (rule->cr.wc.wildcards) {
3119         /* Update stats.  (This code will be a no-op if the rule expired
3120          * due to an idle timeout, because in that case the rule has no
3121          * subrules left.) */
3122         struct rule *subrule, *next;
3123         LIST_FOR_EACH_SAFE (subrule, next, struct rule, list, &rule->list) {
3124             rule_remove(p, subrule);
3125         }
3126     }
3127
3128     send_flow_exp(p, rule, now,
3129                   (now >= hard_expire
3130                    ? OFPER_HARD_TIMEOUT : OFPER_IDLE_TIMEOUT));
3131     rule_remove(p, rule);
3132 }
3133
3134 static void
3135 update_used(struct ofproto *p)
3136 {
3137     struct odp_flow *flows;
3138     size_t n_flows;
3139     size_t i;
3140     int error;
3141
3142     error = dpif_flow_list_all(&p->dpif, &flows, &n_flows);
3143     if (error) {
3144         return;
3145     }
3146
3147     for (i = 0; i < n_flows; i++) {
3148         struct odp_flow *f = &flows[i];
3149         struct rule *rule;
3150
3151         rule = rule_from_cls_rule(
3152             classifier_find_rule_exactly(&p->cls, &f->key, 0, UINT16_MAX));
3153         if (!rule || !rule->installed) {
3154             COVERAGE_INC(ofproto_unexpected_rule);
3155             dpif_flow_del(&p->dpif, f);
3156             continue;
3157         }
3158
3159         update_time(rule, &f->stats);
3160         rule_account(p, rule, f->stats.n_bytes);
3161     }
3162     free(flows);
3163 }
3164
3165 static void
3166 do_send_packet_in(struct ofconn *ofconn, uint32_t buffer_id,
3167                   const struct ofpbuf *packet, int send_len)
3168 {
3169     struct ofp_packet_in *opi;
3170     struct ofpbuf payload, *buf;
3171     struct odp_msg *msg;
3172
3173     msg = packet->data;
3174     payload.data = msg + 1;
3175     payload.size = msg->length - sizeof *msg;
3176
3177     send_len = MIN(send_len, payload.size);
3178     buf = ofpbuf_new(sizeof *opi + send_len);
3179     opi = put_openflow_xid(offsetof(struct ofp_packet_in, data),
3180                            OFPT_PACKET_IN, 0, buf);
3181     opi->buffer_id = htonl(buffer_id);
3182     opi->total_len = htons(payload.size);
3183     opi->in_port = htons(odp_port_to_ofp_port(msg->port));
3184     opi->reason = msg->type == _ODPL_ACTION_NR ? OFPR_ACTION : OFPR_NO_MATCH;
3185     ofpbuf_put(buf, payload.data, MIN(send_len, payload.size));
3186     update_openflow_length(buf);
3187     rconn_send_with_limit(ofconn->rconn, buf, ofconn->packet_in_counter, 100);
3188 }
3189
3190 static void
3191 send_packet_in_action(struct ofpbuf *packet, void *p_)
3192 {
3193     struct ofproto *p = p_;
3194     struct ofconn *ofconn;
3195     struct odp_msg *msg;
3196
3197     msg = packet->data;
3198     LIST_FOR_EACH (ofconn, struct ofconn, node, &p->all_conns) {
3199         if (ofconn == p->controller || ofconn->miss_send_len) {
3200             do_send_packet_in(ofconn, UINT32_MAX, packet, msg->arg);
3201         }
3202     }
3203     ofpbuf_delete(packet);
3204 }
3205
3206 static void
3207 send_packet_in_miss(struct ofpbuf *packet, void *p_)
3208 {
3209     struct ofproto *p = p_;
3210     struct ofconn *ofconn;
3211     struct ofpbuf payload;
3212     struct odp_msg *msg;
3213
3214     msg = packet->data;
3215     payload.data = msg + 1;
3216     payload.size = msg->length - sizeof *msg;
3217     LIST_FOR_EACH (ofconn, struct ofconn, node, &p->all_conns) {
3218         if (ofconn->miss_send_len) {
3219             uint32_t buffer_id = pktbuf_save(ofconn->pktbuf, &payload,
3220                                              msg->port);
3221             int send_len = (buffer_id != UINT32_MAX ? ofconn->miss_send_len
3222                             : UINT32_MAX);
3223             do_send_packet_in(ofconn, buffer_id, packet, send_len);
3224         }
3225     }
3226     ofpbuf_delete(packet);
3227 }
3228
3229 static uint64_t
3230 pick_datapath_id(struct dpif *dpif, uint64_t fallback_dpid)
3231 {
3232     char local_name[IF_NAMESIZE];
3233     uint8_t ea[ETH_ADDR_LEN];
3234     int error;
3235
3236     error = dpif_get_name(dpif, local_name, sizeof local_name);
3237     if (!error) {
3238         error = netdev_nodev_get_etheraddr(local_name, ea);
3239         if (!error) {
3240             return eth_addr_to_uint64(ea);
3241         }
3242         VLOG_WARN("could not get MAC address for %s (%s)",
3243                   local_name, strerror(error));
3244     }
3245
3246     return fallback_dpid;
3247 }
3248
3249 static uint64_t
3250 pick_fallback_dpid(void)
3251 {
3252     uint8_t ea[ETH_ADDR_LEN];
3253     eth_addr_random(ea);
3254     ea[0] = 0x00;               /* Set Nicira OUI. */
3255     ea[1] = 0x23;
3256     ea[2] = 0x20;
3257     return eth_addr_to_uint64(ea);
3258 }
3259 \f
3260 static bool
3261 default_normal_ofhook_cb(const flow_t *flow, const struct ofpbuf *packet,
3262                          struct odp_actions *actions, tag_type *tags,
3263                          void *ofproto_)
3264 {
3265     struct ofproto *ofproto = ofproto_;
3266     int out_port;
3267
3268     /* Drop frames for reserved multicast addresses. */
3269     if (eth_addr_is_reserved(flow->dl_dst)) {
3270         return true;
3271     }
3272
3273     /* Learn source MAC (but don't try to learn from revalidation). */
3274     if (packet != NULL) {
3275         tag_type rev_tag = mac_learning_learn(ofproto->ml, flow->dl_src,
3276                                               0, flow->in_port);
3277         if (rev_tag) {
3278             /* The log messages here could actually be useful in debugging,
3279              * so keep the rate limit relatively high. */
3280             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
3281             VLOG_DBG_RL(&rl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
3282                         ETH_ADDR_ARGS(flow->dl_src), flow->in_port);
3283             ofproto_revalidate(ofproto, rev_tag);
3284         }
3285     }
3286
3287     /* Determine output port. */
3288     out_port = mac_learning_lookup_tag(ofproto->ml, flow->dl_dst, 0, tags);
3289     if (out_port < 0) {
3290         add_output_group_action(actions, DP_GROUP_FLOOD);
3291     } else if (out_port != flow->in_port) {
3292         odp_actions_add(actions, ODPAT_OUTPUT)->output.port = out_port;
3293     } else {
3294         /* Drop. */
3295     }
3296
3297     return true;
3298 }
3299
3300 static const struct ofhooks default_ofhooks = {
3301     NULL,
3302     default_normal_ofhook_cb,
3303     NULL,
3304     NULL
3305 };