kthread.c 18 KB

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