kthread.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  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. goto repeat;
  565. }
  566. EXPORT_SYMBOL_GPL(kthread_worker_fn);
  567. static __printf(3, 0) struct kthread_worker *
  568. __kthread_create_worker(int cpu, unsigned int flags,
  569. const char namefmt[], va_list args)
  570. {
  571. struct kthread_worker *worker;
  572. struct task_struct *task;
  573. int node = -1;
  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. node = cpu_to_node(cpu);
  580. task = __kthread_create_on_node(kthread_worker_fn, worker,
  581. node, namefmt, args);
  582. if (IS_ERR(task))
  583. goto fail_task;
  584. if (cpu >= 0)
  585. kthread_bind(task, cpu);
  586. worker->flags = flags;
  587. worker->task = task;
  588. wake_up_process(task);
  589. return worker;
  590. fail_task:
  591. kfree(worker);
  592. return ERR_CAST(task);
  593. }
  594. /**
  595. * kthread_create_worker - create a kthread worker
  596. * @flags: flags modifying the default behavior of the worker
  597. * @namefmt: printf-style name for the kthread worker (task).
  598. *
  599. * Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
  600. * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
  601. * when the worker was SIGKILLed.
  602. */
  603. struct kthread_worker *
  604. kthread_create_worker(unsigned int flags, const char namefmt[], ...)
  605. {
  606. struct kthread_worker *worker;
  607. va_list args;
  608. va_start(args, namefmt);
  609. worker = __kthread_create_worker(-1, flags, namefmt, args);
  610. va_end(args);
  611. return worker;
  612. }
  613. EXPORT_SYMBOL(kthread_create_worker);
  614. /**
  615. * kthread_create_worker_on_cpu - create a kthread worker and bind it
  616. * it to a given CPU and the associated NUMA node.
  617. * @cpu: CPU number
  618. * @flags: flags modifying the default behavior of the worker
  619. * @namefmt: printf-style name for the kthread worker (task).
  620. *
  621. * Use a valid CPU number if you want to bind the kthread worker
  622. * to the given CPU and the associated NUMA node.
  623. *
  624. * A good practice is to add the cpu number also into the worker name.
  625. * For example, use kthread_create_worker_on_cpu(cpu, "helper/%d", cpu).
  626. *
  627. * Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
  628. * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
  629. * when the worker was SIGKILLed.
  630. */
  631. struct kthread_worker *
  632. kthread_create_worker_on_cpu(int cpu, unsigned int flags,
  633. const char namefmt[], ...)
  634. {
  635. struct kthread_worker *worker;
  636. va_list args;
  637. va_start(args, namefmt);
  638. worker = __kthread_create_worker(cpu, flags, namefmt, args);
  639. va_end(args);
  640. return worker;
  641. }
  642. EXPORT_SYMBOL(kthread_create_worker_on_cpu);
  643. /*
  644. * Returns true when the work could not be queued at the moment.
  645. * It happens when it is already pending in a worker list
  646. * or when it is being cancelled.
  647. */
  648. static inline bool queuing_blocked(struct kthread_worker *worker,
  649. struct kthread_work *work)
  650. {
  651. lockdep_assert_held(&worker->lock);
  652. return !list_empty(&work->node) || work->canceling;
  653. }
  654. static void kthread_insert_work_sanity_check(struct kthread_worker *worker,
  655. struct kthread_work *work)
  656. {
  657. lockdep_assert_held(&worker->lock);
  658. WARN_ON_ONCE(!list_empty(&work->node));
  659. /* Do not use a work with >1 worker, see kthread_queue_work() */
  660. WARN_ON_ONCE(work->worker && work->worker != worker);
  661. }
  662. /* insert @work before @pos in @worker */
  663. static void kthread_insert_work(struct kthread_worker *worker,
  664. struct kthread_work *work,
  665. struct list_head *pos)
  666. {
  667. kthread_insert_work_sanity_check(worker, work);
  668. list_add_tail(&work->node, pos);
  669. work->worker = worker;
  670. if (!worker->current_work && likely(worker->task))
  671. wake_up_process(worker->task);
  672. }
  673. /**
  674. * kthread_queue_work - queue a kthread_work
  675. * @worker: target kthread_worker
  676. * @work: kthread_work to queue
  677. *
  678. * Queue @work to work processor @task for async execution. @task
  679. * must have been created with kthread_worker_create(). Returns %true
  680. * if @work was successfully queued, %false if it was already pending.
  681. *
  682. * Reinitialize the work if it needs to be used by another worker.
  683. * For example, when the worker was stopped and started again.
  684. */
  685. bool kthread_queue_work(struct kthread_worker *worker,
  686. struct kthread_work *work)
  687. {
  688. bool ret = false;
  689. unsigned long flags;
  690. spin_lock_irqsave(&worker->lock, flags);
  691. if (!queuing_blocked(worker, work)) {
  692. kthread_insert_work(worker, work, &worker->work_list);
  693. ret = true;
  694. }
  695. spin_unlock_irqrestore(&worker->lock, flags);
  696. return ret;
  697. }
  698. EXPORT_SYMBOL_GPL(kthread_queue_work);
  699. /**
  700. * kthread_delayed_work_timer_fn - callback that queues the associated kthread
  701. * delayed work when the timer expires.
  702. * @__data: pointer to the data associated with the timer
  703. *
  704. * The format of the function is defined by struct timer_list.
  705. * It should have been called from irqsafe timer with irq already off.
  706. */
  707. void kthread_delayed_work_timer_fn(unsigned long __data)
  708. {
  709. struct kthread_delayed_work *dwork =
  710. (struct kthread_delayed_work *)__data;
  711. struct kthread_work *work = &dwork->work;
  712. struct kthread_worker *worker = work->worker;
  713. /*
  714. * This might happen when a pending work is reinitialized.
  715. * It means that it is used a wrong way.
  716. */
  717. if (WARN_ON_ONCE(!worker))
  718. return;
  719. spin_lock(&worker->lock);
  720. /* Work must not be used with >1 worker, see kthread_queue_work(). */
  721. WARN_ON_ONCE(work->worker != worker);
  722. /* Move the work from worker->delayed_work_list. */
  723. WARN_ON_ONCE(list_empty(&work->node));
  724. list_del_init(&work->node);
  725. kthread_insert_work(worker, work, &worker->work_list);
  726. spin_unlock(&worker->lock);
  727. }
  728. EXPORT_SYMBOL(kthread_delayed_work_timer_fn);
  729. void __kthread_queue_delayed_work(struct kthread_worker *worker,
  730. struct kthread_delayed_work *dwork,
  731. unsigned long delay)
  732. {
  733. struct timer_list *timer = &dwork->timer;
  734. struct kthread_work *work = &dwork->work;
  735. WARN_ON_ONCE(timer->function != kthread_delayed_work_timer_fn ||
  736. timer->data != (unsigned long)dwork);
  737. /*
  738. * If @delay is 0, queue @dwork->work immediately. This is for
  739. * both optimization and correctness. The earliest @timer can
  740. * expire is on the closest next tick and delayed_work users depend
  741. * on that there's no such delay when @delay is 0.
  742. */
  743. if (!delay) {
  744. kthread_insert_work(worker, work, &worker->work_list);
  745. return;
  746. }
  747. /* Be paranoid and try to detect possible races already now. */
  748. kthread_insert_work_sanity_check(worker, work);
  749. list_add(&work->node, &worker->delayed_work_list);
  750. work->worker = worker;
  751. timer->expires = jiffies + delay;
  752. add_timer(timer);
  753. }
  754. /**
  755. * kthread_queue_delayed_work - queue the associated kthread work
  756. * after a delay.
  757. * @worker: target kthread_worker
  758. * @dwork: kthread_delayed_work to queue
  759. * @delay: number of jiffies to wait before queuing
  760. *
  761. * If the work has not been pending it starts a timer that will queue
  762. * the work after the given @delay. If @delay is zero, it queues the
  763. * work immediately.
  764. *
  765. * Return: %false if the @work has already been pending. It means that
  766. * either the timer was running or the work was queued. It returns %true
  767. * otherwise.
  768. */
  769. bool kthread_queue_delayed_work(struct kthread_worker *worker,
  770. struct kthread_delayed_work *dwork,
  771. unsigned long delay)
  772. {
  773. struct kthread_work *work = &dwork->work;
  774. unsigned long flags;
  775. bool ret = false;
  776. spin_lock_irqsave(&worker->lock, flags);
  777. if (!queuing_blocked(worker, work)) {
  778. __kthread_queue_delayed_work(worker, dwork, delay);
  779. ret = true;
  780. }
  781. spin_unlock_irqrestore(&worker->lock, flags);
  782. return ret;
  783. }
  784. EXPORT_SYMBOL_GPL(kthread_queue_delayed_work);
  785. struct kthread_flush_work {
  786. struct kthread_work work;
  787. struct completion done;
  788. };
  789. static void kthread_flush_work_fn(struct kthread_work *work)
  790. {
  791. struct kthread_flush_work *fwork =
  792. container_of(work, struct kthread_flush_work, work);
  793. complete(&fwork->done);
  794. }
  795. /**
  796. * kthread_flush_work - flush a kthread_work
  797. * @work: work to flush
  798. *
  799. * If @work is queued or executing, wait for it to finish execution.
  800. */
  801. void kthread_flush_work(struct kthread_work *work)
  802. {
  803. struct kthread_flush_work fwork = {
  804. KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
  805. COMPLETION_INITIALIZER_ONSTACK(fwork.done),
  806. };
  807. struct kthread_worker *worker;
  808. bool noop = false;
  809. worker = work->worker;
  810. if (!worker)
  811. return;
  812. spin_lock_irq(&worker->lock);
  813. /* Work must not be used with >1 worker, see kthread_queue_work(). */
  814. WARN_ON_ONCE(work->worker != worker);
  815. if (!list_empty(&work->node))
  816. kthread_insert_work(worker, &fwork.work, work->node.next);
  817. else if (worker->current_work == work)
  818. kthread_insert_work(worker, &fwork.work,
  819. worker->work_list.next);
  820. else
  821. noop = true;
  822. spin_unlock_irq(&worker->lock);
  823. if (!noop)
  824. wait_for_completion(&fwork.done);
  825. }
  826. EXPORT_SYMBOL_GPL(kthread_flush_work);
  827. /*
  828. * This function removes the work from the worker queue. Also it makes sure
  829. * that it won't get queued later via the delayed work's timer.
  830. *
  831. * The work might still be in use when this function finishes. See the
  832. * current_work proceed by the worker.
  833. *
  834. * Return: %true if @work was pending and successfully canceled,
  835. * %false if @work was not pending
  836. */
  837. static bool __kthread_cancel_work(struct kthread_work *work, bool is_dwork,
  838. unsigned long *flags)
  839. {
  840. /* Try to cancel the timer if exists. */
  841. if (is_dwork) {
  842. struct kthread_delayed_work *dwork =
  843. container_of(work, struct kthread_delayed_work, work);
  844. struct kthread_worker *worker = work->worker;
  845. /*
  846. * del_timer_sync() must be called to make sure that the timer
  847. * callback is not running. The lock must be temporary released
  848. * to avoid a deadlock with the callback. In the meantime,
  849. * any queuing is blocked by setting the canceling counter.
  850. */
  851. work->canceling++;
  852. spin_unlock_irqrestore(&worker->lock, *flags);
  853. del_timer_sync(&dwork->timer);
  854. spin_lock_irqsave(&worker->lock, *flags);
  855. work->canceling--;
  856. }
  857. /*
  858. * Try to remove the work from a worker list. It might either
  859. * be from worker->work_list or from worker->delayed_work_list.
  860. */
  861. if (!list_empty(&work->node)) {
  862. list_del_init(&work->node);
  863. return true;
  864. }
  865. return false;
  866. }
  867. /**
  868. * kthread_mod_delayed_work - modify delay of or queue a kthread delayed work
  869. * @worker: kthread worker to use
  870. * @dwork: kthread delayed work to queue
  871. * @delay: number of jiffies to wait before queuing
  872. *
  873. * If @dwork is idle, equivalent to kthread_queue_delayed_work(). Otherwise,
  874. * modify @dwork's timer so that it expires after @delay. If @delay is zero,
  875. * @work is guaranteed to be queued immediately.
  876. *
  877. * Return: %true if @dwork was pending and its timer was modified,
  878. * %false otherwise.
  879. *
  880. * A special case is when the work is being canceled in parallel.
  881. * It might be caused either by the real kthread_cancel_delayed_work_sync()
  882. * or yet another kthread_mod_delayed_work() call. We let the other command
  883. * win and return %false here. The caller is supposed to synchronize these
  884. * operations a reasonable way.
  885. *
  886. * This function is safe to call from any context including IRQ handler.
  887. * See __kthread_cancel_work() and kthread_delayed_work_timer_fn()
  888. * for details.
  889. */
  890. bool kthread_mod_delayed_work(struct kthread_worker *worker,
  891. struct kthread_delayed_work *dwork,
  892. unsigned long delay)
  893. {
  894. struct kthread_work *work = &dwork->work;
  895. unsigned long flags;
  896. int ret = false;
  897. spin_lock_irqsave(&worker->lock, flags);
  898. /* Do not bother with canceling when never queued. */
  899. if (!work->worker)
  900. goto fast_queue;
  901. /* Work must not be used with >1 worker, see kthread_queue_work() */
  902. WARN_ON_ONCE(work->worker != worker);
  903. /* Do not fight with another command that is canceling this work. */
  904. if (work->canceling)
  905. goto out;
  906. ret = __kthread_cancel_work(work, true, &flags);
  907. fast_queue:
  908. __kthread_queue_delayed_work(worker, dwork, delay);
  909. out:
  910. spin_unlock_irqrestore(&worker->lock, flags);
  911. return ret;
  912. }
  913. EXPORT_SYMBOL_GPL(kthread_mod_delayed_work);
  914. static bool __kthread_cancel_work_sync(struct kthread_work *work, bool is_dwork)
  915. {
  916. struct kthread_worker *worker = work->worker;
  917. unsigned long flags;
  918. int ret = false;
  919. if (!worker)
  920. goto out;
  921. spin_lock_irqsave(&worker->lock, flags);
  922. /* Work must not be used with >1 worker, see kthread_queue_work(). */
  923. WARN_ON_ONCE(work->worker != worker);
  924. ret = __kthread_cancel_work(work, is_dwork, &flags);
  925. if (worker->current_work != work)
  926. goto out_fast;
  927. /*
  928. * The work is in progress and we need to wait with the lock released.
  929. * In the meantime, block any queuing by setting the canceling counter.
  930. */
  931. work->canceling++;
  932. spin_unlock_irqrestore(&worker->lock, flags);
  933. kthread_flush_work(work);
  934. spin_lock_irqsave(&worker->lock, flags);
  935. work->canceling--;
  936. out_fast:
  937. spin_unlock_irqrestore(&worker->lock, flags);
  938. out:
  939. return ret;
  940. }
  941. /**
  942. * kthread_cancel_work_sync - cancel a kthread work and wait for it to finish
  943. * @work: the kthread work to cancel
  944. *
  945. * Cancel @work and wait for its execution to finish. This function
  946. * can be used even if the work re-queues itself. On return from this
  947. * function, @work is guaranteed to be not pending or executing on any CPU.
  948. *
  949. * kthread_cancel_work_sync(&delayed_work->work) must not be used for
  950. * delayed_work's. Use kthread_cancel_delayed_work_sync() instead.
  951. *
  952. * The caller must ensure that the worker on which @work was last
  953. * queued can't be destroyed before this function returns.
  954. *
  955. * Return: %true if @work was pending, %false otherwise.
  956. */
  957. bool kthread_cancel_work_sync(struct kthread_work *work)
  958. {
  959. return __kthread_cancel_work_sync(work, false);
  960. }
  961. EXPORT_SYMBOL_GPL(kthread_cancel_work_sync);
  962. /**
  963. * kthread_cancel_delayed_work_sync - cancel a kthread delayed work and
  964. * wait for it to finish.
  965. * @dwork: the kthread delayed work to cancel
  966. *
  967. * This is kthread_cancel_work_sync() for delayed works.
  968. *
  969. * Return: %true if @dwork was pending, %false otherwise.
  970. */
  971. bool kthread_cancel_delayed_work_sync(struct kthread_delayed_work *dwork)
  972. {
  973. return __kthread_cancel_work_sync(&dwork->work, true);
  974. }
  975. EXPORT_SYMBOL_GPL(kthread_cancel_delayed_work_sync);
  976. /**
  977. * kthread_flush_worker - flush all current works on a kthread_worker
  978. * @worker: worker to flush
  979. *
  980. * Wait until all currently executing or pending works on @worker are
  981. * finished.
  982. */
  983. void kthread_flush_worker(struct kthread_worker *worker)
  984. {
  985. struct kthread_flush_work fwork = {
  986. KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
  987. COMPLETION_INITIALIZER_ONSTACK(fwork.done),
  988. };
  989. kthread_queue_work(worker, &fwork.work);
  990. wait_for_completion(&fwork.done);
  991. }
  992. EXPORT_SYMBOL_GPL(kthread_flush_worker);
  993. /**
  994. * kthread_destroy_worker - destroy a kthread worker
  995. * @worker: worker to be destroyed
  996. *
  997. * Flush and destroy @worker. The simple flush is enough because the kthread
  998. * worker API is used only in trivial scenarios. There are no multi-step state
  999. * machines needed.
  1000. */
  1001. void kthread_destroy_worker(struct kthread_worker *worker)
  1002. {
  1003. struct task_struct *task;
  1004. task = worker->task;
  1005. if (WARN_ON(!task))
  1006. return;
  1007. kthread_flush_worker(worker);
  1008. kthread_stop(task);
  1009. WARN_ON(!list_empty(&worker->work_list));
  1010. kfree(worker);
  1011. }
  1012. EXPORT_SYMBOL(kthread_destroy_worker);