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