ovs-appctl: Print command arguments for "help".
[cascardo/ovs.git] / ofproto / ofproto.c
1 /*
2  * Copyright (c) 2009, 2010, 2011 Nicira Networks.
3  * Copyright (c) 2010 Jean Tourrilhes - HP-Labs.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at:
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #include <config.h>
19 #include "ofproto.h"
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <stdbool.h>
23 #include <stdlib.h>
24 #include "byte-order.h"
25 #include "classifier.h"
26 #include "connmgr.h"
27 #include "coverage.h"
28 #include "dynamic-string.h"
29 #include "hash.h"
30 #include "hmap.h"
31 #include "netdev.h"
32 #include "nx-match.h"
33 #include "ofp-print.h"
34 #include "ofp-util.h"
35 #include "ofpbuf.h"
36 #include "ofproto-provider.h"
37 #include "openflow/nicira-ext.h"
38 #include "openflow/openflow.h"
39 #include "packets.h"
40 #include "pinsched.h"
41 #include "pktbuf.h"
42 #include "poll-loop.h"
43 #include "shash.h"
44 #include "sset.h"
45 #include "timeval.h"
46 #include "unaligned.h"
47 #include "unixctl.h"
48 #include "vlog.h"
49
50 VLOG_DEFINE_THIS_MODULE(ofproto);
51
52 COVERAGE_DEFINE(ofproto_error);
53 COVERAGE_DEFINE(ofproto_flush);
54 COVERAGE_DEFINE(ofproto_no_packet_in);
55 COVERAGE_DEFINE(ofproto_packet_out);
56 COVERAGE_DEFINE(ofproto_queue_req);
57 COVERAGE_DEFINE(ofproto_recv_openflow);
58 COVERAGE_DEFINE(ofproto_reinit_ports);
59 COVERAGE_DEFINE(ofproto_uninstallable);
60 COVERAGE_DEFINE(ofproto_update_port);
61
62 enum ofproto_state {
63     S_OPENFLOW,                 /* Processing OpenFlow commands. */
64     S_FLUSH,                    /* Deleting all flow table rules. */
65 };
66
67 enum ofoperation_type {
68     OFOPERATION_ADD,
69     OFOPERATION_DELETE,
70     OFOPERATION_MODIFY
71 };
72
73 /* A single OpenFlow request can execute any number of operations.  The
74  * ofopgroup maintain OpenFlow state common to all of the operations, e.g. the
75  * ofconn to which an error reply should be sent if necessary.
76  *
77  * ofproto initiates some operations internally.  These operations are still
78  * assigned to groups but will not have an associated ofconn. */
79 struct ofopgroup {
80     struct ofproto *ofproto;    /* Owning ofproto. */
81     struct list ofproto_node;   /* In ofproto's "pending" list. */
82     struct list ops;            /* List of "struct ofoperation"s. */
83
84     /* Data needed to send OpenFlow reply on failure or to send a buffered
85      * packet on success.
86      *
87      * If list_is_empty(ofconn_node) then this ofopgroup never had an
88      * associated ofconn or its ofconn's connection dropped after it initiated
89      * the operation.  In the latter case 'ofconn' is a wild pointer that
90      * refers to freed memory, so the 'ofconn' member must be used only if
91      * !list_is_empty(ofconn_node).
92      */
93     struct list ofconn_node;    /* In ofconn's list of pending opgroups. */
94     struct ofconn *ofconn;      /* ofconn for reply (but see note above). */
95     struct ofp_header *request; /* Original request (truncated at 64 bytes). */
96     uint32_t buffer_id;         /* Buffer id from original request. */
97     int error;                  /* 0 if no error yet, otherwise error code. */
98 };
99
100 static struct ofopgroup *ofopgroup_create_unattached(struct ofproto *);
101 static struct ofopgroup *ofopgroup_create(struct ofproto *, struct ofconn *,
102                                           const struct ofp_header *,
103                                           uint32_t buffer_id);
104 static void ofopgroup_submit(struct ofopgroup *);
105 static void ofopgroup_destroy(struct ofopgroup *);
106
107 /* A single flow table operation. */
108 struct ofoperation {
109     struct ofopgroup *group;    /* Owning group. */
110     struct list group_node;     /* In ofopgroup's "ops" list. */
111     struct hmap_node hmap_node; /* In ofproto's "deletions" hmap. */
112     struct rule *rule;          /* Rule being operated upon. */
113     enum ofoperation_type type; /* Type of operation. */
114     int status;                 /* -1 if pending, otherwise 0 or error code. */
115     struct rule *victim;        /* OFOPERATION_ADDING: Replaced rule. */
116     union ofp_action *actions;  /* OFOPERATION_MODIFYING: Replaced actions. */
117     int n_actions;              /* OFOPERATION_MODIFYING: # of old actions. */
118     ovs_be64 flow_cookie;       /* Rule's old flow cookie. */
119 };
120
121 static void ofoperation_create(struct ofopgroup *, struct rule *,
122                                enum ofoperation_type);
123 static void ofoperation_destroy(struct ofoperation *);
124
125 static void ofport_destroy__(struct ofport *);
126 static void ofport_destroy(struct ofport *);
127
128 static uint64_t pick_datapath_id(const struct ofproto *);
129 static uint64_t pick_fallback_dpid(void);
130
131 static void ofproto_destroy__(struct ofproto *);
132
133 static void ofproto_rule_destroy__(struct rule *);
134 static void ofproto_rule_send_removed(struct rule *, uint8_t reason);
135
136 static void ofopgroup_destroy(struct ofopgroup *);
137
138 static int add_flow(struct ofproto *, struct ofconn *,
139                     const struct ofputil_flow_mod *,
140                     const struct ofp_header *);
141
142 static bool handle_openflow(struct ofconn *, struct ofpbuf *);
143 static int handle_flow_mod__(struct ofproto *, struct ofconn *,
144                              const struct ofputil_flow_mod *,
145                              const struct ofp_header *);
146
147 static void update_port(struct ofproto *, const char *devname);
148 static int init_ports(struct ofproto *);
149 static void reinit_ports(struct ofproto *);
150 static void set_internal_devs_mtu(struct ofproto *);
151
152 static void ofproto_unixctl_init(void);
153
154 /* All registered ofproto classes, in probe order. */
155 static const struct ofproto_class **ofproto_classes;
156 static size_t n_ofproto_classes;
157 static size_t allocated_ofproto_classes;
158
159 /* Map from datapath name to struct ofproto, for use by unixctl commands. */
160 static struct hmap all_ofprotos = HMAP_INITIALIZER(&all_ofprotos);
161
162 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
163
164 static void
165 ofproto_initialize(void)
166 {
167     static bool inited;
168
169     if (!inited) {
170         inited = true;
171         ofproto_class_register(&ofproto_dpif_class);
172     }
173 }
174
175 /* 'type' should be a normalized datapath type, as returned by
176  * ofproto_normalize_type().  Returns the corresponding ofproto_class
177  * structure, or a null pointer if there is none registered for 'type'. */
178 static const struct ofproto_class *
179 ofproto_class_find__(const char *type)
180 {
181     size_t i;
182
183     ofproto_initialize();
184     for (i = 0; i < n_ofproto_classes; i++) {
185         const struct ofproto_class *class = ofproto_classes[i];
186         struct sset types;
187         bool found;
188
189         sset_init(&types);
190         class->enumerate_types(&types);
191         found = sset_contains(&types, type);
192         sset_destroy(&types);
193
194         if (found) {
195             return class;
196         }
197     }
198     VLOG_WARN("unknown datapath type %s", type);
199     return NULL;
200 }
201
202 /* Registers a new ofproto class.  After successful registration, new ofprotos
203  * of that type can be created using ofproto_create(). */
204 int
205 ofproto_class_register(const struct ofproto_class *new_class)
206 {
207     size_t i;
208
209     for (i = 0; i < n_ofproto_classes; i++) {
210         if (ofproto_classes[i] == new_class) {
211             return EEXIST;
212         }
213     }
214
215     if (n_ofproto_classes >= allocated_ofproto_classes) {
216         ofproto_classes = x2nrealloc(ofproto_classes,
217                                      &allocated_ofproto_classes,
218                                      sizeof *ofproto_classes);
219     }
220     ofproto_classes[n_ofproto_classes++] = new_class;
221     return 0;
222 }
223
224 /* Unregisters a datapath provider.  'type' must have been previously
225  * registered and not currently be in use by any ofprotos.  After
226  * unregistration new datapaths of that type cannot be opened using
227  * ofproto_create(). */
228 int
229 ofproto_class_unregister(const struct ofproto_class *class)
230 {
231     size_t i;
232
233     for (i = 0; i < n_ofproto_classes; i++) {
234         if (ofproto_classes[i] == class) {
235             for (i++; i < n_ofproto_classes; i++) {
236                 ofproto_classes[i - 1] = ofproto_classes[i];
237             }
238             n_ofproto_classes--;
239             return 0;
240         }
241     }
242     VLOG_WARN("attempted to unregister an ofproto class that is not "
243               "registered");
244     return EAFNOSUPPORT;
245 }
246
247 /* Clears 'types' and enumerates all registered ofproto types into it.  The
248  * caller must first initialize the sset. */
249 void
250 ofproto_enumerate_types(struct sset *types)
251 {
252     size_t i;
253
254     ofproto_initialize();
255     for (i = 0; i < n_ofproto_classes; i++) {
256         ofproto_classes[i]->enumerate_types(types);
257     }
258 }
259
260 /* Returns the fully spelled out name for the given ofproto 'type'.
261  *
262  * Normalized type string can be compared with strcmp().  Unnormalized type
263  * string might be the same even if they have different spellings. */
264 const char *
265 ofproto_normalize_type(const char *type)
266 {
267     return type && type[0] ? type : "system";
268 }
269
270 /* Clears 'names' and enumerates the names of all known created ofprotos with
271  * the given 'type'.  The caller must first initialize the sset.  Returns 0 if
272  * successful, otherwise a positive errno value.
273  *
274  * Some kinds of datapaths might not be practically enumerable.  This is not
275  * considered an error. */
276 int
277 ofproto_enumerate_names(const char *type, struct sset *names)
278 {
279     const struct ofproto_class *class = ofproto_class_find__(type);
280     return class ? class->enumerate_names(type, names) : EAFNOSUPPORT;
281  }
282
283 int
284 ofproto_create(const char *datapath_name, const char *datapath_type,
285                struct ofproto **ofprotop)
286 {
287     const struct ofproto_class *class;
288     struct classifier *table;
289     struct ofproto *ofproto;
290     int n_tables;
291     int error;
292
293     *ofprotop = NULL;
294
295     ofproto_initialize();
296     ofproto_unixctl_init();
297
298     datapath_type = ofproto_normalize_type(datapath_type);
299     class = ofproto_class_find__(datapath_type);
300     if (!class) {
301         VLOG_WARN("could not create datapath %s of unknown type %s",
302                   datapath_name, datapath_type);
303         return EAFNOSUPPORT;
304     }
305
306     ofproto = class->alloc();
307     if (!ofproto) {
308         VLOG_ERR("failed to allocate datapath %s of type %s",
309                  datapath_name, datapath_type);
310         return ENOMEM;
311     }
312
313     /* Initialize. */
314     memset(ofproto, 0, sizeof *ofproto);
315     ofproto->ofproto_class = class;
316     ofproto->name = xstrdup(datapath_name);
317     ofproto->type = xstrdup(datapath_type);
318     hmap_insert(&all_ofprotos, &ofproto->hmap_node,
319                 hash_string(ofproto->name, 0));
320     ofproto->datapath_id = 0;
321     ofproto_set_flow_eviction_threshold(ofproto,
322                                         OFPROTO_FLOW_EVICTON_THRESHOLD_DEFAULT);
323     ofproto->forward_bpdu = false;
324     ofproto->fallback_dpid = pick_fallback_dpid();
325     ofproto->mfr_desc = xstrdup(DEFAULT_MFR_DESC);
326     ofproto->hw_desc = xstrdup(DEFAULT_HW_DESC);
327     ofproto->sw_desc = xstrdup(DEFAULT_SW_DESC);
328     ofproto->serial_desc = xstrdup(DEFAULT_SERIAL_DESC);
329     ofproto->dp_desc = xstrdup(DEFAULT_DP_DESC);
330     hmap_init(&ofproto->ports);
331     shash_init(&ofproto->port_by_name);
332     ofproto->tables = NULL;
333     ofproto->n_tables = 0;
334     ofproto->connmgr = connmgr_create(ofproto, datapath_name, datapath_name);
335     ofproto->state = S_OPENFLOW;
336     list_init(&ofproto->pending);
337     ofproto->n_pending = 0;
338     hmap_init(&ofproto->deletions);
339
340     error = ofproto->ofproto_class->construct(ofproto, &n_tables);
341     if (error) {
342         VLOG_ERR("failed to open datapath %s: %s",
343                  datapath_name, strerror(error));
344         ofproto_destroy__(ofproto);
345         return error;
346     }
347
348     assert(n_tables >= 1 && n_tables <= 255);
349     ofproto->n_tables = n_tables;
350     ofproto->tables = xmalloc(n_tables * sizeof *ofproto->tables);
351     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
352         classifier_init(table);
353     }
354
355     ofproto->datapath_id = pick_datapath_id(ofproto);
356     VLOG_INFO("using datapath ID %016"PRIx64, ofproto->datapath_id);
357     init_ports(ofproto);
358
359     *ofprotop = ofproto;
360     return 0;
361 }
362
363 void
364 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
365 {
366     uint64_t old_dpid = p->datapath_id;
367     p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
368     if (p->datapath_id != old_dpid) {
369         VLOG_INFO("datapath ID changed to %016"PRIx64, p->datapath_id);
370
371         /* Force all active connections to reconnect, since there is no way to
372          * notify a controller that the datapath ID has changed. */
373         ofproto_reconnect_controllers(p);
374     }
375 }
376
377 void
378 ofproto_set_controllers(struct ofproto *p,
379                         const struct ofproto_controller *controllers,
380                         size_t n_controllers)
381 {
382     connmgr_set_controllers(p->connmgr, controllers, n_controllers);
383 }
384
385 void
386 ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
387 {
388     connmgr_set_fail_mode(p->connmgr, fail_mode);
389 }
390
391 /* Drops the connections between 'ofproto' and all of its controllers, forcing
392  * them to reconnect. */
393 void
394 ofproto_reconnect_controllers(struct ofproto *ofproto)
395 {
396     connmgr_reconnect(ofproto->connmgr);
397 }
398
399 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
400  * in-band control should guarantee access, in the same way that in-band
401  * control guarantees access to OpenFlow controllers. */
402 void
403 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
404                                   const struct sockaddr_in *extras, size_t n)
405 {
406     connmgr_set_extra_in_band_remotes(ofproto->connmgr, extras, n);
407 }
408
409 /* Sets the OpenFlow queue used by flows set up by in-band control on
410  * 'ofproto' to 'queue_id'.  If 'queue_id' is negative, then in-band control
411  * flows will use the default queue. */
412 void
413 ofproto_set_in_band_queue(struct ofproto *ofproto, int queue_id)
414 {
415     connmgr_set_in_band_queue(ofproto->connmgr, queue_id);
416 }
417
418 /* Sets the number of flows at which eviction from the kernel flow table
419  * will occur. */
420 void
421 ofproto_set_flow_eviction_threshold(struct ofproto *ofproto, unsigned threshold)
422 {
423     if (threshold < OFPROTO_FLOW_EVICTION_THRESHOLD_MIN) {
424         ofproto->flow_eviction_threshold = OFPROTO_FLOW_EVICTION_THRESHOLD_MIN;
425     } else {
426         ofproto->flow_eviction_threshold = threshold;
427     }
428 }
429
430 /* If forward_bpdu is true, the NORMAL action will forward frames with
431  * reserved (e.g. STP) destination Ethernet addresses. if forward_bpdu is false,
432  * the NORMAL action will drop these frames. */
433 void
434 ofproto_set_forward_bpdu(struct ofproto *ofproto, bool forward_bpdu)
435 {
436     bool old_val = ofproto->forward_bpdu;
437     ofproto->forward_bpdu = forward_bpdu;
438     if (old_val != ofproto->forward_bpdu) {
439         if (ofproto->ofproto_class->forward_bpdu_changed) {
440             ofproto->ofproto_class->forward_bpdu_changed(ofproto);
441         }
442     }
443 }
444
445 void
446 ofproto_set_desc(struct ofproto *p,
447                  const char *mfr_desc, const char *hw_desc,
448                  const char *sw_desc, const char *serial_desc,
449                  const char *dp_desc)
450 {
451     struct ofp_desc_stats *ods;
452
453     if (mfr_desc) {
454         if (strlen(mfr_desc) >= sizeof ods->mfr_desc) {
455             VLOG_WARN("truncating mfr_desc, must be less than %zu characters",
456                     sizeof ods->mfr_desc);
457         }
458         free(p->mfr_desc);
459         p->mfr_desc = xstrdup(mfr_desc);
460     }
461     if (hw_desc) {
462         if (strlen(hw_desc) >= sizeof ods->hw_desc) {
463             VLOG_WARN("truncating hw_desc, must be less than %zu characters",
464                     sizeof ods->hw_desc);
465         }
466         free(p->hw_desc);
467         p->hw_desc = xstrdup(hw_desc);
468     }
469     if (sw_desc) {
470         if (strlen(sw_desc) >= sizeof ods->sw_desc) {
471             VLOG_WARN("truncating sw_desc, must be less than %zu characters",
472                     sizeof ods->sw_desc);
473         }
474         free(p->sw_desc);
475         p->sw_desc = xstrdup(sw_desc);
476     }
477     if (serial_desc) {
478         if (strlen(serial_desc) >= sizeof ods->serial_num) {
479             VLOG_WARN("truncating serial_desc, must be less than %zu "
480                     "characters",
481                     sizeof ods->serial_num);
482         }
483         free(p->serial_desc);
484         p->serial_desc = xstrdup(serial_desc);
485     }
486     if (dp_desc) {
487         if (strlen(dp_desc) >= sizeof ods->dp_desc) {
488             VLOG_WARN("truncating dp_desc, must be less than %zu characters",
489                     sizeof ods->dp_desc);
490         }
491         free(p->dp_desc);
492         p->dp_desc = xstrdup(dp_desc);
493     }
494 }
495
496 int
497 ofproto_set_snoops(struct ofproto *ofproto, const struct sset *snoops)
498 {
499     return connmgr_set_snoops(ofproto->connmgr, snoops);
500 }
501
502 int
503 ofproto_set_netflow(struct ofproto *ofproto,
504                     const struct netflow_options *nf_options)
505 {
506     if (nf_options && sset_is_empty(&nf_options->collectors)) {
507         nf_options = NULL;
508     }
509
510     if (ofproto->ofproto_class->set_netflow) {
511         return ofproto->ofproto_class->set_netflow(ofproto, nf_options);
512     } else {
513         return nf_options ? EOPNOTSUPP : 0;
514     }
515 }
516
517 int
518 ofproto_set_sflow(struct ofproto *ofproto,
519                   const struct ofproto_sflow_options *oso)
520 {
521     if (oso && sset_is_empty(&oso->targets)) {
522         oso = NULL;
523     }
524
525     if (ofproto->ofproto_class->set_sflow) {
526         return ofproto->ofproto_class->set_sflow(ofproto, oso);
527     } else {
528         return oso ? EOPNOTSUPP : 0;
529     }
530 }
531 \f
532 /* Connectivity Fault Management configuration. */
533
534 /* Clears the CFM configuration from 'ofp_port' on 'ofproto'. */
535 void
536 ofproto_port_clear_cfm(struct ofproto *ofproto, uint16_t ofp_port)
537 {
538     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
539     if (ofport && ofproto->ofproto_class->set_cfm) {
540         ofproto->ofproto_class->set_cfm(ofport, NULL);
541     }
542 }
543
544 /* Configures connectivity fault management on 'ofp_port' in 'ofproto'.  Takes
545  * basic configuration from the configuration members in 'cfm', and the remote
546  * maintenance point ID from  remote_mpid.  Ignores the statistics members of
547  * 'cfm'.
548  *
549  * This function has no effect if 'ofproto' does not have a port 'ofp_port'. */
550 void
551 ofproto_port_set_cfm(struct ofproto *ofproto, uint16_t ofp_port,
552                      const struct cfm_settings *s)
553 {
554     struct ofport *ofport;
555     int error;
556
557     ofport = ofproto_get_port(ofproto, ofp_port);
558     if (!ofport) {
559         VLOG_WARN("%s: cannot configure CFM on nonexistent port %"PRIu16,
560                   ofproto->name, ofp_port);
561         return;
562     }
563
564     /* XXX: For configuration simplicity, we only support one remote_mpid
565      * outside of the CFM module.  It's not clear if this is the correct long
566      * term solution or not. */
567     error = (ofproto->ofproto_class->set_cfm
568              ? ofproto->ofproto_class->set_cfm(ofport, s)
569              : EOPNOTSUPP);
570     if (error) {
571         VLOG_WARN("%s: CFM configuration on port %"PRIu16" (%s) failed (%s)",
572                   ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
573                   strerror(error));
574     }
575 }
576
577 /* Checks the status of LACP negotiation for 'ofp_port' within ofproto.
578  * Returns 1 if LACP partner information for 'ofp_port' is up-to-date,
579  * 0 if LACP partner information is not current (generally indicating a
580  * connectivity problem), or -1 if LACP is not enabled on 'ofp_port'. */
581 int
582 ofproto_port_is_lacp_current(struct ofproto *ofproto, uint16_t ofp_port)
583 {
584     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
585     return (ofport && ofproto->ofproto_class->port_is_lacp_current
586             ? ofproto->ofproto_class->port_is_lacp_current(ofport)
587             : -1);
588 }
589 \f
590 /* Bundles. */
591
592 /* Registers a "bundle" associated with client data pointer 'aux' in 'ofproto'.
593  * A bundle is the same concept as a Port in OVSDB, that is, it consists of one
594  * or more "slave" devices (Interfaces, in OVSDB) along with a VLAN
595  * configuration plus, if there is more than one slave, a bonding
596  * configuration.
597  *
598  * If 'aux' is already registered then this function updates its configuration
599  * to 's'.  Otherwise, this function registers a new bundle.
600  *
601  * Bundles only affect the NXAST_AUTOPATH action and output to the OFPP_NORMAL
602  * port. */
603 int
604 ofproto_bundle_register(struct ofproto *ofproto, void *aux,
605                         const struct ofproto_bundle_settings *s)
606 {
607     return (ofproto->ofproto_class->bundle_set
608             ? ofproto->ofproto_class->bundle_set(ofproto, aux, s)
609             : EOPNOTSUPP);
610 }
611
612 /* Unregisters the bundle registered on 'ofproto' with auxiliary data 'aux'.
613  * If no such bundle has been registered, this has no effect. */
614 int
615 ofproto_bundle_unregister(struct ofproto *ofproto, void *aux)
616 {
617     return ofproto_bundle_register(ofproto, aux, NULL);
618 }
619
620 \f
621 /* Registers a mirror associated with client data pointer 'aux' in 'ofproto'.
622  * If 'aux' is already registered then this function updates its configuration
623  * to 's'.  Otherwise, this function registers a new mirror.
624  *
625  * Mirrors affect only the treatment of packets output to the OFPP_NORMAL
626  * port.  */
627 int
628 ofproto_mirror_register(struct ofproto *ofproto, void *aux,
629                         const struct ofproto_mirror_settings *s)
630 {
631     return (ofproto->ofproto_class->mirror_set
632             ? ofproto->ofproto_class->mirror_set(ofproto, aux, s)
633             : EOPNOTSUPP);
634 }
635
636 /* Unregisters the mirror registered on 'ofproto' with auxiliary data 'aux'.
637  * If no mirror has been registered, this has no effect. */
638 int
639 ofproto_mirror_unregister(struct ofproto *ofproto, void *aux)
640 {
641     return ofproto_mirror_register(ofproto, aux, NULL);
642 }
643
644 /* Configures the VLANs whose bits are set to 1 in 'flood_vlans' as VLANs on
645  * which all packets are flooded, instead of using MAC learning.  If
646  * 'flood_vlans' is NULL, then MAC learning applies to all VLANs.
647  *
648  * Flood VLANs affect only the treatment of packets output to the OFPP_NORMAL
649  * port. */
650 int
651 ofproto_set_flood_vlans(struct ofproto *ofproto, unsigned long *flood_vlans)
652 {
653     return (ofproto->ofproto_class->set_flood_vlans
654             ? ofproto->ofproto_class->set_flood_vlans(ofproto, flood_vlans)
655             : EOPNOTSUPP);
656 }
657
658 /* Returns true if 'aux' is a registered bundle that is currently in use as the
659  * output for a mirror. */
660 bool
661 ofproto_is_mirror_output_bundle(struct ofproto *ofproto, void *aux)
662 {
663     return (ofproto->ofproto_class->is_mirror_output_bundle
664             ? ofproto->ofproto_class->is_mirror_output_bundle(ofproto, aux)
665             : false);
666 }
667 \f
668 bool
669 ofproto_has_snoops(const struct ofproto *ofproto)
670 {
671     return connmgr_has_snoops(ofproto->connmgr);
672 }
673
674 void
675 ofproto_get_snoops(const struct ofproto *ofproto, struct sset *snoops)
676 {
677     connmgr_get_snoops(ofproto->connmgr, snoops);
678 }
679
680 static void
681 ofproto_flush__(struct ofproto *ofproto)
682 {
683     struct classifier *table;
684     struct ofopgroup *group;
685
686     if (ofproto->ofproto_class->flush) {
687         ofproto->ofproto_class->flush(ofproto);
688     }
689
690     group = ofopgroup_create_unattached(ofproto);
691     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
692         struct rule *rule, *next_rule;
693         struct cls_cursor cursor;
694
695         cls_cursor_init(&cursor, table, NULL);
696         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
697             if (!rule->pending) {
698                 ofoperation_create(group, rule, OFOPERATION_DELETE);
699                 classifier_remove(table, &rule->cr);
700                 ofproto->ofproto_class->rule_destruct(rule);
701             }
702         }
703     }
704     ofopgroup_submit(group);
705 }
706
707 static void
708 ofproto_destroy__(struct ofproto *ofproto)
709 {
710     struct classifier *table;
711
712     assert(list_is_empty(&ofproto->pending));
713     assert(!ofproto->n_pending);
714
715     connmgr_destroy(ofproto->connmgr);
716
717     hmap_remove(&all_ofprotos, &ofproto->hmap_node);
718     free(ofproto->name);
719     free(ofproto->type);
720     free(ofproto->mfr_desc);
721     free(ofproto->hw_desc);
722     free(ofproto->sw_desc);
723     free(ofproto->serial_desc);
724     free(ofproto->dp_desc);
725     hmap_destroy(&ofproto->ports);
726     shash_destroy(&ofproto->port_by_name);
727
728     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
729         assert(classifier_is_empty(table));
730         classifier_destroy(table);
731     }
732     free(ofproto->tables);
733
734     hmap_destroy(&ofproto->deletions);
735
736     ofproto->ofproto_class->dealloc(ofproto);
737 }
738
739 void
740 ofproto_destroy(struct ofproto *p)
741 {
742     struct ofport *ofport, *next_ofport;
743
744     if (!p) {
745         return;
746     }
747
748     ofproto_flush__(p);
749     HMAP_FOR_EACH_SAFE (ofport, next_ofport, hmap_node, &p->ports) {
750         ofport_destroy(ofport);
751     }
752
753     p->ofproto_class->destruct(p);
754     ofproto_destroy__(p);
755 }
756
757 /* Destroys the datapath with the respective 'name' and 'type'.  With the Linux
758  * kernel datapath, for example, this destroys the datapath in the kernel, and
759  * with the netdev-based datapath, it tears down the data structures that
760  * represent the datapath.
761  *
762  * The datapath should not be currently open as an ofproto. */
763 int
764 ofproto_delete(const char *name, const char *type)
765 {
766     const struct ofproto_class *class = ofproto_class_find__(type);
767     return (!class ? EAFNOSUPPORT
768             : !class->del ? EACCES
769             : class->del(type, name));
770 }
771
772 static void
773 process_port_change(struct ofproto *ofproto, int error, char *devname)
774 {
775     if (error == ENOBUFS) {
776         reinit_ports(ofproto);
777     } else if (!error) {
778         update_port(ofproto, devname);
779         free(devname);
780     }
781 }
782
783 int
784 ofproto_run(struct ofproto *p)
785 {
786     struct ofport *ofport;
787     char *devname;
788     int error;
789
790     error = p->ofproto_class->run(p);
791     if (error == ENODEV) {
792         /* Someone destroyed the datapath behind our back.  The caller
793          * better destroy us and give up, because we're just going to
794          * spin from here on out. */
795         static struct vlog_rate_limit rl2 = VLOG_RATE_LIMIT_INIT(1, 5);
796         VLOG_ERR_RL(&rl2, "%s: datapath was destroyed externally",
797                     p->name);
798         return ENODEV;
799     }
800
801     if (p->ofproto_class->port_poll) {
802         while ((error = p->ofproto_class->port_poll(p, &devname)) != EAGAIN) {
803             process_port_change(p, error, devname);
804         }
805     }
806
807     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
808         unsigned int change_seq = netdev_change_seq(ofport->netdev);
809         if (ofport->change_seq != change_seq) {
810             ofport->change_seq = change_seq;
811             update_port(p, netdev_get_name(ofport->netdev));
812         }
813     }
814
815
816     switch (p->state) {
817     case S_OPENFLOW:
818         connmgr_run(p->connmgr, handle_openflow);
819         break;
820
821     case S_FLUSH:
822         connmgr_run(p->connmgr, NULL);
823         ofproto_flush__(p);
824         if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
825             connmgr_flushed(p->connmgr);
826             p->state = S_OPENFLOW;
827         }
828         break;
829
830     default:
831         NOT_REACHED();
832     }
833
834     return 0;
835 }
836
837 void
838 ofproto_wait(struct ofproto *p)
839 {
840     struct ofport *ofport;
841
842     p->ofproto_class->wait(p);
843     if (p->ofproto_class->port_poll_wait) {
844         p->ofproto_class->port_poll_wait(p);
845     }
846
847     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
848         if (ofport->change_seq != netdev_change_seq(ofport->netdev)) {
849             poll_immediate_wake();
850         }
851     }
852
853     switch (p->state) {
854     case S_OPENFLOW:
855         connmgr_wait(p->connmgr, true);
856         break;
857
858     case S_FLUSH:
859         connmgr_wait(p->connmgr, false);
860         if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
861             poll_immediate_wake();
862         }
863         break;
864     }
865 }
866
867 bool
868 ofproto_is_alive(const struct ofproto *p)
869 {
870     return connmgr_has_controllers(p->connmgr);
871 }
872
873 void
874 ofproto_get_ofproto_controller_info(const struct ofproto *ofproto,
875                                     struct shash *info)
876 {
877     connmgr_get_controller_info(ofproto->connmgr, info);
878 }
879
880 void
881 ofproto_free_ofproto_controller_info(struct shash *info)
882 {
883     connmgr_free_controller_info(info);
884 }
885
886 /* Makes a deep copy of 'old' into 'port'. */
887 void
888 ofproto_port_clone(struct ofproto_port *port, const struct ofproto_port *old)
889 {
890     port->name = xstrdup(old->name);
891     port->type = xstrdup(old->type);
892     port->ofp_port = old->ofp_port;
893 }
894
895 /* Frees memory allocated to members of 'ofproto_port'.
896  *
897  * Do not call this function on an ofproto_port obtained from
898  * ofproto_port_dump_next(): that function retains ownership of the data in the
899  * ofproto_port. */
900 void
901 ofproto_port_destroy(struct ofproto_port *ofproto_port)
902 {
903     free(ofproto_port->name);
904     free(ofproto_port->type);
905 }
906
907 /* Initializes 'dump' to begin dumping the ports in an ofproto.
908  *
909  * This function provides no status indication.  An error status for the entire
910  * dump operation is provided when it is completed by calling
911  * ofproto_port_dump_done().
912  */
913 void
914 ofproto_port_dump_start(struct ofproto_port_dump *dump,
915                         const struct ofproto *ofproto)
916 {
917     dump->ofproto = ofproto;
918     dump->error = ofproto->ofproto_class->port_dump_start(ofproto,
919                                                           &dump->state);
920 }
921
922 /* Attempts to retrieve another port from 'dump', which must have been created
923  * with ofproto_port_dump_start().  On success, stores a new ofproto_port into
924  * 'port' and returns true.  On failure, returns false.
925  *
926  * Failure might indicate an actual error or merely that the last port has been
927  * dumped.  An error status for the entire dump operation is provided when it
928  * is completed by calling ofproto_port_dump_done().
929  *
930  * The ofproto owns the data stored in 'port'.  It will remain valid until at
931  * least the next time 'dump' is passed to ofproto_port_dump_next() or
932  * ofproto_port_dump_done(). */
933 bool
934 ofproto_port_dump_next(struct ofproto_port_dump *dump,
935                        struct ofproto_port *port)
936 {
937     const struct ofproto *ofproto = dump->ofproto;
938
939     if (dump->error) {
940         return false;
941     }
942
943     dump->error = ofproto->ofproto_class->port_dump_next(ofproto, dump->state,
944                                                          port);
945     if (dump->error) {
946         ofproto->ofproto_class->port_dump_done(ofproto, dump->state);
947         return false;
948     }
949     return true;
950 }
951
952 /* Completes port table dump operation 'dump', which must have been created
953  * with ofproto_port_dump_start().  Returns 0 if the dump operation was
954  * error-free, otherwise a positive errno value describing the problem. */
955 int
956 ofproto_port_dump_done(struct ofproto_port_dump *dump)
957 {
958     const struct ofproto *ofproto = dump->ofproto;
959     if (!dump->error) {
960         dump->error = ofproto->ofproto_class->port_dump_done(ofproto,
961                                                              dump->state);
962     }
963     return dump->error == EOF ? 0 : dump->error;
964 }
965
966 /* Attempts to add 'netdev' as a port on 'ofproto'.  If successful, returns 0
967  * and sets '*ofp_portp' to the new port's OpenFlow port number (if 'ofp_portp'
968  * is non-null).  On failure, returns a positive errno value and sets
969  * '*ofp_portp' to OFPP_NONE (if 'ofp_portp' is non-null). */
970 int
971 ofproto_port_add(struct ofproto *ofproto, struct netdev *netdev,
972                  uint16_t *ofp_portp)
973 {
974     uint16_t ofp_port;
975     int error;
976
977     error = ofproto->ofproto_class->port_add(ofproto, netdev, &ofp_port);
978     if (!error) {
979         update_port(ofproto, netdev_get_name(netdev));
980     }
981     if (ofp_portp) {
982         *ofp_portp = error ? OFPP_NONE : ofp_port;
983     }
984     return error;
985 }
986
987 /* Looks up a port named 'devname' in 'ofproto'.  On success, returns 0 and
988  * initializes '*port' appropriately; on failure, returns a positive errno
989  * value.
990  *
991  * The caller owns the data in 'ofproto_port' and must free it with
992  * ofproto_port_destroy() when it is no longer needed. */
993 int
994 ofproto_port_query_by_name(const struct ofproto *ofproto, const char *devname,
995                            struct ofproto_port *port)
996 {
997     int error;
998
999     error = ofproto->ofproto_class->port_query_by_name(ofproto, devname, port);
1000     if (error) {
1001         memset(port, 0, sizeof *port);
1002     }
1003     return error;
1004 }
1005
1006 /* Deletes port number 'ofp_port' from the datapath for 'ofproto'.
1007  * Returns 0 if successful, otherwise a positive errno. */
1008 int
1009 ofproto_port_del(struct ofproto *ofproto, uint16_t ofp_port)
1010 {
1011     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1012     const char *name = ofport ? netdev_get_name(ofport->netdev) : "<unknown>";
1013     int error;
1014
1015     error = ofproto->ofproto_class->port_del(ofproto, ofp_port);
1016     if (!error && ofport) {
1017         /* 'name' is the netdev's name and update_port() is going to close the
1018          * netdev.  Just in case update_port() refers to 'name' after it
1019          * destroys 'ofport', make a copy of it around the update_port()
1020          * call. */
1021         char *devname = xstrdup(name);
1022         update_port(ofproto, devname);
1023         free(devname);
1024     }
1025     return error;
1026 }
1027
1028 /* Adds a flow to OpenFlow flow table 0 in 'p' that matches 'cls_rule' and
1029  * performs the 'n_actions' actions in 'actions'.  The new flow will not
1030  * timeout.
1031  *
1032  * If cls_rule->priority is in the range of priorities supported by OpenFlow
1033  * (0...65535, inclusive) then the flow will be visible to OpenFlow
1034  * controllers; otherwise, it will be hidden.
1035  *
1036  * The caller retains ownership of 'cls_rule' and 'actions'.
1037  *
1038  * This is a helper function for in-band control and fail-open. */
1039 void
1040 ofproto_add_flow(struct ofproto *ofproto, const struct cls_rule *cls_rule,
1041                  const union ofp_action *actions, size_t n_actions)
1042 {
1043     const struct rule *rule;
1044
1045     rule = rule_from_cls_rule(classifier_find_rule_exactly(
1046                                     &ofproto->tables[0], cls_rule));
1047     if (!rule || !ofputil_actions_equal(rule->actions, rule->n_actions,
1048                                         actions, n_actions)) {
1049         struct ofputil_flow_mod fm;
1050
1051         memset(&fm, 0, sizeof fm);
1052         fm.cr = *cls_rule;
1053         fm.buffer_id = UINT32_MAX;
1054         fm.actions = (union ofp_action *) actions;
1055         fm.n_actions = n_actions;
1056         add_flow(ofproto, NULL, &fm, NULL);
1057     }
1058 }
1059
1060 /* Executes the flow modification specified in 'fm'.  Returns 0 on success, an
1061  * OpenFlow error code as encoded by ofp_mkerr() on failure, or
1062  * OFPROTO_POSTPONE if the operation cannot be initiated now but may be retried
1063  * later.
1064  *
1065  * This is a helper function for in-band control and fail-open. */
1066 int
1067 ofproto_flow_mod(struct ofproto *ofproto, const struct ofputil_flow_mod *fm)
1068 {
1069     return handle_flow_mod__(ofproto, NULL, fm, NULL);
1070 }
1071
1072 /* Searches for a rule with matching criteria exactly equal to 'target' in
1073  * ofproto's table 0 and, if it finds one, deletes it.
1074  *
1075  * This is a helper function for in-band control and fail-open. */
1076 bool
1077 ofproto_delete_flow(struct ofproto *ofproto, const struct cls_rule *target)
1078 {
1079     struct rule *rule;
1080
1081     rule = rule_from_cls_rule(classifier_find_rule_exactly(
1082                                   &ofproto->tables[0], target));
1083     if (!rule) {
1084         /* No such rule -> success. */
1085         return true;
1086     } else if (rule->pending) {
1087         /* An operation on the rule is already pending -> failure.
1088          * Caller must retry later if it's important. */
1089         return false;
1090     } else {
1091         /* Initiate deletion -> success. */
1092         struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
1093         ofoperation_create(group, rule, OFOPERATION_DELETE);
1094         classifier_remove(&ofproto->tables[rule->table_id], &rule->cr);
1095         rule->ofproto->ofproto_class->rule_destruct(rule);
1096         ofopgroup_submit(group);
1097         return true;
1098     }
1099
1100 }
1101
1102 /* Starts the process of deleting all of the flows from all of ofproto's flow
1103  * tables and then reintroducing the flows required by in-band control and
1104  * fail-open.  The process will complete in a later call to ofproto_run(). */
1105 void
1106 ofproto_flush_flows(struct ofproto *ofproto)
1107 {
1108     COVERAGE_INC(ofproto_flush);
1109     ofproto->state = S_FLUSH;
1110 }
1111 \f
1112 static void
1113 reinit_ports(struct ofproto *p)
1114 {
1115     struct ofproto_port_dump dump;
1116     struct sset devnames;
1117     struct ofport *ofport;
1118     struct ofproto_port ofproto_port;
1119     const char *devname;
1120
1121     COVERAGE_INC(ofproto_reinit_ports);
1122
1123     sset_init(&devnames);
1124     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1125         sset_add(&devnames, netdev_get_name(ofport->netdev));
1126     }
1127     OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
1128         sset_add(&devnames, ofproto_port.name);
1129     }
1130
1131     SSET_FOR_EACH (devname, &devnames) {
1132         update_port(p, devname);
1133     }
1134     sset_destroy(&devnames);
1135 }
1136
1137 /* Opens and returns a netdev for 'ofproto_port', or a null pointer if the
1138  * netdev cannot be opened.  On success, also fills in 'opp'.  */
1139 static struct netdev *
1140 ofport_open(const struct ofproto_port *ofproto_port, struct ofp_phy_port *opp)
1141 {
1142     uint32_t curr, advertised, supported, peer;
1143     enum netdev_flags flags;
1144     struct netdev *netdev;
1145     int error;
1146
1147     error = netdev_open(ofproto_port->name, ofproto_port->type, &netdev);
1148     if (error) {
1149         VLOG_WARN_RL(&rl, "ignoring port %s (%"PRIu16") because netdev %s "
1150                      "cannot be opened (%s)",
1151                      ofproto_port->name, ofproto_port->ofp_port,
1152                      ofproto_port->name, strerror(error));
1153         return NULL;
1154     }
1155
1156     netdev_get_flags(netdev, &flags);
1157     netdev_get_features(netdev, &curr, &advertised, &supported, &peer);
1158
1159     opp->port_no = htons(ofproto_port->ofp_port);
1160     netdev_get_etheraddr(netdev, opp->hw_addr);
1161     ovs_strzcpy(opp->name, ofproto_port->name, sizeof opp->name);
1162     opp->config = flags & NETDEV_UP ? 0 : htonl(OFPPC_PORT_DOWN);
1163     opp->state = netdev_get_carrier(netdev) ? 0 : htonl(OFPPS_LINK_DOWN);
1164     opp->curr = htonl(curr);
1165     opp->advertised = htonl(advertised);
1166     opp->supported = htonl(supported);
1167     opp->peer = htonl(peer);
1168
1169     return netdev;
1170 }
1171
1172 /* Returns true if most fields of 'a' and 'b' are equal.  Differences in name,
1173  * port number, and 'config' bits other than OFPPC_PORT_DOWN are
1174  * disregarded. */
1175 static bool
1176 ofport_equal(const struct ofp_phy_port *a, const struct ofp_phy_port *b)
1177 {
1178     BUILD_ASSERT_DECL(sizeof *a == 48); /* Detect ofp_phy_port changes. */
1179     return (!memcmp(a->hw_addr, b->hw_addr, sizeof a->hw_addr)
1180             && a->state == b->state
1181             && !((a->config ^ b->config) & htonl(OFPPC_PORT_DOWN))
1182             && a->curr == b->curr
1183             && a->advertised == b->advertised
1184             && a->supported == b->supported
1185             && a->peer == b->peer);
1186 }
1187
1188 /* Adds an ofport to 'p' initialized based on the given 'netdev' and 'opp'.
1189  * The caller must ensure that 'p' does not have a conflicting ofport (that is,
1190  * one with the same name or port number). */
1191 static void
1192 ofport_install(struct ofproto *p,
1193                struct netdev *netdev, const struct ofp_phy_port *opp)
1194 {
1195     const char *netdev_name = netdev_get_name(netdev);
1196     struct ofport *ofport;
1197     int dev_mtu;
1198     int error;
1199
1200     /* Create ofport. */
1201     ofport = p->ofproto_class->port_alloc();
1202     if (!ofport) {
1203         error = ENOMEM;
1204         goto error;
1205     }
1206     ofport->ofproto = p;
1207     ofport->netdev = netdev;
1208     ofport->change_seq = netdev_change_seq(netdev);
1209     ofport->opp = *opp;
1210     ofport->ofp_port = ntohs(opp->port_no);
1211
1212     /* Add port to 'p'. */
1213     hmap_insert(&p->ports, &ofport->hmap_node, hash_int(ofport->ofp_port, 0));
1214     shash_add(&p->port_by_name, netdev_name, ofport);
1215
1216     if (!netdev_get_mtu(netdev, &dev_mtu)) {
1217         set_internal_devs_mtu(p);
1218         ofport->mtu = dev_mtu;
1219     } else {
1220         ofport->mtu = 0;
1221     }
1222
1223     /* Let the ofproto_class initialize its private data. */
1224     error = p->ofproto_class->port_construct(ofport);
1225     if (error) {
1226         goto error;
1227     }
1228     connmgr_send_port_status(p->connmgr, opp, OFPPR_ADD);
1229     return;
1230
1231 error:
1232     VLOG_WARN_RL(&rl, "%s: could not add port %s (%s)",
1233                  p->name, netdev_name, strerror(error));
1234     if (ofport) {
1235         ofport_destroy__(ofport);
1236     } else {
1237         netdev_close(netdev);
1238     }
1239 }
1240
1241 /* Removes 'ofport' from 'p' and destroys it. */
1242 static void
1243 ofport_remove(struct ofport *ofport)
1244 {
1245     connmgr_send_port_status(ofport->ofproto->connmgr, &ofport->opp,
1246                              OFPPR_DELETE);
1247     ofport_destroy(ofport);
1248 }
1249
1250 /* If 'ofproto' contains an ofport named 'name', removes it from 'ofproto' and
1251  * destroys it. */
1252 static void
1253 ofport_remove_with_name(struct ofproto *ofproto, const char *name)
1254 {
1255     struct ofport *port = shash_find_data(&ofproto->port_by_name, name);
1256     if (port) {
1257         ofport_remove(port);
1258     }
1259 }
1260
1261 /* Updates 'port' within 'ofproto' with the new 'netdev' and 'opp'.
1262  *
1263  * Does not handle a name or port number change.  The caller must implement
1264  * such a change as a delete followed by an add.  */
1265 static void
1266 ofport_modified(struct ofport *port, struct ofp_phy_port *opp)
1267 {
1268     memcpy(port->opp.hw_addr, opp->hw_addr, ETH_ADDR_LEN);
1269     port->opp.config = ((port->opp.config & ~htonl(OFPPC_PORT_DOWN))
1270                         | (opp->config & htonl(OFPPC_PORT_DOWN)));
1271     port->opp.state = opp->state;
1272     port->opp.curr = opp->curr;
1273     port->opp.advertised = opp->advertised;
1274     port->opp.supported = opp->supported;
1275     port->opp.peer = opp->peer;
1276
1277     connmgr_send_port_status(port->ofproto->connmgr, &port->opp, OFPPR_MODIFY);
1278 }
1279
1280 void
1281 ofproto_port_unregister(struct ofproto *ofproto, uint16_t ofp_port)
1282 {
1283     struct ofport *port = ofproto_get_port(ofproto, ofp_port);
1284     if (port) {
1285         if (port->ofproto->ofproto_class->set_cfm) {
1286             port->ofproto->ofproto_class->set_cfm(port, NULL);
1287         }
1288         if (port->ofproto->ofproto_class->bundle_remove) {
1289             port->ofproto->ofproto_class->bundle_remove(port);
1290         }
1291     }
1292 }
1293
1294 static void
1295 ofport_destroy__(struct ofport *port)
1296 {
1297     struct ofproto *ofproto = port->ofproto;
1298     const char *name = netdev_get_name(port->netdev);
1299
1300     hmap_remove(&ofproto->ports, &port->hmap_node);
1301     shash_delete(&ofproto->port_by_name,
1302                  shash_find(&ofproto->port_by_name, name));
1303
1304     netdev_close(port->netdev);
1305     ofproto->ofproto_class->port_dealloc(port);
1306 }
1307
1308 static void
1309 ofport_destroy(struct ofport *port)
1310 {
1311     if (port) {
1312         port->ofproto->ofproto_class->port_destruct(port);
1313         ofport_destroy__(port);
1314      }
1315 }
1316
1317 struct ofport *
1318 ofproto_get_port(const struct ofproto *ofproto, uint16_t ofp_port)
1319 {
1320     struct ofport *port;
1321
1322     HMAP_FOR_EACH_IN_BUCKET (port, hmap_node,
1323                              hash_int(ofp_port, 0), &ofproto->ports) {
1324         if (port->ofp_port == ofp_port) {
1325             return port;
1326         }
1327     }
1328     return NULL;
1329 }
1330
1331 static void
1332 update_port(struct ofproto *ofproto, const char *name)
1333 {
1334     struct ofproto_port ofproto_port;
1335     struct ofp_phy_port opp;
1336     struct netdev *netdev;
1337     struct ofport *port;
1338
1339     COVERAGE_INC(ofproto_update_port);
1340
1341     /* Fetch 'name''s location and properties from the datapath. */
1342     netdev = (!ofproto_port_query_by_name(ofproto, name, &ofproto_port)
1343               ? ofport_open(&ofproto_port, &opp)
1344               : NULL);
1345     if (netdev) {
1346         port = ofproto_get_port(ofproto, ofproto_port.ofp_port);
1347         if (port && !strcmp(netdev_get_name(port->netdev), name)) {
1348             struct netdev *old_netdev = port->netdev;
1349             int dev_mtu;
1350
1351             /* 'name' hasn't changed location.  Any properties changed? */
1352             if (!ofport_equal(&port->opp, &opp)) {
1353                 ofport_modified(port, &opp);
1354             }
1355
1356             /* If this is a non-internal port and the MTU changed, check
1357              * if the datapath's MTU needs to be updated. */
1358             if (strcmp(netdev_get_type(netdev), "internal")
1359                     && !netdev_get_mtu(netdev, &dev_mtu)
1360                     && port->mtu != dev_mtu) {
1361                 set_internal_devs_mtu(ofproto);
1362                 port->mtu = dev_mtu;
1363             }
1364
1365             /* Install the newly opened netdev in case it has changed.
1366              * Don't close the old netdev yet in case port_modified has to
1367              * remove a retained reference to it.*/
1368             port->netdev = netdev;
1369             port->change_seq = netdev_change_seq(netdev);
1370
1371             if (port->ofproto->ofproto_class->port_modified) {
1372                 port->ofproto->ofproto_class->port_modified(port);
1373             }
1374
1375             netdev_close(old_netdev);
1376         } else {
1377             /* If 'port' is nonnull then its name differs from 'name' and thus
1378              * we should delete it.  If we think there's a port named 'name'
1379              * then its port number must be wrong now so delete it too. */
1380             if (port) {
1381                 ofport_remove(port);
1382             }
1383             ofport_remove_with_name(ofproto, name);
1384             ofport_install(ofproto, netdev, &opp);
1385         }
1386     } else {
1387         /* Any port named 'name' is gone now. */
1388         ofport_remove_with_name(ofproto, name);
1389     }
1390     ofproto_port_destroy(&ofproto_port);
1391 }
1392
1393 static int
1394 init_ports(struct ofproto *p)
1395 {
1396     struct ofproto_port_dump dump;
1397     struct ofproto_port ofproto_port;
1398
1399     OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
1400         uint16_t ofp_port = ofproto_port.ofp_port;
1401         if (ofproto_get_port(p, ofp_port)) {
1402             VLOG_WARN_RL(&rl, "ignoring duplicate port %"PRIu16" in datapath",
1403                          ofp_port);
1404         } else if (shash_find(&p->port_by_name, ofproto_port.name)) {
1405             VLOG_WARN_RL(&rl, "ignoring duplicate device %s in datapath",
1406                          ofproto_port.name);
1407         } else {
1408             struct ofp_phy_port opp;
1409             struct netdev *netdev;
1410
1411             netdev = ofport_open(&ofproto_port, &opp);
1412             if (netdev) {
1413                 ofport_install(p, netdev, &opp);
1414             }
1415         }
1416     }
1417
1418     return 0;
1419 }
1420
1421 /* Find the minimum MTU of all non-datapath devices attached to 'p'.
1422  * Returns ETH_PAYLOAD_MAX or the minimum of the ports. */
1423 static int
1424 find_min_mtu(struct ofproto *p)
1425 {
1426     struct ofport *ofport;
1427     int mtu = 0;
1428
1429     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1430         struct netdev *netdev = ofport->netdev;
1431         int dev_mtu;
1432
1433         /* Skip any internal ports, since that's what we're trying to
1434          * set. */
1435         if (!strcmp(netdev_get_type(netdev), "internal")) {
1436             continue;
1437         }
1438
1439         if (netdev_get_mtu(netdev, &dev_mtu)) {
1440             continue;
1441         }
1442         if (!mtu || dev_mtu < mtu) {
1443             mtu = dev_mtu;
1444         }
1445     }
1446
1447     return mtu ? mtu: ETH_PAYLOAD_MAX;
1448 }
1449
1450 /* Set the MTU of all datapath devices on 'p' to the minimum of the
1451  * non-datapath ports. */
1452 static void
1453 set_internal_devs_mtu(struct ofproto *p)
1454 {
1455     struct ofport *ofport;
1456     int mtu = find_min_mtu(p);
1457
1458     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1459         struct netdev *netdev = ofport->netdev;
1460
1461         if (!strcmp(netdev_get_type(netdev), "internal")) {
1462             netdev_set_mtu(netdev, mtu);
1463         }
1464     }
1465 }
1466 \f
1467 static void
1468 ofproto_rule_destroy__(struct rule *rule)
1469 {
1470     free(rule->actions);
1471     rule->ofproto->ofproto_class->rule_dealloc(rule);
1472 }
1473
1474 /* This function allows an ofproto implementation to destroy any rules that
1475  * remain when its ->destruct() function is called.  The caller must have
1476  * already uninitialized any derived members of 'rule' (step 5 described in the
1477  * large comment in ofproto/ofproto-provider.h titled "Life Cycle").
1478  * This function implements steps 6 and 7.
1479  *
1480  * This function should only be called from an ofproto implementation's
1481  * ->destruct() function.  It is not suitable elsewhere. */
1482 void
1483 ofproto_rule_destroy(struct rule *rule)
1484 {
1485     assert(!rule->pending);
1486     classifier_remove(&rule->ofproto->tables[rule->table_id], &rule->cr);
1487     ofproto_rule_destroy__(rule);
1488 }
1489
1490 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
1491  * that outputs to 'out_port' (output to OFPP_FLOOD and OFPP_ALL doesn't
1492  * count). */
1493 static bool
1494 rule_has_out_port(const struct rule *rule, uint16_t out_port)
1495 {
1496     const union ofp_action *oa;
1497     size_t left;
1498
1499     if (out_port == OFPP_NONE) {
1500         return true;
1501     }
1502     OFPUTIL_ACTION_FOR_EACH_UNSAFE (oa, left, rule->actions, rule->n_actions) {
1503         if (action_outputs_to_port(oa, htons(out_port))) {
1504             return true;
1505         }
1506     }
1507     return false;
1508 }
1509
1510 /* Executes the actions indicated by 'rule' on 'packet' and credits 'rule''s
1511  * statistics appropriately.  'packet' must have at least sizeof(struct
1512  * ofp_packet_in) bytes of headroom.
1513  *
1514  * 'packet' doesn't necessarily have to match 'rule'.  'rule' will be credited
1515  * with statistics for 'packet' either way.
1516  *
1517  * Takes ownership of 'packet'. */
1518 static int
1519 rule_execute(struct rule *rule, uint16_t in_port, struct ofpbuf *packet)
1520 {
1521     struct flow flow;
1522
1523     assert(ofpbuf_headroom(packet) >= sizeof(struct ofp_packet_in));
1524
1525     flow_extract(packet, 0, in_port, &flow);
1526     return rule->ofproto->ofproto_class->rule_execute(rule, &flow, packet);
1527 }
1528
1529 /* Returns true if 'rule' should be hidden from the controller.
1530  *
1531  * Rules with priority higher than UINT16_MAX are set up by ofproto itself
1532  * (e.g. by in-band control) and are intentionally hidden from the
1533  * controller. */
1534 static bool
1535 rule_is_hidden(const struct rule *rule)
1536 {
1537     return rule->cr.priority > UINT16_MAX;
1538 }
1539 \f
1540 static int
1541 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
1542 {
1543     ofconn_send_reply(ofconn, make_echo_reply(oh));
1544     return 0;
1545 }
1546
1547 static int
1548 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
1549 {
1550     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
1551     struct ofp_switch_features *osf;
1552     struct ofpbuf *buf;
1553     struct ofport *port;
1554     bool arp_match_ip;
1555     uint32_t actions;
1556
1557     ofproto->ofproto_class->get_features(ofproto, &arp_match_ip, &actions);
1558     assert(actions & (1 << OFPAT_OUTPUT)); /* sanity check */
1559
1560     osf = make_openflow_xid(sizeof *osf, OFPT_FEATURES_REPLY, oh->xid, &buf);
1561     osf->datapath_id = htonll(ofproto->datapath_id);
1562     osf->n_buffers = htonl(pktbuf_capacity());
1563     osf->n_tables = ofproto->n_tables;
1564     osf->capabilities = htonl(OFPC_FLOW_STATS | OFPC_TABLE_STATS |
1565                               OFPC_PORT_STATS);
1566     if (arp_match_ip) {
1567         osf->capabilities |= htonl(OFPC_ARP_MATCH_IP);
1568     }
1569     osf->actions = htonl(actions);
1570
1571     HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
1572         ofpbuf_put(buf, &port->opp, sizeof port->opp);
1573     }
1574
1575     ofconn_send_reply(ofconn, buf);
1576     return 0;
1577 }
1578
1579 static int
1580 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
1581 {
1582     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
1583     struct ofpbuf *buf;
1584     struct ofp_switch_config *osc;
1585     uint16_t flags;
1586     bool drop_frags;
1587
1588     /* Figure out flags. */
1589     drop_frags = ofproto->ofproto_class->get_drop_frags(ofproto);
1590     flags = drop_frags ? OFPC_FRAG_DROP : OFPC_FRAG_NORMAL;
1591
1592     /* Send reply. */
1593     osc = make_openflow_xid(sizeof *osc, OFPT_GET_CONFIG_REPLY, oh->xid, &buf);
1594     osc->flags = htons(flags);
1595     osc->miss_send_len = htons(ofconn_get_miss_send_len(ofconn));
1596     ofconn_send_reply(ofconn, buf);
1597
1598     return 0;
1599 }
1600
1601 static int
1602 handle_set_config(struct ofconn *ofconn, const struct ofp_switch_config *osc)
1603 {
1604     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
1605     uint16_t flags = ntohs(osc->flags);
1606
1607     if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
1608         && ofconn_get_role(ofconn) != NX_ROLE_SLAVE) {
1609         switch (flags & OFPC_FRAG_MASK) {
1610         case OFPC_FRAG_NORMAL:
1611             ofproto->ofproto_class->set_drop_frags(ofproto, false);
1612             break;
1613         case OFPC_FRAG_DROP:
1614             ofproto->ofproto_class->set_drop_frags(ofproto, true);
1615             break;
1616         default:
1617             VLOG_WARN_RL(&rl, "requested bad fragment mode (flags=%"PRIx16")",
1618                          osc->flags);
1619             break;
1620         }
1621     }
1622
1623     ofconn_set_miss_send_len(ofconn, ntohs(osc->miss_send_len));
1624
1625     return 0;
1626 }
1627
1628 /* Checks whether 'ofconn' is a slave controller.  If so, returns an OpenFlow
1629  * error message code (composed with ofp_mkerr()) for the caller to propagate
1630  * upward.  Otherwise, returns 0.
1631  *
1632  * The log message mentions 'msg_type'. */
1633 static int
1634 reject_slave_controller(struct ofconn *ofconn, const char *msg_type)
1635 {
1636     if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
1637         && ofconn_get_role(ofconn) == NX_ROLE_SLAVE) {
1638         static struct vlog_rate_limit perm_rl = VLOG_RATE_LIMIT_INIT(1, 5);
1639         VLOG_WARN_RL(&perm_rl, "rejecting %s message from slave controller",
1640                      msg_type);
1641
1642         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
1643     } else {
1644         return 0;
1645     }
1646 }
1647
1648 static int
1649 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
1650 {
1651     struct ofproto *p = ofconn_get_ofproto(ofconn);
1652     struct ofp_packet_out *opo;
1653     struct ofpbuf payload, *buffer;
1654     union ofp_action *ofp_actions;
1655     struct ofpbuf request;
1656     struct flow flow;
1657     size_t n_ofp_actions;
1658     int error;
1659
1660     COVERAGE_INC(ofproto_packet_out);
1661
1662     error = reject_slave_controller(ofconn, "OFPT_PACKET_OUT");
1663     if (error) {
1664         return error;
1665     }
1666
1667     /* Get ofp_packet_out. */
1668     ofpbuf_use_const(&request, oh, ntohs(oh->length));
1669     opo = ofpbuf_pull(&request, offsetof(struct ofp_packet_out, actions));
1670
1671     /* Get actions. */
1672     error = ofputil_pull_actions(&request, ntohs(opo->actions_len),
1673                                  &ofp_actions, &n_ofp_actions);
1674     if (error) {
1675         return error;
1676     }
1677
1678     /* Get payload. */
1679     if (opo->buffer_id != htonl(UINT32_MAX)) {
1680         error = ofconn_pktbuf_retrieve(ofconn, ntohl(opo->buffer_id),
1681                                        &buffer, NULL);
1682         if (error || !buffer) {
1683             return error;
1684         }
1685         payload = *buffer;
1686     } else {
1687         payload = request;
1688         buffer = NULL;
1689     }
1690
1691     /* Send out packet. */
1692     flow_extract(&payload, 0, ntohs(opo->in_port), &flow);
1693     error = p->ofproto_class->packet_out(p, &payload, &flow,
1694                                          ofp_actions, n_ofp_actions);
1695     ofpbuf_delete(buffer);
1696
1697     return error;
1698 }
1699
1700 static void
1701 update_port_config(struct ofport *port, ovs_be32 config, ovs_be32 mask)
1702 {
1703     ovs_be32 old_config = port->opp.config;
1704
1705     mask &= config ^ port->opp.config;
1706     if (mask & htonl(OFPPC_PORT_DOWN)) {
1707         if (config & htonl(OFPPC_PORT_DOWN)) {
1708             netdev_turn_flags_off(port->netdev, NETDEV_UP, true);
1709         } else {
1710             netdev_turn_flags_on(port->netdev, NETDEV_UP, true);
1711         }
1712     }
1713
1714     port->opp.config ^= mask & (htonl(OFPPC_NO_RECV | OFPPC_NO_RECV_STP |
1715                                       OFPPC_NO_FLOOD | OFPPC_NO_FWD |
1716                                       OFPPC_NO_PACKET_IN));
1717     if (port->opp.config != old_config) {
1718         port->ofproto->ofproto_class->port_reconfigured(port, old_config);
1719     }
1720 }
1721
1722 static int
1723 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
1724 {
1725     struct ofproto *p = ofconn_get_ofproto(ofconn);
1726     const struct ofp_port_mod *opm = (const struct ofp_port_mod *) oh;
1727     struct ofport *port;
1728     int error;
1729
1730     error = reject_slave_controller(ofconn, "OFPT_PORT_MOD");
1731     if (error) {
1732         return error;
1733     }
1734
1735     port = ofproto_get_port(p, ntohs(opm->port_no));
1736     if (!port) {
1737         return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_PORT);
1738     } else if (memcmp(port->opp.hw_addr, opm->hw_addr, OFP_ETH_ALEN)) {
1739         return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_HW_ADDR);
1740     } else {
1741         update_port_config(port, opm->config, opm->mask);
1742         if (opm->advertise) {
1743             netdev_set_advertisements(port->netdev, ntohl(opm->advertise));
1744         }
1745     }
1746     return 0;
1747 }
1748
1749 static int
1750 handle_desc_stats_request(struct ofconn *ofconn,
1751                           const struct ofp_stats_msg *request)
1752 {
1753     struct ofproto *p = ofconn_get_ofproto(ofconn);
1754     struct ofp_desc_stats *ods;
1755     struct ofpbuf *msg;
1756
1757     ods = ofputil_make_stats_reply(sizeof *ods, request, &msg);
1758     ovs_strlcpy(ods->mfr_desc, p->mfr_desc, sizeof ods->mfr_desc);
1759     ovs_strlcpy(ods->hw_desc, p->hw_desc, sizeof ods->hw_desc);
1760     ovs_strlcpy(ods->sw_desc, p->sw_desc, sizeof ods->sw_desc);
1761     ovs_strlcpy(ods->serial_num, p->serial_desc, sizeof ods->serial_num);
1762     ovs_strlcpy(ods->dp_desc, p->dp_desc, sizeof ods->dp_desc);
1763     ofconn_send_reply(ofconn, msg);
1764
1765     return 0;
1766 }
1767
1768 static int
1769 handle_table_stats_request(struct ofconn *ofconn,
1770                            const struct ofp_stats_msg *request)
1771 {
1772     struct ofproto *p = ofconn_get_ofproto(ofconn);
1773     struct ofp_table_stats *ots;
1774     struct ofpbuf *msg;
1775     size_t i;
1776
1777     ofputil_make_stats_reply(sizeof(struct ofp_stats_msg), request, &msg);
1778
1779     ots = ofpbuf_put_zeros(msg, sizeof *ots * p->n_tables);
1780     for (i = 0; i < p->n_tables; i++) {
1781         ots[i].table_id = i;
1782         sprintf(ots[i].name, "table%zu", i);
1783         ots[i].wildcards = htonl(OFPFW_ALL);
1784         ots[i].max_entries = htonl(1000000); /* An arbitrary big number. */
1785         ots[i].active_count = htonl(classifier_count(&p->tables[i]));
1786     }
1787
1788     p->ofproto_class->get_tables(p, ots);
1789
1790     ofconn_send_reply(ofconn, msg);
1791     return 0;
1792 }
1793
1794 static void
1795 append_port_stat(struct ofport *port, struct list *replies)
1796 {
1797     struct netdev_stats stats;
1798     struct ofp_port_stats *ops;
1799
1800     /* Intentionally ignore return value, since errors will set
1801      * 'stats' to all-1s, which is correct for OpenFlow, and
1802      * netdev_get_stats() will log errors. */
1803     netdev_get_stats(port->netdev, &stats);
1804
1805     ops = ofputil_append_stats_reply(sizeof *ops, replies);
1806     ops->port_no = port->opp.port_no;
1807     memset(ops->pad, 0, sizeof ops->pad);
1808     put_32aligned_be64(&ops->rx_packets, htonll(stats.rx_packets));
1809     put_32aligned_be64(&ops->tx_packets, htonll(stats.tx_packets));
1810     put_32aligned_be64(&ops->rx_bytes, htonll(stats.rx_bytes));
1811     put_32aligned_be64(&ops->tx_bytes, htonll(stats.tx_bytes));
1812     put_32aligned_be64(&ops->rx_dropped, htonll(stats.rx_dropped));
1813     put_32aligned_be64(&ops->tx_dropped, htonll(stats.tx_dropped));
1814     put_32aligned_be64(&ops->rx_errors, htonll(stats.rx_errors));
1815     put_32aligned_be64(&ops->tx_errors, htonll(stats.tx_errors));
1816     put_32aligned_be64(&ops->rx_frame_err, htonll(stats.rx_frame_errors));
1817     put_32aligned_be64(&ops->rx_over_err, htonll(stats.rx_over_errors));
1818     put_32aligned_be64(&ops->rx_crc_err, htonll(stats.rx_crc_errors));
1819     put_32aligned_be64(&ops->collisions, htonll(stats.collisions));
1820 }
1821
1822 static int
1823 handle_port_stats_request(struct ofconn *ofconn,
1824                           const struct ofp_port_stats_request *psr)
1825 {
1826     struct ofproto *p = ofconn_get_ofproto(ofconn);
1827     struct ofport *port;
1828     struct list replies;
1829
1830     ofputil_start_stats_reply(&psr->osm, &replies);
1831     if (psr->port_no != htons(OFPP_NONE)) {
1832         port = ofproto_get_port(p, ntohs(psr->port_no));
1833         if (port) {
1834             append_port_stat(port, &replies);
1835         }
1836     } else {
1837         HMAP_FOR_EACH (port, hmap_node, &p->ports) {
1838             append_port_stat(port, &replies);
1839         }
1840     }
1841
1842     ofconn_send_replies(ofconn, &replies);
1843     return 0;
1844 }
1845
1846 static void
1847 calc_flow_duration__(long long int start, uint32_t *sec, uint32_t *nsec)
1848 {
1849     long long int msecs = time_msec() - start;
1850     *sec = msecs / 1000;
1851     *nsec = (msecs % 1000) * (1000 * 1000);
1852 }
1853
1854 static struct classifier *
1855 first_matching_table(struct ofproto *ofproto, uint8_t table_id)
1856 {
1857     if (table_id == 0xff) {
1858         return &ofproto->tables[0];
1859     } else if (table_id < ofproto->n_tables) {
1860         return &ofproto->tables[table_id];
1861     } else {
1862         /* It would probably be better to reply with an error but there doesn't
1863          * seem to be any appropriate value, so that might just be
1864          * confusing. */
1865         VLOG_WARN_RL(&rl, "controller asked for invalid table %"PRIu8,
1866                      table_id);
1867         return NULL;
1868     }
1869 }
1870
1871 static struct classifier *
1872 next_matching_table(struct ofproto *ofproto,
1873                     struct classifier *cls, uint8_t table_id)
1874 {
1875     return (table_id == 0xff && cls != &ofproto->tables[ofproto->n_tables - 1]
1876             ? cls + 1
1877             : NULL);
1878 }
1879
1880 /* Assigns CLS to each classifier table, in turn, that matches TABLE_ID in
1881  * OFPROTO:
1882  *
1883  *   - If TABLE_ID is 0xff, this iterates over every classifier table in
1884  *     OFPROTO.
1885  *
1886  *   - If TABLE_ID is the number of a table in OFPROTO, then the loop iterates
1887  *     only once, for that table.
1888  *
1889  *   - Otherwise, TABLE_ID isn't valid for OFPROTO, so ofproto logs a warning
1890  *     and does not enter the loop at all.
1891  *
1892  * All parameters are evaluated multiple times.
1893  */
1894 #define FOR_EACH_MATCHING_TABLE(CLS, TABLE_ID, OFPROTO)         \
1895     for ((CLS) = first_matching_table(OFPROTO, TABLE_ID);       \
1896          (CLS) != NULL;                                         \
1897          (CLS) = next_matching_table(OFPROTO, CLS, TABLE_ID))
1898
1899 /* Searches 'ofproto' for rules in table 'table_id' (or in all tables, if
1900  * 'table_id' is 0xff) that match 'match' in the "loose" way required for
1901  * OpenFlow OFPFC_MODIFY and OFPFC_DELETE requests and puts them on list
1902  * 'rules'.
1903  *
1904  * If 'out_port' is anything other than OFPP_NONE, then only rules that output
1905  * to 'out_port' are included.
1906  *
1907  * Hidden rules are always omitted.
1908  *
1909  * Returns 0 on success, otherwise an OpenFlow error code. */
1910 static int
1911 collect_rules_loose(struct ofproto *ofproto, uint8_t table_id,
1912                     const struct cls_rule *match, uint16_t out_port,
1913                     struct list *rules)
1914 {
1915     struct classifier *cls;
1916
1917     list_init(rules);
1918     FOR_EACH_MATCHING_TABLE (cls, table_id, ofproto) {
1919         struct cls_cursor cursor;
1920         struct rule *rule;
1921
1922         cls_cursor_init(&cursor, cls, match);
1923         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
1924             if (rule->pending) {
1925                 return OFPROTO_POSTPONE;
1926             }
1927             if (!rule_is_hidden(rule) && rule_has_out_port(rule, out_port)) {
1928                 list_push_back(rules, &rule->ofproto_node);
1929             }
1930         }
1931     }
1932     return 0;
1933 }
1934
1935 /* Searches 'ofproto' for rules in table 'table_id' (or in all tables, if
1936  * 'table_id' is 0xff) that match 'match' in the "strict" way required for
1937  * OpenFlow OFPFC_MODIFY_STRICT and OFPFC_DELETE_STRICT requests and puts them
1938  * on list 'rules'.
1939  *
1940  * If 'out_port' is anything other than OFPP_NONE, then only rules that output
1941  * to 'out_port' are included.
1942  *
1943  * Hidden rules are always omitted.
1944  *
1945  * Returns 0 on success, otherwise an OpenFlow error code. */
1946 static int
1947 collect_rules_strict(struct ofproto *ofproto, uint8_t table_id,
1948                      const struct cls_rule *match, uint16_t out_port,
1949                      struct list *rules)
1950 {
1951     struct classifier *cls;
1952
1953     list_init(rules);
1954     FOR_EACH_MATCHING_TABLE (cls, table_id, ofproto) {
1955         struct rule *rule;
1956
1957         rule = rule_from_cls_rule(classifier_find_rule_exactly(cls, match));
1958         if (rule) {
1959             if (rule->pending) {
1960                 return OFPROTO_POSTPONE;
1961             }
1962             if (!rule_is_hidden(rule) && rule_has_out_port(rule, out_port)) {
1963                 list_push_back(rules, &rule->ofproto_node);
1964             }
1965         }
1966     }
1967     return 0;
1968 }
1969
1970 static int
1971 handle_flow_stats_request(struct ofconn *ofconn,
1972                           const struct ofp_stats_msg *osm)
1973 {
1974     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
1975     struct ofputil_flow_stats_request fsr;
1976     struct list replies;
1977     struct list rules;
1978     struct rule *rule;
1979     int error;
1980
1981     error = ofputil_decode_flow_stats_request(&fsr, &osm->header);
1982     if (error) {
1983         return error;
1984     }
1985
1986     error = collect_rules_loose(ofproto, fsr.table_id, &fsr.match,
1987                                 fsr.out_port, &rules);
1988     if (error) {
1989         return error;
1990     }
1991
1992     ofputil_start_stats_reply(osm, &replies);
1993     LIST_FOR_EACH (rule, ofproto_node, &rules) {
1994         struct ofputil_flow_stats fs;
1995
1996         fs.rule = rule->cr;
1997         fs.cookie = rule->flow_cookie;
1998         fs.table_id = rule->table_id;
1999         calc_flow_duration__(rule->created, &fs.duration_sec,
2000                              &fs.duration_nsec);
2001         fs.idle_timeout = rule->idle_timeout;
2002         fs.hard_timeout = rule->hard_timeout;
2003         ofproto->ofproto_class->rule_get_stats(rule, &fs.packet_count,
2004                                                &fs.byte_count);
2005         fs.actions = rule->actions;
2006         fs.n_actions = rule->n_actions;
2007         ofputil_append_flow_stats_reply(&fs, &replies);
2008     }
2009     ofconn_send_replies(ofconn, &replies);
2010
2011     return 0;
2012 }
2013
2014 static void
2015 flow_stats_ds(struct rule *rule, struct ds *results)
2016 {
2017     uint64_t packet_count, byte_count;
2018
2019     rule->ofproto->ofproto_class->rule_get_stats(rule,
2020                                                  &packet_count, &byte_count);
2021
2022     if (rule->table_id != 0) {
2023         ds_put_format(results, "table_id=%"PRIu8", ", rule->table_id);
2024     }
2025     ds_put_format(results, "duration=%llds, ",
2026                   (time_msec() - rule->created) / 1000);
2027     ds_put_format(results, "priority=%u, ", rule->cr.priority);
2028     ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
2029     ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
2030     cls_rule_format(&rule->cr, results);
2031     ds_put_char(results, ',');
2032     if (rule->n_actions > 0) {
2033         ofp_print_actions(results, rule->actions, rule->n_actions);
2034     } else {
2035         ds_put_cstr(results, "drop");
2036     }
2037     ds_put_cstr(results, "\n");
2038 }
2039
2040 /* Adds a pretty-printed description of all flows to 'results', including
2041  * hidden flows (e.g., set up by in-band control). */
2042 void
2043 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
2044 {
2045     struct classifier *cls;
2046
2047     OFPROTO_FOR_EACH_TABLE (cls, p) {
2048         struct cls_cursor cursor;
2049         struct rule *rule;
2050
2051         cls_cursor_init(&cursor, cls, NULL);
2052         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
2053             flow_stats_ds(rule, results);
2054         }
2055     }
2056 }
2057
2058 /* Obtains the NetFlow engine type and engine ID for 'ofproto' into
2059  * '*engine_type' and '*engine_id', respectively. */
2060 void
2061 ofproto_get_netflow_ids(const struct ofproto *ofproto,
2062                         uint8_t *engine_type, uint8_t *engine_id)
2063 {
2064     ofproto->ofproto_class->get_netflow_ids(ofproto, engine_type, engine_id);
2065 }
2066
2067 /* Checks the fault status of CFM for 'ofp_port' within 'ofproto'.  Returns 1
2068  * if CFM is faulted (generally indiciating a connectivity problem), 0 if CFM
2069  * is not faulted, and -1 if CFM is not enabled on 'ofp_port'. */
2070 int
2071 ofproto_port_get_cfm_fault(const struct ofproto *ofproto, uint16_t ofp_port)
2072 {
2073     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
2074     return (ofport && ofproto->ofproto_class->get_cfm_fault
2075             ? ofproto->ofproto_class->get_cfm_fault(ofport)
2076             : -1);
2077 }
2078
2079 /* Gets the MPIDs of the remote maintenance points broadcasting to 'ofp_port'
2080  * within 'ofproto'.  Populates 'rmps' with an array of MPIDs owned by
2081  * 'ofproto', and 'n_rmps' with the number of MPIDs in 'rmps'.  Returns a
2082  * number less than 0 if CFM is not enabled on 'ofp_port'. */
2083 int
2084 ofproto_port_get_cfm_remote_mpids(const struct ofproto *ofproto,
2085                                   uint16_t ofp_port, const uint64_t **rmps,
2086                                   size_t *n_rmps)
2087 {
2088     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
2089
2090     *rmps = NULL;
2091     *n_rmps = 0;
2092     return (ofport && ofproto->ofproto_class->get_cfm_remote_mpids
2093             ? ofproto->ofproto_class->get_cfm_remote_mpids(ofport, rmps,
2094                                                            n_rmps)
2095             : -1);
2096 }
2097
2098 static int
2099 handle_aggregate_stats_request(struct ofconn *ofconn,
2100                                const struct ofp_stats_msg *osm)
2101 {
2102     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2103     struct ofputil_flow_stats_request request;
2104     struct ofputil_aggregate_stats stats;
2105     bool unknown_packets, unknown_bytes;
2106     struct ofpbuf *reply;
2107     struct list rules;
2108     struct rule *rule;
2109     int error;
2110
2111     error = ofputil_decode_flow_stats_request(&request, &osm->header);
2112     if (error) {
2113         return error;
2114     }
2115
2116     error = collect_rules_loose(ofproto, request.table_id, &request.match,
2117                                 request.out_port, &rules);
2118     if (error) {
2119         return error;
2120     }
2121
2122     memset(&stats, 0, sizeof stats);
2123     unknown_packets = unknown_bytes = false;
2124     LIST_FOR_EACH (rule, ofproto_node, &rules) {
2125         uint64_t packet_count;
2126         uint64_t byte_count;
2127
2128         ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
2129                                                &byte_count);
2130
2131         if (packet_count == UINT64_MAX) {
2132             unknown_packets = true;
2133         } else {
2134             stats.packet_count += packet_count;
2135         }
2136
2137         if (byte_count == UINT64_MAX) {
2138             unknown_bytes = true;
2139         } else {
2140             stats.byte_count += byte_count;
2141         }
2142
2143         stats.flow_count++;
2144     }
2145     if (unknown_packets) {
2146         stats.packet_count = UINT64_MAX;
2147     }
2148     if (unknown_bytes) {
2149         stats.byte_count = UINT64_MAX;
2150     }
2151
2152     reply = ofputil_encode_aggregate_stats_reply(&stats, osm);
2153     ofconn_send_reply(ofconn, reply);
2154
2155     return 0;
2156 }
2157
2158 struct queue_stats_cbdata {
2159     struct ofport *ofport;
2160     struct list replies;
2161 };
2162
2163 static void
2164 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
2165                 const struct netdev_queue_stats *stats)
2166 {
2167     struct ofp_queue_stats *reply;
2168
2169     reply = ofputil_append_stats_reply(sizeof *reply, &cbdata->replies);
2170     reply->port_no = cbdata->ofport->opp.port_no;
2171     memset(reply->pad, 0, sizeof reply->pad);
2172     reply->queue_id = htonl(queue_id);
2173     put_32aligned_be64(&reply->tx_bytes, htonll(stats->tx_bytes));
2174     put_32aligned_be64(&reply->tx_packets, htonll(stats->tx_packets));
2175     put_32aligned_be64(&reply->tx_errors, htonll(stats->tx_errors));
2176 }
2177
2178 static void
2179 handle_queue_stats_dump_cb(uint32_t queue_id,
2180                            struct netdev_queue_stats *stats,
2181                            void *cbdata_)
2182 {
2183     struct queue_stats_cbdata *cbdata = cbdata_;
2184
2185     put_queue_stats(cbdata, queue_id, stats);
2186 }
2187
2188 static void
2189 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
2190                             struct queue_stats_cbdata *cbdata)
2191 {
2192     cbdata->ofport = port;
2193     if (queue_id == OFPQ_ALL) {
2194         netdev_dump_queue_stats(port->netdev,
2195                                 handle_queue_stats_dump_cb, cbdata);
2196     } else {
2197         struct netdev_queue_stats stats;
2198
2199         if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
2200             put_queue_stats(cbdata, queue_id, &stats);
2201         }
2202     }
2203 }
2204
2205 static int
2206 handle_queue_stats_request(struct ofconn *ofconn,
2207                            const struct ofp_queue_stats_request *qsr)
2208 {
2209     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2210     struct queue_stats_cbdata cbdata;
2211     struct ofport *port;
2212     unsigned int port_no;
2213     uint32_t queue_id;
2214
2215     COVERAGE_INC(ofproto_queue_req);
2216
2217     ofputil_start_stats_reply(&qsr->osm, &cbdata.replies);
2218
2219     port_no = ntohs(qsr->port_no);
2220     queue_id = ntohl(qsr->queue_id);
2221     if (port_no == OFPP_ALL) {
2222         HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
2223             handle_queue_stats_for_port(port, queue_id, &cbdata);
2224         }
2225     } else if (port_no < OFPP_MAX) {
2226         port = ofproto_get_port(ofproto, port_no);
2227         if (port) {
2228             handle_queue_stats_for_port(port, queue_id, &cbdata);
2229         }
2230     } else {
2231         ofpbuf_list_delete(&cbdata.replies);
2232         return ofp_mkerr(OFPET_QUEUE_OP_FAILED, OFPQOFC_BAD_PORT);
2233     }
2234     ofconn_send_replies(ofconn, &cbdata.replies);
2235
2236     return 0;
2237 }
2238
2239 static bool
2240 is_flow_deletion_pending(const struct ofproto *ofproto,
2241                          const struct cls_rule *cls_rule,
2242                          uint8_t table_id)
2243 {
2244     if (!hmap_is_empty(&ofproto->deletions)) {
2245         struct ofoperation *op;
2246
2247         HMAP_FOR_EACH_WITH_HASH (op, hmap_node,
2248                                  cls_rule_hash(cls_rule, table_id),
2249                                  &ofproto->deletions) {
2250             if (cls_rule_equal(cls_rule, &op->rule->cr)) {
2251                 return true;
2252             }
2253         }
2254     }
2255
2256     return false;
2257 }
2258
2259 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
2260  * in which no matching flow already exists in the flow table.
2261  *
2262  * Adds the flow specified by 'ofm', which is followed by 'n_actions'
2263  * ofp_actions, to the ofproto's flow table.  Returns 0 on success, an OpenFlow
2264  * error code as encoded by ofp_mkerr() on failure, or OFPROTO_POSTPONE if the
2265  * operation cannot be initiated now but may be retried later.
2266  *
2267  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
2268  * if any. */
2269 static int
2270 add_flow(struct ofproto *ofproto, struct ofconn *ofconn,
2271          const struct ofputil_flow_mod *fm, const struct ofp_header *request)
2272 {
2273     struct classifier *table;
2274     struct ofopgroup *group;
2275     struct rule *victim;
2276     struct rule *rule;
2277     int error;
2278
2279     /* Check for overlap, if requested. */
2280     if (fm->flags & OFPFF_CHECK_OVERLAP) {
2281         struct classifier *cls;
2282
2283         FOR_EACH_MATCHING_TABLE (cls, fm->table_id, ofproto) {
2284             if (classifier_rule_overlaps(cls, &fm->cr)) {
2285                 return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_OVERLAP);
2286             }
2287         }
2288     }
2289
2290     /* Pick table. */
2291     if (fm->table_id == 0xff) {
2292         uint8_t table_id;
2293         if (ofproto->ofproto_class->rule_choose_table) {
2294             error = ofproto->ofproto_class->rule_choose_table(ofproto, &fm->cr,
2295                                                               &table_id);
2296             if (error) {
2297                 return error;
2298             }
2299             assert(table_id < ofproto->n_tables);
2300             table = &ofproto->tables[table_id];
2301         } else {
2302             table = &ofproto->tables[0];
2303         }
2304     } else if (fm->table_id < ofproto->n_tables) {
2305         table = &ofproto->tables[fm->table_id];
2306     } else {
2307         return ofp_mkerr_nicira(OFPET_FLOW_MOD_FAILED, NXFMFC_BAD_TABLE_ID);
2308     }
2309
2310     /* Serialize against pending deletion. */
2311     if (is_flow_deletion_pending(ofproto, &fm->cr, table - ofproto->tables)) {
2312         return OFPROTO_POSTPONE;
2313     }
2314
2315     /* Allocate new rule. */
2316     rule = ofproto->ofproto_class->rule_alloc();
2317     if (!rule) {
2318         VLOG_WARN_RL(&rl, "%s: failed to create rule (%s)",
2319                      ofproto->name, strerror(error));
2320         return ENOMEM;
2321     }
2322     rule->ofproto = ofproto;
2323     rule->cr = fm->cr;
2324     rule->pending = NULL;
2325     rule->flow_cookie = fm->cookie;
2326     rule->created = rule->modified = time_msec();
2327     rule->idle_timeout = fm->idle_timeout;
2328     rule->hard_timeout = fm->hard_timeout;
2329     rule->table_id = table - ofproto->tables;
2330     rule->send_flow_removed = (fm->flags & OFPFF_SEND_FLOW_REM) != 0;
2331     rule->actions = ofputil_actions_clone(fm->actions, fm->n_actions);
2332     rule->n_actions = fm->n_actions;
2333
2334     /* Insert new rule. */
2335     victim = rule_from_cls_rule(classifier_replace(table, &rule->cr));
2336     if (victim && victim->pending) {
2337         error = OFPROTO_POSTPONE;
2338     } else {
2339         group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
2340         ofoperation_create(group, rule, OFOPERATION_ADD);
2341         rule->pending->victim = victim;
2342
2343         error = ofproto->ofproto_class->rule_construct(rule);
2344         if (error) {
2345             ofoperation_destroy(rule->pending);
2346         }
2347         ofopgroup_submit(group);
2348     }
2349
2350     /* Back out if an error occurred. */
2351     if (error) {
2352         if (victim) {
2353             classifier_replace(table, &victim->cr);
2354         } else {
2355             classifier_remove(table, &rule->cr);
2356         }
2357         ofproto_rule_destroy__(rule);
2358     }
2359     return error;
2360 }
2361 \f
2362 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
2363
2364 /* Modifies the rules listed in 'rules', changing their actions to match those
2365  * in 'fm'.
2366  *
2367  * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
2368  * if any.
2369  *
2370  * Returns 0 on success, otherwise an OpenFlow error code. */
2371 static int
2372 modify_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
2373                const struct ofputil_flow_mod *fm,
2374                const struct ofp_header *request, struct list *rules)
2375 {
2376     struct ofopgroup *group;
2377     struct rule *rule;
2378
2379     group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
2380     LIST_FOR_EACH (rule, ofproto_node, rules) {
2381         if (!ofputil_actions_equal(fm->actions, fm->n_actions,
2382                                    rule->actions, rule->n_actions)) {
2383             ofoperation_create(group, rule, OFOPERATION_MODIFY);
2384             rule->pending->actions = rule->actions;
2385             rule->pending->n_actions = rule->n_actions;
2386             rule->actions = ofputil_actions_clone(fm->actions, fm->n_actions);
2387             rule->n_actions = fm->n_actions;
2388             rule->ofproto->ofproto_class->rule_modify_actions(rule);
2389         } else {
2390             rule->modified = time_msec();
2391         }
2392         rule->flow_cookie = fm->cookie;
2393     }
2394     ofopgroup_submit(group);
2395
2396     return 0;
2397 }
2398
2399 /* Implements OFPFC_MODIFY.  Returns 0 on success or an OpenFlow error code as
2400  * encoded by ofp_mkerr() on failure.
2401  *
2402  * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
2403  * if any. */
2404 static int
2405 modify_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
2406                    const struct ofputil_flow_mod *fm,
2407                    const struct ofp_header *request)
2408 {
2409     struct list rules;
2410     int error;
2411
2412     error = collect_rules_loose(ofproto, fm->table_id, &fm->cr, OFPP_NONE,
2413                                 &rules);
2414     return (error ? error
2415             : list_is_empty(&rules) ? add_flow(ofproto, ofconn, fm, request)
2416             : modify_flows__(ofproto, ofconn, fm, request, &rules));
2417 }
2418
2419 /* Implements OFPFC_MODIFY_STRICT.  Returns 0 on success or an OpenFlow error
2420  * code as encoded by ofp_mkerr() on failure.
2421  *
2422  * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
2423  * if any. */
2424 static int
2425 modify_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
2426                    const struct ofputil_flow_mod *fm,
2427                    const struct ofp_header *request)
2428 {
2429     struct list rules;
2430     int error;
2431
2432     error = collect_rules_strict(ofproto, fm->table_id, &fm->cr, OFPP_NONE,
2433                                  &rules);
2434     return (error ? error
2435             : list_is_empty(&rules) ? add_flow(ofproto, ofconn, fm, request)
2436             : list_is_singleton(&rules) ? modify_flows__(ofproto, ofconn,
2437                                                          fm, request, &rules)
2438             : 0);
2439 }
2440 \f
2441 /* OFPFC_DELETE implementation. */
2442
2443 /* Deletes the rules listed in 'rules'.
2444  *
2445  * Returns 0 on success, otherwise an OpenFlow error code. */
2446 static int
2447 delete_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
2448                const struct ofp_header *request, struct list *rules)
2449 {
2450     struct rule *rule, *next;
2451     struct ofopgroup *group;
2452
2453     group = ofopgroup_create(ofproto, ofconn, request, UINT32_MAX);
2454     LIST_FOR_EACH_SAFE (rule, next, ofproto_node, rules) {
2455         ofproto_rule_send_removed(rule, OFPRR_DELETE);
2456
2457         ofoperation_create(group, rule, OFOPERATION_DELETE);
2458         classifier_remove(&ofproto->tables[rule->table_id], &rule->cr);
2459         rule->ofproto->ofproto_class->rule_destruct(rule);
2460     }
2461     ofopgroup_submit(group);
2462
2463     return 0;
2464 }
2465
2466 /* Implements OFPFC_DELETE. */
2467 static int
2468 delete_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
2469                    const struct ofputil_flow_mod *fm,
2470                    const struct ofp_header *request)
2471 {
2472     struct list rules;
2473     int error;
2474
2475     error = collect_rules_loose(ofproto, fm->table_id, &fm->cr, fm->out_port,
2476                                 &rules);
2477     return (error ? error
2478             : !list_is_empty(&rules) ? delete_flows__(ofproto, ofconn, request,
2479                                                       &rules)
2480             : 0);
2481 }
2482
2483 /* Implements OFPFC_DELETE_STRICT. */
2484 static int
2485 delete_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
2486                    const struct ofputil_flow_mod *fm,
2487                    const struct ofp_header *request)
2488 {
2489     struct list rules;
2490     int error;
2491
2492     error = collect_rules_strict(ofproto, fm->table_id, &fm->cr, fm->out_port,
2493                                  &rules);
2494     return (error ? error
2495             : list_is_singleton(&rules) ? delete_flows__(ofproto, ofconn,
2496                                                          request, &rules)
2497             : 0);
2498 }
2499
2500 static void
2501 ofproto_rule_send_removed(struct rule *rule, uint8_t reason)
2502 {
2503     struct ofputil_flow_removed fr;
2504
2505     if (rule_is_hidden(rule) || !rule->send_flow_removed) {
2506         return;
2507     }
2508
2509     fr.rule = rule->cr;
2510     fr.cookie = rule->flow_cookie;
2511     fr.reason = reason;
2512     calc_flow_duration__(rule->created, &fr.duration_sec, &fr.duration_nsec);
2513     fr.idle_timeout = rule->idle_timeout;
2514     rule->ofproto->ofproto_class->rule_get_stats(rule, &fr.packet_count,
2515                                                  &fr.byte_count);
2516
2517     connmgr_send_flow_removed(rule->ofproto->connmgr, &fr);
2518 }
2519
2520 /* Sends an OpenFlow "flow removed" message with the given 'reason' (either
2521  * OFPRR_HARD_TIMEOUT or OFPRR_IDLE_TIMEOUT), and then removes 'rule' from its
2522  * ofproto.
2523  *
2524  * ofproto implementation ->run() functions should use this function to expire
2525  * OpenFlow flows. */
2526 void
2527 ofproto_rule_expire(struct rule *rule, uint8_t reason)
2528 {
2529     struct ofproto *ofproto = rule->ofproto;
2530     struct ofopgroup *group;
2531
2532     assert(reason == OFPRR_HARD_TIMEOUT || reason == OFPRR_IDLE_TIMEOUT);
2533
2534     ofproto_rule_send_removed(rule, reason);
2535
2536     group = ofopgroup_create_unattached(ofproto);
2537     ofoperation_create(group, rule, OFOPERATION_DELETE);
2538     classifier_remove(&ofproto->tables[rule->table_id], &rule->cr);
2539     rule->ofproto->ofproto_class->rule_destruct(rule);
2540     ofopgroup_submit(group);
2541 }
2542 \f
2543 static int
2544 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
2545 {
2546     struct ofputil_flow_mod fm;
2547     int error;
2548
2549     error = reject_slave_controller(ofconn, "flow_mod");
2550     if (error) {
2551         return error;
2552     }
2553
2554     error = ofputil_decode_flow_mod(&fm, oh,
2555                                     ofconn_get_flow_mod_table_id(ofconn));
2556     if (error) {
2557         return error;
2558     }
2559
2560     /* We do not support the emergency flow cache.  It will hopefully get
2561      * dropped from OpenFlow in the near future. */
2562     if (fm.flags & OFPFF_EMERG) {
2563         /* There isn't a good fit for an error code, so just state that the
2564          * flow table is full. */
2565         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_ALL_TABLES_FULL);
2566     }
2567
2568     return handle_flow_mod__(ofconn_get_ofproto(ofconn), ofconn, &fm, oh);
2569 }
2570
2571 static int
2572 handle_flow_mod__(struct ofproto *ofproto, struct ofconn *ofconn,
2573                   const struct ofputil_flow_mod *fm,
2574                   const struct ofp_header *oh)
2575 {
2576     if (ofproto->n_pending >= 50) {
2577         assert(!list_is_empty(&ofproto->pending));
2578         return OFPROTO_POSTPONE;
2579     }
2580
2581     switch (fm->command) {
2582     case OFPFC_ADD:
2583         return add_flow(ofproto, ofconn, fm, oh);
2584
2585     case OFPFC_MODIFY:
2586         return modify_flows_loose(ofproto, ofconn, fm, oh);
2587
2588     case OFPFC_MODIFY_STRICT:
2589         return modify_flow_strict(ofproto, ofconn, fm, oh);
2590
2591     case OFPFC_DELETE:
2592         return delete_flows_loose(ofproto, ofconn, fm, oh);
2593
2594     case OFPFC_DELETE_STRICT:
2595         return delete_flow_strict(ofproto, ofconn, fm, oh);
2596
2597     default:
2598         if (fm->command > 0xff) {
2599             VLOG_WARN_RL(&rl, "flow_mod has explicit table_id but "
2600                          "flow_mod_table_id extension is not enabled");
2601         }
2602         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_BAD_COMMAND);
2603     }
2604 }
2605
2606 static int
2607 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
2608 {
2609     struct nx_role_request *nrr = (struct nx_role_request *) oh;
2610     struct nx_role_request *reply;
2611     struct ofpbuf *buf;
2612     uint32_t role;
2613
2614     if (ofconn_get_type(ofconn) != OFCONN_PRIMARY) {
2615         VLOG_WARN_RL(&rl, "ignoring role request on service connection");
2616         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
2617     }
2618
2619     role = ntohl(nrr->role);
2620     if (role != NX_ROLE_OTHER && role != NX_ROLE_MASTER
2621         && role != NX_ROLE_SLAVE) {
2622         VLOG_WARN_RL(&rl, "received request for unknown role %"PRIu32, role);
2623
2624         /* There's no good error code for this. */
2625         return ofp_mkerr(OFPET_BAD_REQUEST, -1);
2626     }
2627
2628     if (ofconn_get_role(ofconn) != role
2629         && ofconn_has_pending_opgroups(ofconn)) {
2630         return OFPROTO_POSTPONE;
2631     }
2632
2633     ofconn_set_role(ofconn, role);
2634
2635     reply = make_nxmsg_xid(sizeof *reply, NXT_ROLE_REPLY, oh->xid, &buf);
2636     reply->role = htonl(role);
2637     ofconn_send_reply(ofconn, buf);
2638
2639     return 0;
2640 }
2641
2642 static int
2643 handle_nxt_flow_mod_table_id(struct ofconn *ofconn,
2644                              const struct ofp_header *oh)
2645 {
2646     const struct nxt_flow_mod_table_id *msg
2647         = (const struct nxt_flow_mod_table_id *) oh;
2648
2649     ofconn_set_flow_mod_table_id(ofconn, msg->set != 0);
2650     return 0;
2651 }
2652
2653 static int
2654 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
2655 {
2656     const struct nxt_set_flow_format *msg
2657         = (const struct nxt_set_flow_format *) oh;
2658     uint32_t format;
2659
2660     format = ntohl(msg->format);
2661     if (format != NXFF_OPENFLOW10 && format != NXFF_NXM) {
2662         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
2663     }
2664
2665     if (format != ofconn_get_flow_format(ofconn)
2666         && ofconn_has_pending_opgroups(ofconn)) {
2667         /* Avoid sending async messages in surprising flow format. */
2668         return OFPROTO_POSTPONE;
2669     }
2670
2671     ofconn_set_flow_format(ofconn, format);
2672     return 0;
2673 }
2674
2675 static int
2676 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
2677 {
2678     struct ofp_header *ob;
2679     struct ofpbuf *buf;
2680
2681     if (ofconn_has_pending_opgroups(ofconn)) {
2682         return OFPROTO_POSTPONE;
2683     }
2684
2685     ob = make_openflow_xid(sizeof *ob, OFPT_BARRIER_REPLY, oh->xid, &buf);
2686     ofconn_send_reply(ofconn, buf);
2687     return 0;
2688 }
2689
2690 static int
2691 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
2692 {
2693     const struct ofp_header *oh = msg->data;
2694     const struct ofputil_msg_type *type;
2695     int error;
2696
2697     error = ofputil_decode_msg_type(oh, &type);
2698     if (error) {
2699         return error;
2700     }
2701
2702     switch (ofputil_msg_type_code(type)) {
2703         /* OpenFlow requests. */
2704     case OFPUTIL_OFPT_ECHO_REQUEST:
2705         return handle_echo_request(ofconn, oh);
2706
2707     case OFPUTIL_OFPT_FEATURES_REQUEST:
2708         return handle_features_request(ofconn, oh);
2709
2710     case OFPUTIL_OFPT_GET_CONFIG_REQUEST:
2711         return handle_get_config_request(ofconn, oh);
2712
2713     case OFPUTIL_OFPT_SET_CONFIG:
2714         return handle_set_config(ofconn, msg->data);
2715
2716     case OFPUTIL_OFPT_PACKET_OUT:
2717         return handle_packet_out(ofconn, oh);
2718
2719     case OFPUTIL_OFPT_PORT_MOD:
2720         return handle_port_mod(ofconn, oh);
2721
2722     case OFPUTIL_OFPT_FLOW_MOD:
2723         return handle_flow_mod(ofconn, oh);
2724
2725     case OFPUTIL_OFPT_BARRIER_REQUEST:
2726         return handle_barrier_request(ofconn, oh);
2727
2728         /* OpenFlow replies. */
2729     case OFPUTIL_OFPT_ECHO_REPLY:
2730         return 0;
2731
2732         /* Nicira extension requests. */
2733     case OFPUTIL_NXT_ROLE_REQUEST:
2734         return handle_role_request(ofconn, oh);
2735
2736     case OFPUTIL_NXT_FLOW_MOD_TABLE_ID:
2737         return handle_nxt_flow_mod_table_id(ofconn, oh);
2738
2739     case OFPUTIL_NXT_SET_FLOW_FORMAT:
2740         return handle_nxt_set_flow_format(ofconn, oh);
2741
2742     case OFPUTIL_NXT_FLOW_MOD:
2743         return handle_flow_mod(ofconn, oh);
2744
2745         /* Statistics requests. */
2746     case OFPUTIL_OFPST_DESC_REQUEST:
2747         return handle_desc_stats_request(ofconn, msg->data);
2748
2749     case OFPUTIL_OFPST_FLOW_REQUEST:
2750     case OFPUTIL_NXST_FLOW_REQUEST:
2751         return handle_flow_stats_request(ofconn, msg->data);
2752
2753     case OFPUTIL_OFPST_AGGREGATE_REQUEST:
2754     case OFPUTIL_NXST_AGGREGATE_REQUEST:
2755         return handle_aggregate_stats_request(ofconn, msg->data);
2756
2757     case OFPUTIL_OFPST_TABLE_REQUEST:
2758         return handle_table_stats_request(ofconn, msg->data);
2759
2760     case OFPUTIL_OFPST_PORT_REQUEST:
2761         return handle_port_stats_request(ofconn, msg->data);
2762
2763     case OFPUTIL_OFPST_QUEUE_REQUEST:
2764         return handle_queue_stats_request(ofconn, msg->data);
2765
2766     case OFPUTIL_MSG_INVALID:
2767     case OFPUTIL_OFPT_HELLO:
2768     case OFPUTIL_OFPT_ERROR:
2769     case OFPUTIL_OFPT_FEATURES_REPLY:
2770     case OFPUTIL_OFPT_GET_CONFIG_REPLY:
2771     case OFPUTIL_OFPT_PACKET_IN:
2772     case OFPUTIL_OFPT_FLOW_REMOVED:
2773     case OFPUTIL_OFPT_PORT_STATUS:
2774     case OFPUTIL_OFPT_BARRIER_REPLY:
2775     case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REQUEST:
2776     case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REPLY:
2777     case OFPUTIL_OFPST_DESC_REPLY:
2778     case OFPUTIL_OFPST_FLOW_REPLY:
2779     case OFPUTIL_OFPST_QUEUE_REPLY:
2780     case OFPUTIL_OFPST_PORT_REPLY:
2781     case OFPUTIL_OFPST_TABLE_REPLY:
2782     case OFPUTIL_OFPST_AGGREGATE_REPLY:
2783     case OFPUTIL_NXT_ROLE_REPLY:
2784     case OFPUTIL_NXT_FLOW_REMOVED:
2785     case OFPUTIL_NXST_FLOW_REPLY:
2786     case OFPUTIL_NXST_AGGREGATE_REPLY:
2787     default:
2788         if (VLOG_IS_WARN_ENABLED()) {
2789             char *s = ofp_to_string(oh, ntohs(oh->length), 2);
2790             VLOG_DBG_RL(&rl, "OpenFlow message ignored: %s", s);
2791             free(s);
2792         }
2793         if (oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY) {
2794             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT);
2795         } else {
2796             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
2797         }
2798     }
2799 }
2800
2801 static bool
2802 handle_openflow(struct ofconn *ofconn, struct ofpbuf *ofp_msg)
2803 {
2804     int error = handle_openflow__(ofconn, ofp_msg);
2805     if (error && error != OFPROTO_POSTPONE) {
2806         ofconn_send_error(ofconn, ofp_msg->data, error);
2807     }
2808     COVERAGE_INC(ofproto_recv_openflow);
2809     return error != OFPROTO_POSTPONE;
2810 }
2811 \f
2812 /* Asynchronous operations. */
2813
2814 /* Creates and returns a new ofopgroup that is not associated with any
2815  * OpenFlow connection.
2816  *
2817  * The caller should add operations to the returned group with
2818  * ofoperation_create() and then submit it with ofopgroup_submit(). */
2819 static struct ofopgroup *
2820 ofopgroup_create_unattached(struct ofproto *ofproto)
2821 {
2822     struct ofopgroup *group = xzalloc(sizeof *group);
2823     group->ofproto = ofproto;
2824     list_init(&group->ofproto_node);
2825     list_init(&group->ops);
2826     list_init(&group->ofconn_node);
2827     return group;
2828 }
2829
2830 /* Creates and returns a new ofopgroup for 'ofproto'.
2831  *
2832  * If 'ofconn' is NULL, the new ofopgroup is not associated with any OpenFlow
2833  * connection.  The 'request' and 'buffer_id' arguments are ignored.
2834  *
2835  * If 'ofconn' is nonnull, then the new ofopgroup is associated with 'ofconn'.
2836  * If the ofopgroup eventually fails, then the error reply will include
2837  * 'request'.  If the ofopgroup eventually succeeds, then the packet with
2838  * buffer id 'buffer_id' on 'ofconn' will be sent by 'ofconn''s ofproto.
2839  *
2840  * The caller should add operations to the returned group with
2841  * ofoperation_create() and then submit it with ofopgroup_submit(). */
2842 static struct ofopgroup *
2843 ofopgroup_create(struct ofproto *ofproto, struct ofconn *ofconn,
2844                  const struct ofp_header *request, uint32_t buffer_id)
2845 {
2846     struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
2847     if (ofconn) {
2848         size_t request_len = ntohs(request->length);
2849
2850         assert(ofconn_get_ofproto(ofconn) == ofproto);
2851
2852         ofconn_add_opgroup(ofconn, &group->ofconn_node);
2853         group->ofconn = ofconn;
2854         group->request = xmemdup(request, MIN(request_len, 64));
2855         group->buffer_id = buffer_id;
2856     }
2857     return group;
2858 }
2859
2860 /* Submits 'group' for processing.
2861  *
2862  * If 'group' contains no operations (e.g. none were ever added, or all of the
2863  * ones that were added completed synchronously), then it is destroyed
2864  * immediately.  Otherwise it is added to the ofproto's list of pending
2865  * groups. */
2866 static void
2867 ofopgroup_submit(struct ofopgroup *group)
2868 {
2869     if (list_is_empty(&group->ops)) {
2870         ofopgroup_destroy(group);
2871     } else {
2872         list_push_back(&group->ofproto->pending, &group->ofproto_node);
2873         group->ofproto->n_pending++;
2874     }
2875 }
2876
2877 static void
2878 ofopgroup_destroy(struct ofopgroup *group)
2879 {
2880     assert(list_is_empty(&group->ops));
2881     if (!list_is_empty(&group->ofproto_node)) {
2882         assert(group->ofproto->n_pending > 0);
2883         group->ofproto->n_pending--;
2884         list_remove(&group->ofproto_node);
2885     }
2886     if (!list_is_empty(&group->ofconn_node)) {
2887         list_remove(&group->ofconn_node);
2888         if (group->error) {
2889             ofconn_send_error(group->ofconn, group->request, group->error);
2890         }
2891         connmgr_retry(group->ofproto->connmgr);
2892     }
2893     free(group->request);
2894     free(group);
2895 }
2896
2897 /* Initiates a new operation on 'rule', of the specified 'type', within
2898  * 'group'.  Prior to calling, 'rule' must not have any pending operation. */
2899 static void
2900 ofoperation_create(struct ofopgroup *group, struct rule *rule,
2901                    enum ofoperation_type type)
2902 {
2903     struct ofoperation *op;
2904
2905     assert(!rule->pending);
2906
2907     op = rule->pending = xzalloc(sizeof *op);
2908     op->group = group;
2909     list_push_back(&group->ops, &op->group_node);
2910     op->rule = rule;
2911     op->type = type;
2912     op->status = -1;
2913     op->flow_cookie = rule->flow_cookie;
2914
2915     if (type == OFOPERATION_DELETE) {
2916         hmap_insert(&op->group->ofproto->deletions, &op->hmap_node,
2917                     cls_rule_hash(&rule->cr, rule->table_id));
2918     }
2919 }
2920
2921 static void
2922 ofoperation_destroy(struct ofoperation *op)
2923 {
2924     struct ofopgroup *group = op->group;
2925
2926     if (op->rule) {
2927         op->rule->pending = NULL;
2928     }
2929     if (op->type == OFOPERATION_DELETE) {
2930         hmap_remove(&group->ofproto->deletions, &op->hmap_node);
2931     }
2932     list_remove(&op->group_node);
2933     free(op->actions);
2934     free(op);
2935
2936     if (list_is_empty(&group->ops) && !list_is_empty(&group->ofproto_node)) {
2937         ofopgroup_destroy(group);
2938     }
2939 }
2940
2941 /* Indicates that 'op' completed with status 'error', which is either 0 to
2942  * indicate success or an OpenFlow error code (constructed with
2943  * e.g. ofp_mkerr()).
2944  *
2945  * If 'error' is 0, indicating success, the operation will be committed
2946  * permanently to the flow table.  There is one interesting subcase:
2947  *
2948  *   - If 'op' is an "add flow" operation that is replacing an existing rule in
2949  *     the flow table (the "victim" rule) by a new one, then the caller must
2950  *     have uninitialized any derived state in the victim rule, as in step 5 in
2951  *     the "Life Cycle" in ofproto/ofproto-provider.h.  ofoperation_complete()
2952  *     performs steps 6 and 7 for the victim rule, most notably by calling its
2953  *     ->rule_dealloc() function.
2954  *
2955  * If 'error' is nonzero, then generally the operation will be rolled back:
2956  *
2957  *   - If 'op' is an "add flow" operation, ofproto removes the new rule or
2958  *     restores the original rule.  The caller must have uninitialized any
2959  *     derived state in the new rule, as in step 5 of in the "Life Cycle" in
2960  *     ofproto/ofproto-provider.h.  ofoperation_complete() performs steps 6 and
2961  *     and 7 for the new rule, calling its ->rule_dealloc() function.
2962  *
2963  *   - If 'op' is a "modify flow" operation, ofproto restores the original
2964  *     actions.
2965  *
2966  *   - 'op' must not be a "delete flow" operation.  Removing a rule is not
2967  *     allowed to fail.  It must always succeed.
2968  *
2969  * Please see the large comment in ofproto/ofproto-provider.h titled
2970  * "Asynchronous Operation Support" for more information. */
2971 void
2972 ofoperation_complete(struct ofoperation *op, int error)
2973 {
2974     struct ofopgroup *group = op->group;
2975     struct rule *rule = op->rule;
2976     struct classifier *table = &rule->ofproto->tables[rule->table_id];
2977
2978     assert(rule->pending == op);
2979     assert(op->status < 0);
2980     assert(error >= 0);
2981
2982     if (!error
2983         && !group->error
2984         && op->type != OFOPERATION_DELETE
2985         && group->ofconn
2986         && group->buffer_id != UINT32_MAX
2987         && list_is_singleton(&op->group_node)) {
2988         struct ofpbuf *packet;
2989         uint16_t in_port;
2990
2991         error = ofconn_pktbuf_retrieve(group->ofconn, group->buffer_id,
2992                                        &packet, &in_port);
2993         if (packet) {
2994             assert(!error);
2995             error = rule_execute(rule, in_port, packet);
2996         }
2997     }
2998     if (!group->error) {
2999         group->error = error;
3000     }
3001
3002     switch (op->type) {
3003     case OFOPERATION_ADD:
3004         if (!error) {
3005             if (op->victim) {
3006                 ofproto_rule_destroy__(op->victim);
3007             }
3008         } else {
3009             if (op->victim) {
3010                 classifier_replace(table, &op->victim->cr);
3011                 op->victim = NULL;
3012             } else {
3013                 classifier_remove(table, &rule->cr);
3014             }
3015             ofproto_rule_destroy__(rule);
3016         }
3017         op->victim = NULL;
3018         break;
3019
3020     case OFOPERATION_DELETE:
3021         assert(!error);
3022         ofproto_rule_destroy__(rule);
3023         op->rule = NULL;
3024         break;
3025
3026     case OFOPERATION_MODIFY:
3027         if (!error) {
3028             rule->modified = time_msec();
3029         } else {
3030             free(rule->actions);
3031             rule->actions = op->actions;
3032             rule->n_actions = op->n_actions;
3033             op->actions = NULL;
3034         }
3035         break;
3036
3037     default:
3038         NOT_REACHED();
3039     }
3040     ofoperation_destroy(op);
3041 }
3042
3043 struct rule *
3044 ofoperation_get_victim(struct ofoperation *op)
3045 {
3046     assert(op->type == OFOPERATION_ADD);
3047     return op->victim;
3048 }
3049 \f
3050 static uint64_t
3051 pick_datapath_id(const struct ofproto *ofproto)
3052 {
3053     const struct ofport *port;
3054
3055     port = ofproto_get_port(ofproto, OFPP_LOCAL);
3056     if (port) {
3057         uint8_t ea[ETH_ADDR_LEN];
3058         int error;
3059
3060         error = netdev_get_etheraddr(port->netdev, ea);
3061         if (!error) {
3062             return eth_addr_to_uint64(ea);
3063         }
3064         VLOG_WARN("could not get MAC address for %s (%s)",
3065                   netdev_get_name(port->netdev), strerror(error));
3066     }
3067     return ofproto->fallback_dpid;
3068 }
3069
3070 static uint64_t
3071 pick_fallback_dpid(void)
3072 {
3073     uint8_t ea[ETH_ADDR_LEN];
3074     eth_addr_nicira_random(ea);
3075     return eth_addr_to_uint64(ea);
3076 }
3077 \f
3078 /* unixctl commands. */
3079
3080 struct ofproto *
3081 ofproto_lookup(const char *name)
3082 {
3083     struct ofproto *ofproto;
3084
3085     HMAP_FOR_EACH_WITH_HASH (ofproto, hmap_node, hash_string(name, 0),
3086                              &all_ofprotos) {
3087         if (!strcmp(ofproto->name, name)) {
3088             return ofproto;
3089         }
3090     }
3091     return NULL;
3092 }
3093
3094 static void
3095 ofproto_unixctl_list(struct unixctl_conn *conn, const char *arg OVS_UNUSED,
3096                      void *aux OVS_UNUSED)
3097 {
3098     struct ofproto *ofproto;
3099     struct ds results;
3100
3101     ds_init(&results);
3102     HMAP_FOR_EACH (ofproto, hmap_node, &all_ofprotos) {
3103         ds_put_format(&results, "%s\n", ofproto->name);
3104     }
3105     unixctl_command_reply(conn, 200, ds_cstr(&results));
3106     ds_destroy(&results);
3107 }
3108
3109 static void
3110 ofproto_unixctl_init(void)
3111 {
3112     static bool registered;
3113     if (registered) {
3114         return;
3115     }
3116     registered = true;
3117
3118     unixctl_command_register("ofproto/list", "", ofproto_unixctl_list, NULL);
3119 }