ofproto: RCU postpone rule destruction.
[sliver-openvswitch.git] / ofproto / ofproto.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014 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 <unistd.h>
25 #include "bitmap.h"
26 #include "byte-order.h"
27 #include "classifier.h"
28 #include "connectivity.h"
29 #include "connmgr.h"
30 #include "coverage.h"
31 #include "dynamic-string.h"
32 #include "hash.h"
33 #include "hmap.h"
34 #include "meta-flow.h"
35 #include "netdev.h"
36 #include "nx-match.h"
37 #include "ofp-actions.h"
38 #include "ofp-errors.h"
39 #include "ofp-msgs.h"
40 #include "ofp-print.h"
41 #include "ofp-util.h"
42 #include "ofpbuf.h"
43 #include "ofproto-provider.h"
44 #include "openflow/nicira-ext.h"
45 #include "openflow/openflow.h"
46 #include "ovs-rcu.h"
47 #include "packets.h"
48 #include "pinsched.h"
49 #include "pktbuf.h"
50 #include "poll-loop.h"
51 #include "random.h"
52 #include "seq.h"
53 #include "shash.h"
54 #include "simap.h"
55 #include "smap.h"
56 #include "sset.h"
57 #include "timeval.h"
58 #include "unaligned.h"
59 #include "unixctl.h"
60 #include "vlog.h"
61
62 VLOG_DEFINE_THIS_MODULE(ofproto);
63
64 COVERAGE_DEFINE(ofproto_flush);
65 COVERAGE_DEFINE(ofproto_packet_out);
66 COVERAGE_DEFINE(ofproto_queue_req);
67 COVERAGE_DEFINE(ofproto_recv_openflow);
68 COVERAGE_DEFINE(ofproto_reinit_ports);
69 COVERAGE_DEFINE(ofproto_update_port);
70
71 enum ofproto_state {
72     S_OPENFLOW,                 /* Processing OpenFlow commands. */
73     S_EVICT,                    /* Evicting flows from over-limit tables. */
74     S_FLUSH,                    /* Deleting all flow table rules. */
75 };
76
77 enum ofoperation_type {
78     OFOPERATION_ADD,
79     OFOPERATION_DELETE,
80     OFOPERATION_MODIFY,
81     OFOPERATION_REPLACE
82 };
83
84 /* A single OpenFlow request can execute any number of operations.  The
85  * ofopgroup maintain OpenFlow state common to all of the operations, e.g. the
86  * ofconn to which an error reply should be sent if necessary.
87  *
88  * ofproto initiates some operations internally.  These operations are still
89  * assigned to groups but will not have an associated ofconn. */
90 struct ofopgroup {
91     struct ofproto *ofproto;    /* Owning ofproto. */
92     struct list ofproto_node;   /* In ofproto's "pending" list. */
93     struct list ops;            /* List of "struct ofoperation"s. */
94     int n_running;              /* Number of ops still pending. */
95
96     /* Data needed to send OpenFlow reply on failure or to send a buffered
97      * packet on success.
98      *
99      * If list_is_empty(ofconn_node) then this ofopgroup never had an
100      * associated ofconn or its ofconn's connection dropped after it initiated
101      * the operation.  In the latter case 'ofconn' is a wild pointer that
102      * refers to freed memory, so the 'ofconn' member must be used only if
103      * !list_is_empty(ofconn_node).
104      */
105     struct list ofconn_node;    /* In ofconn's list of pending opgroups. */
106     struct ofconn *ofconn;      /* ofconn for reply (but see note above). */
107     struct ofp_header *request; /* Original request (truncated at 64 bytes). */
108     uint32_t buffer_id;         /* Buffer id from original request. */
109 };
110
111 static struct ofopgroup *ofopgroup_create_unattached(struct ofproto *);
112 static struct ofopgroup *ofopgroup_create(struct ofproto *, struct ofconn *,
113                                           const struct ofp_header *,
114                                           uint32_t buffer_id);
115 static void ofopgroup_submit(struct ofopgroup *);
116 static void ofopgroup_complete(struct ofopgroup *);
117
118 /* A single flow table operation. */
119 struct ofoperation {
120     struct ofopgroup *group;    /* Owning group. */
121     struct list group_node;     /* In ofopgroup's "ops" list. */
122     struct hmap_node hmap_node; /* In ofproto's "deletions" hmap. */
123     struct rule *rule;          /* Rule being operated upon. */
124     enum ofoperation_type type; /* Type of operation. */
125
126     /* OFOPERATION_MODIFY, OFOPERATION_REPLACE: The old actions, if the actions
127      * are changing. */
128     struct rule_actions *actions;
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     uint16_t idle_timeout;              /* Rule's old idle timeout. */
135     uint16_t hard_timeout;              /* Rule's old hard timeout. */
136     enum ofputil_flow_mod_flags flags;  /* Rule's old flags. */
137     enum ofperr error;                  /* 0 if no error. */
138 };
139
140 static struct ofoperation *ofoperation_create(struct ofopgroup *,
141                                               struct rule *,
142                                               enum ofoperation_type,
143                                               enum ofp_flow_removed_reason);
144 static void ofoperation_destroy(struct ofoperation *);
145
146 /* oftable. */
147 static void oftable_init(struct oftable *);
148 static void oftable_destroy(struct oftable *);
149
150 static void oftable_set_name(struct oftable *, const char *name);
151
152 static void oftable_disable_eviction(struct oftable *);
153 static void oftable_enable_eviction(struct oftable *,
154                                     const struct mf_subfield *fields,
155                                     size_t n_fields);
156
157 static void oftable_remove_rule(struct rule *rule) OVS_REQUIRES(ofproto_mutex);
158 static void oftable_remove_rule__(struct ofproto *, struct rule *)
159     OVS_REQUIRES(ofproto_mutex);
160 static void oftable_insert_rule(struct rule *);
161
162 /* A set of rules within a single OpenFlow table (oftable) that have the same
163  * values for the oftable's eviction_fields.  A rule to be evicted, when one is
164  * needed, is taken from the eviction group that contains the greatest number
165  * of rules.
166  *
167  * An oftable owns any number of eviction groups, each of which contains any
168  * number of rules.
169  *
170  * Membership in an eviction group is imprecise, based on the hash of the
171  * oftable's eviction_fields (in the eviction_group's id_node.hash member).
172  * That is, if two rules have different eviction_fields, but those
173  * eviction_fields hash to the same value, then they will belong to the same
174  * eviction_group anyway.
175  *
176  * (When eviction is not enabled on an oftable, we don't track any eviction
177  * groups, to save time and space.) */
178 struct eviction_group {
179     struct hmap_node id_node;   /* In oftable's "eviction_groups_by_id". */
180     struct heap_node size_node; /* In oftable's "eviction_groups_by_size". */
181     struct heap rules;          /* Contains "struct rule"s. */
182 };
183
184 static bool choose_rule_to_evict(struct oftable *table, struct rule **rulep);
185 static void ofproto_evict(struct ofproto *) OVS_EXCLUDED(ofproto_mutex);
186 static uint32_t rule_eviction_priority(struct ofproto *ofproto, struct rule *);
187 static void eviction_group_add_rule(struct rule *);
188 static void eviction_group_remove_rule(struct rule *);
189
190 /* Criteria that flow_mod and other operations use for selecting rules on
191  * which to operate. */
192 struct rule_criteria {
193     /* An OpenFlow table or 255 for all tables. */
194     uint8_t table_id;
195
196     /* OpenFlow matching criteria.  Interpreted different in "loose" way by
197      * collect_rules_loose() and "strict" way by collect_rules_strict(), as
198      * defined in the OpenFlow spec. */
199     struct cls_rule cr;
200
201     /* Matching criteria for the OpenFlow cookie.  Consider a bit B in a rule's
202      * cookie and the corresponding bits C in 'cookie' and M in 'cookie_mask'.
203      * The rule will not be selected if M is 1 and B != C.  */
204     ovs_be64 cookie;
205     ovs_be64 cookie_mask;
206
207     /* Selection based on actions within a rule:
208      *
209      * If out_port != OFPP_ANY, selects only rules that output to out_port.
210      * If out_group != OFPG_ALL, select only rules that output to out_group. */
211     ofp_port_t out_port;
212     uint32_t out_group;
213 };
214
215 static void rule_criteria_init(struct rule_criteria *, uint8_t table_id,
216                                const struct match *match,
217                                unsigned int priority,
218                                ovs_be64 cookie, ovs_be64 cookie_mask,
219                                ofp_port_t out_port, uint32_t out_group);
220 static void rule_criteria_destroy(struct rule_criteria *);
221
222 /* A packet that needs to be passed to rule_execute().
223  *
224  * (We can't do this immediately from ofopgroup_complete() because that holds
225  * ofproto_mutex, which rule_execute() needs released.) */
226 struct rule_execute {
227     struct list list_node;      /* In struct ofproto's "rule_executes" list. */
228     struct rule *rule;          /* Owns a reference to the rule. */
229     ofp_port_t in_port;
230     struct ofpbuf *packet;      /* Owns the packet. */
231 };
232
233 static void run_rule_executes(struct ofproto *) OVS_EXCLUDED(ofproto_mutex);
234 static void destroy_rule_executes(struct ofproto *);
235
236 /* ofport. */
237 static void ofport_destroy__(struct ofport *) OVS_EXCLUDED(ofproto_mutex);
238 static void ofport_destroy(struct ofport *);
239
240 static void update_port(struct ofproto *, const char *devname);
241 static int init_ports(struct ofproto *);
242 static void reinit_ports(struct ofproto *);
243
244 static long long int ofport_get_usage(const struct ofproto *,
245                                       ofp_port_t ofp_port);
246 static void ofport_set_usage(struct ofproto *, ofp_port_t ofp_port,
247                              long long int last_used);
248 static void ofport_remove_usage(struct ofproto *, ofp_port_t ofp_port);
249
250 /* Ofport usage.
251  *
252  * Keeps track of the currently used and recently used ofport values and is
253  * used to prevent immediate recycling of ofport values. */
254 struct ofport_usage {
255     struct hmap_node hmap_node; /* In struct ofproto's "ofport_usage" hmap. */
256     ofp_port_t ofp_port;        /* OpenFlow port number. */
257     long long int last_used;    /* Last time the 'ofp_port' was used. LLONG_MAX
258                                    represents in-use ofports. */
259 };
260
261 /* rule. */
262 static void ofproto_rule_send_removed(struct rule *, uint8_t reason);
263 static bool rule_is_modifiable(const struct rule *rule,
264                                enum ofputil_flow_mod_flags flag);
265
266 /* OpenFlow. */
267 static enum ofperr add_flow(struct ofproto *, struct ofconn *,
268                             struct ofputil_flow_mod *,
269                             const struct ofp_header *);
270 static void do_add_flow(struct ofproto *, struct ofconn *,
271                         const struct ofp_header *request, uint32_t buffer_id,
272                         struct rule *);
273 static enum ofperr modify_flows__(struct ofproto *, struct ofconn *,
274                                   struct ofputil_flow_mod *,
275                                   const struct ofp_header *,
276                                   const struct rule_collection *);
277 static void delete_flow__(struct rule *rule, struct ofopgroup *,
278                           enum ofp_flow_removed_reason)
279     OVS_REQUIRES(ofproto_mutex);
280 static bool ofproto_group_exists__(const struct ofproto *ofproto,
281                                    uint32_t group_id)
282     OVS_REQ_RDLOCK(ofproto->groups_rwlock);
283 static bool ofproto_group_exists(const struct ofproto *ofproto,
284                                  uint32_t group_id)
285     OVS_EXCLUDED(ofproto->groups_rwlock);
286 static enum ofperr add_group(struct ofproto *, struct ofputil_group_mod *);
287 static bool handle_openflow(struct ofconn *, const struct ofpbuf *);
288 static enum ofperr handle_flow_mod__(struct ofproto *, struct ofconn *,
289                                      struct ofputil_flow_mod *,
290                                      const struct ofp_header *)
291     OVS_EXCLUDED(ofproto_mutex);
292 static void calc_duration(long long int start, long long int now,
293                           uint32_t *sec, uint32_t *nsec);
294
295 /* ofproto. */
296 static uint64_t pick_datapath_id(const struct ofproto *);
297 static uint64_t pick_fallback_dpid(void);
298 static void ofproto_destroy__(struct ofproto *);
299 static void update_mtu(struct ofproto *, struct ofport *);
300 static void meter_delete(struct ofproto *, uint32_t first, uint32_t last);
301
302 /* unixctl. */
303 static void ofproto_unixctl_init(void);
304
305 /* All registered ofproto classes, in probe order. */
306 static const struct ofproto_class **ofproto_classes;
307 static size_t n_ofproto_classes;
308 static size_t allocated_ofproto_classes;
309
310 /* Global lock that protects all flow table operations. */
311 struct ovs_mutex ofproto_mutex = OVS_MUTEX_INITIALIZER;
312
313 unsigned ofproto_flow_limit = OFPROTO_FLOW_LIMIT_DEFAULT;
314 unsigned ofproto_max_idle = OFPROTO_MAX_IDLE_DEFAULT;
315
316 size_t n_handlers, n_revalidators;
317
318 /* Map from datapath name to struct ofproto, for use by unixctl commands. */
319 static struct hmap all_ofprotos = HMAP_INITIALIZER(&all_ofprotos);
320
321 /* Initial mappings of port to OpenFlow number mappings. */
322 static struct shash init_ofp_ports = SHASH_INITIALIZER(&init_ofp_ports);
323
324 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
325
326 /* The default value of true waits for flow restore. */
327 static bool flow_restore_wait = true;
328
329 /* Must be called to initialize the ofproto library.
330  *
331  * The caller may pass in 'iface_hints', which contains an shash of
332  * "iface_hint" elements indexed by the interface's name.  The provider
333  * may use these hints to describe the startup configuration in order to
334  * reinitialize its state.  The caller owns the provided data, so a
335  * provider will make copies of anything required.  An ofproto provider
336  * will remove any existing state that is not described by the hint, and
337  * may choose to remove it all. */
338 void
339 ofproto_init(const struct shash *iface_hints)
340 {
341     struct shash_node *node;
342     size_t i;
343
344     ofproto_class_register(&ofproto_dpif_class);
345
346     /* Make a local copy, since we don't own 'iface_hints' elements. */
347     SHASH_FOR_EACH(node, iface_hints) {
348         const struct iface_hint *orig_hint = node->data;
349         struct iface_hint *new_hint = xmalloc(sizeof *new_hint);
350         const char *br_type = ofproto_normalize_type(orig_hint->br_type);
351
352         new_hint->br_name = xstrdup(orig_hint->br_name);
353         new_hint->br_type = xstrdup(br_type);
354         new_hint->ofp_port = orig_hint->ofp_port;
355
356         shash_add(&init_ofp_ports, node->name, new_hint);
357     }
358
359     for (i = 0; i < n_ofproto_classes; i++) {
360         ofproto_classes[i]->init(&init_ofp_ports);
361     }
362 }
363
364 /* 'type' should be a normalized datapath type, as returned by
365  * ofproto_normalize_type().  Returns the corresponding ofproto_class
366  * structure, or a null pointer if there is none registered for 'type'. */
367 static const struct ofproto_class *
368 ofproto_class_find__(const char *type)
369 {
370     size_t i;
371
372     for (i = 0; i < n_ofproto_classes; i++) {
373         const struct ofproto_class *class = ofproto_classes[i];
374         struct sset types;
375         bool found;
376
377         sset_init(&types);
378         class->enumerate_types(&types);
379         found = sset_contains(&types, type);
380         sset_destroy(&types);
381
382         if (found) {
383             return class;
384         }
385     }
386     VLOG_WARN("unknown datapath type %s", type);
387     return NULL;
388 }
389
390 /* Registers a new ofproto class.  After successful registration, new ofprotos
391  * of that type can be created using ofproto_create(). */
392 int
393 ofproto_class_register(const struct ofproto_class *new_class)
394 {
395     size_t i;
396
397     for (i = 0; i < n_ofproto_classes; i++) {
398         if (ofproto_classes[i] == new_class) {
399             return EEXIST;
400         }
401     }
402
403     if (n_ofproto_classes >= allocated_ofproto_classes) {
404         ofproto_classes = x2nrealloc(ofproto_classes,
405                                      &allocated_ofproto_classes,
406                                      sizeof *ofproto_classes);
407     }
408     ofproto_classes[n_ofproto_classes++] = new_class;
409     return 0;
410 }
411
412 /* Unregisters a datapath provider.  'type' must have been previously
413  * registered and not currently be in use by any ofprotos.  After
414  * unregistration new datapaths of that type cannot be opened using
415  * ofproto_create(). */
416 int
417 ofproto_class_unregister(const struct ofproto_class *class)
418 {
419     size_t i;
420
421     for (i = 0; i < n_ofproto_classes; i++) {
422         if (ofproto_classes[i] == class) {
423             for (i++; i < n_ofproto_classes; i++) {
424                 ofproto_classes[i - 1] = ofproto_classes[i];
425             }
426             n_ofproto_classes--;
427             return 0;
428         }
429     }
430     VLOG_WARN("attempted to unregister an ofproto class that is not "
431               "registered");
432     return EAFNOSUPPORT;
433 }
434
435 /* Clears 'types' and enumerates all registered ofproto types into it.  The
436  * caller must first initialize the sset. */
437 void
438 ofproto_enumerate_types(struct sset *types)
439 {
440     size_t i;
441
442     sset_clear(types);
443     for (i = 0; i < n_ofproto_classes; i++) {
444         ofproto_classes[i]->enumerate_types(types);
445     }
446 }
447
448 /* Returns the fully spelled out name for the given ofproto 'type'.
449  *
450  * Normalized type string can be compared with strcmp().  Unnormalized type
451  * string might be the same even if they have different spellings. */
452 const char *
453 ofproto_normalize_type(const char *type)
454 {
455     return type && type[0] ? type : "system";
456 }
457
458 /* Clears 'names' and enumerates the names of all known created ofprotos with
459  * the given 'type'.  The caller must first initialize the sset.  Returns 0 if
460  * successful, otherwise a positive errno value.
461  *
462  * Some kinds of datapaths might not be practically enumerable.  This is not
463  * considered an error. */
464 int
465 ofproto_enumerate_names(const char *type, struct sset *names)
466 {
467     const struct ofproto_class *class = ofproto_class_find__(type);
468     return class ? class->enumerate_names(type, names) : EAFNOSUPPORT;
469 }
470
471 int
472 ofproto_create(const char *datapath_name, const char *datapath_type,
473                struct ofproto **ofprotop)
474 {
475     const struct ofproto_class *class;
476     struct ofproto *ofproto;
477     int error;
478     int i;
479
480     *ofprotop = NULL;
481
482     ofproto_unixctl_init();
483
484     datapath_type = ofproto_normalize_type(datapath_type);
485     class = ofproto_class_find__(datapath_type);
486     if (!class) {
487         VLOG_WARN("could not create datapath %s of unknown type %s",
488                   datapath_name, datapath_type);
489         return EAFNOSUPPORT;
490     }
491
492     ofproto = class->alloc();
493     if (!ofproto) {
494         VLOG_ERR("failed to allocate datapath %s of type %s",
495                  datapath_name, datapath_type);
496         return ENOMEM;
497     }
498
499     /* Initialize. */
500     ovs_mutex_lock(&ofproto_mutex);
501     memset(ofproto, 0, sizeof *ofproto);
502     ofproto->ofproto_class = class;
503     ofproto->name = xstrdup(datapath_name);
504     ofproto->type = xstrdup(datapath_type);
505     hmap_insert(&all_ofprotos, &ofproto->hmap_node,
506                 hash_string(ofproto->name, 0));
507     ofproto->datapath_id = 0;
508     ofproto->forward_bpdu = false;
509     ofproto->fallback_dpid = pick_fallback_dpid();
510     ofproto->mfr_desc = NULL;
511     ofproto->hw_desc = NULL;
512     ofproto->sw_desc = NULL;
513     ofproto->serial_desc = NULL;
514     ofproto->dp_desc = NULL;
515     ofproto->frag_handling = OFPC_FRAG_NORMAL;
516     hmap_init(&ofproto->ports);
517     hmap_init(&ofproto->ofport_usage);
518     shash_init(&ofproto->port_by_name);
519     simap_init(&ofproto->ofp_requests);
520     ofproto->max_ports = ofp_to_u16(OFPP_MAX);
521     ofproto->eviction_group_timer = LLONG_MIN;
522     ofproto->tables = NULL;
523     ofproto->n_tables = 0;
524     hindex_init(&ofproto->cookies);
525     list_init(&ofproto->expirable);
526     ofproto->connmgr = connmgr_create(ofproto, datapath_name, datapath_name);
527     ofproto->state = S_OPENFLOW;
528     list_init(&ofproto->pending);
529     ofproto->n_pending = 0;
530     hmap_init(&ofproto->deletions);
531     guarded_list_init(&ofproto->rule_executes);
532     ofproto->n_add = ofproto->n_delete = ofproto->n_modify = 0;
533     ofproto->first_op = ofproto->last_op = LLONG_MIN;
534     ofproto->next_op_report = LLONG_MAX;
535     ofproto->op_backoff = LLONG_MIN;
536     ofproto->vlan_bitmap = NULL;
537     ofproto->vlans_changed = false;
538     ofproto->min_mtu = INT_MAX;
539     ovs_rwlock_init(&ofproto->groups_rwlock);
540     hmap_init(&ofproto->groups);
541     ovs_mutex_unlock(&ofproto_mutex);
542     ofproto->ogf.capabilities = OFPGFC_CHAINING | OFPGFC_SELECT_LIVENESS |
543                                 OFPGFC_SELECT_WEIGHT;
544     ofproto->ogf.max_groups[OFPGT11_ALL] = OFPG_MAX;
545     ofproto->ogf.max_groups[OFPGT11_SELECT] = OFPG_MAX;
546     ofproto->ogf.max_groups[OFPGT11_INDIRECT] = OFPG_MAX;
547     ofproto->ogf.max_groups[OFPGT11_FF] = OFPG_MAX;
548     ofproto->ogf.actions[0] =
549         (1 << OFPAT11_OUTPUT) |
550         (1 << OFPAT11_COPY_TTL_OUT) |
551         (1 << OFPAT11_COPY_TTL_IN) |
552         (1 << OFPAT11_SET_MPLS_TTL) |
553         (1 << OFPAT11_DEC_MPLS_TTL) |
554         (1 << OFPAT11_PUSH_VLAN) |
555         (1 << OFPAT11_POP_VLAN) |
556         (1 << OFPAT11_PUSH_MPLS) |
557         (1 << OFPAT11_POP_MPLS) |
558         (1 << OFPAT11_SET_QUEUE) |
559         (1 << OFPAT11_GROUP) |
560         (1 << OFPAT11_SET_NW_TTL) |
561         (1 << OFPAT11_DEC_NW_TTL) |
562         (1 << OFPAT12_SET_FIELD);
563 /* not supported:
564  *      (1 << OFPAT13_PUSH_PBB) |
565  *      (1 << OFPAT13_POP_PBB) */
566
567     error = ofproto->ofproto_class->construct(ofproto);
568     if (error) {
569         VLOG_ERR("failed to open datapath %s: %s",
570                  datapath_name, ovs_strerror(error));
571         ofproto_destroy__(ofproto);
572         return error;
573     }
574
575     /* Check that hidden tables, if any, are at the end. */
576     ovs_assert(ofproto->n_tables);
577     for (i = 0; i + 1 < ofproto->n_tables; i++) {
578         enum oftable_flags flags = ofproto->tables[i].flags;
579         enum oftable_flags next_flags = ofproto->tables[i + 1].flags;
580
581         ovs_assert(!(flags & OFTABLE_HIDDEN) || next_flags & OFTABLE_HIDDEN);
582     }
583
584     ofproto->datapath_id = pick_datapath_id(ofproto);
585     init_ports(ofproto);
586
587     /* Initialize meters table. */
588     if (ofproto->ofproto_class->meter_get_features) {
589         ofproto->ofproto_class->meter_get_features(ofproto,
590                                                    &ofproto->meter_features);
591     } else {
592         memset(&ofproto->meter_features, 0, sizeof ofproto->meter_features);
593     }
594     ofproto->meters = xzalloc((ofproto->meter_features.max_meters + 1)
595                               * sizeof(struct meter *));
596
597     *ofprotop = ofproto;
598     return 0;
599 }
600
601 /* Must be called (only) by an ofproto implementation in its constructor
602  * function.  See the large comment on 'construct' in struct ofproto_class for
603  * details. */
604 void
605 ofproto_init_tables(struct ofproto *ofproto, int n_tables)
606 {
607     struct oftable *table;
608
609     ovs_assert(!ofproto->n_tables);
610     ovs_assert(n_tables >= 1 && n_tables <= 255);
611
612     ofproto->n_tables = n_tables;
613     ofproto->tables = xmalloc(n_tables * sizeof *ofproto->tables);
614     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
615         oftable_init(table);
616     }
617 }
618
619 /* To be optionally called (only) by an ofproto implementation in its
620  * constructor function.  See the large comment on 'construct' in struct
621  * ofproto_class for details.
622  *
623  * Sets the maximum number of ports to 'max_ports'.  The ofproto generic layer
624  * will then ensure that actions passed into the ofproto implementation will
625  * not refer to OpenFlow ports numbered 'max_ports' or higher.  If this
626  * function is not called, there will be no such restriction.
627  *
628  * Reserved ports numbered OFPP_MAX and higher are special and not subject to
629  * the 'max_ports' restriction. */
630 void
631 ofproto_init_max_ports(struct ofproto *ofproto, uint16_t max_ports)
632 {
633     ovs_assert(max_ports <= ofp_to_u16(OFPP_MAX));
634     ofproto->max_ports = max_ports;
635 }
636
637 uint64_t
638 ofproto_get_datapath_id(const struct ofproto *ofproto)
639 {
640     return ofproto->datapath_id;
641 }
642
643 void
644 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
645 {
646     uint64_t old_dpid = p->datapath_id;
647     p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
648     if (p->datapath_id != old_dpid) {
649         /* Force all active connections to reconnect, since there is no way to
650          * notify a controller that the datapath ID has changed. */
651         ofproto_reconnect_controllers(p);
652     }
653 }
654
655 void
656 ofproto_set_controllers(struct ofproto *p,
657                         const struct ofproto_controller *controllers,
658                         size_t n_controllers, uint32_t allowed_versions)
659 {
660     connmgr_set_controllers(p->connmgr, controllers, n_controllers,
661                             allowed_versions);
662 }
663
664 void
665 ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
666 {
667     connmgr_set_fail_mode(p->connmgr, fail_mode);
668 }
669
670 /* Drops the connections between 'ofproto' and all of its controllers, forcing
671  * them to reconnect. */
672 void
673 ofproto_reconnect_controllers(struct ofproto *ofproto)
674 {
675     connmgr_reconnect(ofproto->connmgr);
676 }
677
678 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
679  * in-band control should guarantee access, in the same way that in-band
680  * control guarantees access to OpenFlow controllers. */
681 void
682 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
683                                   const struct sockaddr_in *extras, size_t n)
684 {
685     connmgr_set_extra_in_band_remotes(ofproto->connmgr, extras, n);
686 }
687
688 /* Sets the OpenFlow queue used by flows set up by in-band control on
689  * 'ofproto' to 'queue_id'.  If 'queue_id' is negative, then in-band control
690  * flows will use the default queue. */
691 void
692 ofproto_set_in_band_queue(struct ofproto *ofproto, int queue_id)
693 {
694     connmgr_set_in_band_queue(ofproto->connmgr, queue_id);
695 }
696
697 /* Sets the number of flows at which eviction from the kernel flow table
698  * will occur. */
699 void
700 ofproto_set_flow_limit(unsigned limit)
701 {
702     ofproto_flow_limit = limit;
703 }
704
705 /* Sets the maximum idle time for flows in the datapath before they are
706  * expired. */
707 void
708 ofproto_set_max_idle(unsigned max_idle)
709 {
710     ofproto_max_idle = max_idle;
711 }
712
713 /* If forward_bpdu is true, the NORMAL action will forward frames with
714  * reserved (e.g. STP) destination Ethernet addresses. if forward_bpdu is false,
715  * the NORMAL action will drop these frames. */
716 void
717 ofproto_set_forward_bpdu(struct ofproto *ofproto, bool forward_bpdu)
718 {
719     bool old_val = ofproto->forward_bpdu;
720     ofproto->forward_bpdu = forward_bpdu;
721     if (old_val != ofproto->forward_bpdu) {
722         if (ofproto->ofproto_class->forward_bpdu_changed) {
723             ofproto->ofproto_class->forward_bpdu_changed(ofproto);
724         }
725     }
726 }
727
728 /* Sets the MAC aging timeout for the OFPP_NORMAL action on 'ofproto' to
729  * 'idle_time', in seconds, and the maximum number of MAC table entries to
730  * 'max_entries'. */
731 void
732 ofproto_set_mac_table_config(struct ofproto *ofproto, unsigned idle_time,
733                              size_t max_entries)
734 {
735     if (ofproto->ofproto_class->set_mac_table_config) {
736         ofproto->ofproto_class->set_mac_table_config(ofproto, idle_time,
737                                                      max_entries);
738     }
739 }
740
741 void
742 ofproto_set_threads(int n_handlers_, int n_revalidators_)
743 {
744     int threads = MAX(count_cpu_cores(), 2);
745
746     n_revalidators = MAX(n_revalidators_, 0);
747     n_handlers = MAX(n_handlers_, 0);
748
749     if (!n_revalidators) {
750         n_revalidators = n_handlers
751             ? MAX(threads - (int) n_handlers, 1)
752             : threads / 4 + 1;
753     }
754
755     if (!n_handlers) {
756         n_handlers = MAX(threads - (int) n_revalidators, 1);
757     }
758 }
759
760 void
761 ofproto_set_dp_desc(struct ofproto *p, const char *dp_desc)
762 {
763     free(p->dp_desc);
764     p->dp_desc = dp_desc ? xstrdup(dp_desc) : NULL;
765 }
766
767 int
768 ofproto_set_snoops(struct ofproto *ofproto, const struct sset *snoops)
769 {
770     return connmgr_set_snoops(ofproto->connmgr, snoops);
771 }
772
773 int
774 ofproto_set_netflow(struct ofproto *ofproto,
775                     const struct netflow_options *nf_options)
776 {
777     if (nf_options && sset_is_empty(&nf_options->collectors)) {
778         nf_options = NULL;
779     }
780
781     if (ofproto->ofproto_class->set_netflow) {
782         return ofproto->ofproto_class->set_netflow(ofproto, nf_options);
783     } else {
784         return nf_options ? EOPNOTSUPP : 0;
785     }
786 }
787
788 int
789 ofproto_set_sflow(struct ofproto *ofproto,
790                   const struct ofproto_sflow_options *oso)
791 {
792     if (oso && sset_is_empty(&oso->targets)) {
793         oso = NULL;
794     }
795
796     if (ofproto->ofproto_class->set_sflow) {
797         return ofproto->ofproto_class->set_sflow(ofproto, oso);
798     } else {
799         return oso ? EOPNOTSUPP : 0;
800     }
801 }
802
803 int
804 ofproto_set_ipfix(struct ofproto *ofproto,
805                   const struct ofproto_ipfix_bridge_exporter_options *bo,
806                   const struct ofproto_ipfix_flow_exporter_options *fo,
807                   size_t n_fo)
808 {
809     if (ofproto->ofproto_class->set_ipfix) {
810         return ofproto->ofproto_class->set_ipfix(ofproto, bo, fo, n_fo);
811     } else {
812         return (bo || fo) ? EOPNOTSUPP : 0;
813     }
814 }
815
816 void
817 ofproto_set_flow_restore_wait(bool flow_restore_wait_db)
818 {
819     flow_restore_wait = flow_restore_wait_db;
820 }
821
822 bool
823 ofproto_get_flow_restore_wait(void)
824 {
825     return flow_restore_wait;
826 }
827
828 \f
829 /* Spanning Tree Protocol (STP) configuration. */
830
831 /* Configures STP on 'ofproto' using the settings defined in 's'.  If
832  * 's' is NULL, disables STP.
833  *
834  * Returns 0 if successful, otherwise a positive errno value. */
835 int
836 ofproto_set_stp(struct ofproto *ofproto,
837                 const struct ofproto_stp_settings *s)
838 {
839     return (ofproto->ofproto_class->set_stp
840             ? ofproto->ofproto_class->set_stp(ofproto, s)
841             : EOPNOTSUPP);
842 }
843
844 /* Retrieves STP status of 'ofproto' and stores it in 's'.  If the
845  * 'enabled' member of 's' is false, then the other members are not
846  * meaningful.
847  *
848  * Returns 0 if successful, otherwise a positive errno value. */
849 int
850 ofproto_get_stp_status(struct ofproto *ofproto,
851                        struct ofproto_stp_status *s)
852 {
853     return (ofproto->ofproto_class->get_stp_status
854             ? ofproto->ofproto_class->get_stp_status(ofproto, s)
855             : EOPNOTSUPP);
856 }
857
858 /* Configures STP on 'ofp_port' of 'ofproto' using the settings defined
859  * in 's'.  The caller is responsible for assigning STP port numbers
860  * (using the 'port_num' member in the range of 1 through 255, inclusive)
861  * and ensuring there are no duplicates.  If the 's' is NULL, then STP
862  * is disabled on the port.
863  *
864  * Returns 0 if successful, otherwise a positive errno value.*/
865 int
866 ofproto_port_set_stp(struct ofproto *ofproto, ofp_port_t ofp_port,
867                      const struct ofproto_port_stp_settings *s)
868 {
869     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
870     if (!ofport) {
871         VLOG_WARN("%s: cannot configure STP on nonexistent port %"PRIu16,
872                   ofproto->name, ofp_port);
873         return ENODEV;
874     }
875
876     return (ofproto->ofproto_class->set_stp_port
877             ? ofproto->ofproto_class->set_stp_port(ofport, s)
878             : EOPNOTSUPP);
879 }
880
881 /* Retrieves STP port status of 'ofp_port' on 'ofproto' and stores it in
882  * 's'.  If the 'enabled' member in 's' is false, then the other members
883  * are not meaningful.
884  *
885  * Returns 0 if successful, otherwise a positive errno value.*/
886 int
887 ofproto_port_get_stp_status(struct ofproto *ofproto, ofp_port_t ofp_port,
888                             struct ofproto_port_stp_status *s)
889 {
890     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
891     if (!ofport) {
892         VLOG_WARN_RL(&rl, "%s: cannot get STP status on nonexistent "
893                      "port %"PRIu16, ofproto->name, ofp_port);
894         return ENODEV;
895     }
896
897     return (ofproto->ofproto_class->get_stp_port_status
898             ? ofproto->ofproto_class->get_stp_port_status(ofport, s)
899             : EOPNOTSUPP);
900 }
901
902 /* Retrieves STP port statistics of 'ofp_port' on 'ofproto' and stores it in
903  * 's'.  If the 'enabled' member in 's' is false, then the other members
904  * are not meaningful.
905  *
906  * Returns 0 if successful, otherwise a positive errno value.*/
907 int
908 ofproto_port_get_stp_stats(struct ofproto *ofproto, ofp_port_t ofp_port,
909                            struct ofproto_port_stp_stats *s)
910 {
911     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
912     if (!ofport) {
913         VLOG_WARN_RL(&rl, "%s: cannot get STP stats on nonexistent "
914                      "port %"PRIu16, ofproto->name, ofp_port);
915         return ENODEV;
916     }
917
918     return (ofproto->ofproto_class->get_stp_port_stats
919             ? ofproto->ofproto_class->get_stp_port_stats(ofport, s)
920             : EOPNOTSUPP);
921 }
922 \f
923 /* Queue DSCP configuration. */
924
925 /* Registers meta-data associated with the 'n_qdscp' Qualities of Service
926  * 'queues' attached to 'ofport'.  This data is not intended to be sufficient
927  * to implement QoS.  Instead, it is used to implement features which require
928  * knowledge of what queues exist on a port, and some basic information about
929  * them.
930  *
931  * Returns 0 if successful, otherwise a positive errno value. */
932 int
933 ofproto_port_set_queues(struct ofproto *ofproto, ofp_port_t ofp_port,
934                         const struct ofproto_port_queue *queues,
935                         size_t n_queues)
936 {
937     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
938
939     if (!ofport) {
940         VLOG_WARN("%s: cannot set queues on nonexistent port %"PRIu16,
941                   ofproto->name, ofp_port);
942         return ENODEV;
943     }
944
945     return (ofproto->ofproto_class->set_queues
946             ? ofproto->ofproto_class->set_queues(ofport, queues, n_queues)
947             : EOPNOTSUPP);
948 }
949 \f
950 /* Connectivity Fault Management configuration. */
951
952 /* Clears the CFM configuration from 'ofp_port' on 'ofproto'. */
953 void
954 ofproto_port_clear_cfm(struct ofproto *ofproto, ofp_port_t ofp_port)
955 {
956     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
957     if (ofport && ofproto->ofproto_class->set_cfm) {
958         ofproto->ofproto_class->set_cfm(ofport, NULL);
959     }
960 }
961
962 /* Configures connectivity fault management on 'ofp_port' in 'ofproto'.  Takes
963  * basic configuration from the configuration members in 'cfm', and the remote
964  * maintenance point ID from  remote_mpid.  Ignores the statistics members of
965  * 'cfm'.
966  *
967  * This function has no effect if 'ofproto' does not have a port 'ofp_port'. */
968 void
969 ofproto_port_set_cfm(struct ofproto *ofproto, ofp_port_t ofp_port,
970                      const struct cfm_settings *s)
971 {
972     struct ofport *ofport;
973     int error;
974
975     ofport = ofproto_get_port(ofproto, ofp_port);
976     if (!ofport) {
977         VLOG_WARN("%s: cannot configure CFM on nonexistent port %"PRIu16,
978                   ofproto->name, ofp_port);
979         return;
980     }
981
982     /* XXX: For configuration simplicity, we only support one remote_mpid
983      * outside of the CFM module.  It's not clear if this is the correct long
984      * term solution or not. */
985     error = (ofproto->ofproto_class->set_cfm
986              ? ofproto->ofproto_class->set_cfm(ofport, s)
987              : EOPNOTSUPP);
988     if (error) {
989         VLOG_WARN("%s: CFM configuration on port %"PRIu16" (%s) failed (%s)",
990                   ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
991                   ovs_strerror(error));
992     }
993 }
994
995 /* Configures BFD on 'ofp_port' in 'ofproto'.  This function has no effect if
996  * 'ofproto' does not have a port 'ofp_port'. */
997 void
998 ofproto_port_set_bfd(struct ofproto *ofproto, ofp_port_t ofp_port,
999                      const struct smap *cfg)
1000 {
1001     struct ofport *ofport;
1002     int error;
1003
1004     ofport = ofproto_get_port(ofproto, ofp_port);
1005     if (!ofport) {
1006         VLOG_WARN("%s: cannot configure bfd on nonexistent port %"PRIu16,
1007                   ofproto->name, ofp_port);
1008         return;
1009     }
1010
1011     error = (ofproto->ofproto_class->set_bfd
1012              ? ofproto->ofproto_class->set_bfd(ofport, cfg)
1013              : EOPNOTSUPP);
1014     if (error) {
1015         VLOG_WARN("%s: bfd configuration on port %"PRIu16" (%s) failed (%s)",
1016                   ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
1017                   ovs_strerror(error));
1018     }
1019 }
1020
1021 /* Populates 'status' with key value pairs indicating the status of the BFD
1022  * session on 'ofp_port'.  This information is intended to be populated in the
1023  * OVS database.  Has no effect if 'ofp_port' is not na OpenFlow port in
1024  * 'ofproto'. */
1025 int
1026 ofproto_port_get_bfd_status(struct ofproto *ofproto, ofp_port_t ofp_port,
1027                             struct smap *status)
1028 {
1029     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1030     return (ofport && ofproto->ofproto_class->get_bfd_status
1031             ? ofproto->ofproto_class->get_bfd_status(ofport, status)
1032             : EOPNOTSUPP);
1033 }
1034
1035 /* Checks the status of LACP negotiation for 'ofp_port' within ofproto.
1036  * Returns 1 if LACP partner information for 'ofp_port' is up-to-date,
1037  * 0 if LACP partner information is not current (generally indicating a
1038  * connectivity problem), or -1 if LACP is not enabled on 'ofp_port'. */
1039 int
1040 ofproto_port_is_lacp_current(struct ofproto *ofproto, ofp_port_t ofp_port)
1041 {
1042     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1043     return (ofport && ofproto->ofproto_class->port_is_lacp_current
1044             ? ofproto->ofproto_class->port_is_lacp_current(ofport)
1045             : -1);
1046 }
1047 \f
1048 /* Bundles. */
1049
1050 /* Registers a "bundle" associated with client data pointer 'aux' in 'ofproto'.
1051  * A bundle is the same concept as a Port in OVSDB, that is, it consists of one
1052  * or more "slave" devices (Interfaces, in OVSDB) along with a VLAN
1053  * configuration plus, if there is more than one slave, a bonding
1054  * configuration.
1055  *
1056  * If 'aux' is already registered then this function updates its configuration
1057  * to 's'.  Otherwise, this function registers a new bundle.
1058  *
1059  * Bundles only affect the NXAST_AUTOPATH action and output to the OFPP_NORMAL
1060  * port. */
1061 int
1062 ofproto_bundle_register(struct ofproto *ofproto, void *aux,
1063                         const struct ofproto_bundle_settings *s)
1064 {
1065     return (ofproto->ofproto_class->bundle_set
1066             ? ofproto->ofproto_class->bundle_set(ofproto, aux, s)
1067             : EOPNOTSUPP);
1068 }
1069
1070 /* Unregisters the bundle registered on 'ofproto' with auxiliary data 'aux'.
1071  * If no such bundle has been registered, this has no effect. */
1072 int
1073 ofproto_bundle_unregister(struct ofproto *ofproto, void *aux)
1074 {
1075     return ofproto_bundle_register(ofproto, aux, NULL);
1076 }
1077
1078 \f
1079 /* Registers a mirror associated with client data pointer 'aux' in 'ofproto'.
1080  * If 'aux' is already registered then this function updates its configuration
1081  * to 's'.  Otherwise, this function registers a new mirror. */
1082 int
1083 ofproto_mirror_register(struct ofproto *ofproto, void *aux,
1084                         const struct ofproto_mirror_settings *s)
1085 {
1086     return (ofproto->ofproto_class->mirror_set
1087             ? ofproto->ofproto_class->mirror_set(ofproto, aux, s)
1088             : EOPNOTSUPP);
1089 }
1090
1091 /* Unregisters the mirror registered on 'ofproto' with auxiliary data 'aux'.
1092  * If no mirror has been registered, this has no effect. */
1093 int
1094 ofproto_mirror_unregister(struct ofproto *ofproto, void *aux)
1095 {
1096     return ofproto_mirror_register(ofproto, aux, NULL);
1097 }
1098
1099 /* Retrieves statistics from mirror associated with client data pointer
1100  * 'aux' in 'ofproto'.  Stores packet and byte counts in 'packets' and
1101  * 'bytes', respectively.  If a particular counters is not supported,
1102  * the appropriate argument is set to UINT64_MAX. */
1103 int
1104 ofproto_mirror_get_stats(struct ofproto *ofproto, void *aux,
1105                          uint64_t *packets, uint64_t *bytes)
1106 {
1107     if (!ofproto->ofproto_class->mirror_get_stats) {
1108         *packets = *bytes = UINT64_MAX;
1109         return EOPNOTSUPP;
1110     }
1111
1112     return ofproto->ofproto_class->mirror_get_stats(ofproto, aux,
1113                                                     packets, bytes);
1114 }
1115
1116 /* Configures the VLANs whose bits are set to 1 in 'flood_vlans' as VLANs on
1117  * which all packets are flooded, instead of using MAC learning.  If
1118  * 'flood_vlans' is NULL, then MAC learning applies to all VLANs.
1119  *
1120  * Flood VLANs affect only the treatment of packets output to the OFPP_NORMAL
1121  * port. */
1122 int
1123 ofproto_set_flood_vlans(struct ofproto *ofproto, unsigned long *flood_vlans)
1124 {
1125     return (ofproto->ofproto_class->set_flood_vlans
1126             ? ofproto->ofproto_class->set_flood_vlans(ofproto, flood_vlans)
1127             : EOPNOTSUPP);
1128 }
1129
1130 /* Returns true if 'aux' is a registered bundle that is currently in use as the
1131  * output for a mirror. */
1132 bool
1133 ofproto_is_mirror_output_bundle(const struct ofproto *ofproto, void *aux)
1134 {
1135     return (ofproto->ofproto_class->is_mirror_output_bundle
1136             ? ofproto->ofproto_class->is_mirror_output_bundle(ofproto, aux)
1137             : false);
1138 }
1139 \f
1140 /* Configuration of OpenFlow tables. */
1141
1142 /* Returns the number of OpenFlow tables in 'ofproto'. */
1143 int
1144 ofproto_get_n_tables(const struct ofproto *ofproto)
1145 {
1146     return ofproto->n_tables;
1147 }
1148
1149 /* Returns the number of Controller visible OpenFlow tables
1150  * in 'ofproto'. This number will exclude Hidden tables.
1151  * This funtion's return value should be less or equal to that of
1152  * ofproto_get_n_tables() . */
1153 uint8_t
1154 ofproto_get_n_visible_tables(const struct ofproto *ofproto)
1155 {
1156     uint8_t n = ofproto->n_tables;
1157
1158     /* Count only non-hidden tables in the number of tables.  (Hidden tables,
1159      * if present, are always at the end.) */
1160     while(n && (ofproto->tables[n - 1].flags & OFTABLE_HIDDEN)) {
1161         n--;
1162     }
1163
1164     return n;
1165 }
1166
1167 /* Configures the OpenFlow table in 'ofproto' with id 'table_id' with the
1168  * settings from 's'.  'table_id' must be in the range 0 through the number of
1169  * OpenFlow tables in 'ofproto' minus 1, inclusive.
1170  *
1171  * For read-only tables, only the name may be configured. */
1172 void
1173 ofproto_configure_table(struct ofproto *ofproto, int table_id,
1174                         const struct ofproto_table_settings *s)
1175 {
1176     struct oftable *table;
1177
1178     ovs_assert(table_id >= 0 && table_id < ofproto->n_tables);
1179     table = &ofproto->tables[table_id];
1180
1181     oftable_set_name(table, s->name);
1182
1183     if (table->flags & OFTABLE_READONLY) {
1184         return;
1185     }
1186
1187     if (s->groups) {
1188         oftable_enable_eviction(table, s->groups, s->n_groups);
1189     } else {
1190         oftable_disable_eviction(table);
1191     }
1192
1193     table->max_flows = s->max_flows;
1194     fat_rwlock_wrlock(&table->cls.rwlock);
1195     if (classifier_count(&table->cls) > table->max_flows
1196         && table->eviction_fields) {
1197         /* 'table' contains more flows than allowed.  We might not be able to
1198          * evict them right away because of the asynchronous nature of flow
1199          * table changes.  Schedule eviction for later. */
1200         switch (ofproto->state) {
1201         case S_OPENFLOW:
1202             ofproto->state = S_EVICT;
1203             break;
1204         case S_EVICT:
1205         case S_FLUSH:
1206             /* We're already deleting flows, nothing more to do. */
1207             break;
1208         }
1209     }
1210
1211     classifier_set_prefix_fields(&table->cls,
1212                                  s->prefix_fields, s->n_prefix_fields);
1213
1214     fat_rwlock_unlock(&table->cls.rwlock);
1215 }
1216 \f
1217 bool
1218 ofproto_has_snoops(const struct ofproto *ofproto)
1219 {
1220     return connmgr_has_snoops(ofproto->connmgr);
1221 }
1222
1223 void
1224 ofproto_get_snoops(const struct ofproto *ofproto, struct sset *snoops)
1225 {
1226     connmgr_get_snoops(ofproto->connmgr, snoops);
1227 }
1228
1229 static void
1230 ofproto_rule_delete__(struct ofproto *ofproto, struct rule *rule,
1231                       uint8_t reason)
1232     OVS_REQUIRES(ofproto_mutex)
1233 {
1234     struct ofopgroup *group;
1235
1236     ovs_assert(!rule->pending);
1237
1238     group = ofopgroup_create_unattached(ofproto);
1239     delete_flow__(rule, group, reason);
1240     ofopgroup_submit(group);
1241 }
1242
1243 /* Deletes 'rule' from 'ofproto'.
1244  *
1245  * Within an ofproto implementation, this function allows an ofproto
1246  * implementation to destroy any rules that remain when its ->destruct()
1247  * function is called.  This function is not suitable for use elsewhere in an
1248  * ofproto implementation.
1249  *
1250  * This function implements steps 4.4 and 4.5 in the section titled "Rule Life
1251  * Cycle" in ofproto-provider.h. */
1252 void
1253 ofproto_rule_delete(struct ofproto *ofproto, struct rule *rule)
1254     OVS_EXCLUDED(ofproto_mutex)
1255 {
1256     struct ofopgroup *group;
1257
1258     ovs_mutex_lock(&ofproto_mutex);
1259     ovs_assert(!rule->pending);
1260
1261     group = ofopgroup_create_unattached(ofproto);
1262     ofoperation_create(group, rule, OFOPERATION_DELETE, OFPRR_DELETE);
1263     oftable_remove_rule__(ofproto, rule);
1264     ofproto->ofproto_class->rule_delete(rule);
1265     ofopgroup_submit(group);
1266
1267     ovs_mutex_unlock(&ofproto_mutex);
1268 }
1269
1270 static void
1271 ofproto_flush__(struct ofproto *ofproto)
1272     OVS_EXCLUDED(ofproto_mutex)
1273 {
1274     struct oftable *table;
1275
1276     if (ofproto->ofproto_class->flush) {
1277         ofproto->ofproto_class->flush(ofproto);
1278     }
1279
1280     ovs_mutex_lock(&ofproto_mutex);
1281     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1282         struct rule *rule, *next_rule;
1283         struct cls_cursor cursor;
1284
1285         if (table->flags & OFTABLE_HIDDEN) {
1286             continue;
1287         }
1288
1289         fat_rwlock_rdlock(&table->cls.rwlock);
1290         cls_cursor_init(&cursor, &table->cls, NULL);
1291         fat_rwlock_unlock(&table->cls.rwlock);
1292         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
1293             if (!rule->pending) {
1294                 ofproto_rule_delete__(ofproto, rule, OFPRR_DELETE);
1295             }
1296         }
1297     }
1298     ovs_mutex_unlock(&ofproto_mutex);
1299 }
1300
1301 static void delete_group(struct ofproto *ofproto, uint32_t group_id);
1302
1303 static void
1304 ofproto_destroy__(struct ofproto *ofproto)
1305     OVS_EXCLUDED(ofproto_mutex)
1306 {
1307     struct oftable *table;
1308
1309     ovs_assert(list_is_empty(&ofproto->pending));
1310
1311     destroy_rule_executes(ofproto);
1312     guarded_list_destroy(&ofproto->rule_executes);
1313
1314     delete_group(ofproto, OFPG_ALL);
1315     ovs_rwlock_destroy(&ofproto->groups_rwlock);
1316     hmap_destroy(&ofproto->groups);
1317
1318     connmgr_destroy(ofproto->connmgr);
1319
1320     hmap_remove(&all_ofprotos, &ofproto->hmap_node);
1321     free(ofproto->name);
1322     free(ofproto->type);
1323     free(ofproto->mfr_desc);
1324     free(ofproto->hw_desc);
1325     free(ofproto->sw_desc);
1326     free(ofproto->serial_desc);
1327     free(ofproto->dp_desc);
1328     hmap_destroy(&ofproto->ports);
1329     hmap_destroy(&ofproto->ofport_usage);
1330     shash_destroy(&ofproto->port_by_name);
1331     simap_destroy(&ofproto->ofp_requests);
1332
1333     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1334         oftable_destroy(table);
1335     }
1336     free(ofproto->tables);
1337
1338     hmap_destroy(&ofproto->deletions);
1339
1340     free(ofproto->vlan_bitmap);
1341
1342     ofproto->ofproto_class->dealloc(ofproto);
1343 }
1344
1345 void
1346 ofproto_destroy(struct ofproto *p)
1347     OVS_EXCLUDED(ofproto_mutex)
1348 {
1349     struct ofport *ofport, *next_ofport;
1350     struct ofport_usage *usage, *next_usage;
1351
1352     if (!p) {
1353         return;
1354     }
1355
1356     if (p->meters) {
1357         meter_delete(p, 1, p->meter_features.max_meters);
1358         p->meter_features.max_meters = 0;
1359         free(p->meters);
1360         p->meters = NULL;
1361     }
1362
1363     ofproto_flush__(p);
1364     HMAP_FOR_EACH_SAFE (ofport, next_ofport, hmap_node, &p->ports) {
1365         ofport_destroy(ofport);
1366     }
1367
1368     HMAP_FOR_EACH_SAFE (usage, next_usage, hmap_node, &p->ofport_usage) {
1369         hmap_remove(&p->ofport_usage, &usage->hmap_node);
1370         free(usage);
1371     }
1372
1373     p->ofproto_class->destruct(p);
1374     /* Destroying rules is deferred, must have 'ofproto' around for them. */
1375     ovsrcu_postpone(ofproto_destroy__, p);
1376 }
1377
1378 /* Destroys the datapath with the respective 'name' and 'type'.  With the Linux
1379  * kernel datapath, for example, this destroys the datapath in the kernel, and
1380  * with the netdev-based datapath, it tears down the data structures that
1381  * represent the datapath.
1382  *
1383  * The datapath should not be currently open as an ofproto. */
1384 int
1385 ofproto_delete(const char *name, const char *type)
1386 {
1387     const struct ofproto_class *class = ofproto_class_find__(type);
1388     return (!class ? EAFNOSUPPORT
1389             : !class->del ? EACCES
1390             : class->del(type, name));
1391 }
1392
1393 static void
1394 process_port_change(struct ofproto *ofproto, int error, char *devname)
1395 {
1396     if (error == ENOBUFS) {
1397         reinit_ports(ofproto);
1398     } else if (!error) {
1399         update_port(ofproto, devname);
1400         free(devname);
1401     }
1402 }
1403
1404 int
1405 ofproto_type_run(const char *datapath_type)
1406 {
1407     const struct ofproto_class *class;
1408     int error;
1409
1410     datapath_type = ofproto_normalize_type(datapath_type);
1411     class = ofproto_class_find__(datapath_type);
1412
1413     error = class->type_run ? class->type_run(datapath_type) : 0;
1414     if (error && error != EAGAIN) {
1415         VLOG_ERR_RL(&rl, "%s: type_run failed (%s)",
1416                     datapath_type, ovs_strerror(error));
1417     }
1418     return error;
1419 }
1420
1421 void
1422 ofproto_type_wait(const char *datapath_type)
1423 {
1424     const struct ofproto_class *class;
1425
1426     datapath_type = ofproto_normalize_type(datapath_type);
1427     class = ofproto_class_find__(datapath_type);
1428
1429     if (class->type_wait) {
1430         class->type_wait(datapath_type);
1431     }
1432 }
1433
1434 static bool
1435 any_pending_ops(const struct ofproto *p)
1436     OVS_EXCLUDED(ofproto_mutex)
1437 {
1438     bool b;
1439
1440     ovs_mutex_lock(&ofproto_mutex);
1441     b = !list_is_empty(&p->pending);
1442     ovs_mutex_unlock(&ofproto_mutex);
1443
1444     return b;
1445 }
1446
1447 int
1448 ofproto_run(struct ofproto *p)
1449 {
1450     int error;
1451     uint64_t new_seq;
1452
1453     error = p->ofproto_class->run(p);
1454     if (error && error != EAGAIN) {
1455         VLOG_ERR_RL(&rl, "%s: run failed (%s)", p->name, ovs_strerror(error));
1456     }
1457
1458     run_rule_executes(p);
1459
1460     /* Restore the eviction group heap invariant occasionally. */
1461     if (p->eviction_group_timer < time_msec()) {
1462         size_t i;
1463
1464         p->eviction_group_timer = time_msec() + 1000;
1465
1466         for (i = 0; i < p->n_tables; i++) {
1467             struct oftable *table = &p->tables[i];
1468             struct eviction_group *evg;
1469             struct cls_cursor cursor;
1470             struct rule *rule;
1471
1472             if (!table->eviction_fields) {
1473                 continue;
1474             }
1475
1476             ovs_mutex_lock(&ofproto_mutex);
1477             fat_rwlock_rdlock(&table->cls.rwlock);
1478             cls_cursor_init(&cursor, &table->cls, NULL);
1479             CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
1480                 if (rule->idle_timeout || rule->hard_timeout) {
1481                     if (!rule->eviction_group) {
1482                         eviction_group_add_rule(rule);
1483                     } else {
1484                         heap_raw_change(&rule->evg_node,
1485                                         rule_eviction_priority(p, rule));
1486                     }
1487                 }
1488             }
1489             fat_rwlock_unlock(&table->cls.rwlock);
1490
1491             HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
1492                 heap_rebuild(&evg->rules);
1493             }
1494             ovs_mutex_unlock(&ofproto_mutex);
1495         }
1496     }
1497
1498     if (p->ofproto_class->port_poll) {
1499         char *devname;
1500
1501         while ((error = p->ofproto_class->port_poll(p, &devname)) != EAGAIN) {
1502             process_port_change(p, error, devname);
1503         }
1504     }
1505
1506     new_seq = seq_read(connectivity_seq_get());
1507     if (new_seq != p->change_seq) {
1508         struct sset devnames;
1509         const char *devname;
1510         struct ofport *ofport;
1511
1512         /* Update OpenFlow port status for any port whose netdev has changed.
1513          *
1514          * Refreshing a given 'ofport' can cause an arbitrary ofport to be
1515          * destroyed, so it's not safe to update ports directly from the
1516          * HMAP_FOR_EACH loop, or even to use HMAP_FOR_EACH_SAFE.  Instead, we
1517          * need this two-phase approach. */
1518         sset_init(&devnames);
1519         HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1520             uint64_t port_change_seq;
1521
1522             port_change_seq = netdev_get_change_seq(ofport->netdev);
1523             if (ofport->change_seq != port_change_seq) {
1524                 ofport->change_seq = port_change_seq;
1525                 sset_add(&devnames, netdev_get_name(ofport->netdev));
1526             }
1527         }
1528         SSET_FOR_EACH (devname, &devnames) {
1529             update_port(p, devname);
1530         }
1531         sset_destroy(&devnames);
1532
1533         p->change_seq = new_seq;
1534     }
1535
1536     switch (p->state) {
1537     case S_OPENFLOW:
1538         connmgr_run(p->connmgr, handle_openflow);
1539         break;
1540
1541     case S_EVICT:
1542         connmgr_run(p->connmgr, NULL);
1543         ofproto_evict(p);
1544         if (!any_pending_ops(p)) {
1545             p->state = S_OPENFLOW;
1546         }
1547         break;
1548
1549     case S_FLUSH:
1550         connmgr_run(p->connmgr, NULL);
1551         ofproto_flush__(p);
1552         if (!any_pending_ops(p)) {
1553             connmgr_flushed(p->connmgr);
1554             p->state = S_OPENFLOW;
1555         }
1556         break;
1557
1558     default:
1559         OVS_NOT_REACHED();
1560     }
1561
1562     if (time_msec() >= p->next_op_report) {
1563         long long int ago = (time_msec() - p->first_op) / 1000;
1564         long long int interval = (p->last_op - p->first_op) / 1000;
1565         struct ds s;
1566
1567         ds_init(&s);
1568         ds_put_format(&s, "%d flow_mods ",
1569                       p->n_add + p->n_delete + p->n_modify);
1570         if (interval == ago) {
1571             ds_put_format(&s, "in the last %lld s", ago);
1572         } else if (interval) {
1573             ds_put_format(&s, "in the %lld s starting %lld s ago",
1574                           interval, ago);
1575         } else {
1576             ds_put_format(&s, "%lld s ago", ago);
1577         }
1578
1579         ds_put_cstr(&s, " (");
1580         if (p->n_add) {
1581             ds_put_format(&s, "%d adds, ", p->n_add);
1582         }
1583         if (p->n_delete) {
1584             ds_put_format(&s, "%d deletes, ", p->n_delete);
1585         }
1586         if (p->n_modify) {
1587             ds_put_format(&s, "%d modifications, ", p->n_modify);
1588         }
1589         s.length -= 2;
1590         ds_put_char(&s, ')');
1591
1592         VLOG_INFO("%s: %s", p->name, ds_cstr(&s));
1593         ds_destroy(&s);
1594
1595         p->n_add = p->n_delete = p->n_modify = 0;
1596         p->next_op_report = LLONG_MAX;
1597     }
1598
1599     return error;
1600 }
1601
1602 void
1603 ofproto_wait(struct ofproto *p)
1604 {
1605     p->ofproto_class->wait(p);
1606     if (p->ofproto_class->port_poll_wait) {
1607         p->ofproto_class->port_poll_wait(p);
1608     }
1609     seq_wait(connectivity_seq_get(), p->change_seq);
1610
1611     switch (p->state) {
1612     case S_OPENFLOW:
1613         connmgr_wait(p->connmgr, true);
1614         break;
1615
1616     case S_EVICT:
1617     case S_FLUSH:
1618         connmgr_wait(p->connmgr, false);
1619         if (!any_pending_ops(p)) {
1620             poll_immediate_wake();
1621         }
1622         break;
1623     }
1624 }
1625
1626 bool
1627 ofproto_is_alive(const struct ofproto *p)
1628 {
1629     return connmgr_has_controllers(p->connmgr);
1630 }
1631
1632 /* Adds some memory usage statistics for 'ofproto' into 'usage', for use with
1633  * memory_report(). */
1634 void
1635 ofproto_get_memory_usage(const struct ofproto *ofproto, struct simap *usage)
1636 {
1637     const struct oftable *table;
1638     unsigned int n_rules;
1639
1640     simap_increase(usage, "ports", hmap_count(&ofproto->ports));
1641
1642     ovs_mutex_lock(&ofproto_mutex);
1643     simap_increase(usage, "ops",
1644                    ofproto->n_pending + hmap_count(&ofproto->deletions));
1645     ovs_mutex_unlock(&ofproto_mutex);
1646
1647     n_rules = 0;
1648     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1649         fat_rwlock_rdlock(&table->cls.rwlock);
1650         n_rules += classifier_count(&table->cls);
1651         fat_rwlock_unlock(&table->cls.rwlock);
1652     }
1653     simap_increase(usage, "rules", n_rules);
1654
1655     if (ofproto->ofproto_class->get_memory_usage) {
1656         ofproto->ofproto_class->get_memory_usage(ofproto, usage);
1657     }
1658
1659     connmgr_get_memory_usage(ofproto->connmgr, usage);
1660 }
1661
1662 void
1663 ofproto_type_get_memory_usage(const char *datapath_type, struct simap *usage)
1664 {
1665     const struct ofproto_class *class;
1666
1667     datapath_type = ofproto_normalize_type(datapath_type);
1668     class = ofproto_class_find__(datapath_type);
1669
1670     if (class && class->type_get_memory_usage) {
1671         class->type_get_memory_usage(datapath_type, usage);
1672     }
1673 }
1674
1675 void
1676 ofproto_get_ofproto_controller_info(const struct ofproto *ofproto,
1677                                     struct shash *info)
1678 {
1679     connmgr_get_controller_info(ofproto->connmgr, info);
1680 }
1681
1682 void
1683 ofproto_free_ofproto_controller_info(struct shash *info)
1684 {
1685     connmgr_free_controller_info(info);
1686 }
1687
1688 /* Makes a deep copy of 'old' into 'port'. */
1689 void
1690 ofproto_port_clone(struct ofproto_port *port, const struct ofproto_port *old)
1691 {
1692     port->name = xstrdup(old->name);
1693     port->type = xstrdup(old->type);
1694     port->ofp_port = old->ofp_port;
1695 }
1696
1697 /* Frees memory allocated to members of 'ofproto_port'.
1698  *
1699  * Do not call this function on an ofproto_port obtained from
1700  * ofproto_port_dump_next(): that function retains ownership of the data in the
1701  * ofproto_port. */
1702 void
1703 ofproto_port_destroy(struct ofproto_port *ofproto_port)
1704 {
1705     free(ofproto_port->name);
1706     free(ofproto_port->type);
1707 }
1708
1709 /* Initializes 'dump' to begin dumping the ports in an ofproto.
1710  *
1711  * This function provides no status indication.  An error status for the entire
1712  * dump operation is provided when it is completed by calling
1713  * ofproto_port_dump_done().
1714  */
1715 void
1716 ofproto_port_dump_start(struct ofproto_port_dump *dump,
1717                         const struct ofproto *ofproto)
1718 {
1719     dump->ofproto = ofproto;
1720     dump->error = ofproto->ofproto_class->port_dump_start(ofproto,
1721                                                           &dump->state);
1722 }
1723
1724 /* Attempts to retrieve another port from 'dump', which must have been created
1725  * with ofproto_port_dump_start().  On success, stores a new ofproto_port into
1726  * 'port' and returns true.  On failure, returns false.
1727  *
1728  * Failure might indicate an actual error or merely that the last port has been
1729  * dumped.  An error status for the entire dump operation is provided when it
1730  * is completed by calling ofproto_port_dump_done().
1731  *
1732  * The ofproto owns the data stored in 'port'.  It will remain valid until at
1733  * least the next time 'dump' is passed to ofproto_port_dump_next() or
1734  * ofproto_port_dump_done(). */
1735 bool
1736 ofproto_port_dump_next(struct ofproto_port_dump *dump,
1737                        struct ofproto_port *port)
1738 {
1739     const struct ofproto *ofproto = dump->ofproto;
1740
1741     if (dump->error) {
1742         return false;
1743     }
1744
1745     dump->error = ofproto->ofproto_class->port_dump_next(ofproto, dump->state,
1746                                                          port);
1747     if (dump->error) {
1748         ofproto->ofproto_class->port_dump_done(ofproto, dump->state);
1749         return false;
1750     }
1751     return true;
1752 }
1753
1754 /* Completes port table dump operation 'dump', which must have been created
1755  * with ofproto_port_dump_start().  Returns 0 if the dump operation was
1756  * error-free, otherwise a positive errno value describing the problem. */
1757 int
1758 ofproto_port_dump_done(struct ofproto_port_dump *dump)
1759 {
1760     const struct ofproto *ofproto = dump->ofproto;
1761     if (!dump->error) {
1762         dump->error = ofproto->ofproto_class->port_dump_done(ofproto,
1763                                                              dump->state);
1764     }
1765     return dump->error == EOF ? 0 : dump->error;
1766 }
1767
1768 /* Returns the type to pass to netdev_open() when a datapath of type
1769  * 'datapath_type' has a port of type 'port_type', for a few special
1770  * cases when a netdev type differs from a port type.  For example, when
1771  * using the userspace datapath, a port of type "internal" needs to be
1772  * opened as "tap".
1773  *
1774  * Returns either 'type' itself or a string literal, which must not be
1775  * freed. */
1776 const char *
1777 ofproto_port_open_type(const char *datapath_type, const char *port_type)
1778 {
1779     const struct ofproto_class *class;
1780
1781     datapath_type = ofproto_normalize_type(datapath_type);
1782     class = ofproto_class_find__(datapath_type);
1783     if (!class) {
1784         return port_type;
1785     }
1786
1787     return (class->port_open_type
1788             ? class->port_open_type(datapath_type, port_type)
1789             : port_type);
1790 }
1791
1792 /* Attempts to add 'netdev' as a port on 'ofproto'.  If 'ofp_portp' is
1793  * non-null and '*ofp_portp' is not OFPP_NONE, attempts to use that as
1794  * the port's OpenFlow port number.
1795  *
1796  * If successful, returns 0 and sets '*ofp_portp' to the new port's
1797  * OpenFlow port number (if 'ofp_portp' is non-null).  On failure,
1798  * returns a positive errno value and sets '*ofp_portp' to OFPP_NONE (if
1799  * 'ofp_portp' is non-null). */
1800 int
1801 ofproto_port_add(struct ofproto *ofproto, struct netdev *netdev,
1802                  ofp_port_t *ofp_portp)
1803 {
1804     ofp_port_t ofp_port = ofp_portp ? *ofp_portp : OFPP_NONE;
1805     int error;
1806
1807     error = ofproto->ofproto_class->port_add(ofproto, netdev);
1808     if (!error) {
1809         const char *netdev_name = netdev_get_name(netdev);
1810
1811         simap_put(&ofproto->ofp_requests, netdev_name,
1812                   ofp_to_u16(ofp_port));
1813         update_port(ofproto, netdev_name);
1814     }
1815     if (ofp_portp) {
1816         *ofp_portp = OFPP_NONE;
1817         if (!error) {
1818             struct ofproto_port ofproto_port;
1819
1820             error = ofproto_port_query_by_name(ofproto,
1821                                                netdev_get_name(netdev),
1822                                                &ofproto_port);
1823             if (!error) {
1824                 *ofp_portp = ofproto_port.ofp_port;
1825                 ofproto_port_destroy(&ofproto_port);
1826             }
1827         }
1828     }
1829     return error;
1830 }
1831
1832 /* Looks up a port named 'devname' in 'ofproto'.  On success, returns 0 and
1833  * initializes '*port' appropriately; on failure, returns a positive errno
1834  * value.
1835  *
1836  * The caller owns the data in 'ofproto_port' and must free it with
1837  * ofproto_port_destroy() when it is no longer needed. */
1838 int
1839 ofproto_port_query_by_name(const struct ofproto *ofproto, const char *devname,
1840                            struct ofproto_port *port)
1841 {
1842     int error;
1843
1844     error = ofproto->ofproto_class->port_query_by_name(ofproto, devname, port);
1845     if (error) {
1846         memset(port, 0, sizeof *port);
1847     }
1848     return error;
1849 }
1850
1851 /* Deletes port number 'ofp_port' from the datapath for 'ofproto'.
1852  * Returns 0 if successful, otherwise a positive errno. */
1853 int
1854 ofproto_port_del(struct ofproto *ofproto, ofp_port_t ofp_port)
1855 {
1856     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1857     const char *name = ofport ? netdev_get_name(ofport->netdev) : "<unknown>";
1858     struct simap_node *ofp_request_node;
1859     int error;
1860
1861     ofp_request_node = simap_find(&ofproto->ofp_requests, name);
1862     if (ofp_request_node) {
1863         simap_delete(&ofproto->ofp_requests, ofp_request_node);
1864     }
1865
1866     error = ofproto->ofproto_class->port_del(ofproto, ofp_port);
1867     if (!error && ofport) {
1868         /* 'name' is the netdev's name and update_port() is going to close the
1869          * netdev.  Just in case update_port() refers to 'name' after it
1870          * destroys 'ofport', make a copy of it around the update_port()
1871          * call. */
1872         char *devname = xstrdup(name);
1873         update_port(ofproto, devname);
1874         free(devname);
1875     }
1876     return error;
1877 }
1878
1879 static void
1880 flow_mod_init(struct ofputil_flow_mod *fm,
1881               const struct match *match, unsigned int priority,
1882               const struct ofpact *ofpacts, size_t ofpacts_len,
1883               enum ofp_flow_mod_command command)
1884 {
1885     memset(fm, 0, sizeof *fm);
1886     fm->match = *match;
1887     fm->priority = priority;
1888     fm->cookie = 0;
1889     fm->new_cookie = 0;
1890     fm->modify_cookie = false;
1891     fm->table_id = 0;
1892     fm->command = command;
1893     fm->idle_timeout = 0;
1894     fm->hard_timeout = 0;
1895     fm->buffer_id = UINT32_MAX;
1896     fm->out_port = OFPP_ANY;
1897     fm->out_group = OFPG_ANY;
1898     fm->flags = 0;
1899     fm->ofpacts = CONST_CAST(struct ofpact *, ofpacts);
1900     fm->ofpacts_len = ofpacts_len;
1901 }
1902
1903 static int
1904 simple_flow_mod(struct ofproto *ofproto,
1905                 const struct match *match, unsigned int priority,
1906                 const struct ofpact *ofpacts, size_t ofpacts_len,
1907                 enum ofp_flow_mod_command command)
1908 {
1909     struct ofputil_flow_mod fm;
1910
1911     flow_mod_init(&fm, match, priority, ofpacts, ofpacts_len, command);
1912
1913     return handle_flow_mod__(ofproto, NULL, &fm, NULL);
1914 }
1915
1916 /* Adds a flow to OpenFlow flow table 0 in 'p' that matches 'cls_rule' and
1917  * performs the 'n_actions' actions in 'actions'.  The new flow will not
1918  * timeout.
1919  *
1920  * If cls_rule->priority is in the range of priorities supported by OpenFlow
1921  * (0...65535, inclusive) then the flow will be visible to OpenFlow
1922  * controllers; otherwise, it will be hidden.
1923  *
1924  * The caller retains ownership of 'cls_rule' and 'ofpacts'.
1925  *
1926  * This is a helper function for in-band control and fail-open. */
1927 void
1928 ofproto_add_flow(struct ofproto *ofproto, const struct match *match,
1929                  unsigned int priority,
1930                  const struct ofpact *ofpacts, size_t ofpacts_len)
1931     OVS_EXCLUDED(ofproto_mutex)
1932 {
1933     const struct rule *rule;
1934     bool must_add;
1935
1936     /* First do a cheap check whether the rule we're looking for already exists
1937      * with the actions that we want.  If it does, then we're done. */
1938     fat_rwlock_rdlock(&ofproto->tables[0].cls.rwlock);
1939     rule = rule_from_cls_rule(classifier_find_match_exactly(
1940                                   &ofproto->tables[0].cls, match, priority));
1941     if (rule) {
1942         struct rule_actions *actions = rule_get_actions(rule);
1943         must_add = !ofpacts_equal(actions->ofpacts, actions->ofpacts_len,
1944                                   ofpacts, ofpacts_len);
1945     } else {
1946         must_add = true;
1947     }
1948     fat_rwlock_unlock(&ofproto->tables[0].cls.rwlock);
1949
1950     /* If there's no such rule or the rule doesn't have the actions we want,
1951      * fall back to a executing a full flow mod.  We can't optimize this at
1952      * all because we didn't take enough locks above to ensure that the flow
1953      * table didn't already change beneath us.  */
1954     if (must_add) {
1955         simple_flow_mod(ofproto, match, priority, ofpacts, ofpacts_len,
1956                         OFPFC_MODIFY_STRICT);
1957     }
1958 }
1959
1960 /* Executes the flow modification specified in 'fm'.  Returns 0 on success, an
1961  * OFPERR_* OpenFlow error code on failure, or OFPROTO_POSTPONE if the
1962  * operation cannot be initiated now but may be retried later.
1963  *
1964  * This is a helper function for in-band control and fail-open and the "learn"
1965  * action. */
1966 int
1967 ofproto_flow_mod(struct ofproto *ofproto, struct ofputil_flow_mod *fm)
1968     OVS_EXCLUDED(ofproto_mutex)
1969 {
1970     /* Optimize for the most common case of a repeated learn action.
1971      * If an identical flow already exists we only need to update its
1972      * 'modified' time. */
1973     if (fm->command == OFPFC_MODIFY_STRICT && fm->table_id != OFPTT_ALL
1974         && !(fm->flags & OFPUTIL_FF_RESET_COUNTS)) {
1975         struct oftable *table = &ofproto->tables[fm->table_id];
1976         struct cls_rule match_rule;
1977         struct rule *rule;
1978         bool done = false;
1979
1980         cls_rule_init(&match_rule, &fm->match, fm->priority);
1981         fat_rwlock_rdlock(&table->cls.rwlock);
1982         rule = rule_from_cls_rule(classifier_find_rule_exactly(&table->cls,
1983                                                                &match_rule));
1984         if (rule) {
1985             /* Reading many of the rule fields and writing on 'modified'
1986              * requires the rule->mutex.  Also, rule->actions may change
1987              * if rule->mutex is not held. */
1988             const struct rule_actions *actions;
1989
1990             ovs_mutex_lock(&rule->mutex);
1991             actions = rule_get_actions(rule);
1992             if (rule->idle_timeout == fm->idle_timeout
1993                 && rule->hard_timeout == fm->hard_timeout
1994                 && rule->flags == (fm->flags & OFPUTIL_FF_STATE)
1995                 && (!fm->modify_cookie || (fm->new_cookie == rule->flow_cookie))
1996                 && ofpacts_equal(fm->ofpacts, fm->ofpacts_len,
1997                                  actions->ofpacts, actions->ofpacts_len)) {
1998                 /* Rule already exists and need not change, only update the
1999                    modified timestamp. */
2000                 rule->modified = time_msec();
2001                 done = true;
2002             }
2003             ovs_mutex_unlock(&rule->mutex);
2004         }
2005         fat_rwlock_unlock(&table->cls.rwlock);
2006
2007         if (done) {
2008             return 0;
2009         }
2010     }
2011
2012     return handle_flow_mod__(ofproto, NULL, fm, NULL);
2013 }
2014
2015 /* Resets the modified time for 'rule' or an equivalent rule. If 'rule' is not
2016  * in the classifier, but an equivalent rule is, unref 'rule' and ref the new
2017  * rule. Otherwise if 'rule' is no longer installed in the classifier,
2018  * reinstall it.
2019  *
2020  * Returns the rule whose modified time has been reset. */
2021 struct rule *
2022 ofproto_refresh_rule(struct rule *rule)
2023 {
2024     const struct oftable *table = &rule->ofproto->tables[rule->table_id];
2025     const struct cls_rule *cr = &rule->cr;
2026     struct rule *r;
2027
2028     /* do_add_flow() requires that the rule is not installed. We lock the
2029      * ofproto_mutex here so that another thread cannot add the flow before
2030      * we get a chance to add it.*/
2031     ovs_mutex_lock(&ofproto_mutex);
2032
2033     fat_rwlock_rdlock(&table->cls.rwlock);
2034     r = rule_from_cls_rule(classifier_find_rule_exactly(&table->cls, cr));
2035     if (r != rule) {
2036         ofproto_rule_ref(r);
2037     }
2038     fat_rwlock_unlock(&table->cls.rwlock);
2039
2040     if (!r) {
2041         do_add_flow(rule->ofproto, NULL, NULL, 0, rule);
2042     } else if  (r != rule) {
2043         ofproto_rule_unref(rule);
2044         rule = r;
2045     }
2046     ovs_mutex_unlock(&ofproto_mutex);
2047
2048     /* Refresh the modified time for the rule. */
2049     ovs_mutex_lock(&rule->mutex);
2050     rule->modified = MAX(rule->modified, time_msec());
2051     ovs_mutex_unlock(&rule->mutex);
2052
2053     return rule;
2054 }
2055
2056 /* Searches for a rule with matching criteria exactly equal to 'target' in
2057  * ofproto's table 0 and, if it finds one, deletes it.
2058  *
2059  * This is a helper function for in-band control and fail-open. */
2060 bool
2061 ofproto_delete_flow(struct ofproto *ofproto,
2062                     const struct match *target, unsigned int priority)
2063     OVS_EXCLUDED(ofproto_mutex)
2064 {
2065     struct classifier *cls = &ofproto->tables[0].cls;
2066     struct rule *rule;
2067
2068     /* First do a cheap check whether the rule we're looking for has already
2069      * been deleted.  If so, then we're done. */
2070     fat_rwlock_rdlock(&cls->rwlock);
2071     rule = rule_from_cls_rule(classifier_find_match_exactly(cls, target,
2072                                                             priority));
2073     fat_rwlock_unlock(&cls->rwlock);
2074     if (!rule) {
2075         return true;
2076     }
2077
2078     /* Fall back to a executing a full flow mod.  We can't optimize this at all
2079      * because we didn't take enough locks above to ensure that the flow table
2080      * didn't already change beneath us.  */
2081     return simple_flow_mod(ofproto, target, priority, NULL, 0,
2082                            OFPFC_DELETE_STRICT) != OFPROTO_POSTPONE;
2083 }
2084
2085 /* Starts the process of deleting all of the flows from all of ofproto's flow
2086  * tables and then reintroducing the flows required by in-band control and
2087  * fail-open.  The process will complete in a later call to ofproto_run(). */
2088 void
2089 ofproto_flush_flows(struct ofproto *ofproto)
2090 {
2091     COVERAGE_INC(ofproto_flush);
2092     ofproto->state = S_FLUSH;
2093 }
2094 \f
2095 static void
2096 reinit_ports(struct ofproto *p)
2097 {
2098     struct ofproto_port_dump dump;
2099     struct sset devnames;
2100     struct ofport *ofport;
2101     struct ofproto_port ofproto_port;
2102     const char *devname;
2103
2104     COVERAGE_INC(ofproto_reinit_ports);
2105
2106     sset_init(&devnames);
2107     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2108         sset_add(&devnames, netdev_get_name(ofport->netdev));
2109     }
2110     OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
2111         sset_add(&devnames, ofproto_port.name);
2112     }
2113
2114     SSET_FOR_EACH (devname, &devnames) {
2115         update_port(p, devname);
2116     }
2117     sset_destroy(&devnames);
2118 }
2119
2120 static ofp_port_t
2121 alloc_ofp_port(struct ofproto *ofproto, const char *netdev_name)
2122 {
2123     uint16_t port_idx;
2124
2125     port_idx = simap_get(&ofproto->ofp_requests, netdev_name);
2126     port_idx = port_idx ? port_idx : UINT16_MAX;
2127
2128     if (port_idx >= ofproto->max_ports
2129         || ofport_get_usage(ofproto, u16_to_ofp(port_idx)) == LLONG_MAX) {
2130         uint16_t lru_ofport = 0, end_port_no = ofproto->alloc_port_no;
2131         long long int last_used_at, lru = LLONG_MAX;
2132
2133         /* Search for a free OpenFlow port number.  We try not to
2134          * immediately reuse them to prevent problems due to old
2135          * flows.
2136          *
2137          * We limit the automatically assigned port numbers to the lower half
2138          * of the port range, to reserve the upper half for assignment by
2139          * controllers. */
2140         for (;;) {
2141             if (++ofproto->alloc_port_no >= MIN(ofproto->max_ports, 32768)) {
2142                 ofproto->alloc_port_no = 1;
2143             }
2144             last_used_at = ofport_get_usage(ofproto,
2145                                          u16_to_ofp(ofproto->alloc_port_no));
2146             if (!last_used_at) {
2147                 port_idx = ofproto->alloc_port_no;
2148                 break;
2149             } else if ( last_used_at < time_msec() - 60*60*1000) {
2150                 /* If the port with ofport 'ofproto->alloc_port_no' was deleted
2151                  * more than an hour ago, consider it usable. */
2152                 ofport_remove_usage(ofproto,
2153                     u16_to_ofp(ofproto->alloc_port_no));
2154                 port_idx = ofproto->alloc_port_no;
2155                 break;
2156             } else if (last_used_at < lru) {
2157                 lru = last_used_at;
2158                 lru_ofport = ofproto->alloc_port_no;
2159             }
2160
2161             if (ofproto->alloc_port_no == end_port_no) {
2162                 if (lru_ofport) {
2163                     port_idx = lru_ofport;
2164                     break;
2165                 }
2166                 return OFPP_NONE;
2167             }
2168         }
2169     }
2170     ofport_set_usage(ofproto, u16_to_ofp(port_idx), LLONG_MAX);
2171     return u16_to_ofp(port_idx);
2172 }
2173
2174 static void
2175 dealloc_ofp_port(struct ofproto *ofproto, ofp_port_t ofp_port)
2176 {
2177     if (ofp_to_u16(ofp_port) < ofproto->max_ports) {
2178         ofport_set_usage(ofproto, ofp_port, time_msec());
2179     }
2180 }
2181
2182 /* Opens and returns a netdev for 'ofproto_port' in 'ofproto', or a null
2183  * pointer if the netdev cannot be opened.  On success, also fills in
2184  * 'opp'.  */
2185 static struct netdev *
2186 ofport_open(struct ofproto *ofproto,
2187             struct ofproto_port *ofproto_port,
2188             struct ofputil_phy_port *pp)
2189 {
2190     enum netdev_flags flags;
2191     struct netdev *netdev;
2192     int error;
2193
2194     error = netdev_open(ofproto_port->name, ofproto_port->type, &netdev);
2195     if (error) {
2196         VLOG_WARN_RL(&rl, "%s: ignoring port %s (%"PRIu16") because netdev %s "
2197                      "cannot be opened (%s)",
2198                      ofproto->name,
2199                      ofproto_port->name, ofproto_port->ofp_port,
2200                      ofproto_port->name, ovs_strerror(error));
2201         return NULL;
2202     }
2203
2204     if (ofproto_port->ofp_port == OFPP_NONE) {
2205         if (!strcmp(ofproto->name, ofproto_port->name)) {
2206             ofproto_port->ofp_port = OFPP_LOCAL;
2207         } else {
2208             ofproto_port->ofp_port = alloc_ofp_port(ofproto,
2209                                                     ofproto_port->name);
2210         }
2211     }
2212     pp->port_no = ofproto_port->ofp_port;
2213     netdev_get_etheraddr(netdev, pp->hw_addr);
2214     ovs_strlcpy(pp->name, ofproto_port->name, sizeof pp->name);
2215     netdev_get_flags(netdev, &flags);
2216     pp->config = flags & NETDEV_UP ? 0 : OFPUTIL_PC_PORT_DOWN;
2217     pp->state = netdev_get_carrier(netdev) ? 0 : OFPUTIL_PS_LINK_DOWN;
2218     netdev_get_features(netdev, &pp->curr, &pp->advertised,
2219                         &pp->supported, &pp->peer);
2220     pp->curr_speed = netdev_features_to_bps(pp->curr, 0) / 1000;
2221     pp->max_speed = netdev_features_to_bps(pp->supported, 0) / 1000;
2222
2223     return netdev;
2224 }
2225
2226 /* Returns true if most fields of 'a' and 'b' are equal.  Differences in name,
2227  * port number, and 'config' bits other than OFPUTIL_PS_LINK_DOWN are
2228  * disregarded. */
2229 static bool
2230 ofport_equal(const struct ofputil_phy_port *a,
2231              const struct ofputil_phy_port *b)
2232 {
2233     return (eth_addr_equals(a->hw_addr, b->hw_addr)
2234             && a->state == b->state
2235             && !((a->config ^ b->config) & OFPUTIL_PC_PORT_DOWN)
2236             && a->curr == b->curr
2237             && a->advertised == b->advertised
2238             && a->supported == b->supported
2239             && a->peer == b->peer
2240             && a->curr_speed == b->curr_speed
2241             && a->max_speed == b->max_speed);
2242 }
2243
2244 /* Adds an ofport to 'p' initialized based on the given 'netdev' and 'opp'.
2245  * The caller must ensure that 'p' does not have a conflicting ofport (that is,
2246  * one with the same name or port number). */
2247 static void
2248 ofport_install(struct ofproto *p,
2249                struct netdev *netdev, const struct ofputil_phy_port *pp)
2250 {
2251     const char *netdev_name = netdev_get_name(netdev);
2252     struct ofport *ofport;
2253     int error;
2254
2255     /* Create ofport. */
2256     ofport = p->ofproto_class->port_alloc();
2257     if (!ofport) {
2258         error = ENOMEM;
2259         goto error;
2260     }
2261     ofport->ofproto = p;
2262     ofport->netdev = netdev;
2263     ofport->change_seq = netdev_get_change_seq(netdev);
2264     ofport->pp = *pp;
2265     ofport->ofp_port = pp->port_no;
2266     ofport->created = time_msec();
2267
2268     /* Add port to 'p'. */
2269     hmap_insert(&p->ports, &ofport->hmap_node,
2270                 hash_ofp_port(ofport->ofp_port));
2271     shash_add(&p->port_by_name, netdev_name, ofport);
2272
2273     update_mtu(p, ofport);
2274
2275     /* Let the ofproto_class initialize its private data. */
2276     error = p->ofproto_class->port_construct(ofport);
2277     if (error) {
2278         goto error;
2279     }
2280     connmgr_send_port_status(p->connmgr, NULL, pp, OFPPR_ADD);
2281     return;
2282
2283 error:
2284     VLOG_WARN_RL(&rl, "%s: could not add port %s (%s)",
2285                  p->name, netdev_name, ovs_strerror(error));
2286     if (ofport) {
2287         ofport_destroy__(ofport);
2288     } else {
2289         netdev_close(netdev);
2290     }
2291 }
2292
2293 /* Removes 'ofport' from 'p' and destroys it. */
2294 static void
2295 ofport_remove(struct ofport *ofport)
2296 {
2297     connmgr_send_port_status(ofport->ofproto->connmgr, NULL, &ofport->pp,
2298                              OFPPR_DELETE);
2299     ofport_destroy(ofport);
2300 }
2301
2302 /* If 'ofproto' contains an ofport named 'name', removes it from 'ofproto' and
2303  * destroys it. */
2304 static void
2305 ofport_remove_with_name(struct ofproto *ofproto, const char *name)
2306 {
2307     struct ofport *port = shash_find_data(&ofproto->port_by_name, name);
2308     if (port) {
2309         ofport_remove(port);
2310     }
2311 }
2312
2313 /* Updates 'port' with new 'pp' description.
2314  *
2315  * Does not handle a name or port number change.  The caller must implement
2316  * such a change as a delete followed by an add.  */
2317 static void
2318 ofport_modified(struct ofport *port, struct ofputil_phy_port *pp)
2319 {
2320     memcpy(port->pp.hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2321     port->pp.config = ((port->pp.config & ~OFPUTIL_PC_PORT_DOWN)
2322                         | (pp->config & OFPUTIL_PC_PORT_DOWN));
2323     port->pp.state = ((port->pp.state & ~OFPUTIL_PS_LINK_DOWN)
2324                       | (pp->state & OFPUTIL_PS_LINK_DOWN));
2325     port->pp.curr = pp->curr;
2326     port->pp.advertised = pp->advertised;
2327     port->pp.supported = pp->supported;
2328     port->pp.peer = pp->peer;
2329     port->pp.curr_speed = pp->curr_speed;
2330     port->pp.max_speed = pp->max_speed;
2331
2332     connmgr_send_port_status(port->ofproto->connmgr, NULL,
2333                              &port->pp, OFPPR_MODIFY);
2334 }
2335
2336 /* Update OpenFlow 'state' in 'port' and notify controller. */
2337 void
2338 ofproto_port_set_state(struct ofport *port, enum ofputil_port_state state)
2339 {
2340     if (port->pp.state != state) {
2341         port->pp.state = state;
2342         connmgr_send_port_status(port->ofproto->connmgr, NULL,
2343                                  &port->pp, OFPPR_MODIFY);
2344     }
2345 }
2346
2347 void
2348 ofproto_port_unregister(struct ofproto *ofproto, ofp_port_t ofp_port)
2349 {
2350     struct ofport *port = ofproto_get_port(ofproto, ofp_port);
2351     if (port) {
2352         if (port->ofproto->ofproto_class->set_realdev) {
2353             port->ofproto->ofproto_class->set_realdev(port, 0, 0);
2354         }
2355         if (port->ofproto->ofproto_class->set_stp_port) {
2356             port->ofproto->ofproto_class->set_stp_port(port, NULL);
2357         }
2358         if (port->ofproto->ofproto_class->set_cfm) {
2359             port->ofproto->ofproto_class->set_cfm(port, NULL);
2360         }
2361         if (port->ofproto->ofproto_class->bundle_remove) {
2362             port->ofproto->ofproto_class->bundle_remove(port);
2363         }
2364     }
2365 }
2366
2367 static void
2368 ofport_destroy__(struct ofport *port)
2369 {
2370     struct ofproto *ofproto = port->ofproto;
2371     const char *name = netdev_get_name(port->netdev);
2372
2373     hmap_remove(&ofproto->ports, &port->hmap_node);
2374     shash_delete(&ofproto->port_by_name,
2375                  shash_find(&ofproto->port_by_name, name));
2376
2377     netdev_close(port->netdev);
2378     ofproto->ofproto_class->port_dealloc(port);
2379 }
2380
2381 static void
2382 ofport_destroy(struct ofport *port)
2383 {
2384     if (port) {
2385         dealloc_ofp_port(port->ofproto, port->ofp_port);
2386         port->ofproto->ofproto_class->port_destruct(port);
2387         ofport_destroy__(port);
2388      }
2389 }
2390
2391 struct ofport *
2392 ofproto_get_port(const struct ofproto *ofproto, ofp_port_t ofp_port)
2393 {
2394     struct ofport *port;
2395
2396     HMAP_FOR_EACH_IN_BUCKET (port, hmap_node, hash_ofp_port(ofp_port),
2397                              &ofproto->ports) {
2398         if (port->ofp_port == ofp_port) {
2399             return port;
2400         }
2401     }
2402     return NULL;
2403 }
2404
2405 static long long int
2406 ofport_get_usage(const struct ofproto *ofproto, ofp_port_t ofp_port)
2407 {
2408     struct ofport_usage *usage;
2409
2410     HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2411                              &ofproto->ofport_usage) {
2412         if (usage->ofp_port == ofp_port) {
2413             return usage->last_used;
2414         }
2415     }
2416     return 0;
2417 }
2418
2419 static void
2420 ofport_set_usage(struct ofproto *ofproto, ofp_port_t ofp_port,
2421                  long long int last_used)
2422 {
2423     struct ofport_usage *usage;
2424     HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2425                              &ofproto->ofport_usage) {
2426         if (usage->ofp_port == ofp_port) {
2427             usage->last_used = last_used;
2428             return;
2429         }
2430     }
2431     ovs_assert(last_used == LLONG_MAX);
2432
2433     usage = xmalloc(sizeof *usage);
2434     usage->ofp_port = ofp_port;
2435     usage->last_used = last_used;
2436     hmap_insert(&ofproto->ofport_usage, &usage->hmap_node,
2437                 hash_ofp_port(ofp_port));
2438 }
2439
2440 static void
2441 ofport_remove_usage(struct ofproto *ofproto, ofp_port_t ofp_port)
2442 {
2443     struct ofport_usage *usage;
2444     HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2445                              &ofproto->ofport_usage) {
2446         if (usage->ofp_port == ofp_port) {
2447             hmap_remove(&ofproto->ofport_usage, &usage->hmap_node);
2448             free(usage);
2449             break;
2450         }
2451     }
2452 }
2453
2454 int
2455 ofproto_port_get_stats(const struct ofport *port, struct netdev_stats *stats)
2456 {
2457     struct ofproto *ofproto = port->ofproto;
2458     int error;
2459
2460     if (ofproto->ofproto_class->port_get_stats) {
2461         error = ofproto->ofproto_class->port_get_stats(port, stats);
2462     } else {
2463         error = EOPNOTSUPP;
2464     }
2465
2466     return error;
2467 }
2468
2469 static void
2470 update_port(struct ofproto *ofproto, const char *name)
2471 {
2472     struct ofproto_port ofproto_port;
2473     struct ofputil_phy_port pp;
2474     struct netdev *netdev;
2475     struct ofport *port;
2476
2477     COVERAGE_INC(ofproto_update_port);
2478
2479     /* Fetch 'name''s location and properties from the datapath. */
2480     netdev = (!ofproto_port_query_by_name(ofproto, name, &ofproto_port)
2481               ? ofport_open(ofproto, &ofproto_port, &pp)
2482               : NULL);
2483
2484     if (netdev) {
2485         port = ofproto_get_port(ofproto, ofproto_port.ofp_port);
2486         if (port && !strcmp(netdev_get_name(port->netdev), name)) {
2487             struct netdev *old_netdev = port->netdev;
2488
2489             /* 'name' hasn't changed location.  Any properties changed? */
2490             if (!ofport_equal(&port->pp, &pp)) {
2491                 ofport_modified(port, &pp);
2492             }
2493
2494             update_mtu(ofproto, port);
2495
2496             /* Install the newly opened netdev in case it has changed.
2497              * Don't close the old netdev yet in case port_modified has to
2498              * remove a retained reference to it.*/
2499             port->netdev = netdev;
2500             port->change_seq = netdev_get_change_seq(netdev);
2501
2502             if (port->ofproto->ofproto_class->port_modified) {
2503                 port->ofproto->ofproto_class->port_modified(port);
2504             }
2505
2506             netdev_close(old_netdev);
2507         } else {
2508             /* If 'port' is nonnull then its name differs from 'name' and thus
2509              * we should delete it.  If we think there's a port named 'name'
2510              * then its port number must be wrong now so delete it too. */
2511             if (port) {
2512                 ofport_remove(port);
2513             }
2514             ofport_remove_with_name(ofproto, name);
2515             ofport_install(ofproto, netdev, &pp);
2516         }
2517     } else {
2518         /* Any port named 'name' is gone now. */
2519         ofport_remove_with_name(ofproto, name);
2520     }
2521     ofproto_port_destroy(&ofproto_port);
2522 }
2523
2524 static int
2525 init_ports(struct ofproto *p)
2526 {
2527     struct ofproto_port_dump dump;
2528     struct ofproto_port ofproto_port;
2529     struct shash_node *node, *next;
2530
2531     OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
2532         const char *name = ofproto_port.name;
2533
2534         if (shash_find(&p->port_by_name, name)) {
2535             VLOG_WARN_RL(&rl, "%s: ignoring duplicate device %s in datapath",
2536                          p->name, name);
2537         } else {
2538             struct ofputil_phy_port pp;
2539             struct netdev *netdev;
2540
2541             /* Check if an OpenFlow port number had been requested. */
2542             node = shash_find(&init_ofp_ports, name);
2543             if (node) {
2544                 const struct iface_hint *iface_hint = node->data;
2545                 simap_put(&p->ofp_requests, name,
2546                           ofp_to_u16(iface_hint->ofp_port));
2547             }
2548
2549             netdev = ofport_open(p, &ofproto_port, &pp);
2550             if (netdev) {
2551                 ofport_install(p, netdev, &pp);
2552                 if (ofp_to_u16(ofproto_port.ofp_port) < p->max_ports) {
2553                     p->alloc_port_no = MAX(p->alloc_port_no,
2554                                            ofp_to_u16(ofproto_port.ofp_port));
2555                 }
2556             }
2557         }
2558     }
2559
2560     SHASH_FOR_EACH_SAFE(node, next, &init_ofp_ports) {
2561         struct iface_hint *iface_hint = node->data;
2562
2563         if (!strcmp(iface_hint->br_name, p->name)) {
2564             free(iface_hint->br_name);
2565             free(iface_hint->br_type);
2566             free(iface_hint);
2567             shash_delete(&init_ofp_ports, node);
2568         }
2569     }
2570
2571     return 0;
2572 }
2573
2574 /* Find the minimum MTU of all non-datapath devices attached to 'p'.
2575  * Returns ETH_PAYLOAD_MAX or the minimum of the ports. */
2576 static int
2577 find_min_mtu(struct ofproto *p)
2578 {
2579     struct ofport *ofport;
2580     int mtu = 0;
2581
2582     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2583         struct netdev *netdev = ofport->netdev;
2584         int dev_mtu;
2585
2586         /* Skip any internal ports, since that's what we're trying to
2587          * set. */
2588         if (!strcmp(netdev_get_type(netdev), "internal")) {
2589             continue;
2590         }
2591
2592         if (netdev_get_mtu(netdev, &dev_mtu)) {
2593             continue;
2594         }
2595         if (!mtu || dev_mtu < mtu) {
2596             mtu = dev_mtu;
2597         }
2598     }
2599
2600     return mtu ? mtu: ETH_PAYLOAD_MAX;
2601 }
2602
2603 /* Update MTU of all datapath devices on 'p' to the minimum of the
2604  * non-datapath ports in event of 'port' added or changed. */
2605 static void
2606 update_mtu(struct ofproto *p, struct ofport *port)
2607 {
2608     struct ofport *ofport;
2609     struct netdev *netdev = port->netdev;
2610     int dev_mtu, old_min;
2611
2612     if (netdev_get_mtu(netdev, &dev_mtu)) {
2613         port->mtu = 0;
2614         return;
2615     }
2616     if (!strcmp(netdev_get_type(port->netdev), "internal")) {
2617         if (dev_mtu > p->min_mtu) {
2618            if (!netdev_set_mtu(port->netdev, p->min_mtu)) {
2619                dev_mtu = p->min_mtu;
2620            }
2621         }
2622         port->mtu = dev_mtu;
2623         return;
2624     }
2625
2626     /* For non-internal port find new min mtu. */
2627     old_min = p->min_mtu;
2628     port->mtu = dev_mtu;
2629     p->min_mtu = find_min_mtu(p);
2630     if (p->min_mtu == old_min) {
2631         return;
2632     }
2633
2634     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2635         struct netdev *netdev = ofport->netdev;
2636
2637         if (!strcmp(netdev_get_type(netdev), "internal")) {
2638             if (!netdev_set_mtu(netdev, p->min_mtu)) {
2639                 ofport->mtu = p->min_mtu;
2640             }
2641         }
2642     }
2643 }
2644 \f
2645 static void
2646 ofproto_rule_destroy__(struct rule *rule)
2647     OVS_NO_THREAD_SAFETY_ANALYSIS
2648 {
2649     cls_rule_destroy(CONST_CAST(struct cls_rule *, &rule->cr));
2650     rule_actions_destroy(rule_get_actions(rule));
2651     ovs_mutex_destroy(&rule->mutex);
2652     rule->ofproto->ofproto_class->rule_dealloc(rule);
2653 }
2654
2655 static void
2656 rule_destroy_cb(struct rule *rule)
2657 {
2658     rule->ofproto->ofproto_class->rule_destruct(rule);
2659     ofproto_rule_destroy__(rule);
2660 }
2661
2662 void
2663 ofproto_rule_ref(struct rule *rule)
2664 {
2665     if (rule) {
2666         ovs_refcount_ref(&rule->ref_count);
2667     }
2668 }
2669
2670 /* Decrements 'rule''s ref_count and schedules 'rule' to be destroyed if the
2671  * ref_count reaches 0.
2672  *
2673  * Use of RCU allows short term use (between RCU quiescent periods) without
2674  * keeping a reference.  A reference must be taken if the rule needs to
2675  * stay around accross the RCU quiescent periods. */
2676 void
2677 ofproto_rule_unref(struct rule *rule)
2678 {
2679     if (rule && ovs_refcount_unref(&rule->ref_count) == 1) {
2680         ovsrcu_postpone(rule_destroy_cb, rule);
2681     }
2682 }
2683
2684 static uint32_t get_provider_meter_id(const struct ofproto *,
2685                                       uint32_t of_meter_id);
2686
2687 /* Creates and returns a new 'struct rule_actions', with a ref_count of 1,
2688  * whose actions are a copy of from the 'ofpacts_len' bytes of 'ofpacts'. */
2689 struct rule_actions *
2690 rule_actions_create(const struct ofproto *ofproto,
2691                     const struct ofpact *ofpacts, size_t ofpacts_len)
2692 {
2693     struct rule_actions *actions;
2694
2695     actions = xmalloc(sizeof *actions);
2696     actions->ofpacts = xmemdup(ofpacts, ofpacts_len);
2697     actions->ofpacts_len = ofpacts_len;
2698     actions->provider_meter_id
2699         = get_provider_meter_id(ofproto,
2700                                 ofpacts_get_meter(ofpacts, ofpacts_len));
2701
2702     return actions;
2703 }
2704
2705 static void
2706 rule_actions_destroy_cb(struct rule_actions *actions)
2707 {
2708     free(actions->ofpacts);
2709     free(actions);
2710 }
2711
2712 /* Decrements 'actions''s ref_count and frees 'actions' if the ref_count
2713  * reaches 0. */
2714 void
2715 rule_actions_destroy(struct rule_actions *actions)
2716 {
2717     if (actions) {
2718         ovsrcu_postpone(rule_actions_destroy_cb, actions);
2719     }
2720 }
2721
2722 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
2723  * that outputs to 'port' (output to OFPP_FLOOD and OFPP_ALL doesn't count). */
2724 static bool
2725 ofproto_rule_has_out_port(const struct rule *rule, ofp_port_t port)
2726     OVS_REQUIRES(ofproto_mutex)
2727 {
2728     if (port == OFPP_ANY) {
2729         return true;
2730     } else {
2731         const struct rule_actions *actions = rule_get_actions(rule);
2732         return ofpacts_output_to_port(actions->ofpacts,
2733                                       actions->ofpacts_len, port);
2734     }
2735 }
2736
2737 /* Returns true if 'rule' has group and equals group_id. */
2738 static bool
2739 ofproto_rule_has_out_group(const struct rule *rule, uint32_t group_id)
2740     OVS_REQUIRES(ofproto_mutex)
2741 {
2742     if (group_id == OFPG_ANY) {
2743         return true;
2744     } else {
2745         const struct rule_actions *actions = rule_get_actions(rule);
2746         return ofpacts_output_to_group(actions->ofpacts,
2747                                        actions->ofpacts_len, group_id);
2748     }
2749 }
2750
2751 /* Returns true if a rule related to 'op' has an OpenFlow OFPAT_OUTPUT or
2752  * OFPAT_ENQUEUE action that outputs to 'out_port'. */
2753 bool
2754 ofoperation_has_out_port(const struct ofoperation *op, ofp_port_t out_port)
2755     OVS_REQUIRES(ofproto_mutex)
2756 {
2757     if (ofproto_rule_has_out_port(op->rule, out_port)) {
2758         return true;
2759     }
2760
2761     switch (op->type) {
2762     case OFOPERATION_ADD:
2763     case OFOPERATION_DELETE:
2764         return false;
2765
2766     case OFOPERATION_MODIFY:
2767     case OFOPERATION_REPLACE:
2768         return ofpacts_output_to_port(op->actions->ofpacts,
2769                                       op->actions->ofpacts_len, out_port);
2770     }
2771
2772     OVS_NOT_REACHED();
2773 }
2774
2775 static void
2776 rule_execute_destroy(struct rule_execute *e)
2777 {
2778     ofproto_rule_unref(e->rule);
2779     list_remove(&e->list_node);
2780     free(e);
2781 }
2782
2783 /* Executes all "rule_execute" operations queued up in ofproto->rule_executes,
2784  * by passing them to the ofproto provider. */
2785 static void
2786 run_rule_executes(struct ofproto *ofproto)
2787     OVS_EXCLUDED(ofproto_mutex)
2788 {
2789     struct rule_execute *e, *next;
2790     struct list executes;
2791
2792     guarded_list_pop_all(&ofproto->rule_executes, &executes);
2793     LIST_FOR_EACH_SAFE (e, next, list_node, &executes) {
2794         struct flow flow;
2795
2796         flow_extract(e->packet, NULL, &flow);
2797         flow.in_port.ofp_port = e->in_port;
2798         ofproto->ofproto_class->rule_execute(e->rule, &flow, e->packet);
2799
2800         rule_execute_destroy(e);
2801     }
2802 }
2803
2804 /* Destroys and discards all "rule_execute" operations queued up in
2805  * ofproto->rule_executes. */
2806 static void
2807 destroy_rule_executes(struct ofproto *ofproto)
2808 {
2809     struct rule_execute *e, *next;
2810     struct list executes;
2811
2812     guarded_list_pop_all(&ofproto->rule_executes, &executes);
2813     LIST_FOR_EACH_SAFE (e, next, list_node, &executes) {
2814         ofpbuf_delete(e->packet);
2815         rule_execute_destroy(e);
2816     }
2817 }
2818
2819 /* Returns true if 'rule' should be hidden from the controller.
2820  *
2821  * Rules with priority higher than UINT16_MAX are set up by ofproto itself
2822  * (e.g. by in-band control) and are intentionally hidden from the
2823  * controller. */
2824 static bool
2825 ofproto_rule_is_hidden(const struct rule *rule)
2826 {
2827     return (rule->cr.priority > UINT16_MAX);
2828 }
2829
2830 static bool
2831 oftable_is_modifiable(const struct oftable *table,
2832                       enum ofputil_flow_mod_flags flags)
2833 {
2834     if (flags & OFPUTIL_FF_NO_READONLY) {
2835         return true;
2836     }
2837
2838     return !(table->flags & OFTABLE_READONLY);
2839 }
2840
2841 static bool
2842 rule_is_modifiable(const struct rule *rule, enum ofputil_flow_mod_flags flags)
2843 {
2844     const struct oftable *rule_table;
2845
2846     rule_table = &rule->ofproto->tables[rule->table_id];
2847     return oftable_is_modifiable(rule_table, flags);
2848 }
2849 \f
2850 static enum ofperr
2851 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
2852 {
2853     ofconn_send_reply(ofconn, make_echo_reply(oh));
2854     return 0;
2855 }
2856
2857 static enum ofperr
2858 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
2859 {
2860     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2861     struct ofputil_switch_features features;
2862     struct ofport *port;
2863     bool arp_match_ip;
2864     struct ofpbuf *b;
2865
2866     ofproto->ofproto_class->get_features(ofproto, &arp_match_ip,
2867                                          &features.actions);
2868     ovs_assert(features.actions & OFPUTIL_A_OUTPUT); /* sanity check */
2869
2870     features.datapath_id = ofproto->datapath_id;
2871     features.n_buffers = pktbuf_capacity();
2872     features.n_tables = ofproto_get_n_visible_tables(ofproto);
2873     features.capabilities = (OFPUTIL_C_FLOW_STATS | OFPUTIL_C_TABLE_STATS |
2874                              OFPUTIL_C_PORT_STATS | OFPUTIL_C_QUEUE_STATS);
2875     if (arp_match_ip) {
2876         features.capabilities |= OFPUTIL_C_ARP_MATCH_IP;
2877     }
2878     /* FIXME: Fill in proper features.auxiliary_id for auxiliary connections */
2879     features.auxiliary_id = 0;
2880     b = ofputil_encode_switch_features(&features, ofconn_get_protocol(ofconn),
2881                                        oh->xid);
2882     HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
2883         ofputil_put_switch_features_port(&port->pp, b);
2884     }
2885
2886     ofconn_send_reply(ofconn, b);
2887     return 0;
2888 }
2889
2890 static enum ofperr
2891 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
2892 {
2893     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2894     struct ofp_switch_config *osc;
2895     enum ofp_config_flags flags;
2896     struct ofpbuf *buf;
2897
2898     /* Send reply. */
2899     buf = ofpraw_alloc_reply(OFPRAW_OFPT_GET_CONFIG_REPLY, oh, 0);
2900     osc = ofpbuf_put_uninit(buf, sizeof *osc);
2901     flags = ofproto->frag_handling;
2902     /* OFPC_INVALID_TTL_TO_CONTROLLER is deprecated in OF 1.3 */
2903     if (oh->version < OFP13_VERSION
2904         && ofconn_get_invalid_ttl_to_controller(ofconn)) {
2905         flags |= OFPC_INVALID_TTL_TO_CONTROLLER;
2906     }
2907     osc->flags = htons(flags);
2908     osc->miss_send_len = htons(ofconn_get_miss_send_len(ofconn));
2909     ofconn_send_reply(ofconn, buf);
2910
2911     return 0;
2912 }
2913
2914 static enum ofperr
2915 handle_set_config(struct ofconn *ofconn, const struct ofp_header *oh)
2916 {
2917     const struct ofp_switch_config *osc = ofpmsg_body(oh);
2918     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2919     uint16_t flags = ntohs(osc->flags);
2920
2921     if (ofconn_get_type(ofconn) != OFCONN_PRIMARY
2922         || ofconn_get_role(ofconn) != OFPCR12_ROLE_SLAVE) {
2923         enum ofp_config_flags cur = ofproto->frag_handling;
2924         enum ofp_config_flags next = flags & OFPC_FRAG_MASK;
2925
2926         ovs_assert((cur & OFPC_FRAG_MASK) == cur);
2927         if (cur != next) {
2928             if (ofproto->ofproto_class->set_frag_handling(ofproto, next)) {
2929                 ofproto->frag_handling = next;
2930             } else {
2931                 VLOG_WARN_RL(&rl, "%s: unsupported fragment handling mode %s",
2932                              ofproto->name,
2933                              ofputil_frag_handling_to_string(next));
2934             }
2935         }
2936     }
2937     /* OFPC_INVALID_TTL_TO_CONTROLLER is deprecated in OF 1.3 */
2938     ofconn_set_invalid_ttl_to_controller(ofconn,
2939              (oh->version < OFP13_VERSION
2940               && flags & OFPC_INVALID_TTL_TO_CONTROLLER));
2941
2942     ofconn_set_miss_send_len(ofconn, ntohs(osc->miss_send_len));
2943
2944     return 0;
2945 }
2946
2947 /* Checks whether 'ofconn' is a slave controller.  If so, returns an OpenFlow
2948  * error message code for the caller to propagate upward.  Otherwise, returns
2949  * 0.
2950  *
2951  * The log message mentions 'msg_type'. */
2952 static enum ofperr
2953 reject_slave_controller(struct ofconn *ofconn)
2954 {
2955     if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
2956         && ofconn_get_role(ofconn) == OFPCR12_ROLE_SLAVE) {
2957         return OFPERR_OFPBRC_EPERM;
2958     } else {
2959         return 0;
2960     }
2961 }
2962
2963 /* Checks that the 'ofpacts_len' bytes of action in 'ofpacts' are appropriate
2964  * for 'ofproto':
2965  *
2966  *    - If they use a meter, then 'ofproto' has that meter configured.
2967  *
2968  *    - If they use any groups, then 'ofproto' has that group configured.
2969  *
2970  * Returns 0 if successful, otherwise an OpenFlow error. */
2971 static enum ofperr
2972 ofproto_check_ofpacts(struct ofproto *ofproto,
2973                       const struct ofpact ofpacts[], size_t ofpacts_len)
2974 {
2975     const struct ofpact *a;
2976     uint32_t mid;
2977
2978     mid = ofpacts_get_meter(ofpacts, ofpacts_len);
2979     if (mid && get_provider_meter_id(ofproto, mid) == UINT32_MAX) {
2980         return OFPERR_OFPMMFC_INVALID_METER;
2981     }
2982
2983     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
2984         if (a->type == OFPACT_GROUP
2985             && !ofproto_group_exists(ofproto, ofpact_get_GROUP(a)->group_id)) {
2986             return OFPERR_OFPBAC_BAD_OUT_GROUP;
2987         }
2988     }
2989
2990     return 0;
2991 }
2992
2993 static enum ofperr
2994 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
2995 {
2996     struct ofproto *p = ofconn_get_ofproto(ofconn);
2997     struct ofputil_packet_out po;
2998     struct ofpbuf *payload;
2999     uint64_t ofpacts_stub[1024 / 8];
3000     struct ofpbuf ofpacts;
3001     struct flow flow;
3002     enum ofperr error;
3003
3004     COVERAGE_INC(ofproto_packet_out);
3005
3006     error = reject_slave_controller(ofconn);
3007     if (error) {
3008         goto exit;
3009     }
3010
3011     /* Decode message. */
3012     ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
3013     error = ofputil_decode_packet_out(&po, oh, &ofpacts);
3014     if (error) {
3015         goto exit_free_ofpacts;
3016     }
3017     if (ofp_to_u16(po.in_port) >= p->max_ports
3018         && ofp_to_u16(po.in_port) < ofp_to_u16(OFPP_MAX)) {
3019         error = OFPERR_OFPBRC_BAD_PORT;
3020         goto exit_free_ofpacts;
3021     }
3022
3023     /* Get payload. */
3024     if (po.buffer_id != UINT32_MAX) {
3025         error = ofconn_pktbuf_retrieve(ofconn, po.buffer_id, &payload, NULL);
3026         if (error || !payload) {
3027             goto exit_free_ofpacts;
3028         }
3029     } else {
3030         /* Ensure that the L3 header is 32-bit aligned. */
3031         payload = ofpbuf_clone_data_with_headroom(po.packet, po.packet_len, 2);
3032     }
3033
3034     /* Verify actions against packet, then send packet if successful. */
3035     flow_extract(payload, NULL, &flow);
3036     flow.in_port.ofp_port = po.in_port;
3037     error = ofproto_check_ofpacts(p, po.ofpacts, po.ofpacts_len);
3038     if (!error) {
3039         error = p->ofproto_class->packet_out(p, payload, &flow,
3040                                              po.ofpacts, po.ofpacts_len);
3041     }
3042     ofpbuf_delete(payload);
3043
3044 exit_free_ofpacts:
3045     ofpbuf_uninit(&ofpacts);
3046 exit:
3047     return error;
3048 }
3049
3050 static void
3051 update_port_config(struct ofconn *ofconn, struct ofport *port,
3052                    enum ofputil_port_config config,
3053                    enum ofputil_port_config mask)
3054 {
3055     enum ofputil_port_config toggle = (config ^ port->pp.config) & mask;
3056
3057     if (toggle & OFPUTIL_PC_PORT_DOWN
3058         && (config & OFPUTIL_PC_PORT_DOWN
3059             ? netdev_turn_flags_off(port->netdev, NETDEV_UP, NULL)
3060             : netdev_turn_flags_on(port->netdev, NETDEV_UP, NULL))) {
3061         /* We tried to bring the port up or down, but it failed, so don't
3062          * update the "down" bit. */
3063         toggle &= ~OFPUTIL_PC_PORT_DOWN;
3064     }
3065
3066     if (toggle) {
3067         enum ofputil_port_config old_config = port->pp.config;
3068         port->pp.config ^= toggle;
3069         port->ofproto->ofproto_class->port_reconfigured(port, old_config);
3070         connmgr_send_port_status(port->ofproto->connmgr, ofconn, &port->pp,
3071                                  OFPPR_MODIFY);
3072     }
3073 }
3074
3075 static enum ofperr
3076 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
3077 {
3078     struct ofproto *p = ofconn_get_ofproto(ofconn);
3079     struct ofputil_port_mod pm;
3080     struct ofport *port;
3081     enum ofperr error;
3082
3083     error = reject_slave_controller(ofconn);
3084     if (error) {
3085         return error;
3086     }
3087
3088     error = ofputil_decode_port_mod(oh, &pm);
3089     if (error) {
3090         return error;
3091     }
3092
3093     port = ofproto_get_port(p, pm.port_no);
3094     if (!port) {
3095         return OFPERR_OFPPMFC_BAD_PORT;
3096     } else if (!eth_addr_equals(port->pp.hw_addr, pm.hw_addr)) {
3097         return OFPERR_OFPPMFC_BAD_HW_ADDR;
3098     } else {
3099         update_port_config(ofconn, port, pm.config, pm.mask);
3100         if (pm.advertise) {
3101             netdev_set_advertisements(port->netdev, pm.advertise);
3102         }
3103     }
3104     return 0;
3105 }
3106
3107 static enum ofperr
3108 handle_desc_stats_request(struct ofconn *ofconn,
3109                           const struct ofp_header *request)
3110 {
3111     static const char *default_mfr_desc = "Nicira, Inc.";
3112     static const char *default_hw_desc = "Open vSwitch";
3113     static const char *default_sw_desc = VERSION;
3114     static const char *default_serial_desc = "None";
3115     static const char *default_dp_desc = "None";
3116
3117     struct ofproto *p = ofconn_get_ofproto(ofconn);
3118     struct ofp_desc_stats *ods;
3119     struct ofpbuf *msg;
3120
3121     msg = ofpraw_alloc_stats_reply(request, 0);
3122     ods = ofpbuf_put_zeros(msg, sizeof *ods);
3123     ovs_strlcpy(ods->mfr_desc, p->mfr_desc ? p->mfr_desc : default_mfr_desc,
3124                 sizeof ods->mfr_desc);
3125     ovs_strlcpy(ods->hw_desc, p->hw_desc ? p->hw_desc : default_hw_desc,
3126                 sizeof ods->hw_desc);
3127     ovs_strlcpy(ods->sw_desc, p->sw_desc ? p->sw_desc : default_sw_desc,
3128                 sizeof ods->sw_desc);
3129     ovs_strlcpy(ods->serial_num,
3130                 p->serial_desc ? p->serial_desc : default_serial_desc,
3131                 sizeof ods->serial_num);
3132     ovs_strlcpy(ods->dp_desc, p->dp_desc ? p->dp_desc : default_dp_desc,
3133                 sizeof ods->dp_desc);
3134     ofconn_send_reply(ofconn, msg);
3135
3136     return 0;
3137 }
3138
3139 static enum ofperr
3140 handle_table_stats_request(struct ofconn *ofconn,
3141                            const struct ofp_header *request)
3142 {
3143     struct ofproto *p = ofconn_get_ofproto(ofconn);
3144     struct ofp12_table_stats *ots;
3145     struct ofpbuf *msg;
3146     int n_tables;
3147     size_t i;
3148
3149     /* Set up default values.
3150      *
3151      * ofp12_table_stats is used as a generic structure as
3152      * it is able to hold all the fields for ofp10_table_stats
3153      * and ofp11_table_stats (and of course itself).
3154      */
3155     ots = xcalloc(p->n_tables, sizeof *ots);
3156     for (i = 0; i < p->n_tables; i++) {
3157         ots[i].table_id = i;
3158         sprintf(ots[i].name, "table%"PRIuSIZE, i);
3159         ots[i].match = htonll(OFPXMT13_MASK);
3160         ots[i].wildcards = htonll(OFPXMT13_MASK);
3161         ots[i].write_actions = htonl(OFPAT11_OUTPUT);
3162         ots[i].apply_actions = htonl(OFPAT11_OUTPUT);
3163         ots[i].write_setfields = htonll(OFPXMT13_MASK);
3164         ots[i].apply_setfields = htonll(OFPXMT13_MASK);
3165         ots[i].metadata_match = OVS_BE64_MAX;
3166         ots[i].metadata_write = OVS_BE64_MAX;
3167         ots[i].instructions = htonl(OFPIT11_ALL);
3168         ots[i].config = htonl(OFPTC11_TABLE_MISS_MASK);
3169         ots[i].max_entries = htonl(1000000); /* An arbitrary big number. */
3170         fat_rwlock_rdlock(&p->tables[i].cls.rwlock);
3171         ots[i].active_count = htonl(classifier_count(&p->tables[i].cls));
3172         fat_rwlock_unlock(&p->tables[i].cls.rwlock);
3173     }
3174
3175     p->ofproto_class->get_tables(p, ots);
3176
3177     /* Post-process the tables, dropping hidden tables. */
3178     n_tables = p->n_tables;
3179     for (i = 0; i < p->n_tables; i++) {
3180         const struct oftable *table = &p->tables[i];
3181
3182         if (table->flags & OFTABLE_HIDDEN) {
3183             n_tables = i;
3184             break;
3185         }
3186
3187         if (table->name) {
3188             ovs_strzcpy(ots[i].name, table->name, sizeof ots[i].name);
3189         }
3190
3191         if (table->max_flows < ntohl(ots[i].max_entries)) {
3192             ots[i].max_entries = htonl(table->max_flows);
3193         }
3194     }
3195
3196     msg = ofputil_encode_table_stats_reply(ots, n_tables, request);
3197     ofconn_send_reply(ofconn, msg);
3198
3199     free(ots);
3200
3201     return 0;
3202 }
3203
3204 static void
3205 append_port_stat(struct ofport *port, struct list *replies)
3206 {
3207     struct ofputil_port_stats ops = { .port_no = port->pp.port_no };
3208
3209     calc_duration(port->created, time_msec(),
3210                   &ops.duration_sec, &ops.duration_nsec);
3211
3212     /* Intentionally ignore return value, since errors will set
3213      * 'stats' to all-1s, which is correct for OpenFlow, and
3214      * netdev_get_stats() will log errors. */
3215     ofproto_port_get_stats(port, &ops.stats);
3216
3217     ofputil_append_port_stat(replies, &ops);
3218 }
3219
3220 static enum ofperr
3221 handle_port_stats_request(struct ofconn *ofconn,
3222                           const struct ofp_header *request)
3223 {
3224     struct ofproto *p = ofconn_get_ofproto(ofconn);
3225     struct ofport *port;
3226     struct list replies;
3227     ofp_port_t port_no;
3228     enum ofperr error;
3229
3230     error = ofputil_decode_port_stats_request(request, &port_no);
3231     if (error) {
3232         return error;
3233     }
3234
3235     ofpmp_init(&replies, request);
3236     if (port_no != OFPP_ANY) {
3237         port = ofproto_get_port(p, port_no);
3238         if (port) {
3239             append_port_stat(port, &replies);
3240         }
3241     } else {
3242         HMAP_FOR_EACH (port, hmap_node, &p->ports) {
3243             append_port_stat(port, &replies);
3244         }
3245     }
3246
3247     ofconn_send_replies(ofconn, &replies);
3248     return 0;
3249 }
3250
3251 static enum ofperr
3252 handle_port_desc_stats_request(struct ofconn *ofconn,
3253                                const struct ofp_header *request)
3254 {
3255     struct ofproto *p = ofconn_get_ofproto(ofconn);
3256     enum ofp_version version;
3257     struct ofport *port;
3258     struct list replies;
3259
3260     ofpmp_init(&replies, request);
3261
3262     version = ofputil_protocol_to_ofp_version(ofconn_get_protocol(ofconn));
3263     HMAP_FOR_EACH (port, hmap_node, &p->ports) {
3264         ofputil_append_port_desc_stats_reply(version, &port->pp, &replies);
3265     }
3266
3267     ofconn_send_replies(ofconn, &replies);
3268     return 0;
3269 }
3270
3271 static uint32_t
3272 hash_cookie(ovs_be64 cookie)
3273 {
3274     return hash_uint64((OVS_FORCE uint64_t)cookie);
3275 }
3276
3277 static void
3278 cookies_insert(struct ofproto *ofproto, struct rule *rule)
3279     OVS_REQUIRES(ofproto_mutex)
3280 {
3281     hindex_insert(&ofproto->cookies, &rule->cookie_node,
3282                   hash_cookie(rule->flow_cookie));
3283 }
3284
3285 static void
3286 cookies_remove(struct ofproto *ofproto, struct rule *rule)
3287     OVS_REQUIRES(ofproto_mutex)
3288 {
3289     hindex_remove(&ofproto->cookies, &rule->cookie_node);
3290 }
3291
3292 static void
3293 ofproto_rule_change_cookie(struct ofproto *ofproto, struct rule *rule,
3294                            ovs_be64 new_cookie)
3295     OVS_REQUIRES(ofproto_mutex)
3296 {
3297     if (new_cookie != rule->flow_cookie) {
3298         cookies_remove(ofproto, rule);
3299
3300         ovs_mutex_lock(&rule->mutex);
3301         rule->flow_cookie = new_cookie;
3302         ovs_mutex_unlock(&rule->mutex);
3303
3304         cookies_insert(ofproto, rule);
3305     }
3306 }
3307
3308 static void
3309 calc_duration(long long int start, long long int now,
3310               uint32_t *sec, uint32_t *nsec)
3311 {
3312     long long int msecs = now - start;
3313     *sec = msecs / 1000;
3314     *nsec = (msecs % 1000) * (1000 * 1000);
3315 }
3316
3317 /* Checks whether 'table_id' is 0xff or a valid table ID in 'ofproto'.  Returns
3318  * true if 'table_id' is OK, false otherwise.  */
3319 static bool
3320 check_table_id(const struct ofproto *ofproto, uint8_t table_id)
3321 {
3322     return table_id == OFPTT_ALL || table_id < ofproto->n_tables;
3323 }
3324
3325 static struct oftable *
3326 next_visible_table(const struct ofproto *ofproto, uint8_t table_id)
3327 {
3328     struct oftable *table;
3329
3330     for (table = &ofproto->tables[table_id];
3331          table < &ofproto->tables[ofproto->n_tables];
3332          table++) {
3333         if (!(table->flags & OFTABLE_HIDDEN)) {
3334             return table;
3335         }
3336     }
3337
3338     return NULL;
3339 }
3340
3341 static struct oftable *
3342 first_matching_table(const struct ofproto *ofproto, uint8_t table_id)
3343 {
3344     if (table_id == 0xff) {
3345         return next_visible_table(ofproto, 0);
3346     } else if (table_id < ofproto->n_tables) {
3347         return &ofproto->tables[table_id];
3348     } else {
3349         return NULL;
3350     }
3351 }
3352
3353 static struct oftable *
3354 next_matching_table(const struct ofproto *ofproto,
3355                     const struct oftable *table, uint8_t table_id)
3356 {
3357     return (table_id == 0xff
3358             ? next_visible_table(ofproto, (table - ofproto->tables) + 1)
3359             : NULL);
3360 }
3361
3362 /* Assigns TABLE to each oftable, in turn, that matches TABLE_ID in OFPROTO:
3363  *
3364  *   - If TABLE_ID is 0xff, this iterates over every classifier table in
3365  *     OFPROTO, skipping tables marked OFTABLE_HIDDEN.
3366  *
3367  *   - If TABLE_ID is the number of a table in OFPROTO, then the loop iterates
3368  *     only once, for that table.  (This can be used to access tables marked
3369  *     OFTABLE_HIDDEN.)
3370  *
3371  *   - Otherwise, TABLE_ID isn't valid for OFPROTO, so the loop won't be
3372  *     entered at all.  (Perhaps you should have validated TABLE_ID with
3373  *     check_table_id().)
3374  *
3375  * All parameters are evaluated multiple times.
3376  */
3377 #define FOR_EACH_MATCHING_TABLE(TABLE, TABLE_ID, OFPROTO)         \
3378     for ((TABLE) = first_matching_table(OFPROTO, TABLE_ID);       \
3379          (TABLE) != NULL;                                         \
3380          (TABLE) = next_matching_table(OFPROTO, TABLE, TABLE_ID))
3381
3382 /* Initializes 'criteria' in a straightforward way based on the other
3383  * parameters.
3384  *
3385  * For "loose" matching, the 'priority' parameter is unimportant and may be
3386  * supplied as 0. */
3387 static void
3388 rule_criteria_init(struct rule_criteria *criteria, uint8_t table_id,
3389                    const struct match *match, unsigned int priority,
3390                    ovs_be64 cookie, ovs_be64 cookie_mask,
3391                    ofp_port_t out_port, uint32_t out_group)
3392 {
3393     criteria->table_id = table_id;
3394     cls_rule_init(&criteria->cr, match, priority);
3395     criteria->cookie = cookie;
3396     criteria->cookie_mask = cookie_mask;
3397     criteria->out_port = out_port;
3398     criteria->out_group = out_group;
3399 }
3400
3401 static void
3402 rule_criteria_destroy(struct rule_criteria *criteria)
3403 {
3404     cls_rule_destroy(&criteria->cr);
3405 }
3406
3407 void
3408 rule_collection_init(struct rule_collection *rules)
3409 {
3410     rules->rules = rules->stub;
3411     rules->n = 0;
3412     rules->capacity = ARRAY_SIZE(rules->stub);
3413 }
3414
3415 void
3416 rule_collection_add(struct rule_collection *rules, struct rule *rule)
3417 {
3418     if (rules->n >= rules->capacity) {
3419         size_t old_size, new_size;
3420
3421         old_size = rules->capacity * sizeof *rules->rules;
3422         rules->capacity *= 2;
3423         new_size = rules->capacity * sizeof *rules->rules;
3424
3425         if (rules->rules == rules->stub) {
3426             rules->rules = xmalloc(new_size);
3427             memcpy(rules->rules, rules->stub, old_size);
3428         } else {
3429             rules->rules = xrealloc(rules->rules, new_size);
3430         }
3431     }
3432
3433     rules->rules[rules->n++] = rule;
3434 }
3435
3436 void
3437 rule_collection_ref(struct rule_collection *rules)
3438     OVS_REQUIRES(ofproto_mutex)
3439 {
3440     size_t i;
3441
3442     for (i = 0; i < rules->n; i++) {
3443         ofproto_rule_ref(rules->rules[i]);
3444     }
3445 }
3446
3447 void
3448 rule_collection_unref(struct rule_collection *rules)
3449 {
3450     size_t i;
3451
3452     for (i = 0; i < rules->n; i++) {
3453         ofproto_rule_unref(rules->rules[i]);
3454     }
3455 }
3456
3457 void
3458 rule_collection_destroy(struct rule_collection *rules)
3459 {
3460     if (rules->rules != rules->stub) {
3461         free(rules->rules);
3462     }
3463 }
3464
3465 static enum ofperr
3466 collect_rule(struct rule *rule, const struct rule_criteria *c,
3467              struct rule_collection *rules)
3468     OVS_REQUIRES(ofproto_mutex)
3469 {
3470     /* We ordinarily want to skip hidden rules, but there has to be a way for
3471      * code internal to OVS to modify and delete them, so if the criteria
3472      * specify a priority that can only be for a hidden flow, then allow hidden
3473      * rules to be selected.  (This doesn't allow OpenFlow clients to meddle
3474      * with hidden flows because OpenFlow uses only a 16-bit field to specify
3475      * priority.) */
3476     if (ofproto_rule_is_hidden(rule) && c->cr.priority <= UINT16_MAX) {
3477         return 0;
3478     } else if (rule->pending) {
3479         return OFPROTO_POSTPONE;
3480     } else {
3481         if ((c->table_id == rule->table_id || c->table_id == 0xff)
3482             && ofproto_rule_has_out_port(rule, c->out_port)
3483             && ofproto_rule_has_out_group(rule, c->out_group)
3484             && !((rule->flow_cookie ^ c->cookie) & c->cookie_mask)) {
3485             rule_collection_add(rules, rule);
3486         }
3487         return 0;
3488     }
3489 }
3490
3491 /* Searches 'ofproto' for rules that match the criteria in 'criteria'.  Matches
3492  * on classifiers rules are done in the "loose" way required for OpenFlow
3493  * OFPFC_MODIFY and OFPFC_DELETE requests.  Puts the selected rules on list
3494  * 'rules'.
3495  *
3496  * Hidden rules are always omitted.
3497  *
3498  * Returns 0 on success, otherwise an OpenFlow error code. */
3499 static enum ofperr
3500 collect_rules_loose(struct ofproto *ofproto,
3501                     const struct rule_criteria *criteria,
3502                     struct rule_collection *rules)
3503     OVS_REQUIRES(ofproto_mutex)
3504 {
3505     struct oftable *table;
3506     enum ofperr error = 0;
3507
3508     rule_collection_init(rules);
3509
3510     if (!check_table_id(ofproto, criteria->table_id)) {
3511         error = OFPERR_OFPBRC_BAD_TABLE_ID;
3512         goto exit;
3513     }
3514
3515     if (criteria->cookie_mask == OVS_BE64_MAX) {
3516         struct rule *rule;
3517
3518         HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
3519                                    hash_cookie(criteria->cookie),
3520                                    &ofproto->cookies) {
3521             if (cls_rule_is_loose_match(&rule->cr, &criteria->cr.match)) {
3522                 error = collect_rule(rule, criteria, rules);
3523                 if (error) {
3524                     break;
3525                 }
3526             }
3527         }
3528     } else {
3529         FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
3530             struct cls_cursor cursor;
3531             struct rule *rule;
3532
3533             fat_rwlock_rdlock(&table->cls.rwlock);
3534             cls_cursor_init(&cursor, &table->cls, &criteria->cr);
3535             CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3536                 error = collect_rule(rule, criteria, rules);
3537                 if (error) {
3538                     break;
3539                 }
3540             }
3541             fat_rwlock_unlock(&table->cls.rwlock);
3542         }
3543     }
3544
3545 exit:
3546     if (error) {
3547         rule_collection_destroy(rules);
3548     }
3549     return error;
3550 }
3551
3552 /* Searches 'ofproto' for rules that match the criteria in 'criteria'.  Matches
3553  * on classifiers rules are done in the "strict" way required for OpenFlow
3554  * OFPFC_MODIFY_STRICT and OFPFC_DELETE_STRICT requests.  Puts the selected
3555  * rules on list 'rules'.
3556  *
3557  * Hidden rules are always omitted.
3558  *
3559  * Returns 0 on success, otherwise an OpenFlow error code. */
3560 static enum ofperr
3561 collect_rules_strict(struct ofproto *ofproto,
3562                      const struct rule_criteria *criteria,
3563                      struct rule_collection *rules)
3564     OVS_REQUIRES(ofproto_mutex)
3565 {
3566     struct oftable *table;
3567     int error = 0;
3568
3569     rule_collection_init(rules);
3570
3571     if (!check_table_id(ofproto, criteria->table_id)) {
3572         error = OFPERR_OFPBRC_BAD_TABLE_ID;
3573         goto exit;
3574     }
3575
3576     if (criteria->cookie_mask == OVS_BE64_MAX) {
3577         struct rule *rule;
3578
3579         HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
3580                                    hash_cookie(criteria->cookie),
3581                                    &ofproto->cookies) {
3582             if (cls_rule_equal(&rule->cr, &criteria->cr)) {
3583                 error = collect_rule(rule, criteria, rules);
3584                 if (error) {
3585                     break;
3586                 }
3587             }
3588         }
3589     } else {
3590         FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
3591             struct rule *rule;
3592
3593             fat_rwlock_rdlock(&table->cls.rwlock);
3594             rule = rule_from_cls_rule(classifier_find_rule_exactly(
3595                                           &table->cls, &criteria->cr));
3596             fat_rwlock_unlock(&table->cls.rwlock);
3597             if (rule) {
3598                 error = collect_rule(rule, criteria, rules);
3599                 if (error) {
3600                     break;
3601                 }
3602             }
3603         }
3604     }
3605
3606 exit:
3607     if (error) {
3608         rule_collection_destroy(rules);
3609     }
3610     return error;
3611 }
3612
3613 /* Returns 'age_ms' (a duration in milliseconds), converted to seconds and
3614  * forced into the range of a uint16_t. */
3615 static int
3616 age_secs(long long int age_ms)
3617 {
3618     return (age_ms < 0 ? 0
3619             : age_ms >= UINT16_MAX * 1000 ? UINT16_MAX
3620             : (unsigned int) age_ms / 1000);
3621 }
3622
3623 static enum ofperr
3624 handle_flow_stats_request(struct ofconn *ofconn,
3625                           const struct ofp_header *request)
3626     OVS_EXCLUDED(ofproto_mutex)
3627 {
3628     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3629     struct ofputil_flow_stats_request fsr;
3630     struct rule_criteria criteria;
3631     struct rule_collection rules;
3632     struct list replies;
3633     enum ofperr error;
3634     size_t i;
3635
3636     error = ofputil_decode_flow_stats_request(&fsr, request);
3637     if (error) {
3638         return error;
3639     }
3640
3641     rule_criteria_init(&criteria, fsr.table_id, &fsr.match, 0, fsr.cookie,
3642                        fsr.cookie_mask, fsr.out_port, fsr.out_group);
3643
3644     ovs_mutex_lock(&ofproto_mutex);
3645     error = collect_rules_loose(ofproto, &criteria, &rules);
3646     rule_criteria_destroy(&criteria);
3647     if (!error) {
3648         rule_collection_ref(&rules);
3649     }
3650     ovs_mutex_unlock(&ofproto_mutex);
3651
3652     if (error) {
3653         return error;
3654     }
3655
3656     ofpmp_init(&replies, request);
3657     for (i = 0; i < rules.n; i++) {
3658         struct rule *rule = rules.rules[i];
3659         long long int now = time_msec();
3660         struct ofputil_flow_stats fs;
3661         long long int created, used, modified;
3662         struct rule_actions *actions;
3663         enum ofputil_flow_mod_flags flags;
3664
3665         ovs_mutex_lock(&rule->mutex);
3666         fs.cookie = rule->flow_cookie;
3667         fs.idle_timeout = rule->idle_timeout;
3668         fs.hard_timeout = rule->hard_timeout;
3669         created = rule->created;
3670         modified = rule->modified;
3671         actions = rule_get_actions(rule);
3672         flags = rule->flags;
3673         ovs_mutex_unlock(&rule->mutex);
3674
3675         ofproto->ofproto_class->rule_get_stats(rule, &fs.packet_count,
3676                                                &fs.byte_count, &used);
3677
3678         minimatch_expand(&rule->cr.match, &fs.match);
3679         fs.table_id = rule->table_id;
3680         calc_duration(created, now, &fs.duration_sec, &fs.duration_nsec);
3681         fs.priority = rule->cr.priority;
3682         fs.idle_age = age_secs(now - used);
3683         fs.hard_age = age_secs(now - modified);
3684         fs.ofpacts = actions->ofpacts;
3685         fs.ofpacts_len = actions->ofpacts_len;
3686
3687         fs.flags = flags;
3688         ofputil_append_flow_stats_reply(&fs, &replies);
3689     }
3690
3691     rule_collection_unref(&rules);
3692     rule_collection_destroy(&rules);
3693
3694     ofconn_send_replies(ofconn, &replies);
3695
3696     return 0;
3697 }
3698
3699 static void
3700 flow_stats_ds(struct rule *rule, struct ds *results)
3701 {
3702     uint64_t packet_count, byte_count;
3703     struct rule_actions *actions;
3704     long long int created, used;
3705
3706     rule->ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
3707                                                  &byte_count, &used);
3708
3709     ovs_mutex_lock(&rule->mutex);
3710     actions = rule_get_actions(rule);
3711     created = rule->created;
3712     ovs_mutex_unlock(&rule->mutex);
3713
3714     if (rule->table_id != 0) {
3715         ds_put_format(results, "table_id=%"PRIu8", ", rule->table_id);
3716     }
3717     ds_put_format(results, "duration=%llds, ", (time_msec() - created) / 1000);
3718     ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
3719     ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
3720     cls_rule_format(&rule->cr, results);
3721     ds_put_char(results, ',');
3722
3723     ds_put_cstr(results, "actions=");
3724     ofpacts_format(actions->ofpacts, actions->ofpacts_len, results);
3725
3726     ds_put_cstr(results, "\n");
3727 }
3728
3729 /* Adds a pretty-printed description of all flows to 'results', including
3730  * hidden flows (e.g., set up by in-band control). */
3731 void
3732 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
3733 {
3734     struct oftable *table;
3735
3736     OFPROTO_FOR_EACH_TABLE (table, p) {
3737         struct cls_cursor cursor;
3738         struct rule *rule;
3739
3740         fat_rwlock_rdlock(&table->cls.rwlock);
3741         cls_cursor_init(&cursor, &table->cls, NULL);
3742         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3743             flow_stats_ds(rule, results);
3744         }
3745         fat_rwlock_unlock(&table->cls.rwlock);
3746     }
3747 }
3748
3749 /* Obtains the NetFlow engine type and engine ID for 'ofproto' into
3750  * '*engine_type' and '*engine_id', respectively. */
3751 void
3752 ofproto_get_netflow_ids(const struct ofproto *ofproto,
3753                         uint8_t *engine_type, uint8_t *engine_id)
3754 {
3755     ofproto->ofproto_class->get_netflow_ids(ofproto, engine_type, engine_id);
3756 }
3757
3758 /* Checks the status of CFM configured on 'ofp_port' within 'ofproto'.  Returns
3759  * true if the port's CFM status was successfully stored into '*status'.
3760  * Returns false if the port did not have CFM configured, in which case
3761  * '*status' is indeterminate.
3762  *
3763  * The caller must provide and owns '*status', and must free 'status->rmps'. */
3764 bool
3765 ofproto_port_get_cfm_status(const struct ofproto *ofproto, ofp_port_t ofp_port,
3766                             struct ofproto_cfm_status *status)
3767 {
3768     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
3769     return (ofport
3770             && ofproto->ofproto_class->get_cfm_status
3771             && ofproto->ofproto_class->get_cfm_status(ofport, status));
3772 }
3773
3774 static enum ofperr
3775 handle_aggregate_stats_request(struct ofconn *ofconn,
3776                                const struct ofp_header *oh)
3777     OVS_EXCLUDED(ofproto_mutex)
3778 {
3779     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3780     struct ofputil_flow_stats_request request;
3781     struct ofputil_aggregate_stats stats;
3782     bool unknown_packets, unknown_bytes;
3783     struct rule_criteria criteria;
3784     struct rule_collection rules;
3785     struct ofpbuf *reply;
3786     enum ofperr error;
3787     size_t i;
3788
3789     error = ofputil_decode_flow_stats_request(&request, oh);
3790     if (error) {
3791         return error;
3792     }
3793
3794     rule_criteria_init(&criteria, request.table_id, &request.match, 0,
3795                        request.cookie, request.cookie_mask,
3796                        request.out_port, request.out_group);
3797
3798     ovs_mutex_lock(&ofproto_mutex);
3799     error = collect_rules_loose(ofproto, &criteria, &rules);
3800     rule_criteria_destroy(&criteria);
3801     if (!error) {
3802         rule_collection_ref(&rules);
3803     }
3804     ovs_mutex_unlock(&ofproto_mutex);
3805
3806     if (error) {
3807         return error;
3808     }
3809
3810     memset(&stats, 0, sizeof stats);
3811     unknown_packets = unknown_bytes = false;
3812     for (i = 0; i < rules.n; i++) {
3813         struct rule *rule = rules.rules[i];
3814         uint64_t packet_count;
3815         uint64_t byte_count;
3816         long long int used;
3817
3818         ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
3819                                                &byte_count, &used);
3820
3821         if (packet_count == UINT64_MAX) {
3822             unknown_packets = true;
3823         } else {
3824             stats.packet_count += packet_count;
3825         }
3826
3827         if (byte_count == UINT64_MAX) {
3828             unknown_bytes = true;
3829         } else {
3830             stats.byte_count += byte_count;
3831         }
3832
3833         stats.flow_count++;
3834     }
3835     if (unknown_packets) {
3836         stats.packet_count = UINT64_MAX;
3837     }
3838     if (unknown_bytes) {
3839         stats.byte_count = UINT64_MAX;
3840     }
3841
3842     rule_collection_unref(&rules);
3843     rule_collection_destroy(&rules);
3844
3845     reply = ofputil_encode_aggregate_stats_reply(&stats, oh);
3846     ofconn_send_reply(ofconn, reply);
3847
3848     return 0;
3849 }
3850
3851 struct queue_stats_cbdata {
3852     struct ofport *ofport;
3853     struct list replies;
3854     long long int now;
3855 };
3856
3857 static void
3858 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
3859                 const struct netdev_queue_stats *stats)
3860 {
3861     struct ofputil_queue_stats oqs;
3862
3863     oqs.port_no = cbdata->ofport->pp.port_no;
3864     oqs.queue_id = queue_id;
3865     oqs.tx_bytes = stats->tx_bytes;
3866     oqs.tx_packets = stats->tx_packets;
3867     oqs.tx_errors = stats->tx_errors;
3868     if (stats->created != LLONG_MIN) {
3869         calc_duration(stats->created, cbdata->now,
3870                       &oqs.duration_sec, &oqs.duration_nsec);
3871     } else {
3872         oqs.duration_sec = oqs.duration_nsec = UINT32_MAX;
3873     }
3874     ofputil_append_queue_stat(&cbdata->replies, &oqs);
3875 }
3876
3877 static void
3878 handle_queue_stats_dump_cb(uint32_t queue_id,
3879                            struct netdev_queue_stats *stats,
3880                            void *cbdata_)
3881 {
3882     struct queue_stats_cbdata *cbdata = cbdata_;
3883
3884     put_queue_stats(cbdata, queue_id, stats);
3885 }
3886
3887 static enum ofperr
3888 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
3889                             struct queue_stats_cbdata *cbdata)
3890 {
3891     cbdata->ofport = port;
3892     if (queue_id == OFPQ_ALL) {
3893         netdev_dump_queue_stats(port->netdev,
3894                                 handle_queue_stats_dump_cb, cbdata);
3895     } else {
3896         struct netdev_queue_stats stats;
3897
3898         if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
3899             put_queue_stats(cbdata, queue_id, &stats);
3900         } else {
3901             return OFPERR_OFPQOFC_BAD_QUEUE;
3902         }
3903     }
3904     return 0;
3905 }
3906
3907 static enum ofperr
3908 handle_queue_stats_request(struct ofconn *ofconn,
3909                            const struct ofp_header *rq)
3910 {
3911     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3912     struct queue_stats_cbdata cbdata;
3913     struct ofport *port;
3914     enum ofperr error;
3915     struct ofputil_queue_stats_request oqsr;
3916
3917     COVERAGE_INC(ofproto_queue_req);
3918
3919     ofpmp_init(&cbdata.replies, rq);
3920     cbdata.now = time_msec();
3921
3922     error = ofputil_decode_queue_stats_request(rq, &oqsr);
3923     if (error) {
3924         return error;
3925     }
3926
3927     if (oqsr.port_no == OFPP_ANY) {
3928         error = OFPERR_OFPQOFC_BAD_QUEUE;
3929         HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3930             if (!handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)) {
3931                 error = 0;
3932             }
3933         }
3934     } else {
3935         port = ofproto_get_port(ofproto, oqsr.port_no);
3936         error = (port
3937                  ? handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)
3938                  : OFPERR_OFPQOFC_BAD_PORT);
3939     }
3940     if (!error) {
3941         ofconn_send_replies(ofconn, &cbdata.replies);
3942     } else {
3943         ofpbuf_list_delete(&cbdata.replies);
3944     }
3945
3946     return error;
3947 }
3948
3949 static bool
3950 is_flow_deletion_pending(const struct ofproto *ofproto,
3951                          const struct cls_rule *cls_rule,
3952                          uint8_t table_id)
3953     OVS_REQUIRES(ofproto_mutex)
3954 {
3955     if (!hmap_is_empty(&ofproto->deletions)) {
3956         struct ofoperation *op;
3957
3958         HMAP_FOR_EACH_WITH_HASH (op, hmap_node,
3959                                  cls_rule_hash(cls_rule, table_id),
3960                                  &ofproto->deletions) {
3961             if (cls_rule_equal(cls_rule, &op->rule->cr)) {
3962                 return true;
3963             }
3964         }
3965     }
3966
3967     return false;
3968 }
3969
3970 static bool
3971 should_evict_a_rule(struct oftable *table, unsigned int extra_space)
3972     OVS_REQUIRES(ofproto_mutex)
3973     OVS_NO_THREAD_SAFETY_ANALYSIS
3974 {
3975     return classifier_count(&table->cls) + extra_space > table->max_flows;
3976 }
3977
3978 static enum ofperr
3979 evict_rules_from_table(struct ofproto *ofproto, struct oftable *table,
3980                        unsigned int extra_space)
3981     OVS_REQUIRES(ofproto_mutex)
3982 {
3983     while (should_evict_a_rule(table, extra_space)) {
3984         struct rule *rule;
3985
3986         if (!choose_rule_to_evict(table, &rule)) {
3987             return OFPERR_OFPFMFC_TABLE_FULL;
3988         } else if (rule->pending) {
3989             return OFPROTO_POSTPONE;
3990         } else {
3991             struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
3992             delete_flow__(rule, group, OFPRR_EVICTION);
3993             ofopgroup_submit(group);
3994         }
3995     }
3996
3997     return 0;
3998 }
3999
4000 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
4001  * in which no matching flow already exists in the flow table.
4002  *
4003  * Adds the flow specified by 'ofm', which is followed by 'n_actions'
4004  * ofp_actions, to the ofproto's flow table.  Returns 0 on success, an OpenFlow
4005  * error code on failure, or OFPROTO_POSTPONE if the operation cannot be
4006  * initiated now but may be retried later.
4007  *
4008  * The caller retains ownership of 'fm->ofpacts'.
4009  *
4010  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
4011  * if any. */
4012 static enum ofperr
4013 add_flow(struct ofproto *ofproto, struct ofconn *ofconn,
4014          struct ofputil_flow_mod *fm, const struct ofp_header *request)
4015     OVS_REQUIRES(ofproto_mutex)
4016 {
4017     struct oftable *table;
4018     struct cls_rule cr;
4019     struct rule *rule;
4020     uint8_t table_id;
4021     int error = 0;
4022
4023     if (!check_table_id(ofproto, fm->table_id)) {
4024         error = OFPERR_OFPBRC_BAD_TABLE_ID;
4025         return error;
4026     }
4027
4028     /* Pick table. */
4029     if (fm->table_id == 0xff) {
4030         if (ofproto->ofproto_class->rule_choose_table) {
4031             error = ofproto->ofproto_class->rule_choose_table(ofproto,
4032                                                               &fm->match,
4033                                                               &table_id);
4034             if (error) {
4035                 return error;
4036             }
4037             ovs_assert(table_id < ofproto->n_tables);
4038         } else {
4039             table_id = 0;
4040         }
4041     } else if (fm->table_id < ofproto->n_tables) {
4042         table_id = fm->table_id;
4043     } else {
4044         return OFPERR_OFPBRC_BAD_TABLE_ID;
4045     }
4046
4047     table = &ofproto->tables[table_id];
4048
4049     if (!oftable_is_modifiable(table, fm->flags)) {
4050         return OFPERR_OFPBRC_EPERM;
4051     }
4052
4053     if (!(fm->flags & OFPUTIL_FF_HIDDEN_FIELDS)) {
4054         if (!match_has_default_hidden_fields(&fm->match)) {
4055             VLOG_WARN_RL(&rl, "%s: (add_flow) only internal flows can set "
4056                          "non-default values to hidden fields", ofproto->name);
4057             return OFPERR_OFPBRC_EPERM;
4058         }
4059     }
4060
4061     cls_rule_init(&cr, &fm->match, fm->priority);
4062
4063     /* Transform "add" into "modify" if there's an existing identical flow. */
4064     fat_rwlock_rdlock(&table->cls.rwlock);
4065     rule = rule_from_cls_rule(classifier_find_rule_exactly(&table->cls, &cr));
4066     fat_rwlock_unlock(&table->cls.rwlock);
4067     if (rule) {
4068         cls_rule_destroy(&cr);
4069         if (!rule_is_modifiable(rule, fm->flags)) {
4070             return OFPERR_OFPBRC_EPERM;
4071         } else if (rule->pending) {
4072             return OFPROTO_POSTPONE;
4073         } else {
4074             struct rule_collection rules;
4075
4076             rule_collection_init(&rules);
4077             rule_collection_add(&rules, rule);
4078             fm->modify_cookie = true;
4079             error = modify_flows__(ofproto, ofconn, fm, request, &rules);
4080             rule_collection_destroy(&rules);
4081
4082             return error;
4083         }
4084     }
4085
4086     /* Serialize against pending deletion. */
4087     if (is_flow_deletion_pending(ofproto, &cr, table_id)) {
4088         cls_rule_destroy(&cr);
4089         return OFPROTO_POSTPONE;
4090     }
4091
4092     /* Check for overlap, if requested. */
4093     if (fm->flags & OFPUTIL_FF_CHECK_OVERLAP) {
4094         bool overlaps;
4095
4096         fat_rwlock_rdlock(&table->cls.rwlock);
4097         overlaps = classifier_rule_overlaps(&table->cls, &cr);
4098         fat_rwlock_unlock(&table->cls.rwlock);
4099
4100         if (overlaps) {
4101             cls_rule_destroy(&cr);
4102             return OFPERR_OFPFMFC_OVERLAP;
4103         }
4104     }
4105
4106     /* If necessary, evict an existing rule to clear out space. */
4107     error = evict_rules_from_table(ofproto, table, 1);
4108     if (error) {
4109         cls_rule_destroy(&cr);
4110         return error;
4111     }
4112
4113     /* Allocate new rule. */
4114     rule = ofproto->ofproto_class->rule_alloc();
4115     if (!rule) {
4116         cls_rule_destroy(&cr);
4117         VLOG_WARN_RL(&rl, "%s: failed to create rule (%s)",
4118                      ofproto->name, ovs_strerror(error));
4119         return ENOMEM;
4120     }
4121
4122     /* Initialize base state. */
4123     *CONST_CAST(struct ofproto **, &rule->ofproto) = ofproto;
4124     cls_rule_move(CONST_CAST(struct cls_rule *, &rule->cr), &cr);
4125     ovs_refcount_init(&rule->ref_count);
4126     rule->pending = NULL;
4127     rule->flow_cookie = fm->new_cookie;
4128     rule->created = rule->modified = time_msec();
4129
4130     ovs_mutex_init(&rule->mutex);
4131     ovs_mutex_lock(&rule->mutex);
4132     rule->idle_timeout = fm->idle_timeout;
4133     rule->hard_timeout = fm->hard_timeout;
4134     ovs_mutex_unlock(&rule->mutex);
4135
4136     *CONST_CAST(uint8_t *, &rule->table_id) = table - ofproto->tables;
4137     rule->flags = fm->flags & OFPUTIL_FF_STATE;
4138     ovsrcu_set(&rule->actions,
4139                rule_actions_create(ofproto, fm->ofpacts, fm->ofpacts_len));
4140     list_init(&rule->meter_list_node);
4141     rule->eviction_group = NULL;
4142     list_init(&rule->expirable);
4143     rule->monitor_flags = 0;
4144     rule->add_seqno = 0;
4145     rule->modify_seqno = 0;
4146
4147     /* Construct rule, initializing derived state. */
4148     error = ofproto->ofproto_class->rule_construct(rule);
4149     if (error) {
4150         ofproto_rule_destroy__(rule);
4151         return error;
4152     }
4153
4154     /* Insert rule. */
4155     do_add_flow(ofproto, ofconn, request, fm->buffer_id, rule);
4156
4157     return error;
4158 }
4159
4160 static void
4161 do_add_flow(struct ofproto *ofproto, struct ofconn *ofconn,
4162             const struct ofp_header *request, uint32_t buffer_id,
4163             struct rule *rule)
4164     OVS_REQUIRES(ofproto_mutex)
4165 {
4166     struct ofopgroup *group;
4167
4168     oftable_insert_rule(rule);
4169
4170     group = ofopgroup_create(ofproto, ofconn, request, buffer_id);
4171     ofoperation_create(group, rule, OFOPERATION_ADD, 0);
4172     ofproto->ofproto_class->rule_insert(rule);
4173     ofopgroup_submit(group);
4174 }
4175 \f
4176 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
4177
4178 /* Modifies the rules listed in 'rules', changing their actions to match those
4179  * in 'fm'.
4180  *
4181  * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
4182  * if any.
4183  *
4184  * Returns 0 on success, otherwise an OpenFlow error code. */
4185 static enum ofperr
4186 modify_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
4187                struct ofputil_flow_mod *fm, const struct ofp_header *request,
4188                const struct rule_collection *rules)
4189     OVS_REQUIRES(ofproto_mutex)
4190 {
4191     enum ofoperation_type type;
4192     struct ofopgroup *group;
4193     enum ofperr error;
4194     size_t i;
4195
4196     type = fm->command == OFPFC_ADD ? OFOPERATION_REPLACE : OFOPERATION_MODIFY;
4197     group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
4198     error = OFPERR_OFPBRC_EPERM;
4199     for (i = 0; i < rules->n; i++) {
4200         struct rule *rule = rules->rules[i];
4201         const struct rule_actions *actions;
4202         struct ofoperation *op;
4203         bool actions_changed;
4204         bool reset_counters;
4205
4206         /* FIXME: Implement OFPFUTIL_FF_RESET_COUNTS */
4207
4208         if (rule_is_modifiable(rule, fm->flags)) {
4209             /* At least one rule is modifiable, don't report EPERM error. */
4210             error = 0;
4211         } else {
4212             continue;
4213         }
4214
4215         actions = rule_get_actions(rule);
4216         actions_changed = !ofpacts_equal(fm->ofpacts, fm->ofpacts_len,
4217                                          actions->ofpacts,
4218                                          actions->ofpacts_len);
4219
4220         op = ofoperation_create(group, rule, type, 0);
4221
4222         if (fm->modify_cookie && fm->new_cookie != OVS_BE64_MAX) {
4223             ofproto_rule_change_cookie(ofproto, rule, fm->new_cookie);
4224         }
4225         if (type == OFOPERATION_REPLACE) {
4226             ovs_mutex_lock(&rule->mutex);
4227             rule->idle_timeout = fm->idle_timeout;
4228             rule->hard_timeout = fm->hard_timeout;
4229             ovs_mutex_unlock(&rule->mutex);
4230
4231             rule->flags = fm->flags & OFPUTIL_FF_STATE;
4232             if (fm->idle_timeout || fm->hard_timeout) {
4233                 if (!rule->eviction_group) {
4234                     eviction_group_add_rule(rule);
4235                 }
4236             } else {
4237                 eviction_group_remove_rule(rule);
4238             }
4239         }
4240
4241         reset_counters = (fm->flags & OFPUTIL_FF_RESET_COUNTS) != 0;
4242         if (actions_changed || reset_counters) {
4243             struct rule_actions *new_actions;
4244
4245             op->actions = rule_get_actions(rule);
4246             new_actions = rule_actions_create(ofproto,
4247                                               fm->ofpacts, fm->ofpacts_len);
4248
4249             ovsrcu_set(&rule->actions, new_actions);
4250
4251             rule->ofproto->ofproto_class->rule_modify_actions(rule,
4252                                                               reset_counters);
4253         } else {
4254             ofoperation_complete(op, 0);
4255         }
4256     }
4257     ofopgroup_submit(group);
4258
4259     return error;
4260 }
4261
4262 static enum ofperr
4263 modify_flows_add(struct ofproto *ofproto, struct ofconn *ofconn,
4264                  struct ofputil_flow_mod *fm, const struct ofp_header *request)
4265     OVS_REQUIRES(ofproto_mutex)
4266 {
4267     if (fm->cookie_mask != htonll(0) || fm->new_cookie == OVS_BE64_MAX) {
4268         return 0;
4269     }
4270     return add_flow(ofproto, ofconn, fm, request);
4271 }
4272
4273 /* Implements OFPFC_MODIFY.  Returns 0 on success or an OpenFlow error code on
4274  * failure.
4275  *
4276  * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
4277  * if any. */
4278 static enum ofperr
4279 modify_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
4280                    struct ofputil_flow_mod *fm,
4281                    const struct ofp_header *request)
4282     OVS_REQUIRES(ofproto_mutex)
4283 {
4284     struct rule_criteria criteria;
4285     struct rule_collection rules;
4286     int error;
4287
4288     rule_criteria_init(&criteria, fm->table_id, &fm->match, 0,
4289                        fm->cookie, fm->cookie_mask, OFPP_ANY, OFPG11_ANY);
4290     error = collect_rules_loose(ofproto, &criteria, &rules);
4291     rule_criteria_destroy(&criteria);
4292
4293     if (!error) {
4294         error = (rules.n > 0
4295                  ? modify_flows__(ofproto, ofconn, fm, request, &rules)
4296                  : modify_flows_add(ofproto, ofconn, fm, request));
4297     }
4298
4299     rule_collection_destroy(&rules);
4300
4301     return error;
4302 }
4303
4304 /* Implements OFPFC_MODIFY_STRICT.  Returns 0 on success or an OpenFlow error
4305  * code on failure.
4306  *
4307  * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
4308  * if any. */
4309 static enum ofperr
4310 modify_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
4311                    struct ofputil_flow_mod *fm,
4312                    const struct ofp_header *request)
4313     OVS_REQUIRES(ofproto_mutex)
4314 {
4315     struct rule_criteria criteria;
4316     struct rule_collection rules;
4317     int error;
4318
4319     rule_criteria_init(&criteria, fm->table_id, &fm->match, fm->priority,
4320                        fm->cookie, fm->cookie_mask, OFPP_ANY, OFPG11_ANY);
4321     error = collect_rules_strict(ofproto, &criteria, &rules);
4322     rule_criteria_destroy(&criteria);
4323
4324     if (!error) {
4325         if (rules.n == 0) {
4326             error =  modify_flows_add(ofproto, ofconn, fm, request);
4327         } else if (rules.n == 1) {
4328             error = modify_flows__(ofproto, ofconn, fm, request, &rules);
4329         }
4330     }
4331
4332     rule_collection_destroy(&rules);
4333
4334     return error;
4335 }
4336 \f
4337 /* OFPFC_DELETE implementation. */
4338
4339 static void
4340 delete_flow__(struct rule *rule, struct ofopgroup *group,
4341               enum ofp_flow_removed_reason reason)
4342     OVS_REQUIRES(ofproto_mutex)
4343 {
4344     struct ofproto *ofproto = rule->ofproto;
4345
4346     ofproto_rule_send_removed(rule, reason);
4347
4348     ofoperation_create(group, rule, OFOPERATION_DELETE, reason);
4349     oftable_remove_rule(rule);
4350     ofproto->ofproto_class->rule_delete(rule);
4351 }
4352
4353 /* Deletes the rules listed in 'rules'.
4354  *
4355  * Returns 0 on success, otherwise an OpenFlow error code. */
4356 static enum ofperr
4357 delete_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
4358                const struct ofp_header *request,
4359                const struct rule_collection *rules,
4360                enum ofp_flow_removed_reason reason)
4361     OVS_REQUIRES(ofproto_mutex)
4362 {
4363     struct ofopgroup *group;
4364     size_t i;
4365
4366     group = ofopgroup_create(ofproto, ofconn, request, UINT32_MAX);
4367     for (i = 0; i < rules->n; i++) {
4368         delete_flow__(rules->rules[i], group, reason);
4369     }
4370     ofopgroup_submit(group);
4371
4372     return 0;
4373 }
4374
4375 /* Implements OFPFC_DELETE. */
4376 static enum ofperr
4377 delete_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
4378                    const struct ofputil_flow_mod *fm,
4379                    const struct ofp_header *request)
4380     OVS_REQUIRES(ofproto_mutex)
4381 {
4382     struct rule_criteria criteria;
4383     struct rule_collection rules;
4384     enum ofperr error;
4385
4386     rule_criteria_init(&criteria, fm->table_id, &fm->match, 0,
4387                        fm->cookie, fm->cookie_mask,
4388                        fm->out_port, fm->out_group);
4389     error = collect_rules_loose(ofproto, &criteria, &rules);
4390     rule_criteria_destroy(&criteria);
4391
4392     if (!error && rules.n > 0) {
4393         error = delete_flows__(ofproto, ofconn, request, &rules, OFPRR_DELETE);
4394     }
4395     rule_collection_destroy(&rules);
4396
4397     return error;
4398 }
4399
4400 /* Implements OFPFC_DELETE_STRICT. */
4401 static enum ofperr
4402 delete_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
4403                    const struct ofputil_flow_mod *fm,
4404                    const struct ofp_header *request)
4405     OVS_REQUIRES(ofproto_mutex)
4406 {
4407     struct rule_criteria criteria;
4408     struct rule_collection rules;
4409     enum ofperr error;
4410
4411     rule_criteria_init(&criteria, fm->table_id, &fm->match, fm->priority,
4412                        fm->cookie, fm->cookie_mask,
4413                        fm->out_port, fm->out_group);
4414     error = collect_rules_strict(ofproto, &criteria, &rules);
4415     rule_criteria_destroy(&criteria);
4416
4417     if (!error && rules.n > 0) {
4418         error = delete_flows__(ofproto, ofconn, request, &rules, OFPRR_DELETE);
4419     }
4420     rule_collection_destroy(&rules);
4421
4422     return error;
4423 }
4424
4425 static void
4426 ofproto_rule_send_removed(struct rule *rule, uint8_t reason)
4427     OVS_REQUIRES(ofproto_mutex)
4428 {
4429     struct ofputil_flow_removed fr;
4430     long long int used;
4431
4432     if (ofproto_rule_is_hidden(rule) ||
4433         !(rule->flags & OFPUTIL_FF_SEND_FLOW_REM)) {
4434         return;
4435     }
4436
4437     minimatch_expand(&rule->cr.match, &fr.match);
4438     fr.priority = rule->cr.priority;
4439     fr.cookie = rule->flow_cookie;
4440     fr.reason = reason;
4441     fr.table_id = rule->table_id;
4442     calc_duration(rule->created, time_msec(),
4443                   &fr.duration_sec, &fr.duration_nsec);
4444     ovs_mutex_lock(&rule->mutex);
4445     fr.idle_timeout = rule->idle_timeout;
4446     fr.hard_timeout = rule->hard_timeout;
4447     ovs_mutex_unlock(&rule->mutex);
4448     rule->ofproto->ofproto_class->rule_get_stats(rule, &fr.packet_count,
4449                                                  &fr.byte_count, &used);
4450
4451     connmgr_send_flow_removed(rule->ofproto->connmgr, &fr);
4452 }
4453
4454 /* Sends an OpenFlow "flow removed" message with the given 'reason' (either
4455  * OFPRR_HARD_TIMEOUT or OFPRR_IDLE_TIMEOUT), and then removes 'rule' from its
4456  * ofproto.
4457  *
4458  * 'rule' must not have a pending operation (that is, 'rule->pending' must be
4459  * NULL).
4460  *
4461  * ofproto implementation ->run() functions should use this function to expire
4462  * OpenFlow flows. */
4463 void
4464 ofproto_rule_expire(struct rule *rule, uint8_t reason)
4465     OVS_REQUIRES(ofproto_mutex)
4466 {
4467     struct ofproto *ofproto = rule->ofproto;
4468
4469     ovs_assert(reason == OFPRR_HARD_TIMEOUT || reason == OFPRR_IDLE_TIMEOUT
4470                || reason == OFPRR_DELETE || reason == OFPRR_GROUP_DELETE);
4471
4472     ofproto_rule_delete__(ofproto, rule, reason);
4473 }
4474
4475 /* Reduces '*timeout' to no more than 'max'.  A value of zero in either case
4476  * means "infinite". */
4477 static void
4478 reduce_timeout(uint16_t max, uint16_t *timeout)
4479 {
4480     if (max && (!*timeout || *timeout > max)) {
4481         *timeout = max;
4482     }
4483 }
4484
4485 /* If 'idle_timeout' is nonzero, and 'rule' has no idle timeout or an idle
4486  * timeout greater than 'idle_timeout', lowers 'rule''s idle timeout to
4487  * 'idle_timeout' seconds.  Similarly for 'hard_timeout'.
4488  *
4489  * Suitable for implementing OFPACT_FIN_TIMEOUT. */
4490 void
4491 ofproto_rule_reduce_timeouts(struct rule *rule,
4492                              uint16_t idle_timeout, uint16_t hard_timeout)
4493     OVS_EXCLUDED(ofproto_mutex, rule->mutex)
4494 {
4495     if (!idle_timeout && !hard_timeout) {
4496         return;
4497     }
4498
4499     ovs_mutex_lock(&ofproto_mutex);
4500     if (list_is_empty(&rule->expirable)) {
4501         list_insert(&rule->ofproto->expirable, &rule->expirable);
4502     }
4503     ovs_mutex_unlock(&ofproto_mutex);
4504
4505     ovs_mutex_lock(&rule->mutex);
4506     reduce_timeout(idle_timeout, &rule->idle_timeout);
4507     reduce_timeout(hard_timeout, &rule->hard_timeout);
4508     ovs_mutex_unlock(&rule->mutex);
4509 }
4510 \f
4511 static enum ofperr
4512 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
4513     OVS_EXCLUDED(ofproto_mutex)
4514 {
4515     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4516     struct ofputil_flow_mod fm;
4517     uint64_t ofpacts_stub[1024 / 8];
4518     struct ofpbuf ofpacts;
4519     enum ofperr error;
4520     long long int now;
4521
4522     error = reject_slave_controller(ofconn);
4523     if (error) {
4524         goto exit;
4525     }
4526
4527     ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
4528     error = ofputil_decode_flow_mod(&fm, oh, ofconn_get_protocol(ofconn),
4529                                     &ofpacts,
4530                                     u16_to_ofp(ofproto->max_ports),
4531                                     ofproto->n_tables);
4532     if (!error) {
4533         error = ofproto_check_ofpacts(ofproto, fm.ofpacts, fm.ofpacts_len);
4534     }
4535     if (!error) {
4536         error = handle_flow_mod__(ofproto, ofconn, &fm, oh);
4537     }
4538     if (error) {
4539         goto exit_free_ofpacts;
4540     }
4541
4542     /* Record the operation for logging a summary report. */
4543     switch (fm.command) {
4544     case OFPFC_ADD:
4545         ofproto->n_add++;
4546         break;
4547
4548     case OFPFC_MODIFY:
4549     case OFPFC_MODIFY_STRICT:
4550         ofproto->n_modify++;
4551         break;
4552
4553     case OFPFC_DELETE:
4554     case OFPFC_DELETE_STRICT:
4555         ofproto->n_delete++;
4556         break;
4557     }
4558
4559     now = time_msec();
4560     if (ofproto->next_op_report == LLONG_MAX) {
4561         ofproto->first_op = now;
4562         ofproto->next_op_report = MAX(now + 10 * 1000,
4563                                       ofproto->op_backoff);
4564         ofproto->op_backoff = ofproto->next_op_report + 60 * 1000;
4565     }
4566     ofproto->last_op = now;
4567
4568 exit_free_ofpacts:
4569     ofpbuf_uninit(&ofpacts);
4570 exit:
4571     return error;
4572 }
4573
4574 static enum ofperr
4575 handle_flow_mod__(struct ofproto *ofproto, struct ofconn *ofconn,
4576                   struct ofputil_flow_mod *fm, const struct ofp_header *oh)
4577     OVS_EXCLUDED(ofproto_mutex)
4578 {
4579     enum ofperr error;
4580
4581     ovs_mutex_lock(&ofproto_mutex);
4582     if (ofproto->n_pending < 50) {
4583         switch (fm->command) {
4584         case OFPFC_ADD:
4585             error = add_flow(ofproto, ofconn, fm, oh);
4586             break;
4587
4588         case OFPFC_MODIFY:
4589             error = modify_flows_loose(ofproto, ofconn, fm, oh);
4590             break;
4591
4592         case OFPFC_MODIFY_STRICT:
4593             error = modify_flow_strict(ofproto, ofconn, fm, oh);
4594             break;
4595
4596         case OFPFC_DELETE:
4597             error = delete_flows_loose(ofproto, ofconn, fm, oh);
4598             break;
4599
4600         case OFPFC_DELETE_STRICT:
4601             error = delete_flow_strict(ofproto, ofconn, fm, oh);
4602             break;
4603
4604         default:
4605             if (fm->command > 0xff) {
4606                 VLOG_WARN_RL(&rl, "%s: flow_mod has explicit table_id but "
4607                              "flow_mod_table_id extension is not enabled",
4608                              ofproto->name);
4609             }
4610             error = OFPERR_OFPFMFC_BAD_COMMAND;
4611             break;
4612         }
4613     } else {
4614         ovs_assert(!list_is_empty(&ofproto->pending));
4615         error = OFPROTO_POSTPONE;
4616     }
4617     ovs_mutex_unlock(&ofproto_mutex);
4618
4619     run_rule_executes(ofproto);
4620     return error;
4621 }
4622
4623 static enum ofperr
4624 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
4625 {
4626     struct ofputil_role_request request;
4627     struct ofputil_role_request reply;
4628     struct ofpbuf *buf;
4629     enum ofperr error;
4630
4631     error = ofputil_decode_role_message(oh, &request);
4632     if (error) {
4633         return error;
4634     }
4635
4636     if (request.role != OFPCR12_ROLE_NOCHANGE) {
4637         if (ofconn_get_role(ofconn) != request.role
4638             && ofconn_has_pending_opgroups(ofconn)) {
4639             return OFPROTO_POSTPONE;
4640         }
4641
4642         if (request.have_generation_id
4643             && !ofconn_set_master_election_id(ofconn, request.generation_id)) {
4644                 return OFPERR_OFPRRFC_STALE;
4645         }
4646
4647         ofconn_set_role(ofconn, request.role);
4648     }
4649
4650     reply.role = ofconn_get_role(ofconn);
4651     reply.have_generation_id = ofconn_get_master_election_id(
4652         ofconn, &reply.generation_id);
4653     buf = ofputil_encode_role_reply(oh, &reply);
4654     ofconn_send_reply(ofconn, buf);
4655
4656     return 0;
4657 }
4658
4659 static enum ofperr
4660 handle_nxt_flow_mod_table_id(struct ofconn *ofconn,
4661                              const struct ofp_header *oh)
4662 {
4663     const struct nx_flow_mod_table_id *msg = ofpmsg_body(oh);
4664     enum ofputil_protocol cur, next;
4665
4666     cur = ofconn_get_protocol(ofconn);
4667     next = ofputil_protocol_set_tid(cur, msg->set != 0);
4668     ofconn_set_protocol(ofconn, next);
4669
4670     return 0;
4671 }
4672
4673 static enum ofperr
4674 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
4675 {
4676     const struct nx_set_flow_format *msg = ofpmsg_body(oh);
4677     enum ofputil_protocol cur, next;
4678     enum ofputil_protocol next_base;
4679
4680     next_base = ofputil_nx_flow_format_to_protocol(ntohl(msg->format));
4681     if (!next_base) {
4682         return OFPERR_OFPBRC_EPERM;
4683     }
4684
4685     cur = ofconn_get_protocol(ofconn);
4686     next = ofputil_protocol_set_base(cur, next_base);
4687     if (cur != next && ofconn_has_pending_opgroups(ofconn)) {
4688         /* Avoid sending async messages in surprising protocol. */
4689         return OFPROTO_POSTPONE;
4690     }
4691
4692     ofconn_set_protocol(ofconn, next);
4693     return 0;
4694 }
4695
4696 static enum ofperr
4697 handle_nxt_set_packet_in_format(struct ofconn *ofconn,
4698                                 const struct ofp_header *oh)
4699 {
4700     const struct nx_set_packet_in_format *msg = ofpmsg_body(oh);
4701     uint32_t format;
4702
4703     format = ntohl(msg->format);
4704     if (format != NXPIF_OPENFLOW10 && format != NXPIF_NXM) {
4705         return OFPERR_OFPBRC_EPERM;
4706     }
4707
4708     if (format != ofconn_get_packet_in_format(ofconn)
4709         && ofconn_has_pending_opgroups(ofconn)) {
4710         /* Avoid sending async message in surprsing packet in format. */
4711         return OFPROTO_POSTPONE;
4712     }
4713
4714     ofconn_set_packet_in_format(ofconn, format);
4715     return 0;
4716 }
4717
4718 static enum ofperr
4719 handle_nxt_set_async_config(struct ofconn *ofconn, const struct ofp_header *oh)
4720 {
4721     const struct nx_async_config *msg = ofpmsg_body(oh);
4722     uint32_t master[OAM_N_TYPES];
4723     uint32_t slave[OAM_N_TYPES];
4724
4725     master[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[0]);
4726     master[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[0]);
4727     master[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[0]);
4728
4729     slave[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[1]);
4730     slave[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[1]);
4731     slave[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[1]);
4732
4733     ofconn_set_async_config(ofconn, master, slave);
4734     if (ofconn_get_type(ofconn) == OFCONN_SERVICE &&
4735         !ofconn_get_miss_send_len(ofconn)) {
4736         ofconn_set_miss_send_len(ofconn, OFP_DEFAULT_MISS_SEND_LEN);
4737     }
4738
4739     return 0;
4740 }
4741
4742 static enum ofperr
4743 handle_nxt_get_async_request(struct ofconn *ofconn, const struct ofp_header *oh)
4744 {
4745     struct ofpbuf *buf;
4746     uint32_t master[OAM_N_TYPES];
4747     uint32_t slave[OAM_N_TYPES];
4748     struct nx_async_config *msg;
4749
4750     ofconn_get_async_config(ofconn, master, slave);
4751     buf = ofpraw_alloc_reply(OFPRAW_OFPT13_GET_ASYNC_REPLY, oh, 0);
4752     msg = ofpbuf_put_zeros(buf, sizeof *msg);
4753
4754     msg->packet_in_mask[0] = htonl(master[OAM_PACKET_IN]);
4755     msg->port_status_mask[0] = htonl(master[OAM_PORT_STATUS]);
4756     msg->flow_removed_mask[0] = htonl(master[OAM_FLOW_REMOVED]);
4757
4758     msg->packet_in_mask[1] = htonl(slave[OAM_PACKET_IN]);
4759     msg->port_status_mask[1] = htonl(slave[OAM_PORT_STATUS]);
4760     msg->flow_removed_mask[1] = htonl(slave[OAM_FLOW_REMOVED]);
4761
4762     ofconn_send_reply(ofconn, buf);
4763
4764     return 0;
4765 }
4766
4767 static enum ofperr
4768 handle_nxt_set_controller_id(struct ofconn *ofconn,
4769                              const struct ofp_header *oh)
4770 {
4771     const struct nx_controller_id *nci = ofpmsg_body(oh);
4772
4773     if (!is_all_zeros(nci->zero, sizeof nci->zero)) {
4774         return OFPERR_NXBRC_MUST_BE_ZERO;
4775     }
4776
4777     ofconn_set_controller_id(ofconn, ntohs(nci->controller_id));
4778     return 0;
4779 }
4780
4781 static enum ofperr
4782 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
4783 {
4784     struct ofpbuf *buf;
4785
4786     if (ofconn_has_pending_opgroups(ofconn)) {
4787         return OFPROTO_POSTPONE;
4788     }
4789
4790     buf = ofpraw_alloc_reply((oh->version == OFP10_VERSION
4791                               ? OFPRAW_OFPT10_BARRIER_REPLY
4792                               : OFPRAW_OFPT11_BARRIER_REPLY), oh, 0);
4793     ofconn_send_reply(ofconn, buf);
4794     return 0;
4795 }
4796
4797 static void
4798 ofproto_compose_flow_refresh_update(const struct rule *rule,
4799                                     enum nx_flow_monitor_flags flags,
4800                                     struct list *msgs)
4801     OVS_REQUIRES(ofproto_mutex)
4802 {
4803     struct ofoperation *op = rule->pending;
4804     const struct rule_actions *actions;
4805     struct ofputil_flow_update fu;
4806     struct match match;
4807
4808     if (op && op->type == OFOPERATION_ADD) {
4809         /* We'll report the final flow when the operation completes.  Reporting
4810          * it now would cause a duplicate report later. */
4811         return;
4812     }
4813
4814     fu.event = (flags & (NXFMF_INITIAL | NXFMF_ADD)
4815                 ? NXFME_ADDED : NXFME_MODIFIED);
4816     fu.reason = 0;
4817     ovs_mutex_lock(&rule->mutex);
4818     fu.idle_timeout = rule->idle_timeout;
4819     fu.hard_timeout = rule->hard_timeout;
4820     ovs_mutex_unlock(&rule->mutex);
4821     fu.table_id = rule->table_id;
4822     fu.cookie = rule->flow_cookie;
4823     minimatch_expand(&rule->cr.match, &match);
4824     fu.match = &match;
4825     fu.priority = rule->cr.priority;
4826
4827     if (!(flags & NXFMF_ACTIONS)) {
4828         actions = NULL;
4829     } else if (!op) {
4830         actions = rule_get_actions(rule);
4831     } else {
4832         /* An operation is in progress.  Use the previous version of the flow's
4833          * actions, so that when the operation commits we report the change. */
4834         switch (op->type) {
4835         case OFOPERATION_ADD:
4836             OVS_NOT_REACHED();
4837
4838         case OFOPERATION_MODIFY:
4839         case OFOPERATION_REPLACE:
4840             actions = op->actions ? op->actions : rule_get_actions(rule);
4841             break;
4842
4843         case OFOPERATION_DELETE:
4844             actions = rule_get_actions(rule);
4845             break;
4846
4847         default:
4848             OVS_NOT_REACHED();
4849         }
4850     }
4851     fu.ofpacts = actions ? actions->ofpacts : NULL;
4852     fu.ofpacts_len = actions ? actions->ofpacts_len : 0;
4853
4854     if (list_is_empty(msgs)) {
4855         ofputil_start_flow_update(msgs);
4856     }
4857     ofputil_append_flow_update(&fu, msgs);
4858 }
4859
4860 void
4861 ofmonitor_compose_refresh_updates(struct rule_collection *rules,
4862                                   struct list *msgs)
4863     OVS_REQUIRES(ofproto_mutex)
4864 {
4865     size_t i;
4866
4867     for (i = 0; i < rules->n; i++) {
4868         struct rule *rule = rules->rules[i];
4869         enum nx_flow_monitor_flags flags = rule->monitor_flags;
4870         rule->monitor_flags = 0;
4871
4872         ofproto_compose_flow_refresh_update(rule, flags, msgs);
4873     }
4874 }
4875
4876 static void
4877 ofproto_collect_ofmonitor_refresh_rule(const struct ofmonitor *m,
4878                                        struct rule *rule, uint64_t seqno,
4879                                        struct rule_collection *rules)
4880     OVS_REQUIRES(ofproto_mutex)
4881 {
4882     enum nx_flow_monitor_flags update;
4883
4884     if (ofproto_rule_is_hidden(rule)) {
4885         return;
4886     }
4887
4888     if (!(rule->pending
4889           ? ofoperation_has_out_port(rule->pending, m->out_port)
4890           : ofproto_rule_has_out_port(rule, m->out_port))) {
4891         return;
4892     }
4893
4894     if (seqno) {
4895         if (rule->add_seqno > seqno) {
4896             update = NXFMF_ADD | NXFMF_MODIFY;
4897         } else if (rule->modify_seqno > seqno) {
4898             update = NXFMF_MODIFY;
4899         } else {
4900             return;
4901         }
4902
4903         if (!(m->flags & update)) {
4904             return;
4905         }
4906     } else {
4907         update = NXFMF_INITIAL;
4908     }
4909
4910     if (!rule->monitor_flags) {
4911         rule_collection_add(rules, rule);
4912     }
4913     rule->monitor_flags |= update | (m->flags & NXFMF_ACTIONS);
4914 }
4915
4916 static void
4917 ofproto_collect_ofmonitor_refresh_rules(const struct ofmonitor *m,
4918                                         uint64_t seqno,
4919                                         struct rule_collection *rules)
4920     OVS_REQUIRES(ofproto_mutex)
4921 {
4922     const struct ofproto *ofproto = ofconn_get_ofproto(m->ofconn);
4923     const struct ofoperation *op;
4924     const struct oftable *table;
4925     struct cls_rule target;
4926
4927     cls_rule_init_from_minimatch(&target, &m->match, 0);
4928     FOR_EACH_MATCHING_TABLE (table, m->table_id, ofproto) {
4929         struct cls_cursor cursor;
4930         struct rule *rule;
4931
4932         fat_rwlock_rdlock(&table->cls.rwlock);
4933         cls_cursor_init(&cursor, &table->cls, &target);
4934         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4935             ovs_assert(!rule->pending); /* XXX */
4936             ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
4937         }
4938         fat_rwlock_unlock(&table->cls.rwlock);
4939     }
4940
4941     HMAP_FOR_EACH (op, hmap_node, &ofproto->deletions) {
4942         struct rule *rule = op->rule;
4943
4944         if (((m->table_id == 0xff
4945               ? !(ofproto->tables[rule->table_id].flags & OFTABLE_HIDDEN)
4946               : m->table_id == rule->table_id))
4947             && cls_rule_is_loose_match(&rule->cr, &target.match)) {
4948             ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
4949         }
4950     }
4951     cls_rule_destroy(&target);
4952 }
4953
4954 static void
4955 ofproto_collect_ofmonitor_initial_rules(struct ofmonitor *m,
4956                                         struct rule_collection *rules)
4957     OVS_REQUIRES(ofproto_mutex)
4958 {
4959     if (m->flags & NXFMF_INITIAL) {
4960         ofproto_collect_ofmonitor_refresh_rules(m, 0, rules);
4961     }
4962 }
4963
4964 void
4965 ofmonitor_collect_resume_rules(struct ofmonitor *m,
4966                                uint64_t seqno, struct rule_collection *rules)
4967     OVS_REQUIRES(ofproto_mutex)
4968 {
4969     ofproto_collect_ofmonitor_refresh_rules(m, seqno, rules);
4970 }
4971
4972 static enum ofperr
4973 handle_flow_monitor_request(struct ofconn *ofconn, const struct ofp_header *oh)
4974     OVS_EXCLUDED(ofproto_mutex)
4975 {
4976     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4977     struct ofmonitor **monitors;
4978     size_t n_monitors, allocated_monitors;
4979     struct rule_collection rules;
4980     struct list replies;
4981     enum ofperr error;
4982     struct ofpbuf b;
4983     size_t i;
4984
4985     error = 0;
4986     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4987     monitors = NULL;
4988     n_monitors = allocated_monitors = 0;
4989
4990     ovs_mutex_lock(&ofproto_mutex);
4991     for (;;) {
4992         struct ofputil_flow_monitor_request request;
4993         struct ofmonitor *m;
4994         int retval;
4995
4996         retval = ofputil_decode_flow_monitor_request(&request, &b);
4997         if (retval == EOF) {
4998             break;
4999         } else if (retval) {
5000             error = retval;
5001             goto error;
5002         }
5003
5004         if (request.table_id != 0xff
5005             && request.table_id >= ofproto->n_tables) {
5006             error = OFPERR_OFPBRC_BAD_TABLE_ID;
5007             goto error;
5008         }
5009
5010         error = ofmonitor_create(&request, ofconn, &m);
5011         if (error) {
5012             goto error;
5013         }
5014
5015         if (n_monitors >= allocated_monitors) {
5016             monitors = x2nrealloc(monitors, &allocated_monitors,
5017                                   sizeof *monitors);
5018         }
5019         monitors[n_monitors++] = m;
5020     }
5021
5022     rule_collection_init(&rules);
5023     for (i = 0; i < n_monitors; i++) {
5024         ofproto_collect_ofmonitor_initial_rules(monitors[i], &rules);
5025     }
5026
5027     ofpmp_init(&replies, oh);
5028     ofmonitor_compose_refresh_updates(&rules, &replies);
5029     ovs_mutex_unlock(&ofproto_mutex);
5030
5031     rule_collection_destroy(&rules);
5032
5033     ofconn_send_replies(ofconn, &replies);
5034     free(monitors);
5035
5036     return 0;
5037
5038 error:
5039     for (i = 0; i < n_monitors; i++) {
5040         ofmonitor_destroy(monitors[i]);
5041     }
5042     free(monitors);
5043     ovs_mutex_unlock(&ofproto_mutex);
5044
5045     return error;
5046 }
5047
5048 static enum ofperr
5049 handle_flow_monitor_cancel(struct ofconn *ofconn, const struct ofp_header *oh)
5050     OVS_EXCLUDED(ofproto_mutex)
5051 {
5052     struct ofmonitor *m;
5053     enum ofperr error;
5054     uint32_t id;
5055
5056     id = ofputil_decode_flow_monitor_cancel(oh);
5057
5058     ovs_mutex_lock(&ofproto_mutex);
5059     m = ofmonitor_lookup(ofconn, id);
5060     if (m) {
5061         ofmonitor_destroy(m);
5062         error = 0;
5063     } else {
5064         error = OFPERR_NXBRC_FM_BAD_ID;
5065     }
5066     ovs_mutex_unlock(&ofproto_mutex);
5067
5068     return error;
5069 }
5070
5071 /* Meters implementation.
5072  *
5073  * Meter table entry, indexed by the OpenFlow meter_id.
5074  * These are always dynamically allocated to allocate enough space for
5075  * the bands.
5076  * 'created' is used to compute the duration for meter stats.
5077  * 'list rules' is needed so that we can delete the dependent rules when the
5078  * meter table entry is deleted.
5079  * 'provider_meter_id' is for the provider's private use.
5080  */
5081 struct meter {
5082     long long int created;      /* Time created. */
5083     struct list rules;          /* List of "struct rule_dpif"s. */
5084     ofproto_meter_id provider_meter_id;
5085     uint16_t flags;             /* Meter flags. */
5086     uint16_t n_bands;           /* Number of meter bands. */
5087     struct ofputil_meter_band *bands;
5088 };
5089
5090 /*
5091  * This is used in instruction validation at flow set-up time,
5092  * as flows may not use non-existing meters.
5093  * Return value of UINT32_MAX signifies an invalid meter.
5094  */
5095 static uint32_t
5096 get_provider_meter_id(const struct ofproto *ofproto, uint32_t of_meter_id)
5097 {
5098     if (of_meter_id && of_meter_id <= ofproto->meter_features.max_meters) {
5099         const struct meter *meter = ofproto->meters[of_meter_id];
5100         if (meter) {
5101             return meter->provider_meter_id.uint32;
5102         }
5103     }
5104     return UINT32_MAX;
5105 }
5106
5107 static void
5108 meter_update(struct meter *meter, const struct ofputil_meter_config *config)
5109 {
5110     free(meter->bands);
5111
5112     meter->flags = config->flags;
5113     meter->n_bands = config->n_bands;
5114     meter->bands = xmemdup(config->bands,
5115                            config->n_bands * sizeof *meter->bands);
5116 }
5117
5118 static struct meter *
5119 meter_create(const struct ofputil_meter_config *config,
5120              ofproto_meter_id provider_meter_id)
5121 {
5122     struct meter *meter;
5123
5124     meter = xzalloc(sizeof *meter);
5125     meter->provider_meter_id = provider_meter_id;
5126     meter->created = time_msec();
5127     list_init(&meter->rules);
5128
5129     meter_update(meter, config);
5130
5131     return meter;
5132 }
5133
5134 static void
5135 meter_delete(struct ofproto *ofproto, uint32_t first, uint32_t last)
5136     OVS_REQUIRES(ofproto_mutex)
5137 {
5138     uint32_t mid;
5139     for (mid = first; mid <= last; ++mid) {
5140         struct meter *meter = ofproto->meters[mid];
5141         if (meter) {
5142             ofproto->meters[mid] = NULL;
5143             ofproto->ofproto_class->meter_del(ofproto,
5144                                               meter->provider_meter_id);
5145             free(meter->bands);
5146             free(meter);
5147         }
5148     }
5149 }
5150
5151 static enum ofperr
5152 handle_add_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
5153 {
5154     ofproto_meter_id provider_meter_id = { UINT32_MAX };
5155     struct meter **meterp = &ofproto->meters[mm->meter.meter_id];
5156     enum ofperr error;
5157
5158     if (*meterp) {
5159         return OFPERR_OFPMMFC_METER_EXISTS;
5160     }
5161
5162     error = ofproto->ofproto_class->meter_set(ofproto, &provider_meter_id,
5163                                               &mm->meter);
5164     if (!error) {
5165         ovs_assert(provider_meter_id.uint32 != UINT32_MAX);
5166         *meterp = meter_create(&mm->meter, provider_meter_id);
5167     }
5168     return error;
5169 }
5170
5171 static enum ofperr
5172 handle_modify_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
5173 {
5174     struct meter *meter = ofproto->meters[mm->meter.meter_id];
5175     enum ofperr error;
5176     uint32_t provider_meter_id;
5177
5178     if (!meter) {
5179         return OFPERR_OFPMMFC_UNKNOWN_METER;
5180     }
5181
5182     provider_meter_id = meter->provider_meter_id.uint32;
5183     error = ofproto->ofproto_class->meter_set(ofproto,
5184                                               &meter->provider_meter_id,
5185                                               &mm->meter);
5186     ovs_assert(meter->provider_meter_id.uint32 == provider_meter_id);
5187     if (!error) {
5188         meter_update(meter, &mm->meter);
5189     }
5190     return error;
5191 }
5192
5193 static enum ofperr
5194 handle_delete_meter(struct ofconn *ofconn, const struct ofp_header *oh,
5195                     struct ofputil_meter_mod *mm)
5196     OVS_EXCLUDED(ofproto_mutex)
5197 {
5198     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5199     uint32_t meter_id = mm->meter.meter_id;
5200     struct rule_collection rules;
5201     enum ofperr error = 0;
5202     uint32_t first, last;
5203
5204     if (meter_id == OFPM13_ALL) {
5205         first = 1;
5206         last = ofproto->meter_features.max_meters;
5207     } else {
5208         if (!meter_id || meter_id > ofproto->meter_features.max_meters) {
5209             return 0;
5210         }
5211         first = last = meter_id;
5212     }
5213
5214     /* First delete the rules that use this meter.  If any of those rules are
5215      * currently being modified, postpone the whole operation until later. */
5216     rule_collection_init(&rules);
5217     ovs_mutex_lock(&ofproto_mutex);
5218     for (meter_id = first; meter_id <= last; ++meter_id) {
5219         struct meter *meter = ofproto->meters[meter_id];
5220         if (meter && !list_is_empty(&meter->rules)) {
5221             struct rule *rule;
5222
5223             LIST_FOR_EACH (rule, meter_list_node, &meter->rules) {
5224                 if (rule->pending) {
5225                     error = OFPROTO_POSTPONE;
5226                     goto exit;
5227                 }
5228                 rule_collection_add(&rules, rule);
5229             }
5230         }
5231     }
5232     if (rules.n > 0) {
5233         delete_flows__(ofproto, ofconn, oh, &rules, OFPRR_METER_DELETE);
5234     }
5235
5236     /* Delete the meters. */
5237     meter_delete(ofproto, first, last);
5238
5239 exit:
5240     ovs_mutex_unlock(&ofproto_mutex);
5241     rule_collection_destroy(&rules);
5242
5243     return error;
5244 }
5245
5246 static enum ofperr
5247 handle_meter_mod(struct ofconn *ofconn, const struct ofp_header *oh)
5248 {
5249     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5250     struct ofputil_meter_mod mm;
5251     uint64_t bands_stub[256 / 8];
5252     struct ofpbuf bands;
5253     uint32_t meter_id;
5254     enum ofperr error;
5255
5256     error = reject_slave_controller(ofconn);
5257     if (error) {
5258         return error;
5259     }
5260
5261     ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
5262
5263     error = ofputil_decode_meter_mod(oh, &mm, &bands);
5264     if (error) {
5265         goto exit_free_bands;
5266     }
5267
5268     meter_id = mm.meter.meter_id;
5269
5270     if (mm.command != OFPMC13_DELETE) {
5271         /* Fails also when meters are not implemented by the provider. */
5272         if (meter_id == 0 || meter_id > OFPM13_MAX) {
5273             error = OFPERR_OFPMMFC_INVALID_METER;
5274             goto exit_free_bands;
5275         } else if (meter_id > ofproto->meter_features.max_meters) {
5276             error = OFPERR_OFPMMFC_OUT_OF_METERS;
5277             goto exit_free_bands;
5278         }
5279         if (mm.meter.n_bands > ofproto->meter_features.max_bands) {
5280             error = OFPERR_OFPMMFC_OUT_OF_BANDS;
5281             goto exit_free_bands;
5282         }
5283     }
5284
5285     switch (mm.command) {
5286     case OFPMC13_ADD:
5287         error = handle_add_meter(ofproto, &mm);
5288         break;
5289
5290     case OFPMC13_MODIFY:
5291         error = handle_modify_meter(ofproto, &mm);
5292         break;
5293
5294     case OFPMC13_DELETE:
5295         error = handle_delete_meter(ofconn, oh, &mm);
5296         break;
5297
5298     default:
5299         error = OFPERR_OFPMMFC_BAD_COMMAND;
5300         break;
5301     }
5302
5303 exit_free_bands:
5304     ofpbuf_uninit(&bands);
5305     return error;
5306 }
5307
5308 static enum ofperr
5309 handle_meter_features_request(struct ofconn *ofconn,
5310                               const struct ofp_header *request)
5311 {
5312     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5313     struct ofputil_meter_features features;
5314     struct ofpbuf *b;
5315
5316     if (ofproto->ofproto_class->meter_get_features) {
5317         ofproto->ofproto_class->meter_get_features(ofproto, &features);
5318     } else {
5319         memset(&features, 0, sizeof features);
5320     }
5321     b = ofputil_encode_meter_features_reply(&features, request);
5322
5323     ofconn_send_reply(ofconn, b);
5324     return 0;
5325 }
5326
5327 static enum ofperr
5328 handle_meter_request(struct ofconn *ofconn, const struct ofp_header *request,
5329                      enum ofptype type)
5330 {
5331     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5332     struct list replies;
5333     uint64_t bands_stub[256 / 8];
5334     struct ofpbuf bands;
5335     uint32_t meter_id, first, last;
5336
5337     ofputil_decode_meter_request(request, &meter_id);
5338
5339     if (meter_id == OFPM13_ALL) {
5340         first = 1;
5341         last = ofproto->meter_features.max_meters;
5342     } else {
5343         if (!meter_id || meter_id > ofproto->meter_features.max_meters ||
5344             !ofproto->meters[meter_id]) {
5345             return OFPERR_OFPMMFC_UNKNOWN_METER;
5346         }
5347         first = last = meter_id;
5348     }
5349
5350     ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
5351     ofpmp_init(&replies, request);
5352
5353     for (meter_id = first; meter_id <= last; ++meter_id) {
5354         struct meter *meter = ofproto->meters[meter_id];
5355         if (!meter) {
5356             continue; /* Skip non-existing meters. */
5357         }
5358         if (type == OFPTYPE_METER_STATS_REQUEST) {
5359             struct ofputil_meter_stats stats;
5360
5361             stats.meter_id = meter_id;
5362
5363             /* Provider sets the packet and byte counts, we do the rest. */
5364             stats.flow_count = list_size(&meter->rules);
5365             calc_duration(meter->created, time_msec(),
5366                           &stats.duration_sec, &stats.duration_nsec);
5367             stats.n_bands = meter->n_bands;
5368             ofpbuf_clear(&bands);
5369             stats.bands
5370                 = ofpbuf_put_uninit(&bands,
5371                                     meter->n_bands * sizeof *stats.bands);
5372
5373             if (!ofproto->ofproto_class->meter_get(ofproto,
5374                                                    meter->provider_meter_id,
5375                                                    &stats)) {
5376                 ofputil_append_meter_stats(&replies, &stats);
5377             }
5378         } else { /* type == OFPTYPE_METER_CONFIG_REQUEST */
5379             struct ofputil_meter_config config;
5380
5381             config.meter_id = meter_id;
5382             config.flags = meter->flags;
5383             config.n_bands = meter->n_bands;
5384             config.bands = meter->bands;
5385             ofputil_append_meter_config(&replies, &config);
5386         }
5387     }
5388
5389     ofconn_send_replies(ofconn, &replies);
5390     ofpbuf_uninit(&bands);
5391     return 0;
5392 }
5393
5394 bool
5395 ofproto_group_lookup(const struct ofproto *ofproto, uint32_t group_id,
5396                      struct ofgroup **group)
5397     OVS_TRY_RDLOCK(true, (*group)->rwlock)
5398 {
5399     ovs_rwlock_rdlock(&ofproto->groups_rwlock);
5400     HMAP_FOR_EACH_IN_BUCKET (*group, hmap_node,
5401                              hash_int(group_id, 0), &ofproto->groups) {
5402         if ((*group)->group_id == group_id) {
5403             ovs_rwlock_rdlock(&(*group)->rwlock);
5404             ovs_rwlock_unlock(&ofproto->groups_rwlock);
5405             return true;
5406         }
5407     }
5408     ovs_rwlock_unlock(&ofproto->groups_rwlock);
5409     return false;
5410 }
5411
5412 void
5413 ofproto_group_release(struct ofgroup *group)
5414     OVS_RELEASES(group->rwlock)
5415 {
5416     ovs_rwlock_unlock(&group->rwlock);
5417 }
5418
5419 static bool
5420 ofproto_group_write_lookup(const struct ofproto *ofproto, uint32_t group_id,
5421                            struct ofgroup **group)
5422     OVS_TRY_WRLOCK(true, ofproto->groups_rwlock)
5423     OVS_TRY_WRLOCK(true, (*group)->rwlock)
5424 {
5425     ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5426     HMAP_FOR_EACH_IN_BUCKET (*group, hmap_node,
5427                              hash_int(group_id, 0), &ofproto->groups) {
5428         if ((*group)->group_id == group_id) {
5429             ovs_rwlock_wrlock(&(*group)->rwlock);
5430             return true;
5431         }
5432     }
5433     ovs_rwlock_unlock(&ofproto->groups_rwlock);
5434     return false;
5435 }
5436
5437 static bool
5438 ofproto_group_exists__(const struct ofproto *ofproto, uint32_t group_id)
5439     OVS_REQ_RDLOCK(ofproto->groups_rwlock)
5440 {
5441     struct ofgroup *grp;
5442
5443     HMAP_FOR_EACH_IN_BUCKET (grp, hmap_node,
5444                              hash_int(group_id, 0), &ofproto->groups) {
5445         if (grp->group_id == group_id) {
5446             return true;
5447         }
5448     }
5449     return false;
5450 }
5451
5452 static bool
5453 ofproto_group_exists(const struct ofproto *ofproto, uint32_t group_id)
5454     OVS_EXCLUDED(ofproto->groups_rwlock)
5455 {
5456     bool exists;
5457
5458     ovs_rwlock_rdlock(&ofproto->groups_rwlock);
5459     exists = ofproto_group_exists__(ofproto, group_id);
5460     ovs_rwlock_unlock(&ofproto->groups_rwlock);
5461
5462     return exists;
5463 }
5464
5465 static uint32_t
5466 group_get_ref_count(struct ofgroup *group)
5467     OVS_EXCLUDED(ofproto_mutex)
5468 {
5469     struct ofproto *ofproto = group->ofproto;
5470     struct rule_criteria criteria;
5471     struct rule_collection rules;
5472     struct match match;
5473     enum ofperr error;
5474     uint32_t count;
5475
5476     match_init_catchall(&match);
5477     rule_criteria_init(&criteria, 0xff, &match, 0, htonll(0), htonll(0),
5478                        OFPP_ANY, group->group_id);
5479     ovs_mutex_lock(&ofproto_mutex);
5480     error = collect_rules_loose(ofproto, &criteria, &rules);
5481     ovs_mutex_unlock(&ofproto_mutex);
5482     rule_criteria_destroy(&criteria);
5483
5484     count = !error && rules.n < UINT32_MAX ? rules.n : UINT32_MAX;
5485
5486     rule_collection_destroy(&rules);
5487     return count;
5488 }
5489
5490 static void
5491 append_group_stats(struct ofgroup *group, struct list *replies)
5492     OVS_REQ_RDLOCK(group->rwlock)
5493 {
5494     struct ofputil_group_stats ogs;
5495     struct ofproto *ofproto = group->ofproto;
5496     long long int now = time_msec();
5497     int error;
5498
5499     ogs.bucket_stats = xmalloc(group->n_buckets * sizeof *ogs.bucket_stats);
5500
5501     /* Provider sets the packet and byte counts, we do the rest. */
5502     ogs.ref_count = group_get_ref_count(group);
5503     ogs.n_buckets = group->n_buckets;
5504
5505     error = (ofproto->ofproto_class->group_get_stats
5506              ? ofproto->ofproto_class->group_get_stats(group, &ogs)
5507              : EOPNOTSUPP);
5508     if (error) {
5509         ogs.packet_count = UINT64_MAX;
5510         ogs.byte_count = UINT64_MAX;
5511         memset(ogs.bucket_stats, 0xff,
5512                ogs.n_buckets * sizeof *ogs.bucket_stats);
5513     }
5514
5515     ogs.group_id = group->group_id;
5516     calc_duration(group->created, now, &ogs.duration_sec, &ogs.duration_nsec);
5517
5518     ofputil_append_group_stats(replies, &ogs);
5519
5520     free(ogs.bucket_stats);
5521 }
5522
5523 static enum ofperr
5524 handle_group_stats_request(struct ofconn *ofconn,
5525                            const struct ofp_header *request)
5526 {
5527     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5528     struct list replies;
5529     enum ofperr error;
5530     struct ofgroup *group;
5531     uint32_t group_id;
5532
5533     error = ofputil_decode_group_stats_request(request, &group_id);
5534     if (error) {
5535         return error;
5536     }
5537
5538     ofpmp_init(&replies, request);
5539
5540     if (group_id == OFPG_ALL) {
5541         ovs_rwlock_rdlock(&ofproto->groups_rwlock);
5542         HMAP_FOR_EACH (group, hmap_node, &ofproto->groups) {
5543             ovs_rwlock_rdlock(&group->rwlock);
5544             append_group_stats(group, &replies);
5545             ovs_rwlock_unlock(&group->rwlock);
5546         }
5547         ovs_rwlock_unlock(&ofproto->groups_rwlock);
5548     } else {
5549         if (ofproto_group_lookup(ofproto, group_id, &group)) {
5550             append_group_stats(group, &replies);
5551             ofproto_group_release(group);
5552         }
5553     }
5554
5555     ofconn_send_replies(ofconn, &replies);
5556
5557     return 0;
5558 }
5559
5560 static enum ofperr
5561 handle_group_desc_stats_request(struct ofconn *ofconn,
5562                                 const struct ofp_header *request)
5563 {
5564     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5565     struct list replies;
5566     struct ofputil_group_desc gds;
5567     struct ofgroup *group;
5568
5569     ofpmp_init(&replies, request);
5570
5571     ovs_rwlock_rdlock(&ofproto->groups_rwlock);
5572     HMAP_FOR_EACH (group, hmap_node, &ofproto->groups) {
5573         gds.group_id = group->group_id;
5574         gds.type = group->type;
5575         ofputil_append_group_desc_reply(&gds, &group->buckets, &replies);
5576     }
5577     ovs_rwlock_unlock(&ofproto->groups_rwlock);
5578
5579     ofconn_send_replies(ofconn, &replies);
5580
5581     return 0;
5582 }
5583
5584 static enum ofperr
5585 handle_group_features_stats_request(struct ofconn *ofconn,
5586                                     const struct ofp_header *request)
5587 {
5588     struct ofproto *p = ofconn_get_ofproto(ofconn);
5589     struct ofpbuf *msg;
5590
5591     msg = ofputil_encode_group_features_reply(&p->ogf, request);
5592     if (msg) {
5593         ofconn_send_reply(ofconn, msg);
5594     }
5595
5596     return 0;
5597 }
5598
5599 static enum ofperr
5600 handle_queue_get_config_request(struct ofconn *ofconn,
5601                                 const struct ofp_header *oh)
5602 {
5603    struct ofproto *p = ofconn_get_ofproto(ofconn);
5604    struct netdev_queue_dump queue_dump;
5605    struct ofport *ofport;
5606    unsigned int queue_id;
5607    struct ofpbuf *reply;
5608    struct smap details;
5609    ofp_port_t request;
5610    enum ofperr error;
5611
5612    error = ofputil_decode_queue_get_config_request(oh, &request);
5613    if (error) {
5614        return error;
5615    }
5616
5617    ofport = ofproto_get_port(p, request);
5618    if (!ofport) {
5619       return OFPERR_OFPQOFC_BAD_PORT;
5620    }
5621
5622    reply = ofputil_encode_queue_get_config_reply(oh);
5623
5624    smap_init(&details);
5625    NETDEV_QUEUE_FOR_EACH (&queue_id, &details, &queue_dump, ofport->netdev) {
5626        struct ofputil_queue_config queue;
5627
5628        /* None of the existing queues have compatible properties, so we
5629         * hard-code omitting min_rate and max_rate. */
5630        queue.queue_id = queue_id;
5631        queue.min_rate = UINT16_MAX;
5632        queue.max_rate = UINT16_MAX;
5633        ofputil_append_queue_get_config_reply(reply, &queue);
5634    }
5635    smap_destroy(&details);
5636
5637    ofconn_send_reply(ofconn, reply);
5638
5639    return 0;
5640 }
5641
5642 /* Implements OFPGC11_ADD
5643  * in which no matching flow already exists in the flow table.
5644  *
5645  * Adds the flow specified by 'ofm', which is followed by 'n_actions'
5646  * ofp_actions, to the ofproto's flow table.  Returns 0 on success, an OpenFlow
5647  * error code on failure, or OFPROTO_POSTPONE if the operation cannot be
5648  * initiated now but may be retried later.
5649  *
5650  * Upon successful return, takes ownership of 'fm->ofpacts'.  On failure,
5651  * ownership remains with the caller.
5652  *
5653  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
5654  * if any. */
5655 static enum ofperr
5656 add_group(struct ofproto *ofproto, struct ofputil_group_mod *gm)
5657 {
5658     struct ofgroup *ofgroup;
5659     enum ofperr error;
5660
5661     if (gm->group_id > OFPG_MAX) {
5662         return OFPERR_OFPGMFC_INVALID_GROUP;
5663     }
5664     if (gm->type > OFPGT11_FF) {
5665         return OFPERR_OFPGMFC_BAD_TYPE;
5666     }
5667
5668     /* Allocate new group and initialize it. */
5669     ofgroup = ofproto->ofproto_class->group_alloc();
5670     if (!ofgroup) {
5671         VLOG_WARN_RL(&rl, "%s: failed to create group", ofproto->name);
5672         return OFPERR_OFPGMFC_OUT_OF_GROUPS;
5673     }
5674
5675     ovs_rwlock_init(&ofgroup->rwlock);
5676     ofgroup->ofproto  = ofproto;
5677     ofgroup->group_id = gm->group_id;
5678     ofgroup->type     = gm->type;
5679     ofgroup->created = ofgroup->modified = time_msec();
5680
5681     list_move(&ofgroup->buckets, &gm->buckets);
5682     ofgroup->n_buckets = list_size(&ofgroup->buckets);
5683
5684     /* Construct called BEFORE any locks are held. */
5685     error = ofproto->ofproto_class->group_construct(ofgroup);
5686     if (error) {
5687         goto free_out;
5688     }
5689
5690     /* We wrlock as late as possible to minimize the time we jam any other
5691      * threads: No visible state changes before acquiring the lock. */
5692     ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5693
5694     if (ofproto->n_groups[gm->type] >= ofproto->ogf.max_groups[gm->type]) {
5695         error = OFPERR_OFPGMFC_OUT_OF_GROUPS;
5696         goto unlock_out;
5697     }
5698
5699     if (ofproto_group_exists__(ofproto, gm->group_id)) {
5700         error = OFPERR_OFPGMFC_GROUP_EXISTS;
5701         goto unlock_out;
5702     }
5703
5704     if (!error) {
5705         /* Insert new group. */
5706         hmap_insert(&ofproto->groups, &ofgroup->hmap_node,
5707                     hash_int(ofgroup->group_id, 0));
5708         ofproto->n_groups[ofgroup->type]++;
5709
5710         ovs_rwlock_unlock(&ofproto->groups_rwlock);
5711         return error;
5712     }
5713
5714  unlock_out:
5715     ovs_rwlock_unlock(&ofproto->groups_rwlock);
5716     ofproto->ofproto_class->group_destruct(ofgroup);
5717  free_out:
5718     ofputil_bucket_list_destroy(&ofgroup->buckets);
5719     ofproto->ofproto_class->group_dealloc(ofgroup);
5720
5721     return error;
5722 }
5723
5724 /* Implements OFPFC_MODIFY.  Returns 0 on success or an OpenFlow error code on
5725  * failure.
5726  *
5727  * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
5728  * if any. */
5729 static enum ofperr
5730 modify_group(struct ofproto *ofproto, struct ofputil_group_mod *gm)
5731 {
5732     struct ofgroup *ofgroup;
5733     struct ofgroup *victim;
5734     enum ofperr error;
5735
5736     if (gm->group_id > OFPG_MAX) {
5737         return OFPERR_OFPGMFC_INVALID_GROUP;
5738     }
5739
5740     if (gm->type > OFPGT11_FF) {
5741         return OFPERR_OFPGMFC_BAD_TYPE;
5742     }
5743
5744     victim = ofproto->ofproto_class->group_alloc();
5745     if (!victim) {
5746         VLOG_WARN_RL(&rl, "%s: failed to allocate group", ofproto->name);
5747         return OFPERR_OFPGMFC_OUT_OF_GROUPS;
5748     }
5749
5750     if (!ofproto_group_write_lookup(ofproto, gm->group_id, &ofgroup)) {
5751         error = OFPERR_OFPGMFC_UNKNOWN_GROUP;
5752         goto free_out;
5753     }
5754     /* Both group's and its container's write locks held now.
5755      * Also, n_groups[] is protected by ofproto->groups_rwlock. */
5756     if (ofgroup->type != gm->type
5757         && ofproto->n_groups[gm->type] >= ofproto->ogf.max_groups[gm->type]) {
5758         error = OFPERR_OFPGMFC_OUT_OF_GROUPS;
5759         goto unlock_out;
5760     }
5761
5762     *victim = *ofgroup;
5763     list_move(&victim->buckets, &ofgroup->buckets);
5764
5765     ofgroup->type = gm->type;
5766     list_move(&ofgroup->buckets, &gm->buckets);
5767     ofgroup->n_buckets = list_size(&ofgroup->buckets);
5768
5769     error = ofproto->ofproto_class->group_modify(ofgroup, victim);
5770     if (!error) {
5771         ofputil_bucket_list_destroy(&victim->buckets);
5772         ofproto->n_groups[victim->type]--;
5773         ofproto->n_groups[ofgroup->type]++;
5774         ofgroup->modified = time_msec();
5775     } else {
5776         ofputil_bucket_list_destroy(&ofgroup->buckets);
5777
5778         *ofgroup = *victim;
5779         list_move(&ofgroup->buckets, &victim->buckets);
5780     }
5781
5782  unlock_out:
5783     ovs_rwlock_unlock(&ofgroup->rwlock);
5784     ovs_rwlock_unlock(&ofproto->groups_rwlock);
5785  free_out:
5786     ofproto->ofproto_class->group_dealloc(victim);
5787     return error;
5788 }
5789
5790 static void
5791 delete_group__(struct ofproto *ofproto, struct ofgroup *ofgroup)
5792     OVS_RELEASES(ofproto->groups_rwlock)
5793 {
5794     struct match match;
5795     struct ofputil_flow_mod fm;
5796
5797     /* Delete all flow entries containing this group in a group action */
5798     match_init_catchall(&match);
5799     flow_mod_init(&fm, &match, 0, NULL, 0, OFPFC_DELETE);
5800     fm.out_group = ofgroup->group_id;
5801     handle_flow_mod__(ofproto, NULL, &fm, NULL);
5802
5803     /* Must wait until existing readers are done,
5804      * while holding the container's write lock at the same time. */
5805     ovs_rwlock_wrlock(&ofgroup->rwlock);
5806     hmap_remove(&ofproto->groups, &ofgroup->hmap_node);
5807     /* No-one can find this group any more. */
5808     ofproto->n_groups[ofgroup->type]--;
5809     ovs_rwlock_unlock(&ofproto->groups_rwlock);
5810
5811     ofproto->ofproto_class->group_destruct(ofgroup);
5812     ofputil_bucket_list_destroy(&ofgroup->buckets);
5813     ovs_rwlock_unlock(&ofgroup->rwlock);
5814     ovs_rwlock_destroy(&ofgroup->rwlock);
5815     ofproto->ofproto_class->group_dealloc(ofgroup);
5816 }
5817
5818 /* Implements OFPGC_DELETE. */
5819 static void
5820 delete_group(struct ofproto *ofproto, uint32_t group_id)
5821 {
5822     struct ofgroup *ofgroup;
5823
5824     ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5825     if (group_id == OFPG_ALL) {
5826         for (;;) {
5827             struct hmap_node *node = hmap_first(&ofproto->groups);
5828             if (!node) {
5829                 break;
5830             }
5831             ofgroup = CONTAINER_OF(node, struct ofgroup, hmap_node);
5832             delete_group__(ofproto, ofgroup);
5833             /* Lock for each node separately, so that we will not jam the
5834              * other threads for too long time. */
5835             ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5836         }
5837     } else {
5838         HMAP_FOR_EACH_IN_BUCKET (ofgroup, hmap_node,
5839                                  hash_int(group_id, 0), &ofproto->groups) {
5840             if (ofgroup->group_id == group_id) {
5841                 delete_group__(ofproto, ofgroup);
5842                 return;
5843             }
5844         }
5845     }
5846     ovs_rwlock_unlock(&ofproto->groups_rwlock);
5847 }
5848
5849 static enum ofperr
5850 handle_group_mod(struct ofconn *ofconn, const struct ofp_header *oh)
5851 {
5852     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5853     struct ofputil_group_mod gm;
5854     enum ofperr error;
5855
5856     error = reject_slave_controller(ofconn);
5857     if (error) {
5858         return error;
5859     }
5860
5861     error = ofputil_decode_group_mod(oh, &gm);
5862     if (error) {
5863         return error;
5864     }
5865
5866     switch (gm.command) {
5867     case OFPGC11_ADD:
5868         return add_group(ofproto, &gm);
5869
5870     case OFPGC11_MODIFY:
5871         return modify_group(ofproto, &gm);
5872
5873     case OFPGC11_DELETE:
5874         delete_group(ofproto, gm.group_id);
5875         return 0;
5876
5877     default:
5878         if (gm.command > OFPGC11_DELETE) {
5879             VLOG_WARN_RL(&rl, "%s: Invalid group_mod command type %d",
5880                          ofproto->name, gm.command);
5881         }
5882         return OFPERR_OFPGMFC_BAD_COMMAND;
5883     }
5884 }
5885
5886 enum ofproto_table_config
5887 ofproto_table_get_config(const struct ofproto *ofproto, uint8_t table_id)
5888 {
5889     unsigned int value;
5890     atomic_read(&ofproto->tables[table_id].config, &value);
5891     return (enum ofproto_table_config)value;
5892 }
5893
5894 static enum ofperr
5895 table_mod(struct ofproto *ofproto, const struct ofputil_table_mod *tm)
5896 {
5897     /* Only accept currently supported configurations */
5898     if (tm->config & ~OFPTC11_TABLE_MISS_MASK) {
5899         return OFPERR_OFPTMFC_BAD_CONFIG;
5900     }
5901
5902     if (tm->table_id == OFPTT_ALL) {
5903         int i;
5904         for (i = 0; i < ofproto->n_tables; i++) {
5905             atomic_store(&ofproto->tables[i].config,
5906                          (unsigned int)tm->config);
5907         }
5908     } else if (!check_table_id(ofproto, tm->table_id)) {
5909         return OFPERR_OFPTMFC_BAD_TABLE;
5910     } else {
5911         atomic_store(&ofproto->tables[tm->table_id].config,
5912                      (unsigned int)tm->config);
5913     }
5914
5915     return 0;
5916 }
5917
5918 static enum ofperr
5919 handle_table_mod(struct ofconn *ofconn, const struct ofp_header *oh)
5920 {
5921     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5922     struct ofputil_table_mod tm;
5923     enum ofperr error;
5924
5925     error = reject_slave_controller(ofconn);
5926     if (error) {
5927         return error;
5928     }
5929
5930     error = ofputil_decode_table_mod(oh, &tm);
5931     if (error) {
5932         return error;
5933     }
5934
5935     return table_mod(ofproto, &tm);
5936 }
5937
5938 static enum ofperr
5939 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
5940     OVS_EXCLUDED(ofproto_mutex)
5941 {
5942     const struct ofp_header *oh = ofpbuf_data(msg);
5943     enum ofptype type;
5944     enum ofperr error;
5945
5946     error = ofptype_decode(&type, oh);
5947     if (error) {
5948         return error;
5949     }
5950     if (oh->version >= OFP13_VERSION && ofpmsg_is_stat_request(oh)
5951         && ofpmp_more(oh)) {
5952         /* We have no buffer implementation for multipart requests.
5953          * Report overflow for requests which consists of multiple
5954          * messages. */
5955         return OFPERR_OFPBRC_MULTIPART_BUFFER_OVERFLOW;
5956     }
5957
5958     switch (type) {
5959         /* OpenFlow requests. */
5960     case OFPTYPE_ECHO_REQUEST:
5961         return handle_echo_request(ofconn, oh);
5962
5963     case OFPTYPE_FEATURES_REQUEST:
5964         return handle_features_request(ofconn, oh);
5965
5966     case OFPTYPE_GET_CONFIG_REQUEST:
5967         return handle_get_config_request(ofconn, oh);
5968
5969     case OFPTYPE_SET_CONFIG:
5970         return handle_set_config(ofconn, oh);
5971
5972     case OFPTYPE_PACKET_OUT:
5973         return handle_packet_out(ofconn, oh);
5974
5975     case OFPTYPE_PORT_MOD:
5976         return handle_port_mod(ofconn, oh);
5977
5978     case OFPTYPE_FLOW_MOD:
5979         return handle_flow_mod(ofconn, oh);
5980
5981     case OFPTYPE_GROUP_MOD:
5982         return handle_group_mod(ofconn, oh);
5983
5984     case OFPTYPE_TABLE_MOD:
5985         return handle_table_mod(ofconn, oh);
5986
5987     case OFPTYPE_METER_MOD:
5988         return handle_meter_mod(ofconn, oh);
5989
5990     case OFPTYPE_BARRIER_REQUEST:
5991         return handle_barrier_request(ofconn, oh);
5992
5993     case OFPTYPE_ROLE_REQUEST:
5994         return handle_role_request(ofconn, oh);
5995
5996         /* OpenFlow replies. */
5997     case OFPTYPE_ECHO_REPLY:
5998         return 0;
5999
6000         /* Nicira extension requests. */
6001     case OFPTYPE_FLOW_MOD_TABLE_ID:
6002         return handle_nxt_flow_mod_table_id(ofconn, oh);
6003
6004     case OFPTYPE_SET_FLOW_FORMAT:
6005         return handle_nxt_set_flow_format(ofconn, oh);
6006
6007     case OFPTYPE_SET_PACKET_IN_FORMAT:
6008         return handle_nxt_set_packet_in_format(ofconn, oh);
6009
6010     case OFPTYPE_SET_CONTROLLER_ID:
6011         return handle_nxt_set_controller_id(ofconn, oh);
6012
6013     case OFPTYPE_FLOW_AGE:
6014         /* Nothing to do. */
6015         return 0;
6016
6017     case OFPTYPE_FLOW_MONITOR_CANCEL:
6018         return handle_flow_monitor_cancel(ofconn, oh);
6019
6020     case OFPTYPE_SET_ASYNC_CONFIG:
6021         return handle_nxt_set_async_config(ofconn, oh);
6022
6023     case OFPTYPE_GET_ASYNC_REQUEST:
6024         return handle_nxt_get_async_request(ofconn, oh);
6025
6026         /* Statistics requests. */
6027     case OFPTYPE_DESC_STATS_REQUEST:
6028         return handle_desc_stats_request(ofconn, oh);
6029
6030     case OFPTYPE_FLOW_STATS_REQUEST:
6031         return handle_flow_stats_request(ofconn, oh);
6032
6033     case OFPTYPE_AGGREGATE_STATS_REQUEST:
6034         return handle_aggregate_stats_request(ofconn, oh);
6035
6036     case OFPTYPE_TABLE_STATS_REQUEST:
6037         return handle_table_stats_request(ofconn, oh);
6038
6039     case OFPTYPE_PORT_STATS_REQUEST:
6040         return handle_port_stats_request(ofconn, oh);
6041
6042     case OFPTYPE_QUEUE_STATS_REQUEST:
6043         return handle_queue_stats_request(ofconn, oh);
6044
6045     case OFPTYPE_PORT_DESC_STATS_REQUEST:
6046         return handle_port_desc_stats_request(ofconn, oh);
6047
6048     case OFPTYPE_FLOW_MONITOR_STATS_REQUEST:
6049         return handle_flow_monitor_request(ofconn, oh);
6050
6051     case OFPTYPE_METER_STATS_REQUEST:
6052     case OFPTYPE_METER_CONFIG_STATS_REQUEST:
6053         return handle_meter_request(ofconn, oh, type);
6054
6055     case OFPTYPE_METER_FEATURES_STATS_REQUEST:
6056         return handle_meter_features_request(ofconn, oh);
6057
6058     case OFPTYPE_GROUP_STATS_REQUEST:
6059         return handle_group_stats_request(ofconn, oh);
6060
6061     case OFPTYPE_GROUP_DESC_STATS_REQUEST:
6062         return handle_group_desc_stats_request(ofconn, oh);
6063
6064     case OFPTYPE_GROUP_FEATURES_STATS_REQUEST:
6065         return handle_group_features_stats_request(ofconn, oh);
6066
6067     case OFPTYPE_QUEUE_GET_CONFIG_REQUEST:
6068         return handle_queue_get_config_request(ofconn, oh);
6069
6070     case OFPTYPE_HELLO:
6071     case OFPTYPE_ERROR:
6072     case OFPTYPE_FEATURES_REPLY:
6073     case OFPTYPE_GET_CONFIG_REPLY:
6074     case OFPTYPE_PACKET_IN:
6075     case OFPTYPE_FLOW_REMOVED:
6076     case OFPTYPE_PORT_STATUS:
6077     case OFPTYPE_BARRIER_REPLY:
6078     case OFPTYPE_QUEUE_GET_CONFIG_REPLY:
6079     case OFPTYPE_DESC_STATS_REPLY:
6080     case OFPTYPE_FLOW_STATS_REPLY:
6081     case OFPTYPE_QUEUE_STATS_REPLY:
6082     case OFPTYPE_PORT_STATS_REPLY:
6083     case OFPTYPE_TABLE_STATS_REPLY:
6084     case OFPTYPE_AGGREGATE_STATS_REPLY:
6085     case OFPTYPE_PORT_DESC_STATS_REPLY:
6086     case OFPTYPE_ROLE_REPLY:
6087     case OFPTYPE_FLOW_MONITOR_PAUSED:
6088     case OFPTYPE_FLOW_MONITOR_RESUMED:
6089     case OFPTYPE_FLOW_MONITOR_STATS_REPLY:
6090     case OFPTYPE_GET_ASYNC_REPLY:
6091     case OFPTYPE_GROUP_STATS_REPLY:
6092     case OFPTYPE_GROUP_DESC_STATS_REPLY:
6093     case OFPTYPE_GROUP_FEATURES_STATS_REPLY:
6094     case OFPTYPE_METER_STATS_REPLY:
6095     case OFPTYPE_METER_CONFIG_STATS_REPLY:
6096     case OFPTYPE_METER_FEATURES_STATS_REPLY:
6097     case OFPTYPE_TABLE_FEATURES_STATS_REQUEST:
6098     case OFPTYPE_TABLE_FEATURES_STATS_REPLY:
6099     case OFPTYPE_ROLE_STATUS:
6100     default:
6101         if (ofpmsg_is_stat_request(oh)) {
6102             return OFPERR_OFPBRC_BAD_STAT;
6103         } else {
6104             return OFPERR_OFPBRC_BAD_TYPE;
6105         }
6106     }
6107 }
6108
6109 static bool
6110 handle_openflow(struct ofconn *ofconn, const struct ofpbuf *ofp_msg)
6111     OVS_EXCLUDED(ofproto_mutex)
6112 {
6113     int error = handle_openflow__(ofconn, ofp_msg);
6114     if (error && error != OFPROTO_POSTPONE) {
6115         ofconn_send_error(ofconn, ofpbuf_data(ofp_msg), error);
6116     }
6117     COVERAGE_INC(ofproto_recv_openflow);
6118     return error != OFPROTO_POSTPONE;
6119 }
6120 \f
6121 /* Asynchronous operations. */
6122
6123 /* Creates and returns a new ofopgroup that is not associated with any
6124  * OpenFlow connection.
6125  *
6126  * The caller should add operations to the returned group with
6127  * ofoperation_create() and then submit it with ofopgroup_submit(). */
6128 static struct ofopgroup *
6129 ofopgroup_create_unattached(struct ofproto *ofproto)
6130     OVS_REQUIRES(ofproto_mutex)
6131 {
6132     struct ofopgroup *group = xzalloc(sizeof *group);
6133     group->ofproto = ofproto;
6134     list_init(&group->ofproto_node);
6135     list_init(&group->ops);
6136     list_init(&group->ofconn_node);
6137     return group;
6138 }
6139
6140 /* Creates and returns a new ofopgroup for 'ofproto'.
6141  *
6142  * If 'ofconn' is NULL, the new ofopgroup is not associated with any OpenFlow
6143  * connection.  The 'request' and 'buffer_id' arguments are ignored.
6144  *
6145  * If 'ofconn' is nonnull, then the new ofopgroup is associated with 'ofconn'.
6146  * If the ofopgroup eventually fails, then the error reply will include
6147  * 'request'.  If the ofopgroup eventually succeeds, then the packet with
6148  * buffer id 'buffer_id' on 'ofconn' will be sent by 'ofconn''s ofproto.
6149  *
6150  * The caller should add operations to the returned group with
6151  * ofoperation_create() and then submit it with ofopgroup_submit(). */
6152 static struct ofopgroup *
6153 ofopgroup_create(struct ofproto *ofproto, struct ofconn *ofconn,
6154                  const struct ofp_header *request, uint32_t buffer_id)
6155     OVS_REQUIRES(ofproto_mutex)
6156 {
6157     struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
6158     if (ofconn) {
6159         size_t request_len = ntohs(request->length);
6160
6161         ovs_assert(ofconn_get_ofproto(ofconn) == ofproto);
6162
6163         ofconn_add_opgroup(ofconn, &group->ofconn_node);
6164         group->ofconn = ofconn;
6165         group->request = xmemdup(request, MIN(request_len, 64));
6166         group->buffer_id = buffer_id;
6167     }
6168     return group;
6169 }
6170
6171 /* Submits 'group' for processing.
6172  *
6173  * If 'group' contains no operations (e.g. none were ever added, or all of the
6174  * ones that were added completed synchronously), then it is destroyed
6175  * immediately.  Otherwise it is added to the ofproto's list of pending
6176  * groups. */
6177 static void
6178 ofopgroup_submit(struct ofopgroup *group)
6179     OVS_REQUIRES(ofproto_mutex)
6180 {
6181     if (!group->n_running) {
6182         ofopgroup_complete(group);
6183     } else {
6184         list_push_back(&group->ofproto->pending, &group->ofproto_node);
6185         group->ofproto->n_pending++;
6186     }
6187 }
6188
6189 static void
6190 ofopgroup_complete(struct ofopgroup *group)
6191     OVS_REQUIRES(ofproto_mutex)
6192 {
6193     struct ofproto *ofproto = group->ofproto;
6194
6195     struct ofconn *abbrev_ofconn;
6196     ovs_be32 abbrev_xid;
6197
6198     struct ofoperation *op, *next_op;
6199     int error;
6200
6201     ovs_assert(!group->n_running);
6202
6203     error = 0;
6204     LIST_FOR_EACH (op, group_node, &group->ops) {
6205         if (op->error) {
6206             error = op->error;
6207             break;
6208         }
6209     }
6210
6211     if (!error && group->ofconn && group->buffer_id != UINT32_MAX) {
6212         LIST_FOR_EACH (op, group_node, &group->ops) {
6213             if (op->type != OFOPERATION_DELETE) {
6214                 struct ofpbuf *packet;
6215                 ofp_port_t in_port;
6216
6217                 error = ofconn_pktbuf_retrieve(group->ofconn, group->buffer_id,
6218                                                &packet, &in_port);
6219                 if (packet) {
6220                     struct rule_execute *re;
6221
6222                     ovs_assert(!error);
6223
6224                     ofproto_rule_ref(op->rule);
6225
6226                     re = xmalloc(sizeof *re);
6227                     re->rule = op->rule;
6228                     re->in_port = in_port;
6229                     re->packet = packet;
6230
6231                     if (!guarded_list_push_back(&ofproto->rule_executes,
6232                                                 &re->list_node, 1024)) {
6233                         ofproto_rule_unref(op->rule);
6234                         ofpbuf_delete(re->packet);
6235                         free(re);
6236                     }
6237                 }
6238                 break;
6239             }
6240         }
6241     }
6242
6243     if (!error && !list_is_empty(&group->ofconn_node)) {
6244         abbrev_ofconn = group->ofconn;
6245         abbrev_xid = group->request->xid;
6246     } else {
6247         abbrev_ofconn = NULL;
6248         abbrev_xid = htonl(0);
6249     }
6250     LIST_FOR_EACH_SAFE (op, next_op, group_node, &group->ops) {
6251         struct rule *rule = op->rule;
6252
6253         /* We generally want to report the change to active OpenFlow flow
6254            monitors (e.g. NXST_FLOW_MONITOR).  There are three exceptions:
6255
6256               - The operation failed.
6257
6258               - The affected rule is not visible to controllers.
6259
6260               - The operation's only effect was to update rule->modified. */
6261         if (!(op->error
6262               || ofproto_rule_is_hidden(rule)
6263               || (op->type == OFOPERATION_MODIFY
6264                   && op->actions
6265                   && rule->flow_cookie == op->flow_cookie))) {
6266             /* Check that we can just cast from ofoperation_type to
6267              * nx_flow_update_event. */
6268             enum nx_flow_update_event event_type;
6269
6270             switch (op->type) {
6271             case OFOPERATION_ADD:
6272             case OFOPERATION_REPLACE:
6273                 event_type = NXFME_ADDED;
6274                 break;
6275
6276             case OFOPERATION_DELETE:
6277                 event_type = NXFME_DELETED;
6278                 break;
6279
6280             case OFOPERATION_MODIFY:
6281                 event_type = NXFME_MODIFIED;
6282                 break;
6283
6284             default:
6285                 OVS_NOT_REACHED();
6286             }
6287
6288             ofmonitor_report(ofproto->connmgr, rule, event_type,
6289                              op->reason, abbrev_ofconn, abbrev_xid);
6290         }
6291
6292         rule->pending = NULL;
6293
6294         switch (op->type) {
6295         case OFOPERATION_ADD:
6296             if (!op->error) {
6297                 uint16_t vid_mask;
6298
6299                 vid_mask = minimask_get_vid_mask(&rule->cr.match.mask);
6300                 if (vid_mask == VLAN_VID_MASK) {
6301                     if (ofproto->vlan_bitmap) {
6302                         uint16_t vid = miniflow_get_vid(&rule->cr.match.flow);
6303                         if (!bitmap_is_set(ofproto->vlan_bitmap, vid)) {
6304                             bitmap_set1(ofproto->vlan_bitmap, vid);
6305                             ofproto->vlans_changed = true;
6306                         }
6307                     } else {
6308                         ofproto->vlans_changed = true;
6309                     }
6310                 }
6311             } else {
6312                 oftable_remove_rule(rule);
6313                 ofproto_rule_unref(rule);
6314             }
6315             break;
6316
6317         case OFOPERATION_DELETE:
6318             ovs_assert(!op->error);
6319             ofproto_rule_unref(rule);
6320             op->rule = NULL;
6321             break;
6322
6323         case OFOPERATION_MODIFY:
6324         case OFOPERATION_REPLACE:
6325             if (!op->error) {
6326                 long long int now = time_msec();
6327
6328                 ovs_mutex_lock(&rule->mutex);
6329                 rule->modified = now;
6330                 if (op->type == OFOPERATION_REPLACE) {
6331                     rule->created = now;
6332                 }
6333                 ovs_mutex_unlock(&rule->mutex);
6334             } else {
6335                 ofproto_rule_change_cookie(ofproto, rule, op->flow_cookie);
6336                 ovs_mutex_lock(&rule->mutex);
6337                 rule->idle_timeout = op->idle_timeout;
6338                 rule->hard_timeout = op->hard_timeout;
6339                 ovs_mutex_unlock(&rule->mutex);
6340                 if (op->actions) {
6341                     struct rule_actions *old_actions;
6342
6343                     ovs_mutex_lock(&rule->mutex);
6344                     old_actions = rule_get_actions(rule);
6345                     ovsrcu_set(&rule->actions, op->actions);
6346                     ovs_mutex_unlock(&rule->mutex);
6347
6348                     op->actions = NULL;
6349                     rule_actions_destroy(old_actions);
6350                 }
6351                 rule->flags = op->flags;
6352             }
6353             break;
6354
6355         default:
6356             OVS_NOT_REACHED();
6357         }
6358
6359         ofoperation_destroy(op);
6360     }
6361
6362     ofmonitor_flush(ofproto->connmgr);
6363
6364     if (!list_is_empty(&group->ofproto_node)) {
6365         ovs_assert(ofproto->n_pending > 0);
6366         ofproto->n_pending--;
6367         list_remove(&group->ofproto_node);
6368     }
6369     if (!list_is_empty(&group->ofconn_node)) {
6370         list_remove(&group->ofconn_node);
6371         if (error) {
6372             ofconn_send_error(group->ofconn, group->request, error);
6373         }
6374         connmgr_retry(ofproto->connmgr);
6375     }
6376     free(group->request);
6377     free(group);
6378 }
6379
6380 /* Initiates a new operation on 'rule', of the specified 'type', within
6381  * 'group'.  Prior to calling, 'rule' must not have any pending operation.
6382  *
6383  * For a 'type' of OFOPERATION_DELETE, 'reason' should specify the reason that
6384  * the flow is being deleted.  For other 'type's, 'reason' is ignored (use 0).
6385  *
6386  * Returns the newly created ofoperation (which is also available as
6387  * rule->pending). */
6388 static struct ofoperation *
6389 ofoperation_create(struct ofopgroup *group, struct rule *rule,
6390                    enum ofoperation_type type,
6391                    enum ofp_flow_removed_reason reason)
6392     OVS_REQUIRES(ofproto_mutex)
6393 {
6394     struct ofproto *ofproto = group->ofproto;
6395     struct ofoperation *op;
6396
6397     ovs_assert(!rule->pending);
6398
6399     op = rule->pending = xzalloc(sizeof *op);
6400     op->group = group;
6401     list_push_back(&group->ops, &op->group_node);
6402     op->rule = rule;
6403     op->type = type;
6404     op->reason = reason;
6405     op->flow_cookie = rule->flow_cookie;
6406     ovs_mutex_lock(&rule->mutex);
6407     op->idle_timeout = rule->idle_timeout;
6408     op->hard_timeout = rule->hard_timeout;
6409     ovs_mutex_unlock(&rule->mutex);
6410     op->flags = rule->flags;
6411
6412     group->n_running++;
6413
6414     if (type == OFOPERATION_DELETE) {
6415         hmap_insert(&ofproto->deletions, &op->hmap_node,
6416                     cls_rule_hash(&rule->cr, rule->table_id));
6417     }
6418
6419     return op;
6420 }
6421
6422 static void
6423 ofoperation_destroy(struct ofoperation *op)
6424     OVS_REQUIRES(ofproto_mutex)
6425 {
6426     struct ofopgroup *group = op->group;
6427
6428     if (op->rule) {
6429         op->rule->pending = NULL;
6430     }
6431     if (op->type == OFOPERATION_DELETE) {
6432         hmap_remove(&group->ofproto->deletions, &op->hmap_node);
6433     }
6434     list_remove(&op->group_node);
6435     rule_actions_destroy(op->actions);
6436     free(op);
6437 }
6438
6439 /* Indicates that 'op' completed with status 'error', which is either 0 to
6440  * indicate success or an OpenFlow error code on failure.
6441  *
6442  * If 'error' is 0, indicating success, the operation will be committed
6443  * permanently to the flow table.
6444  *
6445  * If 'error' is nonzero, then generally the operation will be rolled back:
6446  *
6447  *   - If 'op' is an "add flow" operation, ofproto removes the new rule or
6448  *     restores the original rule.  The caller must have uninitialized any
6449  *     derived state in the new rule, as in step 5 of in the "Life Cycle" in
6450  *     ofproto/ofproto-provider.h.  ofoperation_complete() performs steps 6 and
6451  *     and 7 for the new rule, calling its ->rule_dealloc() function.
6452  *
6453  *   - If 'op' is a "modify flow" operation, ofproto restores the original
6454  *     actions.
6455  *
6456  *   - 'op' must not be a "delete flow" operation.  Removing a rule is not
6457  *     allowed to fail.  It must always succeed.
6458  *
6459  * Please see the large comment in ofproto/ofproto-provider.h titled
6460  * "Asynchronous Operation Support" for more information. */
6461 void
6462 ofoperation_complete(struct ofoperation *op, enum ofperr error)
6463 {
6464     struct ofopgroup *group = op->group;
6465
6466     ovs_assert(group->n_running > 0);
6467     ovs_assert(!error || op->type != OFOPERATION_DELETE);
6468
6469     op->error = error;
6470     if (!--group->n_running && !list_is_empty(&group->ofproto_node)) {
6471         /* This function can be called from ->rule_construct(), in which case
6472          * ofproto_mutex is held, or it can be called from ->run(), in which
6473          * case ofproto_mutex is not held.  But only in the latter case can we
6474          * arrive here, so we can safely take ofproto_mutex now. */
6475         ovs_mutex_lock(&ofproto_mutex);
6476         ovs_assert(op->rule->pending == op);
6477         ofopgroup_complete(group);
6478         ovs_mutex_unlock(&ofproto_mutex);
6479     }
6480 }
6481 \f
6482 static uint64_t
6483 pick_datapath_id(const struct ofproto *ofproto)
6484 {
6485     const struct ofport *port;
6486
6487     port = ofproto_get_port(ofproto, OFPP_LOCAL);
6488     if (port) {
6489         uint8_t ea[ETH_ADDR_LEN];
6490         int error;
6491
6492         error = netdev_get_etheraddr(port->netdev, ea);
6493         if (!error) {
6494             return eth_addr_to_uint64(ea);
6495         }
6496         VLOG_WARN("%s: could not get MAC address for %s (%s)",
6497                   ofproto->name, netdev_get_name(port->netdev),
6498                   ovs_strerror(error));
6499     }
6500     return ofproto->fallback_dpid;
6501 }
6502
6503 static uint64_t
6504 pick_fallback_dpid(void)
6505 {
6506     uint8_t ea[ETH_ADDR_LEN];
6507     eth_addr_nicira_random(ea);
6508     return eth_addr_to_uint64(ea);
6509 }
6510 \f
6511 /* Table overflow policy. */
6512
6513 /* Chooses and updates 'rulep' with a rule to evict from 'table'.  Sets 'rulep'
6514  * to NULL if the table is not configured to evict rules or if the table
6515  * contains no evictable rules.  (Rules with a readlock on their evict rwlock,
6516  * or with no timeouts are not evictable.) */
6517 static bool
6518 choose_rule_to_evict(struct oftable *table, struct rule **rulep)
6519     OVS_REQUIRES(ofproto_mutex)
6520 {
6521     struct eviction_group *evg;
6522
6523     *rulep = NULL;
6524     if (!table->eviction_fields) {
6525         return false;
6526     }
6527
6528     /* In the common case, the outer and inner loops here will each be entered
6529      * exactly once:
6530      *
6531      *   - The inner loop normally "return"s in its first iteration.  If the
6532      *     eviction group has any evictable rules, then it always returns in
6533      *     some iteration.
6534      *
6535      *   - The outer loop only iterates more than once if the largest eviction
6536      *     group has no evictable rules.
6537      *
6538      *   - The outer loop can exit only if table's 'max_flows' is all filled up
6539      *     by unevictable rules. */
6540     HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
6541         struct rule *rule;
6542
6543         HEAP_FOR_EACH (rule, evg_node, &evg->rules) {
6544             *rulep = rule;
6545             return true;
6546         }
6547     }
6548
6549     return false;
6550 }
6551
6552 /* Searches 'ofproto' for tables that have more flows than their configured
6553  * maximum and that have flow eviction enabled, and evicts as many flows as
6554  * necessary and currently feasible from them.
6555  *
6556  * This triggers only when an OpenFlow table has N flows in it and then the
6557  * client configures a maximum number of flows less than N. */
6558 static void
6559 ofproto_evict(struct ofproto *ofproto)
6560 {
6561     struct oftable *table;
6562
6563     ovs_mutex_lock(&ofproto_mutex);
6564     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
6565         evict_rules_from_table(ofproto, table, 0);
6566     }
6567     ovs_mutex_unlock(&ofproto_mutex);
6568 }
6569 \f
6570 /* Eviction groups. */
6571
6572 /* Returns the priority to use for an eviction_group that contains 'n_rules'
6573  * rules.  The priority contains low-order random bits to ensure that eviction
6574  * groups with the same number of rules are prioritized randomly. */
6575 static uint32_t
6576 eviction_group_priority(size_t n_rules)
6577 {
6578     uint16_t size = MIN(UINT16_MAX, n_rules);
6579     return (size << 16) | random_uint16();
6580 }
6581
6582 /* Updates 'evg', an eviction_group within 'table', following a change that
6583  * adds or removes rules in 'evg'. */
6584 static void
6585 eviction_group_resized(struct oftable *table, struct eviction_group *evg)
6586     OVS_REQUIRES(ofproto_mutex)
6587 {
6588     heap_change(&table->eviction_groups_by_size, &evg->size_node,
6589                 eviction_group_priority(heap_count(&evg->rules)));
6590 }
6591
6592 /* Destroys 'evg', an eviction_group within 'table':
6593  *
6594  *   - Removes all the rules, if any, from 'evg'.  (It doesn't destroy the
6595  *     rules themselves, just removes them from the eviction group.)
6596  *
6597  *   - Removes 'evg' from 'table'.
6598  *
6599  *   - Frees 'evg'. */
6600 static void
6601 eviction_group_destroy(struct oftable *table, struct eviction_group *evg)
6602     OVS_REQUIRES(ofproto_mutex)
6603 {
6604     while (!heap_is_empty(&evg->rules)) {
6605         struct rule *rule;
6606
6607         rule = CONTAINER_OF(heap_pop(&evg->rules), struct rule, evg_node);
6608         rule->eviction_group = NULL;
6609     }
6610     hmap_remove(&table->eviction_groups_by_id, &evg->id_node);
6611     heap_remove(&table->eviction_groups_by_size, &evg->size_node);
6612     heap_destroy(&evg->rules);
6613     free(evg);
6614 }
6615
6616 /* Removes 'rule' from its eviction group, if any. */
6617 static void
6618 eviction_group_remove_rule(struct rule *rule)
6619     OVS_REQUIRES(ofproto_mutex)
6620 {
6621     if (rule->eviction_group) {
6622         struct oftable *table = &rule->ofproto->tables[rule->table_id];
6623         struct eviction_group *evg = rule->eviction_group;
6624
6625         rule->eviction_group = NULL;
6626         heap_remove(&evg->rules, &rule->evg_node);
6627         if (heap_is_empty(&evg->rules)) {
6628             eviction_group_destroy(table, evg);
6629         } else {
6630             eviction_group_resized(table, evg);
6631         }
6632     }
6633 }
6634
6635 /* Hashes the 'rule''s values for the eviction_fields of 'rule''s table, and
6636  * returns the hash value. */
6637 static uint32_t
6638 eviction_group_hash_rule(struct rule *rule)
6639     OVS_REQUIRES(ofproto_mutex)
6640 {
6641     struct oftable *table = &rule->ofproto->tables[rule->table_id];
6642     const struct mf_subfield *sf;
6643     struct flow flow;
6644     uint32_t hash;
6645
6646     hash = table->eviction_group_id_basis;
6647     miniflow_expand(&rule->cr.match.flow, &flow);
6648     for (sf = table->eviction_fields;
6649          sf < &table->eviction_fields[table->n_eviction_fields];
6650          sf++)
6651     {
6652         if (mf_are_prereqs_ok(sf->field, &flow)) {
6653             union mf_value value;
6654
6655             mf_get_value(sf->field, &flow, &value);
6656             if (sf->ofs) {
6657                 bitwise_zero(&value, sf->field->n_bytes, 0, sf->ofs);
6658             }
6659             if (sf->ofs + sf->n_bits < sf->field->n_bytes * 8) {
6660                 unsigned int start = sf->ofs + sf->n_bits;
6661                 bitwise_zero(&value, sf->field->n_bytes, start,
6662                              sf->field->n_bytes * 8 - start);
6663             }
6664             hash = hash_bytes(&value, sf->field->n_bytes, hash);
6665         } else {
6666             hash = hash_int(hash, 0);
6667         }
6668     }
6669
6670     return hash;
6671 }
6672
6673 /* Returns an eviction group within 'table' with the given 'id', creating one
6674  * if necessary. */
6675 static struct eviction_group *
6676 eviction_group_find(struct oftable *table, uint32_t id)
6677     OVS_REQUIRES(ofproto_mutex)
6678 {
6679     struct eviction_group *evg;
6680
6681     HMAP_FOR_EACH_WITH_HASH (evg, id_node, id, &table->eviction_groups_by_id) {
6682         return evg;
6683     }
6684
6685     evg = xmalloc(sizeof *evg);
6686     hmap_insert(&table->eviction_groups_by_id, &evg->id_node, id);
6687     heap_insert(&table->eviction_groups_by_size, &evg->size_node,
6688                 eviction_group_priority(0));
6689     heap_init(&evg->rules);
6690
6691     return evg;
6692 }
6693
6694 /* Returns an eviction priority for 'rule'.  The return value should be
6695  * interpreted so that higher priorities make a rule more attractive candidates
6696  * for eviction.
6697  * Called only if have a timeout. */
6698 static uint32_t
6699 rule_eviction_priority(struct ofproto *ofproto, struct rule *rule)
6700     OVS_REQUIRES(ofproto_mutex)
6701 {
6702     long long int expiration = LLONG_MAX;
6703     long long int modified;
6704     uint32_t expiration_offset;
6705
6706     /* 'modified' needs protection even when we hold 'ofproto_mutex'. */
6707     ovs_mutex_lock(&rule->mutex);
6708     modified = rule->modified;
6709     ovs_mutex_unlock(&rule->mutex);
6710
6711     if (rule->hard_timeout) {
6712         expiration = modified + rule->hard_timeout * 1000;
6713     }
6714     if (rule->idle_timeout) {
6715         uint64_t packets, bytes;
6716         long long int used;
6717         long long int idle_expiration;
6718
6719         ofproto->ofproto_class->rule_get_stats(rule, &packets, &bytes, &used);
6720         idle_expiration = used + rule->idle_timeout * 1000;
6721         expiration = MIN(expiration, idle_expiration);
6722     }
6723
6724     if (expiration == LLONG_MAX) {
6725         return 0;
6726     }
6727
6728     /* Calculate the time of expiration as a number of (approximate) seconds
6729      * after program startup.
6730      *
6731      * This should work OK for program runs that last UINT32_MAX seconds or
6732      * less.  Therefore, please restart OVS at least once every 136 years. */
6733     expiration_offset = (expiration >> 10) - (time_boot_msec() >> 10);
6734
6735     /* Invert the expiration offset because we're using a max-heap. */
6736     return UINT32_MAX - expiration_offset;
6737 }
6738
6739 /* Adds 'rule' to an appropriate eviction group for its oftable's
6740  * configuration.  Does nothing if 'rule''s oftable doesn't have eviction
6741  * enabled, or if 'rule' is a permanent rule (one that will never expire on its
6742  * own).
6743  *
6744  * The caller must ensure that 'rule' is not already in an eviction group. */
6745 static void
6746 eviction_group_add_rule(struct rule *rule)
6747     OVS_REQUIRES(ofproto_mutex)
6748 {
6749     struct ofproto *ofproto = rule->ofproto;
6750     struct oftable *table = &ofproto->tables[rule->table_id];
6751     bool has_timeout;
6752
6753     /* Timeouts may be modified only when holding 'ofproto_mutex'.  We have it
6754      * so no additional protection is needed. */
6755     has_timeout = rule->hard_timeout || rule->idle_timeout;
6756
6757     if (table->eviction_fields && has_timeout) {
6758         struct eviction_group *evg;
6759
6760         evg = eviction_group_find(table, eviction_group_hash_rule(rule));
6761
6762         rule->eviction_group = evg;
6763         heap_insert(&evg->rules, &rule->evg_node,
6764                     rule_eviction_priority(ofproto, rule));
6765         eviction_group_resized(table, evg);
6766     }
6767 }
6768 \f
6769 /* oftables. */
6770
6771 /* Initializes 'table'. */
6772 static void
6773 oftable_init(struct oftable *table)
6774 {
6775     memset(table, 0, sizeof *table);
6776     classifier_init(&table->cls, flow_segment_u32s);
6777     table->max_flows = UINT_MAX;
6778     atomic_init(&table->config, (unsigned int)OFPROTO_TABLE_MISS_DEFAULT);
6779 }
6780
6781 /* Destroys 'table', including its classifier and eviction groups.
6782  *
6783  * The caller is responsible for freeing 'table' itself. */
6784 static void
6785 oftable_destroy(struct oftable *table)
6786 {
6787     fat_rwlock_rdlock(&table->cls.rwlock);
6788     ovs_assert(classifier_is_empty(&table->cls));
6789     fat_rwlock_unlock(&table->cls.rwlock);
6790     oftable_disable_eviction(table);
6791     classifier_destroy(&table->cls);
6792     free(table->name);
6793 }
6794
6795 /* Changes the name of 'table' to 'name'.  If 'name' is NULL or the empty
6796  * string, then 'table' will use its default name.
6797  *
6798  * This only affects the name exposed for a table exposed through the OpenFlow
6799  * OFPST_TABLE (as printed by "ovs-ofctl dump-tables"). */
6800 static void
6801 oftable_set_name(struct oftable *table, const char *name)
6802 {
6803     if (name && name[0]) {
6804         int len = strnlen(name, OFP_MAX_TABLE_NAME_LEN);
6805         if (!table->name || strncmp(name, table->name, len)) {
6806             free(table->name);
6807             table->name = xmemdup0(name, len);
6808         }
6809     } else {
6810         free(table->name);
6811         table->name = NULL;
6812     }
6813 }
6814
6815 /* oftables support a choice of two policies when adding a rule would cause the
6816  * number of flows in the table to exceed the configured maximum number: either
6817  * they can refuse to add the new flow or they can evict some existing flow.
6818  * This function configures the former policy on 'table'. */
6819 static void
6820 oftable_disable_eviction(struct oftable *table)
6821     OVS_REQUIRES(ofproto_mutex)
6822 {
6823     if (table->eviction_fields) {
6824         struct eviction_group *evg, *next;
6825
6826         HMAP_FOR_EACH_SAFE (evg, next, id_node,
6827                             &table->eviction_groups_by_id) {
6828             eviction_group_destroy(table, evg);
6829         }
6830         hmap_destroy(&table->eviction_groups_by_id);
6831         heap_destroy(&table->eviction_groups_by_size);
6832
6833         free(table->eviction_fields);
6834         table->eviction_fields = NULL;
6835         table->n_eviction_fields = 0;
6836     }
6837 }
6838
6839 /* oftables support a choice of two policies when adding a rule would cause the
6840  * number of flows in the table to exceed the configured maximum number: either
6841  * they can refuse to add the new flow or they can evict some existing flow.
6842  * This function configures the latter policy on 'table', with fairness based
6843  * on the values of the 'n_fields' fields specified in 'fields'.  (Specifying
6844  * 'n_fields' as 0 disables fairness.) */
6845 static void
6846 oftable_enable_eviction(struct oftable *table,
6847                         const struct mf_subfield *fields, size_t n_fields)
6848     OVS_REQUIRES(ofproto_mutex)
6849 {
6850     struct cls_cursor cursor;
6851     struct rule *rule;
6852
6853     if (table->eviction_fields
6854         && n_fields == table->n_eviction_fields
6855         && (!n_fields
6856             || !memcmp(fields, table->eviction_fields,
6857                        n_fields * sizeof *fields))) {
6858         /* No change. */
6859         return;
6860     }
6861
6862     oftable_disable_eviction(table);
6863
6864     table->n_eviction_fields = n_fields;
6865     table->eviction_fields = xmemdup(fields, n_fields * sizeof *fields);
6866
6867     table->eviction_group_id_basis = random_uint32();
6868     hmap_init(&table->eviction_groups_by_id);
6869     heap_init(&table->eviction_groups_by_size);
6870
6871     fat_rwlock_rdlock(&table->cls.rwlock);
6872     cls_cursor_init(&cursor, &table->cls, NULL);
6873     CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
6874         eviction_group_add_rule(rule);
6875     }
6876     fat_rwlock_unlock(&table->cls.rwlock);
6877 }
6878
6879 /* Removes 'rule' from the oftable that contains it. */
6880 static void
6881 oftable_remove_rule__(struct ofproto *ofproto, struct rule *rule)
6882     OVS_REQUIRES(ofproto_mutex)
6883 {
6884     struct classifier *cls = &ofproto->tables[rule->table_id].cls;
6885
6886     fat_rwlock_wrlock(&cls->rwlock);
6887     classifier_remove(cls, CONST_CAST(struct cls_rule *, &rule->cr));
6888     fat_rwlock_unlock(&cls->rwlock);
6889
6890     cookies_remove(ofproto, rule);
6891
6892     eviction_group_remove_rule(rule);
6893     if (!list_is_empty(&rule->expirable)) {
6894         list_remove(&rule->expirable);
6895     }
6896     if (!list_is_empty(&rule->meter_list_node)) {
6897         list_remove(&rule->meter_list_node);
6898         list_init(&rule->meter_list_node);
6899     }
6900 }
6901
6902 static void
6903 oftable_remove_rule(struct rule *rule)
6904     OVS_REQUIRES(ofproto_mutex)
6905 {
6906     oftable_remove_rule__(rule->ofproto, rule);
6907 }
6908
6909 /* Inserts 'rule' into its oftable, which must not already contain any rule for
6910  * the same cls_rule. */
6911 static void
6912 oftable_insert_rule(struct rule *rule)
6913     OVS_REQUIRES(ofproto_mutex)
6914 {
6915     struct ofproto *ofproto = rule->ofproto;
6916     struct oftable *table = &ofproto->tables[rule->table_id];
6917     struct rule_actions *actions;
6918     bool may_expire;
6919
6920     ovs_mutex_lock(&rule->mutex);
6921     may_expire = rule->hard_timeout || rule->idle_timeout;
6922     ovs_mutex_unlock(&rule->mutex);
6923
6924     if (may_expire) {
6925         list_insert(&ofproto->expirable, &rule->expirable);
6926     }
6927
6928     cookies_insert(ofproto, rule);
6929
6930     actions = rule_get_actions(rule);
6931     if (actions->provider_meter_id != UINT32_MAX) {
6932         uint32_t meter_id = ofpacts_get_meter(actions->ofpacts,
6933                                               actions->ofpacts_len);
6934         struct meter *meter = ofproto->meters[meter_id];
6935         list_insert(&meter->rules, &rule->meter_list_node);
6936     }
6937     fat_rwlock_wrlock(&table->cls.rwlock);
6938     classifier_insert(&table->cls, CONST_CAST(struct cls_rule *, &rule->cr));
6939     fat_rwlock_unlock(&table->cls.rwlock);
6940     eviction_group_add_rule(rule);
6941 }
6942 \f
6943 /* unixctl commands. */
6944
6945 struct ofproto *
6946 ofproto_lookup(const char *name)
6947 {
6948     struct ofproto *ofproto;
6949
6950     HMAP_FOR_EACH_WITH_HASH (ofproto, hmap_node, hash_string(name, 0),
6951                              &all_ofprotos) {
6952         if (!strcmp(ofproto->name, name)) {
6953             return ofproto;
6954         }
6955     }
6956     return NULL;
6957 }
6958
6959 static void
6960 ofproto_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
6961                      const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
6962 {
6963     struct ofproto *ofproto;
6964     struct ds results;
6965
6966     ds_init(&results);
6967     HMAP_FOR_EACH (ofproto, hmap_node, &all_ofprotos) {
6968         ds_put_format(&results, "%s\n", ofproto->name);
6969     }
6970     unixctl_command_reply(conn, ds_cstr(&results));
6971     ds_destroy(&results);
6972 }
6973
6974 static void
6975 ofproto_unixctl_init(void)
6976 {
6977     static bool registered;
6978     if (registered) {
6979         return;
6980     }
6981     registered = true;
6982
6983     unixctl_command_register("ofproto/list", "", 0, 0,
6984                              ofproto_unixctl_list, NULL);
6985 }
6986 \f
6987 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
6988  *
6989  * This is deprecated.  It is only for compatibility with broken device drivers
6990  * in old versions of Linux that do not properly support VLANs when VLAN
6991  * devices are not used.  When broken device drivers are no longer in
6992  * widespread use, we will delete these interfaces. */
6993
6994 /* Sets a 1-bit in the 4096-bit 'vlan_bitmap' for each VLAN ID that is matched
6995  * (exactly) by an OpenFlow rule in 'ofproto'. */
6996 void
6997 ofproto_get_vlan_usage(struct ofproto *ofproto, unsigned long int *vlan_bitmap)
6998 {
6999     const struct oftable *oftable;
7000
7001     free(ofproto->vlan_bitmap);
7002     ofproto->vlan_bitmap = bitmap_allocate(4096);
7003     ofproto->vlans_changed = false;
7004
7005     OFPROTO_FOR_EACH_TABLE (oftable, ofproto) {
7006         const struct cls_subtable *table;
7007
7008         fat_rwlock_rdlock(&oftable->cls.rwlock);
7009         HMAP_FOR_EACH (table, hmap_node, &oftable->cls.subtables) {
7010             if (minimask_get_vid_mask(&table->mask) == VLAN_VID_MASK) {
7011                 const struct cls_rule *rule;
7012
7013                 HMAP_FOR_EACH (rule, hmap_node, &table->rules) {
7014                     uint16_t vid = miniflow_get_vid(&rule->match.flow);
7015                     bitmap_set1(vlan_bitmap, vid);
7016                     bitmap_set1(ofproto->vlan_bitmap, vid);
7017                 }
7018             }
7019         }
7020         fat_rwlock_unlock(&oftable->cls.rwlock);
7021     }
7022 }
7023
7024 /* Returns true if new VLANs have come into use by the flow table since the
7025  * last call to ofproto_get_vlan_usage().
7026  *
7027  * We don't track when old VLANs stop being used. */
7028 bool
7029 ofproto_has_vlan_usage_changed(const struct ofproto *ofproto)
7030 {
7031     return ofproto->vlans_changed;
7032 }
7033
7034 /* Configures a VLAN splinter binding between the ports identified by OpenFlow
7035  * port numbers 'vlandev_ofp_port' and 'realdev_ofp_port'.  If
7036  * 'realdev_ofp_port' is nonzero, then the VLAN device is enslaved to the real
7037  * device as a VLAN splinter for VLAN ID 'vid'.  If 'realdev_ofp_port' is zero,
7038  * then the VLAN device is un-enslaved. */
7039 int
7040 ofproto_port_set_realdev(struct ofproto *ofproto, ofp_port_t vlandev_ofp_port,
7041                          ofp_port_t realdev_ofp_port, int vid)
7042 {
7043     struct ofport *ofport;
7044     int error;
7045
7046     ovs_assert(vlandev_ofp_port != realdev_ofp_port);
7047
7048     ofport = ofproto_get_port(ofproto, vlandev_ofp_port);
7049     if (!ofport) {
7050         VLOG_WARN("%s: cannot set realdev on nonexistent port %"PRIu16,
7051                   ofproto->name, vlandev_ofp_port);
7052         return EINVAL;
7053     }
7054
7055     if (!ofproto->ofproto_class->set_realdev) {
7056         if (!vlandev_ofp_port) {
7057             return 0;
7058         }
7059         VLOG_WARN("%s: vlan splinters not supported", ofproto->name);
7060         return EOPNOTSUPP;
7061     }
7062
7063     error = ofproto->ofproto_class->set_realdev(ofport, realdev_ofp_port, vid);
7064     if (error) {
7065         VLOG_WARN("%s: setting realdev on port %"PRIu16" (%s) failed (%s)",
7066                   ofproto->name, vlandev_ofp_port,
7067                   netdev_get_name(ofport->netdev), ovs_strerror(error));
7068     }
7069     return error;
7070 }