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