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