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