How to implement a driver's read and write operations with synchronization properly

Anh Le anhlq2110 at gmail.com
Tue Jul 29 08:15:08 EDT 2014


Thanks, Jonathan, for the quick reply.

On Tue, Jul 29, 2014 at 3:36 PM, Jonathan Neuschäfer
<j.neuschaefer at gmx.net> wrote:
> Which "write operation" is called twice in your scenario?

It's the "write" method of the "struct file_operations" structure. I
define it like this (no synchronizatin yet):
static ssize_t sample_write(struct file *f, const char __user *buf,
size_t len, loff_t *ppos)
{
        printk(KERN_DEBUG "[sample] buf len: %u, *ppos: %u\n", len, *ppos);
        return simple_write_to_buffer(kbuf, 2048, ppos, buf, len);
}

> If a userspace program writes 1000 bytes at first, how can you know that
> it wants to perform another write later on?

I use printk to debug the module. More details in the answer below.

> If a userspace program wants to write a chunk of data atomically, it
> should use just one call to write(2). (On Linux, one can save some
> copying by using writev(2), which writes data from multiple buffers in
> one atomic step.)

I tried the following command: echo $(perl -e "print 'a'x2000") > /dev/sample
and get the following messages from dmesg:
[30884.066433] [sample] buf len: 1008, *ppos: 0
[30884.066451] [sample] buf len: 993, *ppos: 1008

So as I understand my 2001 bytes has been split into 2 chunks, the
first one with 1008 bytes and the second one with 993 bytes, and
therefore the write operation is called 2 times to consume the whole
input.

-- 
Le Quoc Anh



More information about the Kernelnewbies mailing list