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