kthread.c 17 KB

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