Apply a default baudrate when the OS does not provide one.
[libserialport/gsi.git] / freebsd.c
blobb51b731b6071fc3523e0e2369d861c8822130a48
1 /*
2 * This file is part of the libserialport project.
4 * Copyright (C) 2015 Uffe Jakobsen <uffe@uffe.org>
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as
8 * published by the Free Software Foundation, either version 3 of the
9 * License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 * FreeBSD platform specific serial port information:
23 * FreeBSD has two device nodes for each serial port:
25 * 1) a call-in port
26 * 2) a call-out port
28 * Quoting FreeBSD Handbook section 26.2.1
29 * (https://www.freebsd.org/doc/handbook/serial.html)
31 * In FreeBSD, each serial port is accessed through an entry in /dev.
32 * There are two different kinds of entries:
34 * 1) Call-in ports are named /dev/ttyuN where N is the port number,
35 * starting from zero. If a terminal is connected to the first serial port
36 * (COM1), use /dev/ttyu0 to refer to the terminal. If the terminal is on
37 * the second serial port (COM2), use /dev/ttyu1, and so forth.
38 * Generally, the call-in port is used for terminals. Call-in ports require
39 * that the serial line assert the "Data Carrier Detect" signal to work
40 * correctly.
42 * 2) Call-out ports are named /dev/cuauN on FreeBSD versions 10.x and higher
43 * and /dev/cuadN on FreeBSD versions 9.x and lower. Call-out ports are
44 * usually not used for terminals, but are used for modems. The call-out
45 * port can be used if the serial cable or the terminal does not support
46 * the "Data Carrier Detect" signal.
48 * FreeBSD also provides initialization devices (/dev/ttyuN.init and
49 * /dev/cuauN.init or /dev/cuadN.init) and locking devices (/dev/ttyuN.lock
50 * and /dev/cuauN.lock or /dev/cuadN.lock). The initialization devices are
51 * used to initialize communications port parameters each time a port is
52 * opened, such as crtscts for modems which use RTS/CTS signaling for flow
53 * control. The locking devices are used to lock flags on ports to prevent
54 * users or programs changing certain parameters.
56 * In line with the above device naming USB-serial devices have
57 * the following naming:
59 * 1) call-in ports: /dev/ttyUN where N is the port number
60 * 2) call-out ports: /dev/cuaUN where N is the port number
62 * See also: ucom(4), https://www.freebsd.org/cgi/man.cgi?query=ucom
64 * Getting USB serial port device description:
66 * In order to query USB serial ports for device description - the mapping
67 * between the kernel device driver instances must be correlated with the
68 * above mentioned device nodes.
70 * 1) For each USB-serial port (/dev/cuaUN) use libusb to lookup the device
71 * description and the name of the kernel device driver instance.
72 * 2) Query sysctl for the kernel device driver instance info.
73 * 3) Derive the ttyname and (serial) port count for the kernel device
74 * driver instance.
75 * 4) If sysctl ttyname and port matches /dev/cuaUN apply the libusb
76 * device description.
79 #include <config.h>
80 #include <unistd.h>
81 #include <stdint.h>
82 #include <stdlib.h>
83 #include <limits.h>
84 #include <stdio.h>
85 #include <string.h>
86 #include <sys/types.h>
87 #include <sys/sysctl.h>
88 #include <dirent.h>
89 #include <libusb20.h>
90 #include <libusb20_desc.h>
91 #include "libserialport.h"
92 #include "libserialport_internal.h"
94 #define DEV_CUA_PATH "/dev/cua"
96 //#define DBG(...) printf(__VA_ARGS__)
97 #define DBG(...)
99 static char *strrspn(const char *s, const char *charset)
101 char *t = (char *)s + strlen(s);
102 while (t != (char *)s)
103 if (!strchr(charset, *(--t)))
104 return ++t;
105 return t;
108 static int strend(const char *str, const char *pattern)
110 size_t slen = strlen(str);
111 size_t plen = strlen(pattern);
112 if (slen >= plen)
113 return (!memcmp(pattern, (str + slen - plen), plen));
114 return 0;
117 static int libusb_query_port(struct libusb20_device *dev, int idx,
118 char **drv_name_str, char **drv_inst_str)
120 int rc;
121 char *j;
122 char sbuf[FILENAME_MAX];
124 if (!drv_name_str || !drv_inst_str)
125 return -1;
127 rc = libusb20_dev_kernel_driver_active(dev, idx);
128 if (rc < 0)
129 return rc;
131 sbuf[0] = 0;
132 libusb20_dev_get_iface_desc(dev, idx, (char *)&sbuf,
133 (uint8_t)sizeof(sbuf) - 1);
134 if (sbuf[0] == 0)
135 return rc;
137 DBG("Device interface descriptor: idx=%003d '%s'\n", idx, sbuf);
138 j = strchr(sbuf, ':');
139 if (j > sbuf) {
140 sbuf[j - sbuf] = 0;
142 * The device driver name may contain digits that
143 * is not a part of the device instance number - like "u3g".
145 j = strrspn(sbuf, "0123456789");
146 if (j > sbuf) {
147 *drv_name_str = strndup(sbuf, j - sbuf);
148 *drv_inst_str = strdup((j));
152 return rc;
155 static int sysctl_query_dev_drv(const char *drv_name_str,
156 const char *drv_inst_str, char **ttyname, int *const ttyport_cnt)
158 int rc;
159 char sbuf[FILENAME_MAX];
160 char tbuf[FILENAME_MAX];
161 size_t tbuf_len;
163 if (!ttyname || !ttyport_cnt)
164 return -1;
166 snprintf(sbuf, sizeof(sbuf), "dev.%s.%s.ttyname", drv_name_str,
167 drv_inst_str);
168 tbuf_len = sizeof(tbuf) - 1;
169 if ((rc = sysctlbyname(sbuf, tbuf, &tbuf_len, NULL, 0)) != 0)
170 return rc;
172 tbuf[tbuf_len] = 0;
173 *ttyname = strndup(tbuf, tbuf_len);
174 DBG("sysctl: '%s' (%d) (%d): '%.*s'\n", sbuf, rc, (int)tbuf_len,
175 (int)tbuf_len, tbuf);
177 snprintf(sbuf, sizeof(sbuf), "dev.%s.%s.ttyports",
178 drv_name_str, drv_inst_str);
179 tbuf_len = sizeof(tbuf) - 1;
180 rc = sysctlbyname(sbuf, tbuf, &tbuf_len, NULL, 0);
181 if (rc == 0) {
182 *ttyport_cnt = *(uint32_t *)tbuf;
183 DBG("sysctl: '%s' (%d) (%d): '%d'\n", sbuf, rc,
184 (int)tbuf_len, (int)ttyport_cnt);
185 } else {
186 *ttyport_cnt = 0;
189 return rc;
192 static int populate_port_struct_from_libusb_desc(struct sp_port *const port,
193 struct libusb20_device *dev)
195 char tbuf[FILENAME_MAX];
197 /* Populate port structure from libusb description. */
198 struct LIBUSB20_DEVICE_DESC_DECODED *dev_desc =
199 libusb20_dev_get_device_desc(dev);
201 if (!dev_desc)
202 return -1;
204 port->transport = SP_TRANSPORT_USB;
205 port->usb_vid = dev_desc->idVendor;
206 port->usb_pid = dev_desc->idProduct;
207 port->usb_bus = libusb20_dev_get_bus_number(dev);
208 port->usb_address = libusb20_dev_get_address(dev);
209 if (libusb20_dev_req_string_simple_sync
210 (dev, dev_desc->iManufacturer, tbuf, sizeof(tbuf)) == 0) {
211 port->usb_manufacturer = strdup(tbuf);
213 if (libusb20_dev_req_string_simple_sync
214 (dev, dev_desc->iProduct, tbuf, sizeof(tbuf)) == 0) {
215 port->usb_product = strdup(tbuf);
217 if (libusb20_dev_req_string_simple_sync
218 (dev, dev_desc->iSerialNumber, tbuf, sizeof(tbuf)) == 0) {
219 port->usb_serial = strdup(tbuf);
221 /* If present, add serial to description for better identification. */
222 tbuf[0] = '\0';
223 if (port->usb_product && port->usb_product[0])
224 strncat(tbuf, port->usb_product, sizeof(tbuf) - 1);
225 else
226 strncat(tbuf, libusb20_dev_get_desc(dev), sizeof(tbuf) - 1);
227 if (port->usb_serial && port->usb_serial[0]) {
228 strncat(tbuf, " ", sizeof(tbuf) - 1);
229 strncat(tbuf, port->usb_serial, sizeof(tbuf) - 1);
231 port->description = strdup(tbuf);
232 port->bluetooth_address = NULL;
234 return 0;
237 SP_PRIV enum sp_return get_port_details(struct sp_port *port)
239 int rc;
240 struct libusb20_backend *be;
241 struct libusb20_device *dev, *dev_last;
242 char tbuf[FILENAME_MAX];
243 char *cua_sfx;
244 int cua_dev_found;
245 uint8_t idx;
246 int sub_inst;
248 DBG("Portname: '%s'\n", port->name);
250 if (!strncmp(port->name, DEV_CUA_PATH, strlen(DEV_CUA_PATH))) {
251 cua_sfx = port->name + strlen(DEV_CUA_PATH);
252 DBG("'%s': '%s'\n", DEV_CUA_PATH, cua_sfx);
253 } else {
254 RETURN_ERROR(SP_ERR_ARG, "Device name not recognized");
257 /* Native UART enumeration. */
258 if ((cua_sfx[0] == 'u') || (cua_sfx[0] == 'd')) {
259 port->transport = SP_TRANSPORT_NATIVE;
260 snprintf(tbuf, sizeof(tbuf), "cua%s", cua_sfx);
261 port->description = strdup(tbuf);
262 RETURN_OK();
265 /* USB device enumeration. */
266 dev = dev_last = NULL;
267 be = libusb20_be_alloc_default();
268 cua_dev_found = 0;
269 while (cua_dev_found == 0) {
270 dev = libusb20_be_device_foreach(be, dev_last);
271 if (!dev)
272 break;
274 libusb20_dev_open(dev, 0);
275 DBG("Device descriptor: '%s'\n", libusb20_dev_get_desc(dev));
277 for (idx = 0; idx <= UINT8_MAX - 1; idx++) {
278 char *drv_name_str = NULL;
279 char *drv_inst_str = NULL;
280 char *ttyname = NULL;
281 int ttyport_cnt;
283 rc = libusb_query_port(dev, idx, &drv_name_str, &drv_inst_str);
284 if (rc == 0) {
285 rc = sysctl_query_dev_drv(drv_name_str,
286 drv_inst_str, &ttyname, &ttyport_cnt);
287 if (rc == 0) {
288 /* Handle multiple subinstances of serial ports in the same driver instance. */
289 for (sub_inst = 0; sub_inst < ttyport_cnt; sub_inst++) {
290 if (ttyport_cnt == 1)
291 snprintf(tbuf, sizeof(tbuf), "%s", ttyname);
292 else
293 snprintf(tbuf, sizeof(tbuf), "%s.%d", ttyname, sub_inst);
294 if (!strcmp(cua_sfx, tbuf)) {
295 DBG("MATCH: '%s' == '%s'\n", cua_sfx, tbuf);
296 cua_dev_found = 1;
297 populate_port_struct_from_libusb_desc(port, dev);
298 break; /* Break out of sub instance loop. */
304 /* Clean up. */
305 if (ttyname)
306 free(ttyname);
307 if (drv_name_str)
308 free(drv_name_str);
309 if (drv_inst_str)
310 free(drv_inst_str);
311 if (cua_dev_found)
312 break; /* Break out of USB device port idx loop. */
314 libusb20_dev_close(dev);
315 dev_last = dev;
317 libusb20_be_free(be);
319 if (cua_dev_found == 0)
320 DBG("WARN: Found no match '%s' %s'\n", port->name, cua_sfx);
322 RETURN_OK();
325 SP_PRIV enum sp_return list_ports(struct sp_port ***list)
327 DIR *dir;
328 struct dirent *entry;
329 struct termios tios;
330 char name[PATH_MAX];
331 int fd, ret;
333 DEBUG("Enumerating tty devices");
334 if (!(dir = opendir("/dev")))
335 RETURN_FAIL("Could not open dir /dev");
337 DEBUG("Iterating over results");
338 while ((entry = readdir(dir))) {
339 ret = SP_OK;
340 if (entry->d_type != DT_CHR)
341 continue;
342 if (strncmp(entry->d_name, "cuaU", 4) != 0)
343 if (strncmp(entry->d_name, "cuau", 4) != 0)
344 if (strncmp(entry->d_name, "cuad", 4) != 0)
345 continue;
346 if (strend(entry->d_name, ".init"))
347 continue;
348 if (strend(entry->d_name, ".lock"))
349 continue;
351 snprintf(name, sizeof(name), "/dev/%s", entry->d_name);
352 DEBUG_FMT("Found device %s", name);
354 /* Check that we can open tty/cua device in rw mode - we need that. */
355 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY | O_TTY_INIT | O_CLOEXEC)) < 0) {
356 DEBUG("Open failed, skipping");
357 continue;
360 /* Sanity check if we got a real tty. */
361 if (!isatty(fd)) {
362 close(fd);
363 continue;
366 ret = tcgetattr(fd, &tios);
367 close(fd);
368 if (ret < 0 || cfgetospeed(&tios) <= 0 || cfgetispeed(&tios) <= 0)
369 continue;
371 DEBUG_FMT("Found port %s", name);
372 DBG("%s: %s\n", __func__, entry->d_name);
374 *list = list_append(*list, name);
375 if (!*list) {
376 SET_ERROR(ret, SP_ERR_MEM, "List append failed");
377 break;
380 closedir(dir);
382 return ret;