Merge branch "partner", to simplify partner integration.
[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 <inttypes.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include "chain.h"
42 #include "csum.h"
43 #include "flow.h"
44 #include "list.h"
45 #include "netdev.h"
46 #include "ofpbuf.h"
47 #include "openflow.h"
48 #include "packets.h"
49 #include "poll-loop.h"
50 #include "rconn.h"
51 #include "stp.h"
52 #include "switch-flow.h"
53 #include "table.h"
54 #include "timeval.h"
55 #include "vconn.h"
56 #include "xtoxll.h"
57
58 #define THIS_MODULE VLM_datapath
59 #include "vlog.h"
60
61 extern char mfr_desc;
62 extern char hw_desc;
63 extern char sw_desc;
64 extern char serial_num;
65
66 /* Capabilities supported by this implementation. */
67 #define OFP_SUPPORTED_CAPABILITIES ( OFPC_FLOW_STATS \
68         | OFPC_TABLE_STATS \
69         | OFPC_PORT_STATS \
70         | OFPC_MULTI_PHY_TX )
71
72 /* Actions supported by this implementation. */
73 #define OFP_SUPPORTED_ACTIONS ( (1 << OFPAT_OUTPUT)         \
74                                 | (1 << OFPAT_SET_DL_VLAN)  \
75                                 | (1 << OFPAT_SET_DL_SRC)   \
76                                 | (1 << OFPAT_SET_DL_DST)   \
77                                 | (1 << OFPAT_SET_NW_SRC)   \
78                                 | (1 << OFPAT_SET_NW_DST)   \
79                                 | (1 << OFPAT_SET_TP_SRC)   \
80                                 | (1 << OFPAT_SET_TP_DST) )
81
82 #define PORT_STATUS_BITS (OFPPFL_PORT_DOWN | OFPPFL_LINK_DOWN)
83 #define PORT_FLAG_BITS (~PORT_STATUS_BITS)
84
85 struct sw_port {
86     uint32_t flags;             /* Some subset of PORT_FLAG_BITS. */
87     uint32_t status;            /* Some subset of PORT_STATUS_BITS. */
88     struct datapath *dp;
89     struct netdev *netdev;
90     struct list node; /* Element in datapath.ports. */
91     unsigned long long int rx_packets, tx_packets;
92     unsigned long long int rx_bytes, tx_bytes;
93     unsigned long long int tx_dropped;
94 };
95
96 /* The origin of a received OpenFlow message, to enable sending a reply. */
97 struct sender {
98     struct remote *remote;      /* The device that sent the message. */
99     uint32_t xid;               /* The OpenFlow transaction ID. */
100 };
101
102 /* A connection to a controller or a management device. */
103 struct remote {
104     struct list node;
105     struct rconn *rconn;
106 #define TXQ_LIMIT 128           /* Max number of packets to queue for tx. */
107     int n_txq;                  /* Number of packets queued for tx on rconn. */
108
109     /* Support for reliable, multi-message replies to requests.
110      *
111      * If an incoming request needs to have a reliable reply that might
112      * require multiple messages, it can use remote_start_dump() to set up
113      * a callback that will be called as buffer space for replies. */
114     int (*cb_dump)(struct datapath *, void *aux);
115     void (*cb_done)(void *aux);
116     void *cb_aux;
117 };
118
119 struct datapath {
120     /* Remote connections. */
121     struct remote *controller;  /* Connection to controller. */
122     struct list remotes;        /* All connections (including controller). */
123     struct pvconn *listen_pvconn;
124
125     time_t last_timeout;
126
127     /* Unique identifier for this datapath */
128     uint64_t  id;
129
130     struct sw_chain *chain;  /* Forwarding rules. */
131
132     /* Configuration set from controller. */
133     uint16_t flags;
134     uint16_t miss_send_len;
135
136     /* Switch ports. */
137     struct sw_port ports[OFPP_MAX];
138     struct list port_list; /* List of ports, for flooding. */
139 };
140
141 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 60);
142
143 static struct remote *remote_create(struct datapath *, struct rconn *);
144 static void remote_run(struct datapath *, struct remote *);
145 static void remote_wait(struct remote *);
146 static void remote_destroy(struct remote *);
147
148 void dp_output_port(struct datapath *, struct ofpbuf *,
149                     int in_port, int out_port, bool ignore_no_fwd);
150 void dp_update_port_flags(struct datapath *dp, const struct ofp_port_mod *opm);
151 void dp_output_control(struct datapath *, struct ofpbuf *, int in_port,
152                        size_t max_len, int reason);
153 static void send_flow_expired(struct datapath *, struct sw_flow *,
154                               enum ofp_flow_expired_reason);
155 static int update_port_status(struct sw_port *p);
156 static void send_port_status(struct sw_port *p, uint8_t status);
157 static void del_switch_port(struct sw_port *p);
158 static void execute_actions(struct datapath *, struct ofpbuf *,
159                             int in_port, const struct sw_flow_key *,
160                             const struct ofp_action *, int n_actions,
161                             bool ignore_no_fwd);
162 static void modify_vlan(struct ofpbuf *buffer, const struct sw_flow_key *key,
163                         const struct ofp_action *a);
164 static void modify_nh(struct ofpbuf *buffer, uint16_t eth_proto,
165                       uint8_t nw_proto, const struct ofp_action *a);
166 static void modify_th(struct ofpbuf *buffer, uint16_t eth_proto,
167                           uint8_t nw_proto, const struct ofp_action *a);
168
169 /* Buffers are identified to userspace by a 31-bit opaque ID.  We divide the ID
170  * into a buffer number (low bits) and a cookie (high bits).  The buffer number
171  * is an index into an array of buffers.  The cookie distinguishes between
172  * different packets that have occupied a single buffer.  Thus, the more
173  * buffers we have, the lower-quality the cookie... */
174 #define PKT_BUFFER_BITS 8
175 #define N_PKT_BUFFERS (1 << PKT_BUFFER_BITS)
176 #define PKT_BUFFER_MASK (N_PKT_BUFFERS - 1)
177
178 #define PKT_COOKIE_BITS (32 - PKT_BUFFER_BITS)
179
180 int run_flow_through_tables(struct datapath *, struct ofpbuf *,
181                             struct sw_port *);
182 void fwd_port_input(struct datapath *, struct ofpbuf *, struct sw_port *);
183 int fwd_control_input(struct datapath *, const struct sender *,
184                       const void *, size_t);
185
186 uint32_t save_buffer(struct ofpbuf *);
187 static struct ofpbuf *retrieve_buffer(uint32_t id);
188 static void discard_buffer(uint32_t id);
189
190 static int port_no(struct datapath *dp, struct sw_port *p) 
191 {
192     assert(p >= dp->ports && p < &dp->ports[ARRAY_SIZE(dp->ports)]);
193     return p - dp->ports;
194 }
195
196 /* Generates and returns a random datapath id. */
197 static uint64_t
198 gen_datapath_id(void)
199 {
200     uint8_t ea[ETH_ADDR_LEN];
201     eth_addr_random(ea);
202     return eth_addr_to_uint64(ea);
203 }
204
205 int
206 dp_new(struct datapath **dp_, uint64_t dpid, struct rconn *rconn)
207 {
208     struct datapath *dp;
209
210     dp = calloc(1, sizeof *dp);
211     if (!dp) {
212         return ENOMEM;
213     }
214
215     dp->last_timeout = time_now();
216     list_init(&dp->remotes);
217     dp->controller = remote_create(dp, rconn);
218     dp->listen_pvconn = NULL;
219     dp->id = dpid <= UINT64_C(0xffffffffffff) ? dpid : gen_datapath_id();
220     dp->chain = chain_create();
221     if (!dp->chain) {
222         VLOG_ERR("could not create chain");
223         free(dp);
224         return ENOMEM;
225     }
226
227     list_init(&dp->port_list);
228     dp->flags = 0;
229     dp->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
230     *dp_ = dp;
231     return 0;
232 }
233
234 int
235 dp_add_port(struct datapath *dp, const char *name)
236 {
237     struct netdev *netdev;
238     struct in6_addr in6;
239     struct in_addr in4;
240     struct sw_port *p;
241     int error;
242
243     error = netdev_open(name, NETDEV_ETH_TYPE_ANY, &netdev);
244     if (error) {
245         return error;
246     }
247     error = netdev_set_flags(netdev, NETDEV_UP | NETDEV_PROMISC, false);
248     if (error) {
249         VLOG_ERR("couldn't set promiscuous mode on %s device", name);
250         netdev_close(netdev);
251         return error;
252     }
253     if (netdev_get_in4(netdev, &in4)) {
254         VLOG_ERR("%s device has assigned IP address %s", name, inet_ntoa(in4));
255     }
256     if (netdev_get_in6(netdev, &in6)) {
257         char in6_name[INET6_ADDRSTRLEN + 1];
258         inet_ntop(AF_INET6, &in6, in6_name, sizeof in6_name);
259         VLOG_ERR("%s device has assigned IPv6 address %s", name, in6_name);
260     }
261
262     for (p = dp->ports; ; p++) {
263         if (p >= &dp->ports[ARRAY_SIZE(dp->ports)]) {
264             return EXFULL;
265         } else if (!p->netdev) {
266             break;
267         }
268     }
269
270     memset(p, '\0', sizeof *p);
271
272     p->dp = dp;
273     p->netdev = netdev;
274     list_push_back(&dp->port_list, &p->node);
275
276     /* Notify the ctlpath that this port has been added */
277     send_port_status(p, OFPPR_ADD);
278
279     return 0;
280 }
281
282 void
283 dp_add_listen_pvconn(struct datapath *dp, struct pvconn *listen_pvconn)
284 {
285     assert(!dp->listen_pvconn);
286     dp->listen_pvconn = listen_pvconn;
287 }
288
289 void
290 dp_run(struct datapath *dp)
291 {
292     time_t now = time_now();
293     struct sw_port *p, *pn;
294     struct remote *r, *rn;
295     struct ofpbuf *buffer = NULL;
296
297     if (now != dp->last_timeout) {
298         struct list deleted = LIST_INITIALIZER(&deleted);
299         struct sw_flow *f, *n;
300
301         LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
302             if (update_port_status(p)) {
303                 send_port_status(p, OFPPR_MOD);
304             }
305         }
306
307         chain_timeout(dp->chain, &deleted);
308         LIST_FOR_EACH_SAFE (f, n, struct sw_flow, node, &deleted) {
309             send_flow_expired(dp, f, f->reason);
310             list_remove(&f->node);
311             flow_free(f);
312         }
313         dp->last_timeout = now;
314     }
315     poll_timer_wait(1000);
316     
317     LIST_FOR_EACH_SAFE (p, pn, struct sw_port, node, &dp->port_list) {
318         int error;
319
320         if (!buffer) {
321             /* Allocate buffer with some headroom to add headers in forwarding
322              * to the controller or adding a vlan tag, plus an extra 2 bytes to
323              * allow IP headers to be aligned on a 4-byte boundary.  */
324             const int headroom = 128 + 2;
325             const int hard_header = VLAN_ETH_HEADER_LEN;
326             const int mtu = netdev_get_mtu(p->netdev);
327             buffer = ofpbuf_new(headroom + hard_header + mtu);
328             buffer->data = (char*)buffer->data + headroom;
329         }
330         error = netdev_recv(p->netdev, buffer);
331         if (!error) {
332             p->rx_packets++;
333             p->rx_bytes += buffer->size;
334             fwd_port_input(dp, buffer, p);
335             buffer = NULL;
336         } else if (error != EAGAIN) {
337             VLOG_ERR_RL(&rl, "error receiving data from %s: %s",
338                         netdev_get_name(p->netdev), strerror(error));
339         }
340     }
341     ofpbuf_delete(buffer);
342
343     /* Talk to remotes. */
344     LIST_FOR_EACH_SAFE (r, rn, struct remote, node, &dp->remotes) {
345         remote_run(dp, r);
346     }
347     if (dp->listen_pvconn) {
348         for (;;) {
349             struct vconn *new_vconn;
350             int retval;
351
352             retval = pvconn_accept(dp->listen_pvconn, OFP_VERSION, &new_vconn);
353             if (retval) {
354                 if (retval != EAGAIN) {
355                     VLOG_WARN_RL(&rl, "accept failed (%s)", strerror(retval));
356                 }
357                 break;
358             }
359             remote_create(dp, rconn_new_from_vconn("passive", new_vconn));
360         }
361     }
362 }
363
364 static void
365 remote_run(struct datapath *dp, struct remote *r)
366 {
367     int i;
368
369     rconn_run(r->rconn);
370
371     /* Do some remote processing, but cap it at a reasonable amount so that
372      * other processing doesn't starve. */
373     for (i = 0; i < 50; i++) {
374         if (!r->cb_dump) {
375             struct ofpbuf *buffer;
376             struct ofp_header *oh;
377
378             buffer = rconn_recv(r->rconn);
379             if (!buffer) {
380                 break;
381             }
382
383             if (buffer->size >= sizeof *oh) {
384                 struct sender sender;
385
386                 oh = buffer->data;
387                 sender.remote = r;
388                 sender.xid = oh->xid;
389                 fwd_control_input(dp, &sender, buffer->data, buffer->size);
390             } else {
391                 VLOG_WARN_RL(&rl, "received too-short OpenFlow message");
392             }
393             ofpbuf_delete(buffer); 
394         } else {
395             if (r->n_txq < TXQ_LIMIT) {
396                 int error = r->cb_dump(dp, r->cb_aux);
397                 if (error <= 0) {
398                     if (error) {
399                         VLOG_WARN_RL(&rl, "dump callback error: %s",
400                                      strerror(-error));
401                     }
402                     r->cb_done(r->cb_aux);
403                     r->cb_dump = NULL;
404                 }
405             } else {
406                 break;
407             }
408         }
409     }
410
411     if (!rconn_is_alive(r->rconn)) {
412         remote_destroy(r);
413     }
414 }
415
416 static void
417 remote_wait(struct remote *r) 
418 {
419     rconn_run_wait(r->rconn);
420     rconn_recv_wait(r->rconn);
421 }
422
423 static void
424 remote_destroy(struct remote *r)
425 {
426     if (r) {
427         if (r->cb_dump && r->cb_done) {
428             r->cb_done(r->cb_aux);
429         }
430         list_remove(&r->node);
431         rconn_destroy(r->rconn);
432         free(r);
433     }
434 }
435
436 static struct remote *
437 remote_create(struct datapath *dp, struct rconn *rconn) 
438 {
439     struct remote *remote = xmalloc(sizeof *remote);
440     list_push_back(&dp->remotes, &remote->node);
441     remote->rconn = rconn;
442     remote->cb_dump = NULL;
443     remote->n_txq = 0;
444     return remote;
445 }
446
447 /* Starts a callback-based, reliable, possibly multi-message reply to a
448  * request made by 'remote'.
449  *
450  * 'dump' designates a function that will be called when the 'remote' send
451  * queue has an empty slot.  It should compose a message and send it on
452  * 'remote'.  On success, it should return 1 if it should be called again when
453  * another send queue slot opens up, 0 if its transmissions are complete, or a
454  * negative errno value on failure.
455  *
456  * 'done' designates a function to clean up any resources allocated for the
457  * dump.  It must handle being called before the dump is complete (which will
458  * happen if 'remote' is closed unexpectedly).
459  *
460  * 'aux' is passed to 'dump' and 'done'. */
461 static void
462 remote_start_dump(struct remote *remote,
463                   int (*dump)(struct datapath *, void *),
464                   void (*done)(void *),
465                   void *aux) 
466 {
467     assert(!remote->cb_dump);
468     remote->cb_dump = dump;
469     remote->cb_done = done;
470     remote->cb_aux = aux;
471 }
472
473 void
474 dp_wait(struct datapath *dp) 
475 {
476     struct sw_port *p;
477     struct remote *r;
478
479     LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
480         netdev_recv_wait(p->netdev);
481     }
482     LIST_FOR_EACH (r, struct remote, node, &dp->remotes) {
483         remote_wait(r);
484     }
485     if (dp->listen_pvconn) {
486         pvconn_wait(dp->listen_pvconn);
487     }
488 }
489
490 /* Delete 'p' from switch. */
491 static void
492 del_switch_port(struct sw_port *p)
493 {
494     send_port_status(p, OFPPR_DELETE);
495     netdev_close(p->netdev);
496     p->netdev = NULL;
497     list_remove(&p->node);
498 }
499
500 void
501 dp_destroy(struct datapath *dp)
502 {
503     struct sw_port *p, *n;
504
505     if (!dp) {
506         return;
507     }
508
509     LIST_FOR_EACH_SAFE (p, n, struct sw_port, node, &dp->port_list) {
510         del_switch_port(p); 
511     }
512     chain_destroy(dp->chain);
513     free(dp);
514 }
515
516 /* Send packets out all the ports except the originating one.  If the
517  * "flood" argument is set, don't send out ports with flooding disabled.
518  */
519 static int
520 output_all(struct datapath *dp, struct ofpbuf *buffer, int in_port, int flood)
521 {
522     struct sw_port *p;
523     int prev_port;
524
525     prev_port = -1;
526     LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
527         if (port_no(dp, p) == in_port) {
528             continue;
529         }
530         if (flood && p->flags & OFPPFL_NO_FLOOD) {
531             continue;
532         }
533         if (prev_port != -1) {
534             dp_output_port(dp, ofpbuf_clone(buffer), in_port, prev_port,
535                            false);
536         }
537         prev_port = port_no(dp, p);
538     }
539     if (prev_port != -1)
540         dp_output_port(dp, buffer, in_port, prev_port, false);
541     else
542         ofpbuf_delete(buffer);
543
544     return 0;
545 }
546
547 void
548 output_packet(struct datapath *dp, struct ofpbuf *buffer, int out_port) 
549 {
550     if (out_port >= 0 && out_port < OFPP_MAX) { 
551         struct sw_port *p = &dp->ports[out_port];
552         if (p->netdev != NULL && !(p->status & OFPPFL_PORT_DOWN)) {
553             if (!netdev_send(p->netdev, buffer)) {
554                 p->tx_packets++;
555                 p->tx_bytes += buffer->size;
556             } else {
557                 p->tx_dropped++;
558             }
559             return;
560         }
561     }
562
563     ofpbuf_delete(buffer);
564     VLOG_DBG_RL(&rl, "can't forward to bad port %d\n", out_port);
565 }
566
567 /* Takes ownership of 'buffer' and transmits it to 'out_port' on 'dp'.
568  */
569 void
570 dp_output_port(struct datapath *dp, struct ofpbuf *buffer,
571                int in_port, int out_port, bool ignore_no_fwd)
572 {
573
574     assert(buffer);
575     if (out_port == OFPP_FLOOD) {
576         output_all(dp, buffer, in_port, 1); 
577     } else if (out_port == OFPP_ALL) {
578         output_all(dp, buffer, in_port, 0); 
579     } else if (out_port == OFPP_CONTROLLER) {
580         dp_output_control(dp, buffer, in_port, 0, OFPR_ACTION); 
581     } else if (out_port == OFPP_IN_PORT) {
582         output_packet(dp, buffer, in_port);
583     } else if (out_port == OFPP_TABLE) {
584         struct sw_port *p = in_port < OFPP_MAX ? &dp->ports[in_port] : 0;
585                 if (run_flow_through_tables(dp, buffer, p)) {
586                         ofpbuf_delete(buffer);
587         }
588     } else {
589         if (in_port == out_port) {
590             VLOG_DBG_RL(&rl, "can't directly forward to input port");
591             return;
592         }
593         output_packet(dp, buffer, out_port);
594     }
595 }
596
597 static void *
598 make_openflow_reply(size_t openflow_len, uint8_t type,
599                     const struct sender *sender, struct ofpbuf **bufferp)
600 {
601     return make_openflow_xid(openflow_len, type, sender ? sender->xid : 0,
602                              bufferp);
603 }
604
605 static int
606 send_openflow_buffer(struct datapath *dp, struct ofpbuf *buffer,
607                      const struct sender *sender)
608 {
609     struct remote *remote = sender ? sender->remote : dp->controller;
610     struct rconn *rconn = remote->rconn;
611     int retval;
612
613     update_openflow_length(buffer);
614     retval = rconn_send_with_limit(rconn, buffer, &remote->n_txq, TXQ_LIMIT);
615     if (retval) {
616         VLOG_WARN_RL(&rl, "send to %s failed: %s",
617                      rconn_get_name(rconn), strerror(retval));
618     }
619     return retval;
620 }
621
622 /* Takes ownership of 'buffer' and transmits it to 'dp''s controller.  If the
623  * packet can be saved in a buffer, then only the first max_len bytes of
624  * 'buffer' are sent; otherwise, all of 'buffer' is sent.  'reason' indicates
625  * why 'buffer' is being sent. 'max_len' sets the maximum number of bytes that
626  * the caller wants to be sent; a value of 0 indicates the entire packet should
627  * be sent. */
628 void
629 dp_output_control(struct datapath *dp, struct ofpbuf *buffer, int in_port,
630                   size_t max_len, int reason)
631 {
632     struct ofp_packet_in *opi;
633     size_t total_len;
634     uint32_t buffer_id;
635
636     buffer_id = save_buffer(buffer);
637     total_len = buffer->size;
638     if (buffer_id != UINT32_MAX && max_len && buffer->size > max_len) {
639         buffer->size = max_len;
640     }
641
642     opi = ofpbuf_push_uninit(buffer, offsetof(struct ofp_packet_in, data));
643     opi->header.version = OFP_VERSION;
644     opi->header.type    = OFPT_PACKET_IN;
645     opi->header.length  = htons(buffer->size);
646     opi->header.xid     = htonl(0);
647     opi->buffer_id      = htonl(buffer_id);
648     opi->total_len      = htons(total_len);
649     opi->in_port        = htons(in_port);
650     opi->reason         = reason;
651     opi->pad            = 0;
652     send_openflow_buffer(dp, buffer, NULL);
653 }
654
655 static void fill_port_desc(struct datapath *dp, struct sw_port *p,
656                            struct ofp_phy_port *desc)
657 {
658     desc->port_no = htons(port_no(dp, p));
659     strncpy((char *) desc->name, netdev_get_name(p->netdev),
660             sizeof desc->name);
661     desc->name[sizeof desc->name - 1] = '\0';
662     memcpy(desc->hw_addr, netdev_get_etheraddr(p->netdev), ETH_ADDR_LEN);
663     desc->flags = 0;
664     desc->features = htonl(netdev_get_features(p->netdev));
665     desc->speed = htonl(netdev_get_speed(p->netdev));
666     desc->flags = htonl(p->flags | p->status);
667 }
668
669 static void
670 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
671 {
672     struct ofpbuf *buffer;
673     struct ofp_switch_features *ofr;
674     struct sw_port *p;
675
676     ofr = make_openflow_reply(sizeof *ofr, OFPT_FEATURES_REPLY,
677                                sender, &buffer);
678     ofr->datapath_id  = htonll(dp->id); 
679     ofr->n_tables     = dp->chain->n_tables;
680     ofr->n_buffers    = htonl(N_PKT_BUFFERS);
681     ofr->capabilities = htonl(OFP_SUPPORTED_CAPABILITIES);
682     ofr->actions      = htonl(OFP_SUPPORTED_ACTIONS);
683     LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
684         struct ofp_phy_port *opp = ofpbuf_put_uninit(buffer, sizeof *opp);
685         memset(opp, 0, sizeof *opp);
686         fill_port_desc(dp, p, opp);
687     }
688     send_openflow_buffer(dp, buffer, sender);
689 }
690
691 void
692 dp_update_port_flags(struct datapath *dp, const struct ofp_port_mod *opm)
693 {
694     const struct ofp_phy_port *opp = &opm->desc;
695     int port_no = ntohs(opp->port_no);
696     if (port_no < OFPP_MAX) {
697         struct sw_port *p = &dp->ports[port_no];
698         uint32_t flag_mask;
699
700         /* Make sure the port id hasn't changed since this was sent */
701         if (!p || memcmp(opp->hw_addr, netdev_get_etheraddr(p->netdev),
702                          ETH_ADDR_LEN) != 0) {
703             return;
704         }
705
706
707         flag_mask = ntohl(opm->mask) & PORT_FLAG_BITS;
708         if (flag_mask) {
709             p->flags &= ~flag_mask;
710             p->flags |= ntohl(opp->flags) & flag_mask;
711         }
712
713         if (opm->mask & htonl(OFPPFL_PORT_DOWN)) {
714             if ((opp->flags & htonl(OFPPFL_PORT_DOWN))
715                 && (p->status & OFPPFL_PORT_DOWN) == 0) {
716                 p->status |= OFPPFL_PORT_DOWN;
717                 netdev_turn_flags_off(p->netdev, NETDEV_UP, true);
718             } else if ((opp->flags & htonl(OFPPFL_PORT_DOWN)) == 0
719                        && (p->status & OFPPFL_PORT_DOWN)) {
720                 p->status &= ~OFPPFL_PORT_DOWN;
721                 netdev_turn_flags_on(p->netdev, NETDEV_UP, true);
722             }
723         }
724     }
725 }
726
727 /* Update the port status field of the bridge port.  A non-zero return
728  * value indicates some field has changed. 
729  *
730  * NB: Callers of this function may hold the RCU read lock, so any
731  * additional checks must not sleep.
732  */
733 static int
734 update_port_status(struct sw_port *p)
735 {
736     int retval;
737     enum netdev_flags flags;
738     uint32_t orig_status = p->status;
739
740     if (netdev_get_flags(p->netdev, &flags) < 0) {
741         VLOG_WARN_RL(&rl, "could not get netdev flags for %s", 
742                      netdev_get_name(p->netdev));
743         return 0;
744     } else {
745         if (flags & NETDEV_UP) {
746             p->status &= ~OFPPFL_PORT_DOWN;
747         } else {
748             p->status |= OFPPFL_PORT_DOWN;
749         } 
750     }
751
752     /* Not all cards support this getting link status, so don't warn on
753      * error. */
754     retval = netdev_get_link_status(p->netdev);
755     if (retval == 1) {
756         p->status &= ~OFPPFL_LINK_DOWN;
757     } else if (retval == 0) {
758         p->status |= OFPPFL_LINK_DOWN;
759     } 
760
761     return (orig_status != p->status);
762 }
763
764 static void
765 send_port_status(struct sw_port *p, uint8_t status) 
766 {
767     struct ofpbuf *buffer;
768     struct ofp_port_status *ops;
769     ops = make_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, 0, &buffer);
770     ops->reason = status;
771     memset(ops->pad, 0, sizeof ops->pad);
772     fill_port_desc(p->dp, p, &ops->desc);
773
774     send_openflow_buffer(p->dp, buffer, NULL);
775 }
776
777 void
778 send_flow_expired(struct datapath *dp, struct sw_flow *flow,
779                   enum ofp_flow_expired_reason reason)
780 {
781     struct ofpbuf *buffer;
782     struct ofp_flow_expired *ofe;
783     ofe = make_openflow_xid(sizeof *ofe, OFPT_FLOW_EXPIRED, 0, &buffer);
784     flow_fill_match(&ofe->match, &flow->key);
785
786     ofe->priority = htons(flow->priority);
787     ofe->reason = reason;
788     memset(ofe->pad, 0, sizeof ofe->pad);
789
790     ofe->duration     = htonl(time_now() - flow->created);
791     memset(ofe->pad2, 0, sizeof ofe->pad2);
792     ofe->packet_count = htonll(flow->packet_count);
793     ofe->byte_count   = htonll(flow->byte_count);
794     send_openflow_buffer(dp, buffer, NULL);
795 }
796
797 void
798 dp_send_error_msg(struct datapath *dp, const struct sender *sender,
799                   uint16_t type, uint16_t code, const void *data, size_t len)
800 {
801     struct ofpbuf *buffer;
802     struct ofp_error_msg *oem;
803     oem = make_openflow_reply(sizeof(*oem)+len, OFPT_ERROR, sender, &buffer);
804     oem->type = htons(type);
805     oem->code = htons(code);
806     memcpy(oem->data, data, len);
807     send_openflow_buffer(dp, buffer, sender);
808 }
809
810 static void
811 fill_flow_stats(struct ofpbuf *buffer, struct sw_flow *flow,
812                 int table_idx, time_t now)
813 {
814     struct ofp_flow_stats *ofs;
815     int length = sizeof *ofs + sizeof *ofs->actions * flow->n_actions;
816     ofs = ofpbuf_put_uninit(buffer, length);
817     ofs->length          = htons(length);
818     ofs->table_id        = table_idx;
819     ofs->pad             = 0;
820     ofs->match.wildcards = htonl(flow->key.wildcards);
821     ofs->match.in_port   = flow->key.flow.in_port;
822     memcpy(ofs->match.dl_src, flow->key.flow.dl_src, ETH_ADDR_LEN);
823     memcpy(ofs->match.dl_dst, flow->key.flow.dl_dst, ETH_ADDR_LEN);
824     ofs->match.dl_vlan   = flow->key.flow.dl_vlan;
825     ofs->match.dl_type   = flow->key.flow.dl_type;
826     ofs->match.nw_src    = flow->key.flow.nw_src;
827     ofs->match.nw_dst    = flow->key.flow.nw_dst;
828     ofs->match.nw_proto  = flow->key.flow.nw_proto;
829     ofs->match.pad       = 0;
830     ofs->match.tp_src    = flow->key.flow.tp_src;
831     ofs->match.tp_dst    = flow->key.flow.tp_dst;
832     ofs->duration        = htonl(now - flow->created);
833     ofs->priority        = htons(flow->priority);
834     ofs->idle_timeout    = htons(flow->idle_timeout);
835     ofs->hard_timeout    = htons(flow->hard_timeout);
836     memset(ofs->pad2, 0, sizeof ofs->pad2);
837     ofs->packet_count    = htonll(flow->packet_count);
838     ofs->byte_count      = htonll(flow->byte_count);
839     memcpy(ofs->actions, flow->actions,
840            sizeof *ofs->actions * flow->n_actions);
841 }
842
843 \f
844 /* 'buffer' was received on 'p', which may be a a physical switch port or a
845  * null pointer.  Process it according to 'dp''s flow table.  Returns 0 if
846  * successful, in which case 'buffer' is destroyed, or -ESRCH if there is no
847  * matching flow, in which case 'buffer' still belongs to the caller. */
848 int run_flow_through_tables(struct datapath *dp, struct ofpbuf *buffer,
849                             struct sw_port *p)
850 {
851     struct sw_flow_key key;
852     struct sw_flow *flow;
853
854     key.wildcards = 0;
855     if (flow_extract(buffer, p ? port_no(dp, p) : OFPP_NONE, &key.flow)
856         && (dp->flags & OFPC_FRAG_MASK) == OFPC_FRAG_DROP) {
857         /* Drop fragment. */
858         ofpbuf_delete(buffer);
859         return 0;
860     }
861         if (p && p->flags & (OFPPFL_NO_RECV | OFPPFL_NO_RECV_STP)
862         && p->flags & (!eth_addr_equals(key.flow.dl_dst, stp_eth_addr)
863                        ? OFPPFL_NO_RECV : OFPPFL_NO_RECV_STP)) {
864                 ofpbuf_delete(buffer);
865                 return 0;
866         }
867
868     flow = chain_lookup(dp->chain, &key);
869     if (flow != NULL) {
870         flow_used(flow, buffer);
871         execute_actions(dp, buffer, port_no(dp, p),
872                         &key, flow->actions, flow->n_actions, false);
873         return 0;
874     } else {
875         return -ESRCH;
876     }
877 }
878
879 /* 'buffer' was received on 'p', which may be a a physical switch port or a
880  * null pointer.  Process it according to 'dp''s flow table, sending it up to
881  * the controller if no flow matches.  Takes ownership of 'buffer'. */
882 void fwd_port_input(struct datapath *dp, struct ofpbuf *buffer,
883                     struct sw_port *p)
884 {
885     if (run_flow_through_tables(dp, buffer, p)) {
886         dp_output_control(dp, buffer, port_no(dp, p),
887                           dp->miss_send_len, OFPR_NO_MATCH);
888     }
889 }
890
891 static void
892 do_output(struct datapath *dp, struct ofpbuf *buffer, int in_port,
893           size_t max_len, int out_port, bool ignore_no_fwd)
894 {
895     if (out_port != OFPP_CONTROLLER) {
896         dp_output_port(dp, buffer, in_port, out_port, ignore_no_fwd);
897     } else {
898         dp_output_control(dp, buffer, in_port, max_len, OFPR_ACTION);
899     }
900 }
901
902 static void
903 execute_actions(struct datapath *dp, struct ofpbuf *buffer,
904                 int in_port, const struct sw_flow_key *key,
905                 const struct ofp_action *actions, int n_actions,
906                 bool ignore_no_fwd)
907 {
908     /* Every output action needs a separate clone of 'buffer', but the common
909      * case is just a single output action, so that doing a clone and then
910      * freeing the original buffer is wasteful.  So the following code is
911      * slightly obscure just to avoid that. */
912     int prev_port;
913     size_t max_len=0;        /* Initialze to make compiler happy */
914     uint16_t eth_proto;
915     int i;
916
917     prev_port = -1;
918     eth_proto = ntohs(key->flow.dl_type);
919
920     for (i = 0; i < n_actions; i++) {
921         const struct ofp_action *a = &actions[i];
922         struct eth_header *eh = buffer->l2;
923
924         if (prev_port != -1) {
925             do_output(dp, ofpbuf_clone(buffer), in_port, max_len, prev_port,
926                       ignore_no_fwd);
927             prev_port = -1;
928         }
929
930         switch (ntohs(a->type)) {
931         case OFPAT_OUTPUT:
932             prev_port = ntohs(a->arg.output.port);
933             max_len = ntohs(a->arg.output.max_len);
934             break;
935
936         case OFPAT_SET_DL_VLAN:
937             modify_vlan(buffer, key, a);
938             break;
939
940         case OFPAT_SET_DL_SRC:
941             memcpy(eh->eth_src, a->arg.dl_addr, sizeof eh->eth_src);
942             break;
943
944         case OFPAT_SET_DL_DST:
945             memcpy(eh->eth_dst, a->arg.dl_addr, sizeof eh->eth_dst);
946             break;
947
948         case OFPAT_SET_NW_SRC:
949         case OFPAT_SET_NW_DST:
950             modify_nh(buffer, eth_proto, key->flow.nw_proto, a);
951             break;
952
953         case OFPAT_SET_TP_SRC:
954         case OFPAT_SET_TP_DST:
955             modify_th(buffer, eth_proto, key->flow.nw_proto, a);
956             break;
957
958         default:
959             NOT_REACHED();
960         }
961     }
962     if (prev_port != -1)
963         do_output(dp, buffer, in_port, max_len, prev_port, ignore_no_fwd);
964     else
965         ofpbuf_delete(buffer);
966 }
967
968 static void modify_nh(struct ofpbuf *buffer, uint16_t eth_proto,
969                       uint8_t nw_proto, const struct ofp_action *a)
970 {
971     if (eth_proto == ETH_TYPE_IP) {
972         struct ip_header *nh = buffer->l3;
973         uint32_t new, *field;
974
975         new = a->arg.nw_addr;
976         field = a->type == OFPAT_SET_NW_SRC ? &nh->ip_src : &nh->ip_dst;
977         if (nw_proto == IP_TYPE_TCP) {
978             struct tcp_header *th = buffer->l4;
979             th->tcp_csum = recalc_csum32(th->tcp_csum, *field, new);
980         } else if (nw_proto == IP_TYPE_UDP) {
981             struct udp_header *th = buffer->l4;
982             if (th->udp_csum) {
983                 th->udp_csum = recalc_csum32(th->udp_csum, *field, new);
984                 if (!th->udp_csum) {
985                     th->udp_csum = 0xffff;
986                 }
987             }
988         }
989         nh->ip_csum = recalc_csum32(nh->ip_csum, *field, new);
990         *field = new;
991     }
992 }
993
994 static void modify_th(struct ofpbuf *buffer, uint16_t eth_proto,
995                       uint8_t nw_proto, const struct ofp_action *a)
996 {
997     if (eth_proto == ETH_TYPE_IP) {
998         uint16_t new, *field;
999
1000         new = a->arg.tp;
1001
1002         if (nw_proto == IP_TYPE_TCP) {
1003             struct tcp_header *th = buffer->l4;
1004             field = a->type == OFPAT_SET_TP_SRC ? &th->tcp_src : &th->tcp_dst;
1005             th->tcp_csum = recalc_csum16(th->tcp_csum, *field, new);
1006             *field = new;
1007         } else if (nw_proto == IP_TYPE_UDP) {
1008             struct udp_header *th = buffer->l4;
1009             field = a->type == OFPAT_SET_TP_SRC ? &th->udp_src : &th->udp_dst;
1010             th->udp_csum = recalc_csum16(th->udp_csum, *field, new);
1011             *field = new;
1012         }
1013     }
1014 }
1015
1016 static void
1017 modify_vlan(struct ofpbuf *buffer,
1018             const struct sw_flow_key *key, const struct ofp_action *a)
1019 {
1020     uint16_t new_id = a->arg.vlan_id;
1021     struct vlan_eth_header *veh;
1022
1023     if (new_id != htons(OFP_VLAN_NONE)) {
1024         if (key->flow.dl_vlan != htons(OFP_VLAN_NONE)) {
1025             /* Modify vlan id, but maintain other TCI values */
1026             veh = buffer->l2;
1027             veh->veth_tci &= ~htons(VLAN_VID);
1028             veh->veth_tci |= new_id;
1029         } else {
1030             /* Insert new vlan id. */
1031             struct eth_header *eh = buffer->l2;
1032             struct vlan_eth_header tmp;
1033             memcpy(tmp.veth_dst, eh->eth_dst, ETH_ADDR_LEN);
1034             memcpy(tmp.veth_src, eh->eth_src, ETH_ADDR_LEN);
1035             tmp.veth_type = htons(ETH_TYPE_VLAN);
1036             tmp.veth_tci = new_id;
1037             tmp.veth_next_type = eh->eth_type;
1038             
1039             veh = ofpbuf_push_uninit(buffer, VLAN_HEADER_LEN);
1040             memcpy(veh, &tmp, sizeof tmp);
1041             buffer->l2 = (char*)buffer->l2 - VLAN_HEADER_LEN;
1042         }
1043     } else  {
1044         /* Remove an existing vlan header if it exists */
1045         veh = buffer->l2;
1046         if (veh->veth_type == htons(ETH_TYPE_VLAN)) {
1047             struct eth_header tmp;
1048             
1049             memcpy(tmp.eth_dst, veh->veth_dst, ETH_ADDR_LEN);
1050             memcpy(tmp.eth_src, veh->veth_src, ETH_ADDR_LEN);
1051             tmp.eth_type = veh->veth_next_type;
1052             
1053             buffer->size -= VLAN_HEADER_LEN;
1054             buffer->data = (char*)buffer->data + VLAN_HEADER_LEN;
1055             buffer->l2 = (char*)buffer->l2 + VLAN_HEADER_LEN;
1056             memcpy(buffer->data, &tmp, sizeof tmp);
1057         }
1058     }
1059 }
1060
1061 static int
1062 recv_features_request(struct datapath *dp, const struct sender *sender,
1063                       const void *msg) 
1064 {
1065     dp_send_features_reply(dp, sender);
1066     return 0;
1067 }
1068
1069 static int
1070 recv_get_config_request(struct datapath *dp, const struct sender *sender,
1071                         const void *msg) 
1072 {
1073     struct ofpbuf *buffer;
1074     struct ofp_switch_config *osc;
1075
1076     osc = make_openflow_reply(sizeof *osc, OFPT_GET_CONFIG_REPLY,
1077                               sender, &buffer);
1078
1079     osc->flags = htons(dp->flags);
1080     osc->miss_send_len = htons(dp->miss_send_len);
1081
1082     return send_openflow_buffer(dp, buffer, sender);
1083 }
1084
1085 static int
1086 recv_set_config(struct datapath *dp, const struct sender *sender UNUSED,
1087                 const void *msg)
1088 {
1089     const struct ofp_switch_config *osc = msg;
1090     int flags;
1091
1092     flags = ntohs(osc->flags) & (OFPC_SEND_FLOW_EXP | OFPC_FRAG_MASK);
1093     if ((flags & OFPC_FRAG_MASK) != OFPC_FRAG_NORMAL
1094         && (flags & OFPC_FRAG_MASK) != OFPC_FRAG_DROP) {
1095         flags = (flags & ~OFPC_FRAG_MASK) | OFPC_FRAG_DROP;
1096     }
1097     dp->flags = flags;
1098     dp->miss_send_len = ntohs(osc->miss_send_len);
1099     return 0;
1100 }
1101
1102 static int
1103 recv_packet_out(struct datapath *dp, const struct sender *sender UNUSED,
1104                 const void *msg)
1105 {
1106     const struct ofp_packet_out *opo = msg;
1107     struct sw_flow_key key;
1108     struct ofpbuf *buffer;
1109     int n_actions = ntohs(opo->n_actions);
1110     int act_len = n_actions * sizeof opo->actions[0];
1111
1112     if (act_len > (ntohs(opo->header.length) - sizeof *opo)) {
1113         VLOG_DBG_RL(&rl, "message too short for number of actions");
1114         return -EINVAL;
1115     }
1116
1117     if (ntohl(opo->buffer_id) == (uint32_t) -1) {
1118         /* FIXME: can we avoid copying data here? */
1119         int data_len = ntohs(opo->header.length) - sizeof *opo - act_len;
1120         buffer = ofpbuf_new(data_len);
1121         ofpbuf_put(buffer, &opo->actions[n_actions], data_len);
1122     } else {
1123         buffer = retrieve_buffer(ntohl(opo->buffer_id));
1124         if (!buffer) {
1125             return -ESRCH; 
1126         }
1127     }
1128  
1129     flow_extract(buffer, ntohs(opo->in_port), &key.flow);
1130     execute_actions(dp, buffer, ntohs(opo->in_port),
1131                     &key, opo->actions, n_actions, true);
1132
1133    return 0;
1134 }
1135
1136 static int
1137 recv_port_mod(struct datapath *dp, const struct sender *sender UNUSED,
1138               const void *msg)
1139 {
1140     const struct ofp_port_mod *opm = msg;
1141
1142     dp_update_port_flags(dp, opm);
1143
1144     return 0;
1145 }
1146
1147 static int
1148 add_flow(struct datapath *dp, const struct ofp_flow_mod *ofm)
1149 {
1150     int error = -ENOMEM;
1151     int n_actions;
1152     int i;
1153     struct sw_flow *flow;
1154
1155
1156     /* To prevent loops, make sure there's no action to send to the
1157      * OFP_TABLE virtual port.
1158      */
1159     n_actions = (ntohs(ofm->header.length) - sizeof *ofm) 
1160             / sizeof *ofm->actions;
1161     for (i=0; i<n_actions; i++) {
1162         const struct ofp_action *a = &ofm->actions[i];
1163
1164         if (a->type == htons(OFPAT_OUTPUT)
1165                     && (a->arg.output.port == htons(OFPP_TABLE)
1166                         || a->arg.output.port == htons(OFPP_NONE)
1167                         || a->arg.output.port == ofm->match.in_port)) {
1168             /* xxx Send fancy new error message? */
1169             goto error;
1170         }
1171     }
1172
1173     /* Allocate memory. */
1174     flow = flow_alloc(n_actions);
1175     if (flow == NULL)
1176         goto error;
1177
1178     /* Fill out flow. */
1179     flow_extract_match(&flow->key, &ofm->match);
1180     flow->priority = flow->key.wildcards ? ntohs(ofm->priority) : -1;
1181     flow->idle_timeout = ntohs(ofm->idle_timeout);
1182     flow->hard_timeout = ntohs(ofm->hard_timeout);
1183     flow->used = flow->created = time_now();
1184     flow->n_actions = n_actions;
1185     flow->byte_count = 0;
1186     flow->packet_count = 0;
1187     memcpy(flow->actions, ofm->actions, n_actions * sizeof *flow->actions);
1188
1189     /* Act. */
1190     error = chain_insert(dp->chain, flow);
1191     if (error) {
1192         goto error_free_flow; 
1193     }
1194     error = 0;
1195     if (ntohl(ofm->buffer_id) != UINT32_MAX) {
1196         struct ofpbuf *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
1197         if (buffer) {
1198             struct sw_flow_key key;
1199             uint16_t in_port = ntohs(ofm->match.in_port);
1200             flow_used(flow, buffer);
1201             flow_extract(buffer, in_port, &key.flow);
1202             execute_actions(dp, buffer, in_port, &key,
1203                             ofm->actions, n_actions, false);
1204         } else {
1205             error = -ESRCH; 
1206         }
1207     }
1208     return error;
1209
1210 error_free_flow:
1211     flow_free(flow);
1212 error:
1213     if (ntohl(ofm->buffer_id) != (uint32_t) -1)
1214         discard_buffer(ntohl(ofm->buffer_id));
1215     return error;
1216 }
1217
1218 static int
1219 recv_flow(struct datapath *dp, const struct sender *sender UNUSED,
1220           const void *msg)
1221 {
1222     const struct ofp_flow_mod *ofm = msg;
1223     uint16_t command = ntohs(ofm->command);
1224
1225     if (command == OFPFC_ADD) {
1226         return add_flow(dp, ofm);
1227     }  else if (command == OFPFC_DELETE) {
1228         struct sw_flow_key key;
1229         flow_extract_match(&key, &ofm->match);
1230         return chain_delete(dp->chain, &key, 0, 0) ? 0 : -ESRCH;
1231     } else if (command == OFPFC_DELETE_STRICT) {
1232         struct sw_flow_key key;
1233         uint16_t priority;
1234         flow_extract_match(&key, &ofm->match);
1235         priority = key.wildcards ? ntohs(ofm->priority) : -1;
1236         return chain_delete(dp->chain, &key, priority, 1) ? 0 : -ESRCH;
1237     } else {
1238         return -ENODEV;
1239     }
1240 }
1241
1242 static int desc_stats_dump(struct datapath *dp, void *state,
1243                               struct ofpbuf *buffer)
1244 {
1245     struct ofp_desc_stats *ods = ofpbuf_put_uninit(buffer, sizeof *ods);
1246
1247     strncpy(ods->mfr_desc, &mfr_desc, sizeof ods->mfr_desc);
1248     strncpy(ods->hw_desc, &hw_desc, sizeof ods->hw_desc);
1249     strncpy(ods->sw_desc, &sw_desc, sizeof ods->sw_desc);
1250     strncpy(ods->serial_num, &serial_num, sizeof ods->serial_num);
1251
1252     return 0;
1253 }
1254
1255 struct flow_stats_state {
1256     int table_idx;
1257     struct sw_table_position position;
1258     struct ofp_flow_stats_request rq;
1259     time_t now;
1260
1261     struct ofpbuf *buffer;
1262 };
1263
1264 #define MAX_FLOW_STATS_BYTES 4096
1265
1266 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
1267                            void **state)
1268 {
1269     const struct ofp_flow_stats_request *fsr = body;
1270     struct flow_stats_state *s = xmalloc(sizeof *s);
1271     s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
1272     memset(&s->position, 0, sizeof s->position);
1273     s->rq = *fsr;
1274     *state = s;
1275     return 0;
1276 }
1277
1278 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
1279 {
1280     struct flow_stats_state *s = private;
1281     fill_flow_stats(s->buffer, flow, s->table_idx, s->now);
1282     return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1283 }
1284
1285 static int flow_stats_dump(struct datapath *dp, void *state,
1286                            struct ofpbuf *buffer)
1287 {
1288     struct flow_stats_state *s = state;
1289     struct sw_flow_key match_key;
1290
1291     flow_extract_match(&match_key, &s->rq.match);
1292     s->buffer = buffer;
1293     s->now = time_now();
1294     while (s->table_idx < dp->chain->n_tables
1295            && (s->rq.table_id == 0xff || s->rq.table_id == s->table_idx))
1296     {
1297         struct sw_table *table = dp->chain->tables[s->table_idx];
1298
1299         if (table->iterate(table, &match_key, &s->position,
1300                            flow_stats_dump_callback, s))
1301             break;
1302
1303         s->table_idx++;
1304         memset(&s->position, 0, sizeof s->position);
1305     }
1306     return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1307 }
1308
1309 static void flow_stats_done(void *state)
1310 {
1311     free(state);
1312 }
1313
1314 struct aggregate_stats_state {
1315     struct ofp_aggregate_stats_request rq;
1316 };
1317
1318 static int aggregate_stats_init(struct datapath *dp,
1319                                 const void *body, int body_len,
1320                                 void **state)
1321 {
1322     const struct ofp_aggregate_stats_request *rq = body;
1323     struct aggregate_stats_state *s = xmalloc(sizeof *s);
1324     s->rq = *rq;
1325     *state = s;
1326     return 0;
1327 }
1328
1329 static int aggregate_stats_dump_callback(struct sw_flow *flow, void *private)
1330 {
1331     struct ofp_aggregate_stats_reply *rpy = private;
1332     rpy->packet_count += flow->packet_count;
1333     rpy->byte_count += flow->byte_count;
1334     rpy->flow_count++;
1335     return 0;
1336 }
1337
1338 static int aggregate_stats_dump(struct datapath *dp, void *state,
1339                                 struct ofpbuf *buffer)
1340 {
1341     struct aggregate_stats_state *s = state;
1342     struct ofp_aggregate_stats_request *rq = &s->rq;
1343     struct ofp_aggregate_stats_reply *rpy;
1344     struct sw_table_position position;
1345     struct sw_flow_key match_key;
1346     int table_idx;
1347
1348     rpy = ofpbuf_put_uninit(buffer, sizeof *rpy);
1349     memset(rpy, 0, sizeof *rpy);
1350
1351     flow_extract_match(&match_key, &rq->match);
1352     table_idx = rq->table_id == 0xff ? 0 : rq->table_id;
1353     memset(&position, 0, sizeof position);
1354     while (table_idx < dp->chain->n_tables
1355            && (rq->table_id == 0xff || rq->table_id == table_idx))
1356     {
1357         struct sw_table *table = dp->chain->tables[table_idx];
1358         int error;
1359
1360         error = table->iterate(table, &match_key, &position,
1361                                aggregate_stats_dump_callback, rpy);
1362         if (error)
1363             return error;
1364
1365         table_idx++;
1366         memset(&position, 0, sizeof position);
1367     }
1368
1369     rpy->packet_count = htonll(rpy->packet_count);
1370     rpy->byte_count = htonll(rpy->byte_count);
1371     rpy->flow_count = htonl(rpy->flow_count);
1372     return 0;
1373 }
1374
1375 static void aggregate_stats_done(void *state) 
1376 {
1377     free(state);
1378 }
1379
1380 static int table_stats_dump(struct datapath *dp, void *state,
1381                             struct ofpbuf *buffer)
1382 {
1383     int i;
1384     for (i = 0; i < dp->chain->n_tables; i++) {
1385         struct ofp_table_stats *ots = ofpbuf_put_uninit(buffer, sizeof *ots);
1386         struct sw_table_stats stats;
1387         dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
1388         strncpy(ots->name, stats.name, sizeof ots->name);
1389         ots->table_id = i;
1390         ots->wildcards = htonl(stats.wildcards);
1391         memset(ots->pad, 0, sizeof ots->pad);
1392         ots->max_entries = htonl(stats.max_flows);
1393         ots->active_count = htonl(stats.n_flows);
1394         ots->matched_count = htonll(stats.n_matched);
1395     }
1396     return 0;
1397 }
1398
1399 struct port_stats_state {
1400     int port;
1401 };
1402
1403 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
1404                void **state)
1405 {
1406     struct port_stats_state *s = xmalloc(sizeof *s);
1407     s->port = 0;
1408     *state = s;
1409     return 0;
1410 }
1411
1412 static int port_stats_dump(struct datapath *dp, void *state,
1413                            struct ofpbuf *buffer)
1414 {
1415     struct port_stats_state *s = state;
1416     int i;
1417
1418     for (i = s->port; i < OFPP_MAX; i++) {
1419         struct sw_port *p = &dp->ports[i];
1420         struct ofp_port_stats *ops;
1421         if (!p->netdev) {
1422             continue;
1423         }
1424         ops = ofpbuf_put_uninit(buffer, sizeof *ops);
1425         ops->port_no = htons(port_no(dp, p));
1426         memset(ops->pad, 0, sizeof ops->pad);
1427         ops->rx_packets   = htonll(p->rx_packets);
1428         ops->tx_packets   = htonll(p->tx_packets);
1429         ops->rx_bytes     = htonll(p->rx_bytes);
1430         ops->tx_bytes     = htonll(p->tx_bytes);
1431         ops->rx_dropped   = htonll(-1);
1432         ops->tx_dropped   = htonll(p->tx_dropped);
1433         ops->rx_errors    = htonll(-1);
1434         ops->tx_errors    = htonll(-1);
1435         ops->rx_frame_err = htonll(-1);
1436         ops->rx_over_err  = htonll(-1);
1437         ops->rx_crc_err   = htonll(-1);
1438         ops->collisions   = htonll(-1);
1439         ops++;
1440     }
1441     s->port = i;
1442     return 0;
1443 }
1444
1445 static void port_stats_done(void *state)
1446 {
1447     free(state);
1448 }
1449
1450 struct stats_type {
1451     /* Value for 'type' member of struct ofp_stats_request. */
1452     int type;
1453
1454     /* Minimum and maximum acceptable number of bytes in body member of
1455      * struct ofp_stats_request. */
1456     size_t min_body, max_body;
1457
1458     /* Prepares to dump some kind of statistics on 'dp'.  'body' and
1459      * 'body_len' are the 'body' member of the struct ofp_stats_request.
1460      * Returns zero if successful, otherwise a negative error code.
1461      * May initialize '*state' to state information.  May be null if no
1462      * initialization is required.*/
1463     int (*init)(struct datapath *dp, const void *body, int body_len,
1464             void **state);
1465
1466     /* Appends statistics for 'dp' to 'buffer', which initially contains a
1467      * struct ofp_stats_reply.  On success, it should return 1 if it should be
1468      * called again later with another buffer, 0 if it is done, or a negative
1469      * errno value on failure. */
1470     int (*dump)(struct datapath *dp, void *state, struct ofpbuf *buffer);
1471
1472     /* Cleans any state created by the init or dump functions.  May be null
1473      * if no cleanup is required. */
1474     void (*done)(void *state);
1475 };
1476
1477 static const struct stats_type stats[] = {
1478     {
1479         OFPST_DESC,
1480         0,
1481         0,
1482         NULL,
1483         desc_stats_dump,
1484         NULL
1485     },
1486     {
1487         OFPST_FLOW,
1488         sizeof(struct ofp_flow_stats_request),
1489         sizeof(struct ofp_flow_stats_request),
1490         flow_stats_init,
1491         flow_stats_dump,
1492         flow_stats_done
1493     },
1494     {
1495         OFPST_AGGREGATE,
1496         sizeof(struct ofp_aggregate_stats_request),
1497         sizeof(struct ofp_aggregate_stats_request),
1498         aggregate_stats_init,
1499         aggregate_stats_dump,
1500         aggregate_stats_done
1501     },
1502     {
1503         OFPST_TABLE,
1504         0,
1505         0,
1506         NULL,
1507         table_stats_dump,
1508         NULL
1509     },
1510     {
1511         OFPST_PORT,
1512         0,
1513         0,
1514         port_stats_init,
1515         port_stats_dump,
1516         port_stats_done
1517     },
1518 };
1519
1520 struct stats_dump_cb {
1521     bool done;
1522     struct ofp_stats_request *rq;
1523     struct sender sender;
1524     const struct stats_type *s;
1525     void *state;
1526 };
1527
1528 static int
1529 stats_dump(struct datapath *dp, void *cb_)
1530 {
1531     struct stats_dump_cb *cb = cb_;
1532     struct ofp_stats_reply *osr;
1533     struct ofpbuf *buffer;
1534     int err;
1535
1536     if (cb->done) {
1537         return 0;
1538     }
1539
1540     osr = make_openflow_reply(sizeof *osr, OFPT_STATS_REPLY, &cb->sender,
1541                               &buffer);
1542     osr->type = htons(cb->s->type);
1543     osr->flags = 0;
1544
1545     err = cb->s->dump(dp, cb->state, buffer);
1546     if (err >= 0) {
1547         int err2;
1548         if (!err) {
1549             cb->done = true;
1550         } else {
1551             /* Buffer might have been reallocated, so find our data again. */
1552             osr = ofpbuf_at_assert(buffer, 0, sizeof *osr);
1553             osr->flags = ntohs(OFPSF_REPLY_MORE);
1554         }
1555         err2 = send_openflow_buffer(dp, buffer, &cb->sender);
1556         if (err2) {
1557             err = err2;
1558         }
1559     }
1560
1561     return err;
1562 }
1563
1564 static void
1565 stats_done(void *cb_)
1566 {
1567     struct stats_dump_cb *cb = cb_;
1568     if (cb) {
1569         if (cb->s->done) {
1570             cb->s->done(cb->state);
1571         }
1572         free(cb);
1573     }
1574 }
1575
1576 static int
1577 recv_stats_request(struct datapath *dp, const struct sender *sender,
1578                    const void *oh)
1579 {
1580     const struct ofp_stats_request *rq = oh;
1581     size_t rq_len = ntohs(rq->header.length);
1582     const struct stats_type *st;
1583     struct stats_dump_cb *cb;
1584     int type, body_len;
1585     int err;
1586
1587     type = ntohs(rq->type);
1588     for (st = stats; ; st++) {
1589         if (st >= &stats[ARRAY_SIZE(stats)]) {
1590             VLOG_WARN_RL(&rl, "received stats request of unknown type %d",
1591                          type);
1592             return -EINVAL;
1593         } else if (type == st->type) {
1594             break;
1595         }
1596     }
1597
1598     cb = xmalloc(sizeof *cb);
1599     cb->done = false;
1600     cb->rq = xmemdup(rq, rq_len);
1601     cb->sender = *sender;
1602     cb->s = st;
1603     cb->state = NULL;
1604     
1605     body_len = rq_len - offsetof(struct ofp_stats_request, body);
1606     if (body_len < cb->s->min_body || body_len > cb->s->max_body) {
1607         VLOG_WARN_RL(&rl, "stats request type %d with bad body length %d",
1608                      type, body_len);
1609         err = -EINVAL;
1610         goto error;
1611     }
1612
1613     if (cb->s->init) {
1614         err = cb->s->init(dp, rq->body, body_len, &cb->state);
1615         if (err) {
1616             VLOG_WARN_RL(&rl,
1617                          "failed initialization of stats request type %d: %s",
1618                          type, strerror(-err));
1619             goto error;
1620         }
1621     }
1622
1623     remote_start_dump(sender->remote, stats_dump, stats_done, cb);
1624     return 0;
1625
1626 error:
1627     free(cb->rq);
1628     free(cb);
1629     return err;
1630 }
1631
1632 static int
1633 recv_echo_request(struct datapath *dp, const struct sender *sender,
1634                   const void *oh)
1635 {
1636     return send_openflow_buffer(dp, make_echo_reply(oh), sender);
1637 }
1638
1639 static int
1640 recv_echo_reply(struct datapath *dp UNUSED, const struct sender *sender UNUSED,
1641                   const void *oh UNUSED)
1642 {
1643     return 0;
1644 }
1645
1646 /* 'msg', which is 'length' bytes long, was received from the control path.
1647  * Apply it to 'chain'. */
1648 int
1649 fwd_control_input(struct datapath *dp, const struct sender *sender,
1650                   const void *msg, size_t length)
1651 {
1652     int (*handler)(struct datapath *, const struct sender *, const void *);
1653     struct ofp_header *oh;
1654     size_t min_size;
1655
1656     /* Check encapsulated length. */
1657     oh = (struct ofp_header *) msg;
1658     if (ntohs(oh->length) > length) {
1659         return -EINVAL;
1660     }
1661     assert(oh->version == OFP_VERSION);
1662
1663     /* Figure out how to handle it. */
1664     switch (oh->type) {
1665     case OFPT_FEATURES_REQUEST:
1666         min_size = sizeof(struct ofp_header);
1667         handler = recv_features_request;
1668         break;
1669     case OFPT_GET_CONFIG_REQUEST:
1670         min_size = sizeof(struct ofp_header);
1671         handler = recv_get_config_request;
1672         break;
1673     case OFPT_SET_CONFIG:
1674         min_size = sizeof(struct ofp_switch_config);
1675         handler = recv_set_config;
1676         break;
1677     case OFPT_PACKET_OUT:
1678         min_size = sizeof(struct ofp_packet_out);
1679         handler = recv_packet_out;
1680         break;
1681     case OFPT_FLOW_MOD:
1682         min_size = sizeof(struct ofp_flow_mod);
1683         handler = recv_flow;
1684         break;
1685     case OFPT_PORT_MOD:
1686         min_size = sizeof(struct ofp_port_mod);
1687         handler = recv_port_mod;
1688         break;
1689     case OFPT_STATS_REQUEST:
1690         min_size = sizeof(struct ofp_stats_request);
1691         handler = recv_stats_request;
1692         break;
1693     case OFPT_ECHO_REQUEST:
1694         min_size = sizeof(struct ofp_header);
1695         handler = recv_echo_request;
1696         break;
1697     case OFPT_ECHO_REPLY:
1698         min_size = sizeof(struct ofp_header);
1699         handler = recv_echo_reply;
1700         break;
1701     default:
1702         dp_send_error_msg(dp, sender, OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE,
1703                           msg, length);
1704         return -EINVAL;
1705     }
1706
1707     /* Handle it. */
1708     if (length < min_size)
1709         return -EFAULT;
1710     return handler(dp, sender, msg);
1711 }
1712 \f
1713 /* Packet buffering. */
1714
1715 #define OVERWRITE_SECS  1
1716
1717 struct packet_buffer {
1718     struct ofpbuf *buffer;
1719     uint32_t cookie;
1720     time_t timeout;
1721 };
1722
1723 static struct packet_buffer buffers[N_PKT_BUFFERS];
1724 static unsigned int buffer_idx;
1725
1726 uint32_t save_buffer(struct ofpbuf *buffer)
1727 {
1728     struct packet_buffer *p;
1729     uint32_t id;
1730
1731     buffer_idx = (buffer_idx + 1) & PKT_BUFFER_MASK;
1732     p = &buffers[buffer_idx];
1733     if (p->buffer) {
1734         /* Don't buffer packet if existing entry is less than
1735          * OVERWRITE_SECS old. */
1736         if (time_now() < p->timeout) { /* FIXME */
1737             return -1;
1738         } else {
1739             ofpbuf_delete(p->buffer); 
1740         }
1741     }
1742     /* Don't use maximum cookie value since the all-bits-1 id is
1743      * special. */
1744     if (++p->cookie >= (1u << PKT_COOKIE_BITS) - 1)
1745         p->cookie = 0;
1746     p->buffer = ofpbuf_clone(buffer);      /* FIXME */
1747     p->timeout = time_now() + OVERWRITE_SECS; /* FIXME */
1748     id = buffer_idx | (p->cookie << PKT_BUFFER_BITS);
1749
1750     return id;
1751 }
1752
1753 static struct ofpbuf *retrieve_buffer(uint32_t id)
1754 {
1755     struct ofpbuf *buffer = NULL;
1756     struct packet_buffer *p;
1757
1758     p = &buffers[id & PKT_BUFFER_MASK];
1759     if (p->cookie == id >> PKT_BUFFER_BITS) {
1760         buffer = p->buffer;
1761         p->buffer = NULL;
1762     } else {
1763         printf("cookie mismatch: %x != %x\n",
1764                id >> PKT_BUFFER_BITS, p->cookie);
1765     }
1766
1767     return buffer;
1768 }
1769
1770 static void discard_buffer(uint32_t id)
1771 {
1772     struct packet_buffer *p;
1773
1774     p = &buffers[id & PKT_BUFFER_MASK];
1775     if (p->cookie == id >> PKT_BUFFER_BITS) {
1776         ofpbuf_delete(p->buffer);
1777         p->buffer = NULL;
1778     }
1779 }