问题
What should a .read
operation return in a kernel module character device?
I know that copy_to_user(...)
returns the number of bytes not copied and on success returns 0. I saw examples which make the read()
function return -EFAULT
if copy_to_user(...)
returns anything other than 0.
But then upon success this says to return 0 and this says to return the number of bytes read. What should be returning?
Also should I check the params of
static ssize_t dev_read(struct file *filep, char *buffer, size_t len, loff_t *offset)
like checking if buffer==NULL
or len == something
? If so, what should I return on a bad condition?
回答1:
.read
operation should return either:
- number of bytes copied into user-provided buffer, or
- negative error code
Additionally, operation should update *offset
value, so futher reading from the file will return next portion of data.
If driver implementation follows this rules, standard commmands like cat
, dd
will interpret result of read system call correctly, and, by possibly repeating it, output to the user full "content" of the device.
Normally, correctness of buffer
parameter is checked in copy_to_user
call. If this call fails(returns non-zero), -EFAULT is usually returned by .read
.
len
argument is rarely checked for errors. Assuming data_len
to be length of remaing data:
if
len
<data_len
, copy firstlen
bytes into buffer and returnlen
if
len
>data_len
, copy all remaining bytes into buffer and returndata_len
if
data_len
orlen
is 0, return 0
Sometimes device's data can be read only by portions of predefined size. In that situation you can check len
and return -EINVAL in case it has inappropriate value. buffer
can also being checked for alignment.
As for example, where .read
returns 0 on success, it is correct until device is used by own-written user-space program, which doesn't check actual length of returning data.
来源:https://stackoverflow.com/questions/33423312/error-checking-in-a-read-function-in-kernel-module