I have a ioctl in my kernel driver and that needs to return some data upon read. When I read it back in userspace, it's not showing expected results.
Userspace snippet:
typedef struct abc_T {
int size;
int addr;
int data[32];
} abc_T;
// Read
int abc_read(int addr, int size, int *data) {
abc_T abc = {};
int fd, retval;
abc.size = size;
abc.addr = addr;
fd = open("/dev/"ABC_DEV, O_RDWR);
if (fd >=0) {
retval = ioctl(fd, READ_ABC, &abc);
if (retval == 0)
memcpy(data, abc.data, size);
}
return retval;
}
Kernel:
static int ABC_ioctl(struct file * file, uint cmd, ulong arg)
{
ABC_T abc;
void __user * arg_ptr;
arg_ptr = (void *)arg;
int retval;
if (!access_ok(VERIFY_READ, arg_ptr, sizeof(ABC_T))) {
return -EACCES;
}
if (copy_from_user(&abc, arg_ptr,
sizeof(ABC_T)) != 0) {
return -EFAULT;
}
switch(cmd) {
case READ_ABC:
retval = read_func(&abc);
if (retval == 0) {
if (copy_to_user((void __user *)arg, &abc,
sizeof(ABC_T) != 0)) {
retval = -EFAULT;
} else {
retval = 0;
}
}
return retval;
}
I have printed the results (i.e. data array) in the read_func
and can see that the read is expected value , but when after copy_to_user, when I print data
in the userspace, I see all zeros.
Is there something wrong with this snippet?
Your parens are off on the call to copy_to_user
. I think you mean to test if the response of copy_to_user
is != 0
. Instead, you're putting sizeof(ABC_T) != 0
as the last argument. Since sizeof(ABC_T)
is non-zero, your call ends up being copy_to_user((void __user *)arg, &abc, true)
.
Fix your parens and see if you get better results:
if (copy_to_user((void __user *)arg, &abc, sizeof(ABC_T)) != 0) {
// ...
}