kthread.c 12 KB

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