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