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