kthread.c 33 KB

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