kthread.c 17 KB

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