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