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