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