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