8da282285f204db77ae08e701c237c775886caad
[cascardo/ovs.git] / ofproto / ofproto-provider.h
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #ifndef OFPROTO_OFPROTO_PROVIDER_H
18 #define OFPROTO_OFPROTO_PROVIDER_H 1
19
20 /* Definitions for use within ofproto.
21  *
22  *
23  * Thread-safety
24  * =============
25  *
26  * Lots of ofproto data structures are only accessed from a single thread.
27  * Those data structures are generally not thread-safe.
28  *
29  * The ofproto-dpif ofproto implementation accesses the flow table from
30  * multiple threads, including modifying the flow table from multiple threads
31  * via the "learn" action, so the flow table and various structures that index
32  * it have been made thread-safe.  Refer to comments on individual data
33  * structures for details.
34  */
35
36 #include "cfm.h"
37 #include "classifier.h"
38 #include "guarded-list.h"
39 #include "heap.h"
40 #include "hindex.h"
41 #include "list.h"
42 #include "ofp-actions.h"
43 #include "ofp-errors.h"
44 #include "ofp-util.h"
45 #include "ofproto/ofproto.h"
46 #include "ovs-atomic.h"
47 #include "ovs-rcu.h"
48 #include "ovs-thread.h"
49 #include "shash.h"
50 #include "simap.h"
51 #include "timeval.h"
52
53 struct match;
54 struct ofputil_flow_mod;
55 struct bfd_cfg;
56 struct meter;
57 struct ofoperation;
58
59 extern struct ovs_mutex ofproto_mutex;
60
61 /* An OpenFlow switch.
62  *
63  * With few exceptions, ofproto implementations may look at these fields but
64  * should not modify them. */
65 struct ofproto {
66     struct hmap_node hmap_node; /* In global 'all_ofprotos' hmap. */
67     const struct ofproto_class *ofproto_class;
68     char *type;                 /* Datapath type. */
69     char *name;                 /* Datapath name. */
70
71     /* Settings. */
72     uint64_t fallback_dpid;     /* Datapath ID if no better choice found. */
73     uint64_t datapath_id;       /* Datapath ID. */
74     bool forward_bpdu;          /* Option to allow forwarding of BPDU frames
75                                  * when NORMAL action is invoked. */
76     char *mfr_desc;             /* Manufacturer (NULL for default). */
77     char *hw_desc;              /* Hardware (NULL for default). */
78     char *sw_desc;              /* Software version (NULL for default). */
79     char *serial_desc;          /* Serial number (NULL for default). */
80     char *dp_desc;              /* Datapath description (NULL for default). */
81     enum ofp_config_flags frag_handling; /* One of OFPC_*.  */
82
83     /* Datapath. */
84     struct hmap ports;          /* Contains "struct ofport"s. */
85     struct shash port_by_name;
86     struct simap ofp_requests;  /* OpenFlow port number requests. */
87     uint16_t alloc_port_no;     /* Last allocated OpenFlow port number. */
88     uint16_t max_ports;         /* Max possible OpenFlow port num, plus one. */
89     struct hmap ofport_usage;   /* Map ofport to last used time. */
90     uint64_t change_seq;        /* Change sequence for netdev status. */
91
92     /* Flow tables. */
93     long long int eviction_group_timer; /* For rate limited reheapification. */
94     struct oftable *tables;
95     int n_tables;
96
97     /* Rules indexed on their cookie values, in all flow tables. */
98     struct hindex cookies OVS_GUARDED_BY(ofproto_mutex);
99
100     /* List of expirable flows, in all flow tables. */
101     struct list expirable OVS_GUARDED_BY(ofproto_mutex);
102
103     /* Meter table.
104      * OpenFlow meters start at 1.  To avoid confusion we leave the first
105      * pointer in the array un-used, and index directly with the OpenFlow
106      * meter_id. */
107     struct ofputil_meter_features meter_features;
108     struct meter **meters; /* 'meter_features.max_meter' + 1 pointers. */
109
110     /* OpenFlow connections. */
111     struct connmgr *connmgr;
112
113     /* Delayed rule executions.
114      *
115      * We delay calls to ->ofproto_class->rule_execute() past releasing
116      * ofproto_mutex during a flow_mod, because otherwise a "learn" action
117      * triggered by the executing the packet would try to recursively modify
118      * the flow table and reacquire the global lock. */
119     struct guarded_list rule_executes; /* Contains "struct rule_execute"s. */
120
121     /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
122      *
123      * This is deprecated.  It is only for compatibility with broken device
124      * drivers in old versions of Linux that do not properly support VLANs when
125      * VLAN devices are not used.  When broken device drivers are no longer in
126      * widespread use, we will delete these interfaces. */
127     unsigned long int *vlan_bitmap; /* 4096-bit bitmap of in-use VLANs. */
128     bool vlans_changed;             /* True if new VLANs are in use. */
129     int min_mtu;                    /* Current MTU of non-internal ports. */
130
131     /* Groups. */
132     struct ovs_rwlock groups_rwlock;
133     struct hmap groups OVS_GUARDED;   /* Contains "struct ofgroup"s. */
134     uint32_t n_groups[4] OVS_GUARDED; /* # of existing groups of each type. */
135     struct ofputil_group_features ogf;
136 };
137
138 void ofproto_init_tables(struct ofproto *, int n_tables);
139 void ofproto_init_max_ports(struct ofproto *, uint16_t max_ports);
140
141 struct ofproto *ofproto_lookup(const char *name);
142 struct ofport *ofproto_get_port(const struct ofproto *, ofp_port_t ofp_port);
143
144 /* An OpenFlow port within a "struct ofproto".
145  *
146  * The port's name is netdev_get_name(port->netdev).
147  *
148  * With few exceptions, ofproto implementations may look at these fields but
149  * should not modify them. */
150 struct ofport {
151     struct hmap_node hmap_node; /* In struct ofproto's "ports" hmap. */
152     struct ofproto *ofproto;    /* The ofproto that contains this port. */
153     struct netdev *netdev;
154     struct ofputil_phy_port pp;
155     ofp_port_t ofp_port;        /* OpenFlow port number. */
156     uint64_t change_seq;
157     long long int created;      /* Time created, in msec. */
158     int mtu;
159 };
160
161 void ofproto_port_set_state(struct ofport *, enum ofputil_port_state);
162
163 /* OpenFlow table flags:
164  *
165  *   - "Hidden" tables are not included in OpenFlow operations that operate on
166  *     "all tables".  For example, a request for flow stats on all tables will
167  *     omit flows in hidden tables, table stats requests will omit the table
168  *     entirely, and the switch features reply will not count the hidden table.
169  *
170  *     However, operations that specifically name the particular table still
171  *     operate on it.  For example, flow_mods and flow stats requests on a
172  *     hidden table work.
173  *
174  *     To avoid gaps in table IDs (which have unclear validity in OpenFlow),
175  *     hidden tables must be the highest-numbered tables that a provider
176  *     implements.
177  *
178  *   - "Read-only" tables can't be changed through OpenFlow operations.  (At
179  *     the moment all flow table operations go effectively through OpenFlow, so
180  *     this means that read-only tables can't be changed at all after the
181  *     read-only flag is set.)
182  *
183  * The generic ofproto layer never sets these flags.  An ofproto provider can
184  * set them if it is appropriate.
185  */
186 enum oftable_flags {
187     OFTABLE_HIDDEN = 1 << 0,   /* Hide from most OpenFlow operations. */
188     OFTABLE_READONLY = 1 << 1  /* Don't allow OpenFlow controller to change
189                                   this table. */
190 };
191
192 /* A flow table within a "struct ofproto".
193  *
194  *
195  * Thread-safety
196  * =============
197  *
198  * A cls->rwlock read-lock holder prevents rules from being added or deleted.
199  *
200  * Adding or removing rules requires holding ofproto_mutex AND the cls->rwlock
201  * write-lock.
202  *
203  * cls->rwlock should be held only briefly.  For extended access to a rule,
204  * increment its ref_count with ofproto_rule_ref().  A rule will not be freed
205  * until its ref_count reaches zero.
206  *
207  * Modifying a rule requires the rule's own mutex.  Holding cls->rwlock (for
208  * read or write) does not allow the holder to modify the rule.
209  *
210  * Freeing a rule requires ofproto_mutex and the cls->rwlock write-lock.  After
211  * removing the rule from the classifier, release a ref_count from the rule
212  * ('cls''s reference to the rule).
213  *
214  * Refer to the thread-safety notes on struct rule for more information.*/
215 struct oftable {
216     enum oftable_flags flags;
217     struct classifier cls;      /* Contains "struct rule"s. */
218     char *name;                 /* Table name exposed via OpenFlow, or NULL. */
219
220     /* Maximum number of flows or UINT_MAX if there is no limit besides any
221      * limit imposed by resource limitations. */
222     unsigned int max_flows;
223
224     /* These members determine the handling of an attempt to add a flow that
225      * would cause the table to have more than 'max_flows' flows.
226      *
227      * If 'eviction_fields' is NULL, overflows will be rejected with an error.
228      *
229      * If 'eviction_fields' is nonnull (regardless of whether n_eviction_fields
230      * is nonzero), an overflow will cause a flow to be removed.  The flow to
231      * be removed is chosen to give fairness among groups distinguished by
232      * different values for the subfields within 'groups'. */
233     struct mf_subfield *eviction_fields;
234     size_t n_eviction_fields;
235
236     /* Eviction groups.
237      *
238      * When a flow is added that would cause the table to have more than
239      * 'max_flows' flows, and 'eviction_fields' is nonnull, these groups are
240      * used to decide which rule to evict: the rule is chosen from the eviction
241      * group that contains the greatest number of rules.*/
242     uint32_t eviction_group_id_basis;
243     struct hmap eviction_groups_by_id;
244     struct heap eviction_groups_by_size;
245
246     /* Table config: contains enum ofproto_table_config; accessed atomically. */
247     atomic_uint config;
248
249     atomic_ulong n_matched;
250     atomic_ulong n_missed;
251 };
252
253 /* Assigns TABLE to each oftable, in turn, in OFPROTO.
254  *
255  * All parameters are evaluated multiple times. */
256 #define OFPROTO_FOR_EACH_TABLE(TABLE, OFPROTO)              \
257     for ((TABLE) = (OFPROTO)->tables;                       \
258          (TABLE) < &(OFPROTO)->tables[(OFPROTO)->n_tables]; \
259          (TABLE)++)
260
261 /* An OpenFlow flow within a "struct ofproto".
262  *
263  * With few exceptions, ofproto implementations may look at these fields but
264  * should not modify them.
265  *
266  *
267  * Thread-safety
268  * =============
269  *
270  * Except near the beginning or ending of its lifespan, rule 'rule' belongs to
271  * the classifier rule->ofproto->tables[rule->table_id].cls.  The text below
272  * calls this classifier 'cls'.
273  *
274  * Motivation
275  * ----------
276  *
277  * The thread safety rules described here for "struct rule" are motivated by
278  * two goals:
279  *
280  *    - Prevent threads that read members of "struct rule" from reading bad
281  *      data due to changes by some thread concurrently modifying those
282  *      members.
283  *
284  *    - Prevent two threads making changes to members of a given "struct rule"
285  *      from interfering with each other.
286  *
287  *
288  * Rules
289  * -----
290  *
291  * A rule 'rule' may be accessed without a risk of being freed by code that
292  * holds a read-lock or write-lock on 'cls->rwlock' or that owns a reference to
293  * 'rule->ref_count' (or both).  Code that needs to hold onto a rule for a
294  * while should take 'cls->rwlock', find the rule it needs, increment
295  * 'rule->ref_count' with ofproto_rule_ref(), and drop 'cls->rwlock'.
296  *
297  * 'rule->ref_count' protects 'rule' from being freed.  It doesn't protect the
298  * rule from being deleted from 'cls' (that's 'cls->rwlock') and it doesn't
299  * protect members of 'rule' from modification (that's 'rule->mutex').
300  *
301  * 'rule->mutex' protects the members of 'rule' from modification.  It doesn't
302  * protect the rule from being deleted from 'cls' (that's 'cls->rwlock') and it
303  * doesn't prevent the rule from being freed (that's 'rule->ref_count').
304  *
305  * Regarding thread safety, the members of a rule fall into the following
306  * categories:
307  *
308  *    - Immutable.  These members are marked 'const'.
309  *
310  *    - Members that may be safely read or written only by code holding
311  *      ofproto_mutex.  These are marked OVS_GUARDED_BY(ofproto_mutex).
312  *
313  *    - Members that may be safely read only by code holding ofproto_mutex or
314  *      'rule->mutex', and safely written only by coding holding ofproto_mutex
315  *      AND 'rule->mutex'.  These are marked OVS_GUARDED.
316  */
317 struct rule {
318     /* Where this rule resides in an OpenFlow switch.
319      *
320      * These are immutable once the rule is constructed, hence 'const'. */
321     struct ofproto *const ofproto; /* The ofproto that contains this rule. */
322     const struct cls_rule cr;      /* In owning ofproto's classifier. */
323     const uint8_t table_id;        /* Index in ofproto's 'tables' array. */
324
325     /* Protects members marked OVS_GUARDED.
326      * Readers only need to hold this mutex.
327      * Writers must hold both this mutex AND ofproto_mutex.
328      * By implication writers can read *without* taking this mutex while they
329      * hold ofproto_mutex. */
330     struct ovs_mutex mutex OVS_ACQ_AFTER(ofproto_mutex);
331
332     /* Number of references.
333      * The classifier owns one reference.
334      * Any thread trying to keep a rule from being freed should hold its own
335      * reference. */
336     struct ovs_refcount ref_count;
337
338     /* A "flow cookie" is the OpenFlow name for a 64-bit value associated with
339      * a flow.. */
340     ovs_be64 flow_cookie OVS_GUARDED;
341     struct hindex_node cookie_node OVS_GUARDED_BY(ofproto_mutex);
342
343     enum ofputil_flow_mod_flags flags OVS_GUARDED;
344
345     /* Timeouts. */
346     uint16_t hard_timeout OVS_GUARDED; /* In seconds from ->modified. */
347     uint16_t idle_timeout OVS_GUARDED; /* In seconds from ->used. */
348
349     /* Eviction groups (see comment on struct eviction_group for explanation) .
350      *
351      * 'eviction_group' is this rule's eviction group, or NULL if it is not in
352      * any eviction group.  When 'eviction_group' is nonnull, 'evg_node' is in
353      * the ->eviction_group->rules hmap. */
354     struct eviction_group *eviction_group OVS_GUARDED_BY(ofproto_mutex);
355     struct heap_node evg_node OVS_GUARDED_BY(ofproto_mutex);
356
357     /* OpenFlow actions.  See struct rule_actions for more thread-safety
358      * notes. */
359     OVSRCU_TYPE(const struct rule_actions *) actions;
360
361     /* In owning meter's 'rules' list.  An empty list if there is no meter. */
362     struct list meter_list_node OVS_GUARDED_BY(ofproto_mutex);
363
364     /* Flow monitors (e.g. for NXST_FLOW_MONITOR, related to struct ofmonitor).
365      *
366      * 'add_seqno' is the sequence number when this rule was created.
367      * 'modify_seqno' is the sequence number when this rule was last modified.
368      * See 'monitor_seqno' in connmgr.c for more information. */
369     enum nx_flow_monitor_flags monitor_flags OVS_GUARDED_BY(ofproto_mutex);
370     uint64_t add_seqno OVS_GUARDED_BY(ofproto_mutex);
371     uint64_t modify_seqno OVS_GUARDED_BY(ofproto_mutex);
372
373     /* Optimisation for flow expiry.  In ofproto's 'expirable' list if this
374      * rule is expirable, otherwise empty. */
375     struct list expirable OVS_GUARDED_BY(ofproto_mutex);
376
377     /* Times.  Last so that they are more likely close to the stats managed
378      * by the provider. */
379     long long int created OVS_GUARDED; /* Creation time. */
380
381     /* Must hold 'mutex' for both read/write, 'ofproto_mutex' not needed. */
382     long long int modified OVS_GUARDED; /* Time of last modification. */
383 };
384
385 void ofproto_rule_ref(struct rule *);
386 void ofproto_rule_unref(struct rule *);
387
388 static inline const struct rule_actions * rule_get_actions(const struct rule *);
389 static inline bool rule_is_table_miss(const struct rule *);
390 static inline bool rule_is_hidden(const struct rule *);
391
392 /* A set of actions within a "struct rule".
393  *
394  *
395  * Thread-safety
396  * =============
397  *
398  * A struct rule_actions may be accessed without a risk of being
399  * freed by code that holds a read-lock or write-lock on 'rule->mutex' (where
400  * 'rule' is the rule for which 'rule->actions == actions') or during the RCU
401  * active period. */
402 struct rule_actions {
403     /* These members are immutable: they do not change during the struct's
404      * lifetime.  */
405     uint32_t ofpacts_len;         /* Size of 'ofpacts', in bytes. */
406     uint32_t provider_meter_id;   /* Datapath meter_id, or UINT32_MAX. */
407     struct ofpact ofpacts[];      /* Sequence of "struct ofpacts". */
408 };
409 BUILD_ASSERT_DECL(offsetof(struct rule_actions, ofpacts) % OFPACT_ALIGNTO == 0);
410
411 const struct rule_actions *rule_actions_create(const struct ofproto *,
412                                                const struct ofpact *, size_t);
413 void rule_actions_destroy(const struct rule_actions *);
414
415 /* A set of rules to which an OpenFlow operation applies. */
416 struct rule_collection {
417     struct rule **rules;        /* The rules. */
418     size_t n;                   /* Number of rules collected. */
419
420     size_t capacity;            /* Number of rules that will fit in 'rules'. */
421     struct rule *stub[64];      /* Preallocated rules to avoid malloc(). */
422 };
423
424 void rule_collection_init(struct rule_collection *);
425 void rule_collection_add(struct rule_collection *, struct rule *);
426 void rule_collection_ref(struct rule_collection *) OVS_REQUIRES(ofproto_mutex);
427 void rule_collection_unref(struct rule_collection *);
428 void rule_collection_destroy(struct rule_collection *);
429
430 /* Limits the number of flows allowed in the datapath. Only affects the
431  * ofproto-dpif implementation. */
432 extern unsigned ofproto_flow_limit;
433
434 /* Maximum idle time (in ms) for flows to be cached in the datapath.
435  * Revalidators may expire flows more quickly than the configured value based
436  * on system load and other factors. This variable is subject to change. */
437 extern unsigned ofproto_max_idle;
438
439 /* Number of upcall handler and revalidator threads. Only affects the
440  * ofproto-dpif implementation. */
441 extern size_t n_handlers, n_revalidators;
442
443 static inline struct rule *rule_from_cls_rule(const struct cls_rule *);
444
445 void ofproto_rule_expire(struct rule *rule, uint8_t reason)
446     OVS_REQUIRES(ofproto_mutex);
447 void ofproto_rule_delete(struct ofproto *, struct rule *)
448     OVS_EXCLUDED(ofproto_mutex);
449 void ofproto_rule_reduce_timeouts(struct rule *rule, uint16_t idle_timeout,
450                                   uint16_t hard_timeout)
451     OVS_EXCLUDED(ofproto_mutex);
452
453 /* A group within a "struct ofproto".
454  *
455  * With few exceptions, ofproto implementations may look at these fields but
456  * should not modify them. */
457 struct ofgroup {
458     struct hmap_node hmap_node OVS_GUARDED; /* In ofproto's "groups" hmap. */
459
460     /* Number of references.
461      *
462      * This is needed to keep track of references to the group in the xlate
463      * module.
464      *
465      * If the main thread removes the group from an ofproto, we need to
466      * guarantee that the group remains accessible to users of
467      * xlate_group_actions and the xlate_cache, as the xlate_cache will not be
468      * cleaned up until the corresponding datapath flows are revalidated. */
469     struct ovs_refcount ref_count;
470
471     /* No lock is needed to protect the fields below since they are not
472      * modified after construction. */
473     const struct ofproto *ofproto;  /* The ofproto that contains this group. */
474     const uint32_t group_id;
475     const enum ofp11_group_type type; /* One of OFPGT_*. */
476
477     const long long int created;      /* Creation time. */
478     const long long int modified;     /* Time of last modification. */
479
480     struct list buckets;        /* Contains "struct ofputil_bucket"s. */
481     const uint32_t n_buckets;
482 };
483
484 bool ofproto_group_lookup(const struct ofproto *ofproto, uint32_t group_id,
485                           struct ofgroup **group);
486
487 void ofproto_group_ref(struct ofgroup *);
488 void ofproto_group_unref(struct ofgroup *);
489
490 /* ofproto class structure, to be defined by each ofproto implementation.
491  *
492  *
493  * Data Structures
494  * ===============
495  *
496  * These functions work primarily with four different kinds of data
497  * structures:
498  *
499  *   - "struct ofproto", which represents an OpenFlow switch.
500  *
501  *   - "struct ofport", which represents a port within an ofproto.
502  *
503  *   - "struct rule", which represents an OpenFlow flow within an ofproto.
504  *
505  *   - "struct ofgroup", which represents an OpenFlow 1.1+ group within an
506  *     ofproto.
507  *
508  * Each of these data structures contains all of the implementation-independent
509  * generic state for the respective concept, called the "base" state.  None of
510  * them contains any extra space for ofproto implementations to use.  Instead,
511  * each implementation is expected to declare its own data structure that
512  * contains an instance of the generic data structure plus additional
513  * implementation-specific members, called the "derived" state.  The
514  * implementation can use casts or (preferably) the CONTAINER_OF macro to
515  * obtain access to derived state given only a pointer to the embedded generic
516  * data structure.
517  *
518  *
519  * Life Cycle
520  * ==========
521  *
522  * Four stylized functions accompany each of these data structures:
523  *
524  *            "alloc"       "construct"       "destruct"       "dealloc"
525  *            ------------  ----------------  ---------------  --------------
526  *   ofproto  ->alloc       ->construct       ->destruct       ->dealloc
527  *   ofport   ->port_alloc  ->port_construct  ->port_destruct  ->port_dealloc
528  *   rule     ->rule_alloc  ->rule_construct  ->rule_destruct  ->rule_dealloc
529  *   group    ->group_alloc ->group_construct ->group_destruct ->group_dealloc
530  *
531  * "ofproto", "ofport", and "group" have this exact life cycle.  The "rule"
532  * data structure also follow this life cycle with some additional elaborations
533  * described under "Rule Life Cycle" below.
534  *
535  * Any instance of a given data structure goes through the following life
536  * cycle:
537  *
538  *   1. The client calls the "alloc" function to obtain raw memory.  If "alloc"
539  *      fails, skip all the other steps.
540  *
541  *   2. The client initializes all of the data structure's base state.  If this
542  *      fails, skip to step 7.
543  *
544  *   3. The client calls the "construct" function.  The implementation
545  *      initializes derived state.  It may refer to the already-initialized
546  *      base state.  If "construct" fails, skip to step 6.
547  *
548  *   4. The data structure is now initialized and in use.
549  *
550  *   5. When the data structure is no longer needed, the client calls the
551  *      "destruct" function.  The implementation uninitializes derived state.
552  *      The base state has not been uninitialized yet, so the implementation
553  *      may still refer to it.
554  *
555  *   6. The client uninitializes all of the data structure's base state.
556  *
557  *   7. The client calls the "dealloc" to free the raw memory.  The
558  *      implementation must not refer to base or derived state in the data
559  *      structure, because it has already been uninitialized.
560  *
561  * Each "alloc" function allocates and returns a new instance of the respective
562  * data structure.  The "alloc" function is not given any information about the
563  * use of the new data structure, so it cannot perform much initialization.
564  * Its purpose is just to ensure that the new data structure has enough room
565  * for base and derived state.  It may return a null pointer if memory is not
566  * available, in which case none of the other functions is called.
567  *
568  * Each "construct" function initializes derived state in its respective data
569  * structure.  When "construct" is called, all of the base state has already
570  * been initialized, so the "construct" function may refer to it.  The
571  * "construct" function is allowed to fail, in which case the client calls the
572  * "dealloc" function (but not the "destruct" function).
573  *
574  * Each "destruct" function uninitializes and frees derived state in its
575  * respective data structure.  When "destruct" is called, the base state has
576  * not yet been uninitialized, so the "destruct" function may refer to it.  The
577  * "destruct" function is not allowed to fail.
578  *
579  * Each "dealloc" function frees raw memory that was allocated by the the
580  * "alloc" function.  The memory's base and derived members might not have ever
581  * been initialized (but if "construct" returned successfully, then it has been
582  * "destruct"ed already).  The "dealloc" function is not allowed to fail.
583  *
584  *
585  * Conventions
586  * ===========
587  *
588  * Most of these functions return 0 if they are successful or a positive error
589  * code on failure.  Depending on the function, valid error codes are either
590  * errno values or OFPERR_* OpenFlow error codes.
591  *
592  * Most of these functions are expected to execute synchronously, that is, to
593  * block as necessary to obtain a result.  Thus, these functions may return
594  * EAGAIN (or EWOULDBLOCK or EINPROGRESS) only where the function descriptions
595  * explicitly say those errors are a possibility.  We may relax this
596  * requirement in the future if and when we encounter performance problems. */
597 struct ofproto_class {
598 /* ## ----------------- ## */
599 /* ## Factory Functions ## */
600 /* ## ----------------- ## */
601
602     /* Initializes provider.  The caller may pass in 'iface_hints',
603      * which contains an shash of "struct iface_hint" elements indexed
604      * by the interface's name.  The provider may use these hints to
605      * describe the startup configuration in order to reinitialize its
606      * state.  The caller owns the provided data, so a provider must
607      * make copies of anything required.  An ofproto provider must
608      * remove any existing state that is not described by the hint, and
609      * may choose to remove it all. */
610     void (*init)(const struct shash *iface_hints);
611
612     /* Enumerates the types of all support ofproto types into 'types'.  The
613      * caller has already initialized 'types' and other ofproto classes might
614      * already have added names to it. */
615     void (*enumerate_types)(struct sset *types);
616
617     /* Enumerates the names of all existing datapath of the specified 'type'
618      * into 'names' 'all_dps'.  The caller has already initialized 'names' as
619      * an empty sset.
620      *
621      * 'type' is one of the types enumerated by ->enumerate_types().
622      *
623      * Returns 0 if successful, otherwise a positive errno value.
624      */
625     int (*enumerate_names)(const char *type, struct sset *names);
626
627     /* Deletes the datapath with the specified 'type' and 'name'.  The caller
628      * should have closed any open ofproto with this 'type' and 'name'; this
629      * function is allowed to fail if that is not the case.
630      *
631      * 'type' is one of the types enumerated by ->enumerate_types().
632      * 'name' is one of the names enumerated by ->enumerate_names() for 'type'.
633      *
634      * Returns 0 if successful, otherwise a positive errno value.
635      */
636     int (*del)(const char *type, const char *name);
637
638     /* Returns the type to pass to netdev_open() when a datapath of type
639      * 'datapath_type' has a port of type 'port_type', for a few special
640      * cases when a netdev type differs from a port type.  For example,
641      * when using the userspace datapath, a port of type "internal"
642      * needs to be opened as "tap".
643      *
644      * Returns either 'type' itself or a string literal, which must not
645      * be freed. */
646     const char *(*port_open_type)(const char *datapath_type,
647                                   const char *port_type);
648
649 /* ## ------------------------ ## */
650 /* ## Top-Level type Functions ## */
651 /* ## ------------------------ ## */
652
653     /* Performs any periodic activity required on ofprotos of type
654      * 'type'.
655      *
656      * An ofproto provider may implement it or not, depending on whether
657      * it needs type-level maintenance.
658      *
659      * Returns 0 if successful, otherwise a positive errno value. */
660     int (*type_run)(const char *type);
661
662     /* Causes the poll loop to wake up when a type 'type''s 'run'
663      * function needs to be called, e.g. by calling the timer or fd
664      * waiting functions in poll-loop.h.
665      *
666      * An ofproto provider may implement it or not, depending on whether
667      * it needs type-level maintenance. */
668     void (*type_wait)(const char *type);
669
670 /* ## --------------------------- ## */
671 /* ## Top-Level ofproto Functions ## */
672 /* ## --------------------------- ## */
673
674     /* Life-cycle functions for an "ofproto" (see "Life Cycle" above).
675      *
676      *
677      * Construction
678      * ============
679      *
680      * ->construct() should not modify any base members of the ofproto.  The
681      * client will initialize the ofproto's 'ports' and 'tables' members after
682      * construction is complete.
683      *
684      * When ->construct() is called, the client does not yet know how many flow
685      * tables the datapath supports, so ofproto->n_tables will be 0 and
686      * ofproto->tables will be NULL.  ->construct() should call
687      * ofproto_init_tables() to allocate and initialize ofproto->n_tables and
688      * ofproto->tables.  Each flow table will be initially empty, so
689      * ->construct() should delete flows from the underlying datapath, if
690      * necessary, rather than populating the tables.
691      *
692      * If the ofproto knows the maximum port number that the datapath can have,
693      * then it can call ofproto_init_max_ports().  If it does so, then the
694      * client will ensure that the actions it allows to be used through
695      * OpenFlow do not refer to ports above that maximum number.
696      *
697      * Only one ofproto instance needs to be supported for any given datapath.
698      * If a datapath is already open as part of one "ofproto", then another
699      * attempt to "construct" the same datapath as part of another ofproto is
700      * allowed to fail with an error.
701      *
702      * ->construct() returns 0 if successful, otherwise a positive errno
703      * value.
704      *
705      *
706      * Destruction
707      * ===========
708      *
709      * ->destruct() must also destroy all remaining rules in the ofproto's
710      * tables, by passing each remaining rule to ofproto_rule_delete().
711      *
712      * The client will destroy the flow tables themselves after ->destruct()
713      * returns.
714      */
715     struct ofproto *(*alloc)(void);
716     int (*construct)(struct ofproto *ofproto);
717     void (*destruct)(struct ofproto *ofproto);
718     void (*dealloc)(struct ofproto *ofproto);
719
720     /* Performs any periodic activity required by 'ofproto'.  It should:
721      *
722      *   - Call connmgr_send_packet_in() for each received packet that missed
723      *     in the OpenFlow flow table or that had a OFPP_CONTROLLER output
724      *     action.
725      *
726      *   - Call ofproto_rule_expire() for each OpenFlow flow that has reached
727      *     its hard_timeout or idle_timeout, to expire the flow.
728      *
729      * Returns 0 if successful, otherwise a positive errno value. */
730     int (*run)(struct ofproto *ofproto);
731
732     /* Causes the poll loop to wake up when 'ofproto''s 'run' function needs to
733      * be called, e.g. by calling the timer or fd waiting functions in
734      * poll-loop.h.  */
735     void (*wait)(struct ofproto *ofproto);
736
737     /* Adds some memory usage statistics for the implementation of 'ofproto'
738      * into 'usage', for use with memory_report().
739      *
740      * This function is optional. */
741     void (*get_memory_usage)(const struct ofproto *ofproto,
742                              struct simap *usage);
743
744     /* Adds some memory usage statistics for the implementation of 'type'
745      * into 'usage', for use with memory_report().
746      *
747      * This function is optional. */
748     void (*type_get_memory_usage)(const char *type, struct simap *usage);
749
750     /* Every "struct rule" in 'ofproto' is about to be deleted, one by one.
751      * This function may prepare for that, for example by clearing state in
752      * advance.  It should *not* actually delete any "struct rule"s from
753      * 'ofproto', only prepare for it.
754      *
755      * This function is optional; it's really just for optimization in case
756      * it's cheaper to delete all the flows from your hardware in a single pass
757      * than to do it one by one. */
758     void (*flush)(struct ofproto *ofproto);
759
760     /* Helper for the OpenFlow OFPT_FEATURES_REQUEST request.
761      *
762      * The implementation should store true in '*arp_match_ip' if the switch
763      * supports matching IP addresses inside ARP requests and replies, false
764      * otherwise.
765      *
766      * The implementation should store in '*actions' a bitmap of the supported
767      * OpenFlow actions.  Vendor actions are not included in '*actions'. */
768     void (*get_features)(struct ofproto *ofproto,
769                          bool *arp_match_ip,
770                          enum ofputil_action_bitmap *actions);
771
772     /* Helper for the OpenFlow OFPST_TABLE statistics request.
773      *
774      * The 'ots' array contains 'ofproto->n_tables' elements.  Each element is
775      * initialized as:
776      *
777      *   - 'table_id' to the array index.
778      *
779      *   - 'name' to "table#" where # is the table ID.
780      *
781      *   - 'match' and 'wildcards' to OFPXMT12_MASK.
782      *
783      *   - 'write_actions' and 'apply_actions' to OFPAT12_OUTPUT.
784      *
785      *   - 'write_setfields' and 'apply_setfields' to OFPXMT12_MASK.
786      *
787      *   - 'metadata_match' and 'metadata_write' to OVS_BE64_MAX.
788      *
789      *   - 'instructions' to OFPIT11_ALL.
790      *
791      *   - 'config' to OFPTC11_TABLE_MISS_MASK.
792      *
793      *   - 'max_entries' to 1,000,000.
794      *
795      *   - 'active_count' to the classifier_count() for the table.
796      *
797      *   - 'lookup_count' and 'matched_count' to 0.
798      *
799      * The implementation should update any members in each element for which
800      * it has better values:
801      *
802      *   - 'name' to a more meaningful name.
803      *
804      *   - 'wildcards' to the set of wildcards actually supported by the table
805      *     (if it doesn't support all OpenFlow wildcards).
806      *
807      *   - 'instructions' to set the instructions actually supported by
808      *     the table.
809      *
810      *   - 'write_actions' to set the write actions actually supported by
811      *     the table (if it doesn't support all OpenFlow actions).
812      *
813      *   - 'apply_actions' to set the apply actions actually supported by
814      *     the table (if it doesn't support all OpenFlow actions).
815      *
816      *   - 'write_setfields' to set the write setfields actually supported by
817      *     the table.
818      *
819      *   - 'apply_setfields' to set the apply setfields actually supported by
820      *     the table.
821      *
822      *   - 'max_entries' to the maximum number of flows actually supported by
823      *     the hardware.
824      *
825      *   - 'lookup_count' to the number of packets looked up in this flow table
826      *     so far.
827      *
828      *   - 'matched_count' to the number of packets looked up in this flow
829      *     table so far that matched one of the flow entries.
830      *
831      * All of the members of struct ofp12_table_stats are in network byte
832      * order.
833      */
834     void (*get_tables)(struct ofproto *ofproto, struct ofp12_table_stats *ots);
835
836 /* ## ---------------- ## */
837 /* ## ofport Functions ## */
838 /* ## ---------------- ## */
839
840     /* Life-cycle functions for a "struct ofport" (see "Life Cycle" above).
841      *
842      * ->port_construct() should not modify any base members of the ofport.
843      * An ofproto implementation should use the 'ofp_port' member of
844      * "struct ofport" as the OpenFlow port number.
845      *
846      * ofports are managed by the base ofproto code.  The ofproto
847      * implementation should only create and destroy them in response to calls
848      * to these functions.  The base ofproto code will create and destroy
849      * ofports in the following situations:
850      *
851      *   - Just after the ->construct() function is called, the base ofproto
852      *     iterates over all of the implementation's ports, using
853      *     ->port_dump_start() and related functions, and constructs an ofport
854      *     for each dumped port.
855      *
856      *   - If ->port_poll() reports that a specific port has changed, then the
857      *     base ofproto will query that port with ->port_query_by_name() and
858      *     construct or destruct ofports as necessary to reflect the updated
859      *     set of ports.
860      *
861      *   - If ->port_poll() returns ENOBUFS to report an unspecified port set
862      *     change, then the base ofproto will iterate over all of the
863      *     implementation's ports, in the same way as at ofproto
864      *     initialization, and construct and destruct ofports to reflect all of
865      *     the changes.
866      *
867      * ->port_construct() returns 0 if successful, otherwise a positive errno
868      * value.
869      */
870     struct ofport *(*port_alloc)(void);
871     int (*port_construct)(struct ofport *ofport);
872     void (*port_destruct)(struct ofport *ofport);
873     void (*port_dealloc)(struct ofport *ofport);
874
875     /* Called after 'ofport->netdev' is replaced by a new netdev object.  If
876      * the ofproto implementation uses the ofport's netdev internally, then it
877      * should switch to using the new one.  The old one has been closed.
878      *
879      * An ofproto implementation that doesn't need to do anything in this
880      * function may use a null pointer. */
881     void (*port_modified)(struct ofport *ofport);
882
883     /* Called after an OpenFlow request changes a port's configuration.
884      * 'ofport->pp.config' contains the new configuration.  'old_config'
885      * contains the previous configuration.
886      *
887      * The caller implements OFPUTIL_PC_PORT_DOWN using netdev functions to
888      * turn NETDEV_UP on and off, so this function doesn't have to do anything
889      * for that bit (and it won't be called if that is the only bit that
890      * changes). */
891     void (*port_reconfigured)(struct ofport *ofport,
892                               enum ofputil_port_config old_config);
893
894     /* Looks up a port named 'devname' in 'ofproto'.  On success, returns 0 and
895      * initializes '*port' appropriately. Otherwise, returns a positive errno
896      * value.
897      *
898      * The caller owns the data in 'port' and must free it with
899      * ofproto_port_destroy() when it is no longer needed. */
900     int (*port_query_by_name)(const struct ofproto *ofproto,
901                               const char *devname, struct ofproto_port *port);
902
903     /* Attempts to add 'netdev' as a port on 'ofproto'.  Returns 0 if
904      * successful, otherwise a positive errno value.  The caller should
905      * inform the implementation of the OpenFlow port through the
906      * ->port_construct() method.
907      *
908      * It doesn't matter whether the new port will be returned by a later call
909      * to ->port_poll(); the implementation may do whatever is more
910      * convenient. */
911     int (*port_add)(struct ofproto *ofproto, struct netdev *netdev);
912
913     /* Deletes port number 'ofp_port' from the datapath for 'ofproto'.  Returns
914      * 0 if successful, otherwise a positive errno value.
915      *
916      * It doesn't matter whether the new port will be returned by a later call
917      * to ->port_poll(); the implementation may do whatever is more
918      * convenient. */
919     int (*port_del)(struct ofproto *ofproto, ofp_port_t ofp_port);
920
921     /* Get port stats */
922     int (*port_get_stats)(const struct ofport *port,
923                           struct netdev_stats *stats);
924
925     /* Port iteration functions.
926      *
927      * The client might not be entirely in control of the ports within an
928      * ofproto.  Some hardware implementations, for example, might have a fixed
929      * set of ports in a datapath.  For this reason, the client needs a way to
930      * iterate through all the ports that are actually in a datapath.  These
931      * functions provide that functionality.
932      *
933      * The 'state' pointer provides the implementation a place to
934      * keep track of its position.  Its format is opaque to the caller.
935      *
936      * The ofproto provider retains ownership of the data that it stores into
937      * ->port_dump_next()'s 'port' argument.  The data must remain valid until
938      * at least the next call to ->port_dump_next() or ->port_dump_done() for
939      * 'state'.  The caller will not modify or free it.
940      *
941      * Details
942      * =======
943      *
944      * ->port_dump_start() attempts to begin dumping the ports in 'ofproto'.
945      * On success, it should return 0 and initialize '*statep' with any data
946      * needed for iteration.  On failure, returns a positive errno value, and
947      * the client will not call ->port_dump_next() or ->port_dump_done().
948      *
949      * ->port_dump_next() attempts to retrieve another port from 'ofproto' for
950      * 'state'.  If there is another port, it should store the port's
951      * information into 'port' and return 0.  It should return EOF if all ports
952      * have already been iterated.  Otherwise, on error, it should return a
953      * positive errno value.  This function will not be called again once it
954      * returns nonzero once for a given iteration (but the 'port_dump_done'
955      * function will be called afterward).
956      *
957      * ->port_dump_done() allows the implementation to release resources used
958      * for iteration.  The caller might decide to stop iteration in the middle
959      * by calling this function before ->port_dump_next() returns nonzero.
960      *
961      * Usage Example
962      * =============
963      *
964      * int error;
965      * void *state;
966      *
967      * error = ofproto->ofproto_class->port_dump_start(ofproto, &state);
968      * if (!error) {
969      *     for (;;) {
970      *         struct ofproto_port port;
971      *
972      *         error = ofproto->ofproto_class->port_dump_next(
973      *                     ofproto, state, &port);
974      *         if (error) {
975      *             break;
976      *         }
977      *         // Do something with 'port' here (without modifying or freeing
978      *         // any of its data).
979      *     }
980      *     ofproto->ofproto_class->port_dump_done(ofproto, state);
981      * }
982      * // 'error' is now EOF (success) or a positive errno value (failure).
983      */
984     int (*port_dump_start)(const struct ofproto *ofproto, void **statep);
985     int (*port_dump_next)(const struct ofproto *ofproto, void *state,
986                           struct ofproto_port *port);
987     int (*port_dump_done)(const struct ofproto *ofproto, void *state);
988
989     /* Polls for changes in the set of ports in 'ofproto'.  If the set of ports
990      * in 'ofproto' has changed, then this function should do one of the
991      * following:
992      *
993      * - Preferably: store the name of the device that was added to or deleted
994      *   from 'ofproto' in '*devnamep' and return 0.  The caller is responsible
995      *   for freeing '*devnamep' (with free()) when it no longer needs it.
996      *
997      * - Alternatively: return ENOBUFS, without indicating the device that was
998      *   added or deleted.
999      *
1000      * Occasional 'false positives', in which the function returns 0 while
1001      * indicating a device that was not actually added or deleted or returns
1002      * ENOBUFS without any change, are acceptable.
1003      *
1004      * The purpose of 'port_poll' is to let 'ofproto' know about changes made
1005      * externally to the 'ofproto' object, e.g. by a system administrator via
1006      * ovs-dpctl.  Therefore, it's OK, and even preferable, for port_poll() to
1007      * not report changes made through calls to 'port_add' or 'port_del' on the
1008      * same 'ofproto' object.  (But it's OK for it to report them too, just
1009      * slightly less efficient.)
1010      *
1011      * If the set of ports in 'ofproto' has not changed, returns EAGAIN.  May
1012      * also return other positive errno values to indicate that something has
1013      * gone wrong.
1014      *
1015      * If the set of ports in a datapath is fixed, or if the only way that the
1016      * set of ports in a datapath can change is through ->port_add() and
1017      * ->port_del(), then this function may be a null pointer.
1018      */
1019     int (*port_poll)(const struct ofproto *ofproto, char **devnamep);
1020
1021     /* Arranges for the poll loop to wake up when ->port_poll() will return a
1022      * value other than EAGAIN.
1023      *
1024      * If the set of ports in a datapath is fixed, or if the only way that the
1025      * set of ports in a datapath can change is through ->port_add() and
1026      * ->port_del(), or if the poll loop will always wake up anyway when
1027      * ->port_poll() will return a value other than EAGAIN, then this function
1028      * may be a null pointer.
1029      */
1030     void (*port_poll_wait)(const struct ofproto *ofproto);
1031
1032     /* Checks the status of LACP negotiation for 'port'.  Returns 1 if LACP
1033      * partner information for 'port' is up-to-date, 0 if LACP partner
1034      * information is not current (generally indicating a connectivity
1035      * problem), or -1 if LACP is not enabled on 'port'.
1036      *
1037      * This function may be a null pointer if the ofproto implementation does
1038      * not support LACP. */
1039     int (*port_is_lacp_current)(const struct ofport *port);
1040
1041 /* ## ----------------------- ## */
1042 /* ## OpenFlow Rule Functions ## */
1043 /* ## ----------------------- ## */
1044
1045     /* Chooses an appropriate table for 'match' within 'ofproto'.  On
1046      * success, stores the table ID into '*table_idp' and returns 0.  On
1047      * failure, returns an OpenFlow error code.
1048      *
1049      * The choice of table should be a function of 'match' and 'ofproto''s
1050      * datapath capabilities.  It should not depend on the flows already in
1051      * 'ofproto''s flow tables.  Failure implies that an OpenFlow rule with
1052      * 'match' as its matching condition can never be inserted into 'ofproto',
1053      * even starting from an empty flow table.
1054      *
1055      * If multiple tables are candidates for inserting the flow, the function
1056      * should choose one arbitrarily (but deterministically).
1057      *
1058      * If this function is NULL then table 0 is always chosen. */
1059     enum ofperr (*rule_choose_table)(const struct ofproto *ofproto,
1060                                      const struct match *match,
1061                                      uint8_t *table_idp);
1062
1063     /* Life-cycle functions for a "struct rule".
1064      *
1065      *
1066      * Rule Life Cycle
1067      * ===============
1068      *
1069      * The life cycle of a struct rule is an elaboration of the basic life
1070      * cycle described above under "Life Cycle".
1071      *
1072      * After a rule is successfully constructed, it is then inserted.  If
1073      * insertion is successful, then before it is later destructed, it is
1074      * deleted.
1075      *
1076      * You can think of a rule as having the following extra steps inserted
1077      * between "Life Cycle" steps 4 and 5:
1078      *
1079      *   4.1. The client inserts the rule into the flow table, making it
1080      *        visible in flow table lookups.
1081      *
1082      *   4.2. The client calls "rule_insert" to insert the flow.  The
1083      *        implementation attempts to install the flow in the underlying
1084      *        hardware and returns an error code indicate success or failure.
1085      *        On failure, go to step 5.
1086      *
1087      *   4.3. The rule is now installed in the flow table.  Eventually it will
1088      *        be deleted.
1089      *
1090      *   4.4. The client removes the rule from the flow table.  It is no longer
1091      *        visible in flow table lookups.
1092      *
1093      *   4.5. The client calls "rule_delete".  The implementation uninstalls
1094      *        the flow from the underlying hardware.  Deletion is not allowed
1095      *        to fail.
1096      *
1097      *
1098      * Construction
1099      * ============
1100      *
1101      * When ->rule_construct() is called, 'rule' is a new rule that is not yet
1102      * inserted into a flow table.  ->rule_construct() should initialize enough
1103      * of the rule's derived state for 'rule' to be suitable for inserting into
1104      * a flow table.  ->rule_construct() should not modify any base members of
1105      * struct rule.
1106      *
1107      * If ->rule_construct() fails (as indicated by returning a nonzero
1108      * OpenFlow error code), the ofproto base code will uninitialize and
1109      * deallocate 'rule'.  See "Rule Life Cycle" above for more details.
1110      *
1111      * ->rule_construct() may also:
1112      *
1113      *   - Validate that the datapath supports the matching rule in 'rule->cr'
1114      *     datapath.  For example, if the rule's table does not support
1115      *     registers, then it is an error if 'rule->cr' does not wildcard all
1116      *     registers.
1117      *
1118      *   - Validate that the datapath can correctly implement 'rule->ofpacts'.
1119      *
1120      * Some implementations might need to defer these tasks to ->rule_insert(),
1121      * which is also acceptable.
1122      *
1123      *
1124      * Insertion
1125      * =========
1126      *
1127      * Following successful construction, the ofproto base case inserts 'rule'
1128      * into its flow table, then it calls ->rule_insert().  ->rule_insert()
1129      * must add the new rule to the datapath flow table and return only after
1130      * this is complete (whether it succeeds or fails).
1131      *
1132      * If ->rule_insert() fails, the ofproto base code will remove 'rule' from
1133      * the flow table, destruct, uninitialize, and deallocate 'rule'.  See
1134      * "Rule Life Cycle" above for more details.
1135      *
1136      *
1137      * Deletion
1138      * ========
1139      *
1140      * The ofproto base code removes 'rule' from its flow table before it calls
1141      * ->rule_delete().  ->rule_delete() must remove 'rule' from the datapath
1142      * flow table and return only after this has completed successfully.
1143      *
1144      * Rule deletion must not fail.
1145      *
1146      *
1147      * Destruction
1148      * ===========
1149      *
1150      * ->rule_destruct() must uninitialize derived state.
1151      *
1152      * Rule destruction must not fail. */
1153     struct rule *(*rule_alloc)(void);
1154     enum ofperr (*rule_construct)(struct rule *rule)
1155         /* OVS_REQUIRES(ofproto_mutex) */;
1156     enum ofperr (*rule_insert)(struct rule *rule)
1157         /* OVS_REQUIRES(ofproto_mutex) */;
1158     void (*rule_delete)(struct rule *rule) /* OVS_REQUIRES(ofproto_mutex) */;
1159     void (*rule_destruct)(struct rule *rule);
1160     void (*rule_dealloc)(struct rule *rule);
1161
1162     /* Obtains statistics for 'rule', storing the number of packets that have
1163      * matched it in '*packet_count' and the number of bytes in those packets
1164      * in '*byte_count'.  UINT64_MAX indicates that the packet count or byte
1165      * count is unknown. */
1166     void (*rule_get_stats)(struct rule *rule, uint64_t *packet_count,
1167                            uint64_t *byte_count, long long int *used)
1168         /* OVS_EXCLUDED(ofproto_mutex) */;
1169
1170     /* Applies the actions in 'rule' to 'packet'.  (This implements sending
1171      * buffered packets for OpenFlow OFPT_FLOW_MOD commands.)
1172      *
1173      * Takes ownership of 'packet' (so it should eventually free it, with
1174      * ofpbuf_delete()).
1175      *
1176      * 'flow' reflects the flow information for 'packet'.  All of the
1177      * information in 'flow' is extracted from 'packet', except for
1178      * flow->tunnel and flow->in_port, which are assigned the correct values
1179      * for the incoming packet.  The register values are zeroed.  'packet''s
1180      * header pointers and offsets (e.g. packet->l3) are appropriately
1181      * initialized.  packet->l3 is aligned on a 32-bit boundary.
1182      *
1183      * The implementation should add the statistics for 'packet' into 'rule'.
1184      *
1185      * Returns 0 if successful, otherwise an OpenFlow error code. */
1186     enum ofperr (*rule_execute)(struct rule *rule, const struct flow *flow,
1187                                 struct ofpbuf *packet);
1188
1189     /* If the datapath can properly implement changing 'rule''s actions to the
1190      * 'ofpacts_len' bytes in 'ofpacts', returns 0.  Otherwise, returns an enum
1191      * ofperr indicating why the new actions wouldn't work.
1192      *
1193      * May be a null pointer if any set of actions is acceptable. */
1194     enum ofperr (*rule_premodify_actions)(const struct rule *rule,
1195                                           const struct ofpact *ofpacts,
1196                                           size_t ofpacts_len)
1197         /* OVS_REQUIRES(ofproto_mutex) */;
1198
1199     /* When ->rule_modify_actions() is called, the caller has already replaced
1200      * the OpenFlow actions in 'rule' by a new set.  (If
1201      * ->rule_premodify_actions is nonnull, then it was previously called to
1202      * verify that the new set of actions is acceptable.)
1203      *
1204      * ->rule_modify_actions() must:
1205      *
1206      *   - Update the datapath flow table with the new actions.
1207      *
1208      *   - Only if 'reset_counters' is true, reset any packet or byte counters
1209      *     associated with the rule to zero, so that rule_get_stats() will not
1210      *     longer count those packets or bytes.
1211      *
1212      * Rule modification must not fail.
1213      *
1214      * ->rule_modify_actions() should not modify any base members of struct
1215      * rule. */
1216     void (*rule_modify_actions)(struct rule *rule, bool reset_counters)
1217         /* OVS_REQUIRES(ofproto_mutex) */;
1218
1219     /* Changes the OpenFlow IP fragment handling policy to 'frag_handling',
1220      * which takes one of the following values, with the corresponding
1221      * meanings:
1222      *
1223      *  - OFPC_FRAG_NORMAL: The switch should treat IP fragments the same way
1224      *    as other packets, omitting TCP and UDP port numbers (always setting
1225      *    them to 0).
1226      *
1227      *  - OFPC_FRAG_DROP: The switch should drop all IP fragments without
1228      *    passing them through the flow table.
1229      *
1230      *  - OFPC_FRAG_REASM: The switch should reassemble IP fragments before
1231      *    passing packets through the flow table.
1232      *
1233      *  - OFPC_FRAG_NX_MATCH (a Nicira extension): Similar to OFPC_FRAG_NORMAL,
1234      *    except that TCP and UDP port numbers should be included in fragments
1235      *    with offset 0.
1236      *
1237      * Implementations are not required to support every mode.
1238      * OFPC_FRAG_NORMAL is the default mode when an ofproto is created.
1239      *
1240      * At the time of the call to ->set_frag_handling(), the current mode is
1241      * available in 'ofproto->frag_handling'.  ->set_frag_handling() returns
1242      * true if the requested mode was set, false if it is not supported.
1243      *
1244      * Upon successful return, the caller changes 'ofproto->frag_handling' to
1245      * reflect the new mode.
1246      */
1247     bool (*set_frag_handling)(struct ofproto *ofproto,
1248                               enum ofp_config_flags frag_handling);
1249
1250     /* Implements the OpenFlow OFPT_PACKET_OUT command.  The datapath should
1251      * execute the 'ofpacts_len' bytes of "struct ofpacts" in 'ofpacts'.
1252      *
1253      * The caller retains ownership of 'packet' and of 'ofpacts', so
1254      * ->packet_out() should not modify or free them.
1255      *
1256      * This function must validate that it can correctly implement 'ofpacts'.
1257      * If not, then it should return an OpenFlow error code.
1258      *
1259      * 'flow' reflects the flow information for 'packet'.  All of the
1260      * information in 'flow' is extracted from 'packet', except for
1261      * flow->in_port (see below).  flow->tunnel and its register values are
1262      * zeroed.
1263      *
1264      * flow->in_port comes from the OpenFlow OFPT_PACKET_OUT message.  The
1265      * implementation should reject invalid flow->in_port values by returning
1266      * OFPERR_OFPBRC_BAD_PORT.  (If the implementation called
1267      * ofproto_init_max_ports(), then the client will reject these ports
1268      * itself.)  For consistency, the implementation should consider valid for
1269      * flow->in_port any value that could possibly be seen in a packet that it
1270      * passes to connmgr_send_packet_in().  Ideally, even an implementation
1271      * that never generates packet-ins (e.g. due to hardware limitations)
1272      * should still allow flow->in_port values for every possible physical port
1273      * and OFPP_LOCAL.  The only virtual ports (those above OFPP_MAX) that the
1274      * caller will ever pass in as flow->in_port, other than OFPP_LOCAL, are
1275      * OFPP_NONE and OFPP_CONTROLLER.  The implementation should allow both of
1276      * these, treating each of them as packets generated by the controller as
1277      * opposed to packets originating from some switch port.
1278      *
1279      * (Ordinarily the only effect of flow->in_port is on output actions that
1280      * involve the input port, such as actions that output to OFPP_IN_PORT,
1281      * OFPP_FLOOD, or OFPP_ALL.  flow->in_port can also affect Nicira extension
1282      * "resubmit" actions.)
1283      *
1284      * 'packet' is not matched against the OpenFlow flow table, so its
1285      * statistics should not be included in OpenFlow flow statistics.
1286      *
1287      * Returns 0 if successful, otherwise an OpenFlow error code. */
1288     enum ofperr (*packet_out)(struct ofproto *ofproto, struct ofpbuf *packet,
1289                               const struct flow *flow,
1290                               const struct ofpact *ofpacts,
1291                               size_t ofpacts_len);
1292
1293 /* ## ------------------------- ## */
1294 /* ## OFPP_NORMAL configuration ## */
1295 /* ## ------------------------- ## */
1296
1297     /* Configures NetFlow on 'ofproto' according to the options in
1298      * 'netflow_options', or turns off NetFlow if 'netflow_options' is NULL.
1299      *
1300      * EOPNOTSUPP as a return value indicates that 'ofproto' does not support
1301      * NetFlow, as does a null pointer. */
1302     int (*set_netflow)(struct ofproto *ofproto,
1303                        const struct netflow_options *netflow_options);
1304
1305     void (*get_netflow_ids)(const struct ofproto *ofproto,
1306                             uint8_t *engine_type, uint8_t *engine_id);
1307
1308     /* Configures sFlow on 'ofproto' according to the options in
1309      * 'sflow_options', or turns off sFlow if 'sflow_options' is NULL.
1310      *
1311      * EOPNOTSUPP as a return value indicates that 'ofproto' does not support
1312      * sFlow, as does a null pointer. */
1313     int (*set_sflow)(struct ofproto *ofproto,
1314                      const struct ofproto_sflow_options *sflow_options);
1315
1316     /* Configures IPFIX on 'ofproto' according to the options in
1317      * 'bridge_exporter_options' and the 'flow_exporters_options'
1318      * array, or turns off IPFIX if 'bridge_exporter_options' and
1319      * 'flow_exporters_options' is NULL.
1320      *
1321      * EOPNOTSUPP as a return value indicates that 'ofproto' does not support
1322      * IPFIX, as does a null pointer. */
1323     int (*set_ipfix)(
1324         struct ofproto *ofproto,
1325         const struct ofproto_ipfix_bridge_exporter_options
1326             *bridge_exporter_options,
1327         const struct ofproto_ipfix_flow_exporter_options
1328             *flow_exporters_options, size_t n_flow_exporters_options);
1329
1330     /* Configures connectivity fault management on 'ofport'.
1331      *
1332      * If 'cfm_settings' is nonnull, configures CFM according to its members.
1333      *
1334      * If 'cfm_settings' is null, removes any connectivity fault management
1335      * configuration from 'ofport'.
1336      *
1337      * EOPNOTSUPP as a return value indicates that this ofproto_class does not
1338      * support CFM, as does a null pointer. */
1339     int (*set_cfm)(struct ofport *ofport, const struct cfm_settings *s);
1340
1341     /* Checks the status of CFM configured on 'ofport'.  Returns 0 if the
1342      * port's CFM status was successfully stored into '*status'.  Returns
1343      * negative number if there is no status change since last update.
1344      * Returns positive errno otherwise.
1345      *
1346      * EOPNOTSUPP as a return value indicates that this ofproto_class does not
1347      * support CFM, as does a null pointer.
1348      *
1349      * The caller must provide and own '*status', and it must free the array
1350      * returned in 'status->rmps'.  '*status' is indeterminate if the return
1351      * value is non-zero. */
1352     int (*get_cfm_status)(const struct ofport *ofport,
1353                           struct ofproto_cfm_status *status);
1354
1355     /* Configures BFD on 'ofport'.
1356      *
1357      * If 'cfg' is NULL, or 'cfg' does not contain the key value pair
1358      * "enable=true", removes BFD from 'ofport'.  Otherwise, configures BFD
1359      * according to 'cfg'.
1360      *
1361      * EOPNOTSUPP as a return value indicates that this ofproto_class does not
1362      * support BFD, as does a null pointer. */
1363     int (*set_bfd)(struct ofport *ofport, const struct smap *cfg);
1364
1365     /* Populates 'smap' with the status of BFD on 'ofport'.  Returns 0 on
1366      * success.  Returns a negative number if there is no status change since
1367      * last update.  Returns a positive errno otherwise.
1368      *
1369      * EOPNOTSUPP as a return value indicates that this ofproto_class does not
1370      * support BFD, as does a null pointer. */
1371     int (*get_bfd_status)(struct ofport *ofport, struct smap *smap);
1372
1373     /* Configures spanning tree protocol (STP) on 'ofproto' using the
1374      * settings defined in 's'.
1375      *
1376      * If 's' is nonnull, configures STP according to its members.
1377      *
1378      * If 's' is null, removes any STP configuration from 'ofproto'.
1379      *
1380      * EOPNOTSUPP as a return value indicates that this ofproto_class does not
1381      * support STP, as does a null pointer. */
1382     int (*set_stp)(struct ofproto *ofproto,
1383                    const struct ofproto_stp_settings *s);
1384
1385     /* Retrieves state of spanning tree protocol (STP) on 'ofproto'.
1386      *
1387      * Stores STP state for 'ofproto' in 's'.  If the 'enabled' member
1388      * is false, the other member values are not meaningful.
1389      *
1390      * EOPNOTSUPP as a return value indicates that this ofproto_class does not
1391      * support STP, as does a null pointer. */
1392     int (*get_stp_status)(struct ofproto *ofproto,
1393                           struct ofproto_stp_status *s);
1394
1395     /* Configures spanning tree protocol (STP) on 'ofport' using the
1396      * settings defined in 's'.
1397      *
1398      * If 's' is nonnull, configures STP according to its members.  The
1399      * caller is responsible for assigning STP port numbers (using the
1400      * 'port_num' member in the range of 1 through 255, inclusive) and
1401      * ensuring there are no duplicates.
1402      *
1403      * If 's' is null, removes any STP configuration from 'ofport'.
1404      *
1405      * EOPNOTSUPP as a return value indicates that this ofproto_class does not
1406      * support STP, as does a null pointer. */
1407     int (*set_stp_port)(struct ofport *ofport,
1408                         const struct ofproto_port_stp_settings *s);
1409
1410     /* Retrieves spanning tree protocol (STP) port status of 'ofport'.
1411      *
1412      * Stores STP state for 'ofport' in 's'.  If the 'enabled' member is
1413      * false, the other member values are not meaningful.
1414      *
1415      * EOPNOTSUPP as a return value indicates that this ofproto_class does not
1416      * support STP, as does a null pointer. */
1417     int (*get_stp_port_status)(struct ofport *ofport,
1418                                struct ofproto_port_stp_status *s);
1419
1420     /* Retrieves spanning tree protocol (STP) port statistics of 'ofport'.
1421      *
1422      * Stores STP state for 'ofport' in 's'.  If the 'enabled' member is
1423      * false, the other member values are not meaningful.
1424      *
1425      * EOPNOTSUPP as a return value indicates that this ofproto_class does not
1426      * support STP, as does a null pointer. */
1427     int (*get_stp_port_stats)(struct ofport *ofport,
1428                               struct ofproto_port_stp_stats *s);
1429
1430     /* Registers meta-data associated with the 'n_qdscp' Qualities of Service
1431      * 'queues' attached to 'ofport'.  This data is not intended to be
1432      * sufficient to implement QoS.  Instead, providers may use this
1433      * information to implement features which require knowledge of what queues
1434      * exist on a port, and some basic information about them.
1435      *
1436      * EOPNOTSUPP as a return value indicates that this ofproto_class does not
1437      * support QoS, as does a null pointer. */
1438     int (*set_queues)(struct ofport *ofport,
1439                       const struct ofproto_port_queue *queues, size_t n_qdscp);
1440
1441     /* If 's' is nonnull, this function registers a "bundle" associated with
1442      * client data pointer 'aux' in 'ofproto'.  A bundle is the same concept as
1443      * a Port in OVSDB, that is, it consists of one or more "slave" devices
1444      * (Interfaces, in OVSDB) along with VLAN and LACP configuration and, if
1445      * there is more than one slave, a bonding configuration.  If 'aux' is
1446      * already registered then this function updates its configuration to 's'.
1447      * Otherwise, this function registers a new bundle.
1448      *
1449      * If 's' is NULL, this function unregisters the bundle registered on
1450      * 'ofproto' associated with client data pointer 'aux'.  If no such bundle
1451      * has been registered, this has no effect.
1452      *
1453      * This function affects only the behavior of the NXAST_AUTOPATH action and
1454      * output to the OFPP_NORMAL port.  An implementation that does not support
1455      * it at all may set it to NULL or return EOPNOTSUPP.  An implementation
1456      * that supports only a subset of the functionality should implement what
1457      * it can and return 0. */
1458     int (*bundle_set)(struct ofproto *ofproto, void *aux,
1459                       const struct ofproto_bundle_settings *s);
1460
1461     /* If 'port' is part of any bundle, removes it from that bundle.  If the
1462      * bundle now has no ports, deletes the bundle.  If the bundle now has only
1463      * one port, deconfigures the bundle's bonding configuration. */
1464     void (*bundle_remove)(struct ofport *ofport);
1465
1466     /* If 's' is nonnull, this function registers a mirror associated with
1467      * client data pointer 'aux' in 'ofproto'.  A mirror is the same concept as
1468      * a Mirror in OVSDB.  If 'aux' is already registered then this function
1469      * updates its configuration to 's'.  Otherwise, this function registers a
1470      * new mirror.
1471      *
1472      * If 's' is NULL, this function unregisters the mirror registered on
1473      * 'ofproto' associated with client data pointer 'aux'.  If no such mirror
1474      * has been registered, this has no effect.
1475      *
1476      * An implementation that does not support mirroring at all may set
1477      * it to NULL or return EOPNOTSUPP.  An implementation that supports
1478      * only a subset of the functionality should implement what it can
1479      * and return 0. */
1480     int (*mirror_set)(struct ofproto *ofproto, void *aux,
1481                       const struct ofproto_mirror_settings *s);
1482
1483     /* Retrieves statistics from mirror associated with client data
1484      * pointer 'aux' in 'ofproto'.  Stores packet and byte counts in
1485      * 'packets' and 'bytes', respectively.  If a particular counter is
1486      * not supported, the appropriate argument is set to UINT64_MAX.
1487      *
1488      * EOPNOTSUPP as a return value indicates that this ofproto_class does not
1489      * support retrieving mirror statistics. */
1490     int (*mirror_get_stats)(struct ofproto *ofproto, void *aux,
1491                             uint64_t *packets, uint64_t *bytes);
1492
1493     /* Configures the VLANs whose bits are set to 1 in 'flood_vlans' as VLANs
1494      * on which all packets are flooded, instead of using MAC learning.  If
1495      * 'flood_vlans' is NULL, then MAC learning applies to all VLANs.
1496      *
1497      * This function affects only the behavior of the OFPP_NORMAL action.  An
1498      * implementation that does not support it may set it to NULL or return
1499      * EOPNOTSUPP. */
1500     int (*set_flood_vlans)(struct ofproto *ofproto,
1501                            unsigned long *flood_vlans);
1502
1503     /* Returns true if 'aux' is a registered bundle that is currently in use as
1504      * the output for a mirror. */
1505     bool (*is_mirror_output_bundle)(const struct ofproto *ofproto, void *aux);
1506
1507     /* When the configuration option of forward_bpdu changes, this function
1508      * will be invoked. */
1509     void (*forward_bpdu_changed)(struct ofproto *ofproto);
1510
1511     /* Sets the MAC aging timeout for the OFPP_NORMAL action to 'idle_time', in
1512      * seconds, and the maximum number of MAC table entries to
1513      * 'max_entries'.
1514      *
1515      * An implementation that doesn't support configuring these features may
1516      * set this function to NULL or implement it as a no-op. */
1517     void (*set_mac_table_config)(struct ofproto *ofproto,
1518                                  unsigned int idle_time, size_t max_entries);
1519
1520 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
1521  *
1522  * This is deprecated.  It is only for compatibility with broken device drivers
1523  * in old versions of Linux that do not properly support VLANs when VLAN
1524  * devices are not used.  When broken device drivers are no longer in
1525  * widespread use, we will delete these interfaces. */
1526
1527     /* If 'realdev_ofp_port' is nonzero, then this function configures 'ofport'
1528      * as a VLAN splinter port for VLAN 'vid', associated with the real device
1529      * that has OpenFlow port number 'realdev_ofp_port'.
1530      *
1531      * If 'realdev_ofp_port' is zero, then this function deconfigures 'ofport'
1532      * as a VLAN splinter port.
1533      *
1534      * This function should be NULL if an implementation does not support it.
1535      */
1536     int (*set_realdev)(struct ofport *ofport,
1537                        ofp_port_t realdev_ofp_port, int vid);
1538
1539 /* ## ------------------------ ## */
1540 /* ## OpenFlow meter functions ## */
1541 /* ## ------------------------ ## */
1542
1543     /* These functions should be NULL if an implementation does not support
1544      * them.  They must be all null or all non-null.. */
1545
1546     /* Initializes 'features' to describe the metering features supported by
1547      * 'ofproto'. */
1548     void (*meter_get_features)(const struct ofproto *ofproto,
1549                                struct ofputil_meter_features *features);
1550
1551     /* If '*id' is UINT32_MAX, adds a new meter with the given 'config'.  On
1552      * success the function must store a provider meter ID other than
1553      * UINT32_MAX in '*id'.  All further references to the meter will be made
1554      * with the returned provider meter id rather than the OpenFlow meter id.
1555      * The caller does not try to interpret the provider meter id, giving the
1556      * implementation the freedom to either use the OpenFlow meter_id value
1557      * provided in the meter configuration, or any other value suitable for the
1558      * implementation.
1559      *
1560      * If '*id' is a value other than UINT32_MAX, modifies the existing meter
1561      * with that meter provider ID to have configuration 'config', while
1562      * leaving '*id' unchanged.  On failure, the existing meter configuration
1563      * is left intact. */
1564     enum ofperr (*meter_set)(struct ofproto *ofproto, ofproto_meter_id *id,
1565                              const struct ofputil_meter_config *config);
1566
1567     /* Gets the meter and meter band packet and byte counts for maximum of
1568      * 'stats->n_bands' bands for the meter with provider ID 'id' within
1569      * 'ofproto'.  The caller fills in the other stats values.  The band stats
1570      * are copied to memory at 'stats->bands' provided by the caller.  The
1571      * number of returned band stats is returned in 'stats->n_bands'. */
1572     enum ofperr (*meter_get)(const struct ofproto *ofproto,
1573                              ofproto_meter_id id,
1574                              struct ofputil_meter_stats *stats);
1575
1576     /* Deletes a meter, making the 'ofproto_meter_id' invalid for any
1577      * further calls. */
1578     void (*meter_del)(struct ofproto *, ofproto_meter_id);
1579
1580
1581 /* ## -------------------- ## */
1582 /* ## OpenFlow 1.1+ groups ## */
1583 /* ## -------------------- ## */
1584
1585     struct ofgroup *(*group_alloc)(void);
1586     enum ofperr (*group_construct)(struct ofgroup *);
1587     void (*group_destruct)(struct ofgroup *);
1588     void (*group_dealloc)(struct ofgroup *);
1589
1590     enum ofperr (*group_modify)(struct ofgroup *);
1591
1592     enum ofperr (*group_get_stats)(const struct ofgroup *,
1593                                    struct ofputil_group_stats *);
1594 };
1595
1596 extern const struct ofproto_class ofproto_dpif_class;
1597
1598 int ofproto_class_register(const struct ofproto_class *);
1599 int ofproto_class_unregister(const struct ofproto_class *);
1600
1601 int ofproto_flow_mod(struct ofproto *, struct ofputil_flow_mod *)
1602     OVS_EXCLUDED(ofproto_mutex);
1603 void ofproto_add_flow(struct ofproto *, const struct match *,
1604                       unsigned int priority,
1605                       const struct ofpact *ofpacts, size_t ofpacts_len)
1606     OVS_EXCLUDED(ofproto_mutex);
1607 void ofproto_delete_flow(struct ofproto *,
1608                          const struct match *, unsigned int priority)
1609     OVS_EXCLUDED(ofproto_mutex);
1610 void ofproto_flush_flows(struct ofproto *);
1611
1612 \f
1613 static inline const struct rule_actions *
1614 rule_get_actions(const struct rule *rule)
1615 {
1616     return ovsrcu_get(const struct rule_actions *, &rule->actions);
1617 }
1618
1619 /* Returns true if 'rule' is an OpenFlow 1.3 "table-miss" rule, false
1620  * otherwise.
1621  *
1622  * ("Table-miss" rules are special because a packet_in generated through one
1623  * uses OFPR_NO_MATCH as its reason, whereas packet_ins generated by any other
1624  * rule use OFPR_ACTION.) */
1625 static inline bool
1626 rule_is_table_miss(const struct rule *rule)
1627 {
1628     return rule->cr.priority == 0 && cls_rule_is_catchall(&rule->cr);
1629 }
1630
1631 /* Returns true if 'rule' should be hidden from the controller.
1632  *
1633  * Rules with priority higher than UINT16_MAX are set up by ofproto itself
1634  * (e.g. by in-band control) and are intentionally hidden from the
1635  * controller. */
1636 static inline bool
1637 rule_is_hidden(const struct rule *rule)
1638 {
1639     return rule->cr.priority > UINT16_MAX;
1640 }
1641
1642 static inline struct rule *
1643 rule_from_cls_rule(const struct cls_rule *cls_rule)
1644 {
1645     return cls_rule ? CONTAINER_OF(cls_rule, struct rule, cr) : NULL;
1646 }
1647
1648 #endif /* ofproto/ofproto-provider.h */