ofproto: Make ofproto ->construct() function initialize tables.
[cascardo/ovs.git] / ofproto / ofproto-provider.h
1 /*
2  * Copyright (c) 2009, 2010, 2011 Nicira Networks.
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 #include "ofproto/ofproto.h"
23 #include "cfm.h"
24 #include "classifier.h"
25 #include "list.h"
26 #include "ofp-errors.h"
27 #include "shash.h"
28 #include "timeval.h"
29
30 struct ofputil_flow_mod;
31
32 /* An OpenFlow switch.
33  *
34  * With few exceptions, ofproto implementations may look at these fields but
35  * should not modify them. */
36 struct ofproto {
37     const struct ofproto_class *ofproto_class;
38     char *type;                 /* Datapath type. */
39     char *name;                 /* Datapath name. */
40     struct hmap_node hmap_node; /* In global 'all_ofprotos' hmap. */
41
42     /* Settings. */
43     uint64_t fallback_dpid;     /* Datapath ID if no better choice found. */
44     uint64_t datapath_id;       /* Datapath ID. */
45     unsigned flow_eviction_threshold; /* Threshold at which to begin flow
46                                        * table eviction. Only affects the
47                                        * ofproto-dpif implementation */
48     bool forward_bpdu;          /* Option to allow forwarding of BPDU frames
49                                  * when NORMAL action is invoked. */
50     char *mfr_desc;             /* Manufacturer. */
51     char *hw_desc;              /* Hardware. */
52     char *sw_desc;              /* Software version. */
53     char *serial_desc;          /* Serial number. */
54     char *dp_desc;              /* Datapath description. */
55     enum ofp_config_flags frag_handling; /* One of OFPC_*.  */
56
57     /* Datapath. */
58     struct hmap ports;          /* Contains "struct ofport"s. */
59     struct shash port_by_name;
60
61     /* Flow tables. */
62     struct oftable *tables;
63     int n_tables;
64
65     /* OpenFlow connections. */
66     struct connmgr *connmgr;
67
68     /* Flow table operation tracking. */
69     int state;                  /* Internal state. */
70     struct list pending;        /* List of "struct ofopgroup"s. */
71     unsigned int n_pending;     /* list_size(&pending). */
72     struct hmap deletions;      /* All OFOPERATION_DELETE "ofoperation"s. */
73
74     /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
75      *
76      * This is deprecated.  It is only for compatibility with broken device
77      * drivers in old versions of Linux that do not properly support VLANs when
78      * VLAN devices are not used.  When broken device drivers are no longer in
79      * widespread use, we will delete these interfaces. */
80     unsigned long int *vlan_bitmap; /* 4096-bit bitmap of in-use VLANs. */
81     bool vlans_changed;             /* True if new VLANs are in use. */
82 };
83
84 void ofproto_init_tables(struct ofproto *, int n_tables);
85
86 struct ofproto *ofproto_lookup(const char *name);
87 struct ofport *ofproto_get_port(const struct ofproto *, uint16_t ofp_port);
88
89 /* An OpenFlow port within a "struct ofproto".
90  *
91  * With few exceptions, ofproto implementations may look at these fields but
92  * should not modify them. */
93 struct ofport {
94     struct ofproto *ofproto;    /* The ofproto that contains this port. */
95     struct hmap_node hmap_node; /* In struct ofproto's "ports" hmap. */
96     struct netdev *netdev;
97     struct ofp_phy_port opp;
98     uint16_t ofp_port;          /* OpenFlow port number. */
99     unsigned int change_seq;
100     int mtu;
101 };
102
103 void ofproto_port_set_state(struct ofport *, ovs_be32 state);
104
105 /* A flow table within a "struct ofproto". */
106 struct oftable {
107     struct classifier cls;      /* Contains "struct rule"s. */
108 };
109
110 /* Assigns TABLE to each oftable, in turn, in OFPROTO.
111  *
112  * All parameters are evaluated multiple times. */
113 #define OFPROTO_FOR_EACH_TABLE(TABLE, OFPROTO)              \
114     for ((TABLE) = (OFPROTO)->tables;                       \
115          (TABLE) < &(OFPROTO)->tables[(OFPROTO)->n_tables]; \
116          (TABLE)++)
117
118 /* An OpenFlow flow within a "struct ofproto".
119  *
120  * With few exceptions, ofproto implementations may look at these fields but
121  * should not modify them. */
122 struct rule {
123     struct ofproto *ofproto;     /* The ofproto that contains this rule. */
124     struct list ofproto_node;    /* Owned by ofproto base code. */
125     struct cls_rule cr;          /* In owning ofproto's classifier. */
126
127     struct ofoperation *pending; /* Operation now in progress, if nonnull. */
128
129     ovs_be64 flow_cookie;        /* Controller-issued identifier. */
130
131     long long int created;       /* Creation time. */
132     long long int modified;      /* Time of last modification. */
133     uint16_t idle_timeout;       /* In seconds from time of last use. */
134     uint16_t hard_timeout;       /* In seconds from last modification. */
135     uint8_t table_id;            /* Index in ofproto's 'tables' array. */
136     bool send_flow_removed;      /* Send a flow removed message? */
137
138     union ofp_action *actions;   /* OpenFlow actions. */
139     int n_actions;               /* Number of elements in actions[]. */
140 };
141
142 static inline struct rule *
143 rule_from_cls_rule(const struct cls_rule *cls_rule)
144 {
145     return cls_rule ? CONTAINER_OF(cls_rule, struct rule, cr) : NULL;
146 }
147
148 void ofproto_rule_expire(struct rule *, uint8_t reason);
149 void ofproto_rule_destroy(struct rule *);
150
151 void ofoperation_complete(struct ofoperation *, enum ofperr);
152 struct rule *ofoperation_get_victim(struct ofoperation *);
153
154 /* ofproto class structure, to be defined by each ofproto implementation.
155  *
156  *
157  * Data Structures
158  * ===============
159  *
160  * These functions work primarily with three different kinds of data
161  * structures:
162  *
163  *   - "struct ofproto", which represents an OpenFlow switch.
164  *
165  *   - "struct ofport", which represents a port within an ofproto.
166  *
167  *   - "struct rule", which represents an OpenFlow flow within an ofproto.
168  *
169  * Each of these data structures contains all of the implementation-independent
170  * generic state for the respective concept, called the "base" state.  None of
171  * them contains any extra space for ofproto implementations to use.  Instead,
172  * each implementation is expected to declare its own data structure that
173  * contains an instance of the generic data structure plus additional
174  * implementation-specific members, called the "derived" state.  The
175  * implementation can use casts or (preferably) the CONTAINER_OF macro to
176  * obtain access to derived state given only a pointer to the embedded generic
177  * data structure.
178  *
179  *
180  * Life Cycle
181  * ==========
182  *
183  * Four stylized functions accompany each of these data structures:
184  *
185  *            "alloc"       "construct"       "destruct"       "dealloc"
186  *            ------------  ----------------  ---------------  --------------
187  *   ofproto  ->alloc       ->construct       ->destruct       ->dealloc
188  *   ofport   ->port_alloc  ->port_construct  ->port_destruct  ->port_dealloc
189  *   rule     ->rule_alloc  ->rule_construct  ->rule_destruct  ->rule_dealloc
190  *
191  * Any instance of a given data structure goes through the following life
192  * cycle:
193  *
194  *   1. The client calls the "alloc" function to obtain raw memory.  If "alloc"
195  *      fails, skip all the other steps.
196  *
197  *   2. The client initializes all of the data structure's base state.  If this
198  *      fails, skip to step 7.
199  *
200  *   3. The client calls the "construct" function.  The implementation
201  *      initializes derived state.  It may refer to the already-initialized
202  *      base state.  If "construct" fails, skip to step 6.
203  *
204  *   4. The data structure is now initialized and in use.
205  *
206  *   5. When the data structure is no longer needed, the client calls the
207  *      "destruct" function.  The implementation uninitializes derived state.
208  *      The base state has not been uninitialized yet, so the implementation
209  *      may still refer to it.
210  *
211  *   6. The client uninitializes all of the data structure's base state.
212  *
213  *   7. The client calls the "dealloc" to free the raw memory.  The
214  *      implementation must not refer to base or derived state in the data
215  *      structure, because it has already been uninitialized.
216  *
217  * Each "alloc" function allocates and returns a new instance of the respective
218  * data structure.  The "alloc" function is not given any information about the
219  * use of the new data structure, so it cannot perform much initialization.
220  * Its purpose is just to ensure that the new data structure has enough room
221  * for base and derived state.  It may return a null pointer if memory is not
222  * available, in which case none of the other functions is called.
223  *
224  * Each "construct" function initializes derived state in its respective data
225  * structure.  When "construct" is called, all of the base state has already
226  * been initialized, so the "construct" function may refer to it.  The
227  * "construct" function is allowed to fail, in which case the client calls the
228  * "dealloc" function (but not the "destruct" function).
229  *
230  * Each "destruct" function uninitializes and frees derived state in its
231  * respective data structure.  When "destruct" is called, the base state has
232  * not yet been uninitialized, so the "destruct" function may refer to it.  The
233  * "destruct" function is not allowed to fail.
234  *
235  * Each "dealloc" function frees raw memory that was allocated by the the
236  * "alloc" function.  The memory's base and derived members might not have ever
237  * been initialized (but if "construct" returned successfully, then it has been
238  * "destruct"ed already).  The "dealloc" function is not allowed to fail.
239  *
240  *
241  * Conventions
242  * ===========
243  *
244  * Most of these functions return 0 if they are successful or a positive error
245  * code on failure.  Depending on the function, valid error codes are either
246  * errno values or OFPERR_* OpenFlow error codes.
247  *
248  * Most of these functions are expected to execute synchronously, that is, to
249  * block as necessary to obtain a result.  Thus, these functions may return
250  * EAGAIN (or EWOULDBLOCK or EINPROGRESS) only where the function descriptions
251  * explicitly say those errors are a possibility.  We may relax this
252  * requirement in the future if and when we encounter performance problems. */
253 struct ofproto_class {
254 /* ## ----------------- ## */
255 /* ## Factory Functions ## */
256 /* ## ----------------- ## */
257
258     /* Enumerates the types of all support ofproto types into 'types'.  The
259      * caller has already initialized 'types' and other ofproto classes might
260      * already have added names to it. */
261     void (*enumerate_types)(struct sset *types);
262
263     /* Enumerates the names of all existing datapath of the specified 'type'
264      * into 'names' 'all_dps'.  The caller has already initialized 'names' as
265      * an empty sset.
266      *
267      * 'type' is one of the types enumerated by ->enumerate_types().
268      *
269      * Returns 0 if successful, otherwise a positive errno value.
270      */
271     int (*enumerate_names)(const char *type, struct sset *names);
272
273     /* Deletes the datapath with the specified 'type' and 'name'.  The caller
274      * should have closed any open ofproto with this 'type' and 'name'; this
275      * function is allowed to fail if that is not the case.
276      *
277      * 'type' is one of the types enumerated by ->enumerate_types().
278      * 'name' is one of the names enumerated by ->enumerate_names() for 'type'.
279      *
280      * Returns 0 if successful, otherwise a positive errno value.
281      */
282     int (*del)(const char *type, const char *name);
283
284 /* ## --------------------------- ## */
285 /* ## Top-Level ofproto Functions ## */
286 /* ## --------------------------- ## */
287
288     /* Life-cycle functions for an "ofproto" (see "Life Cycle" above).
289      *
290      *
291      * Construction
292      * ============
293      *
294      * ->construct() should not modify any base members of the ofproto.  The
295      * client will initialize the ofproto's 'ports' and 'tables' members after
296      * construction is complete.
297      *
298      * When ->construct() is called, the client does not yet know how many flow
299      * tables the datapath supports, so ofproto->n_tables will be 0 and
300      * ofproto->tables will be NULL.  ->construct() should call
301      * ofproto_init_tables() to allocate and initialize ofproto->n_tables and
302      * ofproto->tables.  Each flow table will be initially empty, so
303      * ->construct() should delete flows from the underlying datapath, if
304      * necessary, rather than populating the tables.
305      *
306      * Only one ofproto instance needs to be supported for any given datapath.
307      * If a datapath is already open as part of one "ofproto", then another
308      * attempt to "construct" the same datapath as part of another ofproto is
309      * allowed to fail with an error.
310      *
311      * ->construct() returns 0 if successful, otherwise a positive errno
312      * value.
313      *
314      *
315      * Destruction
316      * ===========
317      *
318      * If 'ofproto' has any pending asynchronous operations, ->destruct()
319      * must complete all of them by calling ofoperation_complete().
320      *
321      * ->destruct() must also destroy all remaining rules in the ofproto's
322      * tables, by passing each remaining rule to ofproto_rule_destroy().  The
323      * client will destroy the flow tables themselves after ->destruct()
324      * returns.
325      */
326     struct ofproto *(*alloc)(void);
327     int (*construct)(struct ofproto *ofproto);
328     void (*destruct)(struct ofproto *ofproto);
329     void (*dealloc)(struct ofproto *ofproto);
330
331     /* Performs any periodic activity required by 'ofproto'.  It should:
332      *
333      *   - Call connmgr_send_packet_in() for each received packet that missed
334      *     in the OpenFlow flow table or that had a OFPP_CONTROLLER output
335      *     action.
336      *
337      *   - Call ofproto_rule_expire() for each OpenFlow flow that has reached
338      *     its hard_timeout or idle_timeout, to expire the flow.
339      *
340      * Returns 0 if successful, otherwise a positive errno value. */
341     int (*run)(struct ofproto *ofproto);
342
343     /* Performs periodic activity required by 'ofproto' that needs to be done
344      * with the least possible latency.
345      *
346      * This is run multiple times per main loop.  An ofproto provider may
347      * implement it or not, according to whether it provides a performance
348      * boost for that ofproto implementation. */
349     int (*run_fast)(struct ofproto *ofproto);
350
351     /* Causes the poll loop to wake up when 'ofproto''s 'run' function needs to
352      * be called, e.g. by calling the timer or fd waiting functions in
353      * poll-loop.h.  */
354     void (*wait)(struct ofproto *ofproto);
355
356     /* Every "struct rule" in 'ofproto' is about to be deleted, one by one.
357      * This function may prepare for that, for example by clearing state in
358      * advance.  It should *not* actually delete any "struct rule"s from
359      * 'ofproto', only prepare for it.
360      *
361      * This function is optional; it's really just for optimization in case
362      * it's cheaper to delete all the flows from your hardware in a single pass
363      * than to do it one by one. */
364     void (*flush)(struct ofproto *ofproto);
365
366     /* Helper for the OpenFlow OFPT_FEATURES_REQUEST request.
367      *
368      * The implementation should store true in '*arp_match_ip' if the switch
369      * supports matching IP addresses inside ARP requests and replies, false
370      * otherwise.
371      *
372      * The implementation should store in '*actions' a bitmap of the supported
373      * OpenFlow actions: the bit with value (1 << n) should be set to 1 if the
374      * implementation supports the action with value 'n', and to 0 otherwise.
375      * For example, if the implementation supports the OFPAT_OUTPUT and
376      * OFPAT_ENQUEUE actions, but no others, it would set '*actions' to (1 <<
377      * OFPAT_OUTPUT) | (1 << OFPAT_ENQUEUE).  Vendor actions are not included
378      * in '*actions'. */
379     void (*get_features)(struct ofproto *ofproto,
380                          bool *arp_match_ip, uint32_t *actions);
381
382     /* Helper for the OpenFlow OFPST_TABLE statistics request.
383      *
384      * The 'ots' array contains 'ofproto->n_tables' elements.  Each element is
385      * initialized as:
386      *
387      *   - 'table_id' to the array index.
388      *
389      *   - 'name' to "table#" where # is the table ID.
390      *
391      *   - 'wildcards' to OFPFW_ALL.
392      *
393      *   - 'max_entries' to 1,000,000.
394      *
395      *   - 'active_count' to the classifier_count() for the table.
396      *
397      *   - 'lookup_count' and 'matched_count' to 0.
398      *
399      * The implementation should update any members in each element for which
400      * it has better values:
401      *
402      *   - 'name' to a more meaningful name.
403      *
404      *   - 'wildcards' to the set of wildcards actually supported by the table
405      *     (if it doesn't support all OpenFlow wildcards).
406      *
407      *   - 'max_entries' to the maximum number of flows actually supported by
408      *     the hardware.
409      *
410      *   - 'lookup_count' to the number of packets looked up in this flow table
411      *     so far.
412      *
413      *   - 'matched_count' to the number of packets looked up in this flow
414      *     table so far that matched one of the flow entries.
415      *
416      * Keep in mind that all of the members of struct ofp_table_stats are in
417      * network byte order.
418      */
419     void (*get_tables)(struct ofproto *ofproto, struct ofp_table_stats *ots);
420
421 /* ## ---------------- ## */
422 /* ## ofport Functions ## */
423 /* ## ---------------- ## */
424
425     /* Life-cycle functions for a "struct ofport" (see "Life Cycle" above).
426      *
427      * ->port_construct() should not modify any base members of the ofport.
428      *
429      * ofports are managed by the base ofproto code.  The ofproto
430      * implementation should only create and destroy them in response to calls
431      * to these functions.  The base ofproto code will create and destroy
432      * ofports in the following situations:
433      *
434      *   - Just after the ->construct() function is called, the base ofproto
435      *     iterates over all of the implementation's ports, using
436      *     ->port_dump_start() and related functions, and constructs an ofport
437      *     for each dumped port.
438      *
439      *   - If ->port_poll() reports that a specific port has changed, then the
440      *     base ofproto will query that port with ->port_query_by_name() and
441      *     construct or destruct ofports as necessary to reflect the updated
442      *     set of ports.
443      *
444      *   - If ->port_poll() returns ENOBUFS to report an unspecified port set
445      *     change, then the base ofproto will iterate over all of the
446      *     implementation's ports, in the same way as at ofproto
447      *     initialization, and construct and destruct ofports to reflect all of
448      *     the changes.
449      *
450      * ->port_construct() returns 0 if successful, otherwise a positive errno
451      * value.
452      */
453     struct ofport *(*port_alloc)(void);
454     int (*port_construct)(struct ofport *ofport);
455     void (*port_destruct)(struct ofport *ofport);
456     void (*port_dealloc)(struct ofport *ofport);
457
458     /* Called after 'ofport->netdev' is replaced by a new netdev object.  If
459      * the ofproto implementation uses the ofport's netdev internally, then it
460      * should switch to using the new one.  The old one has been closed.
461      *
462      * An ofproto implementation that doesn't need to do anything in this
463      * function may use a null pointer. */
464     void (*port_modified)(struct ofport *ofport);
465
466     /* Called after an OpenFlow OFPT_PORT_MOD request changes a port's
467      * configuration.  'ofport->opp.config' contains the new configuration.
468      * 'old_config' contains the previous configuration.
469      *
470      * The caller implements OFPPC_PORT_DOWN using netdev functions to turn
471      * NETDEV_UP on and off, so this function doesn't have to do anything for
472      * that bit (and it won't be called if that is the only bit that
473      * changes). */
474     void (*port_reconfigured)(struct ofport *ofport, ovs_be32 old_config);
475
476     /* Looks up a port named 'devname' in 'ofproto'.  On success, initializes
477      * '*port' appropriately.
478      *
479      * The caller owns the data in 'port' and must free it with
480      * ofproto_port_destroy() when it is no longer needed. */
481     int (*port_query_by_name)(const struct ofproto *ofproto,
482                               const char *devname, struct ofproto_port *port);
483
484     /* Attempts to add 'netdev' as a port on 'ofproto'.  Returns 0 if
485      * successful, otherwise a positive errno value.  If successful, sets
486      * '*ofp_portp' to the new port's port number.
487      *
488      * It doesn't matter whether the new port will be returned by a later call
489      * to ->port_poll(); the implementation may do whatever is more
490      * convenient. */
491     int (*port_add)(struct ofproto *ofproto, struct netdev *netdev,
492                     uint16_t *ofp_portp);
493
494     /* Deletes port number 'ofp_port' from the datapath for 'ofproto'.  Returns
495      * 0 if successful, otherwise a positive errno value.
496      *
497      * It doesn't matter whether the new port will be returned by a later call
498      * to ->port_poll(); the implementation may do whatever is more
499      * convenient. */
500     int (*port_del)(struct ofproto *ofproto, uint16_t ofp_port);
501
502     /* Get port stats */
503     int (*port_get_stats)(const struct ofport *port,
504                           struct netdev_stats *stats);
505
506     /* Port iteration functions.
507      *
508      * The client might not be entirely in control of the ports within an
509      * ofproto.  Some hardware implementations, for example, might have a fixed
510      * set of ports in a datapath, and the Linux datapath allows the system
511      * administrator to externally add and remove ports with ovs-dpctl.  For
512      * this reason, the client needs a way to iterate through all the ports
513      * that are actually in a datapath.  These functions provide that
514      * functionality.
515      *
516      * The 'state' pointer provides the implementation a place to
517      * keep track of its position.  Its format is opaque to the caller.
518      *
519      * The ofproto provider retains ownership of the data that it stores into
520      * ->port_dump_next()'s 'port' argument.  The data must remain valid until
521      * at least the next call to ->port_dump_next() or ->port_dump_done() for
522      * 'state'.  The caller will not modify or free it.
523      *
524      * Details
525      * =======
526      *
527      * ->port_dump_start() attempts to begin dumping the ports in 'ofproto'.
528      * On success, it should return 0 and initialize '*statep' with any data
529      * needed for iteration.  On failure, returns a positive errno value, and
530      * the client will not call ->port_dump_next() or ->port_dump_done().
531      *
532      * ->port_dump_next() attempts to retrieve another port from 'ofproto' for
533      * 'state'.  If there is another port, it should store the port's
534      * information into 'port' and return 0.  It should return EOF if all ports
535      * have already been iterated.  Otherwise, on error, it should return a
536      * positive errno value.  This function will not be called again once it
537      * returns nonzero once for a given iteration (but the 'port_dump_done'
538      * function will be called afterward).
539      *
540      * ->port_dump_done() allows the implementation to release resources used
541      * for iteration.  The caller might decide to stop iteration in the middle
542      * by calling this function before ->port_dump_next() returns nonzero.
543      *
544      * Usage Example
545      * =============
546      *
547      * int error;
548      * void *state;
549      *
550      * error = ofproto->ofproto_class->port_dump_start(ofproto, &state);
551      * if (!error) {
552      *     for (;;) {
553      *         struct ofproto_port port;
554      *
555      *         error = ofproto->ofproto_class->port_dump_next(
556      *                     ofproto, state, &port);
557      *         if (error) {
558      *             break;
559      *         }
560      *         // Do something with 'port' here (without modifying or freeing
561      *         // any of its data).
562      *     }
563      *     ofproto->ofproto_class->port_dump_done(ofproto, state);
564      * }
565      * // 'error' is now EOF (success) or a positive errno value (failure).
566      */
567     int (*port_dump_start)(const struct ofproto *ofproto, void **statep);
568     int (*port_dump_next)(const struct ofproto *ofproto, void *state,
569                           struct ofproto_port *port);
570     int (*port_dump_done)(const struct ofproto *ofproto, void *state);
571
572     /* Polls for changes in the set of ports in 'ofproto'.  If the set of ports
573      * in 'ofproto' has changed, then this function should do one of the
574      * following:
575      *
576      * - Preferably: store the name of the device that was added to or deleted
577      *   from 'ofproto' in '*devnamep' and return 0.  The caller is responsible
578      *   for freeing '*devnamep' (with free()) when it no longer needs it.
579      *
580      * - Alternatively: return ENOBUFS, without indicating the device that was
581      *   added or deleted.
582      *
583      * Occasional 'false positives', in which the function returns 0 while
584      * indicating a device that was not actually added or deleted or returns
585      * ENOBUFS without any change, are acceptable.
586      *
587      * The purpose of 'port_poll' is to let 'ofproto' know about changes made
588      * externally to the 'ofproto' object, e.g. by a system administrator via
589      * ovs-dpctl.  Therefore, it's OK, and even preferable, for port_poll() to
590      * not report changes made through calls to 'port_add' or 'port_del' on the
591      * same 'ofproto' object.  (But it's OK for it to report them too, just
592      * slightly less efficient.)
593      *
594      * If the set of ports in 'ofproto' has not changed, returns EAGAIN.  May
595      * also return other positive errno values to indicate that something has
596      * gone wrong.
597      *
598      * If the set of ports in a datapath is fixed, or if the only way that the
599      * set of ports in a datapath can change is through ->port_add() and
600      * ->port_del(), then this function may be a null pointer.
601      */
602     int (*port_poll)(const struct ofproto *ofproto, char **devnamep);
603
604     /* Arranges for the poll loop to wake up when ->port_poll() will return a
605      * value other than EAGAIN.
606      *
607      * If the set of ports in a datapath is fixed, or if the only way that the
608      * set of ports in a datapath can change is through ->port_add() and
609      * ->port_del(), or if the poll loop will always wake up anyway when
610      * ->port_poll() will return a value other than EAGAIN, then this function
611      * may be a null pointer.
612      */
613     void (*port_poll_wait)(const struct ofproto *ofproto);
614
615     /* Checks the status of LACP negotiation for 'port'.  Returns 1 if LACP
616      * partner information for 'port' is up-to-date, 0 if LACP partner
617      * information is not current (generally indicating a connectivity
618      * problem), or -1 if LACP is not enabled on 'port'.
619      *
620      * This function may be a null pointer if the ofproto implementation does
621      * not support LACP. */
622     int (*port_is_lacp_current)(const struct ofport *port);
623
624 /* ## ----------------------- ## */
625 /* ## OpenFlow Rule Functions ## */
626 /* ## ----------------------- ## */
627
628
629
630     /* Chooses an appropriate table for 'cls_rule' within 'ofproto'.  On
631      * success, stores the table ID into '*table_idp' and returns 0.  On
632      * failure, returns an OpenFlow error code.
633      *
634      * The choice of table should be a function of 'cls_rule' and 'ofproto''s
635      * datapath capabilities.  It should not depend on the flows already in
636      * 'ofproto''s flow tables.  Failure implies that an OpenFlow rule with
637      * 'cls_rule' as its matching condition can never be inserted into
638      * 'ofproto', even starting from an empty flow table.
639      *
640      * If multiple tables are candidates for inserting the flow, the function
641      * should choose one arbitrarily (but deterministically).
642      *
643      * If this function is NULL then table 0 is always chosen. */
644     enum ofperr (*rule_choose_table)(const struct ofproto *ofproto,
645                                      const struct cls_rule *cls_rule,
646                                      uint8_t *table_idp);
647
648     /* Life-cycle functions for a "struct rule" (see "Life Cycle" above).
649      *
650      *
651      * Asynchronous Operation Support
652      * ==============================
653      *
654      * The life-cycle operations on rules can operate asynchronously, meaning
655      * that ->rule_construct() and ->rule_destruct() only need to initiate
656      * their respective operations and do not need to wait for them to complete
657      * before they return.  ->rule_modify_actions() also operates
658      * asynchronously.
659      *
660      * An ofproto implementation reports the success or failure of an
661      * asynchronous operation on a rule using the rule's 'pending' member,
662      * which points to a opaque "struct ofoperation" that represents the
663      * ongoing opreation.  When the operation completes, the ofproto
664      * implementation calls ofoperation_complete(), passing the ofoperation and
665      * an error indication.
666      *
667      * Only the following contexts may call ofoperation_complete():
668      *
669      *   - The function called to initiate the operation,
670      *     e.g. ->rule_construct() or ->rule_destruct().  This is the best
671      *     choice if the operation completes quickly.
672      *
673      *   - The implementation's ->run() function.
674      *
675      *   - The implementation's ->destruct() function.
676      *
677      * The ofproto base code updates the flow table optimistically, assuming
678      * that the operation will probably succeed:
679      *
680      *   - ofproto adds or replaces the rule in the flow table before calling
681      *     ->rule_construct().
682      *
683      *   - ofproto updates the rule's actions before calling
684      *     ->rule_modify_actions().
685      *
686      *   - ofproto removes the rule before calling ->rule_destruct().
687      *
688      * With one exception, when an asynchronous operation completes with an
689      * error, ofoperation_complete() backs out the already applied changes:
690      *
691      *   - If adding or replacing a rule in the flow table fails, ofproto
692      *     removes the new rule or restores the original rule.
693      *
694      *   - If modifying a rule's actions fails, ofproto restores the original
695      *     actions.
696      *
697      *   - Removing a rule is not allowed to fail.  It must always succeed.
698      *
699      * The ofproto base code serializes operations: if any operation is in
700      * progress on a given rule, ofproto postpones initiating any new operation
701      * on that rule until the pending operation completes.  Therefore, every
702      * operation must eventually complete through a call to
703      * ofoperation_complete() to avoid delaying new operations indefinitely
704      * (including any OpenFlow request that affects the rule in question, even
705      * just to query its statistics).
706      *
707      *
708      * Construction
709      * ============
710      *
711      * When ->rule_construct() is called, the caller has already inserted
712      * 'rule' into 'rule->ofproto''s flow table numbered 'rule->table_id'.
713      * There are two cases:
714      *
715      *   - 'rule' is a new rule in its flow table.  In this case,
716      *     ofoperation_get_victim(rule) returns NULL.
717      *
718      *   - 'rule' is replacing an existing rule in its flow table that had the
719      *     same matching criteria and priority.  In this case,
720      *     ofoperation_get_victim(rule) returns the rule being replaced (the
721      *     "victim" rule).
722      *
723      * ->rule_construct() should set the following in motion:
724      *
725      *   - Validate that the matching rule in 'rule->cr' is supported by the
726      *     datapath.  For example, if the rule's table does not support
727      *     registers, then it is an error if 'rule->cr' does not wildcard all
728      *     registers.
729      *
730      *   - Validate that 'rule->actions' and 'rule->n_actions' are well-formed
731      *     OpenFlow actions that the datapath can correctly implement.  The
732      *     validate_actions() function (in ofp-util.c) can be useful as a model
733      *     for action validation, but it accepts all of the OpenFlow actions
734      *     that OVS understands.  If your ofproto implementation only
735      *     implements a subset of those, then you should implement your own
736      *     action validation.
737      *
738      *   - If the rule is valid, update the datapath flow table, adding the new
739      *     rule or replacing the existing one.
740      *
741      *   - If 'rule' is replacing an existing rule, uninitialize any derived
742      *     state for the victim rule, as in step 5 in the "Life Cycle"
743      *     described above.
744      *
745      * (On failure, the ofproto code will roll back the insertion from the flow
746      * table, either removing 'rule' or replacing it by the victim rule if
747      * there is one.)
748      *
749      * ->rule_construct() must act in one of the following ways:
750      *
751      *   - If it succeeds, it must call ofoperation_complete() and return 0.
752      *
753      *   - If it fails, it must act in one of the following ways:
754      *
755      *       * Call ofoperation_complete() and return 0.
756      *
757      *       * Return an OpenFlow error code.  (Do not call
758      *         ofoperation_complete() in this case.)
759      *
760      *     Either way, ->rule_destruct() will not be called for 'rule', but
761      *     ->rule_dealloc() will be.
762      *
763      *   - If the operation is only partially complete, then it must return 0.
764      *     Later, when the operation is complete, the ->run() or ->destruct()
765      *     function must call ofoperation_complete() to report success or
766      *     failure.
767      *
768      * ->rule_construct() should not modify any base members of struct rule.
769      *
770      *
771      * Destruction
772      * ===========
773      *
774      * When ->rule_destruct() is called, the caller has already removed 'rule'
775      * from 'rule->ofproto''s flow table.  ->rule_destruct() should set in
776      * motion removing 'rule' from the datapath flow table.  If removal
777      * completes synchronously, it should call ofoperation_complete().
778      * Otherwise, the ->run() or ->destruct() function must later call
779      * ofoperation_complete() after the operation completes.
780      *
781      * Rule destruction must not fail. */
782     struct rule *(*rule_alloc)(void);
783     enum ofperr (*rule_construct)(struct rule *rule);
784     void (*rule_destruct)(struct rule *rule);
785     void (*rule_dealloc)(struct rule *rule);
786
787     /* Obtains statistics for 'rule', storing the number of packets that have
788      * matched it in '*packet_count' and the number of bytes in those packets
789      * in '*byte_count'.  UINT64_MAX indicates that the packet count or byte
790      * count is unknown. */
791     void (*rule_get_stats)(struct rule *rule, uint64_t *packet_count,
792                            uint64_t *byte_count);
793
794     /* Applies the actions in 'rule' to 'packet'.  (This implements sending
795      * buffered packets for OpenFlow OFPT_FLOW_MOD commands.)
796      *
797      * Takes ownership of 'packet' (so it should eventually free it, with
798      * ofpbuf_delete()).
799      *
800      * 'flow' reflects the flow information for 'packet'.  All of the
801      * information in 'flow' is extracted from 'packet', except for
802      * flow->tun_id and flow->in_port, which are assigned the correct values
803      * for the incoming packet.  The register values are zeroed.
804      *
805      * The statistics for 'packet' should be included in 'rule'.
806      *
807      * Returns 0 if successful, otherwise an OpenFlow error code. */
808     enum ofperr (*rule_execute)(struct rule *rule, const struct flow *flow,
809                                 struct ofpbuf *packet);
810
811     /* When ->rule_modify_actions() is called, the caller has already replaced
812      * the OpenFlow actions in 'rule' by a new set.  (The original actions are
813      * in rule->pending->actions.)
814      *
815      * ->rule_modify_actions() should set the following in motion:
816      *
817      *   - Validate that the actions now in 'rule' are well-formed OpenFlow
818      *     actions that the datapath can correctly implement.
819      *
820      *   - Update the datapath flow table with the new actions.
821      *
822      * If the operation synchronously completes, ->rule_modify_actions() may
823      * call ofoperation_complete() before it returns.  Otherwise, ->run()
824      * should call ofoperation_complete() later, after the operation does
825      * complete.
826      *
827      * If the operation fails, then the base ofproto code will restore the
828      * original 'actions' and 'n_actions' of 'rule'.
829      *
830      * ->rule_modify_actions() should not modify any base members of struct
831      * rule. */
832     void (*rule_modify_actions)(struct rule *rule);
833
834     /* Changes the OpenFlow IP fragment handling policy to 'frag_handling',
835      * which takes one of the following values, with the corresponding
836      * meanings:
837      *
838      *  - OFPC_FRAG_NORMAL: The switch should treat IP fragments the same way
839      *    as other packets, omitting TCP and UDP port numbers (always setting
840      *    them to 0).
841      *
842      *  - OFPC_FRAG_DROP: The switch should drop all IP fragments without
843      *    passing them through the flow table.
844      *
845      *  - OFPC_FRAG_REASM: The switch should reassemble IP fragments before
846      *    passing packets through the flow table.
847      *
848      *  - OFPC_FRAG_NX_MATCH (a Nicira extension): Similar to OFPC_FRAG_NORMAL,
849      *    except that TCP and UDP port numbers should be included in fragments
850      *    with offset 0.
851      *
852      * Implementations are not required to support every mode.
853      * OFPC_FRAG_NORMAL is the default mode when an ofproto is created.
854      *
855      * At the time of the call to ->set_frag_handling(), the current mode is
856      * available in 'ofproto->frag_handling'.  ->set_frag_handling() returns
857      * true if the requested mode was set, false if it is not supported.
858      *
859      * Upon successful return, the caller changes 'ofproto->frag_handling' to
860      * reflect the new mode.
861      */
862     bool (*set_frag_handling)(struct ofproto *ofproto,
863                               enum ofp_config_flags frag_handling);
864
865     /* Implements the OpenFlow OFPT_PACKET_OUT command.  The datapath should
866      * execute the 'n_actions' in the 'actions' array on 'packet'.
867      *
868      * The caller retains ownership of 'packet', so ->packet_out() should not
869      * modify or free it.
870      *
871      * This function must validate that the 'n_actions' elements in 'actions'
872      * are well-formed OpenFlow actions that can be correctly implemented by
873      * the datapath.  If not, then it should return an OpenFlow error code.
874      *
875      * 'flow' reflects the flow information for 'packet'.  All of the
876      * information in 'flow' is extracted from 'packet', except for
877      * flow->in_port, which is taken from the OFPT_PACKET_OUT message.
878      * flow->tun_id and its register values are zeroed.
879      *
880      * 'packet' is not matched against the OpenFlow flow table, so its
881      * statistics should not be included in OpenFlow flow statistics.
882      *
883      * Returns 0 if successful, otherwise an OpenFlow error code. */
884     enum ofperr (*packet_out)(struct ofproto *ofproto, struct ofpbuf *packet,
885                               const struct flow *flow,
886                               const union ofp_action *actions,
887                               size_t n_actions);
888
889 /* ## ------------------------- ## */
890 /* ## OFPP_NORMAL configuration ## */
891 /* ## ------------------------- ## */
892
893     /* Configures NetFlow on 'ofproto' according to the options in
894      * 'netflow_options', or turns off NetFlow if 'netflow_options' is NULL.
895      *
896      * EOPNOTSUPP as a return value indicates that 'ofproto' does not support
897      * NetFlow, as does a null pointer. */
898     int (*set_netflow)(struct ofproto *ofproto,
899                        const struct netflow_options *netflow_options);
900
901     void (*get_netflow_ids)(const struct ofproto *ofproto,
902                             uint8_t *engine_type, uint8_t *engine_id);
903
904     /* Configures sFlow on 'ofproto' according to the options in
905      * 'sflow_options', or turns off sFlow if 'sflow_options' is NULL.
906      *
907      * EOPNOTSUPP as a return value indicates that 'ofproto' does not support
908      * sFlow, as does a null pointer. */
909     int (*set_sflow)(struct ofproto *ofproto,
910                      const struct ofproto_sflow_options *sflow_options);
911
912     /* Configures connectivity fault management on 'ofport'.
913      *
914      * If 'cfm_settings' is nonnull, configures CFM according to its members.
915      *
916      * If 'cfm_settings' is null, removes any connectivity fault management
917      * configuration from 'ofport'.
918      *
919      * EOPNOTSUPP as a return value indicates that this ofproto_class does not
920      * support CFM, as does a null pointer. */
921     int (*set_cfm)(struct ofport *ofport, const struct cfm_settings *s);
922
923     /* Checks the fault status of CFM configured on 'ofport'.  Returns 1 if CFM
924      * is faulted (generally indicating a connectivity problem), 0 if CFM is
925      * not faulted, or -1 if CFM is not enabled on 'port'
926      *
927      * This function may be a null pointer if the ofproto implementation does
928      * not support CFM. */
929     int (*get_cfm_fault)(const struct ofport *ofport);
930
931     /* Gets the MPIDs of the remote maintenance points broadcasting to
932      * 'ofport'.  Populates 'rmps' with a provider owned array of MPIDs, and
933      * 'n_rmps' with the number of MPIDs in 'rmps'. Returns a number less than
934      * 0 if CFM is not enabled of 'ofport'.
935      *
936      * This function may be a null pointer if the ofproto implementation does
937      * not support CFM. */
938     int (*get_cfm_remote_mpids)(const struct ofport *ofport,
939                                 const uint64_t **rmps, size_t *n_rmps);
940
941     /* Configures spanning tree protocol (STP) on 'ofproto' using the
942      * settings defined in 's'.
943      *
944      * If 's' is nonnull, configures STP according to its members.
945      *
946      * If 's' is null, removes any STP configuration from 'ofproto'.
947      *
948      * EOPNOTSUPP as a return value indicates that this ofproto_class does not
949      * support STP, as does a null pointer. */
950     int (*set_stp)(struct ofproto *ofproto,
951                    const struct ofproto_stp_settings *s);
952
953     /* Retrieves state of spanning tree protocol (STP) on 'ofproto'.
954      *
955      * Stores STP state for 'ofproto' in 's'.  If the 'enabled' member
956      * is false, the other member values are not meaningful.
957      *
958      * EOPNOTSUPP as a return value indicates that this ofproto_class does not
959      * support STP, as does a null pointer. */
960     int (*get_stp_status)(struct ofproto *ofproto,
961                           struct ofproto_stp_status *s);
962
963     /* Configures spanning tree protocol (STP) on 'ofport' using the
964      * settings defined in 's'.
965      *
966      * If 's' is nonnull, configures STP according to its members.  The
967      * caller is responsible for assigning STP port numbers (using the
968      * 'port_num' member in the range of 1 through 255, inclusive) and
969      * ensuring there are no duplicates.
970      *
971      * If 's' is null, removes any STP configuration from 'ofport'.
972      *
973      * EOPNOTSUPP as a return value indicates that this ofproto_class does not
974      * support STP, as does a null pointer. */
975     int (*set_stp_port)(struct ofport *ofport,
976                         const struct ofproto_port_stp_settings *s);
977
978     /* Retrieves spanning tree protocol (STP) port status of 'ofport'.
979      *
980      * Stores STP state for 'ofport' in 's'.  If the 'enabled' member is
981      * false, the other member values are not meaningful.
982      *
983      * EOPNOTSUPP as a return value indicates that this ofproto_class does not
984      * support STP, as does a null pointer. */
985     int (*get_stp_port_status)(struct ofport *ofport,
986                                struct ofproto_port_stp_status *s);
987
988     /* Registers meta-data associated with the 'n_qdscp' Qualities of Service
989      * 'queues' attached to 'ofport'.  This data is not intended to be
990      * sufficient to implement QoS.  Instead, providers may use this
991      * information to implement features which require knowledge of what queues
992      * exist on a port, and some basic information about them.
993      *
994      * EOPNOTSUPP as a return value indicates that this ofproto_class does not
995      * support QoS, as does a null pointer. */
996     int (*set_queues)(struct ofport *ofport,
997                       const struct ofproto_port_queue *queues, size_t n_qdscp);
998
999     /* If 's' is nonnull, this function registers a "bundle" associated with
1000      * client data pointer 'aux' in 'ofproto'.  A bundle is the same concept as
1001      * a Port in OVSDB, that is, it consists of one or more "slave" devices
1002      * (Interfaces, in OVSDB) along with VLAN and LACP configuration and, if
1003      * there is more than one slave, a bonding configuration.  If 'aux' is
1004      * already registered then this function updates its configuration to 's'.
1005      * Otherwise, this function registers a new bundle.
1006      *
1007      * If 's' is NULL, this function unregisters the bundle registered on
1008      * 'ofproto' associated with client data pointer 'aux'.  If no such bundle
1009      * has been registered, this has no effect.
1010      *
1011      * This function affects only the behavior of the NXAST_AUTOPATH action and
1012      * output to the OFPP_NORMAL port.  An implementation that does not support
1013      * it at all may set it to NULL or return EOPNOTSUPP.  An implementation
1014      * that supports only a subset of the functionality should implement what
1015      * it can and return 0. */
1016     int (*bundle_set)(struct ofproto *ofproto, void *aux,
1017                       const struct ofproto_bundle_settings *s);
1018
1019     /* If 'port' is part of any bundle, removes it from that bundle.  If the
1020      * bundle now has no ports, deletes the bundle.  If the bundle now has only
1021      * one port, deconfigures the bundle's bonding configuration. */
1022     void (*bundle_remove)(struct ofport *ofport);
1023
1024     /* If 's' is nonnull, this function registers a mirror associated with
1025      * client data pointer 'aux' in 'ofproto'.  A mirror is the same concept as
1026      * a Mirror in OVSDB.  If 'aux' is already registered then this function
1027      * updates its configuration to 's'.  Otherwise, this function registers a
1028      * new mirror.
1029      *
1030      * If 's' is NULL, this function unregisters the mirror registered on
1031      * 'ofproto' associated with client data pointer 'aux'.  If no such mirror
1032      * has been registered, this has no effect.
1033      *
1034      * An implementation that does not support mirroring at all may set
1035      * it to NULL or return EOPNOTSUPP.  An implementation that supports
1036      * only a subset of the functionality should implement what it can
1037      * and return 0. */
1038     int (*mirror_set)(struct ofproto *ofproto, void *aux,
1039                       const struct ofproto_mirror_settings *s);
1040
1041     /* Retrieves statistics from mirror associated with client data
1042      * pointer 'aux' in 'ofproto'.  Stores packet and byte counts in
1043      * 'packets' and 'bytes', respectively.  If a particular counter is
1044      * not supported, the appropriate argument is set to UINT64_MAX.
1045      *
1046      * EOPNOTSUPP as a return value indicates that this ofproto_class does not
1047      * support retrieving mirror statistics. */
1048     int (*mirror_get_stats)(struct ofproto *ofproto, void *aux,
1049                             uint64_t *packets, uint64_t *bytes);
1050
1051     /* Configures the VLANs whose bits are set to 1 in 'flood_vlans' as VLANs
1052      * on which all packets are flooded, instead of using MAC learning.  If
1053      * 'flood_vlans' is NULL, then MAC learning applies to all VLANs.
1054      *
1055      * This function affects only the behavior of the OFPP_NORMAL action.  An
1056      * implementation that does not support it may set it to NULL or return
1057      * EOPNOTSUPP. */
1058     int (*set_flood_vlans)(struct ofproto *ofproto,
1059                            unsigned long *flood_vlans);
1060
1061     /* Returns true if 'aux' is a registered bundle that is currently in use as
1062      * the output for a mirror. */
1063     bool (*is_mirror_output_bundle)(const struct ofproto *ofproto, void *aux);
1064
1065     /* When the configuration option of forward_bpdu changes, this function
1066      * will be invoked. */
1067     void (*forward_bpdu_changed)(struct ofproto *ofproto);
1068
1069 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
1070  *
1071  * This is deprecated.  It is only for compatibility with broken device drivers
1072  * in old versions of Linux that do not properly support VLANs when VLAN
1073  * devices are not used.  When broken device drivers are no longer in
1074  * widespread use, we will delete these interfaces. */
1075
1076     /* If 'realdev_ofp_port' is nonzero, then this function configures 'ofport'
1077      * as a VLAN splinter port for VLAN 'vid', associated with the real device
1078      * that has OpenFlow port number 'realdev_ofp_port'.
1079      *
1080      * If 'realdev_ofp_port' is zero, then this function deconfigures 'ofport'
1081      * as a VLAN splinter port.
1082      *
1083      * This function should be NULL if a an implementation does not support
1084      * it. */
1085     int (*set_realdev)(struct ofport *ofport,
1086                        uint16_t realdev_ofp_port, int vid);
1087 };
1088
1089 extern const struct ofproto_class ofproto_dpif_class;
1090
1091 int ofproto_class_register(const struct ofproto_class *);
1092 int ofproto_class_unregister(const struct ofproto_class *);
1093
1094 /* ofproto_flow_mod() returns this value if the flow_mod could not be processed
1095  * because it overlaps with an ongoing flow table operation that has not yet
1096  * completed.  The caller should retry the operation later.
1097  *
1098  * ofproto.c also uses this value internally for additional (similar) purposes.
1099  *
1100  * This particular value is a good choice because it is large, so that it does
1101  * not collide with any errno value, but not large enough to collide with an
1102  * OFPERR_* value. */
1103 enum { OFPROTO_POSTPONE = 1 << 16 };
1104 BUILD_ASSERT_DECL(OFPROTO_POSTPONE < OFPERR_OFS);
1105
1106 int ofproto_flow_mod(struct ofproto *, const struct ofputil_flow_mod *);
1107 void ofproto_add_flow(struct ofproto *, const struct cls_rule *,
1108                       const union ofp_action *, size_t n_actions);
1109 bool ofproto_delete_flow(struct ofproto *, const struct cls_rule *);
1110 void ofproto_flush_flows(struct ofproto *);
1111
1112 #endif /* ofproto/ofproto-provider.h */