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