kthread.c 35 KB

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