]> git.proxmox.com Git - ovs.git/blob - ofproto/ofproto.c
datapath: Make adding and attaching a vport a single step.
[ovs.git] / ofproto / ofproto.c
1 /*
2 * Copyright (c) 2009, 2010 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 <sys/socket.h>
23 #include <net/if.h>
24 #include <netinet/in.h>
25 #include <stdbool.h>
26 #include <stdlib.h>
27 #include "byte-order.h"
28 #include "classifier.h"
29 #include "coverage.h"
30 #include "discovery.h"
31 #include "dpif.h"
32 #include "dynamic-string.h"
33 #include "fail-open.h"
34 #include "hash.h"
35 #include "hmap.h"
36 #include "in-band.h"
37 #include "mac-learning.h"
38 #include "netdev.h"
39 #include "netflow.h"
40 #include "nx-match.h"
41 #include "odp-util.h"
42 #include "ofp-print.h"
43 #include "ofp-util.h"
44 #include "ofproto-sflow.h"
45 #include "ofpbuf.h"
46 #include "openflow/nicira-ext.h"
47 #include "openflow/openflow.h"
48 #include "openvswitch/datapath-protocol.h"
49 #include "packets.h"
50 #include "pinsched.h"
51 #include "pktbuf.h"
52 #include "poll-loop.h"
53 #include "rconn.h"
54 #include "shash.h"
55 #include "status.h"
56 #include "stream-ssl.h"
57 #include "svec.h"
58 #include "tag.h"
59 #include "timeval.h"
60 #include "unixctl.h"
61 #include "vconn.h"
62 #include "vlog.h"
63
64 VLOG_DEFINE_THIS_MODULE(ofproto);
65
66 COVERAGE_DEFINE(facet_changed_rule);
67 COVERAGE_DEFINE(facet_revalidate);
68 COVERAGE_DEFINE(odp_overflow);
69 COVERAGE_DEFINE(ofproto_agg_request);
70 COVERAGE_DEFINE(ofproto_costly_flags);
71 COVERAGE_DEFINE(ofproto_ctlr_action);
72 COVERAGE_DEFINE(ofproto_del_rule);
73 COVERAGE_DEFINE(ofproto_error);
74 COVERAGE_DEFINE(ofproto_expiration);
75 COVERAGE_DEFINE(ofproto_expired);
76 COVERAGE_DEFINE(ofproto_flows_req);
77 COVERAGE_DEFINE(ofproto_flush);
78 COVERAGE_DEFINE(ofproto_invalidated);
79 COVERAGE_DEFINE(ofproto_no_packet_in);
80 COVERAGE_DEFINE(ofproto_ofconn_stuck);
81 COVERAGE_DEFINE(ofproto_ofp2odp);
82 COVERAGE_DEFINE(ofproto_packet_in);
83 COVERAGE_DEFINE(ofproto_packet_out);
84 COVERAGE_DEFINE(ofproto_queue_req);
85 COVERAGE_DEFINE(ofproto_recv_openflow);
86 COVERAGE_DEFINE(ofproto_reinit_ports);
87 COVERAGE_DEFINE(ofproto_unexpected_rule);
88 COVERAGE_DEFINE(ofproto_uninstallable);
89 COVERAGE_DEFINE(ofproto_update_port);
90
91 #include "sflow_api.h"
92
93 struct ofport {
94 struct hmap_node hmap_node; /* In struct ofproto's "ports" hmap. */
95 struct netdev *netdev;
96 struct ofp_phy_port opp; /* In host byte order. */
97 uint16_t odp_port;
98 };
99
100 static void ofport_free(struct ofport *);
101 static void hton_ofp_phy_port(struct ofp_phy_port *);
102
103 static int xlate_actions(const union ofp_action *in, size_t n_in,
104 const struct flow *, struct ofproto *,
105 const struct ofpbuf *packet,
106 struct odp_actions *out, tag_type *tags,
107 bool *may_set_up_flow, uint16_t *nf_output_iface);
108
109 /* An OpenFlow flow. */
110 struct rule {
111 long long int used; /* Time last used; time created if not used. */
112 long long int created; /* Creation time. */
113
114 /* These statistics:
115 *
116 * - Do include packets and bytes from facets that have been deleted or
117 * whose own statistics have been folded into the rule.
118 *
119 * - Do include packets and bytes sent "by hand" that were accounted to
120 * the rule without any facet being involved (this is a rare corner
121 * case in rule_execute()).
122 *
123 * - Do not include packet or bytes that can be obtained from any facet's
124 * packet_count or byte_count member or that can be obtained from the
125 * datapath by, e.g., dpif_flow_get() for any facet.
126 */
127 uint64_t packet_count; /* Number of packets received. */
128 uint64_t byte_count; /* Number of bytes received. */
129
130 ovs_be64 flow_cookie; /* Controller-issued identifier. */
131
132 struct cls_rule cr; /* In owning ofproto's classifier. */
133 uint16_t idle_timeout; /* In seconds from time of last use. */
134 uint16_t hard_timeout; /* In seconds from time of creation. */
135 bool send_flow_removed; /* Send a flow removed message? */
136 int n_actions; /* Number of elements in actions[]. */
137 union ofp_action *actions; /* OpenFlow actions. */
138 struct list facets; /* List of "struct facet"s. */
139 };
140
141 static struct rule *rule_from_cls_rule(const struct cls_rule *);
142 static bool rule_is_hidden(const struct rule *);
143
144 static struct rule *rule_create(const struct cls_rule *,
145 const union ofp_action *, size_t n_actions,
146 uint16_t idle_timeout, uint16_t hard_timeout,
147 ovs_be64 flow_cookie, bool send_flow_removed);
148 static void rule_destroy(struct ofproto *, struct rule *);
149 static void rule_free(struct rule *);
150
151 static struct rule *rule_lookup(struct ofproto *, const struct flow *);
152 static void rule_insert(struct ofproto *, struct rule *);
153 static void rule_remove(struct ofproto *, struct rule *);
154
155 static void rule_send_removed(struct ofproto *, struct rule *, uint8_t reason);
156
157 /* An exact-match instantiation of an OpenFlow flow. */
158 struct facet {
159 long long int used; /* Time last used; time created if not used. */
160
161 /* These statistics:
162 *
163 * - Do include packets and bytes sent "by hand", e.g. with
164 * dpif_execute().
165 *
166 * - Do include packets and bytes that were obtained from the datapath
167 * when a flow was deleted (e.g. dpif_flow_del()) or when its
168 * statistics were reset (e.g. dpif_flow_put() with ODPPF_ZERO_STATS).
169 *
170 * - Do not include any packets or bytes that can currently be obtained
171 * from the datapath by, e.g., dpif_flow_get().
172 */
173 uint64_t packet_count; /* Number of packets received. */
174 uint64_t byte_count; /* Number of bytes received. */
175
176 /* Number of bytes passed to account_cb. This may include bytes that can
177 * currently obtained from the datapath (thus, it can be greater than
178 * byte_count). */
179 uint64_t accounted_bytes;
180
181 struct hmap_node hmap_node; /* In owning ofproto's 'facets' hmap. */
182 struct list list_node; /* In owning rule's 'facets' list. */
183 struct rule *rule; /* Owning rule. */
184 struct flow flow; /* Exact-match flow. */
185 bool installed; /* Installed in datapath? */
186 bool may_install; /* True ordinarily; false if actions must
187 * be reassessed for every packet. */
188 int n_actions; /* Number of elements in actions[]. */
189 union odp_action *actions; /* Datapath actions. */
190 tag_type tags; /* Tags (set only by hooks). */
191 struct netflow_flow nf_flow; /* Per-flow NetFlow tracking data. */
192 };
193
194 static struct facet *facet_create(struct ofproto *, struct rule *,
195 const struct flow *,
196 const struct ofpbuf *packet);
197 static void facet_remove(struct ofproto *, struct facet *);
198 static void facet_free(struct facet *);
199
200 static struct facet *facet_lookup_valid(struct ofproto *, const struct flow *);
201 static bool facet_revalidate(struct ofproto *, struct facet *);
202
203 static void facet_install(struct ofproto *, struct facet *, bool zero_stats);
204 static void facet_uninstall(struct ofproto *, struct facet *);
205 static void facet_flush_stats(struct ofproto *, struct facet *);
206
207 static void facet_make_actions(struct ofproto *, struct facet *,
208 const struct ofpbuf *packet);
209 static void facet_update_stats(struct ofproto *, struct facet *,
210 const struct odp_flow_stats *);
211
212 /* ofproto supports two kinds of OpenFlow connections:
213 *
214 * - "Primary" connections to ordinary OpenFlow controllers. ofproto
215 * maintains persistent connections to these controllers and by default
216 * sends them asynchronous messages such as packet-ins.
217 *
218 * - "Service" connections, e.g. from ovs-ofctl. When these connections
219 * drop, it is the other side's responsibility to reconnect them if
220 * necessary. ofproto does not send them asynchronous messages by default.
221 *
222 * Currently, active (tcp, ssl, unix) connections are always "primary"
223 * connections and passive (ptcp, pssl, punix) connections are always "service"
224 * connections. There is no inherent reason for this, but it reflects the
225 * common case.
226 */
227 enum ofconn_type {
228 OFCONN_PRIMARY, /* An ordinary OpenFlow controller. */
229 OFCONN_SERVICE /* A service connection, e.g. "ovs-ofctl". */
230 };
231
232 /* A listener for incoming OpenFlow "service" connections. */
233 struct ofservice {
234 struct hmap_node node; /* In struct ofproto's "services" hmap. */
235 struct pvconn *pvconn; /* OpenFlow connection listener. */
236
237 /* These are not used by ofservice directly. They are settings for
238 * accepted "struct ofconn"s from the pvconn. */
239 int probe_interval; /* Max idle time before probing, in seconds. */
240 int rate_limit; /* Max packet-in rate in packets per second. */
241 int burst_limit; /* Limit on accumulating packet credits. */
242 };
243
244 static struct ofservice *ofservice_lookup(struct ofproto *,
245 const char *target);
246 static int ofservice_create(struct ofproto *,
247 const struct ofproto_controller *);
248 static void ofservice_reconfigure(struct ofservice *,
249 const struct ofproto_controller *);
250 static void ofservice_destroy(struct ofproto *, struct ofservice *);
251
252 /* An OpenFlow connection. */
253 struct ofconn {
254 struct ofproto *ofproto; /* The ofproto that owns this connection. */
255 struct list node; /* In struct ofproto's "all_conns" list. */
256 struct rconn *rconn; /* OpenFlow connection. */
257 enum ofconn_type type; /* Type. */
258 enum nx_flow_format flow_format; /* Currently selected flow format. */
259
260 /* OFPT_PACKET_IN related data. */
261 struct rconn_packet_counter *packet_in_counter; /* # queued on 'rconn'. */
262 struct pinsched *schedulers[2]; /* Indexed by reason code; see below. */
263 struct pktbuf *pktbuf; /* OpenFlow packet buffers. */
264 int miss_send_len; /* Bytes to send of buffered packets. */
265
266 /* Number of OpenFlow messages queued on 'rconn' as replies to OpenFlow
267 * requests, and the maximum number before we stop reading OpenFlow
268 * requests. */
269 #define OFCONN_REPLY_MAX 100
270 struct rconn_packet_counter *reply_counter;
271
272 /* type == OFCONN_PRIMARY only. */
273 enum nx_role role; /* Role. */
274 struct hmap_node hmap_node; /* In struct ofproto's "controllers" map. */
275 struct discovery *discovery; /* Controller discovery object, if enabled. */
276 struct status_category *ss; /* Switch status category. */
277 enum ofproto_band band; /* In-band or out-of-band? */
278 };
279
280 /* We use OFPR_NO_MATCH and OFPR_ACTION as indexes into struct ofconn's
281 * "schedulers" array. Their values are 0 and 1, and their meanings and values
282 * coincide with _ODPL_MISS_NR and _ODPL_ACTION_NR, so this is convenient. In
283 * case anything ever changes, check their values here. */
284 #define N_SCHEDULERS 2
285 BUILD_ASSERT_DECL(OFPR_NO_MATCH == 0);
286 BUILD_ASSERT_DECL(OFPR_NO_MATCH == _ODPL_MISS_NR);
287 BUILD_ASSERT_DECL(OFPR_ACTION == 1);
288 BUILD_ASSERT_DECL(OFPR_ACTION == _ODPL_ACTION_NR);
289
290 static struct ofconn *ofconn_create(struct ofproto *, struct rconn *,
291 enum ofconn_type);
292 static void ofconn_destroy(struct ofconn *);
293 static void ofconn_run(struct ofconn *);
294 static void ofconn_wait(struct ofconn *);
295 static bool ofconn_receives_async_msgs(const struct ofconn *);
296 static char *ofconn_make_name(const struct ofproto *, const char *target);
297 static void ofconn_set_rate_limit(struct ofconn *, int rate, int burst);
298
299 static void queue_tx(struct ofpbuf *msg, const struct ofconn *ofconn,
300 struct rconn_packet_counter *counter);
301
302 static void send_packet_in(struct ofproto *, struct ofpbuf *odp_msg);
303 static void do_send_packet_in(struct ofpbuf *odp_msg, void *ofconn);
304
305 struct ofproto {
306 /* Settings. */
307 uint64_t datapath_id; /* Datapath ID. */
308 uint64_t fallback_dpid; /* Datapath ID if no better choice found. */
309 char *mfr_desc; /* Manufacturer. */
310 char *hw_desc; /* Hardware. */
311 char *sw_desc; /* Software version. */
312 char *serial_desc; /* Serial number. */
313 char *dp_desc; /* Datapath description. */
314
315 /* Datapath. */
316 struct dpif *dpif;
317 struct netdev_monitor *netdev_monitor;
318 struct hmap ports; /* Contains "struct ofport"s. */
319 struct shash port_by_name;
320 uint32_t max_ports;
321
322 /* Configuration. */
323 struct switch_status *switch_status;
324 struct fail_open *fail_open;
325 struct netflow *netflow;
326 struct ofproto_sflow *sflow;
327
328 /* In-band control. */
329 struct in_band *in_band;
330 long long int next_in_band_update;
331 struct sockaddr_in *extra_in_band_remotes;
332 size_t n_extra_remotes;
333 int in_band_queue;
334
335 /* Flow table. */
336 struct classifier cls;
337 long long int next_expiration;
338
339 /* Facets. */
340 struct hmap facets;
341 bool need_revalidate;
342 struct tag_set revalidate_set;
343
344 /* OpenFlow connections. */
345 struct hmap controllers; /* Controller "struct ofconn"s. */
346 struct list all_conns; /* Contains "struct ofconn"s. */
347 enum ofproto_fail_mode fail_mode;
348
349 /* OpenFlow listeners. */
350 struct hmap services; /* Contains "struct ofservice"s. */
351 struct pvconn **snoops;
352 size_t n_snoops;
353
354 /* Hooks for ovs-vswitchd. */
355 const struct ofhooks *ofhooks;
356 void *aux;
357
358 /* Used by default ofhooks. */
359 struct mac_learning *ml;
360 };
361
362 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
363
364 static const struct ofhooks default_ofhooks;
365
366 static uint64_t pick_datapath_id(const struct ofproto *);
367 static uint64_t pick_fallback_dpid(void);
368
369 static int ofproto_expire(struct ofproto *);
370
371 static void handle_odp_msg(struct ofproto *, struct ofpbuf *);
372
373 static void handle_openflow(struct ofconn *, struct ofpbuf *);
374
375 static struct ofport *get_port(const struct ofproto *, uint16_t odp_port);
376 static void update_port(struct ofproto *, const char *devname);
377 static int init_ports(struct ofproto *);
378 static void reinit_ports(struct ofproto *);
379
380 int
381 ofproto_create(const char *datapath, const char *datapath_type,
382 const struct ofhooks *ofhooks, void *aux,
383 struct ofproto **ofprotop)
384 {
385 struct odp_stats stats;
386 struct ofproto *p;
387 struct dpif *dpif;
388 int error;
389
390 *ofprotop = NULL;
391
392 /* Connect to datapath and start listening for messages. */
393 error = dpif_open(datapath, datapath_type, &dpif);
394 if (error) {
395 VLOG_ERR("failed to open datapath %s: %s", datapath, strerror(error));
396 return error;
397 }
398 error = dpif_get_dp_stats(dpif, &stats);
399 if (error) {
400 VLOG_ERR("failed to obtain stats for datapath %s: %s",
401 datapath, strerror(error));
402 dpif_close(dpif);
403 return error;
404 }
405 error = dpif_recv_set_mask(dpif, ODPL_MISS | ODPL_ACTION | ODPL_SFLOW);
406 if (error) {
407 VLOG_ERR("failed to listen on datapath %s: %s",
408 datapath, strerror(error));
409 dpif_close(dpif);
410 return error;
411 }
412 dpif_flow_flush(dpif);
413 dpif_recv_purge(dpif);
414
415 /* Initialize settings. */
416 p = xzalloc(sizeof *p);
417 p->fallback_dpid = pick_fallback_dpid();
418 p->datapath_id = p->fallback_dpid;
419 p->mfr_desc = xstrdup(DEFAULT_MFR_DESC);
420 p->hw_desc = xstrdup(DEFAULT_HW_DESC);
421 p->sw_desc = xstrdup(DEFAULT_SW_DESC);
422 p->serial_desc = xstrdup(DEFAULT_SERIAL_DESC);
423 p->dp_desc = xstrdup(DEFAULT_DP_DESC);
424
425 /* Initialize datapath. */
426 p->dpif = dpif;
427 p->netdev_monitor = netdev_monitor_create();
428 hmap_init(&p->ports);
429 shash_init(&p->port_by_name);
430 p->max_ports = stats.max_ports;
431
432 /* Initialize submodules. */
433 p->switch_status = switch_status_create(p);
434 p->fail_open = NULL;
435 p->netflow = NULL;
436 p->sflow = NULL;
437
438 /* Initialize in-band control. */
439 p->in_band = NULL;
440 p->in_band_queue = -1;
441
442 /* Initialize flow table. */
443 classifier_init(&p->cls);
444 p->next_expiration = time_msec() + 1000;
445
446 /* Initialize facet table. */
447 hmap_init(&p->facets);
448 p->need_revalidate = false;
449 tag_set_init(&p->revalidate_set);
450
451 /* Initialize OpenFlow connections. */
452 list_init(&p->all_conns);
453 hmap_init(&p->controllers);
454 hmap_init(&p->services);
455 p->snoops = NULL;
456 p->n_snoops = 0;
457
458 /* Initialize hooks. */
459 if (ofhooks) {
460 p->ofhooks = ofhooks;
461 p->aux = aux;
462 p->ml = NULL;
463 } else {
464 p->ofhooks = &default_ofhooks;
465 p->aux = p;
466 p->ml = mac_learning_create();
467 }
468
469 /* Pick final datapath ID. */
470 p->datapath_id = pick_datapath_id(p);
471 VLOG_INFO("using datapath ID %016"PRIx64, p->datapath_id);
472
473 *ofprotop = p;
474 return 0;
475 }
476
477 void
478 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
479 {
480 uint64_t old_dpid = p->datapath_id;
481 p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
482 if (p->datapath_id != old_dpid) {
483 VLOG_INFO("datapath ID changed to %016"PRIx64, p->datapath_id);
484
485 /* Force all active connections to reconnect, since there is no way to
486 * notify a controller that the datapath ID has changed. */
487 ofproto_reconnect_controllers(p);
488 }
489 }
490
491 static bool
492 is_discovery_controller(const struct ofproto_controller *c)
493 {
494 return !strcmp(c->target, "discover");
495 }
496
497 static bool
498 is_in_band_controller(const struct ofproto_controller *c)
499 {
500 return is_discovery_controller(c) || c->band == OFPROTO_IN_BAND;
501 }
502
503 /* Creates a new controller in 'ofproto'. Some of the settings are initially
504 * drawn from 'c', but update_controller() needs to be called later to finish
505 * the new ofconn's configuration. */
506 static void
507 add_controller(struct ofproto *ofproto, const struct ofproto_controller *c)
508 {
509 struct discovery *discovery;
510 struct ofconn *ofconn;
511
512 if (is_discovery_controller(c)) {
513 int error = discovery_create(c->accept_re, c->update_resolv_conf,
514 ofproto->dpif, ofproto->switch_status,
515 &discovery);
516 if (error) {
517 return;
518 }
519 } else {
520 discovery = NULL;
521 }
522
523 ofconn = ofconn_create(ofproto, rconn_create(5, 8), OFCONN_PRIMARY);
524 ofconn->pktbuf = pktbuf_create();
525 ofconn->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
526 if (discovery) {
527 ofconn->discovery = discovery;
528 } else {
529 char *name = ofconn_make_name(ofproto, c->target);
530 rconn_connect(ofconn->rconn, c->target, name);
531 free(name);
532 }
533 hmap_insert(&ofproto->controllers, &ofconn->hmap_node,
534 hash_string(c->target, 0));
535 }
536
537 /* Reconfigures 'ofconn' to match 'c'. This function cannot update an ofconn's
538 * target or turn discovery on or off (these are done by creating new ofconns
539 * and deleting old ones), but it can update the rest of an ofconn's
540 * settings. */
541 static void
542 update_controller(struct ofconn *ofconn, const struct ofproto_controller *c)
543 {
544 int probe_interval;
545
546 ofconn->band = (is_in_band_controller(c)
547 ? OFPROTO_IN_BAND : OFPROTO_OUT_OF_BAND);
548
549 rconn_set_max_backoff(ofconn->rconn, c->max_backoff);
550
551 probe_interval = c->probe_interval ? MAX(c->probe_interval, 5) : 0;
552 rconn_set_probe_interval(ofconn->rconn, probe_interval);
553
554 if (ofconn->discovery) {
555 discovery_set_update_resolv_conf(ofconn->discovery,
556 c->update_resolv_conf);
557 discovery_set_accept_controller_re(ofconn->discovery, c->accept_re);
558 }
559
560 ofconn_set_rate_limit(ofconn, c->rate_limit, c->burst_limit);
561 }
562
563 static const char *
564 ofconn_get_target(const struct ofconn *ofconn)
565 {
566 return ofconn->discovery ? "discover" : rconn_get_target(ofconn->rconn);
567 }
568
569 static struct ofconn *
570 find_controller_by_target(struct ofproto *ofproto, const char *target)
571 {
572 struct ofconn *ofconn;
573
574 HMAP_FOR_EACH_WITH_HASH (ofconn, hmap_node,
575 hash_string(target, 0), &ofproto->controllers) {
576 if (!strcmp(ofconn_get_target(ofconn), target)) {
577 return ofconn;
578 }
579 }
580 return NULL;
581 }
582
583 static void
584 update_in_band_remotes(struct ofproto *ofproto)
585 {
586 const struct ofconn *ofconn;
587 struct sockaddr_in *addrs;
588 size_t max_addrs, n_addrs;
589 bool discovery;
590 size_t i;
591
592 /* Allocate enough memory for as many remotes as we could possibly have. */
593 max_addrs = ofproto->n_extra_remotes + hmap_count(&ofproto->controllers);
594 addrs = xmalloc(max_addrs * sizeof *addrs);
595 n_addrs = 0;
596
597 /* Add all the remotes. */
598 discovery = false;
599 HMAP_FOR_EACH (ofconn, hmap_node, &ofproto->controllers) {
600 struct sockaddr_in *sin = &addrs[n_addrs];
601
602 if (ofconn->band == OFPROTO_OUT_OF_BAND) {
603 continue;
604 }
605
606 sin->sin_addr.s_addr = rconn_get_remote_ip(ofconn->rconn);
607 if (sin->sin_addr.s_addr) {
608 sin->sin_port = rconn_get_remote_port(ofconn->rconn);
609 n_addrs++;
610 }
611 if (ofconn->discovery) {
612 discovery = true;
613 }
614 }
615 for (i = 0; i < ofproto->n_extra_remotes; i++) {
616 addrs[n_addrs++] = ofproto->extra_in_band_remotes[i];
617 }
618
619 /* Create or update or destroy in-band.
620 *
621 * Ordinarily we only enable in-band if there's at least one remote
622 * address, but discovery needs the in-band rules for DHCP to be installed
623 * even before we know any remote addresses. */
624 if (n_addrs || discovery) {
625 if (!ofproto->in_band) {
626 in_band_create(ofproto, ofproto->dpif, ofproto->switch_status,
627 &ofproto->in_band);
628 }
629 if (ofproto->in_band) {
630 in_band_set_remotes(ofproto->in_band, addrs, n_addrs);
631 }
632 in_band_set_queue(ofproto->in_band, ofproto->in_band_queue);
633 ofproto->next_in_band_update = time_msec() + 1000;
634 } else {
635 in_band_destroy(ofproto->in_band);
636 ofproto->in_band = NULL;
637 }
638
639 /* Clean up. */
640 free(addrs);
641 }
642
643 static void
644 update_fail_open(struct ofproto *p)
645 {
646 struct ofconn *ofconn;
647
648 if (!hmap_is_empty(&p->controllers)
649 && p->fail_mode == OFPROTO_FAIL_STANDALONE) {
650 struct rconn **rconns;
651 size_t n;
652
653 if (!p->fail_open) {
654 p->fail_open = fail_open_create(p, p->switch_status);
655 }
656
657 n = 0;
658 rconns = xmalloc(hmap_count(&p->controllers) * sizeof *rconns);
659 HMAP_FOR_EACH (ofconn, hmap_node, &p->controllers) {
660 rconns[n++] = ofconn->rconn;
661 }
662
663 fail_open_set_controllers(p->fail_open, rconns, n);
664 /* p->fail_open takes ownership of 'rconns'. */
665 } else {
666 fail_open_destroy(p->fail_open);
667 p->fail_open = NULL;
668 }
669 }
670
671 void
672 ofproto_set_controllers(struct ofproto *p,
673 const struct ofproto_controller *controllers,
674 size_t n_controllers)
675 {
676 struct shash new_controllers;
677 struct ofconn *ofconn, *next_ofconn;
678 struct ofservice *ofservice, *next_ofservice;
679 bool ss_exists;
680 size_t i;
681
682 /* Create newly configured controllers and services.
683 * Create a name to ofproto_controller mapping in 'new_controllers'. */
684 shash_init(&new_controllers);
685 for (i = 0; i < n_controllers; i++) {
686 const struct ofproto_controller *c = &controllers[i];
687
688 if (!vconn_verify_name(c->target) || !strcmp(c->target, "discover")) {
689 if (!find_controller_by_target(p, c->target)) {
690 add_controller(p, c);
691 }
692 } else if (!pvconn_verify_name(c->target)) {
693 if (!ofservice_lookup(p, c->target) && ofservice_create(p, c)) {
694 continue;
695 }
696 } else {
697 VLOG_WARN_RL(&rl, "%s: unsupported controller \"%s\"",
698 dpif_name(p->dpif), c->target);
699 continue;
700 }
701
702 shash_add_once(&new_controllers, c->target, &controllers[i]);
703 }
704
705 /* Delete controllers that are no longer configured.
706 * Update configuration of all now-existing controllers. */
707 ss_exists = false;
708 HMAP_FOR_EACH_SAFE (ofconn, next_ofconn, hmap_node, &p->controllers) {
709 struct ofproto_controller *c;
710
711 c = shash_find_data(&new_controllers, ofconn_get_target(ofconn));
712 if (!c) {
713 ofconn_destroy(ofconn);
714 } else {
715 update_controller(ofconn, c);
716 if (ofconn->ss) {
717 ss_exists = true;
718 }
719 }
720 }
721
722 /* Delete services that are no longer configured.
723 * Update configuration of all now-existing services. */
724 HMAP_FOR_EACH_SAFE (ofservice, next_ofservice, node, &p->services) {
725 struct ofproto_controller *c;
726
727 c = shash_find_data(&new_controllers,
728 pvconn_get_name(ofservice->pvconn));
729 if (!c) {
730 ofservice_destroy(p, ofservice);
731 } else {
732 ofservice_reconfigure(ofservice, c);
733 }
734 }
735
736 shash_destroy(&new_controllers);
737
738 update_in_band_remotes(p);
739 update_fail_open(p);
740
741 if (!hmap_is_empty(&p->controllers) && !ss_exists) {
742 ofconn = CONTAINER_OF(hmap_first(&p->controllers),
743 struct ofconn, hmap_node);
744 ofconn->ss = switch_status_register(p->switch_status, "remote",
745 rconn_status_cb, ofconn->rconn);
746 }
747 }
748
749 void
750 ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
751 {
752 p->fail_mode = fail_mode;
753 update_fail_open(p);
754 }
755
756 /* Drops the connections between 'ofproto' and all of its controllers, forcing
757 * them to reconnect. */
758 void
759 ofproto_reconnect_controllers(struct ofproto *ofproto)
760 {
761 struct ofconn *ofconn;
762
763 LIST_FOR_EACH (ofconn, node, &ofproto->all_conns) {
764 rconn_reconnect(ofconn->rconn);
765 }
766 }
767
768 static bool
769 any_extras_changed(const struct ofproto *ofproto,
770 const struct sockaddr_in *extras, size_t n)
771 {
772 size_t i;
773
774 if (n != ofproto->n_extra_remotes) {
775 return true;
776 }
777
778 for (i = 0; i < n; i++) {
779 const struct sockaddr_in *old = &ofproto->extra_in_band_remotes[i];
780 const struct sockaddr_in *new = &extras[i];
781
782 if (old->sin_addr.s_addr != new->sin_addr.s_addr ||
783 old->sin_port != new->sin_port) {
784 return true;
785 }
786 }
787
788 return false;
789 }
790
791 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
792 * in-band control should guarantee access, in the same way that in-band
793 * control guarantees access to OpenFlow controllers. */
794 void
795 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
796 const struct sockaddr_in *extras, size_t n)
797 {
798 if (!any_extras_changed(ofproto, extras, n)) {
799 return;
800 }
801
802 free(ofproto->extra_in_band_remotes);
803 ofproto->n_extra_remotes = n;
804 ofproto->extra_in_band_remotes = xmemdup(extras, n * sizeof *extras);
805
806 update_in_band_remotes(ofproto);
807 }
808
809 /* Sets the OpenFlow queue used by flows set up by in-band control on
810 * 'ofproto' to 'queue_id'. If 'queue_id' is negative, then in-band control
811 * flows will use the default queue. */
812 void
813 ofproto_set_in_band_queue(struct ofproto *ofproto, int queue_id)
814 {
815 if (queue_id != ofproto->in_band_queue) {
816 ofproto->in_band_queue = queue_id;
817 update_in_band_remotes(ofproto);
818 }
819 }
820
821 void
822 ofproto_set_desc(struct ofproto *p,
823 const char *mfr_desc, const char *hw_desc,
824 const char *sw_desc, const char *serial_desc,
825 const char *dp_desc)
826 {
827 struct ofp_desc_stats *ods;
828
829 if (mfr_desc) {
830 if (strlen(mfr_desc) >= sizeof ods->mfr_desc) {
831 VLOG_WARN("truncating mfr_desc, must be less than %zu characters",
832 sizeof ods->mfr_desc);
833 }
834 free(p->mfr_desc);
835 p->mfr_desc = xstrdup(mfr_desc);
836 }
837 if (hw_desc) {
838 if (strlen(hw_desc) >= sizeof ods->hw_desc) {
839 VLOG_WARN("truncating hw_desc, must be less than %zu characters",
840 sizeof ods->hw_desc);
841 }
842 free(p->hw_desc);
843 p->hw_desc = xstrdup(hw_desc);
844 }
845 if (sw_desc) {
846 if (strlen(sw_desc) >= sizeof ods->sw_desc) {
847 VLOG_WARN("truncating sw_desc, must be less than %zu characters",
848 sizeof ods->sw_desc);
849 }
850 free(p->sw_desc);
851 p->sw_desc = xstrdup(sw_desc);
852 }
853 if (serial_desc) {
854 if (strlen(serial_desc) >= sizeof ods->serial_num) {
855 VLOG_WARN("truncating serial_desc, must be less than %zu "
856 "characters",
857 sizeof ods->serial_num);
858 }
859 free(p->serial_desc);
860 p->serial_desc = xstrdup(serial_desc);
861 }
862 if (dp_desc) {
863 if (strlen(dp_desc) >= sizeof ods->dp_desc) {
864 VLOG_WARN("truncating dp_desc, must be less than %zu characters",
865 sizeof ods->dp_desc);
866 }
867 free(p->dp_desc);
868 p->dp_desc = xstrdup(dp_desc);
869 }
870 }
871
872 static int
873 set_pvconns(struct pvconn ***pvconnsp, size_t *n_pvconnsp,
874 const struct svec *svec)
875 {
876 struct pvconn **pvconns = *pvconnsp;
877 size_t n_pvconns = *n_pvconnsp;
878 int retval = 0;
879 size_t i;
880
881 for (i = 0; i < n_pvconns; i++) {
882 pvconn_close(pvconns[i]);
883 }
884 free(pvconns);
885
886 pvconns = xmalloc(svec->n * sizeof *pvconns);
887 n_pvconns = 0;
888 for (i = 0; i < svec->n; i++) {
889 const char *name = svec->names[i];
890 struct pvconn *pvconn;
891 int error;
892
893 error = pvconn_open(name, &pvconn);
894 if (!error) {
895 pvconns[n_pvconns++] = pvconn;
896 } else {
897 VLOG_ERR("failed to listen on %s: %s", name, strerror(error));
898 if (!retval) {
899 retval = error;
900 }
901 }
902 }
903
904 *pvconnsp = pvconns;
905 *n_pvconnsp = n_pvconns;
906
907 return retval;
908 }
909
910 int
911 ofproto_set_snoops(struct ofproto *ofproto, const struct svec *snoops)
912 {
913 return set_pvconns(&ofproto->snoops, &ofproto->n_snoops, snoops);
914 }
915
916 int
917 ofproto_set_netflow(struct ofproto *ofproto,
918 const struct netflow_options *nf_options)
919 {
920 if (nf_options && nf_options->collectors.n) {
921 if (!ofproto->netflow) {
922 ofproto->netflow = netflow_create();
923 }
924 return netflow_set_options(ofproto->netflow, nf_options);
925 } else {
926 netflow_destroy(ofproto->netflow);
927 ofproto->netflow = NULL;
928 return 0;
929 }
930 }
931
932 void
933 ofproto_set_sflow(struct ofproto *ofproto,
934 const struct ofproto_sflow_options *oso)
935 {
936 struct ofproto_sflow *os = ofproto->sflow;
937 if (oso) {
938 if (!os) {
939 struct ofport *ofport;
940
941 os = ofproto->sflow = ofproto_sflow_create(ofproto->dpif);
942 HMAP_FOR_EACH (ofport, hmap_node, &ofproto->ports) {
943 ofproto_sflow_add_port(os, ofport->odp_port,
944 netdev_get_name(ofport->netdev));
945 }
946 }
947 ofproto_sflow_set_options(os, oso);
948 } else {
949 ofproto_sflow_destroy(os);
950 ofproto->sflow = NULL;
951 }
952 }
953
954 uint64_t
955 ofproto_get_datapath_id(const struct ofproto *ofproto)
956 {
957 return ofproto->datapath_id;
958 }
959
960 bool
961 ofproto_has_primary_controller(const struct ofproto *ofproto)
962 {
963 return !hmap_is_empty(&ofproto->controllers);
964 }
965
966 enum ofproto_fail_mode
967 ofproto_get_fail_mode(const struct ofproto *p)
968 {
969 return p->fail_mode;
970 }
971
972 void
973 ofproto_get_snoops(const struct ofproto *ofproto, struct svec *snoops)
974 {
975 size_t i;
976
977 for (i = 0; i < ofproto->n_snoops; i++) {
978 svec_add(snoops, pvconn_get_name(ofproto->snoops[i]));
979 }
980 }
981
982 void
983 ofproto_destroy(struct ofproto *p)
984 {
985 struct ofservice *ofservice, *next_ofservice;
986 struct ofconn *ofconn, *next_ofconn;
987 struct ofport *ofport, *next_ofport;
988 size_t i;
989
990 if (!p) {
991 return;
992 }
993
994 /* Destroy fail-open and in-band early, since they touch the classifier. */
995 fail_open_destroy(p->fail_open);
996 p->fail_open = NULL;
997
998 in_band_destroy(p->in_band);
999 p->in_band = NULL;
1000 free(p->extra_in_band_remotes);
1001
1002 ofproto_flush_flows(p);
1003 classifier_destroy(&p->cls);
1004 hmap_destroy(&p->facets);
1005
1006 LIST_FOR_EACH_SAFE (ofconn, next_ofconn, node, &p->all_conns) {
1007 ofconn_destroy(ofconn);
1008 }
1009 hmap_destroy(&p->controllers);
1010
1011 dpif_close(p->dpif);
1012 netdev_monitor_destroy(p->netdev_monitor);
1013 HMAP_FOR_EACH_SAFE (ofport, next_ofport, hmap_node, &p->ports) {
1014 hmap_remove(&p->ports, &ofport->hmap_node);
1015 ofport_free(ofport);
1016 }
1017 shash_destroy(&p->port_by_name);
1018
1019 switch_status_destroy(p->switch_status);
1020 netflow_destroy(p->netflow);
1021 ofproto_sflow_destroy(p->sflow);
1022
1023 HMAP_FOR_EACH_SAFE (ofservice, next_ofservice, node, &p->services) {
1024 ofservice_destroy(p, ofservice);
1025 }
1026 hmap_destroy(&p->services);
1027
1028 for (i = 0; i < p->n_snoops; i++) {
1029 pvconn_close(p->snoops[i]);
1030 }
1031 free(p->snoops);
1032
1033 mac_learning_destroy(p->ml);
1034
1035 free(p->mfr_desc);
1036 free(p->hw_desc);
1037 free(p->sw_desc);
1038 free(p->serial_desc);
1039 free(p->dp_desc);
1040
1041 hmap_destroy(&p->ports);
1042
1043 free(p);
1044 }
1045
1046 int
1047 ofproto_run(struct ofproto *p)
1048 {
1049 int error = ofproto_run1(p);
1050 if (!error) {
1051 error = ofproto_run2(p, false);
1052 }
1053 return error;
1054 }
1055
1056 static void
1057 process_port_change(struct ofproto *ofproto, int error, char *devname)
1058 {
1059 if (error == ENOBUFS) {
1060 reinit_ports(ofproto);
1061 } else if (!error) {
1062 update_port(ofproto, devname);
1063 free(devname);
1064 }
1065 }
1066
1067 /* Returns a "preference level" for snooping 'ofconn'. A higher return value
1068 * means that 'ofconn' is more interesting for monitoring than a lower return
1069 * value. */
1070 static int
1071 snoop_preference(const struct ofconn *ofconn)
1072 {
1073 switch (ofconn->role) {
1074 case NX_ROLE_MASTER:
1075 return 3;
1076 case NX_ROLE_OTHER:
1077 return 2;
1078 case NX_ROLE_SLAVE:
1079 return 1;
1080 default:
1081 /* Shouldn't happen. */
1082 return 0;
1083 }
1084 }
1085
1086 /* One of ofproto's "snoop" pvconns has accepted a new connection on 'vconn'.
1087 * Connects this vconn to a controller. */
1088 static void
1089 add_snooper(struct ofproto *ofproto, struct vconn *vconn)
1090 {
1091 struct ofconn *ofconn, *best;
1092
1093 /* Pick a controller for monitoring. */
1094 best = NULL;
1095 LIST_FOR_EACH (ofconn, node, &ofproto->all_conns) {
1096 if (ofconn->type == OFCONN_PRIMARY
1097 && (!best || snoop_preference(ofconn) > snoop_preference(best))) {
1098 best = ofconn;
1099 }
1100 }
1101
1102 if (best) {
1103 rconn_add_monitor(best->rconn, vconn);
1104 } else {
1105 VLOG_INFO_RL(&rl, "no controller connection to snoop");
1106 vconn_close(vconn);
1107 }
1108 }
1109
1110 int
1111 ofproto_run1(struct ofproto *p)
1112 {
1113 struct ofconn *ofconn, *next_ofconn;
1114 struct ofservice *ofservice;
1115 char *devname;
1116 int error;
1117 int i;
1118
1119 if (shash_is_empty(&p->port_by_name)) {
1120 init_ports(p);
1121 }
1122
1123 for (i = 0; i < 50; i++) {
1124 struct ofpbuf *buf;
1125
1126 error = dpif_recv(p->dpif, &buf);
1127 if (error) {
1128 if (error == ENODEV) {
1129 /* Someone destroyed the datapath behind our back. The caller
1130 * better destroy us and give up, because we're just going to
1131 * spin from here on out. */
1132 static struct vlog_rate_limit rl2 = VLOG_RATE_LIMIT_INIT(1, 5);
1133 VLOG_ERR_RL(&rl2, "%s: datapath was destroyed externally",
1134 dpif_name(p->dpif));
1135 return ENODEV;
1136 }
1137 break;
1138 }
1139
1140 handle_odp_msg(p, buf);
1141 }
1142
1143 while ((error = dpif_port_poll(p->dpif, &devname)) != EAGAIN) {
1144 process_port_change(p, error, devname);
1145 }
1146 while ((error = netdev_monitor_poll(p->netdev_monitor,
1147 &devname)) != EAGAIN) {
1148 process_port_change(p, error, devname);
1149 }
1150
1151 if (p->in_band) {
1152 if (time_msec() >= p->next_in_band_update) {
1153 update_in_band_remotes(p);
1154 }
1155 in_band_run(p->in_band);
1156 }
1157
1158 LIST_FOR_EACH_SAFE (ofconn, next_ofconn, node, &p->all_conns) {
1159 ofconn_run(ofconn);
1160 }
1161
1162 /* Fail-open maintenance. Do this after processing the ofconns since
1163 * fail-open checks the status of the controller rconn. */
1164 if (p->fail_open) {
1165 fail_open_run(p->fail_open);
1166 }
1167
1168 HMAP_FOR_EACH (ofservice, node, &p->services) {
1169 struct vconn *vconn;
1170 int retval;
1171
1172 retval = pvconn_accept(ofservice->pvconn, OFP_VERSION, &vconn);
1173 if (!retval) {
1174 struct rconn *rconn;
1175 char *name;
1176
1177 rconn = rconn_create(ofservice->probe_interval, 0);
1178 name = ofconn_make_name(p, vconn_get_name(vconn));
1179 rconn_connect_unreliably(rconn, vconn, name);
1180 free(name);
1181
1182 ofconn = ofconn_create(p, rconn, OFCONN_SERVICE);
1183 ofconn_set_rate_limit(ofconn, ofservice->rate_limit,
1184 ofservice->burst_limit);
1185 } else if (retval != EAGAIN) {
1186 VLOG_WARN_RL(&rl, "accept failed (%s)", strerror(retval));
1187 }
1188 }
1189
1190 for (i = 0; i < p->n_snoops; i++) {
1191 struct vconn *vconn;
1192 int retval;
1193
1194 retval = pvconn_accept(p->snoops[i], OFP_VERSION, &vconn);
1195 if (!retval) {
1196 add_snooper(p, vconn);
1197 } else if (retval != EAGAIN) {
1198 VLOG_WARN_RL(&rl, "accept failed (%s)", strerror(retval));
1199 }
1200 }
1201
1202 if (time_msec() >= p->next_expiration) {
1203 int delay = ofproto_expire(p);
1204 p->next_expiration = time_msec() + delay;
1205 COVERAGE_INC(ofproto_expiration);
1206 }
1207
1208 if (p->netflow) {
1209 netflow_run(p->netflow);
1210 }
1211 if (p->sflow) {
1212 ofproto_sflow_run(p->sflow);
1213 }
1214
1215 return 0;
1216 }
1217
1218 int
1219 ofproto_run2(struct ofproto *p, bool revalidate_all)
1220 {
1221 /* Figure out what we need to revalidate now, if anything. */
1222 struct tag_set revalidate_set = p->revalidate_set;
1223 if (p->need_revalidate) {
1224 revalidate_all = true;
1225 }
1226
1227 /* Clear the revalidation flags. */
1228 tag_set_init(&p->revalidate_set);
1229 p->need_revalidate = false;
1230
1231 /* Now revalidate if there's anything to do. */
1232 if (revalidate_all || !tag_set_is_empty(&revalidate_set)) {
1233 struct facet *facet, *next;
1234
1235 HMAP_FOR_EACH_SAFE (facet, next, hmap_node, &p->facets) {
1236 if (revalidate_all
1237 || tag_set_intersects(&revalidate_set, facet->tags)) {
1238 facet_revalidate(p, facet);
1239 }
1240 }
1241 }
1242
1243 return 0;
1244 }
1245
1246 void
1247 ofproto_wait(struct ofproto *p)
1248 {
1249 struct ofservice *ofservice;
1250 struct ofconn *ofconn;
1251 size_t i;
1252
1253 dpif_recv_wait(p->dpif);
1254 dpif_port_poll_wait(p->dpif);
1255 netdev_monitor_poll_wait(p->netdev_monitor);
1256 LIST_FOR_EACH (ofconn, node, &p->all_conns) {
1257 ofconn_wait(ofconn);
1258 }
1259 if (p->in_band) {
1260 poll_timer_wait_until(p->next_in_band_update);
1261 in_band_wait(p->in_band);
1262 }
1263 if (p->fail_open) {
1264 fail_open_wait(p->fail_open);
1265 }
1266 if (p->sflow) {
1267 ofproto_sflow_wait(p->sflow);
1268 }
1269 if (!tag_set_is_empty(&p->revalidate_set)) {
1270 poll_immediate_wake();
1271 }
1272 if (p->need_revalidate) {
1273 /* Shouldn't happen, but if it does just go around again. */
1274 VLOG_DBG_RL(&rl, "need revalidate in ofproto_wait_cb()");
1275 poll_immediate_wake();
1276 } else if (p->next_expiration != LLONG_MAX) {
1277 poll_timer_wait_until(p->next_expiration);
1278 }
1279 HMAP_FOR_EACH (ofservice, node, &p->services) {
1280 pvconn_wait(ofservice->pvconn);
1281 }
1282 for (i = 0; i < p->n_snoops; i++) {
1283 pvconn_wait(p->snoops[i]);
1284 }
1285 }
1286
1287 void
1288 ofproto_revalidate(struct ofproto *ofproto, tag_type tag)
1289 {
1290 tag_set_add(&ofproto->revalidate_set, tag);
1291 }
1292
1293 struct tag_set *
1294 ofproto_get_revalidate_set(struct ofproto *ofproto)
1295 {
1296 return &ofproto->revalidate_set;
1297 }
1298
1299 bool
1300 ofproto_is_alive(const struct ofproto *p)
1301 {
1302 return !hmap_is_empty(&p->controllers);
1303 }
1304
1305 /* Deletes port number 'odp_port' from the datapath for 'ofproto'.
1306 *
1307 * This is almost the same as calling dpif_port_del() directly on the
1308 * datapath, but it also makes 'ofproto' close its open netdev for the port
1309 * (if any). This makes it possible to create a new netdev of a different
1310 * type under the same name, which otherwise the netdev library would refuse
1311 * to do because of the conflict. (The netdev would eventually get closed on
1312 * the next trip through ofproto_run(), but this interface is more direct.)
1313 *
1314 * Returns 0 if successful, otherwise a positive errno. */
1315 int
1316 ofproto_port_del(struct ofproto *ofproto, uint16_t odp_port)
1317 {
1318 struct ofport *ofport = get_port(ofproto, odp_port);
1319 const char *name = ofport ? ofport->opp.name : "<unknown>";
1320 int error;
1321
1322 error = dpif_port_del(ofproto->dpif, odp_port);
1323 if (error) {
1324 VLOG_ERR("%s: failed to remove port %"PRIu16" (%s) interface (%s)",
1325 dpif_name(ofproto->dpif), odp_port, name, strerror(error));
1326 } else if (ofport) {
1327 /* 'name' is ofport->opp.name and update_port() is going to destroy
1328 * 'ofport'. Just in case update_port() refers to 'name' after it
1329 * destroys 'ofport', make a copy of it around the update_port()
1330 * call. */
1331 char *devname = xstrdup(name);
1332 update_port(ofproto, devname);
1333 free(devname);
1334 }
1335 return error;
1336 }
1337
1338 /* Checks if 'ofproto' thinks 'odp_port' should be included in floods. Returns
1339 * true if 'odp_port' exists and should be included, false otherwise. */
1340 bool
1341 ofproto_port_is_floodable(struct ofproto *ofproto, uint16_t odp_port)
1342 {
1343 struct ofport *ofport = get_port(ofproto, odp_port);
1344 return ofport && !(ofport->opp.config & OFPPC_NO_FLOOD);
1345 }
1346
1347 int
1348 ofproto_send_packet(struct ofproto *p, const struct flow *flow,
1349 const union ofp_action *actions, size_t n_actions,
1350 const struct ofpbuf *packet)
1351 {
1352 struct odp_actions odp_actions;
1353 int error;
1354
1355 error = xlate_actions(actions, n_actions, flow, p, packet, &odp_actions,
1356 NULL, NULL, NULL);
1357 if (error) {
1358 return error;
1359 }
1360
1361 /* XXX Should we translate the dpif_execute() errno value into an OpenFlow
1362 * error code? */
1363 dpif_execute(p->dpif, odp_actions.actions, odp_actions.n_actions, packet);
1364 return 0;
1365 }
1366
1367 /* Adds a flow to the OpenFlow flow table in 'p' that matches 'cls_rule' and
1368 * performs the 'n_actions' actions in 'actions'. The new flow will not
1369 * timeout.
1370 *
1371 * If cls_rule->priority is in the range of priorities supported by OpenFlow
1372 * (0...65535, inclusive) then the flow will be visible to OpenFlow
1373 * controllers; otherwise, it will be hidden.
1374 *
1375 * The caller retains ownership of 'cls_rule' and 'actions'. */
1376 void
1377 ofproto_add_flow(struct ofproto *p, const struct cls_rule *cls_rule,
1378 const union ofp_action *actions, size_t n_actions)
1379 {
1380 struct rule *rule;
1381 rule = rule_create(cls_rule, actions, n_actions, 0, 0, 0, false);
1382 rule_insert(p, rule);
1383 }
1384
1385 void
1386 ofproto_delete_flow(struct ofproto *ofproto, const struct cls_rule *target)
1387 {
1388 struct rule *rule;
1389
1390 rule = rule_from_cls_rule(classifier_find_rule_exactly(&ofproto->cls,
1391 target));
1392 if (rule) {
1393 rule_remove(ofproto, rule);
1394 }
1395 }
1396
1397 void
1398 ofproto_flush_flows(struct ofproto *ofproto)
1399 {
1400 struct facet *facet, *next_facet;
1401 struct rule *rule, *next_rule;
1402 struct cls_cursor cursor;
1403
1404 COVERAGE_INC(ofproto_flush);
1405
1406 HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
1407 /* Mark the facet as not installed so that facet_remove() doesn't
1408 * bother trying to uninstall it. There is no point in uninstalling it
1409 * individually since we are about to blow away all the facets with
1410 * dpif_flow_flush(). */
1411 facet->installed = false;
1412 facet_remove(ofproto, facet);
1413 }
1414
1415 cls_cursor_init(&cursor, &ofproto->cls, NULL);
1416 CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
1417 rule_remove(ofproto, rule);
1418 }
1419
1420 dpif_flow_flush(ofproto->dpif);
1421 if (ofproto->in_band) {
1422 in_band_flushed(ofproto->in_band);
1423 }
1424 if (ofproto->fail_open) {
1425 fail_open_flushed(ofproto->fail_open);
1426 }
1427 }
1428 \f
1429 static void
1430 reinit_ports(struct ofproto *p)
1431 {
1432 struct svec devnames;
1433 struct ofport *ofport;
1434 struct odp_port *odp_ports;
1435 size_t n_odp_ports;
1436 size_t i;
1437
1438 COVERAGE_INC(ofproto_reinit_ports);
1439
1440 svec_init(&devnames);
1441 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1442 svec_add (&devnames, ofport->opp.name);
1443 }
1444 dpif_port_list(p->dpif, &odp_ports, &n_odp_ports);
1445 for (i = 0; i < n_odp_ports; i++) {
1446 svec_add (&devnames, odp_ports[i].devname);
1447 }
1448 free(odp_ports);
1449
1450 svec_sort_unique(&devnames);
1451 for (i = 0; i < devnames.n; i++) {
1452 update_port(p, devnames.names[i]);
1453 }
1454 svec_destroy(&devnames);
1455 }
1456
1457 static struct ofport *
1458 make_ofport(const struct odp_port *odp_port)
1459 {
1460 struct netdev_options netdev_options;
1461 enum netdev_flags flags;
1462 struct ofport *ofport;
1463 struct netdev *netdev;
1464 int error;
1465
1466 memset(&netdev_options, 0, sizeof netdev_options);
1467 netdev_options.name = odp_port->devname;
1468 netdev_options.type = odp_port->type;
1469 netdev_options.ethertype = NETDEV_ETH_TYPE_NONE;
1470
1471 error = netdev_open(&netdev_options, &netdev);
1472 if (error) {
1473 VLOG_WARN_RL(&rl, "ignoring port %s (%"PRIu16") because netdev %s "
1474 "cannot be opened (%s)",
1475 odp_port->devname, odp_port->port,
1476 odp_port->devname, strerror(error));
1477 return NULL;
1478 }
1479
1480 ofport = xmalloc(sizeof *ofport);
1481 ofport->netdev = netdev;
1482 ofport->odp_port = odp_port->port;
1483 ofport->opp.port_no = odp_port_to_ofp_port(odp_port->port);
1484 netdev_get_etheraddr(netdev, ofport->opp.hw_addr);
1485 memcpy(ofport->opp.name, odp_port->devname,
1486 MIN(sizeof ofport->opp.name, sizeof odp_port->devname));
1487 ofport->opp.name[sizeof ofport->opp.name - 1] = '\0';
1488
1489 netdev_get_flags(netdev, &flags);
1490 ofport->opp.config = flags & NETDEV_UP ? 0 : OFPPC_PORT_DOWN;
1491
1492 ofport->opp.state = netdev_get_carrier(netdev) ? 0 : OFPPS_LINK_DOWN;
1493
1494 netdev_get_features(netdev,
1495 &ofport->opp.curr, &ofport->opp.advertised,
1496 &ofport->opp.supported, &ofport->opp.peer);
1497 return ofport;
1498 }
1499
1500 static bool
1501 ofport_conflicts(const struct ofproto *p, const struct odp_port *odp_port)
1502 {
1503 if (get_port(p, odp_port->port)) {
1504 VLOG_WARN_RL(&rl, "ignoring duplicate port %"PRIu16" in datapath",
1505 odp_port->port);
1506 return true;
1507 } else if (shash_find(&p->port_by_name, odp_port->devname)) {
1508 VLOG_WARN_RL(&rl, "ignoring duplicate device %s in datapath",
1509 odp_port->devname);
1510 return true;
1511 } else {
1512 return false;
1513 }
1514 }
1515
1516 static int
1517 ofport_equal(const struct ofport *a_, const struct ofport *b_)
1518 {
1519 const struct ofp_phy_port *a = &a_->opp;
1520 const struct ofp_phy_port *b = &b_->opp;
1521
1522 BUILD_ASSERT_DECL(sizeof *a == 48); /* Detect ofp_phy_port changes. */
1523 return (a->port_no == b->port_no
1524 && !memcmp(a->hw_addr, b->hw_addr, sizeof a->hw_addr)
1525 && !strcmp(a->name, b->name)
1526 && a->state == b->state
1527 && a->config == b->config
1528 && a->curr == b->curr
1529 && a->advertised == b->advertised
1530 && a->supported == b->supported
1531 && a->peer == b->peer);
1532 }
1533
1534 static void
1535 send_port_status(struct ofproto *p, const struct ofport *ofport,
1536 uint8_t reason)
1537 {
1538 /* XXX Should limit the number of queued port status change messages. */
1539 struct ofconn *ofconn;
1540 LIST_FOR_EACH (ofconn, node, &p->all_conns) {
1541 struct ofp_port_status *ops;
1542 struct ofpbuf *b;
1543
1544 /* Primary controllers, even slaves, should always get port status
1545 updates. Otherwise obey ofconn_receives_async_msgs(). */
1546 if (ofconn->type != OFCONN_PRIMARY
1547 && !ofconn_receives_async_msgs(ofconn)) {
1548 continue;
1549 }
1550
1551 ops = make_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, 0, &b);
1552 ops->reason = reason;
1553 ops->desc = ofport->opp;
1554 hton_ofp_phy_port(&ops->desc);
1555 queue_tx(b, ofconn, NULL);
1556 }
1557 }
1558
1559 static void
1560 ofport_install(struct ofproto *p, struct ofport *ofport)
1561 {
1562 const char *netdev_name = ofport->opp.name;
1563
1564 netdev_monitor_add(p->netdev_monitor, ofport->netdev);
1565 hmap_insert(&p->ports, &ofport->hmap_node, hash_int(ofport->odp_port, 0));
1566 shash_add(&p->port_by_name, netdev_name, ofport);
1567 if (p->sflow) {
1568 ofproto_sflow_add_port(p->sflow, ofport->odp_port, netdev_name);
1569 }
1570 }
1571
1572 static void
1573 ofport_remove(struct ofproto *p, struct ofport *ofport)
1574 {
1575 netdev_monitor_remove(p->netdev_monitor, ofport->netdev);
1576 hmap_remove(&p->ports, &ofport->hmap_node);
1577 shash_delete(&p->port_by_name,
1578 shash_find(&p->port_by_name, ofport->opp.name));
1579 if (p->sflow) {
1580 ofproto_sflow_del_port(p->sflow, ofport->odp_port);
1581 }
1582 }
1583
1584 static void
1585 ofport_free(struct ofport *ofport)
1586 {
1587 if (ofport) {
1588 netdev_close(ofport->netdev);
1589 free(ofport);
1590 }
1591 }
1592
1593 static struct ofport *
1594 get_port(const struct ofproto *ofproto, uint16_t odp_port)
1595 {
1596 struct ofport *port;
1597
1598 HMAP_FOR_EACH_IN_BUCKET (port, hmap_node,
1599 hash_int(odp_port, 0), &ofproto->ports) {
1600 if (port->odp_port == odp_port) {
1601 return port;
1602 }
1603 }
1604 return NULL;
1605 }
1606
1607 static void
1608 update_port(struct ofproto *p, const char *devname)
1609 {
1610 struct odp_port odp_port;
1611 struct ofport *old_ofport;
1612 struct ofport *new_ofport;
1613 int error;
1614
1615 COVERAGE_INC(ofproto_update_port);
1616
1617 /* Query the datapath for port information. */
1618 error = dpif_port_query_by_name(p->dpif, devname, &odp_port);
1619
1620 /* Find the old ofport. */
1621 old_ofport = shash_find_data(&p->port_by_name, devname);
1622 if (!error) {
1623 if (!old_ofport) {
1624 /* There's no port named 'devname' but there might be a port with
1625 * the same port number. This could happen if a port is deleted
1626 * and then a new one added in its place very quickly, or if a port
1627 * is renamed. In the former case we want to send an OFPPR_DELETE
1628 * and an OFPPR_ADD, and in the latter case we want to send a
1629 * single OFPPR_MODIFY. We can distinguish the cases by comparing
1630 * the old port's ifindex against the new port, or perhaps less
1631 * reliably but more portably by comparing the old port's MAC
1632 * against the new port's MAC. However, this code isn't that smart
1633 * and always sends an OFPPR_MODIFY (XXX). */
1634 old_ofport = get_port(p, odp_port.port);
1635 }
1636 } else if (error != ENOENT && error != ENODEV) {
1637 VLOG_WARN_RL(&rl, "dpif_port_query_by_name returned unexpected error "
1638 "%s", strerror(error));
1639 return;
1640 }
1641
1642 /* Create a new ofport. */
1643 new_ofport = !error ? make_ofport(&odp_port) : NULL;
1644
1645 /* Eliminate a few pathological cases. */
1646 if (!old_ofport && !new_ofport) {
1647 return;
1648 } else if (old_ofport && new_ofport) {
1649 /* Most of the 'config' bits are OpenFlow soft state, but
1650 * OFPPC_PORT_DOWN is maintained by the kernel. So transfer the
1651 * OpenFlow bits from old_ofport. (make_ofport() only sets
1652 * OFPPC_PORT_DOWN and leaves the other bits 0.) */
1653 new_ofport->opp.config |= old_ofport->opp.config & ~OFPPC_PORT_DOWN;
1654
1655 if (ofport_equal(old_ofport, new_ofport)) {
1656 /* False alarm--no change. */
1657 ofport_free(new_ofport);
1658 return;
1659 }
1660 }
1661
1662 /* Now deal with the normal cases. */
1663 if (old_ofport) {
1664 ofport_remove(p, old_ofport);
1665 }
1666 if (new_ofport) {
1667 ofport_install(p, new_ofport);
1668 }
1669 send_port_status(p, new_ofport ? new_ofport : old_ofport,
1670 (!old_ofport ? OFPPR_ADD
1671 : !new_ofport ? OFPPR_DELETE
1672 : OFPPR_MODIFY));
1673 ofport_free(old_ofport);
1674 }
1675
1676 static int
1677 init_ports(struct ofproto *p)
1678 {
1679 struct odp_port *ports;
1680 size_t n_ports;
1681 size_t i;
1682 int error;
1683
1684 error = dpif_port_list(p->dpif, &ports, &n_ports);
1685 if (error) {
1686 return error;
1687 }
1688
1689 for (i = 0; i < n_ports; i++) {
1690 const struct odp_port *odp_port = &ports[i];
1691 if (!ofport_conflicts(p, odp_port)) {
1692 struct ofport *ofport = make_ofport(odp_port);
1693 if (ofport) {
1694 ofport_install(p, ofport);
1695 }
1696 }
1697 }
1698 free(ports);
1699 return 0;
1700 }
1701 \f
1702 static struct ofconn *
1703 ofconn_create(struct ofproto *p, struct rconn *rconn, enum ofconn_type type)
1704 {
1705 struct ofconn *ofconn = xzalloc(sizeof *ofconn);
1706 ofconn->ofproto = p;
1707 list_push_back(&p->all_conns, &ofconn->node);
1708 ofconn->rconn = rconn;
1709 ofconn->type = type;
1710 ofconn->flow_format = NXFF_OPENFLOW10;
1711 ofconn->role = NX_ROLE_OTHER;
1712 ofconn->packet_in_counter = rconn_packet_counter_create ();
1713 ofconn->pktbuf = NULL;
1714 ofconn->miss_send_len = 0;
1715 ofconn->reply_counter = rconn_packet_counter_create ();
1716 return ofconn;
1717 }
1718
1719 static void
1720 ofconn_destroy(struct ofconn *ofconn)
1721 {
1722 if (ofconn->type == OFCONN_PRIMARY) {
1723 hmap_remove(&ofconn->ofproto->controllers, &ofconn->hmap_node);
1724 }
1725 discovery_destroy(ofconn->discovery);
1726
1727 list_remove(&ofconn->node);
1728 switch_status_unregister(ofconn->ss);
1729 rconn_destroy(ofconn->rconn);
1730 rconn_packet_counter_destroy(ofconn->packet_in_counter);
1731 rconn_packet_counter_destroy(ofconn->reply_counter);
1732 pktbuf_destroy(ofconn->pktbuf);
1733 free(ofconn);
1734 }
1735
1736 static void
1737 ofconn_run(struct ofconn *ofconn)
1738 {
1739 struct ofproto *p = ofconn->ofproto;
1740 int iteration;
1741 size_t i;
1742
1743 if (ofconn->discovery) {
1744 char *controller_name;
1745 if (rconn_is_connectivity_questionable(ofconn->rconn)) {
1746 discovery_question_connectivity(ofconn->discovery);
1747 }
1748 if (discovery_run(ofconn->discovery, &controller_name)) {
1749 if (controller_name) {
1750 char *ofconn_name = ofconn_make_name(p, controller_name);
1751 rconn_connect(ofconn->rconn, controller_name, ofconn_name);
1752 free(ofconn_name);
1753 } else {
1754 rconn_disconnect(ofconn->rconn);
1755 }
1756 }
1757 }
1758
1759 for (i = 0; i < N_SCHEDULERS; i++) {
1760 pinsched_run(ofconn->schedulers[i], do_send_packet_in, ofconn);
1761 }
1762
1763 rconn_run(ofconn->rconn);
1764
1765 if (rconn_packet_counter_read (ofconn->reply_counter) < OFCONN_REPLY_MAX) {
1766 /* Limit the number of iterations to prevent other tasks from
1767 * starving. */
1768 for (iteration = 0; iteration < 50; iteration++) {
1769 struct ofpbuf *of_msg = rconn_recv(ofconn->rconn);
1770 if (!of_msg) {
1771 break;
1772 }
1773 if (p->fail_open) {
1774 fail_open_maybe_recover(p->fail_open);
1775 }
1776 handle_openflow(ofconn, of_msg);
1777 ofpbuf_delete(of_msg);
1778 }
1779 }
1780
1781 if (!ofconn->discovery && !rconn_is_alive(ofconn->rconn)) {
1782 ofconn_destroy(ofconn);
1783 }
1784 }
1785
1786 static void
1787 ofconn_wait(struct ofconn *ofconn)
1788 {
1789 int i;
1790
1791 if (ofconn->discovery) {
1792 discovery_wait(ofconn->discovery);
1793 }
1794 for (i = 0; i < N_SCHEDULERS; i++) {
1795 pinsched_wait(ofconn->schedulers[i]);
1796 }
1797 rconn_run_wait(ofconn->rconn);
1798 if (rconn_packet_counter_read (ofconn->reply_counter) < OFCONN_REPLY_MAX) {
1799 rconn_recv_wait(ofconn->rconn);
1800 } else {
1801 COVERAGE_INC(ofproto_ofconn_stuck);
1802 }
1803 }
1804
1805 /* Returns true if 'ofconn' should receive asynchronous messages. */
1806 static bool
1807 ofconn_receives_async_msgs(const struct ofconn *ofconn)
1808 {
1809 if (ofconn->type == OFCONN_PRIMARY) {
1810 /* Primary controllers always get asynchronous messages unless they
1811 * have configured themselves as "slaves". */
1812 return ofconn->role != NX_ROLE_SLAVE;
1813 } else {
1814 /* Service connections don't get asynchronous messages unless they have
1815 * explicitly asked for them by setting a nonzero miss send length. */
1816 return ofconn->miss_send_len > 0;
1817 }
1818 }
1819
1820 /* Returns a human-readable name for an OpenFlow connection between 'ofproto'
1821 * and 'target', suitable for use in log messages for identifying the
1822 * connection.
1823 *
1824 * The name is dynamically allocated. The caller should free it (with free())
1825 * when it is no longer needed. */
1826 static char *
1827 ofconn_make_name(const struct ofproto *ofproto, const char *target)
1828 {
1829 return xasprintf("%s<->%s", dpif_base_name(ofproto->dpif), target);
1830 }
1831
1832 static void
1833 ofconn_set_rate_limit(struct ofconn *ofconn, int rate, int burst)
1834 {
1835 int i;
1836
1837 for (i = 0; i < N_SCHEDULERS; i++) {
1838 struct pinsched **s = &ofconn->schedulers[i];
1839
1840 if (rate > 0) {
1841 if (!*s) {
1842 *s = pinsched_create(rate, burst,
1843 ofconn->ofproto->switch_status);
1844 } else {
1845 pinsched_set_limits(*s, rate, burst);
1846 }
1847 } else {
1848 pinsched_destroy(*s);
1849 *s = NULL;
1850 }
1851 }
1852 }
1853 \f
1854 static void
1855 ofservice_reconfigure(struct ofservice *ofservice,
1856 const struct ofproto_controller *c)
1857 {
1858 ofservice->probe_interval = c->probe_interval;
1859 ofservice->rate_limit = c->rate_limit;
1860 ofservice->burst_limit = c->burst_limit;
1861 }
1862
1863 /* Creates a new ofservice in 'ofproto'. Returns 0 if successful, otherwise a
1864 * positive errno value. */
1865 static int
1866 ofservice_create(struct ofproto *ofproto, const struct ofproto_controller *c)
1867 {
1868 struct ofservice *ofservice;
1869 struct pvconn *pvconn;
1870 int error;
1871
1872 error = pvconn_open(c->target, &pvconn);
1873 if (error) {
1874 return error;
1875 }
1876
1877 ofservice = xzalloc(sizeof *ofservice);
1878 hmap_insert(&ofproto->services, &ofservice->node,
1879 hash_string(c->target, 0));
1880 ofservice->pvconn = pvconn;
1881
1882 ofservice_reconfigure(ofservice, c);
1883
1884 return 0;
1885 }
1886
1887 static void
1888 ofservice_destroy(struct ofproto *ofproto, struct ofservice *ofservice)
1889 {
1890 hmap_remove(&ofproto->services, &ofservice->node);
1891 pvconn_close(ofservice->pvconn);
1892 free(ofservice);
1893 }
1894
1895 /* Finds and returns the ofservice within 'ofproto' that has the given
1896 * 'target', or a null pointer if none exists. */
1897 static struct ofservice *
1898 ofservice_lookup(struct ofproto *ofproto, const char *target)
1899 {
1900 struct ofservice *ofservice;
1901
1902 HMAP_FOR_EACH_WITH_HASH (ofservice, node, hash_string(target, 0),
1903 &ofproto->services) {
1904 if (!strcmp(pvconn_get_name(ofservice->pvconn), target)) {
1905 return ofservice;
1906 }
1907 }
1908 return NULL;
1909 }
1910 \f
1911 /* Returns true if 'rule' should be hidden from the controller.
1912 *
1913 * Rules with priority higher than UINT16_MAX are set up by ofproto itself
1914 * (e.g. by in-band control) and are intentionally hidden from the
1915 * controller. */
1916 static bool
1917 rule_is_hidden(const struct rule *rule)
1918 {
1919 return rule->cr.priority > UINT16_MAX;
1920 }
1921
1922 /* Creates and returns a new rule initialized as specified.
1923 *
1924 * The caller is responsible for inserting the rule into the classifier (with
1925 * rule_insert()). */
1926 static struct rule *
1927 rule_create(const struct cls_rule *cls_rule,
1928 const union ofp_action *actions, size_t n_actions,
1929 uint16_t idle_timeout, uint16_t hard_timeout,
1930 ovs_be64 flow_cookie, bool send_flow_removed)
1931 {
1932 struct rule *rule = xzalloc(sizeof *rule);
1933 rule->cr = *cls_rule;
1934 rule->idle_timeout = idle_timeout;
1935 rule->hard_timeout = hard_timeout;
1936 rule->flow_cookie = flow_cookie;
1937 rule->used = rule->created = time_msec();
1938 rule->send_flow_removed = send_flow_removed;
1939 list_init(&rule->facets);
1940 if (n_actions > 0) {
1941 rule->n_actions = n_actions;
1942 rule->actions = xmemdup(actions, n_actions * sizeof *actions);
1943 }
1944
1945 return rule;
1946 }
1947
1948 static struct rule *
1949 rule_from_cls_rule(const struct cls_rule *cls_rule)
1950 {
1951 return cls_rule ? CONTAINER_OF(cls_rule, struct rule, cr) : NULL;
1952 }
1953
1954 static void
1955 rule_free(struct rule *rule)
1956 {
1957 free(rule->actions);
1958 free(rule);
1959 }
1960
1961 /* Destroys 'rule' and iterates through all of its facets and revalidates them,
1962 * destroying any that no longer has a rule (which is probably all of them).
1963 *
1964 * The caller must have already removed 'rule' from the classifier. */
1965 static void
1966 rule_destroy(struct ofproto *ofproto, struct rule *rule)
1967 {
1968 struct facet *facet, *next_facet;
1969 LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
1970 facet_revalidate(ofproto, facet);
1971 }
1972 rule_free(rule);
1973 }
1974
1975 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
1976 * that outputs to 'out_port' (output to OFPP_FLOOD and OFPP_ALL doesn't
1977 * count). */
1978 static bool
1979 rule_has_out_port(const struct rule *rule, ovs_be16 out_port)
1980 {
1981 const union ofp_action *oa;
1982 struct actions_iterator i;
1983
1984 if (out_port == htons(OFPP_NONE)) {
1985 return true;
1986 }
1987 for (oa = actions_first(&i, rule->actions, rule->n_actions); oa;
1988 oa = actions_next(&i)) {
1989 if (action_outputs_to_port(oa, out_port)) {
1990 return true;
1991 }
1992 }
1993 return false;
1994 }
1995
1996 /* Executes, within 'ofproto', the 'n_actions' actions in 'actions' on
1997 * 'packet', which arrived on 'in_port'.
1998 *
1999 * Takes ownership of 'packet'. */
2000 static bool
2001 execute_odp_actions(struct ofproto *ofproto, uint16_t in_port,
2002 const union odp_action *actions, size_t n_actions,
2003 struct ofpbuf *packet)
2004 {
2005 if (n_actions == 1 && actions[0].type == ODPAT_CONTROLLER) {
2006 /* As an optimization, avoid a round-trip from userspace to kernel to
2007 * userspace. This also avoids possibly filling up kernel packet
2008 * buffers along the way. */
2009 struct odp_msg *msg;
2010
2011 msg = ofpbuf_push_uninit(packet, sizeof *msg);
2012 msg->type = _ODPL_ACTION_NR;
2013 msg->length = sizeof(struct odp_msg) + packet->size;
2014 msg->port = in_port;
2015 msg->reserved = 0;
2016 msg->arg = actions[0].controller.arg;
2017
2018 send_packet_in(ofproto, packet);
2019
2020 return true;
2021 } else {
2022 int error;
2023
2024 error = dpif_execute(ofproto->dpif, actions, n_actions, packet);
2025 ofpbuf_delete(packet);
2026 return !error;
2027 }
2028 }
2029
2030 /* Executes the actions indicated by 'facet' on 'packet' and credits 'facet''s
2031 * statistics appropriately. 'packet' must have at least sizeof(struct
2032 * ofp_packet_in) bytes of headroom.
2033 *
2034 * For correct results, 'packet' must actually be in 'facet''s flow; that is,
2035 * applying flow_extract() to 'packet' would yield the same flow as
2036 * 'facet->flow'.
2037 *
2038 * 'facet' must have accurately composed ODP actions; that is, it must not be
2039 * in need of revalidation.
2040 *
2041 * Takes ownership of 'packet'. */
2042 static void
2043 facet_execute(struct ofproto *ofproto, struct facet *facet,
2044 struct ofpbuf *packet)
2045 {
2046 struct odp_flow_stats stats;
2047
2048 assert(ofpbuf_headroom(packet) >= sizeof(struct ofp_packet_in));
2049
2050 flow_extract_stats(&facet->flow, packet, &stats);
2051 if (execute_odp_actions(ofproto, facet->flow.in_port,
2052 facet->actions, facet->n_actions, packet)) {
2053 facet_update_stats(ofproto, facet, &stats);
2054 facet->used = time_msec();
2055 netflow_flow_update_time(ofproto->netflow,
2056 &facet->nf_flow, facet->used);
2057 }
2058 }
2059
2060 /* Executes the actions indicated by 'rule' on 'packet' and credits 'rule''s
2061 * statistics (or the statistics for one of its facets) appropriately.
2062 * 'packet' must have at least sizeof(struct ofp_packet_in) bytes of headroom.
2063 *
2064 * 'packet' doesn't necessarily have to match 'rule'. 'rule' will be credited
2065 * with statistics for 'packet' either way.
2066 *
2067 * Takes ownership of 'packet'. */
2068 static void
2069 rule_execute(struct ofproto *ofproto, struct rule *rule, uint16_t in_port,
2070 struct ofpbuf *packet)
2071 {
2072 struct facet *facet;
2073 struct odp_actions a;
2074 struct flow flow;
2075 size_t size;
2076
2077 assert(ofpbuf_headroom(packet) >= sizeof(struct ofp_packet_in));
2078
2079 flow_extract(packet, 0, in_port, &flow);
2080
2081 /* First look for a related facet. If we find one, account it to that. */
2082 facet = facet_lookup_valid(ofproto, &flow);
2083 if (facet && facet->rule == rule) {
2084 facet_execute(ofproto, facet, packet);
2085 return;
2086 }
2087
2088 /* Otherwise, if 'rule' is in fact the correct rule for 'packet', then
2089 * create a new facet for it and use that. */
2090 if (rule_lookup(ofproto, &flow) == rule) {
2091 facet = facet_create(ofproto, rule, &flow, packet);
2092 facet_execute(ofproto, facet, packet);
2093 facet_install(ofproto, facet, true);
2094 return;
2095 }
2096
2097 /* We can't account anything to a facet. If we were to try, then that
2098 * facet would have a non-matching rule, busting our invariants. */
2099 if (xlate_actions(rule->actions, rule->n_actions, &flow, ofproto,
2100 packet, &a, NULL, 0, NULL)) {
2101 ofpbuf_delete(packet);
2102 return;
2103 }
2104 size = packet->size;
2105 if (execute_odp_actions(ofproto, in_port,
2106 a.actions, a.n_actions, packet)) {
2107 rule->used = time_msec();
2108 rule->packet_count++;
2109 rule->byte_count += size;
2110 }
2111 }
2112
2113 /* Inserts 'rule' into 'p''s flow table. */
2114 static void
2115 rule_insert(struct ofproto *p, struct rule *rule)
2116 {
2117 struct rule *displaced_rule;
2118
2119 displaced_rule = rule_from_cls_rule(classifier_insert(&p->cls, &rule->cr));
2120 if (displaced_rule) {
2121 rule_destroy(p, displaced_rule);
2122 }
2123 p->need_revalidate = true;
2124 }
2125
2126 /* Creates and returns a new facet within 'ofproto' owned by 'rule', given a
2127 * 'flow' and an example 'packet' within that flow.
2128 *
2129 * The caller must already have determined that no facet with an identical
2130 * 'flow' exists in 'ofproto' and that 'flow' is the best match for 'rule' in
2131 * 'ofproto''s classifier table. */
2132 static struct facet *
2133 facet_create(struct ofproto *ofproto, struct rule *rule,
2134 const struct flow *flow, const struct ofpbuf *packet)
2135 {
2136 struct facet *facet;
2137
2138 facet = xzalloc(sizeof *facet);
2139 facet->used = time_msec();
2140 hmap_insert(&ofproto->facets, &facet->hmap_node, flow_hash(flow, 0));
2141 list_push_back(&rule->facets, &facet->list_node);
2142 facet->rule = rule;
2143 facet->flow = *flow;
2144 netflow_flow_init(&facet->nf_flow);
2145 netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, facet->used);
2146
2147 facet_make_actions(ofproto, facet, packet);
2148
2149 return facet;
2150 }
2151
2152 static void
2153 facet_free(struct facet *facet)
2154 {
2155 free(facet->actions);
2156 free(facet);
2157 }
2158
2159 /* Remove 'rule' from 'ofproto' and free up the associated memory:
2160 *
2161 * - Removes 'rule' from the classifier.
2162 *
2163 * - If 'rule' has facets, revalidates them (and possibly uninstalls and
2164 * destroys them), via rule_destroy().
2165 */
2166 static void
2167 rule_remove(struct ofproto *ofproto, struct rule *rule)
2168 {
2169 COVERAGE_INC(ofproto_del_rule);
2170 ofproto->need_revalidate = true;
2171 classifier_remove(&ofproto->cls, &rule->cr);
2172 rule_destroy(ofproto, rule);
2173 }
2174
2175 /* Remove 'facet' from 'ofproto' and free up the associated memory:
2176 *
2177 * - If 'facet' was installed in the datapath, uninstalls it and updates its
2178 * rule's statistics, via facet_uninstall().
2179 *
2180 * - Removes 'facet' from its rule and from ofproto->facets.
2181 */
2182 static void
2183 facet_remove(struct ofproto *ofproto, struct facet *facet)
2184 {
2185 facet_uninstall(ofproto, facet);
2186 facet_flush_stats(ofproto, facet);
2187 hmap_remove(&ofproto->facets, &facet->hmap_node);
2188 list_remove(&facet->list_node);
2189 facet_free(facet);
2190 }
2191
2192 /* Composes the ODP actions for 'facet' based on its rule's actions. */
2193 static void
2194 facet_make_actions(struct ofproto *p, struct facet *facet,
2195 const struct ofpbuf *packet)
2196 {
2197 const struct rule *rule = facet->rule;
2198 struct odp_actions a;
2199 size_t actions_len;
2200
2201 xlate_actions(rule->actions, rule->n_actions, &facet->flow, p,
2202 packet, &a, &facet->tags, &facet->may_install,
2203 &facet->nf_flow.output_iface);
2204
2205 actions_len = a.n_actions * sizeof *a.actions;
2206 if (facet->n_actions != a.n_actions
2207 || memcmp(facet->actions, a.actions, actions_len)) {
2208 free(facet->actions);
2209 facet->n_actions = a.n_actions;
2210 facet->actions = xmemdup(a.actions, actions_len);
2211 }
2212 }
2213
2214 static int
2215 facet_put__(struct ofproto *ofproto, struct facet *facet, int flags,
2216 struct odp_flow_put *put)
2217 {
2218 memset(&put->flow.stats, 0, sizeof put->flow.stats);
2219 odp_flow_key_from_flow(&put->flow.key, &facet->flow);
2220 put->flow.actions = facet->actions;
2221 put->flow.n_actions = facet->n_actions;
2222 put->flow.flags = 0;
2223 put->flags = flags;
2224 return dpif_flow_put(ofproto->dpif, put);
2225 }
2226
2227 /* If 'facet' is installable, inserts or re-inserts it into 'p''s datapath. If
2228 * 'zero_stats' is true, clears any existing statistics from the datapath for
2229 * 'facet'. */
2230 static void
2231 facet_install(struct ofproto *p, struct facet *facet, bool zero_stats)
2232 {
2233 if (facet->may_install) {
2234 struct odp_flow_put put;
2235 int flags;
2236
2237 flags = ODPPF_CREATE | ODPPF_MODIFY;
2238 if (zero_stats) {
2239 flags |= ODPPF_ZERO_STATS;
2240 }
2241 if (!facet_put__(p, facet, flags, &put)) {
2242 facet->installed = true;
2243 }
2244 }
2245 }
2246
2247 /* Ensures that the bytes in 'facet', plus 'extra_bytes', have been passed up
2248 * to the accounting hook function in the ofhooks structure. */
2249 static void
2250 facet_account(struct ofproto *ofproto,
2251 struct facet *facet, uint64_t extra_bytes)
2252 {
2253 uint64_t total_bytes = facet->byte_count + extra_bytes;
2254
2255 if (ofproto->ofhooks->account_flow_cb
2256 && total_bytes > facet->accounted_bytes)
2257 {
2258 ofproto->ofhooks->account_flow_cb(
2259 &facet->flow, facet->tags, facet->actions, facet->n_actions,
2260 total_bytes - facet->accounted_bytes, ofproto->aux);
2261 facet->accounted_bytes = total_bytes;
2262 }
2263 }
2264
2265 /* If 'rule' is installed in the datapath, uninstalls it. */
2266 static void
2267 facet_uninstall(struct ofproto *p, struct facet *facet)
2268 {
2269 if (facet->installed) {
2270 struct odp_flow odp_flow;
2271
2272 odp_flow_key_from_flow(&odp_flow.key, &facet->flow);
2273 odp_flow.actions = NULL;
2274 odp_flow.n_actions = 0;
2275 odp_flow.flags = 0;
2276 if (!dpif_flow_del(p->dpif, &odp_flow)) {
2277 facet_update_stats(p, facet, &odp_flow.stats);
2278 }
2279 facet->installed = false;
2280 }
2281 }
2282
2283 /* Returns true if the only action for 'facet' is to send to the controller.
2284 * (We don't report NetFlow expiration messages for such facets because they
2285 * are just part of the control logic for the network, not real traffic). */
2286 static bool
2287 facet_is_controller_flow(struct facet *facet)
2288 {
2289 return (facet
2290 && facet->rule->n_actions == 1
2291 && action_outputs_to_port(&facet->rule->actions[0],
2292 htons(OFPP_CONTROLLER)));
2293 }
2294
2295 /* Folds all of 'facet''s statistics into its rule. Also updates the
2296 * accounting ofhook and emits a NetFlow expiration if appropriate. */
2297 static void
2298 facet_flush_stats(struct ofproto *ofproto, struct facet *facet)
2299 {
2300 facet_account(ofproto, facet, 0);
2301
2302 if (ofproto->netflow && !facet_is_controller_flow(facet)) {
2303 struct ofexpired expired;
2304 expired.flow = facet->flow;
2305 expired.packet_count = facet->packet_count;
2306 expired.byte_count = facet->byte_count;
2307 expired.used = facet->used;
2308 netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
2309 }
2310
2311 facet->rule->packet_count += facet->packet_count;
2312 facet->rule->byte_count += facet->byte_count;
2313
2314 /* Reset counters to prevent double counting if 'facet' ever gets
2315 * reinstalled. */
2316 facet->packet_count = 0;
2317 facet->byte_count = 0;
2318 facet->accounted_bytes = 0;
2319
2320 netflow_flow_clear(&facet->nf_flow);
2321 }
2322
2323 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
2324 * Returns it if found, otherwise a null pointer.
2325 *
2326 * The returned facet might need revalidation; use facet_lookup_valid()
2327 * instead if that is important. */
2328 static struct facet *
2329 facet_find(struct ofproto *ofproto, const struct flow *flow)
2330 {
2331 struct facet *facet;
2332
2333 HMAP_FOR_EACH_WITH_HASH (facet, hmap_node, flow_hash(flow, 0),
2334 &ofproto->facets) {
2335 if (flow_equal(flow, &facet->flow)) {
2336 return facet;
2337 }
2338 }
2339
2340 return NULL;
2341 }
2342
2343 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
2344 * Returns it if found, otherwise a null pointer.
2345 *
2346 * The returned facet is guaranteed to be valid. */
2347 static struct facet *
2348 facet_lookup_valid(struct ofproto *ofproto, const struct flow *flow)
2349 {
2350 struct facet *facet = facet_find(ofproto, flow);
2351
2352 /* The facet we found might not be valid, since we could be in need of
2353 * revalidation. If it is not valid, don't return it. */
2354 if (facet
2355 && ofproto->need_revalidate
2356 && !facet_revalidate(ofproto, facet)) {
2357 COVERAGE_INC(ofproto_invalidated);
2358 return NULL;
2359 }
2360
2361 return facet;
2362 }
2363
2364 /* Re-searches 'ofproto''s classifier for a rule matching 'facet':
2365 *
2366 * - If the rule found is different from 'facet''s current rule, moves
2367 * 'facet' to the new rule and recompiles its actions.
2368 *
2369 * - If the rule found is the same as 'facet''s current rule, leaves 'facet'
2370 * where it is and recompiles its actions anyway.
2371 *
2372 * - If there is none, destroys 'facet'.
2373 *
2374 * Returns true if 'facet' still exists, false if it has been destroyed. */
2375 static bool
2376 facet_revalidate(struct ofproto *ofproto, struct facet *facet)
2377 {
2378 struct rule *new_rule;
2379 struct odp_actions a;
2380 size_t actions_len;
2381 uint16_t new_nf_output_iface;
2382 bool actions_changed;
2383
2384 COVERAGE_INC(facet_revalidate);
2385
2386 /* Determine the new rule. */
2387 new_rule = rule_lookup(ofproto, &facet->flow);
2388 if (!new_rule) {
2389 /* No new rule, so delete the facet. */
2390 facet_remove(ofproto, facet);
2391 return false;
2392 }
2393
2394 /* Calculate new ODP actions.
2395 *
2396 * We are very cautious about actually modifying 'facet' state at this
2397 * point, because we might need to, e.g., emit a NetFlow expiration and, if
2398 * so, we need to have the old state around to properly compose it. */
2399 xlate_actions(new_rule->actions, new_rule->n_actions, &facet->flow,
2400 ofproto, NULL, &a, &facet->tags, &facet->may_install,
2401 &new_nf_output_iface);
2402 actions_len = a.n_actions * sizeof *a.actions;
2403 actions_changed = (facet->n_actions != a.n_actions
2404 || memcmp(facet->actions, a.actions, actions_len));
2405
2406 /* If the ODP actions changed or the installability changed, then we need
2407 * to talk to the datapath. */
2408 if (actions_changed || facet->may_install != facet->installed) {
2409 if (facet->may_install) {
2410 struct odp_flow_put put;
2411
2412 memset(&put.flow.stats, 0, sizeof put.flow.stats);
2413 odp_flow_key_from_flow(&put.flow.key, &facet->flow);
2414 put.flow.actions = a.actions;
2415 put.flow.n_actions = a.n_actions;
2416 put.flow.flags = 0;
2417 put.flags = ODPPF_CREATE | ODPPF_MODIFY | ODPPF_ZERO_STATS;
2418 dpif_flow_put(ofproto->dpif, &put);
2419
2420 facet_update_stats(ofproto, facet, &put.flow.stats);
2421 } else {
2422 facet_uninstall(ofproto, facet);
2423 }
2424
2425 /* The datapath flow is gone or has zeroed stats, so push stats out of
2426 * 'facet' into 'rule'. */
2427 facet_flush_stats(ofproto, facet);
2428 }
2429
2430 /* Update 'facet' now that we've taken care of all the old state. */
2431 facet->nf_flow.output_iface = new_nf_output_iface;
2432 if (actions_changed) {
2433 free(facet->actions);
2434 facet->n_actions = a.n_actions;
2435 facet->actions = xmemdup(a.actions, actions_len);
2436 }
2437 if (facet->rule != new_rule) {
2438 COVERAGE_INC(facet_changed_rule);
2439 list_remove(&facet->list_node);
2440 list_push_back(&new_rule->facets, &facet->list_node);
2441 facet->rule = new_rule;
2442 facet->used = new_rule->created;
2443 }
2444
2445 return true;
2446 }
2447 \f
2448 static void
2449 queue_tx(struct ofpbuf *msg, const struct ofconn *ofconn,
2450 struct rconn_packet_counter *counter)
2451 {
2452 update_openflow_length(msg);
2453 if (rconn_send(ofconn->rconn, msg, counter)) {
2454 ofpbuf_delete(msg);
2455 }
2456 }
2457
2458 static void
2459 send_error_oh(const struct ofconn *ofconn, const struct ofp_header *oh,
2460 int error)
2461 {
2462 struct ofpbuf *buf = make_ofp_error_msg(error, oh);
2463 if (buf) {
2464 COVERAGE_INC(ofproto_error);
2465 queue_tx(buf, ofconn, ofconn->reply_counter);
2466 }
2467 }
2468
2469 static void
2470 hton_ofp_phy_port(struct ofp_phy_port *opp)
2471 {
2472 opp->port_no = htons(opp->port_no);
2473 opp->config = htonl(opp->config);
2474 opp->state = htonl(opp->state);
2475 opp->curr = htonl(opp->curr);
2476 opp->advertised = htonl(opp->advertised);
2477 opp->supported = htonl(opp->supported);
2478 opp->peer = htonl(opp->peer);
2479 }
2480
2481 static int
2482 handle_echo_request(struct ofconn *ofconn, struct ofp_header *oh)
2483 {
2484 struct ofp_header *rq = oh;
2485 queue_tx(make_echo_reply(rq), ofconn, ofconn->reply_counter);
2486 return 0;
2487 }
2488
2489 static int
2490 handle_features_request(struct ofconn *ofconn, struct ofp_header *oh)
2491 {
2492 struct ofp_switch_features *osf;
2493 struct ofpbuf *buf;
2494 struct ofport *port;
2495
2496 osf = make_openflow_xid(sizeof *osf, OFPT_FEATURES_REPLY, oh->xid, &buf);
2497 osf->datapath_id = htonll(ofconn->ofproto->datapath_id);
2498 osf->n_buffers = htonl(pktbuf_capacity());
2499 osf->n_tables = 2;
2500 osf->capabilities = htonl(OFPC_FLOW_STATS | OFPC_TABLE_STATS |
2501 OFPC_PORT_STATS | OFPC_ARP_MATCH_IP);
2502 osf->actions = htonl((1u << OFPAT_OUTPUT) |
2503 (1u << OFPAT_SET_VLAN_VID) |
2504 (1u << OFPAT_SET_VLAN_PCP) |
2505 (1u << OFPAT_STRIP_VLAN) |
2506 (1u << OFPAT_SET_DL_SRC) |
2507 (1u << OFPAT_SET_DL_DST) |
2508 (1u << OFPAT_SET_NW_SRC) |
2509 (1u << OFPAT_SET_NW_DST) |
2510 (1u << OFPAT_SET_NW_TOS) |
2511 (1u << OFPAT_SET_TP_SRC) |
2512 (1u << OFPAT_SET_TP_DST) |
2513 (1u << OFPAT_ENQUEUE));
2514
2515 HMAP_FOR_EACH (port, hmap_node, &ofconn->ofproto->ports) {
2516 hton_ofp_phy_port(ofpbuf_put(buf, &port->opp, sizeof port->opp));
2517 }
2518
2519 queue_tx(buf, ofconn, ofconn->reply_counter);
2520 return 0;
2521 }
2522
2523 static int
2524 handle_get_config_request(struct ofconn *ofconn, struct ofp_header *oh)
2525 {
2526 struct ofpbuf *buf;
2527 struct ofp_switch_config *osc;
2528 uint16_t flags;
2529 bool drop_frags;
2530
2531 /* Figure out flags. */
2532 dpif_get_drop_frags(ofconn->ofproto->dpif, &drop_frags);
2533 flags = drop_frags ? OFPC_FRAG_DROP : OFPC_FRAG_NORMAL;
2534
2535 /* Send reply. */
2536 osc = make_openflow_xid(sizeof *osc, OFPT_GET_CONFIG_REPLY, oh->xid, &buf);
2537 osc->flags = htons(flags);
2538 osc->miss_send_len = htons(ofconn->miss_send_len);
2539 queue_tx(buf, ofconn, ofconn->reply_counter);
2540
2541 return 0;
2542 }
2543
2544 static int
2545 handle_set_config(struct ofconn *ofconn, struct ofp_switch_config *osc)
2546 {
2547 uint16_t flags;
2548 int error;
2549
2550 error = check_ofp_message(&osc->header, OFPT_SET_CONFIG, sizeof *osc);
2551 if (error) {
2552 return error;
2553 }
2554 flags = ntohs(osc->flags);
2555
2556 if (ofconn->type == OFCONN_PRIMARY && ofconn->role != NX_ROLE_SLAVE) {
2557 switch (flags & OFPC_FRAG_MASK) {
2558 case OFPC_FRAG_NORMAL:
2559 dpif_set_drop_frags(ofconn->ofproto->dpif, false);
2560 break;
2561 case OFPC_FRAG_DROP:
2562 dpif_set_drop_frags(ofconn->ofproto->dpif, true);
2563 break;
2564 default:
2565 VLOG_WARN_RL(&rl, "requested bad fragment mode (flags=%"PRIx16")",
2566 osc->flags);
2567 break;
2568 }
2569 }
2570
2571 ofconn->miss_send_len = ntohs(osc->miss_send_len);
2572
2573 return 0;
2574 }
2575
2576 static void
2577 add_controller_action(struct odp_actions *actions, uint16_t max_len)
2578 {
2579 union odp_action *a = odp_actions_add(actions, ODPAT_CONTROLLER);
2580 a->controller.arg = max_len;
2581 }
2582
2583 struct action_xlate_ctx {
2584 /* Input. */
2585 struct flow flow; /* Flow to which these actions correspond. */
2586 int recurse; /* Recursion level, via xlate_table_action. */
2587 struct ofproto *ofproto;
2588 const struct ofpbuf *packet; /* The packet corresponding to 'flow', or a
2589 * null pointer if we are revalidating
2590 * without a packet to refer to. */
2591
2592 /* Output. */
2593 struct odp_actions *out; /* Datapath actions. */
2594 tag_type tags; /* Tags associated with OFPP_NORMAL actions. */
2595 bool may_set_up_flow; /* True ordinarily; false if the actions must
2596 * be reassessed for every packet. */
2597 uint16_t nf_output_iface; /* Output interface index for NetFlow. */
2598 };
2599
2600 /* Maximum depth of flow table recursion (due to NXAST_RESUBMIT actions) in a
2601 * flow translation. */
2602 #define MAX_RESUBMIT_RECURSION 8
2603
2604 static void do_xlate_actions(const union ofp_action *in, size_t n_in,
2605 struct action_xlate_ctx *ctx);
2606
2607 static void
2608 add_output_action(struct action_xlate_ctx *ctx, uint16_t port)
2609 {
2610 const struct ofport *ofport = get_port(ctx->ofproto, port);
2611
2612 if (ofport) {
2613 if (ofport->opp.config & OFPPC_NO_FWD) {
2614 /* Forwarding disabled on port. */
2615 return;
2616 }
2617 } else {
2618 /*
2619 * We don't have an ofport record for this port, but it doesn't hurt to
2620 * allow forwarding to it anyhow. Maybe such a port will appear later
2621 * and we're pre-populating the flow table.
2622 */
2623 }
2624
2625 odp_actions_add(ctx->out, ODPAT_OUTPUT)->output.port = port;
2626 ctx->nf_output_iface = port;
2627 }
2628
2629 static struct rule *
2630 rule_lookup(struct ofproto *ofproto, const struct flow *flow)
2631 {
2632 return rule_from_cls_rule(classifier_lookup(&ofproto->cls, flow));
2633 }
2634
2635 static void
2636 xlate_table_action(struct action_xlate_ctx *ctx, uint16_t in_port)
2637 {
2638 if (ctx->recurse < MAX_RESUBMIT_RECURSION) {
2639 uint16_t old_in_port;
2640 struct rule *rule;
2641
2642 /* Look up a flow with 'in_port' as the input port. Then restore the
2643 * original input port (otherwise OFPP_NORMAL and OFPP_IN_PORT will
2644 * have surprising behavior). */
2645 old_in_port = ctx->flow.in_port;
2646 ctx->flow.in_port = in_port;
2647 rule = rule_lookup(ctx->ofproto, &ctx->flow);
2648 ctx->flow.in_port = old_in_port;
2649
2650 if (rule) {
2651 ctx->recurse++;
2652 do_xlate_actions(rule->actions, rule->n_actions, ctx);
2653 ctx->recurse--;
2654 }
2655 } else {
2656 struct vlog_rate_limit recurse_rl = VLOG_RATE_LIMIT_INIT(1, 1);
2657
2658 VLOG_ERR_RL(&recurse_rl, "NXAST_RESUBMIT recursed over %d times",
2659 MAX_RESUBMIT_RECURSION);
2660 }
2661 }
2662
2663 static void
2664 flood_packets(struct ofproto *ofproto, uint16_t odp_in_port, uint32_t mask,
2665 uint16_t *nf_output_iface, struct odp_actions *actions)
2666 {
2667 struct ofport *ofport;
2668
2669 HMAP_FOR_EACH (ofport, hmap_node, &ofproto->ports) {
2670 uint16_t odp_port = ofport->odp_port;
2671 if (odp_port != odp_in_port && !(ofport->opp.config & mask)) {
2672 odp_actions_add(actions, ODPAT_OUTPUT)->output.port = odp_port;
2673 }
2674 }
2675 *nf_output_iface = NF_OUT_FLOOD;
2676 }
2677
2678 static void
2679 xlate_output_action__(struct action_xlate_ctx *ctx,
2680 uint16_t port, uint16_t max_len)
2681 {
2682 uint16_t odp_port;
2683 uint16_t prev_nf_output_iface = ctx->nf_output_iface;
2684
2685 ctx->nf_output_iface = NF_OUT_DROP;
2686
2687 switch (port) {
2688 case OFPP_IN_PORT:
2689 add_output_action(ctx, ctx->flow.in_port);
2690 break;
2691 case OFPP_TABLE:
2692 xlate_table_action(ctx, ctx->flow.in_port);
2693 break;
2694 case OFPP_NORMAL:
2695 if (!ctx->ofproto->ofhooks->normal_cb(&ctx->flow, ctx->packet,
2696 ctx->out, &ctx->tags,
2697 &ctx->nf_output_iface,
2698 ctx->ofproto->aux)) {
2699 COVERAGE_INC(ofproto_uninstallable);
2700 ctx->may_set_up_flow = false;
2701 }
2702 break;
2703 case OFPP_FLOOD:
2704 flood_packets(ctx->ofproto, ctx->flow.in_port, OFPPC_NO_FLOOD,
2705 &ctx->nf_output_iface, ctx->out);
2706 break;
2707 case OFPP_ALL:
2708 flood_packets(ctx->ofproto, ctx->flow.in_port, 0,
2709 &ctx->nf_output_iface, ctx->out);
2710 break;
2711 case OFPP_CONTROLLER:
2712 add_controller_action(ctx->out, max_len);
2713 break;
2714 case OFPP_LOCAL:
2715 add_output_action(ctx, ODPP_LOCAL);
2716 break;
2717 default:
2718 odp_port = ofp_port_to_odp_port(port);
2719 if (odp_port != ctx->flow.in_port) {
2720 add_output_action(ctx, odp_port);
2721 }
2722 break;
2723 }
2724
2725 if (prev_nf_output_iface == NF_OUT_FLOOD) {
2726 ctx->nf_output_iface = NF_OUT_FLOOD;
2727 } else if (ctx->nf_output_iface == NF_OUT_DROP) {
2728 ctx->nf_output_iface = prev_nf_output_iface;
2729 } else if (prev_nf_output_iface != NF_OUT_DROP &&
2730 ctx->nf_output_iface != NF_OUT_FLOOD) {
2731 ctx->nf_output_iface = NF_OUT_MULTI;
2732 }
2733 }
2734
2735 static void
2736 xlate_output_action(struct action_xlate_ctx *ctx,
2737 const struct ofp_action_output *oao)
2738 {
2739 xlate_output_action__(ctx, ntohs(oao->port), ntohs(oao->max_len));
2740 }
2741
2742 /* If the final ODP action in 'ctx' is "pop priority", drop it, as an
2743 * optimization, because we're going to add another action that sets the
2744 * priority immediately after, or because there are no actions following the
2745 * pop. */
2746 static void
2747 remove_pop_action(struct action_xlate_ctx *ctx)
2748 {
2749 size_t n = ctx->out->n_actions;
2750 if (n > 0 && ctx->out->actions[n - 1].type == ODPAT_POP_PRIORITY) {
2751 ctx->out->n_actions--;
2752 }
2753 }
2754
2755 static void
2756 xlate_enqueue_action(struct action_xlate_ctx *ctx,
2757 const struct ofp_action_enqueue *oae)
2758 {
2759 uint16_t ofp_port, odp_port;
2760 uint32_t priority;
2761 int error;
2762
2763 error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(oae->queue_id),
2764 &priority);
2765 if (error) {
2766 /* Fall back to ordinary output action. */
2767 xlate_output_action__(ctx, ntohs(oae->port), 0);
2768 return;
2769 }
2770
2771 /* Figure out ODP output port. */
2772 ofp_port = ntohs(oae->port);
2773 if (ofp_port != OFPP_IN_PORT) {
2774 odp_port = ofp_port_to_odp_port(ofp_port);
2775 } else {
2776 odp_port = ctx->flow.in_port;
2777 }
2778
2779 /* Add ODP actions. */
2780 remove_pop_action(ctx);
2781 odp_actions_add(ctx->out, ODPAT_SET_PRIORITY)->priority.priority
2782 = priority;
2783 add_output_action(ctx, odp_port);
2784 odp_actions_add(ctx->out, ODPAT_POP_PRIORITY);
2785
2786 /* Update NetFlow output port. */
2787 if (ctx->nf_output_iface == NF_OUT_DROP) {
2788 ctx->nf_output_iface = odp_port;
2789 } else if (ctx->nf_output_iface != NF_OUT_FLOOD) {
2790 ctx->nf_output_iface = NF_OUT_MULTI;
2791 }
2792 }
2793
2794 static void
2795 xlate_set_queue_action(struct action_xlate_ctx *ctx,
2796 const struct nx_action_set_queue *nasq)
2797 {
2798 uint32_t priority;
2799 int error;
2800
2801 error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(nasq->queue_id),
2802 &priority);
2803 if (error) {
2804 /* Couldn't translate queue to a priority, so ignore. A warning
2805 * has already been logged. */
2806 return;
2807 }
2808
2809 remove_pop_action(ctx);
2810 odp_actions_add(ctx->out, ODPAT_SET_PRIORITY)->priority.priority
2811 = priority;
2812 }
2813
2814 static void
2815 xlate_set_dl_tci(struct action_xlate_ctx *ctx)
2816 {
2817 ovs_be16 tci = ctx->flow.vlan_tci;
2818 if (!(tci & htons(VLAN_CFI))) {
2819 odp_actions_add(ctx->out, ODPAT_STRIP_VLAN);
2820 } else {
2821 union odp_action *oa = odp_actions_add(ctx->out, ODPAT_SET_DL_TCI);
2822 oa->dl_tci.tci = tci & ~htons(VLAN_CFI);
2823 }
2824 }
2825
2826 static void
2827 xlate_reg_move_action(struct action_xlate_ctx *ctx,
2828 const struct nx_action_reg_move *narm)
2829 {
2830 ovs_be16 old_tci = ctx->flow.vlan_tci;
2831
2832 nxm_execute_reg_move(narm, &ctx->flow);
2833
2834 if (ctx->flow.vlan_tci != old_tci) {
2835 xlate_set_dl_tci(ctx);
2836 }
2837 }
2838
2839 static void
2840 xlate_nicira_action(struct action_xlate_ctx *ctx,
2841 const struct nx_action_header *nah)
2842 {
2843 const struct nx_action_resubmit *nar;
2844 const struct nx_action_set_tunnel *nast;
2845 const struct nx_action_set_queue *nasq;
2846 union odp_action *oa;
2847 int subtype = ntohs(nah->subtype);
2848
2849 assert(nah->vendor == htonl(NX_VENDOR_ID));
2850 switch (subtype) {
2851 case NXAST_RESUBMIT:
2852 nar = (const struct nx_action_resubmit *) nah;
2853 xlate_table_action(ctx, ofp_port_to_odp_port(ntohs(nar->in_port)));
2854 break;
2855
2856 case NXAST_SET_TUNNEL:
2857 nast = (const struct nx_action_set_tunnel *) nah;
2858 oa = odp_actions_add(ctx->out, ODPAT_SET_TUNNEL);
2859 ctx->flow.tun_id = oa->tunnel.tun_id = nast->tun_id;
2860 break;
2861
2862 case NXAST_DROP_SPOOFED_ARP:
2863 if (ctx->flow.dl_type == htons(ETH_TYPE_ARP)) {
2864 odp_actions_add(ctx->out, ODPAT_DROP_SPOOFED_ARP);
2865 }
2866 break;
2867
2868 case NXAST_SET_QUEUE:
2869 nasq = (const struct nx_action_set_queue *) nah;
2870 xlate_set_queue_action(ctx, nasq);
2871 break;
2872
2873 case NXAST_POP_QUEUE:
2874 odp_actions_add(ctx->out, ODPAT_POP_PRIORITY);
2875 break;
2876
2877 case NXAST_REG_MOVE:
2878 xlate_reg_move_action(ctx, (const struct nx_action_reg_move *) nah);
2879 break;
2880
2881 case NXAST_REG_LOAD:
2882 nxm_execute_reg_load((const struct nx_action_reg_load *) nah,
2883 &ctx->flow);
2884
2885 case NXAST_NOTE:
2886 /* Nothing to do. */
2887 break;
2888
2889 /* If you add a new action here that modifies flow data, don't forget to
2890 * update the flow key in ctx->flow at the same time. */
2891
2892 default:
2893 VLOG_DBG_RL(&rl, "unknown Nicira action type %"PRIu16, subtype);
2894 break;
2895 }
2896 }
2897
2898 static void
2899 do_xlate_actions(const union ofp_action *in, size_t n_in,
2900 struct action_xlate_ctx *ctx)
2901 {
2902 struct actions_iterator iter;
2903 const union ofp_action *ia;
2904 const struct ofport *port;
2905
2906 port = get_port(ctx->ofproto, ctx->flow.in_port);
2907 if (port && port->opp.config & (OFPPC_NO_RECV | OFPPC_NO_RECV_STP) &&
2908 port->opp.config & (eth_addr_equals(ctx->flow.dl_dst, eth_addr_stp)
2909 ? OFPPC_NO_RECV_STP : OFPPC_NO_RECV)) {
2910 /* Drop this flow. */
2911 return;
2912 }
2913
2914 for (ia = actions_first(&iter, in, n_in); ia; ia = actions_next(&iter)) {
2915 uint16_t type = ntohs(ia->type);
2916 union odp_action *oa;
2917
2918 switch (type) {
2919 case OFPAT_OUTPUT:
2920 xlate_output_action(ctx, &ia->output);
2921 break;
2922
2923 case OFPAT_SET_VLAN_VID:
2924 ctx->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
2925 ctx->flow.vlan_tci |= ia->vlan_vid.vlan_vid | htons(VLAN_CFI);
2926 xlate_set_dl_tci(ctx);
2927 break;
2928
2929 case OFPAT_SET_VLAN_PCP:
2930 ctx->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
2931 ctx->flow.vlan_tci |= htons(
2932 (ia->vlan_pcp.vlan_pcp << VLAN_PCP_SHIFT) | VLAN_CFI);
2933 xlate_set_dl_tci(ctx);
2934 break;
2935
2936 case OFPAT_STRIP_VLAN:
2937 ctx->flow.vlan_tci = htons(0);
2938 xlate_set_dl_tci(ctx);
2939 break;
2940
2941 case OFPAT_SET_DL_SRC:
2942 oa = odp_actions_add(ctx->out, ODPAT_SET_DL_SRC);
2943 memcpy(oa->dl_addr.dl_addr,
2944 ((struct ofp_action_dl_addr *) ia)->dl_addr, ETH_ADDR_LEN);
2945 memcpy(ctx->flow.dl_src,
2946 ((struct ofp_action_dl_addr *) ia)->dl_addr, ETH_ADDR_LEN);
2947 break;
2948
2949 case OFPAT_SET_DL_DST:
2950 oa = odp_actions_add(ctx->out, ODPAT_SET_DL_DST);
2951 memcpy(oa->dl_addr.dl_addr,
2952 ((struct ofp_action_dl_addr *) ia)->dl_addr, ETH_ADDR_LEN);
2953 memcpy(ctx->flow.dl_dst,
2954 ((struct ofp_action_dl_addr *) ia)->dl_addr, ETH_ADDR_LEN);
2955 break;
2956
2957 case OFPAT_SET_NW_SRC:
2958 oa = odp_actions_add(ctx->out, ODPAT_SET_NW_SRC);
2959 ctx->flow.nw_src = oa->nw_addr.nw_addr = ia->nw_addr.nw_addr;
2960 break;
2961
2962 case OFPAT_SET_NW_DST:
2963 oa = odp_actions_add(ctx->out, ODPAT_SET_NW_DST);
2964 ctx->flow.nw_dst = oa->nw_addr.nw_addr = ia->nw_addr.nw_addr;
2965 break;
2966
2967 case OFPAT_SET_NW_TOS:
2968 oa = odp_actions_add(ctx->out, ODPAT_SET_NW_TOS);
2969 ctx->flow.nw_tos = oa->nw_tos.nw_tos = ia->nw_tos.nw_tos;
2970 break;
2971
2972 case OFPAT_SET_TP_SRC:
2973 oa = odp_actions_add(ctx->out, ODPAT_SET_TP_SRC);
2974 ctx->flow.tp_src = oa->tp_port.tp_port = ia->tp_port.tp_port;
2975 break;
2976
2977 case OFPAT_SET_TP_DST:
2978 oa = odp_actions_add(ctx->out, ODPAT_SET_TP_DST);
2979 ctx->flow.tp_dst = oa->tp_port.tp_port = ia->tp_port.tp_port;
2980 break;
2981
2982 case OFPAT_VENDOR:
2983 xlate_nicira_action(ctx, (const struct nx_action_header *) ia);
2984 break;
2985
2986 case OFPAT_ENQUEUE:
2987 xlate_enqueue_action(ctx, (const struct ofp_action_enqueue *) ia);
2988 break;
2989
2990 default:
2991 VLOG_DBG_RL(&rl, "unknown action type %"PRIu16, type);
2992 break;
2993 }
2994 }
2995 }
2996
2997 static int
2998 xlate_actions(const union ofp_action *in, size_t n_in,
2999 const struct flow *flow, struct ofproto *ofproto,
3000 const struct ofpbuf *packet,
3001 struct odp_actions *out, tag_type *tags, bool *may_set_up_flow,
3002 uint16_t *nf_output_iface)
3003 {
3004 struct action_xlate_ctx ctx;
3005
3006 COVERAGE_INC(ofproto_ofp2odp);
3007 odp_actions_init(out);
3008 ctx.flow = *flow;
3009 ctx.recurse = 0;
3010 ctx.ofproto = ofproto;
3011 ctx.packet = packet;
3012 ctx.out = out;
3013 ctx.tags = 0;
3014 ctx.may_set_up_flow = true;
3015 ctx.nf_output_iface = NF_OUT_DROP;
3016 do_xlate_actions(in, n_in, &ctx);
3017 remove_pop_action(&ctx);
3018
3019 /* Check with in-band control to see if we're allowed to set up this
3020 * flow. */
3021 if (!in_band_rule_check(ofproto->in_band, flow, out)) {
3022 ctx.may_set_up_flow = false;
3023 }
3024
3025 if (tags) {
3026 *tags = ctx.tags;
3027 }
3028 if (may_set_up_flow) {
3029 *may_set_up_flow = ctx.may_set_up_flow;
3030 }
3031 if (nf_output_iface) {
3032 *nf_output_iface = ctx.nf_output_iface;
3033 }
3034 if (odp_actions_overflow(out)) {
3035 COVERAGE_INC(odp_overflow);
3036 odp_actions_init(out);
3037 return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_TOO_MANY);
3038 }
3039 return 0;
3040 }
3041
3042 /* Checks whether 'ofconn' is a slave controller. If so, returns an OpenFlow
3043 * error message code (composed with ofp_mkerr()) for the caller to propagate
3044 * upward. Otherwise, returns 0.
3045 *
3046 * The log message mentions 'msg_type'. */
3047 static int
3048 reject_slave_controller(struct ofconn *ofconn, const const char *msg_type)
3049 {
3050 if (ofconn->type == OFCONN_PRIMARY && ofconn->role == NX_ROLE_SLAVE) {
3051 static struct vlog_rate_limit perm_rl = VLOG_RATE_LIMIT_INIT(1, 5);
3052 VLOG_WARN_RL(&perm_rl, "rejecting %s message from slave controller",
3053 msg_type);
3054
3055 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
3056 } else {
3057 return 0;
3058 }
3059 }
3060
3061 static int
3062 handle_packet_out(struct ofconn *ofconn, struct ofp_header *oh)
3063 {
3064 struct ofproto *p = ofconn->ofproto;
3065 struct ofp_packet_out *opo;
3066 struct ofpbuf payload, *buffer;
3067 union ofp_action *ofp_actions;
3068 struct odp_actions odp_actions;
3069 struct ofpbuf request;
3070 struct flow flow;
3071 size_t n_ofp_actions;
3072 uint16_t in_port;
3073 int error;
3074
3075 COVERAGE_INC(ofproto_packet_out);
3076
3077 error = reject_slave_controller(ofconn, "OFPT_PACKET_OUT");
3078 if (error) {
3079 return error;
3080 }
3081
3082 /* Get ofp_packet_out. */
3083 request.data = oh;
3084 request.size = ntohs(oh->length);
3085 opo = ofpbuf_try_pull(&request, offsetof(struct ofp_packet_out, actions));
3086 if (!opo) {
3087 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3088 }
3089
3090 /* Get actions. */
3091 error = ofputil_pull_actions(&request, ntohs(opo->actions_len),
3092 &ofp_actions, &n_ofp_actions);
3093 if (error) {
3094 return error;
3095 }
3096
3097 /* Get payload. */
3098 if (opo->buffer_id != htonl(UINT32_MAX)) {
3099 error = pktbuf_retrieve(ofconn->pktbuf, ntohl(opo->buffer_id),
3100 &buffer, &in_port);
3101 if (error || !buffer) {
3102 return error;
3103 }
3104 payload = *buffer;
3105 } else {
3106 payload = request;
3107 buffer = NULL;
3108 }
3109
3110 /* Extract flow, check actions. */
3111 flow_extract(&payload, 0, ofp_port_to_odp_port(ntohs(opo->in_port)),
3112 &flow);
3113 error = validate_actions(ofp_actions, n_ofp_actions, &flow, p->max_ports);
3114 if (error) {
3115 goto exit;
3116 }
3117
3118 /* Send. */
3119 error = xlate_actions(ofp_actions, n_ofp_actions, &flow, p, &payload,
3120 &odp_actions, NULL, NULL, NULL);
3121 if (!error) {
3122 dpif_execute(p->dpif, odp_actions.actions, odp_actions.n_actions,
3123 &payload);
3124 }
3125
3126 exit:
3127 ofpbuf_delete(buffer);
3128 return 0;
3129 }
3130
3131 static void
3132 update_port_config(struct ofproto *p, struct ofport *port,
3133 uint32_t config, uint32_t mask)
3134 {
3135 mask &= config ^ port->opp.config;
3136 if (mask & OFPPC_PORT_DOWN) {
3137 if (config & OFPPC_PORT_DOWN) {
3138 netdev_turn_flags_off(port->netdev, NETDEV_UP, true);
3139 } else {
3140 netdev_turn_flags_on(port->netdev, NETDEV_UP, true);
3141 }
3142 }
3143 #define REVALIDATE_BITS (OFPPC_NO_RECV | OFPPC_NO_RECV_STP | \
3144 OFPPC_NO_FWD | OFPPC_NO_FLOOD)
3145 if (mask & REVALIDATE_BITS) {
3146 COVERAGE_INC(ofproto_costly_flags);
3147 port->opp.config ^= mask & REVALIDATE_BITS;
3148 p->need_revalidate = true;
3149 }
3150 #undef REVALIDATE_BITS
3151 if (mask & OFPPC_NO_PACKET_IN) {
3152 port->opp.config ^= OFPPC_NO_PACKET_IN;
3153 }
3154 }
3155
3156 static int
3157 handle_port_mod(struct ofconn *ofconn, struct ofp_header *oh)
3158 {
3159 struct ofproto *p = ofconn->ofproto;
3160 const struct ofp_port_mod *opm;
3161 struct ofport *port;
3162 int error;
3163
3164 error = reject_slave_controller(ofconn, "OFPT_PORT_MOD");
3165 if (error) {
3166 return error;
3167 }
3168 error = check_ofp_message(oh, OFPT_PORT_MOD, sizeof *opm);
3169 if (error) {
3170 return error;
3171 }
3172 opm = (struct ofp_port_mod *) oh;
3173
3174 port = get_port(p, ofp_port_to_odp_port(ntohs(opm->port_no)));
3175 if (!port) {
3176 return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_PORT);
3177 } else if (memcmp(port->opp.hw_addr, opm->hw_addr, OFP_ETH_ALEN)) {
3178 return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_HW_ADDR);
3179 } else {
3180 update_port_config(p, port, ntohl(opm->config), ntohl(opm->mask));
3181 if (opm->advertise) {
3182 netdev_set_advertisements(port->netdev, ntohl(opm->advertise));
3183 }
3184 }
3185 return 0;
3186 }
3187
3188 static struct ofpbuf *
3189 make_ofp_stats_reply(ovs_be32 xid, ovs_be16 type, size_t body_len)
3190 {
3191 struct ofp_stats_reply *osr;
3192 struct ofpbuf *msg;
3193
3194 msg = ofpbuf_new(MIN(sizeof *osr + body_len, UINT16_MAX));
3195 osr = put_openflow_xid(sizeof *osr, OFPT_STATS_REPLY, xid, msg);
3196 osr->type = type;
3197 osr->flags = htons(0);
3198 return msg;
3199 }
3200
3201 static struct ofpbuf *
3202 start_ofp_stats_reply(const struct ofp_stats_request *request, size_t body_len)
3203 {
3204 return make_ofp_stats_reply(request->header.xid, request->type, body_len);
3205 }
3206
3207 static void *
3208 append_ofp_stats_reply(size_t nbytes, struct ofconn *ofconn,
3209 struct ofpbuf **msgp)
3210 {
3211 struct ofpbuf *msg = *msgp;
3212 assert(nbytes <= UINT16_MAX - sizeof(struct ofp_stats_reply));
3213 if (nbytes + msg->size > UINT16_MAX) {
3214 struct ofp_stats_reply *reply = msg->data;
3215 reply->flags = htons(OFPSF_REPLY_MORE);
3216 *msgp = make_ofp_stats_reply(reply->header.xid, reply->type, nbytes);
3217 queue_tx(msg, ofconn, ofconn->reply_counter);
3218 }
3219 return ofpbuf_put_uninit(*msgp, nbytes);
3220 }
3221
3222 static struct ofpbuf *
3223 make_nxstats_reply(ovs_be32 xid, ovs_be32 subtype, size_t body_len)
3224 {
3225 struct nicira_stats_msg *nsm;
3226 struct ofpbuf *msg;
3227
3228 msg = ofpbuf_new(MIN(sizeof *nsm + body_len, UINT16_MAX));
3229 nsm = put_openflow_xid(sizeof *nsm, OFPT_STATS_REPLY, xid, msg);
3230 nsm->type = htons(OFPST_VENDOR);
3231 nsm->flags = htons(0);
3232 nsm->vendor = htonl(NX_VENDOR_ID);
3233 nsm->subtype = htonl(subtype);
3234 return msg;
3235 }
3236
3237 static struct ofpbuf *
3238 start_nxstats_reply(const struct nicira_stats_msg *request, size_t body_len)
3239 {
3240 return make_nxstats_reply(request->header.xid, request->subtype, body_len);
3241 }
3242
3243 static void
3244 append_nxstats_reply(size_t nbytes, struct ofconn *ofconn,
3245 struct ofpbuf **msgp)
3246 {
3247 struct ofpbuf *msg = *msgp;
3248 assert(nbytes <= UINT16_MAX - sizeof(struct nicira_stats_msg));
3249 if (nbytes + msg->size > UINT16_MAX) {
3250 struct nicira_stats_msg *reply = msg->data;
3251 reply->flags = htons(OFPSF_REPLY_MORE);
3252 *msgp = make_nxstats_reply(reply->header.xid, reply->subtype, nbytes);
3253 queue_tx(msg, ofconn, ofconn->reply_counter);
3254 }
3255 ofpbuf_prealloc_tailroom(*msgp, nbytes);
3256 }
3257
3258 static int
3259 handle_desc_stats_request(struct ofconn *ofconn,
3260 struct ofp_stats_request *request)
3261 {
3262 struct ofproto *p = ofconn->ofproto;
3263 struct ofp_desc_stats *ods;
3264 struct ofpbuf *msg;
3265
3266 msg = start_ofp_stats_reply(request, sizeof *ods);
3267 ods = append_ofp_stats_reply(sizeof *ods, ofconn, &msg);
3268 memset(ods, 0, sizeof *ods);
3269 ovs_strlcpy(ods->mfr_desc, p->mfr_desc, sizeof ods->mfr_desc);
3270 ovs_strlcpy(ods->hw_desc, p->hw_desc, sizeof ods->hw_desc);
3271 ovs_strlcpy(ods->sw_desc, p->sw_desc, sizeof ods->sw_desc);
3272 ovs_strlcpy(ods->serial_num, p->serial_desc, sizeof ods->serial_num);
3273 ovs_strlcpy(ods->dp_desc, p->dp_desc, sizeof ods->dp_desc);
3274 queue_tx(msg, ofconn, ofconn->reply_counter);
3275
3276 return 0;
3277 }
3278
3279 static int
3280 handle_table_stats_request(struct ofconn *ofconn,
3281 struct ofp_stats_request *request)
3282 {
3283 struct ofproto *p = ofconn->ofproto;
3284 struct ofp_table_stats *ots;
3285 struct ofpbuf *msg;
3286
3287 msg = start_ofp_stats_reply(request, sizeof *ots * 2);
3288
3289 /* Classifier table. */
3290 ots = append_ofp_stats_reply(sizeof *ots, ofconn, &msg);
3291 memset(ots, 0, sizeof *ots);
3292 strcpy(ots->name, "classifier");
3293 ots->wildcards = (ofconn->flow_format == NXFF_OPENFLOW10
3294 ? htonl(OFPFW_ALL) : htonl(OVSFW_ALL));
3295 ots->max_entries = htonl(1024 * 1024); /* An arbitrary big number. */
3296 ots->active_count = htonl(classifier_count(&p->cls));
3297 ots->lookup_count = htonll(0); /* XXX */
3298 ots->matched_count = htonll(0); /* XXX */
3299
3300 queue_tx(msg, ofconn, ofconn->reply_counter);
3301 return 0;
3302 }
3303
3304 static void
3305 append_port_stat(struct ofport *port, struct ofconn *ofconn,
3306 struct ofpbuf **msgp)
3307 {
3308 struct netdev_stats stats;
3309 struct ofp_port_stats *ops;
3310
3311 /* Intentionally ignore return value, since errors will set
3312 * 'stats' to all-1s, which is correct for OpenFlow, and
3313 * netdev_get_stats() will log errors. */
3314 netdev_get_stats(port->netdev, &stats);
3315
3316 ops = append_ofp_stats_reply(sizeof *ops, ofconn, msgp);
3317 ops->port_no = htons(port->opp.port_no);
3318 memset(ops->pad, 0, sizeof ops->pad);
3319 ops->rx_packets = htonll(stats.rx_packets);
3320 ops->tx_packets = htonll(stats.tx_packets);
3321 ops->rx_bytes = htonll(stats.rx_bytes);
3322 ops->tx_bytes = htonll(stats.tx_bytes);
3323 ops->rx_dropped = htonll(stats.rx_dropped);
3324 ops->tx_dropped = htonll(stats.tx_dropped);
3325 ops->rx_errors = htonll(stats.rx_errors);
3326 ops->tx_errors = htonll(stats.tx_errors);
3327 ops->rx_frame_err = htonll(stats.rx_frame_errors);
3328 ops->rx_over_err = htonll(stats.rx_over_errors);
3329 ops->rx_crc_err = htonll(stats.rx_crc_errors);
3330 ops->collisions = htonll(stats.collisions);
3331 }
3332
3333 static int
3334 handle_port_stats_request(struct ofconn *ofconn, struct ofp_stats_request *osr,
3335 size_t arg_size)
3336 {
3337 struct ofproto *p = ofconn->ofproto;
3338 struct ofp_port_stats_request *psr;
3339 struct ofp_port_stats *ops;
3340 struct ofpbuf *msg;
3341 struct ofport *port;
3342
3343 if (arg_size != sizeof *psr) {
3344 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3345 }
3346 psr = (struct ofp_port_stats_request *) osr->body;
3347
3348 msg = start_ofp_stats_reply(osr, sizeof *ops * 16);
3349 if (psr->port_no != htons(OFPP_NONE)) {
3350 port = get_port(p, ofp_port_to_odp_port(ntohs(psr->port_no)));
3351 if (port) {
3352 append_port_stat(port, ofconn, &msg);
3353 }
3354 } else {
3355 HMAP_FOR_EACH (port, hmap_node, &p->ports) {
3356 append_port_stat(port, ofconn, &msg);
3357 }
3358 }
3359
3360 queue_tx(msg, ofconn, ofconn->reply_counter);
3361 return 0;
3362 }
3363
3364 /* Obtains statistic counters for 'rule' within 'p' and stores them into
3365 * '*packet_countp' and '*byte_countp'. The returned statistics include
3366 * statistics for all of 'rule''s facets. */
3367 static void
3368 query_stats(struct ofproto *p, struct rule *rule,
3369 uint64_t *packet_countp, uint64_t *byte_countp)
3370 {
3371 uint64_t packet_count, byte_count;
3372 struct facet *facet;
3373 struct odp_flow *odp_flows;
3374 size_t n_odp_flows;
3375
3376 /* Start from historical data for 'rule' itself that are no longer tracked
3377 * by the datapath. This counts, for example, facets that have expired. */
3378 packet_count = rule->packet_count;
3379 byte_count = rule->byte_count;
3380
3381 /* Prepare to ask the datapath for statistics on all of the rule's facets.
3382 *
3383 * Also, add any statistics that are not tracked by the datapath for each
3384 * facet. This includes, for example, statistics for packets that were
3385 * executed "by hand" by ofproto via dpif_execute() but must be accounted
3386 * to a rule. */
3387 odp_flows = xzalloc(list_size(&rule->facets) * sizeof *odp_flows);
3388 n_odp_flows = 0;
3389 LIST_FOR_EACH (facet, list_node, &rule->facets) {
3390 struct odp_flow *odp_flow = &odp_flows[n_odp_flows++];
3391 odp_flow_key_from_flow(&odp_flow->key, &facet->flow);
3392 packet_count += facet->packet_count;
3393 byte_count += facet->byte_count;
3394 }
3395
3396 /* Fetch up-to-date statistics from the datapath and add them in. */
3397 if (!dpif_flow_get_multiple(p->dpif, odp_flows, n_odp_flows)) {
3398 size_t i;
3399
3400 for (i = 0; i < n_odp_flows; i++) {
3401 struct odp_flow *odp_flow = &odp_flows[i];
3402 packet_count += odp_flow->stats.n_packets;
3403 byte_count += odp_flow->stats.n_bytes;
3404 }
3405 }
3406 free(odp_flows);
3407
3408 /* Return the stats to the caller. */
3409 *packet_countp = packet_count;
3410 *byte_countp = byte_count;
3411 }
3412
3413 static void
3414 calc_flow_duration(long long int start, ovs_be32 *sec, ovs_be32 *nsec)
3415 {
3416 long long int msecs = time_msec() - start;
3417 *sec = htonl(msecs / 1000);
3418 *nsec = htonl((msecs % 1000) * (1000 * 1000));
3419 }
3420
3421 static void
3422 put_ofp_flow_stats(struct ofconn *ofconn, struct rule *rule,
3423 ovs_be16 out_port, struct ofpbuf **replyp)
3424 {
3425 struct ofp_flow_stats *ofs;
3426 uint64_t packet_count, byte_count;
3427 size_t act_len, len;
3428
3429 if (rule_is_hidden(rule) || !rule_has_out_port(rule, out_port)) {
3430 return;
3431 }
3432
3433 act_len = sizeof *rule->actions * rule->n_actions;
3434 len = offsetof(struct ofp_flow_stats, actions) + act_len;
3435
3436 query_stats(ofconn->ofproto, rule, &packet_count, &byte_count);
3437
3438 ofs = append_ofp_stats_reply(len, ofconn, replyp);
3439 ofs->length = htons(len);
3440 ofs->table_id = 0;
3441 ofs->pad = 0;
3442 ofputil_cls_rule_to_match(&rule->cr, ofconn->flow_format, &ofs->match);
3443 calc_flow_duration(rule->created, &ofs->duration_sec, &ofs->duration_nsec);
3444 ofs->cookie = rule->flow_cookie;
3445 ofs->priority = htons(rule->cr.priority);
3446 ofs->idle_timeout = htons(rule->idle_timeout);
3447 ofs->hard_timeout = htons(rule->hard_timeout);
3448 memset(ofs->pad2, 0, sizeof ofs->pad2);
3449 ofs->packet_count = htonll(packet_count);
3450 ofs->byte_count = htonll(byte_count);
3451 if (rule->n_actions > 0) {
3452 memcpy(ofs->actions, rule->actions, act_len);
3453 }
3454 }
3455
3456 static bool
3457 is_valid_table(uint8_t table_id)
3458 {
3459 return table_id == 0 || table_id == 0xff;
3460 }
3461
3462 static int
3463 handle_flow_stats_request(struct ofconn *ofconn,
3464 const struct ofp_stats_request *osr, size_t arg_size)
3465 {
3466 struct ofp_flow_stats_request *fsr;
3467 struct ofpbuf *reply;
3468
3469 if (arg_size != sizeof *fsr) {
3470 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3471 }
3472 fsr = (struct ofp_flow_stats_request *) osr->body;
3473
3474 COVERAGE_INC(ofproto_flows_req);
3475 reply = start_ofp_stats_reply(osr, 1024);
3476 if (is_valid_table(fsr->table_id)) {
3477 struct cls_cursor cursor;
3478 struct cls_rule target;
3479 struct rule *rule;
3480
3481 ofputil_cls_rule_from_match(&fsr->match, 0, NXFF_OPENFLOW10, 0,
3482 &target);
3483 cls_cursor_init(&cursor, &ofconn->ofproto->cls, &target);
3484 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3485 put_ofp_flow_stats(ofconn, rule, fsr->out_port, &reply);
3486 }
3487 }
3488 queue_tx(reply, ofconn, ofconn->reply_counter);
3489
3490 return 0;
3491 }
3492
3493 static void
3494 put_nx_flow_stats(struct ofconn *ofconn, struct rule *rule,
3495 ovs_be16 out_port, struct ofpbuf **replyp)
3496 {
3497 struct nx_flow_stats *nfs;
3498 uint64_t packet_count, byte_count;
3499 size_t act_len, start_len;
3500 struct ofpbuf *reply;
3501
3502 if (rule_is_hidden(rule) || !rule_has_out_port(rule, out_port)) {
3503 return;
3504 }
3505
3506 query_stats(ofconn->ofproto, rule, &packet_count, &byte_count);
3507
3508 act_len = sizeof *rule->actions * rule->n_actions;
3509
3510 start_len = (*replyp)->size;
3511 append_nxstats_reply(sizeof *nfs + NXM_MAX_LEN + act_len, ofconn, replyp);
3512 reply = *replyp;
3513
3514 nfs = ofpbuf_put_uninit(reply, sizeof *nfs);
3515 nfs->table_id = 0;
3516 nfs->pad = 0;
3517 calc_flow_duration(rule->created, &nfs->duration_sec, &nfs->duration_nsec);
3518 nfs->cookie = rule->flow_cookie;
3519 nfs->priority = htons(rule->cr.priority);
3520 nfs->idle_timeout = htons(rule->idle_timeout);
3521 nfs->hard_timeout = htons(rule->hard_timeout);
3522 nfs->match_len = htons(nx_put_match(reply, &rule->cr));
3523 memset(nfs->pad2, 0, sizeof nfs->pad2);
3524 nfs->packet_count = htonll(packet_count);
3525 nfs->byte_count = htonll(byte_count);
3526 if (rule->n_actions > 0) {
3527 ofpbuf_put(reply, rule->actions, act_len);
3528 }
3529 nfs->length = htons(reply->size - start_len);
3530 }
3531
3532 static int
3533 handle_nxst_flow(struct ofconn *ofconn, struct ofpbuf *b)
3534 {
3535 struct nx_flow_stats_request *nfsr;
3536 struct cls_rule target;
3537 struct ofpbuf *reply;
3538 int error;
3539
3540 /* Dissect the message. */
3541 nfsr = ofpbuf_try_pull(b, sizeof *nfsr);
3542 if (!nfsr) {
3543 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3544 }
3545 error = nx_pull_match(b, ntohs(nfsr->match_len), 0, &target);
3546 if (error) {
3547 return error;
3548 }
3549
3550 COVERAGE_INC(ofproto_flows_req);
3551 reply = start_nxstats_reply(&nfsr->nsm, 1024);
3552 if (is_valid_table(nfsr->table_id)) {
3553 struct cls_cursor cursor;
3554 struct rule *rule;
3555
3556 cls_cursor_init(&cursor, &ofconn->ofproto->cls, &target);
3557 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3558 put_nx_flow_stats(ofconn, rule, nfsr->out_port, &reply);
3559 }
3560 }
3561 queue_tx(reply, ofconn, ofconn->reply_counter);
3562
3563 return 0;
3564 }
3565
3566 static void
3567 flow_stats_ds(struct ofproto *ofproto, struct rule *rule, struct ds *results)
3568 {
3569 struct ofp_match match;
3570 uint64_t packet_count, byte_count;
3571 size_t act_len = sizeof *rule->actions * rule->n_actions;
3572
3573 query_stats(ofproto, rule, &packet_count, &byte_count);
3574 ofputil_cls_rule_to_match(&rule->cr, NXFF_OPENFLOW10, &match);
3575
3576 ds_put_format(results, "duration=%llds, ",
3577 (time_msec() - rule->created) / 1000);
3578 ds_put_format(results, "priority=%u, ", rule->cr.priority);
3579 ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
3580 ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
3581 ofp_print_match(results, &match, true);
3582 if (act_len > 0) {
3583 ofp_print_actions(results, &rule->actions->header, act_len);
3584 } else {
3585 ds_put_cstr(results, "drop");
3586 }
3587 ds_put_cstr(results, "\n");
3588 }
3589
3590 /* Adds a pretty-printed description of all flows to 'results', including
3591 * those marked hidden by secchan (e.g., by in-band control). */
3592 void
3593 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
3594 {
3595 struct cls_cursor cursor;
3596 struct rule *rule;
3597
3598 cls_cursor_init(&cursor, &p->cls, NULL);
3599 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3600 flow_stats_ds(p, rule, results);
3601 }
3602 }
3603
3604 static void
3605 query_aggregate_stats(struct ofproto *ofproto, struct cls_rule *target,
3606 ovs_be16 out_port, uint8_t table_id,
3607 struct ofp_aggregate_stats_reply *oasr)
3608 {
3609 uint64_t total_packets = 0;
3610 uint64_t total_bytes = 0;
3611 int n_flows = 0;
3612
3613 COVERAGE_INC(ofproto_agg_request);
3614
3615 if (is_valid_table(table_id)) {
3616 struct cls_cursor cursor;
3617 struct rule *rule;
3618
3619 cls_cursor_init(&cursor, &ofproto->cls, target);
3620 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3621 if (!rule_is_hidden(rule) && rule_has_out_port(rule, out_port)) {
3622 uint64_t packet_count;
3623 uint64_t byte_count;
3624
3625 query_stats(ofproto, rule, &packet_count, &byte_count);
3626
3627 total_packets += packet_count;
3628 total_bytes += byte_count;
3629 n_flows++;
3630 }
3631 }
3632 }
3633
3634 oasr->flow_count = htonl(n_flows);
3635 oasr->packet_count = htonll(total_packets);
3636 oasr->byte_count = htonll(total_bytes);
3637 memset(oasr->pad, 0, sizeof oasr->pad);
3638 }
3639
3640 static int
3641 handle_aggregate_stats_request(struct ofconn *ofconn,
3642 const struct ofp_stats_request *osr,
3643 size_t arg_size)
3644 {
3645 struct ofp_aggregate_stats_request *request;
3646 struct ofp_aggregate_stats_reply *reply;
3647 struct cls_rule target;
3648 struct ofpbuf *msg;
3649
3650 if (arg_size != sizeof *request) {
3651 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3652 }
3653 request = (struct ofp_aggregate_stats_request *) osr->body;
3654
3655 ofputil_cls_rule_from_match(&request->match, 0, NXFF_OPENFLOW10, 0,
3656 &target);
3657
3658 msg = start_ofp_stats_reply(osr, sizeof *reply);
3659 reply = append_ofp_stats_reply(sizeof *reply, ofconn, &msg);
3660 query_aggregate_stats(ofconn->ofproto, &target, request->out_port,
3661 request->table_id, reply);
3662 queue_tx(msg, ofconn, ofconn->reply_counter);
3663 return 0;
3664 }
3665
3666 static int
3667 handle_nxst_aggregate(struct ofconn *ofconn, struct ofpbuf *b)
3668 {
3669 struct nx_aggregate_stats_request *request;
3670 struct ofp_aggregate_stats_reply *reply;
3671 struct cls_rule target;
3672 struct ofpbuf *buf;
3673 int error;
3674
3675 /* Dissect the message. */
3676 request = ofpbuf_try_pull(b, sizeof *request);
3677 if (!request) {
3678 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3679 }
3680 error = nx_pull_match(b, ntohs(request->match_len), 0, &target);
3681 if (error) {
3682 return error;
3683 }
3684
3685 /* Reply. */
3686 COVERAGE_INC(ofproto_flows_req);
3687 buf = start_nxstats_reply(&request->nsm, sizeof *reply);
3688 reply = ofpbuf_put_uninit(buf, sizeof *reply);
3689 query_aggregate_stats(ofconn->ofproto, &target, request->out_port,
3690 request->table_id, reply);
3691 queue_tx(buf, ofconn, ofconn->reply_counter);
3692
3693 return 0;
3694 }
3695
3696 struct queue_stats_cbdata {
3697 struct ofconn *ofconn;
3698 struct ofport *ofport;
3699 struct ofpbuf *msg;
3700 };
3701
3702 static void
3703 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
3704 const struct netdev_queue_stats *stats)
3705 {
3706 struct ofp_queue_stats *reply;
3707
3708 reply = append_ofp_stats_reply(sizeof *reply, cbdata->ofconn, &cbdata->msg);
3709 reply->port_no = htons(cbdata->ofport->opp.port_no);
3710 memset(reply->pad, 0, sizeof reply->pad);
3711 reply->queue_id = htonl(queue_id);
3712 reply->tx_bytes = htonll(stats->tx_bytes);
3713 reply->tx_packets = htonll(stats->tx_packets);
3714 reply->tx_errors = htonll(stats->tx_errors);
3715 }
3716
3717 static void
3718 handle_queue_stats_dump_cb(uint32_t queue_id,
3719 struct netdev_queue_stats *stats,
3720 void *cbdata_)
3721 {
3722 struct queue_stats_cbdata *cbdata = cbdata_;
3723
3724 put_queue_stats(cbdata, queue_id, stats);
3725 }
3726
3727 static void
3728 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
3729 struct queue_stats_cbdata *cbdata)
3730 {
3731 cbdata->ofport = port;
3732 if (queue_id == OFPQ_ALL) {
3733 netdev_dump_queue_stats(port->netdev,
3734 handle_queue_stats_dump_cb, cbdata);
3735 } else {
3736 struct netdev_queue_stats stats;
3737
3738 if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
3739 put_queue_stats(cbdata, queue_id, &stats);
3740 }
3741 }
3742 }
3743
3744 static int
3745 handle_queue_stats_request(struct ofconn *ofconn,
3746 const struct ofp_stats_request *osr,
3747 size_t arg_size)
3748 {
3749 struct ofproto *ofproto = ofconn->ofproto;
3750 struct ofp_queue_stats_request *qsr;
3751 struct queue_stats_cbdata cbdata;
3752 struct ofport *port;
3753 unsigned int port_no;
3754 uint32_t queue_id;
3755
3756 if (arg_size != sizeof *qsr) {
3757 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3758 }
3759 qsr = (struct ofp_queue_stats_request *) osr->body;
3760
3761 COVERAGE_INC(ofproto_queue_req);
3762
3763 cbdata.ofconn = ofconn;
3764 cbdata.msg = start_ofp_stats_reply(osr, 128);
3765
3766 port_no = ntohs(qsr->port_no);
3767 queue_id = ntohl(qsr->queue_id);
3768 if (port_no == OFPP_ALL) {
3769 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3770 handle_queue_stats_for_port(port, queue_id, &cbdata);
3771 }
3772 } else if (port_no < ofproto->max_ports) {
3773 port = get_port(ofproto, ofp_port_to_odp_port(port_no));
3774 if (port) {
3775 handle_queue_stats_for_port(port, queue_id, &cbdata);
3776 }
3777 } else {
3778 ofpbuf_delete(cbdata.msg);
3779 return ofp_mkerr(OFPET_QUEUE_OP_FAILED, OFPQOFC_BAD_PORT);
3780 }
3781 queue_tx(cbdata.msg, ofconn, ofconn->reply_counter);
3782
3783 return 0;
3784 }
3785
3786 static int
3787 handle_vendor_stats_request(struct ofconn *ofconn,
3788 struct ofp_stats_request *osr, size_t arg_size)
3789 {
3790 struct nicira_stats_msg *nsm;
3791 struct ofpbuf b;
3792 ovs_be32 vendor;
3793
3794 if (arg_size < 4) {
3795 VLOG_WARN_RL(&rl, "truncated vendor stats request body");
3796 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3797 }
3798
3799 memcpy(&vendor, osr->body, sizeof vendor);
3800 if (vendor != htonl(NX_VENDOR_ID)) {
3801 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_VENDOR);
3802 }
3803
3804 if (ntohs(osr->header.length) < sizeof(struct nicira_stats_msg)) {
3805 VLOG_WARN_RL(&rl, "truncated Nicira stats request");
3806 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3807 }
3808
3809 nsm = (struct nicira_stats_msg *) osr;
3810 b.data = nsm;
3811 b.size = ntohs(nsm->header.length);
3812 switch (ntohl(nsm->subtype)) {
3813 case NXST_FLOW:
3814 return handle_nxst_flow(ofconn, &b);
3815
3816 case NXST_AGGREGATE:
3817 return handle_nxst_aggregate(ofconn, &b);
3818
3819 default:
3820 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE);
3821 }
3822 }
3823
3824 static int
3825 handle_stats_request(struct ofconn *ofconn, struct ofp_header *oh)
3826 {
3827 struct ofp_stats_request *osr;
3828 size_t arg_size;
3829 int error;
3830
3831 error = check_ofp_message_array(oh, OFPT_STATS_REQUEST, sizeof *osr,
3832 1, &arg_size);
3833 if (error) {
3834 return error;
3835 }
3836 osr = (struct ofp_stats_request *) oh;
3837
3838 switch (ntohs(osr->type)) {
3839 case OFPST_DESC:
3840 return handle_desc_stats_request(ofconn, osr);
3841
3842 case OFPST_FLOW:
3843 return handle_flow_stats_request(ofconn, osr, arg_size);
3844
3845 case OFPST_AGGREGATE:
3846 return handle_aggregate_stats_request(ofconn, osr, arg_size);
3847
3848 case OFPST_TABLE:
3849 return handle_table_stats_request(ofconn, osr);
3850
3851 case OFPST_PORT:
3852 return handle_port_stats_request(ofconn, osr, arg_size);
3853
3854 case OFPST_QUEUE:
3855 return handle_queue_stats_request(ofconn, osr, arg_size);
3856
3857 case OFPST_VENDOR:
3858 return handle_vendor_stats_request(ofconn, osr, arg_size);
3859
3860 default:
3861 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT);
3862 }
3863 }
3864
3865 static long long int
3866 msec_from_nsec(uint64_t sec, uint32_t nsec)
3867 {
3868 return !sec ? 0 : sec * 1000 + nsec / 1000000;
3869 }
3870
3871 static void
3872 facet_update_time(struct ofproto *ofproto, struct facet *facet,
3873 const struct odp_flow_stats *stats)
3874 {
3875 long long int used = msec_from_nsec(stats->used_sec, stats->used_nsec);
3876 if (used > facet->used) {
3877 facet->used = used;
3878 if (used > facet->rule->used) {
3879 facet->rule->used = used;
3880 }
3881 netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, used);
3882 }
3883 }
3884
3885 /* Folds the statistics from 'stats' into the counters in 'facet'.
3886 *
3887 * Because of the meaning of a facet's counters, it only makes sense to do this
3888 * if 'stats' are not tracked in the datapath, that is, if 'stats' represents a
3889 * packet that was sent by hand or if it represents statistics that have been
3890 * cleared out of the datapath. */
3891 static void
3892 facet_update_stats(struct ofproto *ofproto, struct facet *facet,
3893 const struct odp_flow_stats *stats)
3894 {
3895 if (stats->n_packets) {
3896 facet_update_time(ofproto, facet, stats);
3897 facet->packet_count += stats->n_packets;
3898 facet->byte_count += stats->n_bytes;
3899 netflow_flow_update_flags(&facet->nf_flow, stats->tcp_flags);
3900 }
3901 }
3902
3903 struct flow_mod {
3904 struct cls_rule cr;
3905 ovs_be64 cookie;
3906 uint16_t command;
3907 uint16_t idle_timeout;
3908 uint16_t hard_timeout;
3909 uint32_t buffer_id;
3910 uint16_t out_port;
3911 uint16_t flags;
3912 union ofp_action *actions;
3913 size_t n_actions;
3914 };
3915
3916 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
3917 * in which no matching flow already exists in the flow table.
3918 *
3919 * Adds the flow specified by 'ofm', which is followed by 'n_actions'
3920 * ofp_actions, to ofconn->ofproto's flow table. Returns 0 on success or an
3921 * OpenFlow error code as encoded by ofp_mkerr() on failure.
3922 *
3923 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3924 * if any. */
3925 static int
3926 add_flow(struct ofconn *ofconn, struct flow_mod *fm)
3927 {
3928 struct ofproto *p = ofconn->ofproto;
3929 struct ofpbuf *packet;
3930 struct rule *rule;
3931 uint16_t in_port;
3932 int error;
3933
3934 if (fm->flags & OFPFF_CHECK_OVERLAP
3935 && classifier_rule_overlaps(&p->cls, &fm->cr)) {
3936 return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_OVERLAP);
3937 }
3938
3939 error = 0;
3940 if (fm->buffer_id != UINT32_MAX) {
3941 error = pktbuf_retrieve(ofconn->pktbuf, fm->buffer_id,
3942 &packet, &in_port);
3943 } else {
3944 packet = NULL;
3945 in_port = UINT16_MAX;
3946 }
3947
3948 rule = rule_create(&fm->cr, fm->actions, fm->n_actions,
3949 fm->idle_timeout, fm->hard_timeout, fm->cookie,
3950 fm->flags & OFPFF_SEND_FLOW_REM);
3951 rule_insert(p, rule);
3952 if (packet) {
3953 rule_execute(p, rule, in_port, packet);
3954 }
3955 return error;
3956 }
3957
3958 static struct rule *
3959 find_flow_strict(struct ofproto *p, const struct flow_mod *fm)
3960 {
3961 return rule_from_cls_rule(classifier_find_rule_exactly(&p->cls, &fm->cr));
3962 }
3963
3964 static int
3965 send_buffered_packet(struct ofconn *ofconn,
3966 struct rule *rule, uint32_t buffer_id)
3967 {
3968 struct ofpbuf *packet;
3969 uint16_t in_port;
3970 int error;
3971
3972 if (buffer_id == UINT32_MAX) {
3973 return 0;
3974 }
3975
3976 error = pktbuf_retrieve(ofconn->pktbuf, buffer_id, &packet, &in_port);
3977 if (error) {
3978 return error;
3979 }
3980
3981 rule_execute(ofconn->ofproto, rule, in_port, packet);
3982
3983 return 0;
3984 }
3985 \f
3986 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
3987
3988 struct modify_flows_cbdata {
3989 struct ofproto *ofproto;
3990 const struct flow_mod *fm;
3991 struct rule *match;
3992 };
3993
3994 static int modify_flow(struct ofproto *, const struct flow_mod *,
3995 struct rule *);
3996
3997 /* Implements OFPFC_MODIFY. Returns 0 on success or an OpenFlow error code as
3998 * encoded by ofp_mkerr() on failure.
3999 *
4000 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
4001 * if any. */
4002 static int
4003 modify_flows_loose(struct ofconn *ofconn, struct flow_mod *fm)
4004 {
4005 struct ofproto *p = ofconn->ofproto;
4006 struct rule *match = NULL;
4007 struct cls_cursor cursor;
4008 struct rule *rule;
4009
4010 cls_cursor_init(&cursor, &p->cls, &fm->cr);
4011 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4012 if (!rule_is_hidden(rule)) {
4013 match = rule;
4014 modify_flow(p, fm, rule);
4015 }
4016 }
4017
4018 if (match) {
4019 /* This credits the packet to whichever flow happened to match last.
4020 * That's weird. Maybe we should do a lookup for the flow that
4021 * actually matches the packet? Who knows. */
4022 send_buffered_packet(ofconn, match, fm->buffer_id);
4023 return 0;
4024 } else {
4025 return add_flow(ofconn, fm);
4026 }
4027 }
4028
4029 /* Implements OFPFC_MODIFY_STRICT. Returns 0 on success or an OpenFlow error
4030 * code as encoded by ofp_mkerr() on failure.
4031 *
4032 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
4033 * if any. */
4034 static int
4035 modify_flow_strict(struct ofconn *ofconn, struct flow_mod *fm)
4036 {
4037 struct ofproto *p = ofconn->ofproto;
4038 struct rule *rule = find_flow_strict(p, fm);
4039 if (rule && !rule_is_hidden(rule)) {
4040 modify_flow(p, fm, rule);
4041 return send_buffered_packet(ofconn, rule, fm->buffer_id);
4042 } else {
4043 return add_flow(ofconn, fm);
4044 }
4045 }
4046
4047 /* Implements core of OFPFC_MODIFY and OFPFC_MODIFY_STRICT where 'rule' has
4048 * been identified as a flow in 'p''s flow table to be modified, by changing
4049 * the rule's actions to match those in 'ofm' (which is followed by 'n_actions'
4050 * ofp_action[] structures). */
4051 static int
4052 modify_flow(struct ofproto *p, const struct flow_mod *fm, struct rule *rule)
4053 {
4054 size_t actions_len = fm->n_actions * sizeof *rule->actions;
4055
4056 rule->flow_cookie = fm->cookie;
4057
4058 /* If the actions are the same, do nothing. */
4059 if (fm->n_actions == rule->n_actions
4060 && (!fm->n_actions
4061 || !memcmp(fm->actions, rule->actions, actions_len))) {
4062 return 0;
4063 }
4064
4065 /* Replace actions. */
4066 free(rule->actions);
4067 rule->actions = fm->n_actions ? xmemdup(fm->actions, actions_len) : NULL;
4068 rule->n_actions = fm->n_actions;
4069
4070 p->need_revalidate = true;
4071
4072 return 0;
4073 }
4074 \f
4075 /* OFPFC_DELETE implementation. */
4076
4077 static void delete_flow(struct ofproto *, struct rule *, ovs_be16 out_port);
4078
4079 /* Implements OFPFC_DELETE. */
4080 static void
4081 delete_flows_loose(struct ofproto *p, const struct flow_mod *fm)
4082 {
4083 struct rule *rule, *next_rule;
4084 struct cls_cursor cursor;
4085
4086 cls_cursor_init(&cursor, &p->cls, &fm->cr);
4087 CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
4088 delete_flow(p, rule, htons(fm->out_port));
4089 }
4090 }
4091
4092 /* Implements OFPFC_DELETE_STRICT. */
4093 static void
4094 delete_flow_strict(struct ofproto *p, struct flow_mod *fm)
4095 {
4096 struct rule *rule = find_flow_strict(p, fm);
4097 if (rule) {
4098 delete_flow(p, rule, htons(fm->out_port));
4099 }
4100 }
4101
4102 /* Implements core of OFPFC_DELETE and OFPFC_DELETE_STRICT where 'rule' has
4103 * been identified as a flow to delete from 'p''s flow table, by deleting the
4104 * flow and sending out a OFPT_FLOW_REMOVED message to any interested
4105 * controller.
4106 *
4107 * Will not delete 'rule' if it is hidden. Will delete 'rule' only if
4108 * 'out_port' is htons(OFPP_NONE) or if 'rule' actually outputs to the
4109 * specified 'out_port'. */
4110 static void
4111 delete_flow(struct ofproto *p, struct rule *rule, ovs_be16 out_port)
4112 {
4113 if (rule_is_hidden(rule)) {
4114 return;
4115 }
4116
4117 if (out_port != htons(OFPP_NONE) && !rule_has_out_port(rule, out_port)) {
4118 return;
4119 }
4120
4121 rule_send_removed(p, rule, OFPRR_DELETE);
4122 rule_remove(p, rule);
4123 }
4124 \f
4125 static int
4126 flow_mod_core(struct ofconn *ofconn, struct flow_mod *fm)
4127 {
4128 struct ofproto *p = ofconn->ofproto;
4129 int error;
4130
4131 error = reject_slave_controller(ofconn, "flow_mod");
4132 if (error) {
4133 return error;
4134 }
4135
4136 error = validate_actions(fm->actions, fm->n_actions,
4137 &fm->cr.flow, p->max_ports);
4138 if (error) {
4139 return error;
4140 }
4141
4142 /* We do not support the emergency flow cache. It will hopefully
4143 * get dropped from OpenFlow in the near future. */
4144 if (fm->flags & OFPFF_EMERG) {
4145 /* There isn't a good fit for an error code, so just state that the
4146 * flow table is full. */
4147 return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_ALL_TABLES_FULL);
4148 }
4149
4150 switch (fm->command) {
4151 case OFPFC_ADD:
4152 return add_flow(ofconn, fm);
4153
4154 case OFPFC_MODIFY:
4155 return modify_flows_loose(ofconn, fm);
4156
4157 case OFPFC_MODIFY_STRICT:
4158 return modify_flow_strict(ofconn, fm);
4159
4160 case OFPFC_DELETE:
4161 delete_flows_loose(p, fm);
4162 return 0;
4163
4164 case OFPFC_DELETE_STRICT:
4165 delete_flow_strict(p, fm);
4166 return 0;
4167
4168 default:
4169 return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_BAD_COMMAND);
4170 }
4171 }
4172
4173 static int
4174 handle_ofpt_flow_mod(struct ofconn *ofconn, struct ofp_header *oh)
4175 {
4176 struct ofp_match orig_match;
4177 struct ofp_flow_mod *ofm;
4178 struct flow_mod fm;
4179 struct ofpbuf b;
4180 int error;
4181
4182 b.data = oh;
4183 b.size = ntohs(oh->length);
4184
4185 /* Dissect the message. */
4186 ofm = ofpbuf_try_pull(&b, sizeof *ofm);
4187 if (!ofm) {
4188 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
4189 }
4190 error = ofputil_pull_actions(&b, b.size, &fm.actions, &fm.n_actions);
4191 if (error) {
4192 return error;
4193 }
4194
4195 /* Normalize ofm->match. If normalization actually changes anything, then
4196 * log the differences. */
4197 ofm->match.pad1[0] = ofm->match.pad2[0] = 0;
4198 orig_match = ofm->match;
4199 normalize_match(&ofm->match);
4200 if (memcmp(&ofm->match, &orig_match, sizeof orig_match)) {
4201 static struct vlog_rate_limit normal_rl = VLOG_RATE_LIMIT_INIT(1, 1);
4202 if (!VLOG_DROP_INFO(&normal_rl)) {
4203 char *old = ofp_match_to_literal_string(&orig_match);
4204 char *new = ofp_match_to_literal_string(&ofm->match);
4205 VLOG_INFO("%s: normalization changed ofp_match, details:",
4206 rconn_get_name(ofconn->rconn));
4207 VLOG_INFO(" pre: %s", old);
4208 VLOG_INFO("post: %s", new);
4209 free(old);
4210 free(new);
4211 }
4212 }
4213
4214 /* Translate the message. */
4215 ofputil_cls_rule_from_match(&ofm->match, ntohs(ofm->priority),
4216 ofconn->flow_format, ofm->cookie, &fm.cr);
4217 fm.cookie = ofm->cookie;
4218 fm.command = ntohs(ofm->command);
4219 fm.idle_timeout = ntohs(ofm->idle_timeout);
4220 fm.hard_timeout = ntohs(ofm->hard_timeout);
4221 fm.buffer_id = ntohl(ofm->buffer_id);
4222 fm.out_port = ntohs(ofm->out_port);
4223 fm.flags = ntohs(ofm->flags);
4224
4225 /* Execute the command. */
4226 return flow_mod_core(ofconn, &fm);
4227 }
4228
4229 static int
4230 handle_nxt_flow_mod(struct ofconn *ofconn, struct ofp_header *oh)
4231 {
4232 struct nx_flow_mod *nfm;
4233 struct flow_mod fm;
4234 struct ofpbuf b;
4235 int error;
4236
4237 b.data = oh;
4238 b.size = ntohs(oh->length);
4239
4240 /* Dissect the message. */
4241 nfm = ofpbuf_try_pull(&b, sizeof *nfm);
4242 if (!nfm) {
4243 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
4244 }
4245 error = nx_pull_match(&b, ntohs(nfm->match_len), ntohs(nfm->priority),
4246 &fm.cr);
4247 if (error) {
4248 return error;
4249 }
4250 error = ofputil_pull_actions(&b, b.size, &fm.actions, &fm.n_actions);
4251 if (error) {
4252 return error;
4253 }
4254
4255 /* Translate the message. */
4256 fm.cookie = nfm->cookie;
4257 fm.command = ntohs(nfm->command);
4258 fm.idle_timeout = ntohs(nfm->idle_timeout);
4259 fm.hard_timeout = ntohs(nfm->hard_timeout);
4260 fm.buffer_id = ntohl(nfm->buffer_id);
4261 fm.out_port = ntohs(nfm->out_port);
4262 fm.flags = ntohs(nfm->flags);
4263
4264 /* Execute the command. */
4265 return flow_mod_core(ofconn, &fm);
4266 }
4267
4268 static int
4269 handle_tun_id_from_cookie(struct ofconn *ofconn, struct nxt_tun_id_cookie *msg)
4270 {
4271 int error;
4272
4273 error = check_ofp_message(&msg->header, OFPT_VENDOR, sizeof *msg);
4274 if (error) {
4275 return error;
4276 }
4277
4278 ofconn->flow_format = msg->set ? NXFF_TUN_ID_FROM_COOKIE : NXFF_OPENFLOW10;
4279 return 0;
4280 }
4281
4282 static int
4283 handle_role_request(struct ofconn *ofconn, struct nicira_header *msg)
4284 {
4285 struct nx_role_request *nrr;
4286 struct nx_role_request *reply;
4287 struct ofpbuf *buf;
4288 uint32_t role;
4289
4290 if (ntohs(msg->header.length) != sizeof *nrr) {
4291 VLOG_WARN_RL(&rl, "received role request of length %u (expected %zu)",
4292 ntohs(msg->header.length), sizeof *nrr);
4293 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
4294 }
4295 nrr = (struct nx_role_request *) msg;
4296
4297 if (ofconn->type != OFCONN_PRIMARY) {
4298 VLOG_WARN_RL(&rl, "ignoring role request on non-controller "
4299 "connection");
4300 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
4301 }
4302
4303 role = ntohl(nrr->role);
4304 if (role != NX_ROLE_OTHER && role != NX_ROLE_MASTER
4305 && role != NX_ROLE_SLAVE) {
4306 VLOG_WARN_RL(&rl, "received request for unknown role %"PRIu32, role);
4307
4308 /* There's no good error code for this. */
4309 return ofp_mkerr(OFPET_BAD_REQUEST, -1);
4310 }
4311
4312 if (role == NX_ROLE_MASTER) {
4313 struct ofconn *other;
4314
4315 HMAP_FOR_EACH (other, hmap_node, &ofconn->ofproto->controllers) {
4316 if (other->role == NX_ROLE_MASTER) {
4317 other->role = NX_ROLE_SLAVE;
4318 }
4319 }
4320 }
4321 ofconn->role = role;
4322
4323 reply = make_nxmsg_xid(sizeof *reply, NXT_ROLE_REPLY, msg->header.xid,
4324 &buf);
4325 reply->role = htonl(role);
4326 queue_tx(buf, ofconn, ofconn->reply_counter);
4327
4328 return 0;
4329 }
4330
4331 static int
4332 handle_nxt_set_flow_format(struct ofconn *ofconn,
4333 struct nxt_set_flow_format *msg)
4334 {
4335 uint32_t format;
4336 int error;
4337
4338 error = check_ofp_message(&msg->header, OFPT_VENDOR, sizeof *msg);
4339 if (error) {
4340 return error;
4341 }
4342
4343 format = ntohl(msg->format);
4344 if (format == NXFF_OPENFLOW10
4345 || format == NXFF_TUN_ID_FROM_COOKIE
4346 || format == NXFF_NXM) {
4347 ofconn->flow_format = format;
4348 return 0;
4349 } else {
4350 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
4351 }
4352 }
4353
4354 static int
4355 handle_vendor(struct ofconn *ofconn, void *msg)
4356 {
4357 struct ofproto *p = ofconn->ofproto;
4358 struct ofp_vendor_header *ovh = msg;
4359 struct nicira_header *nh;
4360
4361 if (ntohs(ovh->header.length) < sizeof(struct ofp_vendor_header)) {
4362 VLOG_WARN_RL(&rl, "received vendor message of length %u "
4363 "(expected at least %zu)",
4364 ntohs(ovh->header.length), sizeof(struct ofp_vendor_header));
4365 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
4366 }
4367 if (ovh->vendor != htonl(NX_VENDOR_ID)) {
4368 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_VENDOR);
4369 }
4370 if (ntohs(ovh->header.length) < sizeof(struct nicira_header)) {
4371 VLOG_WARN_RL(&rl, "received Nicira vendor message of length %u "
4372 "(expected at least %zu)",
4373 ntohs(ovh->header.length), sizeof(struct nicira_header));
4374 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
4375 }
4376
4377 nh = msg;
4378 switch (ntohl(nh->subtype)) {
4379 case NXT_STATUS_REQUEST:
4380 return switch_status_handle_request(p->switch_status, ofconn->rconn,
4381 msg);
4382
4383 case NXT_TUN_ID_FROM_COOKIE:
4384 return handle_tun_id_from_cookie(ofconn, msg);
4385
4386 case NXT_ROLE_REQUEST:
4387 return handle_role_request(ofconn, msg);
4388
4389 case NXT_SET_FLOW_FORMAT:
4390 return handle_nxt_set_flow_format(ofconn, msg);
4391
4392 case NXT_FLOW_MOD:
4393 return handle_nxt_flow_mod(ofconn, &ovh->header);
4394 }
4395
4396 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE);
4397 }
4398
4399 static int
4400 handle_barrier_request(struct ofconn *ofconn, struct ofp_header *oh)
4401 {
4402 struct ofp_header *ob;
4403 struct ofpbuf *buf;
4404
4405 /* Currently, everything executes synchronously, so we can just
4406 * immediately send the barrier reply. */
4407 ob = make_openflow_xid(sizeof *ob, OFPT_BARRIER_REPLY, oh->xid, &buf);
4408 queue_tx(buf, ofconn, ofconn->reply_counter);
4409 return 0;
4410 }
4411
4412 static void
4413 handle_openflow(struct ofconn *ofconn, struct ofpbuf *ofp_msg)
4414 {
4415 struct ofp_header *oh = ofp_msg->data;
4416 int error;
4417
4418 COVERAGE_INC(ofproto_recv_openflow);
4419 switch (oh->type) {
4420 case OFPT_ECHO_REQUEST:
4421 error = handle_echo_request(ofconn, oh);
4422 break;
4423
4424 case OFPT_ECHO_REPLY:
4425 error = 0;
4426 break;
4427
4428 case OFPT_FEATURES_REQUEST:
4429 error = handle_features_request(ofconn, oh);
4430 break;
4431
4432 case OFPT_GET_CONFIG_REQUEST:
4433 error = handle_get_config_request(ofconn, oh);
4434 break;
4435
4436 case OFPT_SET_CONFIG:
4437 error = handle_set_config(ofconn, ofp_msg->data);
4438 break;
4439
4440 case OFPT_PACKET_OUT:
4441 error = handle_packet_out(ofconn, ofp_msg->data);
4442 break;
4443
4444 case OFPT_PORT_MOD:
4445 error = handle_port_mod(ofconn, oh);
4446 break;
4447
4448 case OFPT_FLOW_MOD:
4449 error = handle_ofpt_flow_mod(ofconn, ofp_msg->data);
4450 break;
4451
4452 case OFPT_STATS_REQUEST:
4453 error = handle_stats_request(ofconn, oh);
4454 break;
4455
4456 case OFPT_VENDOR:
4457 error = handle_vendor(ofconn, ofp_msg->data);
4458 break;
4459
4460 case OFPT_BARRIER_REQUEST:
4461 error = handle_barrier_request(ofconn, oh);
4462 break;
4463
4464 default:
4465 if (VLOG_IS_WARN_ENABLED()) {
4466 char *s = ofp_to_string(oh, ntohs(oh->length), 2);
4467 VLOG_DBG_RL(&rl, "OpenFlow message ignored: %s", s);
4468 free(s);
4469 }
4470 error = ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
4471 break;
4472 }
4473
4474 if (error) {
4475 send_error_oh(ofconn, ofp_msg->data, error);
4476 }
4477 }
4478 \f
4479 static void
4480 handle_odp_miss_msg(struct ofproto *p, struct ofpbuf *packet)
4481 {
4482 struct odp_msg *msg = packet->data;
4483 struct ofpbuf payload;
4484 struct facet *facet;
4485 struct flow flow;
4486
4487 payload.data = msg + 1;
4488 payload.size = msg->length - sizeof *msg;
4489 flow_extract(&payload, msg->arg, msg->port, &flow);
4490
4491 packet->l2 = payload.l2;
4492 packet->l3 = payload.l3;
4493 packet->l4 = payload.l4;
4494 packet->l7 = payload.l7;
4495
4496 /* Check with in-band control to see if this packet should be sent
4497 * to the local port regardless of the flow table. */
4498 if (in_band_msg_in_hook(p->in_band, &flow, &payload)) {
4499 union odp_action action;
4500
4501 memset(&action, 0, sizeof(action));
4502 action.output.type = ODPAT_OUTPUT;
4503 action.output.port = ODPP_LOCAL;
4504 dpif_execute(p->dpif, &action, 1, &payload);
4505 }
4506
4507 facet = facet_lookup_valid(p, &flow);
4508 if (!facet) {
4509 struct rule *rule = rule_lookup(p, &flow);
4510 if (!rule) {
4511 /* Don't send a packet-in if OFPPC_NO_PACKET_IN asserted. */
4512 struct ofport *port = get_port(p, msg->port);
4513 if (port) {
4514 if (port->opp.config & OFPPC_NO_PACKET_IN) {
4515 COVERAGE_INC(ofproto_no_packet_in);
4516 /* XXX install 'drop' flow entry */
4517 ofpbuf_delete(packet);
4518 return;
4519 }
4520 } else {
4521 VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16,
4522 msg->port);
4523 }
4524
4525 COVERAGE_INC(ofproto_packet_in);
4526 send_packet_in(p, packet);
4527 return;
4528 }
4529
4530 facet = facet_create(p, rule, &flow, packet);
4531 } else if (!facet->may_install) {
4532 /* The facet is not installable, that is, we need to process every
4533 * packet, so process the current packet's actions into 'facet'. */
4534 facet_make_actions(p, facet, packet);
4535 }
4536
4537 if (facet->rule->cr.priority == FAIL_OPEN_PRIORITY) {
4538 /*
4539 * Extra-special case for fail-open mode.
4540 *
4541 * We are in fail-open mode and the packet matched the fail-open rule,
4542 * but we are connected to a controller too. We should send the packet
4543 * up to the controller in the hope that it will try to set up a flow
4544 * and thereby allow us to exit fail-open.
4545 *
4546 * See the top-level comment in fail-open.c for more information.
4547 */
4548 send_packet_in(p, ofpbuf_clone_with_headroom(packet,
4549 DPIF_RECV_MSG_PADDING));
4550 }
4551
4552 ofpbuf_pull(packet, sizeof *msg);
4553 facet_execute(p, facet, packet);
4554 facet_install(p, facet, false);
4555 }
4556
4557 static void
4558 handle_odp_msg(struct ofproto *p, struct ofpbuf *packet)
4559 {
4560 struct odp_msg *msg = packet->data;
4561
4562 switch (msg->type) {
4563 case _ODPL_ACTION_NR:
4564 COVERAGE_INC(ofproto_ctlr_action);
4565 send_packet_in(p, packet);
4566 break;
4567
4568 case _ODPL_SFLOW_NR:
4569 if (p->sflow) {
4570 ofproto_sflow_received(p->sflow, msg);
4571 }
4572 ofpbuf_delete(packet);
4573 break;
4574
4575 case _ODPL_MISS_NR:
4576 handle_odp_miss_msg(p, packet);
4577 break;
4578
4579 default:
4580 VLOG_WARN_RL(&rl, "received ODP message of unexpected type %"PRIu32,
4581 msg->type);
4582 break;
4583 }
4584 }
4585 \f
4586 /* Flow expiration. */
4587
4588 static int ofproto_dp_max_idle(const struct ofproto *);
4589 static void ofproto_update_used(struct ofproto *);
4590 static void rule_expire(struct ofproto *, struct rule *);
4591 static void ofproto_expire_facets(struct ofproto *, int dp_max_idle);
4592
4593 /* This function is called periodically by ofproto_run(). Its job is to
4594 * collect updates for the flows that have been installed into the datapath,
4595 * most importantly when they last were used, and then use that information to
4596 * expire flows that have not been used recently.
4597 *
4598 * Returns the number of milliseconds after which it should be called again. */
4599 static int
4600 ofproto_expire(struct ofproto *ofproto)
4601 {
4602 struct rule *rule, *next_rule;
4603 struct cls_cursor cursor;
4604 int dp_max_idle;
4605
4606 /* Update 'used' for each flow in the datapath. */
4607 ofproto_update_used(ofproto);
4608
4609 /* Expire facets that have been idle too long. */
4610 dp_max_idle = ofproto_dp_max_idle(ofproto);
4611 ofproto_expire_facets(ofproto, dp_max_idle);
4612
4613 /* Expire OpenFlow flows whose idle_timeout or hard_timeout has passed. */
4614 cls_cursor_init(&cursor, &ofproto->cls, NULL);
4615 CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
4616 rule_expire(ofproto, rule);
4617 }
4618
4619 /* Let the hook know that we're at a stable point: all outstanding data
4620 * in existing flows has been accounted to the account_cb. Thus, the
4621 * hook can now reasonably do operations that depend on having accurate
4622 * flow volume accounting (currently, that's just bond rebalancing). */
4623 if (ofproto->ofhooks->account_checkpoint_cb) {
4624 ofproto->ofhooks->account_checkpoint_cb(ofproto->aux);
4625 }
4626
4627 return MIN(dp_max_idle, 1000);
4628 }
4629
4630 /* Update 'used' member of installed facets. */
4631 static void
4632 ofproto_update_used(struct ofproto *p)
4633 {
4634 struct odp_flow *flows;
4635 size_t n_flows;
4636 size_t i;
4637 int error;
4638
4639 error = dpif_flow_list_all(p->dpif, &flows, &n_flows);
4640 if (error) {
4641 return;
4642 }
4643
4644 for (i = 0; i < n_flows; i++) {
4645 struct odp_flow *f = &flows[i];
4646 struct facet *facet;
4647 struct flow flow;
4648
4649 odp_flow_key_to_flow(&f->key, &flow);
4650 facet = facet_find(p, &flow);
4651
4652 if (facet && facet->installed) {
4653 facet_update_time(p, facet, &f->stats);
4654 facet_account(p, facet, f->stats.n_bytes);
4655 } else {
4656 /* There's a flow in the datapath that we know nothing about.
4657 * Delete it. */
4658 COVERAGE_INC(ofproto_unexpected_rule);
4659 dpif_flow_del(p->dpif, f);
4660 }
4661
4662 }
4663 free(flows);
4664 }
4665
4666 /* Calculates and returns the number of milliseconds of idle time after which
4667 * facets should expire from the datapath and we should fold their statistics
4668 * into their parent rules in userspace. */
4669 static int
4670 ofproto_dp_max_idle(const struct ofproto *ofproto)
4671 {
4672 /*
4673 * Idle time histogram.
4674 *
4675 * Most of the time a switch has a relatively small number of facets. When
4676 * this is the case we might as well keep statistics for all of them in
4677 * userspace and to cache them in the kernel datapath for performance as
4678 * well.
4679 *
4680 * As the number of facets increases, the memory required to maintain
4681 * statistics about them in userspace and in the kernel becomes
4682 * significant. However, with a large number of facets it is likely that
4683 * only a few of them are "heavy hitters" that consume a large amount of
4684 * bandwidth. At this point, only heavy hitters are worth caching in the
4685 * kernel and maintaining in userspaces; other facets we can discard.
4686 *
4687 * The technique used to compute the idle time is to build a histogram with
4688 * N_BUCKETS buckets whose width is BUCKET_WIDTH msecs each. Each facet
4689 * that is installed in the kernel gets dropped in the appropriate bucket.
4690 * After the histogram has been built, we compute the cutoff so that only
4691 * the most-recently-used 1% of facets (but at least 1000 flows) are kept
4692 * cached. At least the most-recently-used bucket of facets is kept, so
4693 * actually an arbitrary number of facets can be kept in any given
4694 * expiration run (though the next run will delete most of those unless
4695 * they receive additional data).
4696 *
4697 * This requires a second pass through the facets, in addition to the pass
4698 * made by ofproto_update_used(), because the former function never looks
4699 * at uninstallable facets.
4700 */
4701 enum { BUCKET_WIDTH = ROUND_UP(100, TIME_UPDATE_INTERVAL) };
4702 enum { N_BUCKETS = 5000 / BUCKET_WIDTH };
4703 int buckets[N_BUCKETS] = { 0 };
4704 struct facet *facet;
4705 int total, bucket;
4706 long long int now;
4707 int i;
4708
4709 total = hmap_count(&ofproto->facets);
4710 if (total <= 1000) {
4711 return N_BUCKETS * BUCKET_WIDTH;
4712 }
4713
4714 /* Build histogram. */
4715 now = time_msec();
4716 HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
4717 long long int idle = now - facet->used;
4718 int bucket = (idle <= 0 ? 0
4719 : idle >= BUCKET_WIDTH * N_BUCKETS ? N_BUCKETS - 1
4720 : (unsigned int) idle / BUCKET_WIDTH);
4721 buckets[bucket]++;
4722 }
4723
4724 /* Find the first bucket whose flows should be expired. */
4725 for (bucket = 0; bucket < N_BUCKETS; bucket++) {
4726 if (buckets[bucket]) {
4727 int subtotal = 0;
4728 do {
4729 subtotal += buckets[bucket++];
4730 } while (bucket < N_BUCKETS && subtotal < MAX(1000, total / 100));
4731 break;
4732 }
4733 }
4734
4735 if (VLOG_IS_DBG_ENABLED()) {
4736 struct ds s;
4737
4738 ds_init(&s);
4739 ds_put_cstr(&s, "keep");
4740 for (i = 0; i < N_BUCKETS; i++) {
4741 if (i == bucket) {
4742 ds_put_cstr(&s, ", drop");
4743 }
4744 if (buckets[i]) {
4745 ds_put_format(&s, " %d:%d", i * BUCKET_WIDTH, buckets[i]);
4746 }
4747 }
4748 VLOG_INFO("%s: %s (msec:count)",
4749 dpif_name(ofproto->dpif), ds_cstr(&s));
4750 ds_destroy(&s);
4751 }
4752
4753 return bucket * BUCKET_WIDTH;
4754 }
4755
4756 static void
4757 facet_active_timeout(struct ofproto *ofproto, struct facet *facet)
4758 {
4759 if (ofproto->netflow && !facet_is_controller_flow(facet) &&
4760 netflow_active_timeout_expired(ofproto->netflow, &facet->nf_flow)) {
4761 struct ofexpired expired;
4762 struct odp_flow odp_flow;
4763
4764 /* Get updated flow stats.
4765 *
4766 * XXX We could avoid this call entirely if (1) ofproto_update_used()
4767 * updated TCP flags and (2) the dpif_flow_list_all() in
4768 * ofproto_update_used() zeroed TCP flags. */
4769 memset(&odp_flow, 0, sizeof odp_flow);
4770 if (facet->installed) {
4771 odp_flow_key_from_flow(&odp_flow.key, &facet->flow);
4772 odp_flow.flags = ODPFF_ZERO_TCP_FLAGS;
4773 dpif_flow_get(ofproto->dpif, &odp_flow);
4774
4775 if (odp_flow.stats.n_packets) {
4776 facet_update_time(ofproto, facet, &odp_flow.stats);
4777 netflow_flow_update_flags(&facet->nf_flow,
4778 odp_flow.stats.tcp_flags);
4779 }
4780 }
4781
4782 expired.flow = facet->flow;
4783 expired.packet_count = facet->packet_count +
4784 odp_flow.stats.n_packets;
4785 expired.byte_count = facet->byte_count + odp_flow.stats.n_bytes;
4786 expired.used = facet->used;
4787
4788 netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
4789 }
4790 }
4791
4792 static void
4793 ofproto_expire_facets(struct ofproto *ofproto, int dp_max_idle)
4794 {
4795 long long int cutoff = time_msec() - dp_max_idle;
4796 struct facet *facet, *next_facet;
4797
4798 HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
4799 facet_active_timeout(ofproto, facet);
4800 if (facet->used < cutoff) {
4801 facet_remove(ofproto, facet);
4802 }
4803 }
4804 }
4805
4806 /* If 'rule' is an OpenFlow rule, that has expired according to OpenFlow rules,
4807 * then delete it entirely. */
4808 static void
4809 rule_expire(struct ofproto *ofproto, struct rule *rule)
4810 {
4811 struct facet *facet, *next_facet;
4812 long long int now;
4813 uint8_t reason;
4814
4815 /* Has 'rule' expired? */
4816 now = time_msec();
4817 if (rule->hard_timeout
4818 && now > rule->created + rule->hard_timeout * 1000) {
4819 reason = OFPRR_HARD_TIMEOUT;
4820 } else if (rule->idle_timeout && list_is_empty(&rule->facets)
4821 && now >rule->used + rule->idle_timeout * 1000) {
4822 reason = OFPRR_IDLE_TIMEOUT;
4823 } else {
4824 return;
4825 }
4826
4827 COVERAGE_INC(ofproto_expired);
4828
4829 /* Update stats. (This is a no-op if the rule expired due to an idle
4830 * timeout, because that only happens when the rule has no facets left.) */
4831 LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
4832 facet_remove(ofproto, facet);
4833 }
4834
4835 /* Get rid of the rule. */
4836 if (!rule_is_hidden(rule)) {
4837 rule_send_removed(ofproto, rule, reason);
4838 }
4839 rule_remove(ofproto, rule);
4840 }
4841 \f
4842 static struct ofpbuf *
4843 compose_ofp_flow_removed(struct ofconn *ofconn, const struct rule *rule,
4844 uint8_t reason)
4845 {
4846 struct ofp_flow_removed *ofr;
4847 struct ofpbuf *buf;
4848
4849 ofr = make_openflow(sizeof *ofr, OFPT_FLOW_REMOVED, &buf);
4850 ofputil_cls_rule_to_match(&rule->cr, ofconn->flow_format, &ofr->match);
4851 ofr->cookie = rule->flow_cookie;
4852 ofr->priority = htons(rule->cr.priority);
4853 ofr->reason = reason;
4854 calc_flow_duration(rule->created, &ofr->duration_sec, &ofr->duration_nsec);
4855 ofr->idle_timeout = htons(rule->idle_timeout);
4856 ofr->packet_count = htonll(rule->packet_count);
4857 ofr->byte_count = htonll(rule->byte_count);
4858
4859 return buf;
4860 }
4861
4862 static struct ofpbuf *
4863 compose_nx_flow_removed(const struct rule *rule, uint8_t reason)
4864 {
4865 struct nx_flow_removed *nfr;
4866 struct ofpbuf *buf;
4867 int match_len;
4868
4869 nfr = make_nxmsg(sizeof *nfr, NXT_FLOW_REMOVED, &buf);
4870
4871 match_len = nx_put_match(buf, &rule->cr);
4872
4873 nfr->cookie = rule->flow_cookie;
4874 nfr->priority = htons(rule->cr.priority);
4875 nfr->reason = reason;
4876 calc_flow_duration(rule->created, &nfr->duration_sec, &nfr->duration_nsec);
4877 nfr->idle_timeout = htons(rule->idle_timeout);
4878 nfr->match_len = htons(match_len);
4879 nfr->packet_count = htonll(rule->packet_count);
4880 nfr->byte_count = htonll(rule->byte_count);
4881
4882 return buf;
4883 }
4884
4885 static void
4886 rule_send_removed(struct ofproto *p, struct rule *rule, uint8_t reason)
4887 {
4888 struct ofconn *ofconn;
4889
4890 if (!rule->send_flow_removed) {
4891 return;
4892 }
4893
4894 LIST_FOR_EACH (ofconn, node, &p->all_conns) {
4895 struct ofpbuf *msg;
4896
4897 if (!rconn_is_connected(ofconn->rconn)
4898 || !ofconn_receives_async_msgs(ofconn)) {
4899 continue;
4900 }
4901
4902 msg = (ofconn->flow_format == NXFF_NXM
4903 ? compose_nx_flow_removed(rule, reason)
4904 : compose_ofp_flow_removed(ofconn, rule, reason));
4905
4906 /* Account flow expirations under ofconn->reply_counter, the counter
4907 * for replies to OpenFlow requests. That works because preventing
4908 * OpenFlow requests from being processed also prevents new flows from
4909 * being added (and expiring). (It also prevents processing OpenFlow
4910 * requests that would not add new flows, so it is imperfect.) */
4911 queue_tx(msg, ofconn, ofconn->reply_counter);
4912 }
4913 }
4914
4915 /* pinsched callback for sending 'packet' on 'ofconn'. */
4916 static void
4917 do_send_packet_in(struct ofpbuf *packet, void *ofconn_)
4918 {
4919 struct ofconn *ofconn = ofconn_;
4920
4921 rconn_send_with_limit(ofconn->rconn, packet,
4922 ofconn->packet_in_counter, 100);
4923 }
4924
4925 /* Takes 'packet', which has been converted with do_convert_to_packet_in(), and
4926 * finalizes its content for sending on 'ofconn', and passes it to 'ofconn''s
4927 * packet scheduler for sending.
4928 *
4929 * 'max_len' specifies the maximum number of bytes of the packet to send on
4930 * 'ofconn' (INT_MAX specifies no limit).
4931 *
4932 * If 'clone' is true, the caller retains ownership of 'packet'. Otherwise,
4933 * ownership is transferred to this function. */
4934 static void
4935 schedule_packet_in(struct ofconn *ofconn, struct ofpbuf *packet, int max_len,
4936 bool clone)
4937 {
4938 struct ofproto *ofproto = ofconn->ofproto;
4939 struct ofp_packet_in *opi = packet->data;
4940 uint16_t in_port = ofp_port_to_odp_port(ntohs(opi->in_port));
4941 int send_len, trim_size;
4942 uint32_t buffer_id;
4943
4944 /* Get buffer. */
4945 if (opi->reason == OFPR_ACTION) {
4946 buffer_id = UINT32_MAX;
4947 } else if (ofproto->fail_open && fail_open_is_active(ofproto->fail_open)) {
4948 buffer_id = pktbuf_get_null();
4949 } else if (!ofconn->pktbuf) {
4950 buffer_id = UINT32_MAX;
4951 } else {
4952 struct ofpbuf payload;
4953 payload.data = opi->data;
4954 payload.size = packet->size - offsetof(struct ofp_packet_in, data);
4955 buffer_id = pktbuf_save(ofconn->pktbuf, &payload, in_port);
4956 }
4957
4958 /* Figure out how much of the packet to send. */
4959 send_len = ntohs(opi->total_len);
4960 if (buffer_id != UINT32_MAX) {
4961 send_len = MIN(send_len, ofconn->miss_send_len);
4962 }
4963 send_len = MIN(send_len, max_len);
4964
4965 /* Adjust packet length and clone if necessary. */
4966 trim_size = offsetof(struct ofp_packet_in, data) + send_len;
4967 if (clone) {
4968 packet = ofpbuf_clone_data(packet->data, trim_size);
4969 opi = packet->data;
4970 } else {
4971 packet->size = trim_size;
4972 }
4973
4974 /* Update packet headers. */
4975 opi->buffer_id = htonl(buffer_id);
4976 update_openflow_length(packet);
4977
4978 /* Hand over to packet scheduler. It might immediately call into
4979 * do_send_packet_in() or it might buffer it for a while (until a later
4980 * call to pinsched_run()). */
4981 pinsched_send(ofconn->schedulers[opi->reason], in_port,
4982 packet, do_send_packet_in, ofconn);
4983 }
4984
4985 /* Replace struct odp_msg header in 'packet' by equivalent struct
4986 * ofp_packet_in. The odp_msg must have sufficient headroom to do so (e.g. as
4987 * returned by dpif_recv()).
4988 *
4989 * The conversion is not complete: the caller still needs to trim any unneeded
4990 * payload off the end of the buffer, set the length in the OpenFlow header,
4991 * and set buffer_id. Those require us to know the controller settings and so
4992 * must be done on a per-controller basis.
4993 *
4994 * Returns the maximum number of bytes of the packet that should be sent to
4995 * the controller (INT_MAX if no limit). */
4996 static int
4997 do_convert_to_packet_in(struct ofpbuf *packet)
4998 {
4999 struct odp_msg *msg = packet->data;
5000 struct ofp_packet_in *opi;
5001 uint8_t reason;
5002 uint16_t total_len;
5003 uint16_t in_port;
5004 int max_len;
5005
5006 /* Extract relevant header fields */
5007 if (msg->type == _ODPL_ACTION_NR) {
5008 reason = OFPR_ACTION;
5009 max_len = msg->arg;
5010 } else {
5011 reason = OFPR_NO_MATCH;
5012 max_len = INT_MAX;
5013 }
5014 total_len = msg->length - sizeof *msg;
5015 in_port = odp_port_to_ofp_port(msg->port);
5016
5017 /* Repurpose packet buffer by overwriting header. */
5018 ofpbuf_pull(packet, sizeof(struct odp_msg));
5019 opi = ofpbuf_push_zeros(packet, offsetof(struct ofp_packet_in, data));
5020 opi->header.version = OFP_VERSION;
5021 opi->header.type = OFPT_PACKET_IN;
5022 opi->total_len = htons(total_len);
5023 opi->in_port = htons(in_port);
5024 opi->reason = reason;
5025
5026 return max_len;
5027 }
5028
5029 /* Given 'packet' containing an odp_msg of type _ODPL_ACTION_NR or
5030 * _ODPL_MISS_NR, sends an OFPT_PACKET_IN message to each OpenFlow controller
5031 * as necessary according to their individual configurations.
5032 *
5033 * 'packet' must have sufficient headroom to convert it into a struct
5034 * ofp_packet_in (e.g. as returned by dpif_recv()).
5035 *
5036 * Takes ownership of 'packet'. */
5037 static void
5038 send_packet_in(struct ofproto *ofproto, struct ofpbuf *packet)
5039 {
5040 struct ofconn *ofconn, *prev;
5041 int max_len;
5042
5043 max_len = do_convert_to_packet_in(packet);
5044
5045 prev = NULL;
5046 LIST_FOR_EACH (ofconn, node, &ofproto->all_conns) {
5047 if (ofconn_receives_async_msgs(ofconn)) {
5048 if (prev) {
5049 schedule_packet_in(prev, packet, max_len, true);
5050 }
5051 prev = ofconn;
5052 }
5053 }
5054 if (prev) {
5055 schedule_packet_in(prev, packet, max_len, false);
5056 } else {
5057 ofpbuf_delete(packet);
5058 }
5059 }
5060
5061 static uint64_t
5062 pick_datapath_id(const struct ofproto *ofproto)
5063 {
5064 const struct ofport *port;
5065
5066 port = get_port(ofproto, ODPP_LOCAL);
5067 if (port) {
5068 uint8_t ea[ETH_ADDR_LEN];
5069 int error;
5070
5071 error = netdev_get_etheraddr(port->netdev, ea);
5072 if (!error) {
5073 return eth_addr_to_uint64(ea);
5074 }
5075 VLOG_WARN("could not get MAC address for %s (%s)",
5076 netdev_get_name(port->netdev), strerror(error));
5077 }
5078 return ofproto->fallback_dpid;
5079 }
5080
5081 static uint64_t
5082 pick_fallback_dpid(void)
5083 {
5084 uint8_t ea[ETH_ADDR_LEN];
5085 eth_addr_nicira_random(ea);
5086 return eth_addr_to_uint64(ea);
5087 }
5088 \f
5089 static bool
5090 default_normal_ofhook_cb(const struct flow *flow, const struct ofpbuf *packet,
5091 struct odp_actions *actions, tag_type *tags,
5092 uint16_t *nf_output_iface, void *ofproto_)
5093 {
5094 struct ofproto *ofproto = ofproto_;
5095 int out_port;
5096
5097 /* Drop frames for reserved multicast addresses. */
5098 if (eth_addr_is_reserved(flow->dl_dst)) {
5099 return true;
5100 }
5101
5102 /* Learn source MAC (but don't try to learn from revalidation). */
5103 if (packet != NULL) {
5104 tag_type rev_tag = mac_learning_learn(ofproto->ml, flow->dl_src,
5105 0, flow->in_port,
5106 GRAT_ARP_LOCK_NONE);
5107 if (rev_tag) {
5108 /* The log messages here could actually be useful in debugging,
5109 * so keep the rate limit relatively high. */
5110 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
5111 VLOG_DBG_RL(&rl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
5112 ETH_ADDR_ARGS(flow->dl_src), flow->in_port);
5113 ofproto_revalidate(ofproto, rev_tag);
5114 }
5115 }
5116
5117 /* Determine output port. */
5118 out_port = mac_learning_lookup_tag(ofproto->ml, flow->dl_dst, 0, tags,
5119 NULL);
5120 if (out_port < 0) {
5121 flood_packets(ofproto, flow->in_port, OFPPC_NO_FLOOD,
5122 nf_output_iface, actions);
5123 } else if (out_port != flow->in_port) {
5124 odp_actions_add(actions, ODPAT_OUTPUT)->output.port = out_port;
5125 *nf_output_iface = out_port;
5126 } else {
5127 /* Drop. */
5128 }
5129
5130 return true;
5131 }
5132
5133 static const struct ofhooks default_ofhooks = {
5134 default_normal_ofhook_cb,
5135 NULL,
5136 NULL
5137 };