Rename struct buffer to struct ofpbuf.
[sliver-openvswitch.git] / lib / dpif.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 <config.h>
35 #include "dpif.h"
36
37 #include <ctype.h>
38 #include <errno.h>
39 #include <inttypes.h>
40 #include <netinet/in.h>
41 #include <stdlib.h>
42 #include <string.h>
43
44 #include "netlink.h"
45 #include "netlink-protocol.h"
46 #include "ofpbuf.h"
47 #include "ofp-print.h"
48 #include "openflow-netlink.h"
49 #include "openflow.h"
50 #include "packets.h"
51 #include "util.h"
52 #include "xtoxll.h"
53
54 #include "vlog.h"
55 #define THIS_MODULE VLM_dpif
56
57 /* Not really much point in logging many dpif errors. */
58 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 60);
59
60 /* The Generic Netlink family number used for OpenFlow. */
61 static int openflow_family;
62
63 static int lookup_openflow_multicast_group(int dp_idx, int *multicast_group);
64 static int send_mgmt_command(struct dpif *, int command,
65                              const char *netdev);
66
67 /* Opens the local datapath numbered 'dp_idx', initializing 'dp'.  If
68  * 'subscribe' is true, listens for asynchronous messages (packet-in, etc.)
69  * from the datapath; otherwise, 'dp' will receive only replies to explicitly
70  * initiated requests. */
71 int
72 dpif_open(int dp_idx, bool subscribe, struct dpif *dp)
73 {
74     struct nl_sock *sock;
75     int multicast_group = 0;
76     int retval;
77
78     retval = nl_lookup_genl_family(DP_GENL_FAMILY_NAME, &openflow_family);
79     if (retval) {
80         return retval;
81     }
82
83     if (subscribe) {
84         retval = lookup_openflow_multicast_group(dp_idx, &multicast_group);
85         if (retval) {
86             return retval;
87         }
88     }
89
90     /* Specify a large so_rcvbuf size because we occasionally need to be able
91      * to retrieve large collections of flow records. */
92     retval = nl_sock_create(NETLINK_GENERIC, multicast_group, 0,
93                             4 * 1024u * 1024, &sock);
94     if (retval) {
95         return retval;
96     }
97
98     dp->dp_idx = dp_idx;
99     dp->sock = sock;
100     return 0;
101 }
102
103 /* Closes 'dp'. */
104 void
105 dpif_close(struct dpif *dp) 
106 {
107     nl_sock_destroy(dp->sock);
108 }
109
110 static const struct nl_policy openflow_policy[] = {
111     [DP_GENL_A_DP_IDX] = { .type = NL_A_U32 },
112     [DP_GENL_A_OPENFLOW] = { .type = NL_A_UNSPEC,
113                               .min_len = sizeof(struct ofp_header),
114                               .max_len = OFP_MAXLEN },
115 };
116
117 /* Tries to receive an openflow message from the kernel on 'sock'.  If
118  * successful, stores the received message into '*msgp' and returns 0.  The
119  * caller is responsible for destroying the message with ofpbuf_delete().  On
120  * failure, returns a positive errno value and stores a null pointer into
121  * '*msgp'.
122  *
123  * Only Netlink messages with embedded OpenFlow messages are accepted.  Other
124  * Netlink messages provoke errors.
125  *
126  * If 'wait' is true, dpif_recv_openflow waits for a message to be ready;
127  * otherwise, returns EAGAIN if the 'sock' receive buffer is empty. */
128 int
129 dpif_recv_openflow(struct dpif *dp, struct ofpbuf **bufferp,
130                         bool wait) 
131 {
132     struct nlattr *attrs[ARRAY_SIZE(openflow_policy)];
133     struct ofpbuf *buffer;
134     struct ofp_header *oh;
135     uint16_t ofp_len;
136     int retval;
137
138     buffer = *bufferp = NULL;
139     do {
140         ofpbuf_delete(buffer);
141         retval = nl_sock_recv(dp->sock, &buffer, wait);
142     } while (retval == ENOBUFS
143              || (!retval
144                  && (nl_msg_nlmsgerr(buffer, NULL)
145                      || nl_msg_nlmsghdr(buffer)->nlmsg_type == NLMSG_DONE)));
146     if (retval) {
147         if (retval != EAGAIN) {
148             VLOG_WARN_RL(&rl, "dpif_recv_openflow: %s", strerror(retval)); 
149         }
150         return retval;
151     }
152
153     if (nl_msg_genlmsghdr(buffer) == NULL) {
154         VLOG_DBG_RL(&rl, "received packet too short for Generic Netlink");
155         goto error;
156     }
157     if (nl_msg_nlmsghdr(buffer)->nlmsg_type != openflow_family) {
158         VLOG_DBG_RL(&rl, "received type (%"PRIu16") != openflow family (%d)",
159                     nl_msg_nlmsghdr(buffer)->nlmsg_type, openflow_family);
160         goto error;
161     }
162
163     if (!nl_policy_parse(buffer, openflow_policy, attrs,
164                          ARRAY_SIZE(openflow_policy))) {
165         goto error;
166     }
167     if (nl_attr_get_u32(attrs[DP_GENL_A_DP_IDX]) != dp->dp_idx) {
168         VLOG_WARN_RL(&rl, "received dp_idx (%"PRIu32") differs from expected "
169                      "(%d)", nl_attr_get_u32(attrs[DP_GENL_A_DP_IDX]),
170                      dp->dp_idx);
171         goto error;
172     }
173
174     oh = buffer->data = (void *) nl_attr_get(attrs[DP_GENL_A_OPENFLOW]);
175     buffer->size = nl_attr_get_size(attrs[DP_GENL_A_OPENFLOW]);
176     ofp_len = ntohs(oh->length);
177     if (ofp_len != buffer->size) {
178         VLOG_WARN_RL(&rl,
179                      "ofp_header.length %"PRIu16" != attribute length %zu\n",
180                      ofp_len, buffer->size);
181         buffer->size = MIN(ofp_len, buffer->size);
182     }
183     *bufferp = buffer;
184     return 0;
185
186 error:
187     ofpbuf_delete(buffer);
188     return EPROTO;
189 }
190
191 /* Encapsulates 'msg', which must contain an OpenFlow message, in a Netlink
192  * message, and sends it to the OpenFlow kernel module via 'sock'.
193  *
194  * Returns 0 if successful, otherwise a positive errno value.  If
195  * 'wait' is true, then the send will wait until buffer space is ready;
196  * otherwise, returns EAGAIN if the 'sock' send buffer is full.
197  *
198  * If the send is successful, then the kernel module will receive it, but there
199  * is no guarantee that any reply will not be dropped (see nl_sock_transact()
200  * for details). 
201  */
202 int
203 dpif_send_openflow(struct dpif *dp, struct ofpbuf *buffer, bool wait) 
204 {
205     struct ofp_header *oh;
206     unsigned int dump_flag;
207     struct ofpbuf hdr;
208     struct nlattr *nla;
209     uint32_t fixed_buffer[64 / 4];
210     struct iovec iov[3];
211     int pad_bytes;
212     int n_iov;
213     int retval;
214
215     /* The reply to OFPT_STATS_REQUEST may be multiple segments long, so we
216      * need to specify NLM_F_DUMP in the request. */
217     oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
218     dump_flag = oh->type == OFPT_STATS_REQUEST ? NLM_F_DUMP : 0;
219
220     ofpbuf_use(&hdr, fixed_buffer, sizeof fixed_buffer);
221     nl_msg_put_genlmsghdr(&hdr, dp->sock, 32, openflow_family,
222                           NLM_F_REQUEST | dump_flag, DP_GENL_C_OPENFLOW, 1);
223     nl_msg_put_u32(&hdr, DP_GENL_A_DP_IDX, dp->dp_idx);
224     nla = ofpbuf_put_uninit(&hdr, sizeof *nla);
225     nla->nla_len = sizeof *nla + buffer->size;
226     nla->nla_type = DP_GENL_A_OPENFLOW;
227     pad_bytes = NLA_ALIGN(nla->nla_len) - nla->nla_len;
228     nl_msg_nlmsghdr(&hdr)->nlmsg_len = hdr.size + buffer->size + pad_bytes;
229     n_iov = 2;
230     iov[0].iov_base = hdr.data;
231     iov[0].iov_len = hdr.size;
232     iov[1].iov_base = buffer->data;
233     iov[1].iov_len = buffer->size;
234     if (pad_bytes) {
235         static char zeros[NLA_ALIGNTO];
236         n_iov++;
237         iov[2].iov_base = zeros;
238         iov[2].iov_len = pad_bytes; 
239     }
240     retval = nl_sock_sendv(dp->sock, iov, n_iov, false);
241     if (retval && retval != EAGAIN) {
242         VLOG_WARN_RL(&rl, "dpif_send_openflow: %s", strerror(retval));
243     }
244     return retval;
245 }
246
247 /* Creates the datapath represented by 'dp'.  Returns 0 if successful,
248  * otherwise a positive errno value. */
249 int
250 dpif_add_dp(struct dpif *dp)
251 {
252     return send_mgmt_command(dp, DP_GENL_C_ADD_DP, NULL);
253 }
254
255 /* Destroys the datapath represented by 'dp'.  Returns 0 if successful,
256  * otherwise a positive errno value. */
257 int
258 dpif_del_dp(struct dpif *dp) 
259 {
260     return send_mgmt_command(dp, DP_GENL_C_DEL_DP, NULL);
261 }
262
263 /* Adds the Ethernet device named 'netdev' to this datapath.  Returns 0 if
264  * successful, otherwise a positive errno value. */
265 int
266 dpif_add_port(struct dpif *dp, const char *netdev)
267 {
268     return send_mgmt_command(dp, DP_GENL_C_ADD_PORT, netdev);
269 }
270
271 /* Removes the Ethernet device named 'netdev' from this datapath.  Returns 0
272  * if successful, otherwise a positive errno value. */
273 int
274 dpif_del_port(struct dpif *dp, const char *netdev)
275 {
276     return send_mgmt_command(dp, DP_GENL_C_DEL_PORT, netdev);
277 }
278 \f
279 static const struct nl_policy openflow_multicast_policy[] = {
280     [DP_GENL_A_DP_IDX] = { .type = NL_A_U32 },
281     [DP_GENL_A_MC_GROUP] = { .type = NL_A_U32 },
282 };
283
284 /* Looks up the Netlink multicast group used by datapath 'dp_idx'.  If
285  * successful, stores the multicast group in '*multicast_group' and returns 0.
286  * Otherwise, returns a positve errno value. */
287 static int
288 lookup_openflow_multicast_group(int dp_idx, int *multicast_group) 
289 {
290     struct nl_sock *sock;
291     struct ofpbuf request, *reply;
292     struct nlattr *attrs[ARRAY_SIZE(openflow_multicast_policy)];
293     int retval;
294
295     retval = nl_sock_create(NETLINK_GENERIC, 0, 0, 0, &sock);
296     if (retval) {
297         return retval;
298     }
299     ofpbuf_init(&request, 0);
300     nl_msg_put_genlmsghdr(&request, sock, 0, openflow_family, NLM_F_REQUEST,
301                           DP_GENL_C_QUERY_DP, 1);
302     nl_msg_put_u32(&request, DP_GENL_A_DP_IDX, dp_idx);
303     retval = nl_sock_transact(sock, &request, &reply);
304     ofpbuf_uninit(&request);
305     if (retval) {
306         nl_sock_destroy(sock);
307         return retval;
308     }
309     if (!nl_policy_parse(reply, openflow_multicast_policy, attrs,
310                          ARRAY_SIZE(openflow_multicast_policy))) {
311         nl_sock_destroy(sock);
312         ofpbuf_delete(reply);
313         return EPROTO;
314     }
315     *multicast_group = nl_attr_get_u32(attrs[DP_GENL_A_MC_GROUP]);
316     nl_sock_destroy(sock);
317     ofpbuf_delete(reply);
318
319     return 0;
320 }
321
322 /* Sends the given 'command' to datapath 'dp'.  If 'netdev' is nonnull, adds it
323  * to the command as the port name attribute.  Returns 0 if successful,
324  * otherwise a positive errno value. */
325 static int
326 send_mgmt_command(struct dpif *dp, int command, const char *netdev) 
327 {
328     struct ofpbuf request, *reply;
329     int retval;
330
331     ofpbuf_init(&request, 0);
332     nl_msg_put_genlmsghdr(&request, dp->sock, 32, openflow_family,
333                           NLM_F_REQUEST | NLM_F_ACK, command, 1);
334     nl_msg_put_u32(&request, DP_GENL_A_DP_IDX, dp->dp_idx);
335     if (netdev) {
336         nl_msg_put_string(&request, DP_GENL_A_PORTNAME, netdev);
337     }
338     retval = nl_sock_transact(dp->sock, &request, &reply);
339     ofpbuf_uninit(&request);
340     ofpbuf_delete(reply);
341
342     return retval;
343 }