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