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