1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Kernel thread helper functions.
3 * Copyright (C) 2004 IBM Corporation, Rusty Russell.
4 * Copyright (C) 2009 Red Hat, Inc.
5 *
6 * Creation is done via kthreadd, so that we get a clean environment
7 * even if we're invoked from userspace (think modprobe, hotplug cpu,
8 * etc.).
9 */
10 #include <uapi/linux/sched/types.h>
11 #include <linux/mm.h>
12 #include <linux/mmu_context.h>
13 #include <linux/sched.h>
14 #include <linux/sched/mm.h>
15 #include <linux/sched/task.h>
16 #include <linux/kthread.h>
17 #include <linux/completion.h>
18 #include <linux/err.h>
19 #include <linux/cgroup.h>
20 #include <linux/cpuset.h>
21 #include <linux/unistd.h>
22 #include <linux/file.h>
23 #include <linux/export.h>
24 #include <linux/mutex.h>
25 #include <linux/slab.h>
26 #include <linux/freezer.h>
27 #include <linux/ptrace.h>
28 #include <linux/uaccess.h>
29 #include <linux/numa.h>
30 #include <linux/sched/isolation.h>
31 #include <trace/events/sched.h>
32
33
34 static DEFINE_SPINLOCK(kthread_create_lock);
35 static LIST_HEAD(kthread_create_list);
36 struct task_struct *kthreadd_task;
37
38 struct kthread_create_info
39 {
40 /* Information passed to kthread() from kthreadd. */
41 int (*threadfn)(void *data);
42 void *data;
43 int node;
44
45 /* Result passed back to kthread_create() from kthreadd. */
46 struct task_struct *result;
47 struct completion *done;
48
49 struct list_head list;
50 };
51
52 struct kthread {
53 unsigned long flags;
54 unsigned int cpu;
55 int (*threadfn)(void *);
56 void *data;
57 mm_segment_t oldfs;
58 struct completion parked;
59 struct completion exited;
60 #ifdef CONFIG_BLK_CGROUP
61 struct cgroup_subsys_state *blkcg_css;
62 #endif
63 };
64
65 enum KTHREAD_BITS {
66 KTHREAD_IS_PER_CPU = 0,
67 KTHREAD_SHOULD_STOP,
68 KTHREAD_SHOULD_PARK,
69 };
70
to_kthread(struct task_struct * k)71 static inline struct kthread *to_kthread(struct task_struct *k)
72 {
73 WARN_ON(!(k->flags & PF_KTHREAD));
74 return (__force void *)k->set_child_tid;
75 }
76
77 /*
78 * Variant of to_kthread() that doesn't assume @p is a kthread.
79 *
80 * Per construction; when:
81 *
82 * (p->flags & PF_KTHREAD) && p->set_child_tid
83 *
84 * the task is both a kthread and struct kthread is persistent. However
85 * PF_KTHREAD on it's own is not, kernel_thread() can exec() (See umh.c and
86 * begin_new_exec()).
87 */
__to_kthread(struct task_struct * p)88 static inline struct kthread *__to_kthread(struct task_struct *p)
89 {
90 void *kthread = (__force void *)p->set_child_tid;
91 if (kthread && !(p->flags & PF_KTHREAD))
92 kthread = NULL;
93 return kthread;
94 }
95
set_kthread_struct(struct task_struct * p)96 void set_kthread_struct(struct task_struct *p)
97 {
98 struct kthread *kthread;
99
100 if (__to_kthread(p))
101 return;
102
103 kthread = kzalloc(sizeof(*kthread), GFP_KERNEL);
104 /*
105 * We abuse ->set_child_tid to avoid the new member and because it
106 * can't be wrongly copied by copy_process(). We also rely on fact
107 * that the caller can't exec, so PF_KTHREAD can't be cleared.
108 */
109 p->set_child_tid = (__force void __user *)kthread;
110 }
111
free_kthread_struct(struct task_struct * k)112 void free_kthread_struct(struct task_struct *k)
113 {
114 struct kthread *kthread;
115
116 /*
117 * Can be NULL if this kthread was created by kernel_thread()
118 * or if kmalloc() in kthread() failed.
119 */
120 kthread = to_kthread(k);
121 #ifdef CONFIG_BLK_CGROUP
122 WARN_ON_ONCE(kthread && kthread->blkcg_css);
123 #endif
124 kfree(kthread);
125 }
126
127 /**
128 * kthread_should_stop - should this kthread return now?
129 *
130 * When someone calls kthread_stop() on your kthread, it will be woken
131 * and this will return true. You should then return, and your return
132 * value will be passed through to kthread_stop().
133 */
kthread_should_stop(void)134 bool kthread_should_stop(void)
135 {
136 return test_bit(KTHREAD_SHOULD_STOP, &to_kthread(current)->flags);
137 }
138 EXPORT_SYMBOL(kthread_should_stop);
139
__kthread_should_park(struct task_struct * k)140 bool __kthread_should_park(struct task_struct *k)
141 {
142 return test_bit(KTHREAD_SHOULD_PARK, &to_kthread(k)->flags);
143 }
144 EXPORT_SYMBOL_GPL(__kthread_should_park);
145
146 /**
147 * kthread_should_park - should this kthread park now?
148 *
149 * When someone calls kthread_park() on your kthread, it will be woken
150 * and this will return true. You should then do the necessary
151 * cleanup and call kthread_parkme()
152 *
153 * Similar to kthread_should_stop(), but this keeps the thread alive
154 * and in a park position. kthread_unpark() "restarts" the thread and
155 * calls the thread function again.
156 */
kthread_should_park(void)157 bool kthread_should_park(void)
158 {
159 return __kthread_should_park(current);
160 }
161 EXPORT_SYMBOL_GPL(kthread_should_park);
162
163 /**
164 * kthread_freezable_should_stop - should this freezable kthread return now?
165 * @was_frozen: optional out parameter, indicates whether %current was frozen
166 *
167 * kthread_should_stop() for freezable kthreads, which will enter
168 * refrigerator if necessary. This function is safe from kthread_stop() /
169 * freezer deadlock and freezable kthreads should use this function instead
170 * of calling try_to_freeze() directly.
171 */
kthread_freezable_should_stop(bool * was_frozen)172 bool kthread_freezable_should_stop(bool *was_frozen)
173 {
174 bool frozen = false;
175
176 might_sleep();
177
178 if (unlikely(freezing(current)))
179 frozen = __refrigerator(true);
180
181 if (was_frozen)
182 *was_frozen = frozen;
183
184 return kthread_should_stop();
185 }
186 EXPORT_SYMBOL_GPL(kthread_freezable_should_stop);
187
188 /**
189 * kthread_func - return the function specified on kthread creation
190 * @task: kthread task in question
191 *
192 * Returns NULL if the task is not a kthread.
193 */
kthread_func(struct task_struct * task)194 void *kthread_func(struct task_struct *task)
195 {
196 struct kthread *kthread = __to_kthread(task);
197 if (kthread)
198 return kthread->threadfn;
199 return NULL;
200 }
201 EXPORT_SYMBOL_GPL(kthread_func);
202
203 /**
204 * kthread_data - return data value specified on kthread creation
205 * @task: kthread task in question
206 *
207 * Return the data value specified when kthread @task was created.
208 * The caller is responsible for ensuring the validity of @task when
209 * calling this function.
210 */
kthread_data(struct task_struct * task)211 void *kthread_data(struct task_struct *task)
212 {
213 return to_kthread(task)->data;
214 }
215 EXPORT_SYMBOL_GPL(kthread_data);
216
217 /**
218 * kthread_probe_data - speculative version of kthread_data()
219 * @task: possible kthread task in question
220 *
221 * @task could be a kthread task. Return the data value specified when it
222 * was created if accessible. If @task isn't a kthread task or its data is
223 * inaccessible for any reason, %NULL is returned. This function requires
224 * that @task itself is safe to dereference.
225 */
kthread_probe_data(struct task_struct * task)226 void *kthread_probe_data(struct task_struct *task)
227 {
228 struct kthread *kthread = __to_kthread(task);
229 void *data = NULL;
230
231 if (kthread)
232 copy_from_kernel_nofault(&data, &kthread->data, sizeof(data));
233 return data;
234 }
235
__kthread_parkme(struct kthread * self)236 static void __kthread_parkme(struct kthread *self)
237 {
238 for (;;) {
239 /*
240 * TASK_PARKED is a special state; we must serialize against
241 * possible pending wakeups to avoid store-store collisions on
242 * task->state.
243 *
244 * Such a collision might possibly result in the task state
245 * changin from TASK_PARKED and us failing the
246 * wait_task_inactive() in kthread_park().
247 */
248 set_special_state(TASK_PARKED);
249 if (!test_bit(KTHREAD_SHOULD_PARK, &self->flags))
250 break;
251
252 /*
253 * Thread is going to call schedule(), do not preempt it,
254 * or the caller of kthread_park() may spend more time in
255 * wait_task_inactive().
256 */
257 preempt_disable();
258 complete(&self->parked);
259 schedule_preempt_disabled();
260 preempt_enable();
261 }
262 __set_current_state(TASK_RUNNING);
263 }
264
kthread_parkme(void)265 void kthread_parkme(void)
266 {
267 __kthread_parkme(to_kthread(current));
268 }
269 EXPORT_SYMBOL_GPL(kthread_parkme);
270
kthread(void * _create)271 static int kthread(void *_create)
272 {
273 /* Copy data: it's on kthread's stack */
274 struct kthread_create_info *create = _create;
275 int (*threadfn)(void *data) = create->threadfn;
276 void *data = create->data;
277 struct completion *done;
278 struct kthread *self;
279 int ret;
280
281 set_kthread_struct(current);
282 self = to_kthread(current);
283
284 /* If user was SIGKILLed, I release the structure. */
285 done = xchg(&create->done, NULL);
286 if (!done) {
287 kfree(create);
288 do_exit(-EINTR);
289 }
290
291 if (!self) {
292 create->result = ERR_PTR(-ENOMEM);
293 complete(done);
294 do_exit(-ENOMEM);
295 }
296
297 self->threadfn = threadfn;
298 self->data = data;
299 init_completion(&self->exited);
300 init_completion(&self->parked);
301 current->vfork_done = &self->exited;
302
303 /* OK, tell user we're spawned, wait for stop or wakeup */
304 __set_current_state(TASK_UNINTERRUPTIBLE);
305 create->result = current;
306 /*
307 * Thread is going to call schedule(), do not preempt it,
308 * or the creator may spend more time in wait_task_inactive().
309 */
310 preempt_disable();
311 complete(done);
312 schedule_preempt_disabled();
313 preempt_enable();
314
315 ret = -EINTR;
316 if (!test_bit(KTHREAD_SHOULD_STOP, &self->flags)) {
317 cgroup_kthread_ready();
318 __kthread_parkme(self);
319 ret = threadfn(data);
320 }
321 do_exit(ret);
322 }
323
324 /* called from kernel_clone() to get node information for about to be created task */
tsk_fork_get_node(struct task_struct * tsk)325 int tsk_fork_get_node(struct task_struct *tsk)
326 {
327 #ifdef CONFIG_NUMA
328 if (tsk == kthreadd_task)
329 return tsk->pref_node_fork;
330 #endif
331 return NUMA_NO_NODE;
332 }
333
create_kthread(struct kthread_create_info * create)334 static void create_kthread(struct kthread_create_info *create)
335 {
336 int pid;
337
338 #ifdef CONFIG_NUMA
339 current->pref_node_fork = create->node;
340 #endif
341 /* We want our own signal handler (we take no signals by default). */
342 pid = kernel_thread(kthread, create, CLONE_FS | CLONE_FILES | SIGCHLD);
343 if (pid < 0) {
344 /* If user was SIGKILLed, I release the structure. */
345 struct completion *done = xchg(&create->done, NULL);
346
347 if (!done) {
348 kfree(create);
349 return;
350 }
351 create->result = ERR_PTR(pid);
352 complete(done);
353 }
354 }
355
356 static __printf(4, 0)
__kthread_create_on_node(int (* threadfn)(void * data),void * data,int node,const char namefmt[],va_list args)357 struct task_struct *__kthread_create_on_node(int (*threadfn)(void *data),
358 void *data, int node,
359 const char namefmt[],
360 va_list args)
361 {
362 DECLARE_COMPLETION_ONSTACK(done);
363 struct task_struct *task;
364 struct kthread_create_info *create = kmalloc(sizeof(*create),
365 GFP_KERNEL);
366
367 if (!create)
368 return ERR_PTR(-ENOMEM);
369 create->threadfn = threadfn;
370 create->data = data;
371 create->node = node;
372 create->done = &done;
373
374 spin_lock(&kthread_create_lock);
375 list_add_tail(&create->list, &kthread_create_list);
376 spin_unlock(&kthread_create_lock);
377
378 wake_up_process(kthreadd_task);
379 /*
380 * Wait for completion in killable state, for I might be chosen by
381 * the OOM killer while kthreadd is trying to allocate memory for
382 * new kernel thread.
383 */
384 if (unlikely(wait_for_completion_killable(&done))) {
385 /*
386 * If I was SIGKILLed before kthreadd (or new kernel thread)
387 * calls complete(), leave the cleanup of this structure to
388 * that thread.
389 */
390 if (xchg(&create->done, NULL))
391 return ERR_PTR(-EINTR);
392 /*
393 * kthreadd (or new kernel thread) will call complete()
394 * shortly.
395 */
396 wait_for_completion(&done);
397 }
398 task = create->result;
399 if (!IS_ERR(task)) {
400 static const struct sched_param param = { .sched_priority = 0 };
401 char name[TASK_COMM_LEN];
402
403 /*
404 * task is already visible to other tasks, so updating
405 * COMM must be protected.
406 */
407 vsnprintf(name, sizeof(name), namefmt, args);
408 set_task_comm(task, name);
409 /*
410 * root may have changed our (kthreadd's) priority or CPU mask.
411 * The kernel thread should not inherit these properties.
412 */
413 sched_setscheduler_nocheck(task, SCHED_NORMAL, ¶m);
414 set_cpus_allowed_ptr(task,
415 housekeeping_cpumask(HK_FLAG_KTHREAD));
416 }
417 kfree(create);
418 return task;
419 }
420
421 /**
422 * kthread_create_on_node - create a kthread.
423 * @threadfn: the function to run until signal_pending(current).
424 * @data: data ptr for @threadfn.
425 * @node: task and thread structures for the thread are allocated on this node
426 * @namefmt: printf-style name for the thread.
427 *
428 * Description: This helper function creates and names a kernel
429 * thread. The thread will be stopped: use wake_up_process() to start
430 * it. See also kthread_run(). The new thread has SCHED_NORMAL policy and
431 * is affine to all CPUs.
432 *
433 * If thread is going to be bound on a particular cpu, give its node
434 * in @node, to get NUMA affinity for kthread stack, or else give NUMA_NO_NODE.
435 * When woken, the thread will run @threadfn() with @data as its
436 * argument. @threadfn() can either call do_exit() directly if it is a
437 * standalone thread for which no one will call kthread_stop(), or
438 * return when 'kthread_should_stop()' is true (which means
439 * kthread_stop() has been called). The return value should be zero
440 * or a negative error number; it will be passed to kthread_stop().
441 *
442 * Returns a task_struct or ERR_PTR(-ENOMEM) or ERR_PTR(-EINTR).
443 */
kthread_create_on_node(int (* threadfn)(void * data),void * data,int node,const char namefmt[],...)444 struct task_struct *kthread_create_on_node(int (*threadfn)(void *data),
445 void *data, int node,
446 const char namefmt[],
447 ...)
448 {
449 struct task_struct *task;
450 va_list args;
451
452 va_start(args, namefmt);
453 task = __kthread_create_on_node(threadfn, data, node, namefmt, args);
454 va_end(args);
455
456 return task;
457 }
458 EXPORT_SYMBOL(kthread_create_on_node);
459
__kthread_bind_mask(struct task_struct * p,const struct cpumask * mask,unsigned int state)460 static void __kthread_bind_mask(struct task_struct *p, const struct cpumask *mask, unsigned int state)
461 {
462 unsigned long flags;
463
464 if (!wait_task_inactive(p, state)) {
465 WARN_ON(1);
466 return;
467 }
468
469 /* It's safe because the task is inactive. */
470 raw_spin_lock_irqsave(&p->pi_lock, flags);
471 do_set_cpus_allowed(p, mask);
472 p->flags |= PF_NO_SETAFFINITY;
473 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
474 }
475
__kthread_bind(struct task_struct * p,unsigned int cpu,unsigned int state)476 static void __kthread_bind(struct task_struct *p, unsigned int cpu, unsigned int state)
477 {
478 __kthread_bind_mask(p, cpumask_of(cpu), state);
479 }
480
kthread_bind_mask(struct task_struct * p,const struct cpumask * mask)481 void kthread_bind_mask(struct task_struct *p, const struct cpumask *mask)
482 {
483 __kthread_bind_mask(p, mask, TASK_UNINTERRUPTIBLE);
484 }
485 EXPORT_SYMBOL_GPL(kthread_bind_mask);
486
487 /**
488 * kthread_bind - bind a just-created kthread to a cpu.
489 * @p: thread created by kthread_create().
490 * @cpu: cpu (might not be online, must be possible) for @k to run on.
491 *
492 * Description: This function is equivalent to set_cpus_allowed(),
493 * except that @cpu doesn't need to be online, and the thread must be
494 * stopped (i.e., just returned from kthread_create()).
495 */
kthread_bind(struct task_struct * p,unsigned int cpu)496 void kthread_bind(struct task_struct *p, unsigned int cpu)
497 {
498 __kthread_bind(p, cpu, TASK_UNINTERRUPTIBLE);
499 }
500 EXPORT_SYMBOL(kthread_bind);
501
502 /**
503 * kthread_create_on_cpu - Create a cpu bound kthread
504 * @threadfn: the function to run until signal_pending(current).
505 * @data: data ptr for @threadfn.
506 * @cpu: The cpu on which the thread should be bound,
507 * @namefmt: printf-style name for the thread. Format is restricted
508 * to "name.*%u". Code fills in cpu number.
509 *
510 * Description: This helper function creates and names a kernel thread
511 */
kthread_create_on_cpu(int (* threadfn)(void * data),void * data,unsigned int cpu,const char * namefmt)512 struct task_struct *kthread_create_on_cpu(int (*threadfn)(void *data),
513 void *data, unsigned int cpu,
514 const char *namefmt)
515 {
516 struct task_struct *p;
517
518 p = kthread_create_on_node(threadfn, data, cpu_to_node(cpu), namefmt,
519 cpu);
520 if (IS_ERR(p))
521 return p;
522 kthread_bind(p, cpu);
523 /* CPU hotplug need to bind once again when unparking the thread. */
524 to_kthread(p)->cpu = cpu;
525 return p;
526 }
527 EXPORT_SYMBOL(kthread_create_on_cpu);
528
kthread_set_per_cpu(struct task_struct * k,int cpu)529 void kthread_set_per_cpu(struct task_struct *k, int cpu)
530 {
531 struct kthread *kthread = to_kthread(k);
532 if (!kthread)
533 return;
534
535 WARN_ON_ONCE(!(k->flags & PF_NO_SETAFFINITY));
536
537 if (cpu < 0) {
538 clear_bit(KTHREAD_IS_PER_CPU, &kthread->flags);
539 return;
540 }
541
542 kthread->cpu = cpu;
543 set_bit(KTHREAD_IS_PER_CPU, &kthread->flags);
544 }
545 EXPORT_SYMBOL_GPL(kthread_set_per_cpu);
546
kthread_is_per_cpu(struct task_struct * p)547 bool kthread_is_per_cpu(struct task_struct *p)
548 {
549 struct kthread *kthread = __to_kthread(p);
550 if (!kthread)
551 return false;
552
553 return test_bit(KTHREAD_IS_PER_CPU, &kthread->flags);
554 }
555
556 /**
557 * kthread_unpark - unpark a thread created by kthread_create().
558 * @k: thread created by kthread_create().
559 *
560 * Sets kthread_should_park() for @k to return false, wakes it, and
561 * waits for it to return. If the thread is marked percpu then its
562 * bound to the cpu again.
563 */
kthread_unpark(struct task_struct * k)564 void kthread_unpark(struct task_struct *k)
565 {
566 struct kthread *kthread = to_kthread(k);
567
568 /*
569 * Newly created kthread was parked when the CPU was offline.
570 * The binding was lost and we need to set it again.
571 */
572 if (test_bit(KTHREAD_IS_PER_CPU, &kthread->flags))
573 __kthread_bind(k, kthread->cpu, TASK_PARKED);
574
575 clear_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
576 /*
577 * __kthread_parkme() will either see !SHOULD_PARK or get the wakeup.
578 */
579 wake_up_state(k, TASK_PARKED);
580 }
581 EXPORT_SYMBOL_GPL(kthread_unpark);
582
583 /**
584 * kthread_park - park a thread created by kthread_create().
585 * @k: thread created by kthread_create().
586 *
587 * Sets kthread_should_park() for @k to return true, wakes it, and
588 * waits for it to return. This can also be called after kthread_create()
589 * instead of calling wake_up_process(): the thread will park without
590 * calling threadfn().
591 *
592 * Returns 0 if the thread is parked, -ENOSYS if the thread exited.
593 * If called by the kthread itself just the park bit is set.
594 */
kthread_park(struct task_struct * k)595 int kthread_park(struct task_struct *k)
596 {
597 struct kthread *kthread = to_kthread(k);
598
599 if (WARN_ON(k->flags & PF_EXITING))
600 return -ENOSYS;
601
602 if (WARN_ON_ONCE(test_bit(KTHREAD_SHOULD_PARK, &kthread->flags)))
603 return -EBUSY;
604
605 set_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
606 if (k != current) {
607 wake_up_process(k);
608 /*
609 * Wait for __kthread_parkme() to complete(), this means we
610 * _will_ have TASK_PARKED and are about to call schedule().
611 */
612 wait_for_completion(&kthread->parked);
613 /*
614 * Now wait for that schedule() to complete and the task to
615 * get scheduled out.
616 */
617 WARN_ON_ONCE(!wait_task_inactive(k, TASK_PARKED));
618 }
619
620 return 0;
621 }
622 EXPORT_SYMBOL_GPL(kthread_park);
623
624 /**
625 * kthread_stop - stop a thread created by kthread_create().
626 * @k: thread created by kthread_create().
627 *
628 * Sets kthread_should_stop() for @k to return true, wakes it, and
629 * waits for it to exit. This can also be called after kthread_create()
630 * instead of calling wake_up_process(): the thread will exit without
631 * calling threadfn().
632 *
633 * If threadfn() may call do_exit() itself, the caller must ensure
634 * task_struct can't go away.
635 *
636 * Returns the result of threadfn(), or %-EINTR if wake_up_process()
637 * was never called.
638 */
kthread_stop(struct task_struct * k)639 int kthread_stop(struct task_struct *k)
640 {
641 struct kthread *kthread;
642 int ret;
643
644 trace_sched_kthread_stop(k);
645
646 get_task_struct(k);
647 kthread = to_kthread(k);
648 set_bit(KTHREAD_SHOULD_STOP, &kthread->flags);
649 kthread_unpark(k);
650 wake_up_process(k);
651 wait_for_completion(&kthread->exited);
652 ret = k->exit_code;
653 put_task_struct(k);
654
655 trace_sched_kthread_stop_ret(ret);
656 return ret;
657 }
658 EXPORT_SYMBOL(kthread_stop);
659
kthreadd(void * unused)660 int kthreadd(void *unused)
661 {
662 struct task_struct *tsk = current;
663
664 /* Setup a clean context for our children to inherit. */
665 set_task_comm(tsk, "kthreadd");
666 ignore_signals(tsk);
667 set_cpus_allowed_ptr(tsk, housekeeping_cpumask(HK_FLAG_KTHREAD));
668 set_mems_allowed(node_states[N_MEMORY]);
669
670 current->flags |= PF_NOFREEZE;
671 cgroup_init_kthreadd();
672
673 for (;;) {
674 set_current_state(TASK_INTERRUPTIBLE);
675 if (list_empty(&kthread_create_list))
676 schedule();
677 __set_current_state(TASK_RUNNING);
678
679 spin_lock(&kthread_create_lock);
680 while (!list_empty(&kthread_create_list)) {
681 struct kthread_create_info *create;
682
683 create = list_entry(kthread_create_list.next,
684 struct kthread_create_info, list);
685 list_del_init(&create->list);
686 spin_unlock(&kthread_create_lock);
687
688 create_kthread(create);
689
690 spin_lock(&kthread_create_lock);
691 }
692 spin_unlock(&kthread_create_lock);
693 }
694
695 return 0;
696 }
697
__kthread_init_worker(struct kthread_worker * worker,const char * name,struct lock_class_key * key)698 void __kthread_init_worker(struct kthread_worker *worker,
699 const char *name,
700 struct lock_class_key *key)
701 {
702 memset(worker, 0, sizeof(struct kthread_worker));
703 raw_spin_lock_init(&worker->lock);
704 lockdep_set_class_and_name(&worker->lock, key, name);
705 INIT_LIST_HEAD(&worker->work_list);
706 INIT_LIST_HEAD(&worker->delayed_work_list);
707 }
708 EXPORT_SYMBOL_GPL(__kthread_init_worker);
709
710 /**
711 * kthread_worker_fn - kthread function to process kthread_worker
712 * @worker_ptr: pointer to initialized kthread_worker
713 *
714 * This function implements the main cycle of kthread worker. It processes
715 * work_list until it is stopped with kthread_stop(). It sleeps when the queue
716 * is empty.
717 *
718 * The works are not allowed to keep any locks, disable preemption or interrupts
719 * when they finish. There is defined a safe point for freezing when one work
720 * finishes and before a new one is started.
721 *
722 * Also the works must not be handled by more than one worker at the same time,
723 * see also kthread_queue_work().
724 */
kthread_worker_fn(void * worker_ptr)725 int kthread_worker_fn(void *worker_ptr)
726 {
727 struct kthread_worker *worker = worker_ptr;
728 struct kthread_work *work;
729
730 /*
731 * FIXME: Update the check and remove the assignment when all kthread
732 * worker users are created using kthread_create_worker*() functions.
733 */
734 WARN_ON(worker->task && worker->task != current);
735 worker->task = current;
736
737 if (worker->flags & KTW_FREEZABLE)
738 set_freezable();
739
740 repeat:
741 set_current_state(TASK_INTERRUPTIBLE); /* mb paired w/ kthread_stop */
742
743 if (kthread_should_stop()) {
744 __set_current_state(TASK_RUNNING);
745 raw_spin_lock_irq(&worker->lock);
746 worker->task = NULL;
747 raw_spin_unlock_irq(&worker->lock);
748 return 0;
749 }
750
751 work = NULL;
752 raw_spin_lock_irq(&worker->lock);
753 if (!list_empty(&worker->work_list)) {
754 work = list_first_entry(&worker->work_list,
755 struct kthread_work, node);
756 list_del_init(&work->node);
757 }
758 worker->current_work = work;
759 raw_spin_unlock_irq(&worker->lock);
760
761 if (work) {
762 kthread_work_func_t func = work->func;
763 __set_current_state(TASK_RUNNING);
764 trace_sched_kthread_work_execute_start(work);
765 work->func(work);
766 /*
767 * Avoid dereferencing work after this point. The trace
768 * event only cares about the address.
769 */
770 trace_sched_kthread_work_execute_end(work, func);
771 } else if (!freezing(current))
772 schedule();
773
774 try_to_freeze();
775 cond_resched();
776 goto repeat;
777 }
778 EXPORT_SYMBOL_GPL(kthread_worker_fn);
779
780 static __printf(3, 0) struct kthread_worker *
__kthread_create_worker(int cpu,unsigned int flags,const char namefmt[],va_list args)781 __kthread_create_worker(int cpu, unsigned int flags,
782 const char namefmt[], va_list args)
783 {
784 struct kthread_worker *worker;
785 struct task_struct *task;
786 int node = NUMA_NO_NODE;
787
788 worker = kzalloc(sizeof(*worker), GFP_KERNEL);
789 if (!worker)
790 return ERR_PTR(-ENOMEM);
791
792 kthread_init_worker(worker);
793
794 if (cpu >= 0)
795 node = cpu_to_node(cpu);
796
797 task = __kthread_create_on_node(kthread_worker_fn, worker,
798 node, namefmt, args);
799 if (IS_ERR(task))
800 goto fail_task;
801
802 if (cpu >= 0)
803 kthread_bind(task, cpu);
804
805 worker->flags = flags;
806 worker->task = task;
807 wake_up_process(task);
808 return worker;
809
810 fail_task:
811 kfree(worker);
812 return ERR_CAST(task);
813 }
814
815 /**
816 * kthread_create_worker - create a kthread worker
817 * @flags: flags modifying the default behavior of the worker
818 * @namefmt: printf-style name for the kthread worker (task).
819 *
820 * Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
821 * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
822 * when the worker was SIGKILLed.
823 */
824 struct kthread_worker *
kthread_create_worker(unsigned int flags,const char namefmt[],...)825 kthread_create_worker(unsigned int flags, const char namefmt[], ...)
826 {
827 struct kthread_worker *worker;
828 va_list args;
829
830 va_start(args, namefmt);
831 worker = __kthread_create_worker(-1, flags, namefmt, args);
832 va_end(args);
833
834 return worker;
835 }
836 EXPORT_SYMBOL(kthread_create_worker);
837
838 /**
839 * kthread_create_worker_on_cpu - create a kthread worker and bind it
840 * to a given CPU and the associated NUMA node.
841 * @cpu: CPU number
842 * @flags: flags modifying the default behavior of the worker
843 * @namefmt: printf-style name for the kthread worker (task).
844 *
845 * Use a valid CPU number if you want to bind the kthread worker
846 * to the given CPU and the associated NUMA node.
847 *
848 * A good practice is to add the cpu number also into the worker name.
849 * For example, use kthread_create_worker_on_cpu(cpu, "helper/%d", cpu).
850 *
851 * CPU hotplug:
852 * The kthread worker API is simple and generic. It just provides a way
853 * to create, use, and destroy workers.
854 *
855 * It is up to the API user how to handle CPU hotplug. They have to decide
856 * how to handle pending work items, prevent queuing new ones, and
857 * restore the functionality when the CPU goes off and on. There are a
858 * few catches:
859 *
860 * - CPU affinity gets lost when it is scheduled on an offline CPU.
861 *
862 * - The worker might not exist when the CPU was off when the user
863 * created the workers.
864 *
865 * Good practice is to implement two CPU hotplug callbacks and to
866 * destroy/create the worker when the CPU goes down/up.
867 *
868 * Return:
869 * The pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
870 * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
871 * when the worker was SIGKILLed.
872 */
873 struct kthread_worker *
kthread_create_worker_on_cpu(int cpu,unsigned int flags,const char namefmt[],...)874 kthread_create_worker_on_cpu(int cpu, unsigned int flags,
875 const char namefmt[], ...)
876 {
877 struct kthread_worker *worker;
878 va_list args;
879
880 va_start(args, namefmt);
881 worker = __kthread_create_worker(cpu, flags, namefmt, args);
882 va_end(args);
883
884 return worker;
885 }
886 EXPORT_SYMBOL(kthread_create_worker_on_cpu);
887
888 /*
889 * Returns true when the work could not be queued at the moment.
890 * It happens when it is already pending in a worker list
891 * or when it is being cancelled.
892 */
queuing_blocked(struct kthread_worker * worker,struct kthread_work * work)893 static inline bool queuing_blocked(struct kthread_worker *worker,
894 struct kthread_work *work)
895 {
896 lockdep_assert_held(&worker->lock);
897
898 return !list_empty(&work->node) || work->canceling;
899 }
900
kthread_insert_work_sanity_check(struct kthread_worker * worker,struct kthread_work * work)901 static void kthread_insert_work_sanity_check(struct kthread_worker *worker,
902 struct kthread_work *work)
903 {
904 lockdep_assert_held(&worker->lock);
905 WARN_ON_ONCE(!list_empty(&work->node));
906 /* Do not use a work with >1 worker, see kthread_queue_work() */
907 WARN_ON_ONCE(work->worker && work->worker != worker);
908 }
909
910 /* insert @work before @pos in @worker */
kthread_insert_work(struct kthread_worker * worker,struct kthread_work * work,struct list_head * pos)911 static void kthread_insert_work(struct kthread_worker *worker,
912 struct kthread_work *work,
913 struct list_head *pos)
914 {
915 kthread_insert_work_sanity_check(worker, work);
916
917 trace_sched_kthread_work_queue_work(worker, work);
918
919 list_add_tail(&work->node, pos);
920 work->worker = worker;
921 if (!worker->current_work && likely(worker->task))
922 wake_up_process(worker->task);
923 }
924
925 /**
926 * kthread_queue_work - queue a kthread_work
927 * @worker: target kthread_worker
928 * @work: kthread_work to queue
929 *
930 * Queue @work to work processor @task for async execution. @task
931 * must have been created with kthread_worker_create(). Returns %true
932 * if @work was successfully queued, %false if it was already pending.
933 *
934 * Reinitialize the work if it needs to be used by another worker.
935 * For example, when the worker was stopped and started again.
936 */
kthread_queue_work(struct kthread_worker * worker,struct kthread_work * work)937 bool kthread_queue_work(struct kthread_worker *worker,
938 struct kthread_work *work)
939 {
940 bool ret = false;
941 unsigned long flags;
942
943 raw_spin_lock_irqsave(&worker->lock, flags);
944 if (!queuing_blocked(worker, work)) {
945 kthread_insert_work(worker, work, &worker->work_list);
946 ret = true;
947 }
948 raw_spin_unlock_irqrestore(&worker->lock, flags);
949 return ret;
950 }
951 EXPORT_SYMBOL_GPL(kthread_queue_work);
952
953 /**
954 * kthread_delayed_work_timer_fn - callback that queues the associated kthread
955 * delayed work when the timer expires.
956 * @t: pointer to the expired timer
957 *
958 * The format of the function is defined by struct timer_list.
959 * It should have been called from irqsafe timer with irq already off.
960 */
kthread_delayed_work_timer_fn(struct timer_list * t)961 void kthread_delayed_work_timer_fn(struct timer_list *t)
962 {
963 struct kthread_delayed_work *dwork = from_timer(dwork, t, timer);
964 struct kthread_work *work = &dwork->work;
965 struct kthread_worker *worker = work->worker;
966 unsigned long flags;
967
968 /*
969 * This might happen when a pending work is reinitialized.
970 * It means that it is used a wrong way.
971 */
972 if (WARN_ON_ONCE(!worker))
973 return;
974
975 raw_spin_lock_irqsave(&worker->lock, flags);
976 /* Work must not be used with >1 worker, see kthread_queue_work(). */
977 WARN_ON_ONCE(work->worker != worker);
978
979 /* Move the work from worker->delayed_work_list. */
980 WARN_ON_ONCE(list_empty(&work->node));
981 list_del_init(&work->node);
982 if (!work->canceling)
983 kthread_insert_work(worker, work, &worker->work_list);
984
985 raw_spin_unlock_irqrestore(&worker->lock, flags);
986 }
987 EXPORT_SYMBOL(kthread_delayed_work_timer_fn);
988
__kthread_queue_delayed_work(struct kthread_worker * worker,struct kthread_delayed_work * dwork,unsigned long delay)989 static void __kthread_queue_delayed_work(struct kthread_worker *worker,
990 struct kthread_delayed_work *dwork,
991 unsigned long delay)
992 {
993 struct timer_list *timer = &dwork->timer;
994 struct kthread_work *work = &dwork->work;
995
996 WARN_ON_FUNCTION_MISMATCH(timer->function,
997 kthread_delayed_work_timer_fn);
998
999 /*
1000 * If @delay is 0, queue @dwork->work immediately. This is for
1001 * both optimization and correctness. The earliest @timer can
1002 * expire is on the closest next tick and delayed_work users depend
1003 * on that there's no such delay when @delay is 0.
1004 */
1005 if (!delay) {
1006 kthread_insert_work(worker, work, &worker->work_list);
1007 return;
1008 }
1009
1010 /* Be paranoid and try to detect possible races already now. */
1011 kthread_insert_work_sanity_check(worker, work);
1012
1013 list_add(&work->node, &worker->delayed_work_list);
1014 work->worker = worker;
1015 timer->expires = jiffies + delay;
1016 add_timer(timer);
1017 }
1018
1019 /**
1020 * kthread_queue_delayed_work - queue the associated kthread work
1021 * after a delay.
1022 * @worker: target kthread_worker
1023 * @dwork: kthread_delayed_work to queue
1024 * @delay: number of jiffies to wait before queuing
1025 *
1026 * If the work has not been pending it starts a timer that will queue
1027 * the work after the given @delay. If @delay is zero, it queues the
1028 * work immediately.
1029 *
1030 * Return: %false if the @work has already been pending. It means that
1031 * either the timer was running or the work was queued. It returns %true
1032 * otherwise.
1033 */
kthread_queue_delayed_work(struct kthread_worker * worker,struct kthread_delayed_work * dwork,unsigned long delay)1034 bool kthread_queue_delayed_work(struct kthread_worker *worker,
1035 struct kthread_delayed_work *dwork,
1036 unsigned long delay)
1037 {
1038 struct kthread_work *work = &dwork->work;
1039 unsigned long flags;
1040 bool ret = false;
1041
1042 raw_spin_lock_irqsave(&worker->lock, flags);
1043
1044 if (!queuing_blocked(worker, work)) {
1045 __kthread_queue_delayed_work(worker, dwork, delay);
1046 ret = true;
1047 }
1048
1049 raw_spin_unlock_irqrestore(&worker->lock, flags);
1050 return ret;
1051 }
1052 EXPORT_SYMBOL_GPL(kthread_queue_delayed_work);
1053
1054 struct kthread_flush_work {
1055 struct kthread_work work;
1056 struct completion done;
1057 };
1058
kthread_flush_work_fn(struct kthread_work * work)1059 static void kthread_flush_work_fn(struct kthread_work *work)
1060 {
1061 struct kthread_flush_work *fwork =
1062 container_of(work, struct kthread_flush_work, work);
1063 complete(&fwork->done);
1064 }
1065
1066 /**
1067 * kthread_flush_work - flush a kthread_work
1068 * @work: work to flush
1069 *
1070 * If @work is queued or executing, wait for it to finish execution.
1071 */
kthread_flush_work(struct kthread_work * work)1072 void kthread_flush_work(struct kthread_work *work)
1073 {
1074 struct kthread_flush_work fwork = {
1075 KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
1076 COMPLETION_INITIALIZER_ONSTACK(fwork.done),
1077 };
1078 struct kthread_worker *worker;
1079 bool noop = false;
1080
1081 worker = work->worker;
1082 if (!worker)
1083 return;
1084
1085 raw_spin_lock_irq(&worker->lock);
1086 /* Work must not be used with >1 worker, see kthread_queue_work(). */
1087 WARN_ON_ONCE(work->worker != worker);
1088
1089 if (!list_empty(&work->node))
1090 kthread_insert_work(worker, &fwork.work, work->node.next);
1091 else if (worker->current_work == work)
1092 kthread_insert_work(worker, &fwork.work,
1093 worker->work_list.next);
1094 else
1095 noop = true;
1096
1097 raw_spin_unlock_irq(&worker->lock);
1098
1099 if (!noop)
1100 wait_for_completion(&fwork.done);
1101 }
1102 EXPORT_SYMBOL_GPL(kthread_flush_work);
1103
1104 /*
1105 * Make sure that the timer is neither set nor running and could
1106 * not manipulate the work list_head any longer.
1107 *
1108 * The function is called under worker->lock. The lock is temporary
1109 * released but the timer can't be set again in the meantime.
1110 */
kthread_cancel_delayed_work_timer(struct kthread_work * work,unsigned long * flags)1111 static void kthread_cancel_delayed_work_timer(struct kthread_work *work,
1112 unsigned long *flags)
1113 {
1114 struct kthread_delayed_work *dwork =
1115 container_of(work, struct kthread_delayed_work, work);
1116 struct kthread_worker *worker = work->worker;
1117
1118 /*
1119 * del_timer_sync() must be called to make sure that the timer
1120 * callback is not running. The lock must be temporary released
1121 * to avoid a deadlock with the callback. In the meantime,
1122 * any queuing is blocked by setting the canceling counter.
1123 */
1124 work->canceling++;
1125 raw_spin_unlock_irqrestore(&worker->lock, *flags);
1126 del_timer_sync(&dwork->timer);
1127 raw_spin_lock_irqsave(&worker->lock, *flags);
1128 work->canceling--;
1129 }
1130
1131 /*
1132 * This function removes the work from the worker queue.
1133 *
1134 * It is called under worker->lock. The caller must make sure that
1135 * the timer used by delayed work is not running, e.g. by calling
1136 * kthread_cancel_delayed_work_timer().
1137 *
1138 * The work might still be in use when this function finishes. See the
1139 * current_work proceed by the worker.
1140 *
1141 * Return: %true if @work was pending and successfully canceled,
1142 * %false if @work was not pending
1143 */
__kthread_cancel_work(struct kthread_work * work)1144 static bool __kthread_cancel_work(struct kthread_work *work)
1145 {
1146 /*
1147 * Try to remove the work from a worker list. It might either
1148 * be from worker->work_list or from worker->delayed_work_list.
1149 */
1150 if (!list_empty(&work->node)) {
1151 list_del_init(&work->node);
1152 return true;
1153 }
1154
1155 return false;
1156 }
1157
1158 /**
1159 * kthread_mod_delayed_work - modify delay of or queue a kthread delayed work
1160 * @worker: kthread worker to use
1161 * @dwork: kthread delayed work to queue
1162 * @delay: number of jiffies to wait before queuing
1163 *
1164 * If @dwork is idle, equivalent to kthread_queue_delayed_work(). Otherwise,
1165 * modify @dwork's timer so that it expires after @delay. If @delay is zero,
1166 * @work is guaranteed to be queued immediately.
1167 *
1168 * Return: %false if @dwork was idle and queued, %true otherwise.
1169 *
1170 * A special case is when the work is being canceled in parallel.
1171 * It might be caused either by the real kthread_cancel_delayed_work_sync()
1172 * or yet another kthread_mod_delayed_work() call. We let the other command
1173 * win and return %true here. The return value can be used for reference
1174 * counting and the number of queued works stays the same. Anyway, the caller
1175 * is supposed to synchronize these operations a reasonable way.
1176 *
1177 * This function is safe to call from any context including IRQ handler.
1178 * See __kthread_cancel_work() and kthread_delayed_work_timer_fn()
1179 * for details.
1180 */
kthread_mod_delayed_work(struct kthread_worker * worker,struct kthread_delayed_work * dwork,unsigned long delay)1181 bool kthread_mod_delayed_work(struct kthread_worker *worker,
1182 struct kthread_delayed_work *dwork,
1183 unsigned long delay)
1184 {
1185 struct kthread_work *work = &dwork->work;
1186 unsigned long flags;
1187 int ret;
1188
1189 raw_spin_lock_irqsave(&worker->lock, flags);
1190
1191 /* Do not bother with canceling when never queued. */
1192 if (!work->worker) {
1193 ret = false;
1194 goto fast_queue;
1195 }
1196
1197 /* Work must not be used with >1 worker, see kthread_queue_work() */
1198 WARN_ON_ONCE(work->worker != worker);
1199
1200 /*
1201 * Temporary cancel the work but do not fight with another command
1202 * that is canceling the work as well.
1203 *
1204 * It is a bit tricky because of possible races with another
1205 * mod_delayed_work() and cancel_delayed_work() callers.
1206 *
1207 * The timer must be canceled first because worker->lock is released
1208 * when doing so. But the work can be removed from the queue (list)
1209 * only when it can be queued again so that the return value can
1210 * be used for reference counting.
1211 */
1212 kthread_cancel_delayed_work_timer(work, &flags);
1213 if (work->canceling) {
1214 /* The number of works in the queue does not change. */
1215 ret = true;
1216 goto out;
1217 }
1218 ret = __kthread_cancel_work(work);
1219
1220 fast_queue:
1221 __kthread_queue_delayed_work(worker, dwork, delay);
1222 out:
1223 raw_spin_unlock_irqrestore(&worker->lock, flags);
1224 return ret;
1225 }
1226 EXPORT_SYMBOL_GPL(kthread_mod_delayed_work);
1227
__kthread_cancel_work_sync(struct kthread_work * work,bool is_dwork)1228 static bool __kthread_cancel_work_sync(struct kthread_work *work, bool is_dwork)
1229 {
1230 struct kthread_worker *worker = work->worker;
1231 unsigned long flags;
1232 int ret = false;
1233
1234 if (!worker)
1235 goto out;
1236
1237 raw_spin_lock_irqsave(&worker->lock, flags);
1238 /* Work must not be used with >1 worker, see kthread_queue_work(). */
1239 WARN_ON_ONCE(work->worker != worker);
1240
1241 if (is_dwork)
1242 kthread_cancel_delayed_work_timer(work, &flags);
1243
1244 ret = __kthread_cancel_work(work);
1245
1246 if (worker->current_work != work)
1247 goto out_fast;
1248
1249 /*
1250 * The work is in progress and we need to wait with the lock released.
1251 * In the meantime, block any queuing by setting the canceling counter.
1252 */
1253 work->canceling++;
1254 raw_spin_unlock_irqrestore(&worker->lock, flags);
1255 kthread_flush_work(work);
1256 raw_spin_lock_irqsave(&worker->lock, flags);
1257 work->canceling--;
1258
1259 out_fast:
1260 raw_spin_unlock_irqrestore(&worker->lock, flags);
1261 out:
1262 return ret;
1263 }
1264
1265 /**
1266 * kthread_cancel_work_sync - cancel a kthread work and wait for it to finish
1267 * @work: the kthread work to cancel
1268 *
1269 * Cancel @work and wait for its execution to finish. This function
1270 * can be used even if the work re-queues itself. On return from this
1271 * function, @work is guaranteed to be not pending or executing on any CPU.
1272 *
1273 * kthread_cancel_work_sync(&delayed_work->work) must not be used for
1274 * delayed_work's. Use kthread_cancel_delayed_work_sync() instead.
1275 *
1276 * The caller must ensure that the worker on which @work was last
1277 * queued can't be destroyed before this function returns.
1278 *
1279 * Return: %true if @work was pending, %false otherwise.
1280 */
kthread_cancel_work_sync(struct kthread_work * work)1281 bool kthread_cancel_work_sync(struct kthread_work *work)
1282 {
1283 return __kthread_cancel_work_sync(work, false);
1284 }
1285 EXPORT_SYMBOL_GPL(kthread_cancel_work_sync);
1286
1287 /**
1288 * kthread_cancel_delayed_work_sync - cancel a kthread delayed work and
1289 * wait for it to finish.
1290 * @dwork: the kthread delayed work to cancel
1291 *
1292 * This is kthread_cancel_work_sync() for delayed works.
1293 *
1294 * Return: %true if @dwork was pending, %false otherwise.
1295 */
kthread_cancel_delayed_work_sync(struct kthread_delayed_work * dwork)1296 bool kthread_cancel_delayed_work_sync(struct kthread_delayed_work *dwork)
1297 {
1298 return __kthread_cancel_work_sync(&dwork->work, true);
1299 }
1300 EXPORT_SYMBOL_GPL(kthread_cancel_delayed_work_sync);
1301
1302 /**
1303 * kthread_flush_worker - flush all current works on a kthread_worker
1304 * @worker: worker to flush
1305 *
1306 * Wait until all currently executing or pending works on @worker are
1307 * finished.
1308 */
kthread_flush_worker(struct kthread_worker * worker)1309 void kthread_flush_worker(struct kthread_worker *worker)
1310 {
1311 struct kthread_flush_work fwork = {
1312 KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
1313 COMPLETION_INITIALIZER_ONSTACK(fwork.done),
1314 };
1315
1316 kthread_queue_work(worker, &fwork.work);
1317 wait_for_completion(&fwork.done);
1318 }
1319 EXPORT_SYMBOL_GPL(kthread_flush_worker);
1320
1321 /**
1322 * kthread_destroy_worker - destroy a kthread worker
1323 * @worker: worker to be destroyed
1324 *
1325 * Flush and destroy @worker. The simple flush is enough because the kthread
1326 * worker API is used only in trivial scenarios. There are no multi-step state
1327 * machines needed.
1328 */
kthread_destroy_worker(struct kthread_worker * worker)1329 void kthread_destroy_worker(struct kthread_worker *worker)
1330 {
1331 struct task_struct *task;
1332
1333 task = worker->task;
1334 if (WARN_ON(!task))
1335 return;
1336
1337 kthread_flush_worker(worker);
1338 kthread_stop(task);
1339 WARN_ON(!list_empty(&worker->work_list));
1340 kfree(worker);
1341 }
1342 EXPORT_SYMBOL(kthread_destroy_worker);
1343
1344 /**
1345 * kthread_use_mm - make the calling kthread operate on an address space
1346 * @mm: address space to operate on
1347 */
kthread_use_mm(struct mm_struct * mm)1348 void kthread_use_mm(struct mm_struct *mm)
1349 {
1350 struct mm_struct *active_mm;
1351 struct task_struct *tsk = current;
1352
1353 WARN_ON_ONCE(!(tsk->flags & PF_KTHREAD));
1354 WARN_ON_ONCE(tsk->mm);
1355
1356 task_lock(tsk);
1357 /* Hold off tlb flush IPIs while switching mm's */
1358 local_irq_disable();
1359 active_mm = tsk->active_mm;
1360 if (active_mm != mm) {
1361 mmgrab(mm);
1362 tsk->active_mm = mm;
1363 }
1364 tsk->mm = mm;
1365 membarrier_update_current_mm(mm);
1366 switch_mm_irqs_off(active_mm, mm, tsk);
1367 local_irq_enable();
1368 task_unlock(tsk);
1369 #ifdef finish_arch_post_lock_switch
1370 finish_arch_post_lock_switch();
1371 #endif
1372
1373 /*
1374 * When a kthread starts operating on an address space, the loop
1375 * in membarrier_{private,global}_expedited() may not observe
1376 * that tsk->mm, and not issue an IPI. Membarrier requires a
1377 * memory barrier after storing to tsk->mm, before accessing
1378 * user-space memory. A full memory barrier for membarrier
1379 * {PRIVATE,GLOBAL}_EXPEDITED is implicitly provided by
1380 * mmdrop(), or explicitly with smp_mb().
1381 */
1382 if (active_mm != mm)
1383 mmdrop(active_mm);
1384 else
1385 smp_mb();
1386
1387 to_kthread(tsk)->oldfs = force_uaccess_begin();
1388 }
1389 EXPORT_SYMBOL_GPL(kthread_use_mm);
1390
1391 /**
1392 * kthread_unuse_mm - reverse the effect of kthread_use_mm()
1393 * @mm: address space to operate on
1394 */
kthread_unuse_mm(struct mm_struct * mm)1395 void kthread_unuse_mm(struct mm_struct *mm)
1396 {
1397 struct task_struct *tsk = current;
1398
1399 WARN_ON_ONCE(!(tsk->flags & PF_KTHREAD));
1400 WARN_ON_ONCE(!tsk->mm);
1401
1402 force_uaccess_end(to_kthread(tsk)->oldfs);
1403
1404 task_lock(tsk);
1405 /*
1406 * When a kthread stops operating on an address space, the loop
1407 * in membarrier_{private,global}_expedited() may not observe
1408 * that tsk->mm, and not issue an IPI. Membarrier requires a
1409 * memory barrier after accessing user-space memory, before
1410 * clearing tsk->mm.
1411 */
1412 smp_mb__after_spinlock();
1413 sync_mm_rss(mm);
1414 local_irq_disable();
1415 tsk->mm = NULL;
1416 membarrier_update_current_mm(NULL);
1417 /* active_mm is still 'mm' */
1418 enter_lazy_tlb(mm, tsk);
1419 local_irq_enable();
1420 task_unlock(tsk);
1421 }
1422 EXPORT_SYMBOL_GPL(kthread_unuse_mm);
1423
1424 #ifdef CONFIG_BLK_CGROUP
1425 /**
1426 * kthread_associate_blkcg - associate blkcg to current kthread
1427 * @css: the cgroup info
1428 *
1429 * Current thread must be a kthread. The thread is running jobs on behalf of
1430 * other threads. In some cases, we expect the jobs attach cgroup info of
1431 * original threads instead of that of current thread. This function stores
1432 * original thread's cgroup info in current kthread context for later
1433 * retrieval.
1434 */
kthread_associate_blkcg(struct cgroup_subsys_state * css)1435 void kthread_associate_blkcg(struct cgroup_subsys_state *css)
1436 {
1437 struct kthread *kthread;
1438
1439 if (!(current->flags & PF_KTHREAD))
1440 return;
1441 kthread = to_kthread(current);
1442 if (!kthread)
1443 return;
1444
1445 if (kthread->blkcg_css) {
1446 css_put(kthread->blkcg_css);
1447 kthread->blkcg_css = NULL;
1448 }
1449 if (css) {
1450 css_get(css);
1451 kthread->blkcg_css = css;
1452 }
1453 }
1454 EXPORT_SYMBOL(kthread_associate_blkcg);
1455
1456 /**
1457 * kthread_blkcg - get associated blkcg css of current kthread
1458 *
1459 * Current thread must be a kthread.
1460 */
kthread_blkcg(void)1461 struct cgroup_subsys_state *kthread_blkcg(void)
1462 {
1463 struct kthread *kthread;
1464
1465 if (current->flags & PF_KTHREAD) {
1466 kthread = to_kthread(current);
1467 if (kthread)
1468 return kthread->blkcg_css;
1469 }
1470 return NULL;
1471 }
1472 EXPORT_SYMBOL(kthread_blkcg);
1473 #endif
1474