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 <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 void __kthread_unpark(struct task_struct *k, struct kthread *kthread)
  290. {
  291. clear_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
  292. /*
  293. * We clear the IS_PARKED bit here as we don't wait
  294. * until the task has left the park code. So if we'd
  295. * park before that happens we'd see the IS_PARKED bit
  296. * which might be about to be cleared.
  297. */
  298. if (test_and_clear_bit(KTHREAD_IS_PARKED, &kthread->flags)) {
  299. if (test_bit(KTHREAD_IS_PER_CPU, &kthread->flags))
  300. __kthread_bind(k, kthread->cpu, TASK_PARKED);
  301. wake_up_state(k, TASK_PARKED);
  302. }
  303. }
  304. /**
  305. * kthread_unpark - unpark a thread created by kthread_create().
  306. * @k: thread created by kthread_create().
  307. *
  308. * Sets kthread_should_park() for @k to return false, wakes it, and
  309. * waits for it to return. If the thread is marked percpu then its
  310. * bound to the cpu again.
  311. */
  312. void kthread_unpark(struct task_struct *k)
  313. {
  314. struct kthread *kthread = to_live_kthread(k);
  315. if (kthread)
  316. __kthread_unpark(k, kthread);
  317. }
  318. /**
  319. * kthread_park - park a thread created by kthread_create().
  320. * @k: thread created by kthread_create().
  321. *
  322. * Sets kthread_should_park() for @k to return true, wakes it, and
  323. * waits for it to return. This can also be called after kthread_create()
  324. * instead of calling wake_up_process(): the thread will park without
  325. * calling threadfn().
  326. *
  327. * Returns 0 if the thread is parked, -ENOSYS if the thread exited.
  328. * If called by the kthread itself just the park bit is set.
  329. */
  330. int kthread_park(struct task_struct *k)
  331. {
  332. struct kthread *kthread = to_live_kthread(k);
  333. int ret = -ENOSYS;
  334. if (kthread) {
  335. if (!test_bit(KTHREAD_IS_PARKED, &kthread->flags)) {
  336. set_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
  337. if (k != current) {
  338. wake_up_process(k);
  339. wait_for_completion(&kthread->parked);
  340. }
  341. }
  342. ret = 0;
  343. }
  344. return ret;
  345. }
  346. /**
  347. * kthread_stop - stop a thread created by kthread_create().
  348. * @k: thread created by kthread_create().
  349. *
  350. * Sets kthread_should_stop() for @k to return true, wakes it, and
  351. * waits for it to exit. This can also be called after kthread_create()
  352. * instead of calling wake_up_process(): the thread will exit without
  353. * calling threadfn().
  354. *
  355. * If threadfn() may call do_exit() itself, the caller must ensure
  356. * task_struct can't go away.
  357. *
  358. * Returns the result of threadfn(), or %-EINTR if wake_up_process()
  359. * was never called.
  360. */
  361. int kthread_stop(struct task_struct *k)
  362. {
  363. struct kthread *kthread;
  364. int ret;
  365. trace_sched_kthread_stop(k);
  366. get_task_struct(k);
  367. kthread = to_live_kthread(k);
  368. if (kthread) {
  369. set_bit(KTHREAD_SHOULD_STOP, &kthread->flags);
  370. __kthread_unpark(k, kthread);
  371. wake_up_process(k);
  372. wait_for_completion(&kthread->exited);
  373. }
  374. ret = k->exit_code;
  375. put_task_struct(k);
  376. trace_sched_kthread_stop_ret(ret);
  377. return ret;
  378. }
  379. EXPORT_SYMBOL(kthread_stop);
  380. int kthreadd(void *unused)
  381. {
  382. struct task_struct *tsk = current;
  383. /* Setup a clean context for our children to inherit. */
  384. set_task_comm(tsk, "kthreadd");
  385. ignore_signals(tsk);
  386. set_cpus_allowed_ptr(tsk, cpu_all_mask);
  387. set_mems_allowed(node_states[N_MEMORY]);
  388. current->flags |= PF_NOFREEZE;
  389. for (;;) {
  390. set_current_state(TASK_INTERRUPTIBLE);
  391. if (list_empty(&kthread_create_list))
  392. schedule();
  393. __set_current_state(TASK_RUNNING);
  394. spin_lock(&kthread_create_lock);
  395. while (!list_empty(&kthread_create_list)) {
  396. struct kthread_create_info *create;
  397. create = list_entry(kthread_create_list.next,
  398. struct kthread_create_info, list);
  399. list_del_init(&create->list);
  400. spin_unlock(&kthread_create_lock);
  401. create_kthread(create);
  402. spin_lock(&kthread_create_lock);
  403. }
  404. spin_unlock(&kthread_create_lock);
  405. }
  406. return 0;
  407. }
  408. void __init_kthread_worker(struct kthread_worker *worker,
  409. const char *name,
  410. struct lock_class_key *key)
  411. {
  412. spin_lock_init(&worker->lock);
  413. lockdep_set_class_and_name(&worker->lock, key, name);
  414. INIT_LIST_HEAD(&worker->work_list);
  415. worker->task = NULL;
  416. }
  417. EXPORT_SYMBOL_GPL(__init_kthread_worker);
  418. /**
  419. * kthread_worker_fn - kthread function to process kthread_worker
  420. * @worker_ptr: pointer to initialized kthread_worker
  421. *
  422. * This function can be used as @threadfn to kthread_create() or
  423. * kthread_run() with @worker_ptr argument pointing to an initialized
  424. * kthread_worker. The started kthread will process work_list until
  425. * the it is stopped with kthread_stop(). A kthread can also call
  426. * this function directly after extra initialization.
  427. *
  428. * Different kthreads can be used for the same kthread_worker as long
  429. * as there's only one kthread attached to it at any given time. A
  430. * kthread_worker without an attached kthread simply collects queued
  431. * kthread_works.
  432. */
  433. int kthread_worker_fn(void *worker_ptr)
  434. {
  435. struct kthread_worker *worker = worker_ptr;
  436. struct kthread_work *work;
  437. WARN_ON(worker->task);
  438. worker->task = current;
  439. repeat:
  440. set_current_state(TASK_INTERRUPTIBLE); /* mb paired w/ kthread_stop */
  441. if (kthread_should_stop()) {
  442. __set_current_state(TASK_RUNNING);
  443. spin_lock_irq(&worker->lock);
  444. worker->task = NULL;
  445. spin_unlock_irq(&worker->lock);
  446. return 0;
  447. }
  448. work = NULL;
  449. spin_lock_irq(&worker->lock);
  450. if (!list_empty(&worker->work_list)) {
  451. work = list_first_entry(&worker->work_list,
  452. struct kthread_work, node);
  453. list_del_init(&work->node);
  454. }
  455. worker->current_work = work;
  456. spin_unlock_irq(&worker->lock);
  457. if (work) {
  458. __set_current_state(TASK_RUNNING);
  459. work->func(work);
  460. } else if (!freezing(current))
  461. schedule();
  462. try_to_freeze();
  463. goto repeat;
  464. }
  465. EXPORT_SYMBOL_GPL(kthread_worker_fn);
  466. /* insert @work before @pos in @worker */
  467. static void insert_kthread_work(struct kthread_worker *worker,
  468. struct kthread_work *work,
  469. struct list_head *pos)
  470. {
  471. lockdep_assert_held(&worker->lock);
  472. list_add_tail(&work->node, pos);
  473. work->worker = worker;
  474. if (likely(worker->task))
  475. wake_up_process(worker->task);
  476. }
  477. /**
  478. * queue_kthread_work - queue a kthread_work
  479. * @worker: target kthread_worker
  480. * @work: kthread_work to queue
  481. *
  482. * Queue @work to work processor @task for async execution. @task
  483. * must have been created with kthread_worker_create(). Returns %true
  484. * if @work was successfully queued, %false if it was already pending.
  485. */
  486. bool queue_kthread_work(struct kthread_worker *worker,
  487. struct kthread_work *work)
  488. {
  489. bool ret = false;
  490. unsigned long flags;
  491. spin_lock_irqsave(&worker->lock, flags);
  492. if (list_empty(&work->node)) {
  493. insert_kthread_work(worker, work, &worker->work_list);
  494. ret = true;
  495. }
  496. spin_unlock_irqrestore(&worker->lock, flags);
  497. return ret;
  498. }
  499. EXPORT_SYMBOL_GPL(queue_kthread_work);
  500. struct kthread_flush_work {
  501. struct kthread_work work;
  502. struct completion done;
  503. };
  504. static void kthread_flush_work_fn(struct kthread_work *work)
  505. {
  506. struct kthread_flush_work *fwork =
  507. container_of(work, struct kthread_flush_work, work);
  508. complete(&fwork->done);
  509. }
  510. /**
  511. * flush_kthread_work - flush a kthread_work
  512. * @work: work to flush
  513. *
  514. * If @work is queued or executing, wait for it to finish execution.
  515. */
  516. void flush_kthread_work(struct kthread_work *work)
  517. {
  518. struct kthread_flush_work fwork = {
  519. KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
  520. COMPLETION_INITIALIZER_ONSTACK(fwork.done),
  521. };
  522. struct kthread_worker *worker;
  523. bool noop = false;
  524. retry:
  525. worker = work->worker;
  526. if (!worker)
  527. return;
  528. spin_lock_irq(&worker->lock);
  529. if (work->worker != worker) {
  530. spin_unlock_irq(&worker->lock);
  531. goto retry;
  532. }
  533. if (!list_empty(&work->node))
  534. insert_kthread_work(worker, &fwork.work, work->node.next);
  535. else if (worker->current_work == work)
  536. insert_kthread_work(worker, &fwork.work, worker->work_list.next);
  537. else
  538. noop = true;
  539. spin_unlock_irq(&worker->lock);
  540. if (!noop)
  541. wait_for_completion(&fwork.done);
  542. }
  543. EXPORT_SYMBOL_GPL(flush_kthread_work);
  544. /**
  545. * flush_kthread_worker - flush all current works on a kthread_worker
  546. * @worker: worker to flush
  547. *
  548. * Wait until all currently executing or pending works on @worker are
  549. * finished.
  550. */
  551. void flush_kthread_worker(struct kthread_worker *worker)
  552. {
  553. struct kthread_flush_work fwork = {
  554. KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
  555. COMPLETION_INITIALIZER_ONSTACK(fwork.done),
  556. };
  557. queue_kthread_work(worker, &fwork.work);
  558. wait_for_completion(&fwork.done);
  559. }
  560. EXPORT_SYMBOL_GPL(flush_kthread_worker);