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>
46 #include "poll-loop.h"
52 #define THIS_MODULE VLM_datapath
55 #define BRIDGE_PORT_NO_FLOOD 0x00000001
57 /* Capabilities supported by this implementation. */
58 #define OFP_SUPPORTED_CAPABILITIES (OFPC_MULTI_PHY_TX)
60 /* Actions supported by this implementation. */
61 #define OFP_SUPPORTED_ACTIONS ( (1 << OFPAT_OUTPUT) \
62 | (1 << OFPAT_SET_DL_VLAN) \
63 | (1 << OFPAT_SET_DL_SRC) \
64 | (1 << OFPAT_SET_DL_DST) \
65 | (1 << OFPAT_SET_NW_SRC) \
66 | (1 << OFPAT_SET_NW_DST) \
67 | (1 << OFPAT_SET_TP_SRC) \
68 | (1 << OFPAT_SET_TP_DST) )
73 struct netdev *netdev;
74 struct list node; /* Element in datapath.ports. */
75 unsigned long long int rx_count, tx_count, drop_count;
78 /* The origin of a received OpenFlow message, to enable sending a reply. */
80 struct remote *remote; /* The device that sent the message. */
81 uint32_t xid; /* The OpenFlow transaction ID. */
84 /* A connection to a controller or a management device. */
89 /* Support for reliable, multi-message replies to requests.
91 * If an incoming request needs to have a reliable reply that might
92 * require multiple messages, it can use remote_start_dump() to set up
93 * a callback that will be called as buffer space for replies. */
94 int (*cb_dump)(struct datapath *, void *aux);
95 void (*cb_done)(void *aux);
100 /* Remote connections. */
101 struct remote *controller; /* Connection to controller. */
102 struct list remotes; /* All connections (including controller). */
103 struct vconn *listen_vconn;
107 /* Unique identifier for this datapath */
110 struct sw_chain *chain; /* Forwarding rules. */
112 struct ofp_switch_config config;
115 struct sw_port ports[OFPP_MAX];
116 struct list port_list; /* List of ports, for flooding. */
119 static struct remote *remote_create(struct datapath *, struct rconn *);
120 static void remote_run(struct datapath *, struct remote *);
121 static void remote_wait(struct remote *);
122 static void remote_destroy(struct remote *);
124 void dp_output_port(struct datapath *, struct buffer *,
125 int in_port, int out_port);
126 void dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp);
127 void dp_output_control(struct datapath *, struct buffer *, int in_port,
128 size_t max_len, int reason);
129 static void send_flow_expired(struct datapath *, struct sw_flow *);
130 static void send_port_status(struct sw_port *p, uint8_t status);
131 static void del_switch_port(struct sw_port *p);
132 static void execute_actions(struct datapath *, struct buffer *,
133 int in_port, const struct sw_flow_key *,
134 const struct ofp_action *, int n_actions);
135 static void modify_vlan(struct buffer *buffer, const struct sw_flow_key *key,
136 const struct ofp_action *a);
137 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
138 uint8_t nw_proto, const struct ofp_action *a);
139 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
140 uint8_t nw_proto, const struct ofp_action *a);
142 /* Buffers are identified to userspace by a 31-bit opaque ID. We divide the ID
143 * into a buffer number (low bits) and a cookie (high bits). The buffer number
144 * is an index into an array of buffers. The cookie distinguishes between
145 * different packets that have occupied a single buffer. Thus, the more
146 * buffers we have, the lower-quality the cookie... */
147 #define PKT_BUFFER_BITS 8
148 #define N_PKT_BUFFERS (1 << PKT_BUFFER_BITS)
149 #define PKT_BUFFER_MASK (N_PKT_BUFFERS - 1)
151 #define PKT_COOKIE_BITS (32 - PKT_BUFFER_BITS)
153 void fwd_port_input(struct datapath *, struct buffer *, int in_port);
154 int fwd_control_input(struct datapath *, const struct sender *,
155 const void *, size_t);
157 uint32_t save_buffer(struct buffer *);
158 static struct buffer *retrieve_buffer(uint32_t id);
159 static void discard_buffer(uint32_t id);
161 static int port_no(struct datapath *dp, struct sw_port *p)
163 assert(p >= dp->ports && p < &dp->ports[ARRAY_SIZE(dp->ports)]);
164 return p - dp->ports;
167 /* Generates a unique datapath id. It incorporates the datapath index
168 * and a hardware address, if available. If not, it generates a random
172 gen_datapath_id(void)
174 /* Choose a random datapath id. */
180 for (i = 0; i < ETH_ADDR_LEN; i++) {
181 id |= (uint64_t)(rand() & 0xff) << (8*(ETH_ADDR_LEN-1 - i));
188 dp_new(struct datapath **dp_, uint64_t dpid, struct rconn *rconn)
192 dp = calloc(1, sizeof *dp);
197 dp->last_timeout = time(0);
198 list_init(&dp->remotes);
199 dp->controller = remote_create(dp, rconn);
200 dp->listen_vconn = NULL;
201 dp->id = dpid <= UINT64_C(0xffffffffffff) ? dpid : gen_datapath_id();
202 dp->chain = chain_create();
204 VLOG_ERR("could not create chain");
209 list_init(&dp->port_list);
210 dp->config.flags = 0;
211 dp->config.miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
217 dp_add_port(struct datapath *dp, const char *name)
219 struct netdev *netdev;
223 error = netdev_open(name, &netdev);
228 for (p = dp->ports; ; p++) {
229 if (p >= &dp->ports[ARRAY_SIZE(dp->ports)]) {
231 } else if (!p->netdev) {
241 list_push_back(&dp->port_list, &p->node);
243 /* Notify the ctlpath that this port has been added */
244 send_port_status(p, OFPPR_ADD);
250 dp_add_listen_vconn(struct datapath *dp, struct vconn *listen_vconn)
252 assert(!dp->listen_vconn);
253 dp->listen_vconn = listen_vconn;
257 dp_run(struct datapath *dp)
259 time_t now = time(0);
260 struct sw_port *p, *pn;
261 struct remote *r, *rn;
262 struct buffer *buffer = NULL;
264 if (now != dp->last_timeout) {
265 struct list deleted = LIST_INITIALIZER(&deleted);
266 struct sw_flow *f, *n;
268 chain_timeout(dp->chain, &deleted);
269 LIST_FOR_EACH_SAFE (f, n, struct sw_flow, node, &deleted) {
270 send_flow_expired(dp, f);
271 list_remove(&f->node);
274 dp->last_timeout = now;
276 poll_timer_wait(1000);
278 LIST_FOR_EACH_SAFE (p, pn, struct sw_port, node, &dp->port_list) {
282 /* Allocate buffer with some headroom to add headers in forwarding
283 * to the controller or adding a vlan tag, plus an extra 2 bytes to
284 * allow IP headers to be aligned on a 4-byte boundary. */
285 const int headroom = 128 + 2;
286 const int hard_header = VLAN_ETH_HEADER_LEN;
287 const int mtu = netdev_get_mtu(p->netdev);
288 buffer = buffer_new(headroom + hard_header + mtu);
289 buffer->data += headroom;
291 error = netdev_recv(p->netdev, buffer);
294 fwd_port_input(dp, buffer, port_no(dp, p));
296 } else if (error != EAGAIN) {
297 VLOG_ERR("Error receiving data from %s: %s",
298 netdev_get_name(p->netdev), strerror(error));
302 buffer_delete(buffer);
304 /* Talk to remotes. */
305 LIST_FOR_EACH_SAFE (r, rn, struct remote, node, &dp->remotes) {
308 if (dp->listen_vconn) {
310 struct vconn *new_vconn;
313 retval = vconn_accept(dp->listen_vconn, &new_vconn);
315 if (retval != EAGAIN) {
316 VLOG_WARN("accept failed (%s)", strerror(retval));
320 remote_create(dp, rconn_new_from_vconn("passive", 128, new_vconn));
326 remote_run(struct datapath *dp, struct remote *r)
332 /* Do some remote processing, but cap it at a reasonable amount so that
333 * other processing doesn't starve. */
334 for (i = 0; i < 50; i++) {
336 struct buffer *buffer;
337 struct ofp_header *oh;
339 buffer = rconn_recv(r->rconn);
344 if (buffer->size >= sizeof *oh) {
345 struct sender sender;
349 sender.xid = oh->xid;
350 fwd_control_input(dp, &sender, buffer->data, buffer->size);
352 VLOG_WARN("received too-short OpenFlow message");
354 buffer_delete(buffer);
356 if (!rconn_is_full(r->rconn)) {
357 int error = r->cb_dump(dp, r->cb_aux);
360 VLOG_WARN("dump callback error: %s", strerror(-error));
362 r->cb_done(r->cb_aux);
371 if (!rconn_is_alive(r->rconn)) {
377 remote_wait(struct remote *r)
379 rconn_run_wait(r->rconn);
380 rconn_recv_wait(r->rconn);
384 remote_destroy(struct remote *r)
387 if (r->cb_dump && r->cb_done) {
388 r->cb_done(r->cb_aux);
390 list_remove(&r->node);
391 rconn_destroy(r->rconn);
396 static struct remote *
397 remote_create(struct datapath *dp, struct rconn *rconn)
399 struct remote *remote = xmalloc(sizeof *remote);
400 list_push_back(&dp->remotes, &remote->node);
401 remote->rconn = rconn;
402 remote->cb_dump = NULL;
406 /* Starts a callback-based, reliable, possibly multi-message reply to a
407 * request made by 'remote'.
409 * 'dump' designates a function that will be called when the 'remote' send
410 * queue has an empty slot. It should compose a message and send it on
411 * 'remote'. On success, it should return 1 if it should be called again when
412 * another send queue slot opens up, 0 if its transmissions are complete, or a
413 * negative errno value on failure.
415 * 'done' designates a function to clean up any resources allocated for the
416 * dump. It must handle being called before the dump is complete (which will
417 * happen if 'remote' is closed unexpectedly).
419 * 'aux' is passed to 'dump' and 'done'. */
421 remote_start_dump(struct remote *remote,
422 int (*dump)(struct datapath *, void *),
423 void (*done)(void *),
426 assert(!remote->cb_dump);
427 remote->cb_dump = dump;
428 remote->cb_done = done;
429 remote->cb_aux = aux;
433 dp_wait(struct datapath *dp)
438 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
439 netdev_recv_wait(p->netdev);
441 LIST_FOR_EACH (r, struct remote, node, &dp->remotes) {
444 if (dp->listen_vconn) {
445 vconn_accept_wait(dp->listen_vconn);
449 /* Delete 'p' from switch. */
451 del_switch_port(struct sw_port *p)
453 send_port_status(p, OFPPR_DELETE);
454 netdev_close(p->netdev);
456 list_remove(&p->node);
460 dp_destroy(struct datapath *dp)
462 struct sw_port *p, *n;
468 LIST_FOR_EACH_SAFE (p, n, struct sw_port, node, &dp->port_list) {
471 chain_destroy(dp->chain);
476 flood(struct datapath *dp, struct buffer *buffer, int in_port)
482 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
483 if (port_no(dp, p) == in_port || p->flags & BRIDGE_PORT_NO_FLOOD) {
486 if (prev_port != -1) {
487 dp_output_port(dp, buffer_clone(buffer), in_port, prev_port);
489 prev_port = port_no(dp, p);
492 dp_output_port(dp, buffer, in_port, prev_port);
494 buffer_delete(buffer);
500 output_packet(struct datapath *dp, struct buffer *buffer, int out_port)
502 if (out_port >= 0 && out_port < OFPP_MAX) {
503 struct sw_port *p = &dp->ports[out_port];
504 if (p->netdev != NULL) {
505 if (!netdev_send(p->netdev, buffer)) {
514 buffer_delete(buffer);
515 /* FIXME: ratelimit */
516 VLOG_DBG("can't forward to bad port %d\n", out_port);
519 /* Takes ownership of 'buffer' and transmits it to 'out_port' on 'dp'.
522 dp_output_port(struct datapath *dp, struct buffer *buffer,
523 int in_port, int out_port)
527 if (out_port == OFPP_FLOOD) {
528 flood(dp, buffer, in_port);
529 } else if (out_port == OFPP_CONTROLLER) {
530 dp_output_control(dp, buffer, in_port, 0, OFPR_ACTION);
531 } else if (out_port == OFPP_TABLE) {
532 struct sw_flow_key key;
533 struct sw_flow *flow;
536 flow_extract(buffer, in_port, &key.flow);
537 flow = chain_lookup(dp->chain, &key);
539 flow_used(flow, buffer);
540 execute_actions(dp, buffer, in_port, &key,
541 flow->actions, flow->n_actions);
544 output_packet(dp, buffer, out_port);
549 alloc_openflow_buffer(struct datapath *dp, size_t openflow_len, uint8_t type,
550 const struct sender *sender, struct buffer **bufferp)
552 struct buffer *buffer;
553 struct ofp_header *oh;
555 buffer = *bufferp = buffer_new(openflow_len);
556 oh = buffer_put_uninit(buffer, openflow_len);
557 oh->version = OFP_VERSION;
559 oh->length = 0; /* Filled in by send_openflow_buffer(). */
560 oh->xid = sender ? sender->xid : 0;
565 send_openflow_buffer(struct datapath *dp, struct buffer *buffer,
566 const struct sender *sender)
568 struct remote *remote = sender ? sender->remote : dp->controller;
569 struct rconn *rconn = remote->rconn;
570 struct ofp_header *oh;
573 oh = buffer_at_assert(buffer, 0, sizeof *oh);
574 oh->length = htons(buffer->size);
576 retval = rconn_send(rconn, buffer);
578 VLOG_WARN("send to %s failed: %s",
579 rconn_get_name(rconn), strerror(retval));
580 buffer_delete(buffer);
585 /* Takes ownership of 'buffer' and transmits it to 'dp''s controller. If the
586 * packet can be saved in a buffer, then only the first max_len bytes of
587 * 'buffer' are sent; otherwise, all of 'buffer' is sent. 'reason' indicates
588 * why 'buffer' is being sent. 'max_len' sets the maximum number of bytes that
589 * the caller wants to be sent; a value of 0 indicates the entire packet should
592 dp_output_control(struct datapath *dp, struct buffer *buffer, int in_port,
593 size_t max_len, int reason)
595 struct ofp_packet_in *opi;
599 buffer_id = save_buffer(buffer);
600 total_len = buffer->size;
601 if (buffer_id != UINT32_MAX && buffer->size > max_len) {
602 buffer->size = max_len;
605 opi = buffer_push_uninit(buffer, offsetof(struct ofp_packet_in, data));
606 opi->header.version = OFP_VERSION;
607 opi->header.type = OFPT_PACKET_IN;
608 opi->header.length = htons(buffer->size);
609 opi->header.xid = htonl(0);
610 opi->buffer_id = htonl(buffer_id);
611 opi->total_len = htons(total_len);
612 opi->in_port = htons(in_port);
613 opi->reason = reason;
615 send_openflow_buffer(dp, buffer, NULL);
618 static void fill_port_desc(struct datapath *dp, struct sw_port *p,
619 struct ofp_phy_port *desc)
621 desc->port_no = htons(port_no(dp, p));
622 strncpy((char *) desc->name, netdev_get_name(p->netdev),
624 desc->name[sizeof desc->name - 1] = '\0';
625 memcpy(desc->hw_addr, netdev_get_etheraddr(p->netdev), ETH_ADDR_LEN);
626 desc->flags = htonl(p->flags);
627 desc->features = htonl(netdev_get_features(p->netdev));
628 desc->speed = htonl(netdev_get_speed(p->netdev));
632 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
634 struct buffer *buffer;
635 struct ofp_switch_features *ofr;
638 ofr = alloc_openflow_buffer(dp, sizeof *ofr, OFPT_FEATURES_REPLY,
640 ofr->datapath_id = htonll(dp->id);
641 ofr->n_exact = htonl(2 * TABLE_HASH_MAX_FLOWS);
642 ofr->n_compression = 0; /* Not supported */
643 ofr->n_general = htonl(TABLE_LINEAR_MAX_FLOWS);
644 ofr->buffer_mb = htonl(UINT32_MAX);
645 ofr->n_buffers = htonl(N_PKT_BUFFERS);
646 ofr->capabilities = htonl(OFP_SUPPORTED_CAPABILITIES);
647 ofr->actions = htonl(OFP_SUPPORTED_ACTIONS);
648 LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
649 struct ofp_phy_port *opp = buffer_put_uninit(buffer, sizeof *opp);
650 memset(opp, 0, sizeof *opp);
651 fill_port_desc(dp, p, opp);
653 send_openflow_buffer(dp, buffer, sender);
657 dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp)
661 p = &dp->ports[htons(opp->port_no)];
663 /* Make sure the port id hasn't changed since this was sent */
664 if (!p || memcmp(opp->hw_addr, netdev_get_etheraddr(p->netdev),
668 p->flags = htonl(opp->flags);
672 send_port_status(struct sw_port *p, uint8_t status)
674 struct buffer *buffer;
675 struct ofp_port_status *ops;
676 ops = alloc_openflow_buffer(p->dp, sizeof *ops, OFPT_PORT_STATUS, NULL,
678 ops->reason = status;
679 memset(ops->pad, 0, sizeof ops->pad);
680 fill_port_desc(p->dp, p, &ops->desc);
682 send_openflow_buffer(p->dp, buffer, NULL);
686 send_flow_expired(struct datapath *dp, struct sw_flow *flow)
688 struct buffer *buffer;
689 struct ofp_flow_expired *ofe;
690 ofe = alloc_openflow_buffer(dp, sizeof *ofe, OFPT_FLOW_EXPIRED, NULL,
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 = alloc_openflow_buffer(dp, 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 'chain'. */
751 void fwd_port_input(struct datapath *dp, struct buffer *buffer, int in_port)
753 struct sw_flow_key key;
754 struct sw_flow *flow;
757 flow_extract(buffer, in_port, &key.flow);
758 flow = chain_lookup(dp->chain, &key);
760 flow_used(flow, buffer);
761 execute_actions(dp, buffer, in_port, &key,
762 flow->actions, flow->n_actions);
764 dp_output_control(dp, buffer, in_port, ntohs(dp->config.miss_send_len),
770 do_output(struct datapath *dp, struct buffer *buffer, int in_port,
771 size_t max_len, int out_port)
773 if (out_port != OFPP_CONTROLLER) {
774 dp_output_port(dp, buffer, in_port, out_port);
776 dp_output_control(dp, buffer, in_port, max_len, OFPR_ACTION);
781 execute_actions(struct datapath *dp, struct buffer *buffer,
782 int in_port, const struct sw_flow_key *key,
783 const struct ofp_action *actions, int n_actions)
785 /* Every output action needs a separate clone of 'buffer', but the common
786 * case is just a single output action, so that doing a clone and then
787 * freeing the original buffer is wasteful. So the following code is
788 * slightly obscure just to avoid that. */
790 size_t max_len=0; /* Initialze to make compiler happy */
795 eth_proto = ntohs(key->flow.dl_type);
797 for (i = 0; i < n_actions; i++) {
798 const struct ofp_action *a = &actions[i];
799 struct eth_header *eh = buffer->l2;
801 if (prev_port != -1) {
802 do_output(dp, buffer_clone(buffer), in_port, max_len, prev_port);
806 switch (ntohs(a->type)) {
808 prev_port = ntohs(a->arg.output.port);
809 max_len = ntohs(a->arg.output.max_len);
812 case OFPAT_SET_DL_VLAN:
813 modify_vlan(buffer, key, a);
816 case OFPAT_SET_DL_SRC:
817 memcpy(eh->eth_src, a->arg.dl_addr, sizeof eh->eth_src);
820 case OFPAT_SET_DL_DST:
821 memcpy(eh->eth_dst, a->arg.dl_addr, sizeof eh->eth_dst);
824 case OFPAT_SET_NW_SRC:
825 case OFPAT_SET_NW_DST:
826 modify_nh(buffer, eth_proto, key->flow.nw_proto, a);
829 case OFPAT_SET_TP_SRC:
830 case OFPAT_SET_TP_DST:
831 modify_th(buffer, eth_proto, key->flow.nw_proto, a);
839 do_output(dp, buffer, in_port, max_len, prev_port);
841 buffer_delete(buffer);
844 /* Returns the new checksum for a packet in which the checksum field previously
845 * contained 'old_csum' and in which a field that contained 'old_u16' was
846 * changed to contain 'new_u16'. */
848 recalc_csum16(uint16_t old_csum, uint16_t old_u16, uint16_t new_u16)
850 /* Ones-complement arithmetic is endian-independent, so this code does not
851 * use htons() or ntohs().
853 * See RFC 1624 for formula and explanation. */
854 uint16_t hc_complement = ~old_csum;
855 uint16_t m_complement = ~old_u16;
856 uint16_t m_prime = new_u16;
857 uint32_t sum = hc_complement + m_complement + m_prime;
858 uint16_t hc_prime_complement = sum + (sum >> 16);
859 return ~hc_prime_complement;
862 /* Returns the new checksum for a packet in which the checksum field previously
863 * contained 'old_csum' and in which a field that contained 'old_u32' was
864 * changed to contain 'new_u32'. */
866 recalc_csum32(uint16_t old_csum, uint32_t old_u32, uint32_t new_u32)
868 return recalc_csum16(recalc_csum16(old_csum, old_u32, new_u32),
869 old_u32 >> 16, new_u32 >> 16);
872 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
873 uint8_t nw_proto, const struct ofp_action *a)
875 if (eth_proto == ETH_TYPE_IP) {
876 struct ip_header *nh = buffer->l3;
877 uint32_t new, *field;
879 new = a->arg.nw_addr;
880 field = a->type == OFPAT_SET_NW_SRC ? &nh->ip_src : &nh->ip_dst;
881 if (nw_proto == IP_TYPE_TCP) {
882 struct tcp_header *th = buffer->l4;
883 th->tcp_csum = recalc_csum32(th->tcp_csum, *field, new);
884 } else if (nw_proto == IP_TYPE_UDP) {
885 struct udp_header *th = buffer->l4;
887 th->udp_csum = recalc_csum32(th->udp_csum, *field, new);
889 th->udp_csum = 0xffff;
893 nh->ip_csum = recalc_csum32(nh->ip_csum, *field, new);
898 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
899 uint8_t nw_proto, const struct ofp_action *a)
901 if (eth_proto == ETH_TYPE_IP) {
902 uint16_t new, *field;
906 if (nw_proto == IP_TYPE_TCP) {
907 struct tcp_header *th = buffer->l4;
908 field = a->type == OFPAT_SET_TP_SRC ? &th->tcp_src : &th->tcp_dst;
909 th->tcp_csum = recalc_csum16(th->tcp_csum, *field, new);
911 } else if (nw_proto == IP_TYPE_UDP) {
912 struct udp_header *th = buffer->l4;
913 field = a->type == OFPAT_SET_TP_SRC ? &th->udp_src : &th->udp_dst;
914 th->udp_csum = recalc_csum16(th->udp_csum, *field, new);
921 modify_vlan(struct buffer *buffer,
922 const struct sw_flow_key *key, const struct ofp_action *a)
924 uint16_t new_id = a->arg.vlan_id;
925 struct vlan_eth_header *veh;
927 if (new_id != OFP_VLAN_NONE) {
928 if (key->flow.dl_vlan != htons(OFP_VLAN_NONE)) {
929 /* Modify vlan id, but maintain other TCI values */
931 veh->veth_tci &= ~htons(VLAN_VID);
932 veh->veth_tci |= htons(new_id);
934 /* Insert new vlan id. */
935 struct eth_header *eh = buffer->l2;
936 struct vlan_eth_header tmp;
937 memcpy(tmp.veth_dst, eh->eth_dst, ETH_ADDR_LEN);
938 memcpy(tmp.veth_src, eh->eth_src, ETH_ADDR_LEN);
939 tmp.veth_type = htons(ETH_TYPE_VLAN);
940 tmp.veth_tci = new_id;
941 tmp.veth_next_type = eh->eth_type;
943 veh = buffer_push_uninit(buffer, VLAN_HEADER_LEN);
944 memcpy(veh, &tmp, sizeof tmp);
945 buffer->l2 -= VLAN_HEADER_LEN;
948 /* Remove an existing vlan header if it exists */
950 if (veh->veth_type == htons(ETH_TYPE_VLAN)) {
951 struct eth_header tmp;
953 memcpy(tmp.eth_dst, veh->veth_dst, ETH_ADDR_LEN);
954 memcpy(tmp.eth_src, veh->veth_src, ETH_ADDR_LEN);
955 tmp.eth_type = veh->veth_next_type;
957 buffer->size -= VLAN_HEADER_LEN;
958 buffer->data += VLAN_HEADER_LEN;
959 buffer->l2 += VLAN_HEADER_LEN;
960 memcpy(buffer->data, &tmp, sizeof tmp);
966 recv_features_request(struct datapath *dp, const struct sender *sender,
969 dp_send_features_reply(dp, sender);
974 recv_get_config_request(struct datapath *dp, const struct sender *sender,
977 struct buffer *buffer;
978 struct ofp_switch_config *osc;
980 osc = alloc_openflow_buffer(dp, sizeof *osc, OFPT_GET_CONFIG_REPLY,
983 assert(sizeof *osc == sizeof dp->config);
984 memcpy(((char *)osc) + sizeof osc->header,
985 ((char *)&dp->config) + sizeof dp->config.header,
986 sizeof dp->config - sizeof dp->config.header);
988 return send_openflow_buffer(dp, buffer, sender);
992 recv_set_config(struct datapath *dp, const struct sender *sender UNUSED,
995 const struct ofp_switch_config *osc = msg;
1001 recv_packet_out(struct datapath *dp, const struct sender *sender UNUSED,
1004 const struct ofp_packet_out *opo = msg;
1006 if (ntohl(opo->buffer_id) == (uint32_t) -1) {
1007 /* FIXME: can we avoid copying data here? */
1008 int data_len = ntohs(opo->header.length) - sizeof *opo;
1009 struct buffer *buffer = buffer_new(data_len);
1010 buffer_put(buffer, opo->u.data, data_len);
1011 dp_output_port(dp, buffer,
1012 ntohs(opo->in_port), ntohs(opo->out_port));
1014 struct sw_flow_key key;
1015 struct buffer *buffer;
1018 buffer = retrieve_buffer(ntohl(opo->buffer_id));
1023 n_acts = (ntohs(opo->header.length) - sizeof *opo)
1024 / sizeof *opo->u.actions;
1025 flow_extract(buffer, ntohs(opo->in_port), &key.flow);
1026 execute_actions(dp, buffer, ntohs(opo->in_port),
1027 &key, opo->u.actions, n_acts);
1033 recv_port_mod(struct datapath *dp, const struct sender *sender UNUSED,
1036 const struct ofp_port_mod *opm = msg;
1038 dp_update_port_flags(dp, &opm->desc);
1044 add_flow(struct datapath *dp, const struct ofp_flow_mod *ofm)
1046 int error = -ENOMEM;
1049 struct sw_flow *flow;
1052 /* To prevent loops, make sure there's no action to send to the
1053 * OFP_TABLE virtual port.
1055 n_acts = (ntohs(ofm->header.length) - sizeof *ofm) / sizeof *ofm->actions;
1056 for (i=0; i<n_acts; i++) {
1057 const struct ofp_action *a = &ofm->actions[i];
1059 if (a->type == htons(OFPAT_OUTPUT)
1060 && a->arg.output.port == htons(OFPP_TABLE)) {
1061 /* xxx Send fancy new error message? */
1066 /* Allocate memory. */
1067 flow = flow_alloc(n_acts);
1071 /* Fill out flow. */
1072 flow_extract_match(&flow->key, &ofm->match);
1073 flow->max_idle = ntohs(ofm->max_idle);
1074 flow->priority = flow->key.wildcards ? ntohs(ofm->priority) : -1;
1075 flow->timeout = time(0) + flow->max_idle; /* FIXME */
1076 flow->n_actions = n_acts;
1077 flow->created = time(0); /* FIXME */
1078 flow->byte_count = 0;
1079 flow->packet_count = 0;
1080 memcpy(flow->actions, ofm->actions, n_acts * sizeof *flow->actions);
1083 error = chain_insert(dp->chain, flow);
1085 goto error_free_flow;
1088 if (ntohl(ofm->buffer_id) != UINT32_MAX) {
1089 struct buffer *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
1091 struct sw_flow_key key;
1092 uint16_t in_port = ntohs(ofm->match.in_port);
1093 flow_used(flow, buffer);
1094 flow_extract(buffer, in_port, &key.flow);
1095 execute_actions(dp, buffer, in_port, &key, ofm->actions, n_acts);
1105 if (ntohl(ofm->buffer_id) != (uint32_t) -1)
1106 discard_buffer(ntohl(ofm->buffer_id));
1111 recv_flow(struct datapath *dp, const struct sender *sender UNUSED,
1114 const struct ofp_flow_mod *ofm = msg;
1115 uint16_t command = ntohs(ofm->command);
1117 if (command == OFPFC_ADD) {
1118 return add_flow(dp, ofm);
1119 } else if (command == OFPFC_DELETE) {
1120 struct sw_flow_key key;
1121 flow_extract_match(&key, &ofm->match);
1122 return chain_delete(dp->chain, &key, 0, 0) ? 0 : -ESRCH;
1123 } else if (command == OFPFC_DELETE_STRICT) {
1124 struct sw_flow_key key;
1126 flow_extract_match(&key, &ofm->match);
1127 priority = key.wildcards ? ntohs(ofm->priority) : -1;
1128 return chain_delete(dp->chain, &key, priority, 1) ? 0 : -ESRCH;
1134 struct flow_stats_state {
1136 struct sw_table_position position;
1137 struct ofp_flow_stats_request rq;
1140 struct buffer *buffer;
1143 #define MAX_FLOW_STATS_BYTES 4096
1145 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
1148 const struct ofp_flow_stats_request *fsr = body;
1149 struct flow_stats_state *s = xmalloc(sizeof *s);
1150 s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
1151 memset(&s->position, 0, sizeof s->position);
1157 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
1159 struct flow_stats_state *s = private;
1160 fill_flow_stats(s->buffer, flow, s->table_idx, s->now);
1161 return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1164 static int flow_stats_dump(struct datapath *dp, void *state,
1165 struct buffer *buffer)
1167 struct flow_stats_state *s = state;
1168 struct sw_flow_key match_key;
1170 flow_extract_match(&match_key, &s->rq.match);
1173 while (s->table_idx < dp->chain->n_tables
1174 && (s->rq.table_id == 0xff || s->rq.table_id == s->table_idx))
1176 struct sw_table *table = dp->chain->tables[s->table_idx];
1178 if (table->iterate(table, &match_key, &s->position,
1179 flow_stats_dump_callback, s))
1183 memset(&s->position, 0, sizeof s->position);
1185 return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1188 static void flow_stats_done(void *state)
1193 struct aggregate_stats_state {
1194 struct ofp_aggregate_stats_request rq;
1197 static int aggregate_stats_init(struct datapath *dp,
1198 const void *body, int body_len,
1201 const struct ofp_aggregate_stats_request *rq = body;
1202 struct aggregate_stats_state *s = xmalloc(sizeof *s);
1208 static int aggregate_stats_dump_callback(struct sw_flow *flow, void *private)
1210 struct ofp_aggregate_stats_reply *rpy = private;
1211 rpy->packet_count += flow->packet_count;
1212 rpy->byte_count += flow->byte_count;
1217 static int aggregate_stats_dump(struct datapath *dp, void *state,
1218 struct buffer *buffer)
1220 struct aggregate_stats_state *s = state;
1221 struct ofp_aggregate_stats_request *rq = &s->rq;
1222 struct ofp_aggregate_stats_reply *rpy;
1223 struct sw_table_position position;
1224 struct sw_flow_key match_key;
1227 rpy = buffer_put_uninit(buffer, sizeof *rpy);
1228 memset(rpy, 0, sizeof *rpy);
1230 flow_extract_match(&match_key, &rq->match);
1231 table_idx = rq->table_id == 0xff ? 0 : rq->table_id;
1232 memset(&position, 0, sizeof position);
1233 while (table_idx < dp->chain->n_tables
1234 && (rq->table_id == 0xff || rq->table_id == table_idx))
1236 struct sw_table *table = dp->chain->tables[table_idx];
1239 error = table->iterate(table, &match_key, &position,
1240 aggregate_stats_dump_callback, rpy);
1245 memset(&position, 0, sizeof position);
1248 rpy->packet_count = htonll(rpy->packet_count);
1249 rpy->byte_count = htonll(rpy->byte_count);
1250 rpy->flow_count = htonl(rpy->flow_count);
1254 static void aggregate_stats_done(void *state)
1259 static int table_stats_dump(struct datapath *dp, void *state,
1260 struct buffer *buffer)
1263 for (i = 0; i < dp->chain->n_tables; i++) {
1264 struct ofp_table_stats *ots = buffer_put_uninit(buffer, sizeof *ots);
1265 struct sw_table_stats stats;
1266 dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
1267 strncpy(ots->name, stats.name, sizeof ots->name);
1269 memset(ots->pad, 0, sizeof ots->pad);
1270 ots->max_entries = htonl(stats.max_flows);
1271 ots->active_count = htonl(stats.n_flows);
1272 ots->matched_count = htonll(0); /* FIXME */
1277 struct port_stats_state {
1281 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
1284 struct port_stats_state *s = xmalloc(sizeof *s);
1290 static int port_stats_dump(struct datapath *dp, void *state,
1291 struct buffer *buffer)
1293 struct port_stats_state *s = state;
1296 for (i = s->port; i < OFPP_MAX; i++) {
1297 struct sw_port *p = &dp->ports[i];
1298 struct ofp_port_stats *ops;
1302 ops = buffer_put_uninit(buffer, sizeof *ops);
1303 ops->port_no = htons(port_no(dp, p));
1304 memset(ops->pad, 0, sizeof ops->pad);
1305 ops->rx_count = htonll(p->rx_count);
1306 ops->tx_count = htonll(p->tx_count);
1307 ops->drop_count = htonll(p->drop_count);
1314 static void port_stats_done(void *state)
1320 /* Minimum and maximum acceptable number of bytes in body member of
1321 * struct ofp_stats_request. */
1322 size_t min_body, max_body;
1324 /* Prepares to dump some kind of statistics on 'dp'. 'body' and
1325 * 'body_len' are the 'body' member of the struct ofp_stats_request.
1326 * Returns zero if successful, otherwise a negative error code.
1327 * May initialize '*state' to state information. May be null if no
1328 * initialization is required.*/
1329 int (*init)(struct datapath *dp, const void *body, int body_len,
1332 /* Appends statistics for 'dp' to 'buffer', which initially contains a
1333 * struct ofp_stats_reply. On success, it should return 1 if it should be
1334 * called again later with another buffer, 0 if it is done, or a negative
1335 * errno value on failure. */
1336 int (*dump)(struct datapath *dp, void *state, struct buffer *buffer);
1338 /* Cleans any state created by the init or dump functions. May be null
1339 * if no cleanup is required. */
1340 void (*done)(void *state);
1343 static const struct stats_type stats[] = {
1345 sizeof(struct ofp_flow_stats_request),
1346 sizeof(struct ofp_flow_stats_request),
1351 [OFPST_AGGREGATE] = {
1352 sizeof(struct ofp_aggregate_stats_request),
1353 sizeof(struct ofp_aggregate_stats_request),
1354 aggregate_stats_init,
1355 aggregate_stats_dump,
1356 aggregate_stats_done
1374 struct stats_dump_cb {
1376 struct ofp_stats_request *rq;
1377 struct sender sender;
1378 const struct stats_type *s;
1383 stats_dump(struct datapath *dp, void *cb_)
1385 struct stats_dump_cb *cb = cb_;
1386 struct ofp_stats_reply *osr;
1387 struct buffer *buffer;
1394 osr = alloc_openflow_buffer(dp, sizeof *osr, OFPT_STATS_REPLY, &cb->sender,
1396 osr->type = htons(cb->s - stats);
1399 err = cb->s->dump(dp, cb->state, buffer);
1405 /* Buffer might have been reallocated, so find our data again. */
1406 osr = buffer_at_assert(buffer, 0, sizeof *osr);
1407 osr->flags = ntohs(OFPSF_REPLY_MORE);
1409 err2 = send_openflow_buffer(dp, buffer, &cb->sender);
1419 stats_done(void *cb_)
1421 struct stats_dump_cb *cb = cb_;
1424 cb->s->done(cb->state);
1431 recv_stats_request(struct datapath *dp, const struct sender *sender,
1434 const struct ofp_stats_request *rq = oh;
1435 size_t rq_len = ntohs(rq->header.length);
1436 struct stats_dump_cb *cb;
1440 type = ntohs(rq->type);
1441 if (type >= ARRAY_SIZE(stats) || !stats[type].dump) {
1442 VLOG_WARN("received stats request of unknown type %d", type);
1446 cb = xmalloc(sizeof *cb);
1448 cb->rq = xmemdup(rq, rq_len);
1449 cb->sender = *sender;
1450 cb->s = &stats[type];
1453 body_len = rq_len - offsetof(struct ofp_stats_request, body);
1454 if (body_len < cb->s->min_body || body_len > cb->s->max_body) {
1455 VLOG_WARN("stats request type %d with bad body length %d",
1462 err = cb->s->init(dp, rq->body, body_len, &cb->state);
1464 VLOG_WARN("failed initialization of stats request type %d: %s",
1465 type, strerror(-err));
1470 remote_start_dump(sender->remote, stats_dump, stats_done, cb);
1479 /* 'msg', which is 'length' bytes long, was received from the control path.
1480 * Apply it to 'chain'. */
1482 fwd_control_input(struct datapath *dp, const struct sender *sender,
1483 const void *msg, size_t length)
1485 struct openflow_packet {
1487 int (*handler)(struct datapath *, const struct sender *, const void *);
1490 static const struct openflow_packet packets[] = {
1491 [OFPT_FEATURES_REQUEST] = {
1492 sizeof (struct ofp_header),
1493 recv_features_request,
1495 [OFPT_GET_CONFIG_REQUEST] = {
1496 sizeof (struct ofp_header),
1497 recv_get_config_request,
1499 [OFPT_SET_CONFIG] = {
1500 sizeof (struct ofp_switch_config),
1503 [OFPT_PACKET_OUT] = {
1504 sizeof (struct ofp_packet_out),
1508 sizeof (struct ofp_flow_mod),
1512 sizeof (struct ofp_port_mod),
1515 [OFPT_STATS_REQUEST] = {
1516 sizeof (struct ofp_stats_request),
1521 const struct openflow_packet *pkt;
1522 struct ofp_header *oh;
1524 oh = (struct ofp_header *) msg;
1525 if (oh->version != OFP_VERSION || oh->type >= ARRAY_SIZE(packets)
1526 || ntohs(oh->length) > length)
1529 pkt = &packets[oh->type];
1532 if (length < pkt->min_size)
1535 return pkt->handler(dp, sender, msg);
1538 /* Packet buffering. */
1540 #define OVERWRITE_SECS 1
1542 struct packet_buffer {
1543 struct buffer *buffer;
1548 static struct packet_buffer buffers[N_PKT_BUFFERS];
1549 static unsigned int buffer_idx;
1551 uint32_t save_buffer(struct buffer *buffer)
1553 struct packet_buffer *p;
1556 buffer_idx = (buffer_idx + 1) & PKT_BUFFER_MASK;
1557 p = &buffers[buffer_idx];
1559 /* Don't buffer packet if existing entry is less than
1560 * OVERWRITE_SECS old. */
1561 if (time(0) < p->timeout) { /* FIXME */
1564 buffer_delete(p->buffer);
1567 /* Don't use maximum cookie value since the all-bits-1 id is
1569 if (++p->cookie >= (1u << PKT_COOKIE_BITS) - 1)
1571 p->buffer = buffer_clone(buffer); /* FIXME */
1572 p->timeout = time(0) + OVERWRITE_SECS; /* FIXME */
1573 id = buffer_idx | (p->cookie << PKT_BUFFER_BITS);
1578 static struct buffer *retrieve_buffer(uint32_t id)
1580 struct buffer *buffer = NULL;
1581 struct packet_buffer *p;
1583 p = &buffers[id & PKT_BUFFER_MASK];
1584 if (p->cookie == id >> PKT_BUFFER_BITS) {
1588 printf("cookie mismatch: %x != %x\n",
1589 id >> PKT_BUFFER_BITS, p->cookie);
1595 static void discard_buffer(uint32_t id)
1597 struct packet_buffer *p;
1599 p = &buffers[id & PKT_BUFFER_MASK];
1600 if (p->cookie == id >> PKT_BUFFER_BITS) {
1601 buffer_delete(p->buffer);