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