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