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