Separate OpenFlow port numbers from datapath ones.
[openvswitch] / ofproto / ofproto.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012 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 "bitmap.h"
25 #include "byte-order.h"
26 #include "classifier.h"
27 #include "connmgr.h"
28 #include "coverage.h"
29 #include "dynamic-string.h"
30 #include "hash.h"
31 #include "hmap.h"
32 #include "meta-flow.h"
33 #include "netdev.h"
34 #include "nx-match.h"
35 #include "ofp-actions.h"
36 #include "ofp-errors.h"
37 #include "ofp-msgs.h"
38 #include "ofp-print.h"
39 #include "ofp-util.h"
40 #include "ofpbuf.h"
41 #include "ofproto-provider.h"
42 #include "openflow/nicira-ext.h"
43 #include "openflow/openflow.h"
44 #include "packets.h"
45 #include "pinsched.h"
46 #include "pktbuf.h"
47 #include "poll-loop.h"
48 #include "random.h"
49 #include "shash.h"
50 #include "simap.h"
51 #include "sset.h"
52 #include "timeval.h"
53 #include "unaligned.h"
54 #include "unixctl.h"
55 #include "vlog.h"
56
57 VLOG_DEFINE_THIS_MODULE(ofproto);
58
59 COVERAGE_DEFINE(ofproto_error);
60 COVERAGE_DEFINE(ofproto_flush);
61 COVERAGE_DEFINE(ofproto_no_packet_in);
62 COVERAGE_DEFINE(ofproto_packet_out);
63 COVERAGE_DEFINE(ofproto_queue_req);
64 COVERAGE_DEFINE(ofproto_recv_openflow);
65 COVERAGE_DEFINE(ofproto_reinit_ports);
66 COVERAGE_DEFINE(ofproto_uninstallable);
67 COVERAGE_DEFINE(ofproto_update_port);
68
69 enum ofproto_state {
70     S_OPENFLOW,                 /* Processing OpenFlow commands. */
71     S_EVICT,                    /* Evicting flows from over-limit tables. */
72     S_FLUSH,                    /* Deleting all flow table rules. */
73 };
74
75 enum ofoperation_type {
76     OFOPERATION_ADD,
77     OFOPERATION_DELETE,
78     OFOPERATION_MODIFY
79 };
80
81 /* A single OpenFlow request can execute any number of operations.  The
82  * ofopgroup maintain OpenFlow state common to all of the operations, e.g. the
83  * ofconn to which an error reply should be sent if necessary.
84  *
85  * ofproto initiates some operations internally.  These operations are still
86  * assigned to groups but will not have an associated ofconn. */
87 struct ofopgroup {
88     struct ofproto *ofproto;    /* Owning ofproto. */
89     struct list ofproto_node;   /* In ofproto's "pending" list. */
90     struct list ops;            /* List of "struct ofoperation"s. */
91     int n_running;              /* Number of ops still pending. */
92
93     /* Data needed to send OpenFlow reply on failure or to send a buffered
94      * packet on success.
95      *
96      * If list_is_empty(ofconn_node) then this ofopgroup never had an
97      * associated ofconn or its ofconn's connection dropped after it initiated
98      * the operation.  In the latter case 'ofconn' is a wild pointer that
99      * refers to freed memory, so the 'ofconn' member must be used only if
100      * !list_is_empty(ofconn_node).
101      */
102     struct list ofconn_node;    /* In ofconn's list of pending opgroups. */
103     struct ofconn *ofconn;      /* ofconn for reply (but see note above). */
104     struct ofp_header *request; /* Original request (truncated at 64 bytes). */
105     uint32_t buffer_id;         /* Buffer id from original request. */
106 };
107
108 static struct ofopgroup *ofopgroup_create_unattached(struct ofproto *);
109 static struct ofopgroup *ofopgroup_create(struct ofproto *, struct ofconn *,
110                                           const struct ofp_header *,
111                                           uint32_t buffer_id);
112 static void ofopgroup_submit(struct ofopgroup *);
113 static void ofopgroup_complete(struct ofopgroup *);
114
115 /* A single flow table operation. */
116 struct ofoperation {
117     struct ofopgroup *group;    /* Owning group. */
118     struct list group_node;     /* In ofopgroup's "ops" list. */
119     struct hmap_node hmap_node; /* In ofproto's "deletions" hmap. */
120     struct rule *rule;          /* Rule being operated upon. */
121     enum ofoperation_type type; /* Type of operation. */
122
123     /* OFOPERATION_ADD. */
124     struct rule *victim;        /* Rule being replaced, if any.. */
125
126     /* OFOPERATION_MODIFY: The old actions, if the actions are changing. */
127     struct ofpact *ofpacts;
128     size_t ofpacts_len;
129
130     /* OFOPERATION_DELETE. */
131     enum ofp_flow_removed_reason reason; /* Reason flow was removed. */
132
133     ovs_be64 flow_cookie;       /* Rule's old flow cookie. */
134     enum ofperr error;          /* 0 if no error. */
135 };
136
137 static struct ofoperation *ofoperation_create(struct ofopgroup *,
138                                               struct rule *,
139                                               enum ofoperation_type,
140                                               enum ofp_flow_removed_reason);
141 static void ofoperation_destroy(struct ofoperation *);
142
143 /* oftable. */
144 static void oftable_init(struct oftable *);
145 static void oftable_destroy(struct oftable *);
146
147 static void oftable_set_name(struct oftable *, const char *name);
148
149 static void oftable_disable_eviction(struct oftable *);
150 static void oftable_enable_eviction(struct oftable *,
151                                     const struct mf_subfield *fields,
152                                     size_t n_fields);
153
154 static void oftable_remove_rule(struct rule *);
155 static struct rule *oftable_replace_rule(struct rule *);
156 static void oftable_substitute_rule(struct rule *old, struct rule *new);
157
158 /* A set of rules within a single OpenFlow table (oftable) that have the same
159  * values for the oftable's eviction_fields.  A rule to be evicted, when one is
160  * needed, is taken from the eviction group that contains the greatest number
161  * of rules.
162  *
163  * An oftable owns any number of eviction groups, each of which contains any
164  * number of rules.
165  *
166  * Membership in an eviction group is imprecise, based on the hash of the
167  * oftable's eviction_fields (in the eviction_group's id_node.hash member).
168  * That is, if two rules have different eviction_fields, but those
169  * eviction_fields hash to the same value, then they will belong to the same
170  * eviction_group anyway.
171  *
172  * (When eviction is not enabled on an oftable, we don't track any eviction
173  * groups, to save time and space.) */
174 struct eviction_group {
175     struct hmap_node id_node;   /* In oftable's "eviction_groups_by_id". */
176     struct heap_node size_node; /* In oftable's "eviction_groups_by_size". */
177     struct heap rules;          /* Contains "struct rule"s. */
178 };
179
180 static struct rule *choose_rule_to_evict(struct oftable *);
181 static void ofproto_evict(struct ofproto *);
182 static uint32_t rule_eviction_priority(struct rule *);
183
184 /* ofport. */
185 static void ofport_destroy__(struct ofport *);
186 static void ofport_destroy(struct ofport *);
187
188 static void update_port(struct ofproto *, const char *devname);
189 static int init_ports(struct ofproto *);
190 static void reinit_ports(struct ofproto *);
191
192 /* rule. */
193 static void ofproto_rule_destroy__(struct rule *);
194 static void ofproto_rule_send_removed(struct rule *, uint8_t reason);
195 static bool rule_is_modifiable(const struct rule *);
196
197 /* OpenFlow. */
198 static enum ofperr add_flow(struct ofproto *, struct ofconn *,
199                             const struct ofputil_flow_mod *,
200                             const struct ofp_header *);
201 static void delete_flow__(struct rule *, struct ofopgroup *);
202 static bool handle_openflow(struct ofconn *, struct ofpbuf *);
203 static enum ofperr handle_flow_mod__(struct ofproto *, struct ofconn *,
204                                      const struct ofputil_flow_mod *,
205                                      const struct ofp_header *);
206
207 /* ofproto. */
208 static uint64_t pick_datapath_id(const struct ofproto *);
209 static uint64_t pick_fallback_dpid(void);
210 static void ofproto_destroy__(struct ofproto *);
211 static void update_mtu(struct ofproto *, struct ofport *);
212
213 /* unixctl. */
214 static void ofproto_unixctl_init(void);
215
216 /* All registered ofproto classes, in probe order. */
217 static const struct ofproto_class **ofproto_classes;
218 static size_t n_ofproto_classes;
219 static size_t allocated_ofproto_classes;
220
221 /* Map from datapath name to struct ofproto, for use by unixctl commands. */
222 static struct hmap all_ofprotos = HMAP_INITIALIZER(&all_ofprotos);
223
224 /* Initial mappings of port to OpenFlow number mappings. */
225 static struct shash init_ofp_ports = SHASH_INITIALIZER(&init_ofp_ports);
226
227 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
228
229 /* Must be called to initialize the ofproto library.
230  *
231  * The caller may pass in 'iface_hints', which contains an shash of
232  * "iface_hint" elements indexed by the interface's name.  The provider
233  * may use these hints to describe the startup configuration in order to
234  * reinitialize its state.  The caller owns the provided data, so a
235  * provider will make copies of anything required.  An ofproto provider
236  * will remove any existing state that is not described by the hint, and
237  * may choose to remove it all. */
238 void
239 ofproto_init(const struct shash *iface_hints)
240 {
241     struct shash_node *node;
242     size_t i;
243
244     ofproto_class_register(&ofproto_dpif_class);
245
246     /* Make a local copy, since we don't own 'iface_hints' elements. */
247     SHASH_FOR_EACH(node, iface_hints) {
248         const struct iface_hint *orig_hint = node->data;
249         struct iface_hint *new_hint = xmalloc(sizeof *new_hint);
250         const char *br_type = ofproto_normalize_type(orig_hint->br_type);
251
252         new_hint->br_name = xstrdup(orig_hint->br_name);
253         new_hint->br_type = xstrdup(br_type);
254         new_hint->ofp_port = orig_hint->ofp_port;
255
256         shash_add(&init_ofp_ports, node->name, new_hint);
257     }
258
259     for (i = 0; i < n_ofproto_classes; i++) {
260         ofproto_classes[i]->init(&init_ofp_ports);
261     }
262 }
263
264 /* 'type' should be a normalized datapath type, as returned by
265  * ofproto_normalize_type().  Returns the corresponding ofproto_class
266  * structure, or a null pointer if there is none registered for 'type'. */
267 static const struct ofproto_class *
268 ofproto_class_find__(const char *type)
269 {
270     size_t i;
271
272     for (i = 0; i < n_ofproto_classes; i++) {
273         const struct ofproto_class *class = ofproto_classes[i];
274         struct sset types;
275         bool found;
276
277         sset_init(&types);
278         class->enumerate_types(&types);
279         found = sset_contains(&types, type);
280         sset_destroy(&types);
281
282         if (found) {
283             return class;
284         }
285     }
286     VLOG_WARN("unknown datapath type %s", type);
287     return NULL;
288 }
289
290 /* Registers a new ofproto class.  After successful registration, new ofprotos
291  * of that type can be created using ofproto_create(). */
292 int
293 ofproto_class_register(const struct ofproto_class *new_class)
294 {
295     size_t i;
296
297     for (i = 0; i < n_ofproto_classes; i++) {
298         if (ofproto_classes[i] == new_class) {
299             return EEXIST;
300         }
301     }
302
303     if (n_ofproto_classes >= allocated_ofproto_classes) {
304         ofproto_classes = x2nrealloc(ofproto_classes,
305                                      &allocated_ofproto_classes,
306                                      sizeof *ofproto_classes);
307     }
308     ofproto_classes[n_ofproto_classes++] = new_class;
309     return 0;
310 }
311
312 /* Unregisters a datapath provider.  'type' must have been previously
313  * registered and not currently be in use by any ofprotos.  After
314  * unregistration new datapaths of that type cannot be opened using
315  * ofproto_create(). */
316 int
317 ofproto_class_unregister(const struct ofproto_class *class)
318 {
319     size_t i;
320
321     for (i = 0; i < n_ofproto_classes; i++) {
322         if (ofproto_classes[i] == class) {
323             for (i++; i < n_ofproto_classes; i++) {
324                 ofproto_classes[i - 1] = ofproto_classes[i];
325             }
326             n_ofproto_classes--;
327             return 0;
328         }
329     }
330     VLOG_WARN("attempted to unregister an ofproto class that is not "
331               "registered");
332     return EAFNOSUPPORT;
333 }
334
335 /* Clears 'types' and enumerates all registered ofproto types into it.  The
336  * caller must first initialize the sset. */
337 void
338 ofproto_enumerate_types(struct sset *types)
339 {
340     size_t i;
341
342     for (i = 0; i < n_ofproto_classes; i++) {
343         ofproto_classes[i]->enumerate_types(types);
344     }
345 }
346
347 /* Returns the fully spelled out name for the given ofproto 'type'.
348  *
349  * Normalized type string can be compared with strcmp().  Unnormalized type
350  * string might be the same even if they have different spellings. */
351 const char *
352 ofproto_normalize_type(const char *type)
353 {
354     return type && type[0] ? type : "system";
355 }
356
357 /* Clears 'names' and enumerates the names of all known created ofprotos with
358  * the given 'type'.  The caller must first initialize the sset.  Returns 0 if
359  * successful, otherwise a positive errno value.
360  *
361  * Some kinds of datapaths might not be practically enumerable.  This is not
362  * considered an error. */
363 int
364 ofproto_enumerate_names(const char *type, struct sset *names)
365 {
366     const struct ofproto_class *class = ofproto_class_find__(type);
367     return class ? class->enumerate_names(type, names) : EAFNOSUPPORT;
368  }
369
370 int
371 ofproto_create(const char *datapath_name, const char *datapath_type,
372                struct ofproto **ofprotop)
373 {
374     const struct ofproto_class *class;
375     struct ofproto *ofproto;
376     int error;
377
378     *ofprotop = NULL;
379
380     ofproto_unixctl_init();
381
382     datapath_type = ofproto_normalize_type(datapath_type);
383     class = ofproto_class_find__(datapath_type);
384     if (!class) {
385         VLOG_WARN("could not create datapath %s of unknown type %s",
386                   datapath_name, datapath_type);
387         return EAFNOSUPPORT;
388     }
389
390     ofproto = class->alloc();
391     if (!ofproto) {
392         VLOG_ERR("failed to allocate datapath %s of type %s",
393                  datapath_name, datapath_type);
394         return ENOMEM;
395     }
396
397     /* Initialize. */
398     memset(ofproto, 0, sizeof *ofproto);
399     ofproto->ofproto_class = class;
400     ofproto->name = xstrdup(datapath_name);
401     ofproto->type = xstrdup(datapath_type);
402     hmap_insert(&all_ofprotos, &ofproto->hmap_node,
403                 hash_string(ofproto->name, 0));
404     ofproto->datapath_id = 0;
405     ofproto_set_flow_eviction_threshold(ofproto,
406                                         OFPROTO_FLOW_EVICTION_THRESHOLD_DEFAULT);
407     ofproto->forward_bpdu = false;
408     ofproto->fallback_dpid = pick_fallback_dpid();
409     ofproto->mfr_desc = xstrdup(DEFAULT_MFR_DESC);
410     ofproto->hw_desc = xstrdup(DEFAULT_HW_DESC);
411     ofproto->sw_desc = xstrdup(DEFAULT_SW_DESC);
412     ofproto->serial_desc = xstrdup(DEFAULT_SERIAL_DESC);
413     ofproto->dp_desc = xstrdup(DEFAULT_DP_DESC);
414     ofproto->frag_handling = OFPC_FRAG_NORMAL;
415     hmap_init(&ofproto->ports);
416     shash_init(&ofproto->port_by_name);
417     simap_init(&ofproto->ofp_requests);
418     ofproto->max_ports = OFPP_MAX;
419     ofproto->tables = NULL;
420     ofproto->n_tables = 0;
421     ofproto->connmgr = connmgr_create(ofproto, datapath_name, datapath_name);
422     ofproto->state = S_OPENFLOW;
423     list_init(&ofproto->pending);
424     ofproto->n_pending = 0;
425     hmap_init(&ofproto->deletions);
426     ofproto->n_add = ofproto->n_delete = ofproto->n_modify = 0;
427     ofproto->first_op = ofproto->last_op = LLONG_MIN;
428     ofproto->next_op_report = LLONG_MAX;
429     ofproto->op_backoff = LLONG_MIN;
430     ofproto->vlan_bitmap = NULL;
431     ofproto->vlans_changed = false;
432     ofproto->min_mtu = INT_MAX;
433
434     error = ofproto->ofproto_class->construct(ofproto);
435     if (error) {
436         VLOG_ERR("failed to open datapath %s: %s",
437                  datapath_name, strerror(error));
438         ofproto_destroy__(ofproto);
439         return error;
440     }
441
442     /* The "max_ports" member should have been set by ->construct(ofproto).
443      * Port 0 is not a valid OpenFlow port, so mark that as unavailable. */
444     ofproto->ofp_port_ids = bitmap_allocate(ofproto->max_ports);
445     bitmap_set1(ofproto->ofp_port_ids, 0);
446
447     assert(ofproto->n_tables);
448
449     ofproto->datapath_id = pick_datapath_id(ofproto);
450     init_ports(ofproto);
451
452     *ofprotop = ofproto;
453     return 0;
454 }
455
456 /* Must be called (only) by an ofproto implementation in its constructor
457  * function.  See the large comment on 'construct' in struct ofproto_class for
458  * details. */
459 void
460 ofproto_init_tables(struct ofproto *ofproto, int n_tables)
461 {
462     struct oftable *table;
463
464     assert(!ofproto->n_tables);
465     assert(n_tables >= 1 && n_tables <= 255);
466
467     ofproto->n_tables = n_tables;
468     ofproto->tables = xmalloc(n_tables * sizeof *ofproto->tables);
469     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
470         oftable_init(table);
471     }
472 }
473
474 /* To be optionally called (only) by an ofproto implementation in its
475  * constructor function.  See the large comment on 'construct' in struct
476  * ofproto_class for details.
477  *
478  * Sets the maximum number of ports to 'max_ports'.  The ofproto generic layer
479  * will then ensure that actions passed into the ofproto implementation will
480  * not refer to OpenFlow ports numbered 'max_ports' or higher.  If this
481  * function is not called, there will be no such restriction.
482  *
483  * Reserved ports numbered OFPP_MAX and higher are special and not subject to
484  * the 'max_ports' restriction. */
485 void
486 ofproto_init_max_ports(struct ofproto *ofproto, uint16_t max_ports)
487 {
488     assert(max_ports <= OFPP_MAX);
489     ofproto->max_ports = max_ports;
490 }
491
492 uint64_t
493 ofproto_get_datapath_id(const struct ofproto *ofproto)
494 {
495     return ofproto->datapath_id;
496 }
497
498 void
499 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
500 {
501     uint64_t old_dpid = p->datapath_id;
502     p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
503     if (p->datapath_id != old_dpid) {
504         /* Force all active connections to reconnect, since there is no way to
505          * notify a controller that the datapath ID has changed. */
506         ofproto_reconnect_controllers(p);
507     }
508 }
509
510 void
511 ofproto_set_controllers(struct ofproto *p,
512                         const struct ofproto_controller *controllers,
513                         size_t n_controllers)
514 {
515     connmgr_set_controllers(p->connmgr, controllers, n_controllers);
516 }
517
518 void
519 ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
520 {
521     connmgr_set_fail_mode(p->connmgr, fail_mode);
522 }
523
524 /* Drops the connections between 'ofproto' and all of its controllers, forcing
525  * them to reconnect. */
526 void
527 ofproto_reconnect_controllers(struct ofproto *ofproto)
528 {
529     connmgr_reconnect(ofproto->connmgr);
530 }
531
532 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
533  * in-band control should guarantee access, in the same way that in-band
534  * control guarantees access to OpenFlow controllers. */
535 void
536 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
537                                   const struct sockaddr_in *extras, size_t n)
538 {
539     connmgr_set_extra_in_band_remotes(ofproto->connmgr, extras, n);
540 }
541
542 /* Sets the OpenFlow queue used by flows set up by in-band control on
543  * 'ofproto' to 'queue_id'.  If 'queue_id' is negative, then in-band control
544  * flows will use the default queue. */
545 void
546 ofproto_set_in_band_queue(struct ofproto *ofproto, int queue_id)
547 {
548     connmgr_set_in_band_queue(ofproto->connmgr, queue_id);
549 }
550
551 /* Sets the number of flows at which eviction from the kernel flow table
552  * will occur. */
553 void
554 ofproto_set_flow_eviction_threshold(struct ofproto *ofproto, unsigned threshold)
555 {
556     if (threshold < OFPROTO_FLOW_EVICTION_THRESHOLD_MIN) {
557         ofproto->flow_eviction_threshold = OFPROTO_FLOW_EVICTION_THRESHOLD_MIN;
558     } else {
559         ofproto->flow_eviction_threshold = threshold;
560     }
561 }
562
563 /* If forward_bpdu is true, the NORMAL action will forward frames with
564  * reserved (e.g. STP) destination Ethernet addresses. if forward_bpdu is false,
565  * the NORMAL action will drop these frames. */
566 void
567 ofproto_set_forward_bpdu(struct ofproto *ofproto, bool forward_bpdu)
568 {
569     bool old_val = ofproto->forward_bpdu;
570     ofproto->forward_bpdu = forward_bpdu;
571     if (old_val != ofproto->forward_bpdu) {
572         if (ofproto->ofproto_class->forward_bpdu_changed) {
573             ofproto->ofproto_class->forward_bpdu_changed(ofproto);
574         }
575     }
576 }
577
578 /* Sets the MAC aging timeout for the OFPP_NORMAL action on 'ofproto' to
579  * 'idle_time', in seconds. */
580 void
581 ofproto_set_mac_idle_time(struct ofproto *ofproto, unsigned idle_time)
582 {
583     if (ofproto->ofproto_class->set_mac_idle_time) {
584         ofproto->ofproto_class->set_mac_idle_time(ofproto, idle_time);
585     }
586 }
587
588 void
589 ofproto_set_desc(struct ofproto *p,
590                  const char *mfr_desc, const char *hw_desc,
591                  const char *sw_desc, const char *serial_desc,
592                  const char *dp_desc)
593 {
594     struct ofp_desc_stats *ods;
595
596     if (mfr_desc) {
597         if (strlen(mfr_desc) >= sizeof ods->mfr_desc) {
598             VLOG_WARN("%s: truncating mfr_desc, must be less than %zu bytes",
599                       p->name, sizeof ods->mfr_desc);
600         }
601         free(p->mfr_desc);
602         p->mfr_desc = xstrdup(mfr_desc);
603     }
604     if (hw_desc) {
605         if (strlen(hw_desc) >= sizeof ods->hw_desc) {
606             VLOG_WARN("%s: truncating hw_desc, must be less than %zu bytes",
607                       p->name, sizeof ods->hw_desc);
608         }
609         free(p->hw_desc);
610         p->hw_desc = xstrdup(hw_desc);
611     }
612     if (sw_desc) {
613         if (strlen(sw_desc) >= sizeof ods->sw_desc) {
614             VLOG_WARN("%s: truncating sw_desc, must be less than %zu bytes",
615                       p->name, sizeof ods->sw_desc);
616         }
617         free(p->sw_desc);
618         p->sw_desc = xstrdup(sw_desc);
619     }
620     if (serial_desc) {
621         if (strlen(serial_desc) >= sizeof ods->serial_num) {
622             VLOG_WARN("%s: truncating serial_desc, must be less than %zu "
623                       "bytes", p->name, sizeof ods->serial_num);
624         }
625         free(p->serial_desc);
626         p->serial_desc = xstrdup(serial_desc);
627     }
628     if (dp_desc) {
629         if (strlen(dp_desc) >= sizeof ods->dp_desc) {
630             VLOG_WARN("%s: truncating dp_desc, must be less than %zu bytes",
631                       p->name, sizeof ods->dp_desc);
632         }
633         free(p->dp_desc);
634         p->dp_desc = xstrdup(dp_desc);
635     }
636 }
637
638 int
639 ofproto_set_snoops(struct ofproto *ofproto, const struct sset *snoops)
640 {
641     return connmgr_set_snoops(ofproto->connmgr, snoops);
642 }
643
644 int
645 ofproto_set_netflow(struct ofproto *ofproto,
646                     const struct netflow_options *nf_options)
647 {
648     if (nf_options && sset_is_empty(&nf_options->collectors)) {
649         nf_options = NULL;
650     }
651
652     if (ofproto->ofproto_class->set_netflow) {
653         return ofproto->ofproto_class->set_netflow(ofproto, nf_options);
654     } else {
655         return nf_options ? EOPNOTSUPP : 0;
656     }
657 }
658
659 int
660 ofproto_set_sflow(struct ofproto *ofproto,
661                   const struct ofproto_sflow_options *oso)
662 {
663     if (oso && sset_is_empty(&oso->targets)) {
664         oso = NULL;
665     }
666
667     if (ofproto->ofproto_class->set_sflow) {
668         return ofproto->ofproto_class->set_sflow(ofproto, oso);
669     } else {
670         return oso ? EOPNOTSUPP : 0;
671     }
672 }
673 \f
674 /* Spanning Tree Protocol (STP) configuration. */
675
676 /* Configures STP on 'ofproto' using the settings defined in 's'.  If
677  * 's' is NULL, disables STP.
678  *
679  * Returns 0 if successful, otherwise a positive errno value. */
680 int
681 ofproto_set_stp(struct ofproto *ofproto,
682                 const struct ofproto_stp_settings *s)
683 {
684     return (ofproto->ofproto_class->set_stp
685             ? ofproto->ofproto_class->set_stp(ofproto, s)
686             : EOPNOTSUPP);
687 }
688
689 /* Retrieves STP status of 'ofproto' and stores it in 's'.  If the
690  * 'enabled' member of 's' is false, then the other members are not
691  * meaningful.
692  *
693  * Returns 0 if successful, otherwise a positive errno value. */
694 int
695 ofproto_get_stp_status(struct ofproto *ofproto,
696                        struct ofproto_stp_status *s)
697 {
698     return (ofproto->ofproto_class->get_stp_status
699             ? ofproto->ofproto_class->get_stp_status(ofproto, s)
700             : EOPNOTSUPP);
701 }
702
703 /* Configures STP on 'ofp_port' of 'ofproto' using the settings defined
704  * in 's'.  The caller is responsible for assigning STP port numbers
705  * (using the 'port_num' member in the range of 1 through 255, inclusive)
706  * and ensuring there are no duplicates.  If the 's' is NULL, then STP
707  * is disabled on the port.
708  *
709  * Returns 0 if successful, otherwise a positive errno value.*/
710 int
711 ofproto_port_set_stp(struct ofproto *ofproto, uint16_t ofp_port,
712                      const struct ofproto_port_stp_settings *s)
713 {
714     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
715     if (!ofport) {
716         VLOG_WARN("%s: cannot configure STP on nonexistent port %"PRIu16,
717                   ofproto->name, ofp_port);
718         return ENODEV;
719     }
720
721     return (ofproto->ofproto_class->set_stp_port
722             ? ofproto->ofproto_class->set_stp_port(ofport, s)
723             : EOPNOTSUPP);
724 }
725
726 /* Retrieves STP port status of 'ofp_port' on 'ofproto' and stores it in
727  * 's'.  If the 'enabled' member in 's' is false, then the other members
728  * are not meaningful.
729  *
730  * Returns 0 if successful, otherwise a positive errno value.*/
731 int
732 ofproto_port_get_stp_status(struct ofproto *ofproto, uint16_t ofp_port,
733                             struct ofproto_port_stp_status *s)
734 {
735     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
736     if (!ofport) {
737         VLOG_WARN_RL(&rl, "%s: cannot get STP status on nonexistent "
738                      "port %"PRIu16, ofproto->name, ofp_port);
739         return ENODEV;
740     }
741
742     return (ofproto->ofproto_class->get_stp_port_status
743             ? ofproto->ofproto_class->get_stp_port_status(ofport, s)
744             : EOPNOTSUPP);
745 }
746 \f
747 /* Queue DSCP configuration. */
748
749 /* Registers meta-data associated with the 'n_qdscp' Qualities of Service
750  * 'queues' attached to 'ofport'.  This data is not intended to be sufficient
751  * to implement QoS.  Instead, it is used to implement features which require
752  * knowledge of what queues exist on a port, and some basic information about
753  * them.
754  *
755  * Returns 0 if successful, otherwise a positive errno value. */
756 int
757 ofproto_port_set_queues(struct ofproto *ofproto, uint16_t ofp_port,
758                         const struct ofproto_port_queue *queues,
759                         size_t n_queues)
760 {
761     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
762
763     if (!ofport) {
764         VLOG_WARN("%s: cannot set queues on nonexistent port %"PRIu16,
765                   ofproto->name, ofp_port);
766         return ENODEV;
767     }
768
769     return (ofproto->ofproto_class->set_queues
770             ? ofproto->ofproto_class->set_queues(ofport, queues, n_queues)
771             : EOPNOTSUPP);
772 }
773 \f
774 /* Connectivity Fault Management configuration. */
775
776 /* Clears the CFM configuration from 'ofp_port' on 'ofproto'. */
777 void
778 ofproto_port_clear_cfm(struct ofproto *ofproto, uint16_t ofp_port)
779 {
780     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
781     if (ofport && ofproto->ofproto_class->set_cfm) {
782         ofproto->ofproto_class->set_cfm(ofport, NULL);
783     }
784 }
785
786 /* Configures connectivity fault management on 'ofp_port' in 'ofproto'.  Takes
787  * basic configuration from the configuration members in 'cfm', and the remote
788  * maintenance point ID from  remote_mpid.  Ignores the statistics members of
789  * 'cfm'.
790  *
791  * This function has no effect if 'ofproto' does not have a port 'ofp_port'. */
792 void
793 ofproto_port_set_cfm(struct ofproto *ofproto, uint16_t ofp_port,
794                      const struct cfm_settings *s)
795 {
796     struct ofport *ofport;
797     int error;
798
799     ofport = ofproto_get_port(ofproto, ofp_port);
800     if (!ofport) {
801         VLOG_WARN("%s: cannot configure CFM on nonexistent port %"PRIu16,
802                   ofproto->name, ofp_port);
803         return;
804     }
805
806     /* XXX: For configuration simplicity, we only support one remote_mpid
807      * outside of the CFM module.  It's not clear if this is the correct long
808      * term solution or not. */
809     error = (ofproto->ofproto_class->set_cfm
810              ? ofproto->ofproto_class->set_cfm(ofport, s)
811              : EOPNOTSUPP);
812     if (error) {
813         VLOG_WARN("%s: CFM configuration on port %"PRIu16" (%s) failed (%s)",
814                   ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
815                   strerror(error));
816     }
817 }
818
819 /* Checks the status of LACP negotiation for 'ofp_port' within ofproto.
820  * Returns 1 if LACP partner information for 'ofp_port' is up-to-date,
821  * 0 if LACP partner information is not current (generally indicating a
822  * connectivity problem), or -1 if LACP is not enabled on 'ofp_port'. */
823 int
824 ofproto_port_is_lacp_current(struct ofproto *ofproto, uint16_t ofp_port)
825 {
826     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
827     return (ofport && ofproto->ofproto_class->port_is_lacp_current
828             ? ofproto->ofproto_class->port_is_lacp_current(ofport)
829             : -1);
830 }
831 \f
832 /* Bundles. */
833
834 /* Registers a "bundle" associated with client data pointer 'aux' in 'ofproto'.
835  * A bundle is the same concept as a Port in OVSDB, that is, it consists of one
836  * or more "slave" devices (Interfaces, in OVSDB) along with a VLAN
837  * configuration plus, if there is more than one slave, a bonding
838  * configuration.
839  *
840  * If 'aux' is already registered then this function updates its configuration
841  * to 's'.  Otherwise, this function registers a new bundle.
842  *
843  * Bundles only affect the NXAST_AUTOPATH action and output to the OFPP_NORMAL
844  * port. */
845 int
846 ofproto_bundle_register(struct ofproto *ofproto, void *aux,
847                         const struct ofproto_bundle_settings *s)
848 {
849     return (ofproto->ofproto_class->bundle_set
850             ? ofproto->ofproto_class->bundle_set(ofproto, aux, s)
851             : EOPNOTSUPP);
852 }
853
854 /* Unregisters the bundle registered on 'ofproto' with auxiliary data 'aux'.
855  * If no such bundle has been registered, this has no effect. */
856 int
857 ofproto_bundle_unregister(struct ofproto *ofproto, void *aux)
858 {
859     return ofproto_bundle_register(ofproto, aux, NULL);
860 }
861
862 \f
863 /* Registers a mirror associated with client data pointer 'aux' in 'ofproto'.
864  * If 'aux' is already registered then this function updates its configuration
865  * to 's'.  Otherwise, this function registers a new mirror. */
866 int
867 ofproto_mirror_register(struct ofproto *ofproto, void *aux,
868                         const struct ofproto_mirror_settings *s)
869 {
870     return (ofproto->ofproto_class->mirror_set
871             ? ofproto->ofproto_class->mirror_set(ofproto, aux, s)
872             : EOPNOTSUPP);
873 }
874
875 /* Unregisters the mirror registered on 'ofproto' with auxiliary data 'aux'.
876  * If no mirror has been registered, this has no effect. */
877 int
878 ofproto_mirror_unregister(struct ofproto *ofproto, void *aux)
879 {
880     return ofproto_mirror_register(ofproto, aux, NULL);
881 }
882
883 /* Retrieves statistics from mirror associated with client data pointer
884  * 'aux' in 'ofproto'.  Stores packet and byte counts in 'packets' and
885  * 'bytes', respectively.  If a particular counters is not supported,
886  * the appropriate argument is set to UINT64_MAX. */
887 int
888 ofproto_mirror_get_stats(struct ofproto *ofproto, void *aux,
889                          uint64_t *packets, uint64_t *bytes)
890 {
891     if (!ofproto->ofproto_class->mirror_get_stats) {
892         *packets = *bytes = UINT64_MAX;
893         return EOPNOTSUPP;
894     }
895
896     return ofproto->ofproto_class->mirror_get_stats(ofproto, aux,
897                                                     packets, bytes);
898 }
899
900 /* Configures the VLANs whose bits are set to 1 in 'flood_vlans' as VLANs on
901  * which all packets are flooded, instead of using MAC learning.  If
902  * 'flood_vlans' is NULL, then MAC learning applies to all VLANs.
903  *
904  * Flood VLANs affect only the treatment of packets output to the OFPP_NORMAL
905  * port. */
906 int
907 ofproto_set_flood_vlans(struct ofproto *ofproto, unsigned long *flood_vlans)
908 {
909     return (ofproto->ofproto_class->set_flood_vlans
910             ? ofproto->ofproto_class->set_flood_vlans(ofproto, flood_vlans)
911             : EOPNOTSUPP);
912 }
913
914 /* Returns true if 'aux' is a registered bundle that is currently in use as the
915  * output for a mirror. */
916 bool
917 ofproto_is_mirror_output_bundle(const struct ofproto *ofproto, void *aux)
918 {
919     return (ofproto->ofproto_class->is_mirror_output_bundle
920             ? ofproto->ofproto_class->is_mirror_output_bundle(ofproto, aux)
921             : false);
922 }
923 \f
924 /* Configuration of OpenFlow tables. */
925
926 /* Returns the number of OpenFlow tables in 'ofproto'. */
927 int
928 ofproto_get_n_tables(const struct ofproto *ofproto)
929 {
930     return ofproto->n_tables;
931 }
932
933 /* Configures the OpenFlow table in 'ofproto' with id 'table_id' with the
934  * settings from 's'.  'table_id' must be in the range 0 through the number of
935  * OpenFlow tables in 'ofproto' minus 1, inclusive.
936  *
937  * For read-only tables, only the name may be configured. */
938 void
939 ofproto_configure_table(struct ofproto *ofproto, int table_id,
940                         const struct ofproto_table_settings *s)
941 {
942     struct oftable *table;
943
944     assert(table_id >= 0 && table_id < ofproto->n_tables);
945     table = &ofproto->tables[table_id];
946
947     oftable_set_name(table, s->name);
948
949     if (table->flags & OFTABLE_READONLY) {
950         return;
951     }
952
953     if (s->groups) {
954         oftable_enable_eviction(table, s->groups, s->n_groups);
955     } else {
956         oftable_disable_eviction(table);
957     }
958
959     table->max_flows = s->max_flows;
960     if (classifier_count(&table->cls) > table->max_flows
961         && table->eviction_fields) {
962         /* 'table' contains more flows than allowed.  We might not be able to
963          * evict them right away because of the asynchronous nature of flow
964          * table changes.  Schedule eviction for later. */
965         switch (ofproto->state) {
966         case S_OPENFLOW:
967             ofproto->state = S_EVICT;
968             break;
969         case S_EVICT:
970         case S_FLUSH:
971             /* We're already deleting flows, nothing more to do. */
972             break;
973         }
974     }
975 }
976 \f
977 bool
978 ofproto_has_snoops(const struct ofproto *ofproto)
979 {
980     return connmgr_has_snoops(ofproto->connmgr);
981 }
982
983 void
984 ofproto_get_snoops(const struct ofproto *ofproto, struct sset *snoops)
985 {
986     connmgr_get_snoops(ofproto->connmgr, snoops);
987 }
988
989 static void
990 ofproto_flush__(struct ofproto *ofproto)
991 {
992     struct ofopgroup *group;
993     struct oftable *table;
994
995     if (ofproto->ofproto_class->flush) {
996         ofproto->ofproto_class->flush(ofproto);
997     }
998
999     group = ofopgroup_create_unattached(ofproto);
1000     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1001         struct rule *rule, *next_rule;
1002         struct cls_cursor cursor;
1003
1004         if (table->flags & OFTABLE_HIDDEN) {
1005             continue;
1006         }
1007
1008         cls_cursor_init(&cursor, &table->cls, NULL);
1009         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
1010             if (!rule->pending) {
1011                 ofoperation_create(group, rule, OFOPERATION_DELETE,
1012                                    OFPRR_DELETE);
1013                 oftable_remove_rule(rule);
1014                 ofproto->ofproto_class->rule_destruct(rule);
1015             }
1016         }
1017     }
1018     ofopgroup_submit(group);
1019 }
1020
1021 static void
1022 ofproto_destroy__(struct ofproto *ofproto)
1023 {
1024     struct oftable *table;
1025
1026     assert(list_is_empty(&ofproto->pending));
1027     assert(!ofproto->n_pending);
1028
1029     connmgr_destroy(ofproto->connmgr);
1030
1031     hmap_remove(&all_ofprotos, &ofproto->hmap_node);
1032     free(ofproto->name);
1033     free(ofproto->type);
1034     free(ofproto->mfr_desc);
1035     free(ofproto->hw_desc);
1036     free(ofproto->sw_desc);
1037     free(ofproto->serial_desc);
1038     free(ofproto->dp_desc);
1039     hmap_destroy(&ofproto->ports);
1040     shash_destroy(&ofproto->port_by_name);
1041     bitmap_free(ofproto->ofp_port_ids);
1042     simap_destroy(&ofproto->ofp_requests);
1043
1044     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1045         oftable_destroy(table);
1046     }
1047     free(ofproto->tables);
1048
1049     hmap_destroy(&ofproto->deletions);
1050
1051     free(ofproto->vlan_bitmap);
1052
1053     ofproto->ofproto_class->dealloc(ofproto);
1054 }
1055
1056 void
1057 ofproto_destroy(struct ofproto *p)
1058 {
1059     struct ofport *ofport, *next_ofport;
1060
1061     if (!p) {
1062         return;
1063     }
1064
1065     ofproto_flush__(p);
1066     HMAP_FOR_EACH_SAFE (ofport, next_ofport, hmap_node, &p->ports) {
1067         ofport_destroy(ofport);
1068     }
1069
1070     p->ofproto_class->destruct(p);
1071     ofproto_destroy__(p);
1072 }
1073
1074 /* Destroys the datapath with the respective 'name' and 'type'.  With the Linux
1075  * kernel datapath, for example, this destroys the datapath in the kernel, and
1076  * with the netdev-based datapath, it tears down the data structures that
1077  * represent the datapath.
1078  *
1079  * The datapath should not be currently open as an ofproto. */
1080 int
1081 ofproto_delete(const char *name, const char *type)
1082 {
1083     const struct ofproto_class *class = ofproto_class_find__(type);
1084     return (!class ? EAFNOSUPPORT
1085             : !class->del ? EACCES
1086             : class->del(type, name));
1087 }
1088
1089 static void
1090 process_port_change(struct ofproto *ofproto, int error, char *devname)
1091 {
1092     if (error == ENOBUFS) {
1093         reinit_ports(ofproto);
1094     } else if (!error) {
1095         update_port(ofproto, devname);
1096         free(devname);
1097     }
1098 }
1099
1100 int
1101 ofproto_run(struct ofproto *p)
1102 {
1103     struct sset changed_netdevs;
1104     const char *changed_netdev;
1105     struct ofport *ofport;
1106     int error;
1107
1108     error = p->ofproto_class->run(p);
1109     if (error && error != EAGAIN) {
1110         VLOG_ERR_RL(&rl, "%s: run failed (%s)", p->name, strerror(error));
1111     }
1112
1113     if (p->ofproto_class->port_poll) {
1114         char *devname;
1115
1116         while ((error = p->ofproto_class->port_poll(p, &devname)) != EAGAIN) {
1117             process_port_change(p, error, devname);
1118         }
1119     }
1120
1121     /* Update OpenFlow port status for any port whose netdev has changed.
1122      *
1123      * Refreshing a given 'ofport' can cause an arbitrary ofport to be
1124      * destroyed, so it's not safe to update ports directly from the
1125      * HMAP_FOR_EACH loop, or even to use HMAP_FOR_EACH_SAFE.  Instead, we
1126      * need this two-phase approach. */
1127     sset_init(&changed_netdevs);
1128     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1129         unsigned int change_seq = netdev_change_seq(ofport->netdev);
1130         if (ofport->change_seq != change_seq) {
1131             ofport->change_seq = change_seq;
1132             sset_add(&changed_netdevs, netdev_get_name(ofport->netdev));
1133         }
1134     }
1135     SSET_FOR_EACH (changed_netdev, &changed_netdevs) {
1136         update_port(p, changed_netdev);
1137     }
1138     sset_destroy(&changed_netdevs);
1139
1140     switch (p->state) {
1141     case S_OPENFLOW:
1142         connmgr_run(p->connmgr, handle_openflow);
1143         break;
1144
1145     case S_EVICT:
1146         connmgr_run(p->connmgr, NULL);
1147         ofproto_evict(p);
1148         if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1149             p->state = S_OPENFLOW;
1150         }
1151         break;
1152
1153     case S_FLUSH:
1154         connmgr_run(p->connmgr, NULL);
1155         ofproto_flush__(p);
1156         if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1157             connmgr_flushed(p->connmgr);
1158             p->state = S_OPENFLOW;
1159         }
1160         break;
1161
1162     default:
1163         NOT_REACHED();
1164     }
1165
1166     if (time_msec() >= p->next_op_report) {
1167         long long int ago = (time_msec() - p->first_op) / 1000;
1168         long long int interval = (p->last_op - p->first_op) / 1000;
1169         struct ds s;
1170
1171         ds_init(&s);
1172         ds_put_format(&s, "%d flow_mods ",
1173                       p->n_add + p->n_delete + p->n_modify);
1174         if (interval == ago) {
1175             ds_put_format(&s, "in the last %lld s", ago);
1176         } else if (interval) {
1177             ds_put_format(&s, "in the %lld s starting %lld s ago",
1178                           interval, ago);
1179         } else {
1180             ds_put_format(&s, "%lld s ago", ago);
1181         }
1182
1183         ds_put_cstr(&s, " (");
1184         if (p->n_add) {
1185             ds_put_format(&s, "%d adds, ", p->n_add);
1186         }
1187         if (p->n_delete) {
1188             ds_put_format(&s, "%d deletes, ", p->n_delete);
1189         }
1190         if (p->n_modify) {
1191             ds_put_format(&s, "%d modifications, ", p->n_modify);
1192         }
1193         s.length -= 2;
1194         ds_put_char(&s, ')');
1195
1196         VLOG_INFO("%s: %s", p->name, ds_cstr(&s));
1197         ds_destroy(&s);
1198
1199         p->n_add = p->n_delete = p->n_modify = 0;
1200         p->next_op_report = LLONG_MAX;
1201     }
1202
1203     return error;
1204 }
1205
1206 /* Performs periodic activity required by 'ofproto' that needs to be done
1207  * with the least possible latency.
1208  *
1209  * It makes sense to call this function a couple of times per poll loop, to
1210  * provide a significant performance boost on some benchmarks with the
1211  * ofproto-dpif implementation. */
1212 int
1213 ofproto_run_fast(struct ofproto *p)
1214 {
1215     int error;
1216
1217     error = p->ofproto_class->run_fast ? p->ofproto_class->run_fast(p) : 0;
1218     if (error && error != EAGAIN) {
1219         VLOG_ERR_RL(&rl, "%s: fastpath run failed (%s)",
1220                     p->name, strerror(error));
1221     }
1222     return error;
1223 }
1224
1225 void
1226 ofproto_wait(struct ofproto *p)
1227 {
1228     struct ofport *ofport;
1229
1230     p->ofproto_class->wait(p);
1231     if (p->ofproto_class->port_poll_wait) {
1232         p->ofproto_class->port_poll_wait(p);
1233     }
1234
1235     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1236         if (ofport->change_seq != netdev_change_seq(ofport->netdev)) {
1237             poll_immediate_wake();
1238         }
1239     }
1240
1241     switch (p->state) {
1242     case S_OPENFLOW:
1243         connmgr_wait(p->connmgr, true);
1244         break;
1245
1246     case S_EVICT:
1247     case S_FLUSH:
1248         connmgr_wait(p->connmgr, false);
1249         if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1250             poll_immediate_wake();
1251         }
1252         break;
1253     }
1254 }
1255
1256 bool
1257 ofproto_is_alive(const struct ofproto *p)
1258 {
1259     return connmgr_has_controllers(p->connmgr);
1260 }
1261
1262 /* Adds some memory usage statistics for 'ofproto' into 'usage', for use with
1263  * memory_report(). */
1264 void
1265 ofproto_get_memory_usage(const struct ofproto *ofproto, struct simap *usage)
1266 {
1267     const struct oftable *table;
1268     unsigned int n_rules;
1269
1270     simap_increase(usage, "ports", hmap_count(&ofproto->ports));
1271     simap_increase(usage, "ops",
1272                    ofproto->n_pending + hmap_count(&ofproto->deletions));
1273
1274     n_rules = 0;
1275     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1276         n_rules += classifier_count(&table->cls);
1277     }
1278     simap_increase(usage, "rules", n_rules);
1279
1280     if (ofproto->ofproto_class->get_memory_usage) {
1281         ofproto->ofproto_class->get_memory_usage(ofproto, usage);
1282     }
1283
1284     connmgr_get_memory_usage(ofproto->connmgr, usage);
1285 }
1286
1287 void
1288 ofproto_get_ofproto_controller_info(const struct ofproto *ofproto,
1289                                     struct shash *info)
1290 {
1291     connmgr_get_controller_info(ofproto->connmgr, info);
1292 }
1293
1294 void
1295 ofproto_free_ofproto_controller_info(struct shash *info)
1296 {
1297     connmgr_free_controller_info(info);
1298 }
1299
1300 /* Makes a deep copy of 'old' into 'port'. */
1301 void
1302 ofproto_port_clone(struct ofproto_port *port, const struct ofproto_port *old)
1303 {
1304     port->name = xstrdup(old->name);
1305     port->type = xstrdup(old->type);
1306     port->ofp_port = old->ofp_port;
1307 }
1308
1309 /* Frees memory allocated to members of 'ofproto_port'.
1310  *
1311  * Do not call this function on an ofproto_port obtained from
1312  * ofproto_port_dump_next(): that function retains ownership of the data in the
1313  * ofproto_port. */
1314 void
1315 ofproto_port_destroy(struct ofproto_port *ofproto_port)
1316 {
1317     free(ofproto_port->name);
1318     free(ofproto_port->type);
1319 }
1320
1321 /* Initializes 'dump' to begin dumping the ports in an ofproto.
1322  *
1323  * This function provides no status indication.  An error status for the entire
1324  * dump operation is provided when it is completed by calling
1325  * ofproto_port_dump_done().
1326  */
1327 void
1328 ofproto_port_dump_start(struct ofproto_port_dump *dump,
1329                         const struct ofproto *ofproto)
1330 {
1331     dump->ofproto = ofproto;
1332     dump->error = ofproto->ofproto_class->port_dump_start(ofproto,
1333                                                           &dump->state);
1334 }
1335
1336 /* Attempts to retrieve another port from 'dump', which must have been created
1337  * with ofproto_port_dump_start().  On success, stores a new ofproto_port into
1338  * 'port' and returns true.  On failure, returns false.
1339  *
1340  * Failure might indicate an actual error or merely that the last port has been
1341  * dumped.  An error status for the entire dump operation is provided when it
1342  * is completed by calling ofproto_port_dump_done().
1343  *
1344  * The ofproto owns the data stored in 'port'.  It will remain valid until at
1345  * least the next time 'dump' is passed to ofproto_port_dump_next() or
1346  * ofproto_port_dump_done(). */
1347 bool
1348 ofproto_port_dump_next(struct ofproto_port_dump *dump,
1349                        struct ofproto_port *port)
1350 {
1351     const struct ofproto *ofproto = dump->ofproto;
1352
1353     if (dump->error) {
1354         return false;
1355     }
1356
1357     dump->error = ofproto->ofproto_class->port_dump_next(ofproto, dump->state,
1358                                                          port);
1359     if (dump->error) {
1360         ofproto->ofproto_class->port_dump_done(ofproto, dump->state);
1361         return false;
1362     }
1363     return true;
1364 }
1365
1366 /* Completes port table dump operation 'dump', which must have been created
1367  * with ofproto_port_dump_start().  Returns 0 if the dump operation was
1368  * error-free, otherwise a positive errno value describing the problem. */
1369 int
1370 ofproto_port_dump_done(struct ofproto_port_dump *dump)
1371 {
1372     const struct ofproto *ofproto = dump->ofproto;
1373     if (!dump->error) {
1374         dump->error = ofproto->ofproto_class->port_dump_done(ofproto,
1375                                                              dump->state);
1376     }
1377     return dump->error == EOF ? 0 : dump->error;
1378 }
1379
1380 /* Attempts to add 'netdev' as a port on 'ofproto'.  If 'ofp_portp' is
1381  * non-null and '*ofp_portp' is not OFPP_NONE, attempts to use that as
1382  * the port's OpenFlow port number.
1383  *
1384  * If successful, returns 0 and sets '*ofp_portp' to the new port's
1385  * OpenFlow port number (if 'ofp_portp' is non-null).  On failure,
1386  * returns a positive errno value and sets '*ofp_portp' to OFPP_NONE (if
1387  * 'ofp_portp' is non-null). */
1388 int
1389 ofproto_port_add(struct ofproto *ofproto, struct netdev *netdev,
1390                  uint16_t *ofp_portp)
1391 {
1392     uint16_t ofp_port = ofp_portp ? *ofp_portp : OFPP_NONE;
1393     int error;
1394
1395     error = ofproto->ofproto_class->port_add(ofproto, netdev);
1396     if (!error) {
1397         const char *netdev_name = netdev_get_name(netdev);
1398
1399         simap_put(&ofproto->ofp_requests, netdev_name, ofp_port);
1400         update_port(ofproto, netdev_name);
1401     }
1402     if (ofp_portp) {
1403         struct ofproto_port ofproto_port;
1404
1405         ofproto_port_query_by_name(ofproto, netdev_get_name(netdev),
1406                                    &ofproto_port);
1407         *ofp_portp = error ? OFPP_NONE : ofproto_port.ofp_port;
1408         ofproto_port_destroy(&ofproto_port);
1409     }
1410     return error;
1411 }
1412
1413 /* Looks up a port named 'devname' in 'ofproto'.  On success, returns 0 and
1414  * initializes '*port' appropriately; on failure, returns a positive errno
1415  * value.
1416  *
1417  * The caller owns the data in 'ofproto_port' and must free it with
1418  * ofproto_port_destroy() when it is no longer needed. */
1419 int
1420 ofproto_port_query_by_name(const struct ofproto *ofproto, const char *devname,
1421                            struct ofproto_port *port)
1422 {
1423     int error;
1424
1425     error = ofproto->ofproto_class->port_query_by_name(ofproto, devname, port);
1426     if (error) {
1427         memset(port, 0, sizeof *port);
1428     }
1429     return error;
1430 }
1431
1432 /* Deletes port number 'ofp_port' from the datapath for 'ofproto'.
1433  * Returns 0 if successful, otherwise a positive errno. */
1434 int
1435 ofproto_port_del(struct ofproto *ofproto, uint16_t ofp_port)
1436 {
1437     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1438     const char *name = ofport ? netdev_get_name(ofport->netdev) : "<unknown>";
1439     struct simap_node *ofp_request_node;
1440     int error;
1441
1442     ofp_request_node = simap_find(&ofproto->ofp_requests, name);
1443     if (ofp_request_node) {
1444         simap_delete(&ofproto->ofp_requests, ofp_request_node);
1445     }
1446
1447     error = ofproto->ofproto_class->port_del(ofproto, ofp_port);
1448     if (!error && ofport) {
1449         /* 'name' is the netdev's name and update_port() is going to close the
1450          * netdev.  Just in case update_port() refers to 'name' after it
1451          * destroys 'ofport', make a copy of it around the update_port()
1452          * call. */
1453         char *devname = xstrdup(name);
1454         update_port(ofproto, devname);
1455         free(devname);
1456     }
1457     return error;
1458 }
1459
1460 /* Adds a flow to OpenFlow flow table 0 in 'p' that matches 'cls_rule' and
1461  * performs the 'n_actions' actions in 'actions'.  The new flow will not
1462  * timeout.
1463  *
1464  * If cls_rule->priority is in the range of priorities supported by OpenFlow
1465  * (0...65535, inclusive) then the flow will be visible to OpenFlow
1466  * controllers; otherwise, it will be hidden.
1467  *
1468  * The caller retains ownership of 'cls_rule' and 'ofpacts'.
1469  *
1470  * This is a helper function for in-band control and fail-open. */
1471 void
1472 ofproto_add_flow(struct ofproto *ofproto, const struct match *match,
1473                  unsigned int priority,
1474                  const struct ofpact *ofpacts, size_t ofpacts_len)
1475 {
1476     const struct rule *rule;
1477
1478     rule = rule_from_cls_rule(classifier_find_match_exactly(
1479                                   &ofproto->tables[0].cls, match, priority));
1480     if (!rule || !ofpacts_equal(rule->ofpacts, rule->ofpacts_len,
1481                                 ofpacts, ofpacts_len)) {
1482         struct ofputil_flow_mod fm;
1483
1484         memset(&fm, 0, sizeof fm);
1485         fm.match = *match;
1486         fm.priority = priority;
1487         fm.buffer_id = UINT32_MAX;
1488         fm.ofpacts = xmemdup(ofpacts, ofpacts_len);
1489         fm.ofpacts_len = ofpacts_len;
1490         add_flow(ofproto, NULL, &fm, NULL);
1491         free(fm.ofpacts);
1492     }
1493 }
1494
1495 /* Executes the flow modification specified in 'fm'.  Returns 0 on success, an
1496  * OFPERR_* OpenFlow error code on failure, or OFPROTO_POSTPONE if the
1497  * operation cannot be initiated now but may be retried later.
1498  *
1499  * This is a helper function for in-band control and fail-open. */
1500 int
1501 ofproto_flow_mod(struct ofproto *ofproto, const struct ofputil_flow_mod *fm)
1502 {
1503     return handle_flow_mod__(ofproto, NULL, fm, NULL);
1504 }
1505
1506 /* Searches for a rule with matching criteria exactly equal to 'target' in
1507  * ofproto's table 0 and, if it finds one, deletes it.
1508  *
1509  * This is a helper function for in-band control and fail-open. */
1510 bool
1511 ofproto_delete_flow(struct ofproto *ofproto,
1512                     const struct match *target, unsigned int priority)
1513 {
1514     struct rule *rule;
1515
1516     rule = rule_from_cls_rule(classifier_find_match_exactly(
1517                                   &ofproto->tables[0].cls, target, priority));
1518     if (!rule) {
1519         /* No such rule -> success. */
1520         return true;
1521     } else if (rule->pending) {
1522         /* An operation on the rule is already pending -> failure.
1523          * Caller must retry later if it's important. */
1524         return false;
1525     } else {
1526         /* Initiate deletion -> success. */
1527         struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
1528         ofoperation_create(group, rule, OFOPERATION_DELETE, OFPRR_DELETE);
1529         oftable_remove_rule(rule);
1530         ofproto->ofproto_class->rule_destruct(rule);
1531         ofopgroup_submit(group);
1532         return true;
1533     }
1534
1535 }
1536
1537 /* Starts the process of deleting all of the flows from all of ofproto's flow
1538  * tables and then reintroducing the flows required by in-band control and
1539  * fail-open.  The process will complete in a later call to ofproto_run(). */
1540 void
1541 ofproto_flush_flows(struct ofproto *ofproto)
1542 {
1543     COVERAGE_INC(ofproto_flush);
1544     ofproto->state = S_FLUSH;
1545 }
1546 \f
1547 static void
1548 reinit_ports(struct ofproto *p)
1549 {
1550     struct ofproto_port_dump dump;
1551     struct sset devnames;
1552     struct ofport *ofport;
1553     struct ofproto_port ofproto_port;
1554     const char *devname;
1555
1556     COVERAGE_INC(ofproto_reinit_ports);
1557
1558     sset_init(&devnames);
1559     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1560         sset_add(&devnames, netdev_get_name(ofport->netdev));
1561     }
1562     OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
1563         sset_add(&devnames, ofproto_port.name);
1564     }
1565
1566     SSET_FOR_EACH (devname, &devnames) {
1567         update_port(p, devname);
1568     }
1569     sset_destroy(&devnames);
1570 }
1571
1572 static uint16_t
1573 alloc_ofp_port(struct ofproto *ofproto, const char *netdev_name)
1574 {
1575     uint16_t ofp_port;
1576
1577     ofp_port = simap_get(&ofproto->ofp_requests, netdev_name);
1578     ofp_port = ofp_port ? ofp_port : OFPP_NONE;
1579
1580     if (ofp_port >= ofproto->max_ports
1581             || bitmap_is_set(ofproto->ofp_port_ids, ofp_port)) {
1582         bool retry = ofproto->alloc_port_no ? true : false;
1583
1584         /* Search for a free OpenFlow port number.  We try not to
1585          * immediately reuse them to prevent problems due to old
1586          * flows. */
1587         while (ofp_port >= ofproto->max_ports) {
1588             for (ofproto->alloc_port_no++;
1589                  ofproto->alloc_port_no < ofproto->max_ports; ) {
1590                 if (!bitmap_is_set(ofproto->ofp_port_ids,
1591                                    ofproto->alloc_port_no)) {
1592                     ofp_port = ofproto->alloc_port_no;
1593                     break;
1594                 }
1595             }
1596             if (ofproto->alloc_port_no >= ofproto->max_ports) {
1597                 if (retry) {
1598                     ofproto->alloc_port_no = 0;
1599                     retry = false;
1600                 } else {
1601                     return OFPP_NONE;
1602                 }
1603             }
1604         }
1605     }
1606
1607     bitmap_set1(ofproto->ofp_port_ids, ofp_port);
1608     return ofp_port;
1609 }
1610
1611 static void
1612 dealloc_ofp_port(const struct ofproto *ofproto, uint16_t ofp_port)
1613 {
1614     bitmap_set0(ofproto->ofp_port_ids, ofp_port);
1615 }
1616
1617 /* Opens and returns a netdev for 'ofproto_port' in 'ofproto', or a null
1618  * pointer if the netdev cannot be opened.  On success, also fills in
1619  * 'opp'.  */
1620 static struct netdev *
1621 ofport_open(struct ofproto *ofproto,
1622             struct ofproto_port *ofproto_port,
1623             struct ofputil_phy_port *pp)
1624 {
1625     enum netdev_flags flags;
1626     struct netdev *netdev;
1627     int error;
1628
1629     error = netdev_open(ofproto_port->name, ofproto_port->type, &netdev);
1630     if (error) {
1631         VLOG_WARN_RL(&rl, "%s: ignoring port %s (%"PRIu16") because netdev %s "
1632                      "cannot be opened (%s)",
1633                      ofproto->name,
1634                      ofproto_port->name, ofproto_port->ofp_port,
1635                      ofproto_port->name, strerror(error));
1636         return NULL;
1637     }
1638
1639     if (ofproto_port->ofp_port == OFPP_NONE) {
1640         if (!strcmp(ofproto->name, ofproto_port->name)) {
1641             ofproto_port->ofp_port = OFPP_LOCAL;
1642         } else {
1643             ofproto_port->ofp_port = alloc_ofp_port(ofproto,
1644                                                     ofproto_port->name);
1645         }
1646     }
1647     pp->port_no = ofproto_port->ofp_port;
1648     netdev_get_etheraddr(netdev, pp->hw_addr);
1649     ovs_strlcpy(pp->name, ofproto_port->name, sizeof pp->name);
1650     netdev_get_flags(netdev, &flags);
1651     pp->config = flags & NETDEV_UP ? 0 : OFPUTIL_PC_PORT_DOWN;
1652     pp->state = netdev_get_carrier(netdev) ? 0 : OFPUTIL_PS_LINK_DOWN;
1653     netdev_get_features(netdev, &pp->curr, &pp->advertised,
1654                         &pp->supported, &pp->peer);
1655     pp->curr_speed = netdev_features_to_bps(pp->curr);
1656     pp->max_speed = netdev_features_to_bps(pp->supported);
1657
1658     return netdev;
1659 }
1660
1661 /* Returns true if most fields of 'a' and 'b' are equal.  Differences in name,
1662  * port number, and 'config' bits other than OFPUTIL_PS_LINK_DOWN are
1663  * disregarded. */
1664 static bool
1665 ofport_equal(const struct ofputil_phy_port *a,
1666              const struct ofputil_phy_port *b)
1667 {
1668     return (eth_addr_equals(a->hw_addr, b->hw_addr)
1669             && a->state == b->state
1670             && !((a->config ^ b->config) & OFPUTIL_PC_PORT_DOWN)
1671             && a->curr == b->curr
1672             && a->advertised == b->advertised
1673             && a->supported == b->supported
1674             && a->peer == b->peer
1675             && a->curr_speed == b->curr_speed
1676             && a->max_speed == b->max_speed);
1677 }
1678
1679 /* Adds an ofport to 'p' initialized based on the given 'netdev' and 'opp'.
1680  * The caller must ensure that 'p' does not have a conflicting ofport (that is,
1681  * one with the same name or port number). */
1682 static void
1683 ofport_install(struct ofproto *p,
1684                struct netdev *netdev, const struct ofputil_phy_port *pp)
1685 {
1686     const char *netdev_name = netdev_get_name(netdev);
1687     struct ofport *ofport;
1688     int error;
1689
1690     /* Create ofport. */
1691     ofport = p->ofproto_class->port_alloc();
1692     if (!ofport) {
1693         error = ENOMEM;
1694         goto error;
1695     }
1696     ofport->ofproto = p;
1697     ofport->netdev = netdev;
1698     ofport->change_seq = netdev_change_seq(netdev);
1699     ofport->pp = *pp;
1700     ofport->ofp_port = pp->port_no;
1701
1702     /* Add port to 'p'. */
1703     hmap_insert(&p->ports, &ofport->hmap_node, hash_int(ofport->ofp_port, 0));
1704     shash_add(&p->port_by_name, netdev_name, ofport);
1705
1706     update_mtu(p, ofport);
1707
1708     /* Let the ofproto_class initialize its private data. */
1709     error = p->ofproto_class->port_construct(ofport);
1710     if (error) {
1711         goto error;
1712     }
1713     connmgr_send_port_status(p->connmgr, pp, OFPPR_ADD);
1714     return;
1715
1716 error:
1717     VLOG_WARN_RL(&rl, "%s: could not add port %s (%s)",
1718                  p->name, netdev_name, strerror(error));
1719     if (ofport) {
1720         ofport_destroy__(ofport);
1721     } else {
1722         netdev_close(netdev);
1723     }
1724 }
1725
1726 /* Removes 'ofport' from 'p' and destroys it. */
1727 static void
1728 ofport_remove(struct ofport *ofport)
1729 {
1730     connmgr_send_port_status(ofport->ofproto->connmgr, &ofport->pp,
1731                              OFPPR_DELETE);
1732     ofport_destroy(ofport);
1733 }
1734
1735 /* If 'ofproto' contains an ofport named 'name', removes it from 'ofproto' and
1736  * destroys it. */
1737 static void
1738 ofport_remove_with_name(struct ofproto *ofproto, const char *name)
1739 {
1740     struct ofport *port = shash_find_data(&ofproto->port_by_name, name);
1741     if (port) {
1742         ofport_remove(port);
1743     }
1744 }
1745
1746 /* Updates 'port' with new 'pp' description.
1747  *
1748  * Does not handle a name or port number change.  The caller must implement
1749  * such a change as a delete followed by an add.  */
1750 static void
1751 ofport_modified(struct ofport *port, struct ofputil_phy_port *pp)
1752 {
1753     memcpy(port->pp.hw_addr, pp->hw_addr, ETH_ADDR_LEN);
1754     port->pp.config = ((port->pp.config & ~OFPUTIL_PC_PORT_DOWN)
1755                         | (pp->config & OFPUTIL_PC_PORT_DOWN));
1756     port->pp.state = pp->state;
1757     port->pp.curr = pp->curr;
1758     port->pp.advertised = pp->advertised;
1759     port->pp.supported = pp->supported;
1760     port->pp.peer = pp->peer;
1761     port->pp.curr_speed = pp->curr_speed;
1762     port->pp.max_speed = pp->max_speed;
1763
1764     connmgr_send_port_status(port->ofproto->connmgr, &port->pp, OFPPR_MODIFY);
1765 }
1766
1767 /* Update OpenFlow 'state' in 'port' and notify controller. */
1768 void
1769 ofproto_port_set_state(struct ofport *port, enum ofputil_port_state state)
1770 {
1771     if (port->pp.state != state) {
1772         port->pp.state = state;
1773         connmgr_send_port_status(port->ofproto->connmgr, &port->pp,
1774                                  OFPPR_MODIFY);
1775     }
1776 }
1777
1778 void
1779 ofproto_port_unregister(struct ofproto *ofproto, uint16_t ofp_port)
1780 {
1781     struct ofport *port = ofproto_get_port(ofproto, ofp_port);
1782     if (port) {
1783         if (port->ofproto->ofproto_class->set_realdev) {
1784             port->ofproto->ofproto_class->set_realdev(port, 0, 0);
1785         }
1786         if (port->ofproto->ofproto_class->set_stp_port) {
1787             port->ofproto->ofproto_class->set_stp_port(port, NULL);
1788         }
1789         if (port->ofproto->ofproto_class->set_cfm) {
1790             port->ofproto->ofproto_class->set_cfm(port, NULL);
1791         }
1792         if (port->ofproto->ofproto_class->bundle_remove) {
1793             port->ofproto->ofproto_class->bundle_remove(port);
1794         }
1795     }
1796 }
1797
1798 static void
1799 ofport_destroy__(struct ofport *port)
1800 {
1801     struct ofproto *ofproto = port->ofproto;
1802     const char *name = netdev_get_name(port->netdev);
1803
1804     hmap_remove(&ofproto->ports, &port->hmap_node);
1805     shash_delete(&ofproto->port_by_name,
1806                  shash_find(&ofproto->port_by_name, name));
1807
1808     netdev_close(port->netdev);
1809     ofproto->ofproto_class->port_dealloc(port);
1810 }
1811
1812 static void
1813 ofport_destroy(struct ofport *port)
1814 {
1815     if (port) {
1816         dealloc_ofp_port(port->ofproto, port->ofp_port);
1817         port->ofproto->ofproto_class->port_destruct(port);
1818         ofport_destroy__(port);
1819      }
1820 }
1821
1822 struct ofport *
1823 ofproto_get_port(const struct ofproto *ofproto, uint16_t ofp_port)
1824 {
1825     struct ofport *port;
1826
1827     HMAP_FOR_EACH_IN_BUCKET (port, hmap_node,
1828                              hash_int(ofp_port, 0), &ofproto->ports) {
1829         if (port->ofp_port == ofp_port) {
1830             return port;
1831         }
1832     }
1833     return NULL;
1834 }
1835
1836 int
1837 ofproto_port_get_stats(const struct ofport *port, struct netdev_stats *stats)
1838 {
1839     struct ofproto *ofproto = port->ofproto;
1840     int error;
1841
1842     if (ofproto->ofproto_class->port_get_stats) {
1843         error = ofproto->ofproto_class->port_get_stats(port, stats);
1844     } else {
1845         error = EOPNOTSUPP;
1846     }
1847
1848     return error;
1849 }
1850
1851 static void
1852 update_port(struct ofproto *ofproto, const char *name)
1853 {
1854     struct ofproto_port ofproto_port;
1855     struct ofputil_phy_port pp;
1856     struct netdev *netdev;
1857     struct ofport *port;
1858
1859     COVERAGE_INC(ofproto_update_port);
1860
1861     /* Fetch 'name''s location and properties from the datapath. */
1862     netdev = (!ofproto_port_query_by_name(ofproto, name, &ofproto_port)
1863               ? ofport_open(ofproto, &ofproto_port, &pp)
1864               : NULL);
1865     if (netdev) {
1866         port = ofproto_get_port(ofproto, ofproto_port.ofp_port);
1867         if (port && !strcmp(netdev_get_name(port->netdev), name)) {
1868             struct netdev *old_netdev = port->netdev;
1869
1870             /* 'name' hasn't changed location.  Any properties changed? */
1871             if (!ofport_equal(&port->pp, &pp)) {
1872                 ofport_modified(port, &pp);
1873             }
1874
1875             update_mtu(ofproto, port);
1876
1877             /* Install the newly opened netdev in case it has changed.
1878              * Don't close the old netdev yet in case port_modified has to
1879              * remove a retained reference to it.*/
1880             port->netdev = netdev;
1881             port->change_seq = netdev_change_seq(netdev);
1882
1883             if (port->ofproto->ofproto_class->port_modified) {
1884                 port->ofproto->ofproto_class->port_modified(port);
1885             }
1886
1887             netdev_close(old_netdev);
1888         } else {
1889             /* If 'port' is nonnull then its name differs from 'name' and thus
1890              * we should delete it.  If we think there's a port named 'name'
1891              * then its port number must be wrong now so delete it too. */
1892             if (port) {
1893                 ofport_remove(port);
1894             }
1895             ofport_remove_with_name(ofproto, name);
1896             ofport_install(ofproto, netdev, &pp);
1897         }
1898     } else {
1899         /* Any port named 'name' is gone now. */
1900         ofport_remove_with_name(ofproto, name);
1901     }
1902     ofproto_port_destroy(&ofproto_port);
1903 }
1904
1905 static int
1906 init_ports(struct ofproto *p)
1907 {
1908     struct ofproto_port_dump dump;
1909     struct ofproto_port ofproto_port;
1910     struct shash_node *node, *next;
1911
1912     OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
1913         const char *name = ofproto_port.name;
1914
1915         if (shash_find(&p->port_by_name, name)) {
1916             VLOG_WARN_RL(&rl, "%s: ignoring duplicate device %s in datapath",
1917                          p->name, name);
1918         } else {
1919             struct ofputil_phy_port pp;
1920             struct netdev *netdev;
1921
1922             /* Check if an OpenFlow port number had been requested. */
1923             node = shash_find(&init_ofp_ports, name);
1924             if (node) {
1925                 const struct iface_hint *iface_hint = node->data;
1926                 simap_put(&p->ofp_requests, name, iface_hint->ofp_port);
1927             }
1928
1929             netdev = ofport_open(p, &ofproto_port, &pp);
1930             if (netdev) {
1931                 ofport_install(p, netdev, &pp);
1932             }
1933         }
1934     }
1935
1936     SHASH_FOR_EACH_SAFE(node, next, &init_ofp_ports) {
1937         const struct iface_hint *iface_hint = node->data;
1938
1939         if (!strcmp(iface_hint->br_name, p->name)) {
1940             free(iface_hint->br_name);
1941             free(iface_hint->br_type);
1942             shash_delete(&init_ofp_ports, node);
1943         }
1944     }
1945
1946     return 0;
1947 }
1948
1949 /* Find the minimum MTU of all non-datapath devices attached to 'p'.
1950  * Returns ETH_PAYLOAD_MAX or the minimum of the ports. */
1951 static int
1952 find_min_mtu(struct ofproto *p)
1953 {
1954     struct ofport *ofport;
1955     int mtu = 0;
1956
1957     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1958         struct netdev *netdev = ofport->netdev;
1959         int dev_mtu;
1960
1961         /* Skip any internal ports, since that's what we're trying to
1962          * set. */
1963         if (!strcmp(netdev_get_type(netdev), "internal")) {
1964             continue;
1965         }
1966
1967         if (netdev_get_mtu(netdev, &dev_mtu)) {
1968             continue;
1969         }
1970         if (!mtu || dev_mtu < mtu) {
1971             mtu = dev_mtu;
1972         }
1973     }
1974
1975     return mtu ? mtu: ETH_PAYLOAD_MAX;
1976 }
1977
1978 /* Update MTU of all datapath devices on 'p' to the minimum of the
1979  * non-datapath ports in event of 'port' added or changed. */
1980 static void
1981 update_mtu(struct ofproto *p, struct ofport *port)
1982 {
1983     struct ofport *ofport;
1984     struct netdev *netdev = port->netdev;
1985     int dev_mtu, old_min;
1986
1987     if (netdev_get_mtu(netdev, &dev_mtu)) {
1988         port->mtu = 0;
1989         return;
1990     }
1991     if (!strcmp(netdev_get_type(port->netdev), "internal")) {
1992         if (dev_mtu > p->min_mtu) {
1993            if (!netdev_set_mtu(port->netdev, p->min_mtu)) {
1994                dev_mtu = p->min_mtu;
1995            }
1996         }
1997         port->mtu = dev_mtu;
1998         return;
1999     }
2000
2001     /* For non-internal port find new min mtu. */
2002     old_min = p->min_mtu;
2003     port->mtu = dev_mtu;
2004     p->min_mtu = find_min_mtu(p);
2005     if (p->min_mtu == old_min) {
2006         return;
2007     }
2008
2009     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2010         struct netdev *netdev = ofport->netdev;
2011
2012         if (!strcmp(netdev_get_type(netdev), "internal")) {
2013             if (!netdev_set_mtu(netdev, p->min_mtu)) {
2014                 ofport->mtu = p->min_mtu;
2015             }
2016         }
2017     }
2018 }
2019 \f
2020 static void
2021 ofproto_rule_destroy__(struct rule *rule)
2022 {
2023     if (rule) {
2024         cls_rule_destroy(&rule->cr);
2025         free(rule->ofpacts);
2026         rule->ofproto->ofproto_class->rule_dealloc(rule);
2027     }
2028 }
2029
2030 /* This function allows an ofproto implementation to destroy any rules that
2031  * remain when its ->destruct() function is called.  The caller must have
2032  * already uninitialized any derived members of 'rule' (step 5 described in the
2033  * large comment in ofproto/ofproto-provider.h titled "Life Cycle").
2034  * This function implements steps 6 and 7.
2035  *
2036  * This function should only be called from an ofproto implementation's
2037  * ->destruct() function.  It is not suitable elsewhere. */
2038 void
2039 ofproto_rule_destroy(struct rule *rule)
2040 {
2041     assert(!rule->pending);
2042     oftable_remove_rule(rule);
2043     ofproto_rule_destroy__(rule);
2044 }
2045
2046 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
2047  * that outputs to 'port' (output to OFPP_FLOOD and OFPP_ALL doesn't count). */
2048 bool
2049 ofproto_rule_has_out_port(const struct rule *rule, uint16_t port)
2050 {
2051     return (port == OFPP_NONE
2052             || ofpacts_output_to_port(rule->ofpacts, rule->ofpacts_len, port));
2053 }
2054
2055 /* Returns true if a rule related to 'op' has an OpenFlow OFPAT_OUTPUT or
2056  * OFPAT_ENQUEUE action that outputs to 'out_port'. */
2057 bool
2058 ofoperation_has_out_port(const struct ofoperation *op, uint16_t out_port)
2059 {
2060     if (ofproto_rule_has_out_port(op->rule, out_port)) {
2061         return true;
2062     }
2063
2064     switch (op->type) {
2065     case OFOPERATION_ADD:
2066         return op->victim && ofproto_rule_has_out_port(op->victim, out_port);
2067
2068     case OFOPERATION_DELETE:
2069         return false;
2070
2071     case OFOPERATION_MODIFY:
2072         return ofpacts_output_to_port(op->ofpacts, op->ofpacts_len, out_port);
2073     }
2074
2075     NOT_REACHED();
2076 }
2077
2078 /* Executes the actions indicated by 'rule' on 'packet' and credits 'rule''s
2079  * statistics appropriately.  'packet' must have at least sizeof(struct
2080  * ofp_packet_in) bytes of headroom.
2081  *
2082  * 'packet' doesn't necessarily have to match 'rule'.  'rule' will be credited
2083  * with statistics for 'packet' either way.
2084  *
2085  * Takes ownership of 'packet'. */
2086 static int
2087 rule_execute(struct rule *rule, uint16_t in_port, struct ofpbuf *packet)
2088 {
2089     struct flow flow;
2090
2091     assert(ofpbuf_headroom(packet) >= sizeof(struct ofp_packet_in));
2092
2093     flow_extract(packet, 0, NULL, in_port, &flow);
2094     return rule->ofproto->ofproto_class->rule_execute(rule, &flow, packet);
2095 }
2096
2097 /* Returns true if 'rule' should be hidden from the controller.
2098  *
2099  * Rules with priority higher than UINT16_MAX are set up by ofproto itself
2100  * (e.g. by in-band control) and are intentionally hidden from the
2101  * controller. */
2102 bool
2103 ofproto_rule_is_hidden(const struct rule *rule)
2104 {
2105     return rule->cr.priority > UINT16_MAX;
2106 }
2107
2108 static enum oftable_flags
2109 rule_get_flags(const struct rule *rule)
2110 {
2111     return rule->ofproto->tables[rule->table_id].flags;
2112 }
2113
2114 static bool
2115 rule_is_modifiable(const struct rule *rule)
2116 {
2117     return !(rule_get_flags(rule) & OFTABLE_READONLY);
2118 }
2119 \f
2120 static enum ofperr
2121 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
2122 {
2123     ofconn_send_reply(ofconn, make_echo_reply(oh));
2124     return 0;
2125 }
2126
2127 static enum ofperr
2128 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
2129 {
2130     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2131     struct ofputil_switch_features features;
2132     struct ofport *port;
2133     bool arp_match_ip;
2134     struct ofpbuf *b;
2135
2136     ofproto->ofproto_class->get_features(ofproto, &arp_match_ip,
2137                                          &features.actions);
2138     assert(features.actions & OFPUTIL_A_OUTPUT); /* sanity check */
2139
2140     features.datapath_id = ofproto->datapath_id;
2141     features.n_buffers = pktbuf_capacity();
2142     features.n_tables = ofproto->n_tables;
2143     features.capabilities = (OFPUTIL_C_FLOW_STATS | OFPUTIL_C_TABLE_STATS |
2144                              OFPUTIL_C_PORT_STATS | OFPUTIL_C_QUEUE_STATS);
2145     if (arp_match_ip) {
2146         features.capabilities |= OFPUTIL_C_ARP_MATCH_IP;
2147     }
2148
2149     b = ofputil_encode_switch_features(&features, ofconn_get_protocol(ofconn),
2150                                        oh->xid);
2151     HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
2152         ofputil_put_switch_features_port(&port->pp, b);
2153     }
2154
2155     ofconn_send_reply(ofconn, b);
2156     return 0;
2157 }
2158
2159 static enum ofperr
2160 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
2161 {
2162     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2163     struct ofp_switch_config *osc;
2164     enum ofp_config_flags flags;
2165     struct ofpbuf *buf;
2166
2167     /* Send reply. */
2168     buf = ofpraw_alloc_reply(OFPRAW_OFPT_GET_CONFIG_REPLY, oh, 0);
2169     osc = ofpbuf_put_uninit(buf, sizeof *osc);
2170     flags = ofproto->frag_handling;
2171     if (ofconn_get_invalid_ttl_to_controller(ofconn)) {
2172         flags |= OFPC_INVALID_TTL_TO_CONTROLLER;
2173     }
2174     osc->flags = htons(flags);
2175     osc->miss_send_len = htons(ofconn_get_miss_send_len(ofconn));
2176     ofconn_send_reply(ofconn, buf);
2177
2178     return 0;
2179 }
2180
2181 static enum ofperr
2182 handle_set_config(struct ofconn *ofconn, const struct ofp_header *oh)
2183 {
2184     const struct ofp_switch_config *osc = ofpmsg_body(oh);
2185     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2186     uint16_t flags = ntohs(osc->flags);
2187
2188     if (ofconn_get_type(ofconn) != OFCONN_PRIMARY
2189         || ofconn_get_role(ofconn) != NX_ROLE_SLAVE) {
2190         enum ofp_config_flags cur = ofproto->frag_handling;
2191         enum ofp_config_flags next = flags & OFPC_FRAG_MASK;
2192
2193         assert((cur & OFPC_FRAG_MASK) == cur);
2194         if (cur != next) {
2195             if (ofproto->ofproto_class->set_frag_handling(ofproto, next)) {
2196                 ofproto->frag_handling = next;
2197             } else {
2198                 VLOG_WARN_RL(&rl, "%s: unsupported fragment handling mode %s",
2199                              ofproto->name,
2200                              ofputil_frag_handling_to_string(next));
2201             }
2202         }
2203     }
2204     ofconn_set_invalid_ttl_to_controller(ofconn,
2205              (flags & OFPC_INVALID_TTL_TO_CONTROLLER));
2206
2207     ofconn_set_miss_send_len(ofconn, ntohs(osc->miss_send_len));
2208
2209     return 0;
2210 }
2211
2212 /* Checks whether 'ofconn' is a slave controller.  If so, returns an OpenFlow
2213  * error message code for the caller to propagate upward.  Otherwise, returns
2214  * 0.
2215  *
2216  * The log message mentions 'msg_type'. */
2217 static enum ofperr
2218 reject_slave_controller(struct ofconn *ofconn)
2219 {
2220     if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
2221         && ofconn_get_role(ofconn) == NX_ROLE_SLAVE) {
2222         return OFPERR_OFPBRC_EPERM;
2223     } else {
2224         return 0;
2225     }
2226 }
2227
2228 static enum ofperr
2229 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
2230 {
2231     struct ofproto *p = ofconn_get_ofproto(ofconn);
2232     struct ofputil_packet_out po;
2233     struct ofpbuf *payload;
2234     uint64_t ofpacts_stub[1024 / 8];
2235     struct ofpbuf ofpacts;
2236     struct flow flow;
2237     enum ofperr error;
2238
2239     COVERAGE_INC(ofproto_packet_out);
2240
2241     error = reject_slave_controller(ofconn);
2242     if (error) {
2243         goto exit;
2244     }
2245
2246     /* Decode message. */
2247     ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
2248     error = ofputil_decode_packet_out(&po, oh, &ofpacts);
2249     if (error) {
2250         goto exit_free_ofpacts;
2251     }
2252     if (po.in_port >= p->max_ports && po.in_port < OFPP_MAX) {
2253         error = OFPERR_OFPBRC_BAD_PORT;
2254         goto exit_free_ofpacts;
2255     }
2256
2257
2258     /* Get payload. */
2259     if (po.buffer_id != UINT32_MAX) {
2260         error = ofconn_pktbuf_retrieve(ofconn, po.buffer_id, &payload, NULL);
2261         if (error || !payload) {
2262             goto exit_free_ofpacts;
2263         }
2264     } else {
2265         payload = xmalloc(sizeof *payload);
2266         ofpbuf_use_const(payload, po.packet, po.packet_len);
2267     }
2268
2269     /* Verify actions against packet, then send packet if successful. */
2270     flow_extract(payload, 0, NULL, po.in_port, &flow);
2271     error = ofpacts_check(po.ofpacts, po.ofpacts_len, &flow, p->max_ports);
2272     if (!error) {
2273         error = p->ofproto_class->packet_out(p, payload, &flow,
2274                                              po.ofpacts, po.ofpacts_len);
2275     }
2276     ofpbuf_delete(payload);
2277
2278 exit_free_ofpacts:
2279     ofpbuf_uninit(&ofpacts);
2280 exit:
2281     return error;
2282 }
2283
2284 static void
2285 update_port_config(struct ofport *port,
2286                    enum ofputil_port_config config,
2287                    enum ofputil_port_config mask)
2288 {
2289     enum ofputil_port_config old_config = port->pp.config;
2290     enum ofputil_port_config toggle;
2291
2292     toggle = (config ^ port->pp.config) & mask;
2293     if (toggle & OFPUTIL_PC_PORT_DOWN) {
2294         if (config & OFPUTIL_PC_PORT_DOWN) {
2295             netdev_turn_flags_off(port->netdev, NETDEV_UP, true);
2296         } else {
2297             netdev_turn_flags_on(port->netdev, NETDEV_UP, true);
2298         }
2299         toggle &= ~OFPUTIL_PC_PORT_DOWN;
2300     }
2301
2302     port->pp.config ^= toggle;
2303     if (port->pp.config != old_config) {
2304         port->ofproto->ofproto_class->port_reconfigured(port, old_config);
2305     }
2306 }
2307
2308 static enum ofperr
2309 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
2310 {
2311     struct ofproto *p = ofconn_get_ofproto(ofconn);
2312     struct ofputil_port_mod pm;
2313     struct ofport *port;
2314     enum ofperr error;
2315
2316     error = reject_slave_controller(ofconn);
2317     if (error) {
2318         return error;
2319     }
2320
2321     error = ofputil_decode_port_mod(oh, &pm);
2322     if (error) {
2323         return error;
2324     }
2325
2326     port = ofproto_get_port(p, pm.port_no);
2327     if (!port) {
2328         return OFPERR_OFPPMFC_BAD_PORT;
2329     } else if (!eth_addr_equals(port->pp.hw_addr, pm.hw_addr)) {
2330         return OFPERR_OFPPMFC_BAD_HW_ADDR;
2331     } else {
2332         update_port_config(port, pm.config, pm.mask);
2333         if (pm.advertise) {
2334             netdev_set_advertisements(port->netdev, pm.advertise);
2335         }
2336     }
2337     return 0;
2338 }
2339
2340 static enum ofperr
2341 handle_desc_stats_request(struct ofconn *ofconn,
2342                           const struct ofp_header *request)
2343 {
2344     struct ofproto *p = ofconn_get_ofproto(ofconn);
2345     struct ofp_desc_stats *ods;
2346     struct ofpbuf *msg;
2347
2348     msg = ofpraw_alloc_stats_reply(request, 0);
2349     ods = ofpbuf_put_zeros(msg, sizeof *ods);
2350     ovs_strlcpy(ods->mfr_desc, p->mfr_desc, sizeof ods->mfr_desc);
2351     ovs_strlcpy(ods->hw_desc, p->hw_desc, sizeof ods->hw_desc);
2352     ovs_strlcpy(ods->sw_desc, p->sw_desc, sizeof ods->sw_desc);
2353     ovs_strlcpy(ods->serial_num, p->serial_desc, sizeof ods->serial_num);
2354     ovs_strlcpy(ods->dp_desc, p->dp_desc, sizeof ods->dp_desc);
2355     ofconn_send_reply(ofconn, msg);
2356
2357     return 0;
2358 }
2359
2360 static enum ofperr
2361 handle_table_stats_request(struct ofconn *ofconn,
2362                            const struct ofp_header *request)
2363 {
2364     struct ofproto *p = ofconn_get_ofproto(ofconn);
2365     struct ofp12_table_stats *ots;
2366     struct ofpbuf *msg;
2367     size_t i;
2368
2369     /* Set up default values.
2370      *
2371      * ofp12_table_stats is used as a generic structure as
2372      * it is able to hold all the fields for ofp10_table_stats
2373      * and ofp11_table_stats (and of course itself).
2374      */
2375     ots = xcalloc(p->n_tables, sizeof *ots);
2376     for (i = 0; i < p->n_tables; i++) {
2377         ots[i].table_id = i;
2378         sprintf(ots[i].name, "table%zu", i);
2379         ots[i].match = htonll(OFPXMT12_MASK);
2380         ots[i].wildcards = htonll(OFPXMT12_MASK);
2381         ots[i].write_actions = htonl(OFPAT11_OUTPUT);
2382         ots[i].apply_actions = htonl(OFPAT11_OUTPUT);
2383         ots[i].write_setfields = htonll(OFPXMT12_MASK);
2384         ots[i].apply_setfields = htonll(OFPXMT12_MASK);
2385         ots[i].metadata_match = htonll(UINT64_MAX);
2386         ots[i].metadata_write = htonll(UINT64_MAX);
2387         ots[i].instructions = htonl(OFPIT11_ALL);
2388         ots[i].config = htonl(OFPTC11_TABLE_MISS_MASK);
2389         ots[i].max_entries = htonl(1000000); /* An arbitrary big number. */
2390         ots[i].active_count = htonl(classifier_count(&p->tables[i].cls));
2391     }
2392
2393     p->ofproto_class->get_tables(p, ots);
2394
2395     for (i = 0; i < p->n_tables; i++) {
2396         const struct oftable *table = &p->tables[i];
2397
2398         if (table->name) {
2399             ovs_strzcpy(ots[i].name, table->name, sizeof ots[i].name);
2400         }
2401
2402         if (table->max_flows < ntohl(ots[i].max_entries)) {
2403             ots[i].max_entries = htonl(table->max_flows);
2404         }
2405     }
2406
2407     msg = ofputil_encode_table_stats_reply(ots, p->n_tables, request);
2408     ofconn_send_reply(ofconn, msg);
2409
2410     free(ots);
2411
2412     return 0;
2413 }
2414
2415 static void
2416 append_port_stat(struct ofport *port, struct list *replies)
2417 {
2418     struct ofputil_port_stats ops = { .port_no = port->pp.port_no };
2419
2420     /* Intentionally ignore return value, since errors will set
2421      * 'stats' to all-1s, which is correct for OpenFlow, and
2422      * netdev_get_stats() will log errors. */
2423     ofproto_port_get_stats(port, &ops.stats);
2424
2425     ofputil_append_port_stat(replies, &ops);
2426 }
2427
2428 static enum ofperr
2429 handle_port_stats_request(struct ofconn *ofconn,
2430                           const struct ofp_header *request)
2431 {
2432     struct ofproto *p = ofconn_get_ofproto(ofconn);
2433     struct ofport *port;
2434     struct list replies;
2435     uint16_t port_no;
2436     enum ofperr error;
2437
2438     error = ofputil_decode_port_stats_request(request, &port_no);
2439     if (error) {
2440         return error;
2441     }
2442
2443     ofpmp_init(&replies, request);
2444     if (port_no != OFPP_NONE) {
2445         port = ofproto_get_port(p, port_no);
2446         if (port) {
2447             append_port_stat(port, &replies);
2448         }
2449     } else {
2450         HMAP_FOR_EACH (port, hmap_node, &p->ports) {
2451             append_port_stat(port, &replies);
2452         }
2453     }
2454
2455     ofconn_send_replies(ofconn, &replies);
2456     return 0;
2457 }
2458
2459 static enum ofperr
2460 handle_port_desc_stats_request(struct ofconn *ofconn,
2461                                const struct ofp_header *request)
2462 {
2463     struct ofproto *p = ofconn_get_ofproto(ofconn);
2464     enum ofp_version version;
2465     struct ofport *port;
2466     struct list replies;
2467
2468     ofpmp_init(&replies, request);
2469
2470     version = ofputil_protocol_to_ofp_version(ofconn_get_protocol(ofconn));
2471     HMAP_FOR_EACH (port, hmap_node, &p->ports) {
2472         ofputil_append_port_desc_stats_reply(version, &port->pp, &replies);
2473     }
2474
2475     ofconn_send_replies(ofconn, &replies);
2476     return 0;
2477 }
2478
2479 static void
2480 calc_flow_duration__(long long int start, long long int now,
2481                      uint32_t *sec, uint32_t *nsec)
2482 {
2483     long long int msecs = now - start;
2484     *sec = msecs / 1000;
2485     *nsec = (msecs % 1000) * (1000 * 1000);
2486 }
2487
2488 /* Checks whether 'table_id' is 0xff or a valid table ID in 'ofproto'.  Returns
2489  * 0 if 'table_id' is OK, otherwise an OpenFlow error code.  */
2490 static enum ofperr
2491 check_table_id(const struct ofproto *ofproto, uint8_t table_id)
2492 {
2493     return (table_id == 0xff || table_id < ofproto->n_tables
2494             ? 0
2495             : OFPERR_OFPBRC_BAD_TABLE_ID);
2496
2497 }
2498
2499 static struct oftable *
2500 next_visible_table(const struct ofproto *ofproto, uint8_t table_id)
2501 {
2502     struct oftable *table;
2503
2504     for (table = &ofproto->tables[table_id];
2505          table < &ofproto->tables[ofproto->n_tables];
2506          table++) {
2507         if (!(table->flags & OFTABLE_HIDDEN)) {
2508             return table;
2509         }
2510     }
2511
2512     return NULL;
2513 }
2514
2515 static struct oftable *
2516 first_matching_table(const struct ofproto *ofproto, uint8_t table_id)
2517 {
2518     if (table_id == 0xff) {
2519         return next_visible_table(ofproto, 0);
2520     } else if (table_id < ofproto->n_tables) {
2521         return &ofproto->tables[table_id];
2522     } else {
2523         return NULL;
2524     }
2525 }
2526
2527 static struct oftable *
2528 next_matching_table(const struct ofproto *ofproto,
2529                     const struct oftable *table, uint8_t table_id)
2530 {
2531     return (table_id == 0xff
2532             ? next_visible_table(ofproto, (table - ofproto->tables) + 1)
2533             : NULL);
2534 }
2535
2536 /* Assigns TABLE to each oftable, in turn, that matches TABLE_ID in OFPROTO:
2537  *
2538  *   - If TABLE_ID is 0xff, this iterates over every classifier table in
2539  *     OFPROTO, skipping tables marked OFTABLE_HIDDEN.
2540  *
2541  *   - If TABLE_ID is the number of a table in OFPROTO, then the loop iterates
2542  *     only once, for that table.  (This can be used to access tables marked
2543  *     OFTABLE_HIDDEN.)
2544  *
2545  *   - Otherwise, TABLE_ID isn't valid for OFPROTO, so the loop won't be
2546  *     entered at all.  (Perhaps you should have validated TABLE_ID with
2547  *     check_table_id().)
2548  *
2549  * All parameters are evaluated multiple times.
2550  */
2551 #define FOR_EACH_MATCHING_TABLE(TABLE, TABLE_ID, OFPROTO)         \
2552     for ((TABLE) = first_matching_table(OFPROTO, TABLE_ID);       \
2553          (TABLE) != NULL;                                         \
2554          (TABLE) = next_matching_table(OFPROTO, TABLE, TABLE_ID))
2555
2556 /* Searches 'ofproto' for rules in table 'table_id' (or in all tables, if
2557  * 'table_id' is 0xff) that match 'match' in the "loose" way required for
2558  * OpenFlow OFPFC_MODIFY and OFPFC_DELETE requests and puts them on list
2559  * 'rules'.
2560  *
2561  * If 'out_port' is anything other than OFPP_NONE, then only rules that output
2562  * to 'out_port' are included.
2563  *
2564  * Hidden rules are always omitted.
2565  *
2566  * Returns 0 on success, otherwise an OpenFlow error code. */
2567 static enum ofperr
2568 collect_rules_loose(struct ofproto *ofproto, uint8_t table_id,
2569                     const struct match *match,
2570                     ovs_be64 cookie, ovs_be64 cookie_mask,
2571                     uint16_t out_port, struct list *rules)
2572 {
2573     struct oftable *table;
2574     struct cls_rule cr;
2575     enum ofperr error;
2576
2577     error = check_table_id(ofproto, table_id);
2578     if (error) {
2579         return error;
2580     }
2581
2582     list_init(rules);
2583     cls_rule_init(&cr, match, 0);
2584     FOR_EACH_MATCHING_TABLE (table, table_id, ofproto) {
2585         struct cls_cursor cursor;
2586         struct rule *rule;
2587
2588         cls_cursor_init(&cursor, &table->cls, &cr);
2589         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
2590             if (rule->pending) {
2591                 error = OFPROTO_POSTPONE;
2592                 goto exit;
2593             }
2594             if (!ofproto_rule_is_hidden(rule)
2595                 && ofproto_rule_has_out_port(rule, out_port)
2596                     && !((rule->flow_cookie ^ cookie) & cookie_mask)) {
2597                 list_push_back(rules, &rule->ofproto_node);
2598             }
2599         }
2600     }
2601
2602 exit:
2603     cls_rule_destroy(&cr);
2604     return error;
2605 }
2606
2607 /* Searches 'ofproto' for rules in table 'table_id' (or in all tables, if
2608  * 'table_id' is 0xff) that match 'match' in the "strict" way required for
2609  * OpenFlow OFPFC_MODIFY_STRICT and OFPFC_DELETE_STRICT requests and puts them
2610  * on list 'rules'.
2611  *
2612  * If 'out_port' is anything other than OFPP_NONE, then only rules that output
2613  * to 'out_port' are included.
2614  *
2615  * Hidden rules are always omitted.
2616  *
2617  * Returns 0 on success, otherwise an OpenFlow error code. */
2618 static enum ofperr
2619 collect_rules_strict(struct ofproto *ofproto, uint8_t table_id,
2620                      const struct match *match, unsigned int priority,
2621                      ovs_be64 cookie, ovs_be64 cookie_mask,
2622                      uint16_t out_port, struct list *rules)
2623 {
2624     struct oftable *table;
2625     struct cls_rule cr;
2626     int error;
2627
2628     error = check_table_id(ofproto, table_id);
2629     if (error) {
2630         return error;
2631     }
2632
2633     list_init(rules);
2634     cls_rule_init(&cr, match, priority);
2635     FOR_EACH_MATCHING_TABLE (table, table_id, ofproto) {
2636         struct rule *rule;
2637
2638         rule = rule_from_cls_rule(classifier_find_rule_exactly(&table->cls,
2639                                                                &cr));
2640         if (rule) {
2641             if (rule->pending) {
2642                 error = OFPROTO_POSTPONE;
2643                 goto exit;
2644             }
2645             if (!ofproto_rule_is_hidden(rule)
2646                 && ofproto_rule_has_out_port(rule, out_port)
2647                     && !((rule->flow_cookie ^ cookie) & cookie_mask)) {
2648                 list_push_back(rules, &rule->ofproto_node);
2649             }
2650         }
2651     }
2652
2653 exit:
2654     cls_rule_destroy(&cr);
2655     return 0;
2656 }
2657
2658 /* Returns 'age_ms' (a duration in milliseconds), converted to seconds and
2659  * forced into the range of a uint16_t. */
2660 static int
2661 age_secs(long long int age_ms)
2662 {
2663     return (age_ms < 0 ? 0
2664             : age_ms >= UINT16_MAX * 1000 ? UINT16_MAX
2665             : (unsigned int) age_ms / 1000);
2666 }
2667
2668 static enum ofperr
2669 handle_flow_stats_request(struct ofconn *ofconn,
2670                           const struct ofp_header *request)
2671 {
2672     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2673     struct ofputil_flow_stats_request fsr;
2674     struct list replies;
2675     struct list rules;
2676     struct rule *rule;
2677     enum ofperr error;
2678
2679     error = ofputil_decode_flow_stats_request(&fsr, request);
2680     if (error) {
2681         return error;
2682     }
2683
2684     error = collect_rules_loose(ofproto, fsr.table_id, &fsr.match,
2685                                 fsr.cookie, fsr.cookie_mask,
2686                                 fsr.out_port, &rules);
2687     if (error) {
2688         return error;
2689     }
2690
2691     ofpmp_init(&replies, request);
2692     LIST_FOR_EACH (rule, ofproto_node, &rules) {
2693         long long int now = time_msec();
2694         struct ofputil_flow_stats fs;
2695
2696         minimatch_expand(&rule->cr.match, &fs.match);
2697         fs.priority = rule->cr.priority;
2698         fs.cookie = rule->flow_cookie;
2699         fs.table_id = rule->table_id;
2700         calc_flow_duration__(rule->created, now, &fs.duration_sec,
2701                              &fs.duration_nsec);
2702         fs.idle_timeout = rule->idle_timeout;
2703         fs.hard_timeout = rule->hard_timeout;
2704         fs.idle_age = age_secs(now - rule->used);
2705         fs.hard_age = age_secs(now - rule->modified);
2706         ofproto->ofproto_class->rule_get_stats(rule, &fs.packet_count,
2707                                                &fs.byte_count);
2708         fs.ofpacts = rule->ofpacts;
2709         fs.ofpacts_len = rule->ofpacts_len;
2710         ofputil_append_flow_stats_reply(&fs, &replies);
2711     }
2712     ofconn_send_replies(ofconn, &replies);
2713
2714     return 0;
2715 }
2716
2717 static void
2718 flow_stats_ds(struct rule *rule, struct ds *results)
2719 {
2720     uint64_t packet_count, byte_count;
2721
2722     rule->ofproto->ofproto_class->rule_get_stats(rule,
2723                                                  &packet_count, &byte_count);
2724
2725     if (rule->table_id != 0) {
2726         ds_put_format(results, "table_id=%"PRIu8", ", rule->table_id);
2727     }
2728     ds_put_format(results, "duration=%llds, ",
2729                   (time_msec() - rule->created) / 1000);
2730     ds_put_format(results, "priority=%u, ", rule->cr.priority);
2731     ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
2732     ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
2733     cls_rule_format(&rule->cr, results);
2734     ds_put_char(results, ',');
2735     if (rule->ofpacts_len > 0) {
2736         ofpacts_format(rule->ofpacts, rule->ofpacts_len, results);
2737     } else {
2738         ds_put_cstr(results, "drop");
2739     }
2740     ds_put_cstr(results, "\n");
2741 }
2742
2743 /* Adds a pretty-printed description of all flows to 'results', including
2744  * hidden flows (e.g., set up by in-band control). */
2745 void
2746 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
2747 {
2748     struct oftable *table;
2749
2750     OFPROTO_FOR_EACH_TABLE (table, p) {
2751         struct cls_cursor cursor;
2752         struct rule *rule;
2753
2754         cls_cursor_init(&cursor, &table->cls, NULL);
2755         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
2756             flow_stats_ds(rule, results);
2757         }
2758     }
2759 }
2760
2761 /* Obtains the NetFlow engine type and engine ID for 'ofproto' into
2762  * '*engine_type' and '*engine_id', respectively. */
2763 void
2764 ofproto_get_netflow_ids(const struct ofproto *ofproto,
2765                         uint8_t *engine_type, uint8_t *engine_id)
2766 {
2767     ofproto->ofproto_class->get_netflow_ids(ofproto, engine_type, engine_id);
2768 }
2769
2770 /* Checks the fault status of CFM for 'ofp_port' within 'ofproto'.  Returns a
2771  * bitmask of 'cfm_fault_reason's to indicate a CFM fault (generally
2772  * indicating a connectivity problem).  Returns zero if CFM is not faulted,
2773  * and -1 if CFM is not enabled on 'ofp_port'. */
2774 int
2775 ofproto_port_get_cfm_fault(const struct ofproto *ofproto, uint16_t ofp_port)
2776 {
2777     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
2778     return (ofport && ofproto->ofproto_class->get_cfm_fault
2779             ? ofproto->ofproto_class->get_cfm_fault(ofport)
2780             : -1);
2781 }
2782
2783 /* Checks the operational status reported by the remote CFM endpoint of
2784  * 'ofp_port'  Returns 1 if operationally up, 0 if operationally down, and -1
2785  * if CFM is not enabled on 'ofp_port' or does not support operational status.
2786  */
2787 int
2788 ofproto_port_get_cfm_opup(const struct ofproto *ofproto, uint16_t ofp_port)
2789 {
2790     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
2791     return (ofport && ofproto->ofproto_class->get_cfm_opup
2792             ? ofproto->ofproto_class->get_cfm_opup(ofport)
2793             : -1);
2794 }
2795
2796 /* Gets the MPIDs of the remote maintenance points broadcasting to 'ofp_port'
2797  * within 'ofproto'.  Populates 'rmps' with an array of MPIDs owned by
2798  * 'ofproto', and 'n_rmps' with the number of MPIDs in 'rmps'.  Returns a
2799  * number less than 0 if CFM is not enabled on 'ofp_port'. */
2800 int
2801 ofproto_port_get_cfm_remote_mpids(const struct ofproto *ofproto,
2802                                   uint16_t ofp_port, const uint64_t **rmps,
2803                                   size_t *n_rmps)
2804 {
2805     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
2806
2807     *rmps = NULL;
2808     *n_rmps = 0;
2809     return (ofport && ofproto->ofproto_class->get_cfm_remote_mpids
2810             ? ofproto->ofproto_class->get_cfm_remote_mpids(ofport, rmps,
2811                                                            n_rmps)
2812             : -1);
2813 }
2814
2815 /* Checks the health of the CFM for 'ofp_port' within 'ofproto'.  Returns an
2816  * integer value between 0 and 100 to indicate the health of the port as a
2817  * percentage which is the average of cfm health of all the remote_mpids or
2818  * returns -1 if CFM is not enabled on 'ofport'. */
2819 int
2820 ofproto_port_get_cfm_health(const struct ofproto *ofproto, uint16_t ofp_port)
2821 {
2822     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
2823     return (ofport && ofproto->ofproto_class->get_cfm_health
2824             ? ofproto->ofproto_class->get_cfm_health(ofport)
2825             : -1);
2826 }
2827
2828 static enum ofperr
2829 handle_aggregate_stats_request(struct ofconn *ofconn,
2830                                const struct ofp_header *oh)
2831 {
2832     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2833     struct ofputil_flow_stats_request request;
2834     struct ofputil_aggregate_stats stats;
2835     bool unknown_packets, unknown_bytes;
2836     struct ofpbuf *reply;
2837     struct list rules;
2838     struct rule *rule;
2839     enum ofperr error;
2840
2841     error = ofputil_decode_flow_stats_request(&request, oh);
2842     if (error) {
2843         return error;
2844     }
2845
2846     error = collect_rules_loose(ofproto, request.table_id, &request.match,
2847                                 request.cookie, request.cookie_mask,
2848                                 request.out_port, &rules);
2849     if (error) {
2850         return error;
2851     }
2852
2853     memset(&stats, 0, sizeof stats);
2854     unknown_packets = unknown_bytes = false;
2855     LIST_FOR_EACH (rule, ofproto_node, &rules) {
2856         uint64_t packet_count;
2857         uint64_t byte_count;
2858
2859         ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
2860                                                &byte_count);
2861
2862         if (packet_count == UINT64_MAX) {
2863             unknown_packets = true;
2864         } else {
2865             stats.packet_count += packet_count;
2866         }
2867
2868         if (byte_count == UINT64_MAX) {
2869             unknown_bytes = true;
2870         } else {
2871             stats.byte_count += byte_count;
2872         }
2873
2874         stats.flow_count++;
2875     }
2876     if (unknown_packets) {
2877         stats.packet_count = UINT64_MAX;
2878     }
2879     if (unknown_bytes) {
2880         stats.byte_count = UINT64_MAX;
2881     }
2882
2883     reply = ofputil_encode_aggregate_stats_reply(&stats, oh);
2884     ofconn_send_reply(ofconn, reply);
2885
2886     return 0;
2887 }
2888
2889 struct queue_stats_cbdata {
2890     struct ofport *ofport;
2891     struct list replies;
2892 };
2893
2894 static void
2895 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
2896                 const struct netdev_queue_stats *stats)
2897 {
2898
2899     struct ofputil_queue_stats oqs = {
2900         .port_no = cbdata->ofport->pp.port_no,
2901         .queue_id = queue_id,
2902         .stats = *stats,
2903     };
2904     ofputil_append_queue_stat(&cbdata->replies, &oqs);
2905 }
2906
2907 static void
2908 handle_queue_stats_dump_cb(uint32_t queue_id,
2909                            struct netdev_queue_stats *stats,
2910                            void *cbdata_)
2911 {
2912     struct queue_stats_cbdata *cbdata = cbdata_;
2913
2914     put_queue_stats(cbdata, queue_id, stats);
2915 }
2916
2917 static enum ofperr
2918 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
2919                             struct queue_stats_cbdata *cbdata)
2920 {
2921     cbdata->ofport = port;
2922     if (queue_id == OFPQ_ALL) {
2923         netdev_dump_queue_stats(port->netdev,
2924                                 handle_queue_stats_dump_cb, cbdata);
2925     } else {
2926         struct netdev_queue_stats stats;
2927
2928         if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
2929             put_queue_stats(cbdata, queue_id, &stats);
2930         } else {
2931             return OFPERR_OFPQOFC_BAD_QUEUE;
2932         }
2933     }
2934     return 0;
2935 }
2936
2937 static enum ofperr
2938 handle_queue_stats_request(struct ofconn *ofconn,
2939                            const struct ofp_header *rq)
2940 {
2941     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2942     struct queue_stats_cbdata cbdata;
2943     struct ofport *port;
2944     enum ofperr error;
2945     struct ofputil_queue_stats_request oqsr;
2946
2947     COVERAGE_INC(ofproto_queue_req);
2948
2949     ofpmp_init(&cbdata.replies, rq);
2950
2951     error = ofputil_decode_queue_stats_request(rq, &oqsr);
2952     if (error) {
2953         return error;
2954     }
2955
2956     if (oqsr.port_no == OFPP_ALL) {
2957         error = OFPERR_OFPQOFC_BAD_QUEUE;
2958         HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
2959             if (!handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)) {
2960                 error = 0;
2961             }
2962         }
2963     } else {
2964         port = ofproto_get_port(ofproto, oqsr.port_no);
2965         error = (port
2966                  ? handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)
2967                  : OFPERR_OFPQOFC_BAD_PORT);
2968     }
2969     if (!error) {
2970         ofconn_send_replies(ofconn, &cbdata.replies);
2971     } else {
2972         ofpbuf_list_delete(&cbdata.replies);
2973     }
2974
2975     return error;
2976 }
2977
2978 static bool
2979 is_flow_deletion_pending(const struct ofproto *ofproto,
2980                          const struct cls_rule *cls_rule,
2981                          uint8_t table_id)
2982 {
2983     if (!hmap_is_empty(&ofproto->deletions)) {
2984         struct ofoperation *op;
2985
2986         HMAP_FOR_EACH_WITH_HASH (op, hmap_node,
2987                                  cls_rule_hash(cls_rule, table_id),
2988                                  &ofproto->deletions) {
2989             if (cls_rule_equal(cls_rule, &op->rule->cr)) {
2990                 return true;
2991             }
2992         }
2993     }
2994
2995     return false;
2996 }
2997
2998 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
2999  * in which no matching flow already exists in the flow table.
3000  *
3001  * Adds the flow specified by 'ofm', which is followed by 'n_actions'
3002  * ofp_actions, to the ofproto's flow table.  Returns 0 on success, an OpenFlow
3003  * error code on failure, or OFPROTO_POSTPONE if the operation cannot be
3004  * initiated now but may be retried later.
3005  *
3006  * Upon successful return, takes ownership of 'fm->ofpacts'.  On failure,
3007  * ownership remains with the caller.
3008  *
3009  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3010  * if any. */
3011 static enum ofperr
3012 add_flow(struct ofproto *ofproto, struct ofconn *ofconn,
3013          const struct ofputil_flow_mod *fm, const struct ofp_header *request)
3014 {
3015     struct oftable *table;
3016     struct ofopgroup *group;
3017     struct rule *victim;
3018     struct cls_rule cr;
3019     struct rule *rule;
3020     int error;
3021
3022     error = check_table_id(ofproto, fm->table_id);
3023     if (error) {
3024         return error;
3025     }
3026
3027     /* Pick table. */
3028     if (fm->table_id == 0xff) {
3029         uint8_t table_id;
3030         if (ofproto->ofproto_class->rule_choose_table) {
3031             error = ofproto->ofproto_class->rule_choose_table(ofproto,
3032                                                               &fm->match,
3033                                                               &table_id);
3034             if (error) {
3035                 return error;
3036             }
3037             assert(table_id < ofproto->n_tables);
3038             table = &ofproto->tables[table_id];
3039         } else {
3040             table = &ofproto->tables[0];
3041         }
3042     } else if (fm->table_id < ofproto->n_tables) {
3043         table = &ofproto->tables[fm->table_id];
3044     } else {
3045         return OFPERR_OFPBRC_BAD_TABLE_ID;
3046     }
3047
3048     if (table->flags & OFTABLE_READONLY) {
3049         return OFPERR_OFPBRC_EPERM;
3050     }
3051
3052     /* Allocate new rule and initialize classifier rule. */
3053     rule = ofproto->ofproto_class->rule_alloc();
3054     if (!rule) {
3055         VLOG_WARN_RL(&rl, "%s: failed to create rule (%s)",
3056                      ofproto->name, strerror(error));
3057         return ENOMEM;
3058     }
3059     cls_rule_init(&rule->cr, &fm->match, fm->priority);
3060
3061     /* Serialize against pending deletion. */
3062     if (is_flow_deletion_pending(ofproto, &cr, table - ofproto->tables)) {
3063         cls_rule_destroy(&rule->cr);
3064         ofproto->ofproto_class->rule_dealloc(rule);
3065         return OFPROTO_POSTPONE;
3066     }
3067
3068     /* Check for overlap, if requested. */
3069     if (fm->flags & OFPFF_CHECK_OVERLAP
3070         && classifier_rule_overlaps(&table->cls, &rule->cr)) {
3071         cls_rule_destroy(&rule->cr);
3072         ofproto->ofproto_class->rule_dealloc(rule);
3073         return OFPERR_OFPFMFC_OVERLAP;
3074     }
3075
3076     rule->ofproto = ofproto;
3077     rule->pending = NULL;
3078     rule->flow_cookie = fm->new_cookie;
3079     rule->created = rule->modified = rule->used = time_msec();
3080     rule->idle_timeout = fm->idle_timeout;
3081     rule->hard_timeout = fm->hard_timeout;
3082     rule->table_id = table - ofproto->tables;
3083     rule->send_flow_removed = (fm->flags & OFPFF_SEND_FLOW_REM) != 0;
3084     rule->ofpacts = xmemdup(fm->ofpacts, fm->ofpacts_len);
3085     rule->ofpacts_len = fm->ofpacts_len;
3086     rule->evictable = true;
3087     rule->eviction_group = NULL;
3088     rule->monitor_flags = 0;
3089     rule->add_seqno = 0;
3090     rule->modify_seqno = 0;
3091
3092     /* Insert new rule. */
3093     victim = oftable_replace_rule(rule);
3094     if (victim && !rule_is_modifiable(victim)) {
3095         error = OFPERR_OFPBRC_EPERM;
3096     } else if (victim && victim->pending) {
3097         error = OFPROTO_POSTPONE;
3098     } else {
3099         struct ofoperation *op;
3100         struct rule *evict;
3101
3102         if (classifier_count(&table->cls) > table->max_flows) {
3103             bool was_evictable;
3104
3105             was_evictable = rule->evictable;
3106             rule->evictable = false;
3107             evict = choose_rule_to_evict(table);
3108             rule->evictable = was_evictable;
3109
3110             if (!evict) {
3111                 error = OFPERR_OFPFMFC_TABLE_FULL;
3112                 goto exit;
3113             } else if (evict->pending) {
3114                 error = OFPROTO_POSTPONE;
3115                 goto exit;
3116             }
3117         } else {
3118             evict = NULL;
3119         }
3120
3121         group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
3122         op = ofoperation_create(group, rule, OFOPERATION_ADD, 0);
3123         op->victim = victim;
3124
3125         error = ofproto->ofproto_class->rule_construct(rule);
3126         if (error) {
3127             op->group->n_running--;
3128             ofoperation_destroy(rule->pending);
3129         } else if (evict) {
3130             delete_flow__(evict, group);
3131         }
3132         ofopgroup_submit(group);
3133     }
3134
3135 exit:
3136     /* Back out if an error occurred. */
3137     if (error) {
3138         oftable_substitute_rule(rule, victim);
3139         ofproto_rule_destroy__(rule);
3140     }
3141     return error;
3142 }
3143 \f
3144 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
3145
3146 /* Modifies the rules listed in 'rules', changing their actions to match those
3147  * in 'fm'.
3148  *
3149  * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
3150  * if any.
3151  *
3152  * Returns 0 on success, otherwise an OpenFlow error code. */
3153 static enum ofperr
3154 modify_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
3155                const struct ofputil_flow_mod *fm,
3156                const struct ofp_header *request, struct list *rules)
3157 {
3158     struct ofopgroup *group;
3159     struct rule *rule;
3160     enum ofperr error;
3161
3162     group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
3163     error = OFPERR_OFPBRC_EPERM;
3164     LIST_FOR_EACH (rule, ofproto_node, rules) {
3165         struct ofoperation *op;
3166         bool actions_changed;
3167         ovs_be64 new_cookie;
3168
3169         if (rule_is_modifiable(rule)) {
3170             /* At least one rule is modifiable, don't report EPERM error. */
3171             error = 0;
3172         } else {
3173             continue;
3174         }
3175
3176         actions_changed = !ofpacts_equal(fm->ofpacts, fm->ofpacts_len,
3177                                          rule->ofpacts, rule->ofpacts_len);
3178         new_cookie = (fm->new_cookie != htonll(UINT64_MAX)
3179                       ? fm->new_cookie
3180                       : rule->flow_cookie);
3181         if (!actions_changed && new_cookie == rule->flow_cookie) {
3182             /* No change at all. */
3183             continue;
3184         }
3185
3186         op = ofoperation_create(group, rule, OFOPERATION_MODIFY, 0);
3187         rule->flow_cookie = new_cookie;
3188         if (actions_changed) {
3189             op->ofpacts = rule->ofpacts;
3190             op->ofpacts_len = rule->ofpacts_len;
3191             rule->ofpacts = xmemdup(fm->ofpacts, fm->ofpacts_len);
3192             rule->ofpacts_len = fm->ofpacts_len;
3193             rule->ofproto->ofproto_class->rule_modify_actions(rule);
3194         } else {
3195             ofoperation_complete(op, 0);
3196         }
3197     }
3198     ofopgroup_submit(group);
3199
3200     return error;
3201 }
3202
3203 static enum ofperr
3204 modify_flows_add(struct ofproto *ofproto, struct ofconn *ofconn,
3205                  const struct ofputil_flow_mod *fm,
3206                  const struct ofp_header *request)
3207 {
3208     if (fm->cookie_mask != htonll(0) || fm->new_cookie == htonll(UINT64_MAX)) {
3209         return 0;
3210     }
3211     return add_flow(ofproto, ofconn, fm, request);
3212 }
3213
3214 /* Implements OFPFC_MODIFY.  Returns 0 on success or an OpenFlow error code on
3215  * failure.
3216  *
3217  * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
3218  * if any. */
3219 static enum ofperr
3220 modify_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
3221                    const struct ofputil_flow_mod *fm,
3222                    const struct ofp_header *request)
3223 {
3224     struct list rules;
3225     int error;
3226
3227     error = collect_rules_loose(ofproto, fm->table_id, &fm->match,
3228                                 fm->cookie, fm->cookie_mask,
3229                                 OFPP_NONE, &rules);
3230     if (error) {
3231         return error;
3232     } else if (list_is_empty(&rules)) {
3233         return modify_flows_add(ofproto, ofconn, fm, request);
3234     } else {
3235         return modify_flows__(ofproto, ofconn, fm, request, &rules);
3236     }
3237 }
3238
3239 /* Implements OFPFC_MODIFY_STRICT.  Returns 0 on success or an OpenFlow error
3240  * code on failure.
3241  *
3242  * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
3243  * if any. */
3244 static enum ofperr
3245 modify_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
3246                    const struct ofputil_flow_mod *fm,
3247                    const struct ofp_header *request)
3248 {
3249     struct list rules;
3250     int error;
3251
3252     error = collect_rules_strict(ofproto, fm->table_id, &fm->match,
3253                                  fm->priority, fm->cookie, fm->cookie_mask,
3254                                  OFPP_NONE, &rules);
3255
3256     if (error) {
3257         return error;
3258     } else if (list_is_empty(&rules)) {
3259         return modify_flows_add(ofproto, ofconn, fm, request);
3260     } else {
3261         return list_is_singleton(&rules) ? modify_flows__(ofproto, ofconn,
3262                                                           fm, request, &rules)
3263                                          : 0;
3264     }
3265 }
3266 \f
3267 /* OFPFC_DELETE implementation. */
3268
3269 static void
3270 delete_flow__(struct rule *rule, struct ofopgroup *group)
3271 {
3272     struct ofproto *ofproto = rule->ofproto;
3273
3274     ofproto_rule_send_removed(rule, OFPRR_DELETE);
3275
3276     ofoperation_create(group, rule, OFOPERATION_DELETE, OFPRR_DELETE);
3277     oftable_remove_rule(rule);
3278     ofproto->ofproto_class->rule_destruct(rule);
3279 }
3280
3281 /* Deletes the rules listed in 'rules'.
3282  *
3283  * Returns 0 on success, otherwise an OpenFlow error code. */
3284 static enum ofperr
3285 delete_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
3286                const struct ofp_header *request, struct list *rules)
3287 {
3288     struct rule *rule, *next;
3289     struct ofopgroup *group;
3290
3291     group = ofopgroup_create(ofproto, ofconn, request, UINT32_MAX);
3292     LIST_FOR_EACH_SAFE (rule, next, ofproto_node, rules) {
3293         delete_flow__(rule, group);
3294     }
3295     ofopgroup_submit(group);
3296
3297     return 0;
3298 }
3299
3300 /* Implements OFPFC_DELETE. */
3301 static enum ofperr
3302 delete_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
3303                    const struct ofputil_flow_mod *fm,
3304                    const struct ofp_header *request)
3305 {
3306     struct list rules;
3307     enum ofperr error;
3308
3309     error = collect_rules_loose(ofproto, fm->table_id, &fm->match,
3310                                 fm->cookie, fm->cookie_mask,
3311                                 fm->out_port, &rules);
3312     return (error ? error
3313             : !list_is_empty(&rules) ? delete_flows__(ofproto, ofconn, request,
3314                                                       &rules)
3315             : 0);
3316 }
3317
3318 /* Implements OFPFC_DELETE_STRICT. */
3319 static enum ofperr
3320 delete_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
3321                    const struct ofputil_flow_mod *fm,
3322                    const struct ofp_header *request)
3323 {
3324     struct list rules;
3325     enum ofperr error;
3326
3327     error = collect_rules_strict(ofproto, fm->table_id, &fm->match,
3328                                  fm->priority, fm->cookie, fm->cookie_mask,
3329                                  fm->out_port, &rules);
3330     return (error ? error
3331             : list_is_singleton(&rules) ? delete_flows__(ofproto, ofconn,
3332                                                          request, &rules)
3333             : 0);
3334 }
3335
3336 static void
3337 ofproto_rule_send_removed(struct rule *rule, uint8_t reason)
3338 {
3339     struct ofputil_flow_removed fr;
3340
3341     if (ofproto_rule_is_hidden(rule) || !rule->send_flow_removed) {
3342         return;
3343     }
3344
3345     minimatch_expand(&rule->cr.match, &fr.match);
3346     fr.priority = rule->cr.priority;
3347     fr.cookie = rule->flow_cookie;
3348     fr.reason = reason;
3349     fr.table_id = rule->table_id;
3350     calc_flow_duration__(rule->created, time_msec(),
3351                          &fr.duration_sec, &fr.duration_nsec);
3352     fr.idle_timeout = rule->idle_timeout;
3353     fr.hard_timeout = rule->hard_timeout;
3354     rule->ofproto->ofproto_class->rule_get_stats(rule, &fr.packet_count,
3355                                                  &fr.byte_count);
3356
3357     connmgr_send_flow_removed(rule->ofproto->connmgr, &fr);
3358 }
3359
3360 void
3361 ofproto_rule_update_used(struct rule *rule, long long int used)
3362 {
3363     if (used > rule->used) {
3364         struct eviction_group *evg = rule->eviction_group;
3365
3366         rule->used = used;
3367         if (evg) {
3368             heap_change(&evg->rules, &rule->evg_node,
3369                         rule_eviction_priority(rule));
3370         }
3371     }
3372 }
3373
3374 /* Sends an OpenFlow "flow removed" message with the given 'reason' (either
3375  * OFPRR_HARD_TIMEOUT or OFPRR_IDLE_TIMEOUT), and then removes 'rule' from its
3376  * ofproto.
3377  *
3378  * 'rule' must not have a pending operation (that is, 'rule->pending' must be
3379  * NULL).
3380  *
3381  * ofproto implementation ->run() functions should use this function to expire
3382  * OpenFlow flows. */
3383 void
3384 ofproto_rule_expire(struct rule *rule, uint8_t reason)
3385 {
3386     struct ofproto *ofproto = rule->ofproto;
3387     struct ofopgroup *group;
3388
3389     assert(reason == OFPRR_HARD_TIMEOUT || reason == OFPRR_IDLE_TIMEOUT);
3390
3391     ofproto_rule_send_removed(rule, reason);
3392
3393     group = ofopgroup_create_unattached(ofproto);
3394     ofoperation_create(group, rule, OFOPERATION_DELETE, reason);
3395     oftable_remove_rule(rule);
3396     ofproto->ofproto_class->rule_destruct(rule);
3397     ofopgroup_submit(group);
3398 }
3399 \f
3400 static enum ofperr
3401 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
3402 {
3403     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3404     struct ofputil_flow_mod fm;
3405     uint64_t ofpacts_stub[1024 / 8];
3406     struct ofpbuf ofpacts;
3407     enum ofperr error;
3408     long long int now;
3409
3410     error = reject_slave_controller(ofconn);
3411     if (error) {
3412         goto exit;
3413     }
3414
3415     ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
3416     error = ofputil_decode_flow_mod(&fm, oh, ofconn_get_protocol(ofconn),
3417                                     &ofpacts);
3418     if (error) {
3419         goto exit_free_ofpacts;
3420     }
3421
3422     if (fm.flags & OFPFF10_EMERG) {
3423         /* We do not support the OpenFlow 1.0 emergency flow cache, which
3424          * is not required in OpenFlow 1.0.1 and removed from OpenFlow 1.1.
3425          * There is no good error code, so just state that the flow table
3426          * is full. */
3427         error = OFPERR_OFPFMFC_TABLE_FULL;
3428     }
3429     if (!error) {
3430         error = ofpacts_check(fm.ofpacts, fm.ofpacts_len,
3431                               &fm.match.flow, ofproto->max_ports);
3432     }
3433     if (!error) {
3434         error = handle_flow_mod__(ofconn_get_ofproto(ofconn), ofconn, &fm, oh);
3435     }
3436     if (error) {
3437         goto exit_free_ofpacts;
3438     }
3439
3440     /* Record the operation for logging a summary report. */
3441     switch (fm.command) {
3442     case OFPFC_ADD:
3443         ofproto->n_add++;
3444         break;
3445
3446     case OFPFC_MODIFY:
3447     case OFPFC_MODIFY_STRICT:
3448         ofproto->n_modify++;
3449         break;
3450
3451     case OFPFC_DELETE:
3452     case OFPFC_DELETE_STRICT:
3453         ofproto->n_delete++;
3454         break;
3455     }
3456
3457     now = time_msec();
3458     if (ofproto->next_op_report == LLONG_MAX) {
3459         ofproto->first_op = now;
3460         ofproto->next_op_report = MAX(now + 10 * 1000,
3461                                       ofproto->op_backoff);
3462         ofproto->op_backoff = ofproto->next_op_report + 60 * 1000;
3463     }
3464     ofproto->last_op = now;
3465
3466 exit_free_ofpacts:
3467     ofpbuf_uninit(&ofpacts);
3468 exit:
3469     return error;
3470 }
3471
3472 static enum ofperr
3473 handle_flow_mod__(struct ofproto *ofproto, struct ofconn *ofconn,
3474                   const struct ofputil_flow_mod *fm,
3475                   const struct ofp_header *oh)
3476 {
3477     if (ofproto->n_pending >= 50) {
3478         assert(!list_is_empty(&ofproto->pending));
3479         return OFPROTO_POSTPONE;
3480     }
3481
3482     switch (fm->command) {
3483     case OFPFC_ADD:
3484         return add_flow(ofproto, ofconn, fm, oh);
3485
3486     case OFPFC_MODIFY:
3487         return modify_flows_loose(ofproto, ofconn, fm, oh);
3488
3489     case OFPFC_MODIFY_STRICT:
3490         return modify_flow_strict(ofproto, ofconn, fm, oh);
3491
3492     case OFPFC_DELETE:
3493         return delete_flows_loose(ofproto, ofconn, fm, oh);
3494
3495     case OFPFC_DELETE_STRICT:
3496         return delete_flow_strict(ofproto, ofconn, fm, oh);
3497
3498     default:
3499         if (fm->command > 0xff) {
3500             VLOG_WARN_RL(&rl, "%s: flow_mod has explicit table_id but "
3501                          "flow_mod_table_id extension is not enabled",
3502                          ofproto->name);
3503         }
3504         return OFPERR_OFPFMFC_BAD_COMMAND;
3505     }
3506 }
3507
3508 static enum ofperr
3509 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
3510 {
3511     const struct nx_role_request *nrr = ofpmsg_body(oh);
3512     struct nx_role_request *reply;
3513     struct ofpbuf *buf;
3514     uint32_t role;
3515
3516     role = ntohl(nrr->role);
3517     if (role != NX_ROLE_OTHER && role != NX_ROLE_MASTER
3518         && role != NX_ROLE_SLAVE) {
3519         return OFPERR_OFPRRFC_BAD_ROLE;
3520     }
3521
3522     if (ofconn_get_role(ofconn) != role
3523         && ofconn_has_pending_opgroups(ofconn)) {
3524         return OFPROTO_POSTPONE;
3525     }
3526
3527     ofconn_set_role(ofconn, role);
3528
3529     buf = ofpraw_alloc_reply(OFPRAW_NXT_ROLE_REPLY, oh, 0);
3530     reply = ofpbuf_put_zeros(buf, sizeof *reply);
3531     reply->role = htonl(role);
3532     ofconn_send_reply(ofconn, buf);
3533
3534     return 0;
3535 }
3536
3537 static enum ofperr
3538 handle_nxt_flow_mod_table_id(struct ofconn *ofconn,
3539                              const struct ofp_header *oh)
3540 {
3541     const struct nx_flow_mod_table_id *msg = ofpmsg_body(oh);
3542     enum ofputil_protocol cur, next;
3543
3544     cur = ofconn_get_protocol(ofconn);
3545     next = ofputil_protocol_set_tid(cur, msg->set != 0);
3546     ofconn_set_protocol(ofconn, next);
3547
3548     return 0;
3549 }
3550
3551 static enum ofperr
3552 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
3553 {
3554     const struct nx_set_flow_format *msg = ofpmsg_body(oh);
3555     enum ofputil_protocol cur, next;
3556     enum ofputil_protocol next_base;
3557
3558     next_base = ofputil_nx_flow_format_to_protocol(ntohl(msg->format));
3559     if (!next_base) {
3560         return OFPERR_OFPBRC_EPERM;
3561     }
3562
3563     cur = ofconn_get_protocol(ofconn);
3564     next = ofputil_protocol_set_base(cur, next_base);
3565     if (cur != next && ofconn_has_pending_opgroups(ofconn)) {
3566         /* Avoid sending async messages in surprising protocol. */
3567         return OFPROTO_POSTPONE;
3568     }
3569
3570     ofconn_set_protocol(ofconn, next);
3571     return 0;
3572 }
3573
3574 static enum ofperr
3575 handle_nxt_set_packet_in_format(struct ofconn *ofconn,
3576                                 const struct ofp_header *oh)
3577 {
3578     const struct nx_set_packet_in_format *msg = ofpmsg_body(oh);
3579     uint32_t format;
3580
3581     format = ntohl(msg->format);
3582     if (format != NXPIF_OPENFLOW10 && format != NXPIF_NXM) {
3583         return OFPERR_OFPBRC_EPERM;
3584     }
3585
3586     if (format != ofconn_get_packet_in_format(ofconn)
3587         && ofconn_has_pending_opgroups(ofconn)) {
3588         /* Avoid sending async message in surprsing packet in format. */
3589         return OFPROTO_POSTPONE;
3590     }
3591
3592     ofconn_set_packet_in_format(ofconn, format);
3593     return 0;
3594 }
3595
3596 static enum ofperr
3597 handle_nxt_set_async_config(struct ofconn *ofconn, const struct ofp_header *oh)
3598 {
3599     const struct nx_async_config *msg = ofpmsg_body(oh);
3600     uint32_t master[OAM_N_TYPES];
3601     uint32_t slave[OAM_N_TYPES];
3602
3603     master[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[0]);
3604     master[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[0]);
3605     master[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[0]);
3606
3607     slave[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[1]);
3608     slave[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[1]);
3609     slave[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[1]);
3610
3611     ofconn_set_async_config(ofconn, master, slave);
3612     if (ofconn_get_type(ofconn) == OFCONN_SERVICE &&
3613         !ofconn_get_miss_send_len(ofconn)) {
3614         ofconn_set_miss_send_len(ofconn, OFP_DEFAULT_MISS_SEND_LEN);
3615     }
3616
3617     return 0;
3618 }
3619
3620 static enum ofperr
3621 handle_nxt_set_controller_id(struct ofconn *ofconn,
3622                              const struct ofp_header *oh)
3623 {
3624     const struct nx_controller_id *nci = ofpmsg_body(oh);
3625
3626     if (!is_all_zeros(nci->zero, sizeof nci->zero)) {
3627         return OFPERR_NXBRC_MUST_BE_ZERO;
3628     }
3629
3630     ofconn_set_controller_id(ofconn, ntohs(nci->controller_id));
3631     return 0;
3632 }
3633
3634 static enum ofperr
3635 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
3636 {
3637     struct ofpbuf *buf;
3638
3639     if (ofconn_has_pending_opgroups(ofconn)) {
3640         return OFPROTO_POSTPONE;
3641     }
3642
3643     buf = ofpraw_alloc_reply((oh->version == OFP10_VERSION
3644                               ? OFPRAW_OFPT10_BARRIER_REPLY
3645                               : OFPRAW_OFPT11_BARRIER_REPLY), oh, 0);
3646     ofconn_send_reply(ofconn, buf);
3647     return 0;
3648 }
3649
3650 static void
3651 ofproto_compose_flow_refresh_update(const struct rule *rule,
3652                                     enum nx_flow_monitor_flags flags,
3653                                     struct list *msgs)
3654 {
3655     struct ofoperation *op = rule->pending;
3656     struct ofputil_flow_update fu;
3657     struct match match;
3658
3659     if (op && op->type == OFOPERATION_ADD && !op->victim) {
3660         /* We'll report the final flow when the operation completes.  Reporting
3661          * it now would cause a duplicate report later. */
3662         return;
3663     }
3664
3665     fu.event = (flags & (NXFMF_INITIAL | NXFMF_ADD)
3666                 ? NXFME_ADDED : NXFME_MODIFIED);
3667     fu.reason = 0;
3668     fu.idle_timeout = rule->idle_timeout;
3669     fu.hard_timeout = rule->hard_timeout;
3670     fu.table_id = rule->table_id;
3671     fu.cookie = rule->flow_cookie;
3672     minimatch_expand(&rule->cr.match, &match);
3673     fu.match = &match;
3674     fu.priority = rule->cr.priority;
3675     if (!(flags & NXFMF_ACTIONS)) {
3676         fu.ofpacts = NULL;
3677         fu.ofpacts_len = 0;
3678     } else if (!op) {
3679         fu.ofpacts = rule->ofpacts;
3680         fu.ofpacts_len = rule->ofpacts_len;
3681     } else {
3682         /* An operation is in progress.  Use the previous version of the flow's
3683          * actions, so that when the operation commits we report the change. */
3684         switch (op->type) {
3685         case OFOPERATION_ADD:
3686             /* We already verified that there was a victim. */
3687             fu.ofpacts = op->victim->ofpacts;
3688             fu.ofpacts_len = op->victim->ofpacts_len;
3689             break;
3690
3691         case OFOPERATION_MODIFY:
3692             if (op->ofpacts) {
3693                 fu.ofpacts = op->ofpacts;
3694                 fu.ofpacts_len = op->ofpacts_len;
3695             } else {
3696                 fu.ofpacts = rule->ofpacts;
3697                 fu.ofpacts_len = rule->ofpacts_len;
3698             }
3699             break;
3700
3701         case OFOPERATION_DELETE:
3702             fu.ofpacts = rule->ofpacts;
3703             fu.ofpacts_len = rule->ofpacts_len;
3704             break;
3705
3706         default:
3707             NOT_REACHED();
3708         }
3709     }
3710
3711     if (list_is_empty(msgs)) {
3712         ofputil_start_flow_update(msgs);
3713     }
3714     ofputil_append_flow_update(&fu, msgs);
3715 }
3716
3717 void
3718 ofmonitor_compose_refresh_updates(struct list *rules, struct list *msgs)
3719 {
3720     struct rule *rule;
3721
3722     LIST_FOR_EACH (rule, ofproto_node, rules) {
3723         enum nx_flow_monitor_flags flags = rule->monitor_flags;
3724         rule->monitor_flags = 0;
3725
3726         ofproto_compose_flow_refresh_update(rule, flags, msgs);
3727     }
3728 }
3729
3730 static void
3731 ofproto_collect_ofmonitor_refresh_rule(const struct ofmonitor *m,
3732                                        struct rule *rule, uint64_t seqno,
3733                                        struct list *rules)
3734 {
3735     enum nx_flow_monitor_flags update;
3736
3737     if (ofproto_rule_is_hidden(rule)) {
3738         return;
3739     }
3740
3741     if (!(rule->pending
3742           ? ofoperation_has_out_port(rule->pending, m->out_port)
3743           : ofproto_rule_has_out_port(rule, m->out_port))) {
3744         return;
3745     }
3746
3747     if (seqno) {
3748         if (rule->add_seqno > seqno) {
3749             update = NXFMF_ADD | NXFMF_MODIFY;
3750         } else if (rule->modify_seqno > seqno) {
3751             update = NXFMF_MODIFY;
3752         } else {
3753             return;
3754         }
3755
3756         if (!(m->flags & update)) {
3757             return;
3758         }
3759     } else {
3760         update = NXFMF_INITIAL;
3761     }
3762
3763     if (!rule->monitor_flags) {
3764         list_push_back(rules, &rule->ofproto_node);
3765     }
3766     rule->monitor_flags |= update | (m->flags & NXFMF_ACTIONS);
3767 }
3768
3769 static void
3770 ofproto_collect_ofmonitor_refresh_rules(const struct ofmonitor *m,
3771                                         uint64_t seqno,
3772                                         struct list *rules)
3773 {
3774     const struct ofproto *ofproto = ofconn_get_ofproto(m->ofconn);
3775     const struct ofoperation *op;
3776     const struct oftable *table;
3777     struct cls_rule target;
3778
3779     cls_rule_init_from_minimatch(&target, &m->match, 0);
3780     FOR_EACH_MATCHING_TABLE (table, m->table_id, ofproto) {
3781         struct cls_cursor cursor;
3782         struct rule *rule;
3783
3784         cls_cursor_init(&cursor, &table->cls, &target);
3785         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3786             assert(!rule->pending); /* XXX */
3787             ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
3788         }
3789     }
3790
3791     HMAP_FOR_EACH (op, hmap_node, &ofproto->deletions) {
3792         struct rule *rule = op->rule;
3793
3794         if (((m->table_id == 0xff
3795               ? !(ofproto->tables[rule->table_id].flags & OFTABLE_HIDDEN)
3796               : m->table_id == rule->table_id))
3797             && cls_rule_is_loose_match(&rule->cr, &target.match)) {
3798             ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
3799         }
3800     }
3801     cls_rule_destroy(&target);
3802 }
3803
3804 static void
3805 ofproto_collect_ofmonitor_initial_rules(struct ofmonitor *m,
3806                                         struct list *rules)
3807 {
3808     if (m->flags & NXFMF_INITIAL) {
3809         ofproto_collect_ofmonitor_refresh_rules(m, 0, rules);
3810     }
3811 }
3812
3813 void
3814 ofmonitor_collect_resume_rules(struct ofmonitor *m,
3815                                uint64_t seqno, struct list *rules)
3816 {
3817     ofproto_collect_ofmonitor_refresh_rules(m, seqno, rules);
3818 }
3819
3820 static enum ofperr
3821 handle_flow_monitor_request(struct ofconn *ofconn, const struct ofp_header *oh)
3822 {
3823     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3824     struct ofmonitor **monitors;
3825     size_t n_monitors, allocated_monitors;
3826     struct list replies;
3827     enum ofperr error;
3828     struct list rules;
3829     struct ofpbuf b;
3830     size_t i;
3831
3832     error = 0;
3833     ofpbuf_use_const(&b, oh, ntohs(oh->length));
3834     monitors = NULL;
3835     n_monitors = allocated_monitors = 0;
3836     for (;;) {
3837         struct ofputil_flow_monitor_request request;
3838         struct ofmonitor *m;
3839         int retval;
3840
3841         retval = ofputil_decode_flow_monitor_request(&request, &b);
3842         if (retval == EOF) {
3843             break;
3844         } else if (retval) {
3845             error = retval;
3846             goto error;
3847         }
3848
3849         if (request.table_id != 0xff
3850             && request.table_id >= ofproto->n_tables) {
3851             error = OFPERR_OFPBRC_BAD_TABLE_ID;
3852             goto error;
3853         }
3854
3855         error = ofmonitor_create(&request, ofconn, &m);
3856         if (error) {
3857             goto error;
3858         }
3859
3860         if (n_monitors >= allocated_monitors) {
3861             monitors = x2nrealloc(monitors, &allocated_monitors,
3862                                   sizeof *monitors);
3863         }
3864         monitors[n_monitors++] = m;
3865     }
3866
3867     list_init(&rules);
3868     for (i = 0; i < n_monitors; i++) {
3869         ofproto_collect_ofmonitor_initial_rules(monitors[i], &rules);
3870     }
3871
3872     ofpmp_init(&replies, oh);
3873     ofmonitor_compose_refresh_updates(&rules, &replies);
3874     ofconn_send_replies(ofconn, &replies);
3875
3876     free(monitors);
3877
3878     return 0;
3879
3880 error:
3881     for (i = 0; i < n_monitors; i++) {
3882         ofmonitor_destroy(monitors[i]);
3883     }
3884     free(monitors);
3885     return error;
3886 }
3887
3888 static enum ofperr
3889 handle_flow_monitor_cancel(struct ofconn *ofconn, const struct ofp_header *oh)
3890 {
3891     struct ofmonitor *m;
3892     uint32_t id;
3893
3894     id = ofputil_decode_flow_monitor_cancel(oh);
3895     m = ofmonitor_lookup(ofconn, id);
3896     if (!m) {
3897         return OFPERR_NXBRC_FM_BAD_ID;
3898     }
3899
3900     ofmonitor_destroy(m);
3901     return 0;
3902 }
3903
3904 static enum ofperr
3905 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
3906 {
3907     const struct ofp_header *oh = msg->data;
3908     enum ofptype type;
3909     enum ofperr error;
3910
3911     error = ofptype_decode(&type, oh);
3912     if (error) {
3913         return error;
3914     }
3915
3916     switch (type) {
3917         /* OpenFlow requests. */
3918     case OFPTYPE_ECHO_REQUEST:
3919         return handle_echo_request(ofconn, oh);
3920
3921     case OFPTYPE_FEATURES_REQUEST:
3922         return handle_features_request(ofconn, oh);
3923
3924     case OFPTYPE_GET_CONFIG_REQUEST:
3925         return handle_get_config_request(ofconn, oh);
3926
3927     case OFPTYPE_SET_CONFIG:
3928         return handle_set_config(ofconn, oh);
3929
3930     case OFPTYPE_PACKET_OUT:
3931         return handle_packet_out(ofconn, oh);
3932
3933     case OFPTYPE_PORT_MOD:
3934         return handle_port_mod(ofconn, oh);
3935
3936     case OFPTYPE_FLOW_MOD:
3937         return handle_flow_mod(ofconn, oh);
3938
3939     case OFPTYPE_BARRIER_REQUEST:
3940         return handle_barrier_request(ofconn, oh);
3941
3942         /* OpenFlow replies. */
3943     case OFPTYPE_ECHO_REPLY:
3944         return 0;
3945
3946         /* Nicira extension requests. */
3947     case OFPTYPE_ROLE_REQUEST:
3948         return handle_role_request(ofconn, oh);
3949
3950     case OFPTYPE_FLOW_MOD_TABLE_ID:
3951         return handle_nxt_flow_mod_table_id(ofconn, oh);
3952
3953     case OFPTYPE_SET_FLOW_FORMAT:
3954         return handle_nxt_set_flow_format(ofconn, oh);
3955
3956     case OFPTYPE_SET_PACKET_IN_FORMAT:
3957         return handle_nxt_set_packet_in_format(ofconn, oh);
3958
3959     case OFPTYPE_SET_CONTROLLER_ID:
3960         return handle_nxt_set_controller_id(ofconn, oh);
3961
3962     case OFPTYPE_FLOW_AGE:
3963         /* Nothing to do. */
3964         return 0;
3965
3966     case OFPTYPE_FLOW_MONITOR_CANCEL:
3967         return handle_flow_monitor_cancel(ofconn, oh);
3968
3969     case OFPTYPE_SET_ASYNC_CONFIG:
3970         return handle_nxt_set_async_config(ofconn, oh);
3971
3972         /* Statistics requests. */
3973     case OFPTYPE_DESC_STATS_REQUEST:
3974         return handle_desc_stats_request(ofconn, oh);
3975
3976     case OFPTYPE_FLOW_STATS_REQUEST:
3977         return handle_flow_stats_request(ofconn, oh);
3978
3979     case OFPTYPE_AGGREGATE_STATS_REQUEST:
3980         return handle_aggregate_stats_request(ofconn, oh);
3981
3982     case OFPTYPE_TABLE_STATS_REQUEST:
3983         return handle_table_stats_request(ofconn, oh);
3984
3985     case OFPTYPE_PORT_STATS_REQUEST:
3986         return handle_port_stats_request(ofconn, oh);
3987
3988     case OFPTYPE_QUEUE_STATS_REQUEST:
3989         return handle_queue_stats_request(ofconn, oh);
3990
3991     case OFPTYPE_PORT_DESC_STATS_REQUEST:
3992         return handle_port_desc_stats_request(ofconn, oh);
3993
3994     case OFPTYPE_FLOW_MONITOR_STATS_REQUEST:
3995         return handle_flow_monitor_request(ofconn, oh);
3996
3997     case OFPTYPE_HELLO:
3998     case OFPTYPE_ERROR:
3999     case OFPTYPE_FEATURES_REPLY:
4000     case OFPTYPE_GET_CONFIG_REPLY:
4001     case OFPTYPE_PACKET_IN:
4002     case OFPTYPE_FLOW_REMOVED:
4003     case OFPTYPE_PORT_STATUS:
4004     case OFPTYPE_BARRIER_REPLY:
4005     case OFPTYPE_DESC_STATS_REPLY:
4006     case OFPTYPE_FLOW_STATS_REPLY:
4007     case OFPTYPE_QUEUE_STATS_REPLY:
4008     case OFPTYPE_PORT_STATS_REPLY:
4009     case OFPTYPE_TABLE_STATS_REPLY:
4010     case OFPTYPE_AGGREGATE_STATS_REPLY:
4011     case OFPTYPE_PORT_DESC_STATS_REPLY:
4012     case OFPTYPE_ROLE_REPLY:
4013     case OFPTYPE_FLOW_MONITOR_PAUSED:
4014     case OFPTYPE_FLOW_MONITOR_RESUMED:
4015     case OFPTYPE_FLOW_MONITOR_STATS_REPLY:
4016     default:
4017         return OFPERR_OFPBRC_BAD_TYPE;
4018     }
4019 }
4020
4021 static bool
4022 handle_openflow(struct ofconn *ofconn, struct ofpbuf *ofp_msg)
4023 {
4024     int error = handle_openflow__(ofconn, ofp_msg);
4025     if (error && error != OFPROTO_POSTPONE) {
4026         ofconn_send_error(ofconn, ofp_msg->data, error);
4027     }
4028     COVERAGE_INC(ofproto_recv_openflow);
4029     return error != OFPROTO_POSTPONE;
4030 }
4031 \f
4032 /* Asynchronous operations. */
4033
4034 /* Creates and returns a new ofopgroup that is not associated with any
4035  * OpenFlow connection.
4036  *
4037  * The caller should add operations to the returned group with
4038  * ofoperation_create() and then submit it with ofopgroup_submit(). */
4039 static struct ofopgroup *
4040 ofopgroup_create_unattached(struct ofproto *ofproto)
4041 {
4042     struct ofopgroup *group = xzalloc(sizeof *group);
4043     group->ofproto = ofproto;
4044     list_init(&group->ofproto_node);
4045     list_init(&group->ops);
4046     list_init(&group->ofconn_node);
4047     return group;
4048 }
4049
4050 /* Creates and returns a new ofopgroup for 'ofproto'.
4051  *
4052  * If 'ofconn' is NULL, the new ofopgroup is not associated with any OpenFlow
4053  * connection.  The 'request' and 'buffer_id' arguments are ignored.
4054  *
4055  * If 'ofconn' is nonnull, then the new ofopgroup is associated with 'ofconn'.
4056  * If the ofopgroup eventually fails, then the error reply will include
4057  * 'request'.  If the ofopgroup eventually succeeds, then the packet with
4058  * buffer id 'buffer_id' on 'ofconn' will be sent by 'ofconn''s ofproto.
4059  *
4060  * The caller should add operations to the returned group with
4061  * ofoperation_create() and then submit it with ofopgroup_submit(). */
4062 static struct ofopgroup *
4063 ofopgroup_create(struct ofproto *ofproto, struct ofconn *ofconn,
4064                  const struct ofp_header *request, uint32_t buffer_id)
4065 {
4066     struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
4067     if (ofconn) {
4068         size_t request_len = ntohs(request->length);
4069
4070         assert(ofconn_get_ofproto(ofconn) == ofproto);
4071
4072         ofconn_add_opgroup(ofconn, &group->ofconn_node);
4073         group->ofconn = ofconn;
4074         group->request = xmemdup(request, MIN(request_len, 64));
4075         group->buffer_id = buffer_id;
4076     }
4077     return group;
4078 }
4079
4080 /* Submits 'group' for processing.
4081  *
4082  * If 'group' contains no operations (e.g. none were ever added, or all of the
4083  * ones that were added completed synchronously), then it is destroyed
4084  * immediately.  Otherwise it is added to the ofproto's list of pending
4085  * groups. */
4086 static void
4087 ofopgroup_submit(struct ofopgroup *group)
4088 {
4089     if (!group->n_running) {
4090         ofopgroup_complete(group);
4091     } else {
4092         list_push_back(&group->ofproto->pending, &group->ofproto_node);
4093         group->ofproto->n_pending++;
4094     }
4095 }
4096
4097 static void
4098 ofopgroup_complete(struct ofopgroup *group)
4099 {
4100     struct ofproto *ofproto = group->ofproto;
4101
4102     struct ofconn *abbrev_ofconn;
4103     ovs_be32 abbrev_xid;
4104
4105     struct ofoperation *op, *next_op;
4106     int error;
4107
4108     assert(!group->n_running);
4109
4110     error = 0;
4111     LIST_FOR_EACH (op, group_node, &group->ops) {
4112         if (op->error) {
4113             error = op->error;
4114             break;
4115         }
4116     }
4117
4118     if (!error && group->ofconn && group->buffer_id != UINT32_MAX) {
4119         LIST_FOR_EACH (op, group_node, &group->ops) {
4120             if (op->type != OFOPERATION_DELETE) {
4121                 struct ofpbuf *packet;
4122                 uint16_t in_port;
4123
4124                 error = ofconn_pktbuf_retrieve(group->ofconn, group->buffer_id,
4125                                                &packet, &in_port);
4126                 if (packet) {
4127                     assert(!error);
4128                     error = rule_execute(op->rule, in_port, packet);
4129                 }
4130                 break;
4131             }
4132         }
4133     }
4134
4135     if (!error && !list_is_empty(&group->ofconn_node)) {
4136         abbrev_ofconn = group->ofconn;
4137         abbrev_xid = group->request->xid;
4138     } else {
4139         abbrev_ofconn = NULL;
4140         abbrev_xid = htonl(0);
4141     }
4142     LIST_FOR_EACH_SAFE (op, next_op, group_node, &group->ops) {
4143         struct rule *rule = op->rule;
4144
4145         if (!op->error && !ofproto_rule_is_hidden(rule)) {
4146             /* Check that we can just cast from ofoperation_type to
4147              * nx_flow_update_event. */
4148             BUILD_ASSERT_DECL((enum nx_flow_update_event) OFOPERATION_ADD
4149                               == NXFME_ADDED);
4150             BUILD_ASSERT_DECL((enum nx_flow_update_event) OFOPERATION_DELETE
4151                               == NXFME_DELETED);
4152             BUILD_ASSERT_DECL((enum nx_flow_update_event) OFOPERATION_MODIFY
4153                               == NXFME_MODIFIED);
4154
4155             ofmonitor_report(ofproto->connmgr, rule,
4156                              (enum nx_flow_update_event) op->type,
4157                              op->reason, abbrev_ofconn, abbrev_xid);
4158         }
4159
4160         rule->pending = NULL;
4161
4162         switch (op->type) {
4163         case OFOPERATION_ADD:
4164             if (!op->error) {
4165                 uint16_t vid_mask;
4166
4167                 ofproto_rule_destroy__(op->victim);
4168                 vid_mask = minimask_get_vid_mask(&rule->cr.match.mask);
4169                 if (vid_mask == VLAN_VID_MASK) {
4170                     if (ofproto->vlan_bitmap) {
4171                         uint16_t vid = miniflow_get_vid(&rule->cr.match.flow);
4172                         if (!bitmap_is_set(ofproto->vlan_bitmap, vid)) {
4173                             bitmap_set1(ofproto->vlan_bitmap, vid);
4174                             ofproto->vlans_changed = true;
4175                         }
4176                     } else {
4177                         ofproto->vlans_changed = true;
4178                     }
4179                 }
4180             } else {
4181                 oftable_substitute_rule(rule, op->victim);
4182                 ofproto_rule_destroy__(rule);
4183             }
4184             break;
4185
4186         case OFOPERATION_DELETE:
4187             assert(!op->error);
4188             ofproto_rule_destroy__(rule);
4189             op->rule = NULL;
4190             break;
4191
4192         case OFOPERATION_MODIFY:
4193             if (!op->error) {
4194                 rule->modified = time_msec();
4195             } else {
4196                 rule->flow_cookie = op->flow_cookie;
4197                 if (op->ofpacts) {
4198                     free(rule->ofpacts);
4199                     rule->ofpacts = op->ofpacts;
4200                     rule->ofpacts_len = op->ofpacts_len;
4201                     op->ofpacts = NULL;
4202                     op->ofpacts_len = 0;
4203                 }
4204             }
4205             break;
4206
4207         default:
4208             NOT_REACHED();
4209         }
4210
4211         ofoperation_destroy(op);
4212     }
4213
4214     ofmonitor_flush(ofproto->connmgr);
4215
4216     if (!list_is_empty(&group->ofproto_node)) {
4217         assert(ofproto->n_pending > 0);
4218         ofproto->n_pending--;
4219         list_remove(&group->ofproto_node);
4220     }
4221     if (!list_is_empty(&group->ofconn_node)) {
4222         list_remove(&group->ofconn_node);
4223         if (error) {
4224             ofconn_send_error(group->ofconn, group->request, error);
4225         }
4226         connmgr_retry(ofproto->connmgr);
4227     }
4228     free(group->request);
4229     free(group);
4230 }
4231
4232 /* Initiates a new operation on 'rule', of the specified 'type', within
4233  * 'group'.  Prior to calling, 'rule' must not have any pending operation.
4234  *
4235  * For a 'type' of OFOPERATION_DELETE, 'reason' should specify the reason that
4236  * the flow is being deleted.  For other 'type's, 'reason' is ignored (use 0).
4237  *
4238  * Returns the newly created ofoperation (which is also available as
4239  * rule->pending). */
4240 static struct ofoperation *
4241 ofoperation_create(struct ofopgroup *group, struct rule *rule,
4242                    enum ofoperation_type type,
4243                    enum ofp_flow_removed_reason reason)
4244 {
4245     struct ofproto *ofproto = group->ofproto;
4246     struct ofoperation *op;
4247
4248     assert(!rule->pending);
4249
4250     op = rule->pending = xzalloc(sizeof *op);
4251     op->group = group;
4252     list_push_back(&group->ops, &op->group_node);
4253     op->rule = rule;
4254     op->type = type;
4255     op->reason = reason;
4256     op->flow_cookie = rule->flow_cookie;
4257
4258     group->n_running++;
4259
4260     if (type == OFOPERATION_DELETE) {
4261         hmap_insert(&ofproto->deletions, &op->hmap_node,
4262                     cls_rule_hash(&rule->cr, rule->table_id));
4263     }
4264
4265     return op;
4266 }
4267
4268 static void
4269 ofoperation_destroy(struct ofoperation *op)
4270 {
4271     struct ofopgroup *group = op->group;
4272
4273     if (op->rule) {
4274         op->rule->pending = NULL;
4275     }
4276     if (op->type == OFOPERATION_DELETE) {
4277         hmap_remove(&group->ofproto->deletions, &op->hmap_node);
4278     }
4279     list_remove(&op->group_node);
4280     free(op->ofpacts);
4281     free(op);
4282 }
4283
4284 /* Indicates that 'op' completed with status 'error', which is either 0 to
4285  * indicate success or an OpenFlow error code on failure.
4286  *
4287  * If 'error' is 0, indicating success, the operation will be committed
4288  * permanently to the flow table.  There is one interesting subcase:
4289  *
4290  *   - If 'op' is an "add flow" operation that is replacing an existing rule in
4291  *     the flow table (the "victim" rule) by a new one, then the caller must
4292  *     have uninitialized any derived state in the victim rule, as in step 5 in
4293  *     the "Life Cycle" in ofproto/ofproto-provider.h.  ofoperation_complete()
4294  *     performs steps 6 and 7 for the victim rule, most notably by calling its
4295  *     ->rule_dealloc() function.
4296  *
4297  * If 'error' is nonzero, then generally the operation will be rolled back:
4298  *
4299  *   - If 'op' is an "add flow" operation, ofproto removes the new rule or
4300  *     restores the original rule.  The caller must have uninitialized any
4301  *     derived state in the new rule, as in step 5 of in the "Life Cycle" in
4302  *     ofproto/ofproto-provider.h.  ofoperation_complete() performs steps 6 and
4303  *     and 7 for the new rule, calling its ->rule_dealloc() function.
4304  *
4305  *   - If 'op' is a "modify flow" operation, ofproto restores the original
4306  *     actions.
4307  *
4308  *   - 'op' must not be a "delete flow" operation.  Removing a rule is not
4309  *     allowed to fail.  It must always succeed.
4310  *
4311  * Please see the large comment in ofproto/ofproto-provider.h titled
4312  * "Asynchronous Operation Support" for more information. */
4313 void
4314 ofoperation_complete(struct ofoperation *op, enum ofperr error)
4315 {
4316     struct ofopgroup *group = op->group;
4317
4318     assert(op->rule->pending == op);
4319     assert(group->n_running > 0);
4320     assert(!error || op->type != OFOPERATION_DELETE);
4321
4322     op->error = error;
4323     if (!--group->n_running && !list_is_empty(&group->ofproto_node)) {
4324         ofopgroup_complete(group);
4325     }
4326 }
4327
4328 struct rule *
4329 ofoperation_get_victim(struct ofoperation *op)
4330 {
4331     assert(op->type == OFOPERATION_ADD);
4332     return op->victim;
4333 }
4334 \f
4335 static uint64_t
4336 pick_datapath_id(const struct ofproto *ofproto)
4337 {
4338     const struct ofport *port;
4339
4340     port = ofproto_get_port(ofproto, OFPP_LOCAL);
4341     if (port) {
4342         uint8_t ea[ETH_ADDR_LEN];
4343         int error;
4344
4345         error = netdev_get_etheraddr(port->netdev, ea);
4346         if (!error) {
4347             return eth_addr_to_uint64(ea);
4348         }
4349         VLOG_WARN("%s: could not get MAC address for %s (%s)",
4350                   ofproto->name, netdev_get_name(port->netdev),
4351                   strerror(error));
4352     }
4353     return ofproto->fallback_dpid;
4354 }
4355
4356 static uint64_t
4357 pick_fallback_dpid(void)
4358 {
4359     uint8_t ea[ETH_ADDR_LEN];
4360     eth_addr_nicira_random(ea);
4361     return eth_addr_to_uint64(ea);
4362 }
4363 \f
4364 /* Table overflow policy. */
4365
4366 /* Chooses and returns a rule to evict from 'table'.  Returns NULL if the table
4367  * is not configured to evict rules or if the table contains no evictable
4368  * rules.  (Rules with 'evictable' set to false or with no timeouts are not
4369  * evictable.) */
4370 static struct rule *
4371 choose_rule_to_evict(struct oftable *table)
4372 {
4373     struct eviction_group *evg;
4374
4375     if (!table->eviction_fields) {
4376         return NULL;
4377     }
4378
4379     /* In the common case, the outer and inner loops here will each be entered
4380      * exactly once:
4381      *
4382      *   - The inner loop normally "return"s in its first iteration.  If the
4383      *     eviction group has any evictable rules, then it always returns in
4384      *     some iteration.
4385      *
4386      *   - The outer loop only iterates more than once if the largest eviction
4387      *     group has no evictable rules.
4388      *
4389      *   - The outer loop can exit only if table's 'max_flows' is all filled up
4390      *     by unevictable rules'. */
4391     HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
4392         struct rule *rule;
4393
4394         HEAP_FOR_EACH (rule, evg_node, &evg->rules) {
4395             if (rule->evictable) {
4396                 return rule;
4397             }
4398         }
4399     }
4400
4401     return NULL;
4402 }
4403
4404 /* Searches 'ofproto' for tables that have more flows than their configured
4405  * maximum and that have flow eviction enabled, and evicts as many flows as
4406  * necessary and currently feasible from them.
4407  *
4408  * This triggers only when an OpenFlow table has N flows in it and then the
4409  * client configures a maximum number of flows less than N. */
4410 static void
4411 ofproto_evict(struct ofproto *ofproto)
4412 {
4413     struct ofopgroup *group;
4414     struct oftable *table;
4415
4416     group = ofopgroup_create_unattached(ofproto);
4417     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
4418         while (classifier_count(&table->cls) > table->max_flows
4419                && table->eviction_fields) {
4420             struct rule *rule;
4421
4422             rule = choose_rule_to_evict(table);
4423             if (!rule || rule->pending) {
4424                 break;
4425             }
4426
4427             ofoperation_create(group, rule,
4428                                OFOPERATION_DELETE, OFPRR_EVICTION);
4429             oftable_remove_rule(rule);
4430             ofproto->ofproto_class->rule_destruct(rule);
4431         }
4432     }
4433     ofopgroup_submit(group);
4434 }
4435 \f
4436 /* Eviction groups. */
4437
4438 /* Returns the priority to use for an eviction_group that contains 'n_rules'
4439  * rules.  The priority contains low-order random bits to ensure that eviction
4440  * groups with the same number of rules are prioritized randomly. */
4441 static uint32_t
4442 eviction_group_priority(size_t n_rules)
4443 {
4444     uint16_t size = MIN(UINT16_MAX, n_rules);
4445     return (size << 16) | random_uint16();
4446 }
4447
4448 /* Updates 'evg', an eviction_group within 'table', following a change that
4449  * adds or removes rules in 'evg'. */
4450 static void
4451 eviction_group_resized(struct oftable *table, struct eviction_group *evg)
4452 {
4453     heap_change(&table->eviction_groups_by_size, &evg->size_node,
4454                 eviction_group_priority(heap_count(&evg->rules)));
4455 }
4456
4457 /* Destroys 'evg', an eviction_group within 'table':
4458  *
4459  *   - Removes all the rules, if any, from 'evg'.  (It doesn't destroy the
4460  *     rules themselves, just removes them from the eviction group.)
4461  *
4462  *   - Removes 'evg' from 'table'.
4463  *
4464  *   - Frees 'evg'. */
4465 static void
4466 eviction_group_destroy(struct oftable *table, struct eviction_group *evg)
4467 {
4468     while (!heap_is_empty(&evg->rules)) {
4469         struct rule *rule;
4470
4471         rule = CONTAINER_OF(heap_pop(&evg->rules), struct rule, evg_node);
4472         rule->eviction_group = NULL;
4473     }
4474     hmap_remove(&table->eviction_groups_by_id, &evg->id_node);
4475     heap_remove(&table->eviction_groups_by_size, &evg->size_node);
4476     heap_destroy(&evg->rules);
4477     free(evg);
4478 }
4479
4480 /* Removes 'rule' from its eviction group, if any. */
4481 static void
4482 eviction_group_remove_rule(struct rule *rule)
4483 {
4484     if (rule->eviction_group) {
4485         struct oftable *table = &rule->ofproto->tables[rule->table_id];
4486         struct eviction_group *evg = rule->eviction_group;
4487
4488         rule->eviction_group = NULL;
4489         heap_remove(&evg->rules, &rule->evg_node);
4490         if (heap_is_empty(&evg->rules)) {
4491             eviction_group_destroy(table, evg);
4492         } else {
4493             eviction_group_resized(table, evg);
4494         }
4495     }
4496 }
4497
4498 /* Hashes the 'rule''s values for the eviction_fields of 'rule''s table, and
4499  * returns the hash value. */
4500 static uint32_t
4501 eviction_group_hash_rule(struct rule *rule)
4502 {
4503     struct oftable *table = &rule->ofproto->tables[rule->table_id];
4504     const struct mf_subfield *sf;
4505     struct flow flow;
4506     uint32_t hash;
4507
4508     hash = table->eviction_group_id_basis;
4509     miniflow_expand(&rule->cr.match.flow, &flow);
4510     for (sf = table->eviction_fields;
4511          sf < &table->eviction_fields[table->n_eviction_fields];
4512          sf++)
4513     {
4514         if (mf_are_prereqs_ok(sf->field, &flow)) {
4515             union mf_value value;
4516
4517             mf_get_value(sf->field, &flow, &value);
4518             if (sf->ofs) {
4519                 bitwise_zero(&value, sf->field->n_bytes, 0, sf->ofs);
4520             }
4521             if (sf->ofs + sf->n_bits < sf->field->n_bytes * 8) {
4522                 unsigned int start = sf->ofs + sf->n_bits;
4523                 bitwise_zero(&value, sf->field->n_bytes, start,
4524                              sf->field->n_bytes * 8 - start);
4525             }
4526             hash = hash_bytes(&value, sf->field->n_bytes, hash);
4527         } else {
4528             hash = hash_int(hash, 0);
4529         }
4530     }
4531
4532     return hash;
4533 }
4534
4535 /* Returns an eviction group within 'table' with the given 'id', creating one
4536  * if necessary. */
4537 static struct eviction_group *
4538 eviction_group_find(struct oftable *table, uint32_t id)
4539 {
4540     struct eviction_group *evg;
4541
4542     HMAP_FOR_EACH_WITH_HASH (evg, id_node, id, &table->eviction_groups_by_id) {
4543         return evg;
4544     }
4545
4546     evg = xmalloc(sizeof *evg);
4547     hmap_insert(&table->eviction_groups_by_id, &evg->id_node, id);
4548     heap_insert(&table->eviction_groups_by_size, &evg->size_node,
4549                 eviction_group_priority(0));
4550     heap_init(&evg->rules);
4551
4552     return evg;
4553 }
4554
4555 /* Returns an eviction priority for 'rule'.  The return value should be
4556  * interpreted so that higher priorities make a rule more attractive candidates
4557  * for eviction. */
4558 static uint32_t
4559 rule_eviction_priority(struct rule *rule)
4560 {
4561     long long int hard_expiration;
4562     long long int idle_expiration;
4563     long long int expiration;
4564     uint32_t expiration_offset;
4565
4566     /* Calculate time of expiration. */
4567     hard_expiration = (rule->hard_timeout
4568                        ? rule->modified + rule->hard_timeout * 1000
4569                        : LLONG_MAX);
4570     idle_expiration = (rule->idle_timeout
4571                        ? rule->used + rule->idle_timeout * 1000
4572                        : LLONG_MAX);
4573     expiration = MIN(hard_expiration, idle_expiration);
4574     if (expiration == LLONG_MAX) {
4575         return 0;
4576     }
4577
4578     /* Calculate the time of expiration as a number of (approximate) seconds
4579      * after program startup.
4580      *
4581      * This should work OK for program runs that last UINT32_MAX seconds or
4582      * less.  Therefore, please restart OVS at least once every 136 years. */
4583     expiration_offset = (expiration >> 10) - (time_boot_msec() >> 10);
4584
4585     /* Invert the expiration offset because we're using a max-heap. */
4586     return UINT32_MAX - expiration_offset;
4587 }
4588
4589 /* Adds 'rule' to an appropriate eviction group for its oftable's
4590  * configuration.  Does nothing if 'rule''s oftable doesn't have eviction
4591  * enabled, or if 'rule' is a permanent rule (one that will never expire on its
4592  * own).
4593  *
4594  * The caller must ensure that 'rule' is not already in an eviction group. */
4595 static void
4596 eviction_group_add_rule(struct rule *rule)
4597 {
4598     struct ofproto *ofproto = rule->ofproto;
4599     struct oftable *table = &ofproto->tables[rule->table_id];
4600
4601     if (table->eviction_fields
4602         && (rule->hard_timeout || rule->idle_timeout)) {
4603         struct eviction_group *evg;
4604
4605         evg = eviction_group_find(table, eviction_group_hash_rule(rule));
4606
4607         rule->eviction_group = evg;
4608         heap_insert(&evg->rules, &rule->evg_node,
4609                     rule_eviction_priority(rule));
4610         eviction_group_resized(table, evg);
4611     }
4612 }
4613 \f
4614 /* oftables. */
4615
4616 /* Initializes 'table'. */
4617 static void
4618 oftable_init(struct oftable *table)
4619 {
4620     memset(table, 0, sizeof *table);
4621     classifier_init(&table->cls);
4622     table->max_flows = UINT_MAX;
4623 }
4624
4625 /* Destroys 'table', including its classifier and eviction groups.
4626  *
4627  * The caller is responsible for freeing 'table' itself. */
4628 static void
4629 oftable_destroy(struct oftable *table)
4630 {
4631     assert(classifier_is_empty(&table->cls));
4632     oftable_disable_eviction(table);
4633     classifier_destroy(&table->cls);
4634     free(table->name);
4635 }
4636
4637 /* Changes the name of 'table' to 'name'.  If 'name' is NULL or the empty
4638  * string, then 'table' will use its default name.
4639  *
4640  * This only affects the name exposed for a table exposed through the OpenFlow
4641  * OFPST_TABLE (as printed by "ovs-ofctl dump-tables"). */
4642 static void
4643 oftable_set_name(struct oftable *table, const char *name)
4644 {
4645     if (name && name[0]) {
4646         int len = strnlen(name, OFP_MAX_TABLE_NAME_LEN);
4647         if (!table->name || strncmp(name, table->name, len)) {
4648             free(table->name);
4649             table->name = xmemdup0(name, len);
4650         }
4651     } else {
4652         free(table->name);
4653         table->name = NULL;
4654     }
4655 }
4656
4657 /* oftables support a choice of two policies when adding a rule would cause the
4658  * number of flows in the table to exceed the configured maximum number: either
4659  * they can refuse to add the new flow or they can evict some existing flow.
4660  * This function configures the former policy on 'table'. */
4661 static void
4662 oftable_disable_eviction(struct oftable *table)
4663 {
4664     if (table->eviction_fields) {
4665         struct eviction_group *evg, *next;
4666
4667         HMAP_FOR_EACH_SAFE (evg, next, id_node,
4668                             &table->eviction_groups_by_id) {
4669             eviction_group_destroy(table, evg);
4670         }
4671         hmap_destroy(&table->eviction_groups_by_id);
4672         heap_destroy(&table->eviction_groups_by_size);
4673
4674         free(table->eviction_fields);
4675         table->eviction_fields = NULL;
4676         table->n_eviction_fields = 0;
4677     }
4678 }
4679
4680 /* oftables support a choice of two policies when adding a rule would cause the
4681  * number of flows in the table to exceed the configured maximum number: either
4682  * they can refuse to add the new flow or they can evict some existing flow.
4683  * This function configures the latter policy on 'table', with fairness based
4684  * on the values of the 'n_fields' fields specified in 'fields'.  (Specifying
4685  * 'n_fields' as 0 disables fairness.) */
4686 static void
4687 oftable_enable_eviction(struct oftable *table,
4688                         const struct mf_subfield *fields, size_t n_fields)
4689 {
4690     struct cls_cursor cursor;
4691     struct rule *rule;
4692
4693     if (table->eviction_fields
4694         && n_fields == table->n_eviction_fields
4695         && (!n_fields
4696             || !memcmp(fields, table->eviction_fields,
4697                        n_fields * sizeof *fields))) {
4698         /* No change. */
4699         return;
4700     }
4701
4702     oftable_disable_eviction(table);
4703
4704     table->n_eviction_fields = n_fields;
4705     table->eviction_fields = xmemdup(fields, n_fields * sizeof *fields);
4706
4707     table->eviction_group_id_basis = random_uint32();
4708     hmap_init(&table->eviction_groups_by_id);
4709     heap_init(&table->eviction_groups_by_size);
4710
4711     cls_cursor_init(&cursor, &table->cls, NULL);
4712     CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4713         eviction_group_add_rule(rule);
4714     }
4715 }
4716
4717 /* Removes 'rule' from the oftable that contains it. */
4718 static void
4719 oftable_remove_rule(struct rule *rule)
4720 {
4721     struct ofproto *ofproto = rule->ofproto;
4722     struct oftable *table = &ofproto->tables[rule->table_id];
4723
4724     classifier_remove(&table->cls, &rule->cr);
4725     eviction_group_remove_rule(rule);
4726 }
4727
4728 /* Inserts 'rule' into its oftable.  Removes any existing rule from 'rule''s
4729  * oftable that has an identical cls_rule.  Returns the rule that was removed,
4730  * if any, and otherwise NULL. */
4731 static struct rule *
4732 oftable_replace_rule(struct rule *rule)
4733 {
4734     struct ofproto *ofproto = rule->ofproto;
4735     struct oftable *table = &ofproto->tables[rule->table_id];
4736     struct rule *victim;
4737
4738     victim = rule_from_cls_rule(classifier_replace(&table->cls, &rule->cr));
4739     if (victim) {
4740         eviction_group_remove_rule(victim);
4741     }
4742     eviction_group_add_rule(rule);
4743     return victim;
4744 }
4745
4746 /* Removes 'old' from its oftable then, if 'new' is nonnull, inserts 'new'. */
4747 static void
4748 oftable_substitute_rule(struct rule *old, struct rule *new)
4749 {
4750     if (new) {
4751         oftable_replace_rule(new);
4752     } else {
4753         oftable_remove_rule(old);
4754     }
4755 }
4756 \f
4757 /* unixctl commands. */
4758
4759 struct ofproto *
4760 ofproto_lookup(const char *name)
4761 {
4762     struct ofproto *ofproto;
4763
4764     HMAP_FOR_EACH_WITH_HASH (ofproto, hmap_node, hash_string(name, 0),
4765                              &all_ofprotos) {
4766         if (!strcmp(ofproto->name, name)) {
4767             return ofproto;
4768         }
4769     }
4770     return NULL;
4771 }
4772
4773 static void
4774 ofproto_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
4775                      const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
4776 {
4777     struct ofproto *ofproto;
4778     struct ds results;
4779
4780     ds_init(&results);
4781     HMAP_FOR_EACH (ofproto, hmap_node, &all_ofprotos) {
4782         ds_put_format(&results, "%s\n", ofproto->name);
4783     }
4784     unixctl_command_reply(conn, ds_cstr(&results));
4785     ds_destroy(&results);
4786 }
4787
4788 static void
4789 ofproto_unixctl_init(void)
4790 {
4791     static bool registered;
4792     if (registered) {
4793         return;
4794     }
4795     registered = true;
4796
4797     unixctl_command_register("ofproto/list", "", 0, 0,
4798                              ofproto_unixctl_list, NULL);
4799 }
4800 \f
4801 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
4802  *
4803  * This is deprecated.  It is only for compatibility with broken device drivers
4804  * in old versions of Linux that do not properly support VLANs when VLAN
4805  * devices are not used.  When broken device drivers are no longer in
4806  * widespread use, we will delete these interfaces. */
4807
4808 /* Sets a 1-bit in the 4096-bit 'vlan_bitmap' for each VLAN ID that is matched
4809  * (exactly) by an OpenFlow rule in 'ofproto'. */
4810 void
4811 ofproto_get_vlan_usage(struct ofproto *ofproto, unsigned long int *vlan_bitmap)
4812 {
4813     const struct oftable *oftable;
4814
4815     free(ofproto->vlan_bitmap);
4816     ofproto->vlan_bitmap = bitmap_allocate(4096);
4817     ofproto->vlans_changed = false;
4818
4819     OFPROTO_FOR_EACH_TABLE (oftable, ofproto) {
4820         const struct cls_table *table;
4821
4822         HMAP_FOR_EACH (table, hmap_node, &oftable->cls.tables) {
4823             if (minimask_get_vid_mask(&table->mask) == VLAN_VID_MASK) {
4824                 const struct cls_rule *rule;
4825
4826                 HMAP_FOR_EACH (rule, hmap_node, &table->rules) {
4827                     uint16_t vid = miniflow_get_vid(&rule->match.flow);
4828                     bitmap_set1(vlan_bitmap, vid);
4829                     bitmap_set1(ofproto->vlan_bitmap, vid);
4830                 }
4831             }
4832         }
4833     }
4834 }
4835
4836 /* Returns true if new VLANs have come into use by the flow table since the
4837  * last call to ofproto_get_vlan_usage().
4838  *
4839  * We don't track when old VLANs stop being used. */
4840 bool
4841 ofproto_has_vlan_usage_changed(const struct ofproto *ofproto)
4842 {
4843     return ofproto->vlans_changed;
4844 }
4845
4846 /* Configures a VLAN splinter binding between the ports identified by OpenFlow
4847  * port numbers 'vlandev_ofp_port' and 'realdev_ofp_port'.  If
4848  * 'realdev_ofp_port' is nonzero, then the VLAN device is enslaved to the real
4849  * device as a VLAN splinter for VLAN ID 'vid'.  If 'realdev_ofp_port' is zero,
4850  * then the VLAN device is un-enslaved. */
4851 int
4852 ofproto_port_set_realdev(struct ofproto *ofproto, uint16_t vlandev_ofp_port,
4853                          uint16_t realdev_ofp_port, int vid)
4854 {
4855     struct ofport *ofport;
4856     int error;
4857
4858     assert(vlandev_ofp_port != realdev_ofp_port);
4859
4860     ofport = ofproto_get_port(ofproto, vlandev_ofp_port);
4861     if (!ofport) {
4862         VLOG_WARN("%s: cannot set realdev on nonexistent port %"PRIu16,
4863                   ofproto->name, vlandev_ofp_port);
4864         return EINVAL;
4865     }
4866
4867     if (!ofproto->ofproto_class->set_realdev) {
4868         if (!vlandev_ofp_port) {
4869             return 0;
4870         }
4871         VLOG_WARN("%s: vlan splinters not supported", ofproto->name);
4872         return EOPNOTSUPP;
4873     }
4874
4875     error = ofproto->ofproto_class->set_realdev(ofport, realdev_ofp_port, vid);
4876     if (error) {
4877         VLOG_WARN("%s: setting realdev on port %"PRIu16" (%s) failed (%s)",
4878                   ofproto->name, vlandev_ofp_port,
4879                   netdev_get_name(ofport->netdev), strerror(error));
4880     }
4881     return error;
4882 }