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