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 <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 <trace/events/sched.h>
  22. static DEFINE_SPINLOCK(kthread_create_lock);
  23. static LIST_HEAD(kthread_create_list);
  24. struct task_struct *kthreadd_task;
  25. struct kthread_create_info
  26. {
  27. /* Information passed to kthread() from kthreadd. */
  28. int (*threadfn)(void *data);
  29. void *data;
  30. int node;
  31. /* Result passed back to kthread_create() from kthreadd. */
  32. struct task_struct *result;
  33. struct completion *done;
  34. struct list_head list;
  35. };
  36. struct kthread {
  37. unsigned long flags;
  38. unsigned int cpu;
  39. void *data;
  40. struct completion parked;
  41. struct completion exited;
  42. };
  43. enum KTHREAD_BITS {
  44. KTHREAD_IS_PER_CPU = 0,
  45. KTHREAD_SHOULD_STOP,
  46. KTHREAD_SHOULD_PARK,
  47. KTHREAD_IS_PARKED,
  48. };
  49. #define __to_kthread(vfork) \
  50. container_of(vfork, struct kthread, exited)
  51. static inline struct kthread *to_kthread(struct task_struct *k)
  52. {
  53. return __to_kthread(k->vfork_done);
  54. }
  55. static struct kthread *to_live_kthread(struct task_struct *k)
  56. {
  57. struct completion *vfork = ACCESS_ONCE(k->vfork_done);
  58. if (likely(vfork) && try_get_task_stack(k))
  59. return __to_kthread(vfork);
  60. return NULL;
  61. }
  62. /**
  63. * kthread_should_stop - should this kthread return now?
  64. *
  65. * When someone calls kthread_stop() on your kthread, it will be woken
  66. * and this will return true. You should then return, and your return
  67. * value will be passed through to kthread_stop().
  68. */
  69. bool kthread_should_stop(void)
  70. {
  71. return test_bit(KTHREAD_SHOULD_STOP, &to_kthread(current)->flags);
  72. }
  73. EXPORT_SYMBOL(kthread_should_stop);
  74. /**
  75. * kthread_should_park - should this kthread park now?
  76. *
  77. * When someone calls kthread_park() on your kthread, it will be woken
  78. * and this will return true. You should then do the necessary
  79. * cleanup and call kthread_parkme()
  80. *
  81. * Similar to kthread_should_stop(), but this keeps the thread alive
  82. * and in a park position. kthread_unpark() "restarts" the thread and
  83. * calls the thread function again.
  84. */
  85. bool kthread_should_park(void)
  86. {
  87. return test_bit(KTHREAD_SHOULD_PARK, &to_kthread(current)->flags);
  88. }
  89. EXPORT_SYMBOL_GPL(kthread_should_park);
  90. /**
  91. * kthread_freezable_should_stop - should this freezable kthread return now?
  92. * @was_frozen: optional out parameter, indicates whether %current was frozen
  93. *
  94. * kthread_should_stop() for freezable kthreads, which will enter
  95. * refrigerator if necessary. This function is safe from kthread_stop() /
  96. * freezer deadlock and freezable kthreads should use this function instead
  97. * of calling try_to_freeze() directly.
  98. */
  99. bool kthread_freezable_should_stop(bool *was_frozen)
  100. {
  101. bool frozen = false;
  102. might_sleep();
  103. if (unlikely(freezing(current)))
  104. frozen = __refrigerator(true);
  105. if (was_frozen)
  106. *was_frozen = frozen;
  107. return kthread_should_stop();
  108. }
  109. EXPORT_SYMBOL_GPL(kthread_freezable_should_stop);
  110. /**
  111. * kthread_data - return data value specified on kthread creation
  112. * @task: kthread task in question
  113. *
  114. * Return the data value specified when kthread @task was created.
  115. * The caller is responsible for ensuring the validity of @task when
  116. * calling this function.
  117. */
  118. void *kthread_data(struct task_struct *task)
  119. {
  120. return to_kthread(task)->data;
  121. }
  122. /**
  123. * kthread_probe_data - speculative version of kthread_data()
  124. * @task: possible kthread task in question
  125. *
  126. * @task could be a kthread task. Return the data value specified when it
  127. * was created if accessible. If @task isn't a kthread task or its data is
  128. * inaccessible for any reason, %NULL is returned. This function requires
  129. * that @task itself is safe to dereference.
  130. */
  131. void *kthread_probe_data(struct task_struct *task)
  132. {
  133. struct kthread *kthread = to_kthread(task);
  134. void *data = NULL;
  135. probe_kernel_read(&data, &kthread->data, sizeof(data));
  136. return data;
  137. }
  138. static void __kthread_parkme(struct kthread *self)
  139. {
  140. __set_current_state(TASK_PARKED);
  141. while (test_bit(KTHREAD_SHOULD_PARK, &self->flags)) {
  142. if (!test_and_set_bit(KTHREAD_IS_PARKED, &self->flags))
  143. complete(&self->parked);
  144. schedule();
  145. __set_current_state(TASK_PARKED);
  146. }
  147. clear_bit(KTHREAD_IS_PARKED, &self->flags);
  148. __set_current_state(TASK_RUNNING);
  149. }
  150. void kthread_parkme(void)
  151. {
  152. __kthread_parkme(to_kthread(current));
  153. }
  154. EXPORT_SYMBOL_GPL(kthread_parkme);
  155. static int kthread(void *_create)
  156. {
  157. /* Copy data: it's on kthread's stack */
  158. struct kthread_create_info *create = _create;
  159. int (*threadfn)(void *data) = create->threadfn;
  160. void *data = create->data;
  161. struct completion *done;
  162. struct kthread self;
  163. int ret;
  164. self.flags = 0;
  165. self.data = data;
  166. init_completion(&self.exited);
  167. init_completion(&self.parked);
  168. current->vfork_done = &self.exited;
  169. /* If user was SIGKILLed, I release the structure. */
  170. done = xchg(&create->done, NULL);
  171. if (!done) {
  172. kfree(create);
  173. do_exit(-EINTR);
  174. }
  175. /* OK, tell user we're spawned, wait for stop or wakeup */
  176. __set_current_state(TASK_UNINTERRUPTIBLE);
  177. create->result = current;
  178. complete(done);
  179. schedule();
  180. ret = -EINTR;
  181. if (!test_bit(KTHREAD_SHOULD_STOP, &self.flags)) {
  182. __kthread_parkme(&self);
  183. ret = threadfn(data);
  184. }
  185. /* we can't just return, we must preserve "self" on stack */
  186. do_exit(ret);
  187. }
  188. /* called from do_fork() to get node information for about to be created task */
  189. int tsk_fork_get_node(struct task_struct *tsk)
  190. {
  191. #ifdef CONFIG_NUMA
  192. if (tsk == kthreadd_task)
  193. return tsk->pref_node_fork;
  194. #endif
  195. return NUMA_NO_NODE;
  196. }
  197. static void create_kthread(struct kthread_create_info *create)
  198. {
  199. int pid;
  200. #ifdef CONFIG_NUMA
  201. current->pref_node_fork = create->node;
  202. #endif
  203. /* We want our own signal handler (we take no signals by default). */
  204. pid = kernel_thread(kthread, create, CLONE_FS | CLONE_FILES | SIGCHLD);
  205. if (pid < 0) {
  206. /* If user was SIGKILLed, I release the structure. */
  207. struct completion *done = xchg(&create->done, NULL);
  208. if (!done) {
  209. kfree(create);
  210. return;
  211. }
  212. create->result = ERR_PTR(pid);
  213. complete(done);
  214. }
  215. }
  216. static struct task_struct *__kthread_create_on_node(int (*threadfn)(void *data),
  217. void *data, int node,
  218. const char namefmt[],
  219. va_list args)
  220. {
  221. DECLARE_COMPLETION_ONSTACK(done);
  222. struct task_struct *task;
  223. struct kthread_create_info *create = kmalloc(sizeof(*create),
  224. GFP_KERNEL);
  225. if (!create)
  226. return ERR_PTR(-ENOMEM);
  227. create->threadfn = threadfn;
  228. create->data = data;
  229. create->node = node;
  230. create->done = &done;
  231. spin_lock(&kthread_create_lock);
  232. list_add_tail(&create->list, &kthread_create_list);
  233. spin_unlock(&kthread_create_lock);
  234. wake_up_process(kthreadd_task);
  235. /*
  236. * Wait for completion in killable state, for I might be chosen by
  237. * the OOM killer while kthreadd is trying to allocate memory for
  238. * new kernel thread.
  239. */
  240. if (unlikely(wait_for_completion_killable(&done))) {
  241. /*
  242. * If I was SIGKILLed before kthreadd (or new kernel thread)
  243. * calls complete(), leave the cleanup of this structure to
  244. * that thread.
  245. */
  246. if (xchg(&create->done, NULL))
  247. return ERR_PTR(-EINTR);
  248. /*
  249. * kthreadd (or new kernel thread) will call complete()
  250. * shortly.
  251. */
  252. wait_for_completion(&done);
  253. }
  254. task = create->result;
  255. if (!IS_ERR(task)) {
  256. static const struct sched_param param = { .sched_priority = 0 };
  257. vsnprintf(task->comm, sizeof(task->comm), namefmt, args);
  258. /*
  259. * root may have changed our (kthreadd's) priority or CPU mask.
  260. * The kernel thread should not inherit these properties.
  261. */
  262. sched_setscheduler_nocheck(task, SCHED_NORMAL, &param);
  263. set_cpus_allowed_ptr(task, cpu_all_mask);
  264. }
  265. kfree(create);
  266. return task;
  267. }
  268. /**
  269. * kthread_create_on_node - create a kthread.
  270. * @threadfn: the function to run until signal_pending(current).
  271. * @data: data ptr for @threadfn.
  272. * @node: task and thread structures for the thread are allocated on this node
  273. * @namefmt: printf-style name for the thread.
  274. *
  275. * Description: This helper function creates and names a kernel
  276. * thread. The thread will be stopped: use wake_up_process() to start
  277. * it. See also kthread_run(). The new thread has SCHED_NORMAL policy and
  278. * is affine to all CPUs.
  279. *
  280. * If thread is going to be bound on a particular cpu, give its node
  281. * in @node, to get NUMA affinity for kthread stack, or else give NUMA_NO_NODE.
  282. * When woken, the thread will run @threadfn() with @data as its
  283. * argument. @threadfn() can either call do_exit() directly if it is a
  284. * standalone thread for which no one will call kthread_stop(), or
  285. * return when 'kthread_should_stop()' is true (which means
  286. * kthread_stop() has been called). The return value should be zero
  287. * or a negative error number; it will be passed to kthread_stop().
  288. *
  289. * Returns a task_struct or ERR_PTR(-ENOMEM) or ERR_PTR(-EINTR).
  290. */
  291. struct task_struct *kthread_create_on_node(int (*threadfn)(void *data),
  292. void *data, int node,
  293. const char namefmt[],
  294. ...)
  295. {
  296. struct task_struct *task;
  297. va_list args;
  298. va_start(args, namefmt);
  299. task = __kthread_create_on_node(threadfn, data, node, namefmt, args);
  300. va_end(args);
  301. return task;
  302. }
  303. EXPORT_SYMBOL(kthread_create_on_node);
  304. static void __kthread_bind_mask(struct task_struct *p, const struct cpumask *mask, long state)
  305. {
  306. unsigned long flags;
  307. if (!wait_task_inactive(p, state)) {
  308. WARN_ON(1);
  309. return;
  310. }
  311. /* It's safe because the task is inactive. */
  312. raw_spin_lock_irqsave(&p->pi_lock, flags);
  313. do_set_cpus_allowed(p, mask);
  314. p->flags |= PF_NO_SETAFFINITY;
  315. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  316. }
  317. static void __kthread_bind(struct task_struct *p, unsigned int cpu, long state)
  318. {
  319. __kthread_bind_mask(p, cpumask_of(cpu), state);
  320. }
  321. void kthread_bind_mask(struct task_struct *p, const struct cpumask *mask)
  322. {
  323. __kthread_bind_mask(p, mask, TASK_UNINTERRUPTIBLE);
  324. }
  325. /**
  326. * kthread_bind - bind a just-created kthread to a cpu.
  327. * @p: thread created by kthread_create().
  328. * @cpu: cpu (might not be online, must be possible) for @k to run on.
  329. *
  330. * Description: This function is equivalent to set_cpus_allowed(),
  331. * except that @cpu doesn't need to be online, and the thread must be
  332. * stopped (i.e., just returned from kthread_create()).
  333. */
  334. void kthread_bind(struct task_struct *p, unsigned int cpu)
  335. {
  336. __kthread_bind(p, cpu, TASK_UNINTERRUPTIBLE);
  337. }
  338. EXPORT_SYMBOL(kthread_bind);
  339. /**
  340. * kthread_create_on_cpu - Create a cpu bound kthread
  341. * @threadfn: the function to run until signal_pending(current).
  342. * @data: data ptr for @threadfn.
  343. * @cpu: The cpu on which the thread should be bound,
  344. * @namefmt: printf-style name for the thread. Format is restricted
  345. * to "name.*%u". Code fills in cpu number.
  346. *
  347. * Description: This helper function creates and names a kernel thread
  348. * The thread will be woken and put into park mode.
  349. */
  350. struct task_struct *kthread_create_on_cpu(int (*threadfn)(void *data),
  351. void *data, unsigned int cpu,
  352. const char *namefmt)
  353. {
  354. struct task_struct *p;
  355. p = kthread_create_on_node(threadfn, data, cpu_to_node(cpu), namefmt,
  356. cpu);
  357. if (IS_ERR(p))
  358. return p;
  359. kthread_bind(p, cpu);
  360. /* CPU hotplug need to bind once again when unparking the thread. */
  361. set_bit(KTHREAD_IS_PER_CPU, &to_kthread(p)->flags);
  362. to_kthread(p)->cpu = cpu;
  363. return p;
  364. }
  365. static void __kthread_unpark(struct task_struct *k, struct kthread *kthread)
  366. {
  367. clear_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
  368. /*
  369. * We clear the IS_PARKED bit here as we don't wait
  370. * until the task has left the park code. So if we'd
  371. * park before that happens we'd see the IS_PARKED bit
  372. * which might be about to be cleared.
  373. */
  374. if (test_and_clear_bit(KTHREAD_IS_PARKED, &kthread->flags)) {
  375. /*
  376. * Newly created kthread was parked when the CPU was offline.
  377. * The binding was lost and we need to set it again.
  378. */
  379. if (test_bit(KTHREAD_IS_PER_CPU, &kthread->flags))
  380. __kthread_bind(k, kthread->cpu, TASK_PARKED);
  381. wake_up_state(k, TASK_PARKED);
  382. }
  383. }
  384. /**
  385. * kthread_unpark - unpark a thread created by kthread_create().
  386. * @k: thread created by kthread_create().
  387. *
  388. * Sets kthread_should_park() for @k to return false, wakes it, and
  389. * waits for it to return. If the thread is marked percpu then its
  390. * bound to the cpu again.
  391. */
  392. void kthread_unpark(struct task_struct *k)
  393. {
  394. struct kthread *kthread = to_live_kthread(k);
  395. if (kthread) {
  396. __kthread_unpark(k, kthread);
  397. put_task_stack(k);
  398. }
  399. }
  400. EXPORT_SYMBOL_GPL(kthread_unpark);
  401. /**
  402. * kthread_park - park a thread created by kthread_create().
  403. * @k: thread created by kthread_create().
  404. *
  405. * Sets kthread_should_park() for @k to return true, wakes it, and
  406. * waits for it to return. This can also be called after kthread_create()
  407. * instead of calling wake_up_process(): the thread will park without
  408. * calling threadfn().
  409. *
  410. * Returns 0 if the thread is parked, -ENOSYS if the thread exited.
  411. * If called by the kthread itself just the park bit is set.
  412. */
  413. int kthread_park(struct task_struct *k)
  414. {
  415. struct kthread *kthread = to_live_kthread(k);
  416. int ret = -ENOSYS;
  417. if (kthread) {
  418. if (!test_bit(KTHREAD_IS_PARKED, &kthread->flags)) {
  419. set_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
  420. if (k != current) {
  421. wake_up_process(k);
  422. wait_for_completion(&kthread->parked);
  423. }
  424. }
  425. put_task_stack(k);
  426. ret = 0;
  427. }
  428. return ret;
  429. }
  430. EXPORT_SYMBOL_GPL(kthread_park);
  431. /**
  432. * kthread_stop - stop a thread created by kthread_create().
  433. * @k: thread created by kthread_create().
  434. *
  435. * Sets kthread_should_stop() for @k to return true, wakes it, and
  436. * waits for it to exit. This can also be called after kthread_create()
  437. * instead of calling wake_up_process(): the thread will exit without
  438. * calling threadfn().
  439. *
  440. * If threadfn() may call do_exit() itself, the caller must ensure
  441. * task_struct can't go away.
  442. *
  443. * Returns the result of threadfn(), or %-EINTR if wake_up_process()
  444. * was never called.
  445. */
  446. int kthread_stop(struct task_struct *k)
  447. {
  448. struct kthread *kthread;
  449. int ret;
  450. trace_sched_kthread_stop(k);
  451. get_task_struct(k);
  452. kthread = to_live_kthread(k);
  453. if (kthread) {
  454. set_bit(KTHREAD_SHOULD_STOP, &kthread->flags);
  455. __kthread_unpark(k, kthread);
  456. wake_up_process(k);
  457. wait_for_completion(&kthread->exited);
  458. put_task_stack(k);
  459. }
  460. ret = k->exit_code;
  461. put_task_struct(k);
  462. trace_sched_kthread_stop_ret(ret);
  463. return ret;
  464. }
  465. EXPORT_SYMBOL(kthread_stop);
  466. int kthreadd(void *unused)
  467. {
  468. struct task_struct *tsk = current;
  469. /* Setup a clean context for our children to inherit. */
  470. set_task_comm(tsk, "kthreadd");
  471. ignore_signals(tsk);
  472. set_cpus_allowed_ptr(tsk, cpu_all_mask);
  473. set_mems_allowed(node_states[N_MEMORY]);
  474. current->flags |= PF_NOFREEZE;
  475. for (;;) {
  476. set_current_state(TASK_INTERRUPTIBLE);
  477. if (list_empty(&kthread_create_list))
  478. schedule();
  479. __set_current_state(TASK_RUNNING);
  480. spin_lock(&kthread_create_lock);
  481. while (!list_empty(&kthread_create_list)) {
  482. struct kthread_create_info *create;
  483. create = list_entry(kthread_create_list.next,
  484. struct kthread_create_info, list);
  485. list_del_init(&create->list);
  486. spin_unlock(&kthread_create_lock);
  487. create_kthread(create);
  488. spin_lock(&kthread_create_lock);
  489. }
  490. spin_unlock(&kthread_create_lock);
  491. }
  492. return 0;
  493. }
  494. void __kthread_init_worker(struct kthread_worker *worker,
  495. const char *name,
  496. struct lock_class_key *key)
  497. {
  498. memset(worker, 0, sizeof(struct kthread_worker));
  499. spin_lock_init(&worker->lock);
  500. lockdep_set_class_and_name(&worker->lock, key, name);
  501. INIT_LIST_HEAD(&worker->work_list);
  502. INIT_LIST_HEAD(&worker->delayed_work_list);
  503. }
  504. EXPORT_SYMBOL_GPL(__kthread_init_worker);
  505. /**
  506. * kthread_worker_fn - kthread function to process kthread_worker
  507. * @worker_ptr: pointer to initialized kthread_worker
  508. *
  509. * This function implements the main cycle of kthread worker. It processes
  510. * work_list until it is stopped with kthread_stop(). It sleeps when the queue
  511. * is empty.
  512. *
  513. * The works are not allowed to keep any locks, disable preemption or interrupts
  514. * when they finish. There is defined a safe point for freezing when one work
  515. * finishes and before a new one is started.
  516. *
  517. * Also the works must not be handled by more than one worker at the same time,
  518. * see also kthread_queue_work().
  519. */
  520. int kthread_worker_fn(void *worker_ptr)
  521. {
  522. struct kthread_worker *worker = worker_ptr;
  523. struct kthread_work *work;
  524. /*
  525. * FIXME: Update the check and remove the assignment when all kthread
  526. * worker users are created using kthread_create_worker*() functions.
  527. */
  528. WARN_ON(worker->task && worker->task != current);
  529. worker->task = current;
  530. if (worker->flags & KTW_FREEZABLE)
  531. set_freezable();
  532. repeat:
  533. set_current_state(TASK_INTERRUPTIBLE); /* mb paired w/ kthread_stop */
  534. if (kthread_should_stop()) {
  535. __set_current_state(TASK_RUNNING);
  536. spin_lock_irq(&worker->lock);
  537. worker->task = NULL;
  538. spin_unlock_irq(&worker->lock);
  539. return 0;
  540. }
  541. work = NULL;
  542. spin_lock_irq(&worker->lock);
  543. if (!list_empty(&worker->work_list)) {
  544. work = list_first_entry(&worker->work_list,
  545. struct kthread_work, node);
  546. list_del_init(&work->node);
  547. }
  548. worker->current_work = work;
  549. spin_unlock_irq(&worker->lock);
  550. if (work) {
  551. __set_current_state(TASK_RUNNING);
  552. work->func(work);
  553. } else if (!freezing(current))
  554. schedule();
  555. try_to_freeze();
  556. goto repeat;
  557. }
  558. EXPORT_SYMBOL_GPL(kthread_worker_fn);
  559. static struct kthread_worker *
  560. __kthread_create_worker(int cpu, unsigned int flags,
  561. const char namefmt[], va_list args)
  562. {
  563. struct kthread_worker *worker;
  564. struct task_struct *task;
  565. worker = kzalloc(sizeof(*worker), GFP_KERNEL);
  566. if (!worker)
  567. return ERR_PTR(-ENOMEM);
  568. kthread_init_worker(worker);
  569. if (cpu >= 0) {
  570. char name[TASK_COMM_LEN];
  571. /*
  572. * kthread_create_worker_on_cpu() allows to pass a generic
  573. * namefmt in compare with kthread_create_on_cpu. We need
  574. * to format it here.
  575. */
  576. vsnprintf(name, sizeof(name), namefmt, args);
  577. task = kthread_create_on_cpu(kthread_worker_fn, worker,
  578. cpu, name);
  579. } else {
  580. task = __kthread_create_on_node(kthread_worker_fn, worker,
  581. -1, namefmt, args);
  582. }
  583. if (IS_ERR(task))
  584. goto fail_task;
  585. worker->flags = flags;
  586. worker->task = task;
  587. wake_up_process(task);
  588. return worker;
  589. fail_task:
  590. kfree(worker);
  591. return ERR_CAST(task);
  592. }
  593. /**
  594. * kthread_create_worker - create a kthread worker
  595. * @flags: flags modifying the default behavior of the worker
  596. * @namefmt: printf-style name for the kthread worker (task).
  597. *
  598. * Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
  599. * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
  600. * when the worker was SIGKILLed.
  601. */
  602. struct kthread_worker *
  603. kthread_create_worker(unsigned int flags, const char namefmt[], ...)
  604. {
  605. struct kthread_worker *worker;
  606. va_list args;
  607. va_start(args, namefmt);
  608. worker = __kthread_create_worker(-1, flags, namefmt, args);
  609. va_end(args);
  610. return worker;
  611. }
  612. EXPORT_SYMBOL(kthread_create_worker);
  613. /**
  614. * kthread_create_worker_on_cpu - create a kthread worker and bind it
  615. * it to a given CPU and the associated NUMA node.
  616. * @cpu: CPU number
  617. * @flags: flags modifying the default behavior of the worker
  618. * @namefmt: printf-style name for the kthread worker (task).
  619. *
  620. * Use a valid CPU number if you want to bind the kthread worker
  621. * to the given CPU and the associated NUMA node.
  622. *
  623. * A good practice is to add the cpu number also into the worker name.
  624. * For example, use kthread_create_worker_on_cpu(cpu, "helper/%d", cpu).
  625. *
  626. * Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
  627. * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
  628. * when the worker was SIGKILLed.
  629. */
  630. struct kthread_worker *
  631. kthread_create_worker_on_cpu(int cpu, unsigned int flags,
  632. const char namefmt[], ...)
  633. {
  634. struct kthread_worker *worker;
  635. va_list args;
  636. va_start(args, namefmt);
  637. worker = __kthread_create_worker(cpu, flags, namefmt, args);
  638. va_end(args);
  639. return worker;
  640. }
  641. EXPORT_SYMBOL(kthread_create_worker_on_cpu);
  642. /*
  643. * Returns true when the work could not be queued at the moment.
  644. * It happens when it is already pending in a worker list
  645. * or when it is being cancelled.
  646. */
  647. static inline bool queuing_blocked(struct kthread_worker *worker,
  648. struct kthread_work *work)
  649. {
  650. lockdep_assert_held(&worker->lock);
  651. return !list_empty(&work->node) || work->canceling;
  652. }
  653. static void kthread_insert_work_sanity_check(struct kthread_worker *worker,
  654. struct kthread_work *work)
  655. {
  656. lockdep_assert_held(&worker->lock);
  657. WARN_ON_ONCE(!list_empty(&work->node));
  658. /* Do not use a work with >1 worker, see kthread_queue_work() */
  659. WARN_ON_ONCE(work->worker && work->worker != worker);
  660. }
  661. /* insert @work before @pos in @worker */
  662. static void kthread_insert_work(struct kthread_worker *worker,
  663. struct kthread_work *work,
  664. struct list_head *pos)
  665. {
  666. kthread_insert_work_sanity_check(worker, work);
  667. list_add_tail(&work->node, pos);
  668. work->worker = worker;
  669. if (!worker->current_work && likely(worker->task))
  670. wake_up_process(worker->task);
  671. }
  672. /**
  673. * kthread_queue_work - queue a kthread_work
  674. * @worker: target kthread_worker
  675. * @work: kthread_work to queue
  676. *
  677. * Queue @work to work processor @task for async execution. @task
  678. * must have been created with kthread_worker_create(). Returns %true
  679. * if @work was successfully queued, %false if it was already pending.
  680. *
  681. * Reinitialize the work if it needs to be used by another worker.
  682. * For example, when the worker was stopped and started again.
  683. */
  684. bool kthread_queue_work(struct kthread_worker *worker,
  685. struct kthread_work *work)
  686. {
  687. bool ret = false;
  688. unsigned long flags;
  689. spin_lock_irqsave(&worker->lock, flags);
  690. if (!queuing_blocked(worker, work)) {
  691. kthread_insert_work(worker, work, &worker->work_list);
  692. ret = true;
  693. }
  694. spin_unlock_irqrestore(&worker->lock, flags);
  695. return ret;
  696. }
  697. EXPORT_SYMBOL_GPL(kthread_queue_work);
  698. /**
  699. * kthread_delayed_work_timer_fn - callback that queues the associated kthread
  700. * delayed work when the timer expires.
  701. * @__data: pointer to the data associated with the timer
  702. *
  703. * The format of the function is defined by struct timer_list.
  704. * It should have been called from irqsafe timer with irq already off.
  705. */
  706. void kthread_delayed_work_timer_fn(unsigned long __data)
  707. {
  708. struct kthread_delayed_work *dwork =
  709. (struct kthread_delayed_work *)__data;
  710. struct kthread_work *work = &dwork->work;
  711. struct kthread_worker *worker = work->worker;
  712. /*
  713. * This might happen when a pending work is reinitialized.
  714. * It means that it is used a wrong way.
  715. */
  716. if (WARN_ON_ONCE(!worker))
  717. return;
  718. spin_lock(&worker->lock);
  719. /* Work must not be used with >1 worker, see kthread_queue_work(). */
  720. WARN_ON_ONCE(work->worker != worker);
  721. /* Move the work from worker->delayed_work_list. */
  722. WARN_ON_ONCE(list_empty(&work->node));
  723. list_del_init(&work->node);
  724. kthread_insert_work(worker, work, &worker->work_list);
  725. spin_unlock(&worker->lock);
  726. }
  727. EXPORT_SYMBOL(kthread_delayed_work_timer_fn);
  728. void __kthread_queue_delayed_work(struct kthread_worker *worker,
  729. struct kthread_delayed_work *dwork,
  730. unsigned long delay)
  731. {
  732. struct timer_list *timer = &dwork->timer;
  733. struct kthread_work *work = &dwork->work;
  734. WARN_ON_ONCE(timer->function != kthread_delayed_work_timer_fn ||
  735. timer->data != (unsigned long)dwork);
  736. /*
  737. * If @delay is 0, queue @dwork->work immediately. This is for
  738. * both optimization and correctness. The earliest @timer can
  739. * expire is on the closest next tick and delayed_work users depend
  740. * on that there's no such delay when @delay is 0.
  741. */
  742. if (!delay) {
  743. kthread_insert_work(worker, work, &worker->work_list);
  744. return;
  745. }
  746. /* Be paranoid and try to detect possible races already now. */
  747. kthread_insert_work_sanity_check(worker, work);
  748. list_add(&work->node, &worker->delayed_work_list);
  749. work->worker = worker;
  750. timer_stats_timer_set_start_info(&dwork->timer);
  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);