kthread.c 34 KB

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