kthread.c 13 KB

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