Re: [PATCH 3/3] kthread: Stop abusing TASK_UNINTERRUPTIBLE (INCOMPLETE)

Wedson Almeida Filho
2022-06-27T18:04:22Z

On Mon, Jun 27, 2022 at 05:11:36PM +0900, Tejun Heo wrote:
> Yeah, I have a hard time imagining this happening in C but maybe we'll
> get pretty good closure support through rust-in-kernel if that works
> out. That'd be pretty sweet even though we might not be able to use it
> everywhere.

While Rust does support closures and it would work just fine here, I
think in this case its type system allows for better ergonomics and
flexibility without them, for example:

// the pr_info! part is a closure for the body of the thread. Could
// also be replaced with a function.
let new_thread = task::new_paused(|| pr_info!("Hello world\n"))?;

// Do whatever initialisation one wants to do using new_thread. Only
// functions that _can_ be used on a new kthread would be available
// (e.g., wake_up_process() wouldn't).

new_thread.start();

// new_thread isn't accessible anymore. The compiler fails compilation
// if one attempts to use it again, for example, to call start()
// again.

The type returned by task::new_paused() wouldn't be copyable, so we can
guarantee that start() is called at most once.

It would have a Drop implemention (destructor) that puts the task, which
means that we could use the question mark operator for error handling
between new_paused() & start() (or really any kind of early-return
technique) and all error paths would properly clean the new task up
without any goto mess. It also means that if one forgets to call
start(), not only will the thread never start, it will also be freed
(i.e., no leaks).

If the caller wants to keep a reference to the task, they would do
something like the following (instead of calling new_thread.start()):

let task = new_thread.start_and_get();

Then `task` could be used as any task. For example, wake_up() would be
available, but not wake_up_new_task(). It also has automatic handling of
refcounting such that we are garanteed to never have a dangling pointer
to the task.

Lastly, all the checks I mentioned above happen at compile time, so
there is absolutely zero cost at runtime.

Anyway, sorry for the digression. I thought this would be a good
opportunity to talk about some of the possibilities in API design and
enforcement that Rust affords us since this kind of design was the topic
in discussion and Rust was brought up by someone else :)

Cheers,
-Wedson