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