- Add support for OpenFlow error message type.
[sliver-openvswitch.git] / switch / datapath.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  * 
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:
16  * 
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  * 
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
27  * SOFTWARE.
28  * 
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.
32  */
33
34 #include "datapath.h"
35 #include <arpa/inet.h>
36 #include <assert.h>
37 #include <errno.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include "buffer.h"
41 #include "chain.h"
42 #include "flow.h"
43 #include "netdev.h"
44 #include "packets.h"
45 #include "poll-loop.h"
46 #include "rconn.h"
47 #include "vconn.h"
48 #include "table.h"
49 #include "xtoxll.h"
50
51 #define THIS_MODULE VLM_datapath
52 #include "vlog.h"
53
54 #define BRIDGE_PORT_NO_FLOOD    0x00000001
55
56 /* Capabilities supported by this implementation. */
57 #define OFP_SUPPORTED_CAPABILITIES (OFPC_MULTI_PHY_TX)
58
59 /* Actions supported by this implementation. */
60 #define OFP_SUPPORTED_ACTIONS ( (1 << OFPAT_OUTPUT)         \
61                                 | (1 << OFPAT_SET_DL_VLAN)  \
62                                 | (1 << OFPAT_SET_DL_SRC)   \
63                                 | (1 << OFPAT_SET_DL_DST)   \
64                                 | (1 << OFPAT_SET_NW_SRC)   \
65                                 | (1 << OFPAT_SET_NW_DST)   \
66                                 | (1 << OFPAT_SET_TP_SRC)   \
67                                 | (1 << OFPAT_SET_TP_DST) )
68
69 struct sw_port {
70     uint32_t flags;
71     struct datapath *dp;
72     struct netdev *netdev;
73     struct list node; /* Element in datapath.ports. */
74     unsigned long long int rx_count, tx_count, drop_count;
75 };
76
77 /* A connection to a controller or a management device. */
78 struct remote {
79     struct list node;
80     struct rconn *rconn;
81 };
82
83 /* The origin of a received OpenFlow message, to enable sending a reply. */
84 struct sender {
85     struct remote *remote;      /* The device that sent the message. */
86     uint32_t xid;               /* The OpenFlow transaction ID. */
87 };
88
89 struct datapath {
90     /* Remote connections. */
91     struct remote *controller;  /* Connection to controller. */
92     struct list remotes;        /* All connections (including controller). */
93     struct vconn *listen_vconn;
94
95     time_t last_timeout;
96
97     /* Unique identifier for this datapath */
98     uint64_t  id;
99
100     struct sw_chain *chain;  /* Forwarding rules. */
101
102     struct ofp_switch_config config;
103
104     /* Switch ports. */
105     struct sw_port ports[OFPP_MAX];
106     struct list port_list; /* List of ports, for flooding. */
107 };
108
109 static struct remote *remote_create(struct datapath *, struct rconn *);
110 static void remote_run(struct datapath *, struct remote *);
111 static void remote_wait(struct remote *);
112 static void remote_destroy(struct remote *);
113
114 void dp_output_port(struct datapath *, struct buffer *,
115                     int in_port, int out_port);
116 void dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp);
117 void dp_output_control(struct datapath *, struct buffer *, int in_port,
118                        size_t max_len, int reason);
119 static void send_flow_expired(struct datapath *, struct sw_flow *);
120 static void send_port_status(struct sw_port *p, uint8_t status);
121 static void del_switch_port(struct sw_port *p);
122 static void execute_actions(struct datapath *, struct buffer *,
123                             int in_port, const struct sw_flow_key *,
124                             const struct ofp_action *, int n_actions);
125 static void modify_vlan(struct buffer *buffer, const struct sw_flow_key *key,
126                         const struct ofp_action *a);
127 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
128                       uint8_t nw_proto, const struct ofp_action *a);
129 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
130                           uint8_t nw_proto, const struct ofp_action *a);
131
132 /* Buffers are identified to userspace by a 31-bit opaque ID.  We divide the ID
133  * into a buffer number (low bits) and a cookie (high bits).  The buffer number
134  * is an index into an array of buffers.  The cookie distinguishes between
135  * different packets that have occupied a single buffer.  Thus, the more
136  * buffers we have, the lower-quality the cookie... */
137 #define PKT_BUFFER_BITS 8
138 #define N_PKT_BUFFERS (1 << PKT_BUFFER_BITS)
139 #define PKT_BUFFER_MASK (N_PKT_BUFFERS - 1)
140
141 #define PKT_COOKIE_BITS (32 - PKT_BUFFER_BITS)
142
143 void fwd_port_input(struct datapath *, struct buffer *, int in_port);
144 int fwd_control_input(struct datapath *, const struct sender *,
145                       const void *, size_t);
146
147 uint32_t save_buffer(struct buffer *);
148 static struct buffer *retrieve_buffer(uint32_t id);
149 static void discard_buffer(uint32_t id);
150
151 static int port_no(struct datapath *dp, struct sw_port *p) 
152 {
153     assert(p >= dp->ports && p < &dp->ports[ARRAY_SIZE(dp->ports)]);
154     return p - dp->ports;
155 }
156
157 /* Generates a unique datapath id.  It incorporates the datapath index
158  * and a hardware address, if available.  If not, it generates a random
159  * one.
160  */
161 static uint64_t
162 gen_datapath_id(void)
163 {
164     /* Choose a random datapath id. */
165     uint64_t id = 0;
166     int i;
167
168     srand(time(0));
169
170     for (i = 0; i < ETH_ADDR_LEN; i++) {
171         id |= (uint64_t)(rand() & 0xff) << (8*(ETH_ADDR_LEN-1 - i));
172     }
173
174     return id;
175 }
176
177 int
178 dp_new(struct datapath **dp_, uint64_t dpid, struct rconn *rconn)
179 {
180     struct datapath *dp;
181
182     dp = calloc(1, sizeof *dp);
183     if (!dp) {
184         return ENOMEM;
185     }
186
187     dp->last_timeout = time(0);
188     list_init(&dp->remotes);
189     dp->controller = remote_create(dp, rconn);
190     dp->listen_vconn = NULL;
191     dp->id = dpid <= UINT64_C(0xffffffffffff) ? dpid : gen_datapath_id();
192     dp->chain = chain_create();
193     if (!dp->chain) {
194         VLOG_ERR("could not create chain");
195         free(dp);
196         return ENOMEM;
197     }
198
199     list_init(&dp->port_list);
200     dp->config.flags = 0;
201     dp->config.miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
202     *dp_ = dp;
203     return 0;
204 }
205
206 int
207 dp_add_port(struct datapath *dp, const char *name)
208 {
209     struct netdev *netdev;
210     struct sw_port *p;
211     int error;
212
213     error = netdev_open(name, &netdev);
214     if (error) {
215         return error;
216     }
217
218     for (p = dp->ports; ; p++) {
219         if (p >= &dp->ports[ARRAY_SIZE(dp->ports)]) {
220             return EXFULL;
221         } else if (!p->netdev) {
222             break;
223         }
224     }
225
226     p->dp = dp;
227     p->netdev = netdev;
228     p->tx_count = 0;
229     p->rx_count = 0;
230     p->drop_count = 0;
231     list_push_back(&dp->port_list, &p->node);
232
233     /* Notify the ctlpath that this port has been added */
234     send_port_status(p, OFPPR_ADD);
235
236     return 0;
237 }
238
239 void
240 dp_add_listen_vconn(struct datapath *dp, struct vconn *listen_vconn)
241 {
242     assert(!dp->listen_vconn);
243     dp->listen_vconn = listen_vconn;
244 }
245
246 void
247 dp_run(struct datapath *dp) 
248 {
249     time_t now = time(0);
250     struct sw_port *p, *pn;
251     struct remote *r, *rn;
252     struct buffer *buffer = NULL;
253
254     if (now != dp->last_timeout) {
255         struct list deleted = LIST_INITIALIZER(&deleted);
256         struct sw_flow *f, *n;
257
258         chain_timeout(dp->chain, &deleted);
259         LIST_FOR_EACH_SAFE (f, n, struct sw_flow, node, &deleted) {
260             send_flow_expired(dp, f);
261             list_remove(&f->node);
262             flow_free(f);
263         }
264         dp->last_timeout = now;
265     }
266     poll_timer_wait(1000);
267     
268     LIST_FOR_EACH_SAFE (p, pn, struct sw_port, node, &dp->port_list) {
269         int error;
270
271         if (!buffer) {
272             /* Allocate buffer with some headroom to add headers in forwarding
273              * to the controller or adding a vlan tag, plus an extra 2 bytes to
274              * allow IP headers to be aligned on a 4-byte boundary.  */
275             const int headroom = 128 + 2;
276             const int hard_header = VLAN_ETH_HEADER_LEN;
277             const int mtu = netdev_get_mtu(p->netdev);
278             buffer = buffer_new(headroom + hard_header + mtu);
279             buffer->data += headroom;
280         }
281         error = netdev_recv(p->netdev, buffer);
282         if (!error) {
283             p->rx_count++;
284             fwd_port_input(dp, buffer, port_no(dp, p));
285             buffer = NULL;
286         } else if (error != EAGAIN) {
287             VLOG_ERR("Error receiving data from %s: %s",
288                      netdev_get_name(p->netdev), strerror(error));
289             del_switch_port(p);
290         }
291     }
292     buffer_delete(buffer);
293
294     /* Talk to remotes. */
295     LIST_FOR_EACH_SAFE (r, rn, struct remote, node, &dp->remotes) {
296         remote_run(dp, r);
297     }
298     if (dp->listen_vconn) {
299         for (;;) {
300             struct vconn *new_vconn;
301             int retval;
302
303             retval = vconn_accept(dp->listen_vconn, &new_vconn);
304             if (retval) {
305                 if (retval != EAGAIN) {
306                     VLOG_WARN("accept failed (%s)", strerror(retval));
307                 }
308                 break;
309             }
310             remote_create(dp, rconn_new_from_vconn("passive", 128, new_vconn));
311         }
312     }
313 }
314
315 static void
316 remote_run(struct datapath *dp, struct remote *r)
317 {
318     int i;
319
320     rconn_run(r->rconn);
321
322     /* Process a number of commands from the remote, but cap them at a
323      * reasonable number so that other processing doesn't starve. */
324     for (i = 0; i < 50; i++) {
325         struct buffer *buffer;
326         struct ofp_header *oh;
327
328         buffer = rconn_recv(r->rconn);
329         if (!buffer) {
330             break;
331         }
332
333         if (buffer->size >= sizeof *oh) {
334             struct sender sender;
335
336             oh = buffer->data;
337             sender.remote = r;
338             sender.xid = oh->xid;
339             fwd_control_input(dp, &sender, buffer->data, buffer->size);
340         } else {
341             VLOG_WARN("received too-short OpenFlow message"); 
342         }
343         buffer_delete(buffer);
344     }
345
346     if (!rconn_is_alive(r->rconn)) {
347         remote_destroy(r);
348     }
349 }
350
351 static void
352 remote_wait(struct remote *r) 
353 {
354     rconn_run_wait(r->rconn);
355     rconn_recv_wait(r->rconn);
356 }
357
358 static void
359 remote_destroy(struct remote *r)
360 {
361     if (r) {
362         list_remove(&r->node);
363         rconn_destroy(r->rconn);
364         free(r);
365     }
366 }
367
368 static struct remote *
369 remote_create(struct datapath *dp, struct rconn *rconn) 
370 {
371     struct remote *remote = xmalloc(sizeof *remote);
372     list_push_back(&dp->remotes, &remote->node);
373     remote->rconn = rconn;
374     return remote;
375 }
376
377 void
378 dp_wait(struct datapath *dp) 
379 {
380     struct sw_port *p;
381     struct remote *r;
382
383     LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
384         netdev_recv_wait(p->netdev);
385     }
386     LIST_FOR_EACH (r, struct remote, node, &dp->remotes) {
387         remote_wait(r);
388     }
389     if (dp->listen_vconn) {
390         vconn_accept_wait(dp->listen_vconn);
391     }
392 }
393
394 /* Delete 'p' from switch. */
395 static void
396 del_switch_port(struct sw_port *p)
397 {
398     send_port_status(p, OFPPR_DELETE);
399     netdev_close(p->netdev);
400     p->netdev = NULL;
401     list_remove(&p->node);
402 }
403
404 void
405 dp_destroy(struct datapath *dp)
406 {
407     struct sw_port *p, *n;
408
409     if (!dp) {
410         return;
411     }
412
413     LIST_FOR_EACH_SAFE (p, n, struct sw_port, node, &dp->port_list) {
414         del_switch_port(p); 
415     }
416     chain_destroy(dp->chain);
417     free(dp);
418 }
419
420 static int
421 flood(struct datapath *dp, struct buffer *buffer, int in_port)
422 {
423     struct sw_port *p;
424     int prev_port;
425
426     prev_port = -1;
427     LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
428         if (port_no(dp, p) == in_port || p->flags & BRIDGE_PORT_NO_FLOOD) {
429             continue;
430         }
431         if (prev_port != -1) {
432             dp_output_port(dp, buffer_clone(buffer), in_port, prev_port);
433         }
434         prev_port = port_no(dp, p);
435     }
436     if (prev_port != -1)
437         dp_output_port(dp, buffer, in_port, prev_port);
438     else
439         buffer_delete(buffer);
440
441     return 0;
442 }
443
444 void
445 output_packet(struct datapath *dp, struct buffer *buffer, int out_port) 
446 {
447     if (out_port >= 0 && out_port < OFPP_MAX) { 
448         struct sw_port *p = &dp->ports[out_port];
449         if (p->netdev != NULL) {
450             if (!netdev_send(p->netdev, buffer)) {
451                 p->tx_count++;
452             } else {
453                 p->drop_count++;
454             }
455             return;
456         }
457     }
458
459     buffer_delete(buffer);
460     /* FIXME: ratelimit */
461     VLOG_DBG("can't forward to bad port %d\n", out_port);
462 }
463
464 /* Takes ownership of 'buffer' and transmits it to 'out_port' on 'dp'.
465  */
466 void
467 dp_output_port(struct datapath *dp, struct buffer *buffer,
468                int in_port, int out_port)
469 {
470
471     assert(buffer);
472     if (out_port == OFPP_FLOOD) {
473         flood(dp, buffer, in_port); 
474     } else if (out_port == OFPP_CONTROLLER) {
475         dp_output_control(dp, buffer, in_port, 0, OFPR_ACTION); 
476     } else {
477         output_packet(dp, buffer, out_port);
478     }
479 }
480
481 static void *
482 alloc_openflow_buffer(struct datapath *dp, size_t openflow_len, uint8_t type,
483                       const struct sender *sender, struct buffer **bufferp)
484 {
485         struct buffer *buffer;
486         struct ofp_header *oh;
487
488         buffer = *bufferp = buffer_new(openflow_len);
489         oh = buffer_put_uninit(buffer, openflow_len);
490         oh->version = OFP_VERSION;
491         oh->type = type;
492         oh->length = 0;             /* Filled in by send_openflow_buffer(). */
493         oh->xid = sender ? sender->xid : 0;
494         return oh;
495 }
496
497 static int
498 send_openflow_buffer(struct datapath *dp, struct buffer *buffer,
499                      const struct sender *sender)
500 {
501     struct remote *remote = sender ? sender->remote : dp->controller;
502     struct rconn *rconn = remote->rconn;
503     struct ofp_header *oh;
504     int retval;
505
506     oh = buffer_at_assert(buffer, 0, sizeof *oh);
507     oh->length = htons(buffer->size);
508
509     retval = rconn_send(rconn, buffer);
510     if (retval) {
511         VLOG_WARN("send to %s failed: %s",
512                   rconn_get_name(rconn), strerror(retval));
513         buffer_delete(buffer);
514     }
515     return retval;
516 }
517
518 /* Takes ownership of 'buffer' and transmits it to 'dp''s controller.  If the
519  * packet can be saved in a buffer, then only the first max_len bytes of
520  * 'buffer' are sent; otherwise, all of 'buffer' is sent.  'reason' indicates
521  * why 'buffer' is being sent. 'max_len' sets the maximum number of bytes that
522  * the caller wants to be sent; a value of 0 indicates the entire packet should
523  * be sent. */
524 void
525 dp_output_control(struct datapath *dp, struct buffer *buffer, int in_port,
526                   size_t max_len, int reason)
527 {
528     struct ofp_packet_in *opi;
529     size_t total_len;
530     uint32_t buffer_id;
531
532     buffer_id = save_buffer(buffer);
533     total_len = buffer->size;
534     if (buffer_id != UINT32_MAX && buffer->size > max_len) {
535         buffer->size = max_len;
536     }
537
538     opi = buffer_push_uninit(buffer, offsetof(struct ofp_packet_in, data));
539     opi->header.version = OFP_VERSION;
540     opi->header.type    = OFPT_PACKET_IN;
541     opi->header.length  = htons(buffer->size);
542     opi->header.xid     = htonl(0);
543     opi->buffer_id      = htonl(buffer_id);
544     opi->total_len      = htons(total_len);
545     opi->in_port        = htons(in_port);
546     opi->reason         = reason;
547     opi->pad            = 0;
548     send_openflow_buffer(dp, buffer, NULL);
549 }
550
551 static void fill_port_desc(struct datapath *dp, struct sw_port *p,
552                            struct ofp_phy_port *desc)
553 {
554     desc->port_no = htons(port_no(dp, p));
555     strncpy((char *) desc->name, netdev_get_name(p->netdev),
556             sizeof desc->name);
557     desc->name[sizeof desc->name - 1] = '\0';
558     memcpy(desc->hw_addr, netdev_get_etheraddr(p->netdev), ETH_ADDR_LEN);
559     desc->flags = htonl(p->flags);
560     desc->features = htonl(netdev_get_features(p->netdev));
561     desc->speed = htonl(netdev_get_speed(p->netdev));
562 }
563
564 static void
565 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
566 {
567     struct buffer *buffer;
568     struct ofp_switch_features *ofr;
569     struct sw_port *p;
570
571     ofr = alloc_openflow_buffer(dp, sizeof *ofr, OFPT_FEATURES_REPLY,
572                                 sender, &buffer);
573     ofr->datapath_id    = htonll(dp->id); 
574     ofr->n_exact        = htonl(2 * TABLE_HASH_MAX_FLOWS);
575     ofr->n_compression  = 0;         /* Not supported */
576     ofr->n_general      = htonl(TABLE_LINEAR_MAX_FLOWS);
577     ofr->buffer_mb      = htonl(UINT32_MAX);
578     ofr->n_buffers      = htonl(N_PKT_BUFFERS);
579     ofr->capabilities   = htonl(OFP_SUPPORTED_CAPABILITIES);
580     ofr->actions        = htonl(OFP_SUPPORTED_ACTIONS);
581     LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
582         struct ofp_phy_port *opp = buffer_put_uninit(buffer, sizeof *opp);
583         memset(opp, 0, sizeof *opp);
584         fill_port_desc(dp, p, opp);
585     }
586     send_openflow_buffer(dp, buffer, sender);
587 }
588
589 void
590 dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp)
591 {
592     struct sw_port *p;
593
594     p = &dp->ports[htons(opp->port_no)];
595
596     /* Make sure the port id hasn't changed since this was sent */
597     if (!p || memcmp(opp->hw_addr, netdev_get_etheraddr(p->netdev),
598                      ETH_ADDR_LEN) != 0) 
599         return;
600         
601     p->flags = htonl(opp->flags);
602 }
603
604 static void
605 send_port_status(struct sw_port *p, uint8_t status) 
606 {
607     struct buffer *buffer;
608     struct ofp_port_status *ops;
609     ops = alloc_openflow_buffer(p->dp, sizeof *ops, OFPT_PORT_STATUS, NULL,
610                                 &buffer);
611     ops->reason         = status;
612     fill_port_desc(p->dp, p, &ops->desc);
613     send_openflow_buffer(p->dp, buffer, NULL);
614 }
615
616 void
617 send_flow_expired(struct datapath *dp, struct sw_flow *flow)
618 {
619     struct buffer *buffer;
620     struct ofp_flow_expired *ofe;
621     ofe = alloc_openflow_buffer(dp, sizeof *ofe, OFPT_FLOW_EXPIRED, NULL,
622                                 &buffer);
623     flow_fill_match(&ofe->match, &flow->key);
624     ofe->duration   = htonl(flow->timeout - flow->max_idle - flow->created);
625     ofe->packet_count   = htonll(flow->packet_count);
626     ofe->byte_count     = htonll(flow->byte_count);
627     send_openflow_buffer(dp, buffer, NULL);
628 }
629
630 void
631 dp_send_error_msg(struct datapath *dp, const struct sender *sender,
632         uint16_t type, uint16_t code, const uint8_t *data, size_t len)
633 {
634     struct buffer *buffer;
635     struct ofp_error_msg *oem;
636     oem = alloc_openflow_buffer(dp, sizeof(*oem)+len, OFPT_ERROR_MSG, 
637                                 sender, &buffer);
638     oem->type = htons(type);
639     oem->code = htons(code);
640     memcpy(oem->data, data, len);
641     send_openflow_buffer(dp, buffer, sender);
642 }
643
644 static void
645 fill_flow_stats(struct ofp_flow_stats *ofs, struct sw_flow *flow,
646                 int table_idx, time_t now)
647 {
648         ofs->match.wildcards = htons(flow->key.wildcards);
649         ofs->match.in_port   = flow->key.flow.in_port;
650         memcpy(ofs->match.dl_src, flow->key.flow.dl_src, ETH_ADDR_LEN);
651         memcpy(ofs->match.dl_dst, flow->key.flow.dl_dst, ETH_ADDR_LEN);
652         ofs->match.dl_vlan   = flow->key.flow.dl_vlan;
653         ofs->match.dl_type   = flow->key.flow.dl_type;
654         ofs->match.nw_src    = flow->key.flow.nw_src;
655         ofs->match.nw_dst    = flow->key.flow.nw_dst;
656         ofs->match.nw_proto  = flow->key.flow.nw_proto;
657         memset(ofs->match.pad, 0, sizeof ofs->match.pad);
658         ofs->match.tp_src    = flow->key.flow.tp_src;
659         ofs->match.tp_dst    = flow->key.flow.tp_dst;
660         ofs->duration        = htonl(now - flow->created);
661         ofs->priority        = htons(flow->priority);
662         ofs->table_id        = table_idx;
663         ofs->packet_count    = htonll(flow->packet_count);
664         ofs->byte_count      = htonll(flow->byte_count);
665 }
666
667 int
668 dp_send_flow_stats(struct datapath *dp, const struct sender *sender,
669                    const struct ofp_match *match)
670 {
671     struct buffer *buffer;
672     struct ofp_flow_stats_reply *fsr;
673     size_t header_size, fudge, flow_size;
674     struct sw_flow_key match_key;
675     int table_idx, n_flows, max_flows;
676     time_t now;
677
678     header_size = offsetof(struct ofp_flow_stats_reply, flows);
679     fudge = 128;
680     flow_size = sizeof fsr->flows[0];
681     max_flows = (65536 - header_size - fudge) / flow_size;
682     fsr = alloc_openflow_buffer(dp, header_size,
683                                 OFPT_FLOW_STATS_REPLY, sender, &buffer);
684
685     n_flows = 0;
686     flow_extract_match(&match_key, match);
687     now = time(0);
688     for (table_idx = 0; table_idx < dp->chain->n_tables; table_idx++) {
689         struct sw_table *table = dp->chain->tables[table_idx];
690         struct swt_iterator iter;
691
692         if (n_flows >= max_flows) {
693             break;
694         }
695
696         if (!table->iterator(table, &iter)) {
697             printf("iterator failed for table %d\n", table_idx);
698             continue;
699         }
700
701         for (; iter.flow; table->iterator_next(&iter)) {
702             if (flow_matches(&match_key, &iter.flow->key)) {
703                 struct ofp_flow_stats *ofs = buffer_put_uninit(buffer,
704                                                                sizeof *ofs);
705                 fill_flow_stats(ofs, iter.flow, table_idx, now);
706                 if (++n_flows >= max_flows) {
707                     break;
708                 }
709             }
710         }
711         table->iterator_destroy(&iter);
712     }
713     return send_openflow_buffer(dp, buffer, sender);
714 }
715
716 int
717 dp_send_port_stats(struct datapath *dp, const struct sender *sender)
718 {
719         struct buffer *buffer;
720         struct ofp_port_stats_reply *psr;
721     struct sw_port *p;
722
723         psr = alloc_openflow_buffer(dp, offsetof(struct ofp_port_stats_reply,
724                                              ports),
725                                 OFPT_PORT_STATS_REPLY, sender, &buffer);
726     LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
727                 struct ofp_port_stats *ps = buffer_put_uninit(buffer, sizeof *ps);
728                 ps->port_no = htons(port_no(dp, p));
729                 memset(ps->pad, 0, sizeof ps->pad);
730                 ps->rx_count = htonll(p->rx_count);
731                 ps->tx_count = htonll(p->tx_count);
732                 ps->drop_count = htonll(p->drop_count);
733         }
734         return send_openflow_buffer(dp, buffer, sender);
735 }
736
737 int
738 dp_send_table_stats(struct datapath *dp, const struct sender *sender)
739 {
740         struct buffer *buffer;
741         struct ofp_table_stats_reply *tsr;
742         int i;
743
744         tsr = alloc_openflow_buffer(dp, offsetof(struct ofp_table_stats_reply,
745                                              tables),
746                                 OFPT_TABLE_STATS_REPLY, sender, &buffer);
747         for (i = 0; i < dp->chain->n_tables; i++) {
748                 struct ofp_table_stats *ots = buffer_put_uninit(buffer, sizeof *ots);
749                 struct sw_table_stats stats;
750                 dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
751                 strncpy(ots->name, stats.name, sizeof ots->name);
752                 ots->table_id = i;
753                 ots->pad[0] = ots->pad[1] = 0;
754                 ots->max_entries = htonl(stats.max_flows);
755                 ots->active_count = htonl(stats.n_flows);
756                 ots->matched_count = htonll(0); /* FIXME */
757         }
758         return send_openflow_buffer(dp, buffer, sender);
759 }
760 \f
761 /* 'buffer' was received on 'in_port', a physical switch port between 0 and
762  * OFPP_MAX.  Process it according to 'chain'. */
763 void fwd_port_input(struct datapath *dp, struct buffer *buffer, int in_port)
764 {
765     struct sw_flow_key key;
766     struct sw_flow *flow;
767
768     key.wildcards = 0;
769     flow_extract(buffer, in_port, &key.flow);
770     flow = chain_lookup(dp->chain, &key);
771     if (flow != NULL) {
772         flow_used(flow, buffer);
773         execute_actions(dp, buffer, in_port, &key,
774                         flow->actions, flow->n_actions);
775     } else {
776         dp_output_control(dp, buffer, in_port, ntohs(dp->config.miss_send_len),
777                           OFPR_NO_MATCH);
778     }
779 }
780
781 static void
782 do_output(struct datapath *dp, struct buffer *buffer, int in_port,
783           size_t max_len, int out_port)
784 {
785     if (out_port != OFPP_CONTROLLER) {
786         dp_output_port(dp, buffer, in_port, out_port);
787     } else {
788         dp_output_control(dp, buffer, in_port, max_len, OFPR_ACTION);
789     }
790 }
791
792 static void
793 execute_actions(struct datapath *dp, struct buffer *buffer,
794                 int in_port, const struct sw_flow_key *key,
795                 const struct ofp_action *actions, int n_actions)
796 {
797     /* Every output action needs a separate clone of 'buffer', but the common
798      * case is just a single output action, so that doing a clone and then
799      * freeing the original buffer is wasteful.  So the following code is
800      * slightly obscure just to avoid that. */
801     int prev_port;
802     size_t max_len=0;        /* Initialze to make compiler happy */
803     uint16_t eth_proto;
804     int i;
805
806     prev_port = -1;
807     eth_proto = ntohs(key->flow.dl_type);
808
809     for (i = 0; i < n_actions; i++) {
810         const struct ofp_action *a = &actions[i];
811         struct eth_header *eh = buffer->l2;
812
813         if (prev_port != -1) {
814             do_output(dp, buffer_clone(buffer), in_port, max_len, prev_port);
815             prev_port = -1;
816         }
817
818         switch (ntohs(a->type)) {
819         case OFPAT_OUTPUT:
820             prev_port = ntohs(a->arg.output.port);
821             max_len = ntohs(a->arg.output.max_len);
822             break;
823
824         case OFPAT_SET_DL_VLAN:
825             modify_vlan(buffer, key, a);
826             break;
827
828         case OFPAT_SET_DL_SRC:
829             memcpy(eh->eth_src, a->arg.dl_addr, sizeof eh->eth_src);
830             break;
831
832         case OFPAT_SET_DL_DST:
833             memcpy(eh->eth_dst, a->arg.dl_addr, sizeof eh->eth_dst);
834             break;
835
836         case OFPAT_SET_NW_SRC:
837         case OFPAT_SET_NW_DST:
838             modify_nh(buffer, eth_proto, key->flow.nw_proto, a);
839             break;
840
841         case OFPAT_SET_TP_SRC:
842         case OFPAT_SET_TP_DST:
843             modify_th(buffer, eth_proto, key->flow.nw_proto, a);
844             break;
845
846         default:
847             NOT_REACHED();
848         }
849     }
850     if (prev_port != -1)
851         do_output(dp, buffer, in_port, max_len, prev_port);
852     else
853         buffer_delete(buffer);
854 }
855
856 /* Returns the new checksum for a packet in which the checksum field previously
857  * contained 'old_csum' and in which a field that contained 'old_u16' was
858  * changed to contain 'new_u16'. */
859 static uint16_t
860 recalc_csum16(uint16_t old_csum, uint16_t old_u16, uint16_t new_u16)
861 {
862     /* Ones-complement arithmetic is endian-independent, so this code does not
863      * use htons() or ntohs().
864      *
865      * See RFC 1624 for formula and explanation. */
866     uint16_t hc_complement = ~old_csum;
867     uint16_t m_complement = ~old_u16;
868     uint16_t m_prime = new_u16;
869     uint32_t sum = hc_complement + m_complement + m_prime;
870     uint16_t hc_prime_complement = sum + (sum >> 16);
871     return ~hc_prime_complement;
872 }
873
874 /* Returns the new checksum for a packet in which the checksum field previously
875  * contained 'old_csum' and in which a field that contained 'old_u32' was
876  * changed to contain 'new_u32'. */
877 static uint16_t
878 recalc_csum32(uint16_t old_csum, uint32_t old_u32, uint32_t new_u32)
879 {
880     return recalc_csum16(recalc_csum16(old_csum, old_u32, new_u32),
881                          old_u32 >> 16, new_u32 >> 16);
882 }
883
884 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
885                       uint8_t nw_proto, const struct ofp_action *a)
886 {
887     if (eth_proto == ETH_TYPE_IP) {
888         struct ip_header *nh = buffer->l3;
889         uint32_t new, *field;
890
891         new = a->arg.nw_addr;
892         field = a->type == OFPAT_SET_NW_SRC ? &nh->ip_src : &nh->ip_dst;
893         if (nw_proto == IP_TYPE_TCP) {
894             struct tcp_header *th = buffer->l4;
895             th->tcp_csum = recalc_csum32(th->tcp_csum, *field, new);
896         } else if (nw_proto == IP_TYPE_UDP) {
897             struct udp_header *th = buffer->l4;
898             if (th->udp_csum) {
899                 th->udp_csum = recalc_csum32(th->udp_csum, *field, new);
900                 if (!th->udp_csum) {
901                     th->udp_csum = 0xffff;
902                 }
903             }
904         }
905         nh->ip_csum = recalc_csum32(nh->ip_csum, *field, new);
906         *field = new;
907     }
908 }
909
910 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
911                       uint8_t nw_proto, const struct ofp_action *a)
912 {
913     if (eth_proto == ETH_TYPE_IP) {
914         uint16_t new, *field;
915
916         new = a->arg.tp;
917
918         if (nw_proto == IP_TYPE_TCP) {
919             struct tcp_header *th = buffer->l4;
920             field = a->type == OFPAT_SET_TP_SRC ? &th->tcp_src : &th->tcp_dst;
921             th->tcp_csum = recalc_csum16(th->tcp_csum, *field, new);
922             *field = new;
923         } else if (nw_proto == IP_TYPE_UDP) {
924             struct udp_header *th = buffer->l4;
925             field = a->type == OFPAT_SET_TP_SRC ? &th->udp_src : &th->udp_dst;
926             th->udp_csum = recalc_csum16(th->udp_csum, *field, new);
927             *field = new;
928         }
929     }
930 }
931
932 static void
933 modify_vlan(struct buffer *buffer,
934             const struct sw_flow_key *key, const struct ofp_action *a)
935 {
936     uint16_t new_id = a->arg.vlan_id;
937     struct vlan_eth_header *veh;
938
939     if (new_id != OFP_VLAN_NONE) {
940         if (key->flow.dl_vlan != htons(OFP_VLAN_NONE)) {
941             /* Modify vlan id, but maintain other TCI values */
942             veh = buffer->l2;
943             veh->veth_tci &= ~htons(VLAN_VID);
944             veh->veth_tci |= htons(new_id);
945         } else {
946             /* Insert new vlan id. */
947             struct eth_header *eh = buffer->l2;
948             struct vlan_eth_header tmp;
949             memcpy(tmp.veth_dst, eh->eth_dst, ETH_ADDR_LEN);
950             memcpy(tmp.veth_src, eh->eth_src, ETH_ADDR_LEN);
951             tmp.veth_type = htons(ETH_TYPE_VLAN);
952             tmp.veth_tci = new_id;
953             tmp.veth_next_type = eh->eth_type;
954             
955             veh = buffer_push_uninit(buffer, VLAN_HEADER_LEN);
956             memcpy(veh, &tmp, sizeof tmp);
957             buffer->l2 -= VLAN_HEADER_LEN;
958         }
959     } else  {
960         /* Remove an existing vlan header if it exists */
961         veh = buffer->l2;
962         if (veh->veth_type == htons(ETH_TYPE_VLAN)) {
963             struct eth_header tmp;
964             
965             memcpy(tmp.eth_dst, veh->veth_dst, ETH_ADDR_LEN);
966             memcpy(tmp.eth_src, veh->veth_src, ETH_ADDR_LEN);
967             tmp.eth_type = veh->veth_next_type;
968             
969             buffer->size -= VLAN_HEADER_LEN;
970             buffer->data += VLAN_HEADER_LEN;
971             buffer->l2 += VLAN_HEADER_LEN;
972             memcpy(buffer->data, &tmp, sizeof tmp);
973         }
974     }
975 }
976
977 static int
978 recv_features_request(struct datapath *dp, const struct sender *sender,
979                       const void *msg) 
980 {
981     dp_send_features_reply(dp, sender);
982     return 0;
983 }
984
985 static int
986 recv_get_config_request(struct datapath *dp, const struct sender *sender,
987                         const void *msg) 
988 {
989     struct buffer *buffer;
990     struct ofp_switch_config *osc;
991
992     osc = alloc_openflow_buffer(dp, sizeof *osc, OFPT_GET_CONFIG_REPLY,
993                                 sender, &buffer);
994
995     assert(sizeof *osc == sizeof dp->config);
996         memcpy(((char *)osc) + sizeof osc->header,
997                ((char *)&dp->config) + sizeof dp->config.header,
998                sizeof dp->config - sizeof dp->config.header);
999
1000     return send_openflow_buffer(dp, buffer, sender);
1001 }
1002
1003 static int
1004 recv_set_config(struct datapath *dp, const struct sender *sender UNUSED,
1005                 const void *msg)
1006 {
1007     const struct ofp_switch_config *osc = msg;
1008     dp->config = *osc;
1009     return 0;
1010 }
1011
1012 static int
1013 recv_packet_out(struct datapath *dp, const struct sender *sender UNUSED,
1014                 const void *msg)
1015 {
1016     const struct ofp_packet_out *opo = msg;
1017
1018     if (ntohl(opo->buffer_id) == (uint32_t) -1) {
1019         /* FIXME: can we avoid copying data here? */
1020         int data_len = ntohs(opo->header.length) - sizeof *opo;
1021         struct buffer *buffer = buffer_new(data_len);
1022         buffer_put(buffer, opo->u.data, data_len);
1023         dp_output_port(dp, buffer,
1024                        ntohs(opo->in_port), ntohs(opo->out_port));
1025     } else {
1026         struct sw_flow_key key;
1027         struct buffer *buffer;
1028         int n_acts;
1029
1030         buffer = retrieve_buffer(ntohl(opo->buffer_id));
1031         if (!buffer) {
1032             return -ESRCH; 
1033         }
1034
1035         n_acts = (ntohs(opo->header.length) - sizeof *opo) 
1036             / sizeof *opo->u.actions;
1037         flow_extract(buffer, ntohs(opo->in_port), &key.flow);
1038         execute_actions(dp, buffer, ntohs(opo->in_port),
1039                         &key, opo->u.actions, n_acts);
1040     }
1041     return 0;
1042 }
1043
1044 static int
1045 recv_port_mod(struct datapath *dp, const struct sender *sender UNUSED,
1046               const void *msg)
1047 {
1048     const struct ofp_port_mod *opm = msg;
1049
1050     dp_update_port_flags(dp, &opm->desc);
1051
1052     return 0;
1053 }
1054
1055 static int
1056 add_flow(struct datapath *dp, const struct ofp_flow_mod *ofm)
1057 {
1058     int error = -ENOMEM;
1059     int n_acts;
1060     struct sw_flow *flow;
1061
1062
1063     /* Check number of actions. */
1064     n_acts = (ntohs(ofm->header.length) - sizeof *ofm) / sizeof *ofm->actions;
1065     if (n_acts > MAX_ACTIONS) {
1066         error = -E2BIG;
1067         goto error;
1068     }
1069
1070     /* Allocate memory. */
1071     flow = flow_alloc(n_acts);
1072     if (flow == NULL)
1073         goto error;
1074
1075     /* Fill out flow. */
1076     flow_extract_match(&flow->key, &ofm->match);
1077     flow->max_idle = ntohs(ofm->max_idle);
1078     flow->priority = ntohs(ofm->priority);
1079     flow->timeout = time(0) + flow->max_idle; /* FIXME */
1080     flow->n_actions = n_acts;
1081     flow->created = time(0);    /* FIXME */
1082     flow->byte_count = 0;
1083     flow->packet_count = 0;
1084     memcpy(flow->actions, ofm->actions, n_acts * sizeof *flow->actions);
1085
1086     /* Act. */
1087     error = chain_insert(dp->chain, flow);
1088     if (error) {
1089         goto error_free_flow; 
1090     }
1091     error = 0;
1092     if (ntohl(ofm->buffer_id) != UINT32_MAX) {
1093         struct buffer *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
1094         if (buffer) {
1095             struct sw_flow_key key;
1096             uint16_t in_port = ntohs(ofm->match.in_port);
1097             flow_used(flow, buffer);
1098             flow_extract(buffer, in_port, &key.flow);
1099             execute_actions(dp, buffer, in_port, &key, ofm->actions, n_acts);
1100         } else {
1101             error = -ESRCH; 
1102         }
1103     }
1104     return error;
1105
1106 error_free_flow:
1107     flow_free(flow);
1108 error:
1109     if (ntohl(ofm->buffer_id) != (uint32_t) -1)
1110         discard_buffer(ntohl(ofm->buffer_id));
1111     return error;
1112 }
1113
1114 static int
1115 recv_flow(struct datapath *dp, const struct sender *sender UNUSED,
1116           const void *msg)
1117 {
1118     const struct ofp_flow_mod *ofm = msg;
1119     uint16_t command = ntohs(ofm->command);
1120
1121     if (command == OFPFC_ADD) {
1122         return add_flow(dp, ofm);
1123     }  else if (command == OFPFC_DELETE) {
1124         struct sw_flow_key key;
1125         flow_extract_match(&key, &ofm->match);
1126         return chain_delete(dp->chain, &key, 0, 0) ? 0 : -ESRCH;
1127     } else if (command == OFPFC_DELETE_STRICT) {
1128         struct sw_flow_key key;
1129         flow_extract_match(&key, &ofm->match);
1130         return chain_delete(dp->chain, &key, 
1131                     ntohs(ofm->priority), 1) ? 0 : -ESRCH;
1132     } else {
1133         return -ENODEV;
1134     }
1135 }
1136
1137 static int
1138 recv_flow_stats_request(struct datapath *dp, const struct sender *sender,
1139                          const void *msg)
1140 {
1141         const struct ofp_flow_stats_request *fsr = msg;
1142         if (fsr->type == OFPFS_INDIV) {
1143                 return dp_send_flow_stats(dp, sender, &fsr->match); 
1144         } else {
1145                 /* FIXME */
1146                 return -ENOSYS;
1147         }
1148 }
1149
1150 static int
1151 recv_port_stats_request(struct datapath *dp, const struct sender *sender,
1152                          const void *msg)
1153 {
1154         return dp_send_port_stats(dp, sender);
1155 }
1156
1157 static int
1158 recv_table_stats_request(struct datapath *dp, const struct sender *sender,
1159                           const void *msg)
1160 {
1161         return dp_send_table_stats(dp, sender);
1162 }
1163
1164 /* 'msg', which is 'length' bytes long, was received from the control path.
1165  * Apply it to 'chain'. */
1166 int
1167 fwd_control_input(struct datapath *dp, const struct sender *sender,
1168                   const void *msg, size_t length)
1169 {
1170     struct openflow_packet {
1171         size_t min_size;
1172         int (*handler)(struct datapath *, const struct sender *, const void *);
1173     };
1174
1175     static const struct openflow_packet packets[] = {
1176         [OFPT_FEATURES_REQUEST] = {
1177             sizeof (struct ofp_header),
1178             recv_features_request,
1179         },
1180         [OFPT_GET_CONFIG_REQUEST] = {
1181             sizeof (struct ofp_header),
1182             recv_get_config_request,
1183         },
1184         [OFPT_SET_CONFIG] = {
1185             sizeof (struct ofp_switch_config),
1186             recv_set_config,
1187         },
1188         [OFPT_PACKET_OUT] = {
1189             sizeof (struct ofp_packet_out),
1190             recv_packet_out,
1191         },
1192         [OFPT_FLOW_MOD] = {
1193             sizeof (struct ofp_flow_mod),
1194             recv_flow,
1195         },
1196         [OFPT_PORT_MOD] = {
1197             sizeof (struct ofp_port_mod),
1198             recv_port_mod,
1199         },
1200                 [OFPT_FLOW_STATS_REQUEST] = {
1201                         sizeof (struct ofp_flow_stats_request),
1202                         recv_flow_stats_request,
1203                 },
1204                 [OFPT_PORT_STATS_REQUEST] = {
1205                         sizeof (struct ofp_port_stats_request),
1206                         recv_port_stats_request,
1207                 },
1208                 [OFPT_TABLE_STATS_REQUEST] = {
1209                         sizeof (struct ofp_table_stats_request),
1210                         recv_table_stats_request,
1211                 },
1212     };
1213
1214     const struct openflow_packet *pkt;
1215     struct ofp_header *oh;
1216
1217     oh = (struct ofp_header *) msg;
1218     if (oh->version != OFP_VERSION || oh->type >= ARRAY_SIZE(packets)
1219         || ntohs(oh->length) > length)
1220         return -EINVAL;
1221
1222     pkt = &packets[oh->type];
1223     if (!pkt->handler)
1224         return -ENOSYS;
1225     if (length < pkt->min_size)
1226         return -EFAULT;
1227
1228     return pkt->handler(dp, sender, msg);
1229 }
1230 \f
1231 /* Packet buffering. */
1232
1233 #define OVERWRITE_SECS  1
1234
1235 struct packet_buffer {
1236     struct buffer *buffer;
1237     uint32_t cookie;
1238     time_t timeout;
1239 };
1240
1241 static struct packet_buffer buffers[N_PKT_BUFFERS];
1242 static unsigned int buffer_idx;
1243
1244 uint32_t save_buffer(struct buffer *buffer)
1245 {
1246     struct packet_buffer *p;
1247     uint32_t id;
1248
1249     buffer_idx = (buffer_idx + 1) & PKT_BUFFER_MASK;
1250     p = &buffers[buffer_idx];
1251     if (p->buffer) {
1252         /* Don't buffer packet if existing entry is less than
1253          * OVERWRITE_SECS old. */
1254         if (time(0) < p->timeout) { /* FIXME */
1255             return -1;
1256         } else {
1257             buffer_delete(p->buffer); 
1258         }
1259     }
1260     /* Don't use maximum cookie value since the all-bits-1 id is
1261      * special. */
1262     if (++p->cookie >= (1u << PKT_COOKIE_BITS) - 1)
1263         p->cookie = 0;
1264     p->buffer = buffer_clone(buffer);      /* FIXME */
1265     p->timeout = time(0) + OVERWRITE_SECS; /* FIXME */
1266     id = buffer_idx | (p->cookie << PKT_BUFFER_BITS);
1267
1268     return id;
1269 }
1270
1271 static struct buffer *retrieve_buffer(uint32_t id)
1272 {
1273     struct buffer *buffer = NULL;
1274     struct packet_buffer *p;
1275
1276     p = &buffers[id & PKT_BUFFER_MASK];
1277     if (p->cookie == id >> PKT_BUFFER_BITS) {
1278         buffer = p->buffer;
1279         p->buffer = NULL;
1280     } else {
1281         printf("cookie mismatch: %x != %x\n",
1282                id >> PKT_BUFFER_BITS, p->cookie);
1283     }
1284
1285     return buffer;
1286 }
1287
1288 static void discard_buffer(uint32_t id)
1289 {
1290     struct packet_buffer *p;
1291
1292     p = &buffers[id & PKT_BUFFER_MASK];
1293     if (p->cookie == id >> PKT_BUFFER_BITS) {
1294         buffer_delete(p->buffer);
1295         p->buffer = NULL;
1296     }
1297 }