kthread.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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. unsigned long flags;
  36. unsigned int cpu;
  37. void *data;
  38. struct completion parked;
  39. struct completion exited;
  40. };
  41. enum KTHREAD_BITS {
  42. KTHREAD_IS_PER_CPU = 0,
  43. KTHREAD_SHOULD_STOP,
  44. KTHREAD_SHOULD_PARK,
  45. KTHREAD_IS_PARKED,
  46. };
  47. #define to_kthread(tsk) \
  48. container_of((tsk)->vfork_done, struct kthread, exited)
  49. /**
  50. * kthread_should_stop - should this kthread return now?
  51. *
  52. * When someone calls kthread_stop() on your kthread, it will be woken
  53. * and this will return true. You should then return, and your return
  54. * value will be passed through to kthread_stop().
  55. */
  56. bool kthread_should_stop(void)
  57. {
  58. return test_bit(KTHREAD_SHOULD_STOP, &to_kthread(current)->flags);
  59. }
  60. EXPORT_SYMBOL(kthread_should_stop);
  61. /**
  62. * kthread_should_park - should this kthread park now?
  63. *
  64. * When someone calls kthread_park() on your kthread, it will be woken
  65. * and this will return true. You should then do the necessary
  66. * cleanup and call kthread_parkme()
  67. *
  68. * Similar to kthread_should_stop(), but this keeps the thread alive
  69. * and in a park position. kthread_unpark() "restarts" the thread and
  70. * calls the thread function again.
  71. */
  72. bool kthread_should_park(void)
  73. {
  74. return test_bit(KTHREAD_SHOULD_PARK, &to_kthread(current)->flags);
  75. }
  76. /**
  77. * kthread_freezable_should_stop - should this freezable kthread return now?
  78. * @was_frozen: optional out parameter, indicates whether %current was frozen
  79. *
  80. * kthread_should_stop() for freezable kthreads, which will enter
  81. * refrigerator if necessary. This function is safe from kthread_stop() /
  82. * freezer deadlock and freezable kthreads should use this function instead
  83. * of calling try_to_freeze() directly.
  84. */
  85. bool kthread_freezable_should_stop(bool *was_frozen)
  86. {
  87. bool frozen = false;
  88. might_sleep();
  89. if (unlikely(freezing(current)))
  90. frozen = __refrigerator(true);
  91. if (was_frozen)
  92. *was_frozen = frozen;
  93. return kthread_should_stop();
  94. }
  95. EXPORT_SYMBOL_GPL(kthread_freezable_should_stop);
  96. /**
  97. * kthread_data - return data value specified on kthread creation
  98. * @task: kthread task in question
  99. *
  100. * Return the data value specified when kthread @task was created.
  101. * The caller is responsible for ensuring the validity of @task when
  102. * calling this function.
  103. */
  104. void *kthread_data(struct task_struct *task)
  105. {
  106. return to_kthread(task)->data;
  107. }
  108. static void __kthread_parkme(struct kthread *self)
  109. {
  110. __set_current_state(TASK_INTERRUPTIBLE);
  111. while (test_bit(KTHREAD_SHOULD_PARK, &self->flags)) {
  112. if (!test_and_set_bit(KTHREAD_IS_PARKED, &self->flags))
  113. complete(&self->parked);
  114. schedule();
  115. __set_current_state(TASK_INTERRUPTIBLE);
  116. }
  117. clear_bit(KTHREAD_IS_PARKED, &self->flags);
  118. __set_current_state(TASK_RUNNING);
  119. }
  120. void kthread_parkme(void)
  121. {
  122. __kthread_parkme(to_kthread(current));
  123. }
  124. static int kthread(void *_create)
  125. {
  126. /* Copy data: it's on kthread's stack */
  127. struct kthread_create_info *create = _create;
  128. int (*threadfn)(void *data) = create->threadfn;
  129. void *data = create->data;
  130. struct kthread self;
  131. int ret;
  132. self.flags = 0;
  133. self.data = data;
  134. init_completion(&self.exited);
  135. init_completion(&self.parked);
  136. current->vfork_done = &self.exited;
  137. /* OK, tell user we're spawned, wait for stop or wakeup */
  138. __set_current_state(TASK_UNINTERRUPTIBLE);
  139. create->result = current;
  140. complete(&create->done);
  141. schedule();
  142. ret = -EINTR;
  143. if (!test_bit(KTHREAD_SHOULD_STOP, &self.flags)) {
  144. __kthread_parkme(&self);
  145. ret = threadfn(data);
  146. }
  147. /* we can't just return, we must preserve "self" on stack */
  148. do_exit(ret);
  149. }
  150. /* called from do_fork() to get node information for about to be created task */
  151. int tsk_fork_get_node(struct task_struct *tsk)
  152. {
  153. #ifdef CONFIG_NUMA
  154. if (tsk == kthreadd_task)
  155. return tsk->pref_node_fork;
  156. #endif
  157. return numa_node_id();
  158. }
  159. static void create_kthread(struct kthread_create_info *create)
  160. {
  161. int pid;
  162. #ifdef CONFIG_NUMA
  163. current->pref_node_fork = create->node;
  164. #endif
  165. /* We want our own signal handler (we take no signals by default). */
  166. pid = kernel_thread(kthread, create, CLONE_FS | CLONE_FILES | SIGCHLD);
  167. if (pid < 0) {
  168. create->result = ERR_PTR(pid);
  169. complete(&create->done);
  170. }
  171. }
  172. /**
  173. * kthread_create_on_node - create a kthread.
  174. * @threadfn: the function to run until signal_pending(current).
  175. * @data: data ptr for @threadfn.
  176. * @node: memory node number.
  177. * @namefmt: printf-style name for the thread.
  178. *
  179. * Description: This helper function creates and names a kernel
  180. * thread. The thread will be stopped: use wake_up_process() to start
  181. * it. See also kthread_run().
  182. *
  183. * If thread is going to be bound on a particular cpu, give its node
  184. * in @node, to get NUMA affinity for kthread stack, or else give -1.
  185. * When woken, the thread will run @threadfn() with @data as its
  186. * argument. @threadfn() can either call do_exit() directly if it is a
  187. * standalone thread for which no one will call kthread_stop(), or
  188. * return when 'kthread_should_stop()' is true (which means
  189. * kthread_stop() has been called). The return value should be zero
  190. * or a negative error number; it will be passed to kthread_stop().
  191. *
  192. * Returns a task_struct or ERR_PTR(-ENOMEM).
  193. */
  194. struct task_struct *kthread_create_on_node(int (*threadfn)(void *data),
  195. void *data, int node,
  196. const char namefmt[],
  197. ...)
  198. {
  199. struct kthread_create_info create;
  200. create.threadfn = threadfn;
  201. create.data = data;
  202. create.node = node;
  203. init_completion(&create.done);
  204. spin_lock(&kthread_create_lock);
  205. list_add_tail(&create.list, &kthread_create_list);
  206. spin_unlock(&kthread_create_lock);
  207. wake_up_process(kthreadd_task);
  208. wait_for_completion(&create.done);
  209. if (!IS_ERR(create.result)) {
  210. static const struct sched_param param = { .sched_priority = 0 };
  211. va_list args;
  212. va_start(args, namefmt);
  213. vsnprintf(create.result->comm, sizeof(create.result->comm),
  214. namefmt, args);
  215. va_end(args);
  216. /*
  217. * root may have changed our (kthreadd's) priority or CPU mask.
  218. * The kernel thread should not inherit these properties.
  219. */
  220. sched_setscheduler_nocheck(create.result, SCHED_NORMAL, &param);
  221. set_cpus_allowed_ptr(create.result, cpu_all_mask);
  222. }
  223. return create.result;
  224. }
  225. EXPORT_SYMBOL(kthread_create_on_node);
  226. static void __kthread_bind(struct task_struct *p, unsigned int cpu)
  227. {
  228. /* It's safe because the task is inactive. */
  229. do_set_cpus_allowed(p, cpumask_of(cpu));
  230. p->flags |= PF_THREAD_BOUND;
  231. }
  232. /**
  233. * kthread_bind - bind a just-created kthread to a cpu.
  234. * @p: thread created by kthread_create().
  235. * @cpu: cpu (might not be online, must be possible) for @k to run on.
  236. *
  237. * Description: This function is equivalent to set_cpus_allowed(),
  238. * except that @cpu doesn't need to be online, and the thread must be
  239. * stopped (i.e., just returned from kthread_create()).
  240. */
  241. void kthread_bind(struct task_struct *p, unsigned int cpu)
  242. {
  243. /* Must have done schedule() in kthread() before we set_task_cpu */
  244. if (!wait_task_inactive(p, TASK_UNINTERRUPTIBLE)) {
  245. WARN_ON(1);
  246. return;
  247. }
  248. __kthread_bind(p, cpu);
  249. }
  250. EXPORT_SYMBOL(kthread_bind);
  251. /**
  252. * kthread_create_on_cpu - Create a cpu bound kthread
  253. * @threadfn: the function to run until signal_pending(current).
  254. * @data: data ptr for @threadfn.
  255. * @cpu: The cpu on which the thread should be bound,
  256. * @namefmt: printf-style name for the thread. Format is restricted
  257. * to "name.*%u". Code fills in cpu number.
  258. *
  259. * Description: This helper function creates and names a kernel thread
  260. * The thread will be woken and put into park mode.
  261. */
  262. struct task_struct *kthread_create_on_cpu(int (*threadfn)(void *data),
  263. void *data, unsigned int cpu,
  264. const char *namefmt)
  265. {
  266. struct task_struct *p;
  267. p = kthread_create_on_node(threadfn, data, cpu_to_node(cpu), namefmt,
  268. cpu);
  269. if (IS_ERR(p))
  270. return p;
  271. set_bit(KTHREAD_IS_PER_CPU, &to_kthread(p)->flags);
  272. to_kthread(p)->cpu = cpu;
  273. /* Park the thread to get it out of TASK_UNINTERRUPTIBLE state */
  274. kthread_park(p);
  275. return p;
  276. }
  277. static struct kthread *task_get_live_kthread(struct task_struct *k)
  278. {
  279. struct kthread *kthread;
  280. get_task_struct(k);
  281. kthread = to_kthread(k);
  282. /* It might have exited */
  283. barrier();
  284. if (k->vfork_done != NULL)
  285. return kthread;
  286. return NULL;
  287. }
  288. /**
  289. * kthread_unpark - unpark a thread created by kthread_create().
  290. * @k: thread created by kthread_create().
  291. *
  292. * Sets kthread_should_park() for @k to return false, wakes it, and
  293. * waits for it to return. If the thread is marked percpu then its
  294. * bound to the cpu again.
  295. */
  296. void kthread_unpark(struct task_struct *k)
  297. {
  298. struct kthread *kthread = task_get_live_kthread(k);
  299. if (kthread) {
  300. clear_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
  301. /*
  302. * We clear the IS_PARKED bit here as we don't wait
  303. * until the task has left the park code. So if we'd
  304. * park before that happens we'd see the IS_PARKED bit
  305. * which might be about to be cleared.
  306. */
  307. if (test_and_clear_bit(KTHREAD_IS_PARKED, &kthread->flags)) {
  308. if (test_bit(KTHREAD_IS_PER_CPU, &kthread->flags))
  309. __kthread_bind(k, kthread->cpu);
  310. wake_up_process(k);
  311. }
  312. }
  313. put_task_struct(k);
  314. }
  315. /**
  316. * kthread_park - park a thread created by kthread_create().
  317. * @k: thread created by kthread_create().
  318. *
  319. * Sets kthread_should_park() for @k to return true, wakes it, and
  320. * waits for it to return. This can also be called after kthread_create()
  321. * instead of calling wake_up_process(): the thread will park without
  322. * calling threadfn().
  323. *
  324. * Returns 0 if the thread is parked, -ENOSYS if the thread exited.
  325. * If called by the kthread itself just the park bit is set.
  326. */
  327. int kthread_park(struct task_struct *k)
  328. {
  329. struct kthread *kthread = task_get_live_kthread(k);
  330. int ret = -ENOSYS;
  331. if (kthread) {
  332. if (!test_bit(KTHREAD_IS_PARKED, &kthread->flags)) {
  333. set_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
  334. if (k != current) {
  335. wake_up_process(k);
  336. wait_for_completion(&kthread->parked);
  337. }
  338. }
  339. ret = 0;
  340. }
  341. put_task_struct(k);
  342. return ret;
  343. }
  344. /**
  345. * kthread_stop - stop a thread created by kthread_create().
  346. * @k: thread created by kthread_create().
  347. *
  348. * Sets kthread_should_stop() for @k to return true, wakes it, and
  349. * waits for it to exit. This can also be called after kthread_create()
  350. * instead of calling wake_up_process(): the thread will exit without
  351. * calling threadfn().
  352. *
  353. * If threadfn() may call do_exit() itself, the caller must ensure
  354. * task_struct can't go away.
  355. *
  356. * Returns the result of threadfn(), or %-EINTR if wake_up_process()
  357. * was never called.
  358. */
  359. int kthread_stop(struct task_struct *k)
  360. {
  361. struct kthread *kthread = task_get_live_kthread(k);
  362. int ret;
  363. trace_sched_kthread_stop(k);
  364. if (kthread) {
  365. set_bit(KTHREAD_SHOULD_STOP, &kthread->flags);
  366. clear_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
  367. wake_up_process(k);
  368. wait_for_completion(&kthread->exited);
  369. }
  370. ret = k->exit_code;
  371. put_task_struct(k);
  372. trace_sched_kthread_stop_ret(ret);
  373. return ret;
  374. }
  375. EXPORT_SYMBOL(kthread_stop);
  376. int kthreadd(void *unused)
  377. {
  378. struct task_struct *tsk = current;
  379. /* Setup a clean context for our children to inherit. */
  380. set_task_comm(tsk, "kthreadd");
  381. ignore_signals(tsk);
  382. set_cpus_allowed_ptr(tsk, cpu_all_mask);
  383. set_mems_allowed(node_states[N_HIGH_MEMORY]);
  384. current->flags |= PF_NOFREEZE;
  385. for (;;) {
  386. set_current_state(TASK_INTERRUPTIBLE);
  387. if (list_empty(&kthread_create_list))
  388. schedule();
  389. __set_current_state(TASK_RUNNING);
  390. spin_lock(&kthread_create_lock);
  391. while (!list_empty(&kthread_create_list)) {
  392. struct kthread_create_info *create;
  393. create = list_entry(kthread_create_list.next,
  394. struct kthread_create_info, list);
  395. list_del_init(&create->list);
  396. spin_unlock(&kthread_create_lock);
  397. create_kthread(create);
  398. spin_lock(&kthread_create_lock);
  399. }
  400. spin_unlock(&kthread_create_lock);
  401. }
  402. return 0;
  403. }
  404. void __init_kthread_worker(struct kthread_worker *worker,
  405. const char *name,
  406. struct lock_class_key *key)
  407. {
  408. spin_lock_init(&worker->lock);
  409. lockdep_set_class_and_name(&worker->lock, key, name);
  410. INIT_LIST_HEAD(&worker->work_list);
  411. worker->task = NULL;
  412. }
  413. EXPORT_SYMBOL_GPL(__init_kthread_worker);
  414. /**
  415. * kthread_worker_fn - kthread function to process kthread_worker
  416. * @worker_ptr: pointer to initialized kthread_worker
  417. *
  418. * This function can be used as @threadfn to kthread_create() or
  419. * kthread_run() with @worker_ptr argument pointing to an initialized
  420. * kthread_worker. The started kthread will process work_list until
  421. * the it is stopped with kthread_stop(). A kthread can also call
  422. * this function directly after extra initialization.
  423. *
  424. * Different kthreads can be used for the same kthread_worker as long
  425. * as there's only one kthread attached to it at any given time. A
  426. * kthread_worker without an attached kthread simply collects queued
  427. * kthread_works.
  428. */
  429. int kthread_worker_fn(void *worker_ptr)
  430. {
  431. struct kthread_worker *worker = worker_ptr;
  432. struct kthread_work *work;
  433. WARN_ON(worker->task);
  434. worker->task = current;
  435. repeat:
  436. set_current_state(TASK_INTERRUPTIBLE); /* mb paired w/ kthread_stop */
  437. if (kthread_should_stop()) {
  438. __set_current_state(TASK_RUNNING);
  439. spin_lock_irq(&worker->lock);
  440. worker->task = NULL;
  441. spin_unlock_irq(&worker->lock);
  442. return 0;
  443. }
  444. work = NULL;
  445. spin_lock_irq(&worker->lock);
  446. if (!list_empty(&worker->work_list)) {
  447. work = list_first_entry(&worker->work_list,
  448. struct kthread_work, node);
  449. list_del_init(&work->node);
  450. }
  451. worker->current_work = work;
  452. spin_unlock_irq(&worker->lock);
  453. if (work) {
  454. __set_current_state(TASK_RUNNING);
  455. work->func(work);
  456. } else if (!freezing(current))
  457. schedule();
  458. try_to_freeze();
  459. goto repeat;
  460. }
  461. EXPORT_SYMBOL_GPL(kthread_worker_fn);
  462. /* insert @work before @pos in @worker */
  463. static void insert_kthread_work(struct kthread_worker *worker,
  464. struct kthread_work *work,
  465. struct list_head *pos)
  466. {
  467. lockdep_assert_held(&worker->lock);
  468. list_add_tail(&work->node, pos);
  469. work->worker = worker;
  470. if (likely(worker->task))
  471. wake_up_process(worker->task);
  472. }
  473. /**
  474. * queue_kthread_work - queue a kthread_work
  475. * @worker: target kthread_worker
  476. * @work: kthread_work to queue
  477. *
  478. * Queue @work to work processor @task for async execution. @task
  479. * must have been created with kthread_worker_create(). Returns %true
  480. * if @work was successfully queued, %false if it was already pending.
  481. */
  482. bool queue_kthread_work(struct kthread_worker *worker,
  483. struct kthread_work *work)
  484. {
  485. bool ret = false;
  486. unsigned long flags;
  487. spin_lock_irqsave(&worker->lock, flags);
  488. if (list_empty(&work->node)) {
  489. insert_kthread_work(worker, work, &worker->work_list);
  490. ret = true;
  491. }
  492. spin_unlock_irqrestore(&worker->lock, flags);
  493. return ret;
  494. }
  495. EXPORT_SYMBOL_GPL(queue_kthread_work);
  496. struct kthread_flush_work {
  497. struct kthread_work work;
  498. struct completion done;
  499. };
  500. static void kthread_flush_work_fn(struct kthread_work *work)
  501. {
  502. struct kthread_flush_work *fwork =
  503. container_of(work, struct kthread_flush_work, work);
  504. complete(&fwork->done);
  505. }
  506. /**
  507. * flush_kthread_work - flush a kthread_work
  508. * @work: work to flush
  509. *
  510. * If @work is queued or executing, wait for it to finish execution.
  511. */
  512. void flush_kthread_work(struct kthread_work *work)
  513. {
  514. struct kthread_flush_work fwork = {
  515. KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
  516. COMPLETION_INITIALIZER_ONSTACK(fwork.done),
  517. };
  518. struct kthread_worker *worker;
  519. bool noop = false;
  520. retry:
  521. worker = work->worker;
  522. if (!worker)
  523. return;
  524. spin_lock_irq(&worker->lock);
  525. if (work->worker != worker) {
  526. spin_unlock_irq(&worker->lock);
  527. goto retry;
  528. }
  529. if (!list_empty(&work->node))
  530. insert_kthread_work(worker, &fwork.work, work->node.next);
  531. else if (worker->current_work == work)
  532. insert_kthread_work(worker, &fwork.work, worker->work_list.next);
  533. else
  534. noop = true;
  535. spin_unlock_irq(&worker->lock);
  536. if (!noop)
  537. wait_for_completion(&fwork.done);
  538. }
  539. EXPORT_SYMBOL_GPL(flush_kthread_work);
  540. /**
  541. * flush_kthread_worker - flush all current works on a kthread_worker
  542. * @worker: worker to flush
  543. *
  544. * Wait until all currently executing or pending works on @worker are
  545. * finished.
  546. */
  547. void flush_kthread_worker(struct kthread_worker *worker)
  548. {
  549. struct kthread_flush_work fwork = {
  550. KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
  551. COMPLETION_INITIALIZER_ONSTACK(fwork.done),
  552. };
  553. queue_kthread_work(worker, &fwork.work);
  554. wait_for_completion(&fwork.done);
  555. }
  556. EXPORT_SYMBOL_GPL(flush_kthread_worker);