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