kthread.c 17 KB

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