#!/usr/bin/ksh
#
# allslow - Slow down everything.
#	    Written using DTrace (Solaris 10 3/05).
#
# This program prevents greedy CPU-bound processes consuming so much CPU,
# by creating a DTrace program that is even greedier. This deliberatly
# wasts 90% of the CPU capacity by running the DTrace chill function. This
# causes your problematic CPU-bound apps to be throttled down to a tenth
# of their usual speed.
#
# 25-Nov-2005, ver 0.70
#
# USAGE: allslow	# hit Ctrl-C when finished
#
# WARNING: This program will deliberatly slow down every process.
#
# COPYRIGHT: Copyright (c) 2005 Brendan Gregg.
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2
#  of the License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software Foundation,
#  Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
#  (http://www.gnu.org/copyleft/gpl.html)
#
# NOTE: This script runs "adb -kw" to change dtrace_chill_max - a saftey
# feature that usually prevents us from slowing down the system so much.
# The script attempts to reset dtrace_chill_max back to normal after
# it has finished (should be a dtrace_chill_max/Z 0t500000000).
# 
# 25-Nov-2005	Brendan Gregg	Created this.

#
# Relax a DTrace saftey feature
#
print dtrace_chill_max/Z 0t930000000 | /usr/bin/adb -kw > /dev/null
if (( $? != 0 )); then
	print "ERROR1: Couldn't run adb. Are we root?"
	exit 1
fi

#
# Restore a DTrace saftey feature on exit
#
trap 'print dtrace_chill_max/Z 0t500000000 | /usr/bin/adb -kw > /dev/null' 0

#
# Run DTrace
#
/usr/sbin/dtrace -n '

 #pragma D option quiet
 #pragma D option destructive
 #pragma D option bufsize=4k

 int totalc;

 dtrace:::BEGIN
 {
	total = timestamp;
	printf("allslow running...\n");
 }

 profile:::profile-1000
 {
	this->start = timestamp;
	chill(900000);
	totalc += timestamp - this->start;
 }

 dtrace:::END
 {
	total = timestamp - total;
	printf("Wasted CPU time %d%%\n", (totalc * 100) / total);
 }
' 
