update_engine: Remove GPIO support.
We have not used GPIO since Jan 2013. This CL removes the GPIO handling code.
As a side effect, it also removes dependency on libudev.
BUG=chromium:221725
CQ-DEPEND=CL:199683
TEST=unittest
TEST=AU end2end test on real device from older version to a version that
has CL applied, then from that to another newer version (need not have
this CL applied).
Change-Id: I4352488ec360b44a44b137c40a3ae4ec35c6fe9d
Reviewed-on: https://chromium-review.googlesource.com/199626
Reviewed-by: Gilad Arnold <garnold@chromium.org>
Commit-Queue: Nam Nguyen <namnguyen@chromium.org>
Tested-by: Nam Nguyen <namnguyen@chromium.org>
diff --git a/99-gpio-dutflag.rules b/99-gpio-dutflag.rules
deleted file mode 100644
index f8b1d67..0000000
--- a/99-gpio-dutflag.rules
+++ /dev/null
@@ -1,37 +0,0 @@
-# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-#
-# These rules are in charge of exporting the dut_flaga and dut_flagb GPIOs on
-# different platforms. The GPIO IDs are registered as attributes, which can be
-# detected by client processes. This was motivated by update engine
-# auto-testing framework.
-
-# Identify the GPIO chip and set dut_flaga identifier on different platforms.
-# Unfortunately, Mario does not have a debug header, hence no GPIOs exposed.
-#
-# TODO(garnold) dutflaga/b export is disabled until we figure out what's
-# pulling the signal up on zgb and lumpy, and implement a safe fallback
-# machanism for such cases where autoupdate fails with the internal address
-# (http://code.google.com/p/chromium-os/issues/detail?id=27077)
-
-# - Alex:
-ATTR{[dmi/id]product_name}=="Alex", SUBSYSTEM=="gpio", KERNEL=="gpiochip192", \
- ENV{ID_GPIO_DUTFLAGA}="205", ENV{ID_GPIO_DUTFLAGB}="202"
-
-# - ZGB:
-#ATTR{[dmi/id]product_name}=="ZGB", SUBSYSTEM=="gpio", KERNEL=="gpiochip192", \
-# ENV{ID_GPIO_DUTFLAGA}="216", ENV{ID_GPIO_DUTFLAGB}="195"
-
-# - Lumpy, Stumpy:
-# TODO(garnold) stumpy's dutflag GPIOs are non-pull-up wired, which means that
-# they can read arbitrary values when not connected to Servo. Once fixed or
-# properly handled by the application, this should read "Lumpy|Stumpy".
-#ATTR{[dmi/id]product_name}=="Lumpy", SUBSYSTEM=="gpio", KERNEL=="gpiochip160", \
-# ENV{ID_GPIO_DUTFLAGA}="173", ENV{ID_GPIO_DUTFLAGB}="170"
-
-# Export dut_flaga/b and register their identifier as an attribute.
-ACTION=="add|change", SUBSYSTEM=="gpio", \
- ENV{ID_GPIO_DUTFLAGA}=="?*", ENV{ID_GPIO_DUTFLAGB}=="?*", \
- ATTR{subsystem/export}="%E{ID_GPIO_DUTFLAGA}", \
- ATTR{subsystem/export}="%E{ID_GPIO_DUTFLAGB}"
diff --git a/SConstruct b/SConstruct
index 2a88e1a..dd7f5dc 100644
--- a/SConstruct
+++ b/SConstruct
@@ -168,7 +168,6 @@
rootdev
rt
ssl
- udev
vboot_host
xml2""" % (BASE_VER, BASE_VER))
env['CPPPATH'] = ['..']
@@ -214,7 +213,6 @@
file_descriptor.cc
file_writer.cc
filesystem_copier_action.cc
- gpio_handler.cc
hardware.cc
http_common.cc
http_fetcher.cc
@@ -282,9 +280,6 @@
fake_system_state.cc
file_writer_unittest.cc
filesystem_copier_action_unittest.cc
- gpio_handler_unittest.cc
- gpio_mock_file_descriptor.cc
- gpio_mock_udev_interface.cc
http_fetcher_unittest.cc
hwid_override_unittest.cc
mock_http_fetcher.cc
diff --git a/fake_system_state.cc b/fake_system_state.cc
index 6777838..8291ba3 100644
--- a/fake_system_state.cc
+++ b/fake_system_state.cc
@@ -23,7 +23,6 @@
prefs_(&mock_prefs_),
powerwash_safe_prefs_(&mock_powerwash_safe_prefs_),
payload_state_(&mock_payload_state_),
- gpio_handler_(&mock_gpio_handler_),
update_attempter_(&mock_update_attempter_),
request_params_(&default_request_params_),
p2p_manager_(&mock_p2p_manager_),
diff --git a/fake_system_state.h b/fake_system_state.h
index 653849e..a7f4b6f 100644
--- a/fake_system_state.h
+++ b/fake_system_state.h
@@ -14,7 +14,6 @@
#include "update_engine/fake_hardware.h"
#include "update_engine/mock_connection_manager.h"
#include "update_engine/mock_dbus_wrapper.h"
-#include "update_engine/mock_gpio_handler.h"
#include "update_engine/mock_p2p_manager.h"
#include "update_engine/mock_payload_state.h"
#include "update_engine/policy_manager/fake_policy_manager.h"
@@ -71,10 +70,6 @@
return payload_state_;
}
- virtual inline GpioHandler* gpio_handler() override {
- return gpio_handler_;
- }
-
virtual inline UpdateAttempter* update_attempter() override {
return update_attempter_;
}
@@ -130,10 +125,6 @@
payload_state_ = payload_state ? payload_state : &mock_payload_state_;
}
- inline void set_gpio_handler(GpioHandler* gpio_handler) {
- gpio_handler_ = gpio_handler ? gpio_handler : &mock_gpio_handler_;
- }
-
inline void set_update_attempter(UpdateAttempter* update_attempter) {
update_attempter_ = (update_attempter ? update_attempter :
&mock_update_attempter_);
@@ -197,11 +188,6 @@
return &mock_payload_state_;
}
- inline testing::NiceMock<MockGpioHandler>* mock_gpio_handler() {
- CHECK(gpio_handler_ == &mock_gpio_handler_);
- return &mock_gpio_handler_;
- }
-
inline testing::NiceMock<UpdateAttempterMock>* mock_update_attempter() {
CHECK(update_attempter_ == &mock_update_attempter_);
return &mock_update_attempter_;
@@ -231,7 +217,6 @@
testing::NiceMock<PrefsMock> mock_prefs_;
testing::NiceMock<PrefsMock> mock_powerwash_safe_prefs_;
testing::NiceMock<MockPayloadState> mock_payload_state_;
- testing::NiceMock<MockGpioHandler> mock_gpio_handler_;
testing::NiceMock<UpdateAttempterMock> mock_update_attempter_;
OmahaRequestParams default_request_params_;
testing::NiceMock<MockP2PManager> mock_p2p_manager_;
@@ -246,7 +231,6 @@
PrefsInterface* prefs_;
PrefsInterface* powerwash_safe_prefs_;
PayloadStateInterface* payload_state_;
- GpioHandler* gpio_handler_;
UpdateAttempter* update_attempter_;
OmahaRequestParams* request_params_;
P2PManager* p2p_manager_;
diff --git a/gpio_handler.cc b/gpio_handler.cc
deleted file mode 100644
index 7495ed9..0000000
--- a/gpio_handler.cc
+++ /dev/null
@@ -1,592 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "update_engine/gpio_handler.h"
-
-#include <base/memory/scoped_ptr.h>
-#include <base/strings/string_util.h>
-#include <base/strings/stringprintf.h>
-#include <base/time/time.h>
-#include <glib.h>
-
-#include "update_engine/file_descriptor.h"
-
-using base::Time;
-using base::TimeDelta;
-using std::string;
-
-using namespace chromeos_update_engine;
-
-namespace chromeos_update_engine {
-
-const char* StandardGpioHandler::gpio_dirs_[kGpioDirMax] = {
- "in", // kGpioDirIn
- "out", // kGpioDirOut
-};
-
-const char* StandardGpioHandler::gpio_vals_[kGpioValMax] = {
- "1", // kGpioValUp
- "0", // kGpioValDown
-};
-
-const StandardGpioHandler::GpioDef
-StandardGpioHandler::gpio_defs_[kGpioIdMax] = {
- { "dutflaga", "ID_GPIO_DUTFLAGA" }, // kGpioIdDutflaga
- { "dutflagb", "ID_GPIO_DUTFLAGB" }, // kGpioIdDutflagb
-};
-
-unsigned StandardGpioHandler::num_instances_ = 0;
-
-
-StandardGpioHandler::StandardGpioHandler(UdevInterface* udev_iface,
- FileDescriptor* fd,
- bool is_defer_discovery,
- bool is_cache_test_mode)
- : udev_iface_(udev_iface),
- fd_(fd),
- is_cache_test_mode_(is_cache_test_mode),
- is_discovery_attempted_(false),
- is_discovery_successful_(false) {
- CHECK(udev_iface && fd);
-
- // Ensure there's only one instance of this class.
- CHECK_EQ(num_instances_, static_cast<unsigned>(0));
- num_instances_++;
-
- // Reset test signal flags.
- ResetTestModeSignalingFlags();
-
- // If GPIO discovery not deferred, do it.
- if (!is_defer_discovery)
- DiscoverGpios();
-}
-
-StandardGpioHandler::~StandardGpioHandler() {
- num_instances_--;
-}
-
-bool StandardGpioHandler::IsTestModeSignaled() {
- bool is_returning_cached = false; // for logging purposes
-
- // Attempt GPIO discovery first.
- if (DiscoverGpios()) {
- // Force a check if so requested.
- if (!is_cache_test_mode_)
- ResetTestModeSignalingFlags();
-
- is_returning_cached = !is_first_check_; // for logging purposes
- if (is_first_check_) {
- is_first_check_ = false;
- DoTestModeSignalingProtocol();
- }
- }
-
- LOG(INFO) << "result: " << (is_test_mode_ ? "test" : "normal") << " mode"
- << (is_returning_cached ? " (cached)" : "")
- << (is_handshake_completed_ ? "" : " (default)");
- return is_test_mode_;
-}
-
-
-bool StandardGpioHandler::GpioChipUdevEnumHelper::SetupEnumFilters(
- udev_enumerate* udev_enum) {
- CHECK(udev_enum);
-
- return !(gpio_handler_->udev_iface_->EnumerateAddMatchSubsystem(
- udev_enum, "gpio") ||
- gpio_handler_->udev_iface_->EnumerateAddMatchSysname(
- udev_enum, "gpiochip*"));
-}
-
-bool StandardGpioHandler::GpioChipUdevEnumHelper::ProcessDev(udev_device* dev) {
- CHECK(dev);
-
- // Ensure we did not encounter more than one chip.
- if (num_gpio_chips_++) {
- LOG(ERROR) << "enumerated multiple GPIO chips";
- return false;
- }
-
- // Obtain GPIO descriptors.
- for (int id = 0; id < kGpioIdMax; id++) {
- const GpioDef* gpio_def = &gpio_defs_[id];
- const char* descriptor =
- gpio_handler_->udev_iface_->DeviceGetPropertyValue(
- dev, gpio_def->udev_property);
- if (!descriptor) {
- LOG(ERROR) << "could not obtain " << gpio_def->name
- << " descriptor using property " << gpio_def->udev_property;
- return false;
- }
- gpio_handler_->gpios_[id].descriptor = descriptor;
- }
-
- return true;
-}
-
-bool StandardGpioHandler::GpioChipUdevEnumHelper::Finalize() {
- if (num_gpio_chips_ != 1) {
- LOG(ERROR) << "could not enumerate a GPIO chip";
- return false;
- }
- return true;
-}
-
-bool StandardGpioHandler::GpioUdevEnumHelper::SetupEnumFilters(
- udev_enumerate* udev_enum) {
- CHECK(udev_enum);
- const string gpio_pattern =
- string("*").append(gpio_handler_->gpios_[id_].descriptor);
- return !(
- gpio_handler_->udev_iface_->EnumerateAddMatchSubsystem(
- udev_enum, "gpio") ||
- gpio_handler_->udev_iface_->EnumerateAddMatchSysname(
- udev_enum, gpio_pattern.c_str()));
-}
-
-bool StandardGpioHandler::GpioUdevEnumHelper::ProcessDev(udev_device* dev) {
- CHECK(dev);
-
- // Ensure we did not encounter more than one GPIO device.
- if (num_gpios_++) {
- LOG(ERROR) << "enumerated multiple GPIO devices for a given descriptor";
- return false;
- }
-
- // Obtain GPIO device sysfs path.
- const char* dev_path = gpio_handler_->udev_iface_->DeviceGetSyspath(dev);
- if (!dev_path) {
- LOG(ERROR) << "failed to obtain device syspath for GPIO "
- << gpio_defs_[id_].name;
- return false;
- }
- gpio_handler_->gpios_[id_].dev_path = dev_path;
-
- LOG(INFO) << "obtained device syspath: " << gpio_defs_[id_].name << " -> "
- << gpio_handler_->gpios_[id_].dev_path;
- return true;
-}
-
-bool StandardGpioHandler::GpioUdevEnumHelper::Finalize() {
- if (num_gpios_ != 1) {
- LOG(ERROR) << "could not enumerate GPIO device " << gpio_defs_[id_].name;
- return false;
- }
- return true;
-}
-
-StandardGpioHandler::GpioDirResetter::GpioDirResetter(
- StandardGpioHandler* handler, GpioId id, GpioDir dir) :
- do_reset_(false), handler_(handler), id_(id), dir_(dir) {
- CHECK(handler);
- CHECK_GE(id, 0);
- CHECK_LT(id, kGpioIdMax);
- CHECK_GE(dir, 0);
- CHECK_LT(dir, kGpioDirMax);
-}
-
-StandardGpioHandler::GpioDirResetter::~GpioDirResetter() {
- if (do_reset_ && !handler_->SetGpioDirection(id_, dir_)) {
- LOG(WARNING) << "failed to reset direction of " << gpio_defs_[id_].name
- << " to " << gpio_dirs_[dir_];
- }
-}
-
-
-bool StandardGpioHandler::InitUdevEnum(struct udev* udev,
- UdevEnumHelper* enum_helper) {
- // Obtain a udev enumerate object.
- struct udev_enumerate* udev_enum;
- if (!(udev_enum = udev_iface_->EnumerateNew(udev))) {
- LOG(ERROR) << "failed to obtain udev enumerate context";
- return false;
- }
-
- // Assign enumerate object to closer.
- scoped_ptr<UdevInterface::UdevEnumerateCloser>
- udev_enum_closer(udev_iface_->NewUdevEnumerateCloser(&udev_enum));
-
- // Setup enumeration filters.
- if (!enum_helper->SetupEnumFilters(udev_enum)) {
- LOG(ERROR) << "failed to setup udev enumerate filters";
- return false;
- }
-
- // Scan for matching devices.
- if (udev_iface_->EnumerateScanDevices(udev_enum)) {
- LOG(ERROR) << "udev enumerate scan failed";
- return false;
- }
-
- // Iterate over matching devices.
- struct udev_list_entry* list_entry;
- for (list_entry = udev_iface_->EnumerateGetListEntry(udev_enum);
- list_entry; list_entry = udev_iface_->ListEntryGetNext(list_entry)) {
- // Obtain device name.
- const char* dev_path = udev_iface_->ListEntryGetName(list_entry);
- if (!dev_path) {
- LOG(ERROR) << "enumerated device has a null name string";
- return false;
- }
-
- // Obtain device object.
- struct udev_device* dev = udev_iface_->DeviceNewFromSyspath(udev, dev_path);
- if (!dev) {
- LOG(ERROR) << "obtained a null device object for enumerated device";
- return false;
- }
- scoped_ptr<UdevInterface::UdevDeviceCloser>
- dev_closer(udev_iface_->NewUdevDeviceCloser(&dev));
-
- if (!enum_helper->ProcessDev(dev))
- return false;
- }
-
- // Make sure postconditions were met.
- return enum_helper->Finalize();
-}
-
-void StandardGpioHandler::ResetTestModeSignalingFlags() {
- is_first_check_ = true;
- is_handshake_completed_ = false;
- is_test_mode_ = false;
-}
-
-bool StandardGpioHandler::DiscoverGpios() {
- if (is_discovery_attempted_)
- return is_discovery_successful_;
-
- is_discovery_attempted_ = true;
-
- // Obtain libudev instance and attach to a dedicated closer.
- struct udev* udev;
- if (!(udev = udev_iface_->New())) {
- LOG(ERROR) << "failed to obtain libudev instance, aborting GPIO discovery";
- return false;
- }
- scoped_ptr<UdevInterface::UdevCloser>
- udev_closer(udev_iface_->NewUdevCloser(&udev));
-
- // Enumerate GPIO chips, scanning for GPIO descriptors.
- GpioChipUdevEnumHelper chip_enum_helper(this);
- if (!InitUdevEnum(udev, &chip_enum_helper)) {
- LOG(ERROR) << "enumeration error, aborting GPIO discovery";
- return false;
- }
-
- // Obtain device names for all discovered GPIOs, reusing the udev instance.
- for (int id = 0; id < kGpioIdMax; id++) {
- GpioUdevEnumHelper gpio_enum_helper(this, static_cast<GpioId>(id));
- if (!InitUdevEnum(udev, &gpio_enum_helper)) {
- LOG(ERROR) << "enumeration error, aborting GPIO discovery";
- return false;
- }
- }
-
- is_discovery_successful_ = true;
- return true;
-}
-
-bool StandardGpioHandler::GetGpioDevName(StandardGpioHandler::GpioId id,
- string* dev_path_p) {
- CHECK(id >= 0 && id < kGpioIdMax && dev_path_p);
-
- *dev_path_p = gpios_[id].dev_path;
- return true;
-}
-
-bool StandardGpioHandler::OpenGpioFd(StandardGpioHandler::GpioId id,
- const char* dev_name,
- bool is_write) {
- CHECK(id >= 0 && id < kGpioIdMax && dev_name);
- string file_name = base::StringPrintf("%s/%s", gpios_[id].dev_path.c_str(),
- dev_name);
- if (!fd_->Open(file_name.c_str(), (is_write ? O_WRONLY : O_RDONLY))) {
- if (fd_->IsSettingErrno()) {
- PLOG(ERROR) << "failed to open " << file_name
- << " (" << gpio_defs_[id].name << ") for "
- << (is_write ? "writing" : "reading");
- } else {
- LOG(ERROR) << "failed to open " << file_name
- << " (" << gpio_defs_[id].name << ") for "
- << (is_write ? "writing" : "reading");
- }
- return false;
- }
- return true;
-}
-
-bool StandardGpioHandler::SetGpio(StandardGpioHandler::GpioId id,
- const char* dev_name, const char* entries[],
- const int num_entries, int index) {
- CHECK_GE(id, 0);
- CHECK_LT(id, kGpioIdMax);
- CHECK(dev_name);
- CHECK(entries);
- CHECK_GT(num_entries, 0);
- CHECK_GE(index, 0);
- CHECK_LT(index, num_entries);
-
- // Open device for writing.
- if (!OpenGpioFd(id, dev_name, true))
- return false;
- ScopedFileDescriptorCloser dev_fd_closer(fd_);
-
- // Write a string corresponding to the requested output index to the GPIO
- // device, appending a newline.
- string output_str = entries[index];
- output_str += '\n';
- ssize_t write_len = fd_->Write(output_str.c_str(), output_str.length());
- if (write_len != static_cast<ssize_t>(output_str.length())) {
- if (write_len < 0) {
- const string err_str = "failed to write to GPIO";
- if (fd_->IsSettingErrno()) {
- PLOG(ERROR) << err_str;
- } else {
- LOG(ERROR) << err_str;
- }
- } else {
- LOG(ERROR) << "wrong number of bytes written (" << write_len
- << " instead of " << output_str.length() << ")";
- }
- return false;
- }
-
- // Close the device explicitly, returning the close result.
- return fd_->Close();
-}
-
-bool StandardGpioHandler::GetGpio(StandardGpioHandler::GpioId id,
- const char* dev_name, const char* entries[],
- const int num_entries, int* index_p) {
- CHECK_GE(id, 0);
- CHECK_LT(id, kGpioIdMax);
- CHECK(dev_name);
- CHECK(entries);
- CHECK_GT(num_entries, 0);
- CHECK(index_p);
-
- // Open device for reading.
- if (!OpenGpioFd(id, dev_name, false))
- return false;
- ScopedFileDescriptorCloser dev_fd_closer(fd_);
-
- // Read the GPIO device. We attempt to read more than the max number of
- // characters expected followed by a newline, to ensure that we've indeed read
- // all the data available on the device.
- size_t max_entry_len = 0;
- for (int i = 0; i < num_entries; i++) {
- size_t entry_len = strlen(entries[i]);
- if (entry_len > max_entry_len)
- max_entry_len = entry_len;
- }
- max_entry_len++; // account for trailing newline
- size_t buf_len = max_entry_len + 1; // room for excess char / null terminator
- char buf[buf_len];
- memset(buf, 0, buf_len);
- ssize_t read_len = fd_->Read(buf, buf_len);
- if (read_len < 0 || read_len > static_cast<ssize_t>(max_entry_len)) {
- if (read_len < 0) {
- const string err_str = "failed to read GPIO";
- if (fd_->IsSettingErrno()) {
- PLOG(ERROR) << err_str;
- } else {
- LOG(ERROR) << err_str;
- }
- } else {
- LOG(ERROR) << "read too many bytes (" << read_len << ")";
- }
- return false;
- }
-
- // Remove trailing newline.
- read_len--;
- if (buf[read_len] != '\n') {
- LOG(ERROR) << "read value missing trailing newline";
- return false;
- }
- buf[read_len] = '\0';
-
- // Identify and write GPIO status.
- for (int i = 0; i < num_entries; i++)
- if (!strcmp(entries[i], buf)) {
- *index_p = i;
- // Close the device explicitly, returning the close result.
- return fd_->Close();
- }
-
- // Oops, unidentified reading...
- LOG(ERROR) << "read unexpected value from GPIO (`" << buf << "')";
- return false;
-}
-
-bool StandardGpioHandler::SetGpioDirection(StandardGpioHandler::GpioId id,
- StandardGpioHandler::GpioDir dir) {
- return SetGpio(id, "direction", gpio_dirs_, kGpioDirMax, dir);
-}
-
-bool StandardGpioHandler::GetGpioDirection(
- StandardGpioHandler::GpioId id,
- StandardGpioHandler::GpioDir* direction_p) {
- return GetGpio(id, "direction", gpio_dirs_, kGpioDirMax,
- reinterpret_cast<int*>(direction_p));
-}
-
-bool StandardGpioHandler::SetGpioValue(StandardGpioHandler::GpioId id,
- StandardGpioHandler::GpioVal value,
- bool is_check_direction) {
- // If so instructed, ensure that the GPIO is indeed in the output direction
- // before attempting to write to it.
- if (is_check_direction) {
- GpioDir dir;
- if (!(GetGpioDirection(id, &dir) && dir == kGpioDirOut)) {
- LOG(ERROR) << "couldn't verify that GPIO is in the output direction "
- "prior to reading from it";
- return false;
- }
- }
-
- return SetGpio(id, "value", gpio_vals_, kGpioValMax, value);
-}
-
-bool StandardGpioHandler::GetGpioValue(StandardGpioHandler::GpioId id,
- StandardGpioHandler::GpioVal* value_p,
- bool is_check_direction) {
- // If so instructed, ensure that the GPIO is indeed in the input direction
- // before attempting to read from it.
- if (is_check_direction) {
- GpioDir dir;
- if (!(GetGpioDirection(id, &dir) && dir == kGpioDirIn)) {
- LOG(ERROR) << "couldn't verify that GPIO is in the input direction "
- "prior to reading from it";
- return false;
- }
- }
-
- return GetGpio(id, "value", gpio_vals_, kGpioValMax,
- reinterpret_cast<int*>(value_p));
-}
-
-bool StandardGpioHandler::DoTestModeSignalingProtocol() {
- // The test mode signaling protocol is designed to provide a robust indication
- // that a Chrome OS device is physically connected to a servo board in a lab
- // setting. It is making very few assumptions about the soundness of the
- // hardware, firmware and kernel driver implementation of the GPIO mechanism.
- // In general, it is performing a three-way handshake between servo and the
- // Chrome OS client, based on changes in the GPIO value readings. The
- // client-side implementation does the following:
- //
- // 1. Check for an initial signal (0) on the input GPIO (dut_flaga).
- //
- // 2. Flip the signal (1 -> 0) on the output GPIO (dut_flagb).
- //
- // 3. Check for a flipped signal (1) on the input GPIO.
- //
- // TODO(garnold) the current implementation is based on sysfs access to GPIOs.
- // We will likely change this to using a specialized in-kernel driver
- // implementation, which would give us better performance and security
- // guarantees.
-
- LOG(INFO) << "attempting GPIO handshake";
-
- const char* dutflaga_name = gpio_defs_[kGpioIdDutflaga].name;
- const char* dutflagb_name = gpio_defs_[kGpioIdDutflagb].name;
-
- // Flip GPIO direction, set it to "in".
- // TODO(garnold) changing the GPIO direction back and forth is necessary for
- // overcoming a firmware/kernel issue which causes the device to be in the
- // "out" state whereas the kernel thinks it is in the "in" state. This should
- // be abandoned once the firmware and/or kernel driver have been fixed.
- // Details here: http://code.google.com/p/chromium-os/issues/detail?id=27680
- if (!(SetGpioDirection(kGpioIdDutflaga, kGpioDirOut) &&
- SetGpioDirection(kGpioIdDutflaga, kGpioDirIn))) {
- LOG(ERROR) << "failed to flip direction of input GPIO " << dutflaga_name;
- return false;
- }
-
- // Peek input GPIO state.
- GpioVal dutflaga_gpio_value;
- if (!GetGpioValue(kGpioIdDutflaga, &dutflaga_gpio_value, true)) {
- LOG(ERROR) << "failed to read input GPIO " << dutflaga_name;
- return false;
- }
-
- // If initial handshake signal not received, abort.
- if (dutflaga_gpio_value != kGpioValDown) {
- LOG(INFO) << "input GPIO " << dutflaga_name
- << " unset, terminating handshake";
- is_handshake_completed_ = true;
- return true;
- }
-
- // Initialize output GPIO to a default state.
- // TODO(garnold) a similar workaround for possible driver/firmware glitches,
- // we insist on flipping the direction of the GPIO prior to assuming it is in
- // the "out" direction.
- GpioDirResetter dutflagb_dir_resetter(this, kGpioIdDutflagb, kGpioDirIn);
- if (!(SetGpioDirection(kGpioIdDutflagb, kGpioDirIn) &&
- dutflagb_dir_resetter.set_do_reset(
- SetGpioDirection(kGpioIdDutflagb, kGpioDirOut)) &&
- SetGpioValue(kGpioIdDutflagb, kGpioValUp, false))) {
- LOG(ERROR) << "failed to initialize output GPIO " << dutflagb_name;
- return false;
- }
-
- // Wait, giving the receiving end enough time to sense the fall.
- g_usleep(kServoOutputResponseWaitInSecs * G_USEC_PER_SEC);
-
- // Flip the output signal.
- if (!SetGpioValue(kGpioIdDutflagb, kGpioValDown, false)) {
- LOG(ERROR) << "failed to flip output GPIO " << dutflagb_name;
- return false;
- }
-
- // Look for flipped input GPIO value, up to a preset timeout.
- Time expires =
- Time::Now() + TimeDelta::FromSeconds(kServoInputResponseTimeoutInSecs);
- TimeDelta delay =
- TimeDelta::FromMicroseconds(1000000 / kServoInputNumChecksPerSec);
- bool is_first_response_check = true;
- bool is_error = false;
- while (Time::Now() < expires) {
- if (is_first_response_check)
- is_first_response_check = false;
- else
- g_usleep(delay.InMicroseconds());
-
- // Read input GPIO.
- if (!GetGpioValue(kGpioIdDutflaga, &dutflaga_gpio_value, true)) {
- LOG(ERROR) << "failed to read input GPIO " << dutflaga_name;
- is_error = true;
- break;
- }
-
- // If dutflaga is now up (flipped), we got our signal!
- if (dutflaga_gpio_value == kGpioValUp) {
- is_test_mode_ = true;
- break;
- }
- }
-
- if (!is_error) {
- if (is_test_mode_) {
- is_handshake_completed_ = true;
- LOG(INFO) << "GPIO handshake completed, test mode signaled";
- } else {
- LOG(INFO) << "timed out waiting for input GPIO " << dutflaga_name
- << " to flip, terminating handshake";
- }
- }
-
- return is_handshake_completed_;
-}
-
-
-bool NoopGpioHandler::IsTestModeSignaled() {
- LOG(INFO) << "GPIOs not engaged, defaulting to "
- << (is_test_mode_ ? "test" : "normal") << " mode";
- return is_test_mode_;
-}
-
-} // namespace chromeos_update_engine
diff --git a/gpio_handler.h b/gpio_handler.h
deleted file mode 100644
index 580beb1..0000000
--- a/gpio_handler.h
+++ /dev/null
@@ -1,328 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROMEOS_PLATFORM_UPDATE_ENGINE_GPIO_HANDLER_H_
-#define CHROMEOS_PLATFORM_UPDATE_ENGINE_GPIO_HANDLER_H_
-
-#include <libudev.h>
-
-#include <string>
-
-#include "update_engine/file_descriptor.h"
-#include "update_engine/udev_interface.h"
-
-namespace chromeos_update_engine {
-
-// An abstract GPIO handler interface. Serves as basic for both concrete and
-// mock implementations.
-class GpioHandler {
- public:
- GpioHandler() {}
- virtual ~GpioHandler() {}; // ensure virtual destruction
-
- // Returns true iff GPIOs have been used to signal an automated test case.
- // This call may trigger a (deferred) GPIO discovery step prior to engaging in
- // the signaling protocol; if discovery did not reveal GPIO devices, or the
- // protocol has terminated prematurely, it will conservatively default to
- // false.
- virtual bool IsTestModeSignaled() = 0;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(GpioHandler);
-};
-
-
-// Concrete implementation of GPIO signal handling. Currently, it only utilizes
-// the two Chromebook-specific GPIOs (aka 'dut_flaga' and 'dut_flagb') in
-// deciding whether a lab test mode has been signaled. Internal logic includes
-// detection, setup and reading from / writing to GPIOs. Detection is done via
-// libudev calls. This class should be instantiated at most once to avoid race
-// conditions in communicating over GPIO signals; instantiating a second
-// object will actually cause a runtime error.
-class StandardGpioHandler : public GpioHandler {
- public:
- // This constructor accepts a udev interface |udev_iface| and a reusable file
- // descriptor |fd|. The value of |is_defer_discovery| determines whether GPIO
- // discovery should be attempted right away (false) or done lazily, when
- // necessitated by other calls (true). If |is_cache_test_mode| is true,
- // checking for test mode signal is done only once and further queries return
- // the cached result.
- StandardGpioHandler(UdevInterface* udev_iface, FileDescriptor* fd,
- bool is_defer_discovery, bool is_cache_test_mode);
-
- // Free all resources, allow to reinstantiate.
- virtual ~StandardGpioHandler();
-
- // Returns true iff GPIOs have been used to signal an automated test case. The
- // check is performed at most once and the result is cached and returned on
- // subsequent calls, unless |is_force| is true. This call may trigger a
- // delayed GPIO discovery prior to engaging in the signaling protocol; if the
- // delay period has not elapsed, it will conservatively default to false.
- virtual bool IsTestModeSignaled();
-
- private:
- // GPIO identifiers, currently includes only the two dutflags.
- enum GpioId {
- kGpioIdDutflaga = 0,
- kGpioIdDutflagb,
- kGpioIdMax // marker, do not remove!
- };
-
- // GPIO direction specifier.
- enum GpioDir {
- kGpioDirIn = 0,
- kGpioDirOut,
- kGpioDirMax // marker, do not remove!
- };
-
- // GPIO value.
- enum GpioVal {
- kGpioValUp = 0,
- kGpioValDown,
- kGpioValMax // marker, do not remove!
- };
-
- // GPIO definition data.
- struct GpioDef {
- const char* name; // referential name of this GPIO
- const char* udev_property; // udev property containing the device id
- };
-
- // GPIO runtime control structure.
- struct Gpio {
- std::string descriptor; // unique GPIO descriptor
- std::string dev_path; // sysfs device name
- };
-
- // The number of seconds we wait before flipping the output signal (aka,
- // producing the "challenge" signal). Assuming a 1 second sampling frequency
- // on the servo side, a two second wait should be enough.
- static const int kServoOutputResponseWaitInSecs = 2;
-
- // The total number of seconds we wait for a servo response from the point we
- // flip the output signal. Assuming a 1 second sampling frequency on the servo
- // side, a two second wait should suffice. We add one more second for grace
- // (servod / hardware processing delays, etc).
- static const int kServoInputResponseTimeoutInSecs = 3;
-
- // The number of times per second we check for a servo response. Five seems
- // like a reasonable value.
- static const int kServoInputNumChecksPerSec = 5;
-
- // GPIO value/direction conversion tables.
- static const char* gpio_dirs_[kGpioDirMax];
- static const char* gpio_vals_[kGpioValMax];
-
- // GPIO definitions.
- static const GpioDef gpio_defs_[kGpioIdMax];
-
- // Udev device enumeration helper classes. First here is an interface
- // definition, which provides callbacks for enumeration setup and processing.
- class UdevEnumHelper {
- public:
- UdevEnumHelper(StandardGpioHandler* gpio_handler)
- : gpio_handler_(gpio_handler) {}
-
- // Setup the enumeration filters.
- virtual bool SetupEnumFilters(udev_enumerate* udev_enum) = 0;
-
- // Processes an enumerated device. Returns true upon success, false
- // otherwise.
- virtual bool ProcessDev(udev_device* dev) = 0;
-
- // Finalize the enumeration.
- virtual bool Finalize() = 0;
-
- protected:
- StandardGpioHandler* gpio_handler_;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(UdevEnumHelper);
- };
-
- // Specialized udev enumerate helper for extracting GPIO descriptors from the
- // GPIO chip device.
- class GpioChipUdevEnumHelper : public UdevEnumHelper {
- public:
- GpioChipUdevEnumHelper(StandardGpioHandler* gpio_handler)
- : UdevEnumHelper(gpio_handler), num_gpio_chips_(0) {}
- virtual bool SetupEnumFilters(udev_enumerate* udev_enum);
- virtual bool ProcessDev(udev_device* dev);
- virtual bool Finalize();
-
- private:
- // Records the number of times a GPIO chip has been enumerated (should not
- // exceed 1).
- int num_gpio_chips_;
-
- DISALLOW_COPY_AND_ASSIGN(GpioChipUdevEnumHelper);
- };
-
- // Specialized udev enumerate helper for extracting a sysfs device path from a
- // GPIO device.
- class GpioUdevEnumHelper : public UdevEnumHelper {
- public:
- GpioUdevEnumHelper(StandardGpioHandler* gpio_handler, GpioId id)
- : UdevEnumHelper(gpio_handler), num_gpios_(0), id_(id) {}
- virtual bool SetupEnumFilters(udev_enumerate* udev_enum);
- virtual bool ProcessDev(udev_device* dev);
- virtual bool Finalize();
-
- private:
- // Records the number of times a GPIO has been enumerated with a given
- // descriptor (should not exceed 1).
- int num_gpios_;
-
- // The enumerated GPIO identifier.
- GpioId id_;
-
- DISALLOW_COPY_AND_ASSIGN(GpioUdevEnumHelper);
- };
-
- // Helper class for resetting a GPIO direction.
- class GpioDirResetter {
- public:
- GpioDirResetter(StandardGpioHandler* handler, GpioId id, GpioDir dir);
- ~GpioDirResetter();
-
- bool do_reset() const {
- return do_reset_;
- }
- bool set_do_reset(bool do_reset) {
- return (do_reset_ = do_reset);
- }
-
- private:
- // Determines whether or not the GPIO direction should be reset to the
- // initial value.
- bool do_reset_;
-
- // The GPIO handler to use for changing the GPIO direction.
- StandardGpioHandler* handler_;
-
- // The GPIO identifier and initial direction.
- GpioId id_;
- GpioDir dir_;
- };
-
- // An initialization helper performing udev enumeration. |enum_helper|
- // implements an enumeration initialization and processing methods. Returns
- // true upon success, false otherwise.
- bool InitUdevEnum(struct udev* udev, UdevEnumHelper* enum_helper);
-
- // Resets the object's flags which determine the status of test mode
- // signaling.
- void ResetTestModeSignalingFlags();
-
- // Attempt GPIO discovery, at most once. Returns true if discovery process was
- // successfully completed, false otherwise.
- bool DiscoverGpios();
-
- // Assigns a copy of the device name of GPIO |id| to |dev_path_p|. Assumes
- // initialization. Returns true upon success, false otherwise.
- bool GetGpioDevName(GpioId id, std::string* dev_path_p);
-
- // Open a sysfs file device |dev_name| of GPIO |id|, for either reading or
- // writing depending on |is_write|. Uses the internal file descriptor for
- // this purpose, which can be reused as long as it is closed between
- // successive opens. Returns true upon success, false otherwise (optionally,
- // with errno set accordingly).
- bool OpenGpioFd(GpioId id, const char* dev_name, bool is_write);
-
- // Writes a value to device |dev_name| of GPIO |id|. The index |output| is
- // used to index the corresponding string to be written from the list
- // |entries| of length |num_entries|. Returns true upon success, false
- // otherwise.
- bool SetGpio(GpioId id, const char* dev_name, const char* entries[],
- const int num_entries, int output);
-
- // Reads a value from device |dev_name| of GPIO |id|. The list |entries| of
- // length |num_entries| is used to convert the read string into an index,
- // which is written to |input_p|. The call will fail if the value being read
- // is not listed in |entries|. Returns true upon success, false otherwise.
- bool GetGpio(GpioId id, const char* dev_name, const char* entries[],
- const int num_entries, int* input_p);
-
- // Sets GPIO |id| to to operate in a given |direction|. Assumes
- // initialization. Returns true on success, false otherwise.
- bool SetGpioDirection(GpioId id, GpioDir direction);
-
- // Assigns the current direction of GPIO |id| into |direction_p|. Assumes
- // initialization. Returns true on success, false otherwise.
- bool GetGpioDirection(GpioId id, GpioDir* direction_p);
-
- // Sets the value of GPIO |id| to |value|. Assumues initialization. The GPIO
- // direction should be set to 'out' prior to this call. If
- // |is_check_direction| is true, it'll ensure that the direction is indeed
- // 'out' prior to attempting the write. Returns true on success, false
- // otherwise.
- bool SetGpioValue(GpioId id, GpioVal value, bool is_check_direction);
-
- // Reads the value of a GPIO |id| and stores it in |value_p|. Assumes
- // initialization. The GPIO direction should be set to 'in' prior to this
- // call. If |is_check_direction| is true, it'll ensure that the direction is
- // indeed 'in' prior to attempting the read. Returns true upon success, false
- // otherwise.
- bool GetGpioValue(GpioId id, GpioVal *value_p, bool is_check_direction);
-
- // Invokes the actual GPIO handshake protocol to determine whether test mode
- // was signaled. Returns true iff the handshake has terminated gracefully
- // without encountering any errors; note that a true value does *not* mean
- // that a test mode signal has been detected. The spec for this protocol:
- // https://docs.google.com/a/google.com/document/d/1DB-35ptck1wT1TYrgS5AC5Y3ALfHok-iPA7kLBw2XCI/edit
- bool DoTestModeSignalingProtocol();
-
- // Dynamic counter for the number of instances this class has. Used to enforce
- // that no more than one instance created. Thread-unsafe.
- static unsigned num_instances_;
-
- // GPIO control structures.
- Gpio gpios_[kGpioIdMax];
-
- // Udev interface.
- UdevInterface* const udev_iface_;
-
- // A file abstraction for handling GPIO devices.
- FileDescriptor* const fd_;
-
- // Determines whether test mode signal should be checked at most once and
- // cached, or reestablished on each query.
- const bool is_cache_test_mode_;
-
- // Indicates whether GPIO discovery was performed, and whether it's been
- // successful.
- bool is_discovery_attempted_;
- bool is_discovery_successful_;
-
- // Persistent state of the test mode check.
- bool is_first_check_;
- bool is_handshake_completed_;
- bool is_test_mode_;
-
- DISALLOW_COPY_AND_ASSIGN(StandardGpioHandler);
-};
-
-
-// A "no-op" GPIO handler, initialized to return either test or normal mode
-// signal. This is useful for disabling the GPIO functionality in production
-// code.
-class NoopGpioHandler : public GpioHandler {
- public:
- // This constructor accepts a single argument, which is the value to be
- // returned by repeated calls to IsTestModeSignaled().
- NoopGpioHandler(bool is_test_mode) : is_test_mode_(is_test_mode) {}
-
- // Returns the constant Boolean value handed to the constructor.
- virtual bool IsTestModeSignaled();
-
- private:
- // Stores the constant value to return on subsequent test mode checks.
- bool is_test_mode_;
-
- DISALLOW_COPY_AND_ASSIGN(NoopGpioHandler);
-};
-
-} // namespace chromeos_update_engine
-
-#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_GPIO_HANDLER_H_
diff --git a/gpio_handler_unittest.cc b/gpio_handler_unittest.cc
deleted file mode 100644
index 3aaae5c..0000000
--- a/gpio_handler_unittest.cc
+++ /dev/null
@@ -1,277 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-
-#include "update_engine/gpio_handler.h"
-#include "update_engine/gpio_mock_file_descriptor.h"
-#include "update_engine/gpio_mock_udev_interface.h"
-
-namespace chromeos_update_engine {
-
-class StandardGpioHandlerTest : public ::testing::Test {};
-
-TEST(StandardGpioHandlerTest, NormalInitTest) {
- // Ensure that initialization of the GPIO module works as expected, and that
- // all udev resources are deallocated afterwards. The mock file descriptor is
- // not to be used.
- StandardGpioMockUdevInterface mock_udev;
- TestModeGpioMockFileDescriptor
- mock_file_descriptor(base::TimeDelta::FromSeconds(1));
- StandardGpioHandler gpio_hander(&mock_udev, &mock_file_descriptor,
- false, false);
- mock_udev.ExpectAllResourcesDeallocated();
- mock_udev.ExpectDiscoverySuccess();
- mock_file_descriptor.ExpectNumOpenAttempted(0);
-}
-
-TEST(StandardGpioHandlerTest, MultiGpioChipInitTest) {
- // Attempt GPIO discovery with a udev mock that returns two GPIO chip devices.
- // It should fail, of course. The mock file descriptor is not to be used.
- MultiChipGpioMockUdevInterface mock_udev;
- TestModeGpioMockFileDescriptor
- mock_file_descriptor(base::TimeDelta::FromSeconds(1));
- StandardGpioHandler gpio_handler(&mock_udev, &mock_file_descriptor,
- false, false);
- mock_udev.ExpectAllResourcesDeallocated();
- mock_udev.ExpectDiscoveryFail();
- mock_file_descriptor.ExpectNumOpenAttempted(0);
-}
-
-TEST(StandardGpioHandlerTest, FailedFirstGpioInitTest) {
- // Attempt GPIO discovery with a udev mock that fails the initialization on
- // the first attempt, then check for test mode. Ensure that (a) discovery is
- // not attempted a second time, and (b) test mode check returns false (the
- // default) without attempting to use GPIO signals.
- FailInitGpioMockUdevInterface mock_udev;
- TestModeGpioMockFileDescriptor
- mock_file_descriptor(base::TimeDelta::FromSeconds(1));
- StandardGpioHandler gpio_handler(&mock_udev, &mock_file_descriptor,
- false, false);
- EXPECT_FALSE(gpio_handler.IsTestModeSignaled());
- mock_udev.ExpectAllResourcesDeallocated();
- mock_udev.ExpectDiscoveryFail();
- mock_udev.ExpectNumInitAttempts(1);
- mock_file_descriptor.ExpectNumOpenAttempted(0);
-}
-
-TEST(StandardGpioHandlerTest, TestModeGpioSignalingTest) {
- // Initialize the GPIO module and test for successful completion of the test
- // signaling protocol.
- StandardGpioMockUdevInterface mock_udev;
- TestModeGpioMockFileDescriptor
- mock_file_descriptor(base::TimeDelta::FromSeconds(1));
- StandardGpioHandler gpio_handler(&mock_udev, &mock_file_descriptor,
- false, false);
- EXPECT_TRUE(gpio_handler.IsTestModeSignaled());
- mock_udev.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllGpiosRestoredToDefault();
-}
-
-TEST(StandardGpioHandlerTest, DeferredInitTestModeGpioSignalingTest) {
- // Initialize the GPIO module with deferred initialization, test for
- // successful completion of the test signaling protocol.
- StandardGpioMockUdevInterface mock_udev;
- TestModeGpioMockFileDescriptor
- mock_file_descriptor(base::TimeDelta::FromSeconds(1));
- StandardGpioHandler gpio_handler(&mock_udev, &mock_file_descriptor,
- true, false);
- EXPECT_TRUE(gpio_handler.IsTestModeSignaled());
- mock_udev.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllGpiosRestoredToDefault();
-}
-
-TEST(StandardGpioHandlerTest, TestModeGpioSignalingTwiceTest) {
- // Initialize the GPIO module and query for test signal twice (uncached); the
- // first query should succeed whereas the second should fail.
- StandardGpioMockUdevInterface mock_udev;
- TestModeGpioMockFileDescriptor
- mock_file_descriptor(base::TimeDelta::FromSeconds(1));
- StandardGpioHandler gpio_handler(&mock_udev, &mock_file_descriptor,
- false, false);
- EXPECT_TRUE(gpio_handler.IsTestModeSignaled());
- EXPECT_FALSE(gpio_handler.IsTestModeSignaled());
- mock_udev.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllGpiosRestoredToDefault();
-}
-
-TEST(StandardGpioHandlerTest, TestModeGpioSignalingTwiceCachedTest) {
- // Initialize the GPIO module and query for test signal twice (cached); both
- // queries should succeed.
- StandardGpioMockUdevInterface mock_udev;
- TestModeGpioMockFileDescriptor
- mock_file_descriptor(base::TimeDelta::FromSeconds(1));
- StandardGpioHandler gpio_handler(&mock_udev, &mock_file_descriptor,
- false, true);
- EXPECT_TRUE(gpio_handler.IsTestModeSignaled());
- EXPECT_TRUE(gpio_handler.IsTestModeSignaled());
- mock_udev.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllGpiosRestoredToDefault();
-}
-
-TEST(StandardGpioHandlerTest, NormalModeGpioSignalingTest) {
- // Initialize the GPIO module, run the signaling procedure, ensure that it
- // concluded that this is a normal mode run.
- StandardGpioMockUdevInterface mock_udev;
- NormalModeGpioMockFileDescriptor mock_file_descriptor;
- StandardGpioHandler gpio_handler(&mock_udev, &mock_file_descriptor,
- false, false);
- EXPECT_FALSE(gpio_handler.IsTestModeSignaled());
- mock_udev.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllGpiosRestoredToDefault();
-}
-
-TEST(StandardGpioHandlerTest, NonPulledUpNormalModeGpioSignalingTest) {
- // Initialize the GPIO module with a non-pulled up mock (which means the it
- // returns a different default signal), run the signaling procedure, ensure
- // that it concluded that this is a normal mode run.
- StandardGpioMockUdevInterface mock_udev;
- NonPulledUpNormalModeGpioMockFileDescriptor mock_file_descriptor;
- StandardGpioHandler gpio_handler(&mock_udev, &mock_file_descriptor,
- false, false);
- EXPECT_FALSE(gpio_handler.IsTestModeSignaled());
- mock_udev.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllGpiosRestoredToDefault();
-}
-
-TEST(StandardGpioHandlerTest, DeferredInitNormalModeGpioSignalingTest) {
- // Initialize the GPIO module with deferred discovery, run the signaling
- // procedure, ensure that it concluded that this is a normal mode run.
- StandardGpioMockUdevInterface mock_udev;
- NormalModeGpioMockFileDescriptor mock_file_descriptor;
- StandardGpioHandler gpio_handler(&mock_udev, &mock_file_descriptor,
- true, false);
- EXPECT_FALSE(gpio_handler.IsTestModeSignaled());
- mock_udev.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllGpiosRestoredToDefault();
-}
-
-TEST(StandardGpioHandlerTest, FlipInputDirErrorNormalModeGpioSignalingTest) {
- // Test the GPIO module with a mock that simulates a GPIO sysfs race/hack,
- // which causes the input GPIO to flip direction. Ensure that it concludes
- // that this is a normal mode run.
- StandardGpioMockUdevInterface mock_udev;
- ErrorNormalModeGpioMockFileDescriptor
- mock_file_descriptor(
- base::TimeDelta::FromSeconds(1),
- ErrorNormalModeGpioMockFileDescriptor::kGpioErrorFlipInputDir);
- StandardGpioHandler gpio_handler(&mock_udev, &mock_file_descriptor,
- false, false);
- EXPECT_FALSE(gpio_handler.IsTestModeSignaled());
- mock_udev.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllGpiosRestoredToDefault();
-}
-
-TEST(StandardGpioHandlerTest, ReadInvalidValErrorNormalModeGpioSignalingTest) {
- // Test the GPIO module with a mock that simulates an invalid value reading
- // from a GPIO device. Ensure that it concludes that this is a normal mode
- // run.
- StandardGpioMockUdevInterface mock_udev;
- ErrorNormalModeGpioMockFileDescriptor
- mock_file_descriptor(
- base::TimeDelta::FromSeconds(1),
- ErrorNormalModeGpioMockFileDescriptor::kGpioErrorReadInvalidVal);
- StandardGpioHandler gpio_handler(&mock_udev, &mock_file_descriptor,
- false, false);
- EXPECT_FALSE(gpio_handler.IsTestModeSignaled());
- mock_udev.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllGpiosRestoredToDefault();
-}
-
-TEST(StandardGpioHandlerTest, ReadInvalidDirErrorNormalModeGpioSignalingTest) {
- // Test the GPIO module with a mock that simulates an invalid value reading
- // from a GPIO device. Ensure that it concludes that this is a normal mode
- // run.
- StandardGpioMockUdevInterface mock_udev;
- ErrorNormalModeGpioMockFileDescriptor
- mock_file_descriptor(
- base::TimeDelta::FromSeconds(1),
- ErrorNormalModeGpioMockFileDescriptor::kGpioErrorReadInvalidDir);
- StandardGpioHandler gpio_handler(&mock_udev, &mock_file_descriptor,
- false, false);
- EXPECT_FALSE(gpio_handler.IsTestModeSignaled());
- mock_udev.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllGpiosRestoredToDefault();
-}
-
-TEST(StandardGpioHandlerTest, FailFileOpenErrorNormalModeGpioSignalingTest) {
- // Test the GPIO module with a mock that simulates an invalid value reading
- // from a GPIO device. Ensure that it concludes that this is a normal mode
- // run.
- StandardGpioMockUdevInterface mock_udev;
- ErrorNormalModeGpioMockFileDescriptor
- mock_file_descriptor(
- base::TimeDelta::FromSeconds(1),
- ErrorNormalModeGpioMockFileDescriptor::kGpioErrorFailFileOpen);
- StandardGpioHandler gpio_handler(&mock_udev, &mock_file_descriptor,
- false, false);
- EXPECT_FALSE(gpio_handler.IsTestModeSignaled());
- mock_udev.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllGpiosRestoredToDefault();
-}
-
-TEST(StandardGpioHandlerTest, FailFileReadErrorNormalModeGpioSignalingTest) {
- // Test the GPIO module with a mock that simulates an invalid value reading
- // from a GPIO device. Ensure that it concludes that this is a normal mode
- // run.
- StandardGpioMockUdevInterface mock_udev;
- ErrorNormalModeGpioMockFileDescriptor
- mock_file_descriptor(
- base::TimeDelta::FromSeconds(1),
- ErrorNormalModeGpioMockFileDescriptor::kGpioErrorFailFileRead);
- StandardGpioHandler gpio_handler(&mock_udev, &mock_file_descriptor,
- false, false);
- EXPECT_FALSE(gpio_handler.IsTestModeSignaled());
- mock_udev.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllGpiosRestoredToDefault();
-}
-
-TEST(StandardGpioHandlerTest, FailFileWriteErrorNormalModeGpioSignalingTest) {
- // Test the GPIO module with a mock that simulates an invalid value reading
- // from a GPIO device. Ensure that it concludes that this is a normal mode
- // run.
- StandardGpioMockUdevInterface mock_udev;
- ErrorNormalModeGpioMockFileDescriptor
- mock_file_descriptor(
- base::TimeDelta::FromSeconds(1),
- ErrorNormalModeGpioMockFileDescriptor::kGpioErrorFailFileWrite);
- StandardGpioHandler gpio_handler(&mock_udev, &mock_file_descriptor,
- false, false);
- EXPECT_FALSE(gpio_handler.IsTestModeSignaled());
- mock_udev.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllGpiosRestoredToDefault();
-}
-
-TEST(StandardGpioHandlerTest, FailFileCloseErrorNormalModeGpioSignalingTest) {
- // Test the GPIO module with a mock that simulates an invalid value reading
- // from a GPIO device. Ensure that it concludes that this is a normal mode
- // run.
- StandardGpioMockUdevInterface mock_udev;
- ErrorNormalModeGpioMockFileDescriptor
- mock_file_descriptor(
- base::TimeDelta::FromSeconds(1),
- ErrorNormalModeGpioMockFileDescriptor::kGpioErrorFailFileClose);
- StandardGpioHandler gpio_handler(&mock_udev, &mock_file_descriptor,
- false, false);
- EXPECT_FALSE(gpio_handler.IsTestModeSignaled());
- mock_udev.ExpectAllResourcesDeallocated();
- mock_file_descriptor.ExpectAllResourcesDeallocated();
- // Don't test GPIO status restored; since closing of sysfs files fails, all
- // bets are off.
-}
-
-} // namespace chromeos_update_engine
diff --git a/gpio_handler_unittest.h b/gpio_handler_unittest.h
deleted file mode 100644
index 484d1b8..0000000
--- a/gpio_handler_unittest.h
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROMEOS_PLATFORM_UPDATE_ENGINE_GPIO_HANDLER_UNITTEST_H_
-#define CHROMEOS_PLATFORM_UPDATE_ENGINE_GPIO_HANDLER_UNITTEST_H_
-
-// This file contains various definitions that are shared by different mock
-// implementations that emulate GPIO behavior in the system.
-
-// Some common strings used by the different cooperating mocks for this module.
-// We use preprocessor constants to allow concatenation at compile-time.
-#define MOCK_GPIO_CHIP_ID "100"
-#define MOCK_DUTFLAGA_GPIO_ID "101"
-#define MOCK_DUTFLAGB_GPIO_ID "102"
-#define MOCK_SYSFS_PREFIX "/mock/sys/class/gpio"
-
-namespace chromeos_update_engine {
-
-// Mock GPIO identifiers, used by all mocks involved in unit testing the GPIO
-// module. These represent the GPIOs which the unit tests can cover. They should
-// generally match the GPIOs specified inside GpioHandler.
-enum MockGpioId {
- kMockGpioIdDutflaga = 0,
- kMockGpioIdDutflagb,
- kMockGpioIdMax // marker, do not remove!
-};
-
-// Mock GPIO directions, which are analogous to actual GPIO directions.
-enum MockGpioDir {
- kMockGpioDirIn = 0,
- kMockGpioDirOut,
- kMockGpioDirMax // marker, do not remove!
-};
-
-// Mock GPIO values, ditto.
-enum MockGpioVal {
- kMockGpioValUp = 0,
- kMockGpioValDown,
- kMockGpioValMax // marker, do not remove!
-};
-
-} // chromeos_update_engine
-
-#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_GPIO_HANDLER_UNITTEST_H_
diff --git a/gpio_mock_file_descriptor.cc b/gpio_mock_file_descriptor.cc
deleted file mode 100644
index 7fb6d95..0000000
--- a/gpio_mock_file_descriptor.cc
+++ /dev/null
@@ -1,468 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "update_engine/gpio_mock_file_descriptor.h"
-
-#include <base/strings/stringprintf.h>
-#include <gtest/gtest.h>
-
-#include "update_engine/utils.h"
-
-using base::Time;
-using base::TimeDelta;
-using std::string;
-
-namespace chromeos_update_engine {
-
-namespace {
-// Typesets a time object into a string; omits the date.
-string TimeToString(Time time) {
- Time::Exploded exploded_time;
- time.LocalExplode(&exploded_time);
- return base::StringPrintf("%d:%02d:%02d.%03d",
- exploded_time.hour,
- exploded_time.minute,
- exploded_time.second,
- exploded_time.millisecond);
-}
-} // namespace
-
-//
-// GpioMockFileDescriptor
-//
-const char* GpioMockFileDescriptor::gpio_devname_prefixes_[kMockGpioIdMax] = {
- MOCK_SYSFS_PREFIX "/gpio" MOCK_DUTFLAGA_GPIO_ID,
- MOCK_SYSFS_PREFIX "/gpio" MOCK_DUTFLAGB_GPIO_ID,
-};
-
-const char* GpioMockFileDescriptor::gpio_val_strings_[kMockGpioValMax] = {
- "1", // kMockGpioValUp
- "0", // kMockGpioValDown
-};
-
-const char* GpioMockFileDescriptor::gpio_dir_strings_[kMockGpioDirMax] = {
- "in", // kMockGpioDirIn
- "out", // kMockGpioDirOut
-};
-
-
-GpioMockFileDescriptor::GpioMockFileDescriptor()
- : gpio_id_(kMockGpioIdMax),
- gpio_subdev_(kMockGpioSubdevMax),
- num_open_attempted_(0) {
- // All GPIOs are initially in the input direction, their read value is "up",
- // and they assume an initial write value of "up" with current (init) time.
- Time init_time = Time::Now();
- for (size_t i = 0; i < kMockGpioIdMax; i++) {
- gpio_dirs_[i] = kMockGpioDirIn;
- gpio_read_vals_[i] = kMockGpioValUp;
- SetGpioLastWrite(static_cast<MockGpioId>(i), kMockGpioValUp, init_time);
- }
-
- // Nullify the instance-specific override strings.
- for (size_t i = 0; i < kMockGpioValMax; i++)
- override_read_gpio_val_strings_[i] = NULL;
- for (size_t i = 0; i < kMockGpioDirMax; i++)
- override_read_gpio_dir_strings_[i] = NULL;
-}
-
-bool GpioMockFileDescriptor::Open(const char* path, int flags, mode_t mode) {
- num_open_attempted_++;
-
- EXPECT_EQ(gpio_id_, kMockGpioIdMax);
- if (gpio_id_ != kMockGpioIdMax)
- return false;
-
- // Determine identifier of opened GPIO device.
- size_t devname_prefix_len = 0;
- int id;
- for (id = 0; id < kMockGpioIdMax; id++) {
- devname_prefix_len = strlen(gpio_devname_prefixes_[id]);
- if (!strncmp(path, gpio_devname_prefixes_[id], devname_prefix_len))
- break;
- }
- EXPECT_LT(id, kMockGpioIdMax);
- if (id == kMockGpioIdMax)
- return false;
-
- // Determine specific sub-device.
- path += devname_prefix_len;
- EXPECT_EQ(path[0], '/');
- if (path[0] != '/')
- return false;
- path++;
- if (!strcmp(path, "value"))
- gpio_subdev_ = kMockGpioSubdevValue;
- else if (!strcmp(path, "direction"))
- gpio_subdev_ = kMockGpioSubdevDirection;
- else {
- ADD_FAILURE();
- return false;
- }
-
- gpio_id_ = static_cast<MockGpioId>(id);
- LOG(INFO) << "opened mock gpio "
- << (id == kMockGpioIdDutflaga ? "dut_flaga" :
- id == kMockGpioIdDutflagb ? "dut_flagb" :
- "<unknown>")
- << "/"
- << (gpio_subdev_ == kMockGpioSubdevValue ? "value" :
- gpio_subdev_ == kMockGpioSubdevDirection ? "direction" :
- "<unknown>");
- return true;
-}
-
-bool GpioMockFileDescriptor::Open(const char* path, int flags) {
- return Open(path, flags, 0);
-}
-
-ssize_t GpioMockFileDescriptor::Read(void* buf, size_t count) {
- EXPECT_TRUE(IsOpen());
- if (!IsOpen())
- return -1;
-
- LOG(INFO) << "reading from gpio";
-
- // Attempt a state update prior to responding to the read.
- UpdateState();
-
- switch (gpio_subdev_) {
- case kMockGpioSubdevValue: { // reading the GPIO value
- // Read values vary depending on the GPIO's direction: an input GPIO will
- // return the value that was written by the remote end; an output GPIO,
- // however, will return the value last written to its output register...
- MockGpioVal gpio_read_val = kMockGpioValMax;
- switch (gpio_dirs_[gpio_id_]) {
- case kMockGpioDirIn:
- gpio_read_val = gpio_read_vals_[gpio_id_];
- break;
- case kMockGpioDirOut:
- gpio_read_val = gpio_last_writes_[gpio_id_].val;
- break;
- default:
- CHECK(false); // shouldn't get here
- }
-
- // Write the value to the client's buffer.
- return snprintf(reinterpret_cast<char*>(buf), count, "%s\n",
- (override_read_gpio_val_strings_[gpio_read_val] ?
- override_read_gpio_val_strings_[gpio_read_val] :
- gpio_val_strings_[gpio_read_val]));
- }
-
- case kMockGpioSubdevDirection: { // reading the GPIO direction
- // Write the current GPIO direction to the client's buffer.
- MockGpioDir gpio_dir = gpio_dirs_[gpio_id_];
- return snprintf(reinterpret_cast<char*>(buf), count, "%s\n",
- (override_read_gpio_dir_strings_[gpio_dir] ?
- override_read_gpio_dir_strings_[gpio_dir] :
- gpio_dir_strings_[gpio_dir]));
- }
-
- default:
- ADD_FAILURE(); // shouldn't get here
- return -1;
- }
-}
-
-ssize_t GpioMockFileDescriptor::Write(const void* buf, size_t count) {
- EXPECT_TRUE(IsOpen());
- EXPECT_TRUE(buf);
- if (!(IsOpen() && buf))
- return -1;
-
- string str = base::StringPrintf("%-*s", static_cast<int>(count),
- reinterpret_cast<const char*>(buf));
- size_t pos = 0;
- while ((pos = str.find('\n', pos)) != string::npos) {
- str.replace(pos, 1, "\\n");
- pos += 2;
- }
- LOG(INFO) << "writing to gpio: \"" << str << "\"";
-
- // Attempt a state update prior to performing the write operation.
- UpdateState();
-
- switch (gpio_subdev_) {
- case kMockGpioSubdevValue: { // setting the GPIO value
- // Ensure the GPIO is in the "out" direction
- EXPECT_EQ(gpio_dirs_[gpio_id_], kMockGpioDirOut);
- if (gpio_dirs_[gpio_id_] != kMockGpioDirOut)
- return -1;
-
- // Decode the written value.
- MockGpioVal write_val = DecodeGpioVal(reinterpret_cast<const char*>(buf),
- count);
- EXPECT_LT(write_val, kMockGpioValMax);
- if (write_val == kMockGpioValMax)
- return -1;
-
- // Update the last tracked written value.
- SetGpioLastWrite(gpio_id_, write_val);
- break;
- }
-
- case kMockGpioSubdevDirection: { // setting GPIO direction
- // Decipher the direction to be set.
- MockGpioDir write_dir = DecodeGpioDir(reinterpret_cast<const char*>(buf),
- count);
- EXPECT_LT(write_dir, kMockGpioDirMax);
- if (write_dir == kMockGpioDirMax)
- return -1;
-
- // Update the last write time for this GPIO if switching from "in" to
- // "out" and the written value is different from its read value; this is
- // due to the GPIO's DUT-side override, which may cause the Servo-side
- // reading to flip when switching it to "out".
- if (gpio_dirs_[gpio_id_] == kMockGpioDirIn &&
- write_dir == kMockGpioDirOut &&
- gpio_read_vals_[gpio_id_] != gpio_last_writes_[gpio_id_].val)
- gpio_last_writes_[gpio_id_].time = Time::Now();
-
- // Now update the GPIO direction.
- gpio_dirs_[gpio_id_] = write_dir;
- break;
- }
-
- default:
- ADD_FAILURE(); // shouldn't get here
- return -1;
- }
-
- return count;
-}
-
-bool GpioMockFileDescriptor::Close() {
- EXPECT_TRUE(IsOpen());
- if (!IsOpen())
- return false;
-
- Reset();
- return true;
-}
-
-void GpioMockFileDescriptor::Reset() {
- gpio_id_ = kMockGpioIdMax;
-}
-
-bool GpioMockFileDescriptor::IsSettingErrno() {
- // This mock doesn't test errno handling, so no.
- return false;
-}
-
-bool GpioMockFileDescriptor::ExpectAllResourcesDeallocated() {
- EXPECT_EQ(gpio_id_, kMockGpioIdMax);
- return (gpio_id_ == kMockGpioIdMax);
-}
-
-bool GpioMockFileDescriptor::ExpectAllGpiosRestoredToDefault() {
- // We just verify that direction is restored to "in" for all GPIOs.
- bool is_all_gpios_restored_to_default = true;
- for (size_t i = 0; i < kMockGpioIdMax; i++) {
- EXPECT_EQ(gpio_dirs_[i], kMockGpioDirIn)
- << "i=" << i << " gpio_dirs_[i]=" << gpio_dirs_[i];
- is_all_gpios_restored_to_default =
- is_all_gpios_restored_to_default && (gpio_dirs_[i] == kMockGpioDirIn);
- }
- return is_all_gpios_restored_to_default;
-}
-
-bool GpioMockFileDescriptor::ExpectNumOpenAttempted(unsigned count) {
- EXPECT_EQ(num_open_attempted_, count);
- return (num_open_attempted_ == count);
-}
-
-size_t GpioMockFileDescriptor::DecodeGpioString(const char* buf,
- size_t count,
- const char** strs,
- size_t num_strs) const {
- CHECK(buf && strs && count);
-
- // Last character must be a newline.
- count--;
- if (buf[count] != '\n')
- return num_strs;
-
- // Scan for a precise match within the provided string array.
- size_t i;
- for (i = 0; i < num_strs; i++)
- if (count == strlen(strs[i]) &&
- !strncmp(buf, strs[i], count))
- break;
- return i;
-}
-
-//
-// TestModeGpioMockFileDescriptor
-//
-TestModeGpioMockFileDescriptor::TestModeGpioMockFileDescriptor(
- TimeDelta servo_poll_interval)
- : last_state_(kServoStateInit),
- servo_poll_interval_(servo_poll_interval) {}
-
-void TestModeGpioMockFileDescriptor::UpdateState() {
- // The following simulates the Servo state transition logic. Note that all of
- // these tests are (should be) conservative estimates of the actual,
- // asynchronous logic implemented by an actual Servo. Also, they should remain
- // so regardless of which operation (read, write) triggers the check. We
- // repeat the update cycle until no further state changes occur (which assumes
- // that there are no state transition cycles).
- Time curr_time = Time::Now();
- ServoState curr_state = last_state_;
- do {
- if (last_state_ != curr_state) {
- last_state_ = curr_state;
- curr_servo_poll_fuzz_ = RandomServoPollFuzz(); // fix a new poll fuzz
- LOG(INFO) << "state=" << last_state_ << ", new poll fuzz="
- << utils::FormatTimeDelta(curr_servo_poll_fuzz_);
- }
-
- switch (last_state_) {
- case kServoStateInit:
- // Unconditionally establish the trigger signal.
- LOG(INFO) << "unconditionally sending trigger signal over dut_flaga";
- gpio_read_vals_[kMockGpioIdDutflaga] = kMockGpioValDown;
- curr_state = kServoStateTriggerSent;
- break;
-
- case kServoStateTriggerSent:
- // If dut_flagb is in "out" mode, its last written value is "1", and
- // it's probable that Servo has polled it since, then advance the state.
- if (gpio_dirs_[kMockGpioIdDutflagb] == kMockGpioDirOut &&
- gpio_last_writes_[kMockGpioIdDutflagb].val == kMockGpioValUp &&
- (gpio_last_writes_[kMockGpioIdDutflagb].time +
- curr_servo_poll_fuzz_) < curr_time) {
- LOG(INFO) << "an up signal was written to dut_flagb on "
- << TimeToString(gpio_last_writes_[kMockGpioIdDutflagb].time)
- << " and polled at "
- << TimeToString(
- gpio_last_writes_[kMockGpioIdDutflagb].time +
- curr_servo_poll_fuzz_)
- << " (after "
- << utils::FormatTimeDelta(curr_servo_poll_fuzz_)
- << "); current time is " << TimeToString(curr_time);
- curr_state = kServoStateChallengeUpReceived;
- }
- break;
-
- case kServoStateChallengeUpReceived:
- // If dut_flagb is in "out" mode, its last written value is "0", and
- // it's probable that Servo has polled it since, then advance the state
- // and flip the value of dut_flaga.
- if (gpio_dirs_[kMockGpioIdDutflagb] == kMockGpioDirOut &&
- gpio_last_writes_[kMockGpioIdDutflagb].val == kMockGpioValDown &&
- (gpio_last_writes_[kMockGpioIdDutflagb].time +
- curr_servo_poll_fuzz_) < curr_time) {
- LOG(INFO) << "a down signal was written to dut_flagb on "
- << TimeToString(gpio_last_writes_[kMockGpioIdDutflagb].time)
- << " and polled at "
- << TimeToString(
- gpio_last_writes_[kMockGpioIdDutflagb].time +
- curr_servo_poll_fuzz_)
- << " (after "
- << utils::FormatTimeDelta(curr_servo_poll_fuzz_)
- << "); current time is " << TimeToString(curr_time);
- gpio_read_vals_[kMockGpioIdDutflaga] = kMockGpioValUp;
- curr_state = kServoStateChallengeDownReceived;
- }
- break;
-
- case kServoStateChallengeDownReceived:
- break; // terminal state, nothing to do
-
- default:
- CHECK(false); // shouldn't get here
- }
- } while (last_state_ != curr_state);
-}
-
-//
-// ErrorNormalModeGpioMockFileDescriptor
-//
-ErrorNormalModeGpioMockFileDescriptor::ErrorNormalModeGpioMockFileDescriptor(
- TimeDelta servo_poll_interval,
- ErrorNormalModeGpioMockFileDescriptor::GpioError error)
- : TestModeGpioMockFileDescriptor(servo_poll_interval),
- error_(error),
- is_dutflaga_dir_flipped_(false) {}
-
-bool ErrorNormalModeGpioMockFileDescriptor::Open(const char* path, int flags,
- mode_t mode) {
- if (error_ == kGpioErrorFailFileOpen)
- return false;
- return TestModeGpioMockFileDescriptor::Open(path, flags, mode);
-}
-
-ssize_t ErrorNormalModeGpioMockFileDescriptor::Read(void* buf, size_t count) {
- if (error_ == kGpioErrorFailFileRead)
- return -1;
- return TestModeGpioMockFileDescriptor::Read(buf, count);
-}
-
-ssize_t ErrorNormalModeGpioMockFileDescriptor::Write(const void* buf,
- size_t count) {
- if (error_ == kGpioErrorFailFileWrite)
- return -1;
- return TestModeGpioMockFileDescriptor::Write(buf, count);
-}
-
-bool ErrorNormalModeGpioMockFileDescriptor::Close() {
- // We actually need to perform the close operation anyway, to avoid
- // inconsistencies in the file descriptor's state.
- bool ret = TestModeGpioMockFileDescriptor::Close();
- return (error_ == kGpioErrorFailFileClose ? false : ret);
-}
-
-void ErrorNormalModeGpioMockFileDescriptor::UpdateState() {
- // Invoke the base class's update method.
- TestModeGpioMockFileDescriptor::UpdateState();
-
- // Sabotage the normal feedback that is to be expected from the GPIOs, in
- // various ways based on the requested type of error.
- switch (error_) {
- case kGpioErrorFlipInputDir:
- // Intervene by flipping the direction of dut_flaga right after the
- // challenge signal was sent to servo. Among other things, this could
- // simulate a benign race condition, or an intentional attempt to fool the
- // GPIO module to believe that it is talking to an (absent) servo.
- if (!is_dutflaga_dir_flipped_ &&
- last_state_ == kServoStateChallengeDownReceived) {
- is_dutflaga_dir_flipped_ = true;
- LOG(INFO) << "intervention: setting dut_flaga direction to out";
- gpio_dirs_[kMockGpioIdDutflaga] = kMockGpioDirOut;
- }
- break;
-
- case kGpioErrorReadInvalidVal:
- // Cause the GPIO device to return an invalid value reading.
- override_read_gpio_val_strings_[kMockGpioValUp] = "foo";
- override_read_gpio_val_strings_[kMockGpioValDown] = "bar";
- break;
-
- case kGpioErrorReadInvalidDir:
- // Cause the GPIO device to return an invlid direction reading.
- override_read_gpio_dir_strings_[kMockGpioDirIn] = "boo";
- override_read_gpio_dir_strings_[kMockGpioDirOut] = "far";
-
- case kGpioErrorFailFileOpen:
- case kGpioErrorFailFileRead:
- case kGpioErrorFailFileWrite:
- case kGpioErrorFailFileClose:
- break;
-
- default:
- CHECK(false); // shouldn't get here
- }
-}
-
-bool ErrorNormalModeGpioMockFileDescriptor::ExpectAllGpiosRestoredToDefault() {
- if (is_dutflaga_dir_flipped_) {
- LOG(INFO) << "restoring dut_flaga direction back to in";
- gpio_dirs_[kMockGpioIdDutflaga] = kMockGpioDirIn;
- }
-
- return TestModeGpioMockFileDescriptor::ExpectAllGpiosRestoredToDefault();
-}
-
-} // namespace chromeos_update_engine
diff --git a/gpio_mock_file_descriptor.h b/gpio_mock_file_descriptor.h
deleted file mode 100644
index 26b3d0c..0000000
--- a/gpio_mock_file_descriptor.h
+++ /dev/null
@@ -1,262 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROMEOS_PLATFORM_UPDATE_ENGINE_GPIO_MOCK_FILE_DESCRIPTOR_H_
-#define CHROMEOS_PLATFORM_UPDATE_ENGINE_GPIO_MOCK_FILE_DESCRIPTOR_H_
-
-#include <base/rand_util.h>
-#include <base/time/time.h>
-
-#include "update_engine/file_descriptor.h"
-#include "update_engine/gpio_handler_unittest.h"
-
-// A set of mock file descriptors used for unit-testing. All classes here
-// inherit the FileDescriptor interface.
-
-namespace chromeos_update_engine {
-
-// An abstract classs implementing a common mock infrastructure for GPIO
-// reading/writing. This includes all the inherited interface methods, and basic
-// logic to manage the opening, reading, writing and closing of GPIO files. It
-// is up to concrete implementations to manage their internal state machine and
-// update the values to be read by clients. In most cases, this amounts to
-// adding internal state and overloading the UpdateState() method to change to
-// various GPIO "registers" accordingly.
-class GpioMockFileDescriptor : public FileDescriptor {
- public:
- GpioMockFileDescriptor();
-
- // Interface methods.
- virtual bool Open(const char* path, int flags, mode_t mode);
- virtual bool Open(const char* path, int flags);
- virtual ssize_t Read(void* buf, size_t count);
- virtual ssize_t Write(const void* buf, size_t count);
- virtual bool Close();
- virtual void Reset();
- virtual bool IsSettingErrno();
- virtual bool IsOpen() {
- return (gpio_id_ < kMockGpioIdMax && gpio_subdev_ < kMockGpioSubdevMax);
- }
-
-
- // Returns true iff all file resources were freed; otherwise, will fail the
- // current test.
- virtual bool ExpectAllResourcesDeallocated();
-
- // Returns true iff all GPIOs have been restored to their default state;
- // otherwise, will fail the current test.
- virtual bool ExpectAllGpiosRestoredToDefault();
-
- // Returns true iff the number of open attempts equals the argument;
- // otherwise, will fail the current test.
- virtual bool ExpectNumOpenAttempted(unsigned count);
-
- protected:
- // A pair of write value and time at which it was written.
- struct MockGpioWriteEvent {
- MockGpioVal val;
- base::Time time;
- };
-
- // Sets the last written value and timestamp of GPIO |gpio_id|.
- inline MockGpioVal SetGpioLastWrite(MockGpioId gpio_id, MockGpioVal val,
- base::Time time) {
- gpio_last_writes_[gpio_id].time = time;
- return (gpio_last_writes_[gpio_id].val = val);
- }
-
- inline MockGpioVal SetGpioLastWrite(MockGpioId gpio_id, MockGpioVal val) {
- return SetGpioLastWrite(gpio_id, val, base::Time::Now());
- }
-
-
- // The current direction of each GPIO device. These are generally handled by
- // Write(), but can be modified by concrete implementations of this class to
- // simulate race conditions on GPIO devices.
- MockGpioDir gpio_dirs_[kMockGpioIdMax];
-
- // The current values to be read by the DUT. These can be modified by concrete
- // implementations of this class, to reflect current GPIO values.
- MockGpioVal gpio_read_vals_[kMockGpioIdMax];
-
- // The last values and time they were written by the DUT to each GPIO device.
- // These are generally handled by Write(), but can be modified by concrete
- // implementations of this class to simulate race conditions on GPIO devices.
- MockGpioWriteEvent gpio_last_writes_[kMockGpioIdMax];
-
- // Override strings for GPIO value / direction readings. Initialized to null
- // pointers by default, which means the default values will not be overridden.
- const char* override_read_gpio_val_strings_[kMockGpioValMax];
- const char* override_read_gpio_dir_strings_[kMockGpioDirMax];
-
- private:
- // GPIO subdevice identifiers.
- enum MockGpioSubdev {
- kMockGpioSubdevValue,
- kMockGpioSubdevDirection,
- kMockGpioSubdevMax // marker, do not remove!
- };
-
- // Device name prefixes of the different GPIOs.
- static const char* gpio_devname_prefixes_[kMockGpioIdMax];
-
- // Strings to be written as GPIO values, corresponding to the abstract GPIO
- // value.
- static const char* gpio_val_strings_[kMockGpioValMax];
-
- // Strings to be written as GPIO directions, corresponding to the abstract
- // GPIO direction.
- static const char* gpio_dir_strings_[kMockGpioDirMax];
-
-
- // Compare a string |buf| of length |count| that is written to a GPIO device
- // with an array of strings |strs| of length |num_strs|. Returns the index of
- // the string entry that is the same as the written string, or |num_strs| if
- // none was found. Requires that the the last character in |buf| is a newline.
- size_t DecodeGpioString(const char* buf, size_t count, const char** strs,
- size_t num_strs) const;
-
- // Decode a written GPIO value.
- inline MockGpioVal DecodeGpioVal(const char* buf, size_t count) const {
- return static_cast<MockGpioVal>(
- DecodeGpioString(buf, count, gpio_val_strings_, kMockGpioValMax));
- }
-
- // Decodes a written GPIO direction.
- inline MockGpioDir DecodeGpioDir(const char* buf, size_t count) const {
- return static_cast<MockGpioDir>(
- DecodeGpioString(buf, count, gpio_dir_strings_, kMockGpioDirMax));
- }
-
- // Simulate the Servo state transition, based on the last recorded state, the
- // time it was recorded, and the current GPIO values. This is a pure virtual
- // function that must be implemented by concrete subclasses.
- virtual void UpdateState() = 0;
-
- // The identifier of the currently accessed GPIO device.
- MockGpioId gpio_id_;
-
- // The identifier of the currently accessed GPIO sub-device.
- MockGpioSubdev gpio_subdev_;
-
- // Counter for the number of files that were opened with this interface.
- unsigned num_open_attempted_;
-};
-
-
-// A mock file descriptor that implements the GPIO test signaling protocol. In
-// doing so, it simulates the asynchronous behavior of a properly implemented
-// Servo test controller.
-class TestModeGpioMockFileDescriptor : public GpioMockFileDescriptor {
- public:
- TestModeGpioMockFileDescriptor(base::TimeDelta servo_poll_interval);
- virtual ~TestModeGpioMockFileDescriptor() {};
-
- protected:
- // The state of the Servo-side GPIO signaling protocol. These do not include
- // sub-state changes on the DUT side, which can be approximated by tracking
- // read operations but otherwise cannot be observed by an ordinary Servo.
- enum ServoState {
- kServoStateInit,
- kServoStateTriggerSent,
- kServoStateChallengeUpReceived,
- kServoStateChallengeDownReceived,
- kServoStateMax // marker, do not remove!
- };
-
- // Simulate the Servo state transition, based on the last recorded state, the
- // time it was recorded, and the current GPIO values.
- virtual void UpdateState();
-
- // The last recorded state in the GPIO protocol.
- ServoState last_state_;
-
- private:
- // Return a uniformly distributed random time delta within the Servo poll
- // interval.
- inline base::TimeDelta RandomServoPollFuzz() {
- return base::TimeDelta::FromMicroseconds(
- base::RandInt(0, servo_poll_interval_.InMicroseconds()));
- }
-
- // The Servo poll interval.
- base::TimeDelta servo_poll_interval_;
-
- // The current Servo poll fuzz, used for deciding when signals are (simulated
- // to be) sensed within the poll interval. Must be between zero and
- // servo_poll_interval_.
- base::TimeDelta curr_servo_poll_fuzz_;
-};
-
-
-// A mock file descriptor that implements GPIO feedback when not conneced to a
-// Servo, on boards that include a pull-up resistor wiring for GPIOs. This is
-// the typical mode of operations for Chromebooks out in the field, and we need
-// to make sure that the client is not made to believe that it is in test mode.
-class NormalModeGpioMockFileDescriptor : public GpioMockFileDescriptor {
- private:
- // This is a no-op, as there's no Servo connected.
- virtual void UpdateState() {};
-};
-
-// A mock file descriptor that implements GPIOs that are not pulled-up by
-// default, and whose idle reading might be zero. We've seen this problem on
-// Lumpy/Stumpy and need to make sure that the protocol doesn't allow these
-// boards to go into test mode without actually being told so by a Servo.
-class NonPulledUpNormalModeGpioMockFileDescriptor
- : public GpioMockFileDescriptor {
- private:
- // Set the default value of dut_flaga to "down".
- virtual void UpdateState() {
- gpio_read_vals_[kMockGpioIdDutflaga] = kMockGpioValDown;
- }
-};
-
-// A mock file descriptor that implements a bogus GPIO feedback. This includes
-// flipping GPIO directions, invalid value readings, and I/O errors on various
-// file operations. All of these instances must be ruled out by the protocol,
-// resulting in normal mode operation.
-class ErrorNormalModeGpioMockFileDescriptor :
- public TestModeGpioMockFileDescriptor {
- public:
- enum GpioError {
- kGpioErrorFlipInputDir,
- kGpioErrorReadInvalidVal,
- kGpioErrorReadInvalidDir,
- kGpioErrorFailFileOpen,
- kGpioErrorFailFileRead,
- kGpioErrorFailFileWrite,
- kGpioErrorFailFileClose,
- };
-
- ErrorNormalModeGpioMockFileDescriptor(base::TimeDelta servo_poll_interval,
- GpioError error);
- virtual ~ErrorNormalModeGpioMockFileDescriptor() {};
-
- // Wrapper methods for the respectively inherited ones, which can fail the
- // call as part of a test.
- virtual bool Open(const char* path, int flags, mode_t mode);
- virtual ssize_t Read(void* buf, size_t count);
- virtual ssize_t Write(const void* buf, size_t count);
- virtual bool Close();
-
- // Wrapper which restores all state we might have tampered with.
- virtual bool ExpectAllGpiosRestoredToDefault();
-
- private:
- // Wraps the ordinary test mode servo simulation with an error injecting
- // behavior, which corresponds to the requested type of error.
- virtual void UpdateState();
-
- // The GPIO error to be injected into the protocol.
- GpioError error_;
-
- // A flag denoting whether the direction of dut_flaga was already maliciously
- // flipped.
- bool is_dutflaga_dir_flipped_;
-};
-
-} // namespace chromeos_update_engine
-
-#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_GPIO_MOCK_FILE_DESCRIPTOR_H_
diff --git a/gpio_mock_udev_interface.cc b/gpio_mock_udev_interface.cc
deleted file mode 100644
index 071ff41..0000000
--- a/gpio_mock_udev_interface.cc
+++ /dev/null
@@ -1,382 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "update_engine/gpio_mock_udev_interface.h"
-
-#include <string>
-
-#include <base/strings/stringprintf.h>
-#include <gtest/gtest.h>
-
-#include "update_engine/gpio_handler_unittest.h"
-
-namespace chromeos_update_engine {
-
-const char* StandardGpioMockUdevInterface::kUdevGpioSubsystem = "gpio";
-const char* StandardGpioMockUdevInterface::kUdevGpioChipSysname = "gpiochip*";
-
-const StandardGpioMockUdevInterface::GpioDescriptor
- StandardGpioMockUdevInterface::gpio_descriptors_[kMockGpioIdMax] = {
- { "ID_GPIO_DUTFLAGA", MOCK_DUTFLAGA_GPIO_ID },
- { "ID_GPIO_DUTFLAGB", MOCK_DUTFLAGB_GPIO_ID },
-};
-
-const char* StandardGpioMockUdevInterface::enum_gpio_chip_dev_list_[] = {
- "gpiochip" MOCK_GPIO_CHIP_ID,
- NULL
-};
-const char* StandardGpioMockUdevInterface::enum_dutflaga_gpio_dev_list_[] = {
- "gpio" MOCK_DUTFLAGA_GPIO_ID,
- NULL
-};
-const char* StandardGpioMockUdevInterface::enum_dutflagb_gpio_dev_list_[] = {
- "gpio" MOCK_DUTFLAGB_GPIO_ID,
- NULL
-};
-
-StandardGpioMockUdevInterface::StandardGpioMockUdevInterface()
- : udev_id_(0), udev_enum_id_(0), num_discovered_(0) {
- std::fill_n(used_udev_ids_, MAX_UDEV_OBJECTS, false);
- std::fill_n(used_udev_enum_ids_, MAX_UDEV_ENUM_OBJECTS, false);
-
- gpio_chip_dev_ = (MockDevice) {
- MOCK_SYSFS_PREFIX "/gpiochip" MOCK_GPIO_CHIP_ID,
- gpio_descriptors_, kMockGpioIdMax, false, false
- };
- dutflaga_gpio_dev_ = (MockDevice) {
- MOCK_SYSFS_PREFIX "/gpio" MOCK_DUTFLAGA_GPIO_ID, NULL, 0, true, false
- };
- dutflagb_gpio_dev_ = (MockDevice) {
- MOCK_SYSFS_PREFIX "/gpio" MOCK_DUTFLAGB_GPIO_ID, NULL, 0, true, false
- };
-}
-
-// Device lists are simply null-terminated arrays of strings.
-const char* StandardGpioMockUdevInterface::ListEntryGetName(
- struct udev_list_entry* list_entry) {
- const char** mock_list_entry = reinterpret_cast<const char**>(list_entry);
- EXPECT_TRUE(mock_list_entry && *mock_list_entry);
- if (!mock_list_entry)
- return NULL;
- // The mock list entry is the name string itself...
- return *mock_list_entry;
-}
-
-struct udev_list_entry* StandardGpioMockUdevInterface::ListEntryGetNext(
- struct udev_list_entry* list_entry) {
- char** mock_list_entry = reinterpret_cast<char**>(list_entry);
- EXPECT_TRUE(mock_list_entry && *mock_list_entry);
- if (!mock_list_entry)
- return NULL;
- // Advance to the next element in the array.
- mock_list_entry++;
- return (*mock_list_entry ?
- reinterpret_cast<struct udev_list_entry*>(mock_list_entry) : NULL);
-}
-
-struct udev_device* StandardGpioMockUdevInterface::DeviceNewFromSyspath(
- struct udev* udev, const char* syspath) {
- const size_t udev_id = UdevToId(udev);
- if (udev_id >= MAX_UDEV_OBJECTS)
- return NULL;
- MockDevice* mock_dev;
-
- // Generate the desired mock device based on the provided syspath.
- if (!strcmp(syspath, enum_gpio_chip_dev_list_[0])) {
- mock_dev = const_cast<MockDevice*>(&gpio_chip_dev_);
- } else if (!strcmp(syspath, enum_dutflaga_gpio_dev_list_[0])) {
- mock_dev = const_cast<MockDevice*>(&dutflaga_gpio_dev_);
- } else if (!strcmp(syspath, enum_dutflagb_gpio_dev_list_[0])) {
- mock_dev = const_cast<MockDevice*>(&dutflagb_gpio_dev_);
- } else {
- ADD_FAILURE();
- return NULL;
- }
-
- EXPECT_FALSE(mock_dev->is_used);
- if (mock_dev->is_used)
- return NULL;
- mock_dev->is_used = true;
-
- return reinterpret_cast<struct udev_device*>(mock_dev);
-}
-
-const char* StandardGpioMockUdevInterface::DeviceGetPropertyValue(
- struct udev_device* udev_device, const char* key) {
- const MockDevice* mock_dev = UdevDeviceToMock(udev_device);
- EXPECT_TRUE(mock_dev->properties);
- if (!mock_dev->properties)
- return NULL;
- for (size_t i = 0; i < mock_dev->num_properties; i++)
- if (!strcmp(key, mock_dev->properties[i].property))
- return mock_dev->properties[i].value;
- return NULL;
-}
-
-const char* StandardGpioMockUdevInterface::DeviceGetSyspath(
- struct udev_device* udev_device) {
- const MockDevice* mock_dev = UdevDeviceToMock(udev_device);
- if (mock_dev->is_gpio)
- num_discovered_++;
- return mock_dev->syspath;
-}
-
-void StandardGpioMockUdevInterface::DeviceUnref(
- struct udev_device* udev_device) {
- MockDevice* mock_dev = UdevDeviceToMock(udev_device);
- mock_dev->is_used = false;
-}
-
-struct udev_enumerate* StandardGpioMockUdevInterface::EnumerateNew(
- struct udev* udev) {
- const size_t udev_id = UdevToId(udev);
- if (udev_id >= MAX_UDEV_OBJECTS)
- return NULL;
- // A new enumeration "pointer" is cast for an integer identifier.
- EXPECT_LT(udev_enum_id_, MAX_UDEV_ENUM_OBJECTS);
- if (udev_enum_id_ >= MAX_UDEV_ENUM_OBJECTS)
- return NULL;
- used_udev_enum_ids_[udev_enum_id_] = true;
- return reinterpret_cast<struct udev_enumerate*>(++udev_enum_id_);
-}
-
-int StandardGpioMockUdevInterface::EnumerateAddMatchSubsystem(
- struct udev_enumerate* udev_enum, const char* subsystem) {
- const size_t udev_enum_id = UdevEnumToId(udev_enum);
- if (udev_enum_id >= MAX_UDEV_ENUM_OBJECTS)
- return -1;
-
- // Ensure client is correctly requesting the GPIO subsystem.
- EXPECT_STREQ(subsystem, kUdevGpioSubsystem);
- if (strcmp(subsystem, kUdevGpioSubsystem))
- return -1;
-
- return 0;
-}
-
-int StandardGpioMockUdevInterface::EnumerateAddMatchSysname(
- struct udev_enumerate* udev_enum, const char* sysname) {
- const size_t udev_enum_id = UdevEnumToId(udev_enum);
- if (udev_enum_id >= MAX_UDEV_ENUM_OBJECTS)
- return -1;
-
- // Ensure client is requesting the correct sysnamem, depending on the correct
- // phase in the detection process.
- switch (udev_enum_id) {
- case 0: // looking for a GPIO chip
- EXPECT_STREQ(sysname, kUdevGpioChipSysname);
- if (strcmp(sysname, kUdevGpioChipSysname))
- return -1;
- break;
- case 1: // looking for dut_flaga/b
- case 2: {
- const int gpio_id = udev_enum_id - 1;
- const std::string gpio_pattern =
- base::StringPrintf("*%s", gpio_descriptors_[gpio_id].value);
- EXPECT_STREQ(sysname, gpio_pattern.c_str());
- if (strcmp(sysname, gpio_pattern.c_str()))
- return -1;
- break;
- }
- default:
- ADD_FAILURE(); // can't get here
- return -1;
- }
-
- return 0;
-}
-
-int StandardGpioMockUdevInterface::EnumerateScanDevices(
- struct udev_enumerate* udev_enum) {
- const size_t udev_enum_id = UdevEnumToId(udev_enum);
- if (udev_enum_id >= MAX_UDEV_ENUM_OBJECTS)
- return -1;
- return 0; // nothing to do, really
-}
-
-struct udev_list_entry* StandardGpioMockUdevInterface::EnumerateGetListEntry(
- struct udev_enumerate* udev_enum) {
- const size_t udev_enum_id = UdevEnumToId(udev_enum);
- if (udev_enum_id >= MAX_UDEV_ENUM_OBJECTS)
- return NULL;
-
- // Return a list of devices corresponding to the provided enumeration.
- switch (udev_enum_id) {
- case 0:
- return reinterpret_cast<struct udev_list_entry*>(
- enum_gpio_chip_dev_list_);
- case 1:
- return reinterpret_cast<struct udev_list_entry*>(
- enum_dutflaga_gpio_dev_list_);
- case 2:
- return reinterpret_cast<struct udev_list_entry*>(
- enum_dutflagb_gpio_dev_list_);
- }
-
- ADD_FAILURE(); // can't get here
- return NULL;
-}
-
-void StandardGpioMockUdevInterface::EnumerateUnref(
- struct udev_enumerate* udev_enum) {
- const size_t udev_enum_id = UdevEnumToId(udev_enum);
- if (udev_enum_id >= MAX_UDEV_ENUM_OBJECTS)
- return;
- used_udev_enum_ids_[udev_enum_id] = false; // make sure it's freed just once
-}
-
-struct udev* StandardGpioMockUdevInterface::New() {
- // The returned "pointer" is cast from an integer identifier.
- EXPECT_LT(udev_id_, MAX_UDEV_OBJECTS);
- if (udev_id_ >= MAX_UDEV_OBJECTS)
- return NULL;
- used_udev_ids_[udev_id_] = true;
- return reinterpret_cast<struct udev*>(++udev_id_);
-}
-
-void StandardGpioMockUdevInterface::Unref(struct udev* udev) {
- // Convert to object identifier, ensuring the object has been "allocated".
- const size_t udev_id = UdevToId(udev);
- if (udev_id >= MAX_UDEV_OBJECTS)
- return;
- used_udev_ids_[udev_id] = false; // make sure it's freed just once
-}
-
-void StandardGpioMockUdevInterface::ExpectAllResourcesDeallocated() const {
- // Make sure that all handles were released.
- for (size_t i = 0; i < MAX_UDEV_OBJECTS; i++)
- EXPECT_FALSE(used_udev_ids_[i]);
- for (size_t i = 0; i < MAX_UDEV_ENUM_OBJECTS; i++)
- EXPECT_FALSE(used_udev_enum_ids_[i]);
- EXPECT_FALSE(gpio_chip_dev_.is_used);
- EXPECT_FALSE(dutflaga_gpio_dev_.is_used);
- EXPECT_FALSE(dutflagb_gpio_dev_.is_used);
-}
-
-void StandardGpioMockUdevInterface::ExpectDiscoverySuccess() const {
- EXPECT_EQ(num_discovered_, kMockGpioIdMax);
-}
-
-void StandardGpioMockUdevInterface::ExpectDiscoveryFail() const {
- EXPECT_LT(num_discovered_, kMockGpioIdMax);
-}
-
-StandardGpioMockUdevInterface::MockDevice*
-StandardGpioMockUdevInterface::UdevDeviceToMock(
- struct udev_device* udev_dev) const {
- EXPECT_TRUE(udev_dev);
- if (!udev_dev)
- return NULL;
- MockDevice* mock_dev = reinterpret_cast<MockDevice*>(udev_dev);
- EXPECT_TRUE(mock_dev->is_used);
- if (!mock_dev->is_used)
- return NULL;
- return mock_dev;
-}
-
-size_t StandardGpioMockUdevInterface::UdevEnumToId(
- struct udev_enumerate* udev_enum) const {
- EXPECT_TRUE(udev_enum);
- size_t udev_enum_id = reinterpret_cast<size_t>(udev_enum) - 1;
- EXPECT_LT(udev_enum_id, MAX_UDEV_ENUM_OBJECTS);
- EXPECT_TRUE(used_udev_enum_ids_[udev_enum_id]);
- if (!(udev_enum && udev_enum_id < MAX_UDEV_ENUM_OBJECTS &&
- used_udev_enum_ids_[udev_enum_id]))
- return MAX_UDEV_ENUM_OBJECTS;
- return udev_enum_id;
-}
-
-size_t StandardGpioMockUdevInterface::UdevToId(struct udev* udev) const {
- EXPECT_TRUE(udev);
- size_t udev_id = reinterpret_cast<size_t>(udev) - 1;
- EXPECT_LT(udev_id, MAX_UDEV_OBJECTS);
- EXPECT_TRUE(used_udev_ids_[udev_id]);
- if (!(udev && udev_id < MAX_UDEV_OBJECTS && used_udev_ids_[udev_id]))
- return MAX_UDEV_OBJECTS;
- return udev_id;
-}
-
-#define MOCK_GPIO_CHIP1_ID "200"
-#define MOCK_GPIO_CHIP2_ID "201"
-
-const char* MultiChipGpioMockUdevInterface::enum_gpio_chip_dev_list_[] = {
- "gpiochip" MOCK_GPIO_CHIP1_ID,
- "gpiochip" MOCK_GPIO_CHIP2_ID,
- NULL
-};
-
-MultiChipGpioMockUdevInterface::MultiChipGpioMockUdevInterface() {
- gpio_chip1_dev_ = (MockDevice) {
- MOCK_SYSFS_PREFIX "/gpiochip" MOCK_GPIO_CHIP1_ID,
- gpio_descriptors_, kMockGpioIdMax, false, false
- };
- gpio_chip2_dev_ = (MockDevice) {
- MOCK_SYSFS_PREFIX "/gpiochip" MOCK_GPIO_CHIP2_ID,
- gpio_descriptors_, kMockGpioIdMax, false, false
- };
-}
-
-struct udev_device* MultiChipGpioMockUdevInterface::DeviceNewFromSyspath(
- struct udev* udev, const char* syspath) {
- const size_t udev_id = UdevToId(udev);
- if (udev_id >= MAX_UDEV_OBJECTS)
- return NULL;
- MockDevice* mock_dev;
-
- // Generate the desired mock device based on the provided syspath.
- if (!strcmp(syspath, enum_gpio_chip_dev_list_[0])) {
- mock_dev = const_cast<MockDevice*>(&gpio_chip1_dev_);
- } else if (!strcmp(syspath, enum_gpio_chip_dev_list_[1])) {
- mock_dev = const_cast<MockDevice*>(&gpio_chip2_dev_);
- } else if (!strcmp(syspath, enum_dutflaga_gpio_dev_list_[0])) {
- mock_dev = const_cast<MockDevice*>(&dutflaga_gpio_dev_);
- } else if (!strcmp(syspath, enum_dutflagb_gpio_dev_list_[0])) {
- mock_dev = const_cast<MockDevice*>(&dutflagb_gpio_dev_);
- } else {
- ADD_FAILURE();
- return NULL;
- }
-
- EXPECT_FALSE(mock_dev->is_used);
- if (mock_dev->is_used)
- return NULL;
- mock_dev->is_used = true;
-
- return reinterpret_cast<struct udev_device*>(mock_dev);
-}
-
-struct udev_list_entry* MultiChipGpioMockUdevInterface::EnumerateGetListEntry(
- struct udev_enumerate* udev_enum) {
- const size_t udev_enum_id = UdevEnumToId(udev_enum);
-
- // Return a list of devices corresponding to the provided enumeration.
- switch (udev_enum_id) {
- case 0:
- return reinterpret_cast<struct udev_list_entry*>(
- enum_gpio_chip_dev_list_);
- case 1:
- return reinterpret_cast<struct udev_list_entry*>(
- enum_dutflaga_gpio_dev_list_);
- case 2:
- return reinterpret_cast<struct udev_list_entry*>(
- enum_dutflagb_gpio_dev_list_);
- }
-
- ADD_FAILURE(); // can't get here
- return NULL;
-}
-
-
-void FailInitGpioMockUdevInterface::ExpectNumInitAttempts(
- unsigned count) const {
- EXPECT_EQ(num_init_attempts_, count);
-}
-
-struct udev* FailInitGpioMockUdevInterface::New() {
- // Increment udev init attempt counter, failing the first attempt.
- num_init_attempts_++;
- return num_init_attempts_ == 1 ? NULL : StandardGpioMockUdevInterface::New();
-}
-
-} // namespace chromeos_update_engine
diff --git a/gpio_mock_udev_interface.h b/gpio_mock_udev_interface.h
deleted file mode 100644
index 759fa78..0000000
--- a/gpio_mock_udev_interface.h
+++ /dev/null
@@ -1,149 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROMEOS_PLATFORM_UPDATE_ENGINE_GPIO_MOCK_UDEV_INTERFACE_H_
-#define CHROMEOS_PLATFORM_UPDATE_ENGINE_GPIO_MOCK_UDEV_INTERFACE_H_
-
-#include "update_engine/gpio_handler.h"
-#include "update_engine/udev_interface.h"
-
-// A set of mock udev interfaces for unit testing of GPIO handler.
-
-// Constant defining number of allowable mock udev objects.
-#define MAX_UDEV_OBJECTS 1
-#define MAX_UDEV_ENUM_OBJECTS 3
-
-namespace chromeos_update_engine {
-
-// An abstract class providing some diagnostic methods for testing.
-class GpioMockUdevInterface : public UdevInterface {
- public:
- // Asserts that all resources have been properly deallocated.
- virtual void ExpectAllResourcesDeallocated() const = 0;
- // Asserts the the udev client has successfully discovered the syspath of the
- // GPIO signals.
- virtual void ExpectDiscoverySuccess() const = 0;
- // Asserts the opposite.
- virtual void ExpectDiscoveryFail() const = 0;
-};
-
-class StandardGpioMockUdevInterface : public GpioMockUdevInterface {
- public:
- // Default constructor.
- StandardGpioMockUdevInterface();
-
- // Inherited interface methods.
- virtual const char* ListEntryGetName(struct udev_list_entry* list_entry);
- virtual udev_list_entry* ListEntryGetNext(struct udev_list_entry* list_entry);
-
- virtual struct udev_device* DeviceNewFromSyspath(struct udev* udev,
- const char* syspath);
- virtual const char* DeviceGetPropertyValue(struct udev_device* udev_device,
- const char* key);
- virtual const char* DeviceGetSyspath(struct udev_device* udev_device);
- virtual void DeviceUnref(struct udev_device* udev_device);
-
- virtual struct udev_enumerate* EnumerateNew(struct udev* udev);
- virtual int EnumerateAddMatchSubsystem(struct udev_enumerate* udev_enum,
- const char* subsystem);
- virtual int EnumerateAddMatchSysname(struct udev_enumerate* udev_enum,
- const char* sysname);
- virtual int EnumerateScanDevices(struct udev_enumerate* udev_enum);
- virtual struct udev_list_entry* EnumerateGetListEntry(
- struct udev_enumerate* udev_enum);
- virtual void EnumerateUnref(struct udev_enumerate* udev_enum);
-
- virtual struct udev* New();
- virtual void Unref(struct udev* udev);
-
- virtual void ExpectAllResourcesDeallocated() const;
- virtual void ExpectDiscoverySuccess() const;
- virtual void ExpectDiscoveryFail() const;
-
- protected:
- // Some constants.
- static const char* kUdevGpioSubsystem;
- static const char* kUdevGpioChipSysname;
- static const char* kMockGpioSysfsRoot;
-
- // GPIO descriptor lookup.
- struct GpioDescriptor {
- const char* property;
- const char* value;
- };
- static const GpioDescriptor gpio_descriptors_[];
-
- // Numeric identifiers for new udev and enumerate objects.
- size_t udev_id_;
- size_t udev_enum_id_;
-
- // Null-terminated lists of devices returned by various enumerations.
- static const char* enum_gpio_chip_dev_list_[];
- static const char* enum_dutflaga_gpio_dev_list_[];
- static const char* enum_dutflagb_gpio_dev_list_[];
-
- // Mock devices to be used during GPIO discovery. These contain the syspath
- // and a set of properties that the device may contain.
- struct MockDevice {
- const char* syspath;
- const GpioDescriptor* properties;
- size_t num_properties;
- bool is_gpio;
- bool is_used;
- };
- MockDevice gpio_chip_dev_;
- MockDevice dutflaga_gpio_dev_;
- MockDevice dutflagb_gpio_dev_;
-
- // Tracking active mock object handles.
- bool used_udev_ids_[MAX_UDEV_OBJECTS];
- bool used_udev_enum_ids_[MAX_UDEV_ENUM_OBJECTS];
-
- // Track discovery progress of GPIO signals.
- unsigned num_discovered_;
-
- // Convert mock udev handles into internal handles, with sanity checks.
- MockDevice* UdevDeviceToMock(struct udev_device* udev_dev) const;
- size_t UdevEnumToId(struct udev_enumerate* udev_enum) const;
- size_t UdevToId(struct udev* udev) const;
-};
-
-class MultiChipGpioMockUdevInterface : public StandardGpioMockUdevInterface {
- public:
- // Default constructor.
- MultiChipGpioMockUdevInterface();
-
- protected:
- virtual struct udev_device* DeviceNewFromSyspath(struct udev* udev,
- const char* syspath);
- virtual struct udev_list_entry* EnumerateGetListEntry(
- struct udev_enumerate* udev_enum);
-
- // Null-terminated lists of devices returned by various enumerations.
- static const char* enum_gpio_chip_dev_list_[];
-
- // Mock devices to be used during GPIO discovery. These contain the syspath
- // and a set of properties that the device may contain.
- MockDevice gpio_chip1_dev_;
- MockDevice gpio_chip2_dev_;
-};
-
-// A udev mock that fails to provide constructs for proper GPIO initialization.
-class FailInitGpioMockUdevInterface : public StandardGpioMockUdevInterface {
- public:
- // Default constructor.
- FailInitGpioMockUdevInterface() : num_init_attempts_(0) {}
-
- virtual void ExpectNumInitAttempts(unsigned count) const;
-
- protected:
- virtual struct udev* New();
-
- private:
- unsigned num_init_attempts_;
-};
-
-} // namespace chromeos_update_engine
-
-#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_GPIO_MOCK_UDEV_INTERFACE_H_
diff --git a/http_fetcher_unittest.cc b/http_fetcher_unittest.cc
index dc00139..74c6a16 100644
--- a/http_fetcher_unittest.cc
+++ b/http_fetcher_unittest.cc
@@ -268,7 +268,7 @@
proxy_resolver_.set_num_proxies(num_proxies);
LibcurlHttpFetcher *ret = new
LibcurlHttpFetcher(reinterpret_cast<ProxyResolver*>(&proxy_resolver_),
- &fake_system_state_, false);
+ &fake_system_state_);
// Speed up test execution.
ret->set_idle_seconds(1);
ret->set_retry_seconds(1);
@@ -317,7 +317,7 @@
reinterpret_cast<ProxyResolver*>(&proxy_resolver_);
MultiRangeHttpFetcher *ret =
new MultiRangeHttpFetcher(
- new LibcurlHttpFetcher(resolver, &fake_system_state_, false));
+ new LibcurlHttpFetcher(resolver, &fake_system_state_));
ret->ClearRanges();
ret->AddRange(0);
// Speed up test execution.
diff --git a/libcurl_http_fetcher.cc b/libcurl_http_fetcher.cc
index 886a446..2c3fd4d 100644
--- a/libcurl_http_fetcher.cc
+++ b/libcurl_http_fetcher.cc
@@ -192,16 +192,16 @@
kDownloadMaxRedirects),
CURLE_OK);
- // If we are running in test mode or using a dev/test build, then lock down
- // the appropriate curl options for HTTP or HTTPS depending on the url.
- if (!is_test_mode_ && GetSystemState()->hardware()->IsOfficialBuild()) {
+ // Lock down the appropriate curl options for HTTP or HTTPS depending on
+ // the url.
+ if (GetSystemState()->hardware()->IsOfficialBuild()) {
if (StartsWithASCII(url_to_use, "http://", false))
SetCurlOptionsForHttp();
else
SetCurlOptionsForHttps();
} else {
- LOG(INFO) << "Not setting http(s) curl options because we are in "
- << "test mode or running a dev/test image";
+ LOG(INFO) << "Not setting http(s) curl options because we are "
+ << "running a dev/test image";
}
CHECK_EQ(curl_multi_add_handle(curl_multi_handle_, curl_handle_), CURLM_OK);
diff --git a/libcurl_http_fetcher.h b/libcurl_http_fetcher.h
index a59a56e..a3b7919 100644
--- a/libcurl_http_fetcher.h
+++ b/libcurl_http_fetcher.h
@@ -28,8 +28,7 @@
class LibcurlHttpFetcher : public HttpFetcher {
public:
LibcurlHttpFetcher(ProxyResolver* proxy_resolver,
- SystemState* system_state,
- bool is_test_mode)
+ SystemState* system_state)
: HttpFetcher(proxy_resolver, system_state),
curl_multi_handle_(NULL),
curl_handle_(NULL),
@@ -50,7 +49,6 @@
sent_byte_(false),
terminate_requested_(false),
check_certificate_(CertificateChecker::kNone),
- is_test_mode_(is_test_mode),
low_speed_limit_bps_(kDownloadLowSpeedLimitBps),
low_speed_time_seconds_(kDownloadLowSpeedTimeSeconds),
connect_timeout_seconds_(kDownloadConnectTimeoutSeconds) {
@@ -276,9 +274,6 @@
// this should be kNone.
CertificateChecker::ServerToCheck check_certificate_;
- // If true, utilizes a relaxed test mode fetch logic. False by default.
- bool is_test_mode_;
-
int low_speed_limit_bps_;
int low_speed_time_seconds_;
int connect_timeout_seconds_;
diff --git a/main.cc b/main.cc
index 9d2a869..ccf4efa 100644
--- a/main.cc
+++ b/main.cc
@@ -175,9 +175,7 @@
GMainLoop* loop = g_main_loop_new(g_main_context_default(), FALSE);
chromeos_update_engine::RealSystemState real_system_state;
- // TODO(garnold) s/false/true/ once we decide to activate actual GPIO-based
- // protocol for testing of MP-signed images (chromium-os:25400).
- LOG_IF(ERROR, !real_system_state.Initialize(false))
+ LOG_IF(ERROR, !real_system_state.Initialize())
<< "Failed to initialize system state.";
chromeos_update_engine::UpdateAttempter *update_attempter =
real_system_state.update_attempter();
diff --git a/mock_gpio_handler.h b/mock_gpio_handler.h
deleted file mode 100644
index 985f138..0000000
--- a/mock_gpio_handler.h
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROMEOS_PLATFORM_UPDATE_ENGINE_MOCK_GPIO_HANDLER_H_
-#define CHROMEOS_PLATFORM_UPDATE_ENGINE_MOCK_GPIO_HANDLER_H_
-
-#include "gmock/gmock.h"
-#include "update_engine/gpio_handler.h"
-
-namespace chromeos_update_engine {
-
-class MockGpioHandler: public GpioHandler {
- public:
- MOCK_METHOD0(IsTestModeSignaled, bool());
-};
-
-} // namespace chromeos_update_engine
-
-#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_MOCK_GPIO_HANDLER_H_
diff --git a/real_system_state.cc b/real_system_state.cc
index 7fca0ca..10b66f3 100644
--- a/real_system_state.cc
+++ b/real_system_state.cc
@@ -19,7 +19,7 @@
request_params_(this),
system_rebooted_(false) {}
-bool RealSystemState::Initialize(bool enable_gpio) {
+bool RealSystemState::Initialize() {
metrics_lib_.Init();
if (!prefs_.Init(base::FilePath(kPrefsDirectory))) {
@@ -59,22 +59,6 @@
return false;
}
- // Initialize the GPIO handler as instructed.
- if (enable_gpio) {
- // A real GPIO handler. Defer GPIO discovery to ensure the udev has ample
- // time to export the devices. Also require that test mode is physically
- // queried at most once and the result cached, for a more consistent update
- // behavior.
- udev_iface_.reset(new StandardUdevInterface());
- file_descriptor_.reset(new EintrSafeFileDescriptor());
- gpio_handler_.reset(new StandardGpioHandler(udev_iface_.get(),
- file_descriptor_.get(),
- true, true));
- } else {
- // A no-op GPIO handler, always indicating a non-test mode.
- gpio_handler_.reset(new NoopGpioHandler(false));
- }
-
// Initialize the update attempter.
update_attempter_.Init();
diff --git a/real_system_state.h b/real_system_state.h
index aac7efc..28ba254 100644
--- a/real_system_state.h
+++ b/real_system_state.h
@@ -12,7 +12,6 @@
#include "update_engine/clock.h"
#include "update_engine/connection_manager.h"
-#include "update_engine/gpio_handler.h"
#include "update_engine/hardware.h"
#include "update_engine/p2p_manager.h"
#include "update_engine/payload_state.h"
@@ -33,7 +32,7 @@
// Initializes and sets systems objects that require an initialization
// separately from construction. Returns |true| on success.
- bool Initialize(bool enable_gpio);
+ bool Initialize();
virtual inline void set_device_policy(
const policy::DevicePolicy* device_policy) override {
@@ -72,10 +71,6 @@
return &payload_state_;
}
- virtual inline GpioHandler* gpio_handler() override {
- return gpio_handler_.get();
- }
-
virtual inline UpdateAttempter* update_attempter() override {
return &update_attempter_;
}
@@ -124,13 +119,6 @@
// response, URL, backoff states.
PayloadState payload_state_;
- // Pointer to a GPIO handler and other needed modules (note that the order of
- // declaration significant for destruction, as the latter depends on the
- // former).
- scoped_ptr<UdevInterface> udev_iface_;
- scoped_ptr<FileDescriptor> file_descriptor_;
- scoped_ptr<GpioHandler> gpio_handler_;
-
// The dbus object used to initialize the update attempter.
RealDBusWrapper dbus_;
diff --git a/system_state.h b/system_state.h
index de098ee..a9e3c02 100644
--- a/system_state.h
+++ b/system_state.h
@@ -74,9 +74,6 @@
// Gets the interface for the payload state object.
virtual PayloadStateInterface* payload_state() = 0;
- // Returns a pointer to the GPIO handler.
- virtual GpioHandler* gpio_handler() = 0;
-
// Returns a pointer to the update attempter object.
virtual UpdateAttempter* update_attempter() = 0;
diff --git a/udev_interface.h b/udev_interface.h
deleted file mode 100644
index 4b45d4c..0000000
--- a/udev_interface.h
+++ /dev/null
@@ -1,196 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROMEOS_PLATFORM_UPDATE_ENGINE_UDEV_INTERFACE_H_
-#define CHROMEOS_PLATFORM_UPDATE_ENGINE_UDEV_INTERFACE_H_
-
-#include <libudev.h>
-
-#include "update_engine/utils.h"
-
-// An interface for libudev calls, allowing to easily mock it.
-
-namespace chromeos_update_engine {
-
-// An interface for libudev methods that are being used in update engine.
-//
-// TODO(garnold) As is, this is a pretty lame indirection layer that otherwise
-// does not provide any better abstraction than the existing libudev API. Done
-// properly, we should replace it with encapsulated udev, enumerate and device
-// objects, and hide initialization, reference handling and iterators in ways
-// more appropriate to an object-oriented setting...
-class UdevInterface {
- public:
- virtual ~UdevInterface() {}
-
- // Interfaces for various udev closers. All of these are merely containers for
- // a single pointer to some udev handle, which invoke the provided interface's
- // unref method and nullify the handle upon destruction. It should suffice for
- // derivative (concrete) interfaces to implement the various unref methods to
- // fit their needs, making these closers behave as expected.
- class UdevCloser {
- public:
- explicit UdevCloser(UdevInterface* udev_iface, struct udev** udev_p)
- : udev_iface_(udev_iface), udev_p_(udev_p) {
- CHECK(udev_iface && udev_p);
- }
- virtual ~UdevCloser() {
- if (*udev_p_) {
- udev_iface_->Unref(*udev_p_);
- *udev_p_ = NULL;
- }
- }
- protected:
- UdevInterface* udev_iface_;
- struct udev** udev_p_;
- private:
- DISALLOW_IMPLICIT_CONSTRUCTORS(UdevCloser);
- };
-
- class UdevEnumerateCloser {
- public:
- explicit UdevEnumerateCloser(UdevInterface* udev_iface,
- struct udev_enumerate** udev_enum_p)
- : udev_iface_(udev_iface), udev_enum_p_(udev_enum_p) {
- CHECK(udev_iface && udev_enum_p);
- }
- virtual ~UdevEnumerateCloser() {
- if (*udev_enum_p_) {
- udev_iface_->EnumerateUnref(*udev_enum_p_);
- *udev_enum_p_ = NULL;
- }
- }
- protected:
- UdevInterface* udev_iface_;
- struct udev_enumerate** udev_enum_p_;
- private:
- DISALLOW_IMPLICIT_CONSTRUCTORS(UdevEnumerateCloser);
- };
-
- class UdevDeviceCloser {
- public:
- explicit UdevDeviceCloser(UdevInterface* udev_iface,
- struct udev_device** udev_dev_p)
- : udev_iface_(udev_iface), udev_dev_p_(udev_dev_p) {
- CHECK(udev_iface && udev_dev_p);
- }
- virtual ~UdevDeviceCloser() {
- if (*udev_dev_p_) {
- udev_iface_->DeviceUnref(*udev_dev_p_);
- *udev_dev_p_ = NULL;
- }
- }
- protected:
- UdevInterface* udev_iface_;
- struct udev_device** udev_dev_p_;
- private:
- DISALLOW_IMPLICIT_CONSTRUCTORS(UdevDeviceCloser);
- };
-
- virtual UdevCloser* NewUdevCloser(struct udev** udev_p) {
- return new UdevCloser(this, udev_p);
- }
- virtual UdevEnumerateCloser* NewUdevEnumerateCloser(
- struct udev_enumerate** udev_enum_p) {
- return new UdevEnumerateCloser(this, udev_enum_p);
- }
- virtual UdevDeviceCloser* NewUdevDeviceCloser(
- struct udev_device** udev_dev_p) {
- return new UdevDeviceCloser(this, udev_dev_p);
- }
-
- // Lists.
- virtual const char* ListEntryGetName(struct udev_list_entry* list_entry) = 0;
- virtual udev_list_entry* ListEntryGetNext(
- struct udev_list_entry* list_entry) = 0;
-
- // Device methods.
- virtual struct udev_device* DeviceNewFromSyspath(
- struct udev* udev,
- const char* syspath) = 0;
- virtual const char* DeviceGetPropertyValue(struct udev_device* udev_device,
- const char* key) = 0;
- virtual const char* DeviceGetSyspath(
- struct udev_device* udev_device) = 0;
- virtual void DeviceUnref(struct udev_device* udev_device) = 0;
-
- // Enumerate methods.
- virtual struct udev_enumerate* EnumerateNew(struct udev* udev) = 0;
- virtual int EnumerateAddMatchSubsystem(struct udev_enumerate* udev_enum,
- const char* subsystem) = 0;
- virtual int EnumerateAddMatchSysname(struct udev_enumerate* udev_enum,
- const char* sysname) = 0;
- virtual int EnumerateScanDevices(struct udev_enumerate* udev_enum) = 0;
- virtual struct udev_list_entry* EnumerateGetListEntry(
- struct udev_enumerate* udev_enum) = 0;
- virtual void EnumerateUnref(struct udev_enumerate* udev_enum) = 0;
-
- // Udev instance methods.
- virtual struct udev* New() = 0;
- virtual void Unref(struct udev* udev) = 0;
-};
-
-
-// Implementation of libudev interface using concrete udev calls.
-class StandardUdevInterface : public UdevInterface {
- public:
- virtual ~StandardUdevInterface() {}
-
- // Concrete udev API wrappers utilizing the standard libudev calls.
- virtual const char* ListEntryGetName(struct udev_list_entry* list_entry) {
- return udev_list_entry_get_name(list_entry);
- }
- virtual struct udev_list_entry* ListEntryGetNext(
- struct udev_list_entry* list_entry) {
- return udev_list_entry_get_next(list_entry);
- }
-
- virtual struct udev_device* DeviceNewFromSyspath(struct udev* udev,
- const char* syspath) {
- return udev_device_new_from_syspath(udev, syspath);
- }
- virtual const char* DeviceGetPropertyValue(struct udev_device* udev_device,
- const char* key) {
- return udev_device_get_property_value(udev_device, key);
- }
- virtual const char* DeviceGetSyspath(struct udev_device* udev_device) {
- return udev_device_get_syspath(udev_device);
- }
- virtual void DeviceUnref(struct udev_device* udev_device) {
- udev_device_unref(udev_device);
- }
-
- virtual struct udev_enumerate* EnumerateNew(struct udev* udev) {
- return udev_enumerate_new(udev);
- }
- virtual int EnumerateAddMatchSubsystem(struct udev_enumerate* udev_enum,
- const char* subsystem) {
- return udev_enumerate_add_match_subsystem(udev_enum, subsystem);
- }
- virtual int EnumerateAddMatchSysname(struct udev_enumerate* udev_enum,
- const char* sysname) {
- return udev_enumerate_add_match_sysname(udev_enum, sysname);
- }
- virtual int EnumerateScanDevices(struct udev_enumerate* udev_enum) {
- return udev_enumerate_scan_devices(udev_enum);
- }
- virtual struct udev_list_entry* EnumerateGetListEntry(
- struct udev_enumerate* udev_enum) {
- return udev_enumerate_get_list_entry(udev_enum);
- }
- virtual void EnumerateUnref(struct udev_enumerate* udev_enum) {
- udev_enumerate_unref(udev_enum);
- }
-
- virtual struct udev* New() {
- return udev_new();
- }
- virtual void Unref(struct udev* udev) {
- udev_unref(udev);
- }
-};
-
-} // namespace chromeos_update_engine
-
-#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_UDEV_INTERFACE_H_
diff --git a/update_attempter.cc b/update_attempter.cc
index 7df18b1..fc65fb3 100644
--- a/update_attempter.cc
+++ b/update_attempter.cc
@@ -26,7 +26,6 @@
#include "update_engine/dbus_service.h"
#include "update_engine/download_action.h"
#include "update_engine/filesystem_copier_action.h"
-#include "update_engine/gpio_handler.h"
#include "update_engine/hardware_interface.h"
#include "update_engine/libcurl_http_fetcher.h"
#include "update_engine/metrics.h"
@@ -58,12 +57,6 @@
const int UpdateAttempter::kMaxDeltaUpdateFailures = 3;
-// Private test server URL w/ custom port number.
-// TODO(garnold) This is a temporary hack to allow us to test the closed loop
-// automated update testing. To be replaced with an hard-coded local IP address.
-const char* const UpdateAttempter::kTestUpdateUrl(
- "http://garnold.mtv.corp.google.com:8080/update");
-
namespace {
const int kMaxConsecutiveObeyProxyRequests = 20;
@@ -220,8 +213,7 @@
void UpdateAttempter::Update(const string& app_version,
const string& omaha_url,
bool obey_proxies,
- bool interactive,
- bool is_test_mode) {
+ bool interactive) {
// This is called at least every 4 hours (see the constant
// UpdateCheckScheduler::kTimeoutMaxBackoffInterval) so it's
// appropriate to use as a hook for reporting daily metrics.
@@ -252,15 +244,13 @@
if (!CalculateUpdateParams(app_version,
omaha_url,
obey_proxies,
- interactive,
- is_test_mode)) {
+ interactive)) {
return;
}
BuildUpdateActions(interactive);
- SetStatusAndNotify(UPDATE_STATUS_CHECKING_FOR_UPDATE,
- kUpdateNoticeUnspecified);
+ SetStatusAndNotify(UPDATE_STATUS_CHECKING_FOR_UPDATE);
// Just in case we didn't update boot flags yet, make sure they're updated
// before any update processing starts.
@@ -322,12 +312,9 @@
bool UpdateAttempter::CalculateUpdateParams(const string& app_version,
const string& omaha_url,
bool obey_proxies,
- bool interactive,
- bool is_test_mode) {
+ bool interactive) {
http_response_code_ = 0;
- // Set the test mode flag for the current update attempt.
- is_test_mode_ = is_test_mode;
RefreshDevicePolicy();
const policy::DevicePolicy* device_policy = system_state_->device_policy();
if (device_policy) {
@@ -366,15 +353,8 @@
}
}
- // Determine whether an alternative test address should be used.
- string omaha_url_to_use = omaha_url;
- if ((is_using_test_url_ = (omaha_url_to_use.empty() && is_test_mode_))) {
- omaha_url_to_use = kTestUpdateUrl;
- LOG(INFO) << "using alternative server address: " << omaha_url_to_use;
- }
-
if (!omaha_request_params_->Init(app_version,
- omaha_url_to_use,
+ omaha_url,
interactive)) {
LOG(ERROR) << "Unable to initialize Omaha request params.";
return false;
@@ -588,7 +568,7 @@
// Actions:
LibcurlHttpFetcher* update_check_fetcher =
- new LibcurlHttpFetcher(GetProxyResolver(), system_state_, is_test_mode_);
+ new LibcurlHttpFetcher(GetProxyResolver(), system_state_);
// Try harder to connect to the network, esp when not interactive.
// See comment in libcurl_http_fetcher.cc.
update_check_fetcher->set_no_network_max_retries(interactive ? 1 : 3);
@@ -611,11 +591,10 @@
new OmahaEvent(
OmahaEvent::kTypeUpdateDownloadStarted),
new LibcurlHttpFetcher(GetProxyResolver(),
- system_state_,
- is_test_mode_),
+ system_state_),
false));
LibcurlHttpFetcher* download_fetcher =
- new LibcurlHttpFetcher(GetProxyResolver(), system_state_, is_test_mode_);
+ new LibcurlHttpFetcher(GetProxyResolver(), system_state_);
download_fetcher->set_check_certificate(CertificateChecker::kDownload);
shared_ptr<DownloadAction> download_action(
new DownloadAction(prefs_,
@@ -627,8 +606,7 @@
new OmahaEvent(
OmahaEvent::kTypeUpdateDownloadFinished),
new LibcurlHttpFetcher(GetProxyResolver(),
- system_state_,
- is_test_mode_),
+ system_state_),
false));
shared_ptr<FilesystemCopierAction> filesystem_verifier_action(
new FilesystemCopierAction(system_state_, false, true));
@@ -638,8 +616,7 @@
new OmahaRequestAction(system_state_,
new OmahaEvent(OmahaEvent::kTypeUpdateComplete),
new LibcurlHttpFetcher(GetProxyResolver(),
- system_state_,
- is_test_mode_),
+ system_state_),
false));
download_action->set_delegate(this);
@@ -740,8 +717,7 @@
// Update the payload state for Rollback.
system_state_->payload_state()->Rollback();
- SetStatusAndNotify(UPDATE_STATUS_ATTEMPTING_ROLLBACK,
- kUpdateNoticeUnspecified);
+ SetStatusAndNotify(UPDATE_STATUS_ATTEMPTING_ROLLBACK);
// Just in case we didn't update boot flags yet, make sure they're updated
// before any update processing starts. This also schedules the start of the
@@ -825,19 +801,9 @@
return;
}
- // Read GPIO signals and determine whether this is an automated test scenario.
- // For safety, we only allow a test update to be performed once; subsequent
- // update requests will be carried out normally.
- bool is_test_mode = (!is_test_update_attempted_ &&
- system_state_->gpio_handler()->IsTestModeSignaled());
- if (is_test_mode) {
- LOG(WARNING) << "this is a test mode update attempt!";
- is_test_update_attempted_ = true;
- }
-
// Pass through the interactive flag, in case we want to simulate a scheduled
// test.
- Update(app_version, omaha_url, true, interactive, is_test_mode);
+ Update(app_version, omaha_url, true, interactive);
}
bool UpdateAttempter::RebootIfNeeded() {
@@ -874,11 +840,8 @@
if (status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
LOG(INFO) << "Error event sent.";
- // Inform scheduler of new status; also specifically inform about a failed
- // update attempt with a test address.
- SetStatusAndNotify(UPDATE_STATUS_IDLE,
- (is_using_test_url_ ? kUpdateNoticeTestAddrFailed :
- kUpdateNoticeUnspecified));
+ // Inform scheduler of new status;
+ SetStatusAndNotify(UPDATE_STATUS_IDLE);
if (!fake_update_success_) {
return;
@@ -909,8 +872,7 @@
prefs_->Delete(kPrefsWallClockWaitPeriod);
prefs_->Delete(kPrefsUpdateFirstSeenAt);
- SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT,
- kUpdateNoticeUnspecified);
+ SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT);
LOG(INFO) << "Update successfully applied, waiting to reboot.";
// This pointer is NULL during rollback operations, and the stats
@@ -946,14 +908,14 @@
return;
}
LOG(INFO) << "No update.";
- SetStatusAndNotify(UPDATE_STATUS_IDLE, kUpdateNoticeUnspecified);
+ SetStatusAndNotify(UPDATE_STATUS_IDLE);
}
void UpdateAttempter::ProcessingStopped(const ActionProcessor* processor) {
// Reset cpu shares back to normal.
CleanupCpuSharesManagement();
download_progress_ = 0.0;
- SetStatusAndNotify(UPDATE_STATUS_IDLE, kUpdateNoticeUnspecified);
+ SetStatusAndNotify(UPDATE_STATUS_IDLE);
actions_.clear();
error_event_.reset(NULL);
}
@@ -1020,10 +982,9 @@
new_payload_size_ = plan.payload_size;
SetupDownload();
SetupCpuSharesManagement();
- SetStatusAndNotify(UPDATE_STATUS_UPDATE_AVAILABLE,
- kUpdateNoticeUnspecified);
+ SetStatusAndNotify(UPDATE_STATUS_UPDATE_AVAILABLE);
} else if (type == DownloadAction::StaticType()) {
- SetStatusAndNotify(UPDATE_STATUS_FINALIZING, kUpdateNoticeUnspecified);
+ SetStatusAndNotify(UPDATE_STATUS_FINALIZING);
}
}
@@ -1060,7 +1021,7 @@
progress - download_progress_ >= kDeltaPercent ||
TimeTicks::Now() - last_notify_time_ >= TimeDelta::FromSeconds(10)) {
download_progress_ = progress;
- SetStatusAndNotify(UPDATE_STATUS_DOWNLOADING, kUpdateNoticeUnspecified);
+ SetStatusAndNotify(UPDATE_STATUS_DOWNLOADING);
}
}
@@ -1198,11 +1159,10 @@
return false;
}
-void UpdateAttempter::SetStatusAndNotify(UpdateStatus status,
- UpdateNotice notice) {
+void UpdateAttempter::SetStatusAndNotify(UpdateStatus status) {
status_ = status;
if (update_check_scheduler_) {
- update_check_scheduler_->SetUpdateStatus(status_, notice);
+ update_check_scheduler_->SetUpdateStatus(status_);
}
BroadcastStatus();
}
@@ -1268,13 +1228,11 @@
new OmahaRequestAction(system_state_,
error_event_.release(), // Pass ownership.
new LibcurlHttpFetcher(GetProxyResolver(),
- system_state_,
- is_test_mode_),
+ system_state_),
false));
actions_.push_back(shared_ptr<AbstractAction>(error_event_action));
processor_->EnqueueAction(error_event_action.get());
- SetStatusAndNotify(UPDATE_STATUS_REPORTING_ERROR_EVENT,
- kUpdateNoticeUnspecified);
+ SetStatusAndNotify(UPDATE_STATUS_REPORTING_ERROR_EVENT);
processor_->StartProcessing();
return true;
}
@@ -1383,8 +1341,7 @@
new OmahaRequestAction(system_state_,
NULL,
new LibcurlHttpFetcher(GetProxyResolver(),
- system_state_,
- is_test_mode_),
+ system_state_),
true));
actions_.push_back(shared_ptr<OmahaRequestAction>(ping_action));
processor_->set_delegate(NULL);
@@ -1405,8 +1362,7 @@
}
// Update the status which will schedule the next update check
- SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT,
- kUpdateNoticeUnspecified);
+ SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT);
}
diff --git a/update_attempter.h b/update_attempter.h
index c83f121..9c460ad 100644
--- a/update_attempter.h
+++ b/update_attempter.h
@@ -47,11 +47,6 @@
UPDATE_STATUS_ATTEMPTING_ROLLBACK
};
-enum UpdateNotice {
- kUpdateNoticeUnspecified = 0,
- kUpdateNoticeTestAddrFailed,
-};
-
const char* UpdateStatusToString(UpdateStatus status);
class UpdateAttempter : public ActionProcessorDelegate,
@@ -78,8 +73,7 @@
virtual void Update(const std::string& app_version,
const std::string& omaha_url,
bool obey_proxies,
- bool interactive,
- bool is_test_mode);
+ bool interactive);
// ActionProcessorDelegate methods:
void ProcessingDone(const ActionProcessor* processor, ErrorCode code);
@@ -243,9 +237,7 @@
void ReportOSAge();
// Sets the status to the given status and notifies a status update over dbus.
- // Also accepts a supplement notice, which is delegated to the scheduler and
- // used for making better informed scheduling decisions (e.g. retry timeout).
- void SetStatusAndNotify(UpdateStatus status, UpdateNotice notice);
+ void SetStatusAndNotify(UpdateStatus status);
// Sets up the download parameters after receiving the update check response.
void SetupDownload();
@@ -311,8 +303,7 @@
bool CalculateUpdateParams(const std::string& app_version,
const std::string& omaha_url,
bool obey_proxies,
- bool interactive,
- bool is_test);
+ bool interactive);
// Calculates all the scattering related parameters (such as waiting period,
// which type of scattering is enabled, etc.) and also updates/deletes
@@ -446,15 +437,6 @@
// Used for fetching information about the device policy.
scoped_ptr<policy::PolicyProvider> policy_provider_;
- // A flag for indicating whether we are using a test server URL.
- bool is_using_test_url_ = false;
-
- // If true, will induce a test mode update attempt.
- bool is_test_mode_ = false;
-
- // A flag indicating whether a test update cycle was already attempted.
- bool is_test_update_attempted_ = false;
-
// The current scatter factor as found in the policy setting.
base::TimeDelta scatter_factor_;
diff --git a/update_attempter_mock.h b/update_attempter_mock.h
index d2bc447..3bde347 100644
--- a/update_attempter_mock.h
+++ b/update_attempter_mock.h
@@ -15,11 +15,10 @@
public:
using UpdateAttempter::UpdateAttempter;
- MOCK_METHOD5(Update, void(const std::string& app_version,
+ MOCK_METHOD4(Update, void(const std::string& app_version,
const std::string& omaha_url,
bool obey_proxies,
- bool interactive,
- bool is_test));
+ bool interactive));
MOCK_METHOD5(GetStatus, bool(int64_t* last_checked_time,
double* progress,
diff --git a/update_attempter_unittest.cc b/update_attempter_unittest.cc
index c49cb6f..2fdd9f5 100644
--- a/update_attempter_unittest.cc
+++ b/update_attempter_unittest.cc
@@ -441,7 +441,7 @@
}
EXPECT_CALL(*processor_, StartProcessing()).Times(1);
- attempter_.Update("", "", false, false, false);
+ attempter_.Update("", "", false, false);
g_idle_add(&StaticUpdateTestVerify, this);
}
@@ -645,7 +645,7 @@
ASSERT_FALSE(test_dir_.empty());
attempter_.omaha_request_params_->set_root(test_dir_);
- attempter_.Update("", "", false, false, false);
+ attempter_.Update("", "", false, false);
EXPECT_EQ("beta-channel",
attempter_.omaha_request_params_->target_channel());
@@ -675,7 +675,7 @@
SetArgumentPointee<0>(true),
Return(true)));
- attempter_.Update("", "", false, false, false);
+ attempter_.Update("", "", false, false);
EXPECT_TRUE(attempter_.omaha_request_params_->update_disabled());
g_idle_add(&StaticQuitMainLoop, this);
@@ -725,7 +725,7 @@
fake_system_state_.set_p2p_manager(&mock_p2p_manager);
mock_p2p_manager.fake().SetP2PEnabled(false);
EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
- attempter_.Update("", "", false, false, false);
+ attempter_.Update("", "", false, false);
EXPECT_FALSE(attempter_.omaha_request_params_->use_p2p_for_downloading());
EXPECT_FALSE(attempter_.omaha_request_params_->use_p2p_for_sharing());
g_idle_add(&StaticQuitMainLoop, this);
@@ -753,7 +753,7 @@
mock_p2p_manager.fake().SetEnsureP2PRunningResult(false);
mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
- attempter_.Update("", "", false, false, false);
+ attempter_.Update("", "", false, false);
EXPECT_FALSE(attempter_.omaha_request_params_->use_p2p_for_downloading());
EXPECT_FALSE(attempter_.omaha_request_params_->use_p2p_for_sharing());
g_idle_add(&StaticQuitMainLoop, this);
@@ -781,7 +781,7 @@
mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(1);
- attempter_.Update("", "", false, false, false);
+ attempter_.Update("", "", false, false);
EXPECT_FALSE(attempter_.omaha_request_params_->use_p2p_for_downloading());
EXPECT_FALSE(attempter_.omaha_request_params_->use_p2p_for_sharing());
g_idle_add(&StaticQuitMainLoop, this);
@@ -808,7 +808,7 @@
mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(1);
- attempter_.Update("", "", false, false, false);
+ attempter_.Update("", "", false, false);
EXPECT_TRUE(attempter_.omaha_request_params_->use_p2p_for_downloading());
EXPECT_TRUE(attempter_.omaha_request_params_->use_p2p_for_sharing());
g_idle_add(&StaticQuitMainLoop, this);
@@ -836,7 +836,7 @@
mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(1);
- attempter_.Update("", "", false, true /* interactive */, false);
+ attempter_.Update("", "", false, true /* interactive */);
EXPECT_FALSE(attempter_.omaha_request_params_->use_p2p_for_downloading());
EXPECT_TRUE(attempter_.omaha_request_params_->use_p2p_for_sharing());
g_idle_add(&StaticQuitMainLoop, this);
@@ -867,7 +867,7 @@
SetArgumentPointee<0>(target_version_prefix),
Return(true)));
- attempter_.Update("", "", false, false, false);
+ attempter_.Update("", "", false, false);
EXPECT_EQ(target_version_prefix.c_str(),
attempter_.omaha_request_params_->target_version_prefix());
@@ -899,7 +899,7 @@
SetArgumentPointee<0>(scatter_factor_in_seconds),
Return(true)));
- attempter_.Update("", "", false, false, false);
+ attempter_.Update("", "", false, false);
EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
g_idle_add(&StaticQuitMainLoop, this);
@@ -944,7 +944,7 @@
SetArgumentPointee<0>(scatter_factor_in_seconds),
Return(true)));
- attempter_.Update("", "", false, false, false);
+ attempter_.Update("", "", false, false);
EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
// Make sure the file still exists.
@@ -960,7 +960,7 @@
// However, if the count is already 0, it's not decremented. Test that.
initial_value = 0;
EXPECT_TRUE(prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
- attempter_.Update("", "", false, false, false);
+ attempter_.Update("", "", false, false);
EXPECT_TRUE(prefs.Exists(kPrefsUpdateCheckCount));
EXPECT_TRUE(prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
EXPECT_EQ(initial_value, new_value);
@@ -1011,7 +1011,7 @@
Return(true)));
// Trigger an interactive check so we can test that scattering is disabled.
- attempter_.Update("", "", false, true, false);
+ attempter_.Update("", "", false, true);
EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
// Make sure scattering is disabled for manual (i.e. user initiated) update
diff --git a/update_check_scheduler.cc b/update_check_scheduler.cc
index 0f3d960..8eff465 100644
--- a/update_check_scheduler.cc
+++ b/update_check_scheduler.cc
@@ -5,7 +5,6 @@
#include "update_engine/update_check_scheduler.h"
#include "update_engine/certificate_checker.h"
-#include "update_engine/gpio_handler.h"
#include "update_engine/hardware_interface.h"
#include "update_engine/http_common.h"
#include "update_engine/system_state.h"
@@ -17,7 +16,6 @@
// actual fuzz is within +/- half of the indicated value.
const int UpdateCheckScheduler::kTimeoutInitialInterval = 7 * 60;
const int UpdateCheckScheduler::kTimeoutPeriodicInterval = 45 * 60;
-const int UpdateCheckScheduler::kTimeoutQuickInterval = 1 * 60;
const int UpdateCheckScheduler::kTimeoutMaxBackoffInterval = 4 * 60 * 60;
const int UpdateCheckScheduler::kTimeoutRegularFuzz = 10 * 60;
@@ -28,7 +26,6 @@
scheduled_(false),
last_interval_(0),
poll_interval_(0),
- is_test_update_attempted_(false),
system_state_(system_state) {}
UpdateCheckScheduler::~UpdateCheckScheduler() {}
@@ -82,20 +79,10 @@
CHECK(me->scheduled_);
me->scheduled_ = false;
- bool is_test_mode = false;
- GpioHandler* gpio_handler = me->system_state_->gpio_handler();
- if (me->system_state_->hardware()->IsOOBEComplete(nullptr) ||
- (is_test_mode = (!me->is_test_update_attempted_ &&
- gpio_handler->IsTestModeSignaled()))) {
- if (is_test_mode) {
- LOG(WARNING)
- << "test mode signaled, allowing update check prior to OOBE complete";
- me->is_test_update_attempted_ = true;
- }
-
+ if (me->system_state_->hardware()->IsOOBEComplete(nullptr)) {
// Before updating, we flush any previously generated UMA reports.
CertificateChecker::FlushReport();
- me->update_attempter_->Update("", "", false, false, is_test_mode);
+ me->update_attempter_->Update("", "", false, false);
} else {
// Skips all automatic update checks if the OOBE process is not complete and
// schedules a new check as if it is the first one.
@@ -112,41 +99,38 @@
return FALSE; // Don't run again.
}
-void UpdateCheckScheduler::ComputeNextIntervalAndFuzz(const int forced_interval,
- int* next_interval,
+void UpdateCheckScheduler::ComputeNextIntervalAndFuzz(int* next_interval,
int* next_fuzz) {
CHECK(next_interval && next_fuzz);
- int interval = forced_interval;
+ int interval = 0;
int fuzz = 0; // Use default fuzz value (see below)
- if (interval == 0) {
- int http_response_code;
- if (poll_interval_ > 0) {
- // Server-dictated poll interval.
- interval = poll_interval_;
- LOG(WARNING) << "Using server-dictated poll interval: " << interval;
- } else if ((http_response_code = update_attempter_->http_response_code()) ==
- kHttpResponseInternalServerError ||
- http_response_code == kHttpResponseServiceUnavailable) {
- // Implements exponential backoff on 500 (Internal Server Error) and 503
- // (Service Unavailable) HTTP response codes.
- interval = 2 * last_interval_;
- LOG(WARNING) << "Exponential backoff due to HTTP response code ("
- << http_response_code << ")";
- }
+ int http_response_code;
+ if (poll_interval_ > 0) {
+ // Server-dictated poll interval.
+ interval = poll_interval_;
+ LOG(WARNING) << "Using server-dictated poll interval: " << interval;
+ } else if ((http_response_code = update_attempter_->http_response_code()) ==
+ kHttpResponseInternalServerError ||
+ http_response_code == kHttpResponseServiceUnavailable) {
+ // Implements exponential backoff on 500 (Internal Server Error) and 503
+ // (Service Unavailable) HTTP response codes.
+ interval = 2 * last_interval_;
+ LOG(WARNING) << "Exponential backoff due to HTTP response code ("
+ << http_response_code << ")";
+ }
- // Backoff cannot exceed a predetermined maximum period.
- if (interval > kTimeoutMaxBackoffInterval)
- interval = kTimeoutMaxBackoffInterval;
+ // Backoff cannot exceed a predetermined maximum period.
+ if (interval > kTimeoutMaxBackoffInterval)
+ interval = kTimeoutMaxBackoffInterval;
- // Ensures that under normal conditions the regular update check interval
- // and fuzz are used. Also covers the case where backoff is required based
- // on the initial update check.
- if (interval < kTimeoutPeriodicInterval) {
- interval = kTimeoutPeriodicInterval;
- fuzz = kTimeoutRegularFuzz;
- }
+ // Ensures that under normal conditions the regular update check interval
+ // and fuzz are used. Also covers the case where backoff is required based
+ // on the initial update check.
+ if (interval < kTimeoutPeriodicInterval) {
+ interval = kTimeoutPeriodicInterval;
+ fuzz = kTimeoutRegularFuzz;
}
// Set default fuzz to +/- |interval|/2.
@@ -157,21 +141,19 @@
*next_fuzz = fuzz;
}
-void UpdateCheckScheduler::ScheduleNextCheck(bool is_force_quick) {
+void UpdateCheckScheduler::ScheduleNextCheck() {
int interval, fuzz;
- ComputeNextIntervalAndFuzz(is_force_quick ? kTimeoutQuickInterval : 0,
- &interval, &fuzz);
+ ComputeNextIntervalAndFuzz(&interval, &fuzz);
ScheduleCheck(interval, fuzz);
}
-void UpdateCheckScheduler::SetUpdateStatus(UpdateStatus status,
- UpdateNotice notice) {
+void UpdateCheckScheduler::SetUpdateStatus(UpdateStatus status) {
// We want to schedule the update checks for when we're idle as well as
// after we've successfully applied an update and waiting for the user
// to reboot to ensure our active count is accurate.
if (status == UPDATE_STATUS_IDLE ||
status == UPDATE_STATUS_UPDATED_NEED_REBOOT) {
- ScheduleNextCheck(notice == kUpdateNoticeTestAddrFailed);
+ ScheduleNextCheck();
}
}
diff --git a/update_check_scheduler.h b/update_check_scheduler.h
index a2dc41a..ec9e1a6 100644
--- a/update_check_scheduler.h
+++ b/update_check_scheduler.h
@@ -38,7 +38,6 @@
public:
static const int kTimeoutInitialInterval;
static const int kTimeoutPeriodicInterval;
- static const int kTimeoutQuickInterval;
static const int kTimeoutRegularFuzz;
static const int kTimeoutMaxBackoffInterval;
@@ -49,10 +48,8 @@
// Initiates the periodic update checks, if necessary.
void Run();
- // Sets the new update status. This is invoked by UpdateAttempter. |notice|
- // is used for passing supplemental information about recent update events,
- // which may influence scheduling decisions.
- void SetUpdateStatus(UpdateStatus status, UpdateNotice notice);
+ // Sets the new update status. This is invoked by UpdateAttempter.
+ void SetUpdateStatus(UpdateStatus status);
void set_poll_interval(int interval) { poll_interval_ = interval; }
int poll_interval() const { return poll_interval_; }
@@ -97,15 +94,12 @@
static gboolean StaticCheck(void* scheduler);
// Schedules the next update check by setting up a timeout source;
- // |is_force_quick| will enforce a quick subsequent update check interval.
- void ScheduleNextCheck(bool is_force_quick);
+ void ScheduleNextCheck();
// Computes the timeout interval along with its random fuzz range for the next
// update check by taking into account the last timeout interval as well as
- // the last update status. A nonzero |forced_interval|, however, will override
- // all other considerations.
- void ComputeNextIntervalAndFuzz(const int forced_interval,
- int* next_interval, int* next_fuzz);
+ // the last update status.
+ void ComputeNextIntervalAndFuzz(int* next_interval, int* next_fuzz);
// The UpdateAttempter to use for update checks.
UpdateAttempter* update_attempter_;
@@ -122,9 +116,6 @@
// Server dictated poll interval in seconds, if positive.
int poll_interval_;
- // A flag indicating whether a test update cycle was already attempted.
- bool is_test_update_attempted_;
-
// The external state of the system outside the update_engine process.
SystemState* system_state_;
diff --git a/update_check_scheduler_unittest.cc b/update_check_scheduler_unittest.cc
index 74daaf3..79e9974 100644
--- a/update_check_scheduler_unittest.cc
+++ b/update_check_scheduler_unittest.cc
@@ -102,14 +102,14 @@
attempter_.set_http_response_code(500);
int last_interval = UpdateCheckScheduler::kTimeoutPeriodicInterval + 50;
scheduler_.last_interval_ = last_interval;
- scheduler_.ComputeNextIntervalAndFuzz(0, &interval, &fuzz);
+ scheduler_.ComputeNextIntervalAndFuzz(&interval, &fuzz);
EXPECT_EQ(2 * last_interval, interval);
EXPECT_EQ(2 * last_interval, fuzz);
attempter_.set_http_response_code(503);
scheduler_.last_interval_ =
UpdateCheckScheduler::kTimeoutMaxBackoffInterval / 2 + 1;
- scheduler_.ComputeNextIntervalAndFuzz(0, &interval, &fuzz);
+ scheduler_.ComputeNextIntervalAndFuzz(&interval, &fuzz);
EXPECT_EQ(UpdateCheckScheduler::kTimeoutMaxBackoffInterval, interval);
EXPECT_EQ(UpdateCheckScheduler::kTimeoutMaxBackoffInterval, fuzz);
}
@@ -118,19 +118,19 @@
int interval, fuzz;
int poll_interval = UpdateCheckScheduler::kTimeoutPeriodicInterval + 50;
scheduler_.set_poll_interval(poll_interval);
- scheduler_.ComputeNextIntervalAndFuzz(0, &interval, &fuzz);
+ scheduler_.ComputeNextIntervalAndFuzz(&interval, &fuzz);
EXPECT_EQ(poll_interval, interval);
EXPECT_EQ(poll_interval, fuzz);
scheduler_.set_poll_interval(
UpdateCheckScheduler::kTimeoutMaxBackoffInterval + 1);
- scheduler_.ComputeNextIntervalAndFuzz(0, &interval, &fuzz);
+ scheduler_.ComputeNextIntervalAndFuzz(&interval, &fuzz);
EXPECT_EQ(UpdateCheckScheduler::kTimeoutMaxBackoffInterval, interval);
EXPECT_EQ(UpdateCheckScheduler::kTimeoutMaxBackoffInterval, fuzz);
scheduler_.set_poll_interval(
UpdateCheckScheduler::kTimeoutPeriodicInterval - 1);
- scheduler_.ComputeNextIntervalAndFuzz(0, &interval, &fuzz);
+ scheduler_.ComputeNextIntervalAndFuzz(&interval, &fuzz);
EXPECT_EQ(UpdateCheckScheduler::kTimeoutPeriodicInterval, interval);
EXPECT_EQ(UpdateCheckScheduler::kTimeoutRegularFuzz, fuzz);
}
@@ -142,14 +142,14 @@
UpdateCheckScheduler::kTimeoutPeriodicInterval + 50;
int poll_interval = UpdateCheckScheduler::kTimeoutPeriodicInterval + 100;
scheduler_.set_poll_interval(poll_interval);
- scheduler_.ComputeNextIntervalAndFuzz(0, &interval, &fuzz);
+ scheduler_.ComputeNextIntervalAndFuzz(&interval, &fuzz);
EXPECT_EQ(poll_interval, interval);
EXPECT_EQ(poll_interval, fuzz);
}
TEST_F(UpdateCheckSchedulerTest, ComputeNextIntervalAndFuzzTest) {
int interval, fuzz;
- scheduler_.ComputeNextIntervalAndFuzz(0, &interval, &fuzz);
+ scheduler_.ComputeNextIntervalAndFuzz(&interval, &fuzz);
EXPECT_EQ(UpdateCheckScheduler::kTimeoutPeriodicInterval, interval);
EXPECT_EQ(UpdateCheckScheduler::kTimeoutRegularFuzz, fuzz);
}
@@ -225,7 +225,7 @@
TEST_F(UpdateCheckSchedulerTest, ScheduleNextCheckDisabledTest) {
EXPECT_CALL(scheduler_, GTimeoutAddSeconds(_, _)).Times(0);
- scheduler_.ScheduleNextCheck(false);
+ scheduler_.ScheduleNextCheck();
}
TEST_F(UpdateCheckSchedulerTest, ScheduleNextCheckEnabledTest) {
@@ -238,12 +238,12 @@
GTimeoutAddSeconds(AllOf(Ge(interval_min), Le(interval_max)),
scheduler_.StaticCheck)).Times(1);
scheduler_.enabled_ = true;
- scheduler_.ScheduleNextCheck(false);
+ scheduler_.ScheduleNextCheck();
}
TEST_F(UpdateCheckSchedulerTest, SetUpdateStatusIdleDisabledTest) {
EXPECT_CALL(scheduler_, GTimeoutAddSeconds(_, _)).Times(0);
- scheduler_.SetUpdateStatus(UPDATE_STATUS_IDLE, kUpdateNoticeUnspecified);
+ scheduler_.SetUpdateStatus(UPDATE_STATUS_IDLE);
}
TEST_F(UpdateCheckSchedulerTest, SetUpdateStatusIdleEnabledTest) {
@@ -256,16 +256,14 @@
GTimeoutAddSeconds(AllOf(Ge(interval_min), Le(interval_max)),
scheduler_.StaticCheck)).Times(1);
scheduler_.enabled_ = true;
- scheduler_.SetUpdateStatus(UPDATE_STATUS_IDLE, kUpdateNoticeUnspecified);
+ scheduler_.SetUpdateStatus(UPDATE_STATUS_IDLE);
}
TEST_F(UpdateCheckSchedulerTest, SetUpdateStatusNonIdleTest) {
EXPECT_CALL(scheduler_, GTimeoutAddSeconds(_, _)).Times(0);
- scheduler_.SetUpdateStatus(UPDATE_STATUS_DOWNLOADING,
- kUpdateNoticeUnspecified);
+ scheduler_.SetUpdateStatus(UPDATE_STATUS_DOWNLOADING);
scheduler_.enabled_ = true;
- scheduler_.SetUpdateStatus(UPDATE_STATUS_DOWNLOADING,
- kUpdateNoticeUnspecified);
+ scheduler_.SetUpdateStatus(UPDATE_STATUS_DOWNLOADING);
}
TEST_F(UpdateCheckSchedulerTest, StaticCheckOOBECompleteTest) {
@@ -273,7 +271,7 @@
EXPECT_TRUE(scheduler_.fake_system_state_ != NULL);
scheduler_.fake_system_state_->fake_hardware()->SetIsOOBEComplete(
Time::UnixEpoch());
- EXPECT_CALL(attempter_, Update("", "", false, false, false))
+ EXPECT_CALL(attempter_, Update("", "", false, false))
.Times(1)
.WillOnce(Assign(&scheduler_.scheduled_, true));
scheduler_.enabled_ = true;
@@ -284,7 +282,7 @@
TEST_F(UpdateCheckSchedulerTest, StaticCheckOOBENotCompleteTest) {
scheduler_.scheduled_ = true;
scheduler_.fake_system_state_->fake_hardware()->UnsetIsOOBEComplete();
- EXPECT_CALL(attempter_, Update("", "", _, _, _)).Times(0);
+ EXPECT_CALL(attempter_, Update("", "", _, _)).Times(0);
int interval_min, interval_max;
FuzzRange(UpdateCheckScheduler::kTimeoutInitialInterval,
UpdateCheckScheduler::kTimeoutRegularFuzz,