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