build_packages: add option to automatically switch cpu governors

The powersave governor can take quite a while to get up to speed
when building things, so add a tip for users to automatically set
it to performance during the life of the build.

BUG=chromium:1008932
TEST=`./build_packages --noautosetgov` issues powersave warning
TEST=`./build_packages --autosetgov` switches to performance & then back to powersave

Change-Id: Ia56c1cccff68debef9928ade9800ee64e0f7ae0e
Reviewed-on: https://chromium-review.googlesource.com/1841944
Tested-by: Mike Frysinger <vapier@chromium.org>
Commit-Ready: ChromeOS CL Exonerator Bot <chromiumos-cl-exonerator@appspot.gserviceaccount.com>
Legacy-Commit-Queue: Commit Bot <commit-bot@chromium.org>
Reviewed-by: Douglas Anderson <dianders@chromium.org>
diff --git a/build_packages b/build_packages
index e1e04d5..ed9e27b 100755
--- a/build_packages
+++ b/build_packages
@@ -32,6 +32,8 @@
   "Define the file that event logs will be written."
 DEFINE_boolean withrevdeps "${FLAGS_TRUE}" \
   "Calculate reverse dependencies on changed ebuilds."
+DEFINE_boolean autosetgov "${FLAGS_FALSE}" \
+  "Automatically set cpu governor to 'performance'."
 
 # The --board_root flag specifies the environment variables ROOT and PKGDIR.
 # This allows fetching and emerging of all packages to specified board_root.
@@ -117,6 +119,25 @@
 # Right now build_packages has to be run from scripts/
 . ${SRC_ROOT}/third_party/chromiumos-overlay/chromeos/config/chromeos_version.sh
 
+# On some systems, powersave can take a long time to ramp up.  Inform the user
+# so they can get faster builds.  https://crbug.com/1008932
+if grep -qs powersave \
+     /sys/devices/system/cpu/cpufreq/policy*/scaling_governor; then
+  # Make sure we can actually support "performance".
+  if grep -qs performance \
+      /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors; then
+    if [[ "${FLAGS_autosetgov}" -eq "${FLAGS_TRUE}" ]]; then
+      info "Temporarily setting cpu governor to 'performance'"
+      trap "sudo cpupower -c all frequency-set -g powersave >&/dev/null" EXIT
+      sudo cpupower -c all frequency-set -g performance >&/dev/null
+    else
+      warn "Current CPU governor set to 'powersave' which can slow down builds."
+      warn "Use --autosetgov to automatically (and temporarily) switch to" \
+        "'performance'."
+    fi
+  fi
+fi
+
 if [[ -z "${FLAGS_board}" ]]; then
   echo "Error: --board is required."
   exit 1