kthread.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. /* Kernel thread helper functions.
  2. * Copyright (C) 2004 IBM Corporation, Rusty Russell.
  3. *
  4. * Creation is done via kthreadd, so that we get a clean environment
  5. * even if we're invoked from userspace (think modprobe, hotplug cpu,
  6. * etc.).
  7. */
  8. #include <linux/sched.h>
  9. #include <linux/kthread.h>
  10. #include <linux/completion.h>
  11. #include <linux/err.h>
  12. #include <linux/cpuset.h>
  13. #include <linux/unistd.h>
  14. #include <linux/file.h>
  15. #include <linux/module.h>
  16. #include <linux/mutex.h>
  17. #include <linux/slab.h>
  18. #include <linux/freezer.h>
  19. #include <trace/events/sched.h>
  20. static DEFINE_SPINLOCK(kthread_create_lock);
  21. static LIST_HEAD(kthread_create_list);
  22. struct task_struct *kthreadd_task;
  23. struct kthread_create_info
  24. {
  25. /* Information passed to kthread() from kthreadd. */
  26. int (*threadfn)(void *data);
  27. void *data;
  28. /* Result passed back to kthread_create() from kthreadd. */
  29. struct task_struct *result;
  30. struct completion done;
  31. struct list_head list;
  32. };
  33. struct kthread {
  34. int should_stop;
  35. void *data;
  36. struct completion exited;
  37. };
  38. #define to_kthread(tsk) \
  39. container_of((tsk)->vfork_done, struct kthread, exited)
  40. /**
  41. * kthread_should_stop - should this kthread return now?
  42. *
  43. * When someone calls kthread_stop() on your kthread, it will be woken
  44. * and this will return true. You should then return, and your return
  45. * value will be passed through to kthread_stop().
  46. */
  47. int kthread_should_stop(void)
  48. {
  49. return to_kthread(current)->should_stop;
  50. }
  51. EXPORT_SYMBOL(kthread_should_stop);
  52. /**
  53. * kthread_data - return data value specified on kthread creation
  54. * @task: kthread task in question
  55. *
  56. * Return the data value specified when kthread @task was created.
  57. * The caller is responsible for ensuring the validity of @task when
  58. * calling this function.
  59. */
  60. void *kthread_data(struct task_struct *task)
  61. {
  62. return to_kthread(task)->data;
  63. }
  64. static int kthread(void *_create)
  65. {
  66. /* Copy data: it's on kthread's stack */
  67. struct kthread_create_info *create = _create;
  68. int (*threadfn)(void *data) = create->threadfn;
  69. void *data = create->data;
  70. struct kthread self;
  71. int ret;
  72. self.should_stop = 0;
  73. self.data = data;
  74. init_completion(&self.exited);
  75. current->vfork_done = &self.exited;
  76. /* OK, tell user we're spawned, wait for stop or wakeup */
  77. __set_current_state(TASK_UNINTERRUPTIBLE);
  78. create->result = current;
  79. complete(&create->done);
  80. schedule();
  81. ret = -EINTR;
  82. if (!self.should_stop)
  83. ret = threadfn(data);
  84. /* we can't just return, we must preserve "self" on stack */
  85. do_exit(ret);
  86. }
  87. static void create_kthread(struct kthread_create_info *create)
  88. {
  89. int pid;
  90. /* We want our own signal handler (we take no signals by default). */
  91. pid = kernel_thread(kthread, create, CLONE_FS | CLONE_FILES | SIGCHLD);
  92. if (pid < 0) {
  93. create->result = ERR_PTR(pid);
  94. complete(&create->done);
  95. }
  96. }
  97. /**
  98. * kthread_create - create a kthread.
  99. * @threadfn: the function to run until signal_pending(current).
  100. * @data: data ptr for @threadfn.
  101. * @namefmt: printf-style name for the thread.
  102. *
  103. * Description: This helper function creates and names a kernel
  104. * thread. The thread will be stopped: use wake_up_process() to start
  105. * it. See also kthread_run().
  106. *
  107. * When woken, the thread will run @threadfn() with @data as its
  108. * argument. @threadfn() can either call do_exit() directly if it is a
  109. * standalone thread for which noone will call kthread_stop(), or
  110. * return when 'kthread_should_stop()' is true (which means
  111. * kthread_stop() has been called). The return value should be zero
  112. * or a negative error number; it will be passed to kthread_stop().
  113. *
  114. * Returns a task_struct or ERR_PTR(-ENOMEM).
  115. */
  116. struct task_struct *kthread_create(int (*threadfn)(void *data),
  117. void *data,
  118. const char namefmt[],
  119. ...)
  120. {
  121. struct kthread_create_info create;
  122. create.threadfn = threadfn;
  123. create.data = data;
  124. init_completion(&create.done);
  125. spin_lock(&kthread_create_lock);
  126. list_add_tail(&create.list, &kthread_create_list);
  127. spin_unlock(&kthread_create_lock);
  128. wake_up_process(kthreadd_task);
  129. wait_for_completion(&create.done);
  130. if (!IS_ERR(create.result)) {
  131. struct sched_param param = { .sched_priority = 0 };
  132. va_list args;
  133. va_start(args, namefmt);
  134. vsnprintf(create.result->comm, sizeof(create.result->comm),
  135. namefmt, args);
  136. va_end(args);
  137. /*
  138. * root may have changed our (kthreadd's) priority or CPU mask.
  139. * The kernel thread should not inherit these properties.
  140. */
  141. sched_setscheduler_nocheck(create.result, SCHED_NORMAL, &param);
  142. set_cpus_allowed_ptr(create.result, cpu_all_mask);
  143. }
  144. return create.result;
  145. }
  146. EXPORT_SYMBOL(kthread_create);
  147. /**
  148. * kthread_bind - bind a just-created kthread to a cpu.
  149. * @p: thread created by kthread_create().
  150. * @cpu: cpu (might not be online, must be possible) for @k to run on.
  151. *
  152. * Description: This function is equivalent to set_cpus_allowed(),
  153. * except that @cpu doesn't need to be online, and the thread must be
  154. * stopped (i.e., just returned from kthread_create()).
  155. */
  156. void kthread_bind(struct task_struct *p, unsigned int cpu)
  157. {
  158. /* Must have done schedule() in kthread() before we set_task_cpu */
  159. if (!wait_task_inactive(p, TASK_UNINTERRUPTIBLE)) {
  160. WARN_ON(1);
  161. return;
  162. }
  163. p->cpus_allowed = cpumask_of_cpu(cpu);
  164. p->rt.nr_cpus_allowed = 1;
  165. p->flags |= PF_THREAD_BOUND;
  166. }
  167. EXPORT_SYMBOL(kthread_bind);
  168. /**
  169. * kthread_stop - stop a thread created by kthread_create().
  170. * @k: thread created by kthread_create().
  171. *
  172. * Sets kthread_should_stop() for @k to return true, wakes it, and
  173. * waits for it to exit. This can also be called after kthread_create()
  174. * instead of calling wake_up_process(): the thread will exit without
  175. * calling threadfn().
  176. *
  177. * If threadfn() may call do_exit() itself, the caller must ensure
  178. * task_struct can't go away.
  179. *
  180. * Returns the result of threadfn(), or %-EINTR if wake_up_process()
  181. * was never called.
  182. */
  183. int kthread_stop(struct task_struct *k)
  184. {
  185. struct kthread *kthread;
  186. int ret;
  187. trace_sched_kthread_stop(k);
  188. get_task_struct(k);
  189. kthread = to_kthread(k);
  190. barrier(); /* it might have exited */
  191. if (k->vfork_done != NULL) {
  192. kthread->should_stop = 1;
  193. wake_up_process(k);
  194. wait_for_completion(&kthread->exited);
  195. }
  196. ret = k->exit_code;
  197. put_task_struct(k);
  198. trace_sched_kthread_stop_ret(ret);
  199. return ret;
  200. }
  201. EXPORT_SYMBOL(kthread_stop);
  202. int kthreadd(void *unused)
  203. {
  204. struct task_struct *tsk = current;
  205. /* Setup a clean context for our children to inherit. */
  206. set_task_comm(tsk, "kthreadd");
  207. ignore_signals(tsk);
  208. set_cpus_allowed_ptr(tsk, cpu_all_mask);
  209. set_mems_allowed(node_states[N_HIGH_MEMORY]);
  210. current->flags |= PF_NOFREEZE | PF_FREEZER_NOSIG;
  211. for (;;) {
  212. set_current_state(TASK_INTERRUPTIBLE);
  213. if (list_empty(&kthread_create_list))
  214. schedule();
  215. __set_current_state(TASK_RUNNING);
  216. spin_lock(&kthread_create_lock);
  217. while (!list_empty(&kthread_create_list)) {
  218. struct kthread_create_info *create;
  219. create = list_entry(kthread_create_list.next,
  220. struct kthread_create_info, list);
  221. list_del_init(&create->list);
  222. spin_unlock(&kthread_create_lock);
  223. create_kthread(create);
  224. spin_lock(&kthread_create_lock);
  225. }
  226. spin_unlock(&kthread_create_lock);
  227. }
  228. return 0;
  229. }
  230. /**
  231. * kthread_worker_fn - kthread function to process kthread_worker
  232. * @worker_ptr: pointer to initialized kthread_worker
  233. *
  234. * This function can be used as @threadfn to kthread_create() or
  235. * kthread_run() with @worker_ptr argument pointing to an initialized
  236. * kthread_worker. The started kthread will process work_list until
  237. * the it is stopped with kthread_stop(). A kthread can also call
  238. * this function directly after extra initialization.
  239. *
  240. * Different kthreads can be used for the same kthread_worker as long
  241. * as there's only one kthread attached to it at any given time. A
  242. * kthread_worker without an attached kthread simply collects queued
  243. * kthread_works.
  244. */
  245. int kthread_worker_fn(void *worker_ptr)
  246. {
  247. struct kthread_worker *worker = worker_ptr;
  248. struct kthread_work *work;
  249. WARN_ON(worker->task);
  250. worker->task = current;
  251. repeat:
  252. set_current_state(TASK_INTERRUPTIBLE); /* mb paired w/ kthread_stop */
  253. if (kthread_should_stop()) {
  254. __set_current_state(TASK_RUNNING);
  255. spin_lock_irq(&worker->lock);
  256. worker->task = NULL;
  257. spin_unlock_irq(&worker->lock);
  258. return 0;
  259. }
  260. work = NULL;
  261. spin_lock_irq(&worker->lock);
  262. if (!list_empty(&worker->work_list)) {
  263. work = list_first_entry(&worker->work_list,
  264. struct kthread_work, node);
  265. list_del_init(&work->node);
  266. }
  267. spin_unlock_irq(&worker->lock);
  268. if (work) {
  269. __set_current_state(TASK_RUNNING);
  270. work->func(work);
  271. smp_wmb(); /* wmb worker-b0 paired with flush-b1 */
  272. work->done_seq = work->queue_seq;
  273. smp_mb(); /* mb worker-b1 paired with flush-b0 */
  274. if (atomic_read(&work->flushing))
  275. wake_up_all(&work->done);
  276. } else if (!freezing(current))
  277. schedule();
  278. try_to_freeze();
  279. goto repeat;
  280. }
  281. EXPORT_SYMBOL_GPL(kthread_worker_fn);
  282. /**
  283. * queue_kthread_work - queue a kthread_work
  284. * @worker: target kthread_worker
  285. * @work: kthread_work to queue
  286. *
  287. * Queue @work to work processor @task for async execution. @task
  288. * must have been created with kthread_worker_create(). Returns %true
  289. * if @work was successfully queued, %false if it was already pending.
  290. */
  291. bool queue_kthread_work(struct kthread_worker *worker,
  292. struct kthread_work *work)
  293. {
  294. bool ret = false;
  295. unsigned long flags;
  296. spin_lock_irqsave(&worker->lock, flags);
  297. if (list_empty(&work->node)) {
  298. list_add_tail(&work->node, &worker->work_list);
  299. work->queue_seq++;
  300. if (likely(worker->task))
  301. wake_up_process(worker->task);
  302. ret = true;
  303. }
  304. spin_unlock_irqrestore(&worker->lock, flags);
  305. return ret;
  306. }
  307. EXPORT_SYMBOL_GPL(queue_kthread_work);
  308. /**
  309. * flush_kthread_work - flush a kthread_work
  310. * @work: work to flush
  311. *
  312. * If @work is queued or executing, wait for it to finish execution.
  313. */
  314. void flush_kthread_work(struct kthread_work *work)
  315. {
  316. int seq = work->queue_seq;
  317. atomic_inc(&work->flushing);
  318. /*
  319. * mb flush-b0 paired with worker-b1, to make sure either
  320. * worker sees the above increment or we see done_seq update.
  321. */
  322. smp_mb__after_atomic_inc();
  323. /* A - B <= 0 tests whether B is in front of A regardless of overflow */
  324. wait_event(work->done, seq - work->done_seq <= 0);
  325. atomic_dec(&work->flushing);
  326. /*
  327. * rmb flush-b1 paired with worker-b0, to make sure our caller
  328. * sees every change made by work->func().
  329. */
  330. smp_mb__after_atomic_dec();
  331. }
  332. EXPORT_SYMBOL_GPL(flush_kthread_work);
  333. struct kthread_flush_work {
  334. struct kthread_work work;
  335. struct completion done;
  336. };
  337. static void kthread_flush_work_fn(struct kthread_work *work)
  338. {
  339. struct kthread_flush_work *fwork =
  340. container_of(work, struct kthread_flush_work, work);
  341. complete(&fwork->done);
  342. }
  343. /**
  344. * flush_kthread_worker - flush all current works on a kthread_worker
  345. * @worker: worker to flush
  346. *
  347. * Wait until all currently executing or pending works on @worker are
  348. * finished.
  349. */
  350. void flush_kthread_worker(struct kthread_worker *worker)
  351. {
  352. struct kthread_flush_work fwork = {
  353. KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
  354. COMPLETION_INITIALIZER_ONSTACK(fwork.done),
  355. };
  356. queue_kthread_work(worker, &fwork.work);
  357. wait_for_completion(&fwork.done);
  358. }
  359. EXPORT_SYMBOL_GPL(flush_kthread_worker);