slow-work.c 27.1 KB
Newer Older
1 2 3 4 5 6 7 8 9
/* Worker thread pool for slow items, such as filesystem lookups or mkdirs
 *
 * Copyright (C) 2008 Red Hat, Inc. All Rights Reserved.
 * Written by David Howells (dhowells@redhat.com)
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public Licence
 * as published by the Free Software Foundation; either version
 * 2 of the Licence, or (at your option) any later version.
10 11
 *
 * See Documentation/slow-work.txt
12 13 14 15 16 17 18 19
 */

#include <linux/module.h>
#include <linux/slow-work.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <linux/wait.h>

20 21 22 23 24
#define SLOW_WORK_CULL_TIMEOUT (5 * HZ)	/* cull threads 5s after running out of
					 * things to do */
#define SLOW_WORK_OOM_TIMEOUT (5 * HZ)	/* can't start new threads for 5s after
					 * OOM */

25 26
#define SLOW_WORK_THREAD_LIMIT	255	/* abs maximum number of slow-work threads */

27 28 29
static void slow_work_cull_timeout(unsigned long);
static void slow_work_oom_timeout(unsigned long);

30
#ifdef CONFIG_SYSCTL
31
static int slow_work_min_threads_sysctl(struct ctl_table *, int,
32 33
					void __user *, size_t *, loff_t *);

34
static int slow_work_max_threads_sysctl(struct ctl_table *, int ,
35 36 37
					void __user *, size_t *, loff_t *);
#endif

38 39 40 41 42 43 44 45 46 47
/*
 * The pool of threads has at least min threads in it as long as someone is
 * using the facility, and may have as many as max.
 *
 * A portion of the pool may be processing very slow operations.
 */
static unsigned slow_work_min_threads = 2;
static unsigned slow_work_max_threads = 4;
static unsigned vslow_work_proportion = 50; /* % of threads that may process
					     * very slow work */
48 49 50

#ifdef CONFIG_SYSCTL
static const int slow_work_min_min_threads = 2;
51
static int slow_work_max_max_threads = SLOW_WORK_THREAD_LIMIT;
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
static const int slow_work_min_vslow = 1;
static const int slow_work_max_vslow = 99;

ctl_table slow_work_sysctls[] = {
	{
		.ctl_name	= CTL_UNNUMBERED,
		.procname	= "min-threads",
		.data		= &slow_work_min_threads,
		.maxlen		= sizeof(unsigned),
		.mode		= 0644,
		.proc_handler	= slow_work_min_threads_sysctl,
		.extra1		= (void *) &slow_work_min_min_threads,
		.extra2		= &slow_work_max_threads,
	},
	{
		.ctl_name	= CTL_UNNUMBERED,
		.procname	= "max-threads",
		.data		= &slow_work_max_threads,
		.maxlen		= sizeof(unsigned),
		.mode		= 0644,
		.proc_handler	= slow_work_max_threads_sysctl,
		.extra1		= &slow_work_min_threads,
		.extra2		= (void *) &slow_work_max_max_threads,
	},
	{
		.ctl_name	= CTL_UNNUMBERED,
		.procname	= "vslow-percentage",
		.data		= &vslow_work_proportion,
		.maxlen		= sizeof(unsigned),
		.mode		= 0644,
		.proc_handler	= &proc_dointvec_minmax,
		.extra1		= (void *) &slow_work_min_vslow,
		.extra2		= (void *) &slow_work_max_vslow,
	},
	{ .ctl_name = 0 }
};
#endif

/*
 * The active state of the thread pool
 */
93 94 95
static atomic_t slow_work_thread_count;
static atomic_t vslow_work_executing_count;

96 97 98 99 100 101
static bool slow_work_may_not_start_new_thread;
static bool slow_work_cull; /* cull a thread due to lack of activity */
static DEFINE_TIMER(slow_work_cull_timer, slow_work_cull_timeout, 0, 0);
static DEFINE_TIMER(slow_work_oom_timer, slow_work_oom_timeout, 0, 0);
static struct slow_work slow_work_new_thread; /* new thread starter */

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
/*
 * slow work ID allocation (use slow_work_queue_lock)
 */
static DECLARE_BITMAP(slow_work_ids, SLOW_WORK_THREAD_LIMIT);

/*
 * Unregistration tracking to prevent put_ref() from disappearing during module
 * unload
 */
#ifdef CONFIG_MODULES
static struct module *slow_work_thread_processing[SLOW_WORK_THREAD_LIMIT];
static struct module *slow_work_unreg_module;
static struct slow_work *slow_work_unreg_work_item;
static DECLARE_WAIT_QUEUE_HEAD(slow_work_unreg_wq);
static DEFINE_MUTEX(slow_work_unreg_sync_lock);
#endif

119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
/*
 * The queues of work items and the lock governing access to them.  These are
 * shared between all the CPUs.  It doesn't make sense to have per-CPU queues
 * as the number of threads bears no relation to the number of CPUs.
 *
 * There are two queues of work items: one for slow work items, and one for
 * very slow work items.
 */
static LIST_HEAD(slow_work_queue);
static LIST_HEAD(vslow_work_queue);
static DEFINE_SPINLOCK(slow_work_queue_lock);

/*
 * The thread controls.  A variable used to signal to the threads that they
 * should exit when the queue is empty, a waitqueue used by the threads to wait
 * for signals, and a completion set by the last thread to exit.
 */
static bool slow_work_threads_should_exit;
static DECLARE_WAIT_QUEUE_HEAD(slow_work_thread_wq);
static DECLARE_COMPLETION(slow_work_last_thread_exited);

/*
 * The number of users of the thread pool and its lock.  Whilst this is zero we
 * have no threads hanging around, and when this reaches zero, we wait for all
 * active or queued work items to complete and kill all the threads we do have.
 */
static int slow_work_user_count;
static DEFINE_MUTEX(slow_work_user_lock);

148 149 150 151 152 153 154 155 156 157 158 159 160 161
static inline int slow_work_get_ref(struct slow_work *work)
{
	if (work->ops->get_ref)
		return work->ops->get_ref(work);

	return 0;
}

static inline void slow_work_put_ref(struct slow_work *work)
{
	if (work->ops->put_ref)
		work->ops->put_ref(work);
}

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
/*
 * Calculate the maximum number of active threads in the pool that are
 * permitted to process very slow work items.
 *
 * The answer is rounded up to at least 1, but may not equal or exceed the
 * maximum number of the threads in the pool.  This means we always have at
 * least one thread that can process slow work items, and we always have at
 * least one thread that won't get tied up doing so.
 */
static unsigned slow_work_calc_vsmax(void)
{
	unsigned vsmax;

	vsmax = atomic_read(&slow_work_thread_count) * vslow_work_proportion;
	vsmax /= 100;
	vsmax = max(vsmax, 1U);
	return min(vsmax, slow_work_max_threads - 1);
}

/*
 * Attempt to execute stuff queued on a slow thread.  Return true if we managed
 * it, false if there was nothing to do.
 */
185
static bool slow_work_execute(int id)
186
{
187 188 189
#ifdef CONFIG_MODULES
	struct module *module;
#endif
190 191 192 193 194 195
	struct slow_work *work = NULL;
	unsigned vsmax;
	bool very_slow;

	vsmax = slow_work_calc_vsmax();

196 197 198 199 200 201 202 203
	/* see if we can schedule a new thread to be started if we're not
	 * keeping up with the work */
	if (!waitqueue_active(&slow_work_thread_wq) &&
	    (!list_empty(&slow_work_queue) || !list_empty(&vslow_work_queue)) &&
	    atomic_read(&slow_work_thread_count) < slow_work_max_threads &&
	    !slow_work_may_not_start_new_thread)
		slow_work_enqueue(&slow_work_new_thread);

204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
	/* find something to execute */
	spin_lock_irq(&slow_work_queue_lock);
	if (!list_empty(&vslow_work_queue) &&
	    atomic_read(&vslow_work_executing_count) < vsmax) {
		work = list_entry(vslow_work_queue.next,
				  struct slow_work, link);
		if (test_and_set_bit_lock(SLOW_WORK_EXECUTING, &work->flags))
			BUG();
		list_del_init(&work->link);
		atomic_inc(&vslow_work_executing_count);
		very_slow = true;
	} else if (!list_empty(&slow_work_queue)) {
		work = list_entry(slow_work_queue.next,
				  struct slow_work, link);
		if (test_and_set_bit_lock(SLOW_WORK_EXECUTING, &work->flags))
			BUG();
		list_del_init(&work->link);
		very_slow = false;
	} else {
		very_slow = false; /* avoid the compiler warning */
	}
225 226 227 228 229 230

#ifdef CONFIG_MODULES
	if (work)
		slow_work_thread_processing[id] = work->owner;
#endif

231 232 233 234 235 236 237 238
	spin_unlock_irq(&slow_work_queue_lock);

	if (!work)
		return false;

	if (!test_and_clear_bit(SLOW_WORK_PENDING, &work->flags))
		BUG();

239 240 241
	/* don't execute if the work is in the process of being cancelled */
	if (!test_bit(SLOW_WORK_CANCELLING, &work->flags))
		work->ops->execute(work);
242 243 244 245 246

	if (very_slow)
		atomic_dec(&vslow_work_executing_count);
	clear_bit_unlock(SLOW_WORK_EXECUTING, &work->flags);

247 248 249
	/* wake up anyone waiting for this work to be complete */
	wake_up_bit(&work->flags, SLOW_WORK_EXECUTING);

250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
	/* if someone tried to enqueue the item whilst we were executing it,
	 * then it'll be left unenqueued to avoid multiple threads trying to
	 * execute it simultaneously
	 *
	 * there is, however, a race between us testing the pending flag and
	 * getting the spinlock, and between the enqueuer setting the pending
	 * flag and getting the spinlock, so we use a deferral bit to tell us
	 * if the enqueuer got there first
	 */
	if (test_bit(SLOW_WORK_PENDING, &work->flags)) {
		spin_lock_irq(&slow_work_queue_lock);

		if (!test_bit(SLOW_WORK_EXECUTING, &work->flags) &&
		    test_and_clear_bit(SLOW_WORK_ENQ_DEFERRED, &work->flags))
			goto auto_requeue;

		spin_unlock_irq(&slow_work_queue_lock);
	}

269
	/* sort out the race between module unloading and put_ref() */
270
	slow_work_put_ref(work);
271 272 273 274 275 276 277 278 279 280

#ifdef CONFIG_MODULES
	module = slow_work_thread_processing[id];
	slow_work_thread_processing[id] = NULL;
	smp_mb();
	if (slow_work_unreg_work_item == work ||
	    slow_work_unreg_module == module)
		wake_up_all(&slow_work_unreg_wq);
#endif

281 282 283 284 285 286 287 288 289 290 291 292
	return true;

auto_requeue:
	/* we must complete the enqueue operation
	 * - we transfer our ref on the item back to the appropriate queue
	 * - don't wake another thread up as we're awake already
	 */
	if (test_bit(SLOW_WORK_VERY_SLOW, &work->flags))
		list_add_tail(&work->link, &vslow_work_queue);
	else
		list_add_tail(&work->link, &slow_work_queue);
	spin_unlock_irq(&slow_work_queue_lock);
293
	slow_work_thread_processing[id] = NULL;
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
	return true;
}

/**
 * slow_work_enqueue - Schedule a slow work item for processing
 * @work: The work item to queue
 *
 * Schedule a slow work item for processing.  If the item is already undergoing
 * execution, this guarantees not to re-enter the execution routine until the
 * first execution finishes.
 *
 * The item is pinned by this function as it retains a reference to it, managed
 * through the item operations.  The item is unpinned once it has been
 * executed.
 *
 * An item may hog the thread that is running it for a relatively large amount
 * of time, sufficient, for example, to perform several lookup, mkdir, create
 * and setxattr operations.  It may sleep on I/O and may sleep to obtain locks.
 *
 * Conversely, if a number of items are awaiting processing, it may take some
 * time before any given item is given attention.  The number of threads in the
 * pool may be increased to deal with demand, but only up to a limit.
 *
 * If SLOW_WORK_VERY_SLOW is set on the work item, then it will be placed in
 * the very slow queue, from which only a portion of the threads will be
 * allowed to pick items to execute.  This ensures that very slow items won't
 * overly block ones that are just ordinarily slow.
 *
322 323
 * Returns 0 if successful, -EAGAIN if not (or -ECANCELED if cancelled work is
 * attempted queued)
324 325 326 327
 */
int slow_work_enqueue(struct slow_work *work)
{
	unsigned long flags;
328 329 330 331
	int ret;

	if (test_bit(SLOW_WORK_CANCELLING, &work->flags))
		return -ECANCELED;
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347

	BUG_ON(slow_work_user_count <= 0);
	BUG_ON(!work);
	BUG_ON(!work->ops);

	/* when honouring an enqueue request, we only promise that we will run
	 * the work function in the future; we do not promise to run it once
	 * per enqueue request
	 *
	 * we use the PENDING bit to merge together repeat requests without
	 * having to disable IRQs and take the spinlock, whilst still
	 * maintaining our promise
	 */
	if (!test_and_set_bit_lock(SLOW_WORK_PENDING, &work->flags)) {
		spin_lock_irqsave(&slow_work_queue_lock, flags);

348 349 350
		if (unlikely(test_bit(SLOW_WORK_CANCELLING, &work->flags)))
			goto cancelled;

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
		/* we promise that we will not attempt to execute the work
		 * function in more than one thread simultaneously
		 *
		 * this, however, leaves us with a problem if we're asked to
		 * enqueue the work whilst someone is executing the work
		 * function as simply queueing the work immediately means that
		 * another thread may try executing it whilst it is already
		 * under execution
		 *
		 * to deal with this, we set the ENQ_DEFERRED bit instead of
		 * enqueueing, and the thread currently executing the work
		 * function will enqueue the work item when the work function
		 * returns and it has cleared the EXECUTING bit
		 */
		if (test_bit(SLOW_WORK_EXECUTING, &work->flags)) {
			set_bit(SLOW_WORK_ENQ_DEFERRED, &work->flags);
		} else {
368 369 370
			ret = slow_work_get_ref(work);
			if (ret < 0)
				goto failed;
371 372 373 374 375 376 377 378 379 380 381
			if (test_bit(SLOW_WORK_VERY_SLOW, &work->flags))
				list_add_tail(&work->link, &vslow_work_queue);
			else
				list_add_tail(&work->link, &slow_work_queue);
			wake_up(&slow_work_thread_wq);
		}

		spin_unlock_irqrestore(&slow_work_queue_lock, flags);
	}
	return 0;

382 383 384
cancelled:
	ret = -ECANCELED;
failed:
385
	spin_unlock_irqrestore(&slow_work_queue_lock, flags);
386
	return ret;
387 388 389
}
EXPORT_SYMBOL(slow_work_enqueue);

390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
static int slow_work_wait(void *word)
{
	schedule();
	return 0;
}

/**
 * slow_work_cancel - Cancel a slow work item
 * @work: The work item to cancel
 *
 * This function will cancel a previously enqueued work item. If we cannot
 * cancel the work item, it is guarenteed to have run when this function
 * returns.
 */
void slow_work_cancel(struct slow_work *work)
{
	bool wait = true, put = false;

	set_bit(SLOW_WORK_CANCELLING, &work->flags);
409 410 411 412 413 414 415 416 417 418 419 420 421 422
	smp_mb();

	/* if the work item is a delayed work item with an active timer, we
	 * need to wait for the timer to finish _before_ getting the spinlock,
	 * lest we deadlock against the timer routine
	 *
	 * the timer routine will leave DELAYED set if it notices the
	 * CANCELLING flag in time
	 */
	if (test_bit(SLOW_WORK_DELAYED, &work->flags)) {
		struct delayed_slow_work *dwork =
			container_of(work, struct delayed_slow_work, work);
		del_timer_sync(&dwork->timer);
	}
423 424 425

	spin_lock_irq(&slow_work_queue_lock);

426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
	if (test_bit(SLOW_WORK_DELAYED, &work->flags)) {
		/* the timer routine aborted or never happened, so we are left
		 * holding the timer's reference on the item and should just
		 * drop the pending flag and wait for any ongoing execution to
		 * finish */
		struct delayed_slow_work *dwork =
			container_of(work, struct delayed_slow_work, work);

		BUG_ON(timer_pending(&dwork->timer));
		BUG_ON(!list_empty(&work->link));

		clear_bit(SLOW_WORK_DELAYED, &work->flags);
		put = true;
		clear_bit(SLOW_WORK_PENDING, &work->flags);

	} else if (test_bit(SLOW_WORK_PENDING, &work->flags) &&
		   !list_empty(&work->link)) {
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
		/* the link in the pending queue holds a reference on the item
		 * that we will need to release */
		list_del_init(&work->link);
		wait = false;
		put = true;
		clear_bit(SLOW_WORK_PENDING, &work->flags);

	} else if (test_and_clear_bit(SLOW_WORK_ENQ_DEFERRED, &work->flags)) {
		/* the executor is holding our only reference on the item, so
		 * we merely need to wait for it to finish executing */
		clear_bit(SLOW_WORK_PENDING, &work->flags);
	}

	spin_unlock_irq(&slow_work_queue_lock);

	/* the EXECUTING flag is set by the executor whilst the spinlock is set
	 * and before the item is dequeued - so assuming the above doesn't
	 * actually dequeue it, simply waiting for the EXECUTING flag to be
	 * released here should be sufficient */
	if (wait)
		wait_on_bit(&work->flags, SLOW_WORK_EXECUTING, slow_work_wait,
			    TASK_UNINTERRUPTIBLE);

	clear_bit(SLOW_WORK_CANCELLING, &work->flags);
	if (put)
		slow_work_put_ref(work);
}
EXPORT_SYMBOL(slow_work_cancel);

472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
/*
 * Handle expiry of the delay timer, indicating that a delayed slow work item
 * should now be queued if not cancelled
 */
static void delayed_slow_work_timer(unsigned long data)
{
	struct slow_work *work = (struct slow_work *) data;
	unsigned long flags;
	bool queued = false, put = false;

	spin_lock_irqsave(&slow_work_queue_lock, flags);
	if (likely(!test_bit(SLOW_WORK_CANCELLING, &work->flags))) {
		clear_bit(SLOW_WORK_DELAYED, &work->flags);

		if (test_bit(SLOW_WORK_EXECUTING, &work->flags)) {
			/* we discard the reference the timer was holding in
			 * favour of the one the executor holds */
			set_bit(SLOW_WORK_ENQ_DEFERRED, &work->flags);
			put = true;
		} else {
			if (test_bit(SLOW_WORK_VERY_SLOW, &work->flags))
				list_add_tail(&work->link, &vslow_work_queue);
			else
				list_add_tail(&work->link, &slow_work_queue);
			queued = true;
		}
	}

	spin_unlock_irqrestore(&slow_work_queue_lock, flags);
	if (put)
		slow_work_put_ref(work);
	if (queued)
		wake_up(&slow_work_thread_wq);
}

/**
 * delayed_slow_work_enqueue - Schedule a delayed slow work item for processing
 * @dwork: The delayed work item to queue
 * @delay: When to start executing the work, in jiffies from now
 *
 * This is similar to slow_work_enqueue(), but it adds a delay before the work
 * is actually queued for processing.
 *
 * The item can have delayed processing requested on it whilst it is being
 * executed.  The delay will begin immediately, and if it expires before the
 * item finishes executing, the item will be placed back on the queue when it
 * has done executing.
 */
int delayed_slow_work_enqueue(struct delayed_slow_work *dwork,
			      unsigned long delay)
{
	struct slow_work *work = &dwork->work;
	unsigned long flags;
	int ret;

	if (delay == 0)
		return slow_work_enqueue(&dwork->work);

	BUG_ON(slow_work_user_count <= 0);
	BUG_ON(!work);
	BUG_ON(!work->ops);

	if (test_bit(SLOW_WORK_CANCELLING, &work->flags))
		return -ECANCELED;

	if (!test_and_set_bit_lock(SLOW_WORK_PENDING, &work->flags)) {
		spin_lock_irqsave(&slow_work_queue_lock, flags);

		if (test_bit(SLOW_WORK_CANCELLING, &work->flags))
			goto cancelled;

		/* the timer holds a reference whilst it is pending */
		ret = work->ops->get_ref(work);
		if (ret < 0)
			goto cant_get_ref;

		if (test_and_set_bit(SLOW_WORK_DELAYED, &work->flags))
			BUG();
		dwork->timer.expires = jiffies + delay;
		dwork->timer.data = (unsigned long) work;
		dwork->timer.function = delayed_slow_work_timer;
		add_timer(&dwork->timer);

		spin_unlock_irqrestore(&slow_work_queue_lock, flags);
	}

	return 0;

cancelled:
	ret = -ECANCELED;
cant_get_ref:
	spin_unlock_irqrestore(&slow_work_queue_lock, flags);
	return ret;
}
EXPORT_SYMBOL(delayed_slow_work_enqueue);

568 569 570 571 572 573 574 575 576
/*
 * Schedule a cull of the thread pool at some time in the near future
 */
static void slow_work_schedule_cull(void)
{
	mod_timer(&slow_work_cull_timer,
		  round_jiffies(jiffies + SLOW_WORK_CULL_TIMEOUT));
}

577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
/*
 * Worker thread culling algorithm
 */
static bool slow_work_cull_thread(void)
{
	unsigned long flags;
	bool do_cull = false;

	spin_lock_irqsave(&slow_work_queue_lock, flags);

	if (slow_work_cull) {
		slow_work_cull = false;

		if (list_empty(&slow_work_queue) &&
		    list_empty(&vslow_work_queue) &&
		    atomic_read(&slow_work_thread_count) >
		    slow_work_min_threads) {
594
			slow_work_schedule_cull();
595 596 597 598 599 600 601 602
			do_cull = true;
		}
	}

	spin_unlock_irqrestore(&slow_work_queue_lock, flags);
	return do_cull;
}

603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
/*
 * Determine if there is slow work available for dispatch
 */
static inline bool slow_work_available(int vsmax)
{
	return !list_empty(&slow_work_queue) ||
		(!list_empty(&vslow_work_queue) &&
		 atomic_read(&vslow_work_executing_count) < vsmax);
}

/*
 * Worker thread dispatcher
 */
static int slow_work_thread(void *_data)
{
618
	int vsmax, id;
619 620 621 622 623 624

	DEFINE_WAIT(wait);

	set_freezable();
	set_user_nice(current, -5);

625 626 627 628 629 630 631 632 633
	/* allocate ourselves an ID */
	spin_lock_irq(&slow_work_queue_lock);
	id = find_first_zero_bit(slow_work_ids, SLOW_WORK_THREAD_LIMIT);
	BUG_ON(id < 0 || id >= SLOW_WORK_THREAD_LIMIT);
	__set_bit(id, slow_work_ids);
	spin_unlock_irq(&slow_work_queue_lock);

	sprintf(current->comm, "kslowd%03u", id);

634 635 636 637 638
	for (;;) {
		vsmax = vslow_work_proportion;
		vsmax *= atomic_read(&slow_work_thread_count);
		vsmax /= 100;

639 640
		prepare_to_wait_exclusive(&slow_work_thread_wq, &wait,
					  TASK_INTERRUPTIBLE);
641 642
		if (!freezing(current) &&
		    !slow_work_threads_should_exit &&
643 644
		    !slow_work_available(vsmax) &&
		    !slow_work_cull)
645 646 647 648 649 650 651 652 653
			schedule();
		finish_wait(&slow_work_thread_wq, &wait);

		try_to_freeze();

		vsmax = vslow_work_proportion;
		vsmax *= atomic_read(&slow_work_thread_count);
		vsmax /= 100;

654
		if (slow_work_available(vsmax) && slow_work_execute(id)) {
655
			cond_resched();
656 657 658 659
			if (list_empty(&slow_work_queue) &&
			    list_empty(&vslow_work_queue) &&
			    atomic_read(&slow_work_thread_count) >
			    slow_work_min_threads)
660
				slow_work_schedule_cull();
661 662 663 664 665
			continue;
		}

		if (slow_work_threads_should_exit)
			break;
666 667 668

		if (slow_work_cull && slow_work_cull_thread())
			break;
669 670
	}

671 672 673 674
	spin_lock_irq(&slow_work_queue_lock);
	__clear_bit(id, slow_work_ids);
	spin_unlock_irq(&slow_work_queue_lock);

675 676 677 678 679
	if (atomic_dec_and_test(&slow_work_thread_count))
		complete_and_exit(&slow_work_last_thread_exited, 0);
	return 0;
}

680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
/*
 * Handle thread cull timer expiration
 */
static void slow_work_cull_timeout(unsigned long data)
{
	slow_work_cull = true;
	wake_up(&slow_work_thread_wq);
}

/*
 * Start a new slow work thread
 */
static void slow_work_new_thread_execute(struct slow_work *work)
{
	struct task_struct *p;

	if (slow_work_threads_should_exit)
		return;

	if (atomic_read(&slow_work_thread_count) >= slow_work_max_threads)
		return;

	if (!mutex_trylock(&slow_work_user_lock))
		return;

	slow_work_may_not_start_new_thread = true;
	atomic_inc(&slow_work_thread_count);
	p = kthread_run(slow_work_thread, NULL, "kslowd");
	if (IS_ERR(p)) {
		printk(KERN_DEBUG "Slow work thread pool: OOM\n");
		if (atomic_dec_and_test(&slow_work_thread_count))
			BUG(); /* we're running on a slow work thread... */
		mod_timer(&slow_work_oom_timer,
713
			  round_jiffies(jiffies + SLOW_WORK_OOM_TIMEOUT));
714 715 716 717 718 719 720 721 722
	} else {
		/* ratelimit the starting of new threads */
		mod_timer(&slow_work_oom_timer, jiffies + 1);
	}

	mutex_unlock(&slow_work_user_lock);
}

static const struct slow_work_ops slow_work_new_thread_ops = {
723
	.owner		= THIS_MODULE,
724 725 726 727 728 729 730 731 732 733 734
	.execute	= slow_work_new_thread_execute,
};

/*
 * post-OOM new thread start suppression expiration
 */
static void slow_work_oom_timeout(unsigned long data)
{
	slow_work_may_not_start_new_thread = false;
}

735 736 737 738 739
#ifdef CONFIG_SYSCTL
/*
 * Handle adjustment of the minimum number of threads
 */
static int slow_work_min_threads_sysctl(struct ctl_table *table, int write,
740
					void __user *buffer,
741 742
					size_t *lenp, loff_t *ppos)
{
743
	int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
744 745 746 747 748 749 750 751 752 753 754 755
	int n;

	if (ret == 0) {
		mutex_lock(&slow_work_user_lock);
		if (slow_work_user_count > 0) {
			/* see if we need to start or stop threads */
			n = atomic_read(&slow_work_thread_count) -
				slow_work_min_threads;

			if (n < 0 && !slow_work_may_not_start_new_thread)
				slow_work_enqueue(&slow_work_new_thread);
			else if (n > 0)
756
				slow_work_schedule_cull();
757 758 759 760 761 762 763 764 765 766 767
		}
		mutex_unlock(&slow_work_user_lock);
	}

	return ret;
}

/*
 * Handle adjustment of the maximum number of threads
 */
static int slow_work_max_threads_sysctl(struct ctl_table *table, int write,
768
					void __user *buffer,
769 770
					size_t *lenp, loff_t *ppos)
{
771
	int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
772 773 774 775 776 777 778 779 780 781
	int n;

	if (ret == 0) {
		mutex_lock(&slow_work_user_lock);
		if (slow_work_user_count > 0) {
			/* see if we need to stop threads */
			n = slow_work_max_threads -
				atomic_read(&slow_work_thread_count);

			if (n < 0)
782
				slow_work_schedule_cull();
783 784 785 786 787 788 789 790
		}
		mutex_unlock(&slow_work_user_lock);
	}

	return ret;
}
#endif /* CONFIG_SYSCTL */

791 792
/**
 * slow_work_register_user - Register a user of the facility
793
 * @module: The module about to make use of the facility
794 795 796 797 798
 *
 * Register a user of the facility, starting up the initial threads if there
 * aren't any other users at this point.  This will return 0 if successful, or
 * an error if not.
 */
799
int slow_work_register_user(struct module *module)
800 801 802 803 804 805 806 807 808 809 810
{
	struct task_struct *p;
	int loop;

	mutex_lock(&slow_work_user_lock);

	if (slow_work_user_count == 0) {
		printk(KERN_NOTICE "Slow work thread pool: Starting up\n");
		init_completion(&slow_work_last_thread_exited);

		slow_work_threads_should_exit = false;
811 812 813 814
		slow_work_init(&slow_work_new_thread,
			       &slow_work_new_thread_ops);
		slow_work_may_not_start_new_thread = false;
		slow_work_cull = false;
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845

		/* start the minimum number of threads */
		for (loop = 0; loop < slow_work_min_threads; loop++) {
			atomic_inc(&slow_work_thread_count);
			p = kthread_run(slow_work_thread, NULL, "kslowd");
			if (IS_ERR(p))
				goto error;
		}
		printk(KERN_NOTICE "Slow work thread pool: Ready\n");
	}

	slow_work_user_count++;
	mutex_unlock(&slow_work_user_lock);
	return 0;

error:
	if (atomic_dec_and_test(&slow_work_thread_count))
		complete(&slow_work_last_thread_exited);
	if (loop > 0) {
		printk(KERN_ERR "Slow work thread pool:"
		       " Aborting startup on ENOMEM\n");
		slow_work_threads_should_exit = true;
		wake_up_all(&slow_work_thread_wq);
		wait_for_completion(&slow_work_last_thread_exited);
		printk(KERN_ERR "Slow work thread pool: Aborted\n");
	}
	mutex_unlock(&slow_work_user_lock);
	return PTR_ERR(p);
}
EXPORT_SYMBOL(slow_work_register_user);

846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
/*
 * wait for all outstanding items from the calling module to complete
 * - note that more items may be queued whilst we're waiting
 */
static void slow_work_wait_for_items(struct module *module)
{
	DECLARE_WAITQUEUE(myself, current);
	struct slow_work *work;
	int loop;

	mutex_lock(&slow_work_unreg_sync_lock);
	add_wait_queue(&slow_work_unreg_wq, &myself);

	for (;;) {
		spin_lock_irq(&slow_work_queue_lock);

		/* first of all, we wait for the last queued item in each list
		 * to be processed */
		list_for_each_entry_reverse(work, &vslow_work_queue, link) {
			if (work->owner == module) {
				set_current_state(TASK_UNINTERRUPTIBLE);
				slow_work_unreg_work_item = work;
				goto do_wait;
			}
		}
		list_for_each_entry_reverse(work, &slow_work_queue, link) {
			if (work->owner == module) {
				set_current_state(TASK_UNINTERRUPTIBLE);
				slow_work_unreg_work_item = work;
				goto do_wait;
			}
		}

		/* then we wait for the items being processed to finish */
		slow_work_unreg_module = module;
		smp_mb();
		for (loop = 0; loop < SLOW_WORK_THREAD_LIMIT; loop++) {
			if (slow_work_thread_processing[loop] == module)
				goto do_wait;
		}
		spin_unlock_irq(&slow_work_queue_lock);
		break; /* okay, we're done */

	do_wait:
		spin_unlock_irq(&slow_work_queue_lock);
		schedule();
		slow_work_unreg_work_item = NULL;
		slow_work_unreg_module = NULL;
	}

	remove_wait_queue(&slow_work_unreg_wq, &myself);
	mutex_unlock(&slow_work_unreg_sync_lock);
}

900 901
/**
 * slow_work_unregister_user - Unregister a user of the facility
902
 * @module: The module whose items should be cleared
903 904 905
 *
 * Unregister a user of the facility, killing all the threads if this was the
 * last one.
906 907 908
 *
 * This waits for all the work items belonging to the nominated module to go
 * away before proceeding.
909
 */
910
void slow_work_unregister_user(struct module *module)
911
{
912 913 914 915 916 917 918
	/* first of all, wait for all outstanding items from the calling module
	 * to complete */
	if (module)
		slow_work_wait_for_items(module);

	/* then we can actually go about shutting down the facility if need
	 * be */
919 920 921 922 923 924 925 926
	mutex_lock(&slow_work_user_lock);

	BUG_ON(slow_work_user_count <= 0);

	slow_work_user_count--;
	if (slow_work_user_count == 0) {
		printk(KERN_NOTICE "Slow work thread pool: Shutting down\n");
		slow_work_threads_should_exit = true;
927 928
		del_timer_sync(&slow_work_cull_timer);
		del_timer_sync(&slow_work_oom_timer);
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
		wake_up_all(&slow_work_thread_wq);
		wait_for_completion(&slow_work_last_thread_exited);
		printk(KERN_NOTICE "Slow work thread pool:"
		       " Shut down complete\n");
	}

	mutex_unlock(&slow_work_user_lock);
}
EXPORT_SYMBOL(slow_work_unregister_user);

/*
 * Initialise the slow work facility
 */
static int __init init_slow_work(void)
{
	unsigned nr_cpus = num_possible_cpus();

946
	if (slow_work_max_threads < nr_cpus)
947
		slow_work_max_threads = nr_cpus;
948 949 950 951
#ifdef CONFIG_SYSCTL
	if (slow_work_max_max_threads < nr_cpus * 2)
		slow_work_max_max_threads = nr_cpus * 2;
#endif
952 953 954 955
	return 0;
}

subsys_initcall(init_slow_work);