Re: Clean kernel thread termination

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Thomas Petazzoni a écrit :
Hello,

I would like to know how to cleanly terminate a kernel thread at module removal. Basically, what I do is that I use a semaphore to wait the termination of thread before exiting exit_module(). The following pseudo-code illustrate this :

void my_kernel_thread (void)
{
   while (! terminate)
   {
     /* Do the job */
   }

   up (& terminate_sem);
}

int exit_module (void)
{
  terminate = 1;
  down (& terminate_sem);
}

However, I think there's a possible race condition between the up() of the semaphore in my_kernel_thread() and the real termination of the thread, which could lead to the thread being used after module unloading.

In order to avoid this race condition, http://www.scs.ch/~frey/linux/kernelthreads.html suggests to use lock_kernel() and unlock_kernel() in that way :

void my_kernel_thread (void)
{
  while (! terminate)
  {
    /* Do the job */
  }
  lock_kernel();
  up (& terminate_sem);
}

int exit_module (void)
{
  lock_kernel ();
  terminate = 1;
  down (& terminate_sem);
  unlock_kernel();
}

Is it The Right Way To Do It (tm) ? Is it right to use the BKL to do it ?

yes you can use the Big Kernel Lock but this lock should be avoided whenever possible. Also to resolve the problem of your race condition with the semaphores solution, you can try to stop the kernel thread inside you exit_module_function :
int exit_module (void)
{
	lock_kernel ();
	terminate = 1;
	down (& terminate_sem);
	stop_kthread();
}
In that case you're sure the thread will be stopped after the unloading of the module.


--
Kernelnewbies: Help each other learn about the Linux kernel.
Archive:       http://mail.nl.linux.org/kernelnewbies/
FAQ:           http://kernelnewbies.org/faq/


[Index of Archives]     [Newbies FAQ]     [Linux Kernel Mentors]     [Linux Kernel Development]     [IETF Annouce]     [Git]     [Networking]     [Security]     [Bugtraq]     [Yosemite]     [MIPS Linux]     [ARM Linux]     [Linux RAID]     [Linux SCSI]     [Linux ACPI]
  Powered by Linux