Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * Copyright (c) 2021, Microsoft Corporation.
0004  *
0005  * Authors:
0006  *   Beau Belgrave <beaub@linux.microsoft.com>
0007  */
0008 
0009 #include <errno.h>
0010 #include <sys/ioctl.h>
0011 #include <sys/mman.h>
0012 #include <fcntl.h>
0013 #include <stdio.h>
0014 #include <unistd.h>
0015 #include <linux/user_events.h>
0016 
0017 /* Assumes debugfs is mounted */
0018 const char *data_file = "/sys/kernel/debug/tracing/user_events_data";
0019 const char *status_file = "/sys/kernel/debug/tracing/user_events_status";
0020 
0021 static int event_status(char **status)
0022 {
0023     int fd = open(status_file, O_RDONLY);
0024 
0025     *status = mmap(NULL, sysconf(_SC_PAGESIZE), PROT_READ,
0026                MAP_SHARED, fd, 0);
0027 
0028     close(fd);
0029 
0030     if (*status == MAP_FAILED)
0031         return -1;
0032 
0033     return 0;
0034 }
0035 
0036 static int event_reg(int fd, const char *command, int *status, int *write)
0037 {
0038     struct user_reg reg = {0};
0039 
0040     reg.size = sizeof(reg);
0041     reg.name_args = (__u64)command;
0042 
0043     if (ioctl(fd, DIAG_IOCSREG, &reg) == -1)
0044         return -1;
0045 
0046     *status = reg.status_index;
0047     *write = reg.write_index;
0048 
0049     return 0;
0050 }
0051 
0052 int main(int argc, char **argv)
0053 {
0054     int data_fd, status, write;
0055     char *status_page;
0056     struct iovec io[2];
0057     __u32 count = 0;
0058 
0059     if (event_status(&status_page) == -1)
0060         return errno;
0061 
0062     data_fd = open(data_file, O_RDWR);
0063 
0064     if (event_reg(data_fd, "test u32 count", &status, &write) == -1)
0065         return errno;
0066 
0067     /* Setup iovec */
0068     io[0].iov_base = &write;
0069     io[0].iov_len = sizeof(write);
0070     io[1].iov_base = &count;
0071     io[1].iov_len = sizeof(count);
0072 
0073 ask:
0074     printf("Press enter to check status...\n");
0075     getchar();
0076 
0077     /* Check if anyone is listening */
0078     if (status_page[status]) {
0079         /* Yep, trace out our data */
0080         writev(data_fd, (const struct iovec *)io, 2);
0081 
0082         /* Increase the count */
0083         count++;
0084 
0085         printf("Something was attached, wrote data\n");
0086     }
0087 
0088     goto ask;
0089 
0090     return 0;
0091 }