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(tsk) \
  49. container_of((tsk)->vfork_done, struct kthread, exited)
  50. /**
  51. * kthread_should_stop - should this kthread return now?
  52. *
  53. * When someone calls kthread_stop() on your kthread, it will be woken
  54. * and this will return true. You should then return, and your return
  55. * value will be passed through to kthread_stop().
  56. */
  57. bool kthread_should_stop(void)
  58. {
  59. return test_bit(KTHREAD_SHOULD_STOP, &to_kthread(current)->flags);
  60. }
  61. EXPORT_SYMBOL(kthread_should_stop);
  62. /**
  63. * kthread_should_park - should this kthread park now?
  64. *
  65. * When someone calls kthread_park() on your kthread, it will be woken
  66. * and this will return true. You should then do the necessary
  67. * cleanup and call kthread_parkme()
  68. *
  69. * Similar to kthread_should_stop(), but this keeps the thread alive
  70. * and in a park position. kthread_unpark() "restarts" the thread and
  71. * calls the thread function again.
  72. */
  73. bool kthread_should_park(void)
  74. {
  75. return test_bit(KTHREAD_SHOULD_PARK, &to_kthread(current)->flags);
  76. }
  77. /**
  78. * kthread_freezable_should_stop - should this freezable kthread return now?
  79. * @was_frozen: optional out parameter, indicates whether %current was frozen
  80. *
  81. * kthread_should_stop() for freezable kthreads, which will enter
  82. * refrigerator if necessary. This function is safe from kthread_stop() /
  83. * freezer deadlock and freezable kthreads should use this function instead
  84. * of calling try_to_freeze() directly.
  85. */
  86. bool kthread_freezable_should_stop(bool *was_frozen)
  87. {
  88. bool frozen = false;
  89. might_sleep();
  90. if (unlikely(freezing(current)))
  91. frozen = __refrigerator(true);
  92. if (was_frozen)
  93. *was_frozen = frozen;
  94. return kthread_should_stop();
  95. }
  96. EXPORT_SYMBOL_GPL(kthread_freezable_should_stop);
  97. /**
  98. * kthread_data - return data value specified on kthread creation
  99. * @task: kthread task in question
  100. *
  101. * Return the data value specified when kthread @task was created.
  102. * The caller is responsible for ensuring the validity of @task when
  103. * calling this function.
  104. */
  105. void *kthread_data(struct task_struct *task)
  106. {
  107. return to_kthread(task)->data;
  108. }
  109. static void __kthread_parkme(struct kthread *self)
  110. {
  111. __set_current_state(TASK_PARKED);
  112. while (test_bit(KTHREAD_SHOULD_PARK, &self->flags)) {
  113. if (!test_and_set_bit(KTHREAD_IS_PARKED, &self->flags))
  114. complete(&self->parked);
  115. schedule();
  116. __set_current_state(TASK_PARKED);
  117. }
  118. clear_bit(KTHREAD_IS_PARKED, &self->flags);
  119. __set_current_state(TASK_RUNNING);
  120. }
  121. void kthread_parkme(void)
  122. {
  123. __kthread_parkme(to_kthread(current));
  124. }
  125. static int kthread(void *_create)
  126. {
  127. /* Copy data: it's on kthread's stack */
  128. struct kthread_create_info *create = _create;
  129. int (*threadfn)(void *data) = create->threadfn;
  130. void *data = create->data;
  131. struct kthread self;
  132. int ret;
  133. self.flags = 0;
  134. self.data = data;
  135. init_completion(&self.exited);
  136. init_completion(&self.parked);
  137. current->vfork_done = &self.exited;
  138. /* OK, tell user we're spawned, wait for stop or wakeup */
  139. __set_current_state(TASK_UNINTERRUPTIBLE);
  140. create->result = current;
  141. complete(&create->done);
  142. schedule();
  143. ret = -EINTR;
  144. if (!test_bit(KTHREAD_SHOULD_STOP, &self.flags)) {
  145. __kthread_parkme(&self);
  146. ret = threadfn(data);
  147. }
  148. /* we can't just return, we must preserve "self" on stack */
  149. do_exit(ret);
  150. }
  151. /* called from do_fork() to get node information for about to be created task */
  152. int tsk_fork_get_node(struct task_struct *tsk)
  153. {
  154. #ifdef CONFIG_NUMA
  155. if (tsk == kthreadd_task)
  156. return tsk->pref_node_fork;
  157. #endif
  158. return numa_node_id();
  159. }
  160. static void create_kthread(struct kthread_create_info *create)
  161. {
  162. int pid;
  163. #ifdef CONFIG_NUMA
  164. current->pref_node_fork = create->node;
  165. #endif
  166. /* We want our own signal handler (we take no signals by default). */
  167. pid = kernel_thread(kthread, create, CLONE_FS | CLONE_FILES | SIGCHLD);
  168. if (pid < 0) {
  169. create->result = ERR_PTR(pid);
  170. complete(&create->done);
  171. }
  172. }
  173. /**
  174. * kthread_create_on_node - create a kthread.
  175. * @threadfn: the function to run until signal_pending(current).
  176. * @data: data ptr for @threadfn.
  177. * @node: memory node number.
  178. * @namefmt: printf-style name for the thread.
  179. *
  180. * Description: This helper function creates and names a kernel
  181. * thread. The thread will be stopped: use wake_up_process() to start
  182. * it. See also kthread_run().
  183. *
  184. * If thread is going to be bound on a particular cpu, give its node
  185. * in @node, to get NUMA affinity for kthread stack, or else give -1.
  186. * When woken, the thread will run @threadfn() with @data as its
  187. * argument. @threadfn() can either call do_exit() directly if it is a
  188. * standalone thread for which no one will call kthread_stop(), or
  189. * return when 'kthread_should_stop()' is true (which means
  190. * kthread_stop() has been called). The return value should be zero
  191. * or a negative error number; it will be passed to kthread_stop().
  192. *
  193. * Returns a task_struct or ERR_PTR(-ENOMEM).
  194. */
  195. struct task_struct *kthread_create_on_node(int (*threadfn)(void *data),
  196. void *data, int node,
  197. const char namefmt[],
  198. ...)
  199. {
  200. struct kthread_create_info create;
  201. create.threadfn = threadfn;
  202. create.data = data;
  203. create.node = node;
  204. init_completion(&create.done);
  205. spin_lock(&kthread_create_lock);
  206. list_add_tail(&create.list, &kthread_create_list);
  207. spin_unlock(&kthread_create_lock);
  208. wake_up_process(kthreadd_task);
  209. wait_for_completion(&create.done);
  210. if (!IS_ERR(create.result)) {
  211. static const struct sched_param param = { .sched_priority = 0 };
  212. va_list args;
  213. va_start(args, namefmt);
  214. vsnprintf(create.result->comm, sizeof(create.result->comm),
  215. namefmt, args);
  216. va_end(args);
  217. /*
  218. * root may have changed our (kthreadd's) priority or CPU mask.
  219. * The kernel thread should not inherit these properties.
  220. */
  221. sched_setscheduler_nocheck(create.result, SCHED_NORMAL, &param);
  222. set_cpus_allowed_ptr(create.result, cpu_all_mask);
  223. }
  224. return create.result;
  225. }
  226. EXPORT_SYMBOL(kthread_create_on_node);
  227. static void __kthread_bind(struct task_struct *p, unsigned int cpu, long state)
  228. {
  229. /* Must have done schedule() in kthread() before we set_task_cpu */
  230. if (!wait_task_inactive(p, state)) {
  231. WARN_ON(1);
  232. return;
  233. }
  234. /* It's safe because the task is inactive. */
  235. do_set_cpus_allowed(p, cpumask_of(cpu));
  236. p->flags |= PF_THREAD_BOUND;
  237. }
  238. /**
  239. * kthread_bind - bind a just-created kthread to a cpu.
  240. * @p: thread created by kthread_create().
  241. * @cpu: cpu (might not be online, must be possible) for @k to run on.
  242. *
  243. * Description: This function is equivalent to set_cpus_allowed(),
  244. * except that @cpu doesn't need to be online, and the thread must be
  245. * stopped (i.e., just returned from kthread_create()).
  246. */
  247. void kthread_bind(struct task_struct *p, unsigned int cpu)
  248. {
  249. __kthread_bind(p, cpu, TASK_UNINTERRUPTIBLE);
  250. }
  251. EXPORT_SYMBOL(kthread_bind);
  252. /**
  253. * kthread_create_on_cpu - Create a cpu bound kthread
  254. * @threadfn: the function to run until signal_pending(current).
  255. * @data: data ptr for @threadfn.
  256. * @cpu: The cpu on which the thread should be bound,
  257. * @namefmt: printf-style name for the thread. Format is restricted
  258. * to "name.*%u". Code fills in cpu number.
  259. *
  260. * Description: This helper function creates and names a kernel thread
  261. * The thread will be woken and put into park mode.
  262. */
  263. struct task_struct *kthread_create_on_cpu(int (*threadfn)(void *data),
  264. void *data, unsigned int cpu,
  265. const char *namefmt)
  266. {
  267. struct task_struct *p;
  268. p = kthread_create_on_node(threadfn, data, cpu_to_node(cpu), namefmt,
  269. cpu);
  270. if (IS_ERR(p))
  271. return p;
  272. set_bit(KTHREAD_IS_PER_CPU, &to_kthread(p)->flags);
  273. to_kthread(p)->cpu = cpu;
  274. /* Park the thread to get it out of TASK_UNINTERRUPTIBLE state */
  275. kthread_park(p);
  276. return p;
  277. }
  278. static struct kthread *task_get_live_kthread(struct task_struct *k)
  279. {
  280. struct kthread *kthread;
  281. get_task_struct(k);
  282. kthread = to_kthread(k);
  283. /* It might have exited */
  284. barrier();
  285. if (k->vfork_done != NULL)
  286. return kthread;
  287. return NULL;
  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 = task_get_live_kthread(k);
  315. if (kthread)
  316. __kthread_unpark(k, kthread);
  317. put_task_struct(k);
  318. }
  319. /**
  320. * kthread_park - park a thread created by kthread_create().
  321. * @k: thread created by kthread_create().
  322. *
  323. * Sets kthread_should_park() for @k to return true, wakes it, and
  324. * waits for it to return. This can also be called after kthread_create()
  325. * instead of calling wake_up_process(): the thread will park without
  326. * calling threadfn().
  327. *
  328. * Returns 0 if the thread is parked, -ENOSYS if the thread exited.
  329. * If called by the kthread itself just the park bit is set.
  330. */
  331. int kthread_park(struct task_struct *k)
  332. {
  333. struct kthread *kthread = task_get_live_kthread(k);
  334. int ret = -ENOSYS;
  335. if (kthread) {
  336. if (!test_bit(KTHREAD_IS_PARKED, &kthread->flags)) {
  337. set_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
  338. if (k != current) {
  339. wake_up_process(k);
  340. wait_for_completion(&kthread->parked);
  341. }
  342. }
  343. ret = 0;
  344. }
  345. put_task_struct(k);
  346. return ret;
  347. }
  348. /**
  349. * kthread_stop - stop a thread created by kthread_create().
  350. * @k: thread created by kthread_create().
  351. *
  352. * Sets kthread_should_stop() for @k to return true, wakes it, and
  353. * waits for it to exit. This can also be called after kthread_create()
  354. * instead of calling wake_up_process(): the thread will exit without
  355. * calling threadfn().
  356. *
  357. * If threadfn() may call do_exit() itself, the caller must ensure
  358. * task_struct can't go away.
  359. *
  360. * Returns the result of threadfn(), or %-EINTR if wake_up_process()
  361. * was never called.
  362. */
  363. int kthread_stop(struct task_struct *k)
  364. {
  365. struct kthread *kthread = task_get_live_kthread(k);
  366. int ret;
  367. trace_sched_kthread_stop(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);