kthread.c 33 KB

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