testsuite: make a sed command more portable
[sliver-openvswitch.git] / ofproto / ofproto.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
3  * Copyright (c) 2010 Jean Tourrilhes - HP-Labs.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at:
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #include <config.h>
19 #include "ofproto.h"
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <stdbool.h>
23 #include <stdlib.h>
24 #include "bitmap.h"
25 #include "byte-order.h"
26 #include "classifier.h"
27 #include "connmgr.h"
28 #include "coverage.h"
29 #include "dynamic-string.h"
30 #include "hash.h"
31 #include "hmap.h"
32 #include "meta-flow.h"
33 #include "netdev.h"
34 #include "nx-match.h"
35 #include "ofp-actions.h"
36 #include "ofp-errors.h"
37 #include "ofp-msgs.h"
38 #include "ofp-print.h"
39 #include "ofp-util.h"
40 #include "ofpbuf.h"
41 #include "ofproto-provider.h"
42 #include "openflow/nicira-ext.h"
43 #include "openflow/openflow.h"
44 #include "packets.h"
45 #include "pinsched.h"
46 #include "pktbuf.h"
47 #include "poll-loop.h"
48 #include "random.h"
49 #include "shash.h"
50 #include "simap.h"
51 #include "sset.h"
52 #include "timeval.h"
53 #include "unaligned.h"
54 #include "unixctl.h"
55 #include "vlog.h"
56
57 VLOG_DEFINE_THIS_MODULE(ofproto);
58
59 COVERAGE_DEFINE(ofproto_error);
60 COVERAGE_DEFINE(ofproto_flush);
61 COVERAGE_DEFINE(ofproto_no_packet_in);
62 COVERAGE_DEFINE(ofproto_packet_out);
63 COVERAGE_DEFINE(ofproto_queue_req);
64 COVERAGE_DEFINE(ofproto_recv_openflow);
65 COVERAGE_DEFINE(ofproto_reinit_ports);
66 COVERAGE_DEFINE(ofproto_uninstallable);
67 COVERAGE_DEFINE(ofproto_update_port);
68
69 enum ofproto_state {
70     S_OPENFLOW,                 /* Processing OpenFlow commands. */
71     S_EVICT,                    /* Evicting flows from over-limit tables. */
72     S_FLUSH,                    /* Deleting all flow table rules. */
73 };
74
75 enum ofoperation_type {
76     OFOPERATION_ADD,
77     OFOPERATION_DELETE,
78     OFOPERATION_MODIFY
79 };
80
81 /* A single OpenFlow request can execute any number of operations.  The
82  * ofopgroup maintain OpenFlow state common to all of the operations, e.g. the
83  * ofconn to which an error reply should be sent if necessary.
84  *
85  * ofproto initiates some operations internally.  These operations are still
86  * assigned to groups but will not have an associated ofconn. */
87 struct ofopgroup {
88     struct ofproto *ofproto;    /* Owning ofproto. */
89     struct list ofproto_node;   /* In ofproto's "pending" list. */
90     struct list ops;            /* List of "struct ofoperation"s. */
91     int n_running;              /* Number of ops still pending. */
92
93     /* Data needed to send OpenFlow reply on failure or to send a buffered
94      * packet on success.
95      *
96      * If list_is_empty(ofconn_node) then this ofopgroup never had an
97      * associated ofconn or its ofconn's connection dropped after it initiated
98      * the operation.  In the latter case 'ofconn' is a wild pointer that
99      * refers to freed memory, so the 'ofconn' member must be used only if
100      * !list_is_empty(ofconn_node).
101      */
102     struct list ofconn_node;    /* In ofconn's list of pending opgroups. */
103     struct ofconn *ofconn;      /* ofconn for reply (but see note above). */
104     struct ofp_header *request; /* Original request (truncated at 64 bytes). */
105     uint32_t buffer_id;         /* Buffer id from original request. */
106 };
107
108 static struct ofopgroup *ofopgroup_create_unattached(struct ofproto *);
109 static struct ofopgroup *ofopgroup_create(struct ofproto *, struct ofconn *,
110                                           const struct ofp_header *,
111                                           uint32_t buffer_id);
112 static void ofopgroup_submit(struct ofopgroup *);
113 static void ofopgroup_complete(struct ofopgroup *);
114
115 /* A single flow table operation. */
116 struct ofoperation {
117     struct ofopgroup *group;    /* Owning group. */
118     struct list group_node;     /* In ofopgroup's "ops" list. */
119     struct hmap_node hmap_node; /* In ofproto's "deletions" hmap. */
120     struct rule *rule;          /* Rule being operated upon. */
121     enum ofoperation_type type; /* Type of operation. */
122
123     /* OFOPERATION_ADD. */
124     struct rule *victim;        /* Rule being replaced, if any.. */
125
126     /* OFOPERATION_MODIFY: The old actions, if the actions are changing. */
127     struct ofpact *ofpacts;
128     size_t ofpacts_len;
129
130     /* OFOPERATION_DELETE. */
131     enum ofp_flow_removed_reason reason; /* Reason flow was removed. */
132
133     ovs_be64 flow_cookie;       /* Rule's old flow cookie. */
134     enum ofperr error;          /* 0 if no error. */
135 };
136
137 static struct ofoperation *ofoperation_create(struct ofopgroup *,
138                                               struct rule *,
139                                               enum ofoperation_type,
140                                               enum ofp_flow_removed_reason);
141 static void ofoperation_destroy(struct ofoperation *);
142
143 /* oftable. */
144 static void oftable_init(struct oftable *);
145 static void oftable_destroy(struct oftable *);
146
147 static void oftable_set_name(struct oftable *, const char *name);
148
149 static void oftable_disable_eviction(struct oftable *);
150 static void oftable_enable_eviction(struct oftable *,
151                                     const struct mf_subfield *fields,
152                                     size_t n_fields);
153
154 static void oftable_remove_rule(struct rule *);
155 static struct rule *oftable_replace_rule(struct rule *);
156 static void oftable_substitute_rule(struct rule *old, struct rule *new);
157
158 /* A set of rules within a single OpenFlow table (oftable) that have the same
159  * values for the oftable's eviction_fields.  A rule to be evicted, when one is
160  * needed, is taken from the eviction group that contains the greatest number
161  * of rules.
162  *
163  * An oftable owns any number of eviction groups, each of which contains any
164  * number of rules.
165  *
166  * Membership in an eviction group is imprecise, based on the hash of the
167  * oftable's eviction_fields (in the eviction_group's id_node.hash member).
168  * That is, if two rules have different eviction_fields, but those
169  * eviction_fields hash to the same value, then they will belong to the same
170  * eviction_group anyway.
171  *
172  * (When eviction is not enabled on an oftable, we don't track any eviction
173  * groups, to save time and space.) */
174 struct eviction_group {
175     struct hmap_node id_node;   /* In oftable's "eviction_groups_by_id". */
176     struct heap_node size_node; /* In oftable's "eviction_groups_by_size". */
177     struct heap rules;          /* Contains "struct rule"s. */
178 };
179
180 static struct rule *choose_rule_to_evict(struct oftable *);
181 static void ofproto_evict(struct ofproto *);
182 static uint32_t rule_eviction_priority(struct rule *);
183
184 /* ofport. */
185 static void ofport_destroy__(struct ofport *);
186 static void ofport_destroy(struct ofport *);
187
188 static void update_port(struct ofproto *, const char *devname);
189 static int init_ports(struct ofproto *);
190 static void reinit_ports(struct ofproto *);
191
192 /* rule. */
193 static void ofproto_rule_destroy__(struct rule *);
194 static void ofproto_rule_send_removed(struct rule *, uint8_t reason);
195 static bool rule_is_modifiable(const struct rule *);
196
197 /* OpenFlow. */
198 static enum ofperr add_flow(struct ofproto *, struct ofconn *,
199                             const struct ofputil_flow_mod *,
200                             const struct ofp_header *);
201 static void delete_flow__(struct rule *, struct ofopgroup *);
202 static bool handle_openflow(struct ofconn *, struct ofpbuf *);
203 static enum ofperr handle_flow_mod__(struct ofproto *, struct ofconn *,
204                                      const struct ofputil_flow_mod *,
205                                      const struct ofp_header *);
206 static void calc_duration(long long int start, long long int now,
207                           uint32_t *sec, uint32_t *nsec);
208
209 /* ofproto. */
210 static uint64_t pick_datapath_id(const struct ofproto *);
211 static uint64_t pick_fallback_dpid(void);
212 static void ofproto_destroy__(struct ofproto *);
213 static void update_mtu(struct ofproto *, struct ofport *);
214
215 /* unixctl. */
216 static void ofproto_unixctl_init(void);
217
218 /* All registered ofproto classes, in probe order. */
219 static const struct ofproto_class **ofproto_classes;
220 static size_t n_ofproto_classes;
221 static size_t allocated_ofproto_classes;
222
223 /* Map from datapath name to struct ofproto, for use by unixctl commands. */
224 static struct hmap all_ofprotos = HMAP_INITIALIZER(&all_ofprotos);
225
226 /* Initial mappings of port to OpenFlow number mappings. */
227 static struct shash init_ofp_ports = SHASH_INITIALIZER(&init_ofp_ports);
228
229 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
230
231 /* The default value of true waits for flow restore. */
232 static bool flow_restore_wait = true;
233
234 /* Must be called to initialize the ofproto library.
235  *
236  * The caller may pass in 'iface_hints', which contains an shash of
237  * "iface_hint" elements indexed by the interface's name.  The provider
238  * may use these hints to describe the startup configuration in order to
239  * reinitialize its state.  The caller owns the provided data, so a
240  * provider will make copies of anything required.  An ofproto provider
241  * will remove any existing state that is not described by the hint, and
242  * may choose to remove it all. */
243 void
244 ofproto_init(const struct shash *iface_hints)
245 {
246     struct shash_node *node;
247     size_t i;
248
249     ofproto_class_register(&ofproto_dpif_class);
250
251     /* Make a local copy, since we don't own 'iface_hints' elements. */
252     SHASH_FOR_EACH(node, iface_hints) {
253         const struct iface_hint *orig_hint = node->data;
254         struct iface_hint *new_hint = xmalloc(sizeof *new_hint);
255         const char *br_type = ofproto_normalize_type(orig_hint->br_type);
256
257         new_hint->br_name = xstrdup(orig_hint->br_name);
258         new_hint->br_type = xstrdup(br_type);
259         new_hint->ofp_port = orig_hint->ofp_port;
260
261         shash_add(&init_ofp_ports, node->name, new_hint);
262     }
263
264     for (i = 0; i < n_ofproto_classes; i++) {
265         ofproto_classes[i]->init(&init_ofp_ports);
266     }
267 }
268
269 /* 'type' should be a normalized datapath type, as returned by
270  * ofproto_normalize_type().  Returns the corresponding ofproto_class
271  * structure, or a null pointer if there is none registered for 'type'. */
272 static const struct ofproto_class *
273 ofproto_class_find__(const char *type)
274 {
275     size_t i;
276
277     for (i = 0; i < n_ofproto_classes; i++) {
278         const struct ofproto_class *class = ofproto_classes[i];
279         struct sset types;
280         bool found;
281
282         sset_init(&types);
283         class->enumerate_types(&types);
284         found = sset_contains(&types, type);
285         sset_destroy(&types);
286
287         if (found) {
288             return class;
289         }
290     }
291     VLOG_WARN("unknown datapath type %s", type);
292     return NULL;
293 }
294
295 /* Registers a new ofproto class.  After successful registration, new ofprotos
296  * of that type can be created using ofproto_create(). */
297 int
298 ofproto_class_register(const struct ofproto_class *new_class)
299 {
300     size_t i;
301
302     for (i = 0; i < n_ofproto_classes; i++) {
303         if (ofproto_classes[i] == new_class) {
304             return EEXIST;
305         }
306     }
307
308     if (n_ofproto_classes >= allocated_ofproto_classes) {
309         ofproto_classes = x2nrealloc(ofproto_classes,
310                                      &allocated_ofproto_classes,
311                                      sizeof *ofproto_classes);
312     }
313     ofproto_classes[n_ofproto_classes++] = new_class;
314     return 0;
315 }
316
317 /* Unregisters a datapath provider.  'type' must have been previously
318  * registered and not currently be in use by any ofprotos.  After
319  * unregistration new datapaths of that type cannot be opened using
320  * ofproto_create(). */
321 int
322 ofproto_class_unregister(const struct ofproto_class *class)
323 {
324     size_t i;
325
326     for (i = 0; i < n_ofproto_classes; i++) {
327         if (ofproto_classes[i] == class) {
328             for (i++; i < n_ofproto_classes; i++) {
329                 ofproto_classes[i - 1] = ofproto_classes[i];
330             }
331             n_ofproto_classes--;
332             return 0;
333         }
334     }
335     VLOG_WARN("attempted to unregister an ofproto class that is not "
336               "registered");
337     return EAFNOSUPPORT;
338 }
339
340 /* Clears 'types' and enumerates all registered ofproto types into it.  The
341  * caller must first initialize the sset. */
342 void
343 ofproto_enumerate_types(struct sset *types)
344 {
345     size_t i;
346
347     for (i = 0; i < n_ofproto_classes; i++) {
348         ofproto_classes[i]->enumerate_types(types);
349     }
350 }
351
352 /* Returns the fully spelled out name for the given ofproto 'type'.
353  *
354  * Normalized type string can be compared with strcmp().  Unnormalized type
355  * string might be the same even if they have different spellings. */
356 const char *
357 ofproto_normalize_type(const char *type)
358 {
359     return type && type[0] ? type : "system";
360 }
361
362 /* Clears 'names' and enumerates the names of all known created ofprotos with
363  * the given 'type'.  The caller must first initialize the sset.  Returns 0 if
364  * successful, otherwise a positive errno value.
365  *
366  * Some kinds of datapaths might not be practically enumerable.  This is not
367  * considered an error. */
368 int
369 ofproto_enumerate_names(const char *type, struct sset *names)
370 {
371     const struct ofproto_class *class = ofproto_class_find__(type);
372     return class ? class->enumerate_names(type, names) : EAFNOSUPPORT;
373  }
374
375 int
376 ofproto_create(const char *datapath_name, const char *datapath_type,
377                struct ofproto **ofprotop)
378 {
379     const struct ofproto_class *class;
380     struct ofproto *ofproto;
381     int error;
382     int i;
383
384     *ofprotop = NULL;
385
386     ofproto_unixctl_init();
387
388     datapath_type = ofproto_normalize_type(datapath_type);
389     class = ofproto_class_find__(datapath_type);
390     if (!class) {
391         VLOG_WARN("could not create datapath %s of unknown type %s",
392                   datapath_name, datapath_type);
393         return EAFNOSUPPORT;
394     }
395
396     ofproto = class->alloc();
397     if (!ofproto) {
398         VLOG_ERR("failed to allocate datapath %s of type %s",
399                  datapath_name, datapath_type);
400         return ENOMEM;
401     }
402
403     /* Initialize. */
404     memset(ofproto, 0, sizeof *ofproto);
405     ofproto->ofproto_class = class;
406     ofproto->name = xstrdup(datapath_name);
407     ofproto->type = xstrdup(datapath_type);
408     hmap_insert(&all_ofprotos, &ofproto->hmap_node,
409                 hash_string(ofproto->name, 0));
410     ofproto->datapath_id = 0;
411     ofproto_set_flow_eviction_threshold(ofproto,
412                                         OFPROTO_FLOW_EVICTION_THRESHOLD_DEFAULT);
413     ofproto->forward_bpdu = false;
414     ofproto->fallback_dpid = pick_fallback_dpid();
415     ofproto->mfr_desc = NULL;
416     ofproto->hw_desc = NULL;
417     ofproto->sw_desc = NULL;
418     ofproto->serial_desc = NULL;
419     ofproto->dp_desc = NULL;
420     ofproto->frag_handling = OFPC_FRAG_NORMAL;
421     hmap_init(&ofproto->ports);
422     shash_init(&ofproto->port_by_name);
423     simap_init(&ofproto->ofp_requests);
424     ofproto->max_ports = OFPP_MAX;
425     ofproto->tables = NULL;
426     ofproto->n_tables = 0;
427     list_init(&ofproto->expirable);
428     ofproto->connmgr = connmgr_create(ofproto, datapath_name, datapath_name);
429     ofproto->state = S_OPENFLOW;
430     list_init(&ofproto->pending);
431     ofproto->n_pending = 0;
432     hmap_init(&ofproto->deletions);
433     ofproto->n_add = ofproto->n_delete = ofproto->n_modify = 0;
434     ofproto->first_op = ofproto->last_op = LLONG_MIN;
435     ofproto->next_op_report = LLONG_MAX;
436     ofproto->op_backoff = LLONG_MIN;
437     ofproto->vlan_bitmap = NULL;
438     ofproto->vlans_changed = false;
439     ofproto->min_mtu = INT_MAX;
440
441     error = ofproto->ofproto_class->construct(ofproto);
442     if (error) {
443         VLOG_ERR("failed to open datapath %s: %s",
444                  datapath_name, strerror(error));
445         ofproto_destroy__(ofproto);
446         return error;
447     }
448
449     /* The "max_ports" member should have been set by ->construct(ofproto).
450      * Port 0 is not a valid OpenFlow port, so mark that as unavailable. */
451     ofproto->ofp_port_ids = bitmap_allocate(ofproto->max_ports);
452     bitmap_set1(ofproto->ofp_port_ids, 0);
453
454     /* Check that hidden tables, if any, are at the end. */
455     ovs_assert(ofproto->n_tables);
456     for (i = 0; i + 1 < ofproto->n_tables; i++) {
457         enum oftable_flags flags = ofproto->tables[i].flags;
458         enum oftable_flags next_flags = ofproto->tables[i + 1].flags;
459
460         ovs_assert(!(flags & OFTABLE_HIDDEN) || next_flags & OFTABLE_HIDDEN);
461     }
462
463     ofproto->datapath_id = pick_datapath_id(ofproto);
464     init_ports(ofproto);
465
466     *ofprotop = ofproto;
467     return 0;
468 }
469
470 /* Must be called (only) by an ofproto implementation in its constructor
471  * function.  See the large comment on 'construct' in struct ofproto_class for
472  * details. */
473 void
474 ofproto_init_tables(struct ofproto *ofproto, int n_tables)
475 {
476     struct oftable *table;
477
478     ovs_assert(!ofproto->n_tables);
479     ovs_assert(n_tables >= 1 && n_tables <= 255);
480
481     ofproto->n_tables = n_tables;
482     ofproto->tables = xmalloc(n_tables * sizeof *ofproto->tables);
483     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
484         oftable_init(table);
485     }
486 }
487
488 /* To be optionally called (only) by an ofproto implementation in its
489  * constructor function.  See the large comment on 'construct' in struct
490  * ofproto_class for details.
491  *
492  * Sets the maximum number of ports to 'max_ports'.  The ofproto generic layer
493  * will then ensure that actions passed into the ofproto implementation will
494  * not refer to OpenFlow ports numbered 'max_ports' or higher.  If this
495  * function is not called, there will be no such restriction.
496  *
497  * Reserved ports numbered OFPP_MAX and higher are special and not subject to
498  * the 'max_ports' restriction. */
499 void
500 ofproto_init_max_ports(struct ofproto *ofproto, uint16_t max_ports)
501 {
502     ovs_assert(max_ports <= OFPP_MAX);
503     ofproto->max_ports = max_ports;
504 }
505
506 uint64_t
507 ofproto_get_datapath_id(const struct ofproto *ofproto)
508 {
509     return ofproto->datapath_id;
510 }
511
512 void
513 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
514 {
515     uint64_t old_dpid = p->datapath_id;
516     p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
517     if (p->datapath_id != old_dpid) {
518         /* Force all active connections to reconnect, since there is no way to
519          * notify a controller that the datapath ID has changed. */
520         ofproto_reconnect_controllers(p);
521     }
522 }
523
524 void
525 ofproto_set_controllers(struct ofproto *p,
526                         const struct ofproto_controller *controllers,
527                         size_t n_controllers, uint32_t allowed_versions)
528 {
529     connmgr_set_controllers(p->connmgr, controllers, n_controllers,
530                             allowed_versions);
531 }
532
533 void
534 ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
535 {
536     connmgr_set_fail_mode(p->connmgr, fail_mode);
537 }
538
539 /* Drops the connections between 'ofproto' and all of its controllers, forcing
540  * them to reconnect. */
541 void
542 ofproto_reconnect_controllers(struct ofproto *ofproto)
543 {
544     connmgr_reconnect(ofproto->connmgr);
545 }
546
547 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
548  * in-band control should guarantee access, in the same way that in-band
549  * control guarantees access to OpenFlow controllers. */
550 void
551 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
552                                   const struct sockaddr_in *extras, size_t n)
553 {
554     connmgr_set_extra_in_band_remotes(ofproto->connmgr, extras, n);
555 }
556
557 /* Sets the OpenFlow queue used by flows set up by in-band control on
558  * 'ofproto' to 'queue_id'.  If 'queue_id' is negative, then in-band control
559  * flows will use the default queue. */
560 void
561 ofproto_set_in_band_queue(struct ofproto *ofproto, int queue_id)
562 {
563     connmgr_set_in_band_queue(ofproto->connmgr, queue_id);
564 }
565
566 /* Sets the number of flows at which eviction from the kernel flow table
567  * will occur. */
568 void
569 ofproto_set_flow_eviction_threshold(struct ofproto *ofproto, unsigned threshold)
570 {
571     if (threshold < OFPROTO_FLOW_EVICTION_THRESHOLD_MIN) {
572         ofproto->flow_eviction_threshold = OFPROTO_FLOW_EVICTION_THRESHOLD_MIN;
573     } else {
574         ofproto->flow_eviction_threshold = threshold;
575     }
576 }
577
578 /* If forward_bpdu is true, the NORMAL action will forward frames with
579  * reserved (e.g. STP) destination Ethernet addresses. if forward_bpdu is false,
580  * the NORMAL action will drop these frames. */
581 void
582 ofproto_set_forward_bpdu(struct ofproto *ofproto, bool forward_bpdu)
583 {
584     bool old_val = ofproto->forward_bpdu;
585     ofproto->forward_bpdu = forward_bpdu;
586     if (old_val != ofproto->forward_bpdu) {
587         if (ofproto->ofproto_class->forward_bpdu_changed) {
588             ofproto->ofproto_class->forward_bpdu_changed(ofproto);
589         }
590     }
591 }
592
593 /* Sets the MAC aging timeout for the OFPP_NORMAL action on 'ofproto' to
594  * 'idle_time', in seconds, and the maximum number of MAC table entries to
595  * 'max_entries'. */
596 void
597 ofproto_set_mac_table_config(struct ofproto *ofproto, unsigned idle_time,
598                              size_t max_entries)
599 {
600     if (ofproto->ofproto_class->set_mac_table_config) {
601         ofproto->ofproto_class->set_mac_table_config(ofproto, idle_time,
602                                                      max_entries);
603     }
604 }
605
606 void
607 ofproto_set_dp_desc(struct ofproto *p, const char *dp_desc)
608 {
609     free(p->dp_desc);
610     p->dp_desc = dp_desc ? xstrdup(dp_desc) : NULL;
611 }
612
613 int
614 ofproto_set_snoops(struct ofproto *ofproto, const struct sset *snoops)
615 {
616     return connmgr_set_snoops(ofproto->connmgr, snoops);
617 }
618
619 int
620 ofproto_set_netflow(struct ofproto *ofproto,
621                     const struct netflow_options *nf_options)
622 {
623     if (nf_options && sset_is_empty(&nf_options->collectors)) {
624         nf_options = NULL;
625     }
626
627     if (ofproto->ofproto_class->set_netflow) {
628         return ofproto->ofproto_class->set_netflow(ofproto, nf_options);
629     } else {
630         return nf_options ? EOPNOTSUPP : 0;
631     }
632 }
633
634 int
635 ofproto_set_sflow(struct ofproto *ofproto,
636                   const struct ofproto_sflow_options *oso)
637 {
638     if (oso && sset_is_empty(&oso->targets)) {
639         oso = NULL;
640     }
641
642     if (ofproto->ofproto_class->set_sflow) {
643         return ofproto->ofproto_class->set_sflow(ofproto, oso);
644     } else {
645         return oso ? EOPNOTSUPP : 0;
646     }
647 }
648
649 int
650 ofproto_set_ipfix(struct ofproto *ofproto,
651                   const struct ofproto_ipfix_bridge_exporter_options *bo,
652                   const struct ofproto_ipfix_flow_exporter_options *fo,
653                   size_t n_fo)
654 {
655     if (ofproto->ofproto_class->set_ipfix) {
656         return ofproto->ofproto_class->set_ipfix(ofproto, bo, fo, n_fo);
657     } else {
658         return (bo || fo) ? EOPNOTSUPP : 0;
659     }
660 }
661
662 void
663 ofproto_set_flow_restore_wait(bool flow_restore_wait_db)
664 {
665     flow_restore_wait = flow_restore_wait_db;
666 }
667
668 bool
669 ofproto_get_flow_restore_wait(void)
670 {
671     return flow_restore_wait;
672 }
673
674 \f
675 /* Spanning Tree Protocol (STP) configuration. */
676
677 /* Configures STP on 'ofproto' using the settings defined in 's'.  If
678  * 's' is NULL, disables STP.
679  *
680  * Returns 0 if successful, otherwise a positive errno value. */
681 int
682 ofproto_set_stp(struct ofproto *ofproto,
683                 const struct ofproto_stp_settings *s)
684 {
685     return (ofproto->ofproto_class->set_stp
686             ? ofproto->ofproto_class->set_stp(ofproto, s)
687             : EOPNOTSUPP);
688 }
689
690 /* Retrieves STP status of 'ofproto' and stores it in 's'.  If the
691  * 'enabled' member of 's' is false, then the other members are not
692  * meaningful.
693  *
694  * Returns 0 if successful, otherwise a positive errno value. */
695 int
696 ofproto_get_stp_status(struct ofproto *ofproto,
697                        struct ofproto_stp_status *s)
698 {
699     return (ofproto->ofproto_class->get_stp_status
700             ? ofproto->ofproto_class->get_stp_status(ofproto, s)
701             : EOPNOTSUPP);
702 }
703
704 /* Configures STP on 'ofp_port' of 'ofproto' using the settings defined
705  * in 's'.  The caller is responsible for assigning STP port numbers
706  * (using the 'port_num' member in the range of 1 through 255, inclusive)
707  * and ensuring there are no duplicates.  If the 's' is NULL, then STP
708  * is disabled on the port.
709  *
710  * Returns 0 if successful, otherwise a positive errno value.*/
711 int
712 ofproto_port_set_stp(struct ofproto *ofproto, uint16_t ofp_port,
713                      const struct ofproto_port_stp_settings *s)
714 {
715     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
716     if (!ofport) {
717         VLOG_WARN("%s: cannot configure STP on nonexistent port %"PRIu16,
718                   ofproto->name, ofp_port);
719         return ENODEV;
720     }
721
722     return (ofproto->ofproto_class->set_stp_port
723             ? ofproto->ofproto_class->set_stp_port(ofport, s)
724             : EOPNOTSUPP);
725 }
726
727 /* Retrieves STP port status of 'ofp_port' on 'ofproto' and stores it in
728  * 's'.  If the 'enabled' member in 's' is false, then the other members
729  * are not meaningful.
730  *
731  * Returns 0 if successful, otherwise a positive errno value.*/
732 int
733 ofproto_port_get_stp_status(struct ofproto *ofproto, uint16_t ofp_port,
734                             struct ofproto_port_stp_status *s)
735 {
736     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
737     if (!ofport) {
738         VLOG_WARN_RL(&rl, "%s: cannot get STP status on nonexistent "
739                      "port %"PRIu16, ofproto->name, ofp_port);
740         return ENODEV;
741     }
742
743     return (ofproto->ofproto_class->get_stp_port_status
744             ? ofproto->ofproto_class->get_stp_port_status(ofport, s)
745             : EOPNOTSUPP);
746 }
747 \f
748 /* Queue DSCP configuration. */
749
750 /* Registers meta-data associated with the 'n_qdscp' Qualities of Service
751  * 'queues' attached to 'ofport'.  This data is not intended to be sufficient
752  * to implement QoS.  Instead, it is used to implement features which require
753  * knowledge of what queues exist on a port, and some basic information about
754  * them.
755  *
756  * Returns 0 if successful, otherwise a positive errno value. */
757 int
758 ofproto_port_set_queues(struct ofproto *ofproto, uint16_t ofp_port,
759                         const struct ofproto_port_queue *queues,
760                         size_t n_queues)
761 {
762     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
763
764     if (!ofport) {
765         VLOG_WARN("%s: cannot set queues on nonexistent port %"PRIu16,
766                   ofproto->name, ofp_port);
767         return ENODEV;
768     }
769
770     return (ofproto->ofproto_class->set_queues
771             ? ofproto->ofproto_class->set_queues(ofport, queues, n_queues)
772             : EOPNOTSUPP);
773 }
774 \f
775 /* Connectivity Fault Management configuration. */
776
777 /* Clears the CFM configuration from 'ofp_port' on 'ofproto'. */
778 void
779 ofproto_port_clear_cfm(struct ofproto *ofproto, uint16_t ofp_port)
780 {
781     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
782     if (ofport && ofproto->ofproto_class->set_cfm) {
783         ofproto->ofproto_class->set_cfm(ofport, NULL);
784     }
785 }
786
787 /* Configures connectivity fault management on 'ofp_port' in 'ofproto'.  Takes
788  * basic configuration from the configuration members in 'cfm', and the remote
789  * maintenance point ID from  remote_mpid.  Ignores the statistics members of
790  * 'cfm'.
791  *
792  * This function has no effect if 'ofproto' does not have a port 'ofp_port'. */
793 void
794 ofproto_port_set_cfm(struct ofproto *ofproto, uint16_t ofp_port,
795                      const struct cfm_settings *s)
796 {
797     struct ofport *ofport;
798     int error;
799
800     ofport = ofproto_get_port(ofproto, ofp_port);
801     if (!ofport) {
802         VLOG_WARN("%s: cannot configure CFM on nonexistent port %"PRIu16,
803                   ofproto->name, ofp_port);
804         return;
805     }
806
807     /* XXX: For configuration simplicity, we only support one remote_mpid
808      * outside of the CFM module.  It's not clear if this is the correct long
809      * term solution or not. */
810     error = (ofproto->ofproto_class->set_cfm
811              ? ofproto->ofproto_class->set_cfm(ofport, s)
812              : EOPNOTSUPP);
813     if (error) {
814         VLOG_WARN("%s: CFM configuration on port %"PRIu16" (%s) failed (%s)",
815                   ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
816                   strerror(error));
817     }
818 }
819
820 /* Configures BFD on 'ofp_port' in 'ofproto'.  This function has no effect if
821  * 'ofproto' does not have a port 'ofp_port'. */
822 void
823 ofproto_port_set_bfd(struct ofproto *ofproto, uint16_t ofp_port,
824                      const struct smap *cfg)
825 {
826     struct ofport *ofport;
827     int error;
828
829     ofport = ofproto_get_port(ofproto, ofp_port);
830     if (!ofport) {
831         VLOG_WARN("%s: cannot configure bfd on nonexistent port %"PRIu16,
832                   ofproto->name, ofp_port);
833         return;
834     }
835
836     error = (ofproto->ofproto_class->set_bfd
837              ? ofproto->ofproto_class->set_bfd(ofport, cfg)
838              : EOPNOTSUPP);
839     if (error) {
840         VLOG_WARN("%s: bfd configuration on port %"PRIu16" (%s) failed (%s)",
841                   ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
842                   strerror(error));
843     }
844 }
845
846 /* Populates 'status' with key value pairs indicating the status of the BFD
847  * session on 'ofp_port'.  This information is intended to be populated in the
848  * OVS database.  Has no effect if 'ofp_port' is not na OpenFlow port in
849  * 'ofproto'. */
850 int
851 ofproto_port_get_bfd_status(struct ofproto *ofproto, uint16_t ofp_port,
852                             struct smap *status)
853 {
854     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
855     return (ofport && ofproto->ofproto_class->get_bfd_status
856             ? ofproto->ofproto_class->get_bfd_status(ofport, status)
857             : EOPNOTSUPP);
858 }
859
860 /* Checks the status of LACP negotiation for 'ofp_port' within ofproto.
861  * Returns 1 if LACP partner information for 'ofp_port' is up-to-date,
862  * 0 if LACP partner information is not current (generally indicating a
863  * connectivity problem), or -1 if LACP is not enabled on 'ofp_port'. */
864 int
865 ofproto_port_is_lacp_current(struct ofproto *ofproto, uint16_t ofp_port)
866 {
867     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
868     return (ofport && ofproto->ofproto_class->port_is_lacp_current
869             ? ofproto->ofproto_class->port_is_lacp_current(ofport)
870             : -1);
871 }
872 \f
873 /* Bundles. */
874
875 /* Registers a "bundle" associated with client data pointer 'aux' in 'ofproto'.
876  * A bundle is the same concept as a Port in OVSDB, that is, it consists of one
877  * or more "slave" devices (Interfaces, in OVSDB) along with a VLAN
878  * configuration plus, if there is more than one slave, a bonding
879  * configuration.
880  *
881  * If 'aux' is already registered then this function updates its configuration
882  * to 's'.  Otherwise, this function registers a new bundle.
883  *
884  * Bundles only affect the NXAST_AUTOPATH action and output to the OFPP_NORMAL
885  * port. */
886 int
887 ofproto_bundle_register(struct ofproto *ofproto, void *aux,
888                         const struct ofproto_bundle_settings *s)
889 {
890     return (ofproto->ofproto_class->bundle_set
891             ? ofproto->ofproto_class->bundle_set(ofproto, aux, s)
892             : EOPNOTSUPP);
893 }
894
895 /* Unregisters the bundle registered on 'ofproto' with auxiliary data 'aux'.
896  * If no such bundle has been registered, this has no effect. */
897 int
898 ofproto_bundle_unregister(struct ofproto *ofproto, void *aux)
899 {
900     return ofproto_bundle_register(ofproto, aux, NULL);
901 }
902
903 \f
904 /* Registers a mirror associated with client data pointer 'aux' in 'ofproto'.
905  * If 'aux' is already registered then this function updates its configuration
906  * to 's'.  Otherwise, this function registers a new mirror. */
907 int
908 ofproto_mirror_register(struct ofproto *ofproto, void *aux,
909                         const struct ofproto_mirror_settings *s)
910 {
911     return (ofproto->ofproto_class->mirror_set
912             ? ofproto->ofproto_class->mirror_set(ofproto, aux, s)
913             : EOPNOTSUPP);
914 }
915
916 /* Unregisters the mirror registered on 'ofproto' with auxiliary data 'aux'.
917  * If no mirror has been registered, this has no effect. */
918 int
919 ofproto_mirror_unregister(struct ofproto *ofproto, void *aux)
920 {
921     return ofproto_mirror_register(ofproto, aux, NULL);
922 }
923
924 /* Retrieves statistics from mirror associated with client data pointer
925  * 'aux' in 'ofproto'.  Stores packet and byte counts in 'packets' and
926  * 'bytes', respectively.  If a particular counters is not supported,
927  * the appropriate argument is set to UINT64_MAX. */
928 int
929 ofproto_mirror_get_stats(struct ofproto *ofproto, void *aux,
930                          uint64_t *packets, uint64_t *bytes)
931 {
932     if (!ofproto->ofproto_class->mirror_get_stats) {
933         *packets = *bytes = UINT64_MAX;
934         return EOPNOTSUPP;
935     }
936
937     return ofproto->ofproto_class->mirror_get_stats(ofproto, aux,
938                                                     packets, bytes);
939 }
940
941 /* Configures the VLANs whose bits are set to 1 in 'flood_vlans' as VLANs on
942  * which all packets are flooded, instead of using MAC learning.  If
943  * 'flood_vlans' is NULL, then MAC learning applies to all VLANs.
944  *
945  * Flood VLANs affect only the treatment of packets output to the OFPP_NORMAL
946  * port. */
947 int
948 ofproto_set_flood_vlans(struct ofproto *ofproto, unsigned long *flood_vlans)
949 {
950     return (ofproto->ofproto_class->set_flood_vlans
951             ? ofproto->ofproto_class->set_flood_vlans(ofproto, flood_vlans)
952             : EOPNOTSUPP);
953 }
954
955 /* Returns true if 'aux' is a registered bundle that is currently in use as the
956  * output for a mirror. */
957 bool
958 ofproto_is_mirror_output_bundle(const struct ofproto *ofproto, void *aux)
959 {
960     return (ofproto->ofproto_class->is_mirror_output_bundle
961             ? ofproto->ofproto_class->is_mirror_output_bundle(ofproto, aux)
962             : false);
963 }
964 \f
965 /* Configuration of OpenFlow tables. */
966
967 /* Returns the number of OpenFlow tables in 'ofproto'. */
968 int
969 ofproto_get_n_tables(const struct ofproto *ofproto)
970 {
971     return ofproto->n_tables;
972 }
973
974 /* Configures the OpenFlow table in 'ofproto' with id 'table_id' with the
975  * settings from 's'.  'table_id' must be in the range 0 through the number of
976  * OpenFlow tables in 'ofproto' minus 1, inclusive.
977  *
978  * For read-only tables, only the name may be configured. */
979 void
980 ofproto_configure_table(struct ofproto *ofproto, int table_id,
981                         const struct ofproto_table_settings *s)
982 {
983     struct oftable *table;
984
985     ovs_assert(table_id >= 0 && table_id < ofproto->n_tables);
986     table = &ofproto->tables[table_id];
987
988     oftable_set_name(table, s->name);
989
990     if (table->flags & OFTABLE_READONLY) {
991         return;
992     }
993
994     if (s->groups) {
995         oftable_enable_eviction(table, s->groups, s->n_groups);
996     } else {
997         oftable_disable_eviction(table);
998     }
999
1000     table->max_flows = s->max_flows;
1001     if (classifier_count(&table->cls) > table->max_flows
1002         && table->eviction_fields) {
1003         /* 'table' contains more flows than allowed.  We might not be able to
1004          * evict them right away because of the asynchronous nature of flow
1005          * table changes.  Schedule eviction for later. */
1006         switch (ofproto->state) {
1007         case S_OPENFLOW:
1008             ofproto->state = S_EVICT;
1009             break;
1010         case S_EVICT:
1011         case S_FLUSH:
1012             /* We're already deleting flows, nothing more to do. */
1013             break;
1014         }
1015     }
1016 }
1017 \f
1018 bool
1019 ofproto_has_snoops(const struct ofproto *ofproto)
1020 {
1021     return connmgr_has_snoops(ofproto->connmgr);
1022 }
1023
1024 void
1025 ofproto_get_snoops(const struct ofproto *ofproto, struct sset *snoops)
1026 {
1027     connmgr_get_snoops(ofproto->connmgr, snoops);
1028 }
1029
1030 static void
1031 ofproto_flush__(struct ofproto *ofproto)
1032 {
1033     struct ofopgroup *group;
1034     struct oftable *table;
1035
1036     if (ofproto->ofproto_class->flush) {
1037         ofproto->ofproto_class->flush(ofproto);
1038     }
1039
1040     group = ofopgroup_create_unattached(ofproto);
1041     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1042         struct rule *rule, *next_rule;
1043         struct cls_cursor cursor;
1044
1045         if (table->flags & OFTABLE_HIDDEN) {
1046             continue;
1047         }
1048
1049         cls_cursor_init(&cursor, &table->cls, NULL);
1050         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
1051             if (!rule->pending) {
1052                 ofoperation_create(group, rule, OFOPERATION_DELETE,
1053                                    OFPRR_DELETE);
1054                 oftable_remove_rule(rule);
1055                 ofproto->ofproto_class->rule_destruct(rule);
1056             }
1057         }
1058     }
1059     ofopgroup_submit(group);
1060 }
1061
1062 static void
1063 ofproto_destroy__(struct ofproto *ofproto)
1064 {
1065     struct oftable *table;
1066
1067     ovs_assert(list_is_empty(&ofproto->pending));
1068     ovs_assert(!ofproto->n_pending);
1069
1070     connmgr_destroy(ofproto->connmgr);
1071
1072     hmap_remove(&all_ofprotos, &ofproto->hmap_node);
1073     free(ofproto->name);
1074     free(ofproto->type);
1075     free(ofproto->mfr_desc);
1076     free(ofproto->hw_desc);
1077     free(ofproto->sw_desc);
1078     free(ofproto->serial_desc);
1079     free(ofproto->dp_desc);
1080     hmap_destroy(&ofproto->ports);
1081     shash_destroy(&ofproto->port_by_name);
1082     bitmap_free(ofproto->ofp_port_ids);
1083     simap_destroy(&ofproto->ofp_requests);
1084
1085     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1086         oftable_destroy(table);
1087     }
1088     free(ofproto->tables);
1089
1090     hmap_destroy(&ofproto->deletions);
1091
1092     free(ofproto->vlan_bitmap);
1093
1094     ofproto->ofproto_class->dealloc(ofproto);
1095 }
1096
1097 void
1098 ofproto_destroy(struct ofproto *p)
1099 {
1100     struct ofport *ofport, *next_ofport;
1101
1102     if (!p) {
1103         return;
1104     }
1105
1106     ofproto_flush__(p);
1107     HMAP_FOR_EACH_SAFE (ofport, next_ofport, hmap_node, &p->ports) {
1108         ofport_destroy(ofport);
1109     }
1110
1111     p->ofproto_class->destruct(p);
1112     ofproto_destroy__(p);
1113 }
1114
1115 /* Destroys the datapath with the respective 'name' and 'type'.  With the Linux
1116  * kernel datapath, for example, this destroys the datapath in the kernel, and
1117  * with the netdev-based datapath, it tears down the data structures that
1118  * represent the datapath.
1119  *
1120  * The datapath should not be currently open as an ofproto. */
1121 int
1122 ofproto_delete(const char *name, const char *type)
1123 {
1124     const struct ofproto_class *class = ofproto_class_find__(type);
1125     return (!class ? EAFNOSUPPORT
1126             : !class->del ? EACCES
1127             : class->del(type, name));
1128 }
1129
1130 static void
1131 process_port_change(struct ofproto *ofproto, int error, char *devname)
1132 {
1133     if (error == ENOBUFS) {
1134         reinit_ports(ofproto);
1135     } else if (!error) {
1136         update_port(ofproto, devname);
1137         free(devname);
1138     }
1139 }
1140
1141 int
1142 ofproto_type_run(const char *datapath_type)
1143 {
1144     const struct ofproto_class *class;
1145     int error;
1146
1147     datapath_type = ofproto_normalize_type(datapath_type);
1148     class = ofproto_class_find__(datapath_type);
1149
1150     error = class->type_run ? class->type_run(datapath_type) : 0;
1151     if (error && error != EAGAIN) {
1152         VLOG_ERR_RL(&rl, "%s: type_run failed (%s)",
1153                     datapath_type, strerror(error));
1154     }
1155     return error;
1156 }
1157
1158 int
1159 ofproto_type_run_fast(const char *datapath_type)
1160 {
1161     const struct ofproto_class *class;
1162     int error;
1163
1164     datapath_type = ofproto_normalize_type(datapath_type);
1165     class = ofproto_class_find__(datapath_type);
1166
1167     error = class->type_run_fast ? class->type_run_fast(datapath_type) : 0;
1168     if (error && error != EAGAIN) {
1169         VLOG_ERR_RL(&rl, "%s: type_run_fast failed (%s)",
1170                     datapath_type, strerror(error));
1171     }
1172     return error;
1173 }
1174
1175 void
1176 ofproto_type_wait(const char *datapath_type)
1177 {
1178     const struct ofproto_class *class;
1179
1180     datapath_type = ofproto_normalize_type(datapath_type);
1181     class = ofproto_class_find__(datapath_type);
1182
1183     if (class->type_wait) {
1184         class->type_wait(datapath_type);
1185     }
1186 }
1187
1188 int
1189 ofproto_run(struct ofproto *p)
1190 {
1191     struct sset changed_netdevs;
1192     const char *changed_netdev;
1193     struct ofport *ofport;
1194     int error;
1195
1196     error = p->ofproto_class->run(p);
1197     if (error && error != EAGAIN) {
1198         VLOG_ERR_RL(&rl, "%s: run failed (%s)", p->name, strerror(error));
1199     }
1200
1201     if (p->ofproto_class->port_poll) {
1202         char *devname;
1203
1204         while ((error = p->ofproto_class->port_poll(p, &devname)) != EAGAIN) {
1205             process_port_change(p, error, devname);
1206         }
1207     }
1208
1209     /* Update OpenFlow port status for any port whose netdev has changed.
1210      *
1211      * Refreshing a given 'ofport' can cause an arbitrary ofport to be
1212      * destroyed, so it's not safe to update ports directly from the
1213      * HMAP_FOR_EACH loop, or even to use HMAP_FOR_EACH_SAFE.  Instead, we
1214      * need this two-phase approach. */
1215     sset_init(&changed_netdevs);
1216     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1217         unsigned int change_seq = netdev_change_seq(ofport->netdev);
1218         if (ofport->change_seq != change_seq) {
1219             ofport->change_seq = change_seq;
1220             sset_add(&changed_netdevs, netdev_get_name(ofport->netdev));
1221         }
1222     }
1223     SSET_FOR_EACH (changed_netdev, &changed_netdevs) {
1224         update_port(p, changed_netdev);
1225     }
1226     sset_destroy(&changed_netdevs);
1227
1228     switch (p->state) {
1229     case S_OPENFLOW:
1230         connmgr_run(p->connmgr, handle_openflow);
1231         break;
1232
1233     case S_EVICT:
1234         connmgr_run(p->connmgr, NULL);
1235         ofproto_evict(p);
1236         if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1237             p->state = S_OPENFLOW;
1238         }
1239         break;
1240
1241     case S_FLUSH:
1242         connmgr_run(p->connmgr, NULL);
1243         ofproto_flush__(p);
1244         if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1245             connmgr_flushed(p->connmgr);
1246             p->state = S_OPENFLOW;
1247         }
1248         break;
1249
1250     default:
1251         NOT_REACHED();
1252     }
1253
1254     if (time_msec() >= p->next_op_report) {
1255         long long int ago = (time_msec() - p->first_op) / 1000;
1256         long long int interval = (p->last_op - p->first_op) / 1000;
1257         struct ds s;
1258
1259         ds_init(&s);
1260         ds_put_format(&s, "%d flow_mods ",
1261                       p->n_add + p->n_delete + p->n_modify);
1262         if (interval == ago) {
1263             ds_put_format(&s, "in the last %lld s", ago);
1264         } else if (interval) {
1265             ds_put_format(&s, "in the %lld s starting %lld s ago",
1266                           interval, ago);
1267         } else {
1268             ds_put_format(&s, "%lld s ago", ago);
1269         }
1270
1271         ds_put_cstr(&s, " (");
1272         if (p->n_add) {
1273             ds_put_format(&s, "%d adds, ", p->n_add);
1274         }
1275         if (p->n_delete) {
1276             ds_put_format(&s, "%d deletes, ", p->n_delete);
1277         }
1278         if (p->n_modify) {
1279             ds_put_format(&s, "%d modifications, ", p->n_modify);
1280         }
1281         s.length -= 2;
1282         ds_put_char(&s, ')');
1283
1284         VLOG_INFO("%s: %s", p->name, ds_cstr(&s));
1285         ds_destroy(&s);
1286
1287         p->n_add = p->n_delete = p->n_modify = 0;
1288         p->next_op_report = LLONG_MAX;
1289     }
1290
1291     return error;
1292 }
1293
1294 /* Performs periodic activity required by 'ofproto' that needs to be done
1295  * with the least possible latency.
1296  *
1297  * It makes sense to call this function a couple of times per poll loop, to
1298  * provide a significant performance boost on some benchmarks with the
1299  * ofproto-dpif implementation. */
1300 int
1301 ofproto_run_fast(struct ofproto *p)
1302 {
1303     int error;
1304
1305     error = p->ofproto_class->run_fast ? p->ofproto_class->run_fast(p) : 0;
1306     if (error && error != EAGAIN) {
1307         VLOG_ERR_RL(&rl, "%s: fastpath run failed (%s)",
1308                     p->name, strerror(error));
1309     }
1310     return error;
1311 }
1312
1313 void
1314 ofproto_wait(struct ofproto *p)
1315 {
1316     struct ofport *ofport;
1317
1318     p->ofproto_class->wait(p);
1319     if (p->ofproto_class->port_poll_wait) {
1320         p->ofproto_class->port_poll_wait(p);
1321     }
1322
1323     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1324         if (ofport->change_seq != netdev_change_seq(ofport->netdev)) {
1325             poll_immediate_wake();
1326         }
1327     }
1328
1329     switch (p->state) {
1330     case S_OPENFLOW:
1331         connmgr_wait(p->connmgr, true);
1332         break;
1333
1334     case S_EVICT:
1335     case S_FLUSH:
1336         connmgr_wait(p->connmgr, false);
1337         if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1338             poll_immediate_wake();
1339         }
1340         break;
1341     }
1342 }
1343
1344 bool
1345 ofproto_is_alive(const struct ofproto *p)
1346 {
1347     return connmgr_has_controllers(p->connmgr);
1348 }
1349
1350 /* Adds some memory usage statistics for 'ofproto' into 'usage', for use with
1351  * memory_report(). */
1352 void
1353 ofproto_get_memory_usage(const struct ofproto *ofproto, struct simap *usage)
1354 {
1355     const struct oftable *table;
1356     unsigned int n_rules;
1357
1358     simap_increase(usage, "ports", hmap_count(&ofproto->ports));
1359     simap_increase(usage, "ops",
1360                    ofproto->n_pending + hmap_count(&ofproto->deletions));
1361
1362     n_rules = 0;
1363     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1364         n_rules += classifier_count(&table->cls);
1365     }
1366     simap_increase(usage, "rules", n_rules);
1367
1368     if (ofproto->ofproto_class->get_memory_usage) {
1369         ofproto->ofproto_class->get_memory_usage(ofproto, usage);
1370     }
1371
1372     connmgr_get_memory_usage(ofproto->connmgr, usage);
1373 }
1374
1375 void
1376 ofproto_get_ofproto_controller_info(const struct ofproto *ofproto,
1377                                     struct shash *info)
1378 {
1379     connmgr_get_controller_info(ofproto->connmgr, info);
1380 }
1381
1382 void
1383 ofproto_free_ofproto_controller_info(struct shash *info)
1384 {
1385     connmgr_free_controller_info(info);
1386 }
1387
1388 /* Makes a deep copy of 'old' into 'port'. */
1389 void
1390 ofproto_port_clone(struct ofproto_port *port, const struct ofproto_port *old)
1391 {
1392     port->name = xstrdup(old->name);
1393     port->type = xstrdup(old->type);
1394     port->ofp_port = old->ofp_port;
1395 }
1396
1397 /* Frees memory allocated to members of 'ofproto_port'.
1398  *
1399  * Do not call this function on an ofproto_port obtained from
1400  * ofproto_port_dump_next(): that function retains ownership of the data in the
1401  * ofproto_port. */
1402 void
1403 ofproto_port_destroy(struct ofproto_port *ofproto_port)
1404 {
1405     free(ofproto_port->name);
1406     free(ofproto_port->type);
1407 }
1408
1409 /* Initializes 'dump' to begin dumping the ports in an ofproto.
1410  *
1411  * This function provides no status indication.  An error status for the entire
1412  * dump operation is provided when it is completed by calling
1413  * ofproto_port_dump_done().
1414  */
1415 void
1416 ofproto_port_dump_start(struct ofproto_port_dump *dump,
1417                         const struct ofproto *ofproto)
1418 {
1419     dump->ofproto = ofproto;
1420     dump->error = ofproto->ofproto_class->port_dump_start(ofproto,
1421                                                           &dump->state);
1422 }
1423
1424 /* Attempts to retrieve another port from 'dump', which must have been created
1425  * with ofproto_port_dump_start().  On success, stores a new ofproto_port into
1426  * 'port' and returns true.  On failure, returns false.
1427  *
1428  * Failure might indicate an actual error or merely that the last port has been
1429  * dumped.  An error status for the entire dump operation is provided when it
1430  * is completed by calling ofproto_port_dump_done().
1431  *
1432  * The ofproto owns the data stored in 'port'.  It will remain valid until at
1433  * least the next time 'dump' is passed to ofproto_port_dump_next() or
1434  * ofproto_port_dump_done(). */
1435 bool
1436 ofproto_port_dump_next(struct ofproto_port_dump *dump,
1437                        struct ofproto_port *port)
1438 {
1439     const struct ofproto *ofproto = dump->ofproto;
1440
1441     if (dump->error) {
1442         return false;
1443     }
1444
1445     dump->error = ofproto->ofproto_class->port_dump_next(ofproto, dump->state,
1446                                                          port);
1447     if (dump->error) {
1448         ofproto->ofproto_class->port_dump_done(ofproto, dump->state);
1449         return false;
1450     }
1451     return true;
1452 }
1453
1454 /* Completes port table dump operation 'dump', which must have been created
1455  * with ofproto_port_dump_start().  Returns 0 if the dump operation was
1456  * error-free, otherwise a positive errno value describing the problem. */
1457 int
1458 ofproto_port_dump_done(struct ofproto_port_dump *dump)
1459 {
1460     const struct ofproto *ofproto = dump->ofproto;
1461     if (!dump->error) {
1462         dump->error = ofproto->ofproto_class->port_dump_done(ofproto,
1463                                                              dump->state);
1464     }
1465     return dump->error == EOF ? 0 : dump->error;
1466 }
1467
1468 /* Returns the type to pass to netdev_open() when a datapath of type
1469  * 'datapath_type' has a port of type 'port_type', for a few special
1470  * cases when a netdev type differs from a port type.  For example, when
1471  * using the userspace datapath, a port of type "internal" needs to be
1472  * opened as "tap".
1473  *
1474  * Returns either 'type' itself or a string literal, which must not be
1475  * freed. */
1476 const char *
1477 ofproto_port_open_type(const char *datapath_type, const char *port_type)
1478 {
1479     const struct ofproto_class *class;
1480
1481     datapath_type = ofproto_normalize_type(datapath_type);
1482     class = ofproto_class_find__(datapath_type);
1483     if (!class) {
1484         return port_type;
1485     }
1486
1487     return (class->port_open_type
1488             ? class->port_open_type(datapath_type, port_type)
1489             : port_type);
1490 }
1491
1492 /* Attempts to add 'netdev' as a port on 'ofproto'.  If 'ofp_portp' is
1493  * non-null and '*ofp_portp' is not OFPP_NONE, attempts to use that as
1494  * the port's OpenFlow port number.
1495  *
1496  * If successful, returns 0 and sets '*ofp_portp' to the new port's
1497  * OpenFlow port number (if 'ofp_portp' is non-null).  On failure,
1498  * returns a positive errno value and sets '*ofp_portp' to OFPP_NONE (if
1499  * 'ofp_portp' is non-null). */
1500 int
1501 ofproto_port_add(struct ofproto *ofproto, struct netdev *netdev,
1502                  uint16_t *ofp_portp)
1503 {
1504     uint16_t ofp_port = ofp_portp ? *ofp_portp : OFPP_NONE;
1505     int error;
1506
1507     error = ofproto->ofproto_class->port_add(ofproto, netdev);
1508     if (!error) {
1509         const char *netdev_name = netdev_get_name(netdev);
1510
1511         simap_put(&ofproto->ofp_requests, netdev_name, ofp_port);
1512         update_port(ofproto, netdev_name);
1513     }
1514     if (ofp_portp) {
1515         struct ofproto_port ofproto_port;
1516
1517         ofproto_port_query_by_name(ofproto, netdev_get_name(netdev),
1518                                    &ofproto_port);
1519         *ofp_portp = error ? OFPP_NONE : ofproto_port.ofp_port;
1520         ofproto_port_destroy(&ofproto_port);
1521     }
1522     return error;
1523 }
1524
1525 /* Looks up a port named 'devname' in 'ofproto'.  On success, returns 0 and
1526  * initializes '*port' appropriately; on failure, returns a positive errno
1527  * value.
1528  *
1529  * The caller owns the data in 'ofproto_port' and must free it with
1530  * ofproto_port_destroy() when it is no longer needed. */
1531 int
1532 ofproto_port_query_by_name(const struct ofproto *ofproto, const char *devname,
1533                            struct ofproto_port *port)
1534 {
1535     int error;
1536
1537     error = ofproto->ofproto_class->port_query_by_name(ofproto, devname, port);
1538     if (error) {
1539         memset(port, 0, sizeof *port);
1540     }
1541     return error;
1542 }
1543
1544 /* Deletes port number 'ofp_port' from the datapath for 'ofproto'.
1545  * Returns 0 if successful, otherwise a positive errno. */
1546 int
1547 ofproto_port_del(struct ofproto *ofproto, uint16_t ofp_port)
1548 {
1549     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1550     const char *name = ofport ? netdev_get_name(ofport->netdev) : "<unknown>";
1551     struct simap_node *ofp_request_node;
1552     int error;
1553
1554     ofp_request_node = simap_find(&ofproto->ofp_requests, name);
1555     if (ofp_request_node) {
1556         simap_delete(&ofproto->ofp_requests, ofp_request_node);
1557     }
1558
1559     error = ofproto->ofproto_class->port_del(ofproto, ofp_port);
1560     if (!error && ofport) {
1561         /* 'name' is the netdev's name and update_port() is going to close the
1562          * netdev.  Just in case update_port() refers to 'name' after it
1563          * destroys 'ofport', make a copy of it around the update_port()
1564          * call. */
1565         char *devname = xstrdup(name);
1566         update_port(ofproto, devname);
1567         free(devname);
1568     }
1569     return error;
1570 }
1571
1572 /* Adds a flow to OpenFlow flow table 0 in 'p' that matches 'cls_rule' and
1573  * performs the 'n_actions' actions in 'actions'.  The new flow will not
1574  * timeout.
1575  *
1576  * If cls_rule->priority is in the range of priorities supported by OpenFlow
1577  * (0...65535, inclusive) then the flow will be visible to OpenFlow
1578  * controllers; otherwise, it will be hidden.
1579  *
1580  * The caller retains ownership of 'cls_rule' and 'ofpacts'.
1581  *
1582  * This is a helper function for in-band control and fail-open. */
1583 void
1584 ofproto_add_flow(struct ofproto *ofproto, const struct match *match,
1585                  unsigned int priority,
1586                  const struct ofpact *ofpacts, size_t ofpacts_len)
1587 {
1588     const struct rule *rule;
1589
1590     rule = rule_from_cls_rule(classifier_find_match_exactly(
1591                                   &ofproto->tables[0].cls, match, priority));
1592     if (!rule || !ofpacts_equal(rule->ofpacts, rule->ofpacts_len,
1593                                 ofpacts, ofpacts_len)) {
1594         struct ofputil_flow_mod fm;
1595
1596         memset(&fm, 0, sizeof fm);
1597         fm.match = *match;
1598         fm.priority = priority;
1599         fm.buffer_id = UINT32_MAX;
1600         fm.ofpacts = xmemdup(ofpacts, ofpacts_len);
1601         fm.ofpacts_len = ofpacts_len;
1602         add_flow(ofproto, NULL, &fm, NULL);
1603         free(fm.ofpacts);
1604     }
1605 }
1606
1607 /* Executes the flow modification specified in 'fm'.  Returns 0 on success, an
1608  * OFPERR_* OpenFlow error code on failure, or OFPROTO_POSTPONE if the
1609  * operation cannot be initiated now but may be retried later.
1610  *
1611  * This is a helper function for in-band control and fail-open. */
1612 int
1613 ofproto_flow_mod(struct ofproto *ofproto, const struct ofputil_flow_mod *fm)
1614 {
1615     return handle_flow_mod__(ofproto, NULL, fm, NULL);
1616 }
1617
1618 /* Searches for a rule with matching criteria exactly equal to 'target' in
1619  * ofproto's table 0 and, if it finds one, deletes it.
1620  *
1621  * This is a helper function for in-band control and fail-open. */
1622 bool
1623 ofproto_delete_flow(struct ofproto *ofproto,
1624                     const struct match *target, unsigned int priority)
1625 {
1626     struct rule *rule;
1627
1628     rule = rule_from_cls_rule(classifier_find_match_exactly(
1629                                   &ofproto->tables[0].cls, target, priority));
1630     if (!rule) {
1631         /* No such rule -> success. */
1632         return true;
1633     } else if (rule->pending) {
1634         /* An operation on the rule is already pending -> failure.
1635          * Caller must retry later if it's important. */
1636         return false;
1637     } else {
1638         /* Initiate deletion -> success. */
1639         struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
1640         ofoperation_create(group, rule, OFOPERATION_DELETE, OFPRR_DELETE);
1641         oftable_remove_rule(rule);
1642         ofproto->ofproto_class->rule_destruct(rule);
1643         ofopgroup_submit(group);
1644         return true;
1645     }
1646
1647 }
1648
1649 /* Starts the process of deleting all of the flows from all of ofproto's flow
1650  * tables and then reintroducing the flows required by in-band control and
1651  * fail-open.  The process will complete in a later call to ofproto_run(). */
1652 void
1653 ofproto_flush_flows(struct ofproto *ofproto)
1654 {
1655     COVERAGE_INC(ofproto_flush);
1656     ofproto->state = S_FLUSH;
1657 }
1658 \f
1659 static void
1660 reinit_ports(struct ofproto *p)
1661 {
1662     struct ofproto_port_dump dump;
1663     struct sset devnames;
1664     struct ofport *ofport;
1665     struct ofproto_port ofproto_port;
1666     const char *devname;
1667
1668     COVERAGE_INC(ofproto_reinit_ports);
1669
1670     sset_init(&devnames);
1671     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1672         sset_add(&devnames, netdev_get_name(ofport->netdev));
1673     }
1674     OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
1675         sset_add(&devnames, ofproto_port.name);
1676     }
1677
1678     SSET_FOR_EACH (devname, &devnames) {
1679         update_port(p, devname);
1680     }
1681     sset_destroy(&devnames);
1682 }
1683
1684 static uint16_t
1685 alloc_ofp_port(struct ofproto *ofproto, const char *netdev_name)
1686 {
1687     uint16_t ofp_port;
1688     uint16_t end_port_no = ofproto->alloc_port_no;
1689
1690     ofp_port = simap_get(&ofproto->ofp_requests, netdev_name);
1691     ofp_port = ofp_port ? ofp_port : OFPP_NONE;
1692
1693     if (ofp_port >= ofproto->max_ports
1694             || bitmap_is_set(ofproto->ofp_port_ids, ofp_port)) {
1695         /* Search for a free OpenFlow port number.  We try not to
1696          * immediately reuse them to prevent problems due to old
1697          * flows. */
1698         for (;;) {
1699             if (++ofproto->alloc_port_no >= ofproto->max_ports) {
1700                 ofproto->alloc_port_no = 0;
1701             }
1702             if (!bitmap_is_set(ofproto->ofp_port_ids,
1703                                ofproto->alloc_port_no)) {
1704                 ofp_port = ofproto->alloc_port_no;
1705                 break;
1706             }
1707             if (ofproto->alloc_port_no == end_port_no) {
1708                 return OFPP_NONE;
1709             }
1710         }
1711     }
1712     bitmap_set1(ofproto->ofp_port_ids, ofp_port);
1713     return ofp_port;
1714 }
1715
1716 static void
1717 dealloc_ofp_port(const struct ofproto *ofproto, uint16_t ofp_port)
1718 {
1719     if (ofp_port < ofproto->max_ports) {
1720         bitmap_set0(ofproto->ofp_port_ids, ofp_port);
1721     }
1722 }
1723
1724 /* Opens and returns a netdev for 'ofproto_port' in 'ofproto', or a null
1725  * pointer if the netdev cannot be opened.  On success, also fills in
1726  * 'opp'.  */
1727 static struct netdev *
1728 ofport_open(struct ofproto *ofproto,
1729             struct ofproto_port *ofproto_port,
1730             struct ofputil_phy_port *pp)
1731 {
1732     enum netdev_flags flags;
1733     struct netdev *netdev;
1734     int error;
1735
1736     error = netdev_open(ofproto_port->name, ofproto_port->type, &netdev);
1737     if (error) {
1738         VLOG_WARN_RL(&rl, "%s: ignoring port %s (%"PRIu16") because netdev %s "
1739                      "cannot be opened (%s)",
1740                      ofproto->name,
1741                      ofproto_port->name, ofproto_port->ofp_port,
1742                      ofproto_port->name, strerror(error));
1743         return NULL;
1744     }
1745
1746     if (ofproto_port->ofp_port == OFPP_NONE) {
1747         if (!strcmp(ofproto->name, ofproto_port->name)) {
1748             ofproto_port->ofp_port = OFPP_LOCAL;
1749         } else {
1750             ofproto_port->ofp_port = alloc_ofp_port(ofproto,
1751                                                     ofproto_port->name);
1752         }
1753     }
1754     pp->port_no = ofproto_port->ofp_port;
1755     netdev_get_etheraddr(netdev, pp->hw_addr);
1756     ovs_strlcpy(pp->name, ofproto_port->name, sizeof pp->name);
1757     netdev_get_flags(netdev, &flags);
1758     pp->config = flags & NETDEV_UP ? 0 : OFPUTIL_PC_PORT_DOWN;
1759     pp->state = netdev_get_carrier(netdev) ? 0 : OFPUTIL_PS_LINK_DOWN;
1760     netdev_get_features(netdev, &pp->curr, &pp->advertised,
1761                         &pp->supported, &pp->peer);
1762     pp->curr_speed = netdev_features_to_bps(pp->curr, 0);
1763     pp->max_speed = netdev_features_to_bps(pp->supported, 0);
1764
1765     return netdev;
1766 }
1767
1768 /* Returns true if most fields of 'a' and 'b' are equal.  Differences in name,
1769  * port number, and 'config' bits other than OFPUTIL_PS_LINK_DOWN are
1770  * disregarded. */
1771 static bool
1772 ofport_equal(const struct ofputil_phy_port *a,
1773              const struct ofputil_phy_port *b)
1774 {
1775     return (eth_addr_equals(a->hw_addr, b->hw_addr)
1776             && a->state == b->state
1777             && !((a->config ^ b->config) & OFPUTIL_PC_PORT_DOWN)
1778             && a->curr == b->curr
1779             && a->advertised == b->advertised
1780             && a->supported == b->supported
1781             && a->peer == b->peer
1782             && a->curr_speed == b->curr_speed
1783             && a->max_speed == b->max_speed);
1784 }
1785
1786 /* Adds an ofport to 'p' initialized based on the given 'netdev' and 'opp'.
1787  * The caller must ensure that 'p' does not have a conflicting ofport (that is,
1788  * one with the same name or port number). */
1789 static void
1790 ofport_install(struct ofproto *p,
1791                struct netdev *netdev, const struct ofputil_phy_port *pp)
1792 {
1793     const char *netdev_name = netdev_get_name(netdev);
1794     struct ofport *ofport;
1795     int error;
1796
1797     /* Create ofport. */
1798     ofport = p->ofproto_class->port_alloc();
1799     if (!ofport) {
1800         error = ENOMEM;
1801         goto error;
1802     }
1803     ofport->ofproto = p;
1804     ofport->netdev = netdev;
1805     ofport->change_seq = netdev_change_seq(netdev);
1806     ofport->pp = *pp;
1807     ofport->ofp_port = pp->port_no;
1808     ofport->created = time_msec();
1809
1810     /* Add port to 'p'. */
1811     hmap_insert(&p->ports, &ofport->hmap_node, hash_int(ofport->ofp_port, 0));
1812     shash_add(&p->port_by_name, netdev_name, ofport);
1813
1814     update_mtu(p, ofport);
1815
1816     /* Let the ofproto_class initialize its private data. */
1817     error = p->ofproto_class->port_construct(ofport);
1818     if (error) {
1819         goto error;
1820     }
1821     connmgr_send_port_status(p->connmgr, pp, OFPPR_ADD);
1822     return;
1823
1824 error:
1825     VLOG_WARN_RL(&rl, "%s: could not add port %s (%s)",
1826                  p->name, netdev_name, strerror(error));
1827     if (ofport) {
1828         ofport_destroy__(ofport);
1829     } else {
1830         netdev_close(netdev);
1831     }
1832 }
1833
1834 /* Removes 'ofport' from 'p' and destroys it. */
1835 static void
1836 ofport_remove(struct ofport *ofport)
1837 {
1838     connmgr_send_port_status(ofport->ofproto->connmgr, &ofport->pp,
1839                              OFPPR_DELETE);
1840     ofport_destroy(ofport);
1841 }
1842
1843 /* If 'ofproto' contains an ofport named 'name', removes it from 'ofproto' and
1844  * destroys it. */
1845 static void
1846 ofport_remove_with_name(struct ofproto *ofproto, const char *name)
1847 {
1848     struct ofport *port = shash_find_data(&ofproto->port_by_name, name);
1849     if (port) {
1850         ofport_remove(port);
1851     }
1852 }
1853
1854 /* Updates 'port' with new 'pp' description.
1855  *
1856  * Does not handle a name or port number change.  The caller must implement
1857  * such a change as a delete followed by an add.  */
1858 static void
1859 ofport_modified(struct ofport *port, struct ofputil_phy_port *pp)
1860 {
1861     memcpy(port->pp.hw_addr, pp->hw_addr, ETH_ADDR_LEN);
1862     port->pp.config = ((port->pp.config & ~OFPUTIL_PC_PORT_DOWN)
1863                         | (pp->config & OFPUTIL_PC_PORT_DOWN));
1864     port->pp.state = pp->state;
1865     port->pp.curr = pp->curr;
1866     port->pp.advertised = pp->advertised;
1867     port->pp.supported = pp->supported;
1868     port->pp.peer = pp->peer;
1869     port->pp.curr_speed = pp->curr_speed;
1870     port->pp.max_speed = pp->max_speed;
1871
1872     connmgr_send_port_status(port->ofproto->connmgr, &port->pp, OFPPR_MODIFY);
1873 }
1874
1875 /* Update OpenFlow 'state' in 'port' and notify controller. */
1876 void
1877 ofproto_port_set_state(struct ofport *port, enum ofputil_port_state state)
1878 {
1879     if (port->pp.state != state) {
1880         port->pp.state = state;
1881         connmgr_send_port_status(port->ofproto->connmgr, &port->pp,
1882                                  OFPPR_MODIFY);
1883     }
1884 }
1885
1886 void
1887 ofproto_port_unregister(struct ofproto *ofproto, uint16_t ofp_port)
1888 {
1889     struct ofport *port = ofproto_get_port(ofproto, ofp_port);
1890     if (port) {
1891         if (port->ofproto->ofproto_class->set_realdev) {
1892             port->ofproto->ofproto_class->set_realdev(port, 0, 0);
1893         }
1894         if (port->ofproto->ofproto_class->set_stp_port) {
1895             port->ofproto->ofproto_class->set_stp_port(port, NULL);
1896         }
1897         if (port->ofproto->ofproto_class->set_cfm) {
1898             port->ofproto->ofproto_class->set_cfm(port, NULL);
1899         }
1900         if (port->ofproto->ofproto_class->bundle_remove) {
1901             port->ofproto->ofproto_class->bundle_remove(port);
1902         }
1903     }
1904 }
1905
1906 static void
1907 ofport_destroy__(struct ofport *port)
1908 {
1909     struct ofproto *ofproto = port->ofproto;
1910     const char *name = netdev_get_name(port->netdev);
1911
1912     hmap_remove(&ofproto->ports, &port->hmap_node);
1913     shash_delete(&ofproto->port_by_name,
1914                  shash_find(&ofproto->port_by_name, name));
1915
1916     netdev_close(port->netdev);
1917     ofproto->ofproto_class->port_dealloc(port);
1918 }
1919
1920 static void
1921 ofport_destroy(struct ofport *port)
1922 {
1923     if (port) {
1924         dealloc_ofp_port(port->ofproto, port->ofp_port);
1925         port->ofproto->ofproto_class->port_destruct(port);
1926         ofport_destroy__(port);
1927      }
1928 }
1929
1930 struct ofport *
1931 ofproto_get_port(const struct ofproto *ofproto, uint16_t ofp_port)
1932 {
1933     struct ofport *port;
1934
1935     HMAP_FOR_EACH_IN_BUCKET (port, hmap_node,
1936                              hash_int(ofp_port, 0), &ofproto->ports) {
1937         if (port->ofp_port == ofp_port) {
1938             return port;
1939         }
1940     }
1941     return NULL;
1942 }
1943
1944 int
1945 ofproto_port_get_stats(const struct ofport *port, struct netdev_stats *stats)
1946 {
1947     struct ofproto *ofproto = port->ofproto;
1948     int error;
1949
1950     if (ofproto->ofproto_class->port_get_stats) {
1951         error = ofproto->ofproto_class->port_get_stats(port, stats);
1952     } else {
1953         error = EOPNOTSUPP;
1954     }
1955
1956     return error;
1957 }
1958
1959 static void
1960 update_port(struct ofproto *ofproto, const char *name)
1961 {
1962     struct ofproto_port ofproto_port;
1963     struct ofputil_phy_port pp;
1964     struct netdev *netdev;
1965     struct ofport *port;
1966
1967     COVERAGE_INC(ofproto_update_port);
1968
1969     /* Fetch 'name''s location and properties from the datapath. */
1970     netdev = (!ofproto_port_query_by_name(ofproto, name, &ofproto_port)
1971               ? ofport_open(ofproto, &ofproto_port, &pp)
1972               : NULL);
1973     if (netdev) {
1974         port = ofproto_get_port(ofproto, ofproto_port.ofp_port);
1975         if (port && !strcmp(netdev_get_name(port->netdev), name)) {
1976             struct netdev *old_netdev = port->netdev;
1977
1978             /* 'name' hasn't changed location.  Any properties changed? */
1979             if (!ofport_equal(&port->pp, &pp)) {
1980                 ofport_modified(port, &pp);
1981             }
1982
1983             update_mtu(ofproto, port);
1984
1985             /* Install the newly opened netdev in case it has changed.
1986              * Don't close the old netdev yet in case port_modified has to
1987              * remove a retained reference to it.*/
1988             port->netdev = netdev;
1989             port->change_seq = netdev_change_seq(netdev);
1990
1991             if (port->ofproto->ofproto_class->port_modified) {
1992                 port->ofproto->ofproto_class->port_modified(port);
1993             }
1994
1995             netdev_close(old_netdev);
1996         } else {
1997             /* If 'port' is nonnull then its name differs from 'name' and thus
1998              * we should delete it.  If we think there's a port named 'name'
1999              * then its port number must be wrong now so delete it too. */
2000             if (port) {
2001                 ofport_remove(port);
2002             }
2003             ofport_remove_with_name(ofproto, name);
2004             ofport_install(ofproto, netdev, &pp);
2005         }
2006     } else {
2007         /* Any port named 'name' is gone now. */
2008         ofport_remove_with_name(ofproto, name);
2009     }
2010     ofproto_port_destroy(&ofproto_port);
2011 }
2012
2013 static int
2014 init_ports(struct ofproto *p)
2015 {
2016     struct ofproto_port_dump dump;
2017     struct ofproto_port ofproto_port;
2018     struct shash_node *node, *next;
2019
2020     OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
2021         const char *name = ofproto_port.name;
2022
2023         if (shash_find(&p->port_by_name, name)) {
2024             VLOG_WARN_RL(&rl, "%s: ignoring duplicate device %s in datapath",
2025                          p->name, name);
2026         } else {
2027             struct ofputil_phy_port pp;
2028             struct netdev *netdev;
2029
2030             /* Check if an OpenFlow port number had been requested. */
2031             node = shash_find(&init_ofp_ports, name);
2032             if (node) {
2033                 const struct iface_hint *iface_hint = node->data;
2034                 simap_put(&p->ofp_requests, name, iface_hint->ofp_port);
2035             }
2036
2037             netdev = ofport_open(p, &ofproto_port, &pp);
2038             if (netdev) {
2039                 ofport_install(p, netdev, &pp);
2040             }
2041         }
2042     }
2043
2044     SHASH_FOR_EACH_SAFE(node, next, &init_ofp_ports) {
2045         struct iface_hint *iface_hint = node->data;
2046
2047         if (!strcmp(iface_hint->br_name, p->name)) {
2048             free(iface_hint->br_name);
2049             free(iface_hint->br_type);
2050             free(iface_hint);
2051             shash_delete(&init_ofp_ports, node);
2052         }
2053     }
2054
2055     return 0;
2056 }
2057
2058 /* Find the minimum MTU of all non-datapath devices attached to 'p'.
2059  * Returns ETH_PAYLOAD_MAX or the minimum of the ports. */
2060 static int
2061 find_min_mtu(struct ofproto *p)
2062 {
2063     struct ofport *ofport;
2064     int mtu = 0;
2065
2066     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2067         struct netdev *netdev = ofport->netdev;
2068         int dev_mtu;
2069
2070         /* Skip any internal ports, since that's what we're trying to
2071          * set. */
2072         if (!strcmp(netdev_get_type(netdev), "internal")) {
2073             continue;
2074         }
2075
2076         if (netdev_get_mtu(netdev, &dev_mtu)) {
2077             continue;
2078         }
2079         if (!mtu || dev_mtu < mtu) {
2080             mtu = dev_mtu;
2081         }
2082     }
2083
2084     return mtu ? mtu: ETH_PAYLOAD_MAX;
2085 }
2086
2087 /* Update MTU of all datapath devices on 'p' to the minimum of the
2088  * non-datapath ports in event of 'port' added or changed. */
2089 static void
2090 update_mtu(struct ofproto *p, struct ofport *port)
2091 {
2092     struct ofport *ofport;
2093     struct netdev *netdev = port->netdev;
2094     int dev_mtu, old_min;
2095
2096     if (netdev_get_mtu(netdev, &dev_mtu)) {
2097         port->mtu = 0;
2098         return;
2099     }
2100     if (!strcmp(netdev_get_type(port->netdev), "internal")) {
2101         if (dev_mtu > p->min_mtu) {
2102            if (!netdev_set_mtu(port->netdev, p->min_mtu)) {
2103                dev_mtu = p->min_mtu;
2104            }
2105         }
2106         port->mtu = dev_mtu;
2107         return;
2108     }
2109
2110     /* For non-internal port find new min mtu. */
2111     old_min = p->min_mtu;
2112     port->mtu = dev_mtu;
2113     p->min_mtu = find_min_mtu(p);
2114     if (p->min_mtu == old_min) {
2115         return;
2116     }
2117
2118     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2119         struct netdev *netdev = ofport->netdev;
2120
2121         if (!strcmp(netdev_get_type(netdev), "internal")) {
2122             if (!netdev_set_mtu(netdev, p->min_mtu)) {
2123                 ofport->mtu = p->min_mtu;
2124             }
2125         }
2126     }
2127 }
2128 \f
2129 static void
2130 ofproto_rule_destroy__(struct rule *rule)
2131 {
2132     if (rule) {
2133         cls_rule_destroy(&rule->cr);
2134         free(rule->ofpacts);
2135         rule->ofproto->ofproto_class->rule_dealloc(rule);
2136     }
2137 }
2138
2139 /* This function allows an ofproto implementation to destroy any rules that
2140  * remain when its ->destruct() function is called.  The caller must have
2141  * already uninitialized any derived members of 'rule' (step 5 described in the
2142  * large comment in ofproto/ofproto-provider.h titled "Life Cycle").
2143  * This function implements steps 6 and 7.
2144  *
2145  * This function should only be called from an ofproto implementation's
2146  * ->destruct() function.  It is not suitable elsewhere. */
2147 void
2148 ofproto_rule_destroy(struct rule *rule)
2149 {
2150     ovs_assert(!rule->pending);
2151     oftable_remove_rule(rule);
2152     ofproto_rule_destroy__(rule);
2153 }
2154
2155 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
2156  * that outputs to 'port' (output to OFPP_FLOOD and OFPP_ALL doesn't count). */
2157 bool
2158 ofproto_rule_has_out_port(const struct rule *rule, uint16_t port)
2159 {
2160     return (port == OFPP_ANY
2161             || ofpacts_output_to_port(rule->ofpacts, rule->ofpacts_len, port));
2162 }
2163
2164 /* Returns true if a rule related to 'op' has an OpenFlow OFPAT_OUTPUT or
2165  * OFPAT_ENQUEUE action that outputs to 'out_port'. */
2166 bool
2167 ofoperation_has_out_port(const struct ofoperation *op, uint16_t out_port)
2168 {
2169     if (ofproto_rule_has_out_port(op->rule, out_port)) {
2170         return true;
2171     }
2172
2173     switch (op->type) {
2174     case OFOPERATION_ADD:
2175         return op->victim && ofproto_rule_has_out_port(op->victim, out_port);
2176
2177     case OFOPERATION_DELETE:
2178         return false;
2179
2180     case OFOPERATION_MODIFY:
2181         return ofpacts_output_to_port(op->ofpacts, op->ofpacts_len, out_port);
2182     }
2183
2184     NOT_REACHED();
2185 }
2186
2187 /* Executes the actions indicated by 'rule' on 'packet' and credits 'rule''s
2188  * statistics appropriately.  'packet' must have at least sizeof(struct
2189  * ofp10_packet_in) bytes of headroom.
2190  *
2191  * 'packet' doesn't necessarily have to match 'rule'.  'rule' will be credited
2192  * with statistics for 'packet' either way.
2193  *
2194  * Takes ownership of 'packet'. */
2195 static int
2196 rule_execute(struct rule *rule, uint16_t in_port, struct ofpbuf *packet)
2197 {
2198     struct flow flow;
2199
2200     ovs_assert(ofpbuf_headroom(packet) >= sizeof(struct ofp10_packet_in));
2201
2202     flow_extract(packet, 0, 0, NULL, in_port, &flow);
2203     return rule->ofproto->ofproto_class->rule_execute(rule, &flow, packet);
2204 }
2205
2206 /* Returns true if 'rule' should be hidden from the controller.
2207  *
2208  * Rules with priority higher than UINT16_MAX are set up by ofproto itself
2209  * (e.g. by in-band control) and are intentionally hidden from the
2210  * controller. */
2211 bool
2212 ofproto_rule_is_hidden(const struct rule *rule)
2213 {
2214     return rule->cr.priority > UINT16_MAX;
2215 }
2216
2217 static enum oftable_flags
2218 rule_get_flags(const struct rule *rule)
2219 {
2220     return rule->ofproto->tables[rule->table_id].flags;
2221 }
2222
2223 static bool
2224 rule_is_modifiable(const struct rule *rule)
2225 {
2226     return !(rule_get_flags(rule) & OFTABLE_READONLY);
2227 }
2228 \f
2229 static enum ofperr
2230 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
2231 {
2232     ofconn_send_reply(ofconn, make_echo_reply(oh));
2233     return 0;
2234 }
2235
2236 static enum ofperr
2237 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
2238 {
2239     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2240     struct ofputil_switch_features features;
2241     struct ofport *port;
2242     bool arp_match_ip;
2243     struct ofpbuf *b;
2244     int n_tables;
2245     int i;
2246
2247     ofproto->ofproto_class->get_features(ofproto, &arp_match_ip,
2248                                          &features.actions);
2249     ovs_assert(features.actions & OFPUTIL_A_OUTPUT); /* sanity check */
2250
2251     /* Count only non-hidden tables in the number of tables.  (Hidden tables,
2252      * if present, are always at the end.) */
2253     n_tables = ofproto->n_tables;
2254     for (i = 0; i < ofproto->n_tables; i++) {
2255         if (ofproto->tables[i].flags & OFTABLE_HIDDEN) {
2256             n_tables = i;
2257             break;
2258         }
2259     }
2260
2261     features.datapath_id = ofproto->datapath_id;
2262     features.n_buffers = pktbuf_capacity();
2263     features.n_tables = n_tables;
2264     features.capabilities = (OFPUTIL_C_FLOW_STATS | OFPUTIL_C_TABLE_STATS |
2265                              OFPUTIL_C_PORT_STATS | OFPUTIL_C_QUEUE_STATS);
2266     if (arp_match_ip) {
2267         features.capabilities |= OFPUTIL_C_ARP_MATCH_IP;
2268     }
2269     /* FIXME: Fill in proper features.auxiliary_id for auxiliary connections */
2270     features.auxiliary_id = 0;
2271     b = ofputil_encode_switch_features(&features, ofconn_get_protocol(ofconn),
2272                                        oh->xid);
2273     HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
2274         ofputil_put_switch_features_port(&port->pp, b);
2275     }
2276
2277     ofconn_send_reply(ofconn, b);
2278     return 0;
2279 }
2280
2281 static enum ofperr
2282 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
2283 {
2284     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2285     struct ofp_switch_config *osc;
2286     enum ofp_config_flags flags;
2287     struct ofpbuf *buf;
2288
2289     /* Send reply. */
2290     buf = ofpraw_alloc_reply(OFPRAW_OFPT_GET_CONFIG_REPLY, oh, 0);
2291     osc = ofpbuf_put_uninit(buf, sizeof *osc);
2292     flags = ofproto->frag_handling;
2293     /* OFPC_INVALID_TTL_TO_CONTROLLER is deprecated in OF 1.3 */
2294     if (oh->version < OFP13_VERSION
2295         && ofconn_get_invalid_ttl_to_controller(ofconn)) {
2296         flags |= OFPC_INVALID_TTL_TO_CONTROLLER;
2297     }
2298     osc->flags = htons(flags);
2299     osc->miss_send_len = htons(ofconn_get_miss_send_len(ofconn));
2300     ofconn_send_reply(ofconn, buf);
2301
2302     return 0;
2303 }
2304
2305 static enum ofperr
2306 handle_set_config(struct ofconn *ofconn, const struct ofp_header *oh)
2307 {
2308     const struct ofp_switch_config *osc = ofpmsg_body(oh);
2309     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2310     uint16_t flags = ntohs(osc->flags);
2311
2312     if (ofconn_get_type(ofconn) != OFCONN_PRIMARY
2313         || ofconn_get_role(ofconn) != OFPCR12_ROLE_SLAVE) {
2314         enum ofp_config_flags cur = ofproto->frag_handling;
2315         enum ofp_config_flags next = flags & OFPC_FRAG_MASK;
2316
2317         ovs_assert((cur & OFPC_FRAG_MASK) == cur);
2318         if (cur != next) {
2319             if (ofproto->ofproto_class->set_frag_handling(ofproto, next)) {
2320                 ofproto->frag_handling = next;
2321             } else {
2322                 VLOG_WARN_RL(&rl, "%s: unsupported fragment handling mode %s",
2323                              ofproto->name,
2324                              ofputil_frag_handling_to_string(next));
2325             }
2326         }
2327     }
2328     /* OFPC_INVALID_TTL_TO_CONTROLLER is deprecated in OF 1.3 */
2329     ofconn_set_invalid_ttl_to_controller(ofconn,
2330              (oh->version < OFP13_VERSION
2331               && flags & OFPC_INVALID_TTL_TO_CONTROLLER));
2332
2333     ofconn_set_miss_send_len(ofconn, ntohs(osc->miss_send_len));
2334
2335     return 0;
2336 }
2337
2338 /* Checks whether 'ofconn' is a slave controller.  If so, returns an OpenFlow
2339  * error message code for the caller to propagate upward.  Otherwise, returns
2340  * 0.
2341  *
2342  * The log message mentions 'msg_type'. */
2343 static enum ofperr
2344 reject_slave_controller(struct ofconn *ofconn)
2345 {
2346     if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
2347         && ofconn_get_role(ofconn) == OFPCR12_ROLE_SLAVE) {
2348         return OFPERR_OFPBRC_EPERM;
2349     } else {
2350         return 0;
2351     }
2352 }
2353
2354 static enum ofperr
2355 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
2356 {
2357     struct ofproto *p = ofconn_get_ofproto(ofconn);
2358     struct ofputil_packet_out po;
2359     struct ofpbuf *payload;
2360     uint64_t ofpacts_stub[1024 / 8];
2361     struct ofpbuf ofpacts;
2362     struct flow flow;
2363     enum ofperr error;
2364
2365     COVERAGE_INC(ofproto_packet_out);
2366
2367     error = reject_slave_controller(ofconn);
2368     if (error) {
2369         goto exit;
2370     }
2371
2372     /* Decode message. */
2373     ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
2374     error = ofputil_decode_packet_out(&po, oh, &ofpacts);
2375     if (error) {
2376         goto exit_free_ofpacts;
2377     }
2378     if (po.in_port >= p->max_ports && po.in_port < OFPP_MAX) {
2379         error = OFPERR_OFPBRC_BAD_PORT;
2380         goto exit_free_ofpacts;
2381     }
2382
2383
2384     /* Get payload. */
2385     if (po.buffer_id != UINT32_MAX) {
2386         error = ofconn_pktbuf_retrieve(ofconn, po.buffer_id, &payload, NULL);
2387         if (error || !payload) {
2388             goto exit_free_ofpacts;
2389         }
2390     } else {
2391         payload = xmalloc(sizeof *payload);
2392         ofpbuf_use_const(payload, po.packet, po.packet_len);
2393     }
2394
2395     /* Verify actions against packet, then send packet if successful. */
2396     flow_extract(payload, 0, 0, NULL, po.in_port, &flow);
2397     error = ofpacts_check(po.ofpacts, po.ofpacts_len, &flow, p->max_ports);
2398     if (!error) {
2399         error = p->ofproto_class->packet_out(p, payload, &flow,
2400                                              po.ofpacts, po.ofpacts_len);
2401     }
2402     ofpbuf_delete(payload);
2403
2404 exit_free_ofpacts:
2405     ofpbuf_uninit(&ofpacts);
2406 exit:
2407     return error;
2408 }
2409
2410 static void
2411 update_port_config(struct ofport *port,
2412                    enum ofputil_port_config config,
2413                    enum ofputil_port_config mask)
2414 {
2415     enum ofputil_port_config old_config = port->pp.config;
2416     enum ofputil_port_config toggle;
2417
2418     toggle = (config ^ port->pp.config) & mask;
2419     if (toggle & OFPUTIL_PC_PORT_DOWN) {
2420         if (config & OFPUTIL_PC_PORT_DOWN) {
2421             netdev_turn_flags_off(port->netdev, NETDEV_UP, NULL);
2422         } else {
2423             netdev_turn_flags_on(port->netdev, NETDEV_UP, NULL);
2424         }
2425         toggle &= ~OFPUTIL_PC_PORT_DOWN;
2426     }
2427
2428     port->pp.config ^= toggle;
2429     if (port->pp.config != old_config) {
2430         port->ofproto->ofproto_class->port_reconfigured(port, old_config);
2431     }
2432 }
2433
2434 static enum ofperr
2435 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
2436 {
2437     struct ofproto *p = ofconn_get_ofproto(ofconn);
2438     struct ofputil_port_mod pm;
2439     struct ofport *port;
2440     enum ofperr error;
2441
2442     error = reject_slave_controller(ofconn);
2443     if (error) {
2444         return error;
2445     }
2446
2447     error = ofputil_decode_port_mod(oh, &pm);
2448     if (error) {
2449         return error;
2450     }
2451
2452     port = ofproto_get_port(p, pm.port_no);
2453     if (!port) {
2454         return OFPERR_OFPPMFC_BAD_PORT;
2455     } else if (!eth_addr_equals(port->pp.hw_addr, pm.hw_addr)) {
2456         return OFPERR_OFPPMFC_BAD_HW_ADDR;
2457     } else {
2458         update_port_config(port, pm.config, pm.mask);
2459         if (pm.advertise) {
2460             netdev_set_advertisements(port->netdev, pm.advertise);
2461         }
2462     }
2463     return 0;
2464 }
2465
2466 static enum ofperr
2467 handle_desc_stats_request(struct ofconn *ofconn,
2468                           const struct ofp_header *request)
2469 {
2470     static const char *default_mfr_desc = "Nicira, Inc.";
2471     static const char *default_hw_desc = "Open vSwitch";
2472     static const char *default_sw_desc = VERSION;
2473     static const char *default_serial_desc = "None";
2474     static const char *default_dp_desc = "None";
2475
2476     struct ofproto *p = ofconn_get_ofproto(ofconn);
2477     struct ofp_desc_stats *ods;
2478     struct ofpbuf *msg;
2479
2480     msg = ofpraw_alloc_stats_reply(request, 0);
2481     ods = ofpbuf_put_zeros(msg, sizeof *ods);
2482     ovs_strlcpy(ods->mfr_desc, p->mfr_desc ? p->mfr_desc : default_mfr_desc,
2483                 sizeof ods->mfr_desc);
2484     ovs_strlcpy(ods->hw_desc, p->hw_desc ? p->hw_desc : default_hw_desc,
2485                 sizeof ods->hw_desc);
2486     ovs_strlcpy(ods->sw_desc, p->sw_desc ? p->sw_desc : default_sw_desc,
2487                 sizeof ods->sw_desc);
2488     ovs_strlcpy(ods->serial_num,
2489                 p->serial_desc ? p->serial_desc : default_serial_desc,
2490                 sizeof ods->serial_num);
2491     ovs_strlcpy(ods->dp_desc, p->dp_desc ? p->dp_desc : default_dp_desc,
2492                 sizeof ods->dp_desc);
2493     ofconn_send_reply(ofconn, msg);
2494
2495     return 0;
2496 }
2497
2498 static enum ofperr
2499 handle_table_stats_request(struct ofconn *ofconn,
2500                            const struct ofp_header *request)
2501 {
2502     struct ofproto *p = ofconn_get_ofproto(ofconn);
2503     struct ofp12_table_stats *ots;
2504     struct ofpbuf *msg;
2505     int n_tables;
2506     size_t i;
2507
2508     /* Set up default values.
2509      *
2510      * ofp12_table_stats is used as a generic structure as
2511      * it is able to hold all the fields for ofp10_table_stats
2512      * and ofp11_table_stats (and of course itself).
2513      */
2514     ots = xcalloc(p->n_tables, sizeof *ots);
2515     for (i = 0; i < p->n_tables; i++) {
2516         ots[i].table_id = i;
2517         sprintf(ots[i].name, "table%zu", i);
2518         ots[i].match = htonll(OFPXMT12_MASK);
2519         ots[i].wildcards = htonll(OFPXMT12_MASK);
2520         ots[i].write_actions = htonl(OFPAT11_OUTPUT);
2521         ots[i].apply_actions = htonl(OFPAT11_OUTPUT);
2522         ots[i].write_setfields = htonll(OFPXMT12_MASK);
2523         ots[i].apply_setfields = htonll(OFPXMT12_MASK);
2524         ots[i].metadata_match = htonll(UINT64_MAX);
2525         ots[i].metadata_write = htonll(UINT64_MAX);
2526         ots[i].instructions = htonl(OFPIT11_ALL);
2527         ots[i].config = htonl(OFPTC11_TABLE_MISS_MASK);
2528         ots[i].max_entries = htonl(1000000); /* An arbitrary big number. */
2529         ots[i].active_count = htonl(classifier_count(&p->tables[i].cls));
2530     }
2531
2532     p->ofproto_class->get_tables(p, ots);
2533
2534     /* Post-process the tables, dropping hidden tables. */
2535     n_tables = p->n_tables;
2536     for (i = 0; i < p->n_tables; i++) {
2537         const struct oftable *table = &p->tables[i];
2538
2539         if (table->flags & OFTABLE_HIDDEN) {
2540             n_tables = i;
2541             break;
2542         }
2543
2544         if (table->name) {
2545             ovs_strzcpy(ots[i].name, table->name, sizeof ots[i].name);
2546         }
2547
2548         if (table->max_flows < ntohl(ots[i].max_entries)) {
2549             ots[i].max_entries = htonl(table->max_flows);
2550         }
2551     }
2552
2553     msg = ofputil_encode_table_stats_reply(ots, n_tables, request);
2554     ofconn_send_reply(ofconn, msg);
2555
2556     free(ots);
2557
2558     return 0;
2559 }
2560
2561 static void
2562 append_port_stat(struct ofport *port, struct list *replies)
2563 {
2564     struct ofputil_port_stats ops = { .port_no = port->pp.port_no };
2565
2566     calc_duration(port->created, time_msec(),
2567                   &ops.duration_sec, &ops.duration_nsec);
2568
2569     /* Intentionally ignore return value, since errors will set
2570      * 'stats' to all-1s, which is correct for OpenFlow, and
2571      * netdev_get_stats() will log errors. */
2572     ofproto_port_get_stats(port, &ops.stats);
2573
2574     ofputil_append_port_stat(replies, &ops);
2575 }
2576
2577 static enum ofperr
2578 handle_port_stats_request(struct ofconn *ofconn,
2579                           const struct ofp_header *request)
2580 {
2581     struct ofproto *p = ofconn_get_ofproto(ofconn);
2582     struct ofport *port;
2583     struct list replies;
2584     uint16_t port_no;
2585     enum ofperr error;
2586
2587     error = ofputil_decode_port_stats_request(request, &port_no);
2588     if (error) {
2589         return error;
2590     }
2591
2592     ofpmp_init(&replies, request);
2593     if (port_no != OFPP_ANY) {
2594         port = ofproto_get_port(p, port_no);
2595         if (port) {
2596             append_port_stat(port, &replies);
2597         }
2598     } else {
2599         HMAP_FOR_EACH (port, hmap_node, &p->ports) {
2600             append_port_stat(port, &replies);
2601         }
2602     }
2603
2604     ofconn_send_replies(ofconn, &replies);
2605     return 0;
2606 }
2607
2608 static enum ofperr
2609 handle_port_desc_stats_request(struct ofconn *ofconn,
2610                                const struct ofp_header *request)
2611 {
2612     struct ofproto *p = ofconn_get_ofproto(ofconn);
2613     enum ofp_version version;
2614     struct ofport *port;
2615     struct list replies;
2616
2617     ofpmp_init(&replies, request);
2618
2619     version = ofputil_protocol_to_ofp_version(ofconn_get_protocol(ofconn));
2620     HMAP_FOR_EACH (port, hmap_node, &p->ports) {
2621         ofputil_append_port_desc_stats_reply(version, &port->pp, &replies);
2622     }
2623
2624     ofconn_send_replies(ofconn, &replies);
2625     return 0;
2626 }
2627
2628 static void
2629 calc_duration(long long int start, long long int now,
2630               uint32_t *sec, uint32_t *nsec)
2631 {
2632     long long int msecs = now - start;
2633     *sec = msecs / 1000;
2634     *nsec = (msecs % 1000) * (1000 * 1000);
2635 }
2636
2637 /* Checks whether 'table_id' is 0xff or a valid table ID in 'ofproto'.  Returns
2638  * 0 if 'table_id' is OK, otherwise an OpenFlow error code.  */
2639 static enum ofperr
2640 check_table_id(const struct ofproto *ofproto, uint8_t table_id)
2641 {
2642     return (table_id == 0xff || table_id < ofproto->n_tables
2643             ? 0
2644             : OFPERR_OFPBRC_BAD_TABLE_ID);
2645
2646 }
2647
2648 static struct oftable *
2649 next_visible_table(const struct ofproto *ofproto, uint8_t table_id)
2650 {
2651     struct oftable *table;
2652
2653     for (table = &ofproto->tables[table_id];
2654          table < &ofproto->tables[ofproto->n_tables];
2655          table++) {
2656         if (!(table->flags & OFTABLE_HIDDEN)) {
2657             return table;
2658         }
2659     }
2660
2661     return NULL;
2662 }
2663
2664 static struct oftable *
2665 first_matching_table(const struct ofproto *ofproto, uint8_t table_id)
2666 {
2667     if (table_id == 0xff) {
2668         return next_visible_table(ofproto, 0);
2669     } else if (table_id < ofproto->n_tables) {
2670         return &ofproto->tables[table_id];
2671     } else {
2672         return NULL;
2673     }
2674 }
2675
2676 static struct oftable *
2677 next_matching_table(const struct ofproto *ofproto,
2678                     const struct oftable *table, uint8_t table_id)
2679 {
2680     return (table_id == 0xff
2681             ? next_visible_table(ofproto, (table - ofproto->tables) + 1)
2682             : NULL);
2683 }
2684
2685 /* Assigns TABLE to each oftable, in turn, that matches TABLE_ID in OFPROTO:
2686  *
2687  *   - If TABLE_ID is 0xff, this iterates over every classifier table in
2688  *     OFPROTO, skipping tables marked OFTABLE_HIDDEN.
2689  *
2690  *   - If TABLE_ID is the number of a table in OFPROTO, then the loop iterates
2691  *     only once, for that table.  (This can be used to access tables marked
2692  *     OFTABLE_HIDDEN.)
2693  *
2694  *   - Otherwise, TABLE_ID isn't valid for OFPROTO, so the loop won't be
2695  *     entered at all.  (Perhaps you should have validated TABLE_ID with
2696  *     check_table_id().)
2697  *
2698  * All parameters are evaluated multiple times.
2699  */
2700 #define FOR_EACH_MATCHING_TABLE(TABLE, TABLE_ID, OFPROTO)         \
2701     for ((TABLE) = first_matching_table(OFPROTO, TABLE_ID);       \
2702          (TABLE) != NULL;                                         \
2703          (TABLE) = next_matching_table(OFPROTO, TABLE, TABLE_ID))
2704
2705 /* Searches 'ofproto' for rules in table 'table_id' (or in all tables, if
2706  * 'table_id' is 0xff) that match 'match' in the "loose" way required for
2707  * OpenFlow OFPFC_MODIFY and OFPFC_DELETE requests and puts them on list
2708  * 'rules'.
2709  *
2710  * If 'out_port' is anything other than OFPP_ANY, then only rules that output
2711  * to 'out_port' are included.
2712  *
2713  * Hidden rules are always omitted.
2714  *
2715  * Returns 0 on success, otherwise an OpenFlow error code. */
2716 static enum ofperr
2717 collect_rules_loose(struct ofproto *ofproto, uint8_t table_id,
2718                     const struct match *match,
2719                     ovs_be64 cookie, ovs_be64 cookie_mask,
2720                     uint16_t out_port, struct list *rules)
2721 {
2722     struct oftable *table;
2723     struct cls_rule cr;
2724     enum ofperr error;
2725
2726     error = check_table_id(ofproto, table_id);
2727     if (error) {
2728         return error;
2729     }
2730
2731     list_init(rules);
2732     cls_rule_init(&cr, match, 0);
2733     FOR_EACH_MATCHING_TABLE (table, table_id, ofproto) {
2734         struct cls_cursor cursor;
2735         struct rule *rule;
2736
2737         cls_cursor_init(&cursor, &table->cls, &cr);
2738         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
2739             if (rule->pending) {
2740                 error = OFPROTO_POSTPONE;
2741                 goto exit;
2742             }
2743             if (!ofproto_rule_is_hidden(rule)
2744                 && ofproto_rule_has_out_port(rule, out_port)
2745                     && !((rule->flow_cookie ^ cookie) & cookie_mask)) {
2746                 list_push_back(rules, &rule->ofproto_node);
2747             }
2748         }
2749     }
2750
2751 exit:
2752     cls_rule_destroy(&cr);
2753     return error;
2754 }
2755
2756 /* Searches 'ofproto' for rules in table 'table_id' (or in all tables, if
2757  * 'table_id' is 0xff) that match 'match' in the "strict" way required for
2758  * OpenFlow OFPFC_MODIFY_STRICT and OFPFC_DELETE_STRICT requests and puts them
2759  * on list 'rules'.
2760  *
2761  * If 'out_port' is anything other than OFPP_ANY, then only rules that output
2762  * to 'out_port' are included.
2763  *
2764  * Hidden rules are always omitted.
2765  *
2766  * Returns 0 on success, otherwise an OpenFlow error code. */
2767 static enum ofperr
2768 collect_rules_strict(struct ofproto *ofproto, uint8_t table_id,
2769                      const struct match *match, unsigned int priority,
2770                      ovs_be64 cookie, ovs_be64 cookie_mask,
2771                      uint16_t out_port, struct list *rules)
2772 {
2773     struct oftable *table;
2774     struct cls_rule cr;
2775     int error;
2776
2777     error = check_table_id(ofproto, table_id);
2778     if (error) {
2779         return error;
2780     }
2781
2782     list_init(rules);
2783     cls_rule_init(&cr, match, priority);
2784     FOR_EACH_MATCHING_TABLE (table, table_id, ofproto) {
2785         struct rule *rule;
2786
2787         rule = rule_from_cls_rule(classifier_find_rule_exactly(&table->cls,
2788                                                                &cr));
2789         if (rule) {
2790             if (rule->pending) {
2791                 error = OFPROTO_POSTPONE;
2792                 goto exit;
2793             }
2794             if (!ofproto_rule_is_hidden(rule)
2795                 && ofproto_rule_has_out_port(rule, out_port)
2796                     && !((rule->flow_cookie ^ cookie) & cookie_mask)) {
2797                 list_push_back(rules, &rule->ofproto_node);
2798             }
2799         }
2800     }
2801
2802 exit:
2803     cls_rule_destroy(&cr);
2804     return 0;
2805 }
2806
2807 /* Returns 'age_ms' (a duration in milliseconds), converted to seconds and
2808  * forced into the range of a uint16_t. */
2809 static int
2810 age_secs(long long int age_ms)
2811 {
2812     return (age_ms < 0 ? 0
2813             : age_ms >= UINT16_MAX * 1000 ? UINT16_MAX
2814             : (unsigned int) age_ms / 1000);
2815 }
2816
2817 static enum ofperr
2818 handle_flow_stats_request(struct ofconn *ofconn,
2819                           const struct ofp_header *request)
2820 {
2821     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2822     struct ofputil_flow_stats_request fsr;
2823     struct list replies;
2824     struct list rules;
2825     struct rule *rule;
2826     enum ofperr error;
2827
2828     error = ofputil_decode_flow_stats_request(&fsr, request);
2829     if (error) {
2830         return error;
2831     }
2832
2833     error = collect_rules_loose(ofproto, fsr.table_id, &fsr.match,
2834                                 fsr.cookie, fsr.cookie_mask,
2835                                 fsr.out_port, &rules);
2836     if (error) {
2837         return error;
2838     }
2839
2840     ofpmp_init(&replies, request);
2841     LIST_FOR_EACH (rule, ofproto_node, &rules) {
2842         long long int now = time_msec();
2843         struct ofputil_flow_stats fs;
2844
2845         minimatch_expand(&rule->cr.match, &fs.match);
2846         fs.priority = rule->cr.priority;
2847         fs.cookie = rule->flow_cookie;
2848         fs.table_id = rule->table_id;
2849         calc_duration(rule->created, now, &fs.duration_sec, &fs.duration_nsec);
2850         fs.idle_timeout = rule->idle_timeout;
2851         fs.hard_timeout = rule->hard_timeout;
2852         fs.idle_age = age_secs(now - rule->used);
2853         fs.hard_age = age_secs(now - rule->modified);
2854         ofproto->ofproto_class->rule_get_stats(rule, &fs.packet_count,
2855                                                &fs.byte_count);
2856         fs.ofpacts = rule->ofpacts;
2857         fs.ofpacts_len = rule->ofpacts_len;
2858         fs.flags = 0;
2859         if (rule->send_flow_removed) {
2860             fs.flags |= OFPFF_SEND_FLOW_REM;
2861             /* FIXME: Implement OF 1.3 flags OFPFF13_NO_PKT_COUNTS
2862                and OFPFF13_NO_BYT_COUNTS */
2863         }
2864         ofputil_append_flow_stats_reply(&fs, &replies);
2865     }
2866     ofconn_send_replies(ofconn, &replies);
2867
2868     return 0;
2869 }
2870
2871 static void
2872 flow_stats_ds(struct rule *rule, struct ds *results)
2873 {
2874     uint64_t packet_count, byte_count;
2875
2876     rule->ofproto->ofproto_class->rule_get_stats(rule,
2877                                                  &packet_count, &byte_count);
2878
2879     if (rule->table_id != 0) {
2880         ds_put_format(results, "table_id=%"PRIu8", ", rule->table_id);
2881     }
2882     ds_put_format(results, "duration=%llds, ",
2883                   (time_msec() - rule->created) / 1000);
2884     ds_put_format(results, "priority=%u, ", rule->cr.priority);
2885     ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
2886     ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
2887     cls_rule_format(&rule->cr, results);
2888     ds_put_char(results, ',');
2889     ofpacts_format(rule->ofpacts, rule->ofpacts_len, results);
2890     ds_put_cstr(results, "\n");
2891 }
2892
2893 /* Adds a pretty-printed description of all flows to 'results', including
2894  * hidden flows (e.g., set up by in-band control). */
2895 void
2896 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
2897 {
2898     struct oftable *table;
2899
2900     OFPROTO_FOR_EACH_TABLE (table, p) {
2901         struct cls_cursor cursor;
2902         struct rule *rule;
2903
2904         cls_cursor_init(&cursor, &table->cls, NULL);
2905         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
2906             flow_stats_ds(rule, results);
2907         }
2908     }
2909 }
2910
2911 /* Obtains the NetFlow engine type and engine ID for 'ofproto' into
2912  * '*engine_type' and '*engine_id', respectively. */
2913 void
2914 ofproto_get_netflow_ids(const struct ofproto *ofproto,
2915                         uint8_t *engine_type, uint8_t *engine_id)
2916 {
2917     ofproto->ofproto_class->get_netflow_ids(ofproto, engine_type, engine_id);
2918 }
2919
2920 /* Checks the status of CFM configured on 'ofp_port' within 'ofproto'.  Returns
2921  * true if the port's CFM status was successfully stored into '*status'.
2922  * Returns false if the port did not have CFM configured, in which case
2923  * '*status' is indeterminate.
2924  *
2925  * The caller must provide and owns '*status', but it does not own and must not
2926  * modify or free the array returned in 'status->rmps'. */
2927 bool
2928 ofproto_port_get_cfm_status(const struct ofproto *ofproto, uint16_t ofp_port,
2929                             struct ofproto_cfm_status *status)
2930 {
2931     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
2932     return (ofport
2933             && ofproto->ofproto_class->get_cfm_status
2934             && ofproto->ofproto_class->get_cfm_status(ofport, status));
2935 }
2936
2937 static enum ofperr
2938 handle_aggregate_stats_request(struct ofconn *ofconn,
2939                                const struct ofp_header *oh)
2940 {
2941     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2942     struct ofputil_flow_stats_request request;
2943     struct ofputil_aggregate_stats stats;
2944     bool unknown_packets, unknown_bytes;
2945     struct ofpbuf *reply;
2946     struct list rules;
2947     struct rule *rule;
2948     enum ofperr error;
2949
2950     error = ofputil_decode_flow_stats_request(&request, oh);
2951     if (error) {
2952         return error;
2953     }
2954
2955     error = collect_rules_loose(ofproto, request.table_id, &request.match,
2956                                 request.cookie, request.cookie_mask,
2957                                 request.out_port, &rules);
2958     if (error) {
2959         return error;
2960     }
2961
2962     memset(&stats, 0, sizeof stats);
2963     unknown_packets = unknown_bytes = false;
2964     LIST_FOR_EACH (rule, ofproto_node, &rules) {
2965         uint64_t packet_count;
2966         uint64_t byte_count;
2967
2968         ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
2969                                                &byte_count);
2970
2971         if (packet_count == UINT64_MAX) {
2972             unknown_packets = true;
2973         } else {
2974             stats.packet_count += packet_count;
2975         }
2976
2977         if (byte_count == UINT64_MAX) {
2978             unknown_bytes = true;
2979         } else {
2980             stats.byte_count += byte_count;
2981         }
2982
2983         stats.flow_count++;
2984     }
2985     if (unknown_packets) {
2986         stats.packet_count = UINT64_MAX;
2987     }
2988     if (unknown_bytes) {
2989         stats.byte_count = UINT64_MAX;
2990     }
2991
2992     reply = ofputil_encode_aggregate_stats_reply(&stats, oh);
2993     ofconn_send_reply(ofconn, reply);
2994
2995     return 0;
2996 }
2997
2998 struct queue_stats_cbdata {
2999     struct ofport *ofport;
3000     struct list replies;
3001 };
3002
3003 static void
3004 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
3005                 const struct netdev_queue_stats *stats)
3006 {
3007
3008     struct ofputil_queue_stats oqs = {
3009         .port_no = cbdata->ofport->pp.port_no,
3010         .queue_id = queue_id,
3011         .stats = *stats,
3012     };
3013     ofputil_append_queue_stat(&cbdata->replies, &oqs);
3014 }
3015
3016 static void
3017 handle_queue_stats_dump_cb(uint32_t queue_id,
3018                            struct netdev_queue_stats *stats,
3019                            void *cbdata_)
3020 {
3021     struct queue_stats_cbdata *cbdata = cbdata_;
3022
3023     put_queue_stats(cbdata, queue_id, stats);
3024 }
3025
3026 static enum ofperr
3027 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
3028                             struct queue_stats_cbdata *cbdata)
3029 {
3030     cbdata->ofport = port;
3031     if (queue_id == OFPQ_ALL) {
3032         netdev_dump_queue_stats(port->netdev,
3033                                 handle_queue_stats_dump_cb, cbdata);
3034     } else {
3035         struct netdev_queue_stats stats;
3036
3037         if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
3038             put_queue_stats(cbdata, queue_id, &stats);
3039         } else {
3040             return OFPERR_OFPQOFC_BAD_QUEUE;
3041         }
3042     }
3043     return 0;
3044 }
3045
3046 static enum ofperr
3047 handle_queue_stats_request(struct ofconn *ofconn,
3048                            const struct ofp_header *rq)
3049 {
3050     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3051     struct queue_stats_cbdata cbdata;
3052     struct ofport *port;
3053     enum ofperr error;
3054     struct ofputil_queue_stats_request oqsr;
3055
3056     COVERAGE_INC(ofproto_queue_req);
3057
3058     ofpmp_init(&cbdata.replies, rq);
3059
3060     error = ofputil_decode_queue_stats_request(rq, &oqsr);
3061     if (error) {
3062         return error;
3063     }
3064
3065     if (oqsr.port_no == OFPP_ANY) {
3066         error = OFPERR_OFPQOFC_BAD_QUEUE;
3067         HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3068             if (!handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)) {
3069                 error = 0;
3070             }
3071         }
3072     } else {
3073         port = ofproto_get_port(ofproto, oqsr.port_no);
3074         error = (port
3075                  ? handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)
3076                  : OFPERR_OFPQOFC_BAD_PORT);
3077     }
3078     if (!error) {
3079         ofconn_send_replies(ofconn, &cbdata.replies);
3080     } else {
3081         ofpbuf_list_delete(&cbdata.replies);
3082     }
3083
3084     return error;
3085 }
3086
3087 static bool
3088 is_flow_deletion_pending(const struct ofproto *ofproto,
3089                          const struct cls_rule *cls_rule,
3090                          uint8_t table_id)
3091 {
3092     if (!hmap_is_empty(&ofproto->deletions)) {
3093         struct ofoperation *op;
3094
3095         HMAP_FOR_EACH_WITH_HASH (op, hmap_node,
3096                                  cls_rule_hash(cls_rule, table_id),
3097                                  &ofproto->deletions) {
3098             if (cls_rule_equal(cls_rule, &op->rule->cr)) {
3099                 return true;
3100             }
3101         }
3102     }
3103
3104     return false;
3105 }
3106
3107 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
3108  * in which no matching flow already exists in the flow table.
3109  *
3110  * Adds the flow specified by 'ofm', which is followed by 'n_actions'
3111  * ofp_actions, to the ofproto's flow table.  Returns 0 on success, an OpenFlow
3112  * error code on failure, or OFPROTO_POSTPONE if the operation cannot be
3113  * initiated now but may be retried later.
3114  *
3115  * Upon successful return, takes ownership of 'fm->ofpacts'.  On failure,
3116  * ownership remains with the caller.
3117  *
3118  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3119  * if any. */
3120 static enum ofperr
3121 add_flow(struct ofproto *ofproto, struct ofconn *ofconn,
3122          const struct ofputil_flow_mod *fm, const struct ofp_header *request)
3123 {
3124     struct oftable *table;
3125     struct ofopgroup *group;
3126     struct rule *victim;
3127     struct cls_rule cr;
3128     struct rule *rule;
3129     int error;
3130
3131     error = check_table_id(ofproto, fm->table_id);
3132     if (error) {
3133         return error;
3134     }
3135
3136     /* Pick table. */
3137     if (fm->table_id == 0xff) {
3138         uint8_t table_id;
3139         if (ofproto->ofproto_class->rule_choose_table) {
3140             error = ofproto->ofproto_class->rule_choose_table(ofproto,
3141                                                               &fm->match,
3142                                                               &table_id);
3143             if (error) {
3144                 return error;
3145             }
3146             ovs_assert(table_id < ofproto->n_tables);
3147             table = &ofproto->tables[table_id];
3148         } else {
3149             table = &ofproto->tables[0];
3150         }
3151     } else if (fm->table_id < ofproto->n_tables) {
3152         table = &ofproto->tables[fm->table_id];
3153     } else {
3154         return OFPERR_OFPBRC_BAD_TABLE_ID;
3155     }
3156
3157     if (table->flags & OFTABLE_READONLY) {
3158         return OFPERR_OFPBRC_EPERM;
3159     }
3160
3161     /* Allocate new rule and initialize classifier rule. */
3162     rule = ofproto->ofproto_class->rule_alloc();
3163     if (!rule) {
3164         VLOG_WARN_RL(&rl, "%s: failed to create rule (%s)",
3165                      ofproto->name, strerror(error));
3166         return ENOMEM;
3167     }
3168     cls_rule_init(&rule->cr, &fm->match, fm->priority);
3169
3170     /* Serialize against pending deletion. */
3171     if (is_flow_deletion_pending(ofproto, &cr, table - ofproto->tables)) {
3172         cls_rule_destroy(&rule->cr);
3173         ofproto->ofproto_class->rule_dealloc(rule);
3174         return OFPROTO_POSTPONE;
3175     }
3176
3177     /* Check for overlap, if requested. */
3178     if (fm->flags & OFPFF_CHECK_OVERLAP
3179         && classifier_rule_overlaps(&table->cls, &rule->cr)) {
3180         cls_rule_destroy(&rule->cr);
3181         ofproto->ofproto_class->rule_dealloc(rule);
3182         return OFPERR_OFPFMFC_OVERLAP;
3183     }
3184
3185     /* FIXME: Implement OFPFF12_RESET_COUNTS */
3186
3187     rule->ofproto = ofproto;
3188     rule->pending = NULL;
3189     rule->flow_cookie = fm->new_cookie;
3190     rule->created = rule->modified = rule->used = time_msec();
3191     rule->idle_timeout = fm->idle_timeout;
3192     rule->hard_timeout = fm->hard_timeout;
3193     rule->table_id = table - ofproto->tables;
3194     rule->send_flow_removed = (fm->flags & OFPFF_SEND_FLOW_REM) != 0;
3195     /* FIXME: Implement OF 1.3 flags OFPFF13_NO_PKT_COUNTS
3196        and OFPFF13_NO_BYT_COUNTS */
3197     rule->ofpacts = xmemdup(fm->ofpacts, fm->ofpacts_len);
3198     rule->ofpacts_len = fm->ofpacts_len;
3199     rule->evictable = true;
3200     rule->eviction_group = NULL;
3201     list_init(&rule->expirable);
3202     rule->monitor_flags = 0;
3203     rule->add_seqno = 0;
3204     rule->modify_seqno = 0;
3205
3206     /* Insert new rule. */
3207     victim = oftable_replace_rule(rule);
3208     if (victim && !rule_is_modifiable(victim)) {
3209         error = OFPERR_OFPBRC_EPERM;
3210     } else if (victim && victim->pending) {
3211         error = OFPROTO_POSTPONE;
3212     } else {
3213         struct ofoperation *op;
3214         struct rule *evict;
3215
3216         if (classifier_count(&table->cls) > table->max_flows) {
3217             bool was_evictable;
3218
3219             was_evictable = rule->evictable;
3220             rule->evictable = false;
3221             evict = choose_rule_to_evict(table);
3222             rule->evictable = was_evictable;
3223
3224             if (!evict) {
3225                 error = OFPERR_OFPFMFC_TABLE_FULL;
3226                 goto exit;
3227             } else if (evict->pending) {
3228                 error = OFPROTO_POSTPONE;
3229                 goto exit;
3230             }
3231         } else {
3232             evict = NULL;
3233         }
3234
3235         group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
3236         op = ofoperation_create(group, rule, OFOPERATION_ADD, 0);
3237         op->victim = victim;
3238
3239         error = ofproto->ofproto_class->rule_construct(rule);
3240         if (error) {
3241             op->group->n_running--;
3242             ofoperation_destroy(rule->pending);
3243         } else if (evict) {
3244             delete_flow__(evict, group);
3245         }
3246         ofopgroup_submit(group);
3247     }
3248
3249 exit:
3250     /* Back out if an error occurred. */
3251     if (error) {
3252         oftable_substitute_rule(rule, victim);
3253         ofproto_rule_destroy__(rule);
3254     }
3255     return error;
3256 }
3257 \f
3258 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
3259
3260 /* Modifies the rules listed in 'rules', changing their actions to match those
3261  * in 'fm'.
3262  *
3263  * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
3264  * if any.
3265  *
3266  * Returns 0 on success, otherwise an OpenFlow error code. */
3267 static enum ofperr
3268 modify_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
3269                const struct ofputil_flow_mod *fm,
3270                const struct ofp_header *request, struct list *rules)
3271 {
3272     struct ofopgroup *group;
3273     struct rule *rule;
3274     enum ofperr error;
3275
3276     group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
3277     error = OFPERR_OFPBRC_EPERM;
3278     LIST_FOR_EACH (rule, ofproto_node, rules) {
3279         struct ofoperation *op;
3280         bool actions_changed;
3281         ovs_be64 new_cookie;
3282
3283         /* FIXME: Implement OFPFF12_RESET_COUNTS */
3284
3285         if (rule_is_modifiable(rule)) {
3286             /* At least one rule is modifiable, don't report EPERM error. */
3287             error = 0;
3288         } else {
3289             continue;
3290         }
3291
3292         actions_changed = !ofpacts_equal(fm->ofpacts, fm->ofpacts_len,
3293                                          rule->ofpacts, rule->ofpacts_len);
3294         new_cookie = (fm->new_cookie != htonll(UINT64_MAX)
3295                       ? fm->new_cookie
3296                       : rule->flow_cookie);
3297
3298         op = ofoperation_create(group, rule, OFOPERATION_MODIFY, 0);
3299         rule->flow_cookie = new_cookie;
3300         if (actions_changed) {
3301             op->ofpacts = rule->ofpacts;
3302             op->ofpacts_len = rule->ofpacts_len;
3303             rule->ofpacts = xmemdup(fm->ofpacts, fm->ofpacts_len);
3304             rule->ofpacts_len = fm->ofpacts_len;
3305             rule->ofproto->ofproto_class->rule_modify_actions(rule);
3306         } else {
3307             ofoperation_complete(op, 0);
3308         }
3309     }
3310     ofopgroup_submit(group);
3311
3312     return error;
3313 }
3314
3315 static enum ofperr
3316 modify_flows_add(struct ofproto *ofproto, struct ofconn *ofconn,
3317                  const struct ofputil_flow_mod *fm,
3318                  const struct ofp_header *request)
3319 {
3320     if (fm->cookie_mask != htonll(0) || fm->new_cookie == htonll(UINT64_MAX)) {
3321         return 0;
3322     }
3323     return add_flow(ofproto, ofconn, fm, request);
3324 }
3325
3326 /* Implements OFPFC_MODIFY.  Returns 0 on success or an OpenFlow error code on
3327  * failure.
3328  *
3329  * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
3330  * if any. */
3331 static enum ofperr
3332 modify_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
3333                    const struct ofputil_flow_mod *fm,
3334                    const struct ofp_header *request)
3335 {
3336     struct list rules;
3337     int error;
3338
3339     error = collect_rules_loose(ofproto, fm->table_id, &fm->match,
3340                                 fm->cookie, fm->cookie_mask,
3341                                 OFPP_ANY, &rules);
3342     if (error) {
3343         return error;
3344     } else if (list_is_empty(&rules)) {
3345         return modify_flows_add(ofproto, ofconn, fm, request);
3346     } else {
3347         return modify_flows__(ofproto, ofconn, fm, request, &rules);
3348     }
3349 }
3350
3351 /* Implements OFPFC_MODIFY_STRICT.  Returns 0 on success or an OpenFlow error
3352  * code on failure.
3353  *
3354  * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
3355  * if any. */
3356 static enum ofperr
3357 modify_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
3358                    const struct ofputil_flow_mod *fm,
3359                    const struct ofp_header *request)
3360 {
3361     struct list rules;
3362     int error;
3363
3364     error = collect_rules_strict(ofproto, fm->table_id, &fm->match,
3365                                  fm->priority, fm->cookie, fm->cookie_mask,
3366                                  OFPP_ANY, &rules);
3367
3368     if (error) {
3369         return error;
3370     } else if (list_is_empty(&rules)) {
3371         return modify_flows_add(ofproto, ofconn, fm, request);
3372     } else {
3373         return list_is_singleton(&rules) ? modify_flows__(ofproto, ofconn,
3374                                                           fm, request, &rules)
3375                                          : 0;
3376     }
3377 }
3378 \f
3379 /* OFPFC_DELETE implementation. */
3380
3381 static void
3382 delete_flow__(struct rule *rule, struct ofopgroup *group)
3383 {
3384     struct ofproto *ofproto = rule->ofproto;
3385
3386     ofproto_rule_send_removed(rule, OFPRR_DELETE);
3387
3388     ofoperation_create(group, rule, OFOPERATION_DELETE, OFPRR_DELETE);
3389     oftable_remove_rule(rule);
3390     ofproto->ofproto_class->rule_destruct(rule);
3391 }
3392
3393 /* Deletes the rules listed in 'rules'.
3394  *
3395  * Returns 0 on success, otherwise an OpenFlow error code. */
3396 static enum ofperr
3397 delete_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
3398                const struct ofp_header *request, struct list *rules)
3399 {
3400     struct rule *rule, *next;
3401     struct ofopgroup *group;
3402
3403     group = ofopgroup_create(ofproto, ofconn, request, UINT32_MAX);
3404     LIST_FOR_EACH_SAFE (rule, next, ofproto_node, rules) {
3405         delete_flow__(rule, group);
3406     }
3407     ofopgroup_submit(group);
3408
3409     return 0;
3410 }
3411
3412 /* Implements OFPFC_DELETE. */
3413 static enum ofperr
3414 delete_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
3415                    const struct ofputil_flow_mod *fm,
3416                    const struct ofp_header *request)
3417 {
3418     struct list rules;
3419     enum ofperr error;
3420
3421     error = collect_rules_loose(ofproto, fm->table_id, &fm->match,
3422                                 fm->cookie, fm->cookie_mask,
3423                                 fm->out_port, &rules);
3424     return (error ? error
3425             : !list_is_empty(&rules) ? delete_flows__(ofproto, ofconn, request,
3426                                                       &rules)
3427             : 0);
3428 }
3429
3430 /* Implements OFPFC_DELETE_STRICT. */
3431 static enum ofperr
3432 delete_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
3433                    const struct ofputil_flow_mod *fm,
3434                    const struct ofp_header *request)
3435 {
3436     struct list rules;
3437     enum ofperr error;
3438
3439     error = collect_rules_strict(ofproto, fm->table_id, &fm->match,
3440                                  fm->priority, fm->cookie, fm->cookie_mask,
3441                                  fm->out_port, &rules);
3442     return (error ? error
3443             : list_is_singleton(&rules) ? delete_flows__(ofproto, ofconn,
3444                                                          request, &rules)
3445             : 0);
3446 }
3447
3448 static void
3449 ofproto_rule_send_removed(struct rule *rule, uint8_t reason)
3450 {
3451     struct ofputil_flow_removed fr;
3452
3453     if (ofproto_rule_is_hidden(rule) || !rule->send_flow_removed) {
3454         return;
3455     }
3456
3457     minimatch_expand(&rule->cr.match, &fr.match);
3458     fr.priority = rule->cr.priority;
3459     fr.cookie = rule->flow_cookie;
3460     fr.reason = reason;
3461     fr.table_id = rule->table_id;
3462     calc_duration(rule->created, time_msec(),
3463                   &fr.duration_sec, &fr.duration_nsec);
3464     fr.idle_timeout = rule->idle_timeout;
3465     fr.hard_timeout = rule->hard_timeout;
3466     rule->ofproto->ofproto_class->rule_get_stats(rule, &fr.packet_count,
3467                                                  &fr.byte_count);
3468
3469     connmgr_send_flow_removed(rule->ofproto->connmgr, &fr);
3470 }
3471
3472 void
3473 ofproto_rule_update_used(struct rule *rule, long long int used)
3474 {
3475     if (used > rule->used) {
3476         struct eviction_group *evg = rule->eviction_group;
3477
3478         rule->used = used;
3479         if (evg) {
3480             heap_change(&evg->rules, &rule->evg_node,
3481                         rule_eviction_priority(rule));
3482         }
3483     }
3484 }
3485
3486 /* Sends an OpenFlow "flow removed" message with the given 'reason' (either
3487  * OFPRR_HARD_TIMEOUT or OFPRR_IDLE_TIMEOUT), and then removes 'rule' from its
3488  * ofproto.
3489  *
3490  * 'rule' must not have a pending operation (that is, 'rule->pending' must be
3491  * NULL).
3492  *
3493  * ofproto implementation ->run() functions should use this function to expire
3494  * OpenFlow flows. */
3495 void
3496 ofproto_rule_expire(struct rule *rule, uint8_t reason)
3497 {
3498     struct ofproto *ofproto = rule->ofproto;
3499     struct ofopgroup *group;
3500
3501     ovs_assert(reason == OFPRR_HARD_TIMEOUT || reason == OFPRR_IDLE_TIMEOUT);
3502
3503     ofproto_rule_send_removed(rule, reason);
3504
3505     group = ofopgroup_create_unattached(ofproto);
3506     ofoperation_create(group, rule, OFOPERATION_DELETE, reason);
3507     oftable_remove_rule(rule);
3508     ofproto->ofproto_class->rule_destruct(rule);
3509     ofopgroup_submit(group);
3510 }
3511 \f
3512 static enum ofperr
3513 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
3514 {
3515     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3516     struct ofputil_flow_mod fm;
3517     uint64_t ofpacts_stub[1024 / 8];
3518     struct ofpbuf ofpacts;
3519     enum ofperr error;
3520     long long int now;
3521
3522     error = reject_slave_controller(ofconn);
3523     if (error) {
3524         goto exit;
3525     }
3526
3527     ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
3528     error = ofputil_decode_flow_mod(&fm, oh, ofconn_get_protocol(ofconn),
3529                                     &ofpacts);
3530     if (!error) {
3531         error = ofpacts_check(fm.ofpacts, fm.ofpacts_len,
3532                               &fm.match.flow, ofproto->max_ports);
3533     }
3534     if (!error) {
3535         error = handle_flow_mod__(ofproto, ofconn, &fm, oh);
3536     }
3537     if (error) {
3538         goto exit_free_ofpacts;
3539     }
3540
3541     /* Record the operation for logging a summary report. */
3542     switch (fm.command) {
3543     case OFPFC_ADD:
3544         ofproto->n_add++;
3545         break;
3546
3547     case OFPFC_MODIFY:
3548     case OFPFC_MODIFY_STRICT:
3549         ofproto->n_modify++;
3550         break;
3551
3552     case OFPFC_DELETE:
3553     case OFPFC_DELETE_STRICT:
3554         ofproto->n_delete++;
3555         break;
3556     }
3557
3558     now = time_msec();
3559     if (ofproto->next_op_report == LLONG_MAX) {
3560         ofproto->first_op = now;
3561         ofproto->next_op_report = MAX(now + 10 * 1000,
3562                                       ofproto->op_backoff);
3563         ofproto->op_backoff = ofproto->next_op_report + 60 * 1000;
3564     }
3565     ofproto->last_op = now;
3566
3567 exit_free_ofpacts:
3568     ofpbuf_uninit(&ofpacts);
3569 exit:
3570     return error;
3571 }
3572
3573 static enum ofperr
3574 handle_flow_mod__(struct ofproto *ofproto, struct ofconn *ofconn,
3575                   const struct ofputil_flow_mod *fm,
3576                   const struct ofp_header *oh)
3577 {
3578     if (ofproto->n_pending >= 50) {
3579         ovs_assert(!list_is_empty(&ofproto->pending));
3580         return OFPROTO_POSTPONE;
3581     }
3582
3583     switch (fm->command) {
3584     case OFPFC_ADD:
3585         return add_flow(ofproto, ofconn, fm, oh);
3586
3587     case OFPFC_MODIFY:
3588         return modify_flows_loose(ofproto, ofconn, fm, oh);
3589
3590     case OFPFC_MODIFY_STRICT:
3591         return modify_flow_strict(ofproto, ofconn, fm, oh);
3592
3593     case OFPFC_DELETE:
3594         return delete_flows_loose(ofproto, ofconn, fm, oh);
3595
3596     case OFPFC_DELETE_STRICT:
3597         return delete_flow_strict(ofproto, ofconn, fm, oh);
3598
3599     default:
3600         if (fm->command > 0xff) {
3601             VLOG_WARN_RL(&rl, "%s: flow_mod has explicit table_id but "
3602                          "flow_mod_table_id extension is not enabled",
3603                          ofproto->name);
3604         }
3605         return OFPERR_OFPFMFC_BAD_COMMAND;
3606     }
3607 }
3608
3609 static enum ofperr
3610 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
3611 {
3612     struct ofputil_role_request request;
3613     struct ofputil_role_request reply;
3614     struct ofpbuf *buf;
3615     enum ofperr error;
3616
3617     error = ofputil_decode_role_message(oh, &request);
3618     if (error) {
3619         return error;
3620     }
3621
3622     if (request.role != OFPCR12_ROLE_NOCHANGE) {
3623         if (ofconn_get_role(ofconn) != request.role
3624             && ofconn_has_pending_opgroups(ofconn)) {
3625             return OFPROTO_POSTPONE;
3626         }
3627
3628         if (request.have_generation_id
3629             && !ofconn_set_master_election_id(ofconn, request.generation_id)) {
3630                 return OFPERR_OFPRRFC_STALE;
3631         }
3632
3633         ofconn_set_role(ofconn, request.role);
3634     }
3635
3636     reply.role = ofconn_get_role(ofconn);
3637     reply.have_generation_id = ofconn_get_master_election_id(
3638         ofconn, &reply.generation_id);
3639     buf = ofputil_encode_role_reply(oh, &reply);
3640     ofconn_send_reply(ofconn, buf);
3641
3642     return 0;
3643 }
3644
3645 static enum ofperr
3646 handle_nxt_flow_mod_table_id(struct ofconn *ofconn,
3647                              const struct ofp_header *oh)
3648 {
3649     const struct nx_flow_mod_table_id *msg = ofpmsg_body(oh);
3650     enum ofputil_protocol cur, next;
3651
3652     cur = ofconn_get_protocol(ofconn);
3653     next = ofputil_protocol_set_tid(cur, msg->set != 0);
3654     ofconn_set_protocol(ofconn, next);
3655
3656     return 0;
3657 }
3658
3659 static enum ofperr
3660 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
3661 {
3662     const struct nx_set_flow_format *msg = ofpmsg_body(oh);
3663     enum ofputil_protocol cur, next;
3664     enum ofputil_protocol next_base;
3665
3666     next_base = ofputil_nx_flow_format_to_protocol(ntohl(msg->format));
3667     if (!next_base) {
3668         return OFPERR_OFPBRC_EPERM;
3669     }
3670
3671     cur = ofconn_get_protocol(ofconn);
3672     next = ofputil_protocol_set_base(cur, next_base);
3673     if (cur != next && ofconn_has_pending_opgroups(ofconn)) {
3674         /* Avoid sending async messages in surprising protocol. */
3675         return OFPROTO_POSTPONE;
3676     }
3677
3678     ofconn_set_protocol(ofconn, next);
3679     return 0;
3680 }
3681
3682 static enum ofperr
3683 handle_nxt_set_packet_in_format(struct ofconn *ofconn,
3684                                 const struct ofp_header *oh)
3685 {
3686     const struct nx_set_packet_in_format *msg = ofpmsg_body(oh);
3687     uint32_t format;
3688
3689     format = ntohl(msg->format);
3690     if (format != NXPIF_OPENFLOW10 && format != NXPIF_NXM) {
3691         return OFPERR_OFPBRC_EPERM;
3692     }
3693
3694     if (format != ofconn_get_packet_in_format(ofconn)
3695         && ofconn_has_pending_opgroups(ofconn)) {
3696         /* Avoid sending async message in surprsing packet in format. */
3697         return OFPROTO_POSTPONE;
3698     }
3699
3700     ofconn_set_packet_in_format(ofconn, format);
3701     return 0;
3702 }
3703
3704 static enum ofperr
3705 handle_nxt_set_async_config(struct ofconn *ofconn, const struct ofp_header *oh)
3706 {
3707     const struct nx_async_config *msg = ofpmsg_body(oh);
3708     uint32_t master[OAM_N_TYPES];
3709     uint32_t slave[OAM_N_TYPES];
3710
3711     master[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[0]);
3712     master[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[0]);
3713     master[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[0]);
3714
3715     slave[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[1]);
3716     slave[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[1]);
3717     slave[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[1]);
3718
3719     ofconn_set_async_config(ofconn, master, slave);
3720     if (ofconn_get_type(ofconn) == OFCONN_SERVICE &&
3721         !ofconn_get_miss_send_len(ofconn)) {
3722         ofconn_set_miss_send_len(ofconn, OFP_DEFAULT_MISS_SEND_LEN);
3723     }
3724
3725     return 0;
3726 }
3727
3728 static enum ofperr
3729 handle_nxt_set_controller_id(struct ofconn *ofconn,
3730                              const struct ofp_header *oh)
3731 {
3732     const struct nx_controller_id *nci = ofpmsg_body(oh);
3733
3734     if (!is_all_zeros(nci->zero, sizeof nci->zero)) {
3735         return OFPERR_NXBRC_MUST_BE_ZERO;
3736     }
3737
3738     ofconn_set_controller_id(ofconn, ntohs(nci->controller_id));
3739     return 0;
3740 }
3741
3742 static enum ofperr
3743 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
3744 {
3745     struct ofpbuf *buf;
3746
3747     if (ofconn_has_pending_opgroups(ofconn)) {
3748         return OFPROTO_POSTPONE;
3749     }
3750
3751     buf = ofpraw_alloc_reply((oh->version == OFP10_VERSION
3752                               ? OFPRAW_OFPT10_BARRIER_REPLY
3753                               : OFPRAW_OFPT11_BARRIER_REPLY), oh, 0);
3754     ofconn_send_reply(ofconn, buf);
3755     return 0;
3756 }
3757
3758 static void
3759 ofproto_compose_flow_refresh_update(const struct rule *rule,
3760                                     enum nx_flow_monitor_flags flags,
3761                                     struct list *msgs)
3762 {
3763     struct ofoperation *op = rule->pending;
3764     struct ofputil_flow_update fu;
3765     struct match match;
3766
3767     if (op && op->type == OFOPERATION_ADD && !op->victim) {
3768         /* We'll report the final flow when the operation completes.  Reporting
3769          * it now would cause a duplicate report later. */
3770         return;
3771     }
3772
3773     fu.event = (flags & (NXFMF_INITIAL | NXFMF_ADD)
3774                 ? NXFME_ADDED : NXFME_MODIFIED);
3775     fu.reason = 0;
3776     fu.idle_timeout = rule->idle_timeout;
3777     fu.hard_timeout = rule->hard_timeout;
3778     fu.table_id = rule->table_id;
3779     fu.cookie = rule->flow_cookie;
3780     minimatch_expand(&rule->cr.match, &match);
3781     fu.match = &match;
3782     fu.priority = rule->cr.priority;
3783     if (!(flags & NXFMF_ACTIONS)) {
3784         fu.ofpacts = NULL;
3785         fu.ofpacts_len = 0;
3786     } else if (!op) {
3787         fu.ofpacts = rule->ofpacts;
3788         fu.ofpacts_len = rule->ofpacts_len;
3789     } else {
3790         /* An operation is in progress.  Use the previous version of the flow's
3791          * actions, so that when the operation commits we report the change. */
3792         switch (op->type) {
3793         case OFOPERATION_ADD:
3794             /* We already verified that there was a victim. */
3795             fu.ofpacts = op->victim->ofpacts;
3796             fu.ofpacts_len = op->victim->ofpacts_len;
3797             break;
3798
3799         case OFOPERATION_MODIFY:
3800             if (op->ofpacts) {
3801                 fu.ofpacts = op->ofpacts;
3802                 fu.ofpacts_len = op->ofpacts_len;
3803             } else {
3804                 fu.ofpacts = rule->ofpacts;
3805                 fu.ofpacts_len = rule->ofpacts_len;
3806             }
3807             break;
3808
3809         case OFOPERATION_DELETE:
3810             fu.ofpacts = rule->ofpacts;
3811             fu.ofpacts_len = rule->ofpacts_len;
3812             break;
3813
3814         default:
3815             NOT_REACHED();
3816         }
3817     }
3818
3819     if (list_is_empty(msgs)) {
3820         ofputil_start_flow_update(msgs);
3821     }
3822     ofputil_append_flow_update(&fu, msgs);
3823 }
3824
3825 void
3826 ofmonitor_compose_refresh_updates(struct list *rules, struct list *msgs)
3827 {
3828     struct rule *rule;
3829
3830     LIST_FOR_EACH (rule, ofproto_node, rules) {
3831         enum nx_flow_monitor_flags flags = rule->monitor_flags;
3832         rule->monitor_flags = 0;
3833
3834         ofproto_compose_flow_refresh_update(rule, flags, msgs);
3835     }
3836 }
3837
3838 static void
3839 ofproto_collect_ofmonitor_refresh_rule(const struct ofmonitor *m,
3840                                        struct rule *rule, uint64_t seqno,
3841                                        struct list *rules)
3842 {
3843     enum nx_flow_monitor_flags update;
3844
3845     if (ofproto_rule_is_hidden(rule)) {
3846         return;
3847     }
3848
3849     if (!(rule->pending
3850           ? ofoperation_has_out_port(rule->pending, m->out_port)
3851           : ofproto_rule_has_out_port(rule, m->out_port))) {
3852         return;
3853     }
3854
3855     if (seqno) {
3856         if (rule->add_seqno > seqno) {
3857             update = NXFMF_ADD | NXFMF_MODIFY;
3858         } else if (rule->modify_seqno > seqno) {
3859             update = NXFMF_MODIFY;
3860         } else {
3861             return;
3862         }
3863
3864         if (!(m->flags & update)) {
3865             return;
3866         }
3867     } else {
3868         update = NXFMF_INITIAL;
3869     }
3870
3871     if (!rule->monitor_flags) {
3872         list_push_back(rules, &rule->ofproto_node);
3873     }
3874     rule->monitor_flags |= update | (m->flags & NXFMF_ACTIONS);
3875 }
3876
3877 static void
3878 ofproto_collect_ofmonitor_refresh_rules(const struct ofmonitor *m,
3879                                         uint64_t seqno,
3880                                         struct list *rules)
3881 {
3882     const struct ofproto *ofproto = ofconn_get_ofproto(m->ofconn);
3883     const struct ofoperation *op;
3884     const struct oftable *table;
3885     struct cls_rule target;
3886
3887     cls_rule_init_from_minimatch(&target, &m->match, 0);
3888     FOR_EACH_MATCHING_TABLE (table, m->table_id, ofproto) {
3889         struct cls_cursor cursor;
3890         struct rule *rule;
3891
3892         cls_cursor_init(&cursor, &table->cls, &target);
3893         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3894             ovs_assert(!rule->pending); /* XXX */
3895             ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
3896         }
3897     }
3898
3899     HMAP_FOR_EACH (op, hmap_node, &ofproto->deletions) {
3900         struct rule *rule = op->rule;
3901
3902         if (((m->table_id == 0xff
3903               ? !(ofproto->tables[rule->table_id].flags & OFTABLE_HIDDEN)
3904               : m->table_id == rule->table_id))
3905             && cls_rule_is_loose_match(&rule->cr, &target.match)) {
3906             ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
3907         }
3908     }
3909     cls_rule_destroy(&target);
3910 }
3911
3912 static void
3913 ofproto_collect_ofmonitor_initial_rules(struct ofmonitor *m,
3914                                         struct list *rules)
3915 {
3916     if (m->flags & NXFMF_INITIAL) {
3917         ofproto_collect_ofmonitor_refresh_rules(m, 0, rules);
3918     }
3919 }
3920
3921 void
3922 ofmonitor_collect_resume_rules(struct ofmonitor *m,
3923                                uint64_t seqno, struct list *rules)
3924 {
3925     ofproto_collect_ofmonitor_refresh_rules(m, seqno, rules);
3926 }
3927
3928 static enum ofperr
3929 handle_flow_monitor_request(struct ofconn *ofconn, const struct ofp_header *oh)
3930 {
3931     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3932     struct ofmonitor **monitors;
3933     size_t n_monitors, allocated_monitors;
3934     struct list replies;
3935     enum ofperr error;
3936     struct list rules;
3937     struct ofpbuf b;
3938     size_t i;
3939
3940     error = 0;
3941     ofpbuf_use_const(&b, oh, ntohs(oh->length));
3942     monitors = NULL;
3943     n_monitors = allocated_monitors = 0;
3944     for (;;) {
3945         struct ofputil_flow_monitor_request request;
3946         struct ofmonitor *m;
3947         int retval;
3948
3949         retval = ofputil_decode_flow_monitor_request(&request, &b);
3950         if (retval == EOF) {
3951             break;
3952         } else if (retval) {
3953             error = retval;
3954             goto error;
3955         }
3956
3957         if (request.table_id != 0xff
3958             && request.table_id >= ofproto->n_tables) {
3959             error = OFPERR_OFPBRC_BAD_TABLE_ID;
3960             goto error;
3961         }
3962
3963         error = ofmonitor_create(&request, ofconn, &m);
3964         if (error) {
3965             goto error;
3966         }
3967
3968         if (n_monitors >= allocated_monitors) {
3969             monitors = x2nrealloc(monitors, &allocated_monitors,
3970                                   sizeof *monitors);
3971         }
3972         monitors[n_monitors++] = m;
3973     }
3974
3975     list_init(&rules);
3976     for (i = 0; i < n_monitors; i++) {
3977         ofproto_collect_ofmonitor_initial_rules(monitors[i], &rules);
3978     }
3979
3980     ofpmp_init(&replies, oh);
3981     ofmonitor_compose_refresh_updates(&rules, &replies);
3982     ofconn_send_replies(ofconn, &replies);
3983
3984     free(monitors);
3985
3986     return 0;
3987
3988 error:
3989     for (i = 0; i < n_monitors; i++) {
3990         ofmonitor_destroy(monitors[i]);
3991     }
3992     free(monitors);
3993     return error;
3994 }
3995
3996 static enum ofperr
3997 handle_flow_monitor_cancel(struct ofconn *ofconn, const struct ofp_header *oh)
3998 {
3999     struct ofmonitor *m;
4000     uint32_t id;
4001
4002     id = ofputil_decode_flow_monitor_cancel(oh);
4003     m = ofmonitor_lookup(ofconn, id);
4004     if (!m) {
4005         return OFPERR_NXBRC_FM_BAD_ID;
4006     }
4007
4008     ofmonitor_destroy(m);
4009     return 0;
4010 }
4011
4012 static enum ofperr
4013 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
4014 {
4015     const struct ofp_header *oh = msg->data;
4016     enum ofptype type;
4017     enum ofperr error;
4018
4019     error = ofptype_decode(&type, oh);
4020     if (error) {
4021         return error;
4022     }
4023
4024     switch (type) {
4025         /* OpenFlow requests. */
4026     case OFPTYPE_ECHO_REQUEST:
4027         return handle_echo_request(ofconn, oh);
4028
4029     case OFPTYPE_FEATURES_REQUEST:
4030         return handle_features_request(ofconn, oh);
4031
4032     case OFPTYPE_GET_CONFIG_REQUEST:
4033         return handle_get_config_request(ofconn, oh);
4034
4035     case OFPTYPE_SET_CONFIG:
4036         return handle_set_config(ofconn, oh);
4037
4038     case OFPTYPE_PACKET_OUT:
4039         return handle_packet_out(ofconn, oh);
4040
4041     case OFPTYPE_PORT_MOD:
4042         return handle_port_mod(ofconn, oh);
4043
4044     case OFPTYPE_FLOW_MOD:
4045         return handle_flow_mod(ofconn, oh);
4046
4047     case OFPTYPE_BARRIER_REQUEST:
4048         return handle_barrier_request(ofconn, oh);
4049
4050     case OFPTYPE_ROLE_REQUEST:
4051         return handle_role_request(ofconn, oh);
4052
4053         /* OpenFlow replies. */
4054     case OFPTYPE_ECHO_REPLY:
4055         return 0;
4056
4057         /* Nicira extension requests. */
4058     case OFPTYPE_FLOW_MOD_TABLE_ID:
4059         return handle_nxt_flow_mod_table_id(ofconn, oh);
4060
4061     case OFPTYPE_SET_FLOW_FORMAT:
4062         return handle_nxt_set_flow_format(ofconn, oh);
4063
4064     case OFPTYPE_SET_PACKET_IN_FORMAT:
4065         return handle_nxt_set_packet_in_format(ofconn, oh);
4066
4067     case OFPTYPE_SET_CONTROLLER_ID:
4068         return handle_nxt_set_controller_id(ofconn, oh);
4069
4070     case OFPTYPE_FLOW_AGE:
4071         /* Nothing to do. */
4072         return 0;
4073
4074     case OFPTYPE_FLOW_MONITOR_CANCEL:
4075         return handle_flow_monitor_cancel(ofconn, oh);
4076
4077     case OFPTYPE_SET_ASYNC_CONFIG:
4078         return handle_nxt_set_async_config(ofconn, oh);
4079
4080         /* Statistics requests. */
4081     case OFPTYPE_DESC_STATS_REQUEST:
4082         return handle_desc_stats_request(ofconn, oh);
4083
4084     case OFPTYPE_FLOW_STATS_REQUEST:
4085         return handle_flow_stats_request(ofconn, oh);
4086
4087     case OFPTYPE_AGGREGATE_STATS_REQUEST:
4088         return handle_aggregate_stats_request(ofconn, oh);
4089
4090     case OFPTYPE_TABLE_STATS_REQUEST:
4091         return handle_table_stats_request(ofconn, oh);
4092
4093     case OFPTYPE_PORT_STATS_REQUEST:
4094         return handle_port_stats_request(ofconn, oh);
4095
4096     case OFPTYPE_QUEUE_STATS_REQUEST:
4097         return handle_queue_stats_request(ofconn, oh);
4098
4099     case OFPTYPE_PORT_DESC_STATS_REQUEST:
4100         return handle_port_desc_stats_request(ofconn, oh);
4101
4102     case OFPTYPE_FLOW_MONITOR_STATS_REQUEST:
4103         return handle_flow_monitor_request(ofconn, oh);
4104
4105         /* FIXME: Change the following once they are implemented: */
4106     case OFPTYPE_QUEUE_GET_CONFIG_REQUEST:
4107     case OFPTYPE_GET_ASYNC_REQUEST:
4108     case OFPTYPE_METER_MOD:
4109     case OFPTYPE_GROUP_REQUEST:
4110     case OFPTYPE_GROUP_DESC_REQUEST:
4111     case OFPTYPE_GROUP_FEATURES_REQUEST:
4112     case OFPTYPE_METER_REQUEST:
4113     case OFPTYPE_METER_CONFIG_REQUEST:
4114     case OFPTYPE_METER_FEATURES_REQUEST:
4115     case OFPTYPE_TABLE_FEATURES_REQUEST:
4116         return OFPERR_OFPBRC_BAD_TYPE;
4117
4118     case OFPTYPE_HELLO:
4119     case OFPTYPE_ERROR:
4120     case OFPTYPE_FEATURES_REPLY:
4121     case OFPTYPE_GET_CONFIG_REPLY:
4122     case OFPTYPE_PACKET_IN:
4123     case OFPTYPE_FLOW_REMOVED:
4124     case OFPTYPE_PORT_STATUS:
4125     case OFPTYPE_BARRIER_REPLY:
4126     case OFPTYPE_QUEUE_GET_CONFIG_REPLY:
4127     case OFPTYPE_DESC_STATS_REPLY:
4128     case OFPTYPE_FLOW_STATS_REPLY:
4129     case OFPTYPE_QUEUE_STATS_REPLY:
4130     case OFPTYPE_PORT_STATS_REPLY:
4131     case OFPTYPE_TABLE_STATS_REPLY:
4132     case OFPTYPE_AGGREGATE_STATS_REPLY:
4133     case OFPTYPE_PORT_DESC_STATS_REPLY:
4134     case OFPTYPE_ROLE_REPLY:
4135     case OFPTYPE_FLOW_MONITOR_PAUSED:
4136     case OFPTYPE_FLOW_MONITOR_RESUMED:
4137     case OFPTYPE_FLOW_MONITOR_STATS_REPLY:
4138     case OFPTYPE_GET_ASYNC_REPLY:
4139     case OFPTYPE_GROUP_REPLY:
4140     case OFPTYPE_GROUP_DESC_REPLY:
4141     case OFPTYPE_GROUP_FEATURES_REPLY:
4142     case OFPTYPE_METER_REPLY:
4143     case OFPTYPE_METER_CONFIG_REPLY:
4144     case OFPTYPE_METER_FEATURES_REPLY:
4145     case OFPTYPE_TABLE_FEATURES_REPLY:
4146     default:
4147         return OFPERR_OFPBRC_BAD_TYPE;
4148     }
4149 }
4150
4151 static bool
4152 handle_openflow(struct ofconn *ofconn, struct ofpbuf *ofp_msg)
4153 {
4154     int error = handle_openflow__(ofconn, ofp_msg);
4155     if (error && error != OFPROTO_POSTPONE) {
4156         ofconn_send_error(ofconn, ofp_msg->data, error);
4157     }
4158     COVERAGE_INC(ofproto_recv_openflow);
4159     return error != OFPROTO_POSTPONE;
4160 }
4161 \f
4162 /* Asynchronous operations. */
4163
4164 /* Creates and returns a new ofopgroup that is not associated with any
4165  * OpenFlow connection.
4166  *
4167  * The caller should add operations to the returned group with
4168  * ofoperation_create() and then submit it with ofopgroup_submit(). */
4169 static struct ofopgroup *
4170 ofopgroup_create_unattached(struct ofproto *ofproto)
4171 {
4172     struct ofopgroup *group = xzalloc(sizeof *group);
4173     group->ofproto = ofproto;
4174     list_init(&group->ofproto_node);
4175     list_init(&group->ops);
4176     list_init(&group->ofconn_node);
4177     return group;
4178 }
4179
4180 /* Creates and returns a new ofopgroup for 'ofproto'.
4181  *
4182  * If 'ofconn' is NULL, the new ofopgroup is not associated with any OpenFlow
4183  * connection.  The 'request' and 'buffer_id' arguments are ignored.
4184  *
4185  * If 'ofconn' is nonnull, then the new ofopgroup is associated with 'ofconn'.
4186  * If the ofopgroup eventually fails, then the error reply will include
4187  * 'request'.  If the ofopgroup eventually succeeds, then the packet with
4188  * buffer id 'buffer_id' on 'ofconn' will be sent by 'ofconn''s ofproto.
4189  *
4190  * The caller should add operations to the returned group with
4191  * ofoperation_create() and then submit it with ofopgroup_submit(). */
4192 static struct ofopgroup *
4193 ofopgroup_create(struct ofproto *ofproto, struct ofconn *ofconn,
4194                  const struct ofp_header *request, uint32_t buffer_id)
4195 {
4196     struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
4197     if (ofconn) {
4198         size_t request_len = ntohs(request->length);
4199
4200         ovs_assert(ofconn_get_ofproto(ofconn) == ofproto);
4201
4202         ofconn_add_opgroup(ofconn, &group->ofconn_node);
4203         group->ofconn = ofconn;
4204         group->request = xmemdup(request, MIN(request_len, 64));
4205         group->buffer_id = buffer_id;
4206     }
4207     return group;
4208 }
4209
4210 /* Submits 'group' for processing.
4211  *
4212  * If 'group' contains no operations (e.g. none were ever added, or all of the
4213  * ones that were added completed synchronously), then it is destroyed
4214  * immediately.  Otherwise it is added to the ofproto's list of pending
4215  * groups. */
4216 static void
4217 ofopgroup_submit(struct ofopgroup *group)
4218 {
4219     if (!group->n_running) {
4220         ofopgroup_complete(group);
4221     } else {
4222         list_push_back(&group->ofproto->pending, &group->ofproto_node);
4223         group->ofproto->n_pending++;
4224     }
4225 }
4226
4227 static void
4228 ofopgroup_complete(struct ofopgroup *group)
4229 {
4230     struct ofproto *ofproto = group->ofproto;
4231
4232     struct ofconn *abbrev_ofconn;
4233     ovs_be32 abbrev_xid;
4234
4235     struct ofoperation *op, *next_op;
4236     int error;
4237
4238     ovs_assert(!group->n_running);
4239
4240     error = 0;
4241     LIST_FOR_EACH (op, group_node, &group->ops) {
4242         if (op->error) {
4243             error = op->error;
4244             break;
4245         }
4246     }
4247
4248     if (!error && group->ofconn && group->buffer_id != UINT32_MAX) {
4249         LIST_FOR_EACH (op, group_node, &group->ops) {
4250             if (op->type != OFOPERATION_DELETE) {
4251                 struct ofpbuf *packet;
4252                 uint16_t in_port;
4253
4254                 error = ofconn_pktbuf_retrieve(group->ofconn, group->buffer_id,
4255                                                &packet, &in_port);
4256                 if (packet) {
4257                     ovs_assert(!error);
4258                     error = rule_execute(op->rule, in_port, packet);
4259                 }
4260                 break;
4261             }
4262         }
4263     }
4264
4265     if (!error && !list_is_empty(&group->ofconn_node)) {
4266         abbrev_ofconn = group->ofconn;
4267         abbrev_xid = group->request->xid;
4268     } else {
4269         abbrev_ofconn = NULL;
4270         abbrev_xid = htonl(0);
4271     }
4272     LIST_FOR_EACH_SAFE (op, next_op, group_node, &group->ops) {
4273         struct rule *rule = op->rule;
4274
4275         /* We generally want to report the change to active OpenFlow flow
4276            monitors (e.g. NXST_FLOW_MONITOR).  There are three exceptions:
4277
4278               - The operation failed.
4279
4280               - The affected rule is not visible to controllers.
4281
4282               - The operation's only effect was to update rule->modified. */
4283         if (!(op->error
4284               || ofproto_rule_is_hidden(rule)
4285               || (op->type == OFOPERATION_MODIFY
4286                   && op->ofpacts
4287                   && rule->flow_cookie == op->flow_cookie))) {
4288             /* Check that we can just cast from ofoperation_type to
4289              * nx_flow_update_event. */
4290             BUILD_ASSERT_DECL((enum nx_flow_update_event) OFOPERATION_ADD
4291                               == NXFME_ADDED);
4292             BUILD_ASSERT_DECL((enum nx_flow_update_event) OFOPERATION_DELETE
4293                               == NXFME_DELETED);
4294             BUILD_ASSERT_DECL((enum nx_flow_update_event) OFOPERATION_MODIFY
4295                               == NXFME_MODIFIED);
4296
4297             ofmonitor_report(ofproto->connmgr, rule,
4298                              (enum nx_flow_update_event) op->type,
4299                              op->reason, abbrev_ofconn, abbrev_xid);
4300         }
4301
4302         rule->pending = NULL;
4303
4304         switch (op->type) {
4305         case OFOPERATION_ADD:
4306             if (!op->error) {
4307                 uint16_t vid_mask;
4308
4309                 ofproto_rule_destroy__(op->victim);
4310                 vid_mask = minimask_get_vid_mask(&rule->cr.match.mask);
4311                 if (vid_mask == VLAN_VID_MASK) {
4312                     if (ofproto->vlan_bitmap) {
4313                         uint16_t vid = miniflow_get_vid(&rule->cr.match.flow);
4314                         if (!bitmap_is_set(ofproto->vlan_bitmap, vid)) {
4315                             bitmap_set1(ofproto->vlan_bitmap, vid);
4316                             ofproto->vlans_changed = true;
4317                         }
4318                     } else {
4319                         ofproto->vlans_changed = true;
4320                     }
4321                 }
4322             } else {
4323                 oftable_substitute_rule(rule, op->victim);
4324                 ofproto_rule_destroy__(rule);
4325             }
4326             break;
4327
4328         case OFOPERATION_DELETE:
4329             ovs_assert(!op->error);
4330             ofproto_rule_destroy__(rule);
4331             op->rule = NULL;
4332             break;
4333
4334         case OFOPERATION_MODIFY:
4335             if (!op->error) {
4336                 rule->modified = time_msec();
4337             } else {
4338                 rule->flow_cookie = op->flow_cookie;
4339                 if (op->ofpacts) {
4340                     free(rule->ofpacts);
4341                     rule->ofpacts = op->ofpacts;
4342                     rule->ofpacts_len = op->ofpacts_len;
4343                     op->ofpacts = NULL;
4344                     op->ofpacts_len = 0;
4345                 }
4346             }
4347             break;
4348
4349         default:
4350             NOT_REACHED();
4351         }
4352
4353         ofoperation_destroy(op);
4354     }
4355
4356     ofmonitor_flush(ofproto->connmgr);
4357
4358     if (!list_is_empty(&group->ofproto_node)) {
4359         ovs_assert(ofproto->n_pending > 0);
4360         ofproto->n_pending--;
4361         list_remove(&group->ofproto_node);
4362     }
4363     if (!list_is_empty(&group->ofconn_node)) {
4364         list_remove(&group->ofconn_node);
4365         if (error) {
4366             ofconn_send_error(group->ofconn, group->request, error);
4367         }
4368         connmgr_retry(ofproto->connmgr);
4369     }
4370     free(group->request);
4371     free(group);
4372 }
4373
4374 /* Initiates a new operation on 'rule', of the specified 'type', within
4375  * 'group'.  Prior to calling, 'rule' must not have any pending operation.
4376  *
4377  * For a 'type' of OFOPERATION_DELETE, 'reason' should specify the reason that
4378  * the flow is being deleted.  For other 'type's, 'reason' is ignored (use 0).
4379  *
4380  * Returns the newly created ofoperation (which is also available as
4381  * rule->pending). */
4382 static struct ofoperation *
4383 ofoperation_create(struct ofopgroup *group, struct rule *rule,
4384                    enum ofoperation_type type,
4385                    enum ofp_flow_removed_reason reason)
4386 {
4387     struct ofproto *ofproto = group->ofproto;
4388     struct ofoperation *op;
4389
4390     ovs_assert(!rule->pending);
4391
4392     op = rule->pending = xzalloc(sizeof *op);
4393     op->group = group;
4394     list_push_back(&group->ops, &op->group_node);
4395     op->rule = rule;
4396     op->type = type;
4397     op->reason = reason;
4398     op->flow_cookie = rule->flow_cookie;
4399
4400     group->n_running++;
4401
4402     if (type == OFOPERATION_DELETE) {
4403         hmap_insert(&ofproto->deletions, &op->hmap_node,
4404                     cls_rule_hash(&rule->cr, rule->table_id));
4405     }
4406
4407     return op;
4408 }
4409
4410 static void
4411 ofoperation_destroy(struct ofoperation *op)
4412 {
4413     struct ofopgroup *group = op->group;
4414
4415     if (op->rule) {
4416         op->rule->pending = NULL;
4417     }
4418     if (op->type == OFOPERATION_DELETE) {
4419         hmap_remove(&group->ofproto->deletions, &op->hmap_node);
4420     }
4421     list_remove(&op->group_node);
4422     free(op->ofpacts);
4423     free(op);
4424 }
4425
4426 /* Indicates that 'op' completed with status 'error', which is either 0 to
4427  * indicate success or an OpenFlow error code on failure.
4428  *
4429  * If 'error' is 0, indicating success, the operation will be committed
4430  * permanently to the flow table.  There is one interesting subcase:
4431  *
4432  *   - If 'op' is an "add flow" operation that is replacing an existing rule in
4433  *     the flow table (the "victim" rule) by a new one, then the caller must
4434  *     have uninitialized any derived state in the victim rule, as in step 5 in
4435  *     the "Life Cycle" in ofproto/ofproto-provider.h.  ofoperation_complete()
4436  *     performs steps 6 and 7 for the victim rule, most notably by calling its
4437  *     ->rule_dealloc() function.
4438  *
4439  * If 'error' is nonzero, then generally the operation will be rolled back:
4440  *
4441  *   - If 'op' is an "add flow" operation, ofproto removes the new rule or
4442  *     restores the original rule.  The caller must have uninitialized any
4443  *     derived state in the new rule, as in step 5 of in the "Life Cycle" in
4444  *     ofproto/ofproto-provider.h.  ofoperation_complete() performs steps 6 and
4445  *     and 7 for the new rule, calling its ->rule_dealloc() function.
4446  *
4447  *   - If 'op' is a "modify flow" operation, ofproto restores the original
4448  *     actions.
4449  *
4450  *   - 'op' must not be a "delete flow" operation.  Removing a rule is not
4451  *     allowed to fail.  It must always succeed.
4452  *
4453  * Please see the large comment in ofproto/ofproto-provider.h titled
4454  * "Asynchronous Operation Support" for more information. */
4455 void
4456 ofoperation_complete(struct ofoperation *op, enum ofperr error)
4457 {
4458     struct ofopgroup *group = op->group;
4459
4460     ovs_assert(op->rule->pending == op);
4461     ovs_assert(group->n_running > 0);
4462     ovs_assert(!error || op->type != OFOPERATION_DELETE);
4463
4464     op->error = error;
4465     if (!--group->n_running && !list_is_empty(&group->ofproto_node)) {
4466         ofopgroup_complete(group);
4467     }
4468 }
4469
4470 struct rule *
4471 ofoperation_get_victim(struct ofoperation *op)
4472 {
4473     ovs_assert(op->type == OFOPERATION_ADD);
4474     return op->victim;
4475 }
4476 \f
4477 static uint64_t
4478 pick_datapath_id(const struct ofproto *ofproto)
4479 {
4480     const struct ofport *port;
4481
4482     port = ofproto_get_port(ofproto, OFPP_LOCAL);
4483     if (port) {
4484         uint8_t ea[ETH_ADDR_LEN];
4485         int error;
4486
4487         error = netdev_get_etheraddr(port->netdev, ea);
4488         if (!error) {
4489             return eth_addr_to_uint64(ea);
4490         }
4491         VLOG_WARN("%s: could not get MAC address for %s (%s)",
4492                   ofproto->name, netdev_get_name(port->netdev),
4493                   strerror(error));
4494     }
4495     return ofproto->fallback_dpid;
4496 }
4497
4498 static uint64_t
4499 pick_fallback_dpid(void)
4500 {
4501     uint8_t ea[ETH_ADDR_LEN];
4502     eth_addr_nicira_random(ea);
4503     return eth_addr_to_uint64(ea);
4504 }
4505 \f
4506 /* Table overflow policy. */
4507
4508 /* Chooses and returns a rule to evict from 'table'.  Returns NULL if the table
4509  * is not configured to evict rules or if the table contains no evictable
4510  * rules.  (Rules with 'evictable' set to false or with no timeouts are not
4511  * evictable.) */
4512 static struct rule *
4513 choose_rule_to_evict(struct oftable *table)
4514 {
4515     struct eviction_group *evg;
4516
4517     if (!table->eviction_fields) {
4518         return NULL;
4519     }
4520
4521     /* In the common case, the outer and inner loops here will each be entered
4522      * exactly once:
4523      *
4524      *   - The inner loop normally "return"s in its first iteration.  If the
4525      *     eviction group has any evictable rules, then it always returns in
4526      *     some iteration.
4527      *
4528      *   - The outer loop only iterates more than once if the largest eviction
4529      *     group has no evictable rules.
4530      *
4531      *   - The outer loop can exit only if table's 'max_flows' is all filled up
4532      *     by unevictable rules'. */
4533     HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
4534         struct rule *rule;
4535
4536         HEAP_FOR_EACH (rule, evg_node, &evg->rules) {
4537             if (rule->evictable) {
4538                 return rule;
4539             }
4540         }
4541     }
4542
4543     return NULL;
4544 }
4545
4546 /* Searches 'ofproto' for tables that have more flows than their configured
4547  * maximum and that have flow eviction enabled, and evicts as many flows as
4548  * necessary and currently feasible from them.
4549  *
4550  * This triggers only when an OpenFlow table has N flows in it and then the
4551  * client configures a maximum number of flows less than N. */
4552 static void
4553 ofproto_evict(struct ofproto *ofproto)
4554 {
4555     struct ofopgroup *group;
4556     struct oftable *table;
4557
4558     group = ofopgroup_create_unattached(ofproto);
4559     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
4560         while (classifier_count(&table->cls) > table->max_flows
4561                && table->eviction_fields) {
4562             struct rule *rule;
4563
4564             rule = choose_rule_to_evict(table);
4565             if (!rule || rule->pending) {
4566                 break;
4567             }
4568
4569             ofoperation_create(group, rule,
4570                                OFOPERATION_DELETE, OFPRR_EVICTION);
4571             oftable_remove_rule(rule);
4572             ofproto->ofproto_class->rule_destruct(rule);
4573         }
4574     }
4575     ofopgroup_submit(group);
4576 }
4577 \f
4578 /* Eviction groups. */
4579
4580 /* Returns the priority to use for an eviction_group that contains 'n_rules'
4581  * rules.  The priority contains low-order random bits to ensure that eviction
4582  * groups with the same number of rules are prioritized randomly. */
4583 static uint32_t
4584 eviction_group_priority(size_t n_rules)
4585 {
4586     uint16_t size = MIN(UINT16_MAX, n_rules);
4587     return (size << 16) | random_uint16();
4588 }
4589
4590 /* Updates 'evg', an eviction_group within 'table', following a change that
4591  * adds or removes rules in 'evg'. */
4592 static void
4593 eviction_group_resized(struct oftable *table, struct eviction_group *evg)
4594 {
4595     heap_change(&table->eviction_groups_by_size, &evg->size_node,
4596                 eviction_group_priority(heap_count(&evg->rules)));
4597 }
4598
4599 /* Destroys 'evg', an eviction_group within 'table':
4600  *
4601  *   - Removes all the rules, if any, from 'evg'.  (It doesn't destroy the
4602  *     rules themselves, just removes them from the eviction group.)
4603  *
4604  *   - Removes 'evg' from 'table'.
4605  *
4606  *   - Frees 'evg'. */
4607 static void
4608 eviction_group_destroy(struct oftable *table, struct eviction_group *evg)
4609 {
4610     while (!heap_is_empty(&evg->rules)) {
4611         struct rule *rule;
4612
4613         rule = CONTAINER_OF(heap_pop(&evg->rules), struct rule, evg_node);
4614         rule->eviction_group = NULL;
4615     }
4616     hmap_remove(&table->eviction_groups_by_id, &evg->id_node);
4617     heap_remove(&table->eviction_groups_by_size, &evg->size_node);
4618     heap_destroy(&evg->rules);
4619     free(evg);
4620 }
4621
4622 /* Removes 'rule' from its eviction group, if any. */
4623 static void
4624 eviction_group_remove_rule(struct rule *rule)
4625 {
4626     if (rule->eviction_group) {
4627         struct oftable *table = &rule->ofproto->tables[rule->table_id];
4628         struct eviction_group *evg = rule->eviction_group;
4629
4630         rule->eviction_group = NULL;
4631         heap_remove(&evg->rules, &rule->evg_node);
4632         if (heap_is_empty(&evg->rules)) {
4633             eviction_group_destroy(table, evg);
4634         } else {
4635             eviction_group_resized(table, evg);
4636         }
4637     }
4638 }
4639
4640 /* Hashes the 'rule''s values for the eviction_fields of 'rule''s table, and
4641  * returns the hash value. */
4642 static uint32_t
4643 eviction_group_hash_rule(struct rule *rule)
4644 {
4645     struct oftable *table = &rule->ofproto->tables[rule->table_id];
4646     const struct mf_subfield *sf;
4647     struct flow flow;
4648     uint32_t hash;
4649
4650     hash = table->eviction_group_id_basis;
4651     miniflow_expand(&rule->cr.match.flow, &flow);
4652     for (sf = table->eviction_fields;
4653          sf < &table->eviction_fields[table->n_eviction_fields];
4654          sf++)
4655     {
4656         if (mf_are_prereqs_ok(sf->field, &flow)) {
4657             union mf_value value;
4658
4659             mf_get_value(sf->field, &flow, &value);
4660             if (sf->ofs) {
4661                 bitwise_zero(&value, sf->field->n_bytes, 0, sf->ofs);
4662             }
4663             if (sf->ofs + sf->n_bits < sf->field->n_bytes * 8) {
4664                 unsigned int start = sf->ofs + sf->n_bits;
4665                 bitwise_zero(&value, sf->field->n_bytes, start,
4666                              sf->field->n_bytes * 8 - start);
4667             }
4668             hash = hash_bytes(&value, sf->field->n_bytes, hash);
4669         } else {
4670             hash = hash_int(hash, 0);
4671         }
4672     }
4673
4674     return hash;
4675 }
4676
4677 /* Returns an eviction group within 'table' with the given 'id', creating one
4678  * if necessary. */
4679 static struct eviction_group *
4680 eviction_group_find(struct oftable *table, uint32_t id)
4681 {
4682     struct eviction_group *evg;
4683
4684     HMAP_FOR_EACH_WITH_HASH (evg, id_node, id, &table->eviction_groups_by_id) {
4685         return evg;
4686     }
4687
4688     evg = xmalloc(sizeof *evg);
4689     hmap_insert(&table->eviction_groups_by_id, &evg->id_node, id);
4690     heap_insert(&table->eviction_groups_by_size, &evg->size_node,
4691                 eviction_group_priority(0));
4692     heap_init(&evg->rules);
4693
4694     return evg;
4695 }
4696
4697 /* Returns an eviction priority for 'rule'.  The return value should be
4698  * interpreted so that higher priorities make a rule more attractive candidates
4699  * for eviction. */
4700 static uint32_t
4701 rule_eviction_priority(struct rule *rule)
4702 {
4703     long long int hard_expiration;
4704     long long int idle_expiration;
4705     long long int expiration;
4706     uint32_t expiration_offset;
4707
4708     /* Calculate time of expiration. */
4709     hard_expiration = (rule->hard_timeout
4710                        ? rule->modified + rule->hard_timeout * 1000
4711                        : LLONG_MAX);
4712     idle_expiration = (rule->idle_timeout
4713                        ? rule->used + rule->idle_timeout * 1000
4714                        : LLONG_MAX);
4715     expiration = MIN(hard_expiration, idle_expiration);
4716     if (expiration == LLONG_MAX) {
4717         return 0;
4718     }
4719
4720     /* Calculate the time of expiration as a number of (approximate) seconds
4721      * after program startup.
4722      *
4723      * This should work OK for program runs that last UINT32_MAX seconds or
4724      * less.  Therefore, please restart OVS at least once every 136 years. */
4725     expiration_offset = (expiration >> 10) - (time_boot_msec() >> 10);
4726
4727     /* Invert the expiration offset because we're using a max-heap. */
4728     return UINT32_MAX - expiration_offset;
4729 }
4730
4731 /* Adds 'rule' to an appropriate eviction group for its oftable's
4732  * configuration.  Does nothing if 'rule''s oftable doesn't have eviction
4733  * enabled, or if 'rule' is a permanent rule (one that will never expire on its
4734  * own).
4735  *
4736  * The caller must ensure that 'rule' is not already in an eviction group. */
4737 static void
4738 eviction_group_add_rule(struct rule *rule)
4739 {
4740     struct ofproto *ofproto = rule->ofproto;
4741     struct oftable *table = &ofproto->tables[rule->table_id];
4742
4743     if (table->eviction_fields
4744         && (rule->hard_timeout || rule->idle_timeout)) {
4745         struct eviction_group *evg;
4746
4747         evg = eviction_group_find(table, eviction_group_hash_rule(rule));
4748
4749         rule->eviction_group = evg;
4750         heap_insert(&evg->rules, &rule->evg_node,
4751                     rule_eviction_priority(rule));
4752         eviction_group_resized(table, evg);
4753     }
4754 }
4755 \f
4756 /* oftables. */
4757
4758 /* Initializes 'table'. */
4759 static void
4760 oftable_init(struct oftable *table)
4761 {
4762     memset(table, 0, sizeof *table);
4763     classifier_init(&table->cls);
4764     table->max_flows = UINT_MAX;
4765 }
4766
4767 /* Destroys 'table', including its classifier and eviction groups.
4768  *
4769  * The caller is responsible for freeing 'table' itself. */
4770 static void
4771 oftable_destroy(struct oftable *table)
4772 {
4773     ovs_assert(classifier_is_empty(&table->cls));
4774     oftable_disable_eviction(table);
4775     classifier_destroy(&table->cls);
4776     free(table->name);
4777 }
4778
4779 /* Changes the name of 'table' to 'name'.  If 'name' is NULL or the empty
4780  * string, then 'table' will use its default name.
4781  *
4782  * This only affects the name exposed for a table exposed through the OpenFlow
4783  * OFPST_TABLE (as printed by "ovs-ofctl dump-tables"). */
4784 static void
4785 oftable_set_name(struct oftable *table, const char *name)
4786 {
4787     if (name && name[0]) {
4788         int len = strnlen(name, OFP_MAX_TABLE_NAME_LEN);
4789         if (!table->name || strncmp(name, table->name, len)) {
4790             free(table->name);
4791             table->name = xmemdup0(name, len);
4792         }
4793     } else {
4794         free(table->name);
4795         table->name = NULL;
4796     }
4797 }
4798
4799 /* oftables support a choice of two policies when adding a rule would cause the
4800  * number of flows in the table to exceed the configured maximum number: either
4801  * they can refuse to add the new flow or they can evict some existing flow.
4802  * This function configures the former policy on 'table'. */
4803 static void
4804 oftable_disable_eviction(struct oftable *table)
4805 {
4806     if (table->eviction_fields) {
4807         struct eviction_group *evg, *next;
4808
4809         HMAP_FOR_EACH_SAFE (evg, next, id_node,
4810                             &table->eviction_groups_by_id) {
4811             eviction_group_destroy(table, evg);
4812         }
4813         hmap_destroy(&table->eviction_groups_by_id);
4814         heap_destroy(&table->eviction_groups_by_size);
4815
4816         free(table->eviction_fields);
4817         table->eviction_fields = NULL;
4818         table->n_eviction_fields = 0;
4819     }
4820 }
4821
4822 /* oftables support a choice of two policies when adding a rule would cause the
4823  * number of flows in the table to exceed the configured maximum number: either
4824  * they can refuse to add the new flow or they can evict some existing flow.
4825  * This function configures the latter policy on 'table', with fairness based
4826  * on the values of the 'n_fields' fields specified in 'fields'.  (Specifying
4827  * 'n_fields' as 0 disables fairness.) */
4828 static void
4829 oftable_enable_eviction(struct oftable *table,
4830                         const struct mf_subfield *fields, size_t n_fields)
4831 {
4832     struct cls_cursor cursor;
4833     struct rule *rule;
4834
4835     if (table->eviction_fields
4836         && n_fields == table->n_eviction_fields
4837         && (!n_fields
4838             || !memcmp(fields, table->eviction_fields,
4839                        n_fields * sizeof *fields))) {
4840         /* No change. */
4841         return;
4842     }
4843
4844     oftable_disable_eviction(table);
4845
4846     table->n_eviction_fields = n_fields;
4847     table->eviction_fields = xmemdup(fields, n_fields * sizeof *fields);
4848
4849     table->eviction_group_id_basis = random_uint32();
4850     hmap_init(&table->eviction_groups_by_id);
4851     heap_init(&table->eviction_groups_by_size);
4852
4853     cls_cursor_init(&cursor, &table->cls, NULL);
4854     CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4855         eviction_group_add_rule(rule);
4856     }
4857 }
4858
4859 /* Removes 'rule' from the oftable that contains it. */
4860 static void
4861 oftable_remove_rule(struct rule *rule)
4862 {
4863     struct ofproto *ofproto = rule->ofproto;
4864     struct oftable *table = &ofproto->tables[rule->table_id];
4865
4866     classifier_remove(&table->cls, &rule->cr);
4867     eviction_group_remove_rule(rule);
4868     if (!list_is_empty(&rule->expirable)) {
4869         list_remove(&rule->expirable);
4870     }
4871 }
4872
4873 /* Inserts 'rule' into its oftable.  Removes any existing rule from 'rule''s
4874  * oftable that has an identical cls_rule.  Returns the rule that was removed,
4875  * if any, and otherwise NULL. */
4876 static struct rule *
4877 oftable_replace_rule(struct rule *rule)
4878 {
4879     struct ofproto *ofproto = rule->ofproto;
4880     struct oftable *table = &ofproto->tables[rule->table_id];
4881     struct rule *victim;
4882     bool may_expire = rule->hard_timeout || rule->idle_timeout;
4883
4884     if (may_expire) {
4885         list_insert(&ofproto->expirable, &rule->expirable);
4886     }
4887
4888     victim = rule_from_cls_rule(classifier_replace(&table->cls, &rule->cr));
4889     if (victim) {
4890         if (!list_is_empty(&victim->expirable)) {
4891             list_remove(&victim->expirable);
4892         }
4893         eviction_group_remove_rule(victim);
4894     }
4895     eviction_group_add_rule(rule);
4896     return victim;
4897 }
4898
4899 /* Removes 'old' from its oftable then, if 'new' is nonnull, inserts 'new'. */
4900 static void
4901 oftable_substitute_rule(struct rule *old, struct rule *new)
4902 {
4903     if (new) {
4904         oftable_replace_rule(new);
4905     } else {
4906         oftable_remove_rule(old);
4907     }
4908 }
4909 \f
4910 /* unixctl commands. */
4911
4912 struct ofproto *
4913 ofproto_lookup(const char *name)
4914 {
4915     struct ofproto *ofproto;
4916
4917     HMAP_FOR_EACH_WITH_HASH (ofproto, hmap_node, hash_string(name, 0),
4918                              &all_ofprotos) {
4919         if (!strcmp(ofproto->name, name)) {
4920             return ofproto;
4921         }
4922     }
4923     return NULL;
4924 }
4925
4926 static void
4927 ofproto_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
4928                      const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
4929 {
4930     struct ofproto *ofproto;
4931     struct ds results;
4932
4933     ds_init(&results);
4934     HMAP_FOR_EACH (ofproto, hmap_node, &all_ofprotos) {
4935         ds_put_format(&results, "%s\n", ofproto->name);
4936     }
4937     unixctl_command_reply(conn, ds_cstr(&results));
4938     ds_destroy(&results);
4939 }
4940
4941 static void
4942 ofproto_unixctl_init(void)
4943 {
4944     static bool registered;
4945     if (registered) {
4946         return;
4947     }
4948     registered = true;
4949
4950     unixctl_command_register("ofproto/list", "", 0, 0,
4951                              ofproto_unixctl_list, NULL);
4952 }
4953 \f
4954 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
4955  *
4956  * This is deprecated.  It is only for compatibility with broken device drivers
4957  * in old versions of Linux that do not properly support VLANs when VLAN
4958  * devices are not used.  When broken device drivers are no longer in
4959  * widespread use, we will delete these interfaces. */
4960
4961 /* Sets a 1-bit in the 4096-bit 'vlan_bitmap' for each VLAN ID that is matched
4962  * (exactly) by an OpenFlow rule in 'ofproto'. */
4963 void
4964 ofproto_get_vlan_usage(struct ofproto *ofproto, unsigned long int *vlan_bitmap)
4965 {
4966     const struct oftable *oftable;
4967
4968     free(ofproto->vlan_bitmap);
4969     ofproto->vlan_bitmap = bitmap_allocate(4096);
4970     ofproto->vlans_changed = false;
4971
4972     OFPROTO_FOR_EACH_TABLE (oftable, ofproto) {
4973         const struct cls_table *table;
4974
4975         HMAP_FOR_EACH (table, hmap_node, &oftable->cls.tables) {
4976             if (minimask_get_vid_mask(&table->mask) == VLAN_VID_MASK) {
4977                 const struct cls_rule *rule;
4978
4979                 HMAP_FOR_EACH (rule, hmap_node, &table->rules) {
4980                     uint16_t vid = miniflow_get_vid(&rule->match.flow);
4981                     bitmap_set1(vlan_bitmap, vid);
4982                     bitmap_set1(ofproto->vlan_bitmap, vid);
4983                 }
4984             }
4985         }
4986     }
4987 }
4988
4989 /* Returns true if new VLANs have come into use by the flow table since the
4990  * last call to ofproto_get_vlan_usage().
4991  *
4992  * We don't track when old VLANs stop being used. */
4993 bool
4994 ofproto_has_vlan_usage_changed(const struct ofproto *ofproto)
4995 {
4996     return ofproto->vlans_changed;
4997 }
4998
4999 /* Configures a VLAN splinter binding between the ports identified by OpenFlow
5000  * port numbers 'vlandev_ofp_port' and 'realdev_ofp_port'.  If
5001  * 'realdev_ofp_port' is nonzero, then the VLAN device is enslaved to the real
5002  * device as a VLAN splinter for VLAN ID 'vid'.  If 'realdev_ofp_port' is zero,
5003  * then the VLAN device is un-enslaved. */
5004 int
5005 ofproto_port_set_realdev(struct ofproto *ofproto, uint16_t vlandev_ofp_port,
5006                          uint16_t realdev_ofp_port, int vid)
5007 {
5008     struct ofport *ofport;
5009     int error;
5010
5011     ovs_assert(vlandev_ofp_port != realdev_ofp_port);
5012
5013     ofport = ofproto_get_port(ofproto, vlandev_ofp_port);
5014     if (!ofport) {
5015         VLOG_WARN("%s: cannot set realdev on nonexistent port %"PRIu16,
5016                   ofproto->name, vlandev_ofp_port);
5017         return EINVAL;
5018     }
5019
5020     if (!ofproto->ofproto_class->set_realdev) {
5021         if (!vlandev_ofp_port) {
5022             return 0;
5023         }
5024         VLOG_WARN("%s: vlan splinters not supported", ofproto->name);
5025         return EOPNOTSUPP;
5026     }
5027
5028     error = ofproto->ofproto_class->set_realdev(ofport, realdev_ofp_port, vid);
5029     if (error) {
5030         VLOG_WARN("%s: setting realdev on port %"PRIu16" (%s) failed (%s)",
5031                   ofproto->name, vlandev_ofp_port,
5032                   netdev_get_name(ofport->netdev), strerror(error));
5033     }
5034     return error;
5035 }