1 // Copyright 2018 The Fuchsia Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include <fuchsia/usb/debug/c/fidl.h>
6 #include <lib/fzl/fdio.h>
7 
8 #include <dirent.h>
9 #include <fcntl.h>
10 #include <stdio.h>
11 
12 #include <utility>
13 
14 #include "xdc-init.h"
15 
16 static const char* const DEV_XDC_DIR = "/dev/class/usb-dbc";
17 
configure_xdc(uint32_t stream_id,fbl::unique_fd * out_fd)18 zx_status_t configure_xdc(uint32_t stream_id, fbl::unique_fd* out_fd) {
19     DIR* d = opendir(DEV_XDC_DIR);
20     if (d == nullptr) {
21         fprintf(stderr, "Could not open dir: \"%s\"\n", DEV_XDC_DIR);
22         return ZX_ERR_BAD_STATE;
23     }
24 
25     struct dirent* de;
26     while ((de = readdir(d)) != nullptr) {
27         int fd = openat(dirfd(d), de->d_name, O_RDWR);
28         if (fd < 0) {
29             continue;
30         }
31         fzl::FdioCaller caller{fbl::unique_fd(fd)};
32         zx_status_t status;
33         zx_status_t res = fuchsia_usb_debug_DeviceSetStream(caller.borrow_channel(),
34                                                             stream_id, &status);
35         if (res == ZX_OK) {
36             res = status;
37         }
38         if (res != ZX_OK) {
39             fprintf(stderr, "Failed to set stream id %u for device \"%s/%s\", err: %d\n",
40                     stream_id, DEV_XDC_DIR, de->d_name, res);
41             continue;
42         }
43         printf("Configured debug device \"%s/%s\", stream id %u\n",
44                DEV_XDC_DIR, de->d_name, stream_id);
45         *out_fd = caller.release();
46         closedir(d);
47         return ZX_OK;
48     }
49     closedir(d);
50 
51     fprintf(stderr, "No debug device found\n");
52     return ZX_ERR_NOT_FOUND;
53 }
54