#! /bin/sh
#
# Laptop mode tools module to handle CPU Hot Plugging
#


# Determine number cpu cores on machine
max_available_cpus() {
	CPU=/sys/devices/system/cpu/present
	if [ -f $CPU ]; then
		max_cpu=$(cat $CPU | cut -d '-' -f2)
		max_cpu=$(expr $max_cpu + 1)
		echo $max_cpu
	else
		echo -1
	fi
}

# Get a list of cpus to control from a number of cpus that user wants to
# disable.
get_cpus_from_number() {
	counter=0
	cpu_list=

	for cpu in /sys/devices/system/cpu/cpu[0-9]* ; do
		if [ $counter -le $1 ]; then
			counter=$(expr $counter + 1)
		else
			break
		fi

		cpu_list="$cpu_list $cpu"
	done
}

# Get a list of cpus from a list of cpu ids. Where each id is of the form
# cpu<integer>.
get_cpus_from_ids() {
	cpu_list=

	for cpu_id in $1 ; do
		cpu_path="/sys/devices/system/cpu/$cpu_id"
		if [ -d "$cpu_path" ] ; then
			cpu_list="$cpu_list $cpu_path"
		fi
	done
}

# Get a list of cpus to control from DISABLE_AVAILABLE_CPU value.
get_cpus_to_control() {
	num_cpu=`max_available_cpus`

	case "$1" in
		"quarter")
			get_cpus_from_number $(echo $num_cpu*1/4 | bc)
			;;
		"half")
			get_cpus_from_number $(echo $num_cpu*1/2 | bc)
			;;
		"3quarter")
			get_cpus_from_number $(echo $num_cpu*3/4 | bc)
			;;
		[0-9]*)
			get_cpus_from_number $1
			;;
		cpu*)
			get_cpus_from_ids "$1"
			;;
	esac
}


if [ x$CONTROL_CPU_HOTPLUG = x1 ] || [ x$ENABLE_AUTO_MODULES = x1 -a x$CONTROL_CPU_HOTPLUG = xauto ]; then
	if [ $ON_AC -eq 1 ] ; then
		if [ "$ACTIVATE" -eq 1 ] ; then
			ECHO_VAL="$LM_AC_CPU_HOTPLUG"
		else
			ECHO_VAL="$NOLM_AC_CPU_HOTPLUG"
		fi
	else
		ECHO_VAL="$BATT_CPU_HOTPLUG"
	fi

	# To disable the CPU, write 0. So flip it here.
	if [ x$ECHO_VAL = x1 ]; then
		CPU_VAL=0
	else
		CPU_VAL=1
	fi

	get_cpus_to_control "$DISABLE_AVAILABLE_CPU"

	for THISCPU in $cpu_list ; do
		if [ -e "$THISCPU/online" ]; then
			log "VERBOSE" "Bringing CPU $THISCPU to $ECHO_VAL"
			echo $CPU_VAL > $THISCPU/online
		else
			log "VERBOSE" "CPU $THISCPU cannot be hot plugged"
		fi
	done
fi
