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