kthread.c 34 KB

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