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