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