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 <zircon/device/debug.h>
6
7#include <dirent.h>
8#include <fcntl.h>
9
10#include "xdc-init.h"
11
12static const char* const DEV_XDC_DIR = "/dev/class/usb-dbc";
13
14zx_status_t configure_xdc(const uint32_t stream_id, fbl::unique_fd& out_fd) {
15    DIR* d = opendir(DEV_XDC_DIR);
16    if (d == nullptr) {
17        fprintf(stderr, "Could not open dir: \"%s\"\n", DEV_XDC_DIR);
18        return ZX_ERR_BAD_STATE;
19    }
20
21    struct dirent* de;
22    while ((de = readdir(d)) != nullptr) {
23        int fd = openat(dirfd(d), de->d_name, O_RDWR);
24        if (fd < 0) {
25            continue;
26        }
27        zx_status_t status = static_cast<zx_status_t>(ioctl_debug_set_stream_id(fd, &stream_id));
28        if (status != ZX_OK) {
29            fprintf(stderr, "Failed to set stream id %u for device \"%s/%s\", err: %d\n",
30                    stream_id, DEV_XDC_DIR, de->d_name, status);
31            close(fd);
32            continue;
33        }
34        printf("Configured debug device \"%s/%s\", stream id %u\n",
35               DEV_XDC_DIR, de->d_name, stream_id);
36        out_fd.reset(fd);
37        closedir(d);
38        return ZX_OK;
39    }
40    closedir(d);
41
42    fprintf(stderr, "No debug device found\n");
43    return ZX_ERR_NOT_FOUND;
44}
45
46