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