linux uinput: simple example? - linux

I'm having some problems getting both sides of code using uinput working.
Based on Getting started with uinput: the user level input subsystem[dead link; archived] I put together the following writer (minus error handling):
int main(int ac, char **av)
{
int fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK);
int ret = ioctl(fd, UI_SET_EVBIT, EV_ABS);
ret = ioctl(fd, UI_SET_ABSBIT, ABS_X);
struct uinput_user_dev uidev = {0};
snprintf(uidev.name, UINPUT_MAX_NAME_SIZE, "uinput-rotary");
uidev.absmin[ABS_X] = 0;
uidev.absmax[ABS_X] = 255;
ret = write(fd, &uidev, sizeof(uidev));
ret = ioctl(fd, UI_DEV_CREATE);
struct input_event ev = {0};
ev.type = EV_ABS;
ev.code = ABS_X;
ev.value = 42;
ret = write(fd, &ev, sizeof(ev));
getchar();
ret = ioctl(fd, UI_DEV_DESTROY);
return EXIT_SUCCESS;
}
That seems to work, at least the full input_event structure seems to be written.
I then wrote the most naive reader of events I could come up with:
int main(int ac, char **av)
{
int fd = open(av[1], O_RDONLY);
char name[256] = "unknown";
ioctl(fd, EVIOCGNAME(sizeof(name)), name);
printf("reading from %s\n", name);
struct input_event ev = {0};
int ret = read(fd, &ev, sizeof(ev));
printf("Read an event! %i\n", ret);
printf("ev.time.tv_sec: %li\n", ev.time.tv_sec);
printf("ev.time.tv_usec: %li\n", ev.time.tv_usec);
printf("ev.type: %hi\n", ev.type);
printf("ev.code: %hi\n", ev.code);
printf("ev.value: %li\n", ev.value);
return EXIT_SUCCESS;
}
Unfortunately the reader side doesn't work at all; only manages to read 8 bytes each time, which isn't nearly a full input_event structure.
What silly mistake am I making?

You should also be writing a sync event after the actual event. In your writer side code:
struct input_event ev = {0};
ev.type = EV_ABS;
ev.code = ABS_X;
ev.value = 42;
usleep(1500);
memset(&ev, 0, sizeof(ev));
ev.type = EV_SYN;
ev.code = 0;
ev.value = 0;
ret = write(fd, &ev, sizeof(ev));
getchar();

TL;DR: The kernel expects an EV_SYN event of code SYN_REPORT because individual events may be grouped together, i.e., when they happen at the same point in time.
You can think of it as the kernel interpreting a group of events rather than individual events as specified in struct input_event. An EV_SYN event delimits these groups of events with SYN_REPORT as code, i.e., this provides a grouping mechanism for signaling events that occur simultaneously.
For example, imagine you touch with your finger on the surface of a touchpad:
Given the definition of struct input_event in linux/input.h:
struct input_event {
/* ... */
__u16 type; /* e.g., EV_ABS, EV_REL */
__u16 code; /* e.g., ABS_X for EV_ABS */
__s32 value; /* e.g., the value of the x coordinate for ABS_X */
};
It isn't possible to create a single EV_ABS event that can hold both the codes ABS_X and ABS_Y, as well as the values for specifying the x and y coordinates, respectively – there is just a single code member in struct input_event1.
Instead, two EV_ABS events2 will be created:
One with the code ABS_X and the x coordinate as value.
Another with the code ABS_Y and the y coordinate as value.
It wouldn't be entirely correct to interpret these two events as two events separated in time, i.e., one that indicates a change of the x coordinate and another that occurs later in time and indicates a change of the y coordinate.
Instead of two in-time-separated events, these events should be grouped together and interpreted by the kernel as a single unit of input data change that indicates a change of both the x and y coordinates at the same time. This is why the EV_SYN mechanism described above exists: by generating one EV_SYN event with the SYN_REPORT code just after these two EV_ABS events (i.e., ABS_X and ABS_Y), we are able to group them as a unit.
1This is directly related to the fact that a struct input_event is of fixed size and can't grow arbitrarily.
2Tecnically, more events may be created. For example, another event of type EV_KEY with the code BTN_TOUCH will likely be created. However, this is irrelevant for the point I want to make.

Related

Adding a field to msgbuf

I got an assignment to create a message queue in Linux. I need to use msgnd() and msgrcv() functions. Everything works if my message structure has two fields mtype and mtext[] but I need to add one more field an int mpid. But when I read the value from mpid it is just garbage from the memory. I searched for answers or examples but I only found structures with two fields. Can I even add more?
struct myBuff{
long mtype;
char mtext[255];
int mpid;
};
code for the sender
void add_message(int id, struct myBuff buff){
int size = strlen(buff.mtext) + 1 + sizeof(int)
if (size > 255 + sizeof(int))
exit(EXIT_FAILURE);
msgsnd(id, (struct msgbuf*)&buff, size, 0 | MSG_NOERROR);
}
code for the receiver
void check_message(int id, struct myBuff* buff)
{
msgrcv(id, (struct msgbuf*)buff, 255 + sizeof(int), buff->mtype, 0 | MSG_NOERROR);
}

ff_replay substructure in ff_effect empty

I am developing a force feedback driver (linux) for a yet unsupported gamepad.
Whenever a application in userspace requests a ff-effect (e.g rumbling), a function in my driver is called:
static int foo_ff_play(struct input_dev *dev, void *data, struct ff_effect *effect)
this is set by the following code inside my init function:
input_set_capability(dev, EV_FF, FF_RUMBLE);
input_ff_create_memless(dev, NULL, foo_ff_play);
I'm accessing the ff_effect struct (which is passed to my foo_ff_play function) like this:
static int foo_ff_play(struct input_dev *dev, void *data, struct ff_effect *effect)
{
u16 length;
length = effect->replay.length;
printk(KERN_DEBUG "length: %i", length);
return 0;
}
The problem is, that the reported length (in ff_effect->replay) is always zero.
That's confusing, since i am running fftest on my device, and fftest definitely sets the length attribute: https://github.com/flosse/linuxconsole/blob/master/utils/fftest.c (line 308)
/* a strong rumbling effect */
effects[4].type = FF_RUMBLE;
effects[4].id = -1;
effects[4].u.rumble.strong_magnitude = 0x8000;
effects[4].u.rumble.weak_magnitude = 0;
effects[4].replay.length = 5000;
effects[4].replay.delay = 1000;
Does this have something to do with the "memlessness"? Why does the data in ff_replay seem to be zero if it isn't?
Thank you in advance
Why is the replay struct empty?
Taking a look at https://elixir.free-electrons.com/linux/v4.4/source/drivers/input/ff-memless.c#L406 we find:
static void ml_play_effects(struct ml_device *ml)
{
struct ff_effect effect;
DECLARE_BITMAP(handled_bm, FF_MEMLESS_EFFECTS);
memset(handled_bm, 0, sizeof(handled_bm));
while (ml_get_combo_effect(ml, handled_bm, &effect))
ml->play_effect(ml->dev, ml->private, &effect);
ml_schedule_timer(ml);
}
ml_get_combo_effect sets the effect by calling ml_combine_effects., but ml_combine_effects simply does not copy replay.length to the ff_effect struct which is passed to our foo_play_effect (at least not if the effect-type is FF_RUMBLE): https://elixir.free-electrons.com/linux/v4.4/source/drivers/input/ff-memless.c#L286
That's why we cannot read out the ff_replay-data in our foo_play_effect function.
Okay, replay is empty - how can we determine how long we have to play the effect (e.g. FF_RUMBLE) then?
Looks like the replay structure is something we do not even need to carry about. Yes, fftest sets the length and then uploads the effect to the driver, but if we take a look at ml_ff_upload (https://elixir.free-electrons.com/linux/v4.4/source/drivers/input/ff-memless.c#L481), we can see the following:
if (test_bit(FF_EFFECT_STARTED, &state->flags)) {
__clear_bit(FF_EFFECT_PLAYING, &state->flags);
state->play_at = jiffies +
msecs_to_jiffies(state->effect->replay.delay);
state->stop_at = state->play_at +
msecs_to_jiffies(state->effect->replay.length);
state->adj_at = state->play_at;
ml_schedule_timer(ml);
}
That means that the duration is already handled by the input-subsystem. It starts the effect and also stops it as needed.
Furthermore we can see at https://elixir.free-electrons.com/linux/v4.4/source/include/uapi/linux/input.h#L279 that
/*
* All duration values are expressed in ms. Values above 32767 ms (0x7fff)
* should not be used and have unspecified results.
*/
That means that we have to make our effect play at least 32767ms. Everything else (stopping the effect before) is up to the scheduler - which is not our part :D

Significance of parameters in epoll_event structure (epoll)

I am using epoll_ctl() and epoll_wait() system calls.
int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);
int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout);
struct epoll_event {
uint32_t events; /* epoll events (bit mask) */
epoll_data_t data; /* User data */
};
typedef union epoll_data {
enter code here`void *ptr; /* Pointer to user-defined data */
int fd; /* File descriptor */
uint32_t u32; /* 32-bit integer */
uint64_t u64; /* 64-bit integer */
} epoll_data_t;
When using epoll_ctl, I can use the union epoll_data to specify the fd. One way is to specify it in "fd" member. Other way is to specify it in my own structure, "ptr" member will point to the structure.
What is the use of "u32" and "u64" ?
I went through the kernel system call implementation and found the following:
1. epoll_ctl initializes the epoll_event and stores it (in some RB tree format)
2. when fd is ready, epoll_wait returns epoll_event that was filled in epoll_ctl. After this I can identify the fd which becomes ready. I don't understand the purpose of "u32" and "u64".
The predefined union is for convinient usages and you will usually use only one of them:
use ptr if you want to store a pointer
use fd if you want to store socket descriptor
use u32/u64 if you want to store a general/opaque 32/64 bit number
Actually epoll_data is 64bit data associated with a socket event for you to store anything to find event handler as epoll_wait returns just 2 things: the event & associated epoll_data.
The fields of epoll_data do not have any predefined meaning; your application assigns a meaning.
Any of the fields can be used to stored the information needed by your application to identify the event.
(u32 or u64 might be useful for something like an array index.)

How to get errno when epoll_wait returns EPOLLERR?

Is there a way to find out the errno when epoll_wait returns EPOLLERR for a particular fd?
Is there any further information about the nature of the error?
Edit:
Adding more information to prevent ambiguity
epoll_wait waits on a number of file descriptors. When you call epoll_wait you pass it an array of epoll_event structures:
struct epoll_event {
uint32_t events; /* Epoll events */
epoll_data_t data; /* User data variable */
};
The epoll_data_t structure has the same details as the one you used with epoll_ctl to add a file descriptor to epoll:
typedef union epoll_data {
void *ptr;
int fd;
uint32_t u32;
uint64_t u64;
} epoll_data_t;
What I'm looking for is what happens when there is an error on one of the file descriptors that epoll is waiting on.
ie: (epoll_event.events & EPOLLERR) == 1 - is there a way to find out more details of the error on the file descriptor?
Use getsockopt and SO_ERROR to get the pending error on the socket
int error = 0;
socklen_t errlen = sizeof(error);
if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&error, &errlen) == 0)
{
printf("error = %s\n", strerror(error));
}
Just a minor point: Your test won't work correctly, for two reasons. If EPOLLERR is defined as, say, 0x8, then your test will be comparing 8 with one (since == has higher precedence than &), giving you a zero, then anding that with the event mask.
What you want is: (epoll_event.events & EPOLLERR) != 0 to test for the EPOLLERR bit being set.
epoll_wait returns -1 when an error occurs and sets errno appropriately. See "man 2 epoll_wait" for more info.
Include errno.h and use perror to see the error message.
Basically error is from the epfd or interupt, it will not arise from the file descriptor in your set.
include "errno.h"
if(epoll_wait() == -1)
{
perror("Epoll error : ");
}

Passing struct to device driver through IOCTL

I am trying to pass a struct from user space to kernel space. I had been trying for many hours and it isn't working. Here is what I have done so far..
int device_ioctl(struct inode *inode, struct file *filep, unsigned int cmd, unsigned long arg){
int ret, SIZE;
switch(cmd){
case PASS_STRUCT_ARRAY_SIZE:
SIZE = (int *)arg;
if(ret < 0){
printk("Error in PASS_STRUCT_ARRAY_SIZE\n");
return -1;
}
printk("Struct Array Size : %d\n",SIZE);
break;
case PASS_STRUCT:
struct mesg{
int pIDs[SIZE];
int niceVal;
};
struct mesg data;
ret = copy_from_user(&data, arg, sizeof(*data));
if(ret < 0){
printk("PASS_STRUCT\n");
return -1;
}
printk("Message PASS_STRUCT : %d\n",data.niceVal);
break;
default :
return -ENOTTY;
}
return 0;
}
I have trouble defining the struct. What is the correct way to define it? I want to have int pIDs[SIZE]. Will int *pIDs do it(in user space it is defined like pIDs[SIZE])?
EDIT:
With the above change I get this error? error: expected expression before 'struct' any ideas?
There are two variants of the structure in your question.
struct mesg1{
int *pIDs;
int niceVal;
};
struct mesg2{
int pIDs[SIZE];
int niceVal;
};
They are different; in case of mesg1 you has pointer to int array (which is outside the struct). In other case (mesg2) there is int array inside the struct.
If your SIZE is fixed (in API of your module; the same value used in user- and kernel- space), you can use second variant (mesg2).
To use first variant of structure (mesg1) you may add field size to the structure itself, like:
struct mesg1{
int pIDs_size;
int *pIDs;
int niceVal;
};
and fill it with count of ints, pointed by *pIDs.
PS: And please, never use structures with variable-sized arrays in the middle of the struct (aka VLAIS). This is proprietary, wierd, buggy and non-documented extension to C language by GCC compiler. Only last field of struct can be array with variable size (VLA) according to international C standard. Some examples here: 1 2
PPS:
You can declare you struct with VLA (if there is only single array with variable size):
struct mesg2{
int niceVal;
int pIDs[];
};
but you should be careful when allocating memory for such struct with VLA

Resources