kernel driver reading ok from user space, but writing back is always 0

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-04 05:45:58

Your read function always returns 0 because you are returning retval, and not the count of bytes read. As long as the copy_to_user() call always succeeds, retval will always be 0. Instead, as long as copy_to_user() succeeds, you should return the number of bytes actually written to user space. This documentation states that copy_to_user() returns the total number of bytes that it was unable to copy.

As an aside, you are ignoring the value of count. It is very possible that the user is requesting less data than you have available in your buffer. You should never ignore count.

Now you have the problem where your function never returns a 0. Returning a 0 is important because is tells the user application that there is no more data available for reading and the user application should close the device file.

You need to keep track in your driver how many bytes have been read vs. how many bytes have been written. This may be implemented using your actual_rx_size.

Try this:

//Read function
ssize_t memory_read(struct file *filp, char *buf, size_t count, loff_t *f_pos) { 

    ssize_t bytes;

    if (actual_rx_size < count)
        bytes = actual_rx_size;
    else
        bytes = count;

    printk("user requesting data, our buffer has (%d) \n", actual_rx_size);

    /* Check to see if there is data to transfer */
    if (bytes == 0)
        return 0;

    /* Transfering data to user space */ 
    int retval = copy_to_user(buf,rx_buffer,bytes);

    if (retval) {
        printk("copy_to_user() could not copy %d bytes.\n", retval);
        return -EFAULT;
    } else {
        printk("copy_to_user() succeeded!\n");
        actual_rx_size -= bytes;
        return bytes;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!