kthread.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  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 <uapi/linux/sched/types.h>
  9. #include <linux/sched.h>
  10. #include <linux/sched/task.h>
  11. #include <linux/kthread.h>
  12. #include <linux/completion.h>
  13. #include <linux/err.h>
  14. #include <linux/cpuset.h>
  15. #include <linux/unistd.h>
  16. #include <linux/file.h>
  17. #include <linux/export.h>
  18. #include <linux/mutex.h>
  19. #include <linux/slab.h>
  20. #include <linux/freezer.h>
  21. #include <linux/ptrace.h>
  22. #include <linux/uaccess.h>
  23. #include <linux/cgroup.h>
  24. #include <trace/events/sched.h>
  25. static DEFINE_SPINLOCK(kthread_create_lock);
  26. static LIST_HEAD(kthread_create_list);
  27. struct task_struct *kthreadd_task;
  28. struct kthread_create_info
  29. {
  30. /* Information passed to kthread() from kthreadd. */
  31. int (*threadfn)(void *data);
  32. void *data;
  33. int node;
  34. /* Result passed back to kthread_create() from kthreadd. */
  35. struct task_struct *result;
  36. struct completion *done;
  37. struct list_head list;
  38. };
  39. struct kthread {
  40. unsigned long flags;
  41. unsigned int cpu;
  42. void *data;
  43. struct completion parked;
  44. struct completion exited;
  45. };
  46. enum KTHREAD_BITS {
  47. KTHREAD_IS_PER_CPU = 0,
  48. KTHREAD_SHOULD_STOP,
  49. KTHREAD_SHOULD_PARK,
  50. KTHREAD_IS_PARKED,
  51. };
  52. static inline void set_kthread_struct(void *kthread)
  53. {
  54. /*
  55. * We abuse ->set_child_tid to avoid the new member and because it
  56. * can't be wrongly copied by copy_process(). We also rely on fact
  57. * that the caller can't exec, so PF_KTHREAD can't be cleared.
  58. */
  59. current->set_child_tid = (__force void __user *)kthread;
  60. }
  61. static inline struct kthread *to_kthread(struct task_struct *k)
  62. {
  63. WARN_ON(!(k->flags & PF_KTHREAD));
  64. return (__force void *)k->set_child_tid;
  65. }
  66. void free_kthread_struct(struct task_struct *k)
  67. {
  68. /*
  69. * Can be NULL if this kthread was created by kernel_thread()
  70. * or if kmalloc() in kthread() failed.
  71. */
  72. kfree(to_kthread(k));
  73. }
  74. /**
  75. * kthread_should_stop - should this kthread return now?
  76. *
  77. * When someone calls kthread_stop() on your kthread, it will be woken
  78. * and this will return true. You should then return, and your return
  79. * value will be passed through to kthread_stop().
  80. */
  81. bool kthread_should_stop(void)
  82. {
  83. return test_bit(KTHREAD_SHOULD_STOP, &to_kthread(current)->flags);
  84. }
  85. EXPORT_SYMBOL(kthread_should_stop);
  86. /**
  87. * kthread_should_park - should this kthread park now?
  88. *
  89. * When someone calls kthread_park() on your kthread, it will be woken
  90. * and this will return true. You should then do the necessary
  91. * cleanup and call kthread_parkme()
  92. *
  93. * Similar to kthread_should_stop(), but this keeps the thread alive
  94. * and in a park position. kthread_unpark() "restarts" the thread and
  95. * calls the thread function again.
  96. */
  97. bool kthread_should_park(void)
  98. {
  99. return test_bit(KTHREAD_SHOULD_PARK, &to_kthread(current)->flags);
  100. }
  101. EXPORT_SYMBOL_GPL(kthread_should_park);
  102. /**
  103. * kthread_freezable_should_stop - should this freezable kthread return now?
  104. * @was_frozen: optional out parameter, indicates whether %current was frozen
  105. *
  106. * kthread_should_stop() for freezable kthreads, which will enter
  107. * refrigerator if necessary. This function is safe from kthread_stop() /
  108. * freezer deadlock and freezable kthreads should use this function instead
  109. * of calling try_to_freeze() directly.
  110. */
  111. bool kthread_freezable_should_stop(bool *was_frozen)
  112. {
  113. bool frozen = false;
  114. might_sleep();
  115. if (unlikely(freezing(current)))
  116. frozen = __refrigerator(true);
  117. if (was_frozen)
  118. *was_frozen = frozen;
  119. return kthread_should_stop();
  120. }
  121. EXPORT_SYMBOL_GPL(kthread_freezable_should_stop);
  122. /**
  123. * kthread_data - return data value specified on kthread creation
  124. * @task: kthread task in question
  125. *
  126. * Return the data value specified when kthread @task was created.
  127. * The caller is responsible for ensuring the validity of @task when
  128. * calling this function.
  129. */
  130. void *kthread_data(struct task_struct *task)
  131. {
  132. return to_kthread(task)->data;
  133. }
  134. /**
  135. * kthread_probe_data - speculative version of kthread_data()
  136. * @task: possible kthread task in question
  137. *
  138. * @task could be a kthread task. Return the data value specified when it
  139. * was created if accessible. If @task isn't a kthread task or its data is
  140. * inaccessible for any reason, %NULL is returned. This function requires
  141. * that @task itself is safe to dereference.
  142. */
  143. void *kthread_probe_data(struct task_struct *task)
  144. {
  145. struct kthread *kthread = to_kthread(task);
  146. void *data = NULL;
  147. probe_kernel_read(&data, &kthread->data, sizeof(data));
  148. return data;
  149. }
  150. static void __kthread_parkme(struct kthread *self)
  151. {
  152. for (;;) {
  153. set_current_state(TASK_PARKED);
  154. if (!test_bit(KTHREAD_SHOULD_PARK, &self->flags))
  155. break;
  156. if (!test_and_set_bit(KTHREAD_IS_PARKED, &self->flags))
  157. complete(&self->parked);
  158. schedule();
  159. }
  160. clear_bit(KTHREAD_IS_PARKED, &self->flags);
  161. __set_current_state(TASK_RUNNING);
  162. }
  163. void kthread_parkme(void)
  164. {
  165. __kthread_parkme(to_kthread(current));
  166. }
  167. EXPORT_SYMBOL_GPL(kthread_parkme);
  168. static int kthread(void *_create)
  169. {
  170. /* Copy data: it's on kthread's stack */
  171. struct kthread_create_info *create = _create;
  172. int (*threadfn)(void *data) = create->threadfn;
  173. void *data = create->data;
  174. struct completion *done;
  175. struct kthread *self;
  176. int ret;
  177. self = kmalloc(sizeof(*self), GFP_KERNEL);
  178. set_kthread_struct(self);
  179. /* If user was SIGKILLed, I release the structure. */
  180. done = xchg(&create->done, NULL);
  181. if (!done) {
  182. kfree(create);
  183. do_exit(-EINTR);
  184. }
  185. if (!self) {
  186. create->result = ERR_PTR(-ENOMEM);
  187. complete(done);
  188. do_exit(-ENOMEM);
  189. }
  190. self->flags = 0;
  191. self->data = data;
  192. init_completion(&self->exited);
  193. init_completion(&self->parked);
  194. current->vfork_done = &self->exited;
  195. /* OK, tell user we're spawned, wait for stop or wakeup */
  196. __set_current_state(TASK_UNINTERRUPTIBLE);
  197. create->result = current;
  198. complete(done);
  199. schedule();
  200. ret = -EINTR;
  201. if (!test_bit(KTHREAD_SHOULD_STOP, &self->flags)) {
  202. cgroup_kthread_ready();
  203. __kthread_parkme(self);
  204. ret = threadfn(data);
  205. }
  206. do_exit(ret);
  207. }
  208. /* called from do_fork() to get node information for about to be created task */
  209. int tsk_fork_get_node(struct task_struct *tsk)
  210. {
  211. #ifdef CONFIG_NUMA
  212. if (tsk == kthreadd_task)
  213. return tsk->pref_node_fork;
  214. #endif
  215. return NUMA_NO_NODE;
  216. }
  217. static void create_kthread(struct kthread_create_info *create)
  218. {
  219. int pid;
  220. #ifdef CONFIG_NUMA
  221. current->pref_node_fork = create->node;
  222. #endif
  223. /* We want our own signal handler (we take no signals by default). */
  224. pid = kernel_thread(kthread, create, CLONE_FS | CLONE_FILES | SIGCHLD);
  225. if (pid < 0) {
  226. /* If user was SIGKILLed, I release the structure. */
  227. struct completion *done = xchg(&create->done, NULL);
  228. if (!done) {
  229. kfree(create);
  230. return;
  231. }
  232. create->result = ERR_PTR(pid);
  233. complete(done);
  234. }
  235. }
  236. static __printf(4, 0)
  237. struct task_struct *__kthread_create_on_node(int (*threadfn)(void *data),
  238. void *data, int node,
  239. const char namefmt[],
  240. va_list args)
  241. {
  242. DECLARE_COMPLETION_ONSTACK(done);
  243. struct task_struct *task;
  244. struct kthread_create_info *create = kmalloc(sizeof(*create),
  245. GFP_KERNEL);
  246. if (!create)
  247. return ERR_PTR(-ENOMEM);
  248. create->threadfn = threadfn;
  249. create->data = data;
  250. create->node = node;
  251. create->done = &done;
  252. spin_lock(&kthread_create_lock);
  253. list_add_tail(&create->list, &kthread_create_list);
  254. spin_unlock(&kthread_create_lock);
  255. wake_up_process(kthreadd_task);
  256. /*
  257. * Wait for completion in killable state, for I might be chosen by
  258. * the OOM killer while kthreadd is trying to allocate memory for
  259. * new kernel thread.
  260. */
  261. if (unlikely(wait_for_completion_killable(&done))) {
  262. /*
  263. * If I was SIGKILLed before kthreadd (or new kernel thread)
  264. * calls complete(), leave the cleanup of this structure to
  265. * that thread.
  266. */
  267. if (xchg(&create->done, NULL))
  268. return ERR_PTR(-EINTR);
  269. /*
  270. * kthreadd (or new kernel thread) will call complete()
  271. * shortly.
  272. */
  273. wait_for_completion(&done);
  274. }
  275. task = create->result;
  276. if (!IS_ERR(task)) {
  277. static const struct sched_param param = { .sched_priority = 0 };
  278. char name[TASK_COMM_LEN];
  279. /*
  280. * task is already visible to other tasks, so updating
  281. * COMM must be protected.
  282. */
  283. vsnprintf(name, sizeof(name), namefmt, args);
  284. set_task_comm(task, name);
  285. /*
  286. * root may have changed our (kthreadd's) priority or CPU mask.
  287. * The kernel thread should not inherit these properties.
  288. */
  289. sched_setscheduler_nocheck(task, SCHED_NORMAL, &param);
  290. set_cpus_allowed_ptr(task, cpu_all_mask);
  291. }
  292. kfree(create);
  293. return task;
  294. }
  295. /**
  296. * kthread_create_on_node - create a kthread.
  297. * @threadfn: the function to run until signal_pending(current).
  298. * @data: data ptr for @threadfn.
  299. * @node: task and thread structures for the thread are allocated on this node
  300. * @namefmt: printf-style name for the thread.
  301. *
  302. * Description: This helper function creates and names a kernel
  303. * thread. The thread will be stopped: use wake_up_process() to start
  304. * it. See also kthread_run(). The new thread has SCHED_NORMAL policy and
  305. * is affine to all CPUs.
  306. *
  307. * If thread is going to be bound on a particular cpu, give its node
  308. * in @node, to get NUMA affinity for kthread stack, or else give NUMA_NO_NODE.
  309. * When woken, the thread will run @threadfn() with @data as its
  310. * argument. @threadfn() can either call do_exit() directly if it is a
  311. * standalone thread for which no one will call kthread_stop(), or
  312. * return when 'kthread_should_stop()' is true (which means
  313. * kthread_stop() has been called). The return value should be zero
  314. * or a negative error number; it will be passed to kthread_stop().
  315. *
  316. * Returns a task_struct or ERR_PTR(-ENOMEM) or ERR_PTR(-EINTR).
  317. */
  318. struct task_struct *kthread_create_on_node(int (*threadfn)(void *data),
  319. void *data, int node,
  320. const char namefmt[],
  321. ...)
  322. {
  323. struct task_struct *task;
  324. va_list args;
  325. va_start(args, namefmt);
  326. task = __kthread_create_on_node(threadfn, data, node, namefmt, args);
  327. va_end(args);
  328. return task;
  329. }
  330. EXPORT_SYMBOL(kthread_create_on_node);
  331. static void __kthread_bind_mask(struct task_struct *p, const struct cpumask *mask, long state)
  332. {
  333. unsigned long flags;
  334. if (!wait_task_inactive(p, state)) {
  335. WARN_ON(1);
  336. return;
  337. }
  338. /* It's safe because the task is inactive. */
  339. raw_spin_lock_irqsave(&p->pi_lock, flags);
  340. do_set_cpus_allowed(p, mask);
  341. p->flags |= PF_NO_SETAFFINITY;
  342. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  343. }
  344. static void __kthread_bind(struct task_struct *p, unsigned int cpu, long state)
  345. {
  346. __kthread_bind_mask(p, cpumask_of(cpu), state);
  347. }
  348. void kthread_bind_mask(struct task_struct *p, const struct cpumask *mask)
  349. {
  350. __kthread_bind_mask(p, mask, TASK_UNINTERRUPTIBLE);
  351. }
  352. /**
  353. * kthread_bind - bind a just-created kthread to a cpu.
  354. * @p: thread created by kthread_create().
  355. * @cpu: cpu (might not be online, must be possible) for @k to run on.
  356. *
  357. * Description: This function is equivalent to set_cpus_allowed(),
  358. * except that @cpu doesn't need to be online, and the thread must be
  359. * stopped (i.e., just returned from kthread_create()).
  360. */
  361. void kthread_bind(struct task_struct *p, unsigned int cpu)
  362. {
  363. __kthread_bind(p, cpu, TASK_UNINTERRUPTIBLE);
  364. }
  365. EXPORT_SYMBOL(kthread_bind);
  366. /**
  367. * kthread_create_on_cpu - Create a cpu bound kthread
  368. * @threadfn: the function to run until signal_pending(current).
  369. * @data: data ptr for @threadfn.
  370. * @cpu: The cpu on which the thread should be bound,
  371. * @namefmt: printf-style name for the thread. Format is restricted
  372. * to "name.*%u". Code fills in cpu number.
  373. *
  374. * Description: This helper function creates and names a kernel thread
  375. * The thread will be woken and put into park mode.
  376. */
  377. struct task_struct *kthread_create_on_cpu(int (*threadfn)(void *data),
  378. void *data, unsigned int cpu,
  379. const char *namefmt)
  380. {
  381. struct task_struct *p;
  382. p = kthread_create_on_node(threadfn, data, cpu_to_node(cpu), namefmt,
  383. cpu);
  384. if (IS_ERR(p))
  385. return p;
  386. kthread_bind(p, cpu);
  387. /* CPU hotplug need to bind once again when unparking the thread. */
  388. to_kthread(p)->cpu = cpu;
  389. return p;
  390. }
  391. void kthread_set_per_cpu(struct task_struct *k, int cpu)
  392. {
  393. struct kthread *kthread = to_kthread(k);
  394. if (!kthread)
  395. return;
  396. WARN_ON_ONCE(!(k->flags & PF_NO_SETAFFINITY));
  397. if (cpu < 0) {
  398. clear_bit(KTHREAD_IS_PER_CPU, &kthread->flags);
  399. return;
  400. }
  401. kthread->cpu = cpu;
  402. set_bit(KTHREAD_IS_PER_CPU, &kthread->flags);
  403. }
  404. bool kthread_is_per_cpu(struct task_struct *k)
  405. {
  406. struct kthread *kthread = to_kthread(k);
  407. if (!kthread)
  408. return false;
  409. return test_bit(KTHREAD_IS_PER_CPU, &kthread->flags);
  410. }
  411. /**
  412. * kthread_unpark - unpark a thread created by kthread_create().
  413. * @k: thread created by kthread_create().
  414. *
  415. * Sets kthread_should_park() for @k to return false, wakes it, and
  416. * waits for it to return. If the thread is marked percpu then its
  417. * bound to the cpu again.
  418. */
  419. void kthread_unpark(struct task_struct *k)
  420. {
  421. struct kthread *kthread = to_kthread(k);
  422. clear_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
  423. /*
  424. * We clear the IS_PARKED bit here as we don't wait
  425. * until the task has left the park code. So if we'd
  426. * park before that happens we'd see the IS_PARKED bit
  427. * which might be about to be cleared.
  428. */
  429. if (test_and_clear_bit(KTHREAD_IS_PARKED, &kthread->flags)) {
  430. /*
  431. * Newly created kthread was parked when the CPU was offline.
  432. * The binding was lost and we need to set it again.
  433. */
  434. if (test_bit(KTHREAD_IS_PER_CPU, &kthread->flags))
  435. __kthread_bind(k, kthread->cpu, TASK_PARKED);
  436. wake_up_state(k, TASK_PARKED);
  437. }
  438. }
  439. EXPORT_SYMBOL_GPL(kthread_unpark);
  440. /**
  441. * kthread_park - park a thread created by kthread_create().
  442. * @k: thread created by kthread_create().
  443. *
  444. * Sets kthread_should_park() for @k to return true, wakes it, and
  445. * waits for it to return. This can also be called after kthread_create()
  446. * instead of calling wake_up_process(): the thread will park without
  447. * calling threadfn().
  448. *
  449. * Returns 0 if the thread is parked, -ENOSYS if the thread exited.
  450. * If called by the kthread itself just the park bit is set.
  451. */
  452. int kthread_park(struct task_struct *k)
  453. {
  454. struct kthread *kthread = to_kthread(k);
  455. if (WARN_ON(k->flags & PF_EXITING))
  456. return -ENOSYS;
  457. if (!test_bit(KTHREAD_IS_PARKED, &kthread->flags)) {
  458. set_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
  459. if (k != current) {
  460. wake_up_process(k);
  461. wait_for_completion(&kthread->parked);
  462. }
  463. }
  464. return 0;
  465. }
  466. EXPORT_SYMBOL_GPL(kthread_park);
  467. /**
  468. * kthread_stop - stop a thread created by kthread_create().
  469. * @k: thread created by kthread_create().
  470. *
  471. * Sets kthread_should_stop() for @k to return true, wakes it, and
  472. * waits for it to exit. This can also be called after kthread_create()
  473. * instead of calling wake_up_process(): the thread will exit without
  474. * calling threadfn().
  475. *
  476. * If threadfn() may call do_exit() itself, the caller must ensure
  477. * task_struct can't go away.
  478. *
  479. * Returns the result of threadfn(), or %-EINTR if wake_up_process()
  480. * was never called.
  481. */
  482. int kthread_stop(struct task_struct *k)
  483. {
  484. struct kthread *kthread;
  485. int ret;
  486. trace_sched_kthread_stop(k);
  487. get_task_struct(k);
  488. kthread = to_kthread(k);
  489. set_bit(KTHREAD_SHOULD_STOP, &kthread->flags);
  490. kthread_unpark(k);
  491. wake_up_process(k);
  492. wait_for_completion(&kthread->exited);
  493. ret = k->exit_code;
  494. put_task_struct(k);
  495. trace_sched_kthread_stop_ret(ret);
  496. return ret;
  497. }
  498. EXPORT_SYMBOL(kthread_stop);
  499. int kthreadd(void *unused)
  500. {
  501. struct task_struct *tsk = current;
  502. /* Setup a clean context for our children to inherit. */
  503. set_task_comm(tsk, "kthreadd");
  504. ignore_signals(tsk);
  505. set_cpus_allowed_ptr(tsk, cpu_all_mask);
  506. set_mems_allowed(node_states[N_MEMORY]);
  507. current->flags |= PF_NOFREEZE;
  508. cgroup_init_kthreadd();
  509. for (;;) {
  510. set_current_state(TASK_INTERRUPTIBLE);
  511. if (list_empty(&kthread_create_list))
  512. schedule();
  513. __set_current_state(TASK_RUNNING);
  514. spin_lock(&kthread_create_lock);
  515. while (!list_empty(&kthread_create_list)) {
  516. struct kthread_create_info *create;
  517. create = list_entry(kthread_create_list.next,
  518. struct kthread_create_info, list);
  519. list_del_init(&create->list);
  520. spin_unlock(&kthread_create_lock);
  521. create_kthread(create);
  522. spin_lock(&kthread_create_lock);
  523. }
  524. spin_unlock(&kthread_create_lock);
  525. }
  526. return 0;
  527. }
  528. void __kthread_init_worker(struct kthread_worker *worker,
  529. const char *name,
  530. struct lock_class_key *key)
  531. {
  532. memset(worker, 0, sizeof(struct kthread_worker));
  533. spin_lock_init(&worker->lock);
  534. lockdep_set_class_and_name(&worker->lock, key, name);
  535. INIT_LIST_HEAD(&worker->work_list);
  536. INIT_LIST_HEAD(&worker->delayed_work_list);
  537. }
  538. EXPORT_SYMBOL_GPL(__kthread_init_worker);
  539. /**
  540. * kthread_worker_fn - kthread function to process kthread_worker
  541. * @worker_ptr: pointer to initialized kthread_worker
  542. *
  543. * This function implements the main cycle of kthread worker. It processes
  544. * work_list until it is stopped with kthread_stop(). It sleeps when the queue
  545. * is empty.
  546. *
  547. * The works are not allowed to keep any locks, disable preemption or interrupts
  548. * when they finish. There is defined a safe point for freezing when one work
  549. * finishes and before a new one is started.
  550. *
  551. * Also the works must not be handled by more than one worker at the same time,
  552. * see also kthread_queue_work().
  553. */
  554. int kthread_worker_fn(void *worker_ptr)
  555. {
  556. struct kthread_worker *worker = worker_ptr;
  557. struct kthread_work *work;
  558. /*
  559. * FIXME: Update the check and remove the assignment when all kthread
  560. * worker users are created using kthread_create_worker*() functions.
  561. */
  562. WARN_ON(worker->task && worker->task != current);
  563. worker->task = current;
  564. if (worker->flags & KTW_FREEZABLE)
  565. set_freezable();
  566. repeat:
  567. set_current_state(TASK_INTERRUPTIBLE); /* mb paired w/ kthread_stop */
  568. if (kthread_should_stop()) {
  569. __set_current_state(TASK_RUNNING);
  570. spin_lock_irq(&worker->lock);
  571. worker->task = NULL;
  572. spin_unlock_irq(&worker->lock);
  573. return 0;
  574. }
  575. work = NULL;
  576. spin_lock_irq(&worker->lock);
  577. if (!list_empty(&worker->work_list)) {
  578. work = list_first_entry(&worker->work_list,
  579. struct kthread_work, node);
  580. list_del_init(&work->node);
  581. }
  582. worker->current_work = work;
  583. spin_unlock_irq(&worker->lock);
  584. if (work) {
  585. __set_current_state(TASK_RUNNING);
  586. work->func(work);
  587. } else if (!freezing(current))
  588. schedule();
  589. try_to_freeze();
  590. cond_resched();
  591. goto repeat;
  592. }
  593. EXPORT_SYMBOL_GPL(kthread_worker_fn);
  594. static __printf(3, 0) struct kthread_worker *
  595. __kthread_create_worker(int cpu, unsigned int flags,
  596. const char namefmt[], va_list args)
  597. {
  598. struct kthread_worker *worker;
  599. struct task_struct *task;
  600. int node = -1;
  601. worker = kzalloc(sizeof(*worker), GFP_KERNEL);
  602. if (!worker)
  603. return ERR_PTR(-ENOMEM);
  604. kthread_init_worker(worker);
  605. if (cpu >= 0)
  606. node = cpu_to_node(cpu);
  607. task = __kthread_create_on_node(kthread_worker_fn, worker,
  608. node, namefmt, args);
  609. if (IS_ERR(task))
  610. goto fail_task;
  611. if (cpu >= 0)
  612. kthread_bind(task, cpu);
  613. worker->flags = flags;
  614. worker->task = task;
  615. wake_up_process(task);
  616. return worker;
  617. fail_task:
  618. kfree(worker);
  619. return ERR_CAST(task);
  620. }
  621. /**
  622. * kthread_create_worker - create a kthread worker
  623. * @flags: flags modifying the default behavior of the worker
  624. * @namefmt: printf-style name for the kthread worker (task).
  625. *
  626. * Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
  627. * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
  628. * when the worker was SIGKILLed.
  629. */
  630. struct kthread_worker *
  631. kthread_create_worker(unsigned int flags, const char namefmt[], ...)
  632. {
  633. struct kthread_worker *worker;
  634. va_list args;
  635. va_start(args, namefmt);
  636. worker = __kthread_create_worker(-1, flags, namefmt, args);
  637. va_end(args);
  638. return worker;
  639. }
  640. EXPORT_SYMBOL(kthread_create_worker);
  641. /**
  642. * kthread_create_worker_on_cpu - create a kthread worker and bind it
  643. * it to a given CPU and the associated NUMA node.
  644. * @cpu: CPU number
  645. * @flags: flags modifying the default behavior of the worker
  646. * @namefmt: printf-style name for the kthread worker (task).
  647. *
  648. * Use a valid CPU number if you want to bind the kthread worker
  649. * to the given CPU and the associated NUMA node.
  650. *
  651. * A good practice is to add the cpu number also into the worker name.
  652. * For example, use kthread_create_worker_on_cpu(cpu, "helper/%d", cpu).
  653. *
  654. * Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
  655. * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
  656. * when the worker was SIGKILLed.
  657. */
  658. struct kthread_worker *
  659. kthread_create_worker_on_cpu(int cpu, unsigned int flags,
  660. const char namefmt[], ...)
  661. {
  662. struct kthread_worker *worker;
  663. va_list args;
  664. va_start(args, namefmt);
  665. worker = __kthread_create_worker(cpu, flags, namefmt, args);
  666. va_end(args);
  667. return worker;
  668. }
  669. EXPORT_SYMBOL(kthread_create_worker_on_cpu);
  670. /*
  671. * Returns true when the work could not be queued at the moment.
  672. * It happens when it is already pending in a worker list
  673. * or when it is being cancelled.
  674. */
  675. static inline bool queuing_blocked(struct kthread_worker *worker,
  676. struct kthread_work *work)
  677. {
  678. lockdep_assert_held(&worker->lock);
  679. return !list_empty(&work->node) || work->canceling;
  680. }
  681. static void kthread_insert_work_sanity_check(struct kthread_worker *worker,
  682. struct kthread_work *work)
  683. {
  684. lockdep_assert_held(&worker->lock);
  685. WARN_ON_ONCE(!list_empty(&work->node));
  686. /* Do not use a work with >1 worker, see kthread_queue_work() */
  687. WARN_ON_ONCE(work->worker && work->worker != worker);
  688. }
  689. /* insert @work before @pos in @worker */
  690. static void kthread_insert_work(struct kthread_worker *worker,
  691. struct kthread_work *work,
  692. struct list_head *pos)
  693. {
  694. kthread_insert_work_sanity_check(worker, work);
  695. list_add_tail(&work->node, pos);
  696. work->worker = worker;
  697. if (!worker->current_work && likely(worker->task))
  698. wake_up_process(worker->task);
  699. }
  700. /**
  701. * kthread_queue_work - queue a kthread_work
  702. * @worker: target kthread_worker
  703. * @work: kthread_work to queue
  704. *
  705. * Queue @work to work processor @task for async execution. @task
  706. * must have been created with kthread_worker_create(). Returns %true
  707. * if @work was successfully queued, %false if it was already pending.
  708. *
  709. * Reinitialize the work if it needs to be used by another worker.
  710. * For example, when the worker was stopped and started again.
  711. */
  712. bool kthread_queue_work(struct kthread_worker *worker,
  713. struct kthread_work *work)
  714. {
  715. bool ret = false;
  716. unsigned long flags;
  717. spin_lock_irqsave(&worker->lock, flags);
  718. if (!queuing_blocked(worker, work)) {
  719. kthread_insert_work(worker, work, &worker->work_list);
  720. ret = true;
  721. }
  722. spin_unlock_irqrestore(&worker->lock, flags);
  723. return ret;
  724. }
  725. EXPORT_SYMBOL_GPL(kthread_queue_work);
  726. /**
  727. * kthread_delayed_work_timer_fn - callback that queues the associated kthread
  728. * delayed work when the timer expires.
  729. * @__data: pointer to the data associated with the timer
  730. *
  731. * The format of the function is defined by struct timer_list.
  732. * It should have been called from irqsafe timer with irq already off.
  733. */
  734. void kthread_delayed_work_timer_fn(unsigned long __data)
  735. {
  736. struct kthread_delayed_work *dwork =
  737. (struct kthread_delayed_work *)__data;
  738. struct kthread_work *work = &dwork->work;
  739. struct kthread_worker *worker = work->worker;
  740. /*
  741. * This might happen when a pending work is reinitialized.
  742. * It means that it is used a wrong way.
  743. */
  744. if (WARN_ON_ONCE(!worker))
  745. return;
  746. spin_lock(&worker->lock);
  747. /* Work must not be used with >1 worker, see kthread_queue_work(). */
  748. WARN_ON_ONCE(work->worker != worker);
  749. /* Move the work from worker->delayed_work_list. */
  750. WARN_ON_ONCE(list_empty(&work->node));
  751. list_del_init(&work->node);
  752. if (!work->canceling)
  753. kthread_insert_work(worker, work, &worker->work_list);
  754. spin_unlock(&worker->lock);
  755. }
  756. EXPORT_SYMBOL(kthread_delayed_work_timer_fn);
  757. void __kthread_queue_delayed_work(struct kthread_worker *worker,
  758. struct kthread_delayed_work *dwork,
  759. unsigned long delay)
  760. {
  761. struct timer_list *timer = &dwork->timer;
  762. struct kthread_work *work = &dwork->work;
  763. WARN_ON_ONCE(timer->function != kthread_delayed_work_timer_fn ||
  764. timer->data != (unsigned long)dwork);
  765. /*
  766. * If @delay is 0, queue @dwork->work immediately. This is for
  767. * both optimization and correctness. The earliest @timer can
  768. * expire is on the closest next tick and delayed_work users depend
  769. * on that there's no such delay when @delay is 0.
  770. */
  771. if (!delay) {
  772. kthread_insert_work(worker, work, &worker->work_list);
  773. return;
  774. }
  775. /* Be paranoid and try to detect possible races already now. */
  776. kthread_insert_work_sanity_check(worker, work);
  777. list_add(&work->node, &worker->delayed_work_list);
  778. work->worker = worker;
  779. timer->expires = jiffies + delay;
  780. add_timer(timer);
  781. }
  782. /**
  783. * kthread_queue_delayed_work - queue the associated kthread work
  784. * after a delay.
  785. * @worker: target kthread_worker
  786. * @dwork: kthread_delayed_work to queue
  787. * @delay: number of jiffies to wait before queuing
  788. *
  789. * If the work has not been pending it starts a timer that will queue
  790. * the work after the given @delay. If @delay is zero, it queues the
  791. * work immediately.
  792. *
  793. * Return: %false if the @work has already been pending. It means that
  794. * either the timer was running or the work was queued. It returns %true
  795. * otherwise.
  796. */
  797. bool kthread_queue_delayed_work(struct kthread_worker *worker,
  798. struct kthread_delayed_work *dwork,
  799. unsigned long delay)
  800. {
  801. struct kthread_work *work = &dwork->work;
  802. unsigned long flags;
  803. bool ret = false;
  804. spin_lock_irqsave(&worker->lock, flags);
  805. if (!queuing_blocked(worker, work)) {
  806. __kthread_queue_delayed_work(worker, dwork, delay);
  807. ret = true;
  808. }
  809. spin_unlock_irqrestore(&worker->lock, flags);
  810. return ret;
  811. }
  812. EXPORT_SYMBOL_GPL(kthread_queue_delayed_work);
  813. struct kthread_flush_work {
  814. struct kthread_work work;
  815. struct completion done;
  816. };
  817. static void kthread_flush_work_fn(struct kthread_work *work)
  818. {
  819. struct kthread_flush_work *fwork =
  820. container_of(work, struct kthread_flush_work, work);
  821. complete(&fwork->done);
  822. }
  823. /**
  824. * kthread_flush_work - flush a kthread_work
  825. * @work: work to flush
  826. *
  827. * If @work is queued or executing, wait for it to finish execution.
  828. */
  829. void kthread_flush_work(struct kthread_work *work)
  830. {
  831. struct kthread_flush_work fwork = {
  832. KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
  833. COMPLETION_INITIALIZER_ONSTACK(fwork.done),
  834. };
  835. struct kthread_worker *worker;
  836. bool noop = false;
  837. worker = work->worker;
  838. if (!worker)
  839. return;
  840. spin_lock_irq(&worker->lock);
  841. /* Work must not be used with >1 worker, see kthread_queue_work(). */
  842. WARN_ON_ONCE(work->worker != worker);
  843. if (!list_empty(&work->node))
  844. kthread_insert_work(worker, &fwork.work, work->node.next);
  845. else if (worker->current_work == work)
  846. kthread_insert_work(worker, &fwork.work,
  847. worker->work_list.next);
  848. else
  849. noop = true;
  850. spin_unlock_irq(&worker->lock);
  851. if (!noop)
  852. wait_for_completion(&fwork.done);
  853. }
  854. EXPORT_SYMBOL_GPL(kthread_flush_work);
  855. /*
  856. * Make sure that the timer is neither set nor running and could
  857. * not manipulate the work list_head any longer.
  858. *
  859. * The function is called under worker->lock. The lock is temporary
  860. * released but the timer can't be set again in the meantime.
  861. */
  862. static void kthread_cancel_delayed_work_timer(struct kthread_work *work,
  863. unsigned long *flags)
  864. {
  865. struct kthread_delayed_work *dwork =
  866. container_of(work, struct kthread_delayed_work, work);
  867. struct kthread_worker *worker = work->worker;
  868. /*
  869. * del_timer_sync() must be called to make sure that the timer
  870. * callback is not running. The lock must be temporary released
  871. * to avoid a deadlock with the callback. In the meantime,
  872. * any queuing is blocked by setting the canceling counter.
  873. */
  874. work->canceling++;
  875. spin_unlock_irqrestore(&worker->lock, *flags);
  876. del_timer_sync(&dwork->timer);
  877. spin_lock_irqsave(&worker->lock, *flags);
  878. work->canceling--;
  879. }
  880. /*
  881. * This function removes the work from the worker queue.
  882. *
  883. * It is called under worker->lock. The caller must make sure that
  884. * the timer used by delayed work is not running, e.g. by calling
  885. * kthread_cancel_delayed_work_timer().
  886. *
  887. * The work might still be in use when this function finishes. See the
  888. * current_work proceed by the worker.
  889. *
  890. * Return: %true if @work was pending and successfully canceled,
  891. * %false if @work was not pending
  892. */
  893. static bool __kthread_cancel_work(struct kthread_work *work)
  894. {
  895. /*
  896. * Try to remove the work from a worker list. It might either
  897. * be from worker->work_list or from worker->delayed_work_list.
  898. */
  899. if (!list_empty(&work->node)) {
  900. list_del_init(&work->node);
  901. return true;
  902. }
  903. return false;
  904. }
  905. /**
  906. * kthread_mod_delayed_work - modify delay of or queue a kthread delayed work
  907. * @worker: kthread worker to use
  908. * @dwork: kthread delayed work to queue
  909. * @delay: number of jiffies to wait before queuing
  910. *
  911. * If @dwork is idle, equivalent to kthread_queue_delayed_work(). Otherwise,
  912. * modify @dwork's timer so that it expires after @delay. If @delay is zero,
  913. * @work is guaranteed to be queued immediately.
  914. *
  915. * Return: %true if @dwork was pending and its timer was modified,
  916. * %false otherwise.
  917. *
  918. * A special case is when the work is being canceled in parallel.
  919. * It might be caused either by the real kthread_cancel_delayed_work_sync()
  920. * or yet another kthread_mod_delayed_work() call. We let the other command
  921. * win and return %false here. The caller is supposed to synchronize these
  922. * operations a reasonable way.
  923. *
  924. * This function is safe to call from any context including IRQ handler.
  925. * See __kthread_cancel_work() and kthread_delayed_work_timer_fn()
  926. * for details.
  927. */
  928. bool kthread_mod_delayed_work(struct kthread_worker *worker,
  929. struct kthread_delayed_work *dwork,
  930. unsigned long delay)
  931. {
  932. struct kthread_work *work = &dwork->work;
  933. unsigned long flags;
  934. int ret = false;
  935. spin_lock_irqsave(&worker->lock, flags);
  936. /* Do not bother with canceling when never queued. */
  937. if (!work->worker)
  938. goto fast_queue;
  939. /* Work must not be used with >1 worker, see kthread_queue_work() */
  940. WARN_ON_ONCE(work->worker != worker);
  941. /*
  942. * Temporary cancel the work but do not fight with another command
  943. * that is canceling the work as well.
  944. *
  945. * It is a bit tricky because of possible races with another
  946. * mod_delayed_work() and cancel_delayed_work() callers.
  947. *
  948. * The timer must be canceled first because worker->lock is released
  949. * when doing so. But the work can be removed from the queue (list)
  950. * only when it can be queued again so that the return value can
  951. * be used for reference counting.
  952. */
  953. kthread_cancel_delayed_work_timer(work, &flags);
  954. if (work->canceling)
  955. goto out;
  956. ret = __kthread_cancel_work(work);
  957. fast_queue:
  958. __kthread_queue_delayed_work(worker, dwork, delay);
  959. out:
  960. spin_unlock_irqrestore(&worker->lock, flags);
  961. return ret;
  962. }
  963. EXPORT_SYMBOL_GPL(kthread_mod_delayed_work);
  964. static bool __kthread_cancel_work_sync(struct kthread_work *work, bool is_dwork)
  965. {
  966. struct kthread_worker *worker = work->worker;
  967. unsigned long flags;
  968. int ret = false;
  969. if (!worker)
  970. goto out;
  971. spin_lock_irqsave(&worker->lock, flags);
  972. /* Work must not be used with >1 worker, see kthread_queue_work(). */
  973. WARN_ON_ONCE(work->worker != worker);
  974. if (is_dwork)
  975. kthread_cancel_delayed_work_timer(work, &flags);
  976. ret = __kthread_cancel_work(work);
  977. if (worker->current_work != work)
  978. goto out_fast;
  979. /*
  980. * The work is in progress and we need to wait with the lock released.
  981. * In the meantime, block any queuing by setting the canceling counter.
  982. */
  983. work->canceling++;
  984. spin_unlock_irqrestore(&worker->lock, flags);
  985. kthread_flush_work(work);
  986. spin_lock_irqsave(&worker->lock, flags);
  987. work->canceling--;
  988. out_fast:
  989. spin_unlock_irqrestore(&worker->lock, flags);
  990. out:
  991. return ret;
  992. }
  993. /**
  994. * kthread_cancel_work_sync - cancel a kthread work and wait for it to finish
  995. * @work: the kthread work to cancel
  996. *
  997. * Cancel @work and wait for its execution to finish. This function
  998. * can be used even if the work re-queues itself. On return from this
  999. * function, @work is guaranteed to be not pending or executing on any CPU.
  1000. *
  1001. * kthread_cancel_work_sync(&delayed_work->work) must not be used for
  1002. * delayed_work's. Use kthread_cancel_delayed_work_sync() instead.
  1003. *
  1004. * The caller must ensure that the worker on which @work was last
  1005. * queued can't be destroyed before this function returns.
  1006. *
  1007. * Return: %true if @work was pending, %false otherwise.
  1008. */
  1009. bool kthread_cancel_work_sync(struct kthread_work *work)
  1010. {
  1011. return __kthread_cancel_work_sync(work, false);
  1012. }
  1013. EXPORT_SYMBOL_GPL(kthread_cancel_work_sync);
  1014. /**
  1015. * kthread_cancel_delayed_work_sync - cancel a kthread delayed work and
  1016. * wait for it to finish.
  1017. * @dwork: the kthread delayed work to cancel
  1018. *
  1019. * This is kthread_cancel_work_sync() for delayed works.
  1020. *
  1021. * Return: %true if @dwork was pending, %false otherwise.
  1022. */
  1023. bool kthread_cancel_delayed_work_sync(struct kthread_delayed_work *dwork)
  1024. {
  1025. return __kthread_cancel_work_sync(&dwork->work, true);
  1026. }
  1027. EXPORT_SYMBOL_GPL(kthread_cancel_delayed_work_sync);
  1028. /**
  1029. * kthread_flush_worker - flush all current works on a kthread_worker
  1030. * @worker: worker to flush
  1031. *
  1032. * Wait until all currently executing or pending works on @worker are
  1033. * finished.
  1034. */
  1035. void kthread_flush_worker(struct kthread_worker *worker)
  1036. {
  1037. struct kthread_flush_work fwork = {
  1038. KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
  1039. COMPLETION_INITIALIZER_ONSTACK(fwork.done),
  1040. };
  1041. kthread_queue_work(worker, &fwork.work);
  1042. wait_for_completion(&fwork.done);
  1043. }
  1044. EXPORT_SYMBOL_GPL(kthread_flush_worker);
  1045. /**
  1046. * kthread_destroy_worker - destroy a kthread worker
  1047. * @worker: worker to be destroyed
  1048. *
  1049. * Flush and destroy @worker. The simple flush is enough because the kthread
  1050. * worker API is used only in trivial scenarios. There are no multi-step state
  1051. * machines needed.
  1052. */
  1053. void kthread_destroy_worker(struct kthread_worker *worker)
  1054. {
  1055. struct task_struct *task;
  1056. task = worker->task;
  1057. if (WARN_ON(!task))
  1058. return;
  1059. kthread_flush_worker(worker);
  1060. kthread_stop(task);
  1061. WARN_ON(!list_empty(&worker->work_list));
  1062. kfree(worker);
  1063. }
  1064. EXPORT_SYMBOL(kthread_destroy_worker);