Opening and wriiting to file in Kern

Robert Watson rwatson at FreeBSD.org
Sun Feb 6 05:00:31 PST 2005


On Sun, 6 Feb 2005, Ashwin Chandra wrote:

> Does anyone know the correct calls to open a file, write to it, and
> close it, IN *kernel* mode.

I fyou want to be file system independent, you can currently do it using
two different currently available kernel abstractions:

- VFS interface.  Using vn_open(), return a reference to an opened vnode.
  Use vn_rdwr() to perform I/O on the vnode, and vn_close() to close it.
  Make sure to properly lock the vnode during I/O and other operations.
  This interface is abstract in the sense that it's file systme
  independent, but not in most other senses.  This can be done from many
  contexts in the kernel, including kernel worker threads, etc.

- File interface.  Using kern_open(), return a reference to an open
  'struct file'  Use the calls fo_read(), fo_write(), etc.  This is more
  abstract than the VFS interface, and strongly resembles the interface
  used via file descriptors (since that's what it implements).  It's less
  functionally complete than the VFS interface, so you can't do stuff like
  changing the file mode, etc, directly (you have to perform them on the
  file's vnode).  It also requires file descriptor context, so possibly
  one associated with a user process and then "borrowed" by the kernel.

Linux exports a FILE stream like interface in its kernel, and for the
purposes of porting the FLASK/TE components from DTOS/SELinux to FreeBSD,
we also ported a subset of this functionality.  Feel free to grab and
reuse as appropriate in a kernel module or the like.  You can find it at:

  http://fxr.watson.org/fxr/source/security/sebsd/ss/fileutils.c?v=TRUSTEDBSD-SEBSD
  http://fxr.watson.org/fxr/source/security/sebsd/ss/fileutils.h?v=TRUSTEDBSD-SEBSD

Right now it just implements fopen(), fread(), and fclose(), but it would
be easy to imagine implementing fwrite(), feof(), etc by wrapping the
vnode interface.

Robert N M Watson





More information about the freebsd-hackers mailing list