1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
4 * We are making the OpenFlow specification and associated documentation
5 * (Software) available for public use and benefit with the expectation
6 * that others will use, modify and enhance the Software and contribute
7 * those enhancements back to the community. However, since we would
8 * like to make the Software available for broadest use, with as few
9 * restrictions as possible permission is hereby granted, free of
10 * charge, to any person obtaining a copy of this Software to deal in
11 * the Software under the copyrights without restriction, including
12 * without limitation the rights to use, copy, modify, merge, publish,
13 * distribute, sublicense, and/or sell copies of the Software, and to
14 * permit persons to whom the Software is furnished to do so, subject to
15 * the following conditions:
17 * The above copyright notice and this permission notice shall be
18 * included in all copies or substantial portions of the Software.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 * The name and trademarks of copyright holder(s) may NOT be used in
30 * advertising or publicity pertaining to the Software or any
31 * derivatives without specific, written prior permission.
35 #include <arpa/inet.h>
47 #include "poll-loop.h"
53 #define THIS_MODULE VLM_datapath
56 #define BRIDGE_PORT_NO_FLOOD 0x00000001
58 /* Capabilities supported by this implementation. */
59 #define OFP_SUPPORTED_CAPABILITIES ( OFPC_FLOW_STATS \
64 /* Actions supported by this implementation. */
65 #define OFP_SUPPORTED_ACTIONS ( (1 << OFPAT_OUTPUT) \
66 | (1 << OFPAT_SET_DL_VLAN) \
67 | (1 << OFPAT_SET_DL_SRC) \
68 | (1 << OFPAT_SET_DL_DST) \
69 | (1 << OFPAT_SET_NW_SRC) \
70 | (1 << OFPAT_SET_NW_DST) \
71 | (1 << OFPAT_SET_TP_SRC) \
72 | (1 << OFPAT_SET_TP_DST) )
77 struct netdev *netdev;
78 struct list node; /* Element in datapath.ports. */
79 unsigned long long int rx_count, tx_count, drop_count;
82 /* The origin of a received OpenFlow message, to enable sending a reply. */
84 struct remote *remote; /* The device that sent the message. */
85 uint32_t xid; /* The OpenFlow transaction ID. */
88 /* A connection to a controller or a management device. */
93 /* Support for reliable, multi-message replies to requests.
95 * If an incoming request needs to have a reliable reply that might
96 * require multiple messages, it can use remote_start_dump() to set up
97 * a callback that will be called as buffer space for replies. */
98 int (*cb_dump)(struct datapath *, void *aux);
99 void (*cb_done)(void *aux);
104 /* Remote connections. */
105 struct remote *controller; /* Connection to controller. */
106 struct list remotes; /* All connections (including controller). */
107 struct vconn *listen_vconn;
111 /* Unique identifier for this datapath */
114 struct sw_chain *chain; /* Forwarding rules. */
116 /* Configuration set from controller. */
118 uint16_t miss_send_len;
121 struct sw_port ports[OFPP_MAX];
122 struct list port_list; /* List of ports, for flooding. */
125 static struct remote *remote_create(struct datapath *, struct rconn *);
126 static void remote_run(struct datapath *, struct remote *);
127 static void remote_wait(struct remote *);
128 static void remote_destroy(struct remote *);
130 void dp_output_port(struct datapath *, struct buffer *,
131 int in_port, int out_port);
132 void dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp);
133 void dp_output_control(struct datapath *, struct buffer *, int in_port,
134 size_t max_len, int reason);
135 static void send_flow_expired(struct datapath *, struct sw_flow *);
136 static void send_port_status(struct sw_port *p, uint8_t status);
137 static void del_switch_port(struct sw_port *p);
138 static void execute_actions(struct datapath *, struct buffer *,
139 int in_port, const struct sw_flow_key *,
140 const struct ofp_action *, int n_actions);
141 static void modify_vlan(struct buffer *buffer, const struct sw_flow_key *key,
142 const struct ofp_action *a);
143 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
144 uint8_t nw_proto, const struct ofp_action *a);
145 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
146 uint8_t nw_proto, const struct ofp_action *a);
148 /* Buffers are identified to userspace by a 31-bit opaque ID. We divide the ID
149 * into a buffer number (low bits) and a cookie (high bits). The buffer number
150 * is an index into an array of buffers. The cookie distinguishes between
151 * different packets that have occupied a single buffer. Thus, the more
152 * buffers we have, the lower-quality the cookie... */
153 #define PKT_BUFFER_BITS 8
154 #define N_PKT_BUFFERS (1 << PKT_BUFFER_BITS)
155 #define PKT_BUFFER_MASK (N_PKT_BUFFERS - 1)
157 #define PKT_COOKIE_BITS (32 - PKT_BUFFER_BITS)
159 int run_flow_through_tables(struct datapath *, struct buffer *, int in_port);
160 void fwd_port_input(struct datapath *, struct buffer *, int in_port);
161 int fwd_control_input(struct datapath *, const struct sender *,
162 const void *, size_t);
164 uint32_t save_buffer(struct buffer *);
165 static struct buffer *retrieve_buffer(uint32_t id);
166 static void discard_buffer(uint32_t id);
168 static int port_no(struct datapath *dp, struct sw_port *p)
170 assert(p >= dp->ports && p < &dp->ports[ARRAY_SIZE(dp->ports)]);
171 return p - dp->ports;
174 /* Generates and returns a random datapath id. */
176 gen_datapath_id(void)
178 uint8_t ea[ETH_ADDR_LEN];
180 return eth_addr_to_uint64(ea);
184 dp_new(struct datapath **dp_, uint64_t dpid, struct rconn *rconn)
188 dp = calloc(1, sizeof *dp);
193 dp->last_timeout = time(0);
194 list_init(&dp->remotes);
195 dp->controller = remote_create(dp, rconn);
196 dp->listen_vconn = NULL;
197 dp->id = dpid <= UINT64_C(0xffffffffffff) ? dpid : gen_datapath_id();
198 dp->chain = chain_create();
200 VLOG_ERR("could not create chain");
205 list_init(&dp->port_list);
207 dp->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
213 dp_add_port(struct datapath *dp, const char *name)
215 struct netdev *netdev;
221 error = netdev_open(name, NETDEV_ETH_TYPE_ANY, &netdev);
225 error = netdev_set_flags(netdev, NETDEV_UP | NETDEV_PROMISC, false);
227 VLOG_ERR("Couldn't set promiscuous mode on %s device", name);
228 netdev_close(netdev);
231 if (netdev_get_in4(netdev, &in4)) {
232 VLOG_ERR("%s device has assigned IP address %s", name, inet_ntoa(in4));
234 if (netdev_get_in6(netdev, &in6)) {
235 char in6_name[INET6_ADDRSTRLEN + 1];
236 inet_ntop(AF_INET6, &in6, in6_name, sizeof in6_name);
237 VLOG_ERR("%s device has assigned IPv6 address %s", name, in6_name);
240 for (p = dp->ports; ; p++) {
241 if (p >= &dp->ports[ARRAY_SIZE(dp->ports)]) {
243 } else if (!p->netdev) {
253 list_push_back(&dp->port_list, &p->node);
255 /* Notify the ctlpath that this port has been added */
256 send_port_status(p, OFPPR_ADD);
262 dp_add_listen_vconn(struct datapath *dp, struct vconn *listen_vconn)
264 assert(!dp->listen_vconn);
265 dp->listen_vconn = listen_vconn;
269 dp_run(struct datapath *dp)
271 time_t now = time(0);
272 struct sw_port *p, *pn;
273 struct remote *r, *rn;
274 struct buffer *buffer = NULL;
276 if (now != dp->last_timeout) {
277 struct list deleted = LIST_INITIALIZER(&deleted);
278 struct sw_flow *f, *n;
280 chain_timeout(dp->chain, &deleted);
281 LIST_FOR_EACH_SAFE (f, n, struct sw_flow, node, &deleted) {
282 send_flow_expired(dp, f);
283 list_remove(&f->node);
286 dp->last_timeout = now;
288 poll_timer_wait(1000);
290 LIST_FOR_EACH_SAFE (p, pn, struct sw_port, node, &dp->port_list) {
294 /* Allocate buffer with some headroom to add headers in forwarding
295 * to the controller or adding a vlan tag, plus an extra 2 bytes to
296 * allow IP headers to be aligned on a 4-byte boundary. */
297 const int headroom = 128 + 2;
298 const int hard_header = VLAN_ETH_HEADER_LEN;
299 const int mtu = netdev_get_mtu(p->netdev);
300 buffer = buffer_new(headroom + hard_header + mtu);
301 buffer->data += headroom;
303 error = netdev_recv(p->netdev, buffer);
306 fwd_port_input(dp, buffer, port_no(dp, p));
308 } else if (error != EAGAIN) {
309 VLOG_ERR("Error receiving data from %s: %s",
310 netdev_get_name(p->netdev), strerror(error));
314 buffer_delete(buffer);
316 /* Talk to remotes. */
317 LIST_FOR_EACH_SAFE (r, rn, struct remote, node, &dp->remotes) {
320 if (dp->listen_vconn) {
322 struct vconn *new_vconn;
325 retval = vconn_accept(dp->listen_vconn, &new_vconn);
327 if (retval != EAGAIN) {
328 VLOG_WARN("accept failed (%s)", strerror(retval));
332 remote_create(dp, rconn_new_from_vconn("passive", 128, new_vconn));
338 remote_run(struct datapath *dp, struct remote *r)
344 /* Do some remote processing, but cap it at a reasonable amount so that
345 * other processing doesn't starve. */
346 for (i = 0; i < 50; i++) {
348 struct buffer *buffer;
349 struct ofp_header *oh;
351 buffer = rconn_recv(r->rconn);
356 if (buffer->size >= sizeof *oh) {
357 struct sender sender;
361 sender.xid = oh->xid;
362 fwd_control_input(dp, &sender, buffer->data, buffer->size);
364 VLOG_WARN("received too-short OpenFlow message");
366 buffer_delete(buffer);
368 if (!rconn_is_full(r->rconn)) {
369 int error = r->cb_dump(dp, r->cb_aux);
372 VLOG_WARN("dump callback error: %s", strerror(-error));
374 r->cb_done(r->cb_aux);
383 if (!rconn_is_alive(r->rconn)) {
389 remote_wait(struct remote *r)
391 rconn_run_wait(r->rconn);
392 rconn_recv_wait(r->rconn);
396 remote_destroy(struct remote *r)
399 if (r->cb_dump && r->cb_done) {
400 r->cb_done(r->cb_aux);
402 list_remove(&r->node);
403 rconn_destroy(r->rconn);
408 static struct remote *
409 remote_create(struct datapath *dp, struct rconn *rconn)
411 struct remote *remote = xmalloc(sizeof *remote);
412 list_push_back(&dp->remotes, &remote->node);
413 remote->rconn = rconn;
414 remote->cb_dump = NULL;
418 /* Starts a callback-based, reliable, possibly multi-message reply to a
419 * request made by 'remote'.
421 * 'dump' designates a function that will be called when the 'remote' send
422 * queue has an empty slot. It should compose a message and send it on
423 * 'remote'. On success, it should return 1 if it should be called again when
424 * another send queue slot opens up, 0 if its transmissions are complete, or a
425 * negative errno value on failure.
427 * 'done' designates a function to clean up any resources allocated for the
428 * dump. It must handle being called before the dump is complete (which will
429 * happen if 'remote' is closed unexpectedly).
431 * 'aux' is passed to 'dump' and 'done'. */
433 remote_start_dump(struct remote *remote,
434 int (*dump)(struct datapath *, void *),
435 void (*done)(void *),
438 assert(!remote->cb_dump);
439 remote->cb_dump = dump;
440 remote->cb_done = done;
441 remote->cb_aux = aux;
445 dp_wait(struct datapath *dp)
450 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
451 netdev_recv_wait(p->netdev);
453 LIST_FOR_EACH (r, struct remote, node, &dp->remotes) {
456 if (dp->listen_vconn) {
457 vconn_accept_wait(dp->listen_vconn);
461 /* Delete 'p' from switch. */
463 del_switch_port(struct sw_port *p)
465 send_port_status(p, OFPPR_DELETE);
466 netdev_close(p->netdev);
468 list_remove(&p->node);
472 dp_destroy(struct datapath *dp)
474 struct sw_port *p, *n;
480 LIST_FOR_EACH_SAFE (p, n, struct sw_port, node, &dp->port_list) {
483 chain_destroy(dp->chain);
487 /* Send packets out all the ports except the originating one. If the
488 * "flood" argument is set, don't send out ports with flooding disabled.
491 output_all(struct datapath *dp, struct buffer *buffer, int in_port, int flood)
497 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
498 if (port_no(dp, p) == in_port) {
501 if (flood && p->flags & BRIDGE_PORT_NO_FLOOD) {
504 if (prev_port != -1) {
505 dp_output_port(dp, buffer_clone(buffer), in_port, prev_port);
507 prev_port = port_no(dp, p);
510 dp_output_port(dp, buffer, in_port, prev_port);
512 buffer_delete(buffer);
518 output_packet(struct datapath *dp, struct buffer *buffer, int out_port)
520 if (out_port >= 0 && out_port < OFPP_MAX) {
521 struct sw_port *p = &dp->ports[out_port];
522 if (p->netdev != NULL) {
523 if (!netdev_send(p->netdev, buffer)) {
532 buffer_delete(buffer);
533 /* FIXME: ratelimit */
534 VLOG_DBG("can't forward to bad port %d\n", out_port);
537 /* Takes ownership of 'buffer' and transmits it to 'out_port' on 'dp'.
540 dp_output_port(struct datapath *dp, struct buffer *buffer,
541 int in_port, int out_port)
545 if (out_port == OFPP_FLOOD) {
546 output_all(dp, buffer, in_port, 1);
547 } else if (out_port == OFPP_ALL) {
548 output_all(dp, buffer, in_port, 0);
549 } else if (out_port == OFPP_CONTROLLER) {
550 dp_output_control(dp, buffer, in_port, 0, OFPR_ACTION);
551 } else if (out_port == OFPP_TABLE) {
552 if (run_flow_through_tables(dp, buffer, in_port)) {
553 buffer_delete(buffer);
556 output_packet(dp, buffer, out_port);
561 make_openflow_reply(size_t openflow_len, uint8_t type,
562 const struct sender *sender, struct buffer **bufferp)
564 return make_openflow_xid(openflow_len, type, sender ? sender->xid : 0,
569 send_openflow_buffer(struct datapath *dp, struct buffer *buffer,
570 const struct sender *sender)
572 struct remote *remote = sender ? sender->remote : dp->controller;
573 struct rconn *rconn = remote->rconn;
576 update_openflow_length(buffer);
577 retval = rconn_send(rconn, buffer);
579 VLOG_WARN("send to %s failed: %s",
580 rconn_get_name(rconn), strerror(retval));
581 buffer_delete(buffer);
586 /* Takes ownership of 'buffer' and transmits it to 'dp''s controller. If the
587 * packet can be saved in a buffer, then only the first max_len bytes of
588 * 'buffer' are sent; otherwise, all of 'buffer' is sent. 'reason' indicates
589 * why 'buffer' is being sent. 'max_len' sets the maximum number of bytes that
590 * the caller wants to be sent; a value of 0 indicates the entire packet should
593 dp_output_control(struct datapath *dp, struct buffer *buffer, int in_port,
594 size_t max_len, int reason)
596 struct ofp_packet_in *opi;
600 buffer_id = save_buffer(buffer);
601 total_len = buffer->size;
602 if (buffer_id != UINT32_MAX && buffer->size > max_len) {
603 buffer->size = max_len;
606 opi = buffer_push_uninit(buffer, offsetof(struct ofp_packet_in, data));
607 opi->header.version = OFP_VERSION;
608 opi->header.type = OFPT_PACKET_IN;
609 opi->header.length = htons(buffer->size);
610 opi->header.xid = htonl(0);
611 opi->buffer_id = htonl(buffer_id);
612 opi->total_len = htons(total_len);
613 opi->in_port = htons(in_port);
614 opi->reason = reason;
616 send_openflow_buffer(dp, buffer, NULL);
619 static void fill_port_desc(struct datapath *dp, struct sw_port *p,
620 struct ofp_phy_port *desc)
622 desc->port_no = htons(port_no(dp, p));
623 strncpy((char *) desc->name, netdev_get_name(p->netdev),
625 desc->name[sizeof desc->name - 1] = '\0';
626 memcpy(desc->hw_addr, netdev_get_etheraddr(p->netdev), ETH_ADDR_LEN);
627 desc->flags = htonl(p->flags);
628 desc->features = htonl(netdev_get_features(p->netdev));
629 desc->speed = htonl(netdev_get_speed(p->netdev));
633 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
635 struct buffer *buffer;
636 struct ofp_switch_features *ofr;
639 ofr = make_openflow_reply(sizeof *ofr, OFPT_FEATURES_REPLY,
641 ofr->datapath_id = htonll(dp->id);
642 ofr->n_exact = htonl(2 * TABLE_HASH_MAX_FLOWS);
643 ofr->n_compression = 0; /* Not supported */
644 ofr->n_general = htonl(TABLE_LINEAR_MAX_FLOWS);
645 ofr->buffer_mb = htonl(UINT32_MAX);
646 ofr->n_buffers = htonl(N_PKT_BUFFERS);
647 ofr->capabilities = htonl(OFP_SUPPORTED_CAPABILITIES);
648 ofr->actions = htonl(OFP_SUPPORTED_ACTIONS);
649 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
650 struct ofp_phy_port *opp = buffer_put_uninit(buffer, sizeof *opp);
651 memset(opp, 0, sizeof *opp);
652 fill_port_desc(dp, p, opp);
654 send_openflow_buffer(dp, buffer, sender);
658 dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp)
660 int port_no = ntohs(opp->port_no);
661 if (port_no < OFPP_MAX) {
662 struct sw_port *p = &dp->ports[port_no];
664 /* Make sure the port id hasn't changed since this was sent */
665 if (!p || memcmp(opp->hw_addr, netdev_get_etheraddr(p->netdev),
666 ETH_ADDR_LEN) != 0) {
669 p->flags = htonl(opp->flags);
674 send_port_status(struct sw_port *p, uint8_t status)
676 struct buffer *buffer;
677 struct ofp_port_status *ops;
678 ops = make_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, 0, &buffer);
679 ops->reason = status;
680 memset(ops->pad, 0, sizeof ops->pad);
681 fill_port_desc(p->dp, p, &ops->desc);
683 send_openflow_buffer(p->dp, buffer, NULL);
687 send_flow_expired(struct datapath *dp, struct sw_flow *flow)
689 struct buffer *buffer;
690 struct ofp_flow_expired *ofe;
691 ofe = make_openflow_xid(sizeof *ofe, OFPT_FLOW_EXPIRED, 0, &buffer);
692 flow_fill_match(&ofe->match, &flow->key);
694 memset(ofe->pad, 0, sizeof ofe->pad);
695 ofe->priority = htons(flow->priority);
697 ofe->duration = htonl(flow->timeout - flow->max_idle - flow->created);
698 ofe->packet_count = htonll(flow->packet_count);
699 ofe->byte_count = htonll(flow->byte_count);
700 send_openflow_buffer(dp, buffer, NULL);
704 dp_send_error_msg(struct datapath *dp, const struct sender *sender,
705 uint16_t type, uint16_t code, const uint8_t *data, size_t len)
707 struct buffer *buffer;
708 struct ofp_error_msg *oem;
709 oem = make_openflow_reply(sizeof(*oem)+len, OFPT_ERROR_MSG,
711 oem->type = htons(type);
712 oem->code = htons(code);
713 memcpy(oem->data, data, len);
714 send_openflow_buffer(dp, buffer, sender);
718 fill_flow_stats(struct buffer *buffer, struct sw_flow *flow,
719 int table_idx, time_t now)
721 struct ofp_flow_stats *ofs;
722 int length = sizeof *ofs + sizeof *ofs->actions * flow->n_actions;
723 ofs = buffer_put_uninit(buffer, length);
724 ofs->length = htons(length);
725 ofs->table_id = table_idx;
727 ofs->match.wildcards = htons(flow->key.wildcards);
728 ofs->match.in_port = flow->key.flow.in_port;
729 memcpy(ofs->match.dl_src, flow->key.flow.dl_src, ETH_ADDR_LEN);
730 memcpy(ofs->match.dl_dst, flow->key.flow.dl_dst, ETH_ADDR_LEN);
731 ofs->match.dl_vlan = flow->key.flow.dl_vlan;
732 ofs->match.dl_type = flow->key.flow.dl_type;
733 ofs->match.nw_src = flow->key.flow.nw_src;
734 ofs->match.nw_dst = flow->key.flow.nw_dst;
735 ofs->match.nw_proto = flow->key.flow.nw_proto;
736 memset(ofs->match.pad, 0, sizeof ofs->match.pad);
737 ofs->match.tp_src = flow->key.flow.tp_src;
738 ofs->match.tp_dst = flow->key.flow.tp_dst;
739 ofs->duration = htonl(now - flow->created);
740 ofs->packet_count = htonll(flow->packet_count);
741 ofs->byte_count = htonll(flow->byte_count);
742 ofs->priority = htons(flow->priority);
743 ofs->max_idle = htons(flow->max_idle);
744 memcpy(ofs->actions, flow->actions,
745 sizeof *ofs->actions * flow->n_actions);
749 /* 'buffer' was received on 'in_port', a physical switch port between 0 and
750 * OFPP_MAX. Process it according to 'dp''s flow table. Returns 0 if
751 * successful, in which case 'buffer' is destroyed, or -ESRCH if there is no
752 * matching flow, in which case 'buffer' still belongs to the caller. */
753 int run_flow_through_tables(struct datapath *dp, struct buffer *buffer,
756 struct sw_flow_key key;
757 struct sw_flow *flow;
760 if (flow_extract(buffer, in_port, &key.flow)
761 && (dp->flags & OFPC_FRAG_MASK) == OFPC_FRAG_DROP) {
763 buffer_delete(buffer);
767 flow = chain_lookup(dp->chain, &key);
769 flow_used(flow, buffer);
770 execute_actions(dp, buffer, in_port, &key,
771 flow->actions, flow->n_actions);
778 /* 'buffer' was received on 'in_port', a physical switch port between 0 and
779 * OFPP_MAX. Process it according to 'dp''s flow table, sending it up to the
780 * controller if no flow matches. Takes ownership of 'buffer'. */
781 void fwd_port_input(struct datapath *dp, struct buffer *buffer, int in_port)
783 if (run_flow_through_tables(dp, buffer, in_port)) {
784 dp_output_control(dp, buffer, in_port, dp->miss_send_len,
790 do_output(struct datapath *dp, struct buffer *buffer, int in_port,
791 size_t max_len, int out_port)
793 if (out_port != OFPP_CONTROLLER) {
794 dp_output_port(dp, buffer, in_port, out_port);
796 dp_output_control(dp, buffer, in_port, max_len, OFPR_ACTION);
801 execute_actions(struct datapath *dp, struct buffer *buffer,
802 int in_port, const struct sw_flow_key *key,
803 const struct ofp_action *actions, int n_actions)
805 /* Every output action needs a separate clone of 'buffer', but the common
806 * case is just a single output action, so that doing a clone and then
807 * freeing the original buffer is wasteful. So the following code is
808 * slightly obscure just to avoid that. */
810 size_t max_len=0; /* Initialze to make compiler happy */
815 eth_proto = ntohs(key->flow.dl_type);
817 for (i = 0; i < n_actions; i++) {
818 const struct ofp_action *a = &actions[i];
819 struct eth_header *eh = buffer->l2;
821 if (prev_port != -1) {
822 do_output(dp, buffer_clone(buffer), in_port, max_len, prev_port);
826 switch (ntohs(a->type)) {
828 prev_port = ntohs(a->arg.output.port);
829 max_len = ntohs(a->arg.output.max_len);
832 case OFPAT_SET_DL_VLAN:
833 modify_vlan(buffer, key, a);
836 case OFPAT_SET_DL_SRC:
837 memcpy(eh->eth_src, a->arg.dl_addr, sizeof eh->eth_src);
840 case OFPAT_SET_DL_DST:
841 memcpy(eh->eth_dst, a->arg.dl_addr, sizeof eh->eth_dst);
844 case OFPAT_SET_NW_SRC:
845 case OFPAT_SET_NW_DST:
846 modify_nh(buffer, eth_proto, key->flow.nw_proto, a);
849 case OFPAT_SET_TP_SRC:
850 case OFPAT_SET_TP_DST:
851 modify_th(buffer, eth_proto, key->flow.nw_proto, a);
859 do_output(dp, buffer, in_port, max_len, prev_port);
861 buffer_delete(buffer);
864 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
865 uint8_t nw_proto, const struct ofp_action *a)
867 if (eth_proto == ETH_TYPE_IP) {
868 struct ip_header *nh = buffer->l3;
869 uint32_t new, *field;
871 new = a->arg.nw_addr;
872 field = a->type == OFPAT_SET_NW_SRC ? &nh->ip_src : &nh->ip_dst;
873 if (nw_proto == IP_TYPE_TCP) {
874 struct tcp_header *th = buffer->l4;
875 th->tcp_csum = recalc_csum32(th->tcp_csum, *field, new);
876 } else if (nw_proto == IP_TYPE_UDP) {
877 struct udp_header *th = buffer->l4;
879 th->udp_csum = recalc_csum32(th->udp_csum, *field, new);
881 th->udp_csum = 0xffff;
885 nh->ip_csum = recalc_csum32(nh->ip_csum, *field, new);
890 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
891 uint8_t nw_proto, const struct ofp_action *a)
893 if (eth_proto == ETH_TYPE_IP) {
894 uint16_t new, *field;
898 if (nw_proto == IP_TYPE_TCP) {
899 struct tcp_header *th = buffer->l4;
900 field = a->type == OFPAT_SET_TP_SRC ? &th->tcp_src : &th->tcp_dst;
901 th->tcp_csum = recalc_csum16(th->tcp_csum, *field, new);
903 } else if (nw_proto == IP_TYPE_UDP) {
904 struct udp_header *th = buffer->l4;
905 field = a->type == OFPAT_SET_TP_SRC ? &th->udp_src : &th->udp_dst;
906 th->udp_csum = recalc_csum16(th->udp_csum, *field, new);
913 modify_vlan(struct buffer *buffer,
914 const struct sw_flow_key *key, const struct ofp_action *a)
916 uint16_t new_id = a->arg.vlan_id;
917 struct vlan_eth_header *veh;
919 if (new_id != htons(OFP_VLAN_NONE)) {
920 if (key->flow.dl_vlan != htons(OFP_VLAN_NONE)) {
921 /* Modify vlan id, but maintain other TCI values */
923 veh->veth_tci &= ~htons(VLAN_VID);
924 veh->veth_tci |= new_id;
926 /* Insert new vlan id. */
927 struct eth_header *eh = buffer->l2;
928 struct vlan_eth_header tmp;
929 memcpy(tmp.veth_dst, eh->eth_dst, ETH_ADDR_LEN);
930 memcpy(tmp.veth_src, eh->eth_src, ETH_ADDR_LEN);
931 tmp.veth_type = htons(ETH_TYPE_VLAN);
932 tmp.veth_tci = new_id;
933 tmp.veth_next_type = eh->eth_type;
935 veh = buffer_push_uninit(buffer, VLAN_HEADER_LEN);
936 memcpy(veh, &tmp, sizeof tmp);
937 buffer->l2 -= VLAN_HEADER_LEN;
940 /* Remove an existing vlan header if it exists */
942 if (veh->veth_type == htons(ETH_TYPE_VLAN)) {
943 struct eth_header tmp;
945 memcpy(tmp.eth_dst, veh->veth_dst, ETH_ADDR_LEN);
946 memcpy(tmp.eth_src, veh->veth_src, ETH_ADDR_LEN);
947 tmp.eth_type = veh->veth_next_type;
949 buffer->size -= VLAN_HEADER_LEN;
950 buffer->data += VLAN_HEADER_LEN;
951 buffer->l2 += VLAN_HEADER_LEN;
952 memcpy(buffer->data, &tmp, sizeof tmp);
958 recv_features_request(struct datapath *dp, const struct sender *sender,
961 dp_send_features_reply(dp, sender);
966 recv_get_config_request(struct datapath *dp, const struct sender *sender,
969 struct buffer *buffer;
970 struct ofp_switch_config *osc;
972 osc = make_openflow_reply(sizeof *osc, OFPT_GET_CONFIG_REPLY,
975 osc->flags = htons(dp->flags);
976 osc->miss_send_len = htons(dp->miss_send_len);
978 return send_openflow_buffer(dp, buffer, sender);
982 recv_set_config(struct datapath *dp, const struct sender *sender UNUSED,
985 const struct ofp_switch_config *osc = msg;
988 flags = ntohs(osc->flags) & ~(OFPC_SEND_FLOW_EXP | OFPC_FRAG_MASK);
989 if ((flags & OFPC_FRAG_MASK) != OFPC_FRAG_NORMAL
990 && (flags & OFPC_FRAG_MASK) != OFPC_FRAG_DROP) {
991 flags = (flags & ~OFPC_FRAG_MASK) | OFPC_FRAG_DROP;
994 dp->miss_send_len = ntohs(osc->miss_send_len);
999 recv_packet_out(struct datapath *dp, const struct sender *sender UNUSED,
1002 const struct ofp_packet_out *opo = msg;
1004 if (ntohl(opo->buffer_id) == (uint32_t) -1) {
1005 /* FIXME: can we avoid copying data here? */
1006 int data_len = ntohs(opo->header.length) - sizeof *opo;
1007 struct buffer *buffer = buffer_new(data_len);
1008 buffer_put(buffer, opo->u.data, data_len);
1009 dp_output_port(dp, buffer,
1010 ntohs(opo->in_port), ntohs(opo->out_port));
1012 struct sw_flow_key key;
1013 struct buffer *buffer;
1016 buffer = retrieve_buffer(ntohl(opo->buffer_id));
1021 n_acts = (ntohs(opo->header.length) - sizeof *opo)
1022 / sizeof *opo->u.actions;
1023 flow_extract(buffer, ntohs(opo->in_port), &key.flow);
1024 execute_actions(dp, buffer, ntohs(opo->in_port),
1025 &key, opo->u.actions, n_acts);
1031 recv_port_mod(struct datapath *dp, const struct sender *sender UNUSED,
1034 const struct ofp_port_mod *opm = msg;
1036 dp_update_port_flags(dp, &opm->desc);
1042 add_flow(struct datapath *dp, const struct ofp_flow_mod *ofm)
1044 int error = -ENOMEM;
1047 struct sw_flow *flow;
1050 /* To prevent loops, make sure there's no action to send to the
1051 * OFP_TABLE virtual port.
1053 n_acts = (ntohs(ofm->header.length) - sizeof *ofm) / sizeof *ofm->actions;
1054 for (i=0; i<n_acts; i++) {
1055 const struct ofp_action *a = &ofm->actions[i];
1057 if (a->type == htons(OFPAT_OUTPUT)
1058 && (a->arg.output.port == htons(OFPP_TABLE)
1059 || a->arg.output.port == htons(OFPP_NONE))) {
1060 /* xxx Send fancy new error message? */
1065 /* Allocate memory. */
1066 flow = flow_alloc(n_acts);
1070 /* Fill out flow. */
1071 flow_extract_match(&flow->key, &ofm->match);
1072 flow->max_idle = ntohs(ofm->max_idle);
1073 flow->priority = flow->key.wildcards ? ntohs(ofm->priority) : -1;
1074 flow->timeout = time(0) + flow->max_idle; /* FIXME */
1075 flow->n_actions = n_acts;
1076 flow->created = time(0); /* FIXME */
1077 flow->byte_count = 0;
1078 flow->packet_count = 0;
1079 memcpy(flow->actions, ofm->actions, n_acts * sizeof *flow->actions);
1082 error = chain_insert(dp->chain, flow);
1084 goto error_free_flow;
1087 if (ntohl(ofm->buffer_id) != UINT32_MAX) {
1088 struct buffer *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
1090 struct sw_flow_key key;
1091 uint16_t in_port = ntohs(ofm->match.in_port);
1092 flow_used(flow, buffer);
1093 flow_extract(buffer, in_port, &key.flow);
1094 execute_actions(dp, buffer, in_port, &key, ofm->actions, n_acts);
1104 if (ntohl(ofm->buffer_id) != (uint32_t) -1)
1105 discard_buffer(ntohl(ofm->buffer_id));
1110 recv_flow(struct datapath *dp, const struct sender *sender UNUSED,
1113 const struct ofp_flow_mod *ofm = msg;
1114 uint16_t command = ntohs(ofm->command);
1116 if (command == OFPFC_ADD) {
1117 return add_flow(dp, ofm);
1118 } else if (command == OFPFC_DELETE) {
1119 struct sw_flow_key key;
1120 flow_extract_match(&key, &ofm->match);
1121 return chain_delete(dp->chain, &key, 0, 0) ? 0 : -ESRCH;
1122 } else if (command == OFPFC_DELETE_STRICT) {
1123 struct sw_flow_key key;
1125 flow_extract_match(&key, &ofm->match);
1126 priority = key.wildcards ? ntohs(ofm->priority) : -1;
1127 return chain_delete(dp->chain, &key, priority, 1) ? 0 : -ESRCH;
1133 struct flow_stats_state {
1135 struct sw_table_position position;
1136 struct ofp_flow_stats_request rq;
1139 struct buffer *buffer;
1142 #define MAX_FLOW_STATS_BYTES 4096
1144 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
1147 const struct ofp_flow_stats_request *fsr = body;
1148 struct flow_stats_state *s = xmalloc(sizeof *s);
1149 s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
1150 memset(&s->position, 0, sizeof s->position);
1156 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
1158 struct flow_stats_state *s = private;
1159 fill_flow_stats(s->buffer, flow, s->table_idx, s->now);
1160 return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1163 static int flow_stats_dump(struct datapath *dp, void *state,
1164 struct buffer *buffer)
1166 struct flow_stats_state *s = state;
1167 struct sw_flow_key match_key;
1169 flow_extract_match(&match_key, &s->rq.match);
1172 while (s->table_idx < dp->chain->n_tables
1173 && (s->rq.table_id == 0xff || s->rq.table_id == s->table_idx))
1175 struct sw_table *table = dp->chain->tables[s->table_idx];
1177 if (table->iterate(table, &match_key, &s->position,
1178 flow_stats_dump_callback, s))
1182 memset(&s->position, 0, sizeof s->position);
1184 return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1187 static void flow_stats_done(void *state)
1192 struct aggregate_stats_state {
1193 struct ofp_aggregate_stats_request rq;
1196 static int aggregate_stats_init(struct datapath *dp,
1197 const void *body, int body_len,
1200 const struct ofp_aggregate_stats_request *rq = body;
1201 struct aggregate_stats_state *s = xmalloc(sizeof *s);
1207 static int aggregate_stats_dump_callback(struct sw_flow *flow, void *private)
1209 struct ofp_aggregate_stats_reply *rpy = private;
1210 rpy->packet_count += flow->packet_count;
1211 rpy->byte_count += flow->byte_count;
1216 static int aggregate_stats_dump(struct datapath *dp, void *state,
1217 struct buffer *buffer)
1219 struct aggregate_stats_state *s = state;
1220 struct ofp_aggregate_stats_request *rq = &s->rq;
1221 struct ofp_aggregate_stats_reply *rpy;
1222 struct sw_table_position position;
1223 struct sw_flow_key match_key;
1226 rpy = buffer_put_uninit(buffer, sizeof *rpy);
1227 memset(rpy, 0, sizeof *rpy);
1229 flow_extract_match(&match_key, &rq->match);
1230 table_idx = rq->table_id == 0xff ? 0 : rq->table_id;
1231 memset(&position, 0, sizeof position);
1232 while (table_idx < dp->chain->n_tables
1233 && (rq->table_id == 0xff || rq->table_id == table_idx))
1235 struct sw_table *table = dp->chain->tables[table_idx];
1238 error = table->iterate(table, &match_key, &position,
1239 aggregate_stats_dump_callback, rpy);
1244 memset(&position, 0, sizeof position);
1247 rpy->packet_count = htonll(rpy->packet_count);
1248 rpy->byte_count = htonll(rpy->byte_count);
1249 rpy->flow_count = htonl(rpy->flow_count);
1253 static void aggregate_stats_done(void *state)
1258 static int table_stats_dump(struct datapath *dp, void *state,
1259 struct buffer *buffer)
1262 for (i = 0; i < dp->chain->n_tables; i++) {
1263 struct ofp_table_stats *ots = buffer_put_uninit(buffer, sizeof *ots);
1264 struct sw_table_stats stats;
1265 dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
1266 strncpy(ots->name, stats.name, sizeof ots->name);
1268 memset(ots->pad, 0, sizeof ots->pad);
1269 ots->max_entries = htonl(stats.max_flows);
1270 ots->active_count = htonl(stats.n_flows);
1271 ots->matched_count = htonll(stats.n_matched);
1276 struct port_stats_state {
1280 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
1283 struct port_stats_state *s = xmalloc(sizeof *s);
1289 static int port_stats_dump(struct datapath *dp, void *state,
1290 struct buffer *buffer)
1292 struct port_stats_state *s = state;
1295 for (i = s->port; i < OFPP_MAX; i++) {
1296 struct sw_port *p = &dp->ports[i];
1297 struct ofp_port_stats *ops;
1301 ops = buffer_put_uninit(buffer, sizeof *ops);
1302 ops->port_no = htons(port_no(dp, p));
1303 memset(ops->pad, 0, sizeof ops->pad);
1304 ops->rx_count = htonll(p->rx_count);
1305 ops->tx_count = htonll(p->tx_count);
1306 ops->drop_count = htonll(p->drop_count);
1313 static void port_stats_done(void *state)
1319 /* Minimum and maximum acceptable number of bytes in body member of
1320 * struct ofp_stats_request. */
1321 size_t min_body, max_body;
1323 /* Prepares to dump some kind of statistics on 'dp'. 'body' and
1324 * 'body_len' are the 'body' member of the struct ofp_stats_request.
1325 * Returns zero if successful, otherwise a negative error code.
1326 * May initialize '*state' to state information. May be null if no
1327 * initialization is required.*/
1328 int (*init)(struct datapath *dp, const void *body, int body_len,
1331 /* Appends statistics for 'dp' to 'buffer', which initially contains a
1332 * struct ofp_stats_reply. On success, it should return 1 if it should be
1333 * called again later with another buffer, 0 if it is done, or a negative
1334 * errno value on failure. */
1335 int (*dump)(struct datapath *dp, void *state, struct buffer *buffer);
1337 /* Cleans any state created by the init or dump functions. May be null
1338 * if no cleanup is required. */
1339 void (*done)(void *state);
1342 static const struct stats_type stats[] = {
1344 sizeof(struct ofp_flow_stats_request),
1345 sizeof(struct ofp_flow_stats_request),
1350 [OFPST_AGGREGATE] = {
1351 sizeof(struct ofp_aggregate_stats_request),
1352 sizeof(struct ofp_aggregate_stats_request),
1353 aggregate_stats_init,
1354 aggregate_stats_dump,
1355 aggregate_stats_done
1373 struct stats_dump_cb {
1375 struct ofp_stats_request *rq;
1376 struct sender sender;
1377 const struct stats_type *s;
1382 stats_dump(struct datapath *dp, void *cb_)
1384 struct stats_dump_cb *cb = cb_;
1385 struct ofp_stats_reply *osr;
1386 struct buffer *buffer;
1393 osr = make_openflow_reply(sizeof *osr, OFPT_STATS_REPLY, &cb->sender,
1395 osr->type = htons(cb->s - stats);
1398 err = cb->s->dump(dp, cb->state, buffer);
1404 /* Buffer might have been reallocated, so find our data again. */
1405 osr = buffer_at_assert(buffer, 0, sizeof *osr);
1406 osr->flags = ntohs(OFPSF_REPLY_MORE);
1408 err2 = send_openflow_buffer(dp, buffer, &cb->sender);
1418 stats_done(void *cb_)
1420 struct stats_dump_cb *cb = cb_;
1423 cb->s->done(cb->state);
1430 recv_stats_request(struct datapath *dp, const struct sender *sender,
1433 const struct ofp_stats_request *rq = oh;
1434 size_t rq_len = ntohs(rq->header.length);
1435 struct stats_dump_cb *cb;
1439 type = ntohs(rq->type);
1440 if (type >= ARRAY_SIZE(stats) || !stats[type].dump) {
1441 VLOG_WARN("received stats request of unknown type %d", type);
1445 cb = xmalloc(sizeof *cb);
1447 cb->rq = xmemdup(rq, rq_len);
1448 cb->sender = *sender;
1449 cb->s = &stats[type];
1452 body_len = rq_len - offsetof(struct ofp_stats_request, body);
1453 if (body_len < cb->s->min_body || body_len > cb->s->max_body) {
1454 VLOG_WARN("stats request type %d with bad body length %d",
1461 err = cb->s->init(dp, rq->body, body_len, &cb->state);
1463 VLOG_WARN("failed initialization of stats request type %d: %s",
1464 type, strerror(-err));
1469 remote_start_dump(sender->remote, stats_dump, stats_done, cb);
1479 recv_echo_request(struct datapath *dp, const struct sender *sender,
1482 return send_openflow_buffer(dp, make_echo_reply(oh), sender);
1486 recv_echo_reply(struct datapath *dp UNUSED, const struct sender *sender UNUSED,
1487 const void *oh UNUSED)
1492 /* 'msg', which is 'length' bytes long, was received from the control path.
1493 * Apply it to 'chain'. */
1495 fwd_control_input(struct datapath *dp, const struct sender *sender,
1496 const void *msg, size_t length)
1498 struct openflow_packet {
1500 int (*handler)(struct datapath *, const struct sender *, const void *);
1503 static const struct openflow_packet packets[] = {
1504 [OFPT_FEATURES_REQUEST] = {
1505 sizeof (struct ofp_header),
1506 recv_features_request,
1508 [OFPT_GET_CONFIG_REQUEST] = {
1509 sizeof (struct ofp_header),
1510 recv_get_config_request,
1512 [OFPT_SET_CONFIG] = {
1513 sizeof (struct ofp_switch_config),
1516 [OFPT_PACKET_OUT] = {
1517 sizeof (struct ofp_packet_out),
1521 sizeof (struct ofp_flow_mod),
1525 sizeof (struct ofp_port_mod),
1528 [OFPT_STATS_REQUEST] = {
1529 sizeof (struct ofp_stats_request),
1532 [OFPT_ECHO_REQUEST] = {
1533 sizeof (struct ofp_header),
1536 [OFPT_ECHO_REPLY] = {
1537 sizeof (struct ofp_header),
1542 const struct openflow_packet *pkt;
1543 struct ofp_header *oh;
1545 oh = (struct ofp_header *) msg;
1546 assert(oh->version == OFP_VERSION);
1547 if (oh->type >= ARRAY_SIZE(packets) || ntohs(oh->length) > length)
1550 pkt = &packets[oh->type];
1553 if (length < pkt->min_size)
1556 return pkt->handler(dp, sender, msg);
1559 /* Packet buffering. */
1561 #define OVERWRITE_SECS 1
1563 struct packet_buffer {
1564 struct buffer *buffer;
1569 static struct packet_buffer buffers[N_PKT_BUFFERS];
1570 static unsigned int buffer_idx;
1572 uint32_t save_buffer(struct buffer *buffer)
1574 struct packet_buffer *p;
1577 buffer_idx = (buffer_idx + 1) & PKT_BUFFER_MASK;
1578 p = &buffers[buffer_idx];
1580 /* Don't buffer packet if existing entry is less than
1581 * OVERWRITE_SECS old. */
1582 if (time(0) < p->timeout) { /* FIXME */
1585 buffer_delete(p->buffer);
1588 /* Don't use maximum cookie value since the all-bits-1 id is
1590 if (++p->cookie >= (1u << PKT_COOKIE_BITS) - 1)
1592 p->buffer = buffer_clone(buffer); /* FIXME */
1593 p->timeout = time(0) + OVERWRITE_SECS; /* FIXME */
1594 id = buffer_idx | (p->cookie << PKT_BUFFER_BITS);
1599 static struct buffer *retrieve_buffer(uint32_t id)
1601 struct buffer *buffer = NULL;
1602 struct packet_buffer *p;
1604 p = &buffers[id & PKT_BUFFER_MASK];
1605 if (p->cookie == id >> PKT_BUFFER_BITS) {
1609 printf("cookie mismatch: %x != %x\n",
1610 id >> PKT_BUFFER_BITS, p->cookie);
1616 static void discard_buffer(uint32_t id)
1618 struct packet_buffer *p;
1620 p = &buffers[id & PKT_BUFFER_MASK];
1621 if (p->cookie == id >> PKT_BUFFER_BITS) {
1622 buffer_delete(p->buffer);