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