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