"Fossies" - the Fresh Open Source Software Archive

Member "usbutils-014/sysfs.c" (22 Feb 2021, 1616 Bytes) of package /linux/misc/usbutils-014.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "sysfs.c" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 013_vs_014.

    1 // SPDX-License-Identifier: GPL-2.0-or-later
    2 /*
    3  * Helpers for querying USB properties from sysfs
    4  *
    5  * Copied from name.c which is:
    6  * Copyright (C) 1999, 2000 Thomas Sailer (sailer@ife.ee.ethz.ch)
    7  * Copyright (C) 2013 Tom Gundersen (teg@jklm.no)
    8  */
    9 
   10 #include <stdint.h>
   11 #include <sys/stat.h>
   12 #include <fcntl.h>
   13 #include <unistd.h>
   14 #include <stdio.h>
   15 #include <linux/limits.h>
   16 
   17 #include <libusb.h>
   18 
   19 #include "sysfs.h"
   20 
   21 /*
   22  * The documentation of libusb_get_port_numbers() says "As per the USB 3.0
   23  * specs, the current maximum limit for the depth is 7."
   24  */
   25 #define USB_MAX_DEPTH 7
   26 
   27 #define SYSFS_DEV_ATTR_PATH "/sys/bus/usb/devices/%s/%s"
   28 
   29 int get_sysfs_name(char *buf, size_t size, libusb_device *dev)
   30 {
   31     int len = 0;
   32     uint8_t bnum = libusb_get_bus_number(dev);
   33     uint8_t pnums[USB_MAX_DEPTH];
   34     int num_pnums;
   35 
   36     buf[0] = '\0';
   37 
   38     num_pnums = libusb_get_port_numbers(dev, pnums, sizeof(pnums));
   39     if (num_pnums == LIBUSB_ERROR_OVERFLOW) {
   40         return -1;
   41     } else if (num_pnums == 0) {
   42         /* Special-case root devices */
   43         return snprintf(buf, size, "usb%d", bnum);
   44     }
   45 
   46     len += snprintf(buf, size, "%d-", bnum);
   47     for (int i = 0; i < num_pnums; i++)
   48         len += snprintf(buf + len, size - len, i ? ".%d" : "%d", pnums[i]);
   49 
   50     return len;
   51 }
   52 
   53 int read_sysfs_prop(char *buf, size_t size, char *sysfs_name, char *propname)
   54 {
   55     int n, fd;
   56     char path[PATH_MAX];
   57 
   58     buf[0] = '\0';
   59     snprintf(path, sizeof(path), SYSFS_DEV_ATTR_PATH, sysfs_name, propname);
   60     fd = open(path, O_RDONLY);
   61 
   62     if (fd == -1)
   63         return 0;
   64 
   65     n = read(fd, buf, size);
   66 
   67     if (n > 0)
   68         buf[n-1] = '\0';  // Turn newline into null terminator
   69 
   70     close(fd);
   71     return n;
   72 }