Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Improve example in 15.2 Work queues with error handling and cleanup #317

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 6, 2025

Conversation

wurrrrrrrrrr
Copy link
Contributor

Since the example in Chapter 15.2 demonstrates the use of work queues in kernel modules, improving its reliability with proper error handling and cleanup logic helps reflect best practices in modern kernel development. This change enhances safety by preventing null pointer dereference during allocation failure and ensuring all work is completed before module unload.

Summary by Bito

This pull request improves the example in Chapter 15.2, "Work queues", by adding error handling for alloc_workqueue() and ensuring flush_workqueue() is called before destroy_workqueue() in the module exit path. These changes align the code with kernel best practices, prevent common pitfalls like null pointer dereference, and make the example safer for readers and learners on modern kernels.

These changes improve robustness in the workqueue lifecycle and reduce the risk of memory corruption.

Unit_tests added : False

** Estimated effort to review (1-5, lower is better)** : 2

Previously, sched_init() did not check whether alloc_workqueue() succeeded.
This could lead to a NULL pointer dereference and kernel crash if memory
allocation failed. This commit adds a check for a NULL return and logs an
error message if allocation fails.

By returning -ENOMEM early, we ensure the module will not be loaded in an
invalid state and avoid undefined behavior or system instability.
To ensure no work is left running when the module is removed, call
flush_workqueue() before destroy_workqueue() in the module exit path.
According to the kernel documentation, destroy_workqueue() expects
that all work items have already completed:

    "Safely destroy a workqueue. All work currently pending will be
    done first."

This change adds an explicit call to flush_workqueue() in the module
exit function to ensure no work handler remains in progress or pending
at the time of destruction.
@wurrrrrrrrrr
Copy link
Contributor Author

Okay, here's the updated version

@jserv jserv merged commit 989e994 into sysprog21:master May 6, 2025
1 check passed
@jserv
Copy link
Contributor

jserv commented May 6, 2025

Thank @wurrrrrrrrrr for contributing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants