Skip to content

Commit c626914

Browse files
committed
file: add take_fd() cleanup helper
Add a helper that returns the file descriptor and ensures that the old variable contains a negative value. This makes it easy to rely on CLASS(get_unused_fd). Link: https://lore.kernel.org/r/[email protected] Reviewed-by: Jeff Layton <[email protected]> Reviewed-by: Josef Bacik <[email protected]> Reviewed-by: Alexander Mikhalitsyn <[email protected]> Signed-off-by: Christian Brauner <[email protected]>
1 parent ff2c570 commit c626914

File tree

2 files changed

+28
-5
lines changed

2 files changed

+28
-5
lines changed

include/linux/cleanup.h

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -63,17 +63,20 @@
6363

6464
#define __free(_name) __cleanup(__free_##_name)
6565

66-
#define __get_and_null_ptr(p) \
67-
({ __auto_type __ptr = &(p); \
68-
__auto_type __val = *__ptr; \
69-
*__ptr = NULL; __val; })
66+
#define __get_and_null(p, nullvalue) \
67+
({ \
68+
__auto_type __ptr = &(p); \
69+
__auto_type __val = *__ptr; \
70+
*__ptr = nullvalue; \
71+
__val; \
72+
})
7073

7174
static inline __must_check
7275
const volatile void * __must_check_fn(const volatile void *val)
7376
{ return val; }
7477

7578
#define no_free_ptr(p) \
76-
((typeof(p)) __must_check_fn(__get_and_null_ptr(p)))
79+
((typeof(p)) __must_check_fn(__get_and_null(p, NULL)))
7780

7881
#define return_ptr(p) return no_free_ptr(p)
7982

include/linux/file.h

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,26 @@ extern void put_unused_fd(unsigned int fd);
9797
DEFINE_CLASS(get_unused_fd, int, if (_T >= 0) put_unused_fd(_T),
9898
get_unused_fd_flags(flags), unsigned flags)
9999

100+
/*
101+
* take_fd() will take care to set @fd to -EBADF ensuring that
102+
* CLASS(get_unused_fd) won't call put_unused_fd(). This makes it
103+
* easier to rely on CLASS(get_unused_fd):
104+
*
105+
* struct file *f;
106+
*
107+
* CLASS(get_unused_fd, fd)(O_CLOEXEC);
108+
* if (fd < 0)
109+
* return fd;
110+
*
111+
* f = dentry_open(&path, O_RDONLY, current_cred());
112+
* if (IS_ERR(f))
113+
* return PTR_ERR(fd);
114+
*
115+
* fd_install(fd, f);
116+
* return take_fd(fd);
117+
*/
118+
#define take_fd(fd) __get_and_null(fd, -EBADF)
119+
100120
extern void fd_install(unsigned int fd, struct file *file);
101121

102122
int receive_fd(struct file *file, int __user *ufd, unsigned int o_flags);

0 commit comments

Comments
 (0)