#ifndef _LINUXKPI_LINUX_FILE_H_
#define _LINUXKPI_LINUX_FILE_H_
#include <sys/param.h>
#include <sys/file.h>
#include <sys/filedesc.h>
#include <sys/refcount.h>
#include <sys/capsicum.h>
#include <sys/proc.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/compiler.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/cleanup.h>
struct linux_file;
#undef file
extern const struct fileops linuxfileops;
static inline struct linux_file *
linux_fget(unsigned int fd)
{
struct file *file;
if (fget_unlocked(curthread, fd, &cap_no_rights, &file) != 0)
return (NULL);
if (file->f_data == NULL ||
file->f_ops != &linuxfileops) {
fdrop(file, curthread);
return (NULL);
}
return ((struct linux_file *)file->f_data);
}
extern void linux_file_free(struct linux_file *filp);
static inline void
fput(struct linux_file *filp)
{
if (refcount_release(filp->_file == NULL ?
&filp->f_count : &filp->_file->f_count)) {
linux_file_free(filp);
}
}
static inline unsigned int
file_count(struct linux_file *filp)
{
return (filp->_file == NULL ?
filp->f_count : filp->_file->f_count);
}
static inline void
put_unused_fd(unsigned int fd)
{
struct file *file;
if (fget_unlocked(curthread, fd, &cap_no_rights, &file) != 0) {
return;
}
fdclose(curthread, file, fd);
fdrop(file, curthread);
}
static inline void
fd_install(unsigned int fd, struct linux_file *filp)
{
struct file *file;
if (fget_unlocked(curthread, fd, &cap_no_rights, &file) != 0) {
filp->_file = NULL;
} else {
filp->_file = file;
finit(file, filp->f_mode, DTYPE_DEV, filp, &linuxfileops);
while (refcount_release(&filp->f_count) == 0)
refcount_acquire(&file->f_count);
}
fput(filp);
}
static inline int
get_unused_fd(void)
{
struct file *file;
int error;
int fd;
error = falloc(curthread, &file, &fd, 0);
if (error)
return -error;
fdrop(file, curthread);
return fd;
}
static inline int
get_unused_fd_flags(int flags)
{
struct file *file;
int error;
int fd;
error = falloc(curthread, &file, &fd, flags);
if (error)
return -error;
fdrop(file, curthread);
return fd;
}
extern struct linux_file *linux_file_alloc(void);
static inline struct linux_file *
alloc_file(int mode, const struct file_operations *fops)
{
struct linux_file *filp;
filp = linux_file_alloc();
filp->f_op = fops;
filp->f_mode = mode;
return (filp);
}
struct fd {
struct linux_file *linux_file;
};
static inline void fdput(struct fd fd)
{
fput(fd.linux_file);
}
static inline struct fd fdget(unsigned int fd)
{
struct linux_file *f = linux_fget(fd);
return (struct fd){f};
}
#define file linux_file
#define fget(...) linux_fget(__VA_ARGS__)
#endif