workqueue: fix locking in retry path of maybe_create_worker()
[deliverable/linux.git] / kernel / workqueue.c
index e697d6c72daacfd1f0e7ecca67f5d5640a52966d..aca94726e20a937d2bb9d4b711da9c3fbda75bcf 100644 (file)
 #include <linux/debug_locks.h>
 #include <linux/lockdep.h>
 #include <linux/idr.h>
-#include <linux/delay.h>
+
+#include "workqueue_sched.h"
 
 enum {
        /* global_cwq flags */
+       GCWQ_MANAGE_WORKERS     = 1 << 0,       /* need to manage workers */
+       GCWQ_MANAGING_WORKERS   = 1 << 1,       /* managing workers */
+       GCWQ_DISASSOCIATED      = 1 << 2,       /* cpu can't serve workers */
        GCWQ_FREEZING           = 1 << 3,       /* freeze in progress */
+       GCWQ_HIGHPRI_PENDING    = 1 << 4,       /* highpri works on queue */
 
        /* worker flags */
        WORKER_STARTED          = 1 << 0,       /* started */
        WORKER_DIE              = 1 << 1,       /* die die die */
        WORKER_IDLE             = 1 << 2,       /* is idle */
+       WORKER_PREP             = 1 << 3,       /* preparing to run works */
        WORKER_ROGUE            = 1 << 4,       /* not bound to any cpu */
+       WORKER_REBIND           = 1 << 5,       /* mom is home, come back */
+       WORKER_CPU_INTENSIVE    = 1 << 6,       /* cpu intensive */
+       WORKER_UNBOUND          = 1 << 7,       /* worker is unbound */
+
+       WORKER_NOT_RUNNING      = WORKER_PREP | WORKER_ROGUE | WORKER_REBIND |
+                                 WORKER_CPU_INTENSIVE | WORKER_UNBOUND,
 
        /* gcwq->trustee_state */
        TRUSTEE_START           = 0,            /* start */
@@ -57,7 +69,19 @@ enum {
        BUSY_WORKER_HASH_SIZE   = 1 << BUSY_WORKER_HASH_ORDER,
        BUSY_WORKER_HASH_MASK   = BUSY_WORKER_HASH_SIZE - 1,
 
+       MAX_IDLE_WORKERS_RATIO  = 4,            /* 1/4 of busy can be idle */
+       IDLE_WORKER_TIMEOUT     = 300 * HZ,     /* keep idle ones for 5 mins */
+
+       MAYDAY_INITIAL_TIMEOUT  = HZ / 100,     /* call for help after 10ms */
+       MAYDAY_INTERVAL         = HZ / 10,      /* and then every 100ms */
+       CREATE_COOLDOWN         = HZ,           /* time to breath after fail */
        TRUSTEE_COOLDOWN        = HZ / 10,      /* for trustee draining */
+
+       /*
+        * Rescue workers are used only on emergencies and shared by
+        * all cpus.  Give -20.
+        */
+       RESCUER_NICE_LEVEL      = -20,
 };
 
 /*
@@ -65,8 +89,16 @@ enum {
  *
  * I: Set during initialization and read-only afterwards.
  *
+ * P: Preemption protected.  Disabling preemption is enough and should
+ *    only be modified and accessed from the local cpu.
+ *
  * L: gcwq->lock protected.  Access with gcwq->lock held.
  *
+ * X: During normal operation, modification requires gcwq->lock and
+ *    should be done only from local cpu.  Either disabling preemption
+ *    on local cpu or grabbing gcwq->lock is enough for read access.
+ *    If GCWQ_DISASSOCIATED is set, it's identical to L.
+ *
  * F: wq->flush_mutex protected.
  *
  * W: workqueue_lock protected.
@@ -74,6 +106,10 @@ enum {
 
 struct global_cwq;
 
+/*
+ * The poor guys doing the actual heavy lifting.  All on-duty workers
+ * are either serving the manager role, on idle list or on busy hash.
+ */
 struct worker {
        /* on idle list while idle, on busy hash table while busy */
        union {
@@ -86,12 +122,17 @@ struct worker {
        struct list_head        scheduled;      /* L: scheduled works */
        struct task_struct      *task;          /* I: worker task */
        struct global_cwq       *gcwq;          /* I: the associated gcwq */
-       unsigned int            flags;          /* L: flags */
+       /* 64 bytes boundary on 64bit, 32 on 32bit */
+       unsigned long           last_active;    /* L: last active timestamp */
+       unsigned int            flags;          /* X: flags */
        int                     id;             /* I: worker id */
+       struct work_struct      rebind_work;    /* L: rebind worker to cpu */
 };
 
 /*
- * Global per-cpu workqueue.
+ * Global per-cpu workqueue.  There's one and only one for each cpu
+ * and all works are queued and processed here regardless of their
+ * target workqueues.
  */
 struct global_cwq {
        spinlock_t              lock;           /* the gcwq lock */
@@ -103,15 +144,19 @@ struct global_cwq {
        int                     nr_idle;        /* L: currently idle ones */
 
        /* workers are chained either in the idle_list or busy_hash */
-       struct list_head        idle_list;      /* L: list of idle workers */
+       struct list_head        idle_list;      /* X: list of idle workers */
        struct hlist_head       busy_hash[BUSY_WORKER_HASH_SIZE];
                                                /* L: hash of busy workers */
 
+       struct timer_list       idle_timer;     /* L: worker idle timeout */
+       struct timer_list       mayday_timer;   /* L: SOS timer for dworkers */
+
        struct ida              worker_ida;     /* L: for worker IDs */
 
        struct task_struct      *trustee;       /* L: for gcwq shutdown */
        unsigned int            trustee_state;  /* L: trustee state */
        wait_queue_head_t       trustee_wait;   /* trustee wait */
+       struct worker           *first_idle;    /* L: first idle worker */
 } ____cacheline_aligned_in_smp;
 
 /*
@@ -121,7 +166,6 @@ struct global_cwq {
  */
 struct cpu_workqueue_struct {
        struct global_cwq       *gcwq;          /* I: the associated gcwq */
-       struct worker           *worker;
        struct workqueue_struct *wq;            /* I: the owning workqueue */
        int                     work_color;     /* L: current color */
        int                     flush_color;    /* L: flushing color */
@@ -147,7 +191,11 @@ struct wq_flusher {
  */
 struct workqueue_struct {
        unsigned int            flags;          /* I: WQ_* flags */
-       struct cpu_workqueue_struct *cpu_wq;    /* I: cwq's */
+       union {
+               struct cpu_workqueue_struct __percpu    *pcpu;
+               struct cpu_workqueue_struct             *single;
+               unsigned long                           v;
+       } cpu_wq;                               /* I: cwq's */
        struct list_head        list;           /* W: list of all workqueues */
 
        struct mutex            flush_mutex;    /* protects wq flushing */
@@ -158,19 +206,65 @@ struct workqueue_struct {
        struct list_head        flusher_queue;  /* F: flush waiters */
        struct list_head        flusher_overflow; /* F: flush overflow list */
 
-       unsigned long           single_cpu;     /* cpu for single cpu wq */
+       cpumask_var_t           mayday_mask;    /* cpus requesting rescue */
+       struct worker           *rescuer;       /* I: rescue worker */
 
-       int                     saved_max_active; /* I: saved cwq max_active */
+       int                     saved_max_active; /* W: saved cwq max_active */
        const char              *name;          /* I: workqueue name */
 #ifdef CONFIG_LOCKDEP
        struct lockdep_map      lockdep_map;
 #endif
 };
 
+struct workqueue_struct *system_wq __read_mostly;
+struct workqueue_struct *system_long_wq __read_mostly;
+struct workqueue_struct *system_nrt_wq __read_mostly;
+struct workqueue_struct *system_unbound_wq __read_mostly;
+EXPORT_SYMBOL_GPL(system_wq);
+EXPORT_SYMBOL_GPL(system_long_wq);
+EXPORT_SYMBOL_GPL(system_nrt_wq);
+EXPORT_SYMBOL_GPL(system_unbound_wq);
+
 #define for_each_busy_worker(worker, i, pos, gcwq)                     \
        for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)                     \
                hlist_for_each_entry(worker, pos, &gcwq->busy_hash[i], hentry)
 
+static inline int __next_gcwq_cpu(int cpu, const struct cpumask *mask,
+                                 unsigned int sw)
+{
+       if (cpu < nr_cpu_ids) {
+               if (sw & 1) {
+                       cpu = cpumask_next(cpu, mask);
+                       if (cpu < nr_cpu_ids)
+                               return cpu;
+               }
+               if (sw & 2)
+                       return WORK_CPU_UNBOUND;
+       }
+       return WORK_CPU_NONE;
+}
+
+static inline int __next_wq_cpu(int cpu, const struct cpumask *mask,
+                               struct workqueue_struct *wq)
+{
+       return __next_gcwq_cpu(cpu, mask, !(wq->flags & WQ_UNBOUND) ? 1 : 2);
+}
+
+#define for_each_gcwq_cpu(cpu)                                         \
+       for ((cpu) = __next_gcwq_cpu(-1, cpu_possible_mask, 3);         \
+            (cpu) < WORK_CPU_NONE;                                     \
+            (cpu) = __next_gcwq_cpu((cpu), cpu_possible_mask, 3))
+
+#define for_each_online_gcwq_cpu(cpu)                                  \
+       for ((cpu) = __next_gcwq_cpu(-1, cpu_online_mask, 3);           \
+            (cpu) < WORK_CPU_NONE;                                     \
+            (cpu) = __next_gcwq_cpu((cpu), cpu_online_mask, 3))
+
+#define for_each_cwq_cpu(cpu, wq)                                      \
+       for ((cpu) = __next_wq_cpu(-1, cpu_possible_mask, (wq));        \
+            (cpu) < WORK_CPU_NONE;                                     \
+            (cpu) = __next_wq_cpu((cpu), cpu_possible_mask, (wq)))
+
 #ifdef CONFIG_DEBUG_OBJECTS_WORK
 
 static struct debug_obj_descr work_debug_descr;
@@ -286,19 +380,54 @@ static DEFINE_SPINLOCK(workqueue_lock);
 static LIST_HEAD(workqueues);
 static bool workqueue_freezing;                /* W: have wqs started freezing? */
 
+/*
+ * The almighty global cpu workqueues.  nr_running is the only field
+ * which is expected to be used frequently by other cpus via
+ * try_to_wake_up().  Put it in a separate cacheline.
+ */
 static DEFINE_PER_CPU(struct global_cwq, global_cwq);
+static DEFINE_PER_CPU_SHARED_ALIGNED(atomic_t, gcwq_nr_running);
+
+/*
+ * Global cpu workqueue and nr_running counter for unbound gcwq.  The
+ * gcwq is always online, has GCWQ_DISASSOCIATED set, and all its
+ * workers have WORKER_UNBOUND set.
+ */
+static struct global_cwq unbound_global_cwq;
+static atomic_t unbound_gcwq_nr_running = ATOMIC_INIT(0);      /* always 0 */
 
 static int worker_thread(void *__worker);
 
 static struct global_cwq *get_gcwq(unsigned int cpu)
 {
-       return &per_cpu(global_cwq, cpu);
+       if (cpu != WORK_CPU_UNBOUND)
+               return &per_cpu(global_cwq, cpu);
+       else
+               return &unbound_global_cwq;
+}
+
+static atomic_t *get_gcwq_nr_running(unsigned int cpu)
+{
+       if (cpu != WORK_CPU_UNBOUND)
+               return &per_cpu(gcwq_nr_running, cpu);
+       else
+               return &unbound_gcwq_nr_running;
 }
 
 static struct cpu_workqueue_struct *get_cwq(unsigned int cpu,
                                            struct workqueue_struct *wq)
 {
-       return per_cpu_ptr(wq->cpu_wq, cpu);
+       if (!(wq->flags & WQ_UNBOUND)) {
+               if (likely(cpu < nr_cpu_ids)) {
+#ifdef CONFIG_SMP
+                       return per_cpu_ptr(wq->cpu_wq.pcpu, cpu);
+#else
+                       return wq->cpu_wq.single;
+#endif
+               }
+       } else if (likely(cpu == WORK_CPU_UNBOUND))
+               return wq->cpu_wq.single;
+       return NULL;
 }
 
 static unsigned int work_color_to_flags(int color)
@@ -378,13 +507,74 @@ static struct global_cwq *get_work_gcwq(struct work_struct *work)
                return ((struct cpu_workqueue_struct *)data)->gcwq;
 
        cpu = data >> WORK_STRUCT_FLAG_BITS;
-       if (cpu == NR_CPUS)
+       if (cpu == WORK_CPU_NONE)
                return NULL;
 
-       BUG_ON(cpu >= num_possible_cpus());
+       BUG_ON(cpu >= nr_cpu_ids && cpu != WORK_CPU_UNBOUND);
        return get_gcwq(cpu);
 }
 
+/*
+ * Policy functions.  These define the policies on how the global
+ * worker pool is managed.  Unless noted otherwise, these functions
+ * assume that they're being called with gcwq->lock held.
+ */
+
+static bool __need_more_worker(struct global_cwq *gcwq)
+{
+       return !atomic_read(get_gcwq_nr_running(gcwq->cpu)) ||
+               gcwq->flags & GCWQ_HIGHPRI_PENDING;
+}
+
+/*
+ * Need to wake up a worker?  Called from anything but currently
+ * running workers.
+ */
+static bool need_more_worker(struct global_cwq *gcwq)
+{
+       return !list_empty(&gcwq->worklist) && __need_more_worker(gcwq);
+}
+
+/* Can I start working?  Called from busy but !running workers. */
+static bool may_start_working(struct global_cwq *gcwq)
+{
+       return gcwq->nr_idle;
+}
+
+/* Do I need to keep working?  Called from currently running workers. */
+static bool keep_working(struct global_cwq *gcwq)
+{
+       atomic_t *nr_running = get_gcwq_nr_running(gcwq->cpu);
+
+       return !list_empty(&gcwq->worklist) && atomic_read(nr_running) <= 1;
+}
+
+/* Do we need a new worker?  Called from manager. */
+static bool need_to_create_worker(struct global_cwq *gcwq)
+{
+       return need_more_worker(gcwq) && !may_start_working(gcwq);
+}
+
+/* Do I need to be the manager? */
+static bool need_to_manage_workers(struct global_cwq *gcwq)
+{
+       return need_to_create_worker(gcwq) || gcwq->flags & GCWQ_MANAGE_WORKERS;
+}
+
+/* Do we have too many workers and should some go away? */
+static bool too_many_workers(struct global_cwq *gcwq)
+{
+       bool managing = gcwq->flags & GCWQ_MANAGING_WORKERS;
+       int nr_idle = gcwq->nr_idle + managing; /* manager is considered idle */
+       int nr_busy = gcwq->nr_workers - nr_idle;
+
+       return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
+}
+
+/*
+ * Wake up functions.
+ */
+
 /* Return the first worker.  Safe with preemption disabled */
 static struct worker *first_worker(struct global_cwq *gcwq)
 {
@@ -411,6 +601,134 @@ static void wake_up_worker(struct global_cwq *gcwq)
                wake_up_process(worker->task);
 }
 
+/**
+ * wq_worker_waking_up - a worker is waking up
+ * @task: task waking up
+ * @cpu: CPU @task is waking up to
+ *
+ * This function is called during try_to_wake_up() when a worker is
+ * being awoken.
+ *
+ * CONTEXT:
+ * spin_lock_irq(rq->lock)
+ */
+void wq_worker_waking_up(struct task_struct *task, unsigned int cpu)
+{
+       struct worker *worker = kthread_data(task);
+
+       if (likely(!(worker->flags & WORKER_NOT_RUNNING)))
+               atomic_inc(get_gcwq_nr_running(cpu));
+}
+
+/**
+ * wq_worker_sleeping - a worker is going to sleep
+ * @task: task going to sleep
+ * @cpu: CPU in question, must be the current CPU number
+ *
+ * This function is called during schedule() when a busy worker is
+ * going to sleep.  Worker on the same cpu can be woken up by
+ * returning pointer to its task.
+ *
+ * CONTEXT:
+ * spin_lock_irq(rq->lock)
+ *
+ * RETURNS:
+ * Worker task on @cpu to wake up, %NULL if none.
+ */
+struct task_struct *wq_worker_sleeping(struct task_struct *task,
+                                      unsigned int cpu)
+{
+       struct worker *worker = kthread_data(task), *to_wakeup = NULL;
+       struct global_cwq *gcwq = get_gcwq(cpu);
+       atomic_t *nr_running = get_gcwq_nr_running(cpu);
+
+       if (unlikely(worker->flags & WORKER_NOT_RUNNING))
+               return NULL;
+
+       /* this can only happen on the local cpu */
+       BUG_ON(cpu != raw_smp_processor_id());
+
+       /*
+        * The counterpart of the following dec_and_test, implied mb,
+        * worklist not empty test sequence is in insert_work().
+        * Please read comment there.
+        *
+        * NOT_RUNNING is clear.  This means that trustee is not in
+        * charge and we're running on the local cpu w/ rq lock held
+        * and preemption disabled, which in turn means that none else
+        * could be manipulating idle_list, so dereferencing idle_list
+        * without gcwq lock is safe.
+        */
+       if (atomic_dec_and_test(nr_running) && !list_empty(&gcwq->worklist))
+               to_wakeup = first_worker(gcwq);
+       return to_wakeup ? to_wakeup->task : NULL;
+}
+
+/**
+ * worker_set_flags - set worker flags and adjust nr_running accordingly
+ * @worker: self
+ * @flags: flags to set
+ * @wakeup: wakeup an idle worker if necessary
+ *
+ * Set @flags in @worker->flags and adjust nr_running accordingly.  If
+ * nr_running becomes zero and @wakeup is %true, an idle worker is
+ * woken up.
+ *
+ * CONTEXT:
+ * spin_lock_irq(gcwq->lock)
+ */
+static inline void worker_set_flags(struct worker *worker, unsigned int flags,
+                                   bool wakeup)
+{
+       struct global_cwq *gcwq = worker->gcwq;
+
+       WARN_ON_ONCE(worker->task != current);
+
+       /*
+        * If transitioning into NOT_RUNNING, adjust nr_running and
+        * wake up an idle worker as necessary if requested by
+        * @wakeup.
+        */
+       if ((flags & WORKER_NOT_RUNNING) &&
+           !(worker->flags & WORKER_NOT_RUNNING)) {
+               atomic_t *nr_running = get_gcwq_nr_running(gcwq->cpu);
+
+               if (wakeup) {
+                       if (atomic_dec_and_test(nr_running) &&
+                           !list_empty(&gcwq->worklist))
+                               wake_up_worker(gcwq);
+               } else
+                       atomic_dec(nr_running);
+       }
+
+       worker->flags |= flags;
+}
+
+/**
+ * worker_clr_flags - clear worker flags and adjust nr_running accordingly
+ * @worker: self
+ * @flags: flags to clear
+ *
+ * Clear @flags in @worker->flags and adjust nr_running accordingly.
+ *
+ * CONTEXT:
+ * spin_lock_irq(gcwq->lock)
+ */
+static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
+{
+       struct global_cwq *gcwq = worker->gcwq;
+       unsigned int oflags = worker->flags;
+
+       WARN_ON_ONCE(worker->task != current);
+
+       worker->flags &= ~flags;
+
+       /* if transitioning out of NOT_RUNNING, increment nr_running */
+       if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
+               if (!(worker->flags & WORKER_NOT_RUNNING))
+                       atomic_inc(get_gcwq_nr_running(gcwq->cpu));
+}
+
 /**
  * busy_worker_head - return the busy hash head for a work
  * @gcwq: gcwq of interest
@@ -491,6 +809,43 @@ static struct worker *find_worker_executing_work(struct global_cwq *gcwq,
                                            work);
 }
 
+/**
+ * gcwq_determine_ins_pos - find insertion position
+ * @gcwq: gcwq of interest
+ * @cwq: cwq a work is being queued for
+ *
+ * A work for @cwq is about to be queued on @gcwq, determine insertion
+ * position for the work.  If @cwq is for HIGHPRI wq, the work is
+ * queued at the head of the queue but in FIFO order with respect to
+ * other HIGHPRI works; otherwise, at the end of the queue.  This
+ * function also sets GCWQ_HIGHPRI_PENDING flag to hint @gcwq that
+ * there are HIGHPRI works pending.
+ *
+ * CONTEXT:
+ * spin_lock_irq(gcwq->lock).
+ *
+ * RETURNS:
+ * Pointer to inserstion position.
+ */
+static inline struct list_head *gcwq_determine_ins_pos(struct global_cwq *gcwq,
+                                              struct cpu_workqueue_struct *cwq)
+{
+       struct work_struct *twork;
+
+       if (likely(!(cwq->wq->flags & WQ_HIGHPRI)))
+               return &gcwq->worklist;
+
+       list_for_each_entry(twork, &gcwq->worklist, entry) {
+               struct cpu_workqueue_struct *tcwq = get_work_cwq(twork);
+
+               if (!(tcwq->wq->flags & WQ_HIGHPRI))
+                       break;
+       }
+
+       gcwq->flags |= GCWQ_HIGHPRI_PENDING;
+       return &twork->entry;
+}
+
 /**
  * insert_work - insert a work into gcwq
  * @cwq: cwq @work belongs to
@@ -508,6 +863,8 @@ static void insert_work(struct cpu_workqueue_struct *cwq,
                        struct work_struct *work, struct list_head *head,
                        unsigned int extra_flags)
 {
+       struct global_cwq *gcwq = cwq->gcwq;
+
        /* we own @work, set data and link */
        set_work_cwq(work, cwq, extra_flags);
 
@@ -518,35 +875,16 @@ static void insert_work(struct cpu_workqueue_struct *cwq,
        smp_wmb();
 
        list_add_tail(&work->entry, head);
-       wake_up_worker(cwq->gcwq);
-}
-
-/**
- * cwq_unbind_single_cpu - unbind cwq from single cpu workqueue processing
- * @cwq: cwq to unbind
- *
- * Try to unbind @cwq from single cpu workqueue processing.  If
- * @cwq->wq is frozen, unbind is delayed till the workqueue is thawed.
- *
- * CONTEXT:
- * spin_lock_irq(gcwq->lock).
- */
-static void cwq_unbind_single_cpu(struct cpu_workqueue_struct *cwq)
-{
-       struct workqueue_struct *wq = cwq->wq;
-       struct global_cwq *gcwq = cwq->gcwq;
 
-       BUG_ON(wq->single_cpu != gcwq->cpu);
        /*
-        * Unbind from workqueue if @cwq is not frozen.  If frozen,
-        * thaw_workqueues() will either restart processing on this
-        * cpu or unbind if empty.  This keeps works queued while
-        * frozen fully ordered and flushable.
+        * Ensure either worker_sched_deactivated() sees the above
+        * list_add_tail() or we see zero nr_running to avoid workers
+        * lying around lazily while there are works to be processed.
         */
-       if (likely(!(gcwq->flags & GCWQ_FREEZING))) {
-               smp_wmb();      /* paired with cmpxchg() in __queue_work() */
-               wq->single_cpu = NR_CPUS;
-       }
+       smp_mb();
+
+       if (__need_more_worker(gcwq))
+               wake_up_worker(gcwq);
 }
 
 static void __queue_work(unsigned int cpu, struct workqueue_struct *wq,
@@ -556,17 +894,16 @@ static void __queue_work(unsigned int cpu, struct workqueue_struct *wq,
        struct cpu_workqueue_struct *cwq;
        struct list_head *worklist;
        unsigned long flags;
-       bool arbitrate;
 
        debug_work_activate(work);
 
-       /*
-        * Determine gcwq to use.  SINGLE_CPU is inherently
-        * NON_REENTRANT, so test it first.
-        */
-       if (!(wq->flags & WQ_SINGLE_CPU)) {
+       /* determine gcwq to use */
+       if (!(wq->flags & WQ_UNBOUND)) {
                struct global_cwq *last_gcwq;
 
+               if (unlikely(cpu == WORK_CPU_UNBOUND))
+                       cpu = raw_smp_processor_id();
+
                /*
                 * It's multi cpu.  If @wq is non-reentrant and @work
                 * was previously on a different cpu, it might still
@@ -592,37 +929,8 @@ static void __queue_work(unsigned int cpu, struct workqueue_struct *wq,
                } else
                        spin_lock_irqsave(&gcwq->lock, flags);
        } else {
-               unsigned int req_cpu = cpu;
-
-               /*
-                * It's a bit more complex for single cpu workqueues.
-                * We first need to determine which cpu is going to be
-                * used.  If no cpu is currently serving this
-                * workqueue, arbitrate using atomic accesses to
-                * wq->single_cpu; otherwise, use the current one.
-                */
-       retry:
-               cpu = wq->single_cpu;
-               arbitrate = cpu == NR_CPUS;
-               if (arbitrate)
-                       cpu = req_cpu;
-
-               gcwq = get_gcwq(cpu);
+               gcwq = get_gcwq(WORK_CPU_UNBOUND);
                spin_lock_irqsave(&gcwq->lock, flags);
-
-               /*
-                * The following cmpxchg() is a full barrier paired
-                * with smp_wmb() in cwq_unbind_single_cpu() and
-                * guarantees that all changes to wq->st_* fields are
-                * visible on the new cpu after this point.
-                */
-               if (arbitrate)
-                       cmpxchg(&wq->single_cpu, NR_CPUS, cpu);
-
-               if (unlikely(wq->single_cpu != cpu)) {
-                       spin_unlock_irqrestore(&gcwq->lock, flags);
-                       goto retry;
-               }
        }
 
        /* gcwq determined, get cwq and queue */
@@ -634,7 +942,7 @@ static void __queue_work(unsigned int cpu, struct workqueue_struct *wq,
 
        if (likely(cwq->nr_active < cwq->max_active)) {
                cwq->nr_active++;
-               worklist = &gcwq->worklist;
+               worklist = gcwq_determine_ins_pos(gcwq, cwq);
        } else
                worklist = &cwq->delayed_works;
 
@@ -731,19 +1039,30 @@ int queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
        struct work_struct *work = &dwork->work;
 
        if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
-               struct global_cwq *gcwq = get_work_gcwq(work);
-               unsigned int lcpu = gcwq ? gcwq->cpu : raw_smp_processor_id();
+               unsigned int lcpu;
 
                BUG_ON(timer_pending(timer));
                BUG_ON(!list_empty(&work->entry));
 
                timer_stats_timer_set_start_info(&dwork->timer);
+
                /*
                 * This stores cwq for the moment, for the timer_fn.
                 * Note that the work's gcwq is preserved to allow
                 * reentrance detection for delayed works.
                 */
+               if (!(wq->flags & WQ_UNBOUND)) {
+                       struct global_cwq *gcwq = get_work_gcwq(work);
+
+                       if (gcwq && gcwq->cpu != WORK_CPU_UNBOUND)
+                               lcpu = gcwq->cpu;
+                       else
+                               lcpu = raw_smp_processor_id();
+               } else
+                       lcpu = WORK_CPU_UNBOUND;
+
                set_work_cwq(work, get_cwq(lcpu, wq), 0);
+
                timer->expires = jiffies + delay;
                timer->data = (unsigned long)dwork;
                timer->function = delayed_work_timer_fn;
@@ -776,14 +1095,24 @@ static void worker_enter_idle(struct worker *worker)
        BUG_ON(!list_empty(&worker->entry) &&
               (worker->hentry.next || worker->hentry.pprev));
 
+       /* can't use worker_set_flags(), also called from start_worker() */
        worker->flags |= WORKER_IDLE;
        gcwq->nr_idle++;
+       worker->last_active = jiffies;
 
        /* idle_list is LIFO */
        list_add(&worker->entry, &gcwq->idle_list);
 
-       if (unlikely(worker->flags & WORKER_ROGUE))
+       if (likely(!(worker->flags & WORKER_ROGUE))) {
+               if (too_many_workers(gcwq) && !timer_pending(&gcwq->idle_timer))
+                       mod_timer(&gcwq->idle_timer,
+                                 jiffies + IDLE_WORKER_TIMEOUT);
+       } else
                wake_up_all(&gcwq->trustee_wait);
+
+       /* sanity check nr_running */
+       WARN_ON_ONCE(gcwq->nr_workers == gcwq->nr_idle &&
+                    atomic_read(get_gcwq_nr_running(gcwq->cpu)));
 }
 
 /**
@@ -800,11 +1129,87 @@ static void worker_leave_idle(struct worker *worker)
        struct global_cwq *gcwq = worker->gcwq;
 
        BUG_ON(!(worker->flags & WORKER_IDLE));
-       worker->flags &= ~WORKER_IDLE;
+       worker_clr_flags(worker, WORKER_IDLE);
        gcwq->nr_idle--;
        list_del_init(&worker->entry);
 }
 
+/**
+ * worker_maybe_bind_and_lock - bind worker to its cpu if possible and lock gcwq
+ * @worker: self
+ *
+ * Works which are scheduled while the cpu is online must at least be
+ * scheduled to a worker which is bound to the cpu so that if they are
+ * flushed from cpu callbacks while cpu is going down, they are
+ * guaranteed to execute on the cpu.
+ *
+ * This function is to be used by rogue workers and rescuers to bind
+ * themselves to the target cpu and may race with cpu going down or
+ * coming online.  kthread_bind() can't be used because it may put the
+ * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
+ * verbatim as it's best effort and blocking and gcwq may be
+ * [dis]associated in the meantime.
+ *
+ * This function tries set_cpus_allowed() and locks gcwq and verifies
+ * the binding against GCWQ_DISASSOCIATED which is set during
+ * CPU_DYING and cleared during CPU_ONLINE, so if the worker enters
+ * idle state or fetches works without dropping lock, it can guarantee
+ * the scheduling requirement described in the first paragraph.
+ *
+ * CONTEXT:
+ * Might sleep.  Called without any lock but returns with gcwq->lock
+ * held.
+ *
+ * RETURNS:
+ * %true if the associated gcwq is online (@worker is successfully
+ * bound), %false if offline.
+ */
+static bool worker_maybe_bind_and_lock(struct worker *worker)
+{
+       struct global_cwq *gcwq = worker->gcwq;
+       struct task_struct *task = worker->task;
+
+       while (true) {
+               /*
+                * The following call may fail, succeed or succeed
+                * without actually migrating the task to the cpu if
+                * it races with cpu hotunplug operation.  Verify
+                * against GCWQ_DISASSOCIATED.
+                */
+               if (!(gcwq->flags & GCWQ_DISASSOCIATED))
+                       set_cpus_allowed_ptr(task, get_cpu_mask(gcwq->cpu));
+
+               spin_lock_irq(&gcwq->lock);
+               if (gcwq->flags & GCWQ_DISASSOCIATED)
+                       return false;
+               if (task_cpu(task) == gcwq->cpu &&
+                   cpumask_equal(&current->cpus_allowed,
+                                 get_cpu_mask(gcwq->cpu)))
+                       return true;
+               spin_unlock_irq(&gcwq->lock);
+
+               /* CPU has come up inbetween, retry migration */
+               cpu_relax();
+       }
+}
+
+/*
+ * Function for worker->rebind_work used to rebind rogue busy workers
+ * to the associated cpu which is coming back online.  This is
+ * scheduled by cpu up but can race with other cpu hotplug operations
+ * and may be executed twice without intervening cpu down.
+ */
+static void worker_rebind_fn(struct work_struct *work)
+{
+       struct worker *worker = container_of(work, struct worker, rebind_work);
+       struct global_cwq *gcwq = worker->gcwq;
+
+       if (worker_maybe_bind_and_lock(worker))
+               worker_clr_flags(worker, WORKER_REBIND);
+
+       spin_unlock_irq(&gcwq->lock);
+}
+
 static struct worker *alloc_worker(void)
 {
        struct worker *worker;
@@ -813,6 +1218,9 @@ static struct worker *alloc_worker(void)
        if (worker) {
                INIT_LIST_HEAD(&worker->entry);
                INIT_LIST_HEAD(&worker->scheduled);
+               INIT_WORK(&worker->rebind_work, worker_rebind_fn);
+               /* on creation a worker is in !idle && prep state */
+               worker->flags = WORKER_PREP;
        }
        return worker;
 }
@@ -834,8 +1242,9 @@ static struct worker *alloc_worker(void)
  */
 static struct worker *create_worker(struct global_cwq *gcwq, bool bind)
 {
-       int id = -1;
+       bool on_unbound_cpu = gcwq->cpu == WORK_CPU_UNBOUND;
        struct worker *worker = NULL;
+       int id = -1;
 
        spin_lock_irq(&gcwq->lock);
        while (ida_get_new(&gcwq->worker_ida, &id)) {
@@ -853,8 +1262,12 @@ static struct worker *create_worker(struct global_cwq *gcwq, bool bind)
        worker->gcwq = gcwq;
        worker->id = id;
 
-       worker->task = kthread_create(worker_thread, worker, "kworker/%u:%d",
-                                     gcwq->cpu, id);
+       if (!on_unbound_cpu)
+               worker->task = kthread_create(worker_thread, worker,
+                                             "kworker/%u:%d", gcwq->cpu, id);
+       else
+               worker->task = kthread_create(worker_thread, worker,
+                                             "kworker/u:%d", id);
        if (IS_ERR(worker->task))
                goto fail;
 
@@ -863,10 +1276,13 @@ static struct worker *create_worker(struct global_cwq *gcwq, bool bind)
         * online later on.  Make sure every worker has
         * PF_THREAD_BOUND set.
         */
-       if (bind)
+       if (bind && !on_unbound_cpu)
                kthread_bind(worker->task, gcwq->cpu);
-       else
+       else {
                worker->task->flags |= PF_THREAD_BOUND;
+               if (on_unbound_cpu)
+                       worker->flags |= WORKER_UNBOUND;
+       }
 
        return worker;
 fail:
@@ -931,6 +1347,223 @@ static void destroy_worker(struct worker *worker)
        ida_remove(&gcwq->worker_ida, id);
 }
 
+static void idle_worker_timeout(unsigned long __gcwq)
+{
+       struct global_cwq *gcwq = (void *)__gcwq;
+
+       spin_lock_irq(&gcwq->lock);
+
+       if (too_many_workers(gcwq)) {
+               struct worker *worker;
+               unsigned long expires;
+
+               /* idle_list is kept in LIFO order, check the last one */
+               worker = list_entry(gcwq->idle_list.prev, struct worker, entry);
+               expires = worker->last_active + IDLE_WORKER_TIMEOUT;
+
+               if (time_before(jiffies, expires))
+                       mod_timer(&gcwq->idle_timer, expires);
+               else {
+                       /* it's been idle for too long, wake up manager */
+                       gcwq->flags |= GCWQ_MANAGE_WORKERS;
+                       wake_up_worker(gcwq);
+               }
+       }
+
+       spin_unlock_irq(&gcwq->lock);
+}
+
+static bool send_mayday(struct work_struct *work)
+{
+       struct cpu_workqueue_struct *cwq = get_work_cwq(work);
+       struct workqueue_struct *wq = cwq->wq;
+       unsigned int cpu;
+
+       if (!(wq->flags & WQ_RESCUER))
+               return false;
+
+       /* mayday mayday mayday */
+       cpu = cwq->gcwq->cpu;
+       /* WORK_CPU_UNBOUND can't be set in cpumask, use cpu 0 instead */
+       if (cpu == WORK_CPU_UNBOUND)
+               cpu = 0;
+       if (!cpumask_test_and_set_cpu(cpu, wq->mayday_mask))
+               wake_up_process(wq->rescuer->task);
+       return true;
+}
+
+static void gcwq_mayday_timeout(unsigned long __gcwq)
+{
+       struct global_cwq *gcwq = (void *)__gcwq;
+       struct work_struct *work;
+
+       spin_lock_irq(&gcwq->lock);
+
+       if (need_to_create_worker(gcwq)) {
+               /*
+                * We've been trying to create a new worker but
+                * haven't been successful.  We might be hitting an
+                * allocation deadlock.  Send distress signals to
+                * rescuers.
+                */
+               list_for_each_entry(work, &gcwq->worklist, entry)
+                       send_mayday(work);
+       }
+
+       spin_unlock_irq(&gcwq->lock);
+
+       mod_timer(&gcwq->mayday_timer, jiffies + MAYDAY_INTERVAL);
+}
+
+/**
+ * maybe_create_worker - create a new worker if necessary
+ * @gcwq: gcwq to create a new worker for
+ *
+ * Create a new worker for @gcwq if necessary.  @gcwq is guaranteed to
+ * have at least one idle worker on return from this function.  If
+ * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
+ * sent to all rescuers with works scheduled on @gcwq to resolve
+ * possible allocation deadlock.
+ *
+ * On return, need_to_create_worker() is guaranteed to be false and
+ * may_start_working() true.
+ *
+ * LOCKING:
+ * spin_lock_irq(gcwq->lock) which may be released and regrabbed
+ * multiple times.  Does GFP_KERNEL allocations.  Called only from
+ * manager.
+ *
+ * RETURNS:
+ * false if no action was taken and gcwq->lock stayed locked, true
+ * otherwise.
+ */
+static bool maybe_create_worker(struct global_cwq *gcwq)
+{
+       if (!need_to_create_worker(gcwq))
+               return false;
+restart:
+       spin_unlock_irq(&gcwq->lock);
+
+       /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
+       mod_timer(&gcwq->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
+
+       while (true) {
+               struct worker *worker;
+
+               worker = create_worker(gcwq, true);
+               if (worker) {
+                       del_timer_sync(&gcwq->mayday_timer);
+                       spin_lock_irq(&gcwq->lock);
+                       start_worker(worker);
+                       BUG_ON(need_to_create_worker(gcwq));
+                       return true;
+               }
+
+               if (!need_to_create_worker(gcwq))
+                       break;
+
+               __set_current_state(TASK_INTERRUPTIBLE);
+               schedule_timeout(CREATE_COOLDOWN);
+
+               if (!need_to_create_worker(gcwq))
+                       break;
+       }
+
+       del_timer_sync(&gcwq->mayday_timer);
+       spin_lock_irq(&gcwq->lock);
+       if (need_to_create_worker(gcwq))
+               goto restart;
+       return true;
+}
+
+/**
+ * maybe_destroy_worker - destroy workers which have been idle for a while
+ * @gcwq: gcwq to destroy workers for
+ *
+ * Destroy @gcwq workers which have been idle for longer than
+ * IDLE_WORKER_TIMEOUT.
+ *
+ * LOCKING:
+ * spin_lock_irq(gcwq->lock) which may be released and regrabbed
+ * multiple times.  Called only from manager.
+ *
+ * RETURNS:
+ * false if no action was taken and gcwq->lock stayed locked, true
+ * otherwise.
+ */
+static bool maybe_destroy_workers(struct global_cwq *gcwq)
+{
+       bool ret = false;
+
+       while (too_many_workers(gcwq)) {
+               struct worker *worker;
+               unsigned long expires;
+
+               worker = list_entry(gcwq->idle_list.prev, struct worker, entry);
+               expires = worker->last_active + IDLE_WORKER_TIMEOUT;
+
+               if (time_before(jiffies, expires)) {
+                       mod_timer(&gcwq->idle_timer, expires);
+                       break;
+               }
+
+               destroy_worker(worker);
+               ret = true;
+       }
+
+       return ret;
+}
+
+/**
+ * manage_workers - manage worker pool
+ * @worker: self
+ *
+ * Assume the manager role and manage gcwq worker pool @worker belongs
+ * to.  At any given time, there can be only zero or one manager per
+ * gcwq.  The exclusion is handled automatically by this function.
+ *
+ * The caller can safely start processing works on false return.  On
+ * true return, it's guaranteed that need_to_create_worker() is false
+ * and may_start_working() is true.
+ *
+ * CONTEXT:
+ * spin_lock_irq(gcwq->lock) which may be released and regrabbed
+ * multiple times.  Does GFP_KERNEL allocations.
+ *
+ * RETURNS:
+ * false if no action was taken and gcwq->lock stayed locked, true if
+ * some action was taken.
+ */
+static bool manage_workers(struct worker *worker)
+{
+       struct global_cwq *gcwq = worker->gcwq;
+       bool ret = false;
+
+       if (gcwq->flags & GCWQ_MANAGING_WORKERS)
+               return ret;
+
+       gcwq->flags &= ~GCWQ_MANAGE_WORKERS;
+       gcwq->flags |= GCWQ_MANAGING_WORKERS;
+
+       /*
+        * Destroy and then create so that may_start_working() is true
+        * on return.
+        */
+       ret |= maybe_destroy_workers(gcwq);
+       ret |= maybe_create_worker(gcwq);
+
+       gcwq->flags &= ~GCWQ_MANAGING_WORKERS;
+
+       /*
+        * The trustee might be waiting to take over the manager
+        * position, tell it we're done.
+        */
+       if (unlikely(gcwq->trustee))
+               wake_up_all(&gcwq->trustee_wait);
+
+       return ret;
+}
+
 /**
  * move_linked_works - move linked works to a list
  * @work: start of series of works to be scheduled
@@ -976,8 +1609,9 @@ static void cwq_activate_first_delayed(struct cpu_workqueue_struct *cwq)
 {
        struct work_struct *work = list_first_entry(&cwq->delayed_works,
                                                    struct work_struct, entry);
+       struct list_head *pos = gcwq_determine_ins_pos(cwq->gcwq, cwq);
 
-       move_linked_works(work, &cwq->gcwq->worklist, NULL);
+       move_linked_works(work, pos, NULL);
        cwq->nr_active++;
 }
 
@@ -1005,9 +1639,6 @@ static void cwq_dec_nr_in_flight(struct cpu_workqueue_struct *cwq, int color)
                /* one down, submit a delayed one */
                if (cwq->nr_active < cwq->max_active)
                        cwq_activate_first_delayed(cwq);
-       } else if (!cwq->nr_active && cwq->wq->flags & WQ_SINGLE_CPU) {
-               /* this was the last work, unbind from single cpu */
-               cwq_unbind_single_cpu(cwq);
        }
 
        /* is flush in progress and are we at the flushing tip? */
@@ -1048,6 +1679,7 @@ static void process_one_work(struct worker *worker, struct work_struct *work)
        struct cpu_workqueue_struct *cwq = get_work_cwq(work);
        struct global_cwq *gcwq = cwq->gcwq;
        struct hlist_head *bwh = busy_worker_head(gcwq, work);
+       bool cpu_intensive = cwq->wq->flags & WQ_CPU_INTENSIVE;
        work_func_t f = work->func;
        int work_color;
        struct worker *collision;
@@ -1080,9 +1712,31 @@ static void process_one_work(struct worker *worker, struct work_struct *work)
        worker->current_cwq = cwq;
        work_color = get_work_color(work);
 
-       /* record the current cpu number in the work data and dequeue */
-       set_work_cpu(work, gcwq->cpu);
-       list_del_init(&work->entry);
+       /* record the current cpu number in the work data and dequeue */
+       set_work_cpu(work, gcwq->cpu);
+       list_del_init(&work->entry);
+
+       /*
+        * If HIGHPRI_PENDING, check the next work, and, if HIGHPRI,
+        * wake up another worker; otherwise, clear HIGHPRI_PENDING.
+        */
+       if (unlikely(gcwq->flags & GCWQ_HIGHPRI_PENDING)) {
+               struct work_struct *nwork = list_first_entry(&gcwq->worklist,
+                                               struct work_struct, entry);
+
+               if (!list_empty(&gcwq->worklist) &&
+                   get_work_cwq(nwork)->wq->flags & WQ_HIGHPRI)
+                       wake_up_worker(gcwq);
+               else
+                       gcwq->flags &= ~GCWQ_HIGHPRI_PENDING;
+       }
+
+       /*
+        * CPU intensive works don't participate in concurrency
+        * management.  They're the scheduler's responsibility.
+        */
+       if (unlikely(cpu_intensive))
+               worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
 
        spin_unlock_irq(&gcwq->lock);
 
@@ -1105,6 +1759,10 @@ static void process_one_work(struct worker *worker, struct work_struct *work)
 
        spin_lock_irq(&gcwq->lock);
 
+       /* clear cpu intensive status */
+       if (unlikely(cpu_intensive))
+               worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
+
        /* we're done with it, release */
        hlist_del_init(&worker->hentry);
        worker->current_work = NULL;
@@ -1137,24 +1795,39 @@ static void process_scheduled_works(struct worker *worker)
  * worker_thread - the worker thread function
  * @__worker: self
  *
- * The cwq worker thread function.
+ * The gcwq worker thread function.  There's a single dynamic pool of
+ * these per each cpu.  These workers process all works regardless of
+ * their specific target workqueue.  The only exception is works which
+ * belong to workqueues with a rescuer which will be explained in
+ * rescuer_thread().
  */
 static int worker_thread(void *__worker)
 {
        struct worker *worker = __worker;
        struct global_cwq *gcwq = worker->gcwq;
 
+       /* tell the scheduler that this is a workqueue worker */
+       worker->task->flags |= PF_WQ_WORKER;
 woke_up:
        spin_lock_irq(&gcwq->lock);
 
        /* DIE can be set only while we're idle, checking here is enough */
        if (worker->flags & WORKER_DIE) {
                spin_unlock_irq(&gcwq->lock);
+               worker->task->flags &= ~PF_WQ_WORKER;
                return 0;
        }
 
        worker_leave_idle(worker);
 recheck:
+       /* no more worker necessary? */
+       if (!need_more_worker(gcwq))
+               goto sleep;
+
+       /* do we need to manage? */
+       if (unlikely(!may_start_working(gcwq)) && manage_workers(worker))
+               goto recheck;
+
        /*
         * ->scheduled list can only be filled while a worker is
         * preparing to process a work or actually processing it.
@@ -1162,27 +1835,18 @@ recheck:
         */
        BUG_ON(!list_empty(&worker->scheduled));
 
-       while (!list_empty(&gcwq->worklist)) {
+       /*
+        * When control reaches this point, we're guaranteed to have
+        * at least one idle worker or that someone else has already
+        * assumed the manager role.
+        */
+       worker_clr_flags(worker, WORKER_PREP);
+
+       do {
                struct work_struct *work =
                        list_first_entry(&gcwq->worklist,
                                         struct work_struct, entry);
 
-               /*
-                * The following is a rather inefficient way to close
-                * race window against cpu hotplug operations.  Will
-                * be replaced soon.
-                */
-               if (unlikely(!(worker->flags & WORKER_ROGUE) &&
-                            !cpumask_equal(&worker->task->cpus_allowed,
-                                           get_cpu_mask(gcwq->cpu)))) {
-                       spin_unlock_irq(&gcwq->lock);
-                       set_cpus_allowed_ptr(worker->task,
-                                            get_cpu_mask(gcwq->cpu));
-                       cpu_relax();
-                       spin_lock_irq(&gcwq->lock);
-                       goto recheck;
-               }
-
                if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
                        /* optimization path, not strictly necessary */
                        process_one_work(worker, work);
@@ -1192,13 +1856,19 @@ recheck:
                        move_linked_works(work, &worker->scheduled, NULL);
                        process_scheduled_works(worker);
                }
-       }
+       } while (keep_working(gcwq));
+
+       worker_set_flags(worker, WORKER_PREP, false);
+sleep:
+       if (unlikely(need_to_manage_workers(gcwq)) && manage_workers(worker))
+               goto recheck;
 
        /*
-        * gcwq->lock is held and there's no work to process, sleep.
-        * Workers are woken up only while holding gcwq->lock, so
-        * setting the current state before releasing gcwq->lock is
-        * enough to prevent losing any event.
+        * gcwq->lock is held and there's no work to process and no
+        * need to manage, sleep.  Workers are woken up only while
+        * holding gcwq->lock or from local cpu, so setting the
+        * current state before releasing gcwq->lock is enough to
+        * prevent losing any event.
         */
        worker_enter_idle(worker);
        __set_current_state(TASK_INTERRUPTIBLE);
@@ -1207,6 +1877,74 @@ recheck:
        goto woke_up;
 }
 
+/**
+ * rescuer_thread - the rescuer thread function
+ * @__wq: the associated workqueue
+ *
+ * Workqueue rescuer thread function.  There's one rescuer for each
+ * workqueue which has WQ_RESCUER set.
+ *
+ * Regular work processing on a gcwq may block trying to create a new
+ * worker which uses GFP_KERNEL allocation which has slight chance of
+ * developing into deadlock if some works currently on the same queue
+ * need to be processed to satisfy the GFP_KERNEL allocation.  This is
+ * the problem rescuer solves.
+ *
+ * When such condition is possible, the gcwq summons rescuers of all
+ * workqueues which have works queued on the gcwq and let them process
+ * those works so that forward progress can be guaranteed.
+ *
+ * This should happen rarely.
+ */
+static int rescuer_thread(void *__wq)
+{
+       struct workqueue_struct *wq = __wq;
+       struct worker *rescuer = wq->rescuer;
+       struct list_head *scheduled = &rescuer->scheduled;
+       bool is_unbound = wq->flags & WQ_UNBOUND;
+       unsigned int cpu;
+
+       set_user_nice(current, RESCUER_NICE_LEVEL);
+repeat:
+       set_current_state(TASK_INTERRUPTIBLE);
+
+       if (kthread_should_stop())
+               return 0;
+
+       /*
+        * See whether any cpu is asking for help.  Unbounded
+        * workqueues use cpu 0 in mayday_mask for CPU_UNBOUND.
+        */
+       for_each_cpu(cpu, wq->mayday_mask) {
+               unsigned int tcpu = is_unbound ? WORK_CPU_UNBOUND : cpu;
+               struct cpu_workqueue_struct *cwq = get_cwq(tcpu, wq);
+               struct global_cwq *gcwq = cwq->gcwq;
+               struct work_struct *work, *n;
+
+               __set_current_state(TASK_RUNNING);
+               cpumask_clear_cpu(cpu, wq->mayday_mask);
+
+               /* migrate to the target cpu if possible */
+               rescuer->gcwq = gcwq;
+               worker_maybe_bind_and_lock(rescuer);
+
+               /*
+                * Slurp in all works issued via this workqueue and
+                * process'em.
+                */
+               BUG_ON(!list_empty(&rescuer->scheduled));
+               list_for_each_entry_safe(work, n, &gcwq->worklist, entry)
+                       if (get_work_cwq(work) == cwq)
+                               move_linked_works(work, scheduled, &n);
+
+               process_scheduled_works(rescuer);
+               spin_unlock_irq(&gcwq->lock);
+       }
+
+       schedule();
+       goto repeat;
+}
+
 struct wq_barrier {
        struct work_struct      work;
        struct completion       done;
@@ -1321,7 +2059,7 @@ static bool flush_workqueue_prep_cwqs(struct workqueue_struct *wq,
                atomic_set(&wq->nr_cwqs_to_flush, 1);
        }
 
-       for_each_possible_cpu(cpu) {
+       for_each_cwq_cpu(cpu, wq) {
                struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
                struct global_cwq *gcwq = cwq->gcwq;
 
@@ -1433,6 +2171,10 @@ void flush_workqueue(struct workqueue_struct *wq)
 
        mutex_lock(&wq->flush_mutex);
 
+       /* we might have raced, check again with mutex held */
+       if (wq->first_flusher != &this_flusher)
+               goto out_unlock;
+
        wq->first_flusher = NULL;
 
        BUG_ON(!list_empty(&this_flusher.list));
@@ -1627,7 +2369,7 @@ static void wait_on_work(struct work_struct *work)
        lock_map_acquire(&work->lockdep_map);
        lock_map_release(&work->lockdep_map);
 
-       for_each_possible_cpu(cpu)
+       for_each_gcwq_cpu(cpu)
                wait_on_cpu_work(get_gcwq(cpu), work);
 }
 
@@ -1689,8 +2431,6 @@ int cancel_delayed_work_sync(struct delayed_work *dwork)
 }
 EXPORT_SYMBOL(cancel_delayed_work_sync);
 
-static struct workqueue_struct *keventd_wq __read_mostly;
-
 /**
  * schedule_work - put work task in global workqueue
  * @work: job to be done
@@ -1704,7 +2444,7 @@ static struct workqueue_struct *keventd_wq __read_mostly;
  */
 int schedule_work(struct work_struct *work)
 {
-       return queue_work(keventd_wq, work);
+       return queue_work(system_wq, work);
 }
 EXPORT_SYMBOL(schedule_work);
 
@@ -1717,7 +2457,7 @@ EXPORT_SYMBOL(schedule_work);
  */
 int schedule_work_on(int cpu, struct work_struct *work)
 {
-       return queue_work_on(cpu, keventd_wq, work);
+       return queue_work_on(cpu, system_wq, work);
 }
 EXPORT_SYMBOL(schedule_work_on);
 
@@ -1732,7 +2472,7 @@ EXPORT_SYMBOL(schedule_work_on);
 int schedule_delayed_work(struct delayed_work *dwork,
                                        unsigned long delay)
 {
-       return queue_delayed_work(keventd_wq, dwork, delay);
+       return queue_delayed_work(system_wq, dwork, delay);
 }
 EXPORT_SYMBOL(schedule_delayed_work);
 
@@ -1765,7 +2505,7 @@ EXPORT_SYMBOL(flush_delayed_work);
 int schedule_delayed_work_on(int cpu,
                        struct delayed_work *dwork, unsigned long delay)
 {
-       return queue_delayed_work_on(cpu, keventd_wq, dwork, delay);
+       return queue_delayed_work_on(cpu, system_wq, dwork, delay);
 }
 EXPORT_SYMBOL(schedule_delayed_work_on);
 
@@ -1781,7 +2521,6 @@ EXPORT_SYMBOL(schedule_delayed_work_on);
 int schedule_on_each_cpu(work_func_t func)
 {
        int cpu;
-       int orig = -1;
        struct work_struct *works;
 
        works = alloc_percpu(struct work_struct);
@@ -1790,23 +2529,12 @@ int schedule_on_each_cpu(work_func_t func)
 
        get_online_cpus();
 
-       /*
-        * When running in keventd don't schedule a work item on
-        * itself.  Can just call directly because the work queue is
-        * already bound.  This also is faster.
-        */
-       if (current_is_keventd())
-               orig = raw_smp_processor_id();
-
        for_each_online_cpu(cpu) {
                struct work_struct *work = per_cpu_ptr(works, cpu);
 
                INIT_WORK(work, func);
-               if (cpu != orig)
-                       schedule_work_on(cpu, work);
+               schedule_work_on(cpu, work);
        }
-       if (orig >= 0)
-               func(per_cpu_ptr(works, orig));
 
        for_each_online_cpu(cpu)
                flush_work(per_cpu_ptr(works, cpu));
@@ -1842,7 +2570,7 @@ int schedule_on_each_cpu(work_func_t func)
  */
 void flush_scheduled_work(void)
 {
-       flush_workqueue(keventd_wq);
+       flush_workqueue(system_wq);
 }
 EXPORT_SYMBOL(flush_scheduled_work);
 
@@ -1874,45 +2602,10 @@ EXPORT_SYMBOL_GPL(execute_in_process_context);
 
 int keventd_up(void)
 {
-       return keventd_wq != NULL;
-}
-
-int current_is_keventd(void)
-{
-       bool found = false;
-       unsigned int cpu;
-
-       /*
-        * There no longer is one-to-one relation between worker and
-        * work queue and a worker task might be unbound from its cpu
-        * if the cpu was offlined.  Match all busy workers.  This
-        * function will go away once dynamic pool is implemented.
-        */
-       for_each_possible_cpu(cpu) {
-               struct global_cwq *gcwq = get_gcwq(cpu);
-               struct worker *worker;
-               struct hlist_node *pos;
-               unsigned long flags;
-               int i;
-
-               spin_lock_irqsave(&gcwq->lock, flags);
-
-               for_each_busy_worker(worker, i, pos, gcwq) {
-                       if (worker->task == current) {
-                               found = true;
-                               break;
-                       }
-               }
-
-               spin_unlock_irqrestore(&gcwq->lock, flags);
-               if (found)
-                       break;
-       }
-
-       return found;
+       return system_wq != NULL;
 }
 
-static struct cpu_workqueue_struct *alloc_cwqs(void)
+static int alloc_cwqs(struct workqueue_struct *wq)
 {
        /*
         * cwqs are forced aligned according to WORK_STRUCT_FLAG_BITS.
@@ -1922,83 +2615,91 @@ static struct cpu_workqueue_struct *alloc_cwqs(void)
        const size_t size = sizeof(struct cpu_workqueue_struct);
        const size_t align = max_t(size_t, 1 << WORK_STRUCT_FLAG_BITS,
                                   __alignof__(unsigned long long));
-       struct cpu_workqueue_struct *cwqs;
-#ifndef CONFIG_SMP
-       void *ptr;
 
-       /*
-        * On UP, percpu allocator doesn't honor alignment parameter
-        * and simply uses arch-dependent default.  Allocate enough
-        * room to align cwq and put an extra pointer at the end
-        * pointing back to the originally allocated pointer which
-        * will be used for free.
-        *
-        * FIXME: This really belongs to UP percpu code.  Update UP
-        * percpu code to honor alignment and remove this ugliness.
-        */
-       ptr = __alloc_percpu(size + align + sizeof(void *), 1);
-       cwqs = PTR_ALIGN(ptr, align);
-       *(void **)per_cpu_ptr(cwqs + 1, 0) = ptr;
-#else
-       /* On SMP, percpu allocator can do it itself */
-       cwqs = __alloc_percpu(size, align);
-#endif
+       if (CONFIG_SMP && !(wq->flags & WQ_UNBOUND)) {
+               /* on SMP, percpu allocator can align itself */
+               wq->cpu_wq.pcpu = __alloc_percpu(size, align);
+       } else {
+               void *ptr;
+
+               /*
+                * Allocate enough room to align cwq and put an extra
+                * pointer at the end pointing back to the originally
+                * allocated pointer which will be used for free.
+                */
+               ptr = kzalloc(size + align + sizeof(void *), GFP_KERNEL);
+               if (ptr) {
+                       wq->cpu_wq.single = PTR_ALIGN(ptr, align);
+                       *(void **)(wq->cpu_wq.single + 1) = ptr;
+               }
+       }
+
        /* just in case, make sure it's actually aligned */
-       BUG_ON(!IS_ALIGNED((unsigned long)cwqs, align));
-       return cwqs;
+       BUG_ON(!IS_ALIGNED(wq->cpu_wq.v, align));
+       return wq->cpu_wq.v ? 0 : -ENOMEM;
 }
 
-static void free_cwqs(struct cpu_workqueue_struct *cwqs)
+static void free_cwqs(struct workqueue_struct *wq)
 {
-#ifndef CONFIG_SMP
-       /* on UP, the pointer to free is stored right after the cwq */
-       if (cwqs)
-               free_percpu(*(void **)per_cpu_ptr(cwqs + 1, 0));
-#else
-       free_percpu(cwqs);
-#endif
+       if (CONFIG_SMP && !(wq->flags & WQ_UNBOUND))
+               free_percpu(wq->cpu_wq.pcpu);
+       else if (wq->cpu_wq.single) {
+               /* the pointer to free is stored right after the cwq */
+               kfree(*(void **)(wq->cpu_wq.single + 1));
+       }
+}
+
+static int wq_clamp_max_active(int max_active, unsigned int flags,
+                              const char *name)
+{
+       int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
+
+       if (max_active < 1 || max_active > lim)
+               printk(KERN_WARNING "workqueue: max_active %d requested for %s "
+                      "is out of range, clamping between %d and %d\n",
+                      max_active, name, 1, lim);
+
+       return clamp_val(max_active, 1, lim);
 }
 
-struct workqueue_struct *__create_workqueue_key(const char *name,
-                                               unsigned int flags,
-                                               int max_active,
-                                               struct lock_class_key *key,
-                                               const char *lock_name)
+struct workqueue_struct *__alloc_workqueue_key(const char *name,
+                                              unsigned int flags,
+                                              int max_active,
+                                              struct lock_class_key *key,
+                                              const char *lock_name)
 {
        struct workqueue_struct *wq;
-       bool failed = false;
        unsigned int cpu;
 
-       max_active = clamp_val(max_active, 1, INT_MAX);
+       /*
+        * Unbound workqueues aren't concurrency managed and should be
+        * dispatched to workers immediately.
+        */
+       if (flags & WQ_UNBOUND)
+               flags |= WQ_HIGHPRI;
+
+       max_active = max_active ?: WQ_DFL_ACTIVE;
+       max_active = wq_clamp_max_active(max_active, flags, name);
 
        wq = kzalloc(sizeof(*wq), GFP_KERNEL);
        if (!wq)
                goto err;
 
-       wq->cpu_wq = alloc_cwqs();
-       if (!wq->cpu_wq)
-               goto err;
-
        wq->flags = flags;
        wq->saved_max_active = max_active;
        mutex_init(&wq->flush_mutex);
        atomic_set(&wq->nr_cwqs_to_flush, 0);
        INIT_LIST_HEAD(&wq->flusher_queue);
        INIT_LIST_HEAD(&wq->flusher_overflow);
-       wq->single_cpu = NR_CPUS;
 
        wq->name = name;
        lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
        INIT_LIST_HEAD(&wq->list);
 
-       cpu_maps_update_begin();
-       /*
-        * We must initialize cwqs for each possible cpu even if we
-        * are going to call destroy_workqueue() finally. Otherwise
-        * cpu_up() can hit the uninitialized cwq once we drop the
-        * lock.
-        */
-       for_each_possible_cpu(cpu) {
+       if (alloc_cwqs(wq) < 0)
+               goto err;
+
+       for_each_cwq_cpu(cpu, wq) {
                struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
                struct global_cwq *gcwq = get_gcwq(cpu);
 
@@ -2008,14 +2709,25 @@ struct workqueue_struct *__create_workqueue_key(const char *name,
                cwq->flush_color = -1;
                cwq->max_active = max_active;
                INIT_LIST_HEAD(&cwq->delayed_works);
+       }
 
-               if (failed)
-                       continue;
-               cwq->worker = create_worker(gcwq, cpu_online(cpu));
-               if (cwq->worker)
-                       start_worker(cwq->worker);
-               else
-                       failed = true;
+       if (flags & WQ_RESCUER) {
+               struct worker *rescuer;
+
+               if (!alloc_cpumask_var(&wq->mayday_mask, GFP_KERNEL))
+                       goto err;
+
+               wq->rescuer = rescuer = alloc_worker();
+               if (!rescuer)
+                       goto err;
+
+               rescuer->task = kthread_create(rescuer_thread, wq, "%s", name);
+               if (IS_ERR(rescuer->task))
+                       goto err;
+
+               wq->rescuer = rescuer;
+               rescuer->task->flags |= PF_THREAD_BOUND;
+               wake_up_process(rescuer->task);
        }
 
        /*
@@ -2026,28 +2738,24 @@ struct workqueue_struct *__create_workqueue_key(const char *name,
        spin_lock(&workqueue_lock);
 
        if (workqueue_freezing && wq->flags & WQ_FREEZEABLE)
-               for_each_possible_cpu(cpu)
+               for_each_cwq_cpu(cpu, wq)
                        get_cwq(cpu, wq)->max_active = 0;
 
        list_add(&wq->list, &workqueues);
 
        spin_unlock(&workqueue_lock);
 
-       cpu_maps_update_done();
-
-       if (failed) {
-               destroy_workqueue(wq);
-               wq = NULL;
-       }
        return wq;
 err:
        if (wq) {
-               free_cwqs(wq->cpu_wq);
+               free_cwqs(wq);
+               free_cpumask_var(wq->mayday_mask);
+               kfree(wq->rescuer);
                kfree(wq);
        }
        return NULL;
 }
-EXPORT_SYMBOL_GPL(__create_workqueue_key);
+EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
 
 /**
  * destroy_workqueue - safely terminate a workqueue
@@ -2065,54 +2773,152 @@ void destroy_workqueue(struct workqueue_struct *wq)
         * wq list is used to freeze wq, remove from list after
         * flushing is complete in case freeze races us.
         */
-       cpu_maps_update_begin();
        spin_lock(&workqueue_lock);
        list_del(&wq->list);
        spin_unlock(&workqueue_lock);
-       cpu_maps_update_done();
 
-       for_each_possible_cpu(cpu) {
+       /* sanity check */
+       for_each_cwq_cpu(cpu, wq) {
                struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
-               struct global_cwq *gcwq = cwq->gcwq;
                int i;
 
-               if (cwq->worker) {
-               retry:
-                       spin_lock_irq(&gcwq->lock);
-                       /*
-                        * Worker can only be destroyed while idle.
-                        * Wait till it becomes idle.  This is ugly
-                        * and prone to starvation.  It will go away
-                        * once dynamic worker pool is implemented.
-                        */
-                       if (!(cwq->worker->flags & WORKER_IDLE)) {
-                               spin_unlock_irq(&gcwq->lock);
-                               msleep(100);
-                               goto retry;
-                       }
-                       destroy_worker(cwq->worker);
-                       cwq->worker = NULL;
-                       spin_unlock_irq(&gcwq->lock);
-               }
-
                for (i = 0; i < WORK_NR_COLORS; i++)
                        BUG_ON(cwq->nr_in_flight[i]);
                BUG_ON(cwq->nr_active);
                BUG_ON(!list_empty(&cwq->delayed_works));
        }
 
-       free_cwqs(wq->cpu_wq);
+       if (wq->flags & WQ_RESCUER) {
+               kthread_stop(wq->rescuer->task);
+               free_cpumask_var(wq->mayday_mask);
+       }
+
+       free_cwqs(wq);
        kfree(wq);
 }
 EXPORT_SYMBOL_GPL(destroy_workqueue);
 
+/**
+ * workqueue_set_max_active - adjust max_active of a workqueue
+ * @wq: target workqueue
+ * @max_active: new max_active value.
+ *
+ * Set max_active of @wq to @max_active.
+ *
+ * CONTEXT:
+ * Don't call from IRQ context.
+ */
+void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
+{
+       unsigned int cpu;
+
+       max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
+
+       spin_lock(&workqueue_lock);
+
+       wq->saved_max_active = max_active;
+
+       for_each_cwq_cpu(cpu, wq) {
+               struct global_cwq *gcwq = get_gcwq(cpu);
+
+               spin_lock_irq(&gcwq->lock);
+
+               if (!(wq->flags & WQ_FREEZEABLE) ||
+                   !(gcwq->flags & GCWQ_FREEZING))
+                       get_cwq(gcwq->cpu, wq)->max_active = max_active;
+
+               spin_unlock_irq(&gcwq->lock);
+       }
+
+       spin_unlock(&workqueue_lock);
+}
+EXPORT_SYMBOL_GPL(workqueue_set_max_active);
+
+/**
+ * workqueue_congested - test whether a workqueue is congested
+ * @cpu: CPU in question
+ * @wq: target workqueue
+ *
+ * Test whether @wq's cpu workqueue for @cpu is congested.  There is
+ * no synchronization around this function and the test result is
+ * unreliable and only useful as advisory hints or for debugging.
+ *
+ * RETURNS:
+ * %true if congested, %false otherwise.
+ */
+bool workqueue_congested(unsigned int cpu, struct workqueue_struct *wq)
+{
+       struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
+
+       return !list_empty(&cwq->delayed_works);
+}
+EXPORT_SYMBOL_GPL(workqueue_congested);
+
+/**
+ * work_cpu - return the last known associated cpu for @work
+ * @work: the work of interest
+ *
+ * RETURNS:
+ * CPU number if @work was ever queued.  WORK_CPU_NONE otherwise.
+ */
+unsigned int work_cpu(struct work_struct *work)
+{
+       struct global_cwq *gcwq = get_work_gcwq(work);
+
+       return gcwq ? gcwq->cpu : WORK_CPU_NONE;
+}
+EXPORT_SYMBOL_GPL(work_cpu);
+
+/**
+ * work_busy - test whether a work is currently pending or running
+ * @work: the work to be tested
+ *
+ * Test whether @work is currently pending or running.  There is no
+ * synchronization around this function and the test result is
+ * unreliable and only useful as advisory hints or for debugging.
+ * Especially for reentrant wqs, the pending state might hide the
+ * running state.
+ *
+ * RETURNS:
+ * OR'd bitmask of WORK_BUSY_* bits.
+ */
+unsigned int work_busy(struct work_struct *work)
+{
+       struct global_cwq *gcwq = get_work_gcwq(work);
+       unsigned long flags;
+       unsigned int ret = 0;
+
+       if (!gcwq)
+               return false;
+
+       spin_lock_irqsave(&gcwq->lock, flags);
+
+       if (work_pending(work))
+               ret |= WORK_BUSY_PENDING;
+       if (find_worker_executing_work(gcwq, work))
+               ret |= WORK_BUSY_RUNNING;
+
+       spin_unlock_irqrestore(&gcwq->lock, flags);
+
+       return ret;
+}
+EXPORT_SYMBOL_GPL(work_busy);
+
 /*
  * CPU hotplug.
  *
- * CPU hotplug is implemented by allowing cwqs to be detached from
- * CPU, running with unbound workers and allowing them to be
- * reattached later if the cpu comes back online.  A separate thread
- * is created to govern cwqs in such state and is called the trustee.
+ * There are two challenges in supporting CPU hotplug.  Firstly, there
+ * are a lot of assumptions on strong associations among work, cwq and
+ * gcwq which make migrating pending and scheduled works very
+ * difficult to implement without impacting hot paths.  Secondly,
+ * gcwqs serve mix of short, long and very long running works making
+ * blocked draining impractical.
+ *
+ * This is solved by allowing a gcwq to be detached from CPU, running
+ * it with unbound (rogue) workers and allowing it to be reattached
+ * later if the cpu comes back online.  A separate thread is created
+ * to govern a gcwq in such state and is called the trustee of the
+ * gcwq.
  *
  * Trustee states and their descriptions.
  *
@@ -2120,11 +2926,12 @@ EXPORT_SYMBOL_GPL(destroy_workqueue);
  *             new trustee is started with this state.
  *
  * IN_CHARGE   Once started, trustee will enter this state after
- *             making all existing workers rogue.  DOWN_PREPARE waits
- *             for trustee to enter this state.  After reaching
- *             IN_CHARGE, trustee tries to execute the pending
- *             worklist until it's empty and the state is set to
- *             BUTCHER, or the state is set to RELEASE.
+ *             assuming the manager role and making all existing
+ *             workers rogue.  DOWN_PREPARE waits for trustee to
+ *             enter this state.  After reaching IN_CHARGE, trustee
+ *             tries to execute the pending worklist until it's empty
+ *             and the state is set to BUTCHER, or the state is set
+ *             to RELEASE.
  *
  * BUTCHER     Command state which is set by the cpu callback after
  *             the cpu has went down.  Once this state is set trustee
@@ -2135,7 +2942,9 @@ EXPORT_SYMBOL_GPL(destroy_workqueue);
  * RELEASE     Command state which is set by the cpu callback if the
  *             cpu down has been canceled or it has come online
  *             again.  After recognizing this state, trustee stops
- *             trying to drain or butcher and transits to DONE.
+ *             trying to drain or butcher and clears ROGUE, rebinds
+ *             all remaining workers back to the cpu and releases
+ *             manager role.
  *
  * DONE                Trustee will enter this state after BUTCHER or RELEASE
  *             is complete.
@@ -2201,17 +3010,24 @@ static int __cpuinit trustee_thread(void *__gcwq)
 {
        struct global_cwq *gcwq = __gcwq;
        struct worker *worker;
+       struct work_struct *work;
        struct hlist_node *pos;
+       long rc;
        int i;
 
        BUG_ON(gcwq->cpu != smp_processor_id());
 
        spin_lock_irq(&gcwq->lock);
        /*
-        * Make all workers rogue.  Trustee must be bound to the
-        * target cpu and can't be cancelled.
+        * Claim the manager position and make all workers rogue.
+        * Trustee must be bound to the target cpu and can't be
+        * cancelled.
         */
        BUG_ON(gcwq->cpu != smp_processor_id());
+       rc = trustee_wait_event(!(gcwq->flags & GCWQ_MANAGING_WORKERS));
+       BUG_ON(rc < 0);
+
+       gcwq->flags |= GCWQ_MANAGING_WORKERS;
 
        list_for_each_entry(worker, &gcwq->idle_list, entry)
                worker->flags |= WORKER_ROGUE;
@@ -2219,6 +3035,28 @@ static int __cpuinit trustee_thread(void *__gcwq)
        for_each_busy_worker(worker, i, pos, gcwq)
                worker->flags |= WORKER_ROGUE;
 
+       /*
+        * Call schedule() so that we cross rq->lock and thus can
+        * guarantee sched callbacks see the rogue flag.  This is
+        * necessary as scheduler callbacks may be invoked from other
+        * cpus.
+        */
+       spin_unlock_irq(&gcwq->lock);
+       schedule();
+       spin_lock_irq(&gcwq->lock);
+
+       /*
+        * Sched callbacks are disabled now.  Zap nr_running.  After
+        * this, nr_running stays zero and need_more_worker() and
+        * keep_working() are always true as long as the worklist is
+        * not empty.
+        */
+       atomic_set(get_gcwq_nr_running(gcwq->cpu), 0);
+
+       spin_unlock_irq(&gcwq->lock);
+       del_timer_sync(&gcwq->idle_timer);
+       spin_lock_irq(&gcwq->lock);
+
        /*
         * We're now in charge.  Notify and proceed to drain.  We need
         * to keep the gcwq running during the whole CPU down
@@ -2231,18 +3069,90 @@ static int __cpuinit trustee_thread(void *__gcwq)
        /*
         * The original cpu is in the process of dying and may go away
         * anytime now.  When that happens, we and all workers would
-        * be migrated to other cpus.  Try draining any left work.
-        * Note that if the gcwq is frozen, there may be frozen works
-        * in freezeable cwqs.  Don't declare completion while frozen.
+        * be migrated to other cpus.  Try draining any left work.  We
+        * want to get it over with ASAP - spam rescuers, wake up as
+        * many idlers as necessary and create new ones till the
+        * worklist is empty.  Note that if the gcwq is frozen, there
+        * may be frozen works in freezeable cwqs.  Don't declare
+        * completion while frozen.
         */
        while (gcwq->nr_workers != gcwq->nr_idle ||
               gcwq->flags & GCWQ_FREEZING ||
               gcwq->trustee_state == TRUSTEE_IN_CHARGE) {
+               int nr_works = 0;
+
+               list_for_each_entry(work, &gcwq->worklist, entry) {
+                       send_mayday(work);
+                       nr_works++;
+               }
+
+               list_for_each_entry(worker, &gcwq->idle_list, entry) {
+                       if (!nr_works--)
+                               break;
+                       wake_up_process(worker->task);
+               }
+
+               if (need_to_create_worker(gcwq)) {
+                       spin_unlock_irq(&gcwq->lock);
+                       worker = create_worker(gcwq, false);
+                       spin_lock_irq(&gcwq->lock);
+                       if (worker) {
+                               worker->flags |= WORKER_ROGUE;
+                               start_worker(worker);
+                       }
+               }
+
                /* give a breather */
                if (trustee_wait_event_timeout(false, TRUSTEE_COOLDOWN) < 0)
                        break;
        }
 
+       /*
+        * Either all works have been scheduled and cpu is down, or
+        * cpu down has already been canceled.  Wait for and butcher
+        * all workers till we're canceled.
+        */
+       do {
+               rc = trustee_wait_event(!list_empty(&gcwq->idle_list));
+               while (!list_empty(&gcwq->idle_list))
+                       destroy_worker(list_first_entry(&gcwq->idle_list,
+                                                       struct worker, entry));
+       } while (gcwq->nr_workers && rc >= 0);
+
+       /*
+        * At this point, either draining has completed and no worker
+        * is left, or cpu down has been canceled or the cpu is being
+        * brought back up.  There shouldn't be any idle one left.
+        * Tell the remaining busy ones to rebind once it finishes the
+        * currently scheduled works by scheduling the rebind_work.
+        */
+       WARN_ON(!list_empty(&gcwq->idle_list));
+
+       for_each_busy_worker(worker, i, pos, gcwq) {
+               struct work_struct *rebind_work = &worker->rebind_work;
+
+               /*
+                * Rebind_work may race with future cpu hotplug
+                * operations.  Use a separate flag to mark that
+                * rebinding is scheduled.
+                */
+               worker->flags |= WORKER_REBIND;
+               worker->flags &= ~WORKER_ROGUE;
+
+               /* queue rebind_work, wq doesn't matter, use the default one */
+               if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
+                                    work_data_bits(rebind_work)))
+                       continue;
+
+               debug_work_activate(rebind_work);
+               insert_work(get_cwq(gcwq->cpu, system_wq), rebind_work,
+                           worker->scheduled.next,
+                           work_color_to_flags(WORK_NO_COLOR));
+       }
+
+       /* relinquish manager role */
+       gcwq->flags &= ~GCWQ_MANAGING_WORKERS;
+
        /* notify completion */
        gcwq->trustee = NULL;
        gcwq->trustee_state = TRUSTEE_DONE;
@@ -2281,10 +3191,8 @@ static int __devinit workqueue_cpu_callback(struct notifier_block *nfb,
        unsigned int cpu = (unsigned long)hcpu;
        struct global_cwq *gcwq = get_gcwq(cpu);
        struct task_struct *new_trustee = NULL;
-       struct worker *worker;
-       struct hlist_node *pos;
+       struct worker *uninitialized_var(new_worker);
        unsigned long flags;
-       int i;
 
        action &= ~CPU_TASKS_FROZEN;
 
@@ -2295,6 +3203,15 @@ static int __devinit workqueue_cpu_callback(struct notifier_block *nfb,
                if (IS_ERR(new_trustee))
                        return notifier_from_errno(PTR_ERR(new_trustee));
                kthread_bind(new_trustee, cpu);
+               /* fall through */
+       case CPU_UP_PREPARE:
+               BUG_ON(gcwq->first_idle);
+               new_worker = create_worker(gcwq, false);
+               if (!new_worker) {
+                       if (new_trustee)
+                               kthread_stop(new_trustee);
+                       return NOTIFY_BAD;
+               }
        }
 
        /* some are called w/ irq disabled, don't disturb irq status */
@@ -2308,26 +3225,50 @@ static int __devinit workqueue_cpu_callback(struct notifier_block *nfb,
                gcwq->trustee_state = TRUSTEE_START;
                wake_up_process(gcwq->trustee);
                wait_trustee_state(gcwq, TRUSTEE_IN_CHARGE);
+               /* fall through */
+       case CPU_UP_PREPARE:
+               BUG_ON(gcwq->first_idle);
+               gcwq->first_idle = new_worker;
+               break;
+
+       case CPU_DYING:
+               /*
+                * Before this, the trustee and all workers except for
+                * the ones which are still executing works from
+                * before the last CPU down must be on the cpu.  After
+                * this, they'll all be diasporas.
+                */
+               gcwq->flags |= GCWQ_DISASSOCIATED;
                break;
 
        case CPU_POST_DEAD:
                gcwq->trustee_state = TRUSTEE_BUTCHER;
+               /* fall through */
+       case CPU_UP_CANCELED:
+               destroy_worker(gcwq->first_idle);
+               gcwq->first_idle = NULL;
                break;
 
        case CPU_DOWN_FAILED:
        case CPU_ONLINE:
+               gcwq->flags &= ~GCWQ_DISASSOCIATED;
                if (gcwq->trustee_state != TRUSTEE_DONE) {
                        gcwq->trustee_state = TRUSTEE_RELEASE;
                        wake_up_process(gcwq->trustee);
                        wait_trustee_state(gcwq, TRUSTEE_DONE);
                }
 
-               /* clear ROGUE from all workers */
-               list_for_each_entry(worker, &gcwq->idle_list, entry)
-                       worker->flags &= ~WORKER_ROGUE;
-
-               for_each_busy_worker(worker, i, pos, gcwq)
-                       worker->flags &= ~WORKER_ROGUE;
+               /*
+                * Trustee is done and there might be no worker left.
+                * Put the first_idle in and request a real manager to
+                * take a look.
+                */
+               spin_unlock_irq(&gcwq->lock);
+               kthread_bind(gcwq->first_idle->task, cpu);
+               spin_lock_irq(&gcwq->lock);
+               gcwq->flags |= GCWQ_MANAGE_WORKERS;
+               start_worker(gcwq->first_idle);
+               gcwq->first_idle = NULL;
                break;
        }
 
@@ -2397,7 +3338,6 @@ EXPORT_SYMBOL_GPL(work_on_cpu);
  */
 void freeze_workqueues_begin(void)
 {
-       struct workqueue_struct *wq;
        unsigned int cpu;
 
        spin_lock(&workqueue_lock);
@@ -2405,8 +3345,9 @@ void freeze_workqueues_begin(void)
        BUG_ON(workqueue_freezing);
        workqueue_freezing = true;
 
-       for_each_possible_cpu(cpu) {
+       for_each_gcwq_cpu(cpu) {
                struct global_cwq *gcwq = get_gcwq(cpu);
+               struct workqueue_struct *wq;
 
                spin_lock_irq(&gcwq->lock);
 
@@ -2416,7 +3357,7 @@ void freeze_workqueues_begin(void)
                list_for_each_entry(wq, &workqueues, list) {
                        struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
 
-                       if (wq->flags & WQ_FREEZEABLE)
+                       if (cwq && wq->flags & WQ_FREEZEABLE)
                                cwq->max_active = 0;
                }
 
@@ -2441,7 +3382,6 @@ void freeze_workqueues_begin(void)
  */
 bool freeze_workqueues_busy(void)
 {
-       struct workqueue_struct *wq;
        unsigned int cpu;
        bool busy = false;
 
@@ -2449,7 +3389,8 @@ bool freeze_workqueues_busy(void)
 
        BUG_ON(!workqueue_freezing);
 
-       for_each_possible_cpu(cpu) {
+       for_each_gcwq_cpu(cpu) {
+               struct workqueue_struct *wq;
                /*
                 * nr_active is monotonically decreasing.  It's safe
                 * to peek without lock.
@@ -2457,7 +3398,7 @@ bool freeze_workqueues_busy(void)
                list_for_each_entry(wq, &workqueues, list) {
                        struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
 
-                       if (!(wq->flags & WQ_FREEZEABLE))
+                       if (!cwq || !(wq->flags & WQ_FREEZEABLE))
                                continue;
 
                        BUG_ON(cwq->nr_active < 0);
@@ -2483,7 +3424,6 @@ out_unlock:
  */
 void thaw_workqueues(void)
 {
-       struct workqueue_struct *wq;
        unsigned int cpu;
 
        spin_lock(&workqueue_lock);
@@ -2491,8 +3431,9 @@ void thaw_workqueues(void)
        if (!workqueue_freezing)
                goto out_unlock;
 
-       for_each_possible_cpu(cpu) {
+       for_each_gcwq_cpu(cpu) {
                struct global_cwq *gcwq = get_gcwq(cpu);
+               struct workqueue_struct *wq;
 
                spin_lock_irq(&gcwq->lock);
 
@@ -2502,7 +3443,7 @@ void thaw_workqueues(void)
                list_for_each_entry(wq, &workqueues, list) {
                        struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
 
-                       if (!(wq->flags & WQ_FREEZEABLE))
+                       if (!cwq || !(wq->flags & WQ_FREEZEABLE))
                                continue;
 
                        /* restore max_active and repopulate worklist */
@@ -2511,15 +3452,10 @@ void thaw_workqueues(void)
                        while (!list_empty(&cwq->delayed_works) &&
                               cwq->nr_active < cwq->max_active)
                                cwq_activate_first_delayed(cwq);
-
-                       /* perform delayed unbind from single cpu if empty */
-                       if (wq->single_cpu == gcwq->cpu &&
-                           !cwq->nr_active && list_empty(&cwq->delayed_works))
-                               cwq_unbind_single_cpu(cwq);
-
-                       wake_up_process(cwq->worker->task);
                }
 
+               wake_up_worker(gcwq);
+
                spin_unlock_irq(&gcwq->lock);
        }
 
@@ -2540,28 +3476,53 @@ void __init init_workqueues(void)
         * sure cpu number won't overflow into kernel pointer area so
         * that they can be distinguished.
         */
-       BUILD_BUG_ON(NR_CPUS << WORK_STRUCT_FLAG_BITS >= PAGE_OFFSET);
+       BUILD_BUG_ON(WORK_CPU_LAST << WORK_STRUCT_FLAG_BITS >= PAGE_OFFSET);
 
        hotcpu_notifier(workqueue_cpu_callback, CPU_PRI_WORKQUEUE);
 
        /* initialize gcwqs */
-       for_each_possible_cpu(cpu) {
+       for_each_gcwq_cpu(cpu) {
                struct global_cwq *gcwq = get_gcwq(cpu);
 
                spin_lock_init(&gcwq->lock);
                INIT_LIST_HEAD(&gcwq->worklist);
                gcwq->cpu = cpu;
+               if (cpu == WORK_CPU_UNBOUND)
+                       gcwq->flags |= GCWQ_DISASSOCIATED;
 
                INIT_LIST_HEAD(&gcwq->idle_list);
                for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)
                        INIT_HLIST_HEAD(&gcwq->busy_hash[i]);
 
+               init_timer_deferrable(&gcwq->idle_timer);
+               gcwq->idle_timer.function = idle_worker_timeout;
+               gcwq->idle_timer.data = (unsigned long)gcwq;
+
+               setup_timer(&gcwq->mayday_timer, gcwq_mayday_timeout,
+                           (unsigned long)gcwq);
+
                ida_init(&gcwq->worker_ida);
 
                gcwq->trustee_state = TRUSTEE_DONE;
                init_waitqueue_head(&gcwq->trustee_wait);
        }
 
-       keventd_wq = create_workqueue("events");
-       BUG_ON(!keventd_wq);
+       /* create the initial worker */
+       for_each_online_gcwq_cpu(cpu) {
+               struct global_cwq *gcwq = get_gcwq(cpu);
+               struct worker *worker;
+
+               worker = create_worker(gcwq, true);
+               BUG_ON(!worker);
+               spin_lock_irq(&gcwq->lock);
+               start_worker(worker);
+               spin_unlock_irq(&gcwq->lock);
+       }
+
+       system_wq = alloc_workqueue("events", 0, 0);
+       system_long_wq = alloc_workqueue("events_long", 0, 0);
+       system_nrt_wq = alloc_workqueue("events_nrt", WQ_NON_REENTRANT, 0);
+       system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
+                                           WQ_UNBOUND_MAX_ACTIVE);
+       BUG_ON(!system_wq || !system_long_wq || !system_nrt_wq);
 }
This page took 0.05158 seconds and 5 git commands to generate.