]> bbs.cooldavid.org Git - net-next-2.6.git/blob - kernel/workqueue.c
workqueue: fix mayday_mask handling on UP
[net-next-2.6.git] / kernel / workqueue.c
1 /*
2  * linux/kernel/workqueue.c
3  *
4  * Generic mechanism for defining kernel helper threads for running
5  * arbitrary tasks in process context.
6  *
7  * Started by Ingo Molnar, Copyright (C) 2002
8  *
9  * Derived from the taskqueue/keventd code by:
10  *
11  *   David Woodhouse <dwmw2@infradead.org>
12  *   Andrew Morton
13  *   Kai Petzke <wpp@marie.physik.tu-berlin.de>
14  *   Theodore Ts'o <tytso@mit.edu>
15  *
16  * Made to use alloc_percpu by Christoph Lameter.
17  */
18
19 #include <linux/module.h>
20 #include <linux/kernel.h>
21 #include <linux/sched.h>
22 #include <linux/init.h>
23 #include <linux/signal.h>
24 #include <linux/completion.h>
25 #include <linux/workqueue.h>
26 #include <linux/slab.h>
27 #include <linux/cpu.h>
28 #include <linux/notifier.h>
29 #include <linux/kthread.h>
30 #include <linux/hardirq.h>
31 #include <linux/mempolicy.h>
32 #include <linux/freezer.h>
33 #include <linux/kallsyms.h>
34 #include <linux/debug_locks.h>
35 #include <linux/lockdep.h>
36 #include <linux/idr.h>
37
38 #include "workqueue_sched.h"
39
40 enum {
41         /* global_cwq flags */
42         GCWQ_MANAGE_WORKERS     = 1 << 0,       /* need to manage workers */
43         GCWQ_MANAGING_WORKERS   = 1 << 1,       /* managing workers */
44         GCWQ_DISASSOCIATED      = 1 << 2,       /* cpu can't serve workers */
45         GCWQ_FREEZING           = 1 << 3,       /* freeze in progress */
46         GCWQ_HIGHPRI_PENDING    = 1 << 4,       /* highpri works on queue */
47
48         /* worker flags */
49         WORKER_STARTED          = 1 << 0,       /* started */
50         WORKER_DIE              = 1 << 1,       /* die die die */
51         WORKER_IDLE             = 1 << 2,       /* is idle */
52         WORKER_PREP             = 1 << 3,       /* preparing to run works */
53         WORKER_ROGUE            = 1 << 4,       /* not bound to any cpu */
54         WORKER_REBIND           = 1 << 5,       /* mom is home, come back */
55         WORKER_CPU_INTENSIVE    = 1 << 6,       /* cpu intensive */
56         WORKER_UNBOUND          = 1 << 7,       /* worker is unbound */
57
58         WORKER_NOT_RUNNING      = WORKER_PREP | WORKER_ROGUE | WORKER_REBIND |
59                                   WORKER_CPU_INTENSIVE | WORKER_UNBOUND,
60
61         /* gcwq->trustee_state */
62         TRUSTEE_START           = 0,            /* start */
63         TRUSTEE_IN_CHARGE       = 1,            /* trustee in charge of gcwq */
64         TRUSTEE_BUTCHER         = 2,            /* butcher workers */
65         TRUSTEE_RELEASE         = 3,            /* release workers */
66         TRUSTEE_DONE            = 4,            /* trustee is done */
67
68         BUSY_WORKER_HASH_ORDER  = 6,            /* 64 pointers */
69         BUSY_WORKER_HASH_SIZE   = 1 << BUSY_WORKER_HASH_ORDER,
70         BUSY_WORKER_HASH_MASK   = BUSY_WORKER_HASH_SIZE - 1,
71
72         MAX_IDLE_WORKERS_RATIO  = 4,            /* 1/4 of busy can be idle */
73         IDLE_WORKER_TIMEOUT     = 300 * HZ,     /* keep idle ones for 5 mins */
74
75         MAYDAY_INITIAL_TIMEOUT  = HZ / 100,     /* call for help after 10ms */
76         MAYDAY_INTERVAL         = HZ / 10,      /* and then every 100ms */
77         CREATE_COOLDOWN         = HZ,           /* time to breath after fail */
78         TRUSTEE_COOLDOWN        = HZ / 10,      /* for trustee draining */
79
80         /*
81          * Rescue workers are used only on emergencies and shared by
82          * all cpus.  Give -20.
83          */
84         RESCUER_NICE_LEVEL      = -20,
85 };
86
87 /*
88  * Structure fields follow one of the following exclusion rules.
89  *
90  * I: Set during initialization and read-only afterwards.
91  *
92  * P: Preemption protected.  Disabling preemption is enough and should
93  *    only be modified and accessed from the local cpu.
94  *
95  * L: gcwq->lock protected.  Access with gcwq->lock held.
96  *
97  * X: During normal operation, modification requires gcwq->lock and
98  *    should be done only from local cpu.  Either disabling preemption
99  *    on local cpu or grabbing gcwq->lock is enough for read access.
100  *    If GCWQ_DISASSOCIATED is set, it's identical to L.
101  *
102  * F: wq->flush_mutex protected.
103  *
104  * W: workqueue_lock protected.
105  */
106
107 struct global_cwq;
108
109 /*
110  * The poor guys doing the actual heavy lifting.  All on-duty workers
111  * are either serving the manager role, on idle list or on busy hash.
112  */
113 struct worker {
114         /* on idle list while idle, on busy hash table while busy */
115         union {
116                 struct list_head        entry;  /* L: while idle */
117                 struct hlist_node       hentry; /* L: while busy */
118         };
119
120         struct work_struct      *current_work;  /* L: work being processed */
121         struct cpu_workqueue_struct *current_cwq; /* L: current_work's cwq */
122         struct list_head        scheduled;      /* L: scheduled works */
123         struct task_struct      *task;          /* I: worker task */
124         struct global_cwq       *gcwq;          /* I: the associated gcwq */
125         /* 64 bytes boundary on 64bit, 32 on 32bit */
126         unsigned long           last_active;    /* L: last active timestamp */
127         unsigned int            flags;          /* X: flags */
128         int                     id;             /* I: worker id */
129         struct work_struct      rebind_work;    /* L: rebind worker to cpu */
130 };
131
132 /*
133  * Global per-cpu workqueue.  There's one and only one for each cpu
134  * and all works are queued and processed here regardless of their
135  * target workqueues.
136  */
137 struct global_cwq {
138         spinlock_t              lock;           /* the gcwq lock */
139         struct list_head        worklist;       /* L: list of pending works */
140         unsigned int            cpu;            /* I: the associated cpu */
141         unsigned int            flags;          /* L: GCWQ_* flags */
142
143         int                     nr_workers;     /* L: total number of workers */
144         int                     nr_idle;        /* L: currently idle ones */
145
146         /* workers are chained either in the idle_list or busy_hash */
147         struct list_head        idle_list;      /* X: list of idle workers */
148         struct hlist_head       busy_hash[BUSY_WORKER_HASH_SIZE];
149                                                 /* L: hash of busy workers */
150
151         struct timer_list       idle_timer;     /* L: worker idle timeout */
152         struct timer_list       mayday_timer;   /* L: SOS timer for dworkers */
153
154         struct ida              worker_ida;     /* L: for worker IDs */
155
156         struct task_struct      *trustee;       /* L: for gcwq shutdown */
157         unsigned int            trustee_state;  /* L: trustee state */
158         wait_queue_head_t       trustee_wait;   /* trustee wait */
159         struct worker           *first_idle;    /* L: first idle worker */
160 } ____cacheline_aligned_in_smp;
161
162 /*
163  * The per-CPU workqueue.  The lower WORK_STRUCT_FLAG_BITS of
164  * work_struct->data are used for flags and thus cwqs need to be
165  * aligned at two's power of the number of flag bits.
166  */
167 struct cpu_workqueue_struct {
168         struct global_cwq       *gcwq;          /* I: the associated gcwq */
169         struct workqueue_struct *wq;            /* I: the owning workqueue */
170         int                     work_color;     /* L: current color */
171         int                     flush_color;    /* L: flushing color */
172         int                     nr_in_flight[WORK_NR_COLORS];
173                                                 /* L: nr of in_flight works */
174         int                     nr_active;      /* L: nr of active works */
175         int                     max_active;     /* L: max active works */
176         struct list_head        delayed_works;  /* L: delayed works */
177 };
178
179 /*
180  * Structure used to wait for workqueue flush.
181  */
182 struct wq_flusher {
183         struct list_head        list;           /* F: list of flushers */
184         int                     flush_color;    /* F: flush color waiting for */
185         struct completion       done;           /* flush completion */
186 };
187
188 /*
189  * All cpumasks are assumed to be always set on UP and thus can't be
190  * used to determine whether there's something to be done.
191  */
192 #ifdef CONFIG_SMP
193 typedef cpumask_var_t mayday_mask_t;
194 #define mayday_test_and_set_cpu(cpu, mask)      \
195         cpumask_test_and_set_cpu((cpu), (mask))
196 #define mayday_clear_cpu(cpu, mask)             cpumask_clear_cpu((cpu), (mask))
197 #define for_each_mayday_cpu(cpu, mask)          for_each_cpu((cpu), (mask))
198 #define alloc_mayday_mask(maskp, gfp)           alloc_cpumask_var((maskp), (gfp))
199 #define free_mayday_mask(mask)                  free_cpumask_var((mask))
200 #else
201 typedef unsigned long mayday_mask_t;
202 #define mayday_test_and_set_cpu(cpu, mask)      test_and_set_bit(0, &(mask))
203 #define mayday_clear_cpu(cpu, mask)             clear_bit(0, &(mask))
204 #define for_each_mayday_cpu(cpu, mask)          if ((cpu) = 0, (mask))
205 #define alloc_mayday_mask(maskp, gfp)           true
206 #define free_mayday_mask(mask)                  do { } while (0)
207 #endif
208
209 /*
210  * The externally visible workqueue abstraction is an array of
211  * per-CPU workqueues:
212  */
213 struct workqueue_struct {
214         unsigned int            flags;          /* I: WQ_* flags */
215         union {
216                 struct cpu_workqueue_struct __percpu    *pcpu;
217                 struct cpu_workqueue_struct             *single;
218                 unsigned long                           v;
219         } cpu_wq;                               /* I: cwq's */
220         struct list_head        list;           /* W: list of all workqueues */
221
222         struct mutex            flush_mutex;    /* protects wq flushing */
223         int                     work_color;     /* F: current work color */
224         int                     flush_color;    /* F: current flush color */
225         atomic_t                nr_cwqs_to_flush; /* flush in progress */
226         struct wq_flusher       *first_flusher; /* F: first flusher */
227         struct list_head        flusher_queue;  /* F: flush waiters */
228         struct list_head        flusher_overflow; /* F: flush overflow list */
229
230         mayday_mask_t           mayday_mask;    /* cpus requesting rescue */
231         struct worker           *rescuer;       /* I: rescue worker */
232
233         int                     saved_max_active; /* W: saved cwq max_active */
234         const char              *name;          /* I: workqueue name */
235 #ifdef CONFIG_LOCKDEP
236         struct lockdep_map      lockdep_map;
237 #endif
238 };
239
240 struct workqueue_struct *system_wq __read_mostly;
241 struct workqueue_struct *system_long_wq __read_mostly;
242 struct workqueue_struct *system_nrt_wq __read_mostly;
243 struct workqueue_struct *system_unbound_wq __read_mostly;
244 EXPORT_SYMBOL_GPL(system_wq);
245 EXPORT_SYMBOL_GPL(system_long_wq);
246 EXPORT_SYMBOL_GPL(system_nrt_wq);
247 EXPORT_SYMBOL_GPL(system_unbound_wq);
248
249 #define for_each_busy_worker(worker, i, pos, gcwq)                      \
250         for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)                     \
251                 hlist_for_each_entry(worker, pos, &gcwq->busy_hash[i], hentry)
252
253 static inline int __next_gcwq_cpu(int cpu, const struct cpumask *mask,
254                                   unsigned int sw)
255 {
256         if (cpu < nr_cpu_ids) {
257                 if (sw & 1) {
258                         cpu = cpumask_next(cpu, mask);
259                         if (cpu < nr_cpu_ids)
260                                 return cpu;
261                 }
262                 if (sw & 2)
263                         return WORK_CPU_UNBOUND;
264         }
265         return WORK_CPU_NONE;
266 }
267
268 static inline int __next_wq_cpu(int cpu, const struct cpumask *mask,
269                                 struct workqueue_struct *wq)
270 {
271         return __next_gcwq_cpu(cpu, mask, !(wq->flags & WQ_UNBOUND) ? 1 : 2);
272 }
273
274 #define for_each_gcwq_cpu(cpu)                                          \
275         for ((cpu) = __next_gcwq_cpu(-1, cpu_possible_mask, 3);         \
276              (cpu) < WORK_CPU_NONE;                                     \
277              (cpu) = __next_gcwq_cpu((cpu), cpu_possible_mask, 3))
278
279 #define for_each_online_gcwq_cpu(cpu)                                   \
280         for ((cpu) = __next_gcwq_cpu(-1, cpu_online_mask, 3);           \
281              (cpu) < WORK_CPU_NONE;                                     \
282              (cpu) = __next_gcwq_cpu((cpu), cpu_online_mask, 3))
283
284 #define for_each_cwq_cpu(cpu, wq)                                       \
285         for ((cpu) = __next_wq_cpu(-1, cpu_possible_mask, (wq));        \
286              (cpu) < WORK_CPU_NONE;                                     \
287              (cpu) = __next_wq_cpu((cpu), cpu_possible_mask, (wq)))
288
289 #ifdef CONFIG_DEBUG_OBJECTS_WORK
290
291 static struct debug_obj_descr work_debug_descr;
292
293 /*
294  * fixup_init is called when:
295  * - an active object is initialized
296  */
297 static int work_fixup_init(void *addr, enum debug_obj_state state)
298 {
299         struct work_struct *work = addr;
300
301         switch (state) {
302         case ODEBUG_STATE_ACTIVE:
303                 cancel_work_sync(work);
304                 debug_object_init(work, &work_debug_descr);
305                 return 1;
306         default:
307                 return 0;
308         }
309 }
310
311 /*
312  * fixup_activate is called when:
313  * - an active object is activated
314  * - an unknown object is activated (might be a statically initialized object)
315  */
316 static int work_fixup_activate(void *addr, enum debug_obj_state state)
317 {
318         struct work_struct *work = addr;
319
320         switch (state) {
321
322         case ODEBUG_STATE_NOTAVAILABLE:
323                 /*
324                  * This is not really a fixup. The work struct was
325                  * statically initialized. We just make sure that it
326                  * is tracked in the object tracker.
327                  */
328                 if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
329                         debug_object_init(work, &work_debug_descr);
330                         debug_object_activate(work, &work_debug_descr);
331                         return 0;
332                 }
333                 WARN_ON_ONCE(1);
334                 return 0;
335
336         case ODEBUG_STATE_ACTIVE:
337                 WARN_ON(1);
338
339         default:
340                 return 0;
341         }
342 }
343
344 /*
345  * fixup_free is called when:
346  * - an active object is freed
347  */
348 static int work_fixup_free(void *addr, enum debug_obj_state state)
349 {
350         struct work_struct *work = addr;
351
352         switch (state) {
353         case ODEBUG_STATE_ACTIVE:
354                 cancel_work_sync(work);
355                 debug_object_free(work, &work_debug_descr);
356                 return 1;
357         default:
358                 return 0;
359         }
360 }
361
362 static struct debug_obj_descr work_debug_descr = {
363         .name           = "work_struct",
364         .fixup_init     = work_fixup_init,
365         .fixup_activate = work_fixup_activate,
366         .fixup_free     = work_fixup_free,
367 };
368
369 static inline void debug_work_activate(struct work_struct *work)
370 {
371         debug_object_activate(work, &work_debug_descr);
372 }
373
374 static inline void debug_work_deactivate(struct work_struct *work)
375 {
376         debug_object_deactivate(work, &work_debug_descr);
377 }
378
379 void __init_work(struct work_struct *work, int onstack)
380 {
381         if (onstack)
382                 debug_object_init_on_stack(work, &work_debug_descr);
383         else
384                 debug_object_init(work, &work_debug_descr);
385 }
386 EXPORT_SYMBOL_GPL(__init_work);
387
388 void destroy_work_on_stack(struct work_struct *work)
389 {
390         debug_object_free(work, &work_debug_descr);
391 }
392 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
393
394 #else
395 static inline void debug_work_activate(struct work_struct *work) { }
396 static inline void debug_work_deactivate(struct work_struct *work) { }
397 #endif
398
399 /* Serializes the accesses to the list of workqueues. */
400 static DEFINE_SPINLOCK(workqueue_lock);
401 static LIST_HEAD(workqueues);
402 static bool workqueue_freezing;         /* W: have wqs started freezing? */
403
404 /*
405  * The almighty global cpu workqueues.  nr_running is the only field
406  * which is expected to be used frequently by other cpus via
407  * try_to_wake_up().  Put it in a separate cacheline.
408  */
409 static DEFINE_PER_CPU(struct global_cwq, global_cwq);
410 static DEFINE_PER_CPU_SHARED_ALIGNED(atomic_t, gcwq_nr_running);
411
412 /*
413  * Global cpu workqueue and nr_running counter for unbound gcwq.  The
414  * gcwq is always online, has GCWQ_DISASSOCIATED set, and all its
415  * workers have WORKER_UNBOUND set.
416  */
417 static struct global_cwq unbound_global_cwq;
418 static atomic_t unbound_gcwq_nr_running = ATOMIC_INIT(0);       /* always 0 */
419
420 static int worker_thread(void *__worker);
421
422 static struct global_cwq *get_gcwq(unsigned int cpu)
423 {
424         if (cpu != WORK_CPU_UNBOUND)
425                 return &per_cpu(global_cwq, cpu);
426         else
427                 return &unbound_global_cwq;
428 }
429
430 static atomic_t *get_gcwq_nr_running(unsigned int cpu)
431 {
432         if (cpu != WORK_CPU_UNBOUND)
433                 return &per_cpu(gcwq_nr_running, cpu);
434         else
435                 return &unbound_gcwq_nr_running;
436 }
437
438 static struct cpu_workqueue_struct *get_cwq(unsigned int cpu,
439                                             struct workqueue_struct *wq)
440 {
441         if (!(wq->flags & WQ_UNBOUND)) {
442                 if (likely(cpu < nr_cpu_ids)) {
443 #ifdef CONFIG_SMP
444                         return per_cpu_ptr(wq->cpu_wq.pcpu, cpu);
445 #else
446                         return wq->cpu_wq.single;
447 #endif
448                 }
449         } else if (likely(cpu == WORK_CPU_UNBOUND))
450                 return wq->cpu_wq.single;
451         return NULL;
452 }
453
454 static unsigned int work_color_to_flags(int color)
455 {
456         return color << WORK_STRUCT_COLOR_SHIFT;
457 }
458
459 static int get_work_color(struct work_struct *work)
460 {
461         return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
462                 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
463 }
464
465 static int work_next_color(int color)
466 {
467         return (color + 1) % WORK_NR_COLORS;
468 }
469
470 /*
471  * Work data points to the cwq while a work is on queue.  Once
472  * execution starts, it points to the cpu the work was last on.  This
473  * can be distinguished by comparing the data value against
474  * PAGE_OFFSET.
475  *
476  * set_work_{cwq|cpu}() and clear_work_data() can be used to set the
477  * cwq, cpu or clear work->data.  These functions should only be
478  * called while the work is owned - ie. while the PENDING bit is set.
479  *
480  * get_work_[g]cwq() can be used to obtain the gcwq or cwq
481  * corresponding to a work.  gcwq is available once the work has been
482  * queued anywhere after initialization.  cwq is available only from
483  * queueing until execution starts.
484  */
485 static inline void set_work_data(struct work_struct *work, unsigned long data,
486                                  unsigned long flags)
487 {
488         BUG_ON(!work_pending(work));
489         atomic_long_set(&work->data, data | flags | work_static(work));
490 }
491
492 static void set_work_cwq(struct work_struct *work,
493                          struct cpu_workqueue_struct *cwq,
494                          unsigned long extra_flags)
495 {
496         set_work_data(work, (unsigned long)cwq,
497                       WORK_STRUCT_PENDING | extra_flags);
498 }
499
500 static void set_work_cpu(struct work_struct *work, unsigned int cpu)
501 {
502         set_work_data(work, cpu << WORK_STRUCT_FLAG_BITS, WORK_STRUCT_PENDING);
503 }
504
505 static void clear_work_data(struct work_struct *work)
506 {
507         set_work_data(work, WORK_STRUCT_NO_CPU, 0);
508 }
509
510 static inline unsigned long get_work_data(struct work_struct *work)
511 {
512         return atomic_long_read(&work->data) & WORK_STRUCT_WQ_DATA_MASK;
513 }
514
515 static struct cpu_workqueue_struct *get_work_cwq(struct work_struct *work)
516 {
517         unsigned long data = get_work_data(work);
518
519         return data >= PAGE_OFFSET ? (void *)data : NULL;
520 }
521
522 static struct global_cwq *get_work_gcwq(struct work_struct *work)
523 {
524         unsigned long data = get_work_data(work);
525         unsigned int cpu;
526
527         if (data >= PAGE_OFFSET)
528                 return ((struct cpu_workqueue_struct *)data)->gcwq;
529
530         cpu = data >> WORK_STRUCT_FLAG_BITS;
531         if (cpu == WORK_CPU_NONE)
532                 return NULL;
533
534         BUG_ON(cpu >= nr_cpu_ids && cpu != WORK_CPU_UNBOUND);
535         return get_gcwq(cpu);
536 }
537
538 /*
539  * Policy functions.  These define the policies on how the global
540  * worker pool is managed.  Unless noted otherwise, these functions
541  * assume that they're being called with gcwq->lock held.
542  */
543
544 static bool __need_more_worker(struct global_cwq *gcwq)
545 {
546         return !atomic_read(get_gcwq_nr_running(gcwq->cpu)) ||
547                 gcwq->flags & GCWQ_HIGHPRI_PENDING;
548 }
549
550 /*
551  * Need to wake up a worker?  Called from anything but currently
552  * running workers.
553  */
554 static bool need_more_worker(struct global_cwq *gcwq)
555 {
556         return !list_empty(&gcwq->worklist) && __need_more_worker(gcwq);
557 }
558
559 /* Can I start working?  Called from busy but !running workers. */
560 static bool may_start_working(struct global_cwq *gcwq)
561 {
562         return gcwq->nr_idle;
563 }
564
565 /* Do I need to keep working?  Called from currently running workers. */
566 static bool keep_working(struct global_cwq *gcwq)
567 {
568         atomic_t *nr_running = get_gcwq_nr_running(gcwq->cpu);
569
570         return !list_empty(&gcwq->worklist) && atomic_read(nr_running) <= 1;
571 }
572
573 /* Do we need a new worker?  Called from manager. */
574 static bool need_to_create_worker(struct global_cwq *gcwq)
575 {
576         return need_more_worker(gcwq) && !may_start_working(gcwq);
577 }
578
579 /* Do I need to be the manager? */
580 static bool need_to_manage_workers(struct global_cwq *gcwq)
581 {
582         return need_to_create_worker(gcwq) || gcwq->flags & GCWQ_MANAGE_WORKERS;
583 }
584
585 /* Do we have too many workers and should some go away? */
586 static bool too_many_workers(struct global_cwq *gcwq)
587 {
588         bool managing = gcwq->flags & GCWQ_MANAGING_WORKERS;
589         int nr_idle = gcwq->nr_idle + managing; /* manager is considered idle */
590         int nr_busy = gcwq->nr_workers - nr_idle;
591
592         return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
593 }
594
595 /*
596  * Wake up functions.
597  */
598
599 /* Return the first worker.  Safe with preemption disabled */
600 static struct worker *first_worker(struct global_cwq *gcwq)
601 {
602         if (unlikely(list_empty(&gcwq->idle_list)))
603                 return NULL;
604
605         return list_first_entry(&gcwq->idle_list, struct worker, entry);
606 }
607
608 /**
609  * wake_up_worker - wake up an idle worker
610  * @gcwq: gcwq to wake worker for
611  *
612  * Wake up the first idle worker of @gcwq.
613  *
614  * CONTEXT:
615  * spin_lock_irq(gcwq->lock).
616  */
617 static void wake_up_worker(struct global_cwq *gcwq)
618 {
619         struct worker *worker = first_worker(gcwq);
620
621         if (likely(worker))
622                 wake_up_process(worker->task);
623 }
624
625 /**
626  * wq_worker_waking_up - a worker is waking up
627  * @task: task waking up
628  * @cpu: CPU @task is waking up to
629  *
630  * This function is called during try_to_wake_up() when a worker is
631  * being awoken.
632  *
633  * CONTEXT:
634  * spin_lock_irq(rq->lock)
635  */
636 void wq_worker_waking_up(struct task_struct *task, unsigned int cpu)
637 {
638         struct worker *worker = kthread_data(task);
639
640         if (likely(!(worker->flags & WORKER_NOT_RUNNING)))
641                 atomic_inc(get_gcwq_nr_running(cpu));
642 }
643
644 /**
645  * wq_worker_sleeping - a worker is going to sleep
646  * @task: task going to sleep
647  * @cpu: CPU in question, must be the current CPU number
648  *
649  * This function is called during schedule() when a busy worker is
650  * going to sleep.  Worker on the same cpu can be woken up by
651  * returning pointer to its task.
652  *
653  * CONTEXT:
654  * spin_lock_irq(rq->lock)
655  *
656  * RETURNS:
657  * Worker task on @cpu to wake up, %NULL if none.
658  */
659 struct task_struct *wq_worker_sleeping(struct task_struct *task,
660                                        unsigned int cpu)
661 {
662         struct worker *worker = kthread_data(task), *to_wakeup = NULL;
663         struct global_cwq *gcwq = get_gcwq(cpu);
664         atomic_t *nr_running = get_gcwq_nr_running(cpu);
665
666         if (unlikely(worker->flags & WORKER_NOT_RUNNING))
667                 return NULL;
668
669         /* this can only happen on the local cpu */
670         BUG_ON(cpu != raw_smp_processor_id());
671
672         /*
673          * The counterpart of the following dec_and_test, implied mb,
674          * worklist not empty test sequence is in insert_work().
675          * Please read comment there.
676          *
677          * NOT_RUNNING is clear.  This means that trustee is not in
678          * charge and we're running on the local cpu w/ rq lock held
679          * and preemption disabled, which in turn means that none else
680          * could be manipulating idle_list, so dereferencing idle_list
681          * without gcwq lock is safe.
682          */
683         if (atomic_dec_and_test(nr_running) && !list_empty(&gcwq->worklist))
684                 to_wakeup = first_worker(gcwq);
685         return to_wakeup ? to_wakeup->task : NULL;
686 }
687
688 /**
689  * worker_set_flags - set worker flags and adjust nr_running accordingly
690  * @worker: self
691  * @flags: flags to set
692  * @wakeup: wakeup an idle worker if necessary
693  *
694  * Set @flags in @worker->flags and adjust nr_running accordingly.  If
695  * nr_running becomes zero and @wakeup is %true, an idle worker is
696  * woken up.
697  *
698  * CONTEXT:
699  * spin_lock_irq(gcwq->lock)
700  */
701 static inline void worker_set_flags(struct worker *worker, unsigned int flags,
702                                     bool wakeup)
703 {
704         struct global_cwq *gcwq = worker->gcwq;
705
706         WARN_ON_ONCE(worker->task != current);
707
708         /*
709          * If transitioning into NOT_RUNNING, adjust nr_running and
710          * wake up an idle worker as necessary if requested by
711          * @wakeup.
712          */
713         if ((flags & WORKER_NOT_RUNNING) &&
714             !(worker->flags & WORKER_NOT_RUNNING)) {
715                 atomic_t *nr_running = get_gcwq_nr_running(gcwq->cpu);
716
717                 if (wakeup) {
718                         if (atomic_dec_and_test(nr_running) &&
719                             !list_empty(&gcwq->worklist))
720                                 wake_up_worker(gcwq);
721                 } else
722                         atomic_dec(nr_running);
723         }
724
725         worker->flags |= flags;
726 }
727
728 /**
729  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
730  * @worker: self
731  * @flags: flags to clear
732  *
733  * Clear @flags in @worker->flags and adjust nr_running accordingly.
734  *
735  * CONTEXT:
736  * spin_lock_irq(gcwq->lock)
737  */
738 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
739 {
740         struct global_cwq *gcwq = worker->gcwq;
741         unsigned int oflags = worker->flags;
742
743         WARN_ON_ONCE(worker->task != current);
744
745         worker->flags &= ~flags;
746
747         /* if transitioning out of NOT_RUNNING, increment nr_running */
748         if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
749                 if (!(worker->flags & WORKER_NOT_RUNNING))
750                         atomic_inc(get_gcwq_nr_running(gcwq->cpu));
751 }
752
753 /**
754  * busy_worker_head - return the busy hash head for a work
755  * @gcwq: gcwq of interest
756  * @work: work to be hashed
757  *
758  * Return hash head of @gcwq for @work.
759  *
760  * CONTEXT:
761  * spin_lock_irq(gcwq->lock).
762  *
763  * RETURNS:
764  * Pointer to the hash head.
765  */
766 static struct hlist_head *busy_worker_head(struct global_cwq *gcwq,
767                                            struct work_struct *work)
768 {
769         const int base_shift = ilog2(sizeof(struct work_struct));
770         unsigned long v = (unsigned long)work;
771
772         /* simple shift and fold hash, do we need something better? */
773         v >>= base_shift;
774         v += v >> BUSY_WORKER_HASH_ORDER;
775         v &= BUSY_WORKER_HASH_MASK;
776
777         return &gcwq->busy_hash[v];
778 }
779
780 /**
781  * __find_worker_executing_work - find worker which is executing a work
782  * @gcwq: gcwq of interest
783  * @bwh: hash head as returned by busy_worker_head()
784  * @work: work to find worker for
785  *
786  * Find a worker which is executing @work on @gcwq.  @bwh should be
787  * the hash head obtained by calling busy_worker_head() with the same
788  * work.
789  *
790  * CONTEXT:
791  * spin_lock_irq(gcwq->lock).
792  *
793  * RETURNS:
794  * Pointer to worker which is executing @work if found, NULL
795  * otherwise.
796  */
797 static struct worker *__find_worker_executing_work(struct global_cwq *gcwq,
798                                                    struct hlist_head *bwh,
799                                                    struct work_struct *work)
800 {
801         struct worker *worker;
802         struct hlist_node *tmp;
803
804         hlist_for_each_entry(worker, tmp, bwh, hentry)
805                 if (worker->current_work == work)
806                         return worker;
807         return NULL;
808 }
809
810 /**
811  * find_worker_executing_work - find worker which is executing a work
812  * @gcwq: gcwq of interest
813  * @work: work to find worker for
814  *
815  * Find a worker which is executing @work on @gcwq.  This function is
816  * identical to __find_worker_executing_work() except that this
817  * function calculates @bwh itself.
818  *
819  * CONTEXT:
820  * spin_lock_irq(gcwq->lock).
821  *
822  * RETURNS:
823  * Pointer to worker which is executing @work if found, NULL
824  * otherwise.
825  */
826 static struct worker *find_worker_executing_work(struct global_cwq *gcwq,
827                                                  struct work_struct *work)
828 {
829         return __find_worker_executing_work(gcwq, busy_worker_head(gcwq, work),
830                                             work);
831 }
832
833 /**
834  * gcwq_determine_ins_pos - find insertion position
835  * @gcwq: gcwq of interest
836  * @cwq: cwq a work is being queued for
837  *
838  * A work for @cwq is about to be queued on @gcwq, determine insertion
839  * position for the work.  If @cwq is for HIGHPRI wq, the work is
840  * queued at the head of the queue but in FIFO order with respect to
841  * other HIGHPRI works; otherwise, at the end of the queue.  This
842  * function also sets GCWQ_HIGHPRI_PENDING flag to hint @gcwq that
843  * there are HIGHPRI works pending.
844  *
845  * CONTEXT:
846  * spin_lock_irq(gcwq->lock).
847  *
848  * RETURNS:
849  * Pointer to inserstion position.
850  */
851 static inline struct list_head *gcwq_determine_ins_pos(struct global_cwq *gcwq,
852                                                struct cpu_workqueue_struct *cwq)
853 {
854         struct work_struct *twork;
855
856         if (likely(!(cwq->wq->flags & WQ_HIGHPRI)))
857                 return &gcwq->worklist;
858
859         list_for_each_entry(twork, &gcwq->worklist, entry) {
860                 struct cpu_workqueue_struct *tcwq = get_work_cwq(twork);
861
862                 if (!(tcwq->wq->flags & WQ_HIGHPRI))
863                         break;
864         }
865
866         gcwq->flags |= GCWQ_HIGHPRI_PENDING;
867         return &twork->entry;
868 }
869
870 /**
871  * insert_work - insert a work into gcwq
872  * @cwq: cwq @work belongs to
873  * @work: work to insert
874  * @head: insertion point
875  * @extra_flags: extra WORK_STRUCT_* flags to set
876  *
877  * Insert @work which belongs to @cwq into @gcwq after @head.
878  * @extra_flags is or'd to work_struct flags.
879  *
880  * CONTEXT:
881  * spin_lock_irq(gcwq->lock).
882  */
883 static void insert_work(struct cpu_workqueue_struct *cwq,
884                         struct work_struct *work, struct list_head *head,
885                         unsigned int extra_flags)
886 {
887         struct global_cwq *gcwq = cwq->gcwq;
888
889         /* we own @work, set data and link */
890         set_work_cwq(work, cwq, extra_flags);
891
892         /*
893          * Ensure that we get the right work->data if we see the
894          * result of list_add() below, see try_to_grab_pending().
895          */
896         smp_wmb();
897
898         list_add_tail(&work->entry, head);
899
900         /*
901          * Ensure either worker_sched_deactivated() sees the above
902          * list_add_tail() or we see zero nr_running to avoid workers
903          * lying around lazily while there are works to be processed.
904          */
905         smp_mb();
906
907         if (__need_more_worker(gcwq))
908                 wake_up_worker(gcwq);
909 }
910
911 static void __queue_work(unsigned int cpu, struct workqueue_struct *wq,
912                          struct work_struct *work)
913 {
914         struct global_cwq *gcwq;
915         struct cpu_workqueue_struct *cwq;
916         struct list_head *worklist;
917         unsigned long flags;
918
919         debug_work_activate(work);
920
921         /* determine gcwq to use */
922         if (!(wq->flags & WQ_UNBOUND)) {
923                 struct global_cwq *last_gcwq;
924
925                 if (unlikely(cpu == WORK_CPU_UNBOUND))
926                         cpu = raw_smp_processor_id();
927
928                 /*
929                  * It's multi cpu.  If @wq is non-reentrant and @work
930                  * was previously on a different cpu, it might still
931                  * be running there, in which case the work needs to
932                  * be queued on that cpu to guarantee non-reentrance.
933                  */
934                 gcwq = get_gcwq(cpu);
935                 if (wq->flags & WQ_NON_REENTRANT &&
936                     (last_gcwq = get_work_gcwq(work)) && last_gcwq != gcwq) {
937                         struct worker *worker;
938
939                         spin_lock_irqsave(&last_gcwq->lock, flags);
940
941                         worker = find_worker_executing_work(last_gcwq, work);
942
943                         if (worker && worker->current_cwq->wq == wq)
944                                 gcwq = last_gcwq;
945                         else {
946                                 /* meh... not running there, queue here */
947                                 spin_unlock_irqrestore(&last_gcwq->lock, flags);
948                                 spin_lock_irqsave(&gcwq->lock, flags);
949                         }
950                 } else
951                         spin_lock_irqsave(&gcwq->lock, flags);
952         } else {
953                 gcwq = get_gcwq(WORK_CPU_UNBOUND);
954                 spin_lock_irqsave(&gcwq->lock, flags);
955         }
956
957         /* gcwq determined, get cwq and queue */
958         cwq = get_cwq(gcwq->cpu, wq);
959
960         BUG_ON(!list_empty(&work->entry));
961
962         cwq->nr_in_flight[cwq->work_color]++;
963
964         if (likely(cwq->nr_active < cwq->max_active)) {
965                 cwq->nr_active++;
966                 worklist = gcwq_determine_ins_pos(gcwq, cwq);
967         } else
968                 worklist = &cwq->delayed_works;
969
970         insert_work(cwq, work, worklist, work_color_to_flags(cwq->work_color));
971
972         spin_unlock_irqrestore(&gcwq->lock, flags);
973 }
974
975 /**
976  * queue_work - queue work on a workqueue
977  * @wq: workqueue to use
978  * @work: work to queue
979  *
980  * Returns 0 if @work was already on a queue, non-zero otherwise.
981  *
982  * We queue the work to the CPU on which it was submitted, but if the CPU dies
983  * it can be processed by another CPU.
984  */
985 int queue_work(struct workqueue_struct *wq, struct work_struct *work)
986 {
987         int ret;
988
989         ret = queue_work_on(get_cpu(), wq, work);
990         put_cpu();
991
992         return ret;
993 }
994 EXPORT_SYMBOL_GPL(queue_work);
995
996 /**
997  * queue_work_on - queue work on specific cpu
998  * @cpu: CPU number to execute work on
999  * @wq: workqueue to use
1000  * @work: work to queue
1001  *
1002  * Returns 0 if @work was already on a queue, non-zero otherwise.
1003  *
1004  * We queue the work to a specific CPU, the caller must ensure it
1005  * can't go away.
1006  */
1007 int
1008 queue_work_on(int cpu, struct workqueue_struct *wq, struct work_struct *work)
1009 {
1010         int ret = 0;
1011
1012         if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1013                 __queue_work(cpu, wq, work);
1014                 ret = 1;
1015         }
1016         return ret;
1017 }
1018 EXPORT_SYMBOL_GPL(queue_work_on);
1019
1020 static void delayed_work_timer_fn(unsigned long __data)
1021 {
1022         struct delayed_work *dwork = (struct delayed_work *)__data;
1023         struct cpu_workqueue_struct *cwq = get_work_cwq(&dwork->work);
1024
1025         __queue_work(smp_processor_id(), cwq->wq, &dwork->work);
1026 }
1027
1028 /**
1029  * queue_delayed_work - queue work on a workqueue after delay
1030  * @wq: workqueue to use
1031  * @dwork: delayable work to queue
1032  * @delay: number of jiffies to wait before queueing
1033  *
1034  * Returns 0 if @work was already on a queue, non-zero otherwise.
1035  */
1036 int queue_delayed_work(struct workqueue_struct *wq,
1037                         struct delayed_work *dwork, unsigned long delay)
1038 {
1039         if (delay == 0)
1040                 return queue_work(wq, &dwork->work);
1041
1042         return queue_delayed_work_on(-1, wq, dwork, delay);
1043 }
1044 EXPORT_SYMBOL_GPL(queue_delayed_work);
1045
1046 /**
1047  * queue_delayed_work_on - queue work on specific CPU after delay
1048  * @cpu: CPU number to execute work on
1049  * @wq: workqueue to use
1050  * @dwork: work to queue
1051  * @delay: number of jiffies to wait before queueing
1052  *
1053  * Returns 0 if @work was already on a queue, non-zero otherwise.
1054  */
1055 int queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1056                         struct delayed_work *dwork, unsigned long delay)
1057 {
1058         int ret = 0;
1059         struct timer_list *timer = &dwork->timer;
1060         struct work_struct *work = &dwork->work;
1061
1062         if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1063                 unsigned int lcpu;
1064
1065                 BUG_ON(timer_pending(timer));
1066                 BUG_ON(!list_empty(&work->entry));
1067
1068                 timer_stats_timer_set_start_info(&dwork->timer);
1069
1070                 /*
1071                  * This stores cwq for the moment, for the timer_fn.
1072                  * Note that the work's gcwq is preserved to allow
1073                  * reentrance detection for delayed works.
1074                  */
1075                 if (!(wq->flags & WQ_UNBOUND)) {
1076                         struct global_cwq *gcwq = get_work_gcwq(work);
1077
1078                         if (gcwq && gcwq->cpu != WORK_CPU_UNBOUND)
1079                                 lcpu = gcwq->cpu;
1080                         else
1081                                 lcpu = raw_smp_processor_id();
1082                 } else
1083                         lcpu = WORK_CPU_UNBOUND;
1084
1085                 set_work_cwq(work, get_cwq(lcpu, wq), 0);
1086
1087                 timer->expires = jiffies + delay;
1088                 timer->data = (unsigned long)dwork;
1089                 timer->function = delayed_work_timer_fn;
1090
1091                 if (unlikely(cpu >= 0))
1092                         add_timer_on(timer, cpu);
1093                 else
1094                         add_timer(timer);
1095                 ret = 1;
1096         }
1097         return ret;
1098 }
1099 EXPORT_SYMBOL_GPL(queue_delayed_work_on);
1100
1101 /**
1102  * worker_enter_idle - enter idle state
1103  * @worker: worker which is entering idle state
1104  *
1105  * @worker is entering idle state.  Update stats and idle timer if
1106  * necessary.
1107  *
1108  * LOCKING:
1109  * spin_lock_irq(gcwq->lock).
1110  */
1111 static void worker_enter_idle(struct worker *worker)
1112 {
1113         struct global_cwq *gcwq = worker->gcwq;
1114
1115         BUG_ON(worker->flags & WORKER_IDLE);
1116         BUG_ON(!list_empty(&worker->entry) &&
1117                (worker->hentry.next || worker->hentry.pprev));
1118
1119         /* can't use worker_set_flags(), also called from start_worker() */
1120         worker->flags |= WORKER_IDLE;
1121         gcwq->nr_idle++;
1122         worker->last_active = jiffies;
1123
1124         /* idle_list is LIFO */
1125         list_add(&worker->entry, &gcwq->idle_list);
1126
1127         if (likely(!(worker->flags & WORKER_ROGUE))) {
1128                 if (too_many_workers(gcwq) && !timer_pending(&gcwq->idle_timer))
1129                         mod_timer(&gcwq->idle_timer,
1130                                   jiffies + IDLE_WORKER_TIMEOUT);
1131         } else
1132                 wake_up_all(&gcwq->trustee_wait);
1133
1134         /* sanity check nr_running */
1135         WARN_ON_ONCE(gcwq->nr_workers == gcwq->nr_idle &&
1136                      atomic_read(get_gcwq_nr_running(gcwq->cpu)));
1137 }
1138
1139 /**
1140  * worker_leave_idle - leave idle state
1141  * @worker: worker which is leaving idle state
1142  *
1143  * @worker is leaving idle state.  Update stats.
1144  *
1145  * LOCKING:
1146  * spin_lock_irq(gcwq->lock).
1147  */
1148 static void worker_leave_idle(struct worker *worker)
1149 {
1150         struct global_cwq *gcwq = worker->gcwq;
1151
1152         BUG_ON(!(worker->flags & WORKER_IDLE));
1153         worker_clr_flags(worker, WORKER_IDLE);
1154         gcwq->nr_idle--;
1155         list_del_init(&worker->entry);
1156 }
1157
1158 /**
1159  * worker_maybe_bind_and_lock - bind worker to its cpu if possible and lock gcwq
1160  * @worker: self
1161  *
1162  * Works which are scheduled while the cpu is online must at least be
1163  * scheduled to a worker which is bound to the cpu so that if they are
1164  * flushed from cpu callbacks while cpu is going down, they are
1165  * guaranteed to execute on the cpu.
1166  *
1167  * This function is to be used by rogue workers and rescuers to bind
1168  * themselves to the target cpu and may race with cpu going down or
1169  * coming online.  kthread_bind() can't be used because it may put the
1170  * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1171  * verbatim as it's best effort and blocking and gcwq may be
1172  * [dis]associated in the meantime.
1173  *
1174  * This function tries set_cpus_allowed() and locks gcwq and verifies
1175  * the binding against GCWQ_DISASSOCIATED which is set during
1176  * CPU_DYING and cleared during CPU_ONLINE, so if the worker enters
1177  * idle state or fetches works without dropping lock, it can guarantee
1178  * the scheduling requirement described in the first paragraph.
1179  *
1180  * CONTEXT:
1181  * Might sleep.  Called without any lock but returns with gcwq->lock
1182  * held.
1183  *
1184  * RETURNS:
1185  * %true if the associated gcwq is online (@worker is successfully
1186  * bound), %false if offline.
1187  */
1188 static bool worker_maybe_bind_and_lock(struct worker *worker)
1189 {
1190         struct global_cwq *gcwq = worker->gcwq;
1191         struct task_struct *task = worker->task;
1192
1193         while (true) {
1194                 /*
1195                  * The following call may fail, succeed or succeed
1196                  * without actually migrating the task to the cpu if
1197                  * it races with cpu hotunplug operation.  Verify
1198                  * against GCWQ_DISASSOCIATED.
1199                  */
1200                 if (!(gcwq->flags & GCWQ_DISASSOCIATED))
1201                         set_cpus_allowed_ptr(task, get_cpu_mask(gcwq->cpu));
1202
1203                 spin_lock_irq(&gcwq->lock);
1204                 if (gcwq->flags & GCWQ_DISASSOCIATED)
1205                         return false;
1206                 if (task_cpu(task) == gcwq->cpu &&
1207                     cpumask_equal(&current->cpus_allowed,
1208                                   get_cpu_mask(gcwq->cpu)))
1209                         return true;
1210                 spin_unlock_irq(&gcwq->lock);
1211
1212                 /* CPU has come up inbetween, retry migration */
1213                 cpu_relax();
1214         }
1215 }
1216
1217 /*
1218  * Function for worker->rebind_work used to rebind rogue busy workers
1219  * to the associated cpu which is coming back online.  This is
1220  * scheduled by cpu up but can race with other cpu hotplug operations
1221  * and may be executed twice without intervening cpu down.
1222  */
1223 static void worker_rebind_fn(struct work_struct *work)
1224 {
1225         struct worker *worker = container_of(work, struct worker, rebind_work);
1226         struct global_cwq *gcwq = worker->gcwq;
1227
1228         if (worker_maybe_bind_and_lock(worker))
1229                 worker_clr_flags(worker, WORKER_REBIND);
1230
1231         spin_unlock_irq(&gcwq->lock);
1232 }
1233
1234 static struct worker *alloc_worker(void)
1235 {
1236         struct worker *worker;
1237
1238         worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1239         if (worker) {
1240                 INIT_LIST_HEAD(&worker->entry);
1241                 INIT_LIST_HEAD(&worker->scheduled);
1242                 INIT_WORK(&worker->rebind_work, worker_rebind_fn);
1243                 /* on creation a worker is in !idle && prep state */
1244                 worker->flags = WORKER_PREP;
1245         }
1246         return worker;
1247 }
1248
1249 /**
1250  * create_worker - create a new workqueue worker
1251  * @gcwq: gcwq the new worker will belong to
1252  * @bind: whether to set affinity to @cpu or not
1253  *
1254  * Create a new worker which is bound to @gcwq.  The returned worker
1255  * can be started by calling start_worker() or destroyed using
1256  * destroy_worker().
1257  *
1258  * CONTEXT:
1259  * Might sleep.  Does GFP_KERNEL allocations.
1260  *
1261  * RETURNS:
1262  * Pointer to the newly created worker.
1263  */
1264 static struct worker *create_worker(struct global_cwq *gcwq, bool bind)
1265 {
1266         bool on_unbound_cpu = gcwq->cpu == WORK_CPU_UNBOUND;
1267         struct worker *worker = NULL;
1268         int id = -1;
1269
1270         spin_lock_irq(&gcwq->lock);
1271         while (ida_get_new(&gcwq->worker_ida, &id)) {
1272                 spin_unlock_irq(&gcwq->lock);
1273                 if (!ida_pre_get(&gcwq->worker_ida, GFP_KERNEL))
1274                         goto fail;
1275                 spin_lock_irq(&gcwq->lock);
1276         }
1277         spin_unlock_irq(&gcwq->lock);
1278
1279         worker = alloc_worker();
1280         if (!worker)
1281                 goto fail;
1282
1283         worker->gcwq = gcwq;
1284         worker->id = id;
1285
1286         if (!on_unbound_cpu)
1287                 worker->task = kthread_create(worker_thread, worker,
1288                                               "kworker/%u:%d", gcwq->cpu, id);
1289         else
1290                 worker->task = kthread_create(worker_thread, worker,
1291                                               "kworker/u:%d", id);
1292         if (IS_ERR(worker->task))
1293                 goto fail;
1294
1295         /*
1296          * A rogue worker will become a regular one if CPU comes
1297          * online later on.  Make sure every worker has
1298          * PF_THREAD_BOUND set.
1299          */
1300         if (bind && !on_unbound_cpu)
1301                 kthread_bind(worker->task, gcwq->cpu);
1302         else {
1303                 worker->task->flags |= PF_THREAD_BOUND;
1304                 if (on_unbound_cpu)
1305                         worker->flags |= WORKER_UNBOUND;
1306         }
1307
1308         return worker;
1309 fail:
1310         if (id >= 0) {
1311                 spin_lock_irq(&gcwq->lock);
1312                 ida_remove(&gcwq->worker_ida, id);
1313                 spin_unlock_irq(&gcwq->lock);
1314         }
1315         kfree(worker);
1316         return NULL;
1317 }
1318
1319 /**
1320  * start_worker - start a newly created worker
1321  * @worker: worker to start
1322  *
1323  * Make the gcwq aware of @worker and start it.
1324  *
1325  * CONTEXT:
1326  * spin_lock_irq(gcwq->lock).
1327  */
1328 static void start_worker(struct worker *worker)
1329 {
1330         worker->flags |= WORKER_STARTED;
1331         worker->gcwq->nr_workers++;
1332         worker_enter_idle(worker);
1333         wake_up_process(worker->task);
1334 }
1335
1336 /**
1337  * destroy_worker - destroy a workqueue worker
1338  * @worker: worker to be destroyed
1339  *
1340  * Destroy @worker and adjust @gcwq stats accordingly.
1341  *
1342  * CONTEXT:
1343  * spin_lock_irq(gcwq->lock) which is released and regrabbed.
1344  */
1345 static void destroy_worker(struct worker *worker)
1346 {
1347         struct global_cwq *gcwq = worker->gcwq;
1348         int id = worker->id;
1349
1350         /* sanity check frenzy */
1351         BUG_ON(worker->current_work);
1352         BUG_ON(!list_empty(&worker->scheduled));
1353
1354         if (worker->flags & WORKER_STARTED)
1355                 gcwq->nr_workers--;
1356         if (worker->flags & WORKER_IDLE)
1357                 gcwq->nr_idle--;
1358
1359         list_del_init(&worker->entry);
1360         worker->flags |= WORKER_DIE;
1361
1362         spin_unlock_irq(&gcwq->lock);
1363
1364         kthread_stop(worker->task);
1365         kfree(worker);
1366
1367         spin_lock_irq(&gcwq->lock);
1368         ida_remove(&gcwq->worker_ida, id);
1369 }
1370
1371 static void idle_worker_timeout(unsigned long __gcwq)
1372 {
1373         struct global_cwq *gcwq = (void *)__gcwq;
1374
1375         spin_lock_irq(&gcwq->lock);
1376
1377         if (too_many_workers(gcwq)) {
1378                 struct worker *worker;
1379                 unsigned long expires;
1380
1381                 /* idle_list is kept in LIFO order, check the last one */
1382                 worker = list_entry(gcwq->idle_list.prev, struct worker, entry);
1383                 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1384
1385                 if (time_before(jiffies, expires))
1386                         mod_timer(&gcwq->idle_timer, expires);
1387                 else {
1388                         /* it's been idle for too long, wake up manager */
1389                         gcwq->flags |= GCWQ_MANAGE_WORKERS;
1390                         wake_up_worker(gcwq);
1391                 }
1392         }
1393
1394         spin_unlock_irq(&gcwq->lock);
1395 }
1396
1397 static bool send_mayday(struct work_struct *work)
1398 {
1399         struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1400         struct workqueue_struct *wq = cwq->wq;
1401         unsigned int cpu;
1402
1403         if (!(wq->flags & WQ_RESCUER))
1404                 return false;
1405
1406         /* mayday mayday mayday */
1407         cpu = cwq->gcwq->cpu;
1408         /* WORK_CPU_UNBOUND can't be set in cpumask, use cpu 0 instead */
1409         if (cpu == WORK_CPU_UNBOUND)
1410                 cpu = 0;
1411         if (!mayday_test_and_set_cpu(cpu, wq->mayday_mask))
1412                 wake_up_process(wq->rescuer->task);
1413         return true;
1414 }
1415
1416 static void gcwq_mayday_timeout(unsigned long __gcwq)
1417 {
1418         struct global_cwq *gcwq = (void *)__gcwq;
1419         struct work_struct *work;
1420
1421         spin_lock_irq(&gcwq->lock);
1422
1423         if (need_to_create_worker(gcwq)) {
1424                 /*
1425                  * We've been trying to create a new worker but
1426                  * haven't been successful.  We might be hitting an
1427                  * allocation deadlock.  Send distress signals to
1428                  * rescuers.
1429                  */
1430                 list_for_each_entry(work, &gcwq->worklist, entry)
1431                         send_mayday(work);
1432         }
1433
1434         spin_unlock_irq(&gcwq->lock);
1435
1436         mod_timer(&gcwq->mayday_timer, jiffies + MAYDAY_INTERVAL);
1437 }
1438
1439 /**
1440  * maybe_create_worker - create a new worker if necessary
1441  * @gcwq: gcwq to create a new worker for
1442  *
1443  * Create a new worker for @gcwq if necessary.  @gcwq is guaranteed to
1444  * have at least one idle worker on return from this function.  If
1445  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1446  * sent to all rescuers with works scheduled on @gcwq to resolve
1447  * possible allocation deadlock.
1448  *
1449  * On return, need_to_create_worker() is guaranteed to be false and
1450  * may_start_working() true.
1451  *
1452  * LOCKING:
1453  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1454  * multiple times.  Does GFP_KERNEL allocations.  Called only from
1455  * manager.
1456  *
1457  * RETURNS:
1458  * false if no action was taken and gcwq->lock stayed locked, true
1459  * otherwise.
1460  */
1461 static bool maybe_create_worker(struct global_cwq *gcwq)
1462 {
1463         if (!need_to_create_worker(gcwq))
1464                 return false;
1465 restart:
1466         spin_unlock_irq(&gcwq->lock);
1467
1468         /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1469         mod_timer(&gcwq->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1470
1471         while (true) {
1472                 struct worker *worker;
1473
1474                 worker = create_worker(gcwq, true);
1475                 if (worker) {
1476                         del_timer_sync(&gcwq->mayday_timer);
1477                         spin_lock_irq(&gcwq->lock);
1478                         start_worker(worker);
1479                         BUG_ON(need_to_create_worker(gcwq));
1480                         return true;
1481                 }
1482
1483                 if (!need_to_create_worker(gcwq))
1484                         break;
1485
1486                 __set_current_state(TASK_INTERRUPTIBLE);
1487                 schedule_timeout(CREATE_COOLDOWN);
1488
1489                 if (!need_to_create_worker(gcwq))
1490                         break;
1491         }
1492
1493         del_timer_sync(&gcwq->mayday_timer);
1494         spin_lock_irq(&gcwq->lock);
1495         if (need_to_create_worker(gcwq))
1496                 goto restart;
1497         return true;
1498 }
1499
1500 /**
1501  * maybe_destroy_worker - destroy workers which have been idle for a while
1502  * @gcwq: gcwq to destroy workers for
1503  *
1504  * Destroy @gcwq workers which have been idle for longer than
1505  * IDLE_WORKER_TIMEOUT.
1506  *
1507  * LOCKING:
1508  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1509  * multiple times.  Called only from manager.
1510  *
1511  * RETURNS:
1512  * false if no action was taken and gcwq->lock stayed locked, true
1513  * otherwise.
1514  */
1515 static bool maybe_destroy_workers(struct global_cwq *gcwq)
1516 {
1517         bool ret = false;
1518
1519         while (too_many_workers(gcwq)) {
1520                 struct worker *worker;
1521                 unsigned long expires;
1522
1523                 worker = list_entry(gcwq->idle_list.prev, struct worker, entry);
1524                 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1525
1526                 if (time_before(jiffies, expires)) {
1527                         mod_timer(&gcwq->idle_timer, expires);
1528                         break;
1529                 }
1530
1531                 destroy_worker(worker);
1532                 ret = true;
1533         }
1534
1535         return ret;
1536 }
1537
1538 /**
1539  * manage_workers - manage worker pool
1540  * @worker: self
1541  *
1542  * Assume the manager role and manage gcwq worker pool @worker belongs
1543  * to.  At any given time, there can be only zero or one manager per
1544  * gcwq.  The exclusion is handled automatically by this function.
1545  *
1546  * The caller can safely start processing works on false return.  On
1547  * true return, it's guaranteed that need_to_create_worker() is false
1548  * and may_start_working() is true.
1549  *
1550  * CONTEXT:
1551  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1552  * multiple times.  Does GFP_KERNEL allocations.
1553  *
1554  * RETURNS:
1555  * false if no action was taken and gcwq->lock stayed locked, true if
1556  * some action was taken.
1557  */
1558 static bool manage_workers(struct worker *worker)
1559 {
1560         struct global_cwq *gcwq = worker->gcwq;
1561         bool ret = false;
1562
1563         if (gcwq->flags & GCWQ_MANAGING_WORKERS)
1564                 return ret;
1565
1566         gcwq->flags &= ~GCWQ_MANAGE_WORKERS;
1567         gcwq->flags |= GCWQ_MANAGING_WORKERS;
1568
1569         /*
1570          * Destroy and then create so that may_start_working() is true
1571          * on return.
1572          */
1573         ret |= maybe_destroy_workers(gcwq);
1574         ret |= maybe_create_worker(gcwq);
1575
1576         gcwq->flags &= ~GCWQ_MANAGING_WORKERS;
1577
1578         /*
1579          * The trustee might be waiting to take over the manager
1580          * position, tell it we're done.
1581          */
1582         if (unlikely(gcwq->trustee))
1583                 wake_up_all(&gcwq->trustee_wait);
1584
1585         return ret;
1586 }
1587
1588 /**
1589  * move_linked_works - move linked works to a list
1590  * @work: start of series of works to be scheduled
1591  * @head: target list to append @work to
1592  * @nextp: out paramter for nested worklist walking
1593  *
1594  * Schedule linked works starting from @work to @head.  Work series to
1595  * be scheduled starts at @work and includes any consecutive work with
1596  * WORK_STRUCT_LINKED set in its predecessor.
1597  *
1598  * If @nextp is not NULL, it's updated to point to the next work of
1599  * the last scheduled work.  This allows move_linked_works() to be
1600  * nested inside outer list_for_each_entry_safe().
1601  *
1602  * CONTEXT:
1603  * spin_lock_irq(gcwq->lock).
1604  */
1605 static void move_linked_works(struct work_struct *work, struct list_head *head,
1606                               struct work_struct **nextp)
1607 {
1608         struct work_struct *n;
1609
1610         /*
1611          * Linked worklist will always end before the end of the list,
1612          * use NULL for list head.
1613          */
1614         list_for_each_entry_safe_from(work, n, NULL, entry) {
1615                 list_move_tail(&work->entry, head);
1616                 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1617                         break;
1618         }
1619
1620         /*
1621          * If we're already inside safe list traversal and have moved
1622          * multiple works to the scheduled queue, the next position
1623          * needs to be updated.
1624          */
1625         if (nextp)
1626                 *nextp = n;
1627 }
1628
1629 static void cwq_activate_first_delayed(struct cpu_workqueue_struct *cwq)
1630 {
1631         struct work_struct *work = list_first_entry(&cwq->delayed_works,
1632                                                     struct work_struct, entry);
1633         struct list_head *pos = gcwq_determine_ins_pos(cwq->gcwq, cwq);
1634
1635         move_linked_works(work, pos, NULL);
1636         cwq->nr_active++;
1637 }
1638
1639 /**
1640  * cwq_dec_nr_in_flight - decrement cwq's nr_in_flight
1641  * @cwq: cwq of interest
1642  * @color: color of work which left the queue
1643  *
1644  * A work either has completed or is removed from pending queue,
1645  * decrement nr_in_flight of its cwq and handle workqueue flushing.
1646  *
1647  * CONTEXT:
1648  * spin_lock_irq(gcwq->lock).
1649  */
1650 static void cwq_dec_nr_in_flight(struct cpu_workqueue_struct *cwq, int color)
1651 {
1652         /* ignore uncolored works */
1653         if (color == WORK_NO_COLOR)
1654                 return;
1655
1656         cwq->nr_in_flight[color]--;
1657         cwq->nr_active--;
1658
1659         if (!list_empty(&cwq->delayed_works)) {
1660                 /* one down, submit a delayed one */
1661                 if (cwq->nr_active < cwq->max_active)
1662                         cwq_activate_first_delayed(cwq);
1663         }
1664
1665         /* is flush in progress and are we at the flushing tip? */
1666         if (likely(cwq->flush_color != color))
1667                 return;
1668
1669         /* are there still in-flight works? */
1670         if (cwq->nr_in_flight[color])
1671                 return;
1672
1673         /* this cwq is done, clear flush_color */
1674         cwq->flush_color = -1;
1675
1676         /*
1677          * If this was the last cwq, wake up the first flusher.  It
1678          * will handle the rest.
1679          */
1680         if (atomic_dec_and_test(&cwq->wq->nr_cwqs_to_flush))
1681                 complete(&cwq->wq->first_flusher->done);
1682 }
1683
1684 /**
1685  * process_one_work - process single work
1686  * @worker: self
1687  * @work: work to process
1688  *
1689  * Process @work.  This function contains all the logics necessary to
1690  * process a single work including synchronization against and
1691  * interaction with other workers on the same cpu, queueing and
1692  * flushing.  As long as context requirement is met, any worker can
1693  * call this function to process a work.
1694  *
1695  * CONTEXT:
1696  * spin_lock_irq(gcwq->lock) which is released and regrabbed.
1697  */
1698 static void process_one_work(struct worker *worker, struct work_struct *work)
1699 {
1700         struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1701         struct global_cwq *gcwq = cwq->gcwq;
1702         struct hlist_head *bwh = busy_worker_head(gcwq, work);
1703         bool cpu_intensive = cwq->wq->flags & WQ_CPU_INTENSIVE;
1704         work_func_t f = work->func;
1705         int work_color;
1706         struct worker *collision;
1707 #ifdef CONFIG_LOCKDEP
1708         /*
1709          * It is permissible to free the struct work_struct from
1710          * inside the function that is called from it, this we need to
1711          * take into account for lockdep too.  To avoid bogus "held
1712          * lock freed" warnings as well as problems when looking into
1713          * work->lockdep_map, make a copy and use that here.
1714          */
1715         struct lockdep_map lockdep_map = work->lockdep_map;
1716 #endif
1717         /*
1718          * A single work shouldn't be executed concurrently by
1719          * multiple workers on a single cpu.  Check whether anyone is
1720          * already processing the work.  If so, defer the work to the
1721          * currently executing one.
1722          */
1723         collision = __find_worker_executing_work(gcwq, bwh, work);
1724         if (unlikely(collision)) {
1725                 move_linked_works(work, &collision->scheduled, NULL);
1726                 return;
1727         }
1728
1729         /* claim and process */
1730         debug_work_deactivate(work);
1731         hlist_add_head(&worker->hentry, bwh);
1732         worker->current_work = work;
1733         worker->current_cwq = cwq;
1734         work_color = get_work_color(work);
1735
1736         /* record the current cpu number in the work data and dequeue */
1737         set_work_cpu(work, gcwq->cpu);
1738         list_del_init(&work->entry);
1739
1740         /*
1741          * If HIGHPRI_PENDING, check the next work, and, if HIGHPRI,
1742          * wake up another worker; otherwise, clear HIGHPRI_PENDING.
1743          */
1744         if (unlikely(gcwq->flags & GCWQ_HIGHPRI_PENDING)) {
1745                 struct work_struct *nwork = list_first_entry(&gcwq->worklist,
1746                                                 struct work_struct, entry);
1747
1748                 if (!list_empty(&gcwq->worklist) &&
1749                     get_work_cwq(nwork)->wq->flags & WQ_HIGHPRI)
1750                         wake_up_worker(gcwq);
1751                 else
1752                         gcwq->flags &= ~GCWQ_HIGHPRI_PENDING;
1753         }
1754
1755         /*
1756          * CPU intensive works don't participate in concurrency
1757          * management.  They're the scheduler's responsibility.
1758          */
1759         if (unlikely(cpu_intensive))
1760                 worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
1761
1762         spin_unlock_irq(&gcwq->lock);
1763
1764         work_clear_pending(work);
1765         lock_map_acquire(&cwq->wq->lockdep_map);
1766         lock_map_acquire(&lockdep_map);
1767         f(work);
1768         lock_map_release(&lockdep_map);
1769         lock_map_release(&cwq->wq->lockdep_map);
1770
1771         if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
1772                 printk(KERN_ERR "BUG: workqueue leaked lock or atomic: "
1773                        "%s/0x%08x/%d\n",
1774                        current->comm, preempt_count(), task_pid_nr(current));
1775                 printk(KERN_ERR "    last function: ");
1776                 print_symbol("%s\n", (unsigned long)f);
1777                 debug_show_held_locks(current);
1778                 dump_stack();
1779         }
1780
1781         spin_lock_irq(&gcwq->lock);
1782
1783         /* clear cpu intensive status */
1784         if (unlikely(cpu_intensive))
1785                 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
1786
1787         /* we're done with it, release */
1788         hlist_del_init(&worker->hentry);
1789         worker->current_work = NULL;
1790         worker->current_cwq = NULL;
1791         cwq_dec_nr_in_flight(cwq, work_color);
1792 }
1793
1794 /**
1795  * process_scheduled_works - process scheduled works
1796  * @worker: self
1797  *
1798  * Process all scheduled works.  Please note that the scheduled list
1799  * may change while processing a work, so this function repeatedly
1800  * fetches a work from the top and executes it.
1801  *
1802  * CONTEXT:
1803  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1804  * multiple times.
1805  */
1806 static void process_scheduled_works(struct worker *worker)
1807 {
1808         while (!list_empty(&worker->scheduled)) {
1809                 struct work_struct *work = list_first_entry(&worker->scheduled,
1810                                                 struct work_struct, entry);
1811                 process_one_work(worker, work);
1812         }
1813 }
1814
1815 /**
1816  * worker_thread - the worker thread function
1817  * @__worker: self
1818  *
1819  * The gcwq worker thread function.  There's a single dynamic pool of
1820  * these per each cpu.  These workers process all works regardless of
1821  * their specific target workqueue.  The only exception is works which
1822  * belong to workqueues with a rescuer which will be explained in
1823  * rescuer_thread().
1824  */
1825 static int worker_thread(void *__worker)
1826 {
1827         struct worker *worker = __worker;
1828         struct global_cwq *gcwq = worker->gcwq;
1829
1830         /* tell the scheduler that this is a workqueue worker */
1831         worker->task->flags |= PF_WQ_WORKER;
1832 woke_up:
1833         spin_lock_irq(&gcwq->lock);
1834
1835         /* DIE can be set only while we're idle, checking here is enough */
1836         if (worker->flags & WORKER_DIE) {
1837                 spin_unlock_irq(&gcwq->lock);
1838                 worker->task->flags &= ~PF_WQ_WORKER;
1839                 return 0;
1840         }
1841
1842         worker_leave_idle(worker);
1843 recheck:
1844         /* no more worker necessary? */
1845         if (!need_more_worker(gcwq))
1846                 goto sleep;
1847
1848         /* do we need to manage? */
1849         if (unlikely(!may_start_working(gcwq)) && manage_workers(worker))
1850                 goto recheck;
1851
1852         /*
1853          * ->scheduled list can only be filled while a worker is
1854          * preparing to process a work or actually processing it.
1855          * Make sure nobody diddled with it while I was sleeping.
1856          */
1857         BUG_ON(!list_empty(&worker->scheduled));
1858
1859         /*
1860          * When control reaches this point, we're guaranteed to have
1861          * at least one idle worker or that someone else has already
1862          * assumed the manager role.
1863          */
1864         worker_clr_flags(worker, WORKER_PREP);
1865
1866         do {
1867                 struct work_struct *work =
1868                         list_first_entry(&gcwq->worklist,
1869                                          struct work_struct, entry);
1870
1871                 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
1872                         /* optimization path, not strictly necessary */
1873                         process_one_work(worker, work);
1874                         if (unlikely(!list_empty(&worker->scheduled)))
1875                                 process_scheduled_works(worker);
1876                 } else {
1877                         move_linked_works(work, &worker->scheduled, NULL);
1878                         process_scheduled_works(worker);
1879                 }
1880         } while (keep_working(gcwq));
1881
1882         worker_set_flags(worker, WORKER_PREP, false);
1883 sleep:
1884         if (unlikely(need_to_manage_workers(gcwq)) && manage_workers(worker))
1885                 goto recheck;
1886
1887         /*
1888          * gcwq->lock is held and there's no work to process and no
1889          * need to manage, sleep.  Workers are woken up only while
1890          * holding gcwq->lock or from local cpu, so setting the
1891          * current state before releasing gcwq->lock is enough to
1892          * prevent losing any event.
1893          */
1894         worker_enter_idle(worker);
1895         __set_current_state(TASK_INTERRUPTIBLE);
1896         spin_unlock_irq(&gcwq->lock);
1897         schedule();
1898         goto woke_up;
1899 }
1900
1901 /**
1902  * rescuer_thread - the rescuer thread function
1903  * @__wq: the associated workqueue
1904  *
1905  * Workqueue rescuer thread function.  There's one rescuer for each
1906  * workqueue which has WQ_RESCUER set.
1907  *
1908  * Regular work processing on a gcwq may block trying to create a new
1909  * worker which uses GFP_KERNEL allocation which has slight chance of
1910  * developing into deadlock if some works currently on the same queue
1911  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
1912  * the problem rescuer solves.
1913  *
1914  * When such condition is possible, the gcwq summons rescuers of all
1915  * workqueues which have works queued on the gcwq and let them process
1916  * those works so that forward progress can be guaranteed.
1917  *
1918  * This should happen rarely.
1919  */
1920 static int rescuer_thread(void *__wq)
1921 {
1922         struct workqueue_struct *wq = __wq;
1923         struct worker *rescuer = wq->rescuer;
1924         struct list_head *scheduled = &rescuer->scheduled;
1925         bool is_unbound = wq->flags & WQ_UNBOUND;
1926         unsigned int cpu;
1927
1928         set_user_nice(current, RESCUER_NICE_LEVEL);
1929 repeat:
1930         set_current_state(TASK_INTERRUPTIBLE);
1931
1932         if (kthread_should_stop())
1933                 return 0;
1934
1935         /*
1936          * See whether any cpu is asking for help.  Unbounded
1937          * workqueues use cpu 0 in mayday_mask for CPU_UNBOUND.
1938          */
1939         for_each_mayday_cpu(cpu, wq->mayday_mask) {
1940                 unsigned int tcpu = is_unbound ? WORK_CPU_UNBOUND : cpu;
1941                 struct cpu_workqueue_struct *cwq = get_cwq(tcpu, wq);
1942                 struct global_cwq *gcwq = cwq->gcwq;
1943                 struct work_struct *work, *n;
1944
1945                 __set_current_state(TASK_RUNNING);
1946                 mayday_clear_cpu(cpu, wq->mayday_mask);
1947
1948                 /* migrate to the target cpu if possible */
1949                 rescuer->gcwq = gcwq;
1950                 worker_maybe_bind_and_lock(rescuer);
1951
1952                 /*
1953                  * Slurp in all works issued via this workqueue and
1954                  * process'em.
1955                  */
1956                 BUG_ON(!list_empty(&rescuer->scheduled));
1957                 list_for_each_entry_safe(work, n, &gcwq->worklist, entry)
1958                         if (get_work_cwq(work) == cwq)
1959                                 move_linked_works(work, scheduled, &n);
1960
1961                 process_scheduled_works(rescuer);
1962                 spin_unlock_irq(&gcwq->lock);
1963         }
1964
1965         schedule();
1966         goto repeat;
1967 }
1968
1969 struct wq_barrier {
1970         struct work_struct      work;
1971         struct completion       done;
1972 };
1973
1974 static void wq_barrier_func(struct work_struct *work)
1975 {
1976         struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
1977         complete(&barr->done);
1978 }
1979
1980 /**
1981  * insert_wq_barrier - insert a barrier work
1982  * @cwq: cwq to insert barrier into
1983  * @barr: wq_barrier to insert
1984  * @target: target work to attach @barr to
1985  * @worker: worker currently executing @target, NULL if @target is not executing
1986  *
1987  * @barr is linked to @target such that @barr is completed only after
1988  * @target finishes execution.  Please note that the ordering
1989  * guarantee is observed only with respect to @target and on the local
1990  * cpu.
1991  *
1992  * Currently, a queued barrier can't be canceled.  This is because
1993  * try_to_grab_pending() can't determine whether the work to be
1994  * grabbed is at the head of the queue and thus can't clear LINKED
1995  * flag of the previous work while there must be a valid next work
1996  * after a work with LINKED flag set.
1997  *
1998  * Note that when @worker is non-NULL, @target may be modified
1999  * underneath us, so we can't reliably determine cwq from @target.
2000  *
2001  * CONTEXT:
2002  * spin_lock_irq(gcwq->lock).
2003  */
2004 static void insert_wq_barrier(struct cpu_workqueue_struct *cwq,
2005                               struct wq_barrier *barr,
2006                               struct work_struct *target, struct worker *worker)
2007 {
2008         struct list_head *head;
2009         unsigned int linked = 0;
2010
2011         /*
2012          * debugobject calls are safe here even with gcwq->lock locked
2013          * as we know for sure that this will not trigger any of the
2014          * checks and call back into the fixup functions where we
2015          * might deadlock.
2016          */
2017         INIT_WORK_ON_STACK(&barr->work, wq_barrier_func);
2018         __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2019         init_completion(&barr->done);
2020
2021         /*
2022          * If @target is currently being executed, schedule the
2023          * barrier to the worker; otherwise, put it after @target.
2024          */
2025         if (worker)
2026                 head = worker->scheduled.next;
2027         else {
2028                 unsigned long *bits = work_data_bits(target);
2029
2030                 head = target->entry.next;
2031                 /* there can already be other linked works, inherit and set */
2032                 linked = *bits & WORK_STRUCT_LINKED;
2033                 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2034         }
2035
2036         debug_work_activate(&barr->work);
2037         insert_work(cwq, &barr->work, head,
2038                     work_color_to_flags(WORK_NO_COLOR) | linked);
2039 }
2040
2041 /**
2042  * flush_workqueue_prep_cwqs - prepare cwqs for workqueue flushing
2043  * @wq: workqueue being flushed
2044  * @flush_color: new flush color, < 0 for no-op
2045  * @work_color: new work color, < 0 for no-op
2046  *
2047  * Prepare cwqs for workqueue flushing.
2048  *
2049  * If @flush_color is non-negative, flush_color on all cwqs should be
2050  * -1.  If no cwq has in-flight commands at the specified color, all
2051  * cwq->flush_color's stay at -1 and %false is returned.  If any cwq
2052  * has in flight commands, its cwq->flush_color is set to
2053  * @flush_color, @wq->nr_cwqs_to_flush is updated accordingly, cwq
2054  * wakeup logic is armed and %true is returned.
2055  *
2056  * The caller should have initialized @wq->first_flusher prior to
2057  * calling this function with non-negative @flush_color.  If
2058  * @flush_color is negative, no flush color update is done and %false
2059  * is returned.
2060  *
2061  * If @work_color is non-negative, all cwqs should have the same
2062  * work_color which is previous to @work_color and all will be
2063  * advanced to @work_color.
2064  *
2065  * CONTEXT:
2066  * mutex_lock(wq->flush_mutex).
2067  *
2068  * RETURNS:
2069  * %true if @flush_color >= 0 and there's something to flush.  %false
2070  * otherwise.
2071  */
2072 static bool flush_workqueue_prep_cwqs(struct workqueue_struct *wq,
2073                                       int flush_color, int work_color)
2074 {
2075         bool wait = false;
2076         unsigned int cpu;
2077
2078         if (flush_color >= 0) {
2079                 BUG_ON(atomic_read(&wq->nr_cwqs_to_flush));
2080                 atomic_set(&wq->nr_cwqs_to_flush, 1);
2081         }
2082
2083         for_each_cwq_cpu(cpu, wq) {
2084                 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2085                 struct global_cwq *gcwq = cwq->gcwq;
2086
2087                 spin_lock_irq(&gcwq->lock);
2088
2089                 if (flush_color >= 0) {
2090                         BUG_ON(cwq->flush_color != -1);
2091
2092                         if (cwq->nr_in_flight[flush_color]) {
2093                                 cwq->flush_color = flush_color;
2094                                 atomic_inc(&wq->nr_cwqs_to_flush);
2095                                 wait = true;
2096                         }
2097                 }
2098
2099                 if (work_color >= 0) {
2100                         BUG_ON(work_color != work_next_color(cwq->work_color));
2101                         cwq->work_color = work_color;
2102                 }
2103
2104                 spin_unlock_irq(&gcwq->lock);
2105         }
2106
2107         if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_cwqs_to_flush))
2108                 complete(&wq->first_flusher->done);
2109
2110         return wait;
2111 }
2112
2113 /**
2114  * flush_workqueue - ensure that any scheduled work has run to completion.
2115  * @wq: workqueue to flush
2116  *
2117  * Forces execution of the workqueue and blocks until its completion.
2118  * This is typically used in driver shutdown handlers.
2119  *
2120  * We sleep until all works which were queued on entry have been handled,
2121  * but we are not livelocked by new incoming ones.
2122  */
2123 void flush_workqueue(struct workqueue_struct *wq)
2124 {
2125         struct wq_flusher this_flusher = {
2126                 .list = LIST_HEAD_INIT(this_flusher.list),
2127                 .flush_color = -1,
2128                 .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
2129         };
2130         int next_color;
2131
2132         lock_map_acquire(&wq->lockdep_map);
2133         lock_map_release(&wq->lockdep_map);
2134
2135         mutex_lock(&wq->flush_mutex);
2136
2137         /*
2138          * Start-to-wait phase
2139          */
2140         next_color = work_next_color(wq->work_color);
2141
2142         if (next_color != wq->flush_color) {
2143                 /*
2144                  * Color space is not full.  The current work_color
2145                  * becomes our flush_color and work_color is advanced
2146                  * by one.
2147                  */
2148                 BUG_ON(!list_empty(&wq->flusher_overflow));
2149                 this_flusher.flush_color = wq->work_color;
2150                 wq->work_color = next_color;
2151
2152                 if (!wq->first_flusher) {
2153                         /* no flush in progress, become the first flusher */
2154                         BUG_ON(wq->flush_color != this_flusher.flush_color);
2155
2156                         wq->first_flusher = &this_flusher;
2157
2158                         if (!flush_workqueue_prep_cwqs(wq, wq->flush_color,
2159                                                        wq->work_color)) {
2160                                 /* nothing to flush, done */
2161                                 wq->flush_color = next_color;
2162                                 wq->first_flusher = NULL;
2163                                 goto out_unlock;
2164                         }
2165                 } else {
2166                         /* wait in queue */
2167                         BUG_ON(wq->flush_color == this_flusher.flush_color);
2168                         list_add_tail(&this_flusher.list, &wq->flusher_queue);
2169                         flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2170                 }
2171         } else {
2172                 /*
2173                  * Oops, color space is full, wait on overflow queue.
2174                  * The next flush completion will assign us
2175                  * flush_color and transfer to flusher_queue.
2176                  */
2177                 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2178         }
2179
2180         mutex_unlock(&wq->flush_mutex);
2181
2182         wait_for_completion(&this_flusher.done);
2183
2184         /*
2185          * Wake-up-and-cascade phase
2186          *
2187          * First flushers are responsible for cascading flushes and
2188          * handling overflow.  Non-first flushers can simply return.
2189          */
2190         if (wq->first_flusher != &this_flusher)
2191                 return;
2192
2193         mutex_lock(&wq->flush_mutex);
2194
2195         /* we might have raced, check again with mutex held */
2196         if (wq->first_flusher != &this_flusher)
2197                 goto out_unlock;
2198
2199         wq->first_flusher = NULL;
2200
2201         BUG_ON(!list_empty(&this_flusher.list));
2202         BUG_ON(wq->flush_color != this_flusher.flush_color);
2203
2204         while (true) {
2205                 struct wq_flusher *next, *tmp;
2206
2207                 /* complete all the flushers sharing the current flush color */
2208                 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2209                         if (next->flush_color != wq->flush_color)
2210                                 break;
2211                         list_del_init(&next->list);
2212                         complete(&next->done);
2213                 }
2214
2215                 BUG_ON(!list_empty(&wq->flusher_overflow) &&
2216                        wq->flush_color != work_next_color(wq->work_color));
2217
2218                 /* this flush_color is finished, advance by one */
2219                 wq->flush_color = work_next_color(wq->flush_color);
2220
2221                 /* one color has been freed, handle overflow queue */
2222                 if (!list_empty(&wq->flusher_overflow)) {
2223                         /*
2224                          * Assign the same color to all overflowed
2225                          * flushers, advance work_color and append to
2226                          * flusher_queue.  This is the start-to-wait
2227                          * phase for these overflowed flushers.
2228                          */
2229                         list_for_each_entry(tmp, &wq->flusher_overflow, list)
2230                                 tmp->flush_color = wq->work_color;
2231
2232                         wq->work_color = work_next_color(wq->work_color);
2233
2234                         list_splice_tail_init(&wq->flusher_overflow,
2235                                               &wq->flusher_queue);
2236                         flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2237                 }
2238
2239                 if (list_empty(&wq->flusher_queue)) {
2240                         BUG_ON(wq->flush_color != wq->work_color);
2241                         break;
2242                 }
2243
2244                 /*
2245                  * Need to flush more colors.  Make the next flusher
2246                  * the new first flusher and arm cwqs.
2247                  */
2248                 BUG_ON(wq->flush_color == wq->work_color);
2249                 BUG_ON(wq->flush_color != next->flush_color);
2250
2251                 list_del_init(&next->list);
2252                 wq->first_flusher = next;
2253
2254                 if (flush_workqueue_prep_cwqs(wq, wq->flush_color, -1))
2255                         break;
2256
2257                 /*
2258                  * Meh... this color is already done, clear first
2259                  * flusher and repeat cascading.
2260                  */
2261                 wq->first_flusher = NULL;
2262         }
2263
2264 out_unlock:
2265         mutex_unlock(&wq->flush_mutex);
2266 }
2267 EXPORT_SYMBOL_GPL(flush_workqueue);
2268
2269 /**
2270  * flush_work - block until a work_struct's callback has terminated
2271  * @work: the work which is to be flushed
2272  *
2273  * Returns false if @work has already terminated.
2274  *
2275  * It is expected that, prior to calling flush_work(), the caller has
2276  * arranged for the work to not be requeued, otherwise it doesn't make
2277  * sense to use this function.
2278  */
2279 int flush_work(struct work_struct *work)
2280 {
2281         struct worker *worker = NULL;
2282         struct global_cwq *gcwq;
2283         struct cpu_workqueue_struct *cwq;
2284         struct wq_barrier barr;
2285
2286         might_sleep();
2287         gcwq = get_work_gcwq(work);
2288         if (!gcwq)
2289                 return 0;
2290
2291         spin_lock_irq(&gcwq->lock);
2292         if (!list_empty(&work->entry)) {
2293                 /*
2294                  * See the comment near try_to_grab_pending()->smp_rmb().
2295                  * If it was re-queued to a different gcwq under us, we
2296                  * are not going to wait.
2297                  */
2298                 smp_rmb();
2299                 cwq = get_work_cwq(work);
2300                 if (unlikely(!cwq || gcwq != cwq->gcwq))
2301                         goto already_gone;
2302         } else {
2303                 worker = find_worker_executing_work(gcwq, work);
2304                 if (!worker)
2305                         goto already_gone;
2306                 cwq = worker->current_cwq;
2307         }
2308
2309         insert_wq_barrier(cwq, &barr, work, worker);
2310         spin_unlock_irq(&gcwq->lock);
2311
2312         lock_map_acquire(&cwq->wq->lockdep_map);
2313         lock_map_release(&cwq->wq->lockdep_map);
2314
2315         wait_for_completion(&barr.done);
2316         destroy_work_on_stack(&barr.work);
2317         return 1;
2318 already_gone:
2319         spin_unlock_irq(&gcwq->lock);
2320         return 0;
2321 }
2322 EXPORT_SYMBOL_GPL(flush_work);
2323
2324 /*
2325  * Upon a successful return (>= 0), the caller "owns" WORK_STRUCT_PENDING bit,
2326  * so this work can't be re-armed in any way.
2327  */
2328 static int try_to_grab_pending(struct work_struct *work)
2329 {
2330         struct global_cwq *gcwq;
2331         int ret = -1;
2332
2333         if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
2334                 return 0;
2335
2336         /*
2337          * The queueing is in progress, or it is already queued. Try to
2338          * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
2339          */
2340         gcwq = get_work_gcwq(work);
2341         if (!gcwq)
2342                 return ret;
2343
2344         spin_lock_irq(&gcwq->lock);
2345         if (!list_empty(&work->entry)) {
2346                 /*
2347                  * This work is queued, but perhaps we locked the wrong gcwq.
2348                  * In that case we must see the new value after rmb(), see
2349                  * insert_work()->wmb().
2350                  */
2351                 smp_rmb();
2352                 if (gcwq == get_work_gcwq(work)) {
2353                         debug_work_deactivate(work);
2354                         list_del_init(&work->entry);
2355                         cwq_dec_nr_in_flight(get_work_cwq(work),
2356                                              get_work_color(work));
2357                         ret = 1;
2358                 }
2359         }
2360         spin_unlock_irq(&gcwq->lock);
2361
2362         return ret;
2363 }
2364
2365 static void wait_on_cpu_work(struct global_cwq *gcwq, struct work_struct *work)
2366 {
2367         struct wq_barrier barr;
2368         struct worker *worker;
2369
2370         spin_lock_irq(&gcwq->lock);
2371
2372         worker = find_worker_executing_work(gcwq, work);
2373         if (unlikely(worker))
2374                 insert_wq_barrier(worker->current_cwq, &barr, work, worker);
2375
2376         spin_unlock_irq(&gcwq->lock);
2377
2378         if (unlikely(worker)) {
2379                 wait_for_completion(&barr.done);
2380                 destroy_work_on_stack(&barr.work);
2381         }
2382 }
2383
2384 static void wait_on_work(struct work_struct *work)
2385 {
2386         int cpu;
2387
2388         might_sleep();
2389
2390         lock_map_acquire(&work->lockdep_map);
2391         lock_map_release(&work->lockdep_map);
2392
2393         for_each_gcwq_cpu(cpu)
2394                 wait_on_cpu_work(get_gcwq(cpu), work);
2395 }
2396
2397 static int __cancel_work_timer(struct work_struct *work,
2398                                 struct timer_list* timer)
2399 {
2400         int ret;
2401
2402         do {
2403                 ret = (timer && likely(del_timer(timer)));
2404                 if (!ret)
2405                         ret = try_to_grab_pending(work);
2406                 wait_on_work(work);
2407         } while (unlikely(ret < 0));
2408
2409         clear_work_data(work);
2410         return ret;
2411 }
2412
2413 /**
2414  * cancel_work_sync - block until a work_struct's callback has terminated
2415  * @work: the work which is to be flushed
2416  *
2417  * Returns true if @work was pending.
2418  *
2419  * cancel_work_sync() will cancel the work if it is queued. If the work's
2420  * callback appears to be running, cancel_work_sync() will block until it
2421  * has completed.
2422  *
2423  * It is possible to use this function if the work re-queues itself. It can
2424  * cancel the work even if it migrates to another workqueue, however in that
2425  * case it only guarantees that work->func() has completed on the last queued
2426  * workqueue.
2427  *
2428  * cancel_work_sync(&delayed_work->work) should be used only if ->timer is not
2429  * pending, otherwise it goes into a busy-wait loop until the timer expires.
2430  *
2431  * The caller must ensure that workqueue_struct on which this work was last
2432  * queued can't be destroyed before this function returns.
2433  */
2434 int cancel_work_sync(struct work_struct *work)
2435 {
2436         return __cancel_work_timer(work, NULL);
2437 }
2438 EXPORT_SYMBOL_GPL(cancel_work_sync);
2439
2440 /**
2441  * cancel_delayed_work_sync - reliably kill off a delayed work.
2442  * @dwork: the delayed work struct
2443  *
2444  * Returns true if @dwork was pending.
2445  *
2446  * It is possible to use this function if @dwork rearms itself via queue_work()
2447  * or queue_delayed_work(). See also the comment for cancel_work_sync().
2448  */
2449 int cancel_delayed_work_sync(struct delayed_work *dwork)
2450 {
2451         return __cancel_work_timer(&dwork->work, &dwork->timer);
2452 }
2453 EXPORT_SYMBOL(cancel_delayed_work_sync);
2454
2455 /**
2456  * schedule_work - put work task in global workqueue
2457  * @work: job to be done
2458  *
2459  * Returns zero if @work was already on the kernel-global workqueue and
2460  * non-zero otherwise.
2461  *
2462  * This puts a job in the kernel-global workqueue if it was not already
2463  * queued and leaves it in the same position on the kernel-global
2464  * workqueue otherwise.
2465  */
2466 int schedule_work(struct work_struct *work)
2467 {
2468         return queue_work(system_wq, work);
2469 }
2470 EXPORT_SYMBOL(schedule_work);
2471
2472 /*
2473  * schedule_work_on - put work task on a specific cpu
2474  * @cpu: cpu to put the work task on
2475  * @work: job to be done
2476  *
2477  * This puts a job on a specific cpu
2478  */
2479 int schedule_work_on(int cpu, struct work_struct *work)
2480 {
2481         return queue_work_on(cpu, system_wq, work);
2482 }
2483 EXPORT_SYMBOL(schedule_work_on);
2484
2485 /**
2486  * schedule_delayed_work - put work task in global workqueue after delay
2487  * @dwork: job to be done
2488  * @delay: number of jiffies to wait or 0 for immediate execution
2489  *
2490  * After waiting for a given time this puts a job in the kernel-global
2491  * workqueue.
2492  */
2493 int schedule_delayed_work(struct delayed_work *dwork,
2494                                         unsigned long delay)
2495 {
2496         return queue_delayed_work(system_wq, dwork, delay);
2497 }
2498 EXPORT_SYMBOL(schedule_delayed_work);
2499
2500 /**
2501  * flush_delayed_work - block until a dwork_struct's callback has terminated
2502  * @dwork: the delayed work which is to be flushed
2503  *
2504  * Any timeout is cancelled, and any pending work is run immediately.
2505  */
2506 void flush_delayed_work(struct delayed_work *dwork)
2507 {
2508         if (del_timer_sync(&dwork->timer)) {
2509                 __queue_work(get_cpu(), get_work_cwq(&dwork->work)->wq,
2510                              &dwork->work);
2511                 put_cpu();
2512         }
2513         flush_work(&dwork->work);
2514 }
2515 EXPORT_SYMBOL(flush_delayed_work);
2516
2517 /**
2518  * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
2519  * @cpu: cpu to use
2520  * @dwork: job to be done
2521  * @delay: number of jiffies to wait
2522  *
2523  * After waiting for a given time this puts a job in the kernel-global
2524  * workqueue on the specified CPU.
2525  */
2526 int schedule_delayed_work_on(int cpu,
2527                         struct delayed_work *dwork, unsigned long delay)
2528 {
2529         return queue_delayed_work_on(cpu, system_wq, dwork, delay);
2530 }
2531 EXPORT_SYMBOL(schedule_delayed_work_on);
2532
2533 /**
2534  * schedule_on_each_cpu - call a function on each online CPU from keventd
2535  * @func: the function to call
2536  *
2537  * Returns zero on success.
2538  * Returns -ve errno on failure.
2539  *
2540  * schedule_on_each_cpu() is very slow.
2541  */
2542 int schedule_on_each_cpu(work_func_t func)
2543 {
2544         int cpu;
2545         struct work_struct *works;
2546
2547         works = alloc_percpu(struct work_struct);
2548         if (!works)
2549                 return -ENOMEM;
2550
2551         get_online_cpus();
2552
2553         for_each_online_cpu(cpu) {
2554                 struct work_struct *work = per_cpu_ptr(works, cpu);
2555
2556                 INIT_WORK(work, func);
2557                 schedule_work_on(cpu, work);
2558         }
2559
2560         for_each_online_cpu(cpu)
2561                 flush_work(per_cpu_ptr(works, cpu));
2562
2563         put_online_cpus();
2564         free_percpu(works);
2565         return 0;
2566 }
2567
2568 /**
2569  * flush_scheduled_work - ensure that any scheduled work has run to completion.
2570  *
2571  * Forces execution of the kernel-global workqueue and blocks until its
2572  * completion.
2573  *
2574  * Think twice before calling this function!  It's very easy to get into
2575  * trouble if you don't take great care.  Either of the following situations
2576  * will lead to deadlock:
2577  *
2578  *      One of the work items currently on the workqueue needs to acquire
2579  *      a lock held by your code or its caller.
2580  *
2581  *      Your code is running in the context of a work routine.
2582  *
2583  * They will be detected by lockdep when they occur, but the first might not
2584  * occur very often.  It depends on what work items are on the workqueue and
2585  * what locks they need, which you have no control over.
2586  *
2587  * In most situations flushing the entire workqueue is overkill; you merely
2588  * need to know that a particular work item isn't queued and isn't running.
2589  * In such cases you should use cancel_delayed_work_sync() or
2590  * cancel_work_sync() instead.
2591  */
2592 void flush_scheduled_work(void)
2593 {
2594         flush_workqueue(system_wq);
2595 }
2596 EXPORT_SYMBOL(flush_scheduled_work);
2597
2598 /**
2599  * execute_in_process_context - reliably execute the routine with user context
2600  * @fn:         the function to execute
2601  * @ew:         guaranteed storage for the execute work structure (must
2602  *              be available when the work executes)
2603  *
2604  * Executes the function immediately if process context is available,
2605  * otherwise schedules the function for delayed execution.
2606  *
2607  * Returns:     0 - function was executed
2608  *              1 - function was scheduled for execution
2609  */
2610 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
2611 {
2612         if (!in_interrupt()) {
2613                 fn(&ew->work);
2614                 return 0;
2615         }
2616
2617         INIT_WORK(&ew->work, fn);
2618         schedule_work(&ew->work);
2619
2620         return 1;
2621 }
2622 EXPORT_SYMBOL_GPL(execute_in_process_context);
2623
2624 int keventd_up(void)
2625 {
2626         return system_wq != NULL;
2627 }
2628
2629 static int alloc_cwqs(struct workqueue_struct *wq)
2630 {
2631         /*
2632          * cwqs are forced aligned according to WORK_STRUCT_FLAG_BITS.
2633          * Make sure that the alignment isn't lower than that of
2634          * unsigned long long.
2635          */
2636         const size_t size = sizeof(struct cpu_workqueue_struct);
2637         const size_t align = max_t(size_t, 1 << WORK_STRUCT_FLAG_BITS,
2638                                    __alignof__(unsigned long long));
2639 #ifdef CONFIG_SMP
2640         bool percpu = !(wq->flags & WQ_UNBOUND);
2641 #else
2642         bool percpu = false;
2643 #endif
2644
2645         if (percpu)
2646                 wq->cpu_wq.pcpu = __alloc_percpu(size, align);
2647         else {
2648                 void *ptr;
2649
2650                 /*
2651                  * Allocate enough room to align cwq and put an extra
2652                  * pointer at the end pointing back to the originally
2653                  * allocated pointer which will be used for free.
2654                  */
2655                 ptr = kzalloc(size + align + sizeof(void *), GFP_KERNEL);
2656                 if (ptr) {
2657                         wq->cpu_wq.single = PTR_ALIGN(ptr, align);
2658                         *(void **)(wq->cpu_wq.single + 1) = ptr;
2659                 }
2660         }
2661
2662         /* just in case, make sure it's actually aligned */
2663         BUG_ON(!IS_ALIGNED(wq->cpu_wq.v, align));
2664         return wq->cpu_wq.v ? 0 : -ENOMEM;
2665 }
2666
2667 static void free_cwqs(struct workqueue_struct *wq)
2668 {
2669 #ifdef CONFIG_SMP
2670         bool percpu = !(wq->flags & WQ_UNBOUND);
2671 #else
2672         bool percpu = false;
2673 #endif
2674
2675         if (percpu)
2676                 free_percpu(wq->cpu_wq.pcpu);
2677         else if (wq->cpu_wq.single) {
2678                 /* the pointer to free is stored right after the cwq */
2679                 kfree(*(void **)(wq->cpu_wq.single + 1));
2680         }
2681 }
2682
2683 static int wq_clamp_max_active(int max_active, unsigned int flags,
2684                                const char *name)
2685 {
2686         int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
2687
2688         if (max_active < 1 || max_active > lim)
2689                 printk(KERN_WARNING "workqueue: max_active %d requested for %s "
2690                        "is out of range, clamping between %d and %d\n",
2691                        max_active, name, 1, lim);
2692
2693         return clamp_val(max_active, 1, lim);
2694 }
2695
2696 struct workqueue_struct *__alloc_workqueue_key(const char *name,
2697                                                unsigned int flags,
2698                                                int max_active,
2699                                                struct lock_class_key *key,
2700                                                const char *lock_name)
2701 {
2702         struct workqueue_struct *wq;
2703         unsigned int cpu;
2704
2705         /*
2706          * Unbound workqueues aren't concurrency managed and should be
2707          * dispatched to workers immediately.
2708          */
2709         if (flags & WQ_UNBOUND)
2710                 flags |= WQ_HIGHPRI;
2711
2712         max_active = max_active ?: WQ_DFL_ACTIVE;
2713         max_active = wq_clamp_max_active(max_active, flags, name);
2714
2715         wq = kzalloc(sizeof(*wq), GFP_KERNEL);
2716         if (!wq)
2717                 goto err;
2718
2719         wq->flags = flags;
2720         wq->saved_max_active = max_active;
2721         mutex_init(&wq->flush_mutex);
2722         atomic_set(&wq->nr_cwqs_to_flush, 0);
2723         INIT_LIST_HEAD(&wq->flusher_queue);
2724         INIT_LIST_HEAD(&wq->flusher_overflow);
2725
2726         wq->name = name;
2727         lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
2728         INIT_LIST_HEAD(&wq->list);
2729
2730         if (alloc_cwqs(wq) < 0)
2731                 goto err;
2732
2733         for_each_cwq_cpu(cpu, wq) {
2734                 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2735                 struct global_cwq *gcwq = get_gcwq(cpu);
2736
2737                 BUG_ON((unsigned long)cwq & WORK_STRUCT_FLAG_MASK);
2738                 cwq->gcwq = gcwq;
2739                 cwq->wq = wq;
2740                 cwq->flush_color = -1;
2741                 cwq->max_active = max_active;
2742                 INIT_LIST_HEAD(&cwq->delayed_works);
2743         }
2744
2745         if (flags & WQ_RESCUER) {
2746                 struct worker *rescuer;
2747
2748                 if (!alloc_mayday_mask(&wq->mayday_mask, GFP_KERNEL))
2749                         goto err;
2750
2751                 wq->rescuer = rescuer = alloc_worker();
2752                 if (!rescuer)
2753                         goto err;
2754
2755                 rescuer->task = kthread_create(rescuer_thread, wq, "%s", name);
2756                 if (IS_ERR(rescuer->task))
2757                         goto err;
2758
2759                 wq->rescuer = rescuer;
2760                 rescuer->task->flags |= PF_THREAD_BOUND;
2761                 wake_up_process(rescuer->task);
2762         }
2763
2764         /*
2765          * workqueue_lock protects global freeze state and workqueues
2766          * list.  Grab it, set max_active accordingly and add the new
2767          * workqueue to workqueues list.
2768          */
2769         spin_lock(&workqueue_lock);
2770
2771         if (workqueue_freezing && wq->flags & WQ_FREEZEABLE)
2772                 for_each_cwq_cpu(cpu, wq)
2773                         get_cwq(cpu, wq)->max_active = 0;
2774
2775         list_add(&wq->list, &workqueues);
2776
2777         spin_unlock(&workqueue_lock);
2778
2779         return wq;
2780 err:
2781         if (wq) {
2782                 free_cwqs(wq);
2783                 free_mayday_mask(wq->mayday_mask);
2784                 kfree(wq->rescuer);
2785                 kfree(wq);
2786         }
2787         return NULL;
2788 }
2789 EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
2790
2791 /**
2792  * destroy_workqueue - safely terminate a workqueue
2793  * @wq: target workqueue
2794  *
2795  * Safely destroy a workqueue. All work currently pending will be done first.
2796  */
2797 void destroy_workqueue(struct workqueue_struct *wq)
2798 {
2799         unsigned int cpu;
2800
2801         flush_workqueue(wq);
2802
2803         /*
2804          * wq list is used to freeze wq, remove from list after
2805          * flushing is complete in case freeze races us.
2806          */
2807         spin_lock(&workqueue_lock);
2808         list_del(&wq->list);
2809         spin_unlock(&workqueue_lock);
2810
2811         /* sanity check */
2812         for_each_cwq_cpu(cpu, wq) {
2813                 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2814                 int i;
2815
2816                 for (i = 0; i < WORK_NR_COLORS; i++)
2817                         BUG_ON(cwq->nr_in_flight[i]);
2818                 BUG_ON(cwq->nr_active);
2819                 BUG_ON(!list_empty(&cwq->delayed_works));
2820         }
2821
2822         if (wq->flags & WQ_RESCUER) {
2823                 kthread_stop(wq->rescuer->task);
2824                 free_mayday_mask(wq->mayday_mask);
2825         }
2826
2827         free_cwqs(wq);
2828         kfree(wq);
2829 }
2830 EXPORT_SYMBOL_GPL(destroy_workqueue);
2831
2832 /**
2833  * workqueue_set_max_active - adjust max_active of a workqueue
2834  * @wq: target workqueue
2835  * @max_active: new max_active value.
2836  *
2837  * Set max_active of @wq to @max_active.
2838  *
2839  * CONTEXT:
2840  * Don't call from IRQ context.
2841  */
2842 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
2843 {
2844         unsigned int cpu;
2845
2846         max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
2847
2848         spin_lock(&workqueue_lock);
2849
2850         wq->saved_max_active = max_active;
2851
2852         for_each_cwq_cpu(cpu, wq) {
2853                 struct global_cwq *gcwq = get_gcwq(cpu);
2854
2855                 spin_lock_irq(&gcwq->lock);
2856
2857                 if (!(wq->flags & WQ_FREEZEABLE) ||
2858                     !(gcwq->flags & GCWQ_FREEZING))
2859                         get_cwq(gcwq->cpu, wq)->max_active = max_active;
2860
2861                 spin_unlock_irq(&gcwq->lock);
2862         }
2863
2864         spin_unlock(&workqueue_lock);
2865 }
2866 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
2867
2868 /**
2869  * workqueue_congested - test whether a workqueue is congested
2870  * @cpu: CPU in question
2871  * @wq: target workqueue
2872  *
2873  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
2874  * no synchronization around this function and the test result is
2875  * unreliable and only useful as advisory hints or for debugging.
2876  *
2877  * RETURNS:
2878  * %true if congested, %false otherwise.
2879  */
2880 bool workqueue_congested(unsigned int cpu, struct workqueue_struct *wq)
2881 {
2882         struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2883
2884         return !list_empty(&cwq->delayed_works);
2885 }
2886 EXPORT_SYMBOL_GPL(workqueue_congested);
2887
2888 /**
2889  * work_cpu - return the last known associated cpu for @work
2890  * @work: the work of interest
2891  *
2892  * RETURNS:
2893  * CPU number if @work was ever queued.  WORK_CPU_NONE otherwise.
2894  */
2895 unsigned int work_cpu(struct work_struct *work)
2896 {
2897         struct global_cwq *gcwq = get_work_gcwq(work);
2898
2899         return gcwq ? gcwq->cpu : WORK_CPU_NONE;
2900 }
2901 EXPORT_SYMBOL_GPL(work_cpu);
2902
2903 /**
2904  * work_busy - test whether a work is currently pending or running
2905  * @work: the work to be tested
2906  *
2907  * Test whether @work is currently pending or running.  There is no
2908  * synchronization around this function and the test result is
2909  * unreliable and only useful as advisory hints or for debugging.
2910  * Especially for reentrant wqs, the pending state might hide the
2911  * running state.
2912  *
2913  * RETURNS:
2914  * OR'd bitmask of WORK_BUSY_* bits.
2915  */
2916 unsigned int work_busy(struct work_struct *work)
2917 {
2918         struct global_cwq *gcwq = get_work_gcwq(work);
2919         unsigned long flags;
2920         unsigned int ret = 0;
2921
2922         if (!gcwq)
2923                 return false;
2924
2925         spin_lock_irqsave(&gcwq->lock, flags);
2926
2927         if (work_pending(work))
2928                 ret |= WORK_BUSY_PENDING;
2929         if (find_worker_executing_work(gcwq, work))
2930                 ret |= WORK_BUSY_RUNNING;
2931
2932         spin_unlock_irqrestore(&gcwq->lock, flags);
2933
2934         return ret;
2935 }
2936 EXPORT_SYMBOL_GPL(work_busy);
2937
2938 /*
2939  * CPU hotplug.
2940  *
2941  * There are two challenges in supporting CPU hotplug.  Firstly, there
2942  * are a lot of assumptions on strong associations among work, cwq and
2943  * gcwq which make migrating pending and scheduled works very
2944  * difficult to implement without impacting hot paths.  Secondly,
2945  * gcwqs serve mix of short, long and very long running works making
2946  * blocked draining impractical.
2947  *
2948  * This is solved by allowing a gcwq to be detached from CPU, running
2949  * it with unbound (rogue) workers and allowing it to be reattached
2950  * later if the cpu comes back online.  A separate thread is created
2951  * to govern a gcwq in such state and is called the trustee of the
2952  * gcwq.
2953  *
2954  * Trustee states and their descriptions.
2955  *
2956  * START        Command state used on startup.  On CPU_DOWN_PREPARE, a
2957  *              new trustee is started with this state.
2958  *
2959  * IN_CHARGE    Once started, trustee will enter this state after
2960  *              assuming the manager role and making all existing
2961  *              workers rogue.  DOWN_PREPARE waits for trustee to
2962  *              enter this state.  After reaching IN_CHARGE, trustee
2963  *              tries to execute the pending worklist until it's empty
2964  *              and the state is set to BUTCHER, or the state is set
2965  *              to RELEASE.
2966  *
2967  * BUTCHER      Command state which is set by the cpu callback after
2968  *              the cpu has went down.  Once this state is set trustee
2969  *              knows that there will be no new works on the worklist
2970  *              and once the worklist is empty it can proceed to
2971  *              killing idle workers.
2972  *
2973  * RELEASE      Command state which is set by the cpu callback if the
2974  *              cpu down has been canceled or it has come online
2975  *              again.  After recognizing this state, trustee stops
2976  *              trying to drain or butcher and clears ROGUE, rebinds
2977  *              all remaining workers back to the cpu and releases
2978  *              manager role.
2979  *
2980  * DONE         Trustee will enter this state after BUTCHER or RELEASE
2981  *              is complete.
2982  *
2983  *          trustee                 CPU                draining
2984  *         took over                down               complete
2985  * START -----------> IN_CHARGE -----------> BUTCHER -----------> DONE
2986  *                        |                     |                  ^
2987  *                        | CPU is back online  v   return workers |
2988  *                         ----------------> RELEASE --------------
2989  */
2990
2991 /**
2992  * trustee_wait_event_timeout - timed event wait for trustee
2993  * @cond: condition to wait for
2994  * @timeout: timeout in jiffies
2995  *
2996  * wait_event_timeout() for trustee to use.  Handles locking and
2997  * checks for RELEASE request.
2998  *
2999  * CONTEXT:
3000  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
3001  * multiple times.  To be used by trustee.
3002  *
3003  * RETURNS:
3004  * Positive indicating left time if @cond is satisfied, 0 if timed
3005  * out, -1 if canceled.
3006  */
3007 #define trustee_wait_event_timeout(cond, timeout) ({                    \
3008         long __ret = (timeout);                                         \
3009         while (!((cond) || (gcwq->trustee_state == TRUSTEE_RELEASE)) && \
3010                __ret) {                                                 \
3011                 spin_unlock_irq(&gcwq->lock);                           \
3012                 __wait_event_timeout(gcwq->trustee_wait, (cond) ||      \
3013                         (gcwq->trustee_state == TRUSTEE_RELEASE),       \
3014                         __ret);                                         \
3015                 spin_lock_irq(&gcwq->lock);                             \
3016         }                                                               \
3017         gcwq->trustee_state == TRUSTEE_RELEASE ? -1 : (__ret);          \
3018 })
3019
3020 /**
3021  * trustee_wait_event - event wait for trustee
3022  * @cond: condition to wait for
3023  *
3024  * wait_event() for trustee to use.  Automatically handles locking and
3025  * checks for CANCEL request.
3026  *
3027  * CONTEXT:
3028  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
3029  * multiple times.  To be used by trustee.
3030  *
3031  * RETURNS:
3032  * 0 if @cond is satisfied, -1 if canceled.
3033  */
3034 #define trustee_wait_event(cond) ({                                     \
3035         long __ret1;                                                    \
3036         __ret1 = trustee_wait_event_timeout(cond, MAX_SCHEDULE_TIMEOUT);\
3037         __ret1 < 0 ? -1 : 0;                                            \
3038 })
3039
3040 static int __cpuinit trustee_thread(void *__gcwq)
3041 {
3042         struct global_cwq *gcwq = __gcwq;
3043         struct worker *worker;
3044         struct work_struct *work;
3045         struct hlist_node *pos;
3046         long rc;
3047         int i;
3048
3049         BUG_ON(gcwq->cpu != smp_processor_id());
3050
3051         spin_lock_irq(&gcwq->lock);
3052         /*
3053          * Claim the manager position and make all workers rogue.
3054          * Trustee must be bound to the target cpu and can't be
3055          * cancelled.
3056          */
3057         BUG_ON(gcwq->cpu != smp_processor_id());
3058         rc = trustee_wait_event(!(gcwq->flags & GCWQ_MANAGING_WORKERS));
3059         BUG_ON(rc < 0);
3060
3061         gcwq->flags |= GCWQ_MANAGING_WORKERS;
3062
3063         list_for_each_entry(worker, &gcwq->idle_list, entry)
3064                 worker->flags |= WORKER_ROGUE;
3065
3066         for_each_busy_worker(worker, i, pos, gcwq)
3067                 worker->flags |= WORKER_ROGUE;
3068
3069         /*
3070          * Call schedule() so that we cross rq->lock and thus can
3071          * guarantee sched callbacks see the rogue flag.  This is
3072          * necessary as scheduler callbacks may be invoked from other
3073          * cpus.
3074          */
3075         spin_unlock_irq(&gcwq->lock);
3076         schedule();
3077         spin_lock_irq(&gcwq->lock);
3078
3079         /*
3080          * Sched callbacks are disabled now.  Zap nr_running.  After
3081          * this, nr_running stays zero and need_more_worker() and
3082          * keep_working() are always true as long as the worklist is
3083          * not empty.
3084          */
3085         atomic_set(get_gcwq_nr_running(gcwq->cpu), 0);
3086
3087         spin_unlock_irq(&gcwq->lock);
3088         del_timer_sync(&gcwq->idle_timer);
3089         spin_lock_irq(&gcwq->lock);
3090
3091         /*
3092          * We're now in charge.  Notify and proceed to drain.  We need
3093          * to keep the gcwq running during the whole CPU down
3094          * procedure as other cpu hotunplug callbacks may need to
3095          * flush currently running tasks.
3096          */
3097         gcwq->trustee_state = TRUSTEE_IN_CHARGE;
3098         wake_up_all(&gcwq->trustee_wait);
3099
3100         /*
3101          * The original cpu is in the process of dying and may go away
3102          * anytime now.  When that happens, we and all workers would
3103          * be migrated to other cpus.  Try draining any left work.  We
3104          * want to get it over with ASAP - spam rescuers, wake up as
3105          * many idlers as necessary and create new ones till the
3106          * worklist is empty.  Note that if the gcwq is frozen, there
3107          * may be frozen works in freezeable cwqs.  Don't declare
3108          * completion while frozen.
3109          */
3110         while (gcwq->nr_workers != gcwq->nr_idle ||
3111                gcwq->flags & GCWQ_FREEZING ||
3112                gcwq->trustee_state == TRUSTEE_IN_CHARGE) {
3113                 int nr_works = 0;
3114
3115                 list_for_each_entry(work, &gcwq->worklist, entry) {
3116                         send_mayday(work);
3117                         nr_works++;
3118                 }
3119
3120                 list_for_each_entry(worker, &gcwq->idle_list, entry) {
3121                         if (!nr_works--)
3122                                 break;
3123                         wake_up_process(worker->task);
3124                 }
3125
3126                 if (need_to_create_worker(gcwq)) {
3127                         spin_unlock_irq(&gcwq->lock);
3128                         worker = create_worker(gcwq, false);
3129                         spin_lock_irq(&gcwq->lock);
3130                         if (worker) {
3131                                 worker->flags |= WORKER_ROGUE;
3132                                 start_worker(worker);
3133                         }
3134                 }
3135
3136                 /* give a breather */
3137                 if (trustee_wait_event_timeout(false, TRUSTEE_COOLDOWN) < 0)
3138                         break;
3139         }
3140
3141         /*
3142          * Either all works have been scheduled and cpu is down, or
3143          * cpu down has already been canceled.  Wait for and butcher
3144          * all workers till we're canceled.
3145          */
3146         do {
3147                 rc = trustee_wait_event(!list_empty(&gcwq->idle_list));
3148                 while (!list_empty(&gcwq->idle_list))
3149                         destroy_worker(list_first_entry(&gcwq->idle_list,
3150                                                         struct worker, entry));
3151         } while (gcwq->nr_workers && rc >= 0);
3152
3153         /*
3154          * At this point, either draining has completed and no worker
3155          * is left, or cpu down has been canceled or the cpu is being
3156          * brought back up.  There shouldn't be any idle one left.
3157          * Tell the remaining busy ones to rebind once it finishes the
3158          * currently scheduled works by scheduling the rebind_work.
3159          */
3160         WARN_ON(!list_empty(&gcwq->idle_list));
3161
3162         for_each_busy_worker(worker, i, pos, gcwq) {
3163                 struct work_struct *rebind_work = &worker->rebind_work;
3164
3165                 /*
3166                  * Rebind_work may race with future cpu hotplug
3167                  * operations.  Use a separate flag to mark that
3168                  * rebinding is scheduled.
3169                  */
3170                 worker->flags |= WORKER_REBIND;
3171                 worker->flags &= ~WORKER_ROGUE;
3172
3173                 /* queue rebind_work, wq doesn't matter, use the default one */
3174                 if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
3175                                      work_data_bits(rebind_work)))
3176                         continue;
3177
3178                 debug_work_activate(rebind_work);
3179                 insert_work(get_cwq(gcwq->cpu, system_wq), rebind_work,
3180                             worker->scheduled.next,
3181                             work_color_to_flags(WORK_NO_COLOR));
3182         }
3183
3184         /* relinquish manager role */
3185         gcwq->flags &= ~GCWQ_MANAGING_WORKERS;
3186
3187         /* notify completion */
3188         gcwq->trustee = NULL;
3189         gcwq->trustee_state = TRUSTEE_DONE;
3190         wake_up_all(&gcwq->trustee_wait);
3191         spin_unlock_irq(&gcwq->lock);
3192         return 0;
3193 }
3194
3195 /**
3196  * wait_trustee_state - wait for trustee to enter the specified state
3197  * @gcwq: gcwq the trustee of interest belongs to
3198  * @state: target state to wait for
3199  *
3200  * Wait for the trustee to reach @state.  DONE is already matched.
3201  *
3202  * CONTEXT:
3203  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
3204  * multiple times.  To be used by cpu_callback.
3205  */
3206 static void __cpuinit wait_trustee_state(struct global_cwq *gcwq, int state)
3207 {
3208         if (!(gcwq->trustee_state == state ||
3209               gcwq->trustee_state == TRUSTEE_DONE)) {
3210                 spin_unlock_irq(&gcwq->lock);
3211                 __wait_event(gcwq->trustee_wait,
3212                              gcwq->trustee_state == state ||
3213                              gcwq->trustee_state == TRUSTEE_DONE);
3214                 spin_lock_irq(&gcwq->lock);
3215         }
3216 }
3217
3218 static int __devinit workqueue_cpu_callback(struct notifier_block *nfb,
3219                                                 unsigned long action,
3220                                                 void *hcpu)
3221 {
3222         unsigned int cpu = (unsigned long)hcpu;
3223         struct global_cwq *gcwq = get_gcwq(cpu);
3224         struct task_struct *new_trustee = NULL;
3225         struct worker *uninitialized_var(new_worker);
3226         unsigned long flags;
3227
3228         action &= ~CPU_TASKS_FROZEN;
3229
3230         switch (action) {
3231         case CPU_DOWN_PREPARE:
3232                 new_trustee = kthread_create(trustee_thread, gcwq,
3233                                              "workqueue_trustee/%d\n", cpu);
3234                 if (IS_ERR(new_trustee))
3235                         return notifier_from_errno(PTR_ERR(new_trustee));
3236                 kthread_bind(new_trustee, cpu);
3237                 /* fall through */
3238         case CPU_UP_PREPARE:
3239                 BUG_ON(gcwq->first_idle);
3240                 new_worker = create_worker(gcwq, false);
3241                 if (!new_worker) {
3242                         if (new_trustee)
3243                                 kthread_stop(new_trustee);
3244                         return NOTIFY_BAD;
3245                 }
3246         }
3247
3248         /* some are called w/ irq disabled, don't disturb irq status */
3249         spin_lock_irqsave(&gcwq->lock, flags);
3250
3251         switch (action) {
3252         case CPU_DOWN_PREPARE:
3253                 /* initialize trustee and tell it to acquire the gcwq */
3254                 BUG_ON(gcwq->trustee || gcwq->trustee_state != TRUSTEE_DONE);
3255                 gcwq->trustee = new_trustee;
3256                 gcwq->trustee_state = TRUSTEE_START;
3257                 wake_up_process(gcwq->trustee);
3258                 wait_trustee_state(gcwq, TRUSTEE_IN_CHARGE);
3259                 /* fall through */
3260         case CPU_UP_PREPARE:
3261                 BUG_ON(gcwq->first_idle);
3262                 gcwq->first_idle = new_worker;
3263                 break;
3264
3265         case CPU_DYING:
3266                 /*
3267                  * Before this, the trustee and all workers except for
3268                  * the ones which are still executing works from
3269                  * before the last CPU down must be on the cpu.  After
3270                  * this, they'll all be diasporas.
3271                  */
3272                 gcwq->flags |= GCWQ_DISASSOCIATED;
3273                 break;
3274
3275         case CPU_POST_DEAD:
3276                 gcwq->trustee_state = TRUSTEE_BUTCHER;
3277                 /* fall through */
3278         case CPU_UP_CANCELED:
3279                 destroy_worker(gcwq->first_idle);
3280                 gcwq->first_idle = NULL;
3281                 break;
3282
3283         case CPU_DOWN_FAILED:
3284         case CPU_ONLINE:
3285                 gcwq->flags &= ~GCWQ_DISASSOCIATED;
3286                 if (gcwq->trustee_state != TRUSTEE_DONE) {
3287                         gcwq->trustee_state = TRUSTEE_RELEASE;
3288                         wake_up_process(gcwq->trustee);
3289                         wait_trustee_state(gcwq, TRUSTEE_DONE);
3290                 }
3291
3292                 /*
3293                  * Trustee is done and there might be no worker left.
3294                  * Put the first_idle in and request a real manager to
3295                  * take a look.
3296                  */
3297                 spin_unlock_irq(&gcwq->lock);
3298                 kthread_bind(gcwq->first_idle->task, cpu);
3299                 spin_lock_irq(&gcwq->lock);
3300                 gcwq->flags |= GCWQ_MANAGE_WORKERS;
3301                 start_worker(gcwq->first_idle);
3302                 gcwq->first_idle = NULL;
3303                 break;
3304         }
3305
3306         spin_unlock_irqrestore(&gcwq->lock, flags);
3307
3308         return notifier_from_errno(0);
3309 }
3310
3311 #ifdef CONFIG_SMP
3312
3313 struct work_for_cpu {
3314         struct completion completion;
3315         long (*fn)(void *);
3316         void *arg;
3317         long ret;
3318 };
3319
3320 static int do_work_for_cpu(void *_wfc)
3321 {
3322         struct work_for_cpu *wfc = _wfc;
3323         wfc->ret = wfc->fn(wfc->arg);
3324         complete(&wfc->completion);
3325         return 0;
3326 }
3327
3328 /**
3329  * work_on_cpu - run a function in user context on a particular cpu
3330  * @cpu: the cpu to run on
3331  * @fn: the function to run
3332  * @arg: the function arg
3333  *
3334  * This will return the value @fn returns.
3335  * It is up to the caller to ensure that the cpu doesn't go offline.
3336  * The caller must not hold any locks which would prevent @fn from completing.
3337  */
3338 long work_on_cpu(unsigned int cpu, long (*fn)(void *), void *arg)
3339 {
3340         struct task_struct *sub_thread;
3341         struct work_for_cpu wfc = {
3342                 .completion = COMPLETION_INITIALIZER_ONSTACK(wfc.completion),
3343                 .fn = fn,
3344                 .arg = arg,
3345         };
3346
3347         sub_thread = kthread_create(do_work_for_cpu, &wfc, "work_for_cpu");
3348         if (IS_ERR(sub_thread))
3349                 return PTR_ERR(sub_thread);
3350         kthread_bind(sub_thread, cpu);
3351         wake_up_process(sub_thread);
3352         wait_for_completion(&wfc.completion);
3353         return wfc.ret;
3354 }
3355 EXPORT_SYMBOL_GPL(work_on_cpu);
3356 #endif /* CONFIG_SMP */
3357
3358 #ifdef CONFIG_FREEZER
3359
3360 /**
3361  * freeze_workqueues_begin - begin freezing workqueues
3362  *
3363  * Start freezing workqueues.  After this function returns, all
3364  * freezeable workqueues will queue new works to their frozen_works
3365  * list instead of gcwq->worklist.
3366  *
3367  * CONTEXT:
3368  * Grabs and releases workqueue_lock and gcwq->lock's.
3369  */
3370 void freeze_workqueues_begin(void)
3371 {
3372         unsigned int cpu;
3373
3374         spin_lock(&workqueue_lock);
3375
3376         BUG_ON(workqueue_freezing);
3377         workqueue_freezing = true;
3378
3379         for_each_gcwq_cpu(cpu) {
3380                 struct global_cwq *gcwq = get_gcwq(cpu);
3381                 struct workqueue_struct *wq;
3382
3383                 spin_lock_irq(&gcwq->lock);
3384
3385                 BUG_ON(gcwq->flags & GCWQ_FREEZING);
3386                 gcwq->flags |= GCWQ_FREEZING;
3387
3388                 list_for_each_entry(wq, &workqueues, list) {
3389                         struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3390
3391                         if (cwq && wq->flags & WQ_FREEZEABLE)
3392                                 cwq->max_active = 0;
3393                 }
3394
3395                 spin_unlock_irq(&gcwq->lock);
3396         }
3397
3398         spin_unlock(&workqueue_lock);
3399 }
3400
3401 /**
3402  * freeze_workqueues_busy - are freezeable workqueues still busy?
3403  *
3404  * Check whether freezing is complete.  This function must be called
3405  * between freeze_workqueues_begin() and thaw_workqueues().
3406  *
3407  * CONTEXT:
3408  * Grabs and releases workqueue_lock.
3409  *
3410  * RETURNS:
3411  * %true if some freezeable workqueues are still busy.  %false if
3412  * freezing is complete.
3413  */
3414 bool freeze_workqueues_busy(void)
3415 {
3416         unsigned int cpu;
3417         bool busy = false;
3418
3419         spin_lock(&workqueue_lock);
3420
3421         BUG_ON(!workqueue_freezing);
3422
3423         for_each_gcwq_cpu(cpu) {
3424                 struct workqueue_struct *wq;
3425                 /*
3426                  * nr_active is monotonically decreasing.  It's safe
3427                  * to peek without lock.
3428                  */
3429                 list_for_each_entry(wq, &workqueues, list) {
3430                         struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3431
3432                         if (!cwq || !(wq->flags & WQ_FREEZEABLE))
3433                                 continue;
3434
3435                         BUG_ON(cwq->nr_active < 0);
3436                         if (cwq->nr_active) {
3437                                 busy = true;
3438                                 goto out_unlock;
3439                         }
3440                 }
3441         }
3442 out_unlock:
3443         spin_unlock(&workqueue_lock);
3444         return busy;
3445 }
3446
3447 /**
3448  * thaw_workqueues - thaw workqueues
3449  *
3450  * Thaw workqueues.  Normal queueing is restored and all collected
3451  * frozen works are transferred to their respective gcwq worklists.
3452  *
3453  * CONTEXT:
3454  * Grabs and releases workqueue_lock and gcwq->lock's.
3455  */
3456 void thaw_workqueues(void)
3457 {
3458         unsigned int cpu;
3459
3460         spin_lock(&workqueue_lock);
3461
3462         if (!workqueue_freezing)
3463                 goto out_unlock;
3464
3465         for_each_gcwq_cpu(cpu) {
3466                 struct global_cwq *gcwq = get_gcwq(cpu);
3467                 struct workqueue_struct *wq;
3468
3469                 spin_lock_irq(&gcwq->lock);
3470
3471                 BUG_ON(!(gcwq->flags & GCWQ_FREEZING));
3472                 gcwq->flags &= ~GCWQ_FREEZING;
3473
3474                 list_for_each_entry(wq, &workqueues, list) {
3475                         struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3476
3477                         if (!cwq || !(wq->flags & WQ_FREEZEABLE))
3478                                 continue;
3479
3480                         /* restore max_active and repopulate worklist */
3481                         cwq->max_active = wq->saved_max_active;
3482
3483                         while (!list_empty(&cwq->delayed_works) &&
3484                                cwq->nr_active < cwq->max_active)
3485                                 cwq_activate_first_delayed(cwq);
3486                 }
3487
3488                 wake_up_worker(gcwq);
3489
3490                 spin_unlock_irq(&gcwq->lock);
3491         }
3492
3493         workqueue_freezing = false;
3494 out_unlock:
3495         spin_unlock(&workqueue_lock);
3496 }
3497 #endif /* CONFIG_FREEZER */
3498
3499 void __init init_workqueues(void)
3500 {
3501         unsigned int cpu;
3502         int i;
3503
3504         /*
3505          * The pointer part of work->data is either pointing to the
3506          * cwq or contains the cpu number the work ran last on.  Make
3507          * sure cpu number won't overflow into kernel pointer area so
3508          * that they can be distinguished.
3509          */
3510         BUILD_BUG_ON(WORK_CPU_LAST << WORK_STRUCT_FLAG_BITS >= PAGE_OFFSET);
3511
3512         hotcpu_notifier(workqueue_cpu_callback, CPU_PRI_WORKQUEUE);
3513
3514         /* initialize gcwqs */
3515         for_each_gcwq_cpu(cpu) {
3516                 struct global_cwq *gcwq = get_gcwq(cpu);
3517
3518                 spin_lock_init(&gcwq->lock);
3519                 INIT_LIST_HEAD(&gcwq->worklist);
3520                 gcwq->cpu = cpu;
3521                 if (cpu == WORK_CPU_UNBOUND)
3522                         gcwq->flags |= GCWQ_DISASSOCIATED;
3523
3524                 INIT_LIST_HEAD(&gcwq->idle_list);
3525                 for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)
3526                         INIT_HLIST_HEAD(&gcwq->busy_hash[i]);
3527
3528                 init_timer_deferrable(&gcwq->idle_timer);
3529                 gcwq->idle_timer.function = idle_worker_timeout;
3530                 gcwq->idle_timer.data = (unsigned long)gcwq;
3531
3532                 setup_timer(&gcwq->mayday_timer, gcwq_mayday_timeout,
3533                             (unsigned long)gcwq);
3534
3535                 ida_init(&gcwq->worker_ida);
3536
3537                 gcwq->trustee_state = TRUSTEE_DONE;
3538                 init_waitqueue_head(&gcwq->trustee_wait);
3539         }
3540
3541         /* create the initial worker */
3542         for_each_online_gcwq_cpu(cpu) {
3543                 struct global_cwq *gcwq = get_gcwq(cpu);
3544                 struct worker *worker;
3545
3546                 worker = create_worker(gcwq, true);
3547                 BUG_ON(!worker);
3548                 spin_lock_irq(&gcwq->lock);
3549                 start_worker(worker);
3550                 spin_unlock_irq(&gcwq->lock);
3551         }
3552
3553         system_wq = alloc_workqueue("events", 0, 0);
3554         system_long_wq = alloc_workqueue("events_long", 0, 0);
3555         system_nrt_wq = alloc_workqueue("events_nrt", WQ_NON_REENTRANT, 0);
3556         system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
3557                                             WQ_UNBOUND_MAX_ACTIVE);
3558         BUG_ON(!system_wq || !system_long_wq || !system_nrt_wq);
3559 }