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