kthread.c 32 KB

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