kthread.c 32 KB

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