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 void fwd_port_input(struct datapath *, struct buffer *, int in_port);
160 int fwd_control_input(struct datapath *, const struct sender *,
161 const void *, size_t);
163 uint32_t save_buffer(struct buffer *);
164 static struct buffer *retrieve_buffer(uint32_t id);
165 static void discard_buffer(uint32_t id);
167 static int port_no(struct datapath *dp, struct sw_port *p)
169 assert(p >= dp->ports && p < &dp->ports[ARRAY_SIZE(dp->ports)]);
170 return p - dp->ports;
173 /* Generates and returns a random datapath id. */
175 gen_datapath_id(void)
177 uint8_t ea[ETH_ADDR_LEN];
179 return eth_addr_to_uint64(ea);
183 dp_new(struct datapath **dp_, uint64_t dpid, struct rconn *rconn)
187 dp = calloc(1, sizeof *dp);
192 dp->last_timeout = time(0);
193 list_init(&dp->remotes);
194 dp->controller = remote_create(dp, rconn);
195 dp->listen_vconn = NULL;
196 dp->id = dpid <= UINT64_C(0xffffffffffff) ? dpid : gen_datapath_id();
197 dp->chain = chain_create();
199 VLOG_ERR("could not create chain");
204 list_init(&dp->port_list);
206 dp->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
212 dp_add_port(struct datapath *dp, const char *name)
214 struct netdev *netdev;
220 error = netdev_open(name, NETDEV_ETH_TYPE_ANY, &netdev);
224 error = netdev_set_flags(netdev, NETDEV_UP | NETDEV_PROMISC, false);
226 VLOG_ERR("Couldn't set promiscuous mode on %s device", name);
227 netdev_close(netdev);
230 if (netdev_get_in4(netdev, &in4)) {
231 VLOG_ERR("%s device has assigned IP address %s", name, inet_ntoa(in4));
233 if (netdev_get_in6(netdev, &in6)) {
234 char in6_name[INET6_ADDRSTRLEN + 1];
235 inet_ntop(AF_INET6, &in6, in6_name, sizeof in6_name);
236 VLOG_ERR("%s device has assigned IPv6 address %s", name, in6_name);
239 for (p = dp->ports; ; p++) {
240 if (p >= &dp->ports[ARRAY_SIZE(dp->ports)]) {
242 } else if (!p->netdev) {
252 list_push_back(&dp->port_list, &p->node);
254 /* Notify the ctlpath that this port has been added */
255 send_port_status(p, OFPPR_ADD);
261 dp_add_listen_vconn(struct datapath *dp, struct vconn *listen_vconn)
263 assert(!dp->listen_vconn);
264 dp->listen_vconn = listen_vconn;
268 dp_run(struct datapath *dp)
270 time_t now = time(0);
271 struct sw_port *p, *pn;
272 struct remote *r, *rn;
273 struct buffer *buffer = NULL;
275 if (now != dp->last_timeout) {
276 struct list deleted = LIST_INITIALIZER(&deleted);
277 struct sw_flow *f, *n;
279 chain_timeout(dp->chain, &deleted);
280 LIST_FOR_EACH_SAFE (f, n, struct sw_flow, node, &deleted) {
281 send_flow_expired(dp, f);
282 list_remove(&f->node);
285 dp->last_timeout = now;
287 poll_timer_wait(1000);
289 LIST_FOR_EACH_SAFE (p, pn, struct sw_port, node, &dp->port_list) {
293 /* Allocate buffer with some headroom to add headers in forwarding
294 * to the controller or adding a vlan tag, plus an extra 2 bytes to
295 * allow IP headers to be aligned on a 4-byte boundary. */
296 const int headroom = 128 + 2;
297 const int hard_header = VLAN_ETH_HEADER_LEN;
298 const int mtu = netdev_get_mtu(p->netdev);
299 buffer = buffer_new(headroom + hard_header + mtu);
300 buffer->data += headroom;
302 error = netdev_recv(p->netdev, buffer);
305 fwd_port_input(dp, buffer, port_no(dp, p));
307 } else if (error != EAGAIN) {
308 VLOG_ERR("Error receiving data from %s: %s",
309 netdev_get_name(p->netdev), strerror(error));
313 buffer_delete(buffer);
315 /* Talk to remotes. */
316 LIST_FOR_EACH_SAFE (r, rn, struct remote, node, &dp->remotes) {
319 if (dp->listen_vconn) {
321 struct vconn *new_vconn;
324 retval = vconn_accept(dp->listen_vconn, &new_vconn);
326 if (retval != EAGAIN) {
327 VLOG_WARN("accept failed (%s)", strerror(retval));
331 remote_create(dp, rconn_new_from_vconn("passive", 128, new_vconn));
337 remote_run(struct datapath *dp, struct remote *r)
343 /* Do some remote processing, but cap it at a reasonable amount so that
344 * other processing doesn't starve. */
345 for (i = 0; i < 50; i++) {
347 struct buffer *buffer;
348 struct ofp_header *oh;
350 buffer = rconn_recv(r->rconn);
355 if (buffer->size >= sizeof *oh) {
356 struct sender sender;
360 sender.xid = oh->xid;
361 fwd_control_input(dp, &sender, buffer->data, buffer->size);
363 VLOG_WARN("received too-short OpenFlow message");
365 buffer_delete(buffer);
367 if (!rconn_is_full(r->rconn)) {
368 int error = r->cb_dump(dp, r->cb_aux);
371 VLOG_WARN("dump callback error: %s", strerror(-error));
373 r->cb_done(r->cb_aux);
382 if (!rconn_is_alive(r->rconn)) {
388 remote_wait(struct remote *r)
390 rconn_run_wait(r->rconn);
391 rconn_recv_wait(r->rconn);
395 remote_destroy(struct remote *r)
398 if (r->cb_dump && r->cb_done) {
399 r->cb_done(r->cb_aux);
401 list_remove(&r->node);
402 rconn_destroy(r->rconn);
407 static struct remote *
408 remote_create(struct datapath *dp, struct rconn *rconn)
410 struct remote *remote = xmalloc(sizeof *remote);
411 list_push_back(&dp->remotes, &remote->node);
412 remote->rconn = rconn;
413 remote->cb_dump = NULL;
417 /* Starts a callback-based, reliable, possibly multi-message reply to a
418 * request made by 'remote'.
420 * 'dump' designates a function that will be called when the 'remote' send
421 * queue has an empty slot. It should compose a message and send it on
422 * 'remote'. On success, it should return 1 if it should be called again when
423 * another send queue slot opens up, 0 if its transmissions are complete, or a
424 * negative errno value on failure.
426 * 'done' designates a function to clean up any resources allocated for the
427 * dump. It must handle being called before the dump is complete (which will
428 * happen if 'remote' is closed unexpectedly).
430 * 'aux' is passed to 'dump' and 'done'. */
432 remote_start_dump(struct remote *remote,
433 int (*dump)(struct datapath *, void *),
434 void (*done)(void *),
437 assert(!remote->cb_dump);
438 remote->cb_dump = dump;
439 remote->cb_done = done;
440 remote->cb_aux = aux;
444 dp_wait(struct datapath *dp)
449 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
450 netdev_recv_wait(p->netdev);
452 LIST_FOR_EACH (r, struct remote, node, &dp->remotes) {
455 if (dp->listen_vconn) {
456 vconn_accept_wait(dp->listen_vconn);
460 /* Delete 'p' from switch. */
462 del_switch_port(struct sw_port *p)
464 send_port_status(p, OFPPR_DELETE);
465 netdev_close(p->netdev);
467 list_remove(&p->node);
471 dp_destroy(struct datapath *dp)
473 struct sw_port *p, *n;
479 LIST_FOR_EACH_SAFE (p, n, struct sw_port, node, &dp->port_list) {
482 chain_destroy(dp->chain);
486 /* Send packets out all the ports except the originating one. If the
487 * "flood" argument is set, don't send out ports with flooding disabled.
490 output_all(struct datapath *dp, struct buffer *buffer, int in_port, int flood)
496 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
497 if (port_no(dp, p) == in_port) {
500 if (flood && p->flags & BRIDGE_PORT_NO_FLOOD) {
503 if (prev_port != -1) {
504 dp_output_port(dp, buffer_clone(buffer), in_port, prev_port);
506 prev_port = port_no(dp, p);
509 dp_output_port(dp, buffer, in_port, prev_port);
511 buffer_delete(buffer);
517 output_packet(struct datapath *dp, struct buffer *buffer, int out_port)
519 if (out_port >= 0 && out_port < OFPP_MAX) {
520 struct sw_port *p = &dp->ports[out_port];
521 if (p->netdev != NULL) {
522 if (!netdev_send(p->netdev, buffer)) {
531 buffer_delete(buffer);
532 /* FIXME: ratelimit */
533 VLOG_DBG("can't forward to bad port %d\n", out_port);
536 /* Takes ownership of 'buffer' and transmits it to 'out_port' on 'dp'.
539 dp_output_port(struct datapath *dp, struct buffer *buffer,
540 int in_port, int out_port)
544 if (out_port == OFPP_FLOOD) {
545 output_all(dp, buffer, in_port, 1);
546 } else if (out_port == OFPP_ALL) {
547 output_all(dp, buffer, in_port, 0);
548 } else if (out_port == OFPP_CONTROLLER) {
549 dp_output_control(dp, buffer, in_port, 0, OFPR_ACTION);
550 } else if (out_port == OFPP_TABLE) {
551 struct sw_flow_key key;
552 struct sw_flow *flow;
555 flow_extract(buffer, in_port, &key.flow);
556 flow = chain_lookup(dp->chain, &key);
558 flow_used(flow, buffer);
559 execute_actions(dp, buffer, in_port, &key,
560 flow->actions, flow->n_actions);
562 buffer_delete(buffer);
565 output_packet(dp, buffer, out_port);
570 make_openflow_reply(size_t openflow_len, uint8_t type,
571 const struct sender *sender, struct buffer **bufferp)
573 return make_openflow_xid(openflow_len, type, sender ? sender->xid : 0,
578 send_openflow_buffer(struct datapath *dp, struct buffer *buffer,
579 const struct sender *sender)
581 struct remote *remote = sender ? sender->remote : dp->controller;
582 struct rconn *rconn = remote->rconn;
585 update_openflow_length(buffer);
586 retval = rconn_send(rconn, buffer);
588 VLOG_WARN("send to %s failed: %s",
589 rconn_get_name(rconn), strerror(retval));
590 buffer_delete(buffer);
595 /* Takes ownership of 'buffer' and transmits it to 'dp''s controller. If the
596 * packet can be saved in a buffer, then only the first max_len bytes of
597 * 'buffer' are sent; otherwise, all of 'buffer' is sent. 'reason' indicates
598 * why 'buffer' is being sent. 'max_len' sets the maximum number of bytes that
599 * the caller wants to be sent; a value of 0 indicates the entire packet should
602 dp_output_control(struct datapath *dp, struct buffer *buffer, int in_port,
603 size_t max_len, int reason)
605 struct ofp_packet_in *opi;
609 buffer_id = save_buffer(buffer);
610 total_len = buffer->size;
611 if (buffer_id != UINT32_MAX && buffer->size > max_len) {
612 buffer->size = max_len;
615 opi = buffer_push_uninit(buffer, offsetof(struct ofp_packet_in, data));
616 opi->header.version = OFP_VERSION;
617 opi->header.type = OFPT_PACKET_IN;
618 opi->header.length = htons(buffer->size);
619 opi->header.xid = htonl(0);
620 opi->buffer_id = htonl(buffer_id);
621 opi->total_len = htons(total_len);
622 opi->in_port = htons(in_port);
623 opi->reason = reason;
625 send_openflow_buffer(dp, buffer, NULL);
628 static void fill_port_desc(struct datapath *dp, struct sw_port *p,
629 struct ofp_phy_port *desc)
631 desc->port_no = htons(port_no(dp, p));
632 strncpy((char *) desc->name, netdev_get_name(p->netdev),
634 desc->name[sizeof desc->name - 1] = '\0';
635 memcpy(desc->hw_addr, netdev_get_etheraddr(p->netdev), ETH_ADDR_LEN);
636 desc->flags = htonl(p->flags);
637 desc->features = htonl(netdev_get_features(p->netdev));
638 desc->speed = htonl(netdev_get_speed(p->netdev));
642 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
644 struct buffer *buffer;
645 struct ofp_switch_features *ofr;
648 ofr = make_openflow_reply(sizeof *ofr, OFPT_FEATURES_REPLY,
650 ofr->datapath_id = htonll(dp->id);
651 ofr->n_exact = htonl(2 * TABLE_HASH_MAX_FLOWS);
652 ofr->n_compression = 0; /* Not supported */
653 ofr->n_general = htonl(TABLE_LINEAR_MAX_FLOWS);
654 ofr->buffer_mb = htonl(UINT32_MAX);
655 ofr->n_buffers = htonl(N_PKT_BUFFERS);
656 ofr->capabilities = htonl(OFP_SUPPORTED_CAPABILITIES);
657 ofr->actions = htonl(OFP_SUPPORTED_ACTIONS);
658 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
659 struct ofp_phy_port *opp = buffer_put_uninit(buffer, sizeof *opp);
660 memset(opp, 0, sizeof *opp);
661 fill_port_desc(dp, p, opp);
663 send_openflow_buffer(dp, buffer, sender);
667 dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp)
669 int port_no = ntohs(opp->port_no);
670 if (port_no < OFPP_MAX) {
671 struct sw_port *p = &dp->ports[port_no];
673 /* Make sure the port id hasn't changed since this was sent */
674 if (!p || memcmp(opp->hw_addr, netdev_get_etheraddr(p->netdev),
675 ETH_ADDR_LEN) != 0) {
678 p->flags = htonl(opp->flags);
683 send_port_status(struct sw_port *p, uint8_t status)
685 struct buffer *buffer;
686 struct ofp_port_status *ops;
687 ops = make_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, 0, &buffer);
688 ops->reason = status;
689 memset(ops->pad, 0, sizeof ops->pad);
690 fill_port_desc(p->dp, p, &ops->desc);
692 send_openflow_buffer(p->dp, buffer, NULL);
696 send_flow_expired(struct datapath *dp, struct sw_flow *flow)
698 struct buffer *buffer;
699 struct ofp_flow_expired *ofe;
700 ofe = make_openflow_xid(sizeof *ofe, OFPT_FLOW_EXPIRED, 0, &buffer);
701 flow_fill_match(&ofe->match, &flow->key);
703 memset(ofe->pad, 0, sizeof ofe->pad);
704 ofe->priority = htons(flow->priority);
706 ofe->duration = htonl(flow->timeout - flow->max_idle - flow->created);
707 ofe->packet_count = htonll(flow->packet_count);
708 ofe->byte_count = htonll(flow->byte_count);
709 send_openflow_buffer(dp, buffer, NULL);
713 dp_send_error_msg(struct datapath *dp, const struct sender *sender,
714 uint16_t type, uint16_t code, const uint8_t *data, size_t len)
716 struct buffer *buffer;
717 struct ofp_error_msg *oem;
718 oem = make_openflow_reply(sizeof(*oem)+len, OFPT_ERROR_MSG,
720 oem->type = htons(type);
721 oem->code = htons(code);
722 memcpy(oem->data, data, len);
723 send_openflow_buffer(dp, buffer, sender);
727 fill_flow_stats(struct buffer *buffer, struct sw_flow *flow,
728 int table_idx, time_t now)
730 struct ofp_flow_stats *ofs;
731 int length = sizeof *ofs + sizeof *ofs->actions * flow->n_actions;
732 ofs = buffer_put_uninit(buffer, length);
733 ofs->length = htons(length);
734 ofs->table_id = table_idx;
736 ofs->match.wildcards = htons(flow->key.wildcards);
737 ofs->match.in_port = flow->key.flow.in_port;
738 memcpy(ofs->match.dl_src, flow->key.flow.dl_src, ETH_ADDR_LEN);
739 memcpy(ofs->match.dl_dst, flow->key.flow.dl_dst, ETH_ADDR_LEN);
740 ofs->match.dl_vlan = flow->key.flow.dl_vlan;
741 ofs->match.dl_type = flow->key.flow.dl_type;
742 ofs->match.nw_src = flow->key.flow.nw_src;
743 ofs->match.nw_dst = flow->key.flow.nw_dst;
744 ofs->match.nw_proto = flow->key.flow.nw_proto;
745 memset(ofs->match.pad, 0, sizeof ofs->match.pad);
746 ofs->match.tp_src = flow->key.flow.tp_src;
747 ofs->match.tp_dst = flow->key.flow.tp_dst;
748 ofs->duration = htonl(now - flow->created);
749 ofs->packet_count = htonll(flow->packet_count);
750 ofs->byte_count = htonll(flow->byte_count);
751 ofs->priority = htons(flow->priority);
752 ofs->max_idle = htons(flow->max_idle);
753 memcpy(ofs->actions, flow->actions,
754 sizeof *ofs->actions * flow->n_actions);
758 /* 'buffer' was received on 'in_port', a physical switch port between 0 and
759 * OFPP_MAX. Process it according to 'chain'. */
760 void fwd_port_input(struct datapath *dp, struct buffer *buffer, int in_port)
762 struct sw_flow_key key;
763 struct sw_flow *flow;
766 flow_extract(buffer, in_port, &key.flow);
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);
773 dp_output_control(dp, buffer, in_port, dp->miss_send_len,
779 do_output(struct datapath *dp, struct buffer *buffer, int in_port,
780 size_t max_len, int out_port)
782 if (out_port != OFPP_CONTROLLER) {
783 dp_output_port(dp, buffer, in_port, out_port);
785 dp_output_control(dp, buffer, in_port, max_len, OFPR_ACTION);
790 execute_actions(struct datapath *dp, struct buffer *buffer,
791 int in_port, const struct sw_flow_key *key,
792 const struct ofp_action *actions, int n_actions)
794 /* Every output action needs a separate clone of 'buffer', but the common
795 * case is just a single output action, so that doing a clone and then
796 * freeing the original buffer is wasteful. So the following code is
797 * slightly obscure just to avoid that. */
799 size_t max_len=0; /* Initialze to make compiler happy */
804 eth_proto = ntohs(key->flow.dl_type);
806 for (i = 0; i < n_actions; i++) {
807 const struct ofp_action *a = &actions[i];
808 struct eth_header *eh = buffer->l2;
810 if (prev_port != -1) {
811 do_output(dp, buffer_clone(buffer), in_port, max_len, prev_port);
815 switch (ntohs(a->type)) {
817 prev_port = ntohs(a->arg.output.port);
818 max_len = ntohs(a->arg.output.max_len);
821 case OFPAT_SET_DL_VLAN:
822 modify_vlan(buffer, key, a);
825 case OFPAT_SET_DL_SRC:
826 memcpy(eh->eth_src, a->arg.dl_addr, sizeof eh->eth_src);
829 case OFPAT_SET_DL_DST:
830 memcpy(eh->eth_dst, a->arg.dl_addr, sizeof eh->eth_dst);
833 case OFPAT_SET_NW_SRC:
834 case OFPAT_SET_NW_DST:
835 modify_nh(buffer, eth_proto, key->flow.nw_proto, a);
838 case OFPAT_SET_TP_SRC:
839 case OFPAT_SET_TP_DST:
840 modify_th(buffer, eth_proto, key->flow.nw_proto, a);
848 do_output(dp, buffer, in_port, max_len, prev_port);
850 buffer_delete(buffer);
853 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
854 uint8_t nw_proto, const struct ofp_action *a)
856 if (eth_proto == ETH_TYPE_IP) {
857 struct ip_header *nh = buffer->l3;
858 uint32_t new, *field;
860 new = a->arg.nw_addr;
861 field = a->type == OFPAT_SET_NW_SRC ? &nh->ip_src : &nh->ip_dst;
862 if (nw_proto == IP_TYPE_TCP) {
863 struct tcp_header *th = buffer->l4;
864 th->tcp_csum = recalc_csum32(th->tcp_csum, *field, new);
865 } else if (nw_proto == IP_TYPE_UDP) {
866 struct udp_header *th = buffer->l4;
868 th->udp_csum = recalc_csum32(th->udp_csum, *field, new);
870 th->udp_csum = 0xffff;
874 nh->ip_csum = recalc_csum32(nh->ip_csum, *field, new);
879 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
880 uint8_t nw_proto, const struct ofp_action *a)
882 if (eth_proto == ETH_TYPE_IP) {
883 uint16_t new, *field;
887 if (nw_proto == IP_TYPE_TCP) {
888 struct tcp_header *th = buffer->l4;
889 field = a->type == OFPAT_SET_TP_SRC ? &th->tcp_src : &th->tcp_dst;
890 th->tcp_csum = recalc_csum16(th->tcp_csum, *field, new);
892 } else if (nw_proto == IP_TYPE_UDP) {
893 struct udp_header *th = buffer->l4;
894 field = a->type == OFPAT_SET_TP_SRC ? &th->udp_src : &th->udp_dst;
895 th->udp_csum = recalc_csum16(th->udp_csum, *field, new);
902 modify_vlan(struct buffer *buffer,
903 const struct sw_flow_key *key, const struct ofp_action *a)
905 uint16_t new_id = a->arg.vlan_id;
906 struct vlan_eth_header *veh;
908 if (new_id != htons(OFP_VLAN_NONE)) {
909 if (key->flow.dl_vlan != htons(OFP_VLAN_NONE)) {
910 /* Modify vlan id, but maintain other TCI values */
912 veh->veth_tci &= ~htons(VLAN_VID);
913 veh->veth_tci |= new_id;
915 /* Insert new vlan id. */
916 struct eth_header *eh = buffer->l2;
917 struct vlan_eth_header tmp;
918 memcpy(tmp.veth_dst, eh->eth_dst, ETH_ADDR_LEN);
919 memcpy(tmp.veth_src, eh->eth_src, ETH_ADDR_LEN);
920 tmp.veth_type = htons(ETH_TYPE_VLAN);
921 tmp.veth_tci = new_id;
922 tmp.veth_next_type = eh->eth_type;
924 veh = buffer_push_uninit(buffer, VLAN_HEADER_LEN);
925 memcpy(veh, &tmp, sizeof tmp);
926 buffer->l2 -= VLAN_HEADER_LEN;
929 /* Remove an existing vlan header if it exists */
931 if (veh->veth_type == htons(ETH_TYPE_VLAN)) {
932 struct eth_header tmp;
934 memcpy(tmp.eth_dst, veh->veth_dst, ETH_ADDR_LEN);
935 memcpy(tmp.eth_src, veh->veth_src, ETH_ADDR_LEN);
936 tmp.eth_type = veh->veth_next_type;
938 buffer->size -= VLAN_HEADER_LEN;
939 buffer->data += VLAN_HEADER_LEN;
940 buffer->l2 += VLAN_HEADER_LEN;
941 memcpy(buffer->data, &tmp, sizeof tmp);
947 recv_features_request(struct datapath *dp, const struct sender *sender,
950 dp_send_features_reply(dp, sender);
955 recv_get_config_request(struct datapath *dp, const struct sender *sender,
958 struct buffer *buffer;
959 struct ofp_switch_config *osc;
961 osc = make_openflow_reply(sizeof *osc, OFPT_GET_CONFIG_REPLY,
964 osc->flags = htons(dp->flags);
965 osc->miss_send_len = htons(dp->miss_send_len);
967 return send_openflow_buffer(dp, buffer, sender);
971 recv_set_config(struct datapath *dp, const struct sender *sender UNUSED,
974 const struct ofp_switch_config *osc = msg;
975 dp->flags = ntohs(osc->flags);
976 dp->miss_send_len = ntohs(osc->miss_send_len);
981 recv_packet_out(struct datapath *dp, const struct sender *sender UNUSED,
984 const struct ofp_packet_out *opo = msg;
986 if (ntohl(opo->buffer_id) == (uint32_t) -1) {
987 /* FIXME: can we avoid copying data here? */
988 int data_len = ntohs(opo->header.length) - sizeof *opo;
989 struct buffer *buffer = buffer_new(data_len);
990 buffer_put(buffer, opo->u.data, data_len);
991 dp_output_port(dp, buffer,
992 ntohs(opo->in_port), ntohs(opo->out_port));
994 struct sw_flow_key key;
995 struct buffer *buffer;
998 buffer = retrieve_buffer(ntohl(opo->buffer_id));
1003 n_acts = (ntohs(opo->header.length) - sizeof *opo)
1004 / sizeof *opo->u.actions;
1005 flow_extract(buffer, ntohs(opo->in_port), &key.flow);
1006 execute_actions(dp, buffer, ntohs(opo->in_port),
1007 &key, opo->u.actions, n_acts);
1013 recv_port_mod(struct datapath *dp, const struct sender *sender UNUSED,
1016 const struct ofp_port_mod *opm = msg;
1018 dp_update_port_flags(dp, &opm->desc);
1024 add_flow(struct datapath *dp, const struct ofp_flow_mod *ofm)
1026 int error = -ENOMEM;
1029 struct sw_flow *flow;
1032 /* To prevent loops, make sure there's no action to send to the
1033 * OFP_TABLE virtual port.
1035 n_acts = (ntohs(ofm->header.length) - sizeof *ofm) / sizeof *ofm->actions;
1036 for (i=0; i<n_acts; i++) {
1037 const struct ofp_action *a = &ofm->actions[i];
1039 if (a->type == htons(OFPAT_OUTPUT)
1040 && (a->arg.output.port == htons(OFPP_TABLE)
1041 || a->arg.output.port == htons(OFPP_NONE))) {
1042 /* xxx Send fancy new error message? */
1047 /* Allocate memory. */
1048 flow = flow_alloc(n_acts);
1052 /* Fill out flow. */
1053 flow_extract_match(&flow->key, &ofm->match);
1054 flow->max_idle = ntohs(ofm->max_idle);
1055 flow->priority = flow->key.wildcards ? ntohs(ofm->priority) : -1;
1056 flow->timeout = time(0) + flow->max_idle; /* FIXME */
1057 flow->n_actions = n_acts;
1058 flow->created = time(0); /* FIXME */
1059 flow->byte_count = 0;
1060 flow->packet_count = 0;
1061 memcpy(flow->actions, ofm->actions, n_acts * sizeof *flow->actions);
1064 error = chain_insert(dp->chain, flow);
1066 goto error_free_flow;
1069 if (ntohl(ofm->buffer_id) != UINT32_MAX) {
1070 struct buffer *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
1072 struct sw_flow_key key;
1073 uint16_t in_port = ntohs(ofm->match.in_port);
1074 flow_used(flow, buffer);
1075 flow_extract(buffer, in_port, &key.flow);
1076 execute_actions(dp, buffer, in_port, &key, ofm->actions, n_acts);
1086 if (ntohl(ofm->buffer_id) != (uint32_t) -1)
1087 discard_buffer(ntohl(ofm->buffer_id));
1092 recv_flow(struct datapath *dp, const struct sender *sender UNUSED,
1095 const struct ofp_flow_mod *ofm = msg;
1096 uint16_t command = ntohs(ofm->command);
1098 if (command == OFPFC_ADD) {
1099 return add_flow(dp, ofm);
1100 } else if (command == OFPFC_DELETE) {
1101 struct sw_flow_key key;
1102 flow_extract_match(&key, &ofm->match);
1103 return chain_delete(dp->chain, &key, 0, 0) ? 0 : -ESRCH;
1104 } else if (command == OFPFC_DELETE_STRICT) {
1105 struct sw_flow_key key;
1107 flow_extract_match(&key, &ofm->match);
1108 priority = key.wildcards ? ntohs(ofm->priority) : -1;
1109 return chain_delete(dp->chain, &key, priority, 1) ? 0 : -ESRCH;
1115 struct flow_stats_state {
1117 struct sw_table_position position;
1118 struct ofp_flow_stats_request rq;
1121 struct buffer *buffer;
1124 #define MAX_FLOW_STATS_BYTES 4096
1126 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
1129 const struct ofp_flow_stats_request *fsr = body;
1130 struct flow_stats_state *s = xmalloc(sizeof *s);
1131 s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
1132 memset(&s->position, 0, sizeof s->position);
1138 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
1140 struct flow_stats_state *s = private;
1141 fill_flow_stats(s->buffer, flow, s->table_idx, s->now);
1142 return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1145 static int flow_stats_dump(struct datapath *dp, void *state,
1146 struct buffer *buffer)
1148 struct flow_stats_state *s = state;
1149 struct sw_flow_key match_key;
1151 flow_extract_match(&match_key, &s->rq.match);
1154 while (s->table_idx < dp->chain->n_tables
1155 && (s->rq.table_id == 0xff || s->rq.table_id == s->table_idx))
1157 struct sw_table *table = dp->chain->tables[s->table_idx];
1159 if (table->iterate(table, &match_key, &s->position,
1160 flow_stats_dump_callback, s))
1164 memset(&s->position, 0, sizeof s->position);
1166 return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1169 static void flow_stats_done(void *state)
1174 struct aggregate_stats_state {
1175 struct ofp_aggregate_stats_request rq;
1178 static int aggregate_stats_init(struct datapath *dp,
1179 const void *body, int body_len,
1182 const struct ofp_aggregate_stats_request *rq = body;
1183 struct aggregate_stats_state *s = xmalloc(sizeof *s);
1189 static int aggregate_stats_dump_callback(struct sw_flow *flow, void *private)
1191 struct ofp_aggregate_stats_reply *rpy = private;
1192 rpy->packet_count += flow->packet_count;
1193 rpy->byte_count += flow->byte_count;
1198 static int aggregate_stats_dump(struct datapath *dp, void *state,
1199 struct buffer *buffer)
1201 struct aggregate_stats_state *s = state;
1202 struct ofp_aggregate_stats_request *rq = &s->rq;
1203 struct ofp_aggregate_stats_reply *rpy;
1204 struct sw_table_position position;
1205 struct sw_flow_key match_key;
1208 rpy = buffer_put_uninit(buffer, sizeof *rpy);
1209 memset(rpy, 0, sizeof *rpy);
1211 flow_extract_match(&match_key, &rq->match);
1212 table_idx = rq->table_id == 0xff ? 0 : rq->table_id;
1213 memset(&position, 0, sizeof position);
1214 while (table_idx < dp->chain->n_tables
1215 && (rq->table_id == 0xff || rq->table_id == table_idx))
1217 struct sw_table *table = dp->chain->tables[table_idx];
1220 error = table->iterate(table, &match_key, &position,
1221 aggregate_stats_dump_callback, rpy);
1226 memset(&position, 0, sizeof position);
1229 rpy->packet_count = htonll(rpy->packet_count);
1230 rpy->byte_count = htonll(rpy->byte_count);
1231 rpy->flow_count = htonl(rpy->flow_count);
1235 static void aggregate_stats_done(void *state)
1240 static int table_stats_dump(struct datapath *dp, void *state,
1241 struct buffer *buffer)
1244 for (i = 0; i < dp->chain->n_tables; i++) {
1245 struct ofp_table_stats *ots = buffer_put_uninit(buffer, sizeof *ots);
1246 struct sw_table_stats stats;
1247 dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
1248 strncpy(ots->name, stats.name, sizeof ots->name);
1250 memset(ots->pad, 0, sizeof ots->pad);
1251 ots->max_entries = htonl(stats.max_flows);
1252 ots->active_count = htonl(stats.n_flows);
1253 ots->matched_count = htonll(stats.n_matched);
1258 struct port_stats_state {
1262 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
1265 struct port_stats_state *s = xmalloc(sizeof *s);
1271 static int port_stats_dump(struct datapath *dp, void *state,
1272 struct buffer *buffer)
1274 struct port_stats_state *s = state;
1277 for (i = s->port; i < OFPP_MAX; i++) {
1278 struct sw_port *p = &dp->ports[i];
1279 struct ofp_port_stats *ops;
1283 ops = buffer_put_uninit(buffer, sizeof *ops);
1284 ops->port_no = htons(port_no(dp, p));
1285 memset(ops->pad, 0, sizeof ops->pad);
1286 ops->rx_count = htonll(p->rx_count);
1287 ops->tx_count = htonll(p->tx_count);
1288 ops->drop_count = htonll(p->drop_count);
1295 static void port_stats_done(void *state)
1301 /* Minimum and maximum acceptable number of bytes in body member of
1302 * struct ofp_stats_request. */
1303 size_t min_body, max_body;
1305 /* Prepares to dump some kind of statistics on 'dp'. 'body' and
1306 * 'body_len' are the 'body' member of the struct ofp_stats_request.
1307 * Returns zero if successful, otherwise a negative error code.
1308 * May initialize '*state' to state information. May be null if no
1309 * initialization is required.*/
1310 int (*init)(struct datapath *dp, const void *body, int body_len,
1313 /* Appends statistics for 'dp' to 'buffer', which initially contains a
1314 * struct ofp_stats_reply. On success, it should return 1 if it should be
1315 * called again later with another buffer, 0 if it is done, or a negative
1316 * errno value on failure. */
1317 int (*dump)(struct datapath *dp, void *state, struct buffer *buffer);
1319 /* Cleans any state created by the init or dump functions. May be null
1320 * if no cleanup is required. */
1321 void (*done)(void *state);
1324 static const struct stats_type stats[] = {
1326 sizeof(struct ofp_flow_stats_request),
1327 sizeof(struct ofp_flow_stats_request),
1332 [OFPST_AGGREGATE] = {
1333 sizeof(struct ofp_aggregate_stats_request),
1334 sizeof(struct ofp_aggregate_stats_request),
1335 aggregate_stats_init,
1336 aggregate_stats_dump,
1337 aggregate_stats_done
1355 struct stats_dump_cb {
1357 struct ofp_stats_request *rq;
1358 struct sender sender;
1359 const struct stats_type *s;
1364 stats_dump(struct datapath *dp, void *cb_)
1366 struct stats_dump_cb *cb = cb_;
1367 struct ofp_stats_reply *osr;
1368 struct buffer *buffer;
1375 osr = make_openflow_reply(sizeof *osr, OFPT_STATS_REPLY, &cb->sender,
1377 osr->type = htons(cb->s - stats);
1380 err = cb->s->dump(dp, cb->state, buffer);
1386 /* Buffer might have been reallocated, so find our data again. */
1387 osr = buffer_at_assert(buffer, 0, sizeof *osr);
1388 osr->flags = ntohs(OFPSF_REPLY_MORE);
1390 err2 = send_openflow_buffer(dp, buffer, &cb->sender);
1400 stats_done(void *cb_)
1402 struct stats_dump_cb *cb = cb_;
1405 cb->s->done(cb->state);
1412 recv_stats_request(struct datapath *dp, const struct sender *sender,
1415 const struct ofp_stats_request *rq = oh;
1416 size_t rq_len = ntohs(rq->header.length);
1417 struct stats_dump_cb *cb;
1421 type = ntohs(rq->type);
1422 if (type >= ARRAY_SIZE(stats) || !stats[type].dump) {
1423 VLOG_WARN("received stats request of unknown type %d", type);
1427 cb = xmalloc(sizeof *cb);
1429 cb->rq = xmemdup(rq, rq_len);
1430 cb->sender = *sender;
1431 cb->s = &stats[type];
1434 body_len = rq_len - offsetof(struct ofp_stats_request, body);
1435 if (body_len < cb->s->min_body || body_len > cb->s->max_body) {
1436 VLOG_WARN("stats request type %d with bad body length %d",
1443 err = cb->s->init(dp, rq->body, body_len, &cb->state);
1445 VLOG_WARN("failed initialization of stats request type %d: %s",
1446 type, strerror(-err));
1451 remote_start_dump(sender->remote, stats_dump, stats_done, cb);
1461 recv_echo_request(struct datapath *dp, const struct sender *sender,
1464 return send_openflow_buffer(dp, make_echo_reply(oh), sender);
1468 recv_echo_reply(struct datapath *dp UNUSED, const struct sender *sender UNUSED,
1469 const void *oh UNUSED)
1474 /* 'msg', which is 'length' bytes long, was received from the control path.
1475 * Apply it to 'chain'. */
1477 fwd_control_input(struct datapath *dp, const struct sender *sender,
1478 const void *msg, size_t length)
1480 struct openflow_packet {
1482 int (*handler)(struct datapath *, const struct sender *, const void *);
1485 static const struct openflow_packet packets[] = {
1486 [OFPT_FEATURES_REQUEST] = {
1487 sizeof (struct ofp_header),
1488 recv_features_request,
1490 [OFPT_GET_CONFIG_REQUEST] = {
1491 sizeof (struct ofp_header),
1492 recv_get_config_request,
1494 [OFPT_SET_CONFIG] = {
1495 sizeof (struct ofp_switch_config),
1498 [OFPT_PACKET_OUT] = {
1499 sizeof (struct ofp_packet_out),
1503 sizeof (struct ofp_flow_mod),
1507 sizeof (struct ofp_port_mod),
1510 [OFPT_STATS_REQUEST] = {
1511 sizeof (struct ofp_stats_request),
1514 [OFPT_ECHO_REQUEST] = {
1515 sizeof (struct ofp_header),
1518 [OFPT_ECHO_REPLY] = {
1519 sizeof (struct ofp_header),
1524 const struct openflow_packet *pkt;
1525 struct ofp_header *oh;
1527 oh = (struct ofp_header *) msg;
1528 assert(oh->version == OFP_VERSION);
1529 if (oh->type >= ARRAY_SIZE(packets) || ntohs(oh->length) > length)
1532 pkt = &packets[oh->type];
1535 if (length < pkt->min_size)
1538 return pkt->handler(dp, sender, msg);
1541 /* Packet buffering. */
1543 #define OVERWRITE_SECS 1
1545 struct packet_buffer {
1546 struct buffer *buffer;
1551 static struct packet_buffer buffers[N_PKT_BUFFERS];
1552 static unsigned int buffer_idx;
1554 uint32_t save_buffer(struct buffer *buffer)
1556 struct packet_buffer *p;
1559 buffer_idx = (buffer_idx + 1) & PKT_BUFFER_MASK;
1560 p = &buffers[buffer_idx];
1562 /* Don't buffer packet if existing entry is less than
1563 * OVERWRITE_SECS old. */
1564 if (time(0) < p->timeout) { /* FIXME */
1567 buffer_delete(p->buffer);
1570 /* Don't use maximum cookie value since the all-bits-1 id is
1572 if (++p->cookie >= (1u << PKT_COOKIE_BITS) - 1)
1574 p->buffer = buffer_clone(buffer); /* FIXME */
1575 p->timeout = time(0) + OVERWRITE_SECS; /* FIXME */
1576 id = buffer_idx | (p->cookie << PKT_BUFFER_BITS);
1581 static struct buffer *retrieve_buffer(uint32_t id)
1583 struct buffer *buffer = NULL;
1584 struct packet_buffer *p;
1586 p = &buffers[id & PKT_BUFFER_MASK];
1587 if (p->cookie == id >> PKT_BUFFER_BITS) {
1591 printf("cookie mismatch: %x != %x\n",
1592 id >> PKT_BUFFER_BITS, p->cookie);
1598 static void discard_buffer(uint32_t id)
1600 struct packet_buffer *p;
1602 p = &buffers[id & PKT_BUFFER_MASK];
1603 if (p->cookie == id >> PKT_BUFFER_BITS) {
1604 buffer_delete(p->buffer);