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