kthread.c 32 KB

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