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