xref: /openbmc/qemu/net/can/can_socketcan.c (revision 8eb806a7)
1 /*
2  * CAN c support to connect to the Linux host SocketCAN interfaces
3  *
4  * Copyright (c) 2013-2014 Jin Yang
5  * Copyright (c) 2014-2018 Pavel Pisa
6  *
7  * Initial development supported by Google GSoC 2013 from RTEMS project slot
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining a copy
10  * of this software and associated documentation files (the "Software"), to deal
11  * in the Software without restriction, including without limitation the rights
12  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13  * copies of the Software, and to permit persons to whom the Software is
14  * furnished to do so, subject to the following conditions:
15  *
16  * The above copyright notice and this permission notice shall be included in
17  * all copies or substantial portions of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25  * THE SOFTWARE.
26  */
27 
28 #include "qemu/osdep.h"
29 #include "qemu/log.h"
30 #include "qemu/main-loop.h"
31 #include "qemu/module.h"
32 #include "qapi/error.h"
33 #include "chardev/char.h"
34 #include "qemu/sockets.h"
35 #include "qemu/error-report.h"
36 #include "net/can_emu.h"
37 #include "net/can_host.h"
38 
39 #include <sys/ioctl.h>
40 #include <net/if.h>
41 #include <linux/can.h>
42 #include <linux/can/raw.h>
43 #include "qom/object.h"
44 
45 #ifndef DEBUG_CAN
46 #define DEBUG_CAN 0
47 #endif /*DEBUG_CAN*/
48 
49 #define TYPE_CAN_HOST_SOCKETCAN "can-host-socketcan"
50 OBJECT_DECLARE_SIMPLE_TYPE(CanHostSocketCAN, CAN_HOST_SOCKETCAN)
51 
52 #define CAN_READ_BUF_LEN  5
53 struct CanHostSocketCAN {
54     CanHostState       parent;
55     char               *ifname;
56 
57     qemu_can_filter    *rfilter;
58     int                rfilter_num;
59     can_err_mask_t     err_mask;
60 
61     qemu_can_frame     buf[CAN_READ_BUF_LEN];
62     int                bufcnt;
63     int                bufptr;
64 
65     int                fd;
66 };
67 
68 /* Check that QEMU and Linux kernel flags encoding and structure matches */
69 QEMU_BUILD_BUG_ON(QEMU_CAN_EFF_FLAG != CAN_EFF_FLAG);
70 QEMU_BUILD_BUG_ON(QEMU_CAN_RTR_FLAG != CAN_RTR_FLAG);
71 QEMU_BUILD_BUG_ON(QEMU_CAN_ERR_FLAG != CAN_ERR_FLAG);
72 QEMU_BUILD_BUG_ON(QEMU_CAN_INV_FILTER != CAN_INV_FILTER);
73 QEMU_BUILD_BUG_ON(offsetof(qemu_can_frame, data)
74                   != offsetof(struct can_frame, data));
75 
76 static void can_host_socketcan_display_msg(struct qemu_can_frame *msg)
77 {
78     int i;
79     FILE *logfile = qemu_log_trylock();
80 
81     if (logfile) {
82         fprintf(logfile, "[cansocketcan]: %03X [%01d] %s %s",
83                 msg->can_id & QEMU_CAN_EFF_MASK,
84                 msg->can_dlc,
85                 msg->can_id & QEMU_CAN_EFF_FLAG ? "EFF" : "SFF",
86                 msg->can_id & QEMU_CAN_RTR_FLAG ? "RTR" : "DAT");
87 
88         for (i = 0; i < msg->can_dlc; i++) {
89             fprintf(logfile, " %02X", msg->data[i]);
90         }
91         fprintf(logfile, "\n");
92         qemu_log_flush();
93         qemu_log_unlock(logfile);
94     }
95 }
96 
97 static void can_host_socketcan_read(void *opaque)
98 {
99     CanHostSocketCAN *c = opaque;
100     CanHostState *ch = CAN_HOST(c);
101 
102     /* CAN_READ_BUF_LEN for multiple messages syscall is possible for future */
103     c->bufcnt = read(c->fd, c->buf, sizeof(qemu_can_frame));
104     if (c->bufcnt < 0) {
105         warn_report("CAN bus host read failed (%s)", strerror(errno));
106         return;
107     }
108 
109     if (!ch->bus_client.fd_mode) {
110         c->buf[0].flags = 0;
111     } else {
112         if (c->bufcnt > CAN_MTU) {
113             c->buf[0].flags |= QEMU_CAN_FRMF_TYPE_FD;
114         }
115     }
116 
117     can_bus_client_send(&ch->bus_client, c->buf, 1);
118 
119     if (DEBUG_CAN) {
120         can_host_socketcan_display_msg(c->buf);
121     }
122 }
123 
124 static bool can_host_socketcan_can_receive(CanBusClientState *client)
125 {
126     return true;
127 }
128 
129 static ssize_t can_host_socketcan_receive(CanBusClientState *client,
130                             const qemu_can_frame *frames, size_t frames_cnt)
131 {
132     CanHostState *ch = container_of(client, CanHostState, bus_client);
133     CanHostSocketCAN *c = CAN_HOST_SOCKETCAN(ch);
134 
135     size_t len;
136     int res;
137 
138     if (c->fd < 0) {
139         return -1;
140     }
141     if (frames->flags & QEMU_CAN_FRMF_TYPE_FD) {
142         if (!ch->bus_client.fd_mode) {
143             return 0;
144         }
145         len = CANFD_MTU;
146     } else {
147         len = CAN_MTU;
148 
149     }
150 
151     res = write(c->fd, frames, len);
152 
153     if (!res) {
154         warn_report("[cansocketcan]: write message to host returns zero");
155         return -1;
156     }
157 
158     if (res != len) {
159         if (res < 0) {
160             warn_report("[cansocketcan]: write to host failed (%s)",
161                         strerror(errno));
162         } else {
163             warn_report("[cansocketcan]: write to host truncated");
164         }
165         return -1;
166     }
167 
168     return 1;
169 }
170 
171 static void can_host_socketcan_disconnect(CanHostState *ch)
172 {
173     CanHostSocketCAN *c = CAN_HOST_SOCKETCAN(ch);
174 
175     if (c->fd >= 0) {
176         qemu_set_fd_handler(c->fd, NULL, NULL, c);
177         close(c->fd);
178         c->fd = -1;
179     }
180 
181     g_free(c->rfilter);
182     c->rfilter = NULL;
183     c->rfilter_num = 0;
184 }
185 
186 static CanBusClientInfo can_host_socketcan_bus_client_info = {
187     .can_receive = can_host_socketcan_can_receive,
188     .receive = can_host_socketcan_receive,
189 };
190 
191 static void can_host_socketcan_connect(CanHostState *ch, Error **errp)
192 {
193     CanHostSocketCAN *c = CAN_HOST_SOCKETCAN(ch);
194     int s; /* can raw socket */
195     int mtu;
196     int enable_canfd = 1;
197     struct sockaddr_can addr;
198     struct ifreq ifr;
199 
200     if (!c->ifname) {
201         error_setg(errp, "'if' property not set");
202         return;
203     }
204 
205     /* open socket */
206     s = qemu_socket(PF_CAN, SOCK_RAW, CAN_RAW);
207     if (s < 0) {
208         error_setg_errno(errp, errno, "failed to create CAN_RAW socket");
209         return;
210     }
211 
212     addr.can_family = AF_CAN;
213     memset(&ifr.ifr_name, 0, sizeof(ifr.ifr_name));
214     strcpy(ifr.ifr_name, c->ifname);
215     /* check if the frame fits into the CAN netdevice */
216     if (ioctl(s, SIOCGIFINDEX, &ifr) < 0) {
217         error_setg_errno(errp, errno,
218                          "SocketCAN host interface %s not available",
219                          c->ifname);
220         goto fail;
221     }
222     addr.can_ifindex = ifr.ifr_ifindex;
223 
224     if (ioctl(s, SIOCGIFMTU, &ifr) < 0) {
225         error_setg_errno(errp, errno,
226                          "SocketCAN host interface %s SIOCGIFMTU failed",
227                          c->ifname);
228         goto fail;
229     }
230     mtu = ifr.ifr_mtu;
231 
232     if (mtu >= CANFD_MTU) {
233         /* interface is ok - try to switch the socket into CAN FD mode */
234         if (setsockopt(s, SOL_CAN_RAW, CAN_RAW_FD_FRAMES,
235                         &enable_canfd, sizeof(enable_canfd))) {
236             warn_report("SocketCAN host interface %s enabling CAN FD failed",
237                         c->ifname);
238         } else {
239             c->parent.bus_client.fd_mode = true;
240         }
241     }
242 
243     c->err_mask = 0xffffffff; /* Receive error frame. */
244     setsockopt(s, SOL_CAN_RAW, CAN_RAW_ERR_FILTER,
245                    &c->err_mask, sizeof(c->err_mask));
246 
247     c->rfilter_num = 1;
248     c->rfilter = g_new(struct qemu_can_filter, c->rfilter_num);
249 
250     /* Receive all data frame. If |= CAN_INV_FILTER no data. */
251     c->rfilter[0].can_id = 0;
252     c->rfilter[0].can_mask = 0;
253     c->rfilter[0].can_mask &= ~CAN_ERR_FLAG;
254 
255     setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, c->rfilter,
256                c->rfilter_num * sizeof(struct qemu_can_filter));
257 
258     if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
259         error_setg_errno(errp, errno, "failed to bind to host interface %s",
260                          c->ifname);
261         goto fail;
262     }
263 
264     c->fd = s;
265     ch->bus_client.info = &can_host_socketcan_bus_client_info;
266     qemu_set_fd_handler(c->fd, can_host_socketcan_read, NULL, c);
267     return;
268 
269 fail:
270     close(s);
271     g_free(c->rfilter);
272     c->rfilter = NULL;
273     c->rfilter_num = 0;
274 }
275 
276 static char *can_host_socketcan_get_if(Object *obj, Error **errp)
277 {
278     CanHostSocketCAN *c = CAN_HOST_SOCKETCAN(obj);
279 
280     return g_strdup(c->ifname);
281 }
282 
283 static void can_host_socketcan_set_if(Object *obj, const char *value,
284                                       Error **errp)
285 {
286     CanHostSocketCAN *c = CAN_HOST_SOCKETCAN(obj);
287     struct ifreq ifr;
288 
289     if (strlen(value) >= sizeof(ifr.ifr_name)) {
290         error_setg(errp, "CAN interface name longer than %zd characters",
291                    sizeof(ifr.ifr_name) - 1);
292         return;
293     }
294 
295     if (c->fd != -1) {
296         error_setg(errp, "CAN interface already connected");
297         return;
298     }
299 
300     g_free(c->ifname);
301     c->ifname = g_strdup(value);
302 }
303 
304 static void can_host_socketcan_instance_init(Object *obj)
305 {
306     CanHostSocketCAN *c = CAN_HOST_SOCKETCAN(obj);
307 
308     c->fd = -1;
309 }
310 
311 static void can_host_socketcan_class_init(ObjectClass *klass,
312                                           void *class_data G_GNUC_UNUSED)
313 {
314     CanHostClass *chc = CAN_HOST_CLASS(klass);
315 
316     object_class_property_add_str(klass, "if",
317                                   can_host_socketcan_get_if,
318                                   can_host_socketcan_set_if);
319     chc->connect = can_host_socketcan_connect;
320     chc->disconnect = can_host_socketcan_disconnect;
321 }
322 
323 static const TypeInfo can_host_socketcan_info = {
324     .parent = TYPE_CAN_HOST,
325     .name = TYPE_CAN_HOST_SOCKETCAN,
326     .instance_size = sizeof(CanHostSocketCAN),
327     .instance_init = can_host_socketcan_instance_init,
328     .class_init = can_host_socketcan_class_init,
329 };
330 
331 static void can_host_register_types(void)
332 {
333     type_register_static(&can_host_socketcan_info);
334 }
335 
336 type_init(can_host_register_types);
337