Skip to content
Advertisement

linux kernel: is vfs_write thread safe?

In my program, I need to write file in kernel space due to some special reason although I know it’s not recommended.

I’m using vfs_write to write files in kernel space and it works fine. In one case, there are two threads need to write to the same file.

From the internet, it seems that user-space write is thread safe, however, I cannot find whether vfs_write is thread safe or not. Could some one help with this?

Advertisement

Answer

Yes, vfs_write is thread safe.

The only thing you should care is that file’s position, pointer to which you pass to the function as pos argument, shouldn’t be changed during the call to the function.

You can, e.g., use local variable as file’s position, load actual position into it before the call, pass pointer to it as the function’s argument, and update actual position after the call. This technique is used in write syscall implementation:

loff_t pos = file_pos_read(f.file);
ret = vfs_write(f.file, buf, count, &pos);
if (ret >= 0)
   file_pos_write(f.file, pos);

As you can see, vfs_write doesn’t syncrhonize offsets in file between concurrent writers. Possible useful usage scenarios of concurrent writers include:

  1. Append only: set O_APPEND flag for the file. In that case position in the file, passed to vfs_write is ignored and each writer appends data to the file.
  2. Rewrite only: do not set O_APPEND flag for the file and allow each concurrent writer to modify only its own part of the file.
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement