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