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