Re: Buggy __free(kfree) usage pattern already in tree

From: Linus Torvalds
Date: Fri Sep 15 2023 - 17:23:16 EST


On Fri, 15 Sept 2023 at 14:08, Peter Zijlstra <peterz@xxxxxxxxxxxxx> wrote:
>
> So in the perf-event conversion patches I do have this:
>
> struct task_struct *task __free(put_task) = NULL;
>
> ...
>
> if (pid != -1) {
> task = find_lively_task_by_vpid(pid);
> if (!task)
> return -ESRCH;
> }
>
> ...
>
> pattern. The having of task is fully optional in the code-flow.

Yeah, if you end up having conditional initialization, you can't have
the cleanup declaration in the same place, since it would be in an
inner scope and get free'd immediately.

Still, I think that's likely the exception rather than the rule.

Side note: I hope your code snippets are "something like this" rather
than the real deal.

Because code like this:

> But a little later in that same function I then have:
>
> do {
> struct rw_semaphore *exec_update_lock __free(up_read) = NULL;
> if (task) {
> err = down_read_interruptible(&task->signal->exec_update_lock);
>
> struct rw_semaphore *exec_update_lock __free(up_read) = NULL;

is just garbage. That's not a "freeing" function. That should be "__cleanup()".

The last thing we want is misleading naming, making people think that
you are "freeing" a lock.

Naming is hard, let's not make it worse by making it actively misleading.

And honestly, I think the above is actually a *HORIBLE* argument for
doing that "initialize to NULL, change later". I think the above is
exactly the kind of code that we ABSOLUTELY DO NOT WANT.

You should aim for a nice

struct rw_semaphore *struct rw_semaphore *exec_update_lock
__cleanup(release_exec_update_lock) = get_exec_update_lock(task);

and simply have proper constructors and destructors. It's going to be
much cleaner.

You can literally do something like

static inline void release_exec_update_lock(struct rw_semaphore *sem)
{ if (!IS_ERR_OR_NULL(sem)) up_read(sem); }

static inline void get_exec_update_lock(struct task_struct *tsk)
{
if (!task)
return NULL;
if (down_read_interruptible(&task->signal->exec_update_lock))
return ERR_PTR(-EINTR);
retuin &task->signal->exec_update_lock;
}

and the code will be *much* cleaner, wouldn't you say?

Please use proper constructors and destructors when you do these kinds
of automatic cleanup things. Don't write ad-hoc garbage.

You'll thank me a year from now when the code is actually legible.

Linus