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