kthread.c 33 KB

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