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