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