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