kthread.c 33 KB

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