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