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