kthread.c 32 KB

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