file_name int64 0 72.3k | vulnerable_line_numbers stringlengths 1 1.06k ⌀ | dataset_type stringclasses 1 value | commit_hash stringlengths 40 44 | unique_id int64 0 271k | project stringclasses 10 values | target int64 0 1 | repo_url stringclasses 10 values | date stringlengths 25 25 ⌀ | code stringlengths 0 20.4M | CVE stringlengths 13 43 ⌀ | CWE stringclasses 50 values | commit_link stringlengths 73 97 ⌀ | severity stringclasses 4 values | __index_level_0__ int64 0 124k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
66,644 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 66,644 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2018 The Chromium 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 CHROME_BROWSER_DOWNLOAD_DOWNLOAD_PROMPT_STATUS_H_
#define CHROME_BROWSER_DOWNLOAD_DOWNLOAD_PROMPT_STATUS_H_
// The status of the download prompt.
// A Java counterpart will be generated for this enum.
// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.chrome.browser.download
enum class DownloadPromptStatus {
SHOW_INITIAL, // Show the prompt because it hasn't been shown before.
SHOW_PREFERENCE, // Show the prompt because user indicated preference.
DONT_SHOW // Don't show the prompt because user indicated preference.
};
#endif // CHROME_BROWSER_DOWNLOAD_DOWNLOAD_PROMPT_STATUS_H_
| null | null | null | null | 63,507 |
69,963 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 69,963 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright (c) 2012 The Chromium 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 "device/bluetooth/dbus/bluez_dbus_manager.h"
#include <memory>
#include <utility>
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/memory/ptr_util.h"
#include "base/sys_info.h"
#include "base/threading/thread.h"
#include "dbus/bus.h"
#include "dbus/dbus_statistics.h"
#include "dbus/message.h"
#include "dbus/object_manager.h"
#include "dbus/object_proxy.h"
#include "device/base/features.h"
#include "device/bluetooth/dbus/bluetooth_adapter_client.h"
#include "device/bluetooth/dbus/bluetooth_agent_manager_client.h"
#include "device/bluetooth/dbus/bluetooth_device_client.h"
#include "device/bluetooth/dbus/bluetooth_gatt_characteristic_client.h"
#include "device/bluetooth/dbus/bluetooth_gatt_descriptor_client.h"
#include "device/bluetooth/dbus/bluetooth_gatt_manager_client.h"
#include "device/bluetooth/dbus/bluetooth_gatt_service_client.h"
#include "device/bluetooth/dbus/bluetooth_input_client.h"
#include "device/bluetooth/dbus/bluetooth_le_advertising_manager_client.h"
#include "device/bluetooth/dbus/bluetooth_media_client.h"
#include "device/bluetooth/dbus/bluetooth_media_transport_client.h"
#include "device/bluetooth/dbus/bluetooth_profile_manager_client.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
namespace bluez {
static BluezDBusManager* g_bluez_dbus_manager = nullptr;
static bool g_using_bluez_dbus_manager_for_testing = false;
BluezDBusManager::BluezDBusManager(dbus::Bus* bus, bool use_dbus_fakes)
: bus_(bus),
object_manager_support_known_(false),
object_manager_supported_(false),
weak_ptr_factory_(this) {
// On Chrome OS, Bluez might not be ready by the time we initialize the
// BluezDBusManager so we initialize the clients anyway.
bool should_check_object_manager = true;
#if defined(OS_CHROMEOS)
should_check_object_manager = false;
#endif
if (!should_check_object_manager || use_dbus_fakes) {
client_bundle_.reset(new BluetoothDBusClientBundle(use_dbus_fakes));
InitializeClients();
object_manager_supported_ = true;
object_manager_support_known_ = true;
return;
}
CHECK(GetSystemBus()) << "Can't initialize real clients without DBus.";
dbus::MethodCall method_call(dbus::kObjectManagerInterface,
dbus::kObjectManagerGetManagedObjects);
GetSystemBus()
->GetObjectProxy(
GetBluetoothServiceName(),
dbus::ObjectPath(
bluetooth_object_manager::kBluetoothObjectManagerServicePath))
->CallMethodWithErrorCallback(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::BindOnce(&BluezDBusManager::OnObjectManagerSupported,
weak_ptr_factory_.GetWeakPtr()),
base::BindOnce(&BluezDBusManager::OnObjectManagerNotSupported,
weak_ptr_factory_.GetWeakPtr()));
}
BluezDBusManager::~BluezDBusManager() {
// Delete all D-Bus clients before shutting down the system bus.
client_bundle_.reset();
}
dbus::Bus* bluez::BluezDBusManager::GetSystemBus() {
return bus_;
}
void BluezDBusManager::CallWhenObjectManagerSupportIsKnown(
base::Closure callback) {
object_manager_support_known_callback_ = callback;
}
BluetoothAdapterClient* bluez::BluezDBusManager::GetBluetoothAdapterClient() {
DCHECK(object_manager_support_known_);
return client_bundle_->bluetooth_adapter_client();
}
BluetoothLEAdvertisingManagerClient*
bluez::BluezDBusManager::GetBluetoothLEAdvertisingManagerClient() {
DCHECK(object_manager_support_known_);
return client_bundle_->bluetooth_le_advertising_manager_client();
}
BluetoothAgentManagerClient*
bluez::BluezDBusManager::GetBluetoothAgentManagerClient() {
DCHECK(object_manager_support_known_);
return client_bundle_->bluetooth_agent_manager_client();
}
BluetoothDeviceClient* bluez::BluezDBusManager::GetBluetoothDeviceClient() {
DCHECK(object_manager_support_known_);
return client_bundle_->bluetooth_device_client();
}
BluetoothGattCharacteristicClient*
bluez::BluezDBusManager::GetBluetoothGattCharacteristicClient() {
DCHECK(object_manager_support_known_);
return client_bundle_->bluetooth_gatt_characteristic_client();
}
BluetoothGattDescriptorClient*
bluez::BluezDBusManager::GetBluetoothGattDescriptorClient() {
DCHECK(object_manager_support_known_);
return client_bundle_->bluetooth_gatt_descriptor_client();
}
BluetoothGattManagerClient*
bluez::BluezDBusManager::GetBluetoothGattManagerClient() {
DCHECK(object_manager_support_known_);
return client_bundle_->bluetooth_gatt_manager_client();
}
BluetoothGattServiceClient*
bluez::BluezDBusManager::GetBluetoothGattServiceClient() {
DCHECK(object_manager_support_known_);
return client_bundle_->bluetooth_gatt_service_client();
}
BluetoothInputClient* bluez::BluezDBusManager::GetBluetoothInputClient() {
DCHECK(object_manager_support_known_);
return client_bundle_->bluetooth_input_client();
}
BluetoothMediaClient* bluez::BluezDBusManager::GetBluetoothMediaClient() {
DCHECK(object_manager_support_known_);
return client_bundle_->bluetooth_media_client();
}
BluetoothMediaTransportClient*
bluez::BluezDBusManager::GetBluetoothMediaTransportClient() {
DCHECK(object_manager_support_known_);
return client_bundle_->bluetooth_media_transport_client();
}
BluetoothProfileManagerClient*
bluez::BluezDBusManager::GetBluetoothProfileManagerClient() {
DCHECK(object_manager_support_known_);
return client_bundle_->bluetooth_profile_manager_client();
}
void BluezDBusManager::OnObjectManagerSupported(dbus::Response* response) {
VLOG(1) << "Bluetooth supported. Initializing clients.";
object_manager_supported_ = true;
client_bundle_.reset(new BluetoothDBusClientBundle(false /* use_fakes */));
InitializeClients();
object_manager_support_known_ = true;
if (!object_manager_support_known_callback_.is_null()) {
object_manager_support_known_callback_.Run();
object_manager_support_known_callback_.Reset();
}
}
void BluezDBusManager::OnObjectManagerNotSupported(
dbus::ErrorResponse* response) {
VLOG(1) << "Bluetooth not supported.";
object_manager_supported_ = false;
// We don't initialize clients since the clients need ObjectManager.
object_manager_support_known_ = true;
if (!object_manager_support_known_callback_.is_null()) {
object_manager_support_known_callback_.Run();
object_manager_support_known_callback_.Reset();
}
}
void BluezDBusManager::InitializeClients() {
std::string bluetooth_service_name = GetBluetoothServiceName();
client_bundle_->bluetooth_adapter_client()->Init(GetSystemBus(),
bluetooth_service_name);
client_bundle_->bluetooth_agent_manager_client()->Init(
GetSystemBus(), bluetooth_service_name);
client_bundle_->bluetooth_device_client()->Init(GetSystemBus(),
bluetooth_service_name);
client_bundle_->bluetooth_gatt_characteristic_client()->Init(
GetSystemBus(), bluetooth_service_name);
client_bundle_->bluetooth_gatt_descriptor_client()->Init(
GetSystemBus(), bluetooth_service_name);
client_bundle_->bluetooth_gatt_manager_client()->Init(GetSystemBus(),
bluetooth_service_name);
client_bundle_->bluetooth_gatt_service_client()->Init(GetSystemBus(),
bluetooth_service_name);
client_bundle_->bluetooth_input_client()->Init(GetSystemBus(),
bluetooth_service_name);
client_bundle_->bluetooth_le_advertising_manager_client()->Init(
GetSystemBus(), bluetooth_service_name);
client_bundle_->bluetooth_media_client()->Init(GetSystemBus(),
bluetooth_service_name);
client_bundle_->bluetooth_media_transport_client()->Init(
GetSystemBus(), bluetooth_service_name);
client_bundle_->bluetooth_profile_manager_client()->Init(
GetSystemBus(), bluetooth_service_name);
}
std::string BluezDBusManager::GetBluetoothServiceName() {
return base::FeatureList::IsEnabled(device::kNewblueDaemon)
? bluetooth_object_manager::kBluetoothObjectManagerServiceName
: bluez_object_manager::kBluezObjectManagerServiceName;
}
// static
void BluezDBusManager::Initialize(dbus::Bus* bus, bool use_dbus_stub) {
// If we initialize BluezDBusManager twice we may also be shutting it down
// early; do not allow that.
if (g_using_bluez_dbus_manager_for_testing)
return;
CHECK(!g_bluez_dbus_manager);
CreateGlobalInstance(bus, use_dbus_stub);
}
// static
std::unique_ptr<BluezDBusManagerSetter>
bluez::BluezDBusManager::GetSetterForTesting() {
if (!g_using_bluez_dbus_manager_for_testing) {
g_using_bluez_dbus_manager_for_testing = true;
CreateGlobalInstance(nullptr, true);
}
return base::WrapUnique(new BluezDBusManagerSetter());
}
// static
void BluezDBusManager::CreateGlobalInstance(dbus::Bus* bus, bool use_stubs) {
CHECK(!g_bluez_dbus_manager);
g_bluez_dbus_manager = new BluezDBusManager(bus, use_stubs);
}
// static
bool BluezDBusManager::IsInitialized() {
return g_bluez_dbus_manager != nullptr;
}
// static
void BluezDBusManager::Shutdown() {
// Ensure that we only shutdown BluezDBusManager once.
CHECK(g_bluez_dbus_manager);
BluezDBusManager* dbus_manager = g_bluez_dbus_manager;
g_bluez_dbus_manager = nullptr;
g_using_bluez_dbus_manager_for_testing = false;
delete dbus_manager;
VLOG(1) << "BluezDBusManager Shutdown completed";
}
// static
BluezDBusManager* bluez::BluezDBusManager::Get() {
CHECK(g_bluez_dbus_manager)
<< "bluez::BluezDBusManager::Get() called before Initialize()";
return g_bluez_dbus_manager;
}
BluezDBusManagerSetter::BluezDBusManagerSetter() = default;
BluezDBusManagerSetter::~BluezDBusManagerSetter() = default;
void BluezDBusManagerSetter::SetBluetoothAdapterClient(
std::unique_ptr<BluetoothAdapterClient> client) {
bluez::BluezDBusManager::Get()->client_bundle_->bluetooth_adapter_client_ =
std::move(client);
}
void BluezDBusManagerSetter::SetBluetoothLEAdvertisingManagerClient(
std::unique_ptr<BluetoothLEAdvertisingManagerClient> client) {
bluez::BluezDBusManager::Get()
->client_bundle_->bluetooth_le_advertising_manager_client_ =
std::move(client);
}
void BluezDBusManagerSetter::SetBluetoothAgentManagerClient(
std::unique_ptr<BluetoothAgentManagerClient> client) {
bluez::BluezDBusManager::Get()
->client_bundle_->bluetooth_agent_manager_client_ = std::move(client);
}
void BluezDBusManagerSetter::SetBluetoothDeviceClient(
std::unique_ptr<BluetoothDeviceClient> client) {
bluez::BluezDBusManager::Get()->client_bundle_->bluetooth_device_client_ =
std::move(client);
}
void BluezDBusManagerSetter::SetBluetoothGattCharacteristicClient(
std::unique_ptr<BluetoothGattCharacteristicClient> client) {
bluez::BluezDBusManager::Get()
->client_bundle_->bluetooth_gatt_characteristic_client_ =
std::move(client);
}
void BluezDBusManagerSetter::SetBluetoothGattDescriptorClient(
std::unique_ptr<BluetoothGattDescriptorClient> client) {
bluez::BluezDBusManager::Get()
->client_bundle_->bluetooth_gatt_descriptor_client_ = std::move(client);
}
void BluezDBusManagerSetter::SetBluetoothGattManagerClient(
std::unique_ptr<BluetoothGattManagerClient> client) {
bluez::BluezDBusManager::Get()
->client_bundle_->bluetooth_gatt_manager_client_ = std::move(client);
}
void BluezDBusManagerSetter::SetBluetoothGattServiceClient(
std::unique_ptr<BluetoothGattServiceClient> client) {
bluez::BluezDBusManager::Get()
->client_bundle_->bluetooth_gatt_service_client_ = std::move(client);
}
void BluezDBusManagerSetter::SetBluetoothInputClient(
std::unique_ptr<BluetoothInputClient> client) {
bluez::BluezDBusManager::Get()->client_bundle_->bluetooth_input_client_ =
std::move(client);
}
void BluezDBusManagerSetter::SetBluetoothMediaClient(
std::unique_ptr<BluetoothMediaClient> client) {
bluez::BluezDBusManager::Get()->client_bundle_->bluetooth_media_client_ =
std::move(client);
}
void BluezDBusManagerSetter::SetBluetoothMediaTransportClient(
std::unique_ptr<BluetoothMediaTransportClient> client) {
bluez::BluezDBusManager::Get()
->client_bundle_->bluetooth_media_transport_client_ = std::move(client);
}
void BluezDBusManagerSetter::SetBluetoothProfileManagerClient(
std::unique_ptr<BluetoothProfileManagerClient> client) {
bluez::BluezDBusManager::Get()
->client_bundle_->bluetooth_profile_manager_client_ = std::move(client);
}
} // namespace bluez
| null | null | null | null | 66,826 |
51,562 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 51,562 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2018 The Chromium 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 "ui/latency/stream_analyzer.h"
#include "base/time/time.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/latency/frame_metrics_test_common.h"
namespace ui {
namespace frame_metrics {
namespace {
class StreamAnalyzerTest : public testing::Test {
public:
StreamAnalyzerTest() { NewAnalyzer(10, {2, 7, 10}); }
void SetUp() override {}
StreamAnalyzer* analyzer() { return analyzer_.get(); }
void NewAnalyzer(size_t window_size, std::vector<uint32_t> thresholds) {
shared_client_.max_window_size = window_size;
for (auto& t : thresholds) {
t *= kFixedPointMultiplier;
}
thresholds_ = std::move(thresholds);
std::unique_ptr<TestHistogram> histogram =
std::make_unique<TestHistogram>();
histogram_ = histogram.get();
analyzer_ = std::make_unique<StreamAnalyzer>(
&client_, &shared_client_, thresholds_, std::move(histogram));
}
protected:
size_t window_size;
TestStreamAnalyzerClient client_;
SharedWindowedAnalyzerClient shared_client_;
std::vector<uint32_t> thresholds_;
TestHistogram* histogram_;
std::unique_ptr<StreamAnalyzer> analyzer_;
};
TEST_F(StreamAnalyzerTest, AllResultsTheSame) {
// Try adding a single sample vs. multiple samples.
for (size_t samples : {1u, 100u}) {
// A power of 2 sweep for both the value and weight dimensions.
for (uint64_t value = 1; value < 0x100000000ULL; value *= 2) {
// Adding too many samples can result in overflow when multiplied by the
// weight. Divide by samples to avoid overflow.
for (uint64_t weight = 1; weight < 0x100000000ULL / samples;
weight *= 2) {
analyzer()->Reset();
AddSamplesHelper(analyzer(), value, weight, samples);
uint64_t expected_value =
value * TestStreamAnalyzerClient::result_scale;
EXPECT_EQ(expected_value, analyzer_->ComputeMean());
EXPECT_EQ(expected_value, analyzer_->ComputeRMS());
EXPECT_NEAR_SMR(analyzer_->ComputeSMR(), expected_value, weight);
EXPECT_DOUBLE_EQ(0, analyzer_->ComputeStdDev());
EXPECT_NEAR_VARIANCE_OF_ROOT(0, analyzer_->ComputeVarianceOfRoots(),
expected_value, weight);
// Verify values are forwarded to the WindowedAnalyzer.
EXPECT_EQ(expected_value, analyzer_->window().ComputeWorstMean().value);
EXPECT_EQ(expected_value, analyzer_->window().ComputeWorstRMS().value);
EXPECT_NEAR_SMR(expected_value,
analyzer_->window().ComputeWorstSMR().value, weight);
}
}
}
// All min/max combinations of value and weight.
for (uint64_t value : {0u, 0xFFFFFFFFu}) {
for (uint64_t weight : {1u, 0xFFFFFFFFu}) {
const size_t kSamplesToAdd = weight == 1 ? 100 : 1;
analyzer()->Reset();
AddSamplesHelper(analyzer(), value, weight, kSamplesToAdd);
// TestWindowedAnalyzerClient scales the result by 2.
uint64_t expected_value = value * TestStreamAnalyzerClient::result_scale;
// Makes sure our precision is good enough.
EXPECT_EQ(expected_value, analyzer_->ComputeMean());
EXPECT_EQ(expected_value, analyzer_->ComputeRMS());
EXPECT_NEAR_SMR(expected_value, analyzer_->ComputeSMR(), weight);
EXPECT_DOUBLE_EQ(0, analyzer_->ComputeStdDev());
EXPECT_NEAR_VARIANCE_OF_ROOT(0, analyzer_->ComputeVarianceOfRoots(),
expected_value, weight);
// Verify values are forwarded to the WindowedAnalyzer.
EXPECT_EQ(expected_value, analyzer_->window().ComputeWorstMean().value);
EXPECT_EQ(expected_value, analyzer_->window().ComputeWorstRMS().value);
EXPECT_NEAR_SMR(expected_value,
analyzer_->window().ComputeWorstSMR().value, weight);
}
}
}
// This applies a pattern of 2 values that are easy to calculate the expected
// results for. It verifies the mean, rms, smr, standard deviation,
// variance of the roots, and thresholds are calculated properly.
// This doesn't check histogram or windowed analyzer related values since they
// are tested separately and other unit tests verify their interactions
// with StreamAnalyzer.
TEST_F(StreamAnalyzerTest, AllResultsDifferent) {
const uint32_t kSampleWeight = 100;
const std::vector<uint32_t> pattern49 = {4, 9, 4, 9, 4, 9};
const std::vector<uint32_t> pattern4 = {4, 4, 4, 4, 4, 4};
const std::vector<uint32_t> pattern9 = {9, 9, 9, 9, 9, 9};
// Calculate the expected values for an equal number of 4's and 9's.
const double expected_mean = (4 + 9) * .5 * kFixedPointMultiplier *
TestStreamAnalyzerClient::result_scale;
const double expected_rms = std::sqrt((16 + 81) * .5) *
kFixedPointMultiplier *
TestStreamAnalyzerClient::result_scale;
const double mean_root = (2 + 3) * .5;
const double expected_smr = mean_root * mean_root * kFixedPointMultiplier *
TestStreamAnalyzerClient::result_scale;
const double expected_std_dev = (9 - 4) * .5 * kFixedPointMultiplier *
TestStreamAnalyzerClient::result_scale;
const double std_dev_of_roots = (3 - 2) * .5;
const double expected_variance_of_roots =
std_dev_of_roots * std_dev_of_roots * kFixedPointMultiplier *
TestStreamAnalyzerClient::result_scale;
std::vector<ThresholdResult> thresholds;
// Alternate 4 and 9.
for (size_t i = 0; i < 1000; i++) {
AddPatternHelper(&shared_client_, analyzer(), pattern49, kSampleWeight);
EXPECT_DOUBLE_EQ(expected_mean, analyzer_->ComputeMean());
EXPECT_NEAR_SMR(expected_smr, analyzer_->ComputeSMR(), kSampleWeight);
EXPECT_DOUBLE_EQ(expected_rms, analyzer_->ComputeRMS());
EXPECT_DOUBLE_EQ(expected_std_dev, analyzer_->ComputeStdDev());
EXPECT_DOUBLE_EQ(expected_variance_of_roots,
analyzer_->ComputeVarianceOfRoots());
}
thresholds = analyzer_->ComputeThresholds();
ASSERT_EQ(3u, thresholds.size());
EXPECT_EQ(client_.TransformResult(thresholds_[0]), thresholds[0].threshold);
EXPECT_EQ(client_.TransformResult(thresholds_[1]), thresholds[1].threshold);
EXPECT_EQ(client_.TransformResult(thresholds_[2]), thresholds[2].threshold);
EXPECT_EQ(1.0, thresholds[0].ge_fraction);
EXPECT_EQ(0.5, thresholds[1].ge_fraction);
EXPECT_EQ(0.0, thresholds[2].ge_fraction);
// 4's then 9's.
analyzer()->Reset();
for (size_t i = 0; i < 500; i++) {
AddPatternHelper(&shared_client_, analyzer(), pattern4, kSampleWeight);
}
for (size_t i = 0; i < 500; i++) {
AddPatternHelper(&shared_client_, analyzer(), pattern9, kSampleWeight);
}
thresholds = analyzer_->ComputeThresholds();
EXPECT_DOUBLE_EQ(expected_mean, analyzer_->ComputeMean());
EXPECT_NEAR_SMR(expected_smr, analyzer_->ComputeSMR(), kSampleWeight);
EXPECT_DOUBLE_EQ(expected_rms, analyzer_->ComputeRMS());
EXPECT_DOUBLE_EQ(expected_std_dev, analyzer_->ComputeStdDev());
EXPECT_DOUBLE_EQ(expected_variance_of_roots,
analyzer_->ComputeVarianceOfRoots());
EXPECT_EQ(client_.TransformResult(thresholds_[0]), thresholds[0].threshold);
EXPECT_EQ(client_.TransformResult(thresholds_[1]), thresholds[1].threshold);
EXPECT_EQ(client_.TransformResult(thresholds_[2]), thresholds[2].threshold);
EXPECT_EQ(1.0, thresholds[0].ge_fraction);
EXPECT_EQ(0.5, thresholds[1].ge_fraction);
EXPECT_EQ(0.0, thresholds[2].ge_fraction);
// 9's then 4's.
analyzer()->Reset();
for (size_t i = 0; i < 500; i++) {
AddPatternHelper(&shared_client_, analyzer(), pattern9, kSampleWeight);
}
for (size_t i = 0; i < 500; i++) {
AddPatternHelper(&shared_client_, analyzer(), pattern4, kSampleWeight);
}
thresholds = analyzer_->ComputeThresholds();
EXPECT_DOUBLE_EQ(expected_mean, analyzer_->ComputeMean());
EXPECT_NEAR_SMR(expected_smr, analyzer_->ComputeSMR(), kSampleWeight);
EXPECT_DOUBLE_EQ(expected_rms, analyzer_->ComputeRMS());
EXPECT_DOUBLE_EQ(expected_std_dev, analyzer_->ComputeStdDev());
EXPECT_DOUBLE_EQ(expected_variance_of_roots,
analyzer_->ComputeVarianceOfRoots());
EXPECT_EQ(client_.TransformResult(thresholds_[0]), thresholds[0].threshold);
EXPECT_EQ(client_.TransformResult(thresholds_[1]), thresholds[1].threshold);
EXPECT_EQ(client_.TransformResult(thresholds_[2]), thresholds[2].threshold);
EXPECT_EQ(1.0, thresholds[0].ge_fraction);
EXPECT_EQ(0.5, thresholds[1].ge_fraction);
EXPECT_EQ(0.0, thresholds[2].ge_fraction);
}
TEST_F(StreamAnalyzerTest, SamplesForwardedToHistogram) {
const uint32_t kSampleWeight = 123;
const std::vector<uint32_t> pattern = {4, 9, 16, 25, 36, 49};
AddPatternHelper(&shared_client_, analyzer(), pattern, kSampleWeight);
std::vector<TestHistogram::ValueWeightPair> samples(
histogram_->GetAndResetAllAddedSamples());
ASSERT_EQ(pattern.size(), samples.size());
for (size_t i = 0; i < samples.size(); i++) {
EXPECT_EQ(pattern[i] * kFixedPointMultiplier, samples[i].value);
EXPECT_EQ(kSampleWeight, samples[i].weight);
}
}
TEST_F(StreamAnalyzerTest, PercentilesModifiedByClient) {
double result0 = 7;
double result1 = 11;
histogram_->SetResults({{result0, result1}});
PercentileResults results = analyzer()->ComputePercentiles();
EXPECT_EQ(client_.TransformResult(result0), results.values[0]);
EXPECT_EQ(client_.TransformResult(result1), results.values[1]);
}
// StreamAnalyzerNaive is a subset of stream analyzer that only uses single
// precision floating point accumulators and can accumulate error.
// This is used to verify patterns that accumulate error, so we can then verify
// those patterns don't result in acculated error in the actual implementation.
struct StreamAnalyzerNaive {
void AddSample(uint32_t value,
uint32_t weight,
uint64_t weighted_value,
uint64_t weighted_root,
const Accumulator96b& weighted_square) {
accumulator_ += static_cast<double>(weight) * value;
root_accumulator_ += static_cast<double>(weight) * std::sqrt(value);
square_accumulator_ += static_cast<double>(weight) * value * value;
total_weight_ += weight;
}
double ComputeMean() {
return client_.TransformResult(accumulator_ / total_weight_);
}
double ComputeRMS() {
return client_.TransformResult(
std::sqrt(square_accumulator_ / total_weight_));
}
double ComputeSMR() {
double mean_root = root_accumulator_ / total_weight_;
return client_.TransformResult(mean_root * mean_root);
}
float total_weight_ = 0;
float accumulator_ = 0;
float root_accumulator_ = 0;
float square_accumulator_ = 0;
TestStreamAnalyzerClient client_;
};
// Unlike the WindowedAnalyzer, there aren't patterns of input that would
// affect the precision of our results very much with double precision floating
// point accumulators. This is because we aren't subtracting values like the
// WindowedAnalyzer does. Nevertheless, there can be issues if the accumulators
// are only single precision.
TEST_F(StreamAnalyzerTest, Precision) {
StreamAnalyzerNaive naive_analyzer;
uint32_t large_value = 20 * base::TimeTicks::kMicrosecondsPerSecond;
uint32_t large_weight = large_value;
size_t large_sample_count = 1;
AddSamplesHelper(&naive_analyzer, large_value, large_weight,
large_sample_count);
AddSamplesHelper(analyzer(), large_value, large_weight, large_sample_count);
uint32_t small_value = 1 * base::TimeTicks::kMicrosecondsPerMillisecond;
uint32_t small_weight = small_value;
size_t small_sample_count = 60 * 60 * 60; // 1hr of 60Hz frames.
AddSamplesHelper(&naive_analyzer, small_value, small_weight,
small_sample_count);
AddSamplesHelper(analyzer(), small_value, small_weight, small_sample_count);
double total_weight = static_cast<double>(large_sample_count) * large_weight +
static_cast<double>(small_sample_count) * small_weight;
double large_value_f = large_value;
double small_value_f = small_value;
double expected_mean = client_.TransformResult(
(large_value_f * large_weight +
small_sample_count * small_value_f * small_weight) /
total_weight);
EXPECT_ABS_LT(expected_mean * .001,
expected_mean - naive_analyzer.ComputeMean());
EXPECT_DOUBLE_EQ(expected_mean, analyzer_->ComputeMean());
double large_value_squared = large_value_f * large_value_f * large_weight;
double small_value_squared = small_value_f * small_value_f * small_weight;
double mean_square =
(large_value_squared + small_sample_count * small_value_squared) /
total_weight;
double expected_rms = client_.TransformResult(std::sqrt(mean_square));
EXPECT_ABS_LT(expected_rms * .001,
expected_rms - naive_analyzer.ComputeRMS());
EXPECT_DOUBLE_EQ(expected_rms, analyzer_->ComputeRMS());
double large_value_root = std::sqrt(large_value_f) * large_weight;
double small_value_root = std::sqrt(small_value_f) * small_weight;
double mean_root =
(large_value_root + small_sample_count * small_value_root) / total_weight;
double expected_smr = client_.TransformResult(mean_root * mean_root);
EXPECT_ABS_LT(expected_smr * .001,
expected_smr - naive_analyzer.ComputeSMR());
EXPECT_NEAR_SMR(expected_smr, analyzer_->ComputeSMR(), 1);
}
} // namespace
} // namespace frame_metrics
} // namespace ui
| null | null | null | null | 48,425 |
56,524 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 56,524 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2014 The Chromium 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 "chrome/browser/chromeos/login/screenshot_testing/screenshot_tester.h"
#include <stddef.h>
#include <stdint.h>
#include "ash/shell.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/run_loop.h"
#include "chrome/browser/chromeos/login/screenshot_testing/SkDiffPixelsMetric.h"
#include "chrome/browser/chromeos/login/screenshot_testing/SkImageDiffer.h"
#include "chrome/browser/chromeos/login/screenshot_testing/SkPMetric.h"
#include "chromeos/chromeos_switches.h"
#include "content/public/browser/browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "ui/compositor/compositor_switches.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/image/image.h"
#include "ui/snapshot/snapshot.h"
namespace {
// Sets test mode for screenshot testing, using regular comparison.
const char kTestMode[] = "test";
// Sets update mode for screenshot testing.
const char kUpdateMode[] = "update";
// Sets test mode for screenshot testing, using PerceptualDiff as comparison.
const char kPdiffTestMode[] = "pdiff-test";
} // namespace
namespace chromeos {
ScreenshotTester::ScreenshotTester()
: test_mode_(false), pdiff_enabled_(false), weak_factory_(this) {}
ScreenshotTester::~ScreenshotTester() {}
ScreenshotTester::Result::Result() {}
ScreenshotTester::Result::Result(const Result& other) = default;
ScreenshotTester::Result::~Result() {}
bool ScreenshotTester::TryInitialize() {
base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess();
if (!command_line.HasSwitch(switches::kEnableScreenshotTestingWithMode))
return false;
std::string mode = command_line.GetSwitchValueASCII(
switches::kEnableScreenshotTestingWithMode);
CHECK(mode == kUpdateMode || mode == kTestMode || mode == kPdiffTestMode)
<< "Invalid mode for screenshot testing: " << mode;
CHECK(command_line.HasSwitch(chromeos::switches::kGoldenScreenshotsDir))
<< "No directory with golden screenshots specified, use "
"--golden-screenshots-dir";
golden_screenshots_dir_ =
command_line.GetSwitchValuePath(switches::kGoldenScreenshotsDir);
if (mode == kTestMode || mode == kPdiffTestMode) {
test_mode_ = true;
generate_artifacts_ = command_line.HasSwitch(switches::kArtifactsDir);
if (generate_artifacts_) {
artifacts_dir_ = command_line.GetSwitchValuePath(switches::kArtifactsDir);
}
}
if (mode == kPdiffTestMode) {
pdiff_enabled_ = true;
}
return true;
}
std::string ScreenshotTester::GetImageFileName(
const std::string& file_name_prefix,
ImageCategories category) {
std::string file_name = file_name_prefix + "_";
switch (category) {
case kGoldenScreenshot: {
file_name += "golden_screenshot";
break;
}
case kFailedScreenshot: {
file_name += "failed_screenshot";
break;
}
case kDifferenceImage: {
file_name += "difference";
break;
}
}
return file_name + ".png";
}
base::FilePath ScreenshotTester::GetImageFilePath(
const std::string& file_name_prefix,
ImageCategories category) {
std::string file_name = GetImageFileName(file_name_prefix, category);
base::FilePath file_path;
if (category == kGoldenScreenshot) {
file_path = golden_screenshots_dir_.AppendASCII(file_name);
} else {
file_path = artifacts_dir_.AppendASCII(file_name);
}
return file_path;
}
void ScreenshotTester::Run(const std::string& test_name) {
PNGFile current_screenshot = TakeScreenshot();
base::FilePath golden_screenshot_path =
GetImageFilePath(test_name, kGoldenScreenshot);
PNGFile golden_screenshot = LoadGoldenScreenshot(golden_screenshot_path);
if (test_mode_) {
CHECK(golden_screenshot.get())
<< "A golden screenshot is required for screenshot testing";
VLOG(0) << "Loaded golden screenshot";
Result result = CompareScreenshots(golden_screenshot, current_screenshot);
VLOG(0) << "Compared";
LogComparisonResults(result);
if (!result.screenshots_match && generate_artifacts_) {
// Saving diff imag
if (!pdiff_enabled_) {
base::FilePath difference_image_path =
GetImageFilePath(test_name, kDifferenceImage);
CHECK(SaveImage(difference_image_path, result.diff_image));
}
// Saving failed screenshot
base::FilePath failed_screenshot_path =
GetImageFilePath(test_name, kFailedScreenshot);
CHECK(SaveImage(failed_screenshot_path, current_screenshot));
}
ASSERT_TRUE(result.screenshots_match);
} else {
bool golden_screenshot_needs_update;
if (golden_screenshot.get()) {
// There is a golden screenshot, so we need to check it first.
Result result = CompareScreenshots(golden_screenshot, current_screenshot);
golden_screenshot_needs_update = (!result.screenshots_match);
} else {
// There is no golden screenshot for this test at all.
golden_screenshot_needs_update = true;
}
if (golden_screenshot_needs_update) {
bool golden_screenshot_saved =
SaveImage(golden_screenshot_path, current_screenshot);
CHECK(golden_screenshot_saved);
} else {
VLOG(0) << "Golden screenshot does not differ from the current one, no "
"need to update";
}
}
}
void ScreenshotTester::IgnoreArea(const SkIRect& area) {
ignored_areas_.push_back(area);
}
void ScreenshotTester::EraseIgnoredAreas(SkBitmap& bitmap) {
for (std::vector<SkIRect>::iterator it = ignored_areas_.begin();
it != ignored_areas_.end(); ++it) {
bitmap.eraseArea((*it), SK_ColorWHITE);
}
}
bool ScreenshotTester::SaveImage(const base::FilePath& image_path,
PNGFile png_data) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!png_data.get()) {
LOG(ERROR) << "There is no png data";
return false;
}
if (!base::CreateDirectory(image_path.DirName())) {
LOG(ERROR) << "Can't create directory" << image_path.DirName().value();
return false;
}
if (static_cast<size_t>(base::WriteFile(
image_path, reinterpret_cast<const char*>(png_data->front()),
png_data->size())) != png_data->size()) {
LOG(ERROR) << "Can't save screenshot " << image_path.BaseName().value()
<< ".";
return false;
}
VLOG(0) << "Screenshot " << image_path.BaseName().value() << " saved to "
<< image_path.DirName().value() << ".";
return true;
}
void ScreenshotTester::ReturnScreenshot(base::RunLoop* run_loop,
PNGFile* screenshot,
PNGFile png_data) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
*screenshot = png_data;
run_loop->Quit();
}
ScreenshotTester::PNGFile ScreenshotTester::TakeScreenshot() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
aura::Window* primary_window = ash::Shell::GetPrimaryRootWindow();
gfx::Rect rect = primary_window->bounds();
PNGFile screenshot;
base::RunLoop run_loop;
ui::GrabWindowSnapshotAsyncPNG(
primary_window, rect,
base::Bind(&ScreenshotTester::ReturnScreenshot,
weak_factory_.GetWeakPtr(), base::Unretained(&run_loop),
&screenshot));
run_loop.Run();
return screenshot;
}
ScreenshotTester::PNGFile ScreenshotTester::LoadGoldenScreenshot(
base::FilePath image_path) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!base::PathExists(image_path)) {
LOG(WARNING) << "Can't find a golden screenshot for this test";
return 0;
}
int64_t golden_screenshot_size;
base::GetFileSize(image_path, &golden_screenshot_size);
if (golden_screenshot_size == -1) {
CHECK(false) << "Can't get golden screenshot size";
}
scoped_refptr<base::RefCountedBytes> png_data = new base::RefCountedBytes;
png_data->data().resize(golden_screenshot_size);
base::ReadFile(image_path, reinterpret_cast<char*>(&(png_data->data()[0])),
golden_screenshot_size);
return png_data;
}
SkBitmap ScreenshotTester::ProcessImageForComparison(const PNGFile& image) {
CHECK(image.get());
SkBitmap current_bitmap;
gfx::PNGCodec::Decode(image->front(), image->size(), ¤t_bitmap);
EraseIgnoredAreas(current_bitmap);
return current_bitmap;
}
ScreenshotTester::Result ScreenshotTester::CompareScreenshots(
const PNGFile& model,
const PNGFile& sample) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
SkBitmap model_bitmap;
SkBitmap sample_bitmap;
model_bitmap = ProcessImageForComparison(model);
sample_bitmap = ProcessImageForComparison(sample);
if (pdiff_enabled_) {
return CompareScreenshotsPerceptually(model_bitmap, sample_bitmap);
} else {
return CompareScreenshotsRegularly(model_bitmap, sample_bitmap);
}
}
void ScreenshotTester::LogSimilarity(double similarity,
bool screenshots_match) {
VLOG(0) << "Screenshots similarity: " << std::setprecision(5)
<< similarity * 100 << "\%";
if (!pdiff_enabled_ && screenshots_match) {
if (similarity == 1) { // 100%
VLOG(0) << "Screenshots match perfectly";
} else {
VLOG(0) << "Screenshots differ slightly, but it is still a match";
}
}
}
void ScreenshotTester::LogComparisonResults(
const ScreenshotTester::Result& result) {
std::string comparison_type = pdiff_enabled_ ? "PerceptualDiff" : "regular";
if (result.screenshots_match) {
VLOG(0) << "Screenshot testing passed using " << comparison_type
<< " comparison";
} else {
LOG(ERROR) << "Screenshot testing failed using " << comparison_type
<< " comparison";
if (!pdiff_enabled_) {
VLOG(0) << "(HINT): Result may be false negative. Try using "
"PerceptualDiff comparison (use pdiff-test mode instead of "
"test)";
}
}
LogSimilarity(result.similarity, result.screenshots_match);
}
ScreenshotTester::Result ScreenshotTester::CompareScreenshotsRegularly(
SkBitmap model_bitmap,
SkBitmap sample_bitmap) {
SkDifferentPixelsMetric differ;
SkImageDiffer::BitmapsToCreate diff_parameters;
diff_parameters.rgbDiff = true;
SkImageDiffer::Result result;
differ.diff(&model_bitmap, &sample_bitmap, diff_parameters, &result);
Result testing_result;
testing_result.screenshots_match =
(result.result >= kPrecision &&
result.maxRedDiff <= kMaxAllowedColorDifference &&
result.maxGreenDiff <= kMaxAllowedColorDifference &&
result.maxBlueDiff <= kMaxAllowedColorDifference);
testing_result.similarity = result.result;
scoped_refptr<base::RefCountedBytes> diff_image(new base::RefCountedBytes);
diff_image->data().resize(result.rgbDiffBitmap.computeByteSize());
CHECK(gfx::PNGCodec::EncodeBGRASkBitmap(result.rgbDiffBitmap, false,
&diff_image->data()))
<< "Could not encode difference to PNG";
testing_result.diff_image = diff_image;
return testing_result;
}
ScreenshotTester::Result ScreenshotTester::CompareScreenshotsPerceptually(
SkBitmap model_bitmap,
SkBitmap sample_bitmap) {
SkPMetric differ;
SkImageDiffer::BitmapsToCreate diff_parameters;
SkImageDiffer::Result result;
differ.diff(&model_bitmap, &sample_bitmap, diff_parameters, &result);
ScreenshotTester::Result testing_result;
testing_result.similarity = result.result;
testing_result.screenshots_match =
(result.result == SkImageDiffer::RESULT_CORRECT);
return testing_result;
}
} // namespace chromeos
| null | null | null | null | 53,387 |
37,041 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 202,036 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | /*
* Copyright (c) 2014 MediaTek Inc.
* Author: Shunli Wang <shunli.wang@mediatek.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/clk-provider.h>
#include <linux/platform_device.h>
#include "clk-mtk.h"
#include "clk-gate.h"
#include <dt-bindings/clock/mt2701-clk.h>
static const struct mtk_gate_regs disp0_cg_regs = {
.set_ofs = 0x0104,
.clr_ofs = 0x0108,
.sta_ofs = 0x0100,
};
static const struct mtk_gate_regs disp1_cg_regs = {
.set_ofs = 0x0114,
.clr_ofs = 0x0118,
.sta_ofs = 0x0110,
};
#define GATE_DISP0(_id, _name, _parent, _shift) { \
.id = _id, \
.name = _name, \
.parent_name = _parent, \
.regs = &disp0_cg_regs, \
.shift = _shift, \
.ops = &mtk_clk_gate_ops_setclr, \
}
#define GATE_DISP1(_id, _name, _parent, _shift) { \
.id = _id, \
.name = _name, \
.parent_name = _parent, \
.regs = &disp1_cg_regs, \
.shift = _shift, \
.ops = &mtk_clk_gate_ops_setclr, \
}
static const struct mtk_gate mm_clks[] = {
GATE_DISP0(CLK_MM_SMI_COMMON, "mm_smi_comm", "mm_sel", 0),
GATE_DISP0(CLK_MM_SMI_LARB0, "mm_smi_larb0", "mm_sel", 1),
GATE_DISP0(CLK_MM_CMDQ, "mm_cmdq", "mm_sel", 2),
GATE_DISP0(CLK_MM_MUTEX, "mm_mutex", "mm_sel", 3),
GATE_DISP0(CLK_MM_DISP_COLOR, "mm_disp_color", "mm_sel", 4),
GATE_DISP0(CLK_MM_DISP_BLS, "mm_disp_bls", "mm_sel", 5),
GATE_DISP0(CLK_MM_DISP_WDMA, "mm_disp_wdma", "mm_sel", 6),
GATE_DISP0(CLK_MM_DISP_RDMA, "mm_disp_rdma", "mm_sel", 7),
GATE_DISP0(CLK_MM_DISP_OVL, "mm_disp_ovl", "mm_sel", 8),
GATE_DISP0(CLK_MM_MDP_TDSHP, "mm_mdp_tdshp", "mm_sel", 9),
GATE_DISP0(CLK_MM_MDP_WROT, "mm_mdp_wrot", "mm_sel", 10),
GATE_DISP0(CLK_MM_MDP_WDMA, "mm_mdp_wdma", "mm_sel", 11),
GATE_DISP0(CLK_MM_MDP_RSZ1, "mm_mdp_rsz1", "mm_sel", 12),
GATE_DISP0(CLK_MM_MDP_RSZ0, "mm_mdp_rsz0", "mm_sel", 13),
GATE_DISP0(CLK_MM_MDP_RDMA, "mm_mdp_rdma", "mm_sel", 14),
GATE_DISP0(CLK_MM_MDP_BLS_26M, "mm_mdp_bls_26m", "pwm_sel", 15),
GATE_DISP0(CLK_MM_CAM_MDP, "mm_cam_mdp", "mm_sel", 16),
GATE_DISP0(CLK_MM_FAKE_ENG, "mm_fake_eng", "mm_sel", 17),
GATE_DISP0(CLK_MM_MUTEX_32K, "mm_mutex_32k", "rtc_sel", 18),
GATE_DISP0(CLK_MM_DISP_RDMA1, "mm_disp_rdma1", "mm_sel", 19),
GATE_DISP0(CLK_MM_DISP_UFOE, "mm_disp_ufoe", "mm_sel", 20),
GATE_DISP1(CLK_MM_DSI_ENGINE, "mm_dsi_eng", "mm_sel", 0),
GATE_DISP1(CLK_MM_DSI_DIG, "mm_dsi_dig", "dsi0_lntc_dsi", 1),
GATE_DISP1(CLK_MM_DPI_DIGL, "mm_dpi_digl", "dpi0_sel", 2),
GATE_DISP1(CLK_MM_DPI_ENGINE, "mm_dpi_eng", "mm_sel", 3),
GATE_DISP1(CLK_MM_DPI1_DIGL, "mm_dpi1_digl", "dpi1_sel", 4),
GATE_DISP1(CLK_MM_DPI1_ENGINE, "mm_dpi1_eng", "mm_sel", 5),
GATE_DISP1(CLK_MM_TVE_OUTPUT, "mm_tve_output", "tve_sel", 6),
GATE_DISP1(CLK_MM_TVE_INPUT, "mm_tve_input", "dpi0_sel", 7),
GATE_DISP1(CLK_MM_HDMI_PIXEL, "mm_hdmi_pixel", "dpi1_sel", 8),
GATE_DISP1(CLK_MM_HDMI_PLL, "mm_hdmi_pll", "hdmi_sel", 9),
GATE_DISP1(CLK_MM_HDMI_AUDIO, "mm_hdmi_audio", "apll_sel", 10),
GATE_DISP1(CLK_MM_HDMI_SPDIF, "mm_hdmi_spdif", "apll_sel", 11),
GATE_DISP1(CLK_MM_TVE_FMM, "mm_tve_fmm", "mm_sel", 14),
};
static const struct of_device_id of_match_clk_mt2701_mm[] = {
{ .compatible = "mediatek,mt2701-mmsys", },
{}
};
static int clk_mt2701_mm_probe(struct platform_device *pdev)
{
struct clk_onecell_data *clk_data;
int r;
struct device_node *node = pdev->dev.of_node;
clk_data = mtk_alloc_clk_data(CLK_MM_NR);
mtk_clk_register_gates(node, mm_clks, ARRAY_SIZE(mm_clks),
clk_data);
r = of_clk_add_provider(node, of_clk_src_onecell_get, clk_data);
if (r)
dev_err(&pdev->dev,
"could not register clock provider: %s: %d\n",
pdev->name, r);
return r;
}
static struct platform_driver clk_mt2701_mm_drv = {
.probe = clk_mt2701_mm_probe,
.driver = {
.name = "clk-mt2701-mm",
.of_match_table = of_match_clk_mt2701_mm,
},
};
builtin_platform_driver(clk_mt2701_mm_drv);
| null | null | null | null | 110,383 |
14,429 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 179,424 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | #ifndef __iop_sap_in_defs_h
#define __iop_sap_in_defs_h
/*
* This file is autogenerated from
* file: ../../inst/io_proc/rtl/iop_sap_in.r
* id: <not found>
* last modfied: Mon Apr 11 16:08:45 2005
*
* by /n/asic/design/tools/rdesc/src/rdes2c --outfile iop_sap_in_defs.h ../../inst/io_proc/rtl/iop_sap_in.r
* id: $Id: iop_sap_in_defs.h,v 1.5 2005/04/24 18:31:05 starvik Exp $
* Any changes here will be lost.
*
* -*- buffer-read-only: t -*-
*/
/* Main access macros */
#ifndef REG_RD
#define REG_RD( scope, inst, reg ) \
REG_READ( reg_##scope##_##reg, \
(inst) + REG_RD_ADDR_##scope##_##reg )
#endif
#ifndef REG_WR
#define REG_WR( scope, inst, reg, val ) \
REG_WRITE( reg_##scope##_##reg, \
(inst) + REG_WR_ADDR_##scope##_##reg, (val) )
#endif
#ifndef REG_RD_VECT
#define REG_RD_VECT( scope, inst, reg, index ) \
REG_READ( reg_##scope##_##reg, \
(inst) + REG_RD_ADDR_##scope##_##reg + \
(index) * STRIDE_##scope##_##reg )
#endif
#ifndef REG_WR_VECT
#define REG_WR_VECT( scope, inst, reg, index, val ) \
REG_WRITE( reg_##scope##_##reg, \
(inst) + REG_WR_ADDR_##scope##_##reg + \
(index) * STRIDE_##scope##_##reg, (val) )
#endif
#ifndef REG_RD_INT
#define REG_RD_INT( scope, inst, reg ) \
REG_READ( int, (inst) + REG_RD_ADDR_##scope##_##reg )
#endif
#ifndef REG_WR_INT
#define REG_WR_INT( scope, inst, reg, val ) \
REG_WRITE( int, (inst) + REG_WR_ADDR_##scope##_##reg, (val) )
#endif
#ifndef REG_RD_INT_VECT
#define REG_RD_INT_VECT( scope, inst, reg, index ) \
REG_READ( int, (inst) + REG_RD_ADDR_##scope##_##reg + \
(index) * STRIDE_##scope##_##reg )
#endif
#ifndef REG_WR_INT_VECT
#define REG_WR_INT_VECT( scope, inst, reg, index, val ) \
REG_WRITE( int, (inst) + REG_WR_ADDR_##scope##_##reg + \
(index) * STRIDE_##scope##_##reg, (val) )
#endif
#ifndef REG_TYPE_CONV
#define REG_TYPE_CONV( type, orgtype, val ) \
( { union { orgtype o; type n; } r; r.o = val; r.n; } )
#endif
#ifndef reg_page_size
#define reg_page_size 8192
#endif
#ifndef REG_ADDR
#define REG_ADDR( scope, inst, reg ) \
( (inst) + REG_RD_ADDR_##scope##_##reg )
#endif
#ifndef REG_ADDR_VECT
#define REG_ADDR_VECT( scope, inst, reg, index ) \
( (inst) + REG_RD_ADDR_##scope##_##reg + \
(index) * STRIDE_##scope##_##reg )
#endif
/* C-code for register scope iop_sap_in */
/* Register rw_bus0_sync, scope iop_sap_in, type rw */
typedef struct {
unsigned int byte0_sel : 2;
unsigned int byte0_ext_src : 3;
unsigned int byte0_edge : 2;
unsigned int byte0_delay : 1;
unsigned int byte1_sel : 2;
unsigned int byte1_ext_src : 3;
unsigned int byte1_edge : 2;
unsigned int byte1_delay : 1;
unsigned int byte2_sel : 2;
unsigned int byte2_ext_src : 3;
unsigned int byte2_edge : 2;
unsigned int byte2_delay : 1;
unsigned int byte3_sel : 2;
unsigned int byte3_ext_src : 3;
unsigned int byte3_edge : 2;
unsigned int byte3_delay : 1;
} reg_iop_sap_in_rw_bus0_sync;
#define REG_RD_ADDR_iop_sap_in_rw_bus0_sync 0
#define REG_WR_ADDR_iop_sap_in_rw_bus0_sync 0
/* Register rw_bus1_sync, scope iop_sap_in, type rw */
typedef struct {
unsigned int byte0_sel : 2;
unsigned int byte0_ext_src : 3;
unsigned int byte0_edge : 2;
unsigned int byte0_delay : 1;
unsigned int byte1_sel : 2;
unsigned int byte1_ext_src : 3;
unsigned int byte1_edge : 2;
unsigned int byte1_delay : 1;
unsigned int byte2_sel : 2;
unsigned int byte2_ext_src : 3;
unsigned int byte2_edge : 2;
unsigned int byte2_delay : 1;
unsigned int byte3_sel : 2;
unsigned int byte3_ext_src : 3;
unsigned int byte3_edge : 2;
unsigned int byte3_delay : 1;
} reg_iop_sap_in_rw_bus1_sync;
#define REG_RD_ADDR_iop_sap_in_rw_bus1_sync 4
#define REG_WR_ADDR_iop_sap_in_rw_bus1_sync 4
#define STRIDE_iop_sap_in_rw_gio 4
/* Register rw_gio, scope iop_sap_in, type rw */
typedef struct {
unsigned int sync_sel : 2;
unsigned int sync_ext_src : 3;
unsigned int sync_edge : 2;
unsigned int delay : 1;
unsigned int logic : 2;
unsigned int dummy1 : 22;
} reg_iop_sap_in_rw_gio;
#define REG_RD_ADDR_iop_sap_in_rw_gio 8
#define REG_WR_ADDR_iop_sap_in_rw_gio 8
/* Constants */
enum {
regk_iop_sap_in_and = 0x00000002,
regk_iop_sap_in_ext_clk200 = 0x00000003,
regk_iop_sap_in_gio1 = 0x00000000,
regk_iop_sap_in_gio13 = 0x00000005,
regk_iop_sap_in_gio18 = 0x00000003,
regk_iop_sap_in_gio19 = 0x00000004,
regk_iop_sap_in_gio21 = 0x00000006,
regk_iop_sap_in_gio23 = 0x00000005,
regk_iop_sap_in_gio29 = 0x00000007,
regk_iop_sap_in_gio5 = 0x00000004,
regk_iop_sap_in_gio6 = 0x00000001,
regk_iop_sap_in_gio7 = 0x00000002,
regk_iop_sap_in_inv = 0x00000001,
regk_iop_sap_in_neg = 0x00000002,
regk_iop_sap_in_no = 0x00000000,
regk_iop_sap_in_no_del_ext_clk200 = 0x00000001,
regk_iop_sap_in_none = 0x00000000,
regk_iop_sap_in_or = 0x00000003,
regk_iop_sap_in_pos = 0x00000001,
regk_iop_sap_in_pos_neg = 0x00000003,
regk_iop_sap_in_rw_bus0_sync_default = 0x02020202,
regk_iop_sap_in_rw_bus1_sync_default = 0x02020202,
regk_iop_sap_in_rw_gio_default = 0x00000002,
regk_iop_sap_in_rw_gio_size = 0x00000020,
regk_iop_sap_in_timer_grp0_tmr3 = 0x00000006,
regk_iop_sap_in_timer_grp1_tmr3 = 0x00000004,
regk_iop_sap_in_timer_grp2_tmr3 = 0x00000005,
regk_iop_sap_in_timer_grp3_tmr3 = 0x00000007,
regk_iop_sap_in_tmr_clk200 = 0x00000000,
regk_iop_sap_in_two_clk200 = 0x00000002,
regk_iop_sap_in_yes = 0x00000001
};
#endif /* __iop_sap_in_defs_h */
| null | null | null | null | 87,771 |
20,645 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 20,645 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2014 The Chromium 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 CONTENT_SHELL_TEST_RUNNER_MOCK_WEB_THEME_ENGINE_H_
#define CONTENT_SHELL_TEST_RUNNER_MOCK_WEB_THEME_ENGINE_H_
#include "build/build_config.h"
#include "third_party/blink/public/platform/web_theme_engine.h"
namespace test_runner {
class MockWebThemeEngine : public blink::WebThemeEngine {
public:
virtual ~MockWebThemeEngine() {}
#if !defined(OS_MACOSX)
// blink::WebThemeEngine:
blink::WebSize GetSize(blink::WebThemeEngine::Part) override;
void Paint(blink::WebCanvas*,
blink::WebThemeEngine::Part,
blink::WebThemeEngine::State,
const blink::WebRect&,
const blink::WebThemeEngine::ExtraParams*) override;
#endif // !defined(OS_MACOSX)
};
} // namespace test_runner
#endif // CONTENT_SHELL_TEST_RUNNER_MOCK_WEB_THEME_ENGINE_H_
| null | null | null | null | 17,508 |
49,880 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 49,880 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2013 The Chromium 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 "ui/android/window_android.h"
#include "base/android/jni_android.h"
#include "base/android/jni_array.h"
#include "base/android/jni_string.h"
#include "base/android/jni_weak_ref.h"
#include "base/android/scoped_java_ref.h"
#include "base/observer_list.h"
#include "base/stl_util.h"
#include "components/viz/common/frame_sinks/begin_frame_args.h"
#include "components/viz/common/frame_sinks/begin_frame_source.h"
#include "jni/WindowAndroid_jni.h"
#include "ui/android/window_android_compositor.h"
#include "ui/android/window_android_observer.h"
namespace ui {
using base::android::AttachCurrentThread;
using base::android::JavaParamRef;
using base::android::JavaRef;
using base::android::ScopedJavaLocalRef;
const float kDefaultMouseWheelTickMultiplier = 64;
class WindowAndroid::WindowBeginFrameSource : public viz::BeginFrameSource {
public:
explicit WindowBeginFrameSource(WindowAndroid* window)
: BeginFrameSource(kNotRestartableId),
window_(window),
observers_(base::ObserverListPolicy::EXISTING_ONLY),
observer_count_(0),
next_sequence_number_(viz::BeginFrameArgs::kStartingFrameNumber),
paused_(false) {}
~WindowBeginFrameSource() override {}
// viz::BeginFrameSource implementation.
void AddObserver(viz::BeginFrameObserver* obs) override;
void RemoveObserver(viz::BeginFrameObserver* obs) override;
void DidFinishFrame(viz::BeginFrameObserver* obs) override {}
bool IsThrottled() const override { return true; }
void OnVSync(base::TimeTicks frame_time, base::TimeDelta vsync_period);
void OnPauseChanged(bool paused);
private:
WindowAndroid* const window_;
base::ObserverList<viz::BeginFrameObserver> observers_;
int observer_count_;
viz::BeginFrameArgs last_begin_frame_args_;
uint64_t next_sequence_number_;
bool paused_;
};
void WindowAndroid::WindowBeginFrameSource::AddObserver(
viz::BeginFrameObserver* obs) {
DCHECK(obs);
DCHECK(!observers_.HasObserver(obs));
observers_.AddObserver(obs);
observer_count_++;
obs->OnBeginFrameSourcePausedChanged(paused_);
window_->SetNeedsBeginFrames(true);
// Send a MISSED BeginFrame if possible and necessary.
if (last_begin_frame_args_.IsValid()) {
viz::BeginFrameArgs last_args = obs->LastUsedBeginFrameArgs();
if (!last_args.IsValid() ||
last_args.frame_time < last_begin_frame_args_.frame_time) {
DCHECK(last_args.sequence_number <
last_begin_frame_args_.sequence_number ||
last_args.source_id != last_begin_frame_args_.source_id);
last_begin_frame_args_.type = viz::BeginFrameArgs::MISSED;
// TODO(crbug.com/602485): A deadline doesn't make too much sense
// for a missed BeginFrame (the intention rather is 'immediately'),
// but currently the retro frame logic is very strict in discarding
// BeginFrames.
last_begin_frame_args_.deadline =
base::TimeTicks::Now() + last_begin_frame_args_.interval;
obs->OnBeginFrame(last_begin_frame_args_);
}
}
}
void WindowAndroid::WindowBeginFrameSource::RemoveObserver(
viz::BeginFrameObserver* obs) {
DCHECK(obs);
DCHECK(observers_.HasObserver(obs));
observers_.RemoveObserver(obs);
observer_count_--;
if (observer_count_ <= 0)
window_->SetNeedsBeginFrames(false);
}
void WindowAndroid::WindowBeginFrameSource::OnVSync(
base::TimeTicks frame_time,
base::TimeDelta vsync_period) {
// frame time is in the past, so give the next vsync period as the deadline.
base::TimeTicks deadline = frame_time + vsync_period;
last_begin_frame_args_ = viz::BeginFrameArgs::Create(
BEGINFRAME_FROM_HERE, source_id(), next_sequence_number_, frame_time,
deadline, vsync_period, viz::BeginFrameArgs::NORMAL);
DCHECK(last_begin_frame_args_.IsValid());
next_sequence_number_++;
for (auto& obs : observers_)
obs.OnBeginFrame(last_begin_frame_args_);
}
void WindowAndroid::WindowBeginFrameSource::OnPauseChanged(bool paused) {
paused_ = paused;
for (auto& obs : observers_)
obs.OnBeginFrameSourcePausedChanged(paused_);
}
// static
WindowAndroid* WindowAndroid::FromJavaWindowAndroid(
const JavaParamRef<jobject>& jwindow_android) {
if (jwindow_android.is_null())
return nullptr;
return reinterpret_cast<WindowAndroid*>(Java_WindowAndroid_getNativePointer(
AttachCurrentThread(), jwindow_android));
}
WindowAndroid::WindowAndroid(JNIEnv* env,
jobject obj,
int display_id,
float scroll_factor)
: display_id_(display_id),
compositor_(NULL),
begin_frame_source_(new WindowBeginFrameSource(this)),
needs_begin_frames_(false) {
java_window_.Reset(env, obj);
mouse_wheel_scroll_factor_ =
scroll_factor > 0 ? scroll_factor
: kDefaultMouseWheelTickMultiplier * GetDipScale();
}
void WindowAndroid::Destroy(JNIEnv* env, const JavaParamRef<jobject>& obj) {
delete this;
}
ScopedJavaLocalRef<jobject> WindowAndroid::GetJavaObject() {
return base::android::ScopedJavaLocalRef<jobject>(java_window_);
}
WindowAndroid::~WindowAndroid() {
DCHECK(parent_ == nullptr) << "WindowAndroid must be a root view.";
DCHECK(!compositor_);
Java_WindowAndroid_clearNativePointer(AttachCurrentThread(), GetJavaObject());
}
WindowAndroid* WindowAndroid::CreateForTesting() {
JNIEnv* env = AttachCurrentThread();
long native_pointer = Java_WindowAndroid_createForTesting(env);
return reinterpret_cast<WindowAndroid*>(native_pointer);
}
void WindowAndroid::OnCompositingDidCommit() {
for (WindowAndroidObserver& observer : observer_list_)
observer.OnCompositingDidCommit();
}
void WindowAndroid::AddObserver(WindowAndroidObserver* observer) {
if (!observer_list_.HasObserver(observer))
observer_list_.AddObserver(observer);
}
void WindowAndroid::AddVSyncCompleteCallback(const base::Closure& callback) {
vsync_complete_callbacks_.push_back(callback);
}
void WindowAndroid::RemoveObserver(WindowAndroidObserver* observer) {
observer_list_.RemoveObserver(observer);
}
viz::BeginFrameSource* WindowAndroid::GetBeginFrameSource() {
return begin_frame_source_.get();
}
void WindowAndroid::AttachCompositor(WindowAndroidCompositor* compositor) {
if (compositor_ && compositor != compositor_)
DetachCompositor();
compositor_ = compositor;
for (WindowAndroidObserver& observer : observer_list_)
observer.OnAttachCompositor();
}
void WindowAndroid::DetachCompositor() {
compositor_ = NULL;
for (WindowAndroidObserver& observer : observer_list_)
observer.OnDetachCompositor();
observer_list_.Clear();
}
void WindowAndroid::RequestVSyncUpdate() {
JNIEnv* env = AttachCurrentThread();
Java_WindowAndroid_requestVSyncUpdate(env, GetJavaObject());
}
void WindowAndroid::SetNeedsBeginFrames(bool needs_begin_frames) {
if (needs_begin_frames_ == needs_begin_frames)
return;
needs_begin_frames_ = needs_begin_frames;
if (needs_begin_frames_)
RequestVSyncUpdate();
}
void WindowAndroid::SetNeedsAnimate() {
if (compositor_)
compositor_->SetNeedsAnimate();
}
void WindowAndroid::Animate(base::TimeTicks begin_frame_time) {
for (WindowAndroidObserver& observer : observer_list_)
observer.OnAnimate(begin_frame_time);
}
void WindowAndroid::OnVSync(JNIEnv* env,
const JavaParamRef<jobject>& obj,
jlong time_micros,
jlong period_micros) {
// Warning: It is generally unsafe to manufacture TimeTicks values. The
// following assumption is being made, AND COULD EASILY BREAK AT ANY TIME:
// Upstream, Java code is providing "System.nanos() / 1000," and this is the
// same timestamp that would be provided by the CLOCK_MONOTONIC POSIX clock.
DCHECK_EQ(base::TimeTicks::GetClock(),
base::TimeTicks::Clock::LINUX_CLOCK_MONOTONIC);
base::TimeTicks frame_time =
base::TimeTicks() + base::TimeDelta::FromMicroseconds(time_micros);
base::TimeDelta vsync_period(
base::TimeDelta::FromMicroseconds(period_micros));
begin_frame_source_->OnVSync(frame_time, vsync_period);
for (const base::Closure& callback : vsync_complete_callbacks_)
callback.Run();
vsync_complete_callbacks_.clear();
if (needs_begin_frames_)
RequestVSyncUpdate();
}
void WindowAndroid::OnVisibilityChanged(JNIEnv* env,
const JavaParamRef<jobject>& obj,
bool visible) {
for (WindowAndroidObserver& observer : observer_list_)
observer.OnRootWindowVisibilityChanged(visible);
}
void WindowAndroid::OnActivityStopped(JNIEnv* env,
const JavaParamRef<jobject>& obj) {
for (WindowAndroidObserver& observer : observer_list_)
observer.OnActivityStopped();
}
void WindowAndroid::OnActivityStarted(JNIEnv* env,
const JavaParamRef<jobject>& obj) {
for (WindowAndroidObserver& observer : observer_list_)
observer.OnActivityStarted();
}
void WindowAndroid::SetVSyncPaused(JNIEnv* env,
const JavaParamRef<jobject>& obj,
bool paused) {
begin_frame_source_->OnPauseChanged(paused);
}
bool WindowAndroid::HasPermission(const std::string& permission) {
JNIEnv* env = AttachCurrentThread();
return Java_WindowAndroid_hasPermission(
env, GetJavaObject(),
base::android::ConvertUTF8ToJavaString(env, permission));
}
bool WindowAndroid::CanRequestPermission(const std::string& permission) {
JNIEnv* env = AttachCurrentThread();
return Java_WindowAndroid_canRequestPermission(
env, GetJavaObject(),
base::android::ConvertUTF8ToJavaString(env, permission));
}
WindowAndroid* WindowAndroid::GetWindowAndroid() const {
DCHECK(parent_ == nullptr);
return const_cast<WindowAndroid*>(this);
}
ScopedJavaLocalRef<jobject> WindowAndroid::GetWindowToken() {
JNIEnv* env = AttachCurrentThread();
return Java_WindowAndroid_getWindowToken(env, GetJavaObject());
}
// ----------------------------------------------------------------------------
// Native JNI methods
// ----------------------------------------------------------------------------
jlong JNI_WindowAndroid_Init(JNIEnv* env,
const JavaParamRef<jobject>& obj,
int sdk_display_id,
float scroll_factor) {
WindowAndroid* window =
new WindowAndroid(env, obj, sdk_display_id, scroll_factor);
return reinterpret_cast<intptr_t>(window);
}
} // namespace ui
| null | null | null | null | 46,743 |
10,040 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 175,035 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | /*
* arch/arm/mach-vt8500/vt8500.c
*
* Copyright (C) 2012 Tony Prisk <linux@prisktech.co.nz>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/io.h>
#include <linux/pm.h>
#include <linux/reboot.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/time.h>
#include <asm/mach/map.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#define LEGACY_GPIO_BASE 0xD8110000
#define LEGACY_PMC_BASE 0xD8130000
/* Registers in GPIO Controller */
#define VT8500_GPIO_MUX_REG 0x200
/* Registers in Power Management Controller */
#define VT8500_HCR_REG 0x12
#define VT8500_PMSR_REG 0x60
static void __iomem *pmc_base;
static void vt8500_restart(enum reboot_mode mode, const char *cmd)
{
if (pmc_base)
writel(1, pmc_base + VT8500_PMSR_REG);
}
static struct map_desc vt8500_io_desc[] __initdata = {
/* SoC MMIO registers */
[0] = {
.virtual = 0xf8000000,
.pfn = __phys_to_pfn(0xd8000000),
.length = 0x00390000, /* max of all chip variants */
.type = MT_DEVICE
},
};
static void __init vt8500_map_io(void)
{
iotable_init(vt8500_io_desc, ARRAY_SIZE(vt8500_io_desc));
}
static void vt8500_power_off(void)
{
local_irq_disable();
writew(5, pmc_base + VT8500_HCR_REG);
asm("mcr p15, 0, %0, c7, c0, 4" : : "r" (0));
}
static void __init vt8500_init(void)
{
struct device_node *np;
#if defined(CONFIG_FB_VT8500) || defined(CONFIG_FB_WM8505)
struct device_node *fb;
void __iomem *gpio_base;
#endif
#ifdef CONFIG_FB_VT8500
fb = of_find_compatible_node(NULL, NULL, "via,vt8500-fb");
if (fb) {
np = of_find_compatible_node(NULL, NULL, "via,vt8500-gpio");
if (np) {
gpio_base = of_iomap(np, 0);
if (!gpio_base)
pr_err("%s: of_iomap(gpio_mux) failed\n",
__func__);
of_node_put(np);
} else {
gpio_base = ioremap(LEGACY_GPIO_BASE, 0x1000);
if (!gpio_base)
pr_err("%s: ioremap(legacy_gpio_mux) failed\n",
__func__);
}
if (gpio_base) {
writel(readl(gpio_base + VT8500_GPIO_MUX_REG) | 1,
gpio_base + VT8500_GPIO_MUX_REG);
iounmap(gpio_base);
} else
pr_err("%s: Could not remap GPIO mux\n", __func__);
of_node_put(fb);
}
#endif
#ifdef CONFIG_FB_WM8505
fb = of_find_compatible_node(NULL, NULL, "wm,wm8505-fb");
if (fb) {
np = of_find_compatible_node(NULL, NULL, "wm,wm8505-gpio");
if (!np)
np = of_find_compatible_node(NULL, NULL,
"wm,wm8650-gpio");
if (np) {
gpio_base = of_iomap(np, 0);
if (!gpio_base)
pr_err("%s: of_iomap(gpio_mux) failed\n",
__func__);
of_node_put(np);
} else {
gpio_base = ioremap(LEGACY_GPIO_BASE, 0x1000);
if (!gpio_base)
pr_err("%s: ioremap(legacy_gpio_mux) failed\n",
__func__);
}
if (gpio_base) {
writel(readl(gpio_base + VT8500_GPIO_MUX_REG) |
0x80000000, gpio_base + VT8500_GPIO_MUX_REG);
iounmap(gpio_base);
} else
pr_err("%s: Could not remap GPIO mux\n", __func__);
of_node_put(fb);
}
#endif
np = of_find_compatible_node(NULL, NULL, "via,vt8500-pmc");
if (np) {
pmc_base = of_iomap(np, 0);
if (!pmc_base)
pr_err("%s:of_iomap(pmc) failed\n", __func__);
of_node_put(np);
} else {
pmc_base = ioremap(LEGACY_PMC_BASE, 0x1000);
if (!pmc_base)
pr_err("%s:ioremap(power_off) failed\n", __func__);
}
if (pmc_base)
pm_power_off = &vt8500_power_off;
else
pr_err("%s: PMC Hibernation register could not be remapped, not enabling power off!\n", __func__);
}
static const char * const vt8500_dt_compat[] = {
"via,vt8500",
"wm,wm8650",
"wm,wm8505",
"wm,wm8750",
"wm,wm8850",
NULL
};
DT_MACHINE_START(WMT_DT, "VIA/Wondermedia SoC (Device Tree Support)")
.dt_compat = vt8500_dt_compat,
.map_io = vt8500_map_io,
.init_machine = vt8500_init,
.restart = vt8500_restart,
MACHINE_END
| null | null | null | null | 83,382 |
44,076 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 44,076 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright (c) 2014 The Chromium 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 <pthread.h>
#include <stddef.h>
#include <stdint.h>
#include <unistd.h>
#include <sstream>
#include <string>
#include "native_client/src/untrusted/irt/irt.h"
#include "ppapi/cpp/completion_callback.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/tcp_socket.h"
#include "ppapi/cpp/var.h"
#include "ppapi/utility/completion_callback_factory.h"
#if defined(__clang__)
// ipc_message_attachment_set.h depends on C++11 which nacl-g++ does not
// fully support.
#include "ipc/ipc_message_attachment_set.h"
#endif
namespace {
std::string g_last_error;
pp::Instance* g_instance = NULL;
// This should be larger than or equal to
// MessageAttachmentSet::kMaxDescriptorsPerMessage in
// ipc/ipc_message_attachment_set.h.
const size_t kMaxDescriptorsPerMessage = 128;
#if defined(__clang__)
static_assert(kMaxDescriptorsPerMessage >=
IPC::MessageAttachmentSet::kMaxDescriptorsPerMessage,
"kMaxDescriptorsPerMessage is not up to date");
#endif
// Returns true if the resource file whose name is |key| exists and its content
// matches |content|.
bool LoadManifestInternal(nacl_irt_resource_open* nacl_irt_resource_open,
const std::string& key,
const std::string& content) {
int desc;
int error;
error = nacl_irt_resource_open->open_resource(key.c_str(), &desc);
if (0 != error) {
g_last_error = "Can't open file " + key;
return false;
}
std::string str;
char buffer[4096];
int len;
while ((len = read(desc, buffer, sizeof(buffer) - 1)) > 0) {
// Null terminate.
buffer[len] = '\0';
str += buffer;
}
if (close(desc)) {
g_last_error = "Close failed: file=" + key;
return false;
}
if (str != content) {
g_last_error = "Wrong file content: file=" + key + ", expected=" + content +
", actual=" + str;
return false;
}
return true;
}
// Tests if open_resource works in a packaged app. This test is similar to
// NaClBrowserTest*.IrtManifestFile, but unlike the NaCl test, this one tests
// the "fast path" in DownloadNexe() in ppb_nacl_private_impl.cc which opens
// resource files without using URLLoader.
void LoadManifest() {
if (pthread_detach(pthread_self())) {
g_last_error = "pthread_detach failed";
return;
}
struct nacl_irt_resource_open nacl_irt_resource_open;
if (sizeof(nacl_irt_resource_open) !=
nacl_interface_query(NACL_IRT_RESOURCE_OPEN_v0_1,
&nacl_irt_resource_open,
sizeof(nacl_irt_resource_open))) {
g_last_error = "NACL_IRT_RESOURCE_OPEN_v0_1 not found";
return;
}
for (size_t i = 0; i <= kMaxDescriptorsPerMessage; ++i) {
std::stringstream key;
key << "test_file" << i;
std::string content = "Example contents for open_resource test" +
std::string(i % 2 ? "2" : "");
if (!LoadManifestInternal(&nacl_irt_resource_open, key.str(), content))
break;
// Open the same resource file again to make sure each file descriptor
// returned from open_resource has its own file offset.
if (!LoadManifestInternal(&nacl_irt_resource_open, key.str(), content))
break;
}
}
void PostReply(void* user_data, int32_t status) {
if (!g_last_error.empty())
g_instance->PostMessage(g_last_error.c_str());
else
g_instance->PostMessage("PASS");
}
void* RunTestsOnBackgroundThread(void* thread_id) {
LoadManifest();
pp::Module::Get()->core()->CallOnMainThread(
0, pp::CompletionCallback(&PostReply, NULL));
return NULL;
}
class MyInstance : public pp::Instance {
public:
explicit MyInstance(PP_Instance instance)
: pp::Instance(instance), socket_(this), factory_(this) {
g_instance = this;
}
virtual ~MyInstance() { }
void DidBindSocket(int32_t result) {
// We didn't ask for socket permission in our manifest, so it should fail.
if (result == PP_ERROR_NOACCESS)
PostMessage("PASS");
else
PostMessage(result);
}
virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]) {
pthread_t thread;
// irt_open_resource() isn't allowed to be called on the main thread once
// Pepper starts, so the test must happen on a background thread.
if (pthread_create(&thread, NULL, &RunTestsOnBackgroundThread, NULL)) {
g_last_error = "pthread_create failed";
PostReply(NULL, 0);
}
// Attempt to bind a socket. We don't have permissions, so it should fail.
PP_NetAddress_IPv4 ipv4_address = {80, {127, 0, 0, 1} };
pp::NetAddress address(this, ipv4_address);
socket_.Bind(address, factory_.NewCallback(&MyInstance::DidBindSocket));
return true;
}
private:
pp::TCPSocket socket_;
pp::CompletionCallbackFactory<MyInstance> factory_;
};
class MyModule : public pp::Module {
public:
MyModule() : pp::Module() { }
virtual ~MyModule() { }
virtual pp::Instance* CreateInstance(PP_Instance instance) {
return new MyInstance(instance);
}
};
} // namespace
namespace pp {
Module* CreateModule() {
return new MyModule();
}
} // namespace pp
| null | null | null | null | 40,939 |
51,284 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 51,284 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2014 The Chromium 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 "ui/events/ozone/device/device_manager.h"
#include "base/memory/ptr_util.h"
#include "base/trace_event/trace_event.h"
#if defined(USE_UDEV)
#include "ui/events/ozone/device/udev/device_manager_udev.h"
#else
#include "ui/events/ozone/device/device_manager_manual.h"
#endif
namespace ui {
std::unique_ptr<DeviceManager> CreateDeviceManager() {
TRACE_EVENT0("ozone", "CreateDeviceManager");
#if defined(USE_UDEV)
return std::make_unique<DeviceManagerUdev>();
#else
return std::make_unique<DeviceManagerManual>();
#endif
}
} // namespace ui
| null | null | null | null | 48,147 |
5,730 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 5,730 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2013 The Chromium 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_DBUS_FAKE_SHILL_SERVICE_CLIENT_H_
#define CHROMEOS_DBUS_FAKE_SHILL_SERVICE_CLIENT_H_
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "base/callback.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "chromeos/chromeos_export.h"
#include "chromeos/dbus/shill_service_client.h"
namespace chromeos {
// A fake implementation of ShillServiceClient. This works in close coordination
// with FakeShillManagerClient and is not intended to be used independently.
class CHROMEOS_EXPORT FakeShillServiceClient
: public ShillServiceClient,
public ShillServiceClient::TestInterface {
public:
FakeShillServiceClient();
~FakeShillServiceClient() override;
// ShillServiceClient overrides
void Init(dbus::Bus* bus) override;
void AddPropertyChangedObserver(
const dbus::ObjectPath& service_path,
ShillPropertyChangedObserver* observer) override;
void RemovePropertyChangedObserver(
const dbus::ObjectPath& service_path,
ShillPropertyChangedObserver* observer) override;
void GetProperties(const dbus::ObjectPath& service_path,
const DictionaryValueCallback& callback) override;
void SetProperty(const dbus::ObjectPath& service_path,
const std::string& name,
const base::Value& value,
const base::Closure& callback,
const ErrorCallback& error_callback) override;
void SetProperties(const dbus::ObjectPath& service_path,
const base::DictionaryValue& properties,
const base::Closure& callback,
const ErrorCallback& error_callback) override;
void ClearProperty(const dbus::ObjectPath& service_path,
const std::string& name,
const base::Closure& callback,
const ErrorCallback& error_callback) override;
void ClearProperties(const dbus::ObjectPath& service_path,
const std::vector<std::string>& names,
const ListValueCallback& callback,
const ErrorCallback& error_callback) override;
void Connect(const dbus::ObjectPath& service_path,
const base::Closure& callback,
const ErrorCallback& error_callback) override;
void Disconnect(const dbus::ObjectPath& service_path,
const base::Closure& callback,
const ErrorCallback& error_callback) override;
void Remove(const dbus::ObjectPath& service_path,
const base::Closure& callback,
const ErrorCallback& error_callback) override;
void ActivateCellularModem(const dbus::ObjectPath& service_path,
const std::string& carrier,
const base::Closure& callback,
const ErrorCallback& error_callback) override;
void CompleteCellularActivation(const dbus::ObjectPath& service_path,
const base::Closure& callback,
const ErrorCallback& error_callback) override;
void GetLoadableProfileEntries(
const dbus::ObjectPath& service_path,
const DictionaryValueCallback& callback) override;
ShillServiceClient::TestInterface* GetTestInterface() override;
// ShillServiceClient::TestInterface overrides.
void AddService(const std::string& service_path,
const std::string& guid,
const std::string& name,
const std::string& type,
const std::string& state,
bool visible) override;
void AddServiceWithIPConfig(const std::string& service_path,
const std::string& guid,
const std::string& name,
const std::string& type,
const std::string& state,
const std::string& ipconfig_path,
bool visible) override;
base::DictionaryValue* SetServiceProperties(const std::string& service_path,
const std::string& guid,
const std::string& name,
const std::string& type,
const std::string& state,
bool visible) override;
void RemoveService(const std::string& service_path) override;
bool SetServiceProperty(const std::string& service_path,
const std::string& property,
const base::Value& value) override;
const base::DictionaryValue* GetServiceProperties(
const std::string& service_path) const override;
void ClearServices() override;
void SetConnectBehavior(const std::string& service_path,
const base::Closure& behavior) override;
private:
typedef base::ObserverList<ShillPropertyChangedObserver> PropertyObserverList;
void NotifyObserversPropertyChanged(const dbus::ObjectPath& service_path,
const std::string& property);
base::DictionaryValue* GetModifiableServiceProperties(
const std::string& service_path,
bool create_if_missing);
PropertyObserverList& GetObserverList(const dbus::ObjectPath& device_path);
void SetOtherServicesOffline(const std::string& service_path);
void SetCellularActivated(const dbus::ObjectPath& service_path,
const ErrorCallback& error_callback);
void ContinueConnect(const std::string& service_path);
base::DictionaryValue stub_services_;
// Per network service, stores a closure that is executed on each connection
// attempt. The callback can for example modify the services properties in
// order to simulate a connection failure.
std::map<std::string, base::Closure> connect_behavior_;
// Observer list for each service.
std::map<dbus::ObjectPath, std::unique_ptr<PropertyObserverList>>
observer_list_;
// Note: This should remain the last member so it'll be destroyed and
// invalidate its weak pointers before any other members are destroyed.
base::WeakPtrFactory<FakeShillServiceClient> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(FakeShillServiceClient);
};
} // namespace chromeos
#endif // CHROMEOS_DBUS_FAKE_SHILL_SERVICE_CLIENT_H_
| null | null | null | null | 2,593 |
31,448 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 196,443 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | /* sunvdc.c: Sun LDOM Virtual Disk Client.
*
* Copyright (C) 2007, 2008 David S. Miller <davem@davemloft.net>
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/blkdev.h>
#include <linux/hdreg.h>
#include <linux/genhd.h>
#include <linux/cdrom.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/scatterlist.h>
#include <asm/vio.h>
#include <asm/ldc.h>
#define DRV_MODULE_NAME "sunvdc"
#define PFX DRV_MODULE_NAME ": "
#define DRV_MODULE_VERSION "1.2"
#define DRV_MODULE_RELDATE "November 24, 2014"
static char version[] =
DRV_MODULE_NAME ".c:v" DRV_MODULE_VERSION " (" DRV_MODULE_RELDATE ")\n";
MODULE_AUTHOR("David S. Miller (davem@davemloft.net)");
MODULE_DESCRIPTION("Sun LDOM virtual disk client driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_MODULE_VERSION);
#define VDC_TX_RING_SIZE 512
#define VDC_DEFAULT_BLK_SIZE 512
#define WAITING_FOR_LINK_UP 0x01
#define WAITING_FOR_TX_SPACE 0x02
#define WAITING_FOR_GEN_CMD 0x04
#define WAITING_FOR_ANY -1
static struct workqueue_struct *sunvdc_wq;
struct vdc_req_entry {
struct request *req;
};
struct vdc_port {
struct vio_driver_state vio;
struct gendisk *disk;
struct vdc_completion *cmp;
u64 req_id;
u64 seq;
struct vdc_req_entry rq_arr[VDC_TX_RING_SIZE];
unsigned long ring_cookies;
u64 max_xfer_size;
u32 vdisk_block_size;
u64 ldc_timeout;
struct timer_list ldc_reset_timer;
struct work_struct ldc_reset_work;
/* The server fills these in for us in the disk attribute
* ACK packet.
*/
u64 operations;
u32 vdisk_size;
u8 vdisk_type;
u8 vdisk_mtype;
u32 vdisk_phys_blksz;
char disk_name[32];
};
static void vdc_ldc_reset(struct vdc_port *port);
static void vdc_ldc_reset_work(struct work_struct *work);
static void vdc_ldc_reset_timer(unsigned long _arg);
static inline struct vdc_port *to_vdc_port(struct vio_driver_state *vio)
{
return container_of(vio, struct vdc_port, vio);
}
/* Ordered from largest major to lowest */
static struct vio_version vdc_versions[] = {
{ .major = 1, .minor = 2 },
{ .major = 1, .minor = 1 },
{ .major = 1, .minor = 0 },
};
static inline int vdc_version_supported(struct vdc_port *port,
u16 major, u16 minor)
{
return port->vio.ver.major == major && port->vio.ver.minor >= minor;
}
#define VDCBLK_NAME "vdisk"
static int vdc_major;
#define PARTITION_SHIFT 3
static inline u32 vdc_tx_dring_avail(struct vio_dring_state *dr)
{
return vio_dring_avail(dr, VDC_TX_RING_SIZE);
}
static int vdc_getgeo(struct block_device *bdev, struct hd_geometry *geo)
{
struct gendisk *disk = bdev->bd_disk;
sector_t nsect = get_capacity(disk);
sector_t cylinders = nsect;
geo->heads = 0xff;
geo->sectors = 0x3f;
sector_div(cylinders, geo->heads * geo->sectors);
geo->cylinders = cylinders;
if ((sector_t)(geo->cylinders + 1) * geo->heads * geo->sectors < nsect)
geo->cylinders = 0xffff;
return 0;
}
/* Add ioctl/CDROM_GET_CAPABILITY to support cdrom_id in udev
* when vdisk_mtype is VD_MEDIA_TYPE_CD or VD_MEDIA_TYPE_DVD.
* Needed to be able to install inside an ldom from an iso image.
*/
static int vdc_ioctl(struct block_device *bdev, fmode_t mode,
unsigned command, unsigned long argument)
{
int i;
struct gendisk *disk;
switch (command) {
case CDROMMULTISESSION:
pr_debug(PFX "Multisession CDs not supported\n");
for (i = 0; i < sizeof(struct cdrom_multisession); i++)
if (put_user(0, (char __user *)(argument + i)))
return -EFAULT;
return 0;
case CDROM_GET_CAPABILITY:
disk = bdev->bd_disk;
if (bdev->bd_disk && (disk->flags & GENHD_FL_CD))
return 0;
return -EINVAL;
default:
pr_debug(PFX "ioctl %08x not supported\n", command);
return -EINVAL;
}
}
static const struct block_device_operations vdc_fops = {
.owner = THIS_MODULE,
.getgeo = vdc_getgeo,
.ioctl = vdc_ioctl,
};
static void vdc_blk_queue_start(struct vdc_port *port)
{
struct vio_dring_state *dr = &port->vio.drings[VIO_DRIVER_TX_RING];
/* restart blk queue when ring is half emptied. also called after
* handshake completes, so check for initial handshake before we've
* allocated a disk.
*/
if (port->disk && blk_queue_stopped(port->disk->queue) &&
vdc_tx_dring_avail(dr) * 100 / VDC_TX_RING_SIZE >= 50) {
blk_start_queue(port->disk->queue);
}
}
static void vdc_finish(struct vio_driver_state *vio, int err, int waiting_for)
{
if (vio->cmp &&
(waiting_for == -1 ||
vio->cmp->waiting_for == waiting_for)) {
vio->cmp->err = err;
complete(&vio->cmp->com);
vio->cmp = NULL;
}
}
static void vdc_handshake_complete(struct vio_driver_state *vio)
{
struct vdc_port *port = to_vdc_port(vio);
del_timer(&port->ldc_reset_timer);
vdc_finish(vio, 0, WAITING_FOR_LINK_UP);
vdc_blk_queue_start(port);
}
static int vdc_handle_unknown(struct vdc_port *port, void *arg)
{
struct vio_msg_tag *pkt = arg;
printk(KERN_ERR PFX "Received unknown msg [%02x:%02x:%04x:%08x]\n",
pkt->type, pkt->stype, pkt->stype_env, pkt->sid);
printk(KERN_ERR PFX "Resetting connection.\n");
ldc_disconnect(port->vio.lp);
return -ECONNRESET;
}
static int vdc_send_attr(struct vio_driver_state *vio)
{
struct vdc_port *port = to_vdc_port(vio);
struct vio_disk_attr_info pkt;
memset(&pkt, 0, sizeof(pkt));
pkt.tag.type = VIO_TYPE_CTRL;
pkt.tag.stype = VIO_SUBTYPE_INFO;
pkt.tag.stype_env = VIO_ATTR_INFO;
pkt.tag.sid = vio_send_sid(vio);
pkt.xfer_mode = VIO_DRING_MODE;
pkt.vdisk_block_size = port->vdisk_block_size;
pkt.max_xfer_size = port->max_xfer_size;
viodbg(HS, "SEND ATTR xfer_mode[0x%x] blksz[%u] max_xfer[%llu]\n",
pkt.xfer_mode, pkt.vdisk_block_size, pkt.max_xfer_size);
return vio_ldc_send(&port->vio, &pkt, sizeof(pkt));
}
static int vdc_handle_attr(struct vio_driver_state *vio, void *arg)
{
struct vdc_port *port = to_vdc_port(vio);
struct vio_disk_attr_info *pkt = arg;
viodbg(HS, "GOT ATTR stype[0x%x] ops[%llx] disk_size[%llu] disk_type[%x] "
"mtype[0x%x] xfer_mode[0x%x] blksz[%u] max_xfer[%llu]\n",
pkt->tag.stype, pkt->operations,
pkt->vdisk_size, pkt->vdisk_type, pkt->vdisk_mtype,
pkt->xfer_mode, pkt->vdisk_block_size,
pkt->max_xfer_size);
if (pkt->tag.stype == VIO_SUBTYPE_ACK) {
switch (pkt->vdisk_type) {
case VD_DISK_TYPE_DISK:
case VD_DISK_TYPE_SLICE:
break;
default:
printk(KERN_ERR PFX "%s: Bogus vdisk_type 0x%x\n",
vio->name, pkt->vdisk_type);
return -ECONNRESET;
}
if (pkt->vdisk_block_size > port->vdisk_block_size) {
printk(KERN_ERR PFX "%s: BLOCK size increased "
"%u --> %u\n",
vio->name,
port->vdisk_block_size, pkt->vdisk_block_size);
return -ECONNRESET;
}
port->operations = pkt->operations;
port->vdisk_type = pkt->vdisk_type;
if (vdc_version_supported(port, 1, 1)) {
port->vdisk_size = pkt->vdisk_size;
port->vdisk_mtype = pkt->vdisk_mtype;
}
if (pkt->max_xfer_size < port->max_xfer_size)
port->max_xfer_size = pkt->max_xfer_size;
port->vdisk_block_size = pkt->vdisk_block_size;
port->vdisk_phys_blksz = VDC_DEFAULT_BLK_SIZE;
if (vdc_version_supported(port, 1, 2))
port->vdisk_phys_blksz = pkt->phys_block_size;
return 0;
} else {
printk(KERN_ERR PFX "%s: Attribute NACK\n", vio->name);
return -ECONNRESET;
}
}
static void vdc_end_special(struct vdc_port *port, struct vio_disk_desc *desc)
{
int err = desc->status;
vdc_finish(&port->vio, -err, WAITING_FOR_GEN_CMD);
}
static void vdc_end_one(struct vdc_port *port, struct vio_dring_state *dr,
unsigned int index)
{
struct vio_disk_desc *desc = vio_dring_entry(dr, index);
struct vdc_req_entry *rqe = &port->rq_arr[index];
struct request *req;
if (unlikely(desc->hdr.state != VIO_DESC_DONE))
return;
ldc_unmap(port->vio.lp, desc->cookies, desc->ncookies);
desc->hdr.state = VIO_DESC_FREE;
dr->cons = vio_dring_next(dr, index);
req = rqe->req;
if (req == NULL) {
vdc_end_special(port, desc);
return;
}
rqe->req = NULL;
__blk_end_request(req, (desc->status ? -EIO : 0), desc->size);
vdc_blk_queue_start(port);
}
static int vdc_ack(struct vdc_port *port, void *msgbuf)
{
struct vio_dring_state *dr = &port->vio.drings[VIO_DRIVER_TX_RING];
struct vio_dring_data *pkt = msgbuf;
if (unlikely(pkt->dring_ident != dr->ident ||
pkt->start_idx != pkt->end_idx ||
pkt->start_idx >= VDC_TX_RING_SIZE))
return 0;
vdc_end_one(port, dr, pkt->start_idx);
return 0;
}
static int vdc_nack(struct vdc_port *port, void *msgbuf)
{
/* XXX Implement me XXX */
return 0;
}
static void vdc_event(void *arg, int event)
{
struct vdc_port *port = arg;
struct vio_driver_state *vio = &port->vio;
unsigned long flags;
int err;
spin_lock_irqsave(&vio->lock, flags);
if (unlikely(event == LDC_EVENT_RESET)) {
vio_link_state_change(vio, event);
queue_work(sunvdc_wq, &port->ldc_reset_work);
goto out;
}
if (unlikely(event == LDC_EVENT_UP)) {
vio_link_state_change(vio, event);
goto out;
}
if (unlikely(event != LDC_EVENT_DATA_READY)) {
pr_warn(PFX "Unexpected LDC event %d\n", event);
goto out;
}
err = 0;
while (1) {
union {
struct vio_msg_tag tag;
u64 raw[8];
} msgbuf;
err = ldc_read(vio->lp, &msgbuf, sizeof(msgbuf));
if (unlikely(err < 0)) {
if (err == -ECONNRESET)
vio_conn_reset(vio);
break;
}
if (err == 0)
break;
viodbg(DATA, "TAG [%02x:%02x:%04x:%08x]\n",
msgbuf.tag.type,
msgbuf.tag.stype,
msgbuf.tag.stype_env,
msgbuf.tag.sid);
err = vio_validate_sid(vio, &msgbuf.tag);
if (err < 0)
break;
if (likely(msgbuf.tag.type == VIO_TYPE_DATA)) {
if (msgbuf.tag.stype == VIO_SUBTYPE_ACK)
err = vdc_ack(port, &msgbuf);
else if (msgbuf.tag.stype == VIO_SUBTYPE_NACK)
err = vdc_nack(port, &msgbuf);
else
err = vdc_handle_unknown(port, &msgbuf);
} else if (msgbuf.tag.type == VIO_TYPE_CTRL) {
err = vio_control_pkt_engine(vio, &msgbuf);
} else {
err = vdc_handle_unknown(port, &msgbuf);
}
if (err < 0)
break;
}
if (err < 0)
vdc_finish(&port->vio, err, WAITING_FOR_ANY);
out:
spin_unlock_irqrestore(&vio->lock, flags);
}
static int __vdc_tx_trigger(struct vdc_port *port)
{
struct vio_dring_state *dr = &port->vio.drings[VIO_DRIVER_TX_RING];
struct vio_dring_data hdr = {
.tag = {
.type = VIO_TYPE_DATA,
.stype = VIO_SUBTYPE_INFO,
.stype_env = VIO_DRING_DATA,
.sid = vio_send_sid(&port->vio),
},
.dring_ident = dr->ident,
.start_idx = dr->prod,
.end_idx = dr->prod,
};
int err, delay;
hdr.seq = dr->snd_nxt;
delay = 1;
do {
err = vio_ldc_send(&port->vio, &hdr, sizeof(hdr));
if (err > 0) {
dr->snd_nxt++;
break;
}
udelay(delay);
if ((delay <<= 1) > 128)
delay = 128;
} while (err == -EAGAIN);
if (err == -ENOTCONN)
vdc_ldc_reset(port);
return err;
}
static int __send_request(struct request *req)
{
struct vdc_port *port = req->rq_disk->private_data;
struct vio_dring_state *dr = &port->vio.drings[VIO_DRIVER_TX_RING];
struct scatterlist sg[port->ring_cookies];
struct vdc_req_entry *rqe;
struct vio_disk_desc *desc;
unsigned int map_perm;
int nsg, err, i;
u64 len;
u8 op;
map_perm = LDC_MAP_SHADOW | LDC_MAP_DIRECT | LDC_MAP_IO;
if (rq_data_dir(req) == READ) {
map_perm |= LDC_MAP_W;
op = VD_OP_BREAD;
} else {
map_perm |= LDC_MAP_R;
op = VD_OP_BWRITE;
}
sg_init_table(sg, port->ring_cookies);
nsg = blk_rq_map_sg(req->q, req, sg);
len = 0;
for (i = 0; i < nsg; i++)
len += sg[i].length;
desc = vio_dring_cur(dr);
err = ldc_map_sg(port->vio.lp, sg, nsg,
desc->cookies, port->ring_cookies,
map_perm);
if (err < 0) {
printk(KERN_ERR PFX "ldc_map_sg() failure, err=%d.\n", err);
return err;
}
rqe = &port->rq_arr[dr->prod];
rqe->req = req;
desc->hdr.ack = VIO_ACK_ENABLE;
desc->req_id = port->req_id;
desc->operation = op;
if (port->vdisk_type == VD_DISK_TYPE_DISK) {
desc->slice = 0xff;
} else {
desc->slice = 0;
}
desc->status = ~0;
desc->offset = (blk_rq_pos(req) << 9) / port->vdisk_block_size;
desc->size = len;
desc->ncookies = err;
/* This has to be a non-SMP write barrier because we are writing
* to memory which is shared with the peer LDOM.
*/
wmb();
desc->hdr.state = VIO_DESC_READY;
err = __vdc_tx_trigger(port);
if (err < 0) {
printk(KERN_ERR PFX "vdc_tx_trigger() failure, err=%d\n", err);
} else {
port->req_id++;
dr->prod = vio_dring_next(dr, dr->prod);
}
return err;
}
static void do_vdc_request(struct request_queue *rq)
{
struct request *req;
while ((req = blk_peek_request(rq)) != NULL) {
struct vdc_port *port;
struct vio_dring_state *dr;
port = req->rq_disk->private_data;
dr = &port->vio.drings[VIO_DRIVER_TX_RING];
if (unlikely(vdc_tx_dring_avail(dr) < 1))
goto wait;
blk_start_request(req);
if (__send_request(req) < 0) {
blk_requeue_request(rq, req);
wait:
/* Avoid pointless unplugs. */
blk_stop_queue(rq);
break;
}
}
}
static int generic_request(struct vdc_port *port, u8 op, void *buf, int len)
{
struct vio_dring_state *dr;
struct vio_completion comp;
struct vio_disk_desc *desc;
unsigned int map_perm;
unsigned long flags;
int op_len, err;
void *req_buf;
if (!(((u64)1 << (u64)op) & port->operations))
return -EOPNOTSUPP;
switch (op) {
case VD_OP_BREAD:
case VD_OP_BWRITE:
default:
return -EINVAL;
case VD_OP_FLUSH:
op_len = 0;
map_perm = 0;
break;
case VD_OP_GET_WCE:
op_len = sizeof(u32);
map_perm = LDC_MAP_W;
break;
case VD_OP_SET_WCE:
op_len = sizeof(u32);
map_perm = LDC_MAP_R;
break;
case VD_OP_GET_VTOC:
op_len = sizeof(struct vio_disk_vtoc);
map_perm = LDC_MAP_W;
break;
case VD_OP_SET_VTOC:
op_len = sizeof(struct vio_disk_vtoc);
map_perm = LDC_MAP_R;
break;
case VD_OP_GET_DISKGEOM:
op_len = sizeof(struct vio_disk_geom);
map_perm = LDC_MAP_W;
break;
case VD_OP_SET_DISKGEOM:
op_len = sizeof(struct vio_disk_geom);
map_perm = LDC_MAP_R;
break;
case VD_OP_SCSICMD:
op_len = 16;
map_perm = LDC_MAP_RW;
break;
case VD_OP_GET_DEVID:
op_len = sizeof(struct vio_disk_devid);
map_perm = LDC_MAP_W;
break;
case VD_OP_GET_EFI:
case VD_OP_SET_EFI:
return -EOPNOTSUPP;
break;
};
map_perm |= LDC_MAP_SHADOW | LDC_MAP_DIRECT | LDC_MAP_IO;
op_len = (op_len + 7) & ~7;
req_buf = kzalloc(op_len, GFP_KERNEL);
if (!req_buf)
return -ENOMEM;
if (len > op_len)
len = op_len;
if (map_perm & LDC_MAP_R)
memcpy(req_buf, buf, len);
spin_lock_irqsave(&port->vio.lock, flags);
dr = &port->vio.drings[VIO_DRIVER_TX_RING];
/* XXX If we want to use this code generically we have to
* XXX handle TX ring exhaustion etc.
*/
desc = vio_dring_cur(dr);
err = ldc_map_single(port->vio.lp, req_buf, op_len,
desc->cookies, port->ring_cookies,
map_perm);
if (err < 0) {
spin_unlock_irqrestore(&port->vio.lock, flags);
kfree(req_buf);
return err;
}
init_completion(&comp.com);
comp.waiting_for = WAITING_FOR_GEN_CMD;
port->vio.cmp = ∁
desc->hdr.ack = VIO_ACK_ENABLE;
desc->req_id = port->req_id;
desc->operation = op;
desc->slice = 0;
desc->status = ~0;
desc->offset = 0;
desc->size = op_len;
desc->ncookies = err;
/* This has to be a non-SMP write barrier because we are writing
* to memory which is shared with the peer LDOM.
*/
wmb();
desc->hdr.state = VIO_DESC_READY;
err = __vdc_tx_trigger(port);
if (err >= 0) {
port->req_id++;
dr->prod = vio_dring_next(dr, dr->prod);
spin_unlock_irqrestore(&port->vio.lock, flags);
wait_for_completion(&comp.com);
err = comp.err;
} else {
port->vio.cmp = NULL;
spin_unlock_irqrestore(&port->vio.lock, flags);
}
if (map_perm & LDC_MAP_W)
memcpy(buf, req_buf, len);
kfree(req_buf);
return err;
}
static int vdc_alloc_tx_ring(struct vdc_port *port)
{
struct vio_dring_state *dr = &port->vio.drings[VIO_DRIVER_TX_RING];
unsigned long len, entry_size;
int ncookies;
void *dring;
entry_size = sizeof(struct vio_disk_desc) +
(sizeof(struct ldc_trans_cookie) * port->ring_cookies);
len = (VDC_TX_RING_SIZE * entry_size);
ncookies = VIO_MAX_RING_COOKIES;
dring = ldc_alloc_exp_dring(port->vio.lp, len,
dr->cookies, &ncookies,
(LDC_MAP_SHADOW |
LDC_MAP_DIRECT |
LDC_MAP_RW));
if (IS_ERR(dring))
return PTR_ERR(dring);
dr->base = dring;
dr->entry_size = entry_size;
dr->num_entries = VDC_TX_RING_SIZE;
dr->prod = dr->cons = 0;
dr->pending = VDC_TX_RING_SIZE;
dr->ncookies = ncookies;
return 0;
}
static void vdc_free_tx_ring(struct vdc_port *port)
{
struct vio_dring_state *dr = &port->vio.drings[VIO_DRIVER_TX_RING];
if (dr->base) {
ldc_free_exp_dring(port->vio.lp, dr->base,
(dr->entry_size * dr->num_entries),
dr->cookies, dr->ncookies);
dr->base = NULL;
dr->entry_size = 0;
dr->num_entries = 0;
dr->pending = 0;
dr->ncookies = 0;
}
}
static int vdc_port_up(struct vdc_port *port)
{
struct vio_completion comp;
init_completion(&comp.com);
comp.err = 0;
comp.waiting_for = WAITING_FOR_LINK_UP;
port->vio.cmp = ∁
vio_port_up(&port->vio);
wait_for_completion(&comp.com);
return comp.err;
}
static void vdc_port_down(struct vdc_port *port)
{
ldc_disconnect(port->vio.lp);
ldc_unbind(port->vio.lp);
vdc_free_tx_ring(port);
vio_ldc_free(&port->vio);
}
static int probe_disk(struct vdc_port *port)
{
struct request_queue *q;
struct gendisk *g;
int err;
err = vdc_port_up(port);
if (err)
return err;
/* Using version 1.2 means vdisk_phys_blksz should be set unless the
* disk is reserved by another system.
*/
if (vdc_version_supported(port, 1, 2) && !port->vdisk_phys_blksz)
return -ENODEV;
if (vdc_version_supported(port, 1, 1)) {
/* vdisk_size should be set during the handshake, if it wasn't
* then the underlying disk is reserved by another system
*/
if (port->vdisk_size == -1)
return -ENODEV;
} else {
struct vio_disk_geom geom;
err = generic_request(port, VD_OP_GET_DISKGEOM,
&geom, sizeof(geom));
if (err < 0) {
printk(KERN_ERR PFX "VD_OP_GET_DISKGEOM returns "
"error %d\n", err);
return err;
}
port->vdisk_size = ((u64)geom.num_cyl *
(u64)geom.num_hd *
(u64)geom.num_sec);
}
q = blk_init_queue(do_vdc_request, &port->vio.lock);
if (!q) {
printk(KERN_ERR PFX "%s: Could not allocate queue.\n",
port->vio.name);
return -ENOMEM;
}
g = alloc_disk(1 << PARTITION_SHIFT);
if (!g) {
printk(KERN_ERR PFX "%s: Could not allocate gendisk.\n",
port->vio.name);
blk_cleanup_queue(q);
return -ENOMEM;
}
port->disk = g;
/* Each segment in a request is up to an aligned page in size. */
blk_queue_segment_boundary(q, PAGE_SIZE - 1);
blk_queue_max_segment_size(q, PAGE_SIZE);
blk_queue_max_segments(q, port->ring_cookies);
blk_queue_max_hw_sectors(q, port->max_xfer_size);
g->major = vdc_major;
g->first_minor = port->vio.vdev->dev_no << PARTITION_SHIFT;
strcpy(g->disk_name, port->disk_name);
g->fops = &vdc_fops;
g->queue = q;
g->private_data = port;
set_capacity(g, port->vdisk_size);
if (vdc_version_supported(port, 1, 1)) {
switch (port->vdisk_mtype) {
case VD_MEDIA_TYPE_CD:
pr_info(PFX "Virtual CDROM %s\n", port->disk_name);
g->flags |= GENHD_FL_CD;
g->flags |= GENHD_FL_REMOVABLE;
set_disk_ro(g, 1);
break;
case VD_MEDIA_TYPE_DVD:
pr_info(PFX "Virtual DVD %s\n", port->disk_name);
g->flags |= GENHD_FL_CD;
g->flags |= GENHD_FL_REMOVABLE;
set_disk_ro(g, 1);
break;
case VD_MEDIA_TYPE_FIXED:
pr_info(PFX "Virtual Hard disk %s\n", port->disk_name);
break;
}
}
blk_queue_physical_block_size(q, port->vdisk_phys_blksz);
pr_info(PFX "%s: %u sectors (%u MB) protocol %d.%d\n",
g->disk_name,
port->vdisk_size, (port->vdisk_size >> (20 - 9)),
port->vio.ver.major, port->vio.ver.minor);
device_add_disk(&port->vio.vdev->dev, g);
return 0;
}
static struct ldc_channel_config vdc_ldc_cfg = {
.event = vdc_event,
.mtu = 64,
.mode = LDC_MODE_UNRELIABLE,
};
static struct vio_driver_ops vdc_vio_ops = {
.send_attr = vdc_send_attr,
.handle_attr = vdc_handle_attr,
.handshake_complete = vdc_handshake_complete,
};
static void print_version(void)
{
static int version_printed;
if (version_printed++ == 0)
printk(KERN_INFO "%s", version);
}
static int vdc_port_probe(struct vio_dev *vdev, const struct vio_device_id *id)
{
struct mdesc_handle *hp;
struct vdc_port *port;
int err;
const u64 *ldc_timeout;
print_version();
hp = mdesc_grab();
err = -ENODEV;
if ((vdev->dev_no << PARTITION_SHIFT) & ~(u64)MINORMASK) {
printk(KERN_ERR PFX "Port id [%llu] too large.\n",
vdev->dev_no);
goto err_out_release_mdesc;
}
port = kzalloc(sizeof(*port), GFP_KERNEL);
err = -ENOMEM;
if (!port) {
printk(KERN_ERR PFX "Cannot allocate vdc_port.\n");
goto err_out_release_mdesc;
}
if (vdev->dev_no >= 26)
snprintf(port->disk_name, sizeof(port->disk_name),
VDCBLK_NAME "%c%c",
'a' + ((int)vdev->dev_no / 26) - 1,
'a' + ((int)vdev->dev_no % 26));
else
snprintf(port->disk_name, sizeof(port->disk_name),
VDCBLK_NAME "%c", 'a' + ((int)vdev->dev_no % 26));
port->vdisk_size = -1;
/* Actual wall time may be double due to do_generic_file_read() doing
* a readahead I/O first, and once that fails it will try to read a
* single page.
*/
ldc_timeout = mdesc_get_property(hp, vdev->mp, "vdc-timeout", NULL);
port->ldc_timeout = ldc_timeout ? *ldc_timeout : 0;
setup_timer(&port->ldc_reset_timer, vdc_ldc_reset_timer,
(unsigned long)port);
INIT_WORK(&port->ldc_reset_work, vdc_ldc_reset_work);
err = vio_driver_init(&port->vio, vdev, VDEV_DISK,
vdc_versions, ARRAY_SIZE(vdc_versions),
&vdc_vio_ops, port->disk_name);
if (err)
goto err_out_free_port;
port->vdisk_block_size = VDC_DEFAULT_BLK_SIZE;
port->max_xfer_size = ((128 * 1024) / port->vdisk_block_size);
port->ring_cookies = ((port->max_xfer_size *
port->vdisk_block_size) / PAGE_SIZE) + 2;
err = vio_ldc_alloc(&port->vio, &vdc_ldc_cfg, port);
if (err)
goto err_out_free_port;
err = vdc_alloc_tx_ring(port);
if (err)
goto err_out_free_ldc;
err = probe_disk(port);
if (err)
goto err_out_free_tx_ring;
dev_set_drvdata(&vdev->dev, port);
mdesc_release(hp);
return 0;
err_out_free_tx_ring:
vdc_free_tx_ring(port);
err_out_free_ldc:
vio_ldc_free(&port->vio);
err_out_free_port:
kfree(port);
err_out_release_mdesc:
mdesc_release(hp);
return err;
}
static int vdc_port_remove(struct vio_dev *vdev)
{
struct vdc_port *port = dev_get_drvdata(&vdev->dev);
if (port) {
unsigned long flags;
spin_lock_irqsave(&port->vio.lock, flags);
blk_stop_queue(port->disk->queue);
spin_unlock_irqrestore(&port->vio.lock, flags);
flush_work(&port->ldc_reset_work);
del_timer_sync(&port->ldc_reset_timer);
del_timer_sync(&port->vio.timer);
del_gendisk(port->disk);
blk_cleanup_queue(port->disk->queue);
put_disk(port->disk);
port->disk = NULL;
vdc_free_tx_ring(port);
vio_ldc_free(&port->vio);
dev_set_drvdata(&vdev->dev, NULL);
kfree(port);
}
return 0;
}
static void vdc_requeue_inflight(struct vdc_port *port)
{
struct vio_dring_state *dr = &port->vio.drings[VIO_DRIVER_TX_RING];
u32 idx;
for (idx = dr->cons; idx != dr->prod; idx = vio_dring_next(dr, idx)) {
struct vio_disk_desc *desc = vio_dring_entry(dr, idx);
struct vdc_req_entry *rqe = &port->rq_arr[idx];
struct request *req;
ldc_unmap(port->vio.lp, desc->cookies, desc->ncookies);
desc->hdr.state = VIO_DESC_FREE;
dr->cons = vio_dring_next(dr, idx);
req = rqe->req;
if (req == NULL) {
vdc_end_special(port, desc);
continue;
}
rqe->req = NULL;
blk_requeue_request(port->disk->queue, req);
}
}
static void vdc_queue_drain(struct vdc_port *port)
{
struct request *req;
while ((req = blk_fetch_request(port->disk->queue)) != NULL)
__blk_end_request_all(req, -EIO);
}
static void vdc_ldc_reset_timer(unsigned long _arg)
{
struct vdc_port *port = (struct vdc_port *) _arg;
struct vio_driver_state *vio = &port->vio;
unsigned long flags;
spin_lock_irqsave(&vio->lock, flags);
if (!(port->vio.hs_state & VIO_HS_COMPLETE)) {
pr_warn(PFX "%s ldc down %llu seconds, draining queue\n",
port->disk_name, port->ldc_timeout);
vdc_queue_drain(port);
vdc_blk_queue_start(port);
}
spin_unlock_irqrestore(&vio->lock, flags);
}
static void vdc_ldc_reset_work(struct work_struct *work)
{
struct vdc_port *port;
struct vio_driver_state *vio;
unsigned long flags;
port = container_of(work, struct vdc_port, ldc_reset_work);
vio = &port->vio;
spin_lock_irqsave(&vio->lock, flags);
vdc_ldc_reset(port);
spin_unlock_irqrestore(&vio->lock, flags);
}
static void vdc_ldc_reset(struct vdc_port *port)
{
int err;
assert_spin_locked(&port->vio.lock);
pr_warn(PFX "%s ldc link reset\n", port->disk_name);
blk_stop_queue(port->disk->queue);
vdc_requeue_inflight(port);
vdc_port_down(port);
err = vio_ldc_alloc(&port->vio, &vdc_ldc_cfg, port);
if (err) {
pr_err(PFX "%s vio_ldc_alloc:%d\n", port->disk_name, err);
return;
}
err = vdc_alloc_tx_ring(port);
if (err) {
pr_err(PFX "%s vio_alloc_tx_ring:%d\n", port->disk_name, err);
goto err_free_ldc;
}
if (port->ldc_timeout)
mod_timer(&port->ldc_reset_timer,
round_jiffies(jiffies + HZ * port->ldc_timeout));
mod_timer(&port->vio.timer, round_jiffies(jiffies + HZ));
return;
err_free_ldc:
vio_ldc_free(&port->vio);
}
static const struct vio_device_id vdc_port_match[] = {
{
.type = "vdc-port",
},
{},
};
MODULE_DEVICE_TABLE(vio, vdc_port_match);
static struct vio_driver vdc_port_driver = {
.id_table = vdc_port_match,
.probe = vdc_port_probe,
.remove = vdc_port_remove,
.name = "vdc_port",
};
static int __init vdc_init(void)
{
int err;
sunvdc_wq = alloc_workqueue("sunvdc", 0, 0);
if (!sunvdc_wq)
return -ENOMEM;
err = register_blkdev(0, VDCBLK_NAME);
if (err < 0)
goto out_free_wq;
vdc_major = err;
err = vio_register_driver(&vdc_port_driver);
if (err)
goto out_unregister_blkdev;
return 0;
out_unregister_blkdev:
unregister_blkdev(vdc_major, VDCBLK_NAME);
vdc_major = 0;
out_free_wq:
destroy_workqueue(sunvdc_wq);
return err;
}
static void __exit vdc_exit(void)
{
vio_unregister_driver(&vdc_port_driver);
unregister_blkdev(vdc_major, VDCBLK_NAME);
destroy_workqueue(sunvdc_wq);
}
module_init(vdc_init);
module_exit(vdc_exit);
| null | null | null | null | 104,790 |
39,415 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 204,410 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | /*
* Cryptographic API.
*
* Serpent Cipher Algorithm.
*
* Copyright (C) 2002 Dag Arne Osvik <osvik@ii.uib.no>
* 2003 Herbert Valerio Riedel <hvr@gnu.org>
*
* Added tnepres support:
* Ruben Jesus Garcia Hernandez <ruben@ugr.es>, 18.10.2004
* Based on code by hvr
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <asm/byteorder.h>
#include <linux/crypto.h>
#include <linux/types.h>
#include <crypto/serpent.h>
/* Key is padded to the maximum of 256 bits before round key generation.
* Any key length <= 256 bits (32 bytes) is allowed by the algorithm.
*/
#define PHI 0x9e3779b9UL
#define keyiter(a, b, c, d, i, j) \
({ b ^= d; b ^= c; b ^= a; b ^= PHI ^ i; b = rol32(b, 11); k[j] = b; })
#define loadkeys(x0, x1, x2, x3, i) \
({ x0 = k[i]; x1 = k[i+1]; x2 = k[i+2]; x3 = k[i+3]; })
#define storekeys(x0, x1, x2, x3, i) \
({ k[i] = x0; k[i+1] = x1; k[i+2] = x2; k[i+3] = x3; })
#define store_and_load_keys(x0, x1, x2, x3, s, l) \
({ storekeys(x0, x1, x2, x3, s); loadkeys(x0, x1, x2, x3, l); })
#define K(x0, x1, x2, x3, i) ({ \
x3 ^= k[4*(i)+3]; x2 ^= k[4*(i)+2]; \
x1 ^= k[4*(i)+1]; x0 ^= k[4*(i)+0]; \
})
#define LK(x0, x1, x2, x3, x4, i) ({ \
x0 = rol32(x0, 13);\
x2 = rol32(x2, 3); x1 ^= x0; x4 = x0 << 3; \
x3 ^= x2; x1 ^= x2; \
x1 = rol32(x1, 1); x3 ^= x4; \
x3 = rol32(x3, 7); x4 = x1; \
x0 ^= x1; x4 <<= 7; x2 ^= x3; \
x0 ^= x3; x2 ^= x4; x3 ^= k[4*i+3]; \
x1 ^= k[4*i+1]; x0 = rol32(x0, 5); x2 = rol32(x2, 22);\
x0 ^= k[4*i+0]; x2 ^= k[4*i+2]; \
})
#define KL(x0, x1, x2, x3, x4, i) ({ \
x0 ^= k[4*i+0]; x1 ^= k[4*i+1]; x2 ^= k[4*i+2]; \
x3 ^= k[4*i+3]; x0 = ror32(x0, 5); x2 = ror32(x2, 22);\
x4 = x1; x2 ^= x3; x0 ^= x3; \
x4 <<= 7; x0 ^= x1; x1 = ror32(x1, 1); \
x2 ^= x4; x3 = ror32(x3, 7); x4 = x0 << 3; \
x1 ^= x0; x3 ^= x4; x0 = ror32(x0, 13);\
x1 ^= x2; x3 ^= x2; x2 = ror32(x2, 3); \
})
#define S0(x0, x1, x2, x3, x4) ({ \
x4 = x3; \
x3 |= x0; x0 ^= x4; x4 ^= x2; \
x4 = ~x4; x3 ^= x1; x1 &= x0; \
x1 ^= x4; x2 ^= x0; x0 ^= x3; \
x4 |= x0; x0 ^= x2; x2 &= x1; \
x3 ^= x2; x1 = ~x1; x2 ^= x4; \
x1 ^= x2; \
})
#define S1(x0, x1, x2, x3, x4) ({ \
x4 = x1; \
x1 ^= x0; x0 ^= x3; x3 = ~x3; \
x4 &= x1; x0 |= x1; x3 ^= x2; \
x0 ^= x3; x1 ^= x3; x3 ^= x4; \
x1 |= x4; x4 ^= x2; x2 &= x0; \
x2 ^= x1; x1 |= x0; x0 = ~x0; \
x0 ^= x2; x4 ^= x1; \
})
#define S2(x0, x1, x2, x3, x4) ({ \
x3 = ~x3; \
x1 ^= x0; x4 = x0; x0 &= x2; \
x0 ^= x3; x3 |= x4; x2 ^= x1; \
x3 ^= x1; x1 &= x0; x0 ^= x2; \
x2 &= x3; x3 |= x1; x0 = ~x0; \
x3 ^= x0; x4 ^= x0; x0 ^= x2; \
x1 |= x2; \
})
#define S3(x0, x1, x2, x3, x4) ({ \
x4 = x1; \
x1 ^= x3; x3 |= x0; x4 &= x0; \
x0 ^= x2; x2 ^= x1; x1 &= x3; \
x2 ^= x3; x0 |= x4; x4 ^= x3; \
x1 ^= x0; x0 &= x3; x3 &= x4; \
x3 ^= x2; x4 |= x1; x2 &= x1; \
x4 ^= x3; x0 ^= x3; x3 ^= x2; \
})
#define S4(x0, x1, x2, x3, x4) ({ \
x4 = x3; \
x3 &= x0; x0 ^= x4; \
x3 ^= x2; x2 |= x4; x0 ^= x1; \
x4 ^= x3; x2 |= x0; \
x2 ^= x1; x1 &= x0; \
x1 ^= x4; x4 &= x2; x2 ^= x3; \
x4 ^= x0; x3 |= x1; x1 = ~x1; \
x3 ^= x0; \
})
#define S5(x0, x1, x2, x3, x4) ({ \
x4 = x1; x1 |= x0; \
x2 ^= x1; x3 = ~x3; x4 ^= x0; \
x0 ^= x2; x1 &= x4; x4 |= x3; \
x4 ^= x0; x0 &= x3; x1 ^= x3; \
x3 ^= x2; x0 ^= x1; x2 &= x4; \
x1 ^= x2; x2 &= x0; \
x3 ^= x2; \
})
#define S6(x0, x1, x2, x3, x4) ({ \
x4 = x1; \
x3 ^= x0; x1 ^= x2; x2 ^= x0; \
x0 &= x3; x1 |= x3; x4 = ~x4; \
x0 ^= x1; x1 ^= x2; \
x3 ^= x4; x4 ^= x0; x2 &= x0; \
x4 ^= x1; x2 ^= x3; x3 &= x1; \
x3 ^= x0; x1 ^= x2; \
})
#define S7(x0, x1, x2, x3, x4) ({ \
x1 = ~x1; \
x4 = x1; x0 = ~x0; x1 &= x2; \
x1 ^= x3; x3 |= x4; x4 ^= x2; \
x2 ^= x3; x3 ^= x0; x0 |= x1; \
x2 &= x0; x0 ^= x4; x4 ^= x3; \
x3 &= x0; x4 ^= x1; \
x2 ^= x4; x3 ^= x1; x4 |= x0; \
x4 ^= x1; \
})
#define SI0(x0, x1, x2, x3, x4) ({ \
x4 = x3; x1 ^= x0; \
x3 |= x1; x4 ^= x1; x0 = ~x0; \
x2 ^= x3; x3 ^= x0; x0 &= x1; \
x0 ^= x2; x2 &= x3; x3 ^= x4; \
x2 ^= x3; x1 ^= x3; x3 &= x0; \
x1 ^= x0; x0 ^= x2; x4 ^= x3; \
})
#define SI1(x0, x1, x2, x3, x4) ({ \
x1 ^= x3; x4 = x0; \
x0 ^= x2; x2 = ~x2; x4 |= x1; \
x4 ^= x3; x3 &= x1; x1 ^= x2; \
x2 &= x4; x4 ^= x1; x1 |= x3; \
x3 ^= x0; x2 ^= x0; x0 |= x4; \
x2 ^= x4; x1 ^= x0; \
x4 ^= x1; \
})
#define SI2(x0, x1, x2, x3, x4) ({ \
x2 ^= x1; x4 = x3; x3 = ~x3; \
x3 |= x2; x2 ^= x4; x4 ^= x0; \
x3 ^= x1; x1 |= x2; x2 ^= x0; \
x1 ^= x4; x4 |= x3; x2 ^= x3; \
x4 ^= x2; x2 &= x1; \
x2 ^= x3; x3 ^= x4; x4 ^= x0; \
})
#define SI3(x0, x1, x2, x3, x4) ({ \
x2 ^= x1; \
x4 = x1; x1 &= x2; \
x1 ^= x0; x0 |= x4; x4 ^= x3; \
x0 ^= x3; x3 |= x1; x1 ^= x2; \
x1 ^= x3; x0 ^= x2; x2 ^= x3; \
x3 &= x1; x1 ^= x0; x0 &= x2; \
x4 ^= x3; x3 ^= x0; x0 ^= x1; \
})
#define SI4(x0, x1, x2, x3, x4) ({ \
x2 ^= x3; x4 = x0; x0 &= x1; \
x0 ^= x2; x2 |= x3; x4 = ~x4; \
x1 ^= x0; x0 ^= x2; x2 &= x4; \
x2 ^= x0; x0 |= x4; \
x0 ^= x3; x3 &= x2; \
x4 ^= x3; x3 ^= x1; x1 &= x0; \
x4 ^= x1; x0 ^= x3; \
})
#define SI5(x0, x1, x2, x3, x4) ({ \
x4 = x1; x1 |= x2; \
x2 ^= x4; x1 ^= x3; x3 &= x4; \
x2 ^= x3; x3 |= x0; x0 = ~x0; \
x3 ^= x2; x2 |= x0; x4 ^= x1; \
x2 ^= x4; x4 &= x0; x0 ^= x1; \
x1 ^= x3; x0 &= x2; x2 ^= x3; \
x0 ^= x2; x2 ^= x4; x4 ^= x3; \
})
#define SI6(x0, x1, x2, x3, x4) ({ \
x0 ^= x2; \
x4 = x0; x0 &= x3; x2 ^= x3; \
x0 ^= x2; x3 ^= x1; x2 |= x4; \
x2 ^= x3; x3 &= x0; x0 = ~x0; \
x3 ^= x1; x1 &= x2; x4 ^= x0; \
x3 ^= x4; x4 ^= x2; x0 ^= x1; \
x2 ^= x0; \
})
#define SI7(x0, x1, x2, x3, x4) ({ \
x4 = x3; x3 &= x0; x0 ^= x2; \
x2 |= x4; x4 ^= x1; x0 = ~x0; \
x1 |= x3; x4 ^= x0; x0 &= x2; \
x0 ^= x1; x1 &= x2; x3 ^= x2; \
x4 ^= x3; x2 &= x3; x3 |= x0; \
x1 ^= x4; x3 ^= x4; x4 &= x0; \
x4 ^= x2; \
})
int __serpent_setkey(struct serpent_ctx *ctx, const u8 *key,
unsigned int keylen)
{
u32 *k = ctx->expkey;
u8 *k8 = (u8 *)k;
u32 r0, r1, r2, r3, r4;
int i;
/* Copy key, add padding */
for (i = 0; i < keylen; ++i)
k8[i] = key[i];
if (i < SERPENT_MAX_KEY_SIZE)
k8[i++] = 1;
while (i < SERPENT_MAX_KEY_SIZE)
k8[i++] = 0;
/* Expand key using polynomial */
r0 = le32_to_cpu(k[3]);
r1 = le32_to_cpu(k[4]);
r2 = le32_to_cpu(k[5]);
r3 = le32_to_cpu(k[6]);
r4 = le32_to_cpu(k[7]);
keyiter(le32_to_cpu(k[0]), r0, r4, r2, 0, 0);
keyiter(le32_to_cpu(k[1]), r1, r0, r3, 1, 1);
keyiter(le32_to_cpu(k[2]), r2, r1, r4, 2, 2);
keyiter(le32_to_cpu(k[3]), r3, r2, r0, 3, 3);
keyiter(le32_to_cpu(k[4]), r4, r3, r1, 4, 4);
keyiter(le32_to_cpu(k[5]), r0, r4, r2, 5, 5);
keyiter(le32_to_cpu(k[6]), r1, r0, r3, 6, 6);
keyiter(le32_to_cpu(k[7]), r2, r1, r4, 7, 7);
keyiter(k[0], r3, r2, r0, 8, 8);
keyiter(k[1], r4, r3, r1, 9, 9);
keyiter(k[2], r0, r4, r2, 10, 10);
keyiter(k[3], r1, r0, r3, 11, 11);
keyiter(k[4], r2, r1, r4, 12, 12);
keyiter(k[5], r3, r2, r0, 13, 13);
keyiter(k[6], r4, r3, r1, 14, 14);
keyiter(k[7], r0, r4, r2, 15, 15);
keyiter(k[8], r1, r0, r3, 16, 16);
keyiter(k[9], r2, r1, r4, 17, 17);
keyiter(k[10], r3, r2, r0, 18, 18);
keyiter(k[11], r4, r3, r1, 19, 19);
keyiter(k[12], r0, r4, r2, 20, 20);
keyiter(k[13], r1, r0, r3, 21, 21);
keyiter(k[14], r2, r1, r4, 22, 22);
keyiter(k[15], r3, r2, r0, 23, 23);
keyiter(k[16], r4, r3, r1, 24, 24);
keyiter(k[17], r0, r4, r2, 25, 25);
keyiter(k[18], r1, r0, r3, 26, 26);
keyiter(k[19], r2, r1, r4, 27, 27);
keyiter(k[20], r3, r2, r0, 28, 28);
keyiter(k[21], r4, r3, r1, 29, 29);
keyiter(k[22], r0, r4, r2, 30, 30);
keyiter(k[23], r1, r0, r3, 31, 31);
k += 50;
keyiter(k[-26], r2, r1, r4, 32, -18);
keyiter(k[-25], r3, r2, r0, 33, -17);
keyiter(k[-24], r4, r3, r1, 34, -16);
keyiter(k[-23], r0, r4, r2, 35, -15);
keyiter(k[-22], r1, r0, r3, 36, -14);
keyiter(k[-21], r2, r1, r4, 37, -13);
keyiter(k[-20], r3, r2, r0, 38, -12);
keyiter(k[-19], r4, r3, r1, 39, -11);
keyiter(k[-18], r0, r4, r2, 40, -10);
keyiter(k[-17], r1, r0, r3, 41, -9);
keyiter(k[-16], r2, r1, r4, 42, -8);
keyiter(k[-15], r3, r2, r0, 43, -7);
keyiter(k[-14], r4, r3, r1, 44, -6);
keyiter(k[-13], r0, r4, r2, 45, -5);
keyiter(k[-12], r1, r0, r3, 46, -4);
keyiter(k[-11], r2, r1, r4, 47, -3);
keyiter(k[-10], r3, r2, r0, 48, -2);
keyiter(k[-9], r4, r3, r1, 49, -1);
keyiter(k[-8], r0, r4, r2, 50, 0);
keyiter(k[-7], r1, r0, r3, 51, 1);
keyiter(k[-6], r2, r1, r4, 52, 2);
keyiter(k[-5], r3, r2, r0, 53, 3);
keyiter(k[-4], r4, r3, r1, 54, 4);
keyiter(k[-3], r0, r4, r2, 55, 5);
keyiter(k[-2], r1, r0, r3, 56, 6);
keyiter(k[-1], r2, r1, r4, 57, 7);
keyiter(k[0], r3, r2, r0, 58, 8);
keyiter(k[1], r4, r3, r1, 59, 9);
keyiter(k[2], r0, r4, r2, 60, 10);
keyiter(k[3], r1, r0, r3, 61, 11);
keyiter(k[4], r2, r1, r4, 62, 12);
keyiter(k[5], r3, r2, r0, 63, 13);
keyiter(k[6], r4, r3, r1, 64, 14);
keyiter(k[7], r0, r4, r2, 65, 15);
keyiter(k[8], r1, r0, r3, 66, 16);
keyiter(k[9], r2, r1, r4, 67, 17);
keyiter(k[10], r3, r2, r0, 68, 18);
keyiter(k[11], r4, r3, r1, 69, 19);
keyiter(k[12], r0, r4, r2, 70, 20);
keyiter(k[13], r1, r0, r3, 71, 21);
keyiter(k[14], r2, r1, r4, 72, 22);
keyiter(k[15], r3, r2, r0, 73, 23);
keyiter(k[16], r4, r3, r1, 74, 24);
keyiter(k[17], r0, r4, r2, 75, 25);
keyiter(k[18], r1, r0, r3, 76, 26);
keyiter(k[19], r2, r1, r4, 77, 27);
keyiter(k[20], r3, r2, r0, 78, 28);
keyiter(k[21], r4, r3, r1, 79, 29);
keyiter(k[22], r0, r4, r2, 80, 30);
keyiter(k[23], r1, r0, r3, 81, 31);
k += 50;
keyiter(k[-26], r2, r1, r4, 82, -18);
keyiter(k[-25], r3, r2, r0, 83, -17);
keyiter(k[-24], r4, r3, r1, 84, -16);
keyiter(k[-23], r0, r4, r2, 85, -15);
keyiter(k[-22], r1, r0, r3, 86, -14);
keyiter(k[-21], r2, r1, r4, 87, -13);
keyiter(k[-20], r3, r2, r0, 88, -12);
keyiter(k[-19], r4, r3, r1, 89, -11);
keyiter(k[-18], r0, r4, r2, 90, -10);
keyiter(k[-17], r1, r0, r3, 91, -9);
keyiter(k[-16], r2, r1, r4, 92, -8);
keyiter(k[-15], r3, r2, r0, 93, -7);
keyiter(k[-14], r4, r3, r1, 94, -6);
keyiter(k[-13], r0, r4, r2, 95, -5);
keyiter(k[-12], r1, r0, r3, 96, -4);
keyiter(k[-11], r2, r1, r4, 97, -3);
keyiter(k[-10], r3, r2, r0, 98, -2);
keyiter(k[-9], r4, r3, r1, 99, -1);
keyiter(k[-8], r0, r4, r2, 100, 0);
keyiter(k[-7], r1, r0, r3, 101, 1);
keyiter(k[-6], r2, r1, r4, 102, 2);
keyiter(k[-5], r3, r2, r0, 103, 3);
keyiter(k[-4], r4, r3, r1, 104, 4);
keyiter(k[-3], r0, r4, r2, 105, 5);
keyiter(k[-2], r1, r0, r3, 106, 6);
keyiter(k[-1], r2, r1, r4, 107, 7);
keyiter(k[0], r3, r2, r0, 108, 8);
keyiter(k[1], r4, r3, r1, 109, 9);
keyiter(k[2], r0, r4, r2, 110, 10);
keyiter(k[3], r1, r0, r3, 111, 11);
keyiter(k[4], r2, r1, r4, 112, 12);
keyiter(k[5], r3, r2, r0, 113, 13);
keyiter(k[6], r4, r3, r1, 114, 14);
keyiter(k[7], r0, r4, r2, 115, 15);
keyiter(k[8], r1, r0, r3, 116, 16);
keyiter(k[9], r2, r1, r4, 117, 17);
keyiter(k[10], r3, r2, r0, 118, 18);
keyiter(k[11], r4, r3, r1, 119, 19);
keyiter(k[12], r0, r4, r2, 120, 20);
keyiter(k[13], r1, r0, r3, 121, 21);
keyiter(k[14], r2, r1, r4, 122, 22);
keyiter(k[15], r3, r2, r0, 123, 23);
keyiter(k[16], r4, r3, r1, 124, 24);
keyiter(k[17], r0, r4, r2, 125, 25);
keyiter(k[18], r1, r0, r3, 126, 26);
keyiter(k[19], r2, r1, r4, 127, 27);
keyiter(k[20], r3, r2, r0, 128, 28);
keyiter(k[21], r4, r3, r1, 129, 29);
keyiter(k[22], r0, r4, r2, 130, 30);
keyiter(k[23], r1, r0, r3, 131, 31);
/* Apply S-boxes */
S3(r3, r4, r0, r1, r2); store_and_load_keys(r1, r2, r4, r3, 28, 24);
S4(r1, r2, r4, r3, r0); store_and_load_keys(r2, r4, r3, r0, 24, 20);
S5(r2, r4, r3, r0, r1); store_and_load_keys(r1, r2, r4, r0, 20, 16);
S6(r1, r2, r4, r0, r3); store_and_load_keys(r4, r3, r2, r0, 16, 12);
S7(r4, r3, r2, r0, r1); store_and_load_keys(r1, r2, r0, r4, 12, 8);
S0(r1, r2, r0, r4, r3); store_and_load_keys(r0, r2, r4, r1, 8, 4);
S1(r0, r2, r4, r1, r3); store_and_load_keys(r3, r4, r1, r0, 4, 0);
S2(r3, r4, r1, r0, r2); store_and_load_keys(r2, r4, r3, r0, 0, -4);
S3(r2, r4, r3, r0, r1); store_and_load_keys(r0, r1, r4, r2, -4, -8);
S4(r0, r1, r4, r2, r3); store_and_load_keys(r1, r4, r2, r3, -8, -12);
S5(r1, r4, r2, r3, r0); store_and_load_keys(r0, r1, r4, r3, -12, -16);
S6(r0, r1, r4, r3, r2); store_and_load_keys(r4, r2, r1, r3, -16, -20);
S7(r4, r2, r1, r3, r0); store_and_load_keys(r0, r1, r3, r4, -20, -24);
S0(r0, r1, r3, r4, r2); store_and_load_keys(r3, r1, r4, r0, -24, -28);
k -= 50;
S1(r3, r1, r4, r0, r2); store_and_load_keys(r2, r4, r0, r3, 22, 18);
S2(r2, r4, r0, r3, r1); store_and_load_keys(r1, r4, r2, r3, 18, 14);
S3(r1, r4, r2, r3, r0); store_and_load_keys(r3, r0, r4, r1, 14, 10);
S4(r3, r0, r4, r1, r2); store_and_load_keys(r0, r4, r1, r2, 10, 6);
S5(r0, r4, r1, r2, r3); store_and_load_keys(r3, r0, r4, r2, 6, 2);
S6(r3, r0, r4, r2, r1); store_and_load_keys(r4, r1, r0, r2, 2, -2);
S7(r4, r1, r0, r2, r3); store_and_load_keys(r3, r0, r2, r4, -2, -6);
S0(r3, r0, r2, r4, r1); store_and_load_keys(r2, r0, r4, r3, -6, -10);
S1(r2, r0, r4, r3, r1); store_and_load_keys(r1, r4, r3, r2, -10, -14);
S2(r1, r4, r3, r2, r0); store_and_load_keys(r0, r4, r1, r2, -14, -18);
S3(r0, r4, r1, r2, r3); store_and_load_keys(r2, r3, r4, r0, -18, -22);
k -= 50;
S4(r2, r3, r4, r0, r1); store_and_load_keys(r3, r4, r0, r1, 28, 24);
S5(r3, r4, r0, r1, r2); store_and_load_keys(r2, r3, r4, r1, 24, 20);
S6(r2, r3, r4, r1, r0); store_and_load_keys(r4, r0, r3, r1, 20, 16);
S7(r4, r0, r3, r1, r2); store_and_load_keys(r2, r3, r1, r4, 16, 12);
S0(r2, r3, r1, r4, r0); store_and_load_keys(r1, r3, r4, r2, 12, 8);
S1(r1, r3, r4, r2, r0); store_and_load_keys(r0, r4, r2, r1, 8, 4);
S2(r0, r4, r2, r1, r3); store_and_load_keys(r3, r4, r0, r1, 4, 0);
S3(r3, r4, r0, r1, r2); storekeys(r1, r2, r4, r3, 0);
return 0;
}
EXPORT_SYMBOL_GPL(__serpent_setkey);
int serpent_setkey(struct crypto_tfm *tfm, const u8 *key, unsigned int keylen)
{
return __serpent_setkey(crypto_tfm_ctx(tfm), key, keylen);
}
EXPORT_SYMBOL_GPL(serpent_setkey);
void __serpent_encrypt(struct serpent_ctx *ctx, u8 *dst, const u8 *src)
{
const u32 *k = ctx->expkey;
const __le32 *s = (const __le32 *)src;
__le32 *d = (__le32 *)dst;
u32 r0, r1, r2, r3, r4;
/*
* Note: The conversions between u8* and u32* might cause trouble
* on architectures with stricter alignment rules than x86
*/
r0 = le32_to_cpu(s[0]);
r1 = le32_to_cpu(s[1]);
r2 = le32_to_cpu(s[2]);
r3 = le32_to_cpu(s[3]);
K(r0, r1, r2, r3, 0);
S0(r0, r1, r2, r3, r4); LK(r2, r1, r3, r0, r4, 1);
S1(r2, r1, r3, r0, r4); LK(r4, r3, r0, r2, r1, 2);
S2(r4, r3, r0, r2, r1); LK(r1, r3, r4, r2, r0, 3);
S3(r1, r3, r4, r2, r0); LK(r2, r0, r3, r1, r4, 4);
S4(r2, r0, r3, r1, r4); LK(r0, r3, r1, r4, r2, 5);
S5(r0, r3, r1, r4, r2); LK(r2, r0, r3, r4, r1, 6);
S6(r2, r0, r3, r4, r1); LK(r3, r1, r0, r4, r2, 7);
S7(r3, r1, r0, r4, r2); LK(r2, r0, r4, r3, r1, 8);
S0(r2, r0, r4, r3, r1); LK(r4, r0, r3, r2, r1, 9);
S1(r4, r0, r3, r2, r1); LK(r1, r3, r2, r4, r0, 10);
S2(r1, r3, r2, r4, r0); LK(r0, r3, r1, r4, r2, 11);
S3(r0, r3, r1, r4, r2); LK(r4, r2, r3, r0, r1, 12);
S4(r4, r2, r3, r0, r1); LK(r2, r3, r0, r1, r4, 13);
S5(r2, r3, r0, r1, r4); LK(r4, r2, r3, r1, r0, 14);
S6(r4, r2, r3, r1, r0); LK(r3, r0, r2, r1, r4, 15);
S7(r3, r0, r2, r1, r4); LK(r4, r2, r1, r3, r0, 16);
S0(r4, r2, r1, r3, r0); LK(r1, r2, r3, r4, r0, 17);
S1(r1, r2, r3, r4, r0); LK(r0, r3, r4, r1, r2, 18);
S2(r0, r3, r4, r1, r2); LK(r2, r3, r0, r1, r4, 19);
S3(r2, r3, r0, r1, r4); LK(r1, r4, r3, r2, r0, 20);
S4(r1, r4, r3, r2, r0); LK(r4, r3, r2, r0, r1, 21);
S5(r4, r3, r2, r0, r1); LK(r1, r4, r3, r0, r2, 22);
S6(r1, r4, r3, r0, r2); LK(r3, r2, r4, r0, r1, 23);
S7(r3, r2, r4, r0, r1); LK(r1, r4, r0, r3, r2, 24);
S0(r1, r4, r0, r3, r2); LK(r0, r4, r3, r1, r2, 25);
S1(r0, r4, r3, r1, r2); LK(r2, r3, r1, r0, r4, 26);
S2(r2, r3, r1, r0, r4); LK(r4, r3, r2, r0, r1, 27);
S3(r4, r3, r2, r0, r1); LK(r0, r1, r3, r4, r2, 28);
S4(r0, r1, r3, r4, r2); LK(r1, r3, r4, r2, r0, 29);
S5(r1, r3, r4, r2, r0); LK(r0, r1, r3, r2, r4, 30);
S6(r0, r1, r3, r2, r4); LK(r3, r4, r1, r2, r0, 31);
S7(r3, r4, r1, r2, r0); K(r0, r1, r2, r3, 32);
d[0] = cpu_to_le32(r0);
d[1] = cpu_to_le32(r1);
d[2] = cpu_to_le32(r2);
d[3] = cpu_to_le32(r3);
}
EXPORT_SYMBOL_GPL(__serpent_encrypt);
static void serpent_encrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
struct serpent_ctx *ctx = crypto_tfm_ctx(tfm);
__serpent_encrypt(ctx, dst, src);
}
void __serpent_decrypt(struct serpent_ctx *ctx, u8 *dst, const u8 *src)
{
const u32 *k = ctx->expkey;
const __le32 *s = (const __le32 *)src;
__le32 *d = (__le32 *)dst;
u32 r0, r1, r2, r3, r4;
r0 = le32_to_cpu(s[0]);
r1 = le32_to_cpu(s[1]);
r2 = le32_to_cpu(s[2]);
r3 = le32_to_cpu(s[3]);
K(r0, r1, r2, r3, 32);
SI7(r0, r1, r2, r3, r4); KL(r1, r3, r0, r4, r2, 31);
SI6(r1, r3, r0, r4, r2); KL(r0, r2, r4, r1, r3, 30);
SI5(r0, r2, r4, r1, r3); KL(r2, r3, r0, r4, r1, 29);
SI4(r2, r3, r0, r4, r1); KL(r2, r0, r1, r4, r3, 28);
SI3(r2, r0, r1, r4, r3); KL(r1, r2, r3, r4, r0, 27);
SI2(r1, r2, r3, r4, r0); KL(r2, r0, r4, r3, r1, 26);
SI1(r2, r0, r4, r3, r1); KL(r1, r0, r4, r3, r2, 25);
SI0(r1, r0, r4, r3, r2); KL(r4, r2, r0, r1, r3, 24);
SI7(r4, r2, r0, r1, r3); KL(r2, r1, r4, r3, r0, 23);
SI6(r2, r1, r4, r3, r0); KL(r4, r0, r3, r2, r1, 22);
SI5(r4, r0, r3, r2, r1); KL(r0, r1, r4, r3, r2, 21);
SI4(r0, r1, r4, r3, r2); KL(r0, r4, r2, r3, r1, 20);
SI3(r0, r4, r2, r3, r1); KL(r2, r0, r1, r3, r4, 19);
SI2(r2, r0, r1, r3, r4); KL(r0, r4, r3, r1, r2, 18);
SI1(r0, r4, r3, r1, r2); KL(r2, r4, r3, r1, r0, 17);
SI0(r2, r4, r3, r1, r0); KL(r3, r0, r4, r2, r1, 16);
SI7(r3, r0, r4, r2, r1); KL(r0, r2, r3, r1, r4, 15);
SI6(r0, r2, r3, r1, r4); KL(r3, r4, r1, r0, r2, 14);
SI5(r3, r4, r1, r0, r2); KL(r4, r2, r3, r1, r0, 13);
SI4(r4, r2, r3, r1, r0); KL(r4, r3, r0, r1, r2, 12);
SI3(r4, r3, r0, r1, r2); KL(r0, r4, r2, r1, r3, 11);
SI2(r0, r4, r2, r1, r3); KL(r4, r3, r1, r2, r0, 10);
SI1(r4, r3, r1, r2, r0); KL(r0, r3, r1, r2, r4, 9);
SI0(r0, r3, r1, r2, r4); KL(r1, r4, r3, r0, r2, 8);
SI7(r1, r4, r3, r0, r2); KL(r4, r0, r1, r2, r3, 7);
SI6(r4, r0, r1, r2, r3); KL(r1, r3, r2, r4, r0, 6);
SI5(r1, r3, r2, r4, r0); KL(r3, r0, r1, r2, r4, 5);
SI4(r3, r0, r1, r2, r4); KL(r3, r1, r4, r2, r0, 4);
SI3(r3, r1, r4, r2, r0); KL(r4, r3, r0, r2, r1, 3);
SI2(r4, r3, r0, r2, r1); KL(r3, r1, r2, r0, r4, 2);
SI1(r3, r1, r2, r0, r4); KL(r4, r1, r2, r0, r3, 1);
SI0(r4, r1, r2, r0, r3); K(r2, r3, r1, r4, 0);
d[0] = cpu_to_le32(r2);
d[1] = cpu_to_le32(r3);
d[2] = cpu_to_le32(r1);
d[3] = cpu_to_le32(r4);
}
EXPORT_SYMBOL_GPL(__serpent_decrypt);
static void serpent_decrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
struct serpent_ctx *ctx = crypto_tfm_ctx(tfm);
__serpent_decrypt(ctx, dst, src);
}
static int tnepres_setkey(struct crypto_tfm *tfm, const u8 *key,
unsigned int keylen)
{
u8 rev_key[SERPENT_MAX_KEY_SIZE];
int i;
for (i = 0; i < keylen; ++i)
rev_key[keylen - i - 1] = key[i];
return serpent_setkey(tfm, rev_key, keylen);
}
static void tnepres_encrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
const u32 * const s = (const u32 * const)src;
u32 * const d = (u32 * const)dst;
u32 rs[4], rd[4];
rs[0] = swab32(s[3]);
rs[1] = swab32(s[2]);
rs[2] = swab32(s[1]);
rs[3] = swab32(s[0]);
serpent_encrypt(tfm, (u8 *)rd, (u8 *)rs);
d[0] = swab32(rd[3]);
d[1] = swab32(rd[2]);
d[2] = swab32(rd[1]);
d[3] = swab32(rd[0]);
}
static void tnepres_decrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
const u32 * const s = (const u32 * const)src;
u32 * const d = (u32 * const)dst;
u32 rs[4], rd[4];
rs[0] = swab32(s[3]);
rs[1] = swab32(s[2]);
rs[2] = swab32(s[1]);
rs[3] = swab32(s[0]);
serpent_decrypt(tfm, (u8 *)rd, (u8 *)rs);
d[0] = swab32(rd[3]);
d[1] = swab32(rd[2]);
d[2] = swab32(rd[1]);
d[3] = swab32(rd[0]);
}
static struct crypto_alg srp_algs[2] = { {
.cra_name = "serpent",
.cra_driver_name = "serpent-generic",
.cra_priority = 100,
.cra_flags = CRYPTO_ALG_TYPE_CIPHER,
.cra_blocksize = SERPENT_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct serpent_ctx),
.cra_alignmask = 3,
.cra_module = THIS_MODULE,
.cra_u = { .cipher = {
.cia_min_keysize = SERPENT_MIN_KEY_SIZE,
.cia_max_keysize = SERPENT_MAX_KEY_SIZE,
.cia_setkey = serpent_setkey,
.cia_encrypt = serpent_encrypt,
.cia_decrypt = serpent_decrypt } }
}, {
.cra_name = "tnepres",
.cra_flags = CRYPTO_ALG_TYPE_CIPHER,
.cra_blocksize = SERPENT_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct serpent_ctx),
.cra_alignmask = 3,
.cra_module = THIS_MODULE,
.cra_u = { .cipher = {
.cia_min_keysize = SERPENT_MIN_KEY_SIZE,
.cia_max_keysize = SERPENT_MAX_KEY_SIZE,
.cia_setkey = tnepres_setkey,
.cia_encrypt = tnepres_encrypt,
.cia_decrypt = tnepres_decrypt } }
} };
static int __init serpent_mod_init(void)
{
return crypto_register_algs(srp_algs, ARRAY_SIZE(srp_algs));
}
static void __exit serpent_mod_fini(void)
{
crypto_unregister_algs(srp_algs, ARRAY_SIZE(srp_algs));
}
module_init(serpent_mod_init);
module_exit(serpent_mod_fini);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Serpent and tnepres (kerneli compatible serpent reversed) Cipher Algorithm");
MODULE_AUTHOR("Dag Arne Osvik <osvik@ii.uib.no>");
MODULE_ALIAS_CRYPTO("tnepres");
MODULE_ALIAS_CRYPTO("serpent");
MODULE_ALIAS_CRYPTO("serpent-generic");
| null | null | null | null | 112,757 |
43,430 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 208,425 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | #include <asm/poll.h>
| null | null | null | null | 116,772 |
33,000 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 33,000 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | /*
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "third_party/blink/renderer/core/inspector/identifiers_factory.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/core/dom/weak_identifier_map.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/inspector/inspected_frames.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
namespace {
volatile int g_last_used_identifier = 0;
} // namespace
// static
String IdentifiersFactory::CreateIdentifier() {
int identifier = AtomicIncrement(&g_last_used_identifier);
return AddProcessIdPrefixTo(identifier);
}
// static
String IdentifiersFactory::RequestId(DocumentLoader* loader,
unsigned long identifier) {
if (!identifier)
return String();
if (loader && loader->MainResourceIdentifier() == identifier)
return LoaderId(loader);
return AddProcessIdPrefixTo(identifier);
}
// static
String IdentifiersFactory::SubresourceRequestId(unsigned long identifier) {
return RequestId(nullptr, identifier);
}
// static
String IdentifiersFactory::FrameId(Frame* frame) {
// Note: this should be equal to ToTraceValue(frame).
return String(ToTraceValue(frame).data());
}
// static
LocalFrame* IdentifiersFactory::FrameById(InspectedFrames* inspected_frames,
const String& frame_id) {
for (auto* frame : *inspected_frames) {
if (frame->Client() &&
frame_id == IdFromToken(frame->GetDevToolsFrameToken())) {
return frame;
}
}
return nullptr;
}
// static
String IdentifiersFactory::LoaderId(DocumentLoader* loader) {
if (!loader)
return g_empty_string;
const base::UnguessableToken& token = loader->GetDevToolsNavigationToken();
// token.ToString() is latin1.
return String(token.ToString().c_str());
}
// static
String IdentifiersFactory::IdFromToken(const base::UnguessableToken& token) {
if (token.is_empty())
return g_empty_string;
// token.ToString() is latin1.
return String(token.ToString().c_str());
}
// static
String IdentifiersFactory::AddProcessIdPrefixTo(int id) {
static uint32_t process_id = Platform::Current()->GetUniqueIdForProcess();
StringBuilder builder;
builder.AppendNumber(process_id);
builder.Append('.');
builder.AppendNumber(id);
return builder.ToString();
}
// static
int IdentifiersFactory::RemoveProcessIdPrefixFrom(const String& id, bool* ok) {
size_t dot_index = id.find('.');
if (dot_index == kNotFound) {
*ok = false;
return 0;
}
return id.Substring(dot_index + 1).ToInt(ok);
}
} // namespace blink
| null | null | null | null | 29,863 |
4,043 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 4,043 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2015 The Chromium 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 "ios/chrome/browser/chrome_constants.h"
const char kIOSChromeInitialBrowserState[] = "Default";
const char kIOSChromeMultiBrowserStatePrefix[] = "Profile ";
const base::FilePath::CharType kIOSChromeCacheDirname[] =
FILE_PATH_LITERAL("Cache");
const base::FilePath::CharType kIOSChromeChannelIDFilename[] =
FILE_PATH_LITERAL("Origin Bound Certs");
const base::FilePath::CharType kIOSChromeCookieFilename[] =
FILE_PATH_LITERAL("Cookies");
const base::FilePath::CharType kIOSChromeCRLSetFilename[] =
FILE_PATH_LITERAL("Certificate Revocation Lists");
const base::FilePath::CharType kIOSChromeNetworkPersistentStateFilename[] =
FILE_PATH_LITERAL("Network Persistent State");
| null | null | null | null | 906 |
11,530 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 176,525 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | /*
* Copyright 2010 Tilera Corporation. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, version 2.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for
* more details.
*/
#ifndef _ASM_TILE_SWAB_H
#define _ASM_TILE_SWAB_H
/* Tile gcc is always >= 4.3.0, so we use __builtin_bswap. */
#define __arch_swab32(x) __builtin_bswap32(x)
#define __arch_swab64(x) __builtin_bswap64(x)
#define __arch_swab16(x) (__builtin_bswap32(x) >> 16)
#endif /* _ASM_TILE_SWAB_H */
| null | null | null | null | 84,872 |
27,679 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 192,674 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | /*
* GPL HEADER START
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 only,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is included
* in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; If not, see
* http://www.gnu.org/licenses/gpl-2.0.html
*
* GPL HEADER END
*/
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* Use is subject to license terms.
*
* Copyright (c) 2012, Intel Corporation.
*/
/*
* This file is part of Lustre, http://www.lustre.org/
* Lustre is a trademark of Sun Microsystems, Inc.
*
* Author: Nathan Rutman <nathan.rutman@sun.com>
*
* Kernel <-> userspace communication routines.
* Using pipes for all arches.
*/
#define DEBUG_SUBSYSTEM S_CLASS
#define D_KUC D_OTHER
#include "../include/obd_support.h"
#include "../include/lustre_kernelcomm.h"
/**
* libcfs_kkuc_msg_put - send an message from kernel to userspace
* @param fp to send the message to
* @param payload Payload data. First field of payload is always
* struct kuc_hdr
*/
int libcfs_kkuc_msg_put(struct file *filp, void *payload)
{
struct kuc_hdr *kuch = (struct kuc_hdr *)payload;
ssize_t count = kuch->kuc_msglen;
loff_t offset = 0;
mm_segment_t fs;
int rc = -ENXIO;
if (IS_ERR_OR_NULL(filp))
return -EBADF;
if (kuch->kuc_magic != KUC_MAGIC) {
CERROR("KernelComm: bad magic %x\n", kuch->kuc_magic);
return rc;
}
fs = get_fs();
set_fs(KERNEL_DS);
while (count > 0) {
rc = vfs_write(filp, (void __force __user *)payload,
count, &offset);
if (rc < 0)
break;
count -= rc;
payload += rc;
rc = 0;
}
set_fs(fs);
if (rc < 0)
CWARN("message send failed (%d)\n", rc);
else
CDEBUG(D_KUC, "Sent message rc=%d, fp=%p\n", rc, filp);
return rc;
}
EXPORT_SYMBOL(libcfs_kkuc_msg_put);
/*
* Broadcast groups are global across all mounted filesystems;
* i.e. registering for a group on 1 fs will get messages for that
* group from any fs
*/
/** A single group registration has a uid and a file pointer */
struct kkuc_reg {
struct list_head kr_chain;
int kr_uid;
struct file *kr_fp;
char kr_data[0];
};
static struct list_head kkuc_groups[KUC_GRP_MAX + 1] = {};
/* Protect message sending against remove and adds */
static DECLARE_RWSEM(kg_sem);
/** Add a receiver to a broadcast group
* @param filp pipe to write into
* @param uid identifier for this receiver
* @param group group number
* @param data user data
*/
int libcfs_kkuc_group_add(struct file *filp, int uid, unsigned int group,
void *data, size_t data_len)
{
struct kkuc_reg *reg;
if (group > KUC_GRP_MAX) {
CDEBUG(D_WARNING, "Kernelcomm: bad group %d\n", group);
return -EINVAL;
}
/* fput in group_rem */
if (!filp)
return -EBADF;
/* freed in group_rem */
reg = kmalloc(sizeof(*reg) + data_len, 0);
if (!reg)
return -ENOMEM;
reg->kr_fp = filp;
reg->kr_uid = uid;
memcpy(reg->kr_data, data, data_len);
down_write(&kg_sem);
if (!kkuc_groups[group].next)
INIT_LIST_HEAD(&kkuc_groups[group]);
list_add(®->kr_chain, &kkuc_groups[group]);
up_write(&kg_sem);
CDEBUG(D_KUC, "Added uid=%d fp=%p to group %d\n", uid, filp, group);
return 0;
}
EXPORT_SYMBOL(libcfs_kkuc_group_add);
int libcfs_kkuc_group_rem(int uid, unsigned int group)
{
struct kkuc_reg *reg, *next;
if (!kkuc_groups[group].next)
return 0;
if (!uid) {
/* Broadcast a shutdown message */
struct kuc_hdr lh;
lh.kuc_magic = KUC_MAGIC;
lh.kuc_transport = KUC_TRANSPORT_GENERIC;
lh.kuc_msgtype = KUC_MSG_SHUTDOWN;
lh.kuc_msglen = sizeof(lh);
libcfs_kkuc_group_put(group, &lh);
}
down_write(&kg_sem);
list_for_each_entry_safe(reg, next, &kkuc_groups[group], kr_chain) {
if (!uid || (uid == reg->kr_uid)) {
list_del(®->kr_chain);
CDEBUG(D_KUC, "Removed uid=%d fp=%p from group %d\n",
reg->kr_uid, reg->kr_fp, group);
if (reg->kr_fp)
fput(reg->kr_fp);
kfree(reg);
}
}
up_write(&kg_sem);
return 0;
}
EXPORT_SYMBOL(libcfs_kkuc_group_rem);
int libcfs_kkuc_group_put(unsigned int group, void *payload)
{
struct kkuc_reg *reg;
int rc = 0;
int one_success = 0;
down_write(&kg_sem);
list_for_each_entry(reg, &kkuc_groups[group], kr_chain) {
if (reg->kr_fp) {
rc = libcfs_kkuc_msg_put(reg->kr_fp, payload);
if (!rc) {
one_success = 1;
} else if (rc == -EPIPE) {
fput(reg->kr_fp);
reg->kr_fp = NULL;
}
}
}
up_write(&kg_sem);
/*
* don't return an error if the message has been delivered
* at least to one agent
*/
if (one_success)
rc = 0;
return rc;
}
EXPORT_SYMBOL(libcfs_kkuc_group_put);
/**
* Calls a callback function for each link of the given kuc group.
* @param group the group to call the function on.
* @param cb_func the function to be called.
* @param cb_arg extra argument to be passed to the callback function.
*/
int libcfs_kkuc_group_foreach(unsigned int group, libcfs_kkuc_cb_t cb_func,
void *cb_arg)
{
struct kkuc_reg *reg;
int rc = 0;
if (group > KUC_GRP_MAX) {
CDEBUG(D_WARNING, "Kernelcomm: bad group %d\n", group);
return -EINVAL;
}
/* no link for this group */
if (!kkuc_groups[group].next)
return 0;
down_read(&kg_sem);
list_for_each_entry(reg, &kkuc_groups[group], kr_chain) {
if (reg->kr_fp)
rc = cb_func(reg->kr_data, cb_arg);
}
up_read(&kg_sem);
return rc;
}
EXPORT_SYMBOL(libcfs_kkuc_group_foreach);
| null | null | null | null | 101,021 |
30,359 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 30,359 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2016 The Chromium 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 THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_DOUBLE_SIZE_H_
#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_DOUBLE_SIZE_H_
#include "third_party/blink/public/platform/web_common.h"
#if INSIDE_BLINK
#include "third_party/blink/renderer/platform/geometry/double_size.h"
#else
#include <ui/gfx/geometry/size_f.h>
#include <ui/gfx/geometry/vector2d_f.h>
#endif
namespace blink {
class WebDoubleSize {
public:
bool IsEmpty() const { return width_ <= 0 || height_ <= 0; }
WebDoubleSize() : width_(0), height_(0) {}
WebDoubleSize(double width, double height) : width_(width), height_(height) {}
#if INSIDE_BLINK
WebDoubleSize(const DoubleSize& size)
: width_(size.Width()), height_(size.Height()) {}
WebDoubleSize& operator=(const DoubleSize& size) {
width_ = size.Width();
height_ = size.Height();
return *this;
}
operator DoubleSize() const { return DoubleSize(width_, height_); }
#else
WebDoubleSize(const gfx::SizeF& size)
: width_(size.width()), height_(size.height()) {}
WebDoubleSize(const gfx::Vector2dF& vector)
: width_(vector.x()), height_(vector.y()) {}
WebDoubleSize& operator=(const gfx::SizeF& size) {
width_ = size.width();
height_ = size.height();
return *this;
}
WebDoubleSize& operator=(const gfx::Vector2dF& vector) {
width_ = vector.x();
height_ = vector.y();
return *this;
}
#endif
double Width() const { return width_; }
double Height() const { return height_; }
private:
double width_;
double height_;
};
inline bool operator==(const WebDoubleSize& a, const WebDoubleSize& b) {
return a.Width() == b.Width() && a.Height() == b.Height();
}
inline bool operator!=(const WebDoubleSize& a, const WebDoubleSize& b) {
return !(a == b);
}
} // namespace blink
#endif
| null | null | null | null | 27,222 |
27,052 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 192,047 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | /*
* Code for working with individual keys, and sorted sets of keys with in a
* btree node
*
* Copyright 2012 Google, Inc.
*/
#define pr_fmt(fmt) "bcache: %s() " fmt "\n", __func__
#include "util.h"
#include "bset.h"
#include <linux/console.h>
#include <linux/sched/clock.h>
#include <linux/random.h>
#include <linux/prefetch.h>
#ifdef CONFIG_BCACHE_DEBUG
void bch_dump_bset(struct btree_keys *b, struct bset *i, unsigned set)
{
struct bkey *k, *next;
for (k = i->start; k < bset_bkey_last(i); k = next) {
next = bkey_next(k);
printk(KERN_ERR "block %u key %u/%u: ", set,
(unsigned) ((u64 *) k - i->d), i->keys);
if (b->ops->key_dump)
b->ops->key_dump(b, k);
else
printk("%llu:%llu\n", KEY_INODE(k), KEY_OFFSET(k));
if (next < bset_bkey_last(i) &&
bkey_cmp(k, b->ops->is_extents ?
&START_KEY(next) : next) > 0)
printk(KERN_ERR "Key skipped backwards\n");
}
}
void bch_dump_bucket(struct btree_keys *b)
{
unsigned i;
console_lock();
for (i = 0; i <= b->nsets; i++)
bch_dump_bset(b, b->set[i].data,
bset_sector_offset(b, b->set[i].data));
console_unlock();
}
int __bch_count_data(struct btree_keys *b)
{
unsigned ret = 0;
struct btree_iter iter;
struct bkey *k;
if (b->ops->is_extents)
for_each_key(b, k, &iter)
ret += KEY_SIZE(k);
return ret;
}
void __bch_check_keys(struct btree_keys *b, const char *fmt, ...)
{
va_list args;
struct bkey *k, *p = NULL;
struct btree_iter iter;
const char *err;
for_each_key(b, k, &iter) {
if (b->ops->is_extents) {
err = "Keys out of order";
if (p && bkey_cmp(&START_KEY(p), &START_KEY(k)) > 0)
goto bug;
if (bch_ptr_invalid(b, k))
continue;
err = "Overlapping keys";
if (p && bkey_cmp(p, &START_KEY(k)) > 0)
goto bug;
} else {
if (bch_ptr_bad(b, k))
continue;
err = "Duplicate keys";
if (p && !bkey_cmp(p, k))
goto bug;
}
p = k;
}
#if 0
err = "Key larger than btree node key";
if (p && bkey_cmp(p, &b->key) > 0)
goto bug;
#endif
return;
bug:
bch_dump_bucket(b);
va_start(args, fmt);
vprintk(fmt, args);
va_end(args);
panic("bch_check_keys error: %s:\n", err);
}
static void bch_btree_iter_next_check(struct btree_iter *iter)
{
struct bkey *k = iter->data->k, *next = bkey_next(k);
if (next < iter->data->end &&
bkey_cmp(k, iter->b->ops->is_extents ?
&START_KEY(next) : next) > 0) {
bch_dump_bucket(iter->b);
panic("Key skipped backwards\n");
}
}
#else
static inline void bch_btree_iter_next_check(struct btree_iter *iter) {}
#endif
/* Keylists */
int __bch_keylist_realloc(struct keylist *l, unsigned u64s)
{
size_t oldsize = bch_keylist_nkeys(l);
size_t newsize = oldsize + u64s;
uint64_t *old_keys = l->keys_p == l->inline_keys ? NULL : l->keys_p;
uint64_t *new_keys;
newsize = roundup_pow_of_two(newsize);
if (newsize <= KEYLIST_INLINE ||
roundup_pow_of_two(oldsize) == newsize)
return 0;
new_keys = krealloc(old_keys, sizeof(uint64_t) * newsize, GFP_NOIO);
if (!new_keys)
return -ENOMEM;
if (!old_keys)
memcpy(new_keys, l->inline_keys, sizeof(uint64_t) * oldsize);
l->keys_p = new_keys;
l->top_p = new_keys + oldsize;
return 0;
}
struct bkey *bch_keylist_pop(struct keylist *l)
{
struct bkey *k = l->keys;
if (k == l->top)
return NULL;
while (bkey_next(k) != l->top)
k = bkey_next(k);
return l->top = k;
}
void bch_keylist_pop_front(struct keylist *l)
{
l->top_p -= bkey_u64s(l->keys);
memmove(l->keys,
bkey_next(l->keys),
bch_keylist_bytes(l));
}
/* Key/pointer manipulation */
void bch_bkey_copy_single_ptr(struct bkey *dest, const struct bkey *src,
unsigned i)
{
BUG_ON(i > KEY_PTRS(src));
/* Only copy the header, key, and one pointer. */
memcpy(dest, src, 2 * sizeof(uint64_t));
dest->ptr[0] = src->ptr[i];
SET_KEY_PTRS(dest, 1);
/* We didn't copy the checksum so clear that bit. */
SET_KEY_CSUM(dest, 0);
}
bool __bch_cut_front(const struct bkey *where, struct bkey *k)
{
unsigned i, len = 0;
if (bkey_cmp(where, &START_KEY(k)) <= 0)
return false;
if (bkey_cmp(where, k) < 0)
len = KEY_OFFSET(k) - KEY_OFFSET(where);
else
bkey_copy_key(k, where);
for (i = 0; i < KEY_PTRS(k); i++)
SET_PTR_OFFSET(k, i, PTR_OFFSET(k, i) + KEY_SIZE(k) - len);
BUG_ON(len > KEY_SIZE(k));
SET_KEY_SIZE(k, len);
return true;
}
bool __bch_cut_back(const struct bkey *where, struct bkey *k)
{
unsigned len = 0;
if (bkey_cmp(where, k) >= 0)
return false;
BUG_ON(KEY_INODE(where) != KEY_INODE(k));
if (bkey_cmp(where, &START_KEY(k)) > 0)
len = KEY_OFFSET(where) - KEY_START(k);
bkey_copy_key(k, where);
BUG_ON(len > KEY_SIZE(k));
SET_KEY_SIZE(k, len);
return true;
}
/* Auxiliary search trees */
/* 32 bits total: */
#define BKEY_MID_BITS 3
#define BKEY_EXPONENT_BITS 7
#define BKEY_MANTISSA_BITS (32 - BKEY_MID_BITS - BKEY_EXPONENT_BITS)
#define BKEY_MANTISSA_MASK ((1 << BKEY_MANTISSA_BITS) - 1)
struct bkey_float {
unsigned exponent:BKEY_EXPONENT_BITS;
unsigned m:BKEY_MID_BITS;
unsigned mantissa:BKEY_MANTISSA_BITS;
} __packed;
/*
* BSET_CACHELINE was originally intended to match the hardware cacheline size -
* it used to be 64, but I realized the lookup code would touch slightly less
* memory if it was 128.
*
* It definites the number of bytes (in struct bset) per struct bkey_float in
* the auxiliar search tree - when we're done searching the bset_float tree we
* have this many bytes left that we do a linear search over.
*
* Since (after level 5) every level of the bset_tree is on a new cacheline,
* we're touching one fewer cacheline in the bset tree in exchange for one more
* cacheline in the linear search - but the linear search might stop before it
* gets to the second cacheline.
*/
#define BSET_CACHELINE 128
/* Space required for the btree node keys */
static inline size_t btree_keys_bytes(struct btree_keys *b)
{
return PAGE_SIZE << b->page_order;
}
static inline size_t btree_keys_cachelines(struct btree_keys *b)
{
return btree_keys_bytes(b) / BSET_CACHELINE;
}
/* Space required for the auxiliary search trees */
static inline size_t bset_tree_bytes(struct btree_keys *b)
{
return btree_keys_cachelines(b) * sizeof(struct bkey_float);
}
/* Space required for the prev pointers */
static inline size_t bset_prev_bytes(struct btree_keys *b)
{
return btree_keys_cachelines(b) * sizeof(uint8_t);
}
/* Memory allocation */
void bch_btree_keys_free(struct btree_keys *b)
{
struct bset_tree *t = b->set;
if (bset_prev_bytes(b) < PAGE_SIZE)
kfree(t->prev);
else
free_pages((unsigned long) t->prev,
get_order(bset_prev_bytes(b)));
if (bset_tree_bytes(b) < PAGE_SIZE)
kfree(t->tree);
else
free_pages((unsigned long) t->tree,
get_order(bset_tree_bytes(b)));
free_pages((unsigned long) t->data, b->page_order);
t->prev = NULL;
t->tree = NULL;
t->data = NULL;
}
EXPORT_SYMBOL(bch_btree_keys_free);
int bch_btree_keys_alloc(struct btree_keys *b, unsigned page_order, gfp_t gfp)
{
struct bset_tree *t = b->set;
BUG_ON(t->data);
b->page_order = page_order;
t->data = (void *) __get_free_pages(gfp, b->page_order);
if (!t->data)
goto err;
t->tree = bset_tree_bytes(b) < PAGE_SIZE
? kmalloc(bset_tree_bytes(b), gfp)
: (void *) __get_free_pages(gfp, get_order(bset_tree_bytes(b)));
if (!t->tree)
goto err;
t->prev = bset_prev_bytes(b) < PAGE_SIZE
? kmalloc(bset_prev_bytes(b), gfp)
: (void *) __get_free_pages(gfp, get_order(bset_prev_bytes(b)));
if (!t->prev)
goto err;
return 0;
err:
bch_btree_keys_free(b);
return -ENOMEM;
}
EXPORT_SYMBOL(bch_btree_keys_alloc);
void bch_btree_keys_init(struct btree_keys *b, const struct btree_keys_ops *ops,
bool *expensive_debug_checks)
{
unsigned i;
b->ops = ops;
b->expensive_debug_checks = expensive_debug_checks;
b->nsets = 0;
b->last_set_unwritten = 0;
/* XXX: shouldn't be needed */
for (i = 0; i < MAX_BSETS; i++)
b->set[i].size = 0;
/*
* Second loop starts at 1 because b->keys[0]->data is the memory we
* allocated
*/
for (i = 1; i < MAX_BSETS; i++)
b->set[i].data = NULL;
}
EXPORT_SYMBOL(bch_btree_keys_init);
/* Binary tree stuff for auxiliary search trees */
static unsigned inorder_next(unsigned j, unsigned size)
{
if (j * 2 + 1 < size) {
j = j * 2 + 1;
while (j * 2 < size)
j *= 2;
} else
j >>= ffz(j) + 1;
return j;
}
static unsigned inorder_prev(unsigned j, unsigned size)
{
if (j * 2 < size) {
j = j * 2;
while (j * 2 + 1 < size)
j = j * 2 + 1;
} else
j >>= ffs(j);
return j;
}
/* I have no idea why this code works... and I'm the one who wrote it
*
* However, I do know what it does:
* Given a binary tree constructed in an array (i.e. how you normally implement
* a heap), it converts a node in the tree - referenced by array index - to the
* index it would have if you did an inorder traversal.
*
* Also tested for every j, size up to size somewhere around 6 million.
*
* The binary tree starts at array index 1, not 0
* extra is a function of size:
* extra = (size - rounddown_pow_of_two(size - 1)) << 1;
*/
static unsigned __to_inorder(unsigned j, unsigned size, unsigned extra)
{
unsigned b = fls(j);
unsigned shift = fls(size - 1) - b;
j ^= 1U << (b - 1);
j <<= 1;
j |= 1;
j <<= shift;
if (j > extra)
j -= (j - extra) >> 1;
return j;
}
static unsigned to_inorder(unsigned j, struct bset_tree *t)
{
return __to_inorder(j, t->size, t->extra);
}
static unsigned __inorder_to_tree(unsigned j, unsigned size, unsigned extra)
{
unsigned shift;
if (j > extra)
j += j - extra;
shift = ffs(j);
j >>= shift;
j |= roundup_pow_of_two(size) >> shift;
return j;
}
static unsigned inorder_to_tree(unsigned j, struct bset_tree *t)
{
return __inorder_to_tree(j, t->size, t->extra);
}
#if 0
void inorder_test(void)
{
unsigned long done = 0;
ktime_t start = ktime_get();
for (unsigned size = 2;
size < 65536000;
size++) {
unsigned extra = (size - rounddown_pow_of_two(size - 1)) << 1;
unsigned i = 1, j = rounddown_pow_of_two(size - 1);
if (!(size % 4096))
printk(KERN_NOTICE "loop %u, %llu per us\n", size,
done / ktime_us_delta(ktime_get(), start));
while (1) {
if (__inorder_to_tree(i, size, extra) != j)
panic("size %10u j %10u i %10u", size, j, i);
if (__to_inorder(j, size, extra) != i)
panic("size %10u j %10u i %10u", size, j, i);
if (j == rounddown_pow_of_two(size) - 1)
break;
BUG_ON(inorder_prev(inorder_next(j, size), size) != j);
j = inorder_next(j, size);
i++;
}
done += size - 1;
}
}
#endif
/*
* Cacheline/offset <-> bkey pointer arithmetic:
*
* t->tree is a binary search tree in an array; each node corresponds to a key
* in one cacheline in t->set (BSET_CACHELINE bytes).
*
* This means we don't have to store the full index of the key that a node in
* the binary tree points to; to_inorder() gives us the cacheline, and then
* bkey_float->m gives us the offset within that cacheline, in units of 8 bytes.
*
* cacheline_to_bkey() and friends abstract out all the pointer arithmetic to
* make this work.
*
* To construct the bfloat for an arbitrary key we need to know what the key
* immediately preceding it is: we have to check if the two keys differ in the
* bits we're going to store in bkey_float->mantissa. t->prev[j] stores the size
* of the previous key so we can walk backwards to it from t->tree[j]'s key.
*/
static struct bkey *cacheline_to_bkey(struct bset_tree *t, unsigned cacheline,
unsigned offset)
{
return ((void *) t->data) + cacheline * BSET_CACHELINE + offset * 8;
}
static unsigned bkey_to_cacheline(struct bset_tree *t, struct bkey *k)
{
return ((void *) k - (void *) t->data) / BSET_CACHELINE;
}
static unsigned bkey_to_cacheline_offset(struct bset_tree *t,
unsigned cacheline,
struct bkey *k)
{
return (u64 *) k - (u64 *) cacheline_to_bkey(t, cacheline, 0);
}
static struct bkey *tree_to_bkey(struct bset_tree *t, unsigned j)
{
return cacheline_to_bkey(t, to_inorder(j, t), t->tree[j].m);
}
static struct bkey *tree_to_prev_bkey(struct bset_tree *t, unsigned j)
{
return (void *) (((uint64_t *) tree_to_bkey(t, j)) - t->prev[j]);
}
/*
* For the write set - the one we're currently inserting keys into - we don't
* maintain a full search tree, we just keep a simple lookup table in t->prev.
*/
static struct bkey *table_to_bkey(struct bset_tree *t, unsigned cacheline)
{
return cacheline_to_bkey(t, cacheline, t->prev[cacheline]);
}
static inline uint64_t shrd128(uint64_t high, uint64_t low, uint8_t shift)
{
low >>= shift;
low |= (high << 1) << (63U - shift);
return low;
}
static inline unsigned bfloat_mantissa(const struct bkey *k,
struct bkey_float *f)
{
const uint64_t *p = &k->low - (f->exponent >> 6);
return shrd128(p[-1], p[0], f->exponent & 63) & BKEY_MANTISSA_MASK;
}
static void make_bfloat(struct bset_tree *t, unsigned j)
{
struct bkey_float *f = &t->tree[j];
struct bkey *m = tree_to_bkey(t, j);
struct bkey *p = tree_to_prev_bkey(t, j);
struct bkey *l = is_power_of_2(j)
? t->data->start
: tree_to_prev_bkey(t, j >> ffs(j));
struct bkey *r = is_power_of_2(j + 1)
? bset_bkey_idx(t->data, t->data->keys - bkey_u64s(&t->end))
: tree_to_bkey(t, j >> (ffz(j) + 1));
BUG_ON(m < l || m > r);
BUG_ON(bkey_next(p) != m);
if (KEY_INODE(l) != KEY_INODE(r))
f->exponent = fls64(KEY_INODE(r) ^ KEY_INODE(l)) + 64;
else
f->exponent = fls64(r->low ^ l->low);
f->exponent = max_t(int, f->exponent - BKEY_MANTISSA_BITS, 0);
/*
* Setting f->exponent = 127 flags this node as failed, and causes the
* lookup code to fall back to comparing against the original key.
*/
if (bfloat_mantissa(m, f) != bfloat_mantissa(p, f))
f->mantissa = bfloat_mantissa(m, f) - 1;
else
f->exponent = 127;
}
static void bset_alloc_tree(struct btree_keys *b, struct bset_tree *t)
{
if (t != b->set) {
unsigned j = roundup(t[-1].size,
64 / sizeof(struct bkey_float));
t->tree = t[-1].tree + j;
t->prev = t[-1].prev + j;
}
while (t < b->set + MAX_BSETS)
t++->size = 0;
}
static void bch_bset_build_unwritten_tree(struct btree_keys *b)
{
struct bset_tree *t = bset_tree_last(b);
BUG_ON(b->last_set_unwritten);
b->last_set_unwritten = 1;
bset_alloc_tree(b, t);
if (t->tree != b->set->tree + btree_keys_cachelines(b)) {
t->prev[0] = bkey_to_cacheline_offset(t, 0, t->data->start);
t->size = 1;
}
}
void bch_bset_init_next(struct btree_keys *b, struct bset *i, uint64_t magic)
{
if (i != b->set->data) {
b->set[++b->nsets].data = i;
i->seq = b->set->data->seq;
} else
get_random_bytes(&i->seq, sizeof(uint64_t));
i->magic = magic;
i->version = 0;
i->keys = 0;
bch_bset_build_unwritten_tree(b);
}
EXPORT_SYMBOL(bch_bset_init_next);
void bch_bset_build_written_tree(struct btree_keys *b)
{
struct bset_tree *t = bset_tree_last(b);
struct bkey *prev = NULL, *k = t->data->start;
unsigned j, cacheline = 1;
b->last_set_unwritten = 0;
bset_alloc_tree(b, t);
t->size = min_t(unsigned,
bkey_to_cacheline(t, bset_bkey_last(t->data)),
b->set->tree + btree_keys_cachelines(b) - t->tree);
if (t->size < 2) {
t->size = 0;
return;
}
t->extra = (t->size - rounddown_pow_of_two(t->size - 1)) << 1;
/* First we figure out where the first key in each cacheline is */
for (j = inorder_next(0, t->size);
j;
j = inorder_next(j, t->size)) {
while (bkey_to_cacheline(t, k) < cacheline)
prev = k, k = bkey_next(k);
t->prev[j] = bkey_u64s(prev);
t->tree[j].m = bkey_to_cacheline_offset(t, cacheline++, k);
}
while (bkey_next(k) != bset_bkey_last(t->data))
k = bkey_next(k);
t->end = *k;
/* Then we build the tree */
for (j = inorder_next(0, t->size);
j;
j = inorder_next(j, t->size))
make_bfloat(t, j);
}
EXPORT_SYMBOL(bch_bset_build_written_tree);
/* Insert */
void bch_bset_fix_invalidated_key(struct btree_keys *b, struct bkey *k)
{
struct bset_tree *t;
unsigned inorder, j = 1;
for (t = b->set; t <= bset_tree_last(b); t++)
if (k < bset_bkey_last(t->data))
goto found_set;
BUG();
found_set:
if (!t->size || !bset_written(b, t))
return;
inorder = bkey_to_cacheline(t, k);
if (k == t->data->start)
goto fix_left;
if (bkey_next(k) == bset_bkey_last(t->data)) {
t->end = *k;
goto fix_right;
}
j = inorder_to_tree(inorder, t);
if (j &&
j < t->size &&
k == tree_to_bkey(t, j))
fix_left: do {
make_bfloat(t, j);
j = j * 2;
} while (j < t->size);
j = inorder_to_tree(inorder + 1, t);
if (j &&
j < t->size &&
k == tree_to_prev_bkey(t, j))
fix_right: do {
make_bfloat(t, j);
j = j * 2 + 1;
} while (j < t->size);
}
EXPORT_SYMBOL(bch_bset_fix_invalidated_key);
static void bch_bset_fix_lookup_table(struct btree_keys *b,
struct bset_tree *t,
struct bkey *k)
{
unsigned shift = bkey_u64s(k);
unsigned j = bkey_to_cacheline(t, k);
/* We're getting called from btree_split() or btree_gc, just bail out */
if (!t->size)
return;
/* k is the key we just inserted; we need to find the entry in the
* lookup table for the first key that is strictly greater than k:
* it's either k's cacheline or the next one
*/
while (j < t->size &&
table_to_bkey(t, j) <= k)
j++;
/* Adjust all the lookup table entries, and find a new key for any that
* have gotten too big
*/
for (; j < t->size; j++) {
t->prev[j] += shift;
if (t->prev[j] > 7) {
k = table_to_bkey(t, j - 1);
while (k < cacheline_to_bkey(t, j, 0))
k = bkey_next(k);
t->prev[j] = bkey_to_cacheline_offset(t, j, k);
}
}
if (t->size == b->set->tree + btree_keys_cachelines(b) - t->tree)
return;
/* Possibly add a new entry to the end of the lookup table */
for (k = table_to_bkey(t, t->size - 1);
k != bset_bkey_last(t->data);
k = bkey_next(k))
if (t->size == bkey_to_cacheline(t, k)) {
t->prev[t->size] = bkey_to_cacheline_offset(t, t->size, k);
t->size++;
}
}
/*
* Tries to merge l and r: l should be lower than r
* Returns true if we were able to merge. If we did merge, l will be the merged
* key, r will be untouched.
*/
bool bch_bkey_try_merge(struct btree_keys *b, struct bkey *l, struct bkey *r)
{
if (!b->ops->key_merge)
return false;
/*
* Generic header checks
* Assumes left and right are in order
* Left and right must be exactly aligned
*/
if (!bch_bkey_equal_header(l, r) ||
bkey_cmp(l, &START_KEY(r)))
return false;
return b->ops->key_merge(b, l, r);
}
EXPORT_SYMBOL(bch_bkey_try_merge);
void bch_bset_insert(struct btree_keys *b, struct bkey *where,
struct bkey *insert)
{
struct bset_tree *t = bset_tree_last(b);
BUG_ON(!b->last_set_unwritten);
BUG_ON(bset_byte_offset(b, t->data) +
__set_bytes(t->data, t->data->keys + bkey_u64s(insert)) >
PAGE_SIZE << b->page_order);
memmove((uint64_t *) where + bkey_u64s(insert),
where,
(void *) bset_bkey_last(t->data) - (void *) where);
t->data->keys += bkey_u64s(insert);
bkey_copy(where, insert);
bch_bset_fix_lookup_table(b, t, where);
}
EXPORT_SYMBOL(bch_bset_insert);
unsigned bch_btree_insert_key(struct btree_keys *b, struct bkey *k,
struct bkey *replace_key)
{
unsigned status = BTREE_INSERT_STATUS_NO_INSERT;
struct bset *i = bset_tree_last(b)->data;
struct bkey *m, *prev = NULL;
struct btree_iter iter;
BUG_ON(b->ops->is_extents && !KEY_SIZE(k));
m = bch_btree_iter_init(b, &iter, b->ops->is_extents
? PRECEDING_KEY(&START_KEY(k))
: PRECEDING_KEY(k));
if (b->ops->insert_fixup(b, k, &iter, replace_key))
return status;
status = BTREE_INSERT_STATUS_INSERT;
while (m != bset_bkey_last(i) &&
bkey_cmp(k, b->ops->is_extents ? &START_KEY(m) : m) > 0)
prev = m, m = bkey_next(m);
/* prev is in the tree, if we merge we're done */
status = BTREE_INSERT_STATUS_BACK_MERGE;
if (prev &&
bch_bkey_try_merge(b, prev, k))
goto merged;
#if 0
status = BTREE_INSERT_STATUS_OVERWROTE;
if (m != bset_bkey_last(i) &&
KEY_PTRS(m) == KEY_PTRS(k) && !KEY_SIZE(m))
goto copy;
#endif
status = BTREE_INSERT_STATUS_FRONT_MERGE;
if (m != bset_bkey_last(i) &&
bch_bkey_try_merge(b, k, m))
goto copy;
bch_bset_insert(b, m, k);
copy: bkey_copy(m, k);
merged:
return status;
}
EXPORT_SYMBOL(bch_btree_insert_key);
/* Lookup */
struct bset_search_iter {
struct bkey *l, *r;
};
static struct bset_search_iter bset_search_write_set(struct bset_tree *t,
const struct bkey *search)
{
unsigned li = 0, ri = t->size;
while (li + 1 != ri) {
unsigned m = (li + ri) >> 1;
if (bkey_cmp(table_to_bkey(t, m), search) > 0)
ri = m;
else
li = m;
}
return (struct bset_search_iter) {
table_to_bkey(t, li),
ri < t->size ? table_to_bkey(t, ri) : bset_bkey_last(t->data)
};
}
static struct bset_search_iter bset_search_tree(struct bset_tree *t,
const struct bkey *search)
{
struct bkey *l, *r;
struct bkey_float *f;
unsigned inorder, j, n = 1;
do {
unsigned p = n << 4;
p &= ((int) (p - t->size)) >> 31;
prefetch(&t->tree[p]);
j = n;
f = &t->tree[j];
/*
* n = (f->mantissa > bfloat_mantissa())
* ? j * 2
* : j * 2 + 1;
*
* We need to subtract 1 from f->mantissa for the sign bit trick
* to work - that's done in make_bfloat()
*/
if (likely(f->exponent != 127))
n = j * 2 + (((unsigned)
(f->mantissa -
bfloat_mantissa(search, f))) >> 31);
else
n = (bkey_cmp(tree_to_bkey(t, j), search) > 0)
? j * 2
: j * 2 + 1;
} while (n < t->size);
inorder = to_inorder(j, t);
/*
* n would have been the node we recursed to - the low bit tells us if
* we recursed left or recursed right.
*/
if (n & 1) {
l = cacheline_to_bkey(t, inorder, f->m);
if (++inorder != t->size) {
f = &t->tree[inorder_next(j, t->size)];
r = cacheline_to_bkey(t, inorder, f->m);
} else
r = bset_bkey_last(t->data);
} else {
r = cacheline_to_bkey(t, inorder, f->m);
if (--inorder) {
f = &t->tree[inorder_prev(j, t->size)];
l = cacheline_to_bkey(t, inorder, f->m);
} else
l = t->data->start;
}
return (struct bset_search_iter) {l, r};
}
struct bkey *__bch_bset_search(struct btree_keys *b, struct bset_tree *t,
const struct bkey *search)
{
struct bset_search_iter i;
/*
* First, we search for a cacheline, then lastly we do a linear search
* within that cacheline.
*
* To search for the cacheline, there's three different possibilities:
* * The set is too small to have a search tree, so we just do a linear
* search over the whole set.
* * The set is the one we're currently inserting into; keeping a full
* auxiliary search tree up to date would be too expensive, so we
* use a much simpler lookup table to do a binary search -
* bset_search_write_set().
* * Or we use the auxiliary search tree we constructed earlier -
* bset_search_tree()
*/
if (unlikely(!t->size)) {
i.l = t->data->start;
i.r = bset_bkey_last(t->data);
} else if (bset_written(b, t)) {
/*
* Each node in the auxiliary search tree covers a certain range
* of bits, and keys above and below the set it covers might
* differ outside those bits - so we have to special case the
* start and end - handle that here:
*/
if (unlikely(bkey_cmp(search, &t->end) >= 0))
return bset_bkey_last(t->data);
if (unlikely(bkey_cmp(search, t->data->start) < 0))
return t->data->start;
i = bset_search_tree(t, search);
} else {
BUG_ON(!b->nsets &&
t->size < bkey_to_cacheline(t, bset_bkey_last(t->data)));
i = bset_search_write_set(t, search);
}
if (btree_keys_expensive_checks(b)) {
BUG_ON(bset_written(b, t) &&
i.l != t->data->start &&
bkey_cmp(tree_to_prev_bkey(t,
inorder_to_tree(bkey_to_cacheline(t, i.l), t)),
search) > 0);
BUG_ON(i.r != bset_bkey_last(t->data) &&
bkey_cmp(i.r, search) <= 0);
}
while (likely(i.l != i.r) &&
bkey_cmp(i.l, search) <= 0)
i.l = bkey_next(i.l);
return i.l;
}
EXPORT_SYMBOL(__bch_bset_search);
/* Btree iterator */
typedef bool (btree_iter_cmp_fn)(struct btree_iter_set,
struct btree_iter_set);
static inline bool btree_iter_cmp(struct btree_iter_set l,
struct btree_iter_set r)
{
return bkey_cmp(l.k, r.k) > 0;
}
static inline bool btree_iter_end(struct btree_iter *iter)
{
return !iter->used;
}
void bch_btree_iter_push(struct btree_iter *iter, struct bkey *k,
struct bkey *end)
{
if (k != end)
BUG_ON(!heap_add(iter,
((struct btree_iter_set) { k, end }),
btree_iter_cmp));
}
static struct bkey *__bch_btree_iter_init(struct btree_keys *b,
struct btree_iter *iter,
struct bkey *search,
struct bset_tree *start)
{
struct bkey *ret = NULL;
iter->size = ARRAY_SIZE(iter->data);
iter->used = 0;
#ifdef CONFIG_BCACHE_DEBUG
iter->b = b;
#endif
for (; start <= bset_tree_last(b); start++) {
ret = bch_bset_search(b, start, search);
bch_btree_iter_push(iter, ret, bset_bkey_last(start->data));
}
return ret;
}
struct bkey *bch_btree_iter_init(struct btree_keys *b,
struct btree_iter *iter,
struct bkey *search)
{
return __bch_btree_iter_init(b, iter, search, b->set);
}
EXPORT_SYMBOL(bch_btree_iter_init);
static inline struct bkey *__bch_btree_iter_next(struct btree_iter *iter,
btree_iter_cmp_fn *cmp)
{
struct btree_iter_set unused;
struct bkey *ret = NULL;
if (!btree_iter_end(iter)) {
bch_btree_iter_next_check(iter);
ret = iter->data->k;
iter->data->k = bkey_next(iter->data->k);
if (iter->data->k > iter->data->end) {
WARN_ONCE(1, "bset was corrupt!\n");
iter->data->k = iter->data->end;
}
if (iter->data->k == iter->data->end)
heap_pop(iter, unused, cmp);
else
heap_sift(iter, 0, cmp);
}
return ret;
}
struct bkey *bch_btree_iter_next(struct btree_iter *iter)
{
return __bch_btree_iter_next(iter, btree_iter_cmp);
}
EXPORT_SYMBOL(bch_btree_iter_next);
struct bkey *bch_btree_iter_next_filter(struct btree_iter *iter,
struct btree_keys *b, ptr_filter_fn fn)
{
struct bkey *ret;
do {
ret = bch_btree_iter_next(iter);
} while (ret && fn(b, ret));
return ret;
}
/* Mergesort */
void bch_bset_sort_state_free(struct bset_sort_state *state)
{
if (state->pool)
mempool_destroy(state->pool);
}
int bch_bset_sort_state_init(struct bset_sort_state *state, unsigned page_order)
{
spin_lock_init(&state->time.lock);
state->page_order = page_order;
state->crit_factor = int_sqrt(1 << page_order);
state->pool = mempool_create_page_pool(1, page_order);
if (!state->pool)
return -ENOMEM;
return 0;
}
EXPORT_SYMBOL(bch_bset_sort_state_init);
static void btree_mergesort(struct btree_keys *b, struct bset *out,
struct btree_iter *iter,
bool fixup, bool remove_stale)
{
int i;
struct bkey *k, *last = NULL;
BKEY_PADDED(k) tmp;
bool (*bad)(struct btree_keys *, const struct bkey *) = remove_stale
? bch_ptr_bad
: bch_ptr_invalid;
/* Heapify the iterator, using our comparison function */
for (i = iter->used / 2 - 1; i >= 0; --i)
heap_sift(iter, i, b->ops->sort_cmp);
while (!btree_iter_end(iter)) {
if (b->ops->sort_fixup && fixup)
k = b->ops->sort_fixup(iter, &tmp.k);
else
k = NULL;
if (!k)
k = __bch_btree_iter_next(iter, b->ops->sort_cmp);
if (bad(b, k))
continue;
if (!last) {
last = out->start;
bkey_copy(last, k);
} else if (!bch_bkey_try_merge(b, last, k)) {
last = bkey_next(last);
bkey_copy(last, k);
}
}
out->keys = last ? (uint64_t *) bkey_next(last) - out->d : 0;
pr_debug("sorted %i keys", out->keys);
}
static void __btree_sort(struct btree_keys *b, struct btree_iter *iter,
unsigned start, unsigned order, bool fixup,
struct bset_sort_state *state)
{
uint64_t start_time;
bool used_mempool = false;
struct bset *out = (void *) __get_free_pages(__GFP_NOWARN|GFP_NOWAIT,
order);
if (!out) {
struct page *outp;
BUG_ON(order > state->page_order);
outp = mempool_alloc(state->pool, GFP_NOIO);
out = page_address(outp);
used_mempool = true;
order = state->page_order;
}
start_time = local_clock();
btree_mergesort(b, out, iter, fixup, false);
b->nsets = start;
if (!start && order == b->page_order) {
/*
* Our temporary buffer is the same size as the btree node's
* buffer, we can just swap buffers instead of doing a big
* memcpy()
*/
out->magic = b->set->data->magic;
out->seq = b->set->data->seq;
out->version = b->set->data->version;
swap(out, b->set->data);
} else {
b->set[start].data->keys = out->keys;
memcpy(b->set[start].data->start, out->start,
(void *) bset_bkey_last(out) - (void *) out->start);
}
if (used_mempool)
mempool_free(virt_to_page(out), state->pool);
else
free_pages((unsigned long) out, order);
bch_bset_build_written_tree(b);
if (!start)
bch_time_stats_update(&state->time, start_time);
}
void bch_btree_sort_partial(struct btree_keys *b, unsigned start,
struct bset_sort_state *state)
{
size_t order = b->page_order, keys = 0;
struct btree_iter iter;
int oldsize = bch_count_data(b);
__bch_btree_iter_init(b, &iter, NULL, &b->set[start]);
if (start) {
unsigned i;
for (i = start; i <= b->nsets; i++)
keys += b->set[i].data->keys;
order = get_order(__set_bytes(b->set->data, keys));
}
__btree_sort(b, &iter, start, order, false, state);
EBUG_ON(oldsize >= 0 && bch_count_data(b) != oldsize);
}
EXPORT_SYMBOL(bch_btree_sort_partial);
void bch_btree_sort_and_fix_extents(struct btree_keys *b,
struct btree_iter *iter,
struct bset_sort_state *state)
{
__btree_sort(b, iter, 0, b->page_order, true, state);
}
void bch_btree_sort_into(struct btree_keys *b, struct btree_keys *new,
struct bset_sort_state *state)
{
uint64_t start_time = local_clock();
struct btree_iter iter;
bch_btree_iter_init(b, &iter, NULL);
btree_mergesort(b, new->set->data, &iter, false, true);
bch_time_stats_update(&state->time, start_time);
new->set->size = 0; // XXX: why?
}
#define SORT_CRIT (4096 / sizeof(uint64_t))
void bch_btree_sort_lazy(struct btree_keys *b, struct bset_sort_state *state)
{
unsigned crit = SORT_CRIT;
int i;
/* Don't sort if nothing to do */
if (!b->nsets)
goto out;
for (i = b->nsets - 1; i >= 0; --i) {
crit *= state->crit_factor;
if (b->set[i].data->keys < crit) {
bch_btree_sort_partial(b, i, state);
return;
}
}
/* Sort if we'd overflow */
if (b->nsets + 1 == MAX_BSETS) {
bch_btree_sort(b, state);
return;
}
out:
bch_bset_build_written_tree(b);
}
EXPORT_SYMBOL(bch_btree_sort_lazy);
void bch_btree_keys_stats(struct btree_keys *b, struct bset_stats *stats)
{
unsigned i;
for (i = 0; i <= b->nsets; i++) {
struct bset_tree *t = &b->set[i];
size_t bytes = t->data->keys * sizeof(uint64_t);
size_t j;
if (bset_written(b, t)) {
stats->sets_written++;
stats->bytes_written += bytes;
stats->floats += t->size - 1;
for (j = 1; j < t->size; j++)
if (t->tree[j].exponent == 127)
stats->failed++;
} else {
stats->sets_unwritten++;
stats->bytes_unwritten += bytes;
}
}
}
| null | null | null | null | 100,394 |
16,792 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 16,792 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2017 The Chromium 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 COMPONENTS_TRANSLATE_CORE_BROWSER_MOCK_TRANSLATE_CLIENT_H_
#define COMPONENTS_TRANSLATE_CORE_BROWSER_MOCK_TRANSLATE_CLIENT_H_
#include <memory>
#include <string>
#include "base/memory/ptr_util.h"
#include "components/infobars/core/infobar.h"
#include "components/translate/core/browser/translate_client.h"
#include "components/translate/core/browser/translate_driver.h"
#include "components/translate/core/browser/translate_prefs.h"
#include "components/translate/core/common/language_detection_details.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/metrics_proto/translate_event.pb.h"
namespace translate {
namespace testing {
extern const char* preferred_languages_prefs;
extern const char* accept_languages_prefs;
class MockTranslateClient : public TranslateClient {
public:
MockTranslateClient(TranslateDriver* driver, PrefService* prefs);
~MockTranslateClient() override;
TranslateDriver* GetTranslateDriver() override;
PrefService* GetPrefs() override;
std::unique_ptr<TranslatePrefs> GetTranslatePrefs() override;
MOCK_METHOD0(GetTranslateAcceptLanguages, TranslateAcceptLanguages*());
MOCK_CONST_METHOD0(GetInfobarIconID, int());
MOCK_METHOD1(RecordTranslateEvent, void(const metrics::TranslateEventProto&));
#if !defined(USE_AURA)
MOCK_CONST_METHOD1(CreateInfoBarMock,
infobars::InfoBar*(TranslateInfoBarDelegate*));
std::unique_ptr<infobars::InfoBar> CreateInfoBar(
std::unique_ptr<TranslateInfoBarDelegate> delegate) const {
return base::WrapUnique(CreateInfoBarMock(delegate.get()));
}
#endif
MOCK_CONST_METHOD1(RecordLanguageDetectionEvent,
void(const LanguageDetectionDetails&));
MOCK_METHOD5(ShowTranslateUI,
void(translate::TranslateStep,
const std::string&,
const std::string&,
TranslateErrors::Type,
bool));
MOCK_METHOD1(IsTranslatableURL, bool(const GURL&));
MOCK_METHOD1(ShowReportLanguageDetectionErrorUI, void(const GURL&));
private:
TranslateDriver* driver_;
PrefService* prefs_;
};
} // namespace testing
} // namespace translate
#endif // COMPONENTS_TRANSLATE_CORE_BROWSER_MOCK_TRANSLATE_CLIENT_H_
| null | null | null | null | 13,655 |
23,785 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 188,780 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | /*
* linux/drivers/video/fbmon.c
*
* Copyright (C) 2002 James Simmons <jsimmons@users.sf.net>
*
* Credits:
*
* The EDID Parser is a conglomeration from the following sources:
*
* 1. SciTech SNAP Graphics Architecture
* Copyright (C) 1991-2002 SciTech Software, Inc. All rights reserved.
*
* 2. XFree86 4.3.0, interpret_edid.c
* Copyright 1998 by Egbert Eich <Egbert.Eich@Physik.TU-Darmstadt.DE>
*
* 3. John Fremlin <vii@users.sourceforge.net> and
* Ani Joshi <ajoshi@unixbox.com>
*
* Generalized Timing Formula is derived from:
*
* GTF Spreadsheet by Andy Morrish (1/5/97)
* available at http://www.vesa.org
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive
* for more details.
*
*/
#include <linux/fb.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <video/edid.h>
#include <video/of_videomode.h>
#include <video/videomode.h>
#include "../edid.h"
/*
* EDID parser
*/
#undef DEBUG /* define this for verbose EDID parsing output */
#ifdef DEBUG
#define DPRINTK(fmt, args...) printk(fmt,## args)
#else
#define DPRINTK(fmt, args...)
#endif
#define FBMON_FIX_HEADER 1
#define FBMON_FIX_INPUT 2
#define FBMON_FIX_TIMINGS 3
#ifdef CONFIG_FB_MODE_HELPERS
struct broken_edid {
u8 manufacturer[4];
u32 model;
u32 fix;
};
static const struct broken_edid brokendb[] = {
/* DEC FR-PCXAV-YZ */
{
.manufacturer = "DEC",
.model = 0x073a,
.fix = FBMON_FIX_HEADER,
},
/* ViewSonic PF775a */
{
.manufacturer = "VSC",
.model = 0x5a44,
.fix = FBMON_FIX_INPUT,
},
/* Sharp UXGA? */
{
.manufacturer = "SHP",
.model = 0x138e,
.fix = FBMON_FIX_TIMINGS,
},
};
static const unsigned char edid_v1_header[] = { 0x00, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0x00
};
static void copy_string(unsigned char *c, unsigned char *s)
{
int i;
c = c + 5;
for (i = 0; (i < 13 && *c != 0x0A); i++)
*(s++) = *(c++);
*s = 0;
while (i-- && (*--s == 0x20)) *s = 0;
}
static int edid_is_serial_block(unsigned char *block)
{
if ((block[0] == 0x00) && (block[1] == 0x00) &&
(block[2] == 0x00) && (block[3] == 0xff) &&
(block[4] == 0x00))
return 1;
else
return 0;
}
static int edid_is_ascii_block(unsigned char *block)
{
if ((block[0] == 0x00) && (block[1] == 0x00) &&
(block[2] == 0x00) && (block[3] == 0xfe) &&
(block[4] == 0x00))
return 1;
else
return 0;
}
static int edid_is_limits_block(unsigned char *block)
{
if ((block[0] == 0x00) && (block[1] == 0x00) &&
(block[2] == 0x00) && (block[3] == 0xfd) &&
(block[4] == 0x00))
return 1;
else
return 0;
}
static int edid_is_monitor_block(unsigned char *block)
{
if ((block[0] == 0x00) && (block[1] == 0x00) &&
(block[2] == 0x00) && (block[3] == 0xfc) &&
(block[4] == 0x00))
return 1;
else
return 0;
}
static int edid_is_timing_block(unsigned char *block)
{
if ((block[0] != 0x00) || (block[1] != 0x00) ||
(block[2] != 0x00) || (block[4] != 0x00))
return 1;
else
return 0;
}
static int check_edid(unsigned char *edid)
{
unsigned char *block = edid + ID_MANUFACTURER_NAME, manufacturer[4];
unsigned char *b;
u32 model;
int i, fix = 0, ret = 0;
manufacturer[0] = ((block[0] & 0x7c) >> 2) + '@';
manufacturer[1] = ((block[0] & 0x03) << 3) +
((block[1] & 0xe0) >> 5) + '@';
manufacturer[2] = (block[1] & 0x1f) + '@';
manufacturer[3] = 0;
model = block[2] + (block[3] << 8);
for (i = 0; i < ARRAY_SIZE(brokendb); i++) {
if (!strncmp(manufacturer, brokendb[i].manufacturer, 4) &&
brokendb[i].model == model) {
fix = brokendb[i].fix;
break;
}
}
switch (fix) {
case FBMON_FIX_HEADER:
for (i = 0; i < 8; i++) {
if (edid[i] != edid_v1_header[i]) {
ret = fix;
break;
}
}
break;
case FBMON_FIX_INPUT:
b = edid + EDID_STRUCT_DISPLAY;
/* Only if display is GTF capable will
the input type be reset to analog */
if (b[4] & 0x01 && b[0] & 0x80)
ret = fix;
break;
case FBMON_FIX_TIMINGS:
b = edid + DETAILED_TIMING_DESCRIPTIONS_START;
ret = fix;
for (i = 0; i < 4; i++) {
if (edid_is_limits_block(b)) {
ret = 0;
break;
}
b += DETAILED_TIMING_DESCRIPTION_SIZE;
}
break;
}
if (ret)
printk("fbmon: The EDID Block of "
"Manufacturer: %s Model: 0x%x is known to "
"be broken,\n", manufacturer, model);
return ret;
}
static void fix_edid(unsigned char *edid, int fix)
{
int i;
unsigned char *b, csum = 0;
switch (fix) {
case FBMON_FIX_HEADER:
printk("fbmon: trying a header reconstruct\n");
memcpy(edid, edid_v1_header, 8);
break;
case FBMON_FIX_INPUT:
printk("fbmon: trying to fix input type\n");
b = edid + EDID_STRUCT_DISPLAY;
b[0] &= ~0x80;
edid[127] += 0x80;
break;
case FBMON_FIX_TIMINGS:
printk("fbmon: trying to fix monitor timings\n");
b = edid + DETAILED_TIMING_DESCRIPTIONS_START;
for (i = 0; i < 4; i++) {
if (!(edid_is_serial_block(b) ||
edid_is_ascii_block(b) ||
edid_is_monitor_block(b) ||
edid_is_timing_block(b))) {
b[0] = 0x00;
b[1] = 0x00;
b[2] = 0x00;
b[3] = 0xfd;
b[4] = 0x00;
b[5] = 60; /* vfmin */
b[6] = 60; /* vfmax */
b[7] = 30; /* hfmin */
b[8] = 75; /* hfmax */
b[9] = 17; /* pixclock - 170 MHz*/
b[10] = 0; /* GTF */
break;
}
b += DETAILED_TIMING_DESCRIPTION_SIZE;
}
for (i = 0; i < EDID_LENGTH - 1; i++)
csum += edid[i];
edid[127] = 256 - csum;
break;
}
}
static int edid_checksum(unsigned char *edid)
{
unsigned char csum = 0, all_null = 0;
int i, err = 0, fix = check_edid(edid);
if (fix)
fix_edid(edid, fix);
for (i = 0; i < EDID_LENGTH; i++) {
csum += edid[i];
all_null |= edid[i];
}
if (csum == 0x00 && all_null) {
/* checksum passed, everything's good */
err = 1;
}
return err;
}
static int edid_check_header(unsigned char *edid)
{
int i, err = 1, fix = check_edid(edid);
if (fix)
fix_edid(edid, fix);
for (i = 0; i < 8; i++) {
if (edid[i] != edid_v1_header[i])
err = 0;
}
return err;
}
static void parse_vendor_block(unsigned char *block, struct fb_monspecs *specs)
{
specs->manufacturer[0] = ((block[0] & 0x7c) >> 2) + '@';
specs->manufacturer[1] = ((block[0] & 0x03) << 3) +
((block[1] & 0xe0) >> 5) + '@';
specs->manufacturer[2] = (block[1] & 0x1f) + '@';
specs->manufacturer[3] = 0;
specs->model = block[2] + (block[3] << 8);
specs->serial = block[4] + (block[5] << 8) +
(block[6] << 16) + (block[7] << 24);
specs->year = block[9] + 1990;
specs->week = block[8];
DPRINTK(" Manufacturer: %s\n", specs->manufacturer);
DPRINTK(" Model: %x\n", specs->model);
DPRINTK(" Serial#: %u\n", specs->serial);
DPRINTK(" Year: %u Week %u\n", specs->year, specs->week);
}
static void get_dpms_capabilities(unsigned char flags,
struct fb_monspecs *specs)
{
specs->dpms = 0;
if (flags & DPMS_ACTIVE_OFF)
specs->dpms |= FB_DPMS_ACTIVE_OFF;
if (flags & DPMS_SUSPEND)
specs->dpms |= FB_DPMS_SUSPEND;
if (flags & DPMS_STANDBY)
specs->dpms |= FB_DPMS_STANDBY;
DPRINTK(" DPMS: Active %s, Suspend %s, Standby %s\n",
(flags & DPMS_ACTIVE_OFF) ? "yes" : "no",
(flags & DPMS_SUSPEND) ? "yes" : "no",
(flags & DPMS_STANDBY) ? "yes" : "no");
}
static void get_chroma(unsigned char *block, struct fb_monspecs *specs)
{
int tmp;
DPRINTK(" Chroma\n");
/* Chromaticity data */
tmp = ((block[5] & (3 << 6)) >> 6) | (block[0x7] << 2);
tmp *= 1000;
tmp += 512;
specs->chroma.redx = tmp/1024;
DPRINTK(" RedX: 0.%03d ", specs->chroma.redx);
tmp = ((block[5] & (3 << 4)) >> 4) | (block[0x8] << 2);
tmp *= 1000;
tmp += 512;
specs->chroma.redy = tmp/1024;
DPRINTK("RedY: 0.%03d\n", specs->chroma.redy);
tmp = ((block[5] & (3 << 2)) >> 2) | (block[0x9] << 2);
tmp *= 1000;
tmp += 512;
specs->chroma.greenx = tmp/1024;
DPRINTK(" GreenX: 0.%03d ", specs->chroma.greenx);
tmp = (block[5] & 3) | (block[0xa] << 2);
tmp *= 1000;
tmp += 512;
specs->chroma.greeny = tmp/1024;
DPRINTK("GreenY: 0.%03d\n", specs->chroma.greeny);
tmp = ((block[6] & (3 << 6)) >> 6) | (block[0xb] << 2);
tmp *= 1000;
tmp += 512;
specs->chroma.bluex = tmp/1024;
DPRINTK(" BlueX: 0.%03d ", specs->chroma.bluex);
tmp = ((block[6] & (3 << 4)) >> 4) | (block[0xc] << 2);
tmp *= 1000;
tmp += 512;
specs->chroma.bluey = tmp/1024;
DPRINTK("BlueY: 0.%03d\n", specs->chroma.bluey);
tmp = ((block[6] & (3 << 2)) >> 2) | (block[0xd] << 2);
tmp *= 1000;
tmp += 512;
specs->chroma.whitex = tmp/1024;
DPRINTK(" WhiteX: 0.%03d ", specs->chroma.whitex);
tmp = (block[6] & 3) | (block[0xe] << 2);
tmp *= 1000;
tmp += 512;
specs->chroma.whitey = tmp/1024;
DPRINTK("WhiteY: 0.%03d\n", specs->chroma.whitey);
}
static void calc_mode_timings(int xres, int yres, int refresh,
struct fb_videomode *mode)
{
struct fb_var_screeninfo *var;
var = kzalloc(sizeof(struct fb_var_screeninfo), GFP_KERNEL);
if (var) {
var->xres = xres;
var->yres = yres;
fb_get_mode(FB_VSYNCTIMINGS | FB_IGNOREMON,
refresh, var, NULL);
mode->xres = xres;
mode->yres = yres;
mode->pixclock = var->pixclock;
mode->refresh = refresh;
mode->left_margin = var->left_margin;
mode->right_margin = var->right_margin;
mode->upper_margin = var->upper_margin;
mode->lower_margin = var->lower_margin;
mode->hsync_len = var->hsync_len;
mode->vsync_len = var->vsync_len;
mode->vmode = 0;
mode->sync = 0;
kfree(var);
}
}
static int get_est_timing(unsigned char *block, struct fb_videomode *mode)
{
int num = 0;
unsigned char c;
c = block[0];
if (c&0x80) {
calc_mode_timings(720, 400, 70, &mode[num]);
mode[num++].flag = FB_MODE_IS_CALCULATED;
DPRINTK(" 720x400@70Hz\n");
}
if (c&0x40) {
calc_mode_timings(720, 400, 88, &mode[num]);
mode[num++].flag = FB_MODE_IS_CALCULATED;
DPRINTK(" 720x400@88Hz\n");
}
if (c&0x20) {
mode[num++] = vesa_modes[3];
DPRINTK(" 640x480@60Hz\n");
}
if (c&0x10) {
calc_mode_timings(640, 480, 67, &mode[num]);
mode[num++].flag = FB_MODE_IS_CALCULATED;
DPRINTK(" 640x480@67Hz\n");
}
if (c&0x08) {
mode[num++] = vesa_modes[4];
DPRINTK(" 640x480@72Hz\n");
}
if (c&0x04) {
mode[num++] = vesa_modes[5];
DPRINTK(" 640x480@75Hz\n");
}
if (c&0x02) {
mode[num++] = vesa_modes[7];
DPRINTK(" 800x600@56Hz\n");
}
if (c&0x01) {
mode[num++] = vesa_modes[8];
DPRINTK(" 800x600@60Hz\n");
}
c = block[1];
if (c&0x80) {
mode[num++] = vesa_modes[9];
DPRINTK(" 800x600@72Hz\n");
}
if (c&0x40) {
mode[num++] = vesa_modes[10];
DPRINTK(" 800x600@75Hz\n");
}
if (c&0x20) {
calc_mode_timings(832, 624, 75, &mode[num]);
mode[num++].flag = FB_MODE_IS_CALCULATED;
DPRINTK(" 832x624@75Hz\n");
}
if (c&0x10) {
mode[num++] = vesa_modes[12];
DPRINTK(" 1024x768@87Hz Interlaced\n");
}
if (c&0x08) {
mode[num++] = vesa_modes[13];
DPRINTK(" 1024x768@60Hz\n");
}
if (c&0x04) {
mode[num++] = vesa_modes[14];
DPRINTK(" 1024x768@70Hz\n");
}
if (c&0x02) {
mode[num++] = vesa_modes[15];
DPRINTK(" 1024x768@75Hz\n");
}
if (c&0x01) {
mode[num++] = vesa_modes[21];
DPRINTK(" 1280x1024@75Hz\n");
}
c = block[2];
if (c&0x80) {
mode[num++] = vesa_modes[17];
DPRINTK(" 1152x870@75Hz\n");
}
DPRINTK(" Manufacturer's mask: %x\n",c&0x7F);
return num;
}
static int get_std_timing(unsigned char *block, struct fb_videomode *mode,
int ver, int rev, const struct fb_monspecs *specs)
{
int i;
for (i = 0; i < DMT_SIZE; i++) {
u32 std_2byte_code = block[0] << 8 | block[1];
if (std_2byte_code == dmt_modes[i].std_2byte_code)
break;
}
if (i < DMT_SIZE && dmt_modes[i].mode) {
/* DMT mode found */
*mode = *dmt_modes[i].mode;
mode->flag |= FB_MODE_IS_STANDARD;
DPRINTK(" DMT id=%d\n", dmt_modes[i].dmt_id);
} else {
int xres, yres = 0, refresh, ratio;
xres = (block[0] + 31) * 8;
if (xres <= 256)
return 0;
ratio = (block[1] & 0xc0) >> 6;
switch (ratio) {
case 0:
/* in EDID 1.3 the meaning of 0 changed to 16:10 (prior 1:1) */
if (ver < 1 || (ver == 1 && rev < 3))
yres = xres;
else
yres = (xres * 10)/16;
break;
case 1:
yres = (xres * 3)/4;
break;
case 2:
yres = (xres * 4)/5;
break;
case 3:
yres = (xres * 9)/16;
break;
}
refresh = (block[1] & 0x3f) + 60;
DPRINTK(" %dx%d@%dHz\n", xres, yres, refresh);
calc_mode_timings(xres, yres, refresh, mode);
}
/* Check the mode we got is within valid spec of the monitor */
if (specs && specs->dclkmax
&& PICOS2KHZ(mode->pixclock) * 1000 > specs->dclkmax) {
DPRINTK(" mode exceed max DCLK\n");
return 0;
}
return 1;
}
static int get_dst_timing(unsigned char *block, struct fb_videomode *mode,
int ver, int rev, const struct fb_monspecs *specs)
{
int j, num = 0;
for (j = 0; j < 6; j++, block += STD_TIMING_DESCRIPTION_SIZE)
num += get_std_timing(block, &mode[num], ver, rev, specs);
return num;
}
static void get_detailed_timing(unsigned char *block,
struct fb_videomode *mode)
{
mode->xres = H_ACTIVE;
mode->yres = V_ACTIVE;
mode->pixclock = PIXEL_CLOCK;
mode->pixclock /= 1000;
mode->pixclock = KHZ2PICOS(mode->pixclock);
mode->right_margin = H_SYNC_OFFSET;
mode->left_margin = (H_ACTIVE + H_BLANKING) -
(H_ACTIVE + H_SYNC_OFFSET + H_SYNC_WIDTH);
mode->upper_margin = V_BLANKING - V_SYNC_OFFSET -
V_SYNC_WIDTH;
mode->lower_margin = V_SYNC_OFFSET;
mode->hsync_len = H_SYNC_WIDTH;
mode->vsync_len = V_SYNC_WIDTH;
if (HSYNC_POSITIVE)
mode->sync |= FB_SYNC_HOR_HIGH_ACT;
if (VSYNC_POSITIVE)
mode->sync |= FB_SYNC_VERT_HIGH_ACT;
mode->refresh = PIXEL_CLOCK/((H_ACTIVE + H_BLANKING) *
(V_ACTIVE + V_BLANKING));
if (INTERLACED) {
mode->yres *= 2;
mode->upper_margin *= 2;
mode->lower_margin *= 2;
mode->vsync_len *= 2;
mode->vmode |= FB_VMODE_INTERLACED;
}
mode->flag = FB_MODE_IS_DETAILED;
DPRINTK(" %d MHz ", PIXEL_CLOCK/1000000);
DPRINTK("%d %d %d %d ", H_ACTIVE, H_ACTIVE + H_SYNC_OFFSET,
H_ACTIVE + H_SYNC_OFFSET + H_SYNC_WIDTH, H_ACTIVE + H_BLANKING);
DPRINTK("%d %d %d %d ", V_ACTIVE, V_ACTIVE + V_SYNC_OFFSET,
V_ACTIVE + V_SYNC_OFFSET + V_SYNC_WIDTH, V_ACTIVE + V_BLANKING);
DPRINTK("%sHSync %sVSync\n\n", (HSYNC_POSITIVE) ? "+" : "-",
(VSYNC_POSITIVE) ? "+" : "-");
}
/**
* fb_create_modedb - create video mode database
* @edid: EDID data
* @dbsize: database size
*
* RETURNS: struct fb_videomode, @dbsize contains length of database
*
* DESCRIPTION:
* This function builds a mode database using the contents of the EDID
* data
*/
static struct fb_videomode *fb_create_modedb(unsigned char *edid, int *dbsize,
const struct fb_monspecs *specs)
{
struct fb_videomode *mode, *m;
unsigned char *block;
int num = 0, i, first = 1;
int ver, rev;
mode = kzalloc(50 * sizeof(struct fb_videomode), GFP_KERNEL);
if (mode == NULL)
return NULL;
if (edid == NULL || !edid_checksum(edid) ||
!edid_check_header(edid)) {
kfree(mode);
return NULL;
}
ver = edid[EDID_STRUCT_VERSION];
rev = edid[EDID_STRUCT_REVISION];
*dbsize = 0;
DPRINTK(" Detailed Timings\n");
block = edid + DETAILED_TIMING_DESCRIPTIONS_START;
for (i = 0; i < 4; i++, block+= DETAILED_TIMING_DESCRIPTION_SIZE) {
if (!(block[0] == 0x00 && block[1] == 0x00)) {
get_detailed_timing(block, &mode[num]);
if (first) {
mode[num].flag |= FB_MODE_IS_FIRST;
first = 0;
}
num++;
}
}
DPRINTK(" Supported VESA Modes\n");
block = edid + ESTABLISHED_TIMING_1;
num += get_est_timing(block, &mode[num]);
DPRINTK(" Standard Timings\n");
block = edid + STD_TIMING_DESCRIPTIONS_START;
for (i = 0; i < STD_TIMING; i++, block += STD_TIMING_DESCRIPTION_SIZE)
num += get_std_timing(block, &mode[num], ver, rev, specs);
block = edid + DETAILED_TIMING_DESCRIPTIONS_START;
for (i = 0; i < 4; i++, block+= DETAILED_TIMING_DESCRIPTION_SIZE) {
if (block[0] == 0x00 && block[1] == 0x00 && block[3] == 0xfa)
num += get_dst_timing(block + 5, &mode[num],
ver, rev, specs);
}
/* Yikes, EDID data is totally useless */
if (!num) {
kfree(mode);
return NULL;
}
*dbsize = num;
m = kmalloc(num * sizeof(struct fb_videomode), GFP_KERNEL);
if (!m)
return mode;
memmove(m, mode, num * sizeof(struct fb_videomode));
kfree(mode);
return m;
}
/**
* fb_destroy_modedb - destroys mode database
* @modedb: mode database to destroy
*
* DESCRIPTION:
* Destroy mode database created by fb_create_modedb
*/
void fb_destroy_modedb(struct fb_videomode *modedb)
{
kfree(modedb);
}
static int fb_get_monitor_limits(unsigned char *edid, struct fb_monspecs *specs)
{
int i, retval = 1;
unsigned char *block;
block = edid + DETAILED_TIMING_DESCRIPTIONS_START;
DPRINTK(" Monitor Operating Limits: ");
for (i = 0; i < 4; i++, block += DETAILED_TIMING_DESCRIPTION_SIZE) {
if (edid_is_limits_block(block)) {
specs->hfmin = H_MIN_RATE * 1000;
specs->hfmax = H_MAX_RATE * 1000;
specs->vfmin = V_MIN_RATE;
specs->vfmax = V_MAX_RATE;
specs->dclkmax = MAX_PIXEL_CLOCK * 1000000;
specs->gtf = (GTF_SUPPORT) ? 1 : 0;
retval = 0;
DPRINTK("From EDID\n");
break;
}
}
/* estimate monitor limits based on modes supported */
if (retval) {
struct fb_videomode *modes, *mode;
int num_modes, hz, hscan, pixclock;
int vtotal, htotal;
modes = fb_create_modedb(edid, &num_modes, specs);
if (!modes) {
DPRINTK("None Available\n");
return 1;
}
retval = 0;
for (i = 0; i < num_modes; i++) {
mode = &modes[i];
pixclock = PICOS2KHZ(modes[i].pixclock) * 1000;
htotal = mode->xres + mode->right_margin + mode->hsync_len
+ mode->left_margin;
vtotal = mode->yres + mode->lower_margin + mode->vsync_len
+ mode->upper_margin;
if (mode->vmode & FB_VMODE_INTERLACED)
vtotal /= 2;
if (mode->vmode & FB_VMODE_DOUBLE)
vtotal *= 2;
hscan = (pixclock + htotal / 2) / htotal;
hscan = (hscan + 500) / 1000 * 1000;
hz = (hscan + vtotal / 2) / vtotal;
if (specs->dclkmax == 0 || specs->dclkmax < pixclock)
specs->dclkmax = pixclock;
if (specs->dclkmin == 0 || specs->dclkmin > pixclock)
specs->dclkmin = pixclock;
if (specs->hfmax == 0 || specs->hfmax < hscan)
specs->hfmax = hscan;
if (specs->hfmin == 0 || specs->hfmin > hscan)
specs->hfmin = hscan;
if (specs->vfmax == 0 || specs->vfmax < hz)
specs->vfmax = hz;
if (specs->vfmin == 0 || specs->vfmin > hz)
specs->vfmin = hz;
}
DPRINTK("Extrapolated\n");
fb_destroy_modedb(modes);
}
DPRINTK(" H: %d-%dKHz V: %d-%dHz DCLK: %dMHz\n",
specs->hfmin/1000, specs->hfmax/1000, specs->vfmin,
specs->vfmax, specs->dclkmax/1000000);
return retval;
}
static void get_monspecs(unsigned char *edid, struct fb_monspecs *specs)
{
unsigned char c, *block;
block = edid + EDID_STRUCT_DISPLAY;
fb_get_monitor_limits(edid, specs);
c = block[0] & 0x80;
specs->input = 0;
if (c) {
specs->input |= FB_DISP_DDI;
DPRINTK(" Digital Display Input");
} else {
DPRINTK(" Analog Display Input: Input Voltage - ");
switch ((block[0] & 0x60) >> 5) {
case 0:
DPRINTK("0.700V/0.300V");
specs->input |= FB_DISP_ANA_700_300;
break;
case 1:
DPRINTK("0.714V/0.286V");
specs->input |= FB_DISP_ANA_714_286;
break;
case 2:
DPRINTK("1.000V/0.400V");
specs->input |= FB_DISP_ANA_1000_400;
break;
case 3:
DPRINTK("0.700V/0.000V");
specs->input |= FB_DISP_ANA_700_000;
break;
}
}
DPRINTK("\n Sync: ");
c = block[0] & 0x10;
if (c)
DPRINTK(" Configurable signal level\n");
c = block[0] & 0x0f;
specs->signal = 0;
if (c & 0x10) {
DPRINTK("Blank to Blank ");
specs->signal |= FB_SIGNAL_BLANK_BLANK;
}
if (c & 0x08) {
DPRINTK("Separate ");
specs->signal |= FB_SIGNAL_SEPARATE;
}
if (c & 0x04) {
DPRINTK("Composite ");
specs->signal |= FB_SIGNAL_COMPOSITE;
}
if (c & 0x02) {
DPRINTK("Sync on Green ");
specs->signal |= FB_SIGNAL_SYNC_ON_GREEN;
}
if (c & 0x01) {
DPRINTK("Serration on ");
specs->signal |= FB_SIGNAL_SERRATION_ON;
}
DPRINTK("\n");
specs->max_x = block[1];
specs->max_y = block[2];
DPRINTK(" Max H-size in cm: ");
if (specs->max_x)
DPRINTK("%d\n", specs->max_x);
else
DPRINTK("variable\n");
DPRINTK(" Max V-size in cm: ");
if (specs->max_y)
DPRINTK("%d\n", specs->max_y);
else
DPRINTK("variable\n");
c = block[3];
specs->gamma = c+100;
DPRINTK(" Gamma: ");
DPRINTK("%d.%d\n", specs->gamma/100, specs->gamma % 100);
get_dpms_capabilities(block[4], specs);
switch ((block[4] & 0x18) >> 3) {
case 0:
DPRINTK(" Monochrome/Grayscale\n");
specs->input |= FB_DISP_MONO;
break;
case 1:
DPRINTK(" RGB Color Display\n");
specs->input |= FB_DISP_RGB;
break;
case 2:
DPRINTK(" Non-RGB Multicolor Display\n");
specs->input |= FB_DISP_MULTI;
break;
default:
DPRINTK(" Unknown\n");
specs->input |= FB_DISP_UNKNOWN;
break;
}
get_chroma(block, specs);
specs->misc = 0;
c = block[4] & 0x7;
if (c & 0x04) {
DPRINTK(" Default color format is primary\n");
specs->misc |= FB_MISC_PRIM_COLOR;
}
if (c & 0x02) {
DPRINTK(" First DETAILED Timing is preferred\n");
specs->misc |= FB_MISC_1ST_DETAIL;
}
if (c & 0x01) {
printk(" Display is GTF capable\n");
specs->gtf = 1;
}
}
int fb_parse_edid(unsigned char *edid, struct fb_var_screeninfo *var)
{
int i;
unsigned char *block;
if (edid == NULL || var == NULL)
return 1;
if (!(edid_checksum(edid)))
return 1;
if (!(edid_check_header(edid)))
return 1;
block = edid + DETAILED_TIMING_DESCRIPTIONS_START;
for (i = 0; i < 4; i++, block += DETAILED_TIMING_DESCRIPTION_SIZE) {
if (edid_is_timing_block(block)) {
var->xres = var->xres_virtual = H_ACTIVE;
var->yres = var->yres_virtual = V_ACTIVE;
var->height = var->width = 0;
var->right_margin = H_SYNC_OFFSET;
var->left_margin = (H_ACTIVE + H_BLANKING) -
(H_ACTIVE + H_SYNC_OFFSET + H_SYNC_WIDTH);
var->upper_margin = V_BLANKING - V_SYNC_OFFSET -
V_SYNC_WIDTH;
var->lower_margin = V_SYNC_OFFSET;
var->hsync_len = H_SYNC_WIDTH;
var->vsync_len = V_SYNC_WIDTH;
var->pixclock = PIXEL_CLOCK;
var->pixclock /= 1000;
var->pixclock = KHZ2PICOS(var->pixclock);
if (HSYNC_POSITIVE)
var->sync |= FB_SYNC_HOR_HIGH_ACT;
if (VSYNC_POSITIVE)
var->sync |= FB_SYNC_VERT_HIGH_ACT;
return 0;
}
}
return 1;
}
void fb_edid_to_monspecs(unsigned char *edid, struct fb_monspecs *specs)
{
unsigned char *block;
int i, found = 0;
if (edid == NULL)
return;
if (!(edid_checksum(edid)))
return;
if (!(edid_check_header(edid)))
return;
memset(specs, 0, sizeof(struct fb_monspecs));
specs->version = edid[EDID_STRUCT_VERSION];
specs->revision = edid[EDID_STRUCT_REVISION];
DPRINTK("========================================\n");
DPRINTK("Display Information (EDID)\n");
DPRINTK("========================================\n");
DPRINTK(" EDID Version %d.%d\n", (int) specs->version,
(int) specs->revision);
parse_vendor_block(edid + ID_MANUFACTURER_NAME, specs);
block = edid + DETAILED_TIMING_DESCRIPTIONS_START;
for (i = 0; i < 4; i++, block += DETAILED_TIMING_DESCRIPTION_SIZE) {
if (edid_is_serial_block(block)) {
copy_string(block, specs->serial_no);
DPRINTK(" Serial Number: %s\n", specs->serial_no);
} else if (edid_is_ascii_block(block)) {
copy_string(block, specs->ascii);
DPRINTK(" ASCII Block: %s\n", specs->ascii);
} else if (edid_is_monitor_block(block)) {
copy_string(block, specs->monitor);
DPRINTK(" Monitor Name: %s\n", specs->monitor);
}
}
DPRINTK(" Display Characteristics:\n");
get_monspecs(edid, specs);
specs->modedb = fb_create_modedb(edid, &specs->modedb_len, specs);
/*
* Workaround for buggy EDIDs that sets that the first
* detailed timing is preferred but has not detailed
* timing specified
*/
for (i = 0; i < specs->modedb_len; i++) {
if (specs->modedb[i].flag & FB_MODE_IS_DETAILED) {
found = 1;
break;
}
}
if (!found)
specs->misc &= ~FB_MISC_1ST_DETAIL;
DPRINTK("========================================\n");
}
/**
* fb_edid_add_monspecs() - add monitor video modes from E-EDID data
* @edid: 128 byte array with an E-EDID block
* @spacs: monitor specs to be extended
*/
void fb_edid_add_monspecs(unsigned char *edid, struct fb_monspecs *specs)
{
unsigned char *block;
struct fb_videomode *m;
int num = 0, i;
u8 svd[64], edt[(128 - 4) / DETAILED_TIMING_DESCRIPTION_SIZE];
u8 pos = 4, svd_n = 0;
if (!edid)
return;
if (!edid_checksum(edid))
return;
if (edid[0] != 0x2 ||
edid[2] < 4 || edid[2] > 128 - DETAILED_TIMING_DESCRIPTION_SIZE)
return;
DPRINTK(" Short Video Descriptors\n");
while (pos < edid[2]) {
u8 len = edid[pos] & 0x1f, type = (edid[pos] >> 5) & 7;
pr_debug("Data block %u of %u bytes\n", type, len);
if (type == 2) {
for (i = pos; i < pos + len; i++) {
u8 idx = edid[pos + i] & 0x7f;
svd[svd_n++] = idx;
pr_debug("N%sative mode #%d\n",
edid[pos + i] & 0x80 ? "" : "on-n", idx);
}
} else if (type == 3 && len >= 3) {
/* Check Vendor Specific Data Block. For HDMI,
it is always 00-0C-03 for HDMI Licensing, LLC. */
if (edid[pos + 1] == 3 && edid[pos + 2] == 0xc &&
edid[pos + 3] == 0)
specs->misc |= FB_MISC_HDMI;
}
pos += len + 1;
}
block = edid + edid[2];
DPRINTK(" Extended Detailed Timings\n");
for (i = 0; i < (128 - edid[2]) / DETAILED_TIMING_DESCRIPTION_SIZE;
i++, block += DETAILED_TIMING_DESCRIPTION_SIZE)
if (PIXEL_CLOCK)
edt[num++] = block - edid;
/* Yikes, EDID data is totally useless */
if (!(num + svd_n))
return;
m = kzalloc((specs->modedb_len + num + svd_n) *
sizeof(struct fb_videomode), GFP_KERNEL);
if (!m)
return;
memcpy(m, specs->modedb, specs->modedb_len * sizeof(struct fb_videomode));
for (i = specs->modedb_len; i < specs->modedb_len + num; i++) {
get_detailed_timing(edid + edt[i - specs->modedb_len], &m[i]);
if (i == specs->modedb_len)
m[i].flag |= FB_MODE_IS_FIRST;
pr_debug("Adding %ux%u@%u\n", m[i].xres, m[i].yres, m[i].refresh);
}
for (i = specs->modedb_len + num; i < specs->modedb_len + num + svd_n; i++) {
int idx = svd[i - specs->modedb_len - num];
if (!idx || idx >= ARRAY_SIZE(cea_modes)) {
pr_warning("Reserved SVD code %d\n", idx);
} else if (!cea_modes[idx].xres) {
pr_warning("Unimplemented SVD code %d\n", idx);
} else {
memcpy(&m[i], cea_modes + idx, sizeof(m[i]));
pr_debug("Adding SVD #%d: %ux%u@%u\n", idx,
m[i].xres, m[i].yres, m[i].refresh);
}
}
kfree(specs->modedb);
specs->modedb = m;
specs->modedb_len = specs->modedb_len + num + svd_n;
}
/*
* VESA Generalized Timing Formula (GTF)
*/
#define FLYBACK 550
#define V_FRONTPORCH 1
#define H_OFFSET 40
#define H_SCALEFACTOR 20
#define H_BLANKSCALE 128
#define H_GRADIENT 600
#define C_VAL 30
#define M_VAL 300
struct __fb_timings {
u32 dclk;
u32 hfreq;
u32 vfreq;
u32 hactive;
u32 vactive;
u32 hblank;
u32 vblank;
u32 htotal;
u32 vtotal;
};
/**
* fb_get_vblank - get vertical blank time
* @hfreq: horizontal freq
*
* DESCRIPTION:
* vblank = right_margin + vsync_len + left_margin
*
* given: right_margin = 1 (V_FRONTPORCH)
* vsync_len = 3
* flyback = 550
*
* flyback * hfreq
* left_margin = --------------- - vsync_len
* 1000000
*/
static u32 fb_get_vblank(u32 hfreq)
{
u32 vblank;
vblank = (hfreq * FLYBACK)/1000;
vblank = (vblank + 500)/1000;
return (vblank + V_FRONTPORCH);
}
/**
* fb_get_hblank_by_freq - get horizontal blank time given hfreq
* @hfreq: horizontal freq
* @xres: horizontal resolution in pixels
*
* DESCRIPTION:
*
* xres * duty_cycle
* hblank = ------------------
* 100 - duty_cycle
*
* duty cycle = percent of htotal assigned to inactive display
* duty cycle = C - (M/Hfreq)
*
* where: C = ((offset - scale factor) * blank_scale)
* -------------------------------------- + scale factor
* 256
* M = blank_scale * gradient
*
*/
static u32 fb_get_hblank_by_hfreq(u32 hfreq, u32 xres)
{
u32 c_val, m_val, duty_cycle, hblank;
c_val = (((H_OFFSET - H_SCALEFACTOR) * H_BLANKSCALE)/256 +
H_SCALEFACTOR) * 1000;
m_val = (H_BLANKSCALE * H_GRADIENT)/256;
m_val = (m_val * 1000000)/hfreq;
duty_cycle = c_val - m_val;
hblank = (xres * duty_cycle)/(100000 - duty_cycle);
return (hblank);
}
/**
* fb_get_hblank_by_dclk - get horizontal blank time given pixelclock
* @dclk: pixelclock in Hz
* @xres: horizontal resolution in pixels
*
* DESCRIPTION:
*
* xres * duty_cycle
* hblank = ------------------
* 100 - duty_cycle
*
* duty cycle = percent of htotal assigned to inactive display
* duty cycle = C - (M * h_period)
*
* where: h_period = SQRT(100 - C + (0.4 * xres * M)/dclk) + C - 100
* -----------------------------------------------
* 2 * M
* M = 300;
* C = 30;
*/
static u32 fb_get_hblank_by_dclk(u32 dclk, u32 xres)
{
u32 duty_cycle, h_period, hblank;
dclk /= 1000;
h_period = 100 - C_VAL;
h_period *= h_period;
h_period += (M_VAL * xres * 2 * 1000)/(5 * dclk);
h_period *= 10000;
h_period = int_sqrt(h_period);
h_period -= (100 - C_VAL) * 100;
h_period *= 1000;
h_period /= 2 * M_VAL;
duty_cycle = C_VAL * 1000 - (M_VAL * h_period)/100;
hblank = (xres * duty_cycle)/(100000 - duty_cycle) + 8;
hblank &= ~15;
return (hblank);
}
/**
* fb_get_hfreq - estimate hsync
* @vfreq: vertical refresh rate
* @yres: vertical resolution
*
* DESCRIPTION:
*
* (yres + front_port) * vfreq * 1000000
* hfreq = -------------------------------------
* (1000000 - (vfreq * FLYBACK)
*
*/
static u32 fb_get_hfreq(u32 vfreq, u32 yres)
{
u32 divisor, hfreq;
divisor = (1000000 - (vfreq * FLYBACK))/1000;
hfreq = (yres + V_FRONTPORCH) * vfreq * 1000;
return (hfreq/divisor);
}
static void fb_timings_vfreq(struct __fb_timings *timings)
{
timings->hfreq = fb_get_hfreq(timings->vfreq, timings->vactive);
timings->vblank = fb_get_vblank(timings->hfreq);
timings->vtotal = timings->vactive + timings->vblank;
timings->hblank = fb_get_hblank_by_hfreq(timings->hfreq,
timings->hactive);
timings->htotal = timings->hactive + timings->hblank;
timings->dclk = timings->htotal * timings->hfreq;
}
static void fb_timings_hfreq(struct __fb_timings *timings)
{
timings->vblank = fb_get_vblank(timings->hfreq);
timings->vtotal = timings->vactive + timings->vblank;
timings->vfreq = timings->hfreq/timings->vtotal;
timings->hblank = fb_get_hblank_by_hfreq(timings->hfreq,
timings->hactive);
timings->htotal = timings->hactive + timings->hblank;
timings->dclk = timings->htotal * timings->hfreq;
}
static void fb_timings_dclk(struct __fb_timings *timings)
{
timings->hblank = fb_get_hblank_by_dclk(timings->dclk,
timings->hactive);
timings->htotal = timings->hactive + timings->hblank;
timings->hfreq = timings->dclk/timings->htotal;
timings->vblank = fb_get_vblank(timings->hfreq);
timings->vtotal = timings->vactive + timings->vblank;
timings->vfreq = timings->hfreq/timings->vtotal;
}
/*
* fb_get_mode - calculates video mode using VESA GTF
* @flags: if: 0 - maximize vertical refresh rate
* 1 - vrefresh-driven calculation;
* 2 - hscan-driven calculation;
* 3 - pixelclock-driven calculation;
* @val: depending on @flags, ignored, vrefresh, hsync or pixelclock
* @var: pointer to fb_var_screeninfo
* @info: pointer to fb_info
*
* DESCRIPTION:
* Calculates video mode based on monitor specs using VESA GTF.
* The GTF is best for VESA GTF compliant monitors but is
* specifically formulated to work for older monitors as well.
*
* If @flag==0, the function will attempt to maximize the
* refresh rate. Otherwise, it will calculate timings based on
* the flag and accompanying value.
*
* If FB_IGNOREMON bit is set in @flags, monitor specs will be
* ignored and @var will be filled with the calculated timings.
*
* All calculations are based on the VESA GTF Spreadsheet
* available at VESA's public ftp (http://www.vesa.org).
*
* NOTES:
* The timings generated by the GTF will be different from VESA
* DMT. It might be a good idea to keep a table of standard
* VESA modes as well. The GTF may also not work for some displays,
* such as, and especially, analog TV.
*
* REQUIRES:
* A valid info->monspecs, otherwise 'safe numbers' will be used.
*/
int fb_get_mode(int flags, u32 val, struct fb_var_screeninfo *var, struct fb_info *info)
{
struct __fb_timings *timings;
u32 interlace = 1, dscan = 1;
u32 hfmin, hfmax, vfmin, vfmax, dclkmin, dclkmax, err = 0;
timings = kzalloc(sizeof(struct __fb_timings), GFP_KERNEL);
if (!timings)
return -ENOMEM;
/*
* If monspecs are invalid, use values that are enough
* for 640x480@60
*/
if (!info || !info->monspecs.hfmax || !info->monspecs.vfmax ||
!info->monspecs.dclkmax ||
info->monspecs.hfmax < info->monspecs.hfmin ||
info->monspecs.vfmax < info->monspecs.vfmin ||
info->monspecs.dclkmax < info->monspecs.dclkmin) {
hfmin = 29000; hfmax = 30000;
vfmin = 60; vfmax = 60;
dclkmin = 0; dclkmax = 25000000;
} else {
hfmin = info->monspecs.hfmin;
hfmax = info->monspecs.hfmax;
vfmin = info->monspecs.vfmin;
vfmax = info->monspecs.vfmax;
dclkmin = info->monspecs.dclkmin;
dclkmax = info->monspecs.dclkmax;
}
timings->hactive = var->xres;
timings->vactive = var->yres;
if (var->vmode & FB_VMODE_INTERLACED) {
timings->vactive /= 2;
interlace = 2;
}
if (var->vmode & FB_VMODE_DOUBLE) {
timings->vactive *= 2;
dscan = 2;
}
switch (flags & ~FB_IGNOREMON) {
case FB_MAXTIMINGS: /* maximize refresh rate */
timings->hfreq = hfmax;
fb_timings_hfreq(timings);
if (timings->vfreq > vfmax) {
timings->vfreq = vfmax;
fb_timings_vfreq(timings);
}
if (timings->dclk > dclkmax) {
timings->dclk = dclkmax;
fb_timings_dclk(timings);
}
break;
case FB_VSYNCTIMINGS: /* vrefresh driven */
timings->vfreq = val;
fb_timings_vfreq(timings);
break;
case FB_HSYNCTIMINGS: /* hsync driven */
timings->hfreq = val;
fb_timings_hfreq(timings);
break;
case FB_DCLKTIMINGS: /* pixelclock driven */
timings->dclk = PICOS2KHZ(val) * 1000;
fb_timings_dclk(timings);
break;
default:
err = -EINVAL;
}
if (err || (!(flags & FB_IGNOREMON) &&
(timings->vfreq < vfmin || timings->vfreq > vfmax ||
timings->hfreq < hfmin || timings->hfreq > hfmax ||
timings->dclk < dclkmin || timings->dclk > dclkmax))) {
err = -EINVAL;
} else {
var->pixclock = KHZ2PICOS(timings->dclk/1000);
var->hsync_len = (timings->htotal * 8)/100;
var->right_margin = (timings->hblank/2) - var->hsync_len;
var->left_margin = timings->hblank - var->right_margin -
var->hsync_len;
var->vsync_len = (3 * interlace)/dscan;
var->lower_margin = (1 * interlace)/dscan;
var->upper_margin = (timings->vblank * interlace)/dscan -
(var->vsync_len + var->lower_margin);
}
kfree(timings);
return err;
}
#ifdef CONFIG_VIDEOMODE_HELPERS
int fb_videomode_from_videomode(const struct videomode *vm,
struct fb_videomode *fbmode)
{
unsigned int htotal, vtotal;
fbmode->xres = vm->hactive;
fbmode->left_margin = vm->hback_porch;
fbmode->right_margin = vm->hfront_porch;
fbmode->hsync_len = vm->hsync_len;
fbmode->yres = vm->vactive;
fbmode->upper_margin = vm->vback_porch;
fbmode->lower_margin = vm->vfront_porch;
fbmode->vsync_len = vm->vsync_len;
/* prevent division by zero in KHZ2PICOS macro */
fbmode->pixclock = vm->pixelclock ?
KHZ2PICOS(vm->pixelclock / 1000) : 0;
fbmode->sync = 0;
fbmode->vmode = 0;
if (vm->flags & DISPLAY_FLAGS_HSYNC_HIGH)
fbmode->sync |= FB_SYNC_HOR_HIGH_ACT;
if (vm->flags & DISPLAY_FLAGS_VSYNC_HIGH)
fbmode->sync |= FB_SYNC_VERT_HIGH_ACT;
if (vm->flags & DISPLAY_FLAGS_INTERLACED)
fbmode->vmode |= FB_VMODE_INTERLACED;
if (vm->flags & DISPLAY_FLAGS_DOUBLESCAN)
fbmode->vmode |= FB_VMODE_DOUBLE;
fbmode->flag = 0;
htotal = vm->hactive + vm->hfront_porch + vm->hback_porch +
vm->hsync_len;
vtotal = vm->vactive + vm->vfront_porch + vm->vback_porch +
vm->vsync_len;
/* prevent division by zero */
if (htotal && vtotal) {
fbmode->refresh = vm->pixelclock / (htotal * vtotal);
/* a mode must have htotal and vtotal != 0 or it is invalid */
} else {
fbmode->refresh = 0;
return -EINVAL;
}
return 0;
}
EXPORT_SYMBOL_GPL(fb_videomode_from_videomode);
#ifdef CONFIG_OF
static inline void dump_fb_videomode(const struct fb_videomode *m)
{
pr_debug("fb_videomode = %ux%u@%uHz (%ukHz) %u %u %u %u %u %u %u %u %u\n",
m->xres, m->yres, m->refresh, m->pixclock, m->left_margin,
m->right_margin, m->upper_margin, m->lower_margin,
m->hsync_len, m->vsync_len, m->sync, m->vmode, m->flag);
}
/**
* of_get_fb_videomode - get a fb_videomode from devicetree
* @np: device_node with the timing specification
* @fb: will be set to the return value
* @index: index into the list of display timings in devicetree
*
* DESCRIPTION:
* This function is expensive and should only be used, if only one mode is to be
* read from DT. To get multiple modes start with of_get_display_timings ond
* work with that instead.
*/
int of_get_fb_videomode(struct device_node *np, struct fb_videomode *fb,
int index)
{
struct videomode vm;
int ret;
ret = of_get_videomode(np, &vm, index);
if (ret)
return ret;
ret = fb_videomode_from_videomode(&vm, fb);
if (ret)
return ret;
pr_debug("%s: got %dx%d display mode from %s\n",
of_node_full_name(np), vm.hactive, vm.vactive, np->name);
dump_fb_videomode(fb);
return 0;
}
EXPORT_SYMBOL_GPL(of_get_fb_videomode);
#endif /* CONFIG_OF */
#endif /* CONFIG_VIDEOMODE_HELPERS */
#else
int fb_parse_edid(unsigned char *edid, struct fb_var_screeninfo *var)
{
return 1;
}
void fb_edid_to_monspecs(unsigned char *edid, struct fb_monspecs *specs)
{
}
void fb_edid_add_monspecs(unsigned char *edid, struct fb_monspecs *specs)
{
}
void fb_destroy_modedb(struct fb_videomode *modedb)
{
}
int fb_get_mode(int flags, u32 val, struct fb_var_screeninfo *var,
struct fb_info *info)
{
return -EINVAL;
}
#endif /* CONFIG_FB_MODE_HELPERS */
/*
* fb_validate_mode - validates var against monitor capabilities
* @var: pointer to fb_var_screeninfo
* @info: pointer to fb_info
*
* DESCRIPTION:
* Validates video mode against monitor capabilities specified in
* info->monspecs.
*
* REQUIRES:
* A valid info->monspecs.
*/
int fb_validate_mode(const struct fb_var_screeninfo *var, struct fb_info *info)
{
u32 hfreq, vfreq, htotal, vtotal, pixclock;
u32 hfmin, hfmax, vfmin, vfmax, dclkmin, dclkmax;
/*
* If monspecs are invalid, use values that are enough
* for 640x480@60
*/
if (!info->monspecs.hfmax || !info->monspecs.vfmax ||
!info->monspecs.dclkmax ||
info->monspecs.hfmax < info->monspecs.hfmin ||
info->monspecs.vfmax < info->monspecs.vfmin ||
info->monspecs.dclkmax < info->monspecs.dclkmin) {
hfmin = 29000; hfmax = 30000;
vfmin = 60; vfmax = 60;
dclkmin = 0; dclkmax = 25000000;
} else {
hfmin = info->monspecs.hfmin;
hfmax = info->monspecs.hfmax;
vfmin = info->monspecs.vfmin;
vfmax = info->monspecs.vfmax;
dclkmin = info->monspecs.dclkmin;
dclkmax = info->monspecs.dclkmax;
}
if (!var->pixclock)
return -EINVAL;
pixclock = PICOS2KHZ(var->pixclock) * 1000;
htotal = var->xres + var->right_margin + var->hsync_len +
var->left_margin;
vtotal = var->yres + var->lower_margin + var->vsync_len +
var->upper_margin;
if (var->vmode & FB_VMODE_INTERLACED)
vtotal /= 2;
if (var->vmode & FB_VMODE_DOUBLE)
vtotal *= 2;
hfreq = pixclock/htotal;
hfreq = (hfreq + 500) / 1000 * 1000;
vfreq = hfreq/vtotal;
return (vfreq < vfmin || vfreq > vfmax ||
hfreq < hfmin || hfreq > hfmax ||
pixclock < dclkmin || pixclock > dclkmax) ?
-EINVAL : 0;
}
#if defined(CONFIG_FIRMWARE_EDID) && defined(CONFIG_X86)
/*
* We need to ensure that the EDID block is only returned for
* the primary graphics adapter.
*/
const unsigned char *fb_firmware_edid(struct device *device)
{
struct pci_dev *dev = NULL;
struct resource *res = NULL;
unsigned char *edid = NULL;
if (device)
dev = to_pci_dev(device);
if (dev)
res = &dev->resource[PCI_ROM_RESOURCE];
if (res && res->flags & IORESOURCE_ROM_SHADOW)
edid = edid_info.dummy;
return edid;
}
#else
const unsigned char *fb_firmware_edid(struct device *device)
{
return NULL;
}
#endif
EXPORT_SYMBOL(fb_firmware_edid);
EXPORT_SYMBOL(fb_parse_edid);
EXPORT_SYMBOL(fb_edid_to_monspecs);
EXPORT_SYMBOL(fb_edid_add_monspecs);
EXPORT_SYMBOL(fb_get_mode);
EXPORT_SYMBOL(fb_validate_mode);
EXPORT_SYMBOL(fb_destroy_modedb);
| null | null | null | null | 97,127 |
5,195 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 170,190 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | /*
* Driver for Digigram pcxhr compatible soundcards
*
* main file with alsa callbacks
*
* Copyright (c) 2004 by Digigram <alsa@digigram.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/pci.h>
#include <linux/dma-mapping.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <sound/core.h>
#include <sound/initval.h>
#include <sound/info.h>
#include <sound/control.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include "pcxhr.h"
#include "pcxhr_mixer.h"
#include "pcxhr_hwdep.h"
#include "pcxhr_core.h"
#include "pcxhr_mix22.h"
#define DRIVER_NAME "pcxhr"
MODULE_AUTHOR("Markus Bollinger <bollinger@digigram.com>, "
"Marc Titinger <titinger@digigram.com>");
MODULE_DESCRIPTION("Digigram " DRIVER_NAME " " PCXHR_DRIVER_VERSION_STRING);
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{Digigram," DRIVER_NAME "}}");
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;/* Enable this card */
static bool mono[SNDRV_CARDS]; /* capture mono only */
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for Digigram " DRIVER_NAME " soundcard");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for Digigram " DRIVER_NAME " soundcard");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable Digigram " DRIVER_NAME " soundcard");
module_param_array(mono, bool, NULL, 0444);
MODULE_PARM_DESC(mono, "Mono capture mode (default is stereo)");
enum {
PCI_ID_VX882HR,
PCI_ID_PCX882HR,
PCI_ID_VX881HR,
PCI_ID_PCX881HR,
PCI_ID_VX882E,
PCI_ID_PCX882E,
PCI_ID_VX881E,
PCI_ID_PCX881E,
PCI_ID_VX1222HR,
PCI_ID_PCX1222HR,
PCI_ID_VX1221HR,
PCI_ID_PCX1221HR,
PCI_ID_VX1222E,
PCI_ID_PCX1222E,
PCI_ID_VX1221E,
PCI_ID_PCX1221E,
PCI_ID_VX222HR,
PCI_ID_VX222E,
PCI_ID_PCX22HR,
PCI_ID_PCX22E,
PCI_ID_VX222HRMIC,
PCI_ID_VX222E_MIC,
PCI_ID_PCX924HR,
PCI_ID_PCX924E,
PCI_ID_PCX924HRMIC,
PCI_ID_PCX924E_MIC,
PCI_ID_VX442HR,
PCI_ID_PCX442HR,
PCI_ID_VX442E,
PCI_ID_PCX442E,
PCI_ID_VX822HR,
PCI_ID_PCX822HR,
PCI_ID_VX822E,
PCI_ID_PCX822E,
PCI_ID_LAST
};
static const struct pci_device_id pcxhr_ids[] = {
{ 0x10b5, 0x9656, 0x1369, 0xb001, 0, 0, PCI_ID_VX882HR, },
{ 0x10b5, 0x9656, 0x1369, 0xb101, 0, 0, PCI_ID_PCX882HR, },
{ 0x10b5, 0x9656, 0x1369, 0xb201, 0, 0, PCI_ID_VX881HR, },
{ 0x10b5, 0x9656, 0x1369, 0xb301, 0, 0, PCI_ID_PCX881HR, },
{ 0x10b5, 0x9056, 0x1369, 0xb021, 0, 0, PCI_ID_VX882E, },
{ 0x10b5, 0x9056, 0x1369, 0xb121, 0, 0, PCI_ID_PCX882E, },
{ 0x10b5, 0x9056, 0x1369, 0xb221, 0, 0, PCI_ID_VX881E, },
{ 0x10b5, 0x9056, 0x1369, 0xb321, 0, 0, PCI_ID_PCX881E, },
{ 0x10b5, 0x9656, 0x1369, 0xb401, 0, 0, PCI_ID_VX1222HR, },
{ 0x10b5, 0x9656, 0x1369, 0xb501, 0, 0, PCI_ID_PCX1222HR, },
{ 0x10b5, 0x9656, 0x1369, 0xb601, 0, 0, PCI_ID_VX1221HR, },
{ 0x10b5, 0x9656, 0x1369, 0xb701, 0, 0, PCI_ID_PCX1221HR, },
{ 0x10b5, 0x9056, 0x1369, 0xb421, 0, 0, PCI_ID_VX1222E, },
{ 0x10b5, 0x9056, 0x1369, 0xb521, 0, 0, PCI_ID_PCX1222E, },
{ 0x10b5, 0x9056, 0x1369, 0xb621, 0, 0, PCI_ID_VX1221E, },
{ 0x10b5, 0x9056, 0x1369, 0xb721, 0, 0, PCI_ID_PCX1221E, },
{ 0x10b5, 0x9056, 0x1369, 0xba01, 0, 0, PCI_ID_VX222HR, },
{ 0x10b5, 0x9056, 0x1369, 0xba21, 0, 0, PCI_ID_VX222E, },
{ 0x10b5, 0x9056, 0x1369, 0xbd01, 0, 0, PCI_ID_PCX22HR, },
{ 0x10b5, 0x9056, 0x1369, 0xbd21, 0, 0, PCI_ID_PCX22E, },
{ 0x10b5, 0x9056, 0x1369, 0xbc01, 0, 0, PCI_ID_VX222HRMIC, },
{ 0x10b5, 0x9056, 0x1369, 0xbc21, 0, 0, PCI_ID_VX222E_MIC, },
{ 0x10b5, 0x9056, 0x1369, 0xbb01, 0, 0, PCI_ID_PCX924HR, },
{ 0x10b5, 0x9056, 0x1369, 0xbb21, 0, 0, PCI_ID_PCX924E, },
{ 0x10b5, 0x9056, 0x1369, 0xbf01, 0, 0, PCI_ID_PCX924HRMIC, },
{ 0x10b5, 0x9056, 0x1369, 0xbf21, 0, 0, PCI_ID_PCX924E_MIC, },
{ 0x10b5, 0x9656, 0x1369, 0xd001, 0, 0, PCI_ID_VX442HR, },
{ 0x10b5, 0x9656, 0x1369, 0xd101, 0, 0, PCI_ID_PCX442HR, },
{ 0x10b5, 0x9056, 0x1369, 0xd021, 0, 0, PCI_ID_VX442E, },
{ 0x10b5, 0x9056, 0x1369, 0xd121, 0, 0, PCI_ID_PCX442E, },
{ 0x10b5, 0x9656, 0x1369, 0xd201, 0, 0, PCI_ID_VX822HR, },
{ 0x10b5, 0x9656, 0x1369, 0xd301, 0, 0, PCI_ID_PCX822HR, },
{ 0x10b5, 0x9056, 0x1369, 0xd221, 0, 0, PCI_ID_VX822E, },
{ 0x10b5, 0x9056, 0x1369, 0xd321, 0, 0, PCI_ID_PCX822E, },
{ 0, }
};
MODULE_DEVICE_TABLE(pci, pcxhr_ids);
struct board_parameters {
char* board_name;
short playback_chips;
short capture_chips;
short fw_file_set;
short firmware_num;
};
static struct board_parameters pcxhr_board_params[] = {
[PCI_ID_VX882HR] = { "VX882HR", 4, 4, 0, 41 },
[PCI_ID_PCX882HR] = { "PCX882HR", 4, 4, 0, 41 },
[PCI_ID_VX881HR] = { "VX881HR", 4, 4, 0, 41 },
[PCI_ID_PCX881HR] = { "PCX881HR", 4, 4, 0, 41 },
[PCI_ID_VX882E] = { "VX882e", 4, 4, 1, 41 },
[PCI_ID_PCX882E] = { "PCX882e", 4, 4, 1, 41 },
[PCI_ID_VX881E] = { "VX881e", 4, 4, 1, 41 },
[PCI_ID_PCX881E] = { "PCX881e", 4, 4, 1, 41 },
[PCI_ID_VX1222HR] = { "VX1222HR", 6, 1, 2, 42 },
[PCI_ID_PCX1222HR] = { "PCX1222HR", 6, 1, 2, 42 },
[PCI_ID_VX1221HR] = { "VX1221HR", 6, 1, 2, 42 },
[PCI_ID_PCX1221HR] = { "PCX1221HR", 6, 1, 2, 42 },
[PCI_ID_VX1222E] = { "VX1222e", 6, 1, 3, 42 },
[PCI_ID_PCX1222E] = { "PCX1222e", 6, 1, 3, 42 },
[PCI_ID_VX1221E] = { "VX1221e", 6, 1, 3, 42 },
[PCI_ID_PCX1221E] = { "PCX1221e", 6, 1, 3, 42 },
[PCI_ID_VX222HR] = { "VX222HR", 1, 1, 4, 44 },
[PCI_ID_VX222E] = { "VX222e", 1, 1, 4, 44 },
[PCI_ID_PCX22HR] = { "PCX22HR", 1, 0, 4, 44 },
[PCI_ID_PCX22E] = { "PCX22e", 1, 0, 4, 44 },
[PCI_ID_VX222HRMIC] = { "VX222HR-Mic", 1, 1, 5, 44 },
[PCI_ID_VX222E_MIC] = { "VX222e-Mic", 1, 1, 5, 44 },
[PCI_ID_PCX924HR] = { "PCX924HR", 1, 1, 5, 44 },
[PCI_ID_PCX924E] = { "PCX924e", 1, 1, 5, 44 },
[PCI_ID_PCX924HRMIC] = { "PCX924HR-Mic", 1, 1, 5, 44 },
[PCI_ID_PCX924E_MIC] = { "PCX924e-Mic", 1, 1, 5, 44 },
[PCI_ID_VX442HR] = { "VX442HR", 2, 2, 0, 41 },
[PCI_ID_PCX442HR] = { "PCX442HR", 2, 2, 0, 41 },
[PCI_ID_VX442E] = { "VX442e", 2, 2, 1, 41 },
[PCI_ID_PCX442E] = { "PCX442e", 2, 2, 1, 41 },
[PCI_ID_VX822HR] = { "VX822HR", 4, 1, 2, 42 },
[PCI_ID_PCX822HR] = { "PCX822HR", 4, 1, 2, 42 },
[PCI_ID_VX822E] = { "VX822e", 4, 1, 3, 42 },
[PCI_ID_PCX822E] = { "PCX822e", 4, 1, 3, 42 },
};
/* boards without hw AES1 and SRC onboard are all using fw_file_set==4 */
/* VX222HR, VX222e, PCX22HR and PCX22e */
#define PCXHR_BOARD_HAS_AES1(x) (x->fw_file_set != 4)
/* some boards do not support 192kHz on digital AES input plugs */
#define PCXHR_BOARD_AESIN_NO_192K(x) ((x->capture_chips == 0) || \
(x->fw_file_set == 0) || \
(x->fw_file_set == 2))
static int pcxhr_pll_freq_register(unsigned int freq, unsigned int* pllreg,
unsigned int* realfreq)
{
unsigned int reg;
if (freq < 6900 || freq > 110000)
return -EINVAL;
reg = (28224000 * 2) / freq;
reg = (reg - 1) / 2;
if (reg < 0x200)
*pllreg = reg + 0x800;
else if (reg < 0x400)
*pllreg = reg & 0x1ff;
else if (reg < 0x800) {
*pllreg = ((reg >> 1) & 0x1ff) + 0x200;
reg &= ~1;
} else {
*pllreg = ((reg >> 2) & 0x1ff) + 0x400;
reg &= ~3;
}
if (realfreq)
*realfreq = (28224000 / (reg + 1));
return 0;
}
#define PCXHR_FREQ_REG_MASK 0x1f
#define PCXHR_FREQ_QUARTZ_48000 0x00
#define PCXHR_FREQ_QUARTZ_24000 0x01
#define PCXHR_FREQ_QUARTZ_12000 0x09
#define PCXHR_FREQ_QUARTZ_32000 0x08
#define PCXHR_FREQ_QUARTZ_16000 0x04
#define PCXHR_FREQ_QUARTZ_8000 0x0c
#define PCXHR_FREQ_QUARTZ_44100 0x02
#define PCXHR_FREQ_QUARTZ_22050 0x0a
#define PCXHR_FREQ_QUARTZ_11025 0x06
#define PCXHR_FREQ_PLL 0x05
#define PCXHR_FREQ_QUARTZ_192000 0x10
#define PCXHR_FREQ_QUARTZ_96000 0x18
#define PCXHR_FREQ_QUARTZ_176400 0x14
#define PCXHR_FREQ_QUARTZ_88200 0x1c
#define PCXHR_FREQ_QUARTZ_128000 0x12
#define PCXHR_FREQ_QUARTZ_64000 0x1a
#define PCXHR_FREQ_WORD_CLOCK 0x0f
#define PCXHR_FREQ_SYNC_AES 0x0e
#define PCXHR_FREQ_AES_1 0x07
#define PCXHR_FREQ_AES_2 0x0b
#define PCXHR_FREQ_AES_3 0x03
#define PCXHR_FREQ_AES_4 0x0d
static int pcxhr_get_clock_reg(struct pcxhr_mgr *mgr, unsigned int rate,
unsigned int *reg, unsigned int *freq)
{
unsigned int val, realfreq, pllreg;
struct pcxhr_rmh rmh;
int err;
realfreq = rate;
switch (mgr->use_clock_type) {
case PCXHR_CLOCK_TYPE_INTERNAL : /* clock by quartz or pll */
switch (rate) {
case 48000 : val = PCXHR_FREQ_QUARTZ_48000; break;
case 24000 : val = PCXHR_FREQ_QUARTZ_24000; break;
case 12000 : val = PCXHR_FREQ_QUARTZ_12000; break;
case 32000 : val = PCXHR_FREQ_QUARTZ_32000; break;
case 16000 : val = PCXHR_FREQ_QUARTZ_16000; break;
case 8000 : val = PCXHR_FREQ_QUARTZ_8000; break;
case 44100 : val = PCXHR_FREQ_QUARTZ_44100; break;
case 22050 : val = PCXHR_FREQ_QUARTZ_22050; break;
case 11025 : val = PCXHR_FREQ_QUARTZ_11025; break;
case 192000 : val = PCXHR_FREQ_QUARTZ_192000; break;
case 96000 : val = PCXHR_FREQ_QUARTZ_96000; break;
case 176400 : val = PCXHR_FREQ_QUARTZ_176400; break;
case 88200 : val = PCXHR_FREQ_QUARTZ_88200; break;
case 128000 : val = PCXHR_FREQ_QUARTZ_128000; break;
case 64000 : val = PCXHR_FREQ_QUARTZ_64000; break;
default :
val = PCXHR_FREQ_PLL;
/* get the value for the pll register */
err = pcxhr_pll_freq_register(rate, &pllreg, &realfreq);
if (err)
return err;
pcxhr_init_rmh(&rmh, CMD_ACCESS_IO_WRITE);
rmh.cmd[0] |= IO_NUM_REG_GENCLK;
rmh.cmd[1] = pllreg & MASK_DSP_WORD;
rmh.cmd[2] = pllreg >> 24;
rmh.cmd_len = 3;
err = pcxhr_send_msg(mgr, &rmh);
if (err < 0) {
dev_err(&mgr->pci->dev,
"error CMD_ACCESS_IO_WRITE "
"for PLL register : %x!\n", err);
return err;
}
}
break;
case PCXHR_CLOCK_TYPE_WORD_CLOCK:
val = PCXHR_FREQ_WORD_CLOCK;
break;
case PCXHR_CLOCK_TYPE_AES_SYNC:
val = PCXHR_FREQ_SYNC_AES;
break;
case PCXHR_CLOCK_TYPE_AES_1:
val = PCXHR_FREQ_AES_1;
break;
case PCXHR_CLOCK_TYPE_AES_2:
val = PCXHR_FREQ_AES_2;
break;
case PCXHR_CLOCK_TYPE_AES_3:
val = PCXHR_FREQ_AES_3;
break;
case PCXHR_CLOCK_TYPE_AES_4:
val = PCXHR_FREQ_AES_4;
break;
default:
return -EINVAL;
}
*reg = val;
*freq = realfreq;
return 0;
}
static int pcxhr_sub_set_clock(struct pcxhr_mgr *mgr,
unsigned int rate,
int *changed)
{
unsigned int val, realfreq, speed;
struct pcxhr_rmh rmh;
int err;
err = pcxhr_get_clock_reg(mgr, rate, &val, &realfreq);
if (err)
return err;
/* codec speed modes */
if (rate < 55000)
speed = 0; /* single speed */
else if (rate < 100000)
speed = 1; /* dual speed */
else
speed = 2; /* quad speed */
if (mgr->codec_speed != speed) {
pcxhr_init_rmh(&rmh, CMD_ACCESS_IO_WRITE); /* mute outputs */
rmh.cmd[0] |= IO_NUM_REG_MUTE_OUT;
if (DSP_EXT_CMD_SET(mgr)) {
rmh.cmd[1] = 1;
rmh.cmd_len = 2;
}
err = pcxhr_send_msg(mgr, &rmh);
if (err)
return err;
pcxhr_init_rmh(&rmh, CMD_ACCESS_IO_WRITE); /* set speed ratio */
rmh.cmd[0] |= IO_NUM_SPEED_RATIO;
rmh.cmd[1] = speed;
rmh.cmd_len = 2;
err = pcxhr_send_msg(mgr, &rmh);
if (err)
return err;
}
/* set the new frequency */
dev_dbg(&mgr->pci->dev, "clock register : set %x\n", val);
err = pcxhr_write_io_num_reg_cont(mgr, PCXHR_FREQ_REG_MASK,
val, changed);
if (err)
return err;
mgr->sample_rate_real = realfreq;
mgr->cur_clock_type = mgr->use_clock_type;
/* unmute after codec speed modes */
if (mgr->codec_speed != speed) {
pcxhr_init_rmh(&rmh, CMD_ACCESS_IO_READ); /* unmute outputs */
rmh.cmd[0] |= IO_NUM_REG_MUTE_OUT;
if (DSP_EXT_CMD_SET(mgr)) {
rmh.cmd[1] = 1;
rmh.cmd_len = 2;
}
err = pcxhr_send_msg(mgr, &rmh);
if (err)
return err;
mgr->codec_speed = speed; /* save new codec speed */
}
dev_dbg(&mgr->pci->dev, "pcxhr_sub_set_clock to %dHz (realfreq=%d)\n",
rate, realfreq);
return 0;
}
#define PCXHR_MODIFY_CLOCK_S_BIT 0x04
#define PCXHR_IRQ_TIMER_FREQ 92000
#define PCXHR_IRQ_TIMER_PERIOD 48
int pcxhr_set_clock(struct pcxhr_mgr *mgr, unsigned int rate)
{
struct pcxhr_rmh rmh;
int err, changed;
if (rate == 0)
return 0; /* nothing to do */
if (mgr->is_hr_stereo)
err = hr222_sub_set_clock(mgr, rate, &changed);
else
err = pcxhr_sub_set_clock(mgr, rate, &changed);
if (err)
return err;
if (changed) {
pcxhr_init_rmh(&rmh, CMD_MODIFY_CLOCK);
rmh.cmd[0] |= PCXHR_MODIFY_CLOCK_S_BIT; /* resync fifos */
if (rate < PCXHR_IRQ_TIMER_FREQ)
rmh.cmd[1] = PCXHR_IRQ_TIMER_PERIOD;
else
rmh.cmd[1] = PCXHR_IRQ_TIMER_PERIOD * 2;
rmh.cmd[2] = rate;
rmh.cmd_len = 3;
err = pcxhr_send_msg(mgr, &rmh);
if (err)
return err;
}
return 0;
}
static int pcxhr_sub_get_external_clock(struct pcxhr_mgr *mgr,
enum pcxhr_clock_type clock_type,
int *sample_rate)
{
struct pcxhr_rmh rmh;
unsigned char reg;
int err, rate;
switch (clock_type) {
case PCXHR_CLOCK_TYPE_WORD_CLOCK:
reg = REG_STATUS_WORD_CLOCK;
break;
case PCXHR_CLOCK_TYPE_AES_SYNC:
reg = REG_STATUS_AES_SYNC;
break;
case PCXHR_CLOCK_TYPE_AES_1:
reg = REG_STATUS_AES_1;
break;
case PCXHR_CLOCK_TYPE_AES_2:
reg = REG_STATUS_AES_2;
break;
case PCXHR_CLOCK_TYPE_AES_3:
reg = REG_STATUS_AES_3;
break;
case PCXHR_CLOCK_TYPE_AES_4:
reg = REG_STATUS_AES_4;
break;
default:
return -EINVAL;
}
pcxhr_init_rmh(&rmh, CMD_ACCESS_IO_READ);
rmh.cmd_len = 2;
rmh.cmd[0] |= IO_NUM_REG_STATUS;
if (mgr->last_reg_stat != reg) {
rmh.cmd[1] = reg;
err = pcxhr_send_msg(mgr, &rmh);
if (err)
return err;
udelay(100); /* wait minimum 2 sample_frames at 32kHz ! */
mgr->last_reg_stat = reg;
}
rmh.cmd[1] = REG_STATUS_CURRENT;
err = pcxhr_send_msg(mgr, &rmh);
if (err)
return err;
switch (rmh.stat[1] & 0x0f) {
case REG_STATUS_SYNC_32000 : rate = 32000; break;
case REG_STATUS_SYNC_44100 : rate = 44100; break;
case REG_STATUS_SYNC_48000 : rate = 48000; break;
case REG_STATUS_SYNC_64000 : rate = 64000; break;
case REG_STATUS_SYNC_88200 : rate = 88200; break;
case REG_STATUS_SYNC_96000 : rate = 96000; break;
case REG_STATUS_SYNC_128000 : rate = 128000; break;
case REG_STATUS_SYNC_176400 : rate = 176400; break;
case REG_STATUS_SYNC_192000 : rate = 192000; break;
default: rate = 0;
}
dev_dbg(&mgr->pci->dev, "External clock is at %d Hz\n", rate);
*sample_rate = rate;
return 0;
}
int pcxhr_get_external_clock(struct pcxhr_mgr *mgr,
enum pcxhr_clock_type clock_type,
int *sample_rate)
{
if (mgr->is_hr_stereo)
return hr222_get_external_clock(mgr, clock_type,
sample_rate);
else
return pcxhr_sub_get_external_clock(mgr, clock_type,
sample_rate);
}
/*
* start or stop playback/capture substream
*/
static int pcxhr_set_stream_state(struct snd_pcxhr *chip,
struct pcxhr_stream *stream)
{
int err;
struct pcxhr_rmh rmh;
int stream_mask, start;
if (stream->status == PCXHR_STREAM_STATUS_SCHEDULE_RUN)
start = 1;
else {
if (stream->status != PCXHR_STREAM_STATUS_SCHEDULE_STOP) {
dev_err(chip->card->dev,
"pcxhr_set_stream_state CANNOT be stopped\n");
return -EINVAL;
}
start = 0;
}
if (!stream->substream)
return -EINVAL;
stream->timer_abs_periods = 0;
stream->timer_period_frag = 0; /* reset theoretical stream pos */
stream->timer_buf_periods = 0;
stream->timer_is_synced = 0;
stream_mask =
stream->pipe->is_capture ? 1 : 1<<stream->substream->number;
pcxhr_init_rmh(&rmh, start ? CMD_START_STREAM : CMD_STOP_STREAM);
pcxhr_set_pipe_cmd_params(&rmh, stream->pipe->is_capture,
stream->pipe->first_audio, 0, stream_mask);
chip = snd_pcm_substream_chip(stream->substream);
err = pcxhr_send_msg(chip->mgr, &rmh);
if (err)
dev_err(chip->card->dev,
"ERROR pcxhr_set_stream_state err=%x;\n", err);
stream->status =
start ? PCXHR_STREAM_STATUS_STARTED : PCXHR_STREAM_STATUS_STOPPED;
return err;
}
#define HEADER_FMT_BASE_LIN 0xfed00000
#define HEADER_FMT_BASE_FLOAT 0xfad00000
#define HEADER_FMT_INTEL 0x00008000
#define HEADER_FMT_24BITS 0x00004000
#define HEADER_FMT_16BITS 0x00002000
#define HEADER_FMT_UPTO11 0x00000200
#define HEADER_FMT_UPTO32 0x00000100
#define HEADER_FMT_MONO 0x00000080
static int pcxhr_set_format(struct pcxhr_stream *stream)
{
int err, is_capture, sample_rate, stream_num;
struct snd_pcxhr *chip;
struct pcxhr_rmh rmh;
unsigned int header;
chip = snd_pcm_substream_chip(stream->substream);
switch (stream->format) {
case SNDRV_PCM_FORMAT_U8:
header = HEADER_FMT_BASE_LIN;
break;
case SNDRV_PCM_FORMAT_S16_LE:
header = HEADER_FMT_BASE_LIN |
HEADER_FMT_16BITS | HEADER_FMT_INTEL;
break;
case SNDRV_PCM_FORMAT_S16_BE:
header = HEADER_FMT_BASE_LIN | HEADER_FMT_16BITS;
break;
case SNDRV_PCM_FORMAT_S24_3LE:
header = HEADER_FMT_BASE_LIN |
HEADER_FMT_24BITS | HEADER_FMT_INTEL;
break;
case SNDRV_PCM_FORMAT_S24_3BE:
header = HEADER_FMT_BASE_LIN | HEADER_FMT_24BITS;
break;
case SNDRV_PCM_FORMAT_FLOAT_LE:
header = HEADER_FMT_BASE_FLOAT | HEADER_FMT_INTEL;
break;
default:
dev_err(chip->card->dev,
"error pcxhr_set_format() : unknown format\n");
return -EINVAL;
}
sample_rate = chip->mgr->sample_rate;
if (sample_rate <= 32000 && sample_rate !=0) {
if (sample_rate <= 11025)
header |= HEADER_FMT_UPTO11;
else
header |= HEADER_FMT_UPTO32;
}
if (stream->channels == 1)
header |= HEADER_FMT_MONO;
is_capture = stream->pipe->is_capture;
stream_num = is_capture ? 0 : stream->substream->number;
pcxhr_init_rmh(&rmh, is_capture ?
CMD_FORMAT_STREAM_IN : CMD_FORMAT_STREAM_OUT);
pcxhr_set_pipe_cmd_params(&rmh, is_capture, stream->pipe->first_audio,
stream_num, 0);
if (is_capture) {
/* bug with old dsp versions: */
/* bit 12 also sets the format of the playback stream */
if (DSP_EXT_CMD_SET(chip->mgr))
rmh.cmd[0] |= 1<<10;
else
rmh.cmd[0] |= 1<<12;
}
rmh.cmd[1] = 0;
rmh.cmd_len = 2;
if (DSP_EXT_CMD_SET(chip->mgr)) {
/* add channels and set bit 19 if channels>2 */
rmh.cmd[1] = stream->channels;
if (!is_capture) {
/* playback : add channel mask to command */
rmh.cmd[2] = (stream->channels == 1) ? 0x01 : 0x03;
rmh.cmd_len = 3;
}
}
rmh.cmd[rmh.cmd_len++] = header >> 8;
rmh.cmd[rmh.cmd_len++] = (header & 0xff) << 16;
err = pcxhr_send_msg(chip->mgr, &rmh);
if (err)
dev_err(chip->card->dev,
"ERROR pcxhr_set_format err=%x;\n", err);
return err;
}
static int pcxhr_update_r_buffer(struct pcxhr_stream *stream)
{
int err, is_capture, stream_num;
struct pcxhr_rmh rmh;
struct snd_pcm_substream *subs = stream->substream;
struct snd_pcxhr *chip = snd_pcm_substream_chip(subs);
is_capture = (subs->stream == SNDRV_PCM_STREAM_CAPTURE);
stream_num = is_capture ? 0 : subs->number;
dev_dbg(chip->card->dev,
"pcxhr_update_r_buffer(pcm%c%d) : addr(%p) bytes(%zx) subs(%d)\n",
is_capture ? 'c' : 'p',
chip->chip_idx, (void *)(long)subs->runtime->dma_addr,
subs->runtime->dma_bytes, subs->number);
pcxhr_init_rmh(&rmh, CMD_UPDATE_R_BUFFERS);
pcxhr_set_pipe_cmd_params(&rmh, is_capture, stream->pipe->first_audio,
stream_num, 0);
/* max buffer size is 2 MByte */
snd_BUG_ON(subs->runtime->dma_bytes >= 0x200000);
/* size in bits */
rmh.cmd[1] = subs->runtime->dma_bytes * 8;
/* most significant byte */
rmh.cmd[2] = subs->runtime->dma_addr >> 24;
/* this is a circular buffer */
rmh.cmd[2] |= 1<<19;
/* least 3 significant bytes */
rmh.cmd[3] = subs->runtime->dma_addr & MASK_DSP_WORD;
rmh.cmd_len = 4;
err = pcxhr_send_msg(chip->mgr, &rmh);
if (err)
dev_err(chip->card->dev,
"ERROR CMD_UPDATE_R_BUFFERS err=%x;\n", err);
return err;
}
#if 0
static int pcxhr_pipe_sample_count(struct pcxhr_stream *stream,
snd_pcm_uframes_t *sample_count)
{
struct pcxhr_rmh rmh;
int err;
pcxhr_t *chip = snd_pcm_substream_chip(stream->substream);
pcxhr_init_rmh(&rmh, CMD_PIPE_SAMPLE_COUNT);
pcxhr_set_pipe_cmd_params(&rmh, stream->pipe->is_capture, 0, 0,
1<<stream->pipe->first_audio);
err = pcxhr_send_msg(chip->mgr, &rmh);
if (err == 0) {
*sample_count = ((snd_pcm_uframes_t)rmh.stat[0]) << 24;
*sample_count += (snd_pcm_uframes_t)rmh.stat[1];
}
dev_dbg(chip->card->dev, "PIPE_SAMPLE_COUNT = %lx\n", *sample_count);
return err;
}
#endif
static inline int pcxhr_stream_scheduled_get_pipe(struct pcxhr_stream *stream,
struct pcxhr_pipe **pipe)
{
if (stream->status == PCXHR_STREAM_STATUS_SCHEDULE_RUN) {
*pipe = stream->pipe;
return 1;
}
return 0;
}
static void pcxhr_start_linked_stream(struct pcxhr_mgr *mgr)
{
int i, j, err;
struct pcxhr_pipe *pipe;
struct snd_pcxhr *chip;
int capture_mask = 0;
int playback_mask = 0;
#ifdef CONFIG_SND_DEBUG_VERBOSE
ktime_t start_time, stop_time, diff_time;
start_time = ktime_get();
#endif
mutex_lock(&mgr->setup_mutex);
/* check the pipes concerned and build pipe_array */
for (i = 0; i < mgr->num_cards; i++) {
chip = mgr->chip[i];
for (j = 0; j < chip->nb_streams_capt; j++) {
if (pcxhr_stream_scheduled_get_pipe(&chip->capture_stream[j], &pipe))
capture_mask |= (1 << pipe->first_audio);
}
for (j = 0; j < chip->nb_streams_play; j++) {
if (pcxhr_stream_scheduled_get_pipe(&chip->playback_stream[j], &pipe)) {
playback_mask |= (1 << pipe->first_audio);
break; /* add only once, as all playback
* streams of one chip use the same pipe
*/
}
}
}
if (capture_mask == 0 && playback_mask == 0) {
mutex_unlock(&mgr->setup_mutex);
dev_err(&mgr->pci->dev, "pcxhr_start_linked_stream : no pipes\n");
return;
}
dev_dbg(&mgr->pci->dev, "pcxhr_start_linked_stream : "
"playback_mask=%x capture_mask=%x\n",
playback_mask, capture_mask);
/* synchronous stop of all the pipes concerned */
err = pcxhr_set_pipe_state(mgr, playback_mask, capture_mask, 0);
if (err) {
mutex_unlock(&mgr->setup_mutex);
dev_err(&mgr->pci->dev, "pcxhr_start_linked_stream : "
"error stop pipes (P%x C%x)\n",
playback_mask, capture_mask);
return;
}
/* the dsp lost format and buffer info with the stop pipe */
for (i = 0; i < mgr->num_cards; i++) {
struct pcxhr_stream *stream;
chip = mgr->chip[i];
for (j = 0; j < chip->nb_streams_capt; j++) {
stream = &chip->capture_stream[j];
if (pcxhr_stream_scheduled_get_pipe(stream, &pipe)) {
err = pcxhr_set_format(stream);
err = pcxhr_update_r_buffer(stream);
}
}
for (j = 0; j < chip->nb_streams_play; j++) {
stream = &chip->playback_stream[j];
if (pcxhr_stream_scheduled_get_pipe(stream, &pipe)) {
err = pcxhr_set_format(stream);
err = pcxhr_update_r_buffer(stream);
}
}
}
/* start all the streams */
for (i = 0; i < mgr->num_cards; i++) {
struct pcxhr_stream *stream;
chip = mgr->chip[i];
for (j = 0; j < chip->nb_streams_capt; j++) {
stream = &chip->capture_stream[j];
if (pcxhr_stream_scheduled_get_pipe(stream, &pipe))
err = pcxhr_set_stream_state(chip, stream);
}
for (j = 0; j < chip->nb_streams_play; j++) {
stream = &chip->playback_stream[j];
if (pcxhr_stream_scheduled_get_pipe(stream, &pipe))
err = pcxhr_set_stream_state(chip, stream);
}
}
/* synchronous start of all the pipes concerned */
err = pcxhr_set_pipe_state(mgr, playback_mask, capture_mask, 1);
if (err) {
mutex_unlock(&mgr->setup_mutex);
dev_err(&mgr->pci->dev, "pcxhr_start_linked_stream : "
"error start pipes (P%x C%x)\n",
playback_mask, capture_mask);
return;
}
/* put the streams into the running state now
* (increment pointer by interrupt)
*/
mutex_lock(&mgr->lock);
for ( i =0; i < mgr->num_cards; i++) {
struct pcxhr_stream *stream;
chip = mgr->chip[i];
for(j = 0; j < chip->nb_streams_capt; j++) {
stream = &chip->capture_stream[j];
if(stream->status == PCXHR_STREAM_STATUS_STARTED)
stream->status = PCXHR_STREAM_STATUS_RUNNING;
}
for (j = 0; j < chip->nb_streams_play; j++) {
stream = &chip->playback_stream[j];
if (stream->status == PCXHR_STREAM_STATUS_STARTED) {
/* playback will already have advanced ! */
stream->timer_period_frag += mgr->granularity;
stream->status = PCXHR_STREAM_STATUS_RUNNING;
}
}
}
mutex_unlock(&mgr->lock);
mutex_unlock(&mgr->setup_mutex);
#ifdef CONFIG_SND_DEBUG_VERBOSE
stop_time = ktime_get();
diff_time = ktime_sub(stop_time, start_time);
dev_dbg(&mgr->pci->dev, "***TRIGGER START*** TIME = %ld (err = %x)\n",
(long)(ktime_to_ns(diff_time)), err);
#endif
}
/*
* trigger callback
*/
static int pcxhr_trigger(struct snd_pcm_substream *subs, int cmd)
{
struct pcxhr_stream *stream;
struct snd_pcm_substream *s;
struct snd_pcxhr *chip = snd_pcm_substream_chip(subs);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
dev_dbg(chip->card->dev, "SNDRV_PCM_TRIGGER_START\n");
if (snd_pcm_stream_linked(subs)) {
snd_pcm_group_for_each_entry(s, subs) {
if (snd_pcm_substream_chip(s) != chip)
continue;
stream = s->runtime->private_data;
stream->status =
PCXHR_STREAM_STATUS_SCHEDULE_RUN;
snd_pcm_trigger_done(s, subs);
}
pcxhr_start_linked_stream(chip->mgr);
} else {
stream = subs->runtime->private_data;
dev_dbg(chip->card->dev, "Only one Substream %c %d\n",
stream->pipe->is_capture ? 'C' : 'P',
stream->pipe->first_audio);
if (pcxhr_set_format(stream))
return -EINVAL;
if (pcxhr_update_r_buffer(stream))
return -EINVAL;
stream->status = PCXHR_STREAM_STATUS_SCHEDULE_RUN;
if (pcxhr_set_stream_state(chip, stream))
return -EINVAL;
stream->status = PCXHR_STREAM_STATUS_RUNNING;
}
break;
case SNDRV_PCM_TRIGGER_STOP:
dev_dbg(chip->card->dev, "SNDRV_PCM_TRIGGER_STOP\n");
snd_pcm_group_for_each_entry(s, subs) {
stream = s->runtime->private_data;
stream->status = PCXHR_STREAM_STATUS_SCHEDULE_STOP;
if (pcxhr_set_stream_state(chip, stream))
return -EINVAL;
snd_pcm_trigger_done(s, subs);
}
break;
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
/* TODO */
default:
return -EINVAL;
}
return 0;
}
static int pcxhr_hardware_timer(struct pcxhr_mgr *mgr, int start)
{
struct pcxhr_rmh rmh;
int err;
pcxhr_init_rmh(&rmh, CMD_SET_TIMER_INTERRUPT);
if (start) {
/* last dsp time invalid */
mgr->dsp_time_last = PCXHR_DSP_TIME_INVALID;
rmh.cmd[0] |= mgr->granularity;
}
err = pcxhr_send_msg(mgr, &rmh);
if (err < 0)
dev_err(&mgr->pci->dev, "error pcxhr_hardware_timer err(%x)\n",
err);
return err;
}
/*
* prepare callback for all pcms
*/
static int pcxhr_prepare(struct snd_pcm_substream *subs)
{
struct snd_pcxhr *chip = snd_pcm_substream_chip(subs);
struct pcxhr_mgr *mgr = chip->mgr;
int err = 0;
dev_dbg(chip->card->dev,
"pcxhr_prepare : period_size(%lx) periods(%x) buffer_size(%lx)\n",
subs->runtime->period_size, subs->runtime->periods,
subs->runtime->buffer_size);
mutex_lock(&mgr->setup_mutex);
do {
/* only the first stream can choose the sample rate */
/* set the clock only once (first stream) */
if (mgr->sample_rate != subs->runtime->rate) {
err = pcxhr_set_clock(mgr, subs->runtime->rate);
if (err)
break;
if (mgr->sample_rate == 0)
/* start the DSP-timer */
err = pcxhr_hardware_timer(mgr, 1);
mgr->sample_rate = subs->runtime->rate;
}
} while(0); /* do only once (so we can use break instead of goto) */
mutex_unlock(&mgr->setup_mutex);
return err;
}
/*
* HW_PARAMS callback for all pcms
*/
static int pcxhr_hw_params(struct snd_pcm_substream *subs,
struct snd_pcm_hw_params *hw)
{
struct snd_pcxhr *chip = snd_pcm_substream_chip(subs);
struct pcxhr_mgr *mgr = chip->mgr;
struct pcxhr_stream *stream = subs->runtime->private_data;
snd_pcm_format_t format;
int err;
int channels;
/* set up channels */
channels = params_channels(hw);
/* set up format for the stream */
format = params_format(hw);
mutex_lock(&mgr->setup_mutex);
stream->channels = channels;
stream->format = format;
/* allocate buffer */
err = snd_pcm_lib_malloc_pages(subs, params_buffer_bytes(hw));
mutex_unlock(&mgr->setup_mutex);
return err;
}
static int pcxhr_hw_free(struct snd_pcm_substream *subs)
{
snd_pcm_lib_free_pages(subs);
return 0;
}
/*
* CONFIGURATION SPACE for all pcms, mono pcm must update channels_max
*/
static struct snd_pcm_hardware pcxhr_caps =
{
.info = (SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_SYNC_START),
.formats = (SNDRV_PCM_FMTBIT_U8 |
SNDRV_PCM_FMTBIT_S16_LE |
SNDRV_PCM_FMTBIT_S16_BE |
SNDRV_PCM_FMTBIT_S24_3LE |
SNDRV_PCM_FMTBIT_S24_3BE |
SNDRV_PCM_FMTBIT_FLOAT_LE),
.rates = (SNDRV_PCM_RATE_CONTINUOUS |
SNDRV_PCM_RATE_8000_192000),
.rate_min = 8000,
.rate_max = 192000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = (32*1024),
/* 1 byte == 1 frame U8 mono (PCXHR_GRANULARITY is frames!) */
.period_bytes_min = (2*PCXHR_GRANULARITY),
.period_bytes_max = (16*1024),
.periods_min = 2,
.periods_max = (32*1024/PCXHR_GRANULARITY),
};
static int pcxhr_open(struct snd_pcm_substream *subs)
{
struct snd_pcxhr *chip = snd_pcm_substream_chip(subs);
struct pcxhr_mgr *mgr = chip->mgr;
struct snd_pcm_runtime *runtime = subs->runtime;
struct pcxhr_stream *stream;
int err;
mutex_lock(&mgr->setup_mutex);
/* copy the struct snd_pcm_hardware struct */
runtime->hw = pcxhr_caps;
if( subs->stream == SNDRV_PCM_STREAM_PLAYBACK ) {
dev_dbg(chip->card->dev, "pcxhr_open playback chip%d subs%d\n",
chip->chip_idx, subs->number);
stream = &chip->playback_stream[subs->number];
} else {
dev_dbg(chip->card->dev, "pcxhr_open capture chip%d subs%d\n",
chip->chip_idx, subs->number);
if (mgr->mono_capture)
runtime->hw.channels_max = 1;
else
runtime->hw.channels_min = 2;
stream = &chip->capture_stream[subs->number];
}
if (stream->status != PCXHR_STREAM_STATUS_FREE){
/* streams in use */
dev_err(chip->card->dev, "pcxhr_open chip%d subs%d in use\n",
chip->chip_idx, subs->number);
mutex_unlock(&mgr->setup_mutex);
return -EBUSY;
}
/* float format support is in some cases buggy on stereo cards */
if (mgr->is_hr_stereo)
runtime->hw.formats &= ~SNDRV_PCM_FMTBIT_FLOAT_LE;
/* buffer-size should better be multiple of period-size */
err = snd_pcm_hw_constraint_integer(runtime,
SNDRV_PCM_HW_PARAM_PERIODS);
if (err < 0) {
mutex_unlock(&mgr->setup_mutex);
return err;
}
/* if a sample rate is already used or fixed by external clock,
* the stream cannot change
*/
if (mgr->sample_rate)
runtime->hw.rate_min = runtime->hw.rate_max = mgr->sample_rate;
else {
if (mgr->use_clock_type != PCXHR_CLOCK_TYPE_INTERNAL) {
int external_rate;
if (pcxhr_get_external_clock(mgr, mgr->use_clock_type,
&external_rate) ||
external_rate == 0) {
/* cannot detect the external clock rate */
mutex_unlock(&mgr->setup_mutex);
return -EBUSY;
}
runtime->hw.rate_min = external_rate;
runtime->hw.rate_max = external_rate;
}
}
stream->status = PCXHR_STREAM_STATUS_OPEN;
stream->substream = subs;
stream->channels = 0; /* not configured yet */
runtime->private_data = stream;
/* better get a divisor of granularity values (96 or 192) */
snd_pcm_hw_constraint_step(runtime, 0,
SNDRV_PCM_HW_PARAM_BUFFER_SIZE, 32);
snd_pcm_hw_constraint_step(runtime, 0,
SNDRV_PCM_HW_PARAM_PERIOD_SIZE, 32);
snd_pcm_set_sync(subs);
mgr->ref_count_rate++;
mutex_unlock(&mgr->setup_mutex);
return 0;
}
static int pcxhr_close(struct snd_pcm_substream *subs)
{
struct snd_pcxhr *chip = snd_pcm_substream_chip(subs);
struct pcxhr_mgr *mgr = chip->mgr;
struct pcxhr_stream *stream = subs->runtime->private_data;
mutex_lock(&mgr->setup_mutex);
dev_dbg(chip->card->dev, "pcxhr_close chip%d subs%d\n",
chip->chip_idx, subs->number);
/* sample rate released */
if (--mgr->ref_count_rate == 0) {
mgr->sample_rate = 0; /* the sample rate is no more locked */
pcxhr_hardware_timer(mgr, 0); /* stop the DSP-timer */
}
stream->status = PCXHR_STREAM_STATUS_FREE;
stream->substream = NULL;
mutex_unlock(&mgr->setup_mutex);
return 0;
}
static snd_pcm_uframes_t pcxhr_stream_pointer(struct snd_pcm_substream *subs)
{
u_int32_t timer_period_frag;
int timer_buf_periods;
struct snd_pcxhr *chip = snd_pcm_substream_chip(subs);
struct snd_pcm_runtime *runtime = subs->runtime;
struct pcxhr_stream *stream = runtime->private_data;
mutex_lock(&chip->mgr->lock);
/* get the period fragment and the nb of periods in the buffer */
timer_period_frag = stream->timer_period_frag;
timer_buf_periods = stream->timer_buf_periods;
mutex_unlock(&chip->mgr->lock);
return (snd_pcm_uframes_t)((timer_buf_periods * runtime->period_size) +
timer_period_frag);
}
static const struct snd_pcm_ops pcxhr_ops = {
.open = pcxhr_open,
.close = pcxhr_close,
.ioctl = snd_pcm_lib_ioctl,
.prepare = pcxhr_prepare,
.hw_params = pcxhr_hw_params,
.hw_free = pcxhr_hw_free,
.trigger = pcxhr_trigger,
.pointer = pcxhr_stream_pointer,
};
/*
*/
int pcxhr_create_pcm(struct snd_pcxhr *chip)
{
int err;
struct snd_pcm *pcm;
char name[32];
sprintf(name, "pcxhr %d", chip->chip_idx);
if ((err = snd_pcm_new(chip->card, name, 0,
chip->nb_streams_play,
chip->nb_streams_capt, &pcm)) < 0) {
dev_err(chip->card->dev, "cannot create pcm %s\n", name);
return err;
}
pcm->private_data = chip;
if (chip->nb_streams_play)
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &pcxhr_ops);
if (chip->nb_streams_capt)
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &pcxhr_ops);
pcm->info_flags = 0;
pcm->nonatomic = true;
strcpy(pcm->name, name);
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(chip->mgr->pci),
32*1024, 32*1024);
chip->pcm = pcm;
return 0;
}
static int pcxhr_chip_free(struct snd_pcxhr *chip)
{
kfree(chip);
return 0;
}
static int pcxhr_chip_dev_free(struct snd_device *device)
{
struct snd_pcxhr *chip = device->device_data;
return pcxhr_chip_free(chip);
}
/*
*/
static int pcxhr_create(struct pcxhr_mgr *mgr,
struct snd_card *card, int idx)
{
int err;
struct snd_pcxhr *chip;
static struct snd_device_ops ops = {
.dev_free = pcxhr_chip_dev_free,
};
chip = kzalloc(sizeof(*chip), GFP_KERNEL);
if (! chip) {
dev_err(card->dev, "cannot allocate chip\n");
return -ENOMEM;
}
chip->card = card;
chip->chip_idx = idx;
chip->mgr = mgr;
if (idx < mgr->playback_chips)
/* stereo or mono streams */
chip->nb_streams_play = PCXHR_PLAYBACK_STREAMS;
if (idx < mgr->capture_chips) {
if (mgr->mono_capture)
chip->nb_streams_capt = 2; /* 2 mono streams */
else
chip->nb_streams_capt = 1; /* or 1 stereo stream */
}
if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops)) < 0) {
pcxhr_chip_free(chip);
return err;
}
mgr->chip[idx] = chip;
return 0;
}
/* proc interface */
static void pcxhr_proc_info(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_pcxhr *chip = entry->private_data;
struct pcxhr_mgr *mgr = chip->mgr;
snd_iprintf(buffer, "\n%s\n", mgr->longname);
/* stats available when embedded DSP is running */
if (mgr->dsp_loaded & (1 << PCXHR_FIRMWARE_DSP_MAIN_INDEX)) {
struct pcxhr_rmh rmh;
short ver_maj = (mgr->dsp_version >> 16) & 0xff;
short ver_min = (mgr->dsp_version >> 8) & 0xff;
short ver_build = mgr->dsp_version & 0xff;
snd_iprintf(buffer, "module version %s\n",
PCXHR_DRIVER_VERSION_STRING);
snd_iprintf(buffer, "dsp version %d.%d.%d\n",
ver_maj, ver_min, ver_build);
if (mgr->board_has_analog)
snd_iprintf(buffer, "analog io available\n");
else
snd_iprintf(buffer, "digital only board\n");
/* calc cpu load of the dsp */
pcxhr_init_rmh(&rmh, CMD_GET_DSP_RESOURCES);
if( ! pcxhr_send_msg(mgr, &rmh) ) {
int cur = rmh.stat[0];
int ref = rmh.stat[1];
if (ref > 0) {
if (mgr->sample_rate_real != 0 &&
mgr->sample_rate_real != 48000) {
ref = (ref * 48000) /
mgr->sample_rate_real;
if (mgr->sample_rate_real >=
PCXHR_IRQ_TIMER_FREQ)
ref *= 2;
}
cur = 100 - (100 * cur) / ref;
snd_iprintf(buffer, "cpu load %d%%\n", cur);
snd_iprintf(buffer, "buffer pool %d/%d\n",
rmh.stat[2], rmh.stat[3]);
}
}
snd_iprintf(buffer, "dma granularity : %d\n",
mgr->granularity);
snd_iprintf(buffer, "dsp time errors : %d\n",
mgr->dsp_time_err);
snd_iprintf(buffer, "dsp async pipe xrun errors : %d\n",
mgr->async_err_pipe_xrun);
snd_iprintf(buffer, "dsp async stream xrun errors : %d\n",
mgr->async_err_stream_xrun);
snd_iprintf(buffer, "dsp async last other error : %x\n",
mgr->async_err_other_last);
/* debug zone dsp */
rmh.cmd[0] = 0x4200 + PCXHR_SIZE_MAX_STATUS;
rmh.cmd_len = 1;
rmh.stat_len = PCXHR_SIZE_MAX_STATUS;
rmh.dsp_stat = 0;
rmh.cmd_idx = CMD_LAST_INDEX;
if( ! pcxhr_send_msg(mgr, &rmh) ) {
int i;
if (rmh.stat_len > 8)
rmh.stat_len = 8;
for (i = 0; i < rmh.stat_len; i++)
snd_iprintf(buffer, "debug[%02d] = %06x\n",
i, rmh.stat[i]);
}
} else
snd_iprintf(buffer, "no firmware loaded\n");
snd_iprintf(buffer, "\n");
}
static void pcxhr_proc_sync(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_pcxhr *chip = entry->private_data;
struct pcxhr_mgr *mgr = chip->mgr;
static const char *textsHR22[3] = {
"Internal", "AES Sync", "AES 1"
};
static const char *textsPCXHR[7] = {
"Internal", "Word", "AES Sync",
"AES 1", "AES 2", "AES 3", "AES 4"
};
const char **texts;
int max_clock;
if (mgr->is_hr_stereo) {
texts = textsHR22;
max_clock = HR22_CLOCK_TYPE_MAX;
} else {
texts = textsPCXHR;
max_clock = PCXHR_CLOCK_TYPE_MAX;
}
snd_iprintf(buffer, "\n%s\n", mgr->longname);
snd_iprintf(buffer, "Current Sample Clock\t: %s\n",
texts[mgr->cur_clock_type]);
snd_iprintf(buffer, "Current Sample Rate\t= %d\n",
mgr->sample_rate_real);
/* commands available when embedded DSP is running */
if (mgr->dsp_loaded & (1 << PCXHR_FIRMWARE_DSP_MAIN_INDEX)) {
int i, err, sample_rate;
for (i = 1; i <= max_clock; i++) {
err = pcxhr_get_external_clock(mgr, i, &sample_rate);
if (err)
break;
snd_iprintf(buffer, "%s Clock\t\t= %d\n",
texts[i], sample_rate);
}
} else
snd_iprintf(buffer, "no firmware loaded\n");
snd_iprintf(buffer, "\n");
}
static void pcxhr_proc_gpio_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_pcxhr *chip = entry->private_data;
struct pcxhr_mgr *mgr = chip->mgr;
/* commands available when embedded DSP is running */
if (mgr->dsp_loaded & (1 << PCXHR_FIRMWARE_DSP_MAIN_INDEX)) {
/* gpio ports on stereo boards only available */
int value = 0;
hr222_read_gpio(mgr, 1, &value); /* GPI */
snd_iprintf(buffer, "GPI: 0x%x\n", value);
hr222_read_gpio(mgr, 0, &value); /* GP0 */
snd_iprintf(buffer, "GPO: 0x%x\n", value);
} else
snd_iprintf(buffer, "no firmware loaded\n");
snd_iprintf(buffer, "\n");
}
static void pcxhr_proc_gpo_write(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_pcxhr *chip = entry->private_data;
struct pcxhr_mgr *mgr = chip->mgr;
char line[64];
int value;
/* commands available when embedded DSP is running */
if (!(mgr->dsp_loaded & (1 << PCXHR_FIRMWARE_DSP_MAIN_INDEX)))
return;
while (!snd_info_get_line(buffer, line, sizeof(line))) {
if (sscanf(line, "GPO: 0x%x", &value) != 1)
continue;
hr222_write_gpo(mgr, value); /* GP0 */
}
}
/* Access to the results of the CMD_GET_TIME_CODE RMH */
#define TIME_CODE_VALID_MASK 0x00800000
#define TIME_CODE_NEW_MASK 0x00400000
#define TIME_CODE_BACK_MASK 0x00200000
#define TIME_CODE_WAIT_MASK 0x00100000
/* Values for the CMD_MANAGE_SIGNAL RMH */
#define MANAGE_SIGNAL_TIME_CODE 0x01
#define MANAGE_SIGNAL_MIDI 0x02
/* linear time code read proc*/
static void pcxhr_proc_ltc(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_pcxhr *chip = entry->private_data;
struct pcxhr_mgr *mgr = chip->mgr;
struct pcxhr_rmh rmh;
unsigned int ltcHrs, ltcMin, ltcSec, ltcFrm;
int err;
/* commands available when embedded DSP is running */
if (!(mgr->dsp_loaded & (1 << PCXHR_FIRMWARE_DSP_MAIN_INDEX))) {
snd_iprintf(buffer, "no firmware loaded\n");
return;
}
if (!mgr->capture_ltc) {
pcxhr_init_rmh(&rmh, CMD_MANAGE_SIGNAL);
rmh.cmd[0] |= MANAGE_SIGNAL_TIME_CODE;
err = pcxhr_send_msg(mgr, &rmh);
if (err) {
snd_iprintf(buffer, "ltc not activated (%d)\n", err);
return;
}
if (mgr->is_hr_stereo)
hr222_manage_timecode(mgr, 1);
else
pcxhr_write_io_num_reg_cont(mgr, REG_CONT_VALSMPTE,
REG_CONT_VALSMPTE, NULL);
mgr->capture_ltc = 1;
}
pcxhr_init_rmh(&rmh, CMD_GET_TIME_CODE);
err = pcxhr_send_msg(mgr, &rmh);
if (err) {
snd_iprintf(buffer, "ltc read error (err=%d)\n", err);
return ;
}
ltcHrs = 10*((rmh.stat[0] >> 8) & 0x3) + (rmh.stat[0] & 0xf);
ltcMin = 10*((rmh.stat[1] >> 16) & 0x7) + ((rmh.stat[1] >> 8) & 0xf);
ltcSec = 10*(rmh.stat[1] & 0x7) + ((rmh.stat[2] >> 16) & 0xf);
ltcFrm = 10*((rmh.stat[2] >> 8) & 0x3) + (rmh.stat[2] & 0xf);
snd_iprintf(buffer, "timecode: %02u:%02u:%02u-%02u\n",
ltcHrs, ltcMin, ltcSec, ltcFrm);
snd_iprintf(buffer, "raw: 0x%04x%06x%06x\n", rmh.stat[0] & 0x00ffff,
rmh.stat[1] & 0xffffff, rmh.stat[2] & 0xffffff);
/*snd_iprintf(buffer, "dsp ref time: 0x%06x%06x\n",
rmh.stat[3] & 0xffffff, rmh.stat[4] & 0xffffff);*/
if (!(rmh.stat[0] & TIME_CODE_VALID_MASK)) {
snd_iprintf(buffer, "warning: linear timecode not valid\n");
}
}
static void pcxhr_proc_init(struct snd_pcxhr *chip)
{
struct snd_info_entry *entry;
if (! snd_card_proc_new(chip->card, "info", &entry))
snd_info_set_text_ops(entry, chip, pcxhr_proc_info);
if (! snd_card_proc_new(chip->card, "sync", &entry))
snd_info_set_text_ops(entry, chip, pcxhr_proc_sync);
/* gpio available on stereo sound cards only */
if (chip->mgr->is_hr_stereo &&
!snd_card_proc_new(chip->card, "gpio", &entry)) {
snd_info_set_text_ops(entry, chip, pcxhr_proc_gpio_read);
entry->c.text.write = pcxhr_proc_gpo_write;
entry->mode |= S_IWUSR;
}
if (!snd_card_proc_new(chip->card, "ltc", &entry))
snd_info_set_text_ops(entry, chip, pcxhr_proc_ltc);
}
/* end of proc interface */
/*
* release all the cards assigned to a manager instance
*/
static int pcxhr_free(struct pcxhr_mgr *mgr)
{
unsigned int i;
for (i = 0; i < mgr->num_cards; i++) {
if (mgr->chip[i])
snd_card_free(mgr->chip[i]->card);
}
/* reset board if some firmware was loaded */
if(mgr->dsp_loaded) {
pcxhr_reset_board(mgr);
dev_dbg(&mgr->pci->dev, "reset pcxhr !\n");
}
/* release irq */
if (mgr->irq >= 0)
free_irq(mgr->irq, mgr);
pci_release_regions(mgr->pci);
/* free hostport purgebuffer */
if (mgr->hostport.area) {
snd_dma_free_pages(&mgr->hostport);
mgr->hostport.area = NULL;
}
kfree(mgr->prmh);
pci_disable_device(mgr->pci);
kfree(mgr);
return 0;
}
/*
* probe function - creates the card manager
*/
static int pcxhr_probe(struct pci_dev *pci,
const struct pci_device_id *pci_id)
{
static int dev;
struct pcxhr_mgr *mgr;
unsigned int i;
int err;
size_t size;
char *card_name;
if (dev >= SNDRV_CARDS)
return -ENODEV;
if (! enable[dev]) {
dev++;
return -ENOENT;
}
/* enable PCI device */
if ((err = pci_enable_device(pci)) < 0)
return err;
pci_set_master(pci);
/* check if we can restrict PCI DMA transfers to 32 bits */
if (dma_set_mask(&pci->dev, DMA_BIT_MASK(32)) < 0) {
dev_err(&pci->dev,
"architecture does not support 32bit PCI busmaster DMA\n");
pci_disable_device(pci);
return -ENXIO;
}
/* alloc card manager */
mgr = kzalloc(sizeof(*mgr), GFP_KERNEL);
if (! mgr) {
pci_disable_device(pci);
return -ENOMEM;
}
if (snd_BUG_ON(pci_id->driver_data >= PCI_ID_LAST)) {
kfree(mgr);
pci_disable_device(pci);
return -ENODEV;
}
card_name =
pcxhr_board_params[pci_id->driver_data].board_name;
mgr->playback_chips =
pcxhr_board_params[pci_id->driver_data].playback_chips;
mgr->capture_chips =
pcxhr_board_params[pci_id->driver_data].capture_chips;
mgr->fw_file_set =
pcxhr_board_params[pci_id->driver_data].fw_file_set;
mgr->firmware_num =
pcxhr_board_params[pci_id->driver_data].firmware_num;
mgr->mono_capture = mono[dev];
mgr->is_hr_stereo = (mgr->playback_chips == 1);
mgr->board_has_aes1 = PCXHR_BOARD_HAS_AES1(mgr);
mgr->board_aes_in_192k = !PCXHR_BOARD_AESIN_NO_192K(mgr);
if (mgr->is_hr_stereo)
mgr->granularity = PCXHR_GRANULARITY_HR22;
else
mgr->granularity = PCXHR_GRANULARITY;
/* resource assignment */
if ((err = pci_request_regions(pci, card_name)) < 0) {
kfree(mgr);
pci_disable_device(pci);
return err;
}
for (i = 0; i < 3; i++)
mgr->port[i] = pci_resource_start(pci, i);
mgr->pci = pci;
mgr->irq = -1;
if (request_threaded_irq(pci->irq, pcxhr_interrupt,
pcxhr_threaded_irq, IRQF_SHARED,
KBUILD_MODNAME, mgr)) {
dev_err(&pci->dev, "unable to grab IRQ %d\n", pci->irq);
pcxhr_free(mgr);
return -EBUSY;
}
mgr->irq = pci->irq;
sprintf(mgr->shortname, "Digigram %s", card_name);
sprintf(mgr->longname, "%s at 0x%lx & 0x%lx, 0x%lx irq %i",
mgr->shortname,
mgr->port[0], mgr->port[1], mgr->port[2], mgr->irq);
/* ISR lock */
mutex_init(&mgr->lock);
mutex_init(&mgr->msg_lock);
/* init setup mutex*/
mutex_init(&mgr->setup_mutex);
mgr->prmh = kmalloc(sizeof(*mgr->prmh) +
sizeof(u32) * (PCXHR_SIZE_MAX_LONG_STATUS -
PCXHR_SIZE_MAX_STATUS),
GFP_KERNEL);
if (! mgr->prmh) {
pcxhr_free(mgr);
return -ENOMEM;
}
for (i=0; i < PCXHR_MAX_CARDS; i++) {
struct snd_card *card;
char tmpid[16];
int idx;
if (i >= max(mgr->playback_chips, mgr->capture_chips))
break;
mgr->num_cards++;
if (index[dev] < 0)
idx = index[dev];
else
idx = index[dev] + i;
snprintf(tmpid, sizeof(tmpid), "%s-%d",
id[dev] ? id[dev] : card_name, i);
err = snd_card_new(&pci->dev, idx, tmpid, THIS_MODULE,
0, &card);
if (err < 0) {
dev_err(&pci->dev, "cannot allocate the card %d\n", i);
pcxhr_free(mgr);
return err;
}
strcpy(card->driver, DRIVER_NAME);
sprintf(card->shortname, "%s [PCM #%d]", mgr->shortname, i);
sprintf(card->longname, "%s [PCM #%d]", mgr->longname, i);
if ((err = pcxhr_create(mgr, card, i)) < 0) {
snd_card_free(card);
pcxhr_free(mgr);
return err;
}
if (i == 0)
/* init proc interface only for chip0 */
pcxhr_proc_init(mgr->chip[i]);
if ((err = snd_card_register(card)) < 0) {
pcxhr_free(mgr);
return err;
}
}
/* create hostport purgebuffer */
size = PAGE_ALIGN(sizeof(struct pcxhr_hostport));
if (snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(pci),
size, &mgr->hostport) < 0) {
pcxhr_free(mgr);
return -ENOMEM;
}
/* init purgebuffer */
memset(mgr->hostport.area, 0, size);
/* create a DSP loader */
err = pcxhr_setup_firmware(mgr);
if (err < 0) {
pcxhr_free(mgr);
return err;
}
pci_set_drvdata(pci, mgr);
dev++;
return 0;
}
static void pcxhr_remove(struct pci_dev *pci)
{
pcxhr_free(pci_get_drvdata(pci));
}
static struct pci_driver pcxhr_driver = {
.name = KBUILD_MODNAME,
.id_table = pcxhr_ids,
.probe = pcxhr_probe,
.remove = pcxhr_remove,
};
module_pci_driver(pcxhr_driver);
| null | null | null | null | 78,537 |
43,386 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 208,381 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | /* atmclip.h - Classical IP over ATM */
/* Written 1995-1998 by Werner Almesberger, EPFL LRC/ICA */
#ifndef LINUX_ATMCLIP_H
#define LINUX_ATMCLIP_H
#include <linux/sockios.h>
#include <linux/atmioc.h>
#define RFC1483LLC_LEN 8 /* LLC+OUI+PID = 8 */
#define RFC1626_MTU 9180 /* RFC1626 default MTU */
#define CLIP_DEFAULT_IDLETIMER 1200 /* 20 minutes, see RFC1755 */
#define CLIP_CHECK_INTERVAL 10 /* check every ten seconds */
#define SIOCMKCLIP _IO('a',ATMIOC_CLIP) /* create IP interface */
#endif
| null | null | null | null | 116,728 |
20,011 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 20,011 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright (c) 2016 The Chromium 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 CONTENT_PUBLIC_COMMON_BROWSER_CONTROLS_STATE_H_
#define CONTENT_PUBLIC_COMMON_BROWSER_CONTROLS_STATE_H_
namespace content {
// A Java counterpart will be generated for this enum.
// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.content_public.common
enum BrowserControlsState {
BROWSER_CONTROLS_STATE_SHOWN = 1,
BROWSER_CONTROLS_STATE_HIDDEN = 2,
BROWSER_CONTROLS_STATE_BOTH = 3,
BROWSER_CONTROLS_STATE_LAST = BROWSER_CONTROLS_STATE_BOTH,
};
} // namespace content
#endif // CONTENT_PUBLIC_COMMON_BROWSER_CONTROLS_STATE_H_
| null | null | null | null | 16,874 |
66,217 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 66,217 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2016 The Chromium 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 CHROME_BROWSER_MEDIA_ROUTER_MOJO_MEDIA_ROUTE_PROVIDER_UTIL_WIN_H_
#define CHROME_BROWSER_MEDIA_ROUTER_MOJO_MEDIA_ROUTE_PROVIDER_UTIL_WIN_H_
#include "base/callback.h"
namespace media_router {
// Asynchronously checks whether there will be a firewall prompt for using local
// ports on Windows. |callback| will be called with the result where |true|
// means that local ports can be used without triggering a firewall prompt.
void CanFirewallUseLocalPorts(base::OnceCallback<void(bool)> callback);
} // namespace media_router
#endif // CHROME_BROWSER_MEDIA_ROUTER_MOJO_MEDIA_ROUTE_PROVIDER_UTIL_WIN_H_
| null | null | null | null | 63,080 |
24,524 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 24,524 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright (c) 2011 The Chromium 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 COURGETTE_ASSEMBLY_PROGRAM_H_
#define COURGETTE_ASSEMBLY_PROGRAM_H_
#include <stdint.h>
#include <vector>
#include "base/macros.h"
#include "courgette/courgette.h"
#include "courgette/image_utils.h"
#include "courgette/instruction_utils.h"
#include "courgette/label_manager.h"
#include "courgette/memory_allocator.h" // For CheckBool.
namespace courgette {
class EncodedProgram;
// An AssemblyProgram stores Labels extracted from an executable file, and
// (optionally) Label annotations. It is initialized by a Disassembler, but
// stores separate state so that the Disassembler can be deleted. Typical usage:
//
// * The Disassembler calls PrecomputeLabels() and injects RVAs for abs32/rel32
// references. These are used to initialize labels.
// * The Disassembler calls DefaultAssignIndexes() to assign addresses to
// positions in the address tables.
// * [Optional step]
// * The Disassembler can use Labels in AssemblyProgram to convert the
// executable file to an EncodedProgram, serialized to an output stream.
// * Later, the Disassembler can use the AssemblyProgram to can be deserialized
// and assembled into the original executable file via an EncodedProgram.
//
// The optional step is to adjust Labels in the AssemblyProgram. One form of
// adjustment is to assign indexes in such a way as to make the EncodedProgram
// for an executable look more like the EncodedProgram for another exectuable.
// The adjustment process should call UnassignIndexes(), do its own assignment,
// and then call AssignRemainingIndexes() to ensure all indexes are assigned.
class AssemblyProgram {
public:
AssemblyProgram(ExecutableType kind, uint64_t image_base);
~AssemblyProgram();
ExecutableType kind() const { return kind_; }
const std::vector<Label*>& abs32_label_annotations() const {
return abs32_label_annotations_;
}
const std::vector<Label*>& rel32_label_annotations() const {
return rel32_label_annotations_;
}
// Traverses RVAs in |abs32_visitor| and |rel32_visitor| to precompute Labels.
void PrecomputeLabels(RvaVisitor* abs32_visitor, RvaVisitor* rel32_visitor);
// Removes underused Labels. Thresholds used (0 = no trimming) is
// architecture-dependent.
void TrimLabels();
void UnassignIndexes();
void DefaultAssignIndexes();
void AssignRemainingIndexes();
// Looks up abs32 label. Returns null if none found.
Label* FindAbs32Label(RVA rva);
// Looks up rel32 label. Returns null if none found.
Label* FindRel32Label(RVA rva);
// Uses |gen| to initializes |*_label_annotations_|.
CheckBool AnnotateLabels(const InstructionGenerator& gen);
// Initializes |encoded| by injecting basic data and Label data.
bool PrepareEncodedProgram(EncodedProgram* encoded) const;
private:
static const int kLabelLowerLimit;
// Looks up a label or creates a new one. Might return NULL.
Label* FindLabel(RVA rva, RVAToLabel* labels);
const ExecutableType kind_;
const uint64_t image_base_; // Desired or mandated base address of image.
// Storage and lookup of Labels associated with target addresses. We use
// separate abs32 and rel32 labels.
LabelManager abs32_label_manager_;
LabelManager rel32_label_manager_;
// Label pointers for each abs32 and rel32 location, sorted by file offset.
// These are used by Label adjustment during patch generation.
std::vector<Label*> abs32_label_annotations_;
std::vector<Label*> rel32_label_annotations_;
DISALLOW_COPY_AND_ASSIGN(AssemblyProgram);
};
} // namespace courgette
#endif // COURGETTE_ASSEMBLY_PROGRAM_H_
| null | null | null | null | 21,387 |
41,344 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 206,339 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | /*
* Filename: ks0108.h
* Version: 0.1.0
* Description: ks0108 LCD Controller driver header
* License: GPLv2
*
* Author: Copyright (C) Miguel Ojeda Sandonis
* Date: 2006-10-31
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#ifndef _KS0108_H_
#define _KS0108_H_
/* Write a byte to the data port */
extern void ks0108_writedata(unsigned char byte);
/* Write a byte to the control port */
extern void ks0108_writecontrol(unsigned char byte);
/* Set the controller's current display state (0..1) */
extern void ks0108_displaystate(unsigned char state);
/* Set the controller's current startline (0..63) */
extern void ks0108_startline(unsigned char startline);
/* Set the controller's current address (0..63) */
extern void ks0108_address(unsigned char address);
/* Set the controller's current page (0..7) */
extern void ks0108_page(unsigned char page);
/* Is the module inited? */
extern unsigned char ks0108_isinited(void);
#endif /* _KS0108_H_ */
| null | null | null | null | 114,686 |
52,299 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 52,299 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2013 The Chromium 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 MEDIA_AUDIO_PULSE_AUDIO_MANAGER_PULSE_H_
#define MEDIA_AUDIO_PULSE_AUDIO_MANAGER_PULSE_H_
#include <pulse/pulseaudio.h>
#include <string>
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "media/audio/audio_manager_base.h"
namespace media {
class MEDIA_EXPORT AudioManagerPulse : public AudioManagerBase {
public:
AudioManagerPulse(std::unique_ptr<AudioThread> audio_thread,
AudioLogFactory* audio_log_factory,
pa_threaded_mainloop* pa_mainloop,
pa_context* pa_context);
~AudioManagerPulse() override;
// Implementation of AudioManager.
bool HasAudioOutputDevices() override;
bool HasAudioInputDevices() override;
void GetAudioInputDeviceNames(AudioDeviceNames* device_names) override;
void GetAudioOutputDeviceNames(AudioDeviceNames* device_names) override;
AudioParameters GetInputStreamParameters(
const std::string& device_id) override;
const char* GetName() override;
// Implementation of AudioManagerBase.
AudioOutputStream* MakeLinearOutputStream(
const AudioParameters& params,
const LogCallback& log_callback) override;
AudioOutputStream* MakeLowLatencyOutputStream(
const AudioParameters& params,
const std::string& device_id,
const LogCallback& log_callback) override;
AudioInputStream* MakeLinearInputStream(
const AudioParameters& params,
const std::string& device_id,
const LogCallback& log_callback) override;
AudioInputStream* MakeLowLatencyInputStream(
const AudioParameters& params,
const std::string& device_id,
const LogCallback& log_callback) override;
protected:
void ShutdownOnAudioThread() override;
AudioParameters GetPreferredOutputStreamParameters(
const std::string& output_device_id,
const AudioParameters& input_params) override;
private:
void GetAudioDeviceNames(bool input, media::AudioDeviceNames* device_names);
// Callback to get the devices' info like names, used by GetInputDevices().
static void InputDevicesInfoCallback(pa_context* context,
const pa_source_info* info,
int error, void* user_data);
static void OutputDevicesInfoCallback(pa_context* context,
const pa_sink_info* info,
int error, void* user_data);
// Callback to get the native sample rate of PulseAudio, used by
// UpdateNativeAudioHardwareInfo().
static void AudioHardwareInfoCallback(pa_context* context,
const pa_server_info* info,
void* user_data);
// Called by MakeLinearOutputStream and MakeLowLatencyOutputStream.
AudioOutputStream* MakeOutputStream(const AudioParameters& params,
const std::string& device_id);
// Called by MakeLinearInputStream and MakeLowLatencyInputStream.
AudioInputStream* MakeInputStream(const AudioParameters& params,
const std::string& device_id);
// Updates |native_input_sample_rate_| and |native_channel_count_|.
void UpdateNativeAudioHardwareInfo();
pa_threaded_mainloop* input_mainloop_;
pa_context* input_context_;
AudioDeviceNames* devices_;
int native_input_sample_rate_;
int native_channel_count_;
DISALLOW_COPY_AND_ASSIGN(AudioManagerPulse);
};
} // namespace media
#endif // MEDIA_AUDIO_PULSE_AUDIO_MANAGER_PULSE_H_
| null | null | null | null | 49,162 |
16,884 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 16,884 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2014 The Chromium 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 <stddef.h>
#include <limits>
#include <vector>
#include "base/memory/ptr_util.h"
#include "base/numerics/math_constants.h"
#include "base/stl_util.h"
#include "build/build_config.h"
#include "components/viz/service/display/bsp_compare_result.h"
#include "components/viz/service/display/draw_polygon.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/transform.h"
namespace viz {
#if !defined(OS_WIN)
void DrawPolygon::RecomputeNormalForTesting() {
ConstructNormal();
}
#endif
static int sign(float v) {
static const float epsilon = 0.00001f;
if (v > epsilon)
return 1;
if (v < -epsilon)
return -1;
return 0;
}
bool IsPlanarForTesting(const DrawPolygon& p) {
static const float epsilon = 0.00001f;
for (size_t i = 1; i < p.points_.size(); i++) {
if (gfx::DotProduct(p.points_[i] - p.points_[0], p.normal_) > epsilon)
return false;
}
return true;
}
bool IsConvexForTesting(const DrawPolygon& p) {
if (p.points_.size() < 3)
return true;
gfx::Vector3dF prev =
p.points_[p.points_.size() - 1] - p.points_[p.points_.size() - 2];
gfx::Vector3dF next = p.points_[0] - p.points_[p.points_.size() - 1];
int ccw = sign(gfx::DotProduct(CrossProduct(prev, next), p.normal_));
for (size_t i = 1; i < p.points_.size(); i++) {
prev = next;
next = p.points_[i] - p.points_[i - 1];
int next_sign = sign(gfx::DotProduct(CrossProduct(prev, next), p.normal_));
if (ccw == 0)
ccw = next_sign;
if (next_sign != 0 && next_sign != ccw)
return false;
}
return true;
}
namespace {
#define CREATE_NEW_DRAW_POLYGON(name, points_vector, normal, polygon_id) \
DrawPolygon name(NULL, points_vector, normal, polygon_id)
#define CREATE_NEW_DRAW_POLYGON_PTR(name, points_vector, normal, polygon_id) \
std::unique_ptr<DrawPolygon> name(std::make_unique<DrawPolygon>( \
nullptr, points_vector, normal, polygon_id))
#define CREATE_TEST_DRAW_FORWARD_POLYGON(name, points_vector, id) \
DrawPolygon name(NULL, points_vector, gfx::Vector3dF(0, 0, 1.0f), id); \
name.RecomputeNormalForTesting()
#define CREATE_TEST_DRAW_REVERSE_POLYGON(name, points_vector, id) \
DrawPolygon name(NULL, points_vector, gfx::Vector3dF(0, 0, -1.0f), id); \
name.RecomputeNormalForTesting()
#define EXPECT_FLOAT_WITHIN_EPSILON_OF(a, b) \
LOG(WARNING) << "a=" << a << " b= " << b << " diff=" << std::abs(a - b); \
EXPECT_TRUE(std::abs(a - b) < std::numeric_limits<float>::epsilon());
#define EXPECT_POINT_EQ(point_a, point_b) \
EXPECT_FLOAT_EQ(point_a.x(), point_b.x()); \
EXPECT_FLOAT_EQ(point_a.y(), point_b.y()); \
EXPECT_FLOAT_EQ(point_a.z(), point_b.z());
#define EXPECT_NORMAL(poly, n_x, n_y, n_z) \
EXPECT_FLOAT_WITHIN_EPSILON_OF(poly.normal().x(), n_x); \
EXPECT_FLOAT_WITHIN_EPSILON_OF(poly.normal().y(), n_y); \
EXPECT_FLOAT_WITHIN_EPSILON_OF(poly.normal().z(), n_z);
static void ValidatePoints(const DrawPolygon& polygon,
const std::vector<gfx::Point3F>& points) {
EXPECT_EQ(polygon.points().size(), points.size());
for (size_t i = 0; i < points.size(); i++) {
EXPECT_POINT_EQ(polygon.points()[i], points[i]);
}
}
static void ValidatePointsWithinDeltaOf(const DrawPolygon& polygon,
const std::vector<gfx::Point3F>& points,
float delta) {
EXPECT_EQ(polygon.points().size(), points.size());
for (size_t i = 0; i < points.size(); i++) {
EXPECT_LE((polygon.points()[i] - points[i]).Length(), delta);
}
}
// A simple square in a plane.
TEST(DrawPolygonConstructionTest, NormalNormal) {
gfx::Transform Identity;
DrawPolygon polygon(nullptr, gfx::RectF(10.0f, 10.0f), Identity, 1);
EXPECT_NORMAL(polygon, 0.0f, 0.0f, 1.0f);
}
// More complicated shapes.
TEST(DrawPolygonConstructionTest, TestNormal) {
std::vector<gfx::Point3F> vertices;
vertices.push_back(gfx::Point3F(0.0f, 10.0f, 0.0f));
vertices.push_back(gfx::Point3F(0.0f, 0.0f, 0.0f));
vertices.push_back(gfx::Point3F(10.0f, 0.0f, 0.0f));
vertices.push_back(gfx::Point3F(10.0f, 10.0f, 0.0f));
CREATE_TEST_DRAW_FORWARD_POLYGON(polygon, vertices, 1);
EXPECT_NORMAL(polygon, 0.0f, 0.0f, 1.0f);
}
TEST(DrawPolygonConstructionTest, ClippedNormal) {
std::vector<gfx::Point3F> vertices;
vertices.push_back(gfx::Point3F(0.1f, 10.0f, 0.0f));
vertices.push_back(gfx::Point3F(0.0f, 9.9f, 0.0f));
vertices.push_back(gfx::Point3F(0.0f, 10.0f, 0.0f));
vertices.push_back(gfx::Point3F(0.0f, 0.0f, 0.0f));
vertices.push_back(gfx::Point3F(10.0f, 0.0f, 0.0f));
vertices.push_back(gfx::Point3F(10.0f, 10.0f, 0.0f));
CREATE_TEST_DRAW_FORWARD_POLYGON(polygon, vertices, 1);
EXPECT_NORMAL(polygon, 0.0f, 0.0f, 1.0f);
}
TEST(DrawPolygonConstructionTest, SlimTriangleNormal) {
std::vector<gfx::Point3F> vertices;
vertices.push_back(gfx::Point3F(0.0f, 0.0f, 0.0f));
vertices.push_back(gfx::Point3F(5000.0f, 0.0f, 0.0f));
vertices.push_back(gfx::Point3F(10000.0f, 1.0f, 0.0f));
CREATE_TEST_DRAW_FORWARD_POLYGON(polygon, vertices, 2);
EXPECT_NORMAL(polygon, 0.0f, 0.0f, 1.0f);
}
TEST(DrawPolygonConstructionTest, ManyVertexNormal) {
std::vector<gfx::Point3F> vertices_c;
std::vector<gfx::Point3F> vertices_d;
for (int i = 0; i < 100; i++) {
const double step = i * base::kPiDouble / 50;
vertices_c.push_back(gfx::Point3F(cos(step), sin(step), 0.0f));
vertices_d.push_back(
gfx::Point3F(cos(step) + 99.0f, sin(step) + 99.0f, 100.0f));
}
CREATE_TEST_DRAW_FORWARD_POLYGON(polygon_c, vertices_c, 3);
EXPECT_NORMAL(polygon_c, 0.0f, 0.0f, 1.0f);
CREATE_TEST_DRAW_FORWARD_POLYGON(polygon_d, vertices_d, 4);
EXPECT_NORMAL(polygon_d, 0.0f, 0.0f, 1.0f);
}
// A simple rect being transformed.
TEST(DrawPolygonConstructionTest, SimpleNormal) {
gfx::RectF src(-0.1f, -10.0f, 0.2f, 20.0f);
gfx::Transform transform_i(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
DrawPolygon polygon_i(nullptr, src, transform_i, 1);
EXPECT_NORMAL(polygon_i, 0.0f, 0.0f, 1.0f);
}
TEST(DrawPolygonConstructionTest, DISABLED_NormalInvertXY) {
gfx::RectF src(-0.1f, -10.0f, 0.2f, 20.0f);
gfx::Transform transform(0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
DrawPolygon polygon_a(nullptr, src, transform, 2);
EXPECT_NORMAL(polygon_a, 0.0f, 0.0f, 1.0f);
}
TEST(DrawPolygonConstructionTest, DISABLED_NormalInvertXZ) {
gfx::RectF src(-0.1f, -10.0f, 0.2f, 20.0f);
gfx::Transform transform(0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1);
DrawPolygon polygon_b(nullptr, src, transform, 3);
EXPECT_NORMAL(polygon_b, 1.0f, 0.0f, 0.0f);
}
TEST(DrawPolygonConstructionTest, DISABLED_NormalInvertYZ) {
gfx::RectF src(-0.1f, -10.0f, 0.2f, 20.0f);
gfx::Transform transform(1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1);
DrawPolygon polygon_c(nullptr, src, transform, 4);
EXPECT_NORMAL(polygon_c, 0.0f, 1.0f, 0.0f);
}
TEST(DrawPolygonConstructionTest, NormalRotate90) {
gfx::RectF src(-0.1f, -10.0f, 0.2f, 20.0f);
gfx::Transform transform(0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1);
DrawPolygon polygon_b(nullptr, src, transform, 3);
EXPECT_NORMAL(polygon_b, 0.0f, 0.0f, 1.0f);
}
TEST(DrawPolygonConstructionTest, InvertXNormal) {
gfx::RectF src(-0.1f, -10.0f, 0.2f, 20.0f);
gfx::Transform transform(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
DrawPolygon polygon_d(nullptr, src, transform, 5);
EXPECT_NORMAL(polygon_d, 0.0f, 0.0f, 1.0f);
}
TEST(DrawPolygonConstructionTest, InvertYNormal) {
gfx::RectF src(-0.1f, -10.0f, 0.2f, 20.0f);
gfx::Transform transform(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
DrawPolygon polygon_d(nullptr, src, transform, 5);
EXPECT_NORMAL(polygon_d, 0.0f, 0.0f, 1.0f);
}
TEST(DrawPolygonConstructionTest, InvertZNormal) {
gfx::RectF src(-0.1f, -10.0f, 0.2f, 20.0f);
gfx::Transform transform(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1);
DrawPolygon polygon_d(nullptr, src, transform, 5);
EXPECT_NORMAL(polygon_d, 0.0f, 0.0f, -1.0f);
}
// Two quads are nearly touching but definitely ordered. Second one should
// compare in front.
TEST(DrawPolygonSplitTest, NearlyTouchingOrder) {
std::vector<gfx::Point3F> vertices_a;
vertices_a.push_back(gfx::Point3F(0.0f, 10.0f, 0.0f));
vertices_a.push_back(gfx::Point3F(0.0f, 0.0f, 0.0f));
vertices_a.push_back(gfx::Point3F(10.0f, 0.0f, 0.0f));
vertices_a.push_back(gfx::Point3F(10.0f, 10.0f, 0.0f));
std::vector<gfx::Point3F> vertices_b;
vertices_b.push_back(gfx::Point3F(0.0f, 10.0f, -1.0f));
vertices_b.push_back(gfx::Point3F(0.0f, 0.0f, -1.0f));
vertices_b.push_back(gfx::Point3F(10.0f, 0.0f, -1.0f));
vertices_b.push_back(gfx::Point3F(10.0f, 10.0f, -1.0f));
gfx::Vector3dF normal(0.0f, 0.0f, 1.0f);
CREATE_NEW_DRAW_POLYGON(polygon_a, vertices_a, normal, 0);
CREATE_NEW_DRAW_POLYGON_PTR(polygon_b, vertices_b, normal, 1);
std::unique_ptr<DrawPolygon> front;
std::unique_ptr<DrawPolygon> back;
bool is_coplanar;
polygon_a.SplitPolygon(std::move(polygon_b), &front, &back, &is_coplanar);
EXPECT_EQ(is_coplanar, false);
EXPECT_EQ(front, nullptr);
EXPECT_NE(back, nullptr);
}
// Two quads are definitely not touching and so no split should occur.
TEST(DrawPolygonSplitTest, NotClearlyInFront) {
std::vector<gfx::Point3F> vertices_a;
vertices_a.push_back(gfx::Point3F(87.2f, 1185.0f, 0.9f));
vertices_a.push_back(gfx::Point3F(288.3f, 1185.0f, -0.7f));
vertices_a.push_back(gfx::Point3F(288.3f, 1196.0f, -0.7f));
vertices_a.push_back(gfx::Point3F(87.2f, 1196.0f, 0.9f));
gfx::Vector3dF normal_a = gfx::CrossProduct(vertices_a[1] - vertices_a[0],
vertices_a[1] - vertices_a[2]);
normal_a.Scale(1.0f / normal_a.Length());
std::vector<gfx::Point3F> vertices_b;
vertices_b.push_back(gfx::Point3F(62.1f, 1034.7f, 1.0f));
vertices_b.push_back(gfx::Point3F(313.4f, 1035.3f, -1.0f));
vertices_b.push_back(gfx::Point3F(313.4f, 1196.0f, -1.0f));
vertices_b.push_back(gfx::Point3F(62.1f, 1196.0f, 1.0f));
gfx::Vector3dF normal_b = gfx::CrossProduct(vertices_b[1] - vertices_b[0],
vertices_b[1] - vertices_b[2]);
normal_b.Scale(1.0f / normal_b.Length());
CREATE_NEW_DRAW_POLYGON(polygon_a, vertices_a, normal_a, 0);
CREATE_NEW_DRAW_POLYGON_PTR(polygon_b, vertices_b, normal_b, 1);
std::unique_ptr<DrawPolygon> front;
std::unique_ptr<DrawPolygon> back;
bool is_coplanar;
polygon_a.SplitPolygon(std::move(polygon_b), &front, &back, &is_coplanar);
EXPECT_EQ(is_coplanar, false);
EXPECT_NE(front, nullptr);
EXPECT_EQ(back, nullptr);
}
// Two quads are definitely not touching and so no split should occur.
TEST(DrawPolygonSplitTest, NotTouchingNoSplit) {
std::vector<gfx::Point3F> vertices_a;
vertices_a.push_back(gfx::Point3F(0.0f, 10.0f, 0.0f));
vertices_a.push_back(gfx::Point3F(0.0f, 0.0f, 0.0f));
vertices_a.push_back(gfx::Point3F(10.0f, 0.0f, 0.0f));
vertices_a.push_back(gfx::Point3F(10.0f, 10.0f, 0.0f));
std::vector<gfx::Point3F> vertices_b;
vertices_b.push_back(gfx::Point3F(5.0f, 10.0f, 5.0f));
vertices_b.push_back(gfx::Point3F(5.0f, 10.0f, 15.0f));
vertices_b.push_back(gfx::Point3F(5.0f, 0.0f, 15.0f));
vertices_b.push_back(gfx::Point3F(5.0f, 0.0f, 5.0f));
CREATE_NEW_DRAW_POLYGON(polygon_a, vertices_a,
gfx::Vector3dF(0.0f, 0.0f, 1.0f), 0);
CREATE_NEW_DRAW_POLYGON_PTR(polygon_b, vertices_b,
gfx::Vector3dF(-1.0f, 0.0f, 0.0f), 1);
std::unique_ptr<DrawPolygon> front;
std::unique_ptr<DrawPolygon> back;
bool is_coplanar;
polygon_a.SplitPolygon(std::move(polygon_b), &front, &back, &is_coplanar);
EXPECT_EQ(is_coplanar, false);
EXPECT_NE(front, nullptr);
EXPECT_EQ(back, nullptr);
}
// One quad is resting against another, but doesn't cross its plane so no
// split
// should occur.
TEST(DrawPolygonSplitTest, BarelyTouchingNoSplit) {
std::vector<gfx::Point3F> vertices_a;
vertices_a.push_back(gfx::Point3F(0.0f, 10.0f, 0.0f));
vertices_a.push_back(gfx::Point3F(0.0f, 0.0f, 0.0f));
vertices_a.push_back(gfx::Point3F(10.0f, 0.0f, 0.0f));
vertices_a.push_back(gfx::Point3F(10.0f, 10.0f, 0.0f));
std::vector<gfx::Point3F> vertices_b;
vertices_b.push_back(gfx::Point3F(5.0f, 10.0f, 0.0f));
vertices_b.push_back(gfx::Point3F(5.0f, 10.0f, -10.0f));
vertices_b.push_back(gfx::Point3F(5.0f, 0.0f, -10.0f));
vertices_b.push_back(gfx::Point3F(5.0f, 0.0f, 0.0f));
CREATE_NEW_DRAW_POLYGON(polygon_a, vertices_a,
gfx::Vector3dF(0.0f, 0.0f, 1.0f), 0);
CREATE_NEW_DRAW_POLYGON_PTR(polygon_b, vertices_b,
gfx::Vector3dF(-1.0f, 0.0f, 0.0f), 1);
std::unique_ptr<DrawPolygon> front;
std::unique_ptr<DrawPolygon> back;
bool is_coplanar;
polygon_a.SplitPolygon(std::move(polygon_b), &front, &back, &is_coplanar);
EXPECT_EQ(is_coplanar, false);
EXPECT_EQ(front, nullptr);
EXPECT_NE(back, nullptr);
}
// One quad intersects a pent with an occluded side.
TEST(DrawPolygonSplitTest, SlimClip) {
std::vector<gfx::Point3F> vertices_a;
vertices_a.push_back(gfx::Point3F(0.0f, 10.0f, 0.0f));
vertices_a.push_back(gfx::Point3F(0.0f, 0.0f, 0.0f));
vertices_a.push_back(gfx::Point3F(10.0f, 0.0f, 0.0f));
vertices_a.push_back(gfx::Point3F(10.0f, 10.0f, 0.0f));
std::vector<gfx::Point3F> vertices_b;
vertices_b.push_back(gfx::Point3F(9.0f, 9.0f, 5.000f));
vertices_b.push_back(gfx::Point3F(1.0f, 1.0f, 0.001f));
vertices_b.push_back(gfx::Point3F(1.0f, 1.0f, 0.000f));
vertices_b.push_back(gfx::Point3F(1.002f, 1.002f, -0.005f));
vertices_b.push_back(gfx::Point3F(9.0f, 9.0f, -4.000f));
CREATE_NEW_DRAW_POLYGON_PTR(polygon_a, vertices_a,
gfx::Vector3dF(0.0f, 0.0f, 1.0f), 0);
CREATE_NEW_DRAW_POLYGON_PTR(
polygon_b, vertices_b,
gfx::Vector3dF(sqrt(2) / 2, -sqrt(2) / 2, 0.000000), 1);
// These are well formed, convex polygons.
EXPECT_TRUE(IsPlanarForTesting(*polygon_a));
EXPECT_TRUE(IsConvexForTesting(*polygon_a));
EXPECT_TRUE(IsPlanarForTesting(*polygon_b));
EXPECT_TRUE(IsConvexForTesting(*polygon_b));
std::unique_ptr<DrawPolygon> front_polygon;
std::unique_ptr<DrawPolygon> back_polygon;
bool is_coplanar;
polygon_a->SplitPolygon(std::move(polygon_b), &front_polygon, &back_polygon,
&is_coplanar);
EXPECT_FALSE(is_coplanar);
EXPECT_TRUE(front_polygon != nullptr);
EXPECT_TRUE(back_polygon != nullptr);
}
// One quad intersects another and becomes two pieces.
TEST(DrawPolygonSplitTest, BasicSplit) {
std::vector<gfx::Point3F> vertices_a;
vertices_a.push_back(gfx::Point3F(0.0f, 10.0f, 0.0f));
vertices_a.push_back(gfx::Point3F(0.0f, 0.0f, 0.0f));
vertices_a.push_back(gfx::Point3F(10.0f, 0.0f, 0.0f));
vertices_a.push_back(gfx::Point3F(10.0f, 10.0f, 0.0f));
std::vector<gfx::Point3F> vertices_b;
vertices_b.push_back(gfx::Point3F(5.0f, 10.0f, -5.0f));
vertices_b.push_back(gfx::Point3F(5.0f, 0.0f, -5.0f));
vertices_b.push_back(gfx::Point3F(5.0f, 0.0f, 5.0f));
vertices_b.push_back(gfx::Point3F(5.0f, 10.0f, 5.0f));
CREATE_NEW_DRAW_POLYGON_PTR(polygon_a, vertices_a,
gfx::Vector3dF(0.0f, 0.0f, 1.0f), 0);
CREATE_NEW_DRAW_POLYGON_PTR(polygon_b, vertices_b,
gfx::Vector3dF(-1.0f, 0.0f, 0.0f), 1);
std::unique_ptr<DrawPolygon> front_polygon;
std::unique_ptr<DrawPolygon> back_polygon;
bool is_coplanar;
polygon_a->SplitPolygon(std::move(polygon_b), &front_polygon, &back_polygon,
&is_coplanar);
EXPECT_FALSE(is_coplanar);
EXPECT_TRUE(front_polygon != nullptr);
EXPECT_TRUE(back_polygon != nullptr);
std::vector<gfx::Point3F> test_points_a;
test_points_a.push_back(gfx::Point3F(5.0f, 0.0f, 0.0f));
test_points_a.push_back(gfx::Point3F(5.0f, 0.0f, 5.0f));
test_points_a.push_back(gfx::Point3F(5.0f, 10.0f, 5.0f));
test_points_a.push_back(gfx::Point3F(5.0f, 10.0f, 0.0f));
std::vector<gfx::Point3F> test_points_b;
test_points_b.push_back(gfx::Point3F(5.0f, 10.0f, 0.0f));
test_points_b.push_back(gfx::Point3F(5.0f, 10.0f, -5.0f));
test_points_b.push_back(gfx::Point3F(5.0f, 0.0f, -5.0f));
test_points_b.push_back(gfx::Point3F(5.0f, 0.0f, 0.0f));
ValidatePoints(*front_polygon, test_points_a);
ValidatePoints(*back_polygon, test_points_b);
EXPECT_EQ(4u, front_polygon->points().size());
EXPECT_EQ(4u, back_polygon->points().size());
}
// In this test we cut the corner of a quad so that it creates a triangle and
// a pentagon as a result.
TEST(DrawPolygonSplitTest, AngledSplit) {
std::vector<gfx::Point3F> vertices_a;
vertices_a.push_back(gfx::Point3F(0.0f, 0.0f, 0.0f));
vertices_a.push_back(gfx::Point3F(0.0f, 0.0f, 10.0f));
vertices_a.push_back(gfx::Point3F(10.0f, 0.0f, 10.0f));
vertices_a.push_back(gfx::Point3F(10.0f, 0.0f, 0.0f));
std::vector<gfx::Point3F> vertices_b;
vertices_b.push_back(gfx::Point3F(2.0f, 5.0f, 1.0f));
vertices_b.push_back(gfx::Point3F(2.0f, -5.0f, 1.0f));
vertices_b.push_back(gfx::Point3F(-1.0f, -5.0f, -2.0f));
vertices_b.push_back(gfx::Point3F(-1.0f, 5.0f, -2.0f));
CREATE_NEW_DRAW_POLYGON_PTR(polygon_a, vertices_a,
gfx::Vector3dF(0.0f, 1.0f, 0.0f), 0);
CREATE_NEW_DRAW_POLYGON_PTR(polygon_b, vertices_b,
gfx::Vector3dF(0.707107f, 0.0f, -0.707107f), 1);
std::unique_ptr<DrawPolygon> front_polygon;
std::unique_ptr<DrawPolygon> back_polygon;
bool is_coplanar;
polygon_b->SplitPolygon(std::move(polygon_a), &front_polygon, &back_polygon,
&is_coplanar);
EXPECT_FALSE(is_coplanar);
EXPECT_TRUE(front_polygon != nullptr);
EXPECT_TRUE(back_polygon != nullptr);
std::vector<gfx::Point3F> test_points_a;
test_points_a.push_back(gfx::Point3F(10.0f, 0.0f, 9.0f));
test_points_a.push_back(gfx::Point3F(10.0f, 0.0f, 0.0f));
test_points_a.push_back(gfx::Point3F(1.0f, 0.0f, 0.0f));
std::vector<gfx::Point3F> test_points_b;
test_points_b.push_back(gfx::Point3F(1.0f, 0.0f, 0.0f));
test_points_b.push_back(gfx::Point3F(0.0f, 0.0f, 0.0f));
test_points_b.push_back(gfx::Point3F(0.0f, 0.0f, 10.0f));
test_points_b.push_back(gfx::Point3F(10.0f, 0.0f, 10.0f));
test_points_b.push_back(gfx::Point3F(10.0f, 0.0f, 9.0f));
ValidatePointsWithinDeltaOf(*front_polygon, test_points_a, 1e-6f);
ValidatePointsWithinDeltaOf(*back_polygon, test_points_b, 1e-6f);
}
// This test was derived from crbug.com/693826. An almost coplanar
// pair of polygons are used for splitting. In this case, the
// splitting plane distance signs are [ 0 0 + - ]. This configuration
// represents a case where snapping to the splitting plane causes the
// polygon to become twisted. Splitting should still give a valid
// result, indicated by all four of the input split polygon vertices
// being present in the output polygons.
TEST(DrawPolygonSplitTest, AlmostCoplanarSplit) {
std::vector<gfx::Point3F> vertices_a;
vertices_a.push_back(gfx::Point3F(723.814758300781250f, 552.810119628906250f,
-206.656036376953125f));
vertices_a.push_back(gfx::Point3F(797.634155273437500f, 549.095703125000000f,
-209.802902221679688f));
vertices_a.push_back(gfx::Point3F(799.264648437500000f, 490.325805664062500f,
-172.261627197265625f));
vertices_a.push_back(gfx::Point3F(720.732421875000000f, 493.944458007812500f,
-168.700469970703125f));
std::vector<gfx::Point3F> vertices_b;
vertices_b.push_back(gfx::Point3F(720.631286621093750f, 487.595977783203125f,
-164.681198120117188f));
vertices_b.push_back(gfx::Point3F(799.672851562500000f, 484.059020996093750f,
-168.219161987304688f));
vertices_b.push_back(gfx::Point3F(801.565490722656250f, 416.416809082031250f,
-125.007690429687500f));
vertices_b.push_back(gfx::Point3F(717.096801757812500f, 419.792327880859375f,
-120.967689514160156f));
CREATE_NEW_DRAW_POLYGON_PTR(
splitting_polygon, vertices_a,
gfx::Vector3dF(-0.062916249036789f, -0.538499474525452f,
-0.840273618698120f),
0);
CREATE_NEW_DRAW_POLYGON_PTR(
split_polygon, vertices_b,
gfx::Vector3dF(-0.061713f, -0.538550f, -0.840330f), 1);
std::unique_ptr<DrawPolygon> front_polygon;
std::unique_ptr<DrawPolygon> back_polygon;
bool is_coplanar;
splitting_polygon->SplitPolygon(std::move(split_polygon), &front_polygon,
&back_polygon, &is_coplanar);
EXPECT_FALSE(is_coplanar);
EXPECT_TRUE(front_polygon != nullptr);
EXPECT_TRUE(back_polygon != nullptr);
for (auto vertex : vertices_b) {
EXPECT_TRUE(base::ContainsValue(front_polygon->points(), vertex) ||
base::ContainsValue(back_polygon->points(), vertex));
}
}
// In this test we cut the corner of a quad so that it creates a triangle and
// a pentagon as a result, and then cut the pentagon.
TEST(DrawPolygonSplitTest, DoubleSplit) {
std::vector<gfx::Point3F> vertices_a;
vertices_a.push_back(gfx::Point3F(0.0f, 0.0f, 0.0f));
vertices_a.push_back(gfx::Point3F(0.0f, 0.0f, 10.0f));
vertices_a.push_back(gfx::Point3F(10.0f, 0.0f, 10.0f));
vertices_a.push_back(gfx::Point3F(10.0f, 0.0f, 0.0f));
std::vector<gfx::Point3F> vertices_b;
vertices_b.push_back(gfx::Point3F(2.0f, 5.0f, 1.0f));
vertices_b.push_back(gfx::Point3F(2.0f, -5.0f, 1.0f));
vertices_b.push_back(gfx::Point3F(-1.0f, -5.0f, -2.0f));
vertices_b.push_back(gfx::Point3F(-1.0f, 5.0f, -2.0f));
CREATE_NEW_DRAW_POLYGON_PTR(polygon_a, vertices_a,
gfx::Vector3dF(0.0f, 1.0f, 0.0f), 0);
CREATE_NEW_DRAW_POLYGON_PTR(polygon_b, vertices_b,
gfx::Vector3dF(sqrt(2) / 2, 0.0f, -sqrt(2) / 2),
1);
std::unique_ptr<DrawPolygon> front_polygon;
std::unique_ptr<DrawPolygon> back_polygon;
bool is_coplanar;
polygon_b->SplitPolygon(std::move(polygon_a), &front_polygon, &back_polygon,
&is_coplanar);
EXPECT_FALSE(is_coplanar);
EXPECT_TRUE(front_polygon != nullptr);
EXPECT_TRUE(back_polygon != nullptr);
EXPECT_EQ(3u, front_polygon->points().size());
EXPECT_EQ(5u, back_polygon->points().size());
std::vector<gfx::Point3F> saved_back_polygon_vertices =
back_polygon->points();
std::vector<gfx::Point3F> vertices_c;
vertices_c.push_back(gfx::Point3F(0.0f, 0.0f, 10.0f));
vertices_c.push_back(gfx::Point3F(1.0f, -0.05f, 0.0f));
vertices_c.push_back(gfx::Point3F(10.0f, 0.05f, 9.0f));
CREATE_NEW_DRAW_POLYGON_PTR(polygon_c, vertices_c,
gfx::Vector3dF(0.005555f, -0.99997f, 0.005555f),
0);
polygon_c->RecomputeNormalForTesting();
std::unique_ptr<DrawPolygon> second_front_polygon;
std::unique_ptr<DrawPolygon> second_back_polygon;
polygon_c->SplitPolygon(std::move(back_polygon), &second_front_polygon,
&second_back_polygon, &is_coplanar);
EXPECT_FALSE(is_coplanar);
EXPECT_TRUE(second_front_polygon != nullptr);
EXPECT_TRUE(second_back_polygon != nullptr);
EXPECT_EQ(4u, second_front_polygon->points().size());
EXPECT_EQ(3u, second_back_polygon->points().size());
for (auto vertex : saved_back_polygon_vertices) {
EXPECT_TRUE(base::ContainsValue(second_front_polygon->points(), vertex) ||
base::ContainsValue(second_back_polygon->points(), vertex));
}
}
TEST(DrawPolygonTransformTest, TransformNormal) {
std::vector<gfx::Point3F> vertices_a;
vertices_a.push_back(gfx::Point3F(1.0f, 0.0f, 1.0f));
vertices_a.push_back(gfx::Point3F(-1.0f, 0.0f, -1.0f));
vertices_a.push_back(gfx::Point3F(0.0f, 1.0f, 0.0f));
CREATE_NEW_DRAW_POLYGON(polygon_a, vertices_a,
gfx::Vector3dF(sqrt(2) / 2, 0.0f, -sqrt(2) / 2), 0);
EXPECT_NORMAL(polygon_a, sqrt(2) / 2, 0.0f, -sqrt(2) / 2);
gfx::Transform transform;
transform.RotateAboutYAxis(45.0f);
// This would transform the vertices as well, but we are transforming a
// DrawPolygon with 0 vertices just to make sure our normal transformation
// using the inverse tranpose matrix gives us the right result.
polygon_a.TransformToScreenSpace(transform);
// Note: We use EXPECT_FLOAT_WITHIN_EPSILON instead of EXPECT_FLOAT_EQUAL here
// because some architectures (e.g., Arm64) employ a fused multiply-add
// instruction which causes rounding asymmetry and reduces precision.
// http://crbug.com/401117.
EXPECT_NORMAL(polygon_a, 0.0f, 0.0f, -1.0f);
}
} // namespace
} // namespace viz
| null | null | null | null | 13,747 |
38,485 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 38,485 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2016 The Chromium 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 THIRD_PARTY_BLINK_RENDERER_MODULES_SENSOR_SENSOR_PROVIDER_PROXY_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_SENSOR_SENSOR_PROVIDER_PROXY_H_
#include "services/device/public/mojom/sensor.mojom-blink.h"
#include "services/device/public/mojom/sensor_provider.mojom-blink.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/supplementable.h"
namespace blink {
class SensorProxy;
// This class wraps 'SensorProvider' mojo interface and it manages
// 'SensorProxy' instances.
class SensorProviderProxy final
: public GarbageCollectedFinalized<SensorProviderProxy>,
public Supplement<LocalFrame> {
USING_GARBAGE_COLLECTED_MIXIN(SensorProviderProxy);
WTF_MAKE_NONCOPYABLE(SensorProviderProxy);
public:
static const char kSupplementName[];
static SensorProviderProxy* From(LocalFrame*);
~SensorProviderProxy();
SensorProxy* CreateSensorProxy(device::mojom::blink::SensorType, Page*);
SensorProxy* GetSensorProxy(device::mojom::blink::SensorType);
virtual void Trace(blink::Visitor*);
private:
friend class SensorProxy; // To call getSensorProvider().
explicit SensorProviderProxy(LocalFrame&);
void InitializeIfNeeded();
bool IsInitialized() const { return sensor_provider_.is_bound(); }
device::mojom::blink::SensorProvider* GetSensorProvider() const {
return sensor_provider_.get();
}
void OnSensorProviderConnectionError();
using SensorsSet = HeapHashSet<WeakMember<SensorProxy>>;
SensorsSet sensor_proxies_;
device::mojom::blink::SensorProviderPtr sensor_provider_;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_SENSOR_SENSOR_PROVIDER_PROXY_H_
| null | null | null | null | 35,348 |
28,166 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 28,166 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: jschorr@google.com (Joseph Schorr)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// TODO(ksroka): Move some of these tests to field_comparator_test.cc.
#include <algorithm>
#include <string>
#include <vector>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/util/field_comparator.h>
#include <google/protobuf/util/message_differencer.h>
#include <google/protobuf/util/message_differencer_unittest.pb.h>
#include <google/protobuf/text_format.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/any_test.pb.h>
#include <google/protobuf/map_unittest.pb.h>
#include <google/protobuf/unittest.pb.h>
#include <google/protobuf/map_test_util.h>
#include <google/protobuf/test_util.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
namespace google {
namespace protobuf {
namespace {
const FieldDescriptor* GetFieldDescriptor(
const Message& message, const string& field_name) {
std::vector<string> field_path =
Split(field_name, ".", true);
const Descriptor* descriptor = message.GetDescriptor();
const FieldDescriptor* field = NULL;
for (int i = 0; i < field_path.size(); i++) {
field = descriptor->FindFieldByName(field_path[i]);
descriptor = field->message_type();
}
return field;
}
void ExpectEqualsWithDifferencer(util::MessageDifferencer* differencer,
const Message& msg1,
const Message& msg2) {
differencer->set_scope(util::MessageDifferencer::FULL);
EXPECT_TRUE(differencer->Compare(msg1, msg2));
differencer->set_scope(util::MessageDifferencer::PARTIAL);
EXPECT_TRUE(differencer->Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, BasicEqualityTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
// Compare
EXPECT_TRUE(util::MessageDifferencer::Equals(msg1, msg2));
}
TEST(MessageDifferencerTest, BasicInequalityTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
msg1.set_optional_int32(-1);
// Compare
EXPECT_FALSE(util::MessageDifferencer::Equals(msg1, msg2));
}
TEST(MessageDifferencerTest, RepeatedFieldInequalityTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
msg1.add_repeated_int32(-1);
// Compare
EXPECT_FALSE(util::MessageDifferencer::Equals(msg1, msg2));
}
TEST(MessageDifferencerTest, MapFieldEqualityTest) {
// Create the testing protos
unittest::TestMap msg1;
unittest::TestMap msg2;
MapReflectionTester tester(unittest::TestMap::descriptor());
tester.SetMapFieldsViaReflection(&msg1);
tester.SetMapFieldsViaReflection(&msg2);
tester.SwapMapsViaReflection(&msg1);
// Compare
EXPECT_TRUE(util::MessageDifferencer::Equals(msg1, msg2));
}
TEST(MessageDifferencerTest, BasicPartialEqualityTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
// Compare
util::MessageDifferencer differencer;
differencer.set_scope(util::MessageDifferencer::PARTIAL);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, PartialEqualityTestExtraField) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
msg1.clear_optional_int32();
// Compare
util::MessageDifferencer differencer;
differencer.set_scope(util::MessageDifferencer::PARTIAL);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, PartialEqualityTestSkipRequiredField) {
// Create the testing protos
unittest::TestRequired msg1;
unittest::TestRequired msg2;
msg1.set_a(401);
msg2.set_a(401);
msg2.set_b(402);
// Compare
util::MessageDifferencer differencer;
differencer.set_scope(util::MessageDifferencer::PARTIAL);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, BasicPartialInequalityTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
msg1.set_optional_int32(-1);
// Compare
util::MessageDifferencer differencer;
differencer.set_scope(util::MessageDifferencer::PARTIAL);
EXPECT_FALSE(differencer.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, PartialInequalityMissingFieldTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
msg2.clear_optional_int32();
// Compare
util::MessageDifferencer differencer;
differencer.set_scope(util::MessageDifferencer::PARTIAL);
EXPECT_FALSE(differencer.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, RepeatedFieldPartialInequalityTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
msg1.add_repeated_int32(-1);
// Compare
util::MessageDifferencer differencer;
differencer.set_scope(util::MessageDifferencer::PARTIAL);
EXPECT_FALSE(differencer.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, BasicEquivalencyTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
// Compare
EXPECT_TRUE(util::MessageDifferencer::Equivalent(msg1, msg2));
}
TEST(MessageDifferencerTest, EquivalencyNotEqualTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
msg1.clear_optional_int32();
msg2.set_optional_int32(0);
// Compare
EXPECT_FALSE(util::MessageDifferencer::Equals(msg1, msg2));
EXPECT_TRUE(util::MessageDifferencer::Equivalent(msg1, msg2));
}
TEST(MessageDifferencerTest, BasicInequivalencyTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
msg1.set_optional_int32(-1);
// Compare
EXPECT_FALSE(util::MessageDifferencer::Equivalent(msg1, msg2));
}
TEST(MessageDifferencerTest, BasicEquivalencyNonSetTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
// Compare
EXPECT_TRUE(util::MessageDifferencer::Equivalent(msg1, msg2));
}
TEST(MessageDifferencerTest, BasicInequivalencyNonSetTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
msg1.set_optional_int32(-1);
// Compare
EXPECT_FALSE(util::MessageDifferencer::Equivalent(msg1, msg2));
}
TEST(MessageDifferencerTest, BasicPartialEquivalencyTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
// Compare
util::MessageDifferencer differencer;
differencer.set_message_field_comparison(
util::MessageDifferencer::EQUIVALENT);
differencer.set_scope(util::MessageDifferencer::PARTIAL);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, PartialEquivalencyNotEqualTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
msg1.set_optional_int32(0);
msg2.clear_optional_int32();
// Compare
EXPECT_FALSE(util::MessageDifferencer::Equals(msg1, msg2));
util::MessageDifferencer differencer;
differencer.set_message_field_comparison(
util::MessageDifferencer::EQUIVALENT);
differencer.set_scope(util::MessageDifferencer::PARTIAL);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, PartialEquivalencyTestExtraField) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
msg1.clear_optional_int32();
// Compare
util::MessageDifferencer differencer;
differencer.set_message_field_comparison(
util::MessageDifferencer::EQUIVALENT);
differencer.set_scope(util::MessageDifferencer::PARTIAL);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, PartialEquivalencyTestSkipRequiredField) {
// Create the testing protos
unittest::TestRequired msg1;
unittest::TestRequired msg2;
msg1.set_a(401);
msg2.set_a(401);
msg2.set_b(402);
// Compare
util::MessageDifferencer differencer;
differencer.set_message_field_comparison(
util::MessageDifferencer::EQUIVALENT);
differencer.set_scope(util::MessageDifferencer::PARTIAL);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, BasicPartialInequivalencyTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
msg1.set_optional_int32(-1);
// Compare
util::MessageDifferencer differencer;
differencer.set_message_field_comparison(
util::MessageDifferencer::EQUIVALENT);
differencer.set_scope(util::MessageDifferencer::PARTIAL);
EXPECT_FALSE(differencer.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, BasicPartialEquivalencyNonSetTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
// Compare
util::MessageDifferencer differencer;
differencer.set_message_field_comparison(
util::MessageDifferencer::EQUIVALENT);
differencer.set_scope(util::MessageDifferencer::PARTIAL);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, BasicPartialInequivalencyNonSetTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
msg1.set_optional_int32(-1);
// Compare
util::MessageDifferencer differencer;
differencer.set_message_field_comparison(
util::MessageDifferencer::EQUIVALENT);
differencer.set_scope(util::MessageDifferencer::PARTIAL);
EXPECT_FALSE(differencer.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, ApproximateEqualityTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
// Compare
EXPECT_TRUE(util::MessageDifferencer::ApproximatelyEquals(msg1, msg2));
}
TEST(MessageDifferencerTest, ApproximateModifiedEqualityTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
const float v1 = 2.300005f;
const float v2 = 2.300006f;
msg1.set_optional_float(v1);
msg2.set_optional_float(v2);
// Compare
ASSERT_NE(v1, v2) << "Should not be the same: " << v1 << ", " << v2;
ASSERT_FLOAT_EQ(v1, v2) << "Should be approx. equal: " << v1 << ", " << v2;
EXPECT_FALSE(util::MessageDifferencer::Equals(msg1, msg2));
EXPECT_TRUE(util::MessageDifferencer::ApproximatelyEquals(msg1, msg2));
}
TEST(MessageDifferencerTest, ApproximateEquivalencyTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
// Compare
EXPECT_TRUE(util::MessageDifferencer::ApproximatelyEquivalent(msg1,
msg2));
}
TEST(MessageDifferencerTest, ApproximateModifiedEquivalencyTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
// Modify the approximateness requirement
const float v1 = 2.300005f;
const float v2 = 2.300006f;
msg1.set_optional_float(v1);
msg2.set_optional_float(v2);
// Compare
ASSERT_NE(v1, v2) << "Should not be the same: " << v1 << ", " << v2;
ASSERT_FLOAT_EQ(v1, v2) << "Should be approx. equal: " << v1 << ", " << v2;
EXPECT_FALSE(util::MessageDifferencer::Equals(msg1, msg2));
EXPECT_TRUE(util::MessageDifferencer::ApproximatelyEquivalent(msg1,
msg2));
// Modify the equivalency requirement too
msg1.clear_optional_int32();
msg2.set_optional_int32(0);
// Compare. Now should only pass on ApproximatelyEquivalent
EXPECT_FALSE(util::MessageDifferencer::Equals(msg1, msg2));
EXPECT_FALSE(util::MessageDifferencer::Equivalent(msg1, msg2));
EXPECT_FALSE(util::MessageDifferencer::ApproximatelyEquals(msg1, msg2));
EXPECT_TRUE(util::MessageDifferencer::ApproximatelyEquivalent(msg1,
msg2));
}
TEST(MessageDifferencerTest, ApproximateInequivalencyTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
// Should fail on equivalency
msg1.set_optional_int32(-1);
EXPECT_FALSE(util::MessageDifferencer::ApproximatelyEquivalent(msg1,
msg2));
// Make these fields the same again.
msg1.set_optional_int32(0);
msg2.set_optional_int32(0);
EXPECT_TRUE(util::MessageDifferencer::ApproximatelyEquivalent(msg1,
msg2));
// Should fail on approximate equality check
const float v1 = 2.3f;
const float v2 = 9.3f;
msg1.set_optional_float(v1);
msg2.set_optional_float(v2);
EXPECT_FALSE(util::MessageDifferencer::ApproximatelyEquivalent(msg1,
msg2));
}
TEST(MessageDifferencerTest, WithinFractionOrMarginFloatTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
// Should fail on approximate equality check
const float v1 = 100.0f;
const float v2 = 109.9f;
msg1.set_optional_float(v1);
msg2.set_optional_float(v2);
// Compare
util::MessageDifferencer differencer;
EXPECT_FALSE(differencer.Compare(msg1, msg2));
const FieldDescriptor* fd =
msg1.GetDescriptor()->FindFieldByName("optional_float");
// Set float comparison to exact, margin and fraction value should not matter.
differencer.set_float_comparison(util::MessageDifferencer::EXACT);
// Set margin for float comparison.
differencer.SetFractionAndMargin(fd, 0.0, 10.0);
EXPECT_FALSE(differencer.Compare(msg1, msg2));
// Margin and fraction float comparison is activated when float comparison is
// set to approximate.
differencer.set_float_comparison(util::MessageDifferencer::APPROXIMATE);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
// Test out float comparison with fraction.
differencer.SetFractionAndMargin(fd, 0.2, 0.0);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
// Should fail since the fraction is smaller than error.
differencer.SetFractionAndMargin(fd, 0.01, 0.0);
EXPECT_FALSE(differencer.Compare(msg1, msg2));
// Should pass if either fraction or margin are satisfied.
differencer.SetFractionAndMargin(fd, 0.01, 10.0);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
// Make sure that the margin and fraction only affects the field that it was
// set for.
msg1.set_default_float(v1);
msg2.set_default_float(v2);
EXPECT_FALSE(differencer.Compare(msg1, msg2));
msg1.set_default_float(v1);
msg2.set_default_float(v1);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, WithinFractionOrMarginDoubleTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
// Should fail on approximate equality check
const double v1 = 100.0;
const double v2 = 109.9;
msg1.set_optional_double(v1);
msg2.set_optional_double(v2);
// Compare
util::MessageDifferencer differencer;
EXPECT_FALSE(differencer.Compare(msg1, msg2));
// Set comparison to exact, margin and fraction value should not matter.
differencer.set_float_comparison(util::MessageDifferencer::EXACT);
// Set margin for float comparison.
const FieldDescriptor* fd =
msg1.GetDescriptor()->FindFieldByName("optional_double");
differencer.SetFractionAndMargin(fd, 0.0, 10.0);
EXPECT_FALSE(differencer.Compare(msg1, msg2));
// Margin and fraction comparison is activated when float comparison is
// set to approximate.
differencer.set_float_comparison(util::MessageDifferencer::APPROXIMATE);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
// Test out comparison with fraction.
differencer.SetFractionAndMargin(fd, 0.2, 0.0);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
// Should fail since the fraction is smaller than error.
differencer.SetFractionAndMargin(fd, 0.01, 0.0);
EXPECT_FALSE(differencer.Compare(msg1, msg2));
// Should pass if either fraction or margin are satisfied.
differencer.SetFractionAndMargin(fd, 0.01, 10.0);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
// Make sure that the margin and fraction only affects the field that it was
// set for.
msg1.set_default_double(v1);
msg2.set_default_double(v2);
EXPECT_FALSE(differencer.Compare(msg1, msg2));
msg1.set_default_double(v1);
msg2.set_default_double(v1);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, WithinDefaultFractionOrMarginDoubleTest) {
// Create the testing protos
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
// Should fail on approximate equality check
const double v1 = 100.0;
const double v2 = 109.9;
msg1.set_optional_double(v1);
msg2.set_optional_double(v2);
util::MessageDifferencer differencer;
// Compare
EXPECT_FALSE(differencer.Compare(msg1, msg2));
// Set up a custom field comparitor, with a default fraction and margin for
// float and double comparison.
util::DefaultFieldComparator field_comparitor;
field_comparitor.SetDefaultFractionAndMargin(0.0, 10.0);
differencer.set_field_comparator(&field_comparitor);
// Set comparison to exact, margin and fraction value should not matter.
field_comparitor.set_float_comparison(util::DefaultFieldComparator::EXACT);
EXPECT_FALSE(differencer.Compare(msg1, msg2));
// Margin and fraction comparison is activated when float comparison is
// set to approximate.
field_comparitor.set_float_comparison(
util::DefaultFieldComparator::APPROXIMATE);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
// Test out comparison with fraction.
field_comparitor.SetDefaultFractionAndMargin(0.2, 0.0);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
// Should fail since the fraction is smaller than error.
field_comparitor.SetDefaultFractionAndMargin(0.01, 0.0);
EXPECT_FALSE(differencer.Compare(msg1, msg2));
// Should pass if either fraction or margin are satisfied.
field_comparitor.SetDefaultFractionAndMargin(0.01, 10.0);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
// Make sure that the default margin and fraction affects all fields
msg1.set_default_double(v1);
msg2.set_default_double(v2);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, BasicFieldOrderingsTest) {
// Create the testing protos
unittest::TestFieldOrderings msg1;
unittest::TestFieldOrderings msg2;
TestUtil::SetAllFieldsAndExtensions(&msg1);
TestUtil::SetAllFieldsAndExtensions(&msg2);
// Compare
EXPECT_TRUE(util::MessageDifferencer::Equals(msg1, msg2));
}
TEST(MessageDifferencerTest, BasicFieldOrderingInequalityTest) {
// Create the testing protos
unittest::TestFieldOrderings msg1;
unittest::TestFieldOrderings msg2;
TestUtil::SetAllFieldsAndExtensions(&msg1);
TestUtil::SetAllFieldsAndExtensions(&msg2);
msg1.set_my_float(15.00);
msg2.set_my_float(16.00);
// Compare
EXPECT_FALSE(util::MessageDifferencer::Equals(msg1, msg2));
}
TEST(MessageDifferencerTest, BasicExtensionTest) {
// Create the testing protos
unittest::TestAllExtensions msg1;
unittest::TestAllExtensions msg2;
TestUtil::SetAllExtensions(&msg1);
TestUtil::SetAllExtensions(&msg2);
// Compare
EXPECT_TRUE(util::MessageDifferencer::Equals(msg1, msg2));
}
TEST(MessageDifferencerTest, BasicExtensionInequalityTest) {
// Create the testing protos
unittest::TestAllExtensions msg1;
unittest::TestAllExtensions msg2;
TestUtil::SetAllExtensions(&msg1);
TestUtil::SetAllExtensions(&msg2);
msg1.SetExtension(unittest::optional_int32_extension, 101);
msg2.SetExtension(unittest::optional_int32_extension, 102);
// Compare
EXPECT_FALSE(util::MessageDifferencer::Equals(msg1, msg2));
}
TEST(MessageDifferencerTest, OneofTest) {
// Create the testing protos
unittest::TestOneof2 msg1;
unittest::TestOneof2 msg2;
TestUtil::SetOneof1(&msg1);
TestUtil::SetOneof1(&msg2);
// Compare
EXPECT_TRUE(util::MessageDifferencer::Equals(msg1, msg2));
}
TEST(MessageDifferencerTest, OneofInequalityTest) {
// Create the testing protos
unittest::TestOneof2 msg1;
unittest::TestOneof2 msg2;
TestUtil::SetOneof1(&msg1);
TestUtil::SetOneof2(&msg2);
// Compare
EXPECT_FALSE(util::MessageDifferencer::Equals(msg1, msg2));
}
TEST(MessageDifferencerTest, UnknownFieldPartialEqualTest) {
unittest::TestEmptyMessage empty1;
unittest::TestEmptyMessage empty2;
UnknownFieldSet* unknown1 = empty1.mutable_unknown_fields();
UnknownFieldSet* unknown2 = empty2.mutable_unknown_fields();
unknown1->AddVarint(243, 122);
unknown1->AddLengthDelimited(245, "abc");
unknown1->AddGroup(246)->AddFixed32(248, 1);
unknown1->mutable_field(2)->mutable_group()->AddFixed32(248, 2);
unknown2->AddVarint(243, 122);
unknown2->AddLengthDelimited(245, "abc");
unknown2->AddGroup(246)->AddFixed32(248, 1);
unknown2->mutable_field(2)->mutable_group()->AddFixed32(248, 2);
util::MessageDifferencer differencer;
differencer.set_scope(util::MessageDifferencer::PARTIAL);
EXPECT_TRUE(differencer.Compare(empty1, empty2));
}
TEST(MessageDifferencerTest, SpecifiedFieldsEqualityAllTest) {
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
std::vector<const FieldDescriptor*> fields1;
std::vector<const FieldDescriptor*> fields2;
msg1.GetReflection()->ListFields(msg1, &fields1);
msg2.GetReflection()->ListFields(msg2, &fields2);
util::MessageDifferencer differencer;
EXPECT_TRUE(differencer.CompareWithFields(msg1, msg2, fields1, fields2));
}
TEST(MessageDifferencerTest, SpecifiedFieldsInequalityAllTest) {
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
std::vector<const FieldDescriptor*> fields1;
std::vector<const FieldDescriptor*> fields2;
msg1.GetReflection()->ListFields(msg1, &fields1);
msg2.GetReflection()->ListFields(msg2, &fields2);
util::MessageDifferencer differencer;
EXPECT_FALSE(differencer.CompareWithFields(msg1, msg2, fields1, fields2));
}
TEST(MessageDifferencerTest, SpecifiedFieldsEmptyListAlwaysSucceeds) {
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
std::vector<const FieldDescriptor*> empty_fields;
util::MessageDifferencer differencer;
EXPECT_TRUE(differencer.CompareWithFields(msg1, msg2,
empty_fields, empty_fields));
TestUtil::SetAllFields(&msg2);
EXPECT_TRUE(differencer.CompareWithFields(msg1, msg2,
empty_fields, empty_fields));
}
TEST(MessageDifferencerTest, SpecifiedFieldsCompareWithSelf) {
unittest::TestAllTypes msg1;
TestUtil::SetAllFields(&msg1);
std::vector<const FieldDescriptor*> fields;
msg1.GetReflection()->ListFields(msg1, &fields);
util::MessageDifferencer differencer;
EXPECT_TRUE(differencer.CompareWithFields(msg1, msg1, fields, fields));
{
// Compare with a subset of fields.
std::vector<const FieldDescriptor*> compare_fields;
for (int i = 0; i < fields.size(); ++i) {
if (i % 2 == 0) {
compare_fields.push_back(fields[i]);
}
}
EXPECT_TRUE(differencer.CompareWithFields(msg1, msg1,
compare_fields, compare_fields));
}
{
// Specify a different set of fields to compare, even though we're using the
// same message. This should fail, since we are explicitly saying that the
// set of fields are different.
std::vector<const FieldDescriptor*> compare_fields1;
std::vector<const FieldDescriptor*> compare_fields2;
for (int i = 0; i < fields.size(); ++i) {
if (i % 2 == 0) {
compare_fields1.push_back(fields[i]);
} else {
compare_fields2.push_back(fields[i]);
}
}
EXPECT_FALSE(differencer.CompareWithFields(
msg1, msg1, compare_fields1, compare_fields2));
}
}
TEST(MessageDifferencerTest, SpecifiedFieldsEqualityAllShuffledTest) {
// This is a public function, so make sure there are no assumptions about the
// list of fields. Randomly shuffle them to make sure that they are properly
// ordered for comparison.
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
std::vector<const FieldDescriptor*> fields1;
std::vector<const FieldDescriptor*> fields2;
msg1.GetReflection()->ListFields(msg1, &fields1);
msg2.GetReflection()->ListFields(msg2, &fields2);
std::random_shuffle(fields1.begin(), fields1.end());
std::random_shuffle(fields2.begin(), fields2.end());
util::MessageDifferencer differencer;
EXPECT_TRUE(differencer.CompareWithFields(msg1, msg2, fields1, fields2));
}
TEST(MessageDifferencerTest, SpecifiedFieldsSubsetEqualityTest) {
// Specify a set of fields to compare. All the fields are equal.
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
std::vector<const FieldDescriptor*> fields1;
msg1.GetReflection()->ListFields(msg1, &fields1);
std::vector<const FieldDescriptor*> compare_fields;
// Only compare the field descriptors with even indices.
for (int i = 0; i < fields1.size(); ++i) {
if (i % 2 == 0) {
compare_fields.push_back(fields1[i]);
}
}
util::MessageDifferencer differencer;
EXPECT_TRUE(differencer.CompareWithFields(msg1, msg2,
compare_fields, compare_fields));
}
TEST(MessageDifferencerTest,
SpecifiedFieldsSubsetIgnoresOtherFieldDifferencesTest) {
// Specify a set of fields to compare, but clear all the other fields in one
// of the messages. This should fail a regular compare, but CompareWithFields
// should succeed.
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
std::vector<const FieldDescriptor*> fields1;
const Reflection* reflection = msg1.GetReflection();
reflection->ListFields(msg1, &fields1);
std::vector<const FieldDescriptor*> compare_fields;
// Only compare the field descriptors with even indices.
for (int i = 0; i < fields1.size(); ++i) {
if (i % 2 == 0) {
compare_fields.push_back(fields1[i]);
} else {
reflection->ClearField(&msg2, fields1[i]);
}
}
util::MessageDifferencer differencer;
EXPECT_FALSE(differencer.Compare(msg1, msg2));
EXPECT_TRUE(differencer.CompareWithFields(msg1, msg2,
compare_fields, compare_fields));
}
TEST(MessageDifferencerTest, SpecifiedFieldsDetectsDifferencesTest) {
// Change all of the repeated fields in one of the messages, and use only
// those fields for comparison.
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
TestUtil::ModifyRepeatedFields(&msg2);
std::vector<const FieldDescriptor*> fields1;
msg1.GetReflection()->ListFields(msg1, &fields1);
std::vector<const FieldDescriptor*> compare_fields;
// Only compare the repeated field descriptors.
for (int i = 0; i < fields1.size(); ++i) {
if (fields1[i]->is_repeated()) {
compare_fields.push_back(fields1[i]);
}
}
util::MessageDifferencer differencer;
EXPECT_FALSE(differencer.CompareWithFields(msg1, msg2,
compare_fields, compare_fields));
}
TEST(MessageDifferencerTest, SpecifiedFieldsEquivalenceAllTest) {
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
TestUtil::SetAllFields(&msg1);
TestUtil::SetAllFields(&msg2);
std::vector<const FieldDescriptor*> fields1;
std::vector<const FieldDescriptor*> fields2;
msg1.GetReflection()->ListFields(msg1, &fields1);
msg2.GetReflection()->ListFields(msg2, &fields2);
util::MessageDifferencer differencer;
differencer.set_message_field_comparison(
util::MessageDifferencer::EQUIVALENT);
EXPECT_TRUE(differencer.CompareWithFields(msg1, msg2, fields1, fields2));
}
TEST(MessageDifferencerTest,
SpecifiedFieldsEquivalenceIgnoresOtherFieldDifferencesTest) {
unittest::TestAllTypes msg1;
unittest::TestAllTypes msg2;
const Descriptor* desc = msg1.GetDescriptor();
const FieldDescriptor* optional_int32_desc =
desc->FindFieldByName("optional_int32");
const FieldDescriptor* optional_int64_desc =
desc->FindFieldByName("optional_int64");
const FieldDescriptor* default_int64_desc =
desc->FindFieldByName("default_int64");
ASSERT_TRUE(optional_int32_desc != NULL);
ASSERT_TRUE(optional_int64_desc != NULL);
ASSERT_TRUE(default_int64_desc != NULL);
msg1.set_optional_int32(0);
msg2.set_optional_int64(0);
msg1.set_default_int64(default_int64_desc->default_value_int64());
// Set a field to a non-default value so we know that field selection is
// actually doing something.
msg2.set_optional_uint64(23);
std::vector<const FieldDescriptor*> fields1;
std::vector<const FieldDescriptor*> fields2;
fields1.push_back(optional_int32_desc);
fields1.push_back(default_int64_desc);
fields2.push_back(optional_int64_desc);
util::MessageDifferencer differencer;
EXPECT_FALSE(differencer.CompareWithFields(msg1, msg2, fields1, fields2));
differencer.set_message_field_comparison(
util::MessageDifferencer::EQUIVALENT);
EXPECT_FALSE(differencer.Compare(msg1, msg2));
EXPECT_TRUE(differencer.CompareWithFields(msg1, msg2, fields1, fields2));
}
TEST(MessageDifferencerTest, RepeatedFieldSetTest_SetOfSet) {
// Create the testing protos
protobuf_unittest::TestDiffMessage msg1;
protobuf_unittest::TestDiffMessage msg2;
protobuf_unittest::TestDiffMessage::Item* item = msg1.add_item();
item->add_ra(1); item->add_ra(2); item->add_ra(3);
item = msg1.add_item();
item->add_ra(5); item->add_ra(6);
item = msg1.add_item();
item->add_ra(1); item->add_ra(3);
item = msg1.add_item();
item->add_ra(6); item->add_ra(7); item->add_ra(8);
item = msg2.add_item();
item->add_ra(6); item->add_ra(5);
item = msg2.add_item();
item->add_ra(6); item->add_ra(8); item->add_ra(7);
item = msg2.add_item();
item->add_ra(1); item->add_ra(3);
item = msg2.add_item();
item->add_ra(3); item->add_ra(2); item->add_ra(1);
// Compare
util::MessageDifferencer differencer;
differencer.set_repeated_field_comparison(util::MessageDifferencer::AS_SET);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, RepeatedFieldSetTest_Combination) {
// Create the testing protos
protobuf_unittest::TestDiffMessage msg1;
protobuf_unittest::TestDiffMessage msg2;
// Treat "item" as Map, with key = "a"
// Treat "item.ra" also as Set
// Treat "rv" as Set
// Treat "rw" as List
protobuf_unittest::TestDiffMessage::Item* item = msg1.add_item();
item->set_a(3);
item->add_ra(1); item->add_ra(2); item->add_ra(3);
item = msg1.add_item();
item->set_a(4);
item->add_ra(5); item->add_ra(6);
item = msg1.add_item();
item->set_a(1);
item->add_ra(1); item->add_ra(3);
item = msg1.add_item();
item->set_a(2);
item->add_ra(6); item->add_ra(7); item->add_ra(8);
item = msg2.add_item();
item->set_a(4);
item->add_ra(6); item->add_ra(5);
item = msg2.add_item();
item->set_a(2);
item->add_ra(6); item->add_ra(8); item->add_ra(7);
item = msg2.add_item();
item->set_a(1);
item->add_ra(1); item->add_ra(3);
item = msg2.add_item();
item->set_a(3);
item->add_ra(3); item->add_ra(2); item->add_ra(1);
msg1.add_rv(3);
msg1.add_rv(4);
msg1.add_rv(7);
msg1.add_rv(0);
msg2.add_rv(4);
msg2.add_rv(3);
msg2.add_rv(0);
msg2.add_rv(7);
msg1.add_rw("nothing"); msg2.add_rw("nothing");
msg1.add_rw("should"); msg2.add_rw("should");
msg1.add_rw("change"); msg2.add_rw("change");
// Compare
util::MessageDifferencer differencer1;
differencer1.TreatAsMap(msg1.GetDescriptor()->FindFieldByName("item"),
item->GetDescriptor()->FindFieldByName("a"));
differencer1.TreatAsSet(msg1.GetDescriptor()->FindFieldByName("rv"));
differencer1.TreatAsSet(item->GetDescriptor()->FindFieldByName("ra"));
EXPECT_TRUE(differencer1.Compare(msg1, msg2));
util::MessageDifferencer differencer2;
differencer2.TreatAsMap(msg1.GetDescriptor()->FindFieldByName("item"),
item->GetDescriptor()->FindFieldByName("a"));
differencer2.set_repeated_field_comparison(util::MessageDifferencer::AS_SET);
differencer2.TreatAsList(msg1.GetDescriptor()->FindFieldByName("rw"));
EXPECT_TRUE(differencer2.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, RepeatedFieldMapTest_Partial) {
protobuf_unittest::TestDiffMessage msg1;
// message msg1 {
// item { a: 1; b: "11" }
// }
protobuf_unittest::TestDiffMessage::Item* item = msg1.add_item();
item->set_a(1);
item->set_b("11");
protobuf_unittest::TestDiffMessage msg2;
// message msg2 {
// item { a: 2; b: "22" }
// item { a: 1; b: "11" }
// }
item = msg2.add_item();
item->set_a(2);
item->set_b("22");
item = msg2.add_item();
item->set_a(1);
item->set_b("11");
// Compare
util::MessageDifferencer differencer;
differencer.TreatAsMap(GetFieldDescriptor(msg1, "item"),
GetFieldDescriptor(msg1, "item.a"));
differencer.set_scope(util::MessageDifferencer::PARTIAL);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, RepeatedFieldSetTest_Duplicates) {
protobuf_unittest::TestDiffMessage a, b, c;
// message a: {
// rv: 0
// rv: 1
// rv: 0
// }
a.add_rv(0);
a.add_rv(1);
a.add_rv(0);
// message b: {
// rv: 0
// rv: 0
// rv: 1
// }
b.add_rv(0);
b.add_rv(0);
b.add_rv(1);
// message c: {
// rv: 0
// rv: 1
// }
c.add_rv(0);
c.add_rv(1);
util::MessageDifferencer differencer;
differencer.TreatAsSet(GetFieldDescriptor(a, "rv"));
EXPECT_TRUE(differencer.Compare(b, a));
EXPECT_FALSE(differencer.Compare(c, a));
util::MessageDifferencer differencer1;
differencer1.set_repeated_field_comparison(util::MessageDifferencer::AS_SET);
EXPECT_TRUE(differencer1.Compare(b, a));
EXPECT_FALSE(differencer1.Compare(c, a));
}
TEST(MessageDifferencerTest, RepeatedFieldSetTest_PartialSimple) {
protobuf_unittest::TestDiffMessage a, b, c;
// message a: {
// rm { c: 1 }
// rm { c: 0 }
// }
a.add_rm()->set_c(1);
a.add_rm()->set_c(0);
// message b: {
// rm { c: 1 }
// rm {}
// }
b.add_rm()->set_c(1);
b.add_rm();
// message c: {
// rm {}
// rm { c: 1 }
// }
c.add_rm();
c.add_rm()->set_c(1);
util::MessageDifferencer differencer;
differencer.set_scope(util::MessageDifferencer::PARTIAL);
differencer.TreatAsSet(GetFieldDescriptor(a, "rm"));
EXPECT_TRUE(differencer.Compare(b, a));
EXPECT_TRUE(differencer.Compare(c, a));
}
TEST(MessageDifferencerTest, RepeatedFieldSetTest_Partial) {
protobuf_unittest::TestDiffMessage msg1, msg2;
// message msg1: {
// rm { a: 1 }
// rm { b: 2 }
// rm { c: 3 }
// }
msg1.add_rm()->set_a(1);
msg1.add_rm()->set_b(2);
msg1.add_rm()->set_c(3);
// message msg2: {
// rm { a: 1; c: 3 }
// rm { b: 2; c: 3 }
// rm { b: 2 }
// }
protobuf_unittest::TestField* field = msg2.add_rm();
field->set_a(1);
field->set_c(3);
field = msg2.add_rm();
field->set_b(2);
field->set_c(3);
field = msg2.add_rm();
field->set_b(2);
util::MessageDifferencer differencer;
differencer.set_scope(util::MessageDifferencer::PARTIAL);
differencer.TreatAsSet(GetFieldDescriptor(msg1, "rm"));
EXPECT_TRUE(differencer.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, RepeatedFieldMapTest_MultipleFieldsAsKey) {
protobuf_unittest::TestDiffMessage msg1;
protobuf_unittest::TestDiffMessage msg2;
// Treat "item" as Map, with key = ("a", "ra")
// Treat "item.ra" as Set
protobuf_unittest::TestDiffMessage::Item* item = msg1.add_item();
// key => value: (1, {2, 3}) => "a"
item->set_a(1);
item->add_ra(2);
item->add_ra(3);
item->set_b("a");
item = msg1.add_item();
// key => value: (2, {1, 3}) => "b"
item->set_a(2);
item->add_ra(1);
item->add_ra(3);
item->set_b("b");
item = msg1.add_item();
// key => value: (1, {1, 3}) => "c"
item->set_a(1);
item->add_ra(1);
item->add_ra(3);
item->set_b("c");
item = msg2.add_item();
// key => value: (1, {1, 3}) => "c"
item->set_a(1);
item->add_ra(3);
item->add_ra(1);
item->set_b("c");
item = msg2.add_item();
// key => value: (1, {2, 3}) => "a"
item->set_a(1);
item->add_ra(3);
item->add_ra(2);
item->set_b("a");
item = msg2.add_item();
// key => value: (2, {1, 3}) => "b"
item->set_a(2);
item->add_ra(3);
item->add_ra(1);
item->set_b("b");
// Compare
util::MessageDifferencer differencer;
differencer.TreatAsSet(GetFieldDescriptor(msg1, "item.ra"));
EXPECT_FALSE(differencer.Compare(msg1, msg2));
std::vector<const FieldDescriptor*> key_fields;
key_fields.push_back(GetFieldDescriptor(msg1, "item.a"));
key_fields.push_back(GetFieldDescriptor(msg1, "item.ra"));
differencer.TreatAsMapWithMultipleFieldsAsKey(
GetFieldDescriptor(msg1, "item"), key_fields);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
// Introduce some differences.
msg1.clear_item();
msg2.clear_item();
item = msg1.add_item();
item->set_a(4);
item->add_ra(5);
item->add_ra(6);
item->set_b("hello");
item = msg2.add_item();
item->set_a(4);
item->add_ra(6);
item->add_ra(5);
item->set_b("world");
string output;
differencer.ReportDifferencesToString(&output);
EXPECT_FALSE(differencer.Compare(msg1, msg2));
EXPECT_EQ(
"moved: item[0].ra[0] -> item[0].ra[1] : 5\n"
"moved: item[0].ra[1] -> item[0].ra[0] : 6\n"
"modified: item[0].b: \"hello\" -> \"world\"\n",
output);
}
TEST(MessageDifferencerTest, RepeatedFieldMapTest_MultipleFieldPathsAsKey) {
protobuf_unittest::TestDiffMessage msg1;
protobuf_unittest::TestDiffMessage msg2;
// Treat "item" as Map, with key = ("m.a", "m.rc")
// Treat "item.m.rc" as Set
protobuf_unittest::TestDiffMessage::Item* item = msg1.add_item();
// key => value: (1, {2, 3}) => "a"
item->mutable_m()->set_a(1);
item->mutable_m()->add_rc(2);
item->mutable_m()->add_rc(3);
item->set_b("a");
item = msg1.add_item();
// key => value: (2, {1, 3}) => "b"
item->mutable_m()->set_a(2);
item->mutable_m()->add_rc(1);
item->mutable_m()->add_rc(3);
item->set_b("b");
item = msg1.add_item();
// key => value: (1, {1, 3}) => "c"
item->mutable_m()->set_a(1);
item->mutable_m()->add_rc(1);
item->mutable_m()->add_rc(3);
item->set_b("c");
item = msg2.add_item();
// key => value: (1, {1, 3}) => "c"
item->mutable_m()->set_a(1);
item->mutable_m()->add_rc(3);
item->mutable_m()->add_rc(1);
item->set_b("c");
item = msg2.add_item();
// key => value: (1, {2, 3}) => "a"
item->mutable_m()->set_a(1);
item->mutable_m()->add_rc(3);
item->mutable_m()->add_rc(2);
item->set_b("a");
item = msg2.add_item();
// key => value: (2, {1, 3}) => "b"
item->mutable_m()->set_a(2);
item->mutable_m()->add_rc(3);
item->mutable_m()->add_rc(1);
item->set_b("b");
// Compare
util::MessageDifferencer differencer;
differencer.TreatAsSet(GetFieldDescriptor(msg1, "item.m.rc"));
EXPECT_FALSE(differencer.Compare(msg1, msg2));
std::vector<std::vector<const FieldDescriptor*> > key_field_paths;
std::vector<const FieldDescriptor*> key_field_path1;
key_field_path1.push_back(GetFieldDescriptor(msg1, "item.m"));
key_field_path1.push_back(GetFieldDescriptor(msg1, "item.m.a"));
std::vector<const FieldDescriptor*> key_field_path2;
key_field_path2.push_back(GetFieldDescriptor(msg1, "item.m"));
key_field_path2.push_back(GetFieldDescriptor(msg1, "item.m.rc"));
key_field_paths.push_back(key_field_path1);
key_field_paths.push_back(key_field_path2);
differencer.TreatAsMapWithMultipleFieldPathsAsKey(
GetFieldDescriptor(msg1, "item"), key_field_paths);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
// Introduce some differences.
msg1.clear_item();
msg2.clear_item();
item = msg1.add_item();
item->mutable_m()->set_a(4);
item->mutable_m()->add_rc(5);
item->mutable_m()->add_rc(6);
item->set_b("hello");
item = msg2.add_item();
item->mutable_m()->set_a(4);
item->mutable_m()->add_rc(6);
item->mutable_m()->add_rc(5);
item->set_b("world");
string output;
differencer.ReportDifferencesToString(&output);
EXPECT_FALSE(differencer.Compare(msg1, msg2));
EXPECT_EQ(
"modified: item[0].b: \"hello\" -> \"world\"\n"
"moved: item[0].m.rc[0] -> item[0].m.rc[1] : 5\n"
"moved: item[0].m.rc[1] -> item[0].m.rc[0] : 6\n",
output);
}
TEST(MessageDifferencerTest, RepeatedFieldMapTest_IgnoredKeyFields) {
protobuf_unittest::TestDiffMessage msg1;
protobuf_unittest::TestDiffMessage msg2;
// Treat "item" as Map, with key = ("a", "ra")
protobuf_unittest::TestDiffMessage::Item* item = msg1.add_item();
item->set_a(1);
item->add_ra(2);
item->set_b("hello");
item = msg2.add_item();
item->set_a(1);
item->add_ra(3);
item->set_b("world");
// Compare
util::MessageDifferencer differencer;
std::vector<const FieldDescriptor*> key_fields;
key_fields.push_back(GetFieldDescriptor(msg1, "item.a"));
key_fields.push_back(GetFieldDescriptor(msg1, "item.ra"));
differencer.TreatAsMapWithMultipleFieldsAsKey(
GetFieldDescriptor(msg1, "item"), key_fields);
string output;
differencer.ReportDifferencesToString(&output);
EXPECT_FALSE(differencer.Compare(msg1, msg2));
EXPECT_EQ(
"added: item[0]: { a: 1 ra: 3 b: \"world\" }\n"
"deleted: item[0]: { a: 1 ra: 2 b: \"hello\" }\n",
output);
// Ignored fields that are listed as parts of the key are still used
// in key comparison, but they're not used in value comparison.
differencer.IgnoreField(GetFieldDescriptor(msg1, "item.ra"));
output.clear();
EXPECT_FALSE(differencer.Compare(msg1, msg2));
EXPECT_EQ(
"added: item[0]: { a: 1 ra: 3 b: \"world\" }\n"
"deleted: item[0]: { a: 1 ra: 2 b: \"hello\" }\n",
output);
// Ignoring a field in the key is different from treating the left fields
// as key. That is:
// (key = ("a", "ra") && ignore "ra") != (key = ("a") && ignore "ra")
util::MessageDifferencer differencer2;
differencer2.TreatAsMap(GetFieldDescriptor(msg1, "item"),
GetFieldDescriptor(msg1, "item.a"));
differencer2.IgnoreField(GetFieldDescriptor(msg1, "item.ra"));
output.clear();
differencer2.ReportDifferencesToString(&output);
EXPECT_FALSE(differencer2.Compare(msg1, msg2));
EXPECT_EQ(
"ignored: item[0].ra\n"
"modified: item[0].b: \"hello\" -> \"world\"\n",
output);
}
static const char* const kIgnoredFields[] = {"rm.b", "rm.m.b"};
class TestIgnorer : public util::MessageDifferencer::IgnoreCriteria {
public:
virtual bool IsIgnored(
const Message& message1, const Message& message2,
const FieldDescriptor* field,
const std::vector<util::MessageDifferencer::SpecificField>&
parent_fields) {
string name = "";
for (int i = 0; i < parent_fields.size(); ++i) {
name += parent_fields[i].field->name() + ".";
}
name += field->name();
for (int i = 0; i < GOOGLE_ARRAYSIZE(kIgnoredFields); ++i) {
if (name.compare(kIgnoredFields[i]) == 0) {
return true;
}
}
return false;
}
};
TEST(MessageDifferencerTest, TreatRepeatedFieldAsSetWithIgnoredFields) {
protobuf_unittest::TestDiffMessage msg1;
protobuf_unittest::TestDiffMessage msg2;
TextFormat::MergeFromString("rm { a: 11\n b: 12 }", &msg1);
TextFormat::MergeFromString("rm { a: 11\n b: 13 }", &msg2);
util::MessageDifferencer differ;
differ.TreatAsSet(GetFieldDescriptor(msg1, "rm"));
differ.AddIgnoreCriteria(new TestIgnorer);
EXPECT_TRUE(differ.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, TreatRepeatedFieldAsMapWithIgnoredKeyFields) {
protobuf_unittest::TestDiffMessage msg1;
protobuf_unittest::TestDiffMessage msg2;
TextFormat::MergeFromString("rm { a: 11\n m { a: 12\n b: 13\n } }", &msg1);
TextFormat::MergeFromString("rm { a: 11\n m { a: 12\n b: 14\n } }", &msg2);
util::MessageDifferencer differ;
differ.TreatAsMap(GetFieldDescriptor(msg1, "rm"),
GetFieldDescriptor(msg1, "rm.m"));
differ.AddIgnoreCriteria(new TestIgnorer);
EXPECT_TRUE(differ.Compare(msg1, msg2));
}
// Takes the product of all elements of item.ra as the key for key comparison.
class ValueProductMapKeyComparator
: public util::MessageDifferencer::MapKeyComparator {
public:
typedef util::MessageDifferencer::SpecificField SpecificField;
virtual bool IsMatch(
const Message &message1, const Message &message2,
const std::vector<SpecificField>& parent_fields) const {
const Reflection* reflection1 = message1.GetReflection();
const Reflection* reflection2 = message2.GetReflection();
// FieldDescriptor for item.ra
const FieldDescriptor* ra_field =
message1.GetDescriptor()->FindFieldByName("ra");
// Get the product of all elements in item.ra
int result1 = 1, result2 = 1;
for (int i = 0; i < reflection1->FieldSize(message1, ra_field); ++i) {
result1 *= reflection1->GetRepeatedInt32(message1, ra_field, i);
}
for (int i = 0; i < reflection2->FieldSize(message2, ra_field); ++i) {
result2 *= reflection2->GetRepeatedInt32(message2, ra_field, i);
}
return result1 == result2;
}
};
TEST(MessageDifferencerTest, RepeatedFieldMapTest_CustomMapKeyComparator) {
protobuf_unittest::TestDiffMessage msg1;
protobuf_unittest::TestDiffMessage msg2;
// Treat "item" as Map, using custom key comparator to determine if two
// elements have the same key.
protobuf_unittest::TestDiffMessage::Item* item = msg1.add_item();
item->add_ra(6);
item->add_ra(35);
item->set_b("hello");
item = msg2.add_item();
item->add_ra(10);
item->add_ra(21);
item->set_b("hello");
util::MessageDifferencer differencer;
ValueProductMapKeyComparator key_comparator;
differencer.TreatAsMapUsingKeyComparator(
GetFieldDescriptor(msg1, "item"), &key_comparator);
string output;
differencer.ReportDifferencesToString(&output);
// Though the above two messages have different values for item.ra, they
// are regarded as having the same key because 6 * 35 == 10 * 21. That's
// how the key comparator determines if the two have the same key.
// However, in value comparison, all fields of the message are taken into
// consideration, so they are different because their item.ra fields have
// different values using normal value comparison.
EXPECT_FALSE(differencer.Compare(msg1, msg2));
EXPECT_EQ(
"modified: item[0].ra[0]: 6 -> 10\n"
"modified: item[0].ra[1]: 35 -> 21\n",
output);
differencer.IgnoreField(GetFieldDescriptor(msg1, "item.ra"));
output.clear();
// item.ra is ignored in value comparison, so the two messages equal.
EXPECT_TRUE(differencer.Compare(msg1, msg2));
EXPECT_EQ("ignored: item[0].ra\n", output);
}
TEST(MessageDifferencerTest, RepeatedFieldSetTest_Subset) {
protobuf_unittest::TestDiffMessage msg1;
protobuf_unittest::TestDiffMessage msg2;
msg1.add_rv(3);
msg1.add_rv(8);
msg1.add_rv(2);
msg2.add_rv(2);
msg2.add_rv(3);
msg2.add_rv(5);
msg2.add_rv(8);
util::MessageDifferencer differencer;
// Fail with only partial scope set.
differencer.set_scope(util::MessageDifferencer::PARTIAL);
differencer.set_repeated_field_comparison(util::MessageDifferencer::AS_LIST);
EXPECT_FALSE(differencer.Compare(msg1, msg2));
// Fail with only set-like comparison set.
differencer.set_scope(util::MessageDifferencer::FULL);
differencer.set_repeated_field_comparison(util::MessageDifferencer::AS_SET);
EXPECT_FALSE(differencer.Compare(msg1, msg2));
// Succeed with scope and repeated field comparison set properly.
differencer.set_scope(util::MessageDifferencer::PARTIAL);
differencer.set_repeated_field_comparison(util::MessageDifferencer::AS_SET);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, IgnoreField_Single) {
protobuf_unittest::TestField msg1;
protobuf_unittest::TestField msg2;
msg1.set_c(3);
msg1.add_rc(1);
msg2.set_c(5);
msg2.add_rc(1);
util::MessageDifferencer differencer;
differencer.IgnoreField(GetFieldDescriptor(msg1, "c"));
ExpectEqualsWithDifferencer(&differencer, msg1, msg2);
}
TEST(MessageDifferencerTest, IgnoreField_Repeated) {
protobuf_unittest::TestField msg1;
protobuf_unittest::TestField msg2;
msg1.set_c(3);
msg1.add_rc(1);
msg1.add_rc(2);
msg2.set_c(3);
msg2.add_rc(1);
msg2.add_rc(3);
util::MessageDifferencer differencer;
differencer.IgnoreField(GetFieldDescriptor(msg1, "rc"));
ExpectEqualsWithDifferencer(&differencer, msg1, msg2);
}
TEST(MessageDifferencerTest, IgnoreField_Message) {
protobuf_unittest::TestDiffMessage msg1;
protobuf_unittest::TestDiffMessage msg2;
protobuf_unittest::TestField* field;
field = msg1.add_rm();
field->set_c(3);
field = msg2.add_rm();
field->set_c(4);
util::MessageDifferencer differencer;
differencer.IgnoreField(GetFieldDescriptor(msg1, "rm"));
ExpectEqualsWithDifferencer(&differencer, msg1, msg2);
}
TEST(MessageDifferencerTest, IgnoreField_Group) {
protobuf_unittest::TestDiffMessage msg1;
protobuf_unittest::TestDiffMessage msg2;
protobuf_unittest::TestDiffMessage::Item* item;
item = msg1.add_item();
item->set_a(3);
item = msg2.add_item();
item->set_a(4);
util::MessageDifferencer differencer;
differencer.IgnoreField(GetFieldDescriptor(msg1, "item"));
ExpectEqualsWithDifferencer(&differencer, msg1, msg2);
}
TEST(MessageDifferencerTest, IgnoreField_Missing) {
protobuf_unittest::TestField msg1;
protobuf_unittest::TestField msg2;
msg1.set_c(3);
msg1.add_rc(1);
msg2.add_rc(1);
util::MessageDifferencer differencer;
differencer.IgnoreField(GetFieldDescriptor(msg1, "c"));
ExpectEqualsWithDifferencer(&differencer, msg1, msg2);
ExpectEqualsWithDifferencer(&differencer, msg2, msg1);
}
TEST(MessageDifferencerTest, IgnoreField_Multiple) {
protobuf_unittest::TestField msg1;
protobuf_unittest::TestField msg2;
msg1.set_c(3);
msg1.add_rc(1);
msg1.add_rc(2);
msg2.set_c(5);
msg2.add_rc(1);
msg2.add_rc(3);
const FieldDescriptor* c = GetFieldDescriptor(msg1, "c");
const FieldDescriptor* rc = GetFieldDescriptor(msg1, "rc");
{ // Ignore c
util::MessageDifferencer differencer;
differencer.IgnoreField(c);
EXPECT_FALSE(differencer.Compare(msg1, msg2));
}
{ // Ignore rc
util::MessageDifferencer differencer;
differencer.IgnoreField(rc);
EXPECT_FALSE(differencer.Compare(msg1, msg2));
}
{ // Ignore both
util::MessageDifferencer differencer;
differencer.IgnoreField(c);
differencer.IgnoreField(rc);
ExpectEqualsWithDifferencer(&differencer, msg1, msg2);
}
}
TEST(MessageDifferencerTest, IgnoreField_NestedMessage) {
protobuf_unittest::TestDiffMessage msg1;
protobuf_unittest::TestDiffMessage msg2;
protobuf_unittest::TestField* field;
field = msg1.add_rm();
field->set_c(3);
field->add_rc(1);
field = msg2.add_rm();
field->set_c(4);
field->add_rc(1);
util::MessageDifferencer differencer;
differencer.IgnoreField(GetFieldDescriptor(msg1, "rm.c"));
ExpectEqualsWithDifferencer(&differencer, msg1, msg2);
}
TEST(MessageDifferencerTest, IgnoreField_NestedGroup) {
protobuf_unittest::TestDiffMessage msg1;
protobuf_unittest::TestDiffMessage msg2;
protobuf_unittest::TestDiffMessage::Item* item;
item = msg1.add_item();
item->set_a(3);
item->set_b("foo");
item = msg2.add_item();
item->set_a(4);
item->set_b("foo");
util::MessageDifferencer differencer;
differencer.IgnoreField(GetFieldDescriptor(msg1, "item.a"));
ExpectEqualsWithDifferencer(&differencer, msg1, msg2);
}
TEST(MessageDifferencerTest, IgnoreField_InsideSet) {
protobuf_unittest::TestDiffMessage msg1;
protobuf_unittest::TestDiffMessage msg2;
protobuf_unittest::TestDiffMessage::Item* item;
item = msg1.add_item();
item->set_a(1);
item->set_b("foo");
item->add_ra(1);
item = msg1.add_item();
item->set_a(2);
item->set_b("bar");
item->add_ra(2);
item = msg2.add_item();
item->set_a(2);
item->set_b("bar");
item->add_ra(2);
item = msg2.add_item();
item->set_a(1);
item->set_b("baz");
item->add_ra(1);
const FieldDescriptor* item_desc = GetFieldDescriptor(msg1, "item");
const FieldDescriptor* b = GetFieldDescriptor(msg1, "item.b");
util::MessageDifferencer differencer;
differencer.IgnoreField(b);
differencer.TreatAsSet(item_desc);
ExpectEqualsWithDifferencer(&differencer, msg1, msg2);
}
TEST(MessageDifferencerTest, IgnoreField_InsideMap) {
protobuf_unittest::TestDiffMessage msg1;
protobuf_unittest::TestDiffMessage msg2;
protobuf_unittest::TestDiffMessage::Item* item;
item = msg1.add_item();
item->set_a(1);
item->set_b("foo");
item->add_ra(1);
item = msg1.add_item();
item->set_a(2);
item->set_b("bar");
item->add_ra(2);
item = msg2.add_item();
item->set_a(2);
item->set_b("bar");
item->add_ra(2);
item = msg2.add_item();
item->set_a(1);
item->set_b("baz");
item->add_ra(1);
const FieldDescriptor* item_desc = GetFieldDescriptor(msg1, "item");
const FieldDescriptor* a = GetFieldDescriptor(msg1, "item.a");
const FieldDescriptor* b = GetFieldDescriptor(msg1, "item.b");
util::MessageDifferencer differencer;
differencer.IgnoreField(b);
differencer.TreatAsMap(item_desc, a);
ExpectEqualsWithDifferencer(&differencer, msg1, msg2);
}
TEST(MessageDifferencerTest, IgnoreField_DoesNotIgnoreKey) {
protobuf_unittest::TestDiffMessage msg1;
protobuf_unittest::TestDiffMessage msg2;
protobuf_unittest::TestDiffMessage::Item* item;
item = msg1.add_item();
item->set_a(1);
item->set_b("foo");
item->add_ra(1);
item = msg2.add_item();
item->set_a(2);
item->set_b("foo");
item->add_ra(1);
const FieldDescriptor* item_desc = GetFieldDescriptor(msg1, "item");
const FieldDescriptor* a = GetFieldDescriptor(msg1, "item.a");
util::MessageDifferencer differencer;
differencer.IgnoreField(a);
differencer.TreatAsMap(item_desc, a);
EXPECT_FALSE(differencer.Compare(msg1, msg2));
}
TEST(MessageDifferencerTest, IgnoreField_TrumpsCompareWithFields) {
protobuf_unittest::TestField msg1;
protobuf_unittest::TestField msg2;
msg1.set_c(3);
msg1.add_rc(1);
msg1.add_rc(2);
msg2.set_c(3);
msg2.add_rc(1);
msg2.add_rc(3);
const FieldDescriptor* c = GetFieldDescriptor(msg1, "c");
const FieldDescriptor* rc = GetFieldDescriptor(msg1, "rc");
std::vector<const FieldDescriptor*> fields;
fields.push_back(c);
fields.push_back(rc);
util::MessageDifferencer differencer;
differencer.IgnoreField(rc);
differencer.set_scope(util::MessageDifferencer::FULL);
EXPECT_TRUE(differencer.CompareWithFields(msg1, msg2, fields, fields));
differencer.set_scope(util::MessageDifferencer::PARTIAL);
EXPECT_TRUE(differencer.CompareWithFields(msg1, msg2, fields, fields));
}
// Test class to save a copy of the last field_context.parent_fields() vector
// passed to the comparison function.
class ParentSavingFieldComparator : public util::FieldComparator {
public:
ParentSavingFieldComparator() {}
virtual ComparisonResult Compare(
const google::protobuf::Message& message_1,
const google::protobuf::Message& message_2,
const google::protobuf::FieldDescriptor* field,
int index_1, int index_2,
const google::protobuf::util::FieldContext* field_context) {
if (field_context)
parent_fields_ = *(field_context->parent_fields());
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
return RECURSE;
} else {
return SAME;
}
}
std::vector<google::protobuf::util::MessageDifferencer::SpecificField> parent_fields() {
return parent_fields_;
}
private:
std::vector<google::protobuf::util::MessageDifferencer::SpecificField> parent_fields_;
};
// Tests if MessageDifferencer sends the parent fields in the FieldContext
// parameter.
TEST(MessageDifferencerTest, FieldContextParentFieldsTest) {
protobuf_unittest::TestDiffMessage msg1;
msg1.add_rm()->set_c(1);
protobuf_unittest::TestDiffMessage msg2;
msg2.add_rm()->set_c(1);
ParentSavingFieldComparator field_comparator;
util::MessageDifferencer differencer;
differencer.set_field_comparator(&field_comparator);
differencer.Compare(msg1, msg2);
// We want only one parent with the name "rm"
ASSERT_EQ(1, field_comparator.parent_fields().size());
EXPECT_EQ("rm", field_comparator.parent_fields()[0].field->name());
}
class ComparisonTest : public testing::Test {
protected:
ComparisonTest() : use_equivalency_(false), repeated_field_as_set_(false) {
// Setup the test.
TestUtil::SetAllFields(&proto1_);
TestUtil::SetAllFields(&proto2_);
TestUtil::SetAllExtensions(&proto1ex_);
TestUtil::SetAllExtensions(&proto2ex_);
TestUtil::SetAllFieldsAndExtensions(&orderings_proto1_);
TestUtil::SetAllFieldsAndExtensions(&orderings_proto2_);
unknown1_ = empty1_.mutable_unknown_fields();
unknown2_ = empty2_.mutable_unknown_fields();
}
~ComparisonTest() { }
void SetSpecialFieldOption(const Message& message,
util::MessageDifferencer* d) {
if (!ignored_field_.empty()) {
d->IgnoreField(GetFieldDescriptor(message, ignored_field_));
}
if (repeated_field_as_set_) {
d->set_repeated_field_comparison(util::MessageDifferencer::AS_SET);
}
if (!set_field_.empty()) {
d->TreatAsSet(GetFieldDescriptor(message, set_field_));
}
if (!map_field_.empty() && !map_key_.empty()) {
d->TreatAsMap(GetFieldDescriptor(message, map_field_),
GetFieldDescriptor(message, map_field_ + "." + map_key_));
}
}
string Run(const Message& msg1, const Message& msg2) {
string output;
// Setup the comparison.
util::MessageDifferencer differencer;
differencer.ReportDifferencesToString(&output);
if (use_equivalency_) {
differencer.set_message_field_comparison(
util::MessageDifferencer::EQUIVALENT);
}
SetSpecialFieldOption(msg1, &differencer);
// Conduct the comparison.
EXPECT_FALSE(differencer.Compare(msg1, msg2));
return output;
}
string Run() {
return Run(proto1_, proto2_);
}
string RunOrder() {
return Run(orderings_proto1_, orderings_proto2_);
}
string RunEx() {
return Run(proto1ex_, proto2ex_);
}
string RunDiff() {
return Run(proto1diff_, proto2diff_);
}
string RunUn() {
return Run(empty1_, empty2_);
}
void use_equivalency() {
use_equivalency_ = true;
}
void repeated_field_as_set() {
repeated_field_as_set_ = true;
}
void field_as_set(const string& field) {
set_field_ = field;
}
void field_as_map(const string& field, const string& key) {
map_field_ = field;
map_key_ = key;
}
void ignore_field(const string& field) {
ignored_field_ = field;
}
unittest::TestAllTypes proto1_;
unittest::TestAllTypes proto2_;
unittest::TestFieldOrderings orderings_proto1_;
unittest::TestFieldOrderings orderings_proto2_;
unittest::TestAllExtensions proto1ex_;
unittest::TestAllExtensions proto2ex_;
unittest::TestDiffMessage proto1diff_;
unittest::TestDiffMessage proto2diff_;
unittest::TestEmptyMessage empty1_;
unittest::TestEmptyMessage empty2_;
unittest::TestMap map_proto1_;
unittest::TestMap map_proto2_;
UnknownFieldSet* unknown1_;
UnknownFieldSet* unknown2_;
bool use_equivalency_;
bool repeated_field_as_set_;
string set_field_;
string map_field_;
string map_key_;
string ignored_field_;
};
// Basic tests.
TEST_F(ComparisonTest, AdditionTest) {
proto1_.clear_optional_int32();
EXPECT_EQ("added: optional_int32: 101\n",
Run());
}
TEST_F(ComparisonTest, Addition_OrderTest) {
orderings_proto1_.clear_my_int();
EXPECT_EQ("added: my_int: 1\n",
RunOrder());
}
TEST_F(ComparisonTest, DeletionTest) {
proto2_.clear_optional_int32();
EXPECT_EQ("deleted: optional_int32: 101\n",
Run());
}
TEST_F(ComparisonTest, Deletion_OrderTest) {
orderings_proto2_.clear_my_string();
EXPECT_EQ("deleted: my_string: \"foo\"\n",
RunOrder());
}
TEST_F(ComparisonTest, RepeatedDeletionTest) {
proto2_.clear_repeated_int32();
EXPECT_EQ("deleted: repeated_int32[0]: 201\n"
"deleted: repeated_int32[1]: 301\n",
Run());
}
TEST_F(ComparisonTest, ModificationTest) {
proto1_.set_optional_int32(-1);
EXPECT_EQ("modified: optional_int32: -1 -> 101\n",
Run());
}
// Basic equivalency tests.
TEST_F(ComparisonTest, EquivalencyAdditionTest) {
use_equivalency();
proto1_.clear_optional_int32();
EXPECT_EQ("modified: optional_int32: 0 -> 101\n",
Run());
}
TEST_F(ComparisonTest, EquivalencyDeletionTest) {
use_equivalency();
proto2_.clear_optional_int32();
EXPECT_EQ("modified: optional_int32: 101 -> 0\n",
Run());
}
// Group tests.
TEST_F(ComparisonTest, GroupAdditionTest) {
proto1_.mutable_optionalgroup()->clear_a();
EXPECT_EQ("added: optionalgroup.a: 117\n",
Run());
}
TEST_F(ComparisonTest, GroupDeletionTest) {
proto2_.mutable_optionalgroup()->clear_a();
EXPECT_EQ("deleted: optionalgroup.a: 117\n",
Run());
}
TEST_F(ComparisonTest, GroupModificationTest) {
proto1_.mutable_optionalgroup()->set_a(2);
EXPECT_EQ("modified: optionalgroup.a: 2 -> 117\n",
Run());
}
TEST_F(ComparisonTest, GroupFullAdditionTest) {
proto1_.clear_optionalgroup();
// Note the difference in the output between this and GroupAdditionTest.
EXPECT_EQ("added: optionalgroup: { a: 117 }\n",
Run());
}
TEST_F(ComparisonTest, GroupFullDeletionTest) {
proto2_.clear_optionalgroup();
EXPECT_EQ("deleted: optionalgroup: { a: 117 }\n",
Run());
}
TEST_F(ComparisonTest, RepeatedSetOptionTest) {
repeated_field_as_set();
proto2_.clear_repeatedgroup();
proto1_.clear_repeatedgroup();
proto1_.add_repeatedgroup()->set_a(317);
proto2_.add_repeatedgroup()->set_a(909);
proto2_.add_repeatedgroup()->set_a(907);
proto1_.add_repeatedgroup()->set_a(904);
proto1_.add_repeatedgroup()->set_a(907);
proto1_.add_repeatedgroup()->set_a(909);
EXPECT_EQ("moved: repeatedgroup[2] -> repeatedgroup[1] : { a: 907 }\n"
"moved: repeatedgroup[3] -> repeatedgroup[0] : { a: 909 }\n"
"deleted: repeatedgroup[0]: { a: 317 }\n"
"deleted: repeatedgroup[1]: { a: 904 }\n",
Run());
}
TEST_F(ComparisonTest, RepeatedSetOptionTest_Ex) {
repeated_field_as_set();
proto1ex_.ClearExtension(protobuf_unittest::repeated_nested_message_extension);
proto2ex_.ClearExtension(protobuf_unittest::repeated_nested_message_extension);
proto2ex_.AddExtension(protobuf_unittest::repeated_nested_message_extension)
->set_bb(909);
proto2ex_.AddExtension(protobuf_unittest::repeated_nested_message_extension)
->set_bb(907);
proto1ex_.AddExtension(protobuf_unittest::repeated_nested_message_extension)
->set_bb(904);
proto1ex_.AddExtension(protobuf_unittest::repeated_nested_message_extension)
->set_bb(907);
proto1ex_.AddExtension(protobuf_unittest::repeated_nested_message_extension)
->set_bb(909);
EXPECT_EQ("moved: (protobuf_unittest.repeated_nested_message_extension)[2] ->"
" (protobuf_unittest.repeated_nested_message_extension)[0] :"
" { bb: 909 }\n"
"deleted: (protobuf_unittest.repeated_nested_message_extension)[0]:"
" { bb: 904 }\n",
RunEx());
}
TEST_F(ComparisonTest, RepeatedMapFieldTest_Group) {
field_as_map("repeatedgroup", "a");
proto1_.clear_repeatedgroup();
proto2_.clear_repeatedgroup();
proto1_.add_repeatedgroup()->set_a(317); // deleted
proto1_.add_repeatedgroup()->set_a(904); // deleted
proto1_.add_repeatedgroup()->set_a(907); // moved from
proto1_.add_repeatedgroup()->set_a(909); // moved from
proto2_.add_repeatedgroup()->set_a(909); // moved to
proto2_.add_repeatedgroup()->set_a(318); // added
proto2_.add_repeatedgroup()->set_a(907); // moved to
EXPECT_EQ("moved: repeatedgroup[3] -> repeatedgroup[0] : { a: 909 }\n"
"added: repeatedgroup[1]: { a: 318 }\n"
"deleted: repeatedgroup[0]: { a: 317 }\n"
"deleted: repeatedgroup[1]: { a: 904 }\n",
Run());
}
TEST_F(ComparisonTest, RepeatedMapFieldTest_MessageKey) {
// Use m as key, but use b as value.
field_as_map("item", "m");
protobuf_unittest::TestDiffMessage msg1;
protobuf_unittest::TestDiffMessage msg2;
protobuf_unittest::TestDiffMessage::Item* item = msg1.add_item();
// The following code creates one deletion, one addition and two moved fields
// on the messages.
item->mutable_m()->set_c(0);
item->set_b("first");
item = msg1.add_item();
item->mutable_m()->set_c(2);
item->set_b("second");
item = msg1.add_item(); item->set_b("null"); // empty key moved
item = msg1.add_item();
item->mutable_m()->set_c(3);
item->set_b("third"); // deletion
item = msg1.add_item();
item->mutable_m()->set_c(2);
item->set_b("second"); // duplicated key ( deletion )
item = msg2.add_item();
item->mutable_m()->set_c(2);
item->set_b("second"); // modification
item = msg2.add_item();
item->mutable_m()->set_c(4);
item->set_b("fourth"); // addition
item = msg2.add_item();
item->mutable_m()->set_c(0);
item->set_b("fist"); // move with change
item = msg2.add_item(); item->set_b("null");
EXPECT_EQ(
"modified: item[0].b -> item[2].b: \"first\" -> \"fist\"\n"
"moved: item[1] -> item[0] : { b: \"second\" m { c: 2 } }\n"
"moved: item[2] -> item[3] : { b: \"null\" }\n"
"added: item[1]: { b: \"fourth\" m { c: 4 } }\n"
"deleted: item[3]: { b: \"third\" m { c: 3 } }\n"
"deleted: item[4]: { b: \"second\" m { c: 2 } }\n",
Run(msg1, msg2));
}
TEST_F(ComparisonTest, RepeatedFieldSetTest_SetOfSet) {
repeated_field_as_set();
// Create the testing protos
protobuf_unittest::TestDiffMessage msg1;
protobuf_unittest::TestDiffMessage msg2;
protobuf_unittest::TestDiffMessage::Item* item = msg1.add_item();
item->add_ra(1); item->add_ra(2); item->add_ra(3);
item = msg1.add_item();
item->add_ra(5); item->add_ra(6);
item = msg1.add_item();
item->add_ra(1); item->add_ra(3);
item = msg1.add_item();
item->add_ra(6); item->add_ra(7); item->add_ra(8);
item = msg2.add_item();
item->add_ra(6); item->add_ra(5);
item = msg2.add_item();
item->add_ra(6); item->add_ra(8);
item = msg2.add_item();
item->add_ra(1); item->add_ra(3);
item = msg2.add_item();
item->add_ra(3); item->add_ra(2); item->add_ra(1);
// Compare
EXPECT_EQ("moved: item[0].ra[0] -> item[3].ra[2] : 1\n"
"moved: item[0].ra[2] -> item[3].ra[0] : 3\n"
"moved: item[0] -> item[3] : { ra: 1 ra: 2 ra: 3 }\n"
"moved: item[1].ra[0] -> item[0].ra[1] : 5\n"
"moved: item[1].ra[1] -> item[0].ra[0] : 6\n"
"moved: item[1] -> item[0] : { ra: 5 ra: 6 }\n"
"added: item[1]: { ra: 6 ra: 8 }\n"
"deleted: item[3]: { ra: 6 ra: 7 ra: 8 }\n",
Run(msg1, msg2));
}
TEST_F(ComparisonTest, RepeatedMapFieldTest_RepeatedKey) {
// used rb as a key, but b is the value.
repeated_field_as_set();
field_as_map("item", "rb");
protobuf_unittest::TestDiffMessage msg1;
protobuf_unittest::TestDiffMessage msg2;
protobuf_unittest::TestDiffMessage::Item* item = msg1.add_item();
item->add_rb("a");
item->add_rb("b");
item->set_b("first");
item = msg2.add_item();
item->add_rb("c");
item->set_b("second");
item = msg2.add_item();
item->add_rb("b");
item->add_rb("a");
item->set_b("fist");
EXPECT_EQ("modified: item[0].b -> item[1].b: \"first\" -> \"fist\"\n"
"moved: item[0].rb[0] -> item[1].rb[1] : \"a\"\n"
"moved: item[0].rb[1] -> item[1].rb[0] : \"b\"\n"
"added: item[0]: { b: \"second\" rb: \"c\" }\n",
Run(msg1, msg2));
}
TEST_F(ComparisonTest, RepeatedMapFieldTest_RepeatedMessageKey) {
field_as_map("item", "rm");
protobuf_unittest::TestDiffMessage msg1;
protobuf_unittest::TestDiffMessage msg2;
protobuf_unittest::TestDiffMessage::Item* item = msg1.add_item();
protobuf_unittest::TestField* key = item->add_rm();
key->set_c(2); key->add_rc(10); key->add_rc(10);
item = msg1.add_item(); key = item->add_rm();
key->set_c(0); key->add_rc(1); key->add_rc(2);
key = item->add_rm();
key->set_c(0);
item->add_rb("first");
item = msg2.add_item();
item->CopyFrom(msg1.item(1));
item->add_rb("second");
EXPECT_EQ("added: item[0].rb[1]: \"second\"\n"
"deleted: item[0]: { rm { c: 2 rc: 10 rc: 10 } }\n",
Run(msg1, msg2));
}
TEST_F(ComparisonTest, RepeatedSetOptionTest_Unknown) {
// Currently, as_set option doesn't have affects on unknown field.
// If needed, this feature will be added by request.
repeated_field_as_set();
unknown1_->AddGroup(245)->AddFixed32(248, 1);
unknown2_->AddGroup(245)->AddFixed32(248, 3);
unknown2_->AddGroup(245)->AddFixed32(248, 1);
// We expect it behaves the same as normal comparison.
EXPECT_EQ("modified: 245[0].248[0]: 0x00000001 -> 0x00000003\n"
"added: 245[1]: { ... }\n",
RunUn());
}
TEST_F(ComparisonTest, Matching_Unknown) {
unknown1_->AddGroup(245)->AddFixed32(248, 1);
unknown2_->AddGroup(245)->AddFixed32(248, 1);
unknown1_->AddGroup(245)->AddFixed32(248, 3);
unknown2_->AddGroup(245)->AddFixed32(248, 3);
unknown2_->AddLengthDelimited(242, "cat");
unknown2_->AddGroup(246)->AddFixed32(248, 4);
// report_match is false so only added/modified fields are expected.
EXPECT_EQ("added: 242[0]: \"cat\"\n"
"added: 246[0]: { ... }\n",
RunUn());
}
TEST_F(ComparisonTest, RepeatedSetFieldTest) {
field_as_set("repeatedgroup");
proto1_.clear_repeatedgroup();
proto2_.clear_repeatedgroup();
proto2_.add_repeatedgroup()->set_a(909);
proto2_.add_repeatedgroup()->set_a(907);
proto1_.add_repeatedgroup()->set_a(317);
proto1_.add_repeatedgroup()->set_a(904);
proto1_.add_repeatedgroup()->set_a(907);
proto1_.add_repeatedgroup()->set_a(909);
EXPECT_EQ("moved: repeatedgroup[2] -> repeatedgroup[1] : { a: 907 }\n"
"moved: repeatedgroup[3] -> repeatedgroup[0] : { a: 909 }\n"
"deleted: repeatedgroup[0]: { a: 317 }\n"
"deleted: repeatedgroup[1]: { a: 904 }\n",
Run());
}
// Embedded message tests.
TEST_F(ComparisonTest, EmbeddedAdditionTest) {
proto1_.mutable_optional_nested_message()->clear_bb();
EXPECT_EQ("added: optional_nested_message.bb: 118\n",
Run());
}
TEST_F(ComparisonTest, EmbeddedDeletionTest) {
proto2_.mutable_optional_nested_message()->clear_bb();
EXPECT_EQ("deleted: optional_nested_message.bb: 118\n",
Run());
}
TEST_F(ComparisonTest, EmbeddedModificationTest) {
proto1_.mutable_optional_nested_message()->set_bb(2);
EXPECT_EQ("modified: optional_nested_message.bb: 2 -> 118\n",
Run());
}
TEST_F(ComparisonTest, EmbeddedFullAdditionTest) {
proto1_.clear_optional_nested_message();
EXPECT_EQ("added: optional_nested_message: { bb: 118 }\n",
Run());
}
TEST_F(ComparisonTest, EmbeddedPartialAdditionTest) {
proto1_.clear_optional_nested_message();
proto2_.mutable_optional_nested_message()->clear_bb();
EXPECT_EQ("added: optional_nested_message: { }\n",
Run());
}
TEST_F(ComparisonTest, EmbeddedFullDeletionTest) {
proto2_.clear_optional_nested_message();
EXPECT_EQ("deleted: optional_nested_message: { bb: 118 }\n",
Run());
}
// Repeated element tests.
TEST_F(ComparisonTest, BasicRepeatedTest) {
proto1_.clear_repeated_int32();
proto2_.clear_repeated_int32();
proto1_.add_repeated_int32(500);
proto1_.add_repeated_int32(501);
proto1_.add_repeated_int32(502);
proto1_.add_repeated_int32(503);
proto1_.add_repeated_int32(500);
proto2_.add_repeated_int32(500);
proto2_.add_repeated_int32(509);
proto2_.add_repeated_int32(502);
proto2_.add_repeated_int32(504);
EXPECT_EQ("modified: repeated_int32[1]: 501 -> 509\n"
"modified: repeated_int32[3]: 503 -> 504\n"
"deleted: repeated_int32[4]: 500\n",
Run());
}
TEST_F(ComparisonTest, BasicRepeatedTest_SetOption) {
repeated_field_as_set();
proto1_.clear_repeated_int32();
proto2_.clear_repeated_int32();
proto1_.add_repeated_int32(501);
proto1_.add_repeated_int32(502);
proto1_.add_repeated_int32(503);
proto1_.add_repeated_int32(500);
proto1_.add_repeated_int32(500);
proto2_.add_repeated_int32(500);
proto2_.add_repeated_int32(509);
proto2_.add_repeated_int32(503);
proto2_.add_repeated_int32(502);
proto2_.add_repeated_int32(504);
EXPECT_EQ("moved: repeated_int32[1] -> repeated_int32[3] : 502\n"
"moved: repeated_int32[3] -> repeated_int32[0] : 500\n"
"added: repeated_int32[1]: 509\n"
"added: repeated_int32[4]: 504\n"
"deleted: repeated_int32[0]: 501\n"
"deleted: repeated_int32[4]: 500\n",
Run());
}
TEST_F(ComparisonTest, BasicRepeatedTest_SetField) {
field_as_set("repeated_int32");
proto1_.clear_repeated_int32();
proto2_.clear_repeated_int32();
proto1_.add_repeated_int32(501);
proto1_.add_repeated_int32(502);
proto1_.add_repeated_int32(503);
proto1_.add_repeated_int32(500);
proto1_.add_repeated_int32(500);
proto2_.add_repeated_int32(500);
proto2_.add_repeated_int32(509);
proto2_.add_repeated_int32(503);
proto2_.add_repeated_int32(502);
proto2_.add_repeated_int32(504);
EXPECT_EQ("moved: repeated_int32[1] -> repeated_int32[3] : 502\n"
"moved: repeated_int32[3] -> repeated_int32[0] : 500\n"
"added: repeated_int32[1]: 509\n"
"added: repeated_int32[4]: 504\n"
"deleted: repeated_int32[0]: 501\n"
"deleted: repeated_int32[4]: 500\n",
Run());
}
// Multiple action tests.
TEST_F(ComparisonTest, AddDeleteTest) {
proto1_.clear_optional_int32();
proto2_.clear_optional_int64();
EXPECT_EQ("added: optional_int32: 101\n"
"deleted: optional_int64: 102\n",
Run());
}
TEST_F(ComparisonTest, AddDelete_FieldOrderingTest) {
orderings_proto1_.ClearExtension(unittest::my_extension_string);
orderings_proto2_.clear_my_int();
EXPECT_EQ("deleted: my_int: 1\n"
"added: (protobuf_unittest.my_extension_string): \"bar\"\n",
RunOrder());
}
TEST_F(ComparisonTest, AllThreeTest) {
proto1_.clear_optional_int32();
proto2_.clear_optional_float();
proto2_.set_optional_string("hello world!");
EXPECT_EQ("added: optional_int32: 101\n"
"deleted: optional_float: 111\n"
"modified: optional_string: \"115\" -> \"hello world!\"\n",
Run());
}
TEST_F(ComparisonTest, SandwhichTest) {
proto1_.clear_optional_int64();
proto1_.clear_optional_uint32();
proto2_.clear_optional_uint64();
EXPECT_EQ("added: optional_int64: 102\n"
"added: optional_uint32: 103\n"
"deleted: optional_uint64: 104\n",
Run());
}
TEST_F(ComparisonTest, IgnoredNoChangeTest) {
proto1diff_.set_v(3);
proto2diff_.set_v(3);
proto2diff_.set_w("foo");
ignore_field("v");
EXPECT_EQ("ignored: v\n"
"added: w: \"foo\"\n",
RunDiff());
}
TEST_F(ComparisonTest, IgnoredAddTest) {
proto2diff_.set_v(3);
proto2diff_.set_w("foo");
ignore_field("v");
EXPECT_EQ("ignored: v\n"
"added: w: \"foo\"\n",
RunDiff());
}
TEST_F(ComparisonTest, IgnoredDeleteTest) {
proto1diff_.set_v(3);
proto2diff_.set_w("foo");
ignore_field("v");
EXPECT_EQ("ignored: v\n"
"added: w: \"foo\"\n",
RunDiff());
}
TEST_F(ComparisonTest, IgnoredModifyTest) {
proto1diff_.set_v(3);
proto2diff_.set_v(4);
proto2diff_.set_w("foo");
ignore_field("v");
EXPECT_EQ("ignored: v\n"
"added: w: \"foo\"\n",
RunDiff());
}
TEST_F(ComparisonTest, IgnoredRepeatedAddTest) {
proto1diff_.add_rv(3);
proto1diff_.add_rv(4);
proto2diff_.add_rv(3);
proto2diff_.add_rv(4);
proto2diff_.add_rv(5);
proto2diff_.set_w("foo");
ignore_field("rv");
EXPECT_EQ("ignored: rv\n"
"added: w: \"foo\"\n",
RunDiff());
}
TEST_F(ComparisonTest, IgnoredRepeatedDeleteTest) {
proto1diff_.add_rv(3);
proto1diff_.add_rv(4);
proto1diff_.add_rv(5);
proto2diff_.add_rv(3);
proto2diff_.add_rv(4);
proto2diff_.set_w("foo");
ignore_field("rv");
EXPECT_EQ("ignored: rv\n"
"added: w: \"foo\"\n",
RunDiff());
}
TEST_F(ComparisonTest, IgnoredRepeatedModifyTest) {
proto1diff_.add_rv(3);
proto1diff_.add_rv(4);
proto2diff_.add_rv(3);
proto2diff_.add_rv(5);
proto2diff_.set_w("foo");
ignore_field("rv");
EXPECT_EQ("ignored: rv\n"
"added: w: \"foo\"\n",
RunDiff());
}
TEST_F(ComparisonTest, IgnoredWholeNestedMessage) {
proto1diff_.mutable_m()->set_c(3);
proto2diff_.mutable_m()->set_c(4);
proto2diff_.set_w("foo");
ignore_field("m");
EXPECT_EQ("added: w: \"foo\"\n"
"ignored: m\n",
RunDiff());
}
TEST_F(ComparisonTest, IgnoredNestedField) {
proto1diff_.mutable_m()->set_c(3);
proto2diff_.mutable_m()->set_c(4);
proto2diff_.set_w("foo");
ignore_field("m.c");
EXPECT_EQ("added: w: \"foo\"\n"
"ignored: m.c\n",
RunDiff());
}
TEST_F(ComparisonTest, IgnoredRepeatedNested) {
proto1diff_.add_rm()->set_c(0);
proto1diff_.add_rm()->set_c(1);
proto2diff_.add_rm()->set_c(2);
proto2diff_.add_rm()->set_c(3);
proto2diff_.set_w("foo");
ignore_field("rm.c");
EXPECT_EQ("ignored: rm[0].c\n"
"ignored: rm[1].c\n"
"added: w: \"foo\"\n",
RunDiff());
}
TEST_F(ComparisonTest, IgnoredNestedRepeated) {
proto1diff_.mutable_m()->add_rc(23);
proto1diff_.mutable_m()->add_rc(24);
proto2diff_.mutable_m()->add_rc(25);
proto2diff_.set_w("foo");
ignore_field("m.rc");
EXPECT_EQ("added: w: \"foo\"\n"
"ignored: m.rc\n",
RunDiff());
}
TEST_F(ComparisonTest, ExtensionTest) {
proto1ex_.SetExtension(unittest::optional_int32_extension, 401);
proto2ex_.SetExtension(unittest::optional_int32_extension, 402);
proto1ex_.ClearExtension(unittest::optional_int64_extension);
proto2ex_.SetExtension(unittest::optional_int64_extension, 403);
EXPECT_EQ(
"modified: (protobuf_unittest.optional_int32_extension): 401 -> 402\n"
"added: (protobuf_unittest.optional_int64_extension): 403\n",
RunEx());
}
TEST_F(ComparisonTest, MatchedUnknownFieldTagTest) {
unknown1_->AddVarint(240, 122);
unknown2_->AddVarint(240, 121);
unknown1_->AddFixed32(241, 1);
unknown2_->AddFixed64(241, 2);
unknown1_->AddLengthDelimited(242, "cat");
unknown2_->AddLengthDelimited(242, "dog");
EXPECT_EQ(
"modified: 240[0]: 122 -> 121\n"
"deleted: 241[0]: 0x00000001\n"
"added: 241[0]: 0x0000000000000002\n"
"modified: 242[0]: \"cat\" -> \"dog\"\n",
RunUn());
}
TEST_F(ComparisonTest, UnmatchedUnknownFieldTagTest) {
unknown1_->AddFixed32(243, 1);
unknown2_->AddVarint(244, 2);
unknown2_->AddVarint(244, 4);
EXPECT_EQ(
"deleted: 243[0]: 0x00000001\n"
"added: 244[0]: 2\n"
"added: 244[1]: 4\n",
RunUn());
}
TEST_F(ComparisonTest, DifferentSizedUnknownFieldTest) {
unknown1_->AddVarint(240, 1);
unknown1_->AddVarint(240, 3);
unknown1_->AddVarint(240, 4);
unknown2_->AddVarint(240, 2);
unknown2_->AddVarint(240, 3);
unknown2_->AddVarint(240, 2);
unknown2_->AddVarint(240, 5);
EXPECT_EQ(
"modified: 240[0]: 1 -> 2\n"
"modified: 240[2]: 4 -> 2\n"
"added: 240[3]: 5\n",
RunUn());
}
TEST_F(ComparisonTest, UnknownFieldsAll) {
unknown1_->AddVarint(243, 122);
unknown1_->AddFixed64(244, 0x0172356);
unknown1_->AddFixed64(244, 0x098);
unknown1_->AddGroup(245)->AddFixed32(248, 1);
unknown1_->mutable_field(3)->mutable_group()->AddFixed32(248, 2);
unknown1_->AddGroup(249)->AddFixed64(250, 1);
unknown2_->AddVarint(243, 121);
unknown2_->AddLengthDelimited(73882, "test 123");
unknown2_->AddGroup(245)->AddFixed32(248, 3);
unknown2_->AddGroup(247);
EXPECT_EQ(
"modified: 243[0]: 122 -> 121\n"
"deleted: 244[0]: 0x0000000000172356\n"
"deleted: 244[1]: 0x0000000000000098\n"
"modified: 245[0].248[0]: 0x00000001 -> 0x00000003\n"
"deleted: 245[0].248[1]: 0x00000002\n"
"added: 247[0]: { ... }\n"
"deleted: 249[0]: { ... }\n"
"added: 73882[0]: \"test 123\"\n",
RunUn());
}
TEST_F(ComparisonTest, EquivalentIgnoresUnknown) {
unittest::ForeignMessage message1, message2;
message1.set_c(5);
message1.mutable_unknown_fields()->AddVarint(123, 456);
message2.set_c(5);
message2.mutable_unknown_fields()->AddVarint(321, 654);
EXPECT_FALSE(util::MessageDifferencer::Equals(message1, message2));
EXPECT_TRUE(util::MessageDifferencer::Equivalent(message1, message2));
}
TEST_F(ComparisonTest, MapTest) {
repeated_field_as_set();
Map<string, string>& map1 = *map_proto1_.mutable_map_string_string();
map1["1"] = "1";
map1["2"] = "2";
map1["3"] = "3";
Map<string, string>& map2 = *map_proto2_.mutable_map_string_string();
map2["3"] = "0";
map2["2"] = "2";
map2["1"] = "1";
EXPECT_EQ(
"added: map_string_string: { key: \"3\" value: \"0\" }\n"
"deleted: map_string_string: { key: \"3\" value: \"3\" }\n",
Run(map_proto1_, map_proto2_));
}
class MatchingTest : public testing::Test {
public:
typedef util::MessageDifferencer MessageDifferencer;
protected:
MatchingTest() {
}
~MatchingTest() {
}
string RunWithResult(MessageDifferencer* differencer,
const Message& msg1, const Message& msg2,
bool result) {
string output;
{
// Before we return the "output" string, we must make sure the
// StreamReporter is destructored because its destructor will
// flush the stream.
io::StringOutputStream output_stream(&output);
MessageDifferencer::StreamReporter reporter(&output_stream);
reporter.set_report_modified_aggregates(true);
differencer->set_report_matches(true);
differencer->ReportDifferencesTo(&reporter);
if (result) {
EXPECT_TRUE(differencer->Compare(msg1, msg2));
} else {
EXPECT_FALSE(differencer->Compare(msg1, msg2));
}
}
return output;
}
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MatchingTest);
};
TEST_F(MatchingTest, StreamReporterMatching) {
protobuf_unittest::TestField msg1, msg2;
msg1.set_c(72);
msg2.set_c(72);
msg1.add_rc(13);
msg2.add_rc(13);
msg1.add_rc(17);
msg2.add_rc(17);
string output;
MessageDifferencer differencer;
differencer.set_report_matches(true);
differencer.ReportDifferencesToString(&output);
EXPECT_TRUE(differencer.Compare(msg1, msg2));
EXPECT_EQ(
"matched: c : 72\n"
"matched: rc[0] : 13\n"
"matched: rc[1] : 17\n",
output);
}
TEST_F(MatchingTest, DontReportMatchedWhenIgnoring) {
protobuf_unittest::TestField msg1, msg2;
msg1.set_c(72);
msg2.set_c(72);
msg1.add_rc(13);
msg2.add_rc(13);
msg1.add_rc(17);
msg2.add_rc(17);
string output;
MessageDifferencer differencer;
differencer.set_report_matches(true);
differencer.ReportDifferencesToString(&output);
differencer.IgnoreField(msg1.GetDescriptor()->FindFieldByName("c"));
EXPECT_TRUE(differencer.Compare(msg1, msg2));
EXPECT_EQ(
"ignored: c\n"
"matched: rc[0] : 13\n"
"matched: rc[1] : 17\n",
output);
}
TEST_F(MatchingTest, ReportMatchedForMovedFields) {
protobuf_unittest::TestDiffMessage msg1, msg2;
protobuf_unittest::TestDiffMessage::Item* item = msg1.add_item();
item->set_a(53);
item->set_b("hello");
item = msg2.add_item();
item->set_a(27);
item = msg2.add_item();
item->set_a(53);
item->set_b("hello");
item = msg1.add_item();
item->set_a(27);
MessageDifferencer differencer;
const FieldDescriptor* desc;
desc = msg1.GetDescriptor()->FindFieldByName("item");
differencer.TreatAsSet(desc);
EXPECT_EQ(
"matched: item[0].a -> item[1].a : 53\n"
"matched: item[0].b -> item[1].b : \"hello\"\n"
"moved: item[0] -> item[1] : { a: 53 b: \"hello\" }\n"
"matched: item[1].a -> item[0].a : 27\n"
"moved: item[1] -> item[0] : { a: 27 }\n",
RunWithResult(&differencer, msg1, msg2, true));
}
TEST_F(MatchingTest, MatchesAppearInPostTraversalOrderForMovedFields) {
protobuf_unittest::TestDiffMessage msg1, msg2;
protobuf_unittest::TestDiffMessage::Item* item;
protobuf_unittest::TestField* field;
const FieldDescriptor* desc;
const FieldDescriptor* nested_desc;
const FieldDescriptor* double_nested_desc;
desc = msg1.GetDescriptor()->FindFieldByName("item");
nested_desc = desc->message_type()->FindFieldByName("rm");
double_nested_desc = nested_desc->message_type()->FindFieldByName("rc");
MessageDifferencer differencer;
differencer.TreatAsSet(desc);
differencer.TreatAsSet(nested_desc);
differencer.TreatAsSet(double_nested_desc);
item = msg1.add_item();
field = item->add_rm();
field->set_c(1);
field->add_rc(2);
field->add_rc(3);
field = item->add_rm();
field->set_c(4);
field->add_rc(5);
field->add_rc(6);
field->add_rc(7);
item = msg2.add_item();
field = item->add_rm();
field->set_c(4);
field->add_rc(7);
field->add_rc(6);
field->add_rc(5);
field = item->add_rm();
field->set_c(1);
field->add_rc(3);
field->add_rc(2);
item = msg1.add_item();
field = item->add_rm();
field->set_c(8);
field->add_rc(10);
field->add_rc(11);
field->add_rc(9);
item = msg2.add_item();
field = item->add_rm();
field->set_c(8);
field->add_rc(9);
field->add_rc(10);
field->add_rc(11);
EXPECT_EQ(
"matched: item[0].rm[0].c -> item[0].rm[1].c : 1\n"
"moved: item[0].rm[0].rc[0] -> item[0].rm[1].rc[1] : 2\n"
"moved: item[0].rm[0].rc[1] -> item[0].rm[1].rc[0] : 3\n"
"moved: item[0].rm[0] -> item[0].rm[1] : { c: 1 rc: 2 rc: 3 }\n"
"matched: item[0].rm[1].c -> item[0].rm[0].c : 4\n"
"moved: item[0].rm[1].rc[0] -> item[0].rm[0].rc[2] : 5\n"
"matched: item[0].rm[1].rc[1] -> item[0].rm[0].rc[1] : 6\n"
"moved: item[0].rm[1].rc[2] -> item[0].rm[0].rc[0] : 7\n"
"moved: item[0].rm[1] -> item[0].rm[0] : { c: 4 rc: 5 rc: 6 rc: 7 }\n"
"matched: item[0] : { rm { c: 1 rc: 2 rc: 3 }"
" rm { c: 4 rc: 5 rc: 6 rc: 7 } }\n"
"matched: item[1].rm[0].c : 8\n"
"moved: item[1].rm[0].rc[0] -> item[1].rm[0].rc[1] : 10\n"
"moved: item[1].rm[0].rc[1] -> item[1].rm[0].rc[2] : 11\n"
"moved: item[1].rm[0].rc[2] -> item[1].rm[0].rc[0] : 9\n"
"matched: item[1].rm[0] : { c: 8 rc: 10 rc: 11 rc: 9 }\n"
"matched: item[1] : { rm { c: 8 rc: 10 rc: 11 rc: 9 } }\n",
RunWithResult(&differencer, msg1, msg2, true));
}
TEST_F(MatchingTest, MatchAndModifiedInterleaveProperly) {
protobuf_unittest::TestDiffMessage msg1, msg2;
protobuf_unittest::TestDiffMessage::Item* item;
protobuf_unittest::TestField* field;
const FieldDescriptor* desc;
const FieldDescriptor* nested_key;
const FieldDescriptor* nested_desc;
const FieldDescriptor* double_nested_key;
const FieldDescriptor* double_nested_desc;
desc = msg1.GetDescriptor()->FindFieldByName("item");
nested_key = desc->message_type()->FindFieldByName("a");
nested_desc = desc->message_type()->FindFieldByName("rm");
double_nested_key = nested_desc->message_type()->FindFieldByName("c");
double_nested_desc = nested_desc->message_type()->FindFieldByName("rc");
MessageDifferencer differencer;
differencer.TreatAsMap(desc, nested_key);
differencer.TreatAsMap(nested_desc, double_nested_key);
differencer.TreatAsSet(double_nested_desc);
item = msg1.add_item();
item->set_a(1);
field = item->add_rm();
field->set_c(2);
field->add_rc(3);
field->add_rc(4);
field = item->add_rm();
field->set_c(5);
field->add_rc(6);
field->add_rc(7);
field->add_rc(8);
item = msg1.add_item();
item->set_a(9);
field = item->add_rm();
field->set_c(10);
field->add_rc(11);
field->add_rc(12);
field = item->add_rm();
field->set_c(13);
item = msg2.add_item();
item->set_a(1);
field = item->add_rm();
field->set_c(5);
field->add_rc(8);
field->add_rc(8);
field->add_rc(6);
field = item->add_rm();
field->set_c(3);
field->add_rc(2);
field->add_rc(4);
item = msg2.add_item();
item->set_a(9);
field = item->add_rm();
field->set_c(10);
field->add_rc(12);
field->add_rc(11);
field = item->add_rm();
field->set_c(13);
EXPECT_EQ(
"matched: item[0].a : 1\n"
"matched: item[0].rm[1].c -> item[0].rm[0].c : 5\n"
"moved: item[0].rm[1].rc[0] -> item[0].rm[0].rc[2] : 6\n"
"moved: item[0].rm[1].rc[2] -> item[0].rm[0].rc[0] : 8\n"
"added: item[0].rm[0].rc[1]: 8\n"
"deleted: item[0].rm[1].rc[1]: 7\n"
"modified: item[0].rm[1] -> item[0].rm[0]: { c: 5 rc: 6 rc: 7 rc: 8 } ->"
" { c: 5 rc: 8 rc: 8 rc: 6 }\n"
"added: item[0].rm[1]: { c: 3 rc: 2 rc: 4 }\n"
"deleted: item[0].rm[0]: { c: 2 rc: 3 rc: 4 }\n"
"modified: item[0]: { a: 1 rm { c: 2 rc: 3 rc: 4 }"
" rm { c: 5 rc: 6 rc: 7 rc: 8 } } ->"
" { a: 1 rm { c: 5 rc: 8 rc: 8 rc: 6 }"
" rm { c: 3 rc: 2 rc: 4 } }\n"
"matched: item[1].a : 9\n"
"matched: item[1].rm[0].c : 10\n"
"moved: item[1].rm[0].rc[0] -> item[1].rm[0].rc[1] : 11\n"
"moved: item[1].rm[0].rc[1] -> item[1].rm[0].rc[0] : 12\n"
"matched: item[1].rm[0] : { c: 10 rc: 11 rc: 12 }\n"
"matched: item[1].rm[1].c : 13\n"
"matched: item[1].rm[1] : { c: 13 }\n"
"matched: item[1] : { a: 9 rm { c: 10 rc: 11 rc: 12 } rm { c: 13 } }\n",
RunWithResult(&differencer, msg1, msg2, false));
}
TEST_F(MatchingTest, MatchingWorksWithExtensions) {
protobuf_unittest::TestAllExtensions msg1, msg2;
protobuf_unittest::TestAllTypes::NestedMessage* nested;
using protobuf_unittest::repeated_nested_message_extension;
const FileDescriptor* descriptor;
const FieldDescriptor* desc;
const FieldDescriptor* nested_key;
descriptor = msg1.GetDescriptor()->file();
desc = descriptor->FindExtensionByName("repeated_nested_message_extension");
ASSERT_FALSE(desc == NULL);
nested_key = desc->message_type()->FindFieldByName("bb");
MessageDifferencer differencer;
differencer.TreatAsMap(desc, nested_key);
nested = msg1.AddExtension(repeated_nested_message_extension);
nested->set_bb(7);
nested = msg1.AddExtension(repeated_nested_message_extension);
nested->set_bb(13);
nested = msg1.AddExtension(repeated_nested_message_extension);
nested->set_bb(11);
nested = msg2.AddExtension(repeated_nested_message_extension);
nested->set_bb(11);
nested = msg2.AddExtension(repeated_nested_message_extension);
nested->set_bb(13);
nested = msg2.AddExtension(repeated_nested_message_extension);
nested->set_bb(7);
EXPECT_EQ(
"matched: (protobuf_unittest.repeated_nested_message_extension)[0].bb ->"
" (protobuf_unittest.repeated_nested_message_extension)[2].bb : 7\n"
"moved: (protobuf_unittest.repeated_nested_message_extension)[0] ->"
" (protobuf_unittest.repeated_nested_message_extension)[2] :"
" { bb: 7 }\n"
"matched: (protobuf_unittest.repeated_nested_message_extension)[1].bb :"
" 13\n"
"matched: (protobuf_unittest.repeated_nested_message_extension)[1] :"
" { bb: 13 }\n"
"matched: (protobuf_unittest.repeated_nested_message_extension)[2].bb ->"
" (protobuf_unittest.repeated_nested_message_extension)[0].bb :"
" 11\n"
"moved: (protobuf_unittest.repeated_nested_message_extension)[2] ->"
" (protobuf_unittest.repeated_nested_message_extension)[0] :"
" { bb: 11 }\n",
RunWithResult(&differencer, msg1, msg2, true));
}
TEST(AnyTest, Simple) {
protobuf_unittest::TestField value1, value2;
value1.set_a(20);
value2.set_a(21);
protobuf_unittest::TestAny m1, m2;
m1.mutable_any_value()->PackFrom(value1);
m2.mutable_any_value()->PackFrom(value2);
util::MessageDifferencer message_differencer;
string difference_string;
message_differencer.ReportDifferencesToString(&difference_string);
EXPECT_FALSE(message_differencer.Compare(m1, m2));
EXPECT_EQ("modified: any_value.a: 20 -> 21\n", difference_string);
}
TEST(Anytest, TreatAsSet) {
protobuf_unittest::TestField value1, value2;
value1.set_a(20);
value1.set_b(30);
value2.set_a(20);
value2.set_b(31);
protobuf_unittest::TestAny m1, m2;
m1.add_repeated_any_value()->PackFrom(value1);
m1.add_repeated_any_value()->PackFrom(value2);
m2.add_repeated_any_value()->PackFrom(value2);
m2.add_repeated_any_value()->PackFrom(value1);
util::MessageDifferencer message_differencer;
message_differencer.TreatAsSet(GetFieldDescriptor(m1, "repeated_any_value"));
EXPECT_TRUE(message_differencer.Compare(m1, m2));
}
TEST(Anytest, TreatAsSet_DifferentType) {
protobuf_unittest::TestField value1;
value1.set_a(20);
value1.set_b(30);
protobuf_unittest::TestDiffMessage value2;
value2.add_rv(40);
protobuf_unittest::TestAny m1, m2;
m1.add_repeated_any_value()->PackFrom(value1);
m1.add_repeated_any_value()->PackFrom(value2);
m2.add_repeated_any_value()->PackFrom(value2);
m2.add_repeated_any_value()->PackFrom(value1);
util::MessageDifferencer message_differencer;
message_differencer.TreatAsSet(GetFieldDescriptor(m1, "repeated_any_value"));
EXPECT_TRUE(message_differencer.Compare(m1, m2));
}
} // namespace
} // namespace protobuf
} // namespace google
| null | null | null | null | 25,029 |
41,672 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 41,672 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
namespace blink {
// Stuff in blink:: should be renamed.
void foo();
// Stuff in nested namespaces should be renamed.
namespace nested {
void foo();
} // namespace nested
// blink::protocol namespace is blacklisted.
namespace protocol {
void foo();
} // namespace protocol
} // namespace blink
namespace WTF {
// Stuff in WTF:: should be renamed.
void foo();
// Stuff in nested namespaces should be renamed.
namespace nested {
void foo();
} // namespace nested
} // namespace WTF
// Stuff outside blink:: and WTF:: should not be.
namespace other {
void foo();
namespace blink {
void foo();
} // namespace blink
namespace WTF {
void foo();
} // namespace WTF
} // namespace other
void foo();
void G() {
blink::foo();
blink::nested::foo();
WTF::foo();
WTF::nested::foo();
other::foo();
foo();
other::blink::foo();
other::WTF::foo();
}
| null | null | null | null | 38,535 |
23,996 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 23,996 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2016 The Chromium 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 "content/browser/media/audible_metrics.h"
#include "base/metrics/histogram_samples.h"
#include "base/test/histogram_tester.h"
#include "base/test/simple_test_tick_clock.h"
#include "base/test/user_action_tester.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace content {
namespace {
static const WebContents* WEB_CONTENTS_0 = reinterpret_cast<WebContents*>(0x00);
static const WebContents* WEB_CONTENTS_1 = reinterpret_cast<WebContents*>(0x01);
static const WebContents* WEB_CONTENTS_2 = reinterpret_cast<WebContents*>(0x10);
static const WebContents* WEB_CONTENTS_3 = reinterpret_cast<WebContents*>(0x11);
static const char* CONCURRENT_TAB_WHEN_STARTING_HISTOGRAM =
"Media.Audible.ConcurrentTabsWhenStarting";
static const char* MAX_CONCURRENT_TAB_IN_SESSION_HISTOGRAM =
"Media.Audible.MaxConcurrentTabsInSession";
static const char* CONCURRENT_TABS_TIME_HISTOGRAM =
"Media.Audible.ConcurrentTabsTime";
class AudibleMetricsTest : public testing::Test {
public:
AudibleMetricsTest() = default;
void SetUp() override {
// Set the clock to a value different than 0 so the time it gives is
// recognized as initialized.
clock_.Advance(base::TimeDelta::FromMilliseconds(1));
audible_metrics_.SetClockForTest(&clock_);
}
base::SimpleTestTickClock* clock() { return &clock_; }
AudibleMetrics* audible_metrics() {
return &audible_metrics_;
};
const base::UserActionTester& user_action_tester() const {
return user_action_tester_;
}
std::unique_ptr<base::HistogramSamples> GetHistogramSamplesSinceTestStart(
const std::string& name) {
return histogram_tester_.GetHistogramSamplesSinceCreation(name);
}
private:
base::SimpleTestTickClock clock_;
AudibleMetrics audible_metrics_;
base::HistogramTester histogram_tester_;
base::UserActionTester user_action_tester_;
DISALLOW_COPY_AND_ASSIGN(AudibleMetricsTest);
};
} // anonymous namespace
TEST_F(AudibleMetricsTest, CreateAndKillDoesNothing) {
{ std::unique_ptr<AudibleMetrics> audible_metrics(new AudibleMetrics()); }
{
std::unique_ptr<base::HistogramSamples> samples(
GetHistogramSamplesSinceTestStart(
CONCURRENT_TAB_WHEN_STARTING_HISTOGRAM));
EXPECT_EQ(0, samples->TotalCount());
}
{
std::unique_ptr<base::HistogramSamples> samples(
GetHistogramSamplesSinceTestStart(
MAX_CONCURRENT_TAB_IN_SESSION_HISTOGRAM));
EXPECT_EQ(0, samples->TotalCount());
}
{
std::unique_ptr<base::HistogramSamples> samples(
GetHistogramSamplesSinceTestStart(CONCURRENT_TABS_TIME_HISTOGRAM));
EXPECT_EQ(0, samples->TotalCount());
}
}
TEST_F(AudibleMetricsTest, AudibleStart) {
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, true);
{
std::unique_ptr<base::HistogramSamples> samples(
GetHistogramSamplesSinceTestStart(
CONCURRENT_TAB_WHEN_STARTING_HISTOGRAM));
EXPECT_EQ(1, samples->TotalCount());
EXPECT_EQ(1, samples->GetCount(0));
}
{
std::unique_ptr<base::HistogramSamples> samples(
GetHistogramSamplesSinceTestStart(
MAX_CONCURRENT_TAB_IN_SESSION_HISTOGRAM));
EXPECT_EQ(1, samples->TotalCount());
EXPECT_EQ(1, samples->GetCount(1));
}
{
std::unique_ptr<base::HistogramSamples> samples(
GetHistogramSamplesSinceTestStart(CONCURRENT_TABS_TIME_HISTOGRAM));
EXPECT_EQ(0, samples->TotalCount());
}
}
TEST_F(AudibleMetricsTest, AudibleStartAndStop) {
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, false);
{
std::unique_ptr<base::HistogramSamples> samples(
GetHistogramSamplesSinceTestStart(
CONCURRENT_TAB_WHEN_STARTING_HISTOGRAM));
EXPECT_EQ(1, samples->TotalCount());
EXPECT_EQ(1, samples->GetCount(0));
}
{
std::unique_ptr<base::HistogramSamples> samples(
GetHistogramSamplesSinceTestStart(
MAX_CONCURRENT_TAB_IN_SESSION_HISTOGRAM));
EXPECT_EQ(1, samples->TotalCount());
EXPECT_EQ(1, samples->GetCount(1));
}
{
std::unique_ptr<base::HistogramSamples> samples(
GetHistogramSamplesSinceTestStart(CONCURRENT_TABS_TIME_HISTOGRAM));
EXPECT_EQ(0, samples->TotalCount());
}
}
TEST_F(AudibleMetricsTest, AddSameTabIsNoOp) {
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, true);
{
std::unique_ptr<base::HistogramSamples> samples(
GetHistogramSamplesSinceTestStart(
CONCURRENT_TAB_WHEN_STARTING_HISTOGRAM));
EXPECT_EQ(1, samples->TotalCount());
EXPECT_EQ(1, samples->GetCount(0));
}
{
std::unique_ptr<base::HistogramSamples> samples(
GetHistogramSamplesSinceTestStart(
MAX_CONCURRENT_TAB_IN_SESSION_HISTOGRAM));
EXPECT_EQ(1, samples->TotalCount());
EXPECT_EQ(1, samples->GetCount(1));
}
{
std::unique_ptr<base::HistogramSamples> samples(
GetHistogramSamplesSinceTestStart(CONCURRENT_TABS_TIME_HISTOGRAM));
EXPECT_EQ(0, samples->TotalCount());
}
}
TEST_F(AudibleMetricsTest, RemoveUnknownTabIsNoOp) {
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, false);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, false);
EXPECT_EQ(0, GetHistogramSamplesSinceTestStart(
CONCURRENT_TAB_WHEN_STARTING_HISTOGRAM)->TotalCount());
EXPECT_EQ(0, GetHistogramSamplesSinceTestStart(
MAX_CONCURRENT_TAB_IN_SESSION_HISTOGRAM)->TotalCount());
EXPECT_EQ(0, GetHistogramSamplesSinceTestStart(
CONCURRENT_TABS_TIME_HISTOGRAM)->TotalCount());
}
TEST_F(AudibleMetricsTest, ConcurrentTabsInSessionIsIncremental) {
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_1, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_2, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_3, true);
std::unique_ptr<base::HistogramSamples> samples(
GetHistogramSamplesSinceTestStart(
MAX_CONCURRENT_TAB_IN_SESSION_HISTOGRAM));
EXPECT_EQ(4, samples->TotalCount());
EXPECT_EQ(1, samples->GetCount(1));
EXPECT_EQ(1, samples->GetCount(2));
EXPECT_EQ(1, samples->GetCount(3));
EXPECT_EQ(1, samples->GetCount(4));
}
TEST_F(AudibleMetricsTest, ConcurrentTabsInSessionKeepTrackOfRemovedTabs) {
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, false);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_1, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_2, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_1, false);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_2, false);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_3, true);
std::unique_ptr<base::HistogramSamples> samples(
GetHistogramSamplesSinceTestStart(
MAX_CONCURRENT_TAB_IN_SESSION_HISTOGRAM));
EXPECT_EQ(2, samples->TotalCount());
EXPECT_EQ(1, samples->GetCount(1));
EXPECT_EQ(1, samples->GetCount(2));
}
TEST_F(AudibleMetricsTest, ConcurrentTabsInSessionIsNotCountedTwice) {
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_1, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_2, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_3, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, false);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_1, false);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_2, false);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_3, false);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_1, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_2, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_3, true);
std::unique_ptr<base::HistogramSamples> samples(
GetHistogramSamplesSinceTestStart(
MAX_CONCURRENT_TAB_IN_SESSION_HISTOGRAM));
EXPECT_EQ(4, samples->TotalCount());
EXPECT_EQ(1, samples->GetCount(1));
EXPECT_EQ(1, samples->GetCount(2));
EXPECT_EQ(1, samples->GetCount(3));
EXPECT_EQ(1, samples->GetCount(4));
}
TEST_F(AudibleMetricsTest, ConcurrentTabsWhenStartingAddedPerTab) {
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_1, true);
{
std::unique_ptr<base::HistogramSamples> samples(
GetHistogramSamplesSinceTestStart(
CONCURRENT_TAB_WHEN_STARTING_HISTOGRAM));
EXPECT_EQ(2, samples->TotalCount());
EXPECT_EQ(1, samples->GetCount(0));
EXPECT_EQ(1, samples->GetCount(1));
}
// Added again: ignored.
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_1, true);
{
std::unique_ptr<base::HistogramSamples> samples(
GetHistogramSamplesSinceTestStart(
CONCURRENT_TAB_WHEN_STARTING_HISTOGRAM));
EXPECT_EQ(2, samples->TotalCount());
EXPECT_EQ(1, samples->GetCount(0));
EXPECT_EQ(1, samples->GetCount(1));
}
// Removing both.
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, false);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_1, false);
{
std::unique_ptr<base::HistogramSamples> samples(
GetHistogramSamplesSinceTestStart(
CONCURRENT_TAB_WHEN_STARTING_HISTOGRAM));
EXPECT_EQ(2, samples->TotalCount());
EXPECT_EQ(1, samples->GetCount(0));
EXPECT_EQ(1, samples->GetCount(1));
}
// Adding them after removed, it is counted.
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_1, true);
{
std::unique_ptr<base::HistogramSamples> samples(
GetHistogramSamplesSinceTestStart(
CONCURRENT_TAB_WHEN_STARTING_HISTOGRAM));
EXPECT_EQ(4, samples->TotalCount());
EXPECT_EQ(2, samples->GetCount(0));
EXPECT_EQ(2, samples->GetCount(1));
}
}
TEST_F(AudibleMetricsTest, ConcurrentTabsTimeRequiresTwoAudibleTabs) {
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_1, true);
clock()->Advance(base::TimeDelta::FromMilliseconds(1000));
// No record because concurrent audible tabs still running.
EXPECT_EQ(0, GetHistogramSamplesSinceTestStart(
CONCURRENT_TABS_TIME_HISTOGRAM)->TotalCount());
// No longer concurrent.
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, false);
{
std::unique_ptr<base::HistogramSamples> samples(
GetHistogramSamplesSinceTestStart(CONCURRENT_TABS_TIME_HISTOGRAM));
EXPECT_EQ(1, samples->TotalCount());
EXPECT_EQ(1, samples->GetCount(1000));
}
// Stopping the second tab is a no-op.
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_1, false);
{
std::unique_ptr<base::HistogramSamples> samples(
GetHistogramSamplesSinceTestStart(CONCURRENT_TABS_TIME_HISTOGRAM));
EXPECT_EQ(1, samples->TotalCount());
EXPECT_EQ(1, samples->GetCount(1000));
}
}
TEST_F(AudibleMetricsTest, ConcurrentTabsTimeRunsAsLongAsTwoAudibleTabs) {
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, true);
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_1, true);
clock()->Advance(base::TimeDelta::FromMilliseconds(1000));
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_2, true);
clock()->Advance(base::TimeDelta::FromMilliseconds(500));
// Mutes one of the three audible tabs.
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_1, false);
// No record because concurrent audible tabs still running.
EXPECT_EQ(0, GetHistogramSamplesSinceTestStart(
CONCURRENT_TABS_TIME_HISTOGRAM)->TotalCount());
// Mutes the first audible tab.
audible_metrics()->UpdateAudibleWebContentsState(WEB_CONTENTS_0, false);
{
std::unique_ptr<base::HistogramSamples> samples(
GetHistogramSamplesSinceTestStart(CONCURRENT_TABS_TIME_HISTOGRAM));
EXPECT_EQ(1, samples->TotalCount());
EXPECT_EQ(1, samples->GetCount(1500));
}
}
} // namespace content
| null | null | null | null | 20,859 |
64,729 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 64,729 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2014 The Chromium 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 CHROME_BROWSER_UI_COCOA_AUTOFILL_PASSWORD_GENERATION_POPUP_VIEW_COCOA_H_
#define CHROME_BROWSER_UI_COCOA_AUTOFILL_PASSWORD_GENERATION_POPUP_VIEW_COCOA_H_
#import <Cocoa/Cocoa.h>
#include "base/mac/scoped_nsobject.h"
#include "chrome/browser/ui/autofill/password_generation_popup_controller.h"
#import "chrome/browser/ui/cocoa/autofill/autofill_popup_base_view_cocoa.h"
#import "ui/base/cocoa/tracking_area.h"
@class HyperlinkTextView;
// Draws the native password generation popup view on Mac.
@interface PasswordGenerationPopupViewCocoa
: AutofillPopupBaseViewCocoa <NSTextViewDelegate> {
@private
// The cross-platform controller for this view.
autofill::PasswordGenerationPopupController* controller_; // weak
base::scoped_nsobject<NSView> passwordSection_;
base::scoped_nsobject<NSTextField> passwordField_;
base::scoped_nsobject<NSTextField> passwordTitleField_;
base::scoped_nsobject<NSImageView> keyIcon_;
base::scoped_nsobject<NSBox> divider_;
base::scoped_nsobject<HyperlinkTextView> helpTextView_;
ui::ScopedCrTrackingArea helpTextTrackingArea_;
}
// Designated initializer.
- (id)initWithController:
(autofill::PasswordGenerationPopupController*)controller
frame:(NSRect)frame;
// Determines whether |point| falls inside the password section of the popup.
// |point| needs to be in the popup's coordinate system.
- (BOOL)isPointInPasswordBounds:(NSPoint)point;
// Informs the view that its controller has been (or will imminently be)
// destroyed.
- (void)controllerDestroyed;
// The preferred size for the popup.
- (NSSize)preferredSize;
@end
#endif // CHROME_BROWSER_UI_COCOA_AUTOFILL_PASSWORD_GENERATION_POPUP_VIEW_COCOA_H_
| null | null | null | null | 61,592 |
56,777 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 56,777 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2014 The Chromium 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 "chrome/browser/chromeos/dbus/chrome_proxy_resolution_service_provider_delegate.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "net/url_request/url_request_context_getter.h"
namespace chromeos {
ChromeProxyResolutionServiceProviderDelegate::
ChromeProxyResolutionServiceProviderDelegate() {}
ChromeProxyResolutionServiceProviderDelegate::
~ChromeProxyResolutionServiceProviderDelegate() {}
scoped_refptr<net::URLRequestContextGetter>
ChromeProxyResolutionServiceProviderDelegate::GetRequestContext() {
Profile* profile = ProfileManager::GetPrimaryUserProfile();
return profile->GetRequestContext();
}
} // namespace chromeos
| null | null | null | null | 53,640 |
23,927 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 23,927 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright (c) 2013 The Chromium 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 CONTENT_BROWSER_STREAMS_STREAM_REGISTRY_H_
#define CONTENT_BROWSER_STREAMS_STREAM_REGISTRY_H_
#include <stddef.h>
#include <map>
#include <set>
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/sequence_checker.h"
#include "content/browser/streams/stream_register_observer.h"
#include "content/common/content_export.h"
#include "url/gurl.h"
namespace content {
class Stream;
// Maintains a mapping of blob: URLs to active streams.
class CONTENT_EXPORT StreamRegistry {
public:
StreamRegistry();
virtual ~StreamRegistry();
// Registers a stream, and sets its URL.
void RegisterStream(Stream* stream);
// Clones a stream. Returns true on success, or false if |src_url| doesn't
// exist.
bool CloneStream(const GURL& url, const GURL& src_url);
void UnregisterStream(const GURL& url);
// Called by Stream instances to request increase of memory usage. If the
// total memory usage for this registry is going to exceed the limit,
// returns false. Otherwise, updates |total_memory_usage_| and returns true.
//
// |current_size| is the up-to-date size of ByteStream of the Stream instance
// and |increase| must be the amount of data going to be added to the Stream
// instance.
bool UpdateMemoryUsage(const GURL& url, size_t current_size, size_t increase);
// Gets the stream associated with |url|. Returns NULL if there is no such
// stream.
scoped_refptr<Stream> GetStream(const GURL& url);
void set_max_memory_usage_for_testing(size_t size) {
max_memory_usage_ = size;
}
void SetRegisterObserver(const GURL& url, StreamRegisterObserver* observer);
void RemoveRegisterObserver(const GURL& url);
// If the reader is aborted before the stream is registered, call this method
// to reduce the memory consumption. After this method is called,
// RegisterStream doesn't register the stream of the URL.
void AbortPendingStream(const GURL& url);
private:
typedef std::map<GURL, scoped_refptr<Stream> > StreamMap;
StreamMap streams_;
std::map<GURL, StreamRegisterObserver*> register_observers_;
std::set<GURL> reader_aborted_urls_;
size_t total_memory_usage_;
// Maximum amount of memory allowed to use for Stream instances registered
// with this registry.
size_t max_memory_usage_;
SEQUENCE_CHECKER(sequence_checker_);
DISALLOW_COPY_AND_ASSIGN(StreamRegistry);
};
} // namespace content
#endif // CONTENT_BROWSER_STREAMS_STREAM_REGISTRY_H_
| null | null | null | null | 20,790 |
32,191 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 32,191 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2017 The Chromium 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 "third_party/blink/renderer/core/css/properties/longhands/webkit_border_vertical_spacing.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_context.h"
#include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h"
#include "third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h"
namespace blink {
namespace CSSLonghand {
const CSSValue* WebkitBorderVerticalSpacing::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
return CSSPropertyParserHelpers::ConsumeLength(range, context.Mode(),
kValueRangeNonNegative);
}
const CSSValue* WebkitBorderVerticalSpacing::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
Node*,
bool allow_visited_style) const {
return ZoomAdjustedPixelValue(style.VerticalBorderSpacing(), style);
}
} // namespace CSSLonghand
} // namespace blink
| null | null | null | null | 29,054 |
25,643 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 190,638 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | /*
* ARC PGU DRM driver.
*
* Copyright (C) 2016 Synopsys, Inc. (www.synopsys.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#ifndef _ARCPGU_H_
#define _ARCPGU_H_
struct arcpgu_drm_private {
void __iomem *regs;
struct clk *clk;
struct drm_fbdev_cma *fbdev;
struct drm_framebuffer *fb;
struct drm_crtc crtc;
struct drm_plane *plane;
};
#define crtc_to_arcpgu_priv(x) container_of(x, struct arcpgu_drm_private, crtc)
static inline void arc_pgu_write(struct arcpgu_drm_private *arcpgu,
unsigned int reg, u32 value)
{
iowrite32(value, arcpgu->regs + reg);
}
static inline u32 arc_pgu_read(struct arcpgu_drm_private *arcpgu,
unsigned int reg)
{
return ioread32(arcpgu->regs + reg);
}
int arc_pgu_setup_crtc(struct drm_device *dev);
int arcpgu_drm_hdmi_init(struct drm_device *drm, struct device_node *np);
int arcpgu_drm_sim_init(struct drm_device *drm, struct device_node *np);
struct drm_fbdev_cma *arcpgu_fbdev_cma_init(struct drm_device *dev,
unsigned int preferred_bpp, unsigned int num_crtc,
unsigned int max_conn_count);
#endif
| null | null | null | null | 98,985 |
20,950 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 185,945 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | /*
* drivers/net/bond/bond_netlink.c - Netlink interface for bonding
* Copyright (c) 2013 Jiri Pirko <jiri@resnulli.us>
* Copyright (c) 2013 Scott Feldman <sfeldma@cumulusnetworks.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/if_link.h>
#include <linux/if_ether.h>
#include <net/netlink.h>
#include <net/rtnetlink.h>
#include <net/bonding.h>
static size_t bond_get_slave_size(const struct net_device *bond_dev,
const struct net_device *slave_dev)
{
return nla_total_size(sizeof(u8)) + /* IFLA_BOND_SLAVE_STATE */
nla_total_size(sizeof(u8)) + /* IFLA_BOND_SLAVE_MII_STATUS */
nla_total_size(sizeof(u32)) + /* IFLA_BOND_SLAVE_LINK_FAILURE_COUNT */
nla_total_size(MAX_ADDR_LEN) + /* IFLA_BOND_SLAVE_PERM_HWADDR */
nla_total_size(sizeof(u16)) + /* IFLA_BOND_SLAVE_QUEUE_ID */
nla_total_size(sizeof(u16)) + /* IFLA_BOND_SLAVE_AD_AGGREGATOR_ID */
nla_total_size(sizeof(u8)) + /* IFLA_BOND_SLAVE_AD_ACTOR_OPER_PORT_STATE */
nla_total_size(sizeof(u16)) + /* IFLA_BOND_SLAVE_AD_PARTNER_OPER_PORT_STATE */
0;
}
static int bond_fill_slave_info(struct sk_buff *skb,
const struct net_device *bond_dev,
const struct net_device *slave_dev)
{
struct slave *slave = bond_slave_get_rtnl(slave_dev);
if (nla_put_u8(skb, IFLA_BOND_SLAVE_STATE, bond_slave_state(slave)))
goto nla_put_failure;
if (nla_put_u8(skb, IFLA_BOND_SLAVE_MII_STATUS, slave->link))
goto nla_put_failure;
if (nla_put_u32(skb, IFLA_BOND_SLAVE_LINK_FAILURE_COUNT,
slave->link_failure_count))
goto nla_put_failure;
if (nla_put(skb, IFLA_BOND_SLAVE_PERM_HWADDR,
slave_dev->addr_len, slave->perm_hwaddr))
goto nla_put_failure;
if (nla_put_u16(skb, IFLA_BOND_SLAVE_QUEUE_ID, slave->queue_id))
goto nla_put_failure;
if (BOND_MODE(slave->bond) == BOND_MODE_8023AD) {
const struct aggregator *agg;
const struct port *ad_port;
ad_port = &SLAVE_AD_INFO(slave)->port;
agg = SLAVE_AD_INFO(slave)->port.aggregator;
if (agg) {
if (nla_put_u16(skb, IFLA_BOND_SLAVE_AD_AGGREGATOR_ID,
agg->aggregator_identifier))
goto nla_put_failure;
if (nla_put_u8(skb,
IFLA_BOND_SLAVE_AD_ACTOR_OPER_PORT_STATE,
ad_port->actor_oper_port_state))
goto nla_put_failure;
if (nla_put_u16(skb,
IFLA_BOND_SLAVE_AD_PARTNER_OPER_PORT_STATE,
ad_port->partner_oper.port_state))
goto nla_put_failure;
}
}
return 0;
nla_put_failure:
return -EMSGSIZE;
}
static const struct nla_policy bond_policy[IFLA_BOND_MAX + 1] = {
[IFLA_BOND_MODE] = { .type = NLA_U8 },
[IFLA_BOND_ACTIVE_SLAVE] = { .type = NLA_U32 },
[IFLA_BOND_MIIMON] = { .type = NLA_U32 },
[IFLA_BOND_UPDELAY] = { .type = NLA_U32 },
[IFLA_BOND_DOWNDELAY] = { .type = NLA_U32 },
[IFLA_BOND_USE_CARRIER] = { .type = NLA_U8 },
[IFLA_BOND_ARP_INTERVAL] = { .type = NLA_U32 },
[IFLA_BOND_ARP_IP_TARGET] = { .type = NLA_NESTED },
[IFLA_BOND_ARP_VALIDATE] = { .type = NLA_U32 },
[IFLA_BOND_ARP_ALL_TARGETS] = { .type = NLA_U32 },
[IFLA_BOND_PRIMARY] = { .type = NLA_U32 },
[IFLA_BOND_PRIMARY_RESELECT] = { .type = NLA_U8 },
[IFLA_BOND_FAIL_OVER_MAC] = { .type = NLA_U8 },
[IFLA_BOND_XMIT_HASH_POLICY] = { .type = NLA_U8 },
[IFLA_BOND_RESEND_IGMP] = { .type = NLA_U32 },
[IFLA_BOND_NUM_PEER_NOTIF] = { .type = NLA_U8 },
[IFLA_BOND_ALL_SLAVES_ACTIVE] = { .type = NLA_U8 },
[IFLA_BOND_MIN_LINKS] = { .type = NLA_U32 },
[IFLA_BOND_LP_INTERVAL] = { .type = NLA_U32 },
[IFLA_BOND_PACKETS_PER_SLAVE] = { .type = NLA_U32 },
[IFLA_BOND_AD_LACP_RATE] = { .type = NLA_U8 },
[IFLA_BOND_AD_SELECT] = { .type = NLA_U8 },
[IFLA_BOND_AD_INFO] = { .type = NLA_NESTED },
[IFLA_BOND_AD_ACTOR_SYS_PRIO] = { .type = NLA_U16 },
[IFLA_BOND_AD_USER_PORT_KEY] = { .type = NLA_U16 },
[IFLA_BOND_AD_ACTOR_SYSTEM] = { .type = NLA_BINARY,
.len = ETH_ALEN },
[IFLA_BOND_TLB_DYNAMIC_LB] = { .type = NLA_U8 },
};
static const struct nla_policy bond_slave_policy[IFLA_BOND_SLAVE_MAX + 1] = {
[IFLA_BOND_SLAVE_QUEUE_ID] = { .type = NLA_U16 },
};
static int bond_validate(struct nlattr *tb[], struct nlattr *data[])
{
if (tb[IFLA_ADDRESS]) {
if (nla_len(tb[IFLA_ADDRESS]) != ETH_ALEN)
return -EINVAL;
if (!is_valid_ether_addr(nla_data(tb[IFLA_ADDRESS])))
return -EADDRNOTAVAIL;
}
return 0;
}
static int bond_slave_changelink(struct net_device *bond_dev,
struct net_device *slave_dev,
struct nlattr *tb[], struct nlattr *data[])
{
struct bonding *bond = netdev_priv(bond_dev);
struct bond_opt_value newval;
int err;
if (!data)
return 0;
if (data[IFLA_BOND_SLAVE_QUEUE_ID]) {
u16 queue_id = nla_get_u16(data[IFLA_BOND_SLAVE_QUEUE_ID]);
char queue_id_str[IFNAMSIZ + 7];
/* queue_id option setting expects slave_name:queue_id */
snprintf(queue_id_str, sizeof(queue_id_str), "%s:%u\n",
slave_dev->name, queue_id);
bond_opt_initstr(&newval, queue_id_str);
err = __bond_opt_set(bond, BOND_OPT_QUEUE_ID, &newval);
if (err)
return err;
}
return 0;
}
static int bond_changelink(struct net_device *bond_dev,
struct nlattr *tb[], struct nlattr *data[])
{
struct bonding *bond = netdev_priv(bond_dev);
struct bond_opt_value newval;
int miimon = 0;
int err;
if (!data)
return 0;
if (data[IFLA_BOND_MODE]) {
int mode = nla_get_u8(data[IFLA_BOND_MODE]);
bond_opt_initval(&newval, mode);
err = __bond_opt_set(bond, BOND_OPT_MODE, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_ACTIVE_SLAVE]) {
int ifindex = nla_get_u32(data[IFLA_BOND_ACTIVE_SLAVE]);
struct net_device *slave_dev;
char *active_slave = "";
if (ifindex != 0) {
slave_dev = __dev_get_by_index(dev_net(bond_dev),
ifindex);
if (!slave_dev)
return -ENODEV;
active_slave = slave_dev->name;
}
bond_opt_initstr(&newval, active_slave);
err = __bond_opt_set(bond, BOND_OPT_ACTIVE_SLAVE, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_MIIMON]) {
miimon = nla_get_u32(data[IFLA_BOND_MIIMON]);
bond_opt_initval(&newval, miimon);
err = __bond_opt_set(bond, BOND_OPT_MIIMON, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_UPDELAY]) {
int updelay = nla_get_u32(data[IFLA_BOND_UPDELAY]);
bond_opt_initval(&newval, updelay);
err = __bond_opt_set(bond, BOND_OPT_UPDELAY, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_DOWNDELAY]) {
int downdelay = nla_get_u32(data[IFLA_BOND_DOWNDELAY]);
bond_opt_initval(&newval, downdelay);
err = __bond_opt_set(bond, BOND_OPT_DOWNDELAY, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_USE_CARRIER]) {
int use_carrier = nla_get_u8(data[IFLA_BOND_USE_CARRIER]);
bond_opt_initval(&newval, use_carrier);
err = __bond_opt_set(bond, BOND_OPT_USE_CARRIER, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_ARP_INTERVAL]) {
int arp_interval = nla_get_u32(data[IFLA_BOND_ARP_INTERVAL]);
if (arp_interval && miimon) {
netdev_err(bond->dev, "ARP monitoring cannot be used with MII monitoring\n");
return -EINVAL;
}
bond_opt_initval(&newval, arp_interval);
err = __bond_opt_set(bond, BOND_OPT_ARP_INTERVAL, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_ARP_IP_TARGET]) {
struct nlattr *attr;
int i = 0, rem;
bond_option_arp_ip_targets_clear(bond);
nla_for_each_nested(attr, data[IFLA_BOND_ARP_IP_TARGET], rem) {
__be32 target;
if (nla_len(attr) < sizeof(target))
return -EINVAL;
target = nla_get_be32(attr);
bond_opt_initval(&newval, (__force u64)target);
err = __bond_opt_set(bond, BOND_OPT_ARP_TARGETS,
&newval);
if (err)
break;
i++;
}
if (i == 0 && bond->params.arp_interval)
netdev_warn(bond->dev, "Removing last arp target with arp_interval on\n");
if (err)
return err;
}
if (data[IFLA_BOND_ARP_VALIDATE]) {
int arp_validate = nla_get_u32(data[IFLA_BOND_ARP_VALIDATE]);
if (arp_validate && miimon) {
netdev_err(bond->dev, "ARP validating cannot be used with MII monitoring\n");
return -EINVAL;
}
bond_opt_initval(&newval, arp_validate);
err = __bond_opt_set(bond, BOND_OPT_ARP_VALIDATE, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_ARP_ALL_TARGETS]) {
int arp_all_targets =
nla_get_u32(data[IFLA_BOND_ARP_ALL_TARGETS]);
bond_opt_initval(&newval, arp_all_targets);
err = __bond_opt_set(bond, BOND_OPT_ARP_ALL_TARGETS, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_PRIMARY]) {
int ifindex = nla_get_u32(data[IFLA_BOND_PRIMARY]);
struct net_device *dev;
char *primary = "";
dev = __dev_get_by_index(dev_net(bond_dev), ifindex);
if (dev)
primary = dev->name;
bond_opt_initstr(&newval, primary);
err = __bond_opt_set(bond, BOND_OPT_PRIMARY, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_PRIMARY_RESELECT]) {
int primary_reselect =
nla_get_u8(data[IFLA_BOND_PRIMARY_RESELECT]);
bond_opt_initval(&newval, primary_reselect);
err = __bond_opt_set(bond, BOND_OPT_PRIMARY_RESELECT, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_FAIL_OVER_MAC]) {
int fail_over_mac =
nla_get_u8(data[IFLA_BOND_FAIL_OVER_MAC]);
bond_opt_initval(&newval, fail_over_mac);
err = __bond_opt_set(bond, BOND_OPT_FAIL_OVER_MAC, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_XMIT_HASH_POLICY]) {
int xmit_hash_policy =
nla_get_u8(data[IFLA_BOND_XMIT_HASH_POLICY]);
bond_opt_initval(&newval, xmit_hash_policy);
err = __bond_opt_set(bond, BOND_OPT_XMIT_HASH, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_RESEND_IGMP]) {
int resend_igmp =
nla_get_u32(data[IFLA_BOND_RESEND_IGMP]);
bond_opt_initval(&newval, resend_igmp);
err = __bond_opt_set(bond, BOND_OPT_RESEND_IGMP, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_NUM_PEER_NOTIF]) {
int num_peer_notif =
nla_get_u8(data[IFLA_BOND_NUM_PEER_NOTIF]);
bond_opt_initval(&newval, num_peer_notif);
err = __bond_opt_set(bond, BOND_OPT_NUM_PEER_NOTIF, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_ALL_SLAVES_ACTIVE]) {
int all_slaves_active =
nla_get_u8(data[IFLA_BOND_ALL_SLAVES_ACTIVE]);
bond_opt_initval(&newval, all_slaves_active);
err = __bond_opt_set(bond, BOND_OPT_ALL_SLAVES_ACTIVE, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_MIN_LINKS]) {
int min_links =
nla_get_u32(data[IFLA_BOND_MIN_LINKS]);
bond_opt_initval(&newval, min_links);
err = __bond_opt_set(bond, BOND_OPT_MINLINKS, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_LP_INTERVAL]) {
int lp_interval =
nla_get_u32(data[IFLA_BOND_LP_INTERVAL]);
bond_opt_initval(&newval, lp_interval);
err = __bond_opt_set(bond, BOND_OPT_LP_INTERVAL, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_PACKETS_PER_SLAVE]) {
int packets_per_slave =
nla_get_u32(data[IFLA_BOND_PACKETS_PER_SLAVE]);
bond_opt_initval(&newval, packets_per_slave);
err = __bond_opt_set(bond, BOND_OPT_PACKETS_PER_SLAVE, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_AD_LACP_RATE]) {
int lacp_rate =
nla_get_u8(data[IFLA_BOND_AD_LACP_RATE]);
bond_opt_initval(&newval, lacp_rate);
err = __bond_opt_set(bond, BOND_OPT_LACP_RATE, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_AD_SELECT]) {
int ad_select =
nla_get_u8(data[IFLA_BOND_AD_SELECT]);
bond_opt_initval(&newval, ad_select);
err = __bond_opt_set(bond, BOND_OPT_AD_SELECT, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_AD_ACTOR_SYS_PRIO]) {
int actor_sys_prio =
nla_get_u16(data[IFLA_BOND_AD_ACTOR_SYS_PRIO]);
bond_opt_initval(&newval, actor_sys_prio);
err = __bond_opt_set(bond, BOND_OPT_AD_ACTOR_SYS_PRIO, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_AD_USER_PORT_KEY]) {
int port_key =
nla_get_u16(data[IFLA_BOND_AD_USER_PORT_KEY]);
bond_opt_initval(&newval, port_key);
err = __bond_opt_set(bond, BOND_OPT_AD_USER_PORT_KEY, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_AD_ACTOR_SYSTEM]) {
if (nla_len(data[IFLA_BOND_AD_ACTOR_SYSTEM]) != ETH_ALEN)
return -EINVAL;
bond_opt_initval(&newval,
nla_get_be64(data[IFLA_BOND_AD_ACTOR_SYSTEM]));
err = __bond_opt_set(bond, BOND_OPT_AD_ACTOR_SYSTEM, &newval);
if (err)
return err;
}
if (data[IFLA_BOND_TLB_DYNAMIC_LB]) {
int dynamic_lb = nla_get_u8(data[IFLA_BOND_TLB_DYNAMIC_LB]);
bond_opt_initval(&newval, dynamic_lb);
err = __bond_opt_set(bond, BOND_OPT_TLB_DYNAMIC_LB, &newval);
if (err)
return err;
}
return 0;
}
static int bond_newlink(struct net *src_net, struct net_device *bond_dev,
struct nlattr *tb[], struct nlattr *data[])
{
int err;
err = bond_changelink(bond_dev, tb, data);
if (err < 0)
return err;
err = register_netdevice(bond_dev);
netif_carrier_off(bond_dev);
return err;
}
static size_t bond_get_size(const struct net_device *bond_dev)
{
return nla_total_size(sizeof(u8)) + /* IFLA_BOND_MODE */
nla_total_size(sizeof(u32)) + /* IFLA_BOND_ACTIVE_SLAVE */
nla_total_size(sizeof(u32)) + /* IFLA_BOND_MIIMON */
nla_total_size(sizeof(u32)) + /* IFLA_BOND_UPDELAY */
nla_total_size(sizeof(u32)) + /* IFLA_BOND_DOWNDELAY */
nla_total_size(sizeof(u8)) + /* IFLA_BOND_USE_CARRIER */
nla_total_size(sizeof(u32)) + /* IFLA_BOND_ARP_INTERVAL */
/* IFLA_BOND_ARP_IP_TARGET */
nla_total_size(sizeof(struct nlattr)) +
nla_total_size(sizeof(u32)) * BOND_MAX_ARP_TARGETS +
nla_total_size(sizeof(u32)) + /* IFLA_BOND_ARP_VALIDATE */
nla_total_size(sizeof(u32)) + /* IFLA_BOND_ARP_ALL_TARGETS */
nla_total_size(sizeof(u32)) + /* IFLA_BOND_PRIMARY */
nla_total_size(sizeof(u8)) + /* IFLA_BOND_PRIMARY_RESELECT */
nla_total_size(sizeof(u8)) + /* IFLA_BOND_FAIL_OVER_MAC */
nla_total_size(sizeof(u8)) + /* IFLA_BOND_XMIT_HASH_POLICY */
nla_total_size(sizeof(u32)) + /* IFLA_BOND_RESEND_IGMP */
nla_total_size(sizeof(u8)) + /* IFLA_BOND_NUM_PEER_NOTIF */
nla_total_size(sizeof(u8)) + /* IFLA_BOND_ALL_SLAVES_ACTIVE */
nla_total_size(sizeof(u32)) + /* IFLA_BOND_MIN_LINKS */
nla_total_size(sizeof(u32)) + /* IFLA_BOND_LP_INTERVAL */
nla_total_size(sizeof(u32)) + /* IFLA_BOND_PACKETS_PER_SLAVE */
nla_total_size(sizeof(u8)) + /* IFLA_BOND_AD_LACP_RATE */
nla_total_size(sizeof(u8)) + /* IFLA_BOND_AD_SELECT */
nla_total_size(sizeof(struct nlattr)) + /* IFLA_BOND_AD_INFO */
nla_total_size(sizeof(u16)) + /* IFLA_BOND_AD_INFO_AGGREGATOR */
nla_total_size(sizeof(u16)) + /* IFLA_BOND_AD_INFO_NUM_PORTS */
nla_total_size(sizeof(u16)) + /* IFLA_BOND_AD_INFO_ACTOR_KEY */
nla_total_size(sizeof(u16)) + /* IFLA_BOND_AD_INFO_PARTNER_KEY*/
nla_total_size(ETH_ALEN) + /* IFLA_BOND_AD_INFO_PARTNER_MAC*/
nla_total_size(sizeof(u16)) + /* IFLA_BOND_AD_ACTOR_SYS_PRIO */
nla_total_size(sizeof(u16)) + /* IFLA_BOND_AD_USER_PORT_KEY */
nla_total_size(ETH_ALEN) + /* IFLA_BOND_AD_ACTOR_SYSTEM */
nla_total_size(sizeof(u8)) + /* IFLA_BOND_TLB_DYNAMIC_LB */
0;
}
static int bond_option_active_slave_get_ifindex(struct bonding *bond)
{
const struct net_device *slave;
int ifindex;
rcu_read_lock();
slave = bond_option_active_slave_get_rcu(bond);
ifindex = slave ? slave->ifindex : 0;
rcu_read_unlock();
return ifindex;
}
static int bond_fill_info(struct sk_buff *skb,
const struct net_device *bond_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
unsigned int packets_per_slave;
int ifindex, i, targets_added;
struct nlattr *targets;
struct slave *primary;
if (nla_put_u8(skb, IFLA_BOND_MODE, BOND_MODE(bond)))
goto nla_put_failure;
ifindex = bond_option_active_slave_get_ifindex(bond);
if (ifindex && nla_put_u32(skb, IFLA_BOND_ACTIVE_SLAVE, ifindex))
goto nla_put_failure;
if (nla_put_u32(skb, IFLA_BOND_MIIMON, bond->params.miimon))
goto nla_put_failure;
if (nla_put_u32(skb, IFLA_BOND_UPDELAY,
bond->params.updelay * bond->params.miimon))
goto nla_put_failure;
if (nla_put_u32(skb, IFLA_BOND_DOWNDELAY,
bond->params.downdelay * bond->params.miimon))
goto nla_put_failure;
if (nla_put_u8(skb, IFLA_BOND_USE_CARRIER, bond->params.use_carrier))
goto nla_put_failure;
if (nla_put_u32(skb, IFLA_BOND_ARP_INTERVAL, bond->params.arp_interval))
goto nla_put_failure;
targets = nla_nest_start(skb, IFLA_BOND_ARP_IP_TARGET);
if (!targets)
goto nla_put_failure;
targets_added = 0;
for (i = 0; i < BOND_MAX_ARP_TARGETS; i++) {
if (bond->params.arp_targets[i]) {
nla_put_be32(skb, i, bond->params.arp_targets[i]);
targets_added = 1;
}
}
if (targets_added)
nla_nest_end(skb, targets);
else
nla_nest_cancel(skb, targets);
if (nla_put_u32(skb, IFLA_BOND_ARP_VALIDATE, bond->params.arp_validate))
goto nla_put_failure;
if (nla_put_u32(skb, IFLA_BOND_ARP_ALL_TARGETS,
bond->params.arp_all_targets))
goto nla_put_failure;
primary = rtnl_dereference(bond->primary_slave);
if (primary &&
nla_put_u32(skb, IFLA_BOND_PRIMARY, primary->dev->ifindex))
goto nla_put_failure;
if (nla_put_u8(skb, IFLA_BOND_PRIMARY_RESELECT,
bond->params.primary_reselect))
goto nla_put_failure;
if (nla_put_u8(skb, IFLA_BOND_FAIL_OVER_MAC,
bond->params.fail_over_mac))
goto nla_put_failure;
if (nla_put_u8(skb, IFLA_BOND_XMIT_HASH_POLICY,
bond->params.xmit_policy))
goto nla_put_failure;
if (nla_put_u32(skb, IFLA_BOND_RESEND_IGMP,
bond->params.resend_igmp))
goto nla_put_failure;
if (nla_put_u8(skb, IFLA_BOND_NUM_PEER_NOTIF,
bond->params.num_peer_notif))
goto nla_put_failure;
if (nla_put_u8(skb, IFLA_BOND_ALL_SLAVES_ACTIVE,
bond->params.all_slaves_active))
goto nla_put_failure;
if (nla_put_u32(skb, IFLA_BOND_MIN_LINKS,
bond->params.min_links))
goto nla_put_failure;
if (nla_put_u32(skb, IFLA_BOND_LP_INTERVAL,
bond->params.lp_interval))
goto nla_put_failure;
packets_per_slave = bond->params.packets_per_slave;
if (nla_put_u32(skb, IFLA_BOND_PACKETS_PER_SLAVE,
packets_per_slave))
goto nla_put_failure;
if (nla_put_u8(skb, IFLA_BOND_AD_LACP_RATE,
bond->params.lacp_fast))
goto nla_put_failure;
if (nla_put_u8(skb, IFLA_BOND_AD_SELECT,
bond->params.ad_select))
goto nla_put_failure;
if (nla_put_u8(skb, IFLA_BOND_TLB_DYNAMIC_LB,
bond->params.tlb_dynamic_lb))
goto nla_put_failure;
if (BOND_MODE(bond) == BOND_MODE_8023AD) {
struct ad_info info;
if (capable(CAP_NET_ADMIN)) {
if (nla_put_u16(skb, IFLA_BOND_AD_ACTOR_SYS_PRIO,
bond->params.ad_actor_sys_prio))
goto nla_put_failure;
if (nla_put_u16(skb, IFLA_BOND_AD_USER_PORT_KEY,
bond->params.ad_user_port_key))
goto nla_put_failure;
if (nla_put(skb, IFLA_BOND_AD_ACTOR_SYSTEM,
sizeof(bond->params.ad_actor_system),
&bond->params.ad_actor_system))
goto nla_put_failure;
}
if (!bond_3ad_get_active_agg_info(bond, &info)) {
struct nlattr *nest;
nest = nla_nest_start(skb, IFLA_BOND_AD_INFO);
if (!nest)
goto nla_put_failure;
if (nla_put_u16(skb, IFLA_BOND_AD_INFO_AGGREGATOR,
info.aggregator_id))
goto nla_put_failure;
if (nla_put_u16(skb, IFLA_BOND_AD_INFO_NUM_PORTS,
info.ports))
goto nla_put_failure;
if (nla_put_u16(skb, IFLA_BOND_AD_INFO_ACTOR_KEY,
info.actor_key))
goto nla_put_failure;
if (nla_put_u16(skb, IFLA_BOND_AD_INFO_PARTNER_KEY,
info.partner_key))
goto nla_put_failure;
if (nla_put(skb, IFLA_BOND_AD_INFO_PARTNER_MAC,
sizeof(info.partner_system),
&info.partner_system))
goto nla_put_failure;
nla_nest_end(skb, nest);
}
}
return 0;
nla_put_failure:
return -EMSGSIZE;
}
struct rtnl_link_ops bond_link_ops __read_mostly = {
.kind = "bond",
.priv_size = sizeof(struct bonding),
.setup = bond_setup,
.maxtype = IFLA_BOND_MAX,
.policy = bond_policy,
.validate = bond_validate,
.newlink = bond_newlink,
.changelink = bond_changelink,
.get_size = bond_get_size,
.fill_info = bond_fill_info,
.get_num_tx_queues = bond_get_num_tx_queues,
.get_num_rx_queues = bond_get_num_tx_queues, /* Use the same number
as for TX queues */
.slave_maxtype = IFLA_BOND_SLAVE_MAX,
.slave_policy = bond_slave_policy,
.slave_changelink = bond_slave_changelink,
.get_slave_size = bond_get_slave_size,
.fill_slave_info = bond_fill_slave_info,
};
int __init bond_netlink_init(void)
{
return rtnl_link_register(&bond_link_ops);
}
void bond_netlink_fini(void)
{
rtnl_link_unregister(&bond_link_ops);
}
MODULE_ALIAS_RTNL_LINK("bond");
| null | null | null | null | 94,292 |
44,842 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 44,842 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2016 The Chromium 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 PPAPI_SHARED_IMPL_PPB_FLASH_FONT_FILE_SHARED_H_
#define PPAPI_SHARED_IMPL_PPB_FLASH_FONT_FILE_SHARED_H_
#include "ppapi/c/pp_bool.h"
namespace ppapi {
class PPB_Flash_FontFile_Shared {
public:
static PP_Bool IsSupportedForWindows() { return PP_TRUE; }
};
} // namespace ppapi
#endif // PPAPI_SHARED_IMPL_PPB_FLASH_FONT_FILE_SHARED_H_ | null | null | null | null | 41,705 |
25,168 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 25,168 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2013 The Chromium 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 "extensions/common/permissions/permission_message.h"
namespace extensions {
PermissionMessage::PermissionMessage(const base::string16& message,
const PermissionIDSet& permissions)
: message_(message), permissions_(permissions) {}
PermissionMessage::PermissionMessage(
const base::string16& message,
const PermissionIDSet& permissions,
const std::vector<base::string16>& submessages)
: message_(message), permissions_(permissions), submessages_(submessages) {}
PermissionMessage::PermissionMessage(const PermissionMessage& other) = default;
PermissionMessage::~PermissionMessage() {}
} // namespace extensions
| null | null | null | null | 22,031 |
2,132 | null | train_val | 04b570817b2b38e35675b17328239746212f4c3f | 155,189 | FFmpeg | 0 | https://github.com/FFmpeg/FFmpeg | 2018-06-01 01:23:12+05:30 | /*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libavutil/avassert.h"
#include "cbs.h"
#include "cbs_internal.h"
#include "cbs_mpeg2.h"
#include "internal.h"
#define HEADER(name) do { \
ff_cbs_trace_header(ctx, name); \
} while (0)
#define CHECK(call) do { \
err = (call); \
if (err < 0) \
return err; \
} while (0)
#define FUNC_NAME(rw, codec, name) cbs_ ## codec ## _ ## rw ## _ ## name
#define FUNC_MPEG2(rw, name) FUNC_NAME(rw, mpeg2, name)
#define FUNC(name) FUNC_MPEG2(READWRITE, name)
#define SUBSCRIPTS(subs, ...) (subs > 0 ? ((int[subs + 1]){ subs, __VA_ARGS__ }) : NULL)
#define ui(width, name) \
xui(width, name, current->name, 0)
#define uis(width, name, subs, ...) \
xui(width, name, current->name, subs, __VA_ARGS__)
#define READ
#define READWRITE read
#define RWContext GetBitContext
#define xui(width, name, var, subs, ...) do { \
uint32_t value = 0; \
CHECK(ff_cbs_read_unsigned(ctx, rw, width, #name, \
SUBSCRIPTS(subs, __VA_ARGS__), \
&value, 0, (1 << width) - 1)); \
var = value; \
} while (0)
#define marker_bit() do { \
av_unused uint32_t one; \
CHECK(ff_cbs_read_unsigned(ctx, rw, 1, "marker_bit", NULL, &one, 1, 1)); \
} while (0)
#define nextbits(width, compare, var) \
(get_bits_left(rw) >= width && \
(var = show_bits(rw, width)) == (compare))
#include "cbs_mpeg2_syntax_template.c"
#undef READ
#undef READWRITE
#undef RWContext
#undef xui
#undef marker_bit
#undef nextbits
#define WRITE
#define READWRITE write
#define RWContext PutBitContext
#define xui(width, name, var, subs, ...) do { \
CHECK(ff_cbs_write_unsigned(ctx, rw, width, #name, \
SUBSCRIPTS(subs, __VA_ARGS__), \
var, 0, (1 << width) - 1)); \
} while (0)
#define marker_bit() do { \
CHECK(ff_cbs_write_unsigned(ctx, rw, 1, "marker_bit", NULL, 1, 1, 1)); \
} while (0)
#define nextbits(width, compare, var) (var)
#include "cbs_mpeg2_syntax_template.c"
#undef READ
#undef READWRITE
#undef RWContext
#undef xui
#undef marker_bit
#undef nextbits
static void cbs_mpeg2_free_user_data(void *unit, uint8_t *content)
{
MPEG2RawUserData *user = (MPEG2RawUserData*)content;
av_buffer_unref(&user->user_data_ref);
av_freep(&content);
}
static void cbs_mpeg2_free_slice(void *unit, uint8_t *content)
{
MPEG2RawSlice *slice = (MPEG2RawSlice*)content;
av_buffer_unref(&slice->header.extra_information_ref);
av_buffer_unref(&slice->data_ref);
av_freep(&content);
}
static int cbs_mpeg2_split_fragment(CodedBitstreamContext *ctx,
CodedBitstreamFragment *frag,
int header)
{
const uint8_t *start, *end;
uint8_t *unit_data;
uint32_t start_code = -1, next_start_code = -1;
size_t unit_size;
int err, i, unit_type;
start = avpriv_find_start_code(frag->data, frag->data + frag->data_size,
&start_code);
for (i = 0;; i++) {
end = avpriv_find_start_code(start, frag->data + frag->data_size,
&next_start_code);
unit_type = start_code & 0xff;
// The start and end pointers point at to the byte following the
// start_code_identifier in the start code that they found.
if (end == frag->data + frag->data_size) {
// We didn't find a start code, so this is the final unit.
unit_size = end - (start - 1);
} else {
// Unit runs from start to the beginning of the start code
// pointed to by end (including any padding zeroes).
unit_size = (end - 4) - (start - 1);
}
unit_data = (uint8_t *)start - 1;
err = ff_cbs_insert_unit_data(ctx, frag, i, unit_type,
unit_data, unit_size, frag->data_ref);
if (err < 0)
return err;
if (end == frag->data + frag->data_size)
break;
start_code = next_start_code;
start = end;
}
return 0;
}
static int cbs_mpeg2_read_unit(CodedBitstreamContext *ctx,
CodedBitstreamUnit *unit)
{
GetBitContext gbc;
int err;
err = init_get_bits(&gbc, unit->data, 8 * unit->data_size);
if (err < 0)
return err;
if (MPEG2_START_IS_SLICE(unit->type)) {
MPEG2RawSlice *slice;
int pos, len;
err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*slice),
&cbs_mpeg2_free_slice);
if (err < 0)
return err;
slice = unit->content;
err = cbs_mpeg2_read_slice_header(ctx, &gbc, &slice->header);
if (err < 0)
return err;
pos = get_bits_count(&gbc);
len = unit->data_size;
slice->data_size = len - pos / 8;
slice->data_ref = av_buffer_ref(unit->data_ref);
if (!slice->data_ref)
return AVERROR(ENOMEM);
slice->data = unit->data + pos / 8;
slice->data_bit_start = pos % 8;
} else {
switch (unit->type) {
#define START(start_code, type, read_func, free_func) \
case start_code: \
{ \
type *header; \
err = ff_cbs_alloc_unit_content(ctx, unit, \
sizeof(*header), free_func); \
if (err < 0) \
return err; \
header = unit->content; \
err = cbs_mpeg2_read_ ## read_func(ctx, &gbc, header); \
if (err < 0) \
return err; \
} \
break;
START(0x00, MPEG2RawPictureHeader, picture_header, NULL);
START(0xb2, MPEG2RawUserData, user_data,
&cbs_mpeg2_free_user_data);
START(0xb3, MPEG2RawSequenceHeader, sequence_header, NULL);
START(0xb5, MPEG2RawExtensionData, extension_data, NULL);
START(0xb8, MPEG2RawGroupOfPicturesHeader,
group_of_pictures_header, NULL);
#undef START
default:
av_log(ctx->log_ctx, AV_LOG_ERROR, "Unknown start code %02"PRIx32".\n",
unit->type);
return AVERROR_INVALIDDATA;
}
}
return 0;
}
static int cbs_mpeg2_write_header(CodedBitstreamContext *ctx,
CodedBitstreamUnit *unit,
PutBitContext *pbc)
{
int err;
switch (unit->type) {
#define START(start_code, type, func) \
case start_code: \
err = cbs_mpeg2_write_ ## func(ctx, pbc, unit->content); \
break;
START(0x00, MPEG2RawPictureHeader, picture_header);
START(0xb2, MPEG2RawUserData, user_data);
START(0xb3, MPEG2RawSequenceHeader, sequence_header);
START(0xb5, MPEG2RawExtensionData, extension_data);
START(0xb8, MPEG2RawGroupOfPicturesHeader, group_of_pictures_header);
#undef START
default:
av_log(ctx->log_ctx, AV_LOG_ERROR, "Write unimplemented for start "
"code %02"PRIx32".\n", unit->type);
return AVERROR_PATCHWELCOME;
}
return err;
}
static int cbs_mpeg2_write_slice(CodedBitstreamContext *ctx,
CodedBitstreamUnit *unit,
PutBitContext *pbc)
{
MPEG2RawSlice *slice = unit->content;
GetBitContext gbc;
size_t bits_left;
int err;
err = cbs_mpeg2_write_slice_header(ctx, pbc, &slice->header);
if (err < 0)
return err;
if (slice->data) {
if (slice->data_size * 8 + 8 > put_bits_left(pbc))
return AVERROR(ENOSPC);
init_get_bits(&gbc, slice->data, slice->data_size * 8);
skip_bits_long(&gbc, slice->data_bit_start);
while (get_bits_left(&gbc) > 15)
put_bits(pbc, 16, get_bits(&gbc, 16));
bits_left = get_bits_left(&gbc);
put_bits(pbc, bits_left, get_bits(&gbc, bits_left));
// Align with zeroes.
while (put_bits_count(pbc) % 8 != 0)
put_bits(pbc, 1, 0);
}
return 0;
}
static int cbs_mpeg2_write_unit(CodedBitstreamContext *ctx,
CodedBitstreamUnit *unit)
{
CodedBitstreamMPEG2Context *priv = ctx->priv_data;
PutBitContext pbc;
int err;
if (!priv->write_buffer) {
// Initial write buffer size is 1MB.
priv->write_buffer_size = 1024 * 1024;
reallocate_and_try_again:
err = av_reallocp(&priv->write_buffer, priv->write_buffer_size);
if (err < 0) {
av_log(ctx->log_ctx, AV_LOG_ERROR, "Unable to allocate a "
"sufficiently large write buffer (last attempt "
"%"SIZE_SPECIFIER" bytes).\n", priv->write_buffer_size);
return err;
}
}
init_put_bits(&pbc, priv->write_buffer, priv->write_buffer_size);
if (unit->type >= 0x01 && unit->type <= 0xaf)
err = cbs_mpeg2_write_slice(ctx, unit, &pbc);
else
err = cbs_mpeg2_write_header(ctx, unit, &pbc);
if (err == AVERROR(ENOSPC)) {
// Overflow.
priv->write_buffer_size *= 2;
goto reallocate_and_try_again;
}
if (err < 0) {
// Write failed for some other reason.
return err;
}
if (put_bits_count(&pbc) % 8)
unit->data_bit_padding = 8 - put_bits_count(&pbc) % 8;
else
unit->data_bit_padding = 0;
unit->data_size = (put_bits_count(&pbc) + 7) / 8;
flush_put_bits(&pbc);
err = ff_cbs_alloc_unit_data(ctx, unit, unit->data_size);
if (err < 0)
return err;
memcpy(unit->data, priv->write_buffer, unit->data_size);
return 0;
}
static int cbs_mpeg2_assemble_fragment(CodedBitstreamContext *ctx,
CodedBitstreamFragment *frag)
{
uint8_t *data;
size_t size, dp;
int i;
size = 0;
for (i = 0; i < frag->nb_units; i++)
size += 3 + frag->units[i].data_size;
frag->data_ref = av_buffer_alloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
if (!frag->data_ref)
return AVERROR(ENOMEM);
data = frag->data_ref->data;
dp = 0;
for (i = 0; i < frag->nb_units; i++) {
CodedBitstreamUnit *unit = &frag->units[i];
data[dp++] = 0;
data[dp++] = 0;
data[dp++] = 1;
memcpy(data + dp, unit->data, unit->data_size);
dp += unit->data_size;
}
av_assert0(dp == size);
memset(data + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
frag->data = data;
frag->data_size = size;
return 0;
}
static void cbs_mpeg2_close(CodedBitstreamContext *ctx)
{
CodedBitstreamMPEG2Context *priv = ctx->priv_data;
av_freep(&priv->write_buffer);
}
const CodedBitstreamType ff_cbs_type_mpeg2 = {
.codec_id = AV_CODEC_ID_MPEG2VIDEO,
.priv_data_size = sizeof(CodedBitstreamMPEG2Context),
.split_fragment = &cbs_mpeg2_split_fragment,
.read_unit = &cbs_mpeg2_read_unit,
.write_unit = &cbs_mpeg2_write_unit,
.assemble_fragment = &cbs_mpeg2_assemble_fragment,
.close = &cbs_mpeg2_close,
};
| null | null | null | null | 71,244 |
61,928 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 61,928 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2014 The Chromium 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 "chrome/browser/supervised_user/legacy/custodian_profile_downloader_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/pref_service.h"
#include "components/signin/core/browser/signin_manager.h"
#include "google_apis/gaia/gaia_auth_util.h"
CustodianProfileDownloaderService::CustodianProfileDownloaderService(
Profile* custodian_profile)
: custodian_profile_(custodian_profile) {
}
CustodianProfileDownloaderService::~CustodianProfileDownloaderService() {}
void CustodianProfileDownloaderService::Shutdown() {
profile_downloader_.reset();
}
void CustodianProfileDownloaderService::DownloadProfile(
const DownloadProfileCallback& callback) {
// The user must be logged in.
if (!SigninManagerFactory::GetForProfile(custodian_profile_)
->IsAuthenticated()) {
return;
}
download_callback_ = callback;
std::string current_email = custodian_profile_->GetProfileUserName();
if (gaia::AreEmailsSame(last_downloaded_profile_email_, current_email)) {
// Profile was previously downloaded successfully, use it as it is unlikely
// that we will need to download it again.
OnProfileDownloadSuccess(profile_downloader_.get());
return;
}
// If another profile download is in progress, drop it. It's not worth
// queueing them up, and more likely that the one that hasn't ended yet is
// failing somehow than that the new one won't succeed.
in_progress_profile_email_ = current_email;
profile_downloader_.reset(new ProfileDownloader(this));
profile_downloader_->Start();
}
bool CustodianProfileDownloaderService::NeedsProfilePicture() const {
return false;
}
int CustodianProfileDownloaderService::GetDesiredImageSideLength() const {
return 0;
}
std::string CustodianProfileDownloaderService::GetCachedPictureURL() const {
return std::string();
}
Profile* CustodianProfileDownloaderService::GetBrowserProfile() {
DCHECK(custodian_profile_);
return custodian_profile_;
}
bool CustodianProfileDownloaderService::IsPreSignin() const {
return false;
}
void CustodianProfileDownloaderService::OnProfileDownloadSuccess(
ProfileDownloader* downloader) {
download_callback_.Run(downloader->GetProfileFullName());
download_callback_.Reset();
last_downloaded_profile_email_ = in_progress_profile_email_;
}
void CustodianProfileDownloaderService::OnProfileDownloadFailure(
ProfileDownloader* downloader,
ProfileDownloaderDelegate::FailureReason reason) {
// Ignore failures; proceed without the custodian's name.
download_callback_.Reset();
profile_downloader_.reset();
}
| null | null | null | null | 58,791 |
14,710 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 14,710 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2015 The Chromium 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 "components/exo/sub_surface.h"
#include "base/memory/ptr_util.h"
#include "components/exo/shell_surface.h"
#include "components/exo/surface.h"
#include "components/exo/test/exo_test_base.h"
#include "components/exo/test/exo_test_helper.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace exo {
namespace {
using SubSurfaceTest = test::ExoTestBase;
TEST_F(SubSurfaceTest, SetPosition) {
auto parent = std::make_unique<Surface>();
auto shell_surface = std::make_unique<ShellSurface>(parent.get());
auto surface = std::make_unique<Surface>();
auto sub_surface = std::make_unique<SubSurface>(surface.get(), parent.get());
// Initial position is at the origin.
EXPECT_EQ(gfx::Point().ToString(),
surface->window()->bounds().origin().ToString());
// Set position to 10, 10.
gfx::Point position(10, 10);
sub_surface->SetPosition(position);
// A call to Commit() is required for position to take effect.
EXPECT_EQ(gfx::Point().ToString(),
surface->window()->bounds().origin().ToString());
// Check that position is updated when Commit() is called.
parent->Commit();
EXPECT_EQ(position.ToString(),
surface->window()->bounds().origin().ToString());
// Create and commit a new sub-surface using the same surface.
sub_surface.reset();
sub_surface = std::make_unique<SubSurface>(surface.get(), parent.get());
parent->Commit();
// Initial position should be reset to origin.
EXPECT_EQ(gfx::Point().ToString(),
surface->window()->bounds().origin().ToString());
}
TEST_F(SubSurfaceTest, PlaceAbove) {
auto parent = std::make_unique<Surface>();
auto shell_surface = std::make_unique<ShellSurface>(parent.get());
auto surface1 = std::make_unique<Surface>();
auto surface2 = std::make_unique<Surface>();
auto non_sibling_surface = std::make_unique<Surface>();
auto sub_surface1 =
std::make_unique<SubSurface>(surface1.get(), parent.get());
auto sub_surface2 =
std::make_unique<SubSurface>(surface2.get(), parent.get());
ASSERT_EQ(2u, parent->window()->children().size());
EXPECT_EQ(surface1->window(), parent->window()->children()[0]);
EXPECT_EQ(surface2->window(), parent->window()->children()[1]);
sub_surface2->PlaceAbove(parent.get());
sub_surface1->PlaceAbove(non_sibling_surface.get()); // Invalid
sub_surface1->PlaceAbove(surface1.get()); // Invalid
sub_surface1->PlaceAbove(surface2.get());
// Nothing should have changed as Commit() is required for new stacking
// order to take effect.
EXPECT_EQ(surface1->window(), parent->window()->children()[0]);
EXPECT_EQ(surface2->window(), parent->window()->children()[1]);
parent->Commit();
// surface1 should now be stacked above surface2.
EXPECT_EQ(surface2->window(), parent->window()->children()[0]);
EXPECT_EQ(surface1->window(), parent->window()->children()[1]);
}
TEST_F(SubSurfaceTest, PlaceBelow) {
auto parent = std::make_unique<Surface>();
auto shell_surface = std::make_unique<ShellSurface>(parent.get());
auto surface1 = std::make_unique<Surface>();
auto surface2 = std::make_unique<Surface>();
auto non_sibling_surface = std::make_unique<Surface>();
auto sub_surface1 =
std::make_unique<SubSurface>(surface1.get(), parent.get());
auto sub_surface2 =
std::make_unique<SubSurface>(surface2.get(), parent.get());
ASSERT_EQ(2u, parent->window()->children().size());
EXPECT_EQ(surface1->window(), parent->window()->children()[0]);
EXPECT_EQ(surface2->window(), parent->window()->children()[1]);
sub_surface2->PlaceBelow(parent.get()); // Invalid
sub_surface2->PlaceBelow(non_sibling_surface.get()); // Invalid
sub_surface1->PlaceBelow(surface2.get());
sub_surface2->PlaceBelow(surface1.get());
// Nothing should have changed as Commit() is required for new stacking
// order to take effect.
EXPECT_EQ(surface1->window(), parent->window()->children()[0]);
EXPECT_EQ(surface2->window(), parent->window()->children()[1]);
parent->Commit();
// surface1 should now be stacked above surface2.
EXPECT_EQ(surface2->window(), parent->window()->children()[0]);
EXPECT_EQ(surface1->window(), parent->window()->children()[1]);
}
TEST_F(SubSurfaceTest, SetCommitBehavior) {
auto parent = std::make_unique<Surface>();
auto shell_surface = std::make_unique<ShellSurface>(parent.get());
auto child = std::make_unique<Surface>();
auto grandchild = std::make_unique<Surface>();
auto child_sub_surface =
std::make_unique<SubSurface>(child.get(), parent.get());
auto grandchild_sub_surface =
std::make_unique<SubSurface>(grandchild.get(), child.get());
// Initial position is at the origin.
EXPECT_EQ(gfx::Point().ToString(),
grandchild->window()->bounds().origin().ToString());
// Set position to 10, 10.
gfx::Point position1(10, 10);
grandchild_sub_surface->SetPosition(position1);
child->Commit();
// Initial commit behavior is synchronous and the effect of the child
// Commit() call will not take effect until Commit() is called on the
// parent.
EXPECT_EQ(gfx::Point().ToString(),
grandchild->window()->bounds().origin().ToString());
parent->Commit();
// Position should have been updated when Commit() has been called on both
// child and parent.
EXPECT_EQ(position1.ToString(),
grandchild->window()->bounds().origin().ToString());
bool synchronized = false;
child_sub_surface->SetCommitBehavior(synchronized);
// Set position to 20, 20.
gfx::Point position2(20, 20);
grandchild_sub_surface->SetPosition(position2);
child->Commit();
// A Commit() call on child should be sufficient for the position of
// grandchild to take effect when synchronous is disabled.
EXPECT_EQ(position2.ToString(),
grandchild->window()->bounds().origin().ToString());
}
} // namespace
} // namespace exo
| null | null | null | null | 11,573 |
59,856 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 59,856 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2013 The Chromium 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 CHROME_BROWSER_PRINTING_CLOUD_PRINT_PRIVET_DEVICE_LISTER_H_
#define CHROME_BROWSER_PRINTING_CLOUD_PRINT_PRIVET_DEVICE_LISTER_H_
#include <string>
#include "chrome/browser/printing/cloud_print/device_description.h"
namespace cloud_print {
class PrivetDeviceLister {
public:
PrivetDeviceLister();
virtual ~PrivetDeviceLister();
class Delegate {
public:
virtual ~Delegate() {}
virtual void DeviceChanged(const std::string& name,
const DeviceDescription& description) = 0;
virtual void DeviceRemoved(const std::string& name) = 0;
virtual void DeviceCacheFlushed() = 0;
};
// Start the PrivetServiceLister.
virtual void Start() = 0;
virtual void DiscoverNewDevices() = 0;
};
} // namespace cloud_print
#endif // CHROME_BROWSER_PRINTING_CLOUD_PRINT_PRIVET_DEVICE_LISTER_H_
| null | null | null | null | 56,719 |
1,664 | null | train_val | 1b0d3845b454eaaac0b2064c78926ca4d739a080 | 264,232 | qemu | 0 | https://github.com/bonzini/qemu | 2016-10-18 11:40:27+01:00 | /*
* QEMU ISA MM VGA Emulator.
*
* Copyright (c) 2003 Fabrice Bellard
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "qemu/osdep.h"
#include "hw/hw.h"
#include "ui/console.h"
#include "hw/i386/pc.h"
#include "vga_int.h"
#include "ui/pixel_ops.h"
#include "qemu/timer.h"
#define VGA_RAM_SIZE (8192 * 1024)
typedef struct ISAVGAMMState {
VGACommonState vga;
int it_shift;
} ISAVGAMMState;
/* Memory mapped interface */
static uint32_t vga_mm_readb (void *opaque, hwaddr addr)
{
ISAVGAMMState *s = opaque;
return vga_ioport_read(&s->vga, addr >> s->it_shift) & 0xff;
}
static void vga_mm_writeb (void *opaque,
hwaddr addr, uint32_t value)
{
ISAVGAMMState *s = opaque;
vga_ioport_write(&s->vga, addr >> s->it_shift, value & 0xff);
}
static uint32_t vga_mm_readw (void *opaque, hwaddr addr)
{
ISAVGAMMState *s = opaque;
return vga_ioport_read(&s->vga, addr >> s->it_shift) & 0xffff;
}
static void vga_mm_writew (void *opaque,
hwaddr addr, uint32_t value)
{
ISAVGAMMState *s = opaque;
vga_ioport_write(&s->vga, addr >> s->it_shift, value & 0xffff);
}
static uint32_t vga_mm_readl (void *opaque, hwaddr addr)
{
ISAVGAMMState *s = opaque;
return vga_ioport_read(&s->vga, addr >> s->it_shift);
}
static void vga_mm_writel (void *opaque,
hwaddr addr, uint32_t value)
{
ISAVGAMMState *s = opaque;
vga_ioport_write(&s->vga, addr >> s->it_shift, value);
}
static const MemoryRegionOps vga_mm_ctrl_ops = {
.old_mmio = {
.read = {
vga_mm_readb,
vga_mm_readw,
vga_mm_readl,
},
.write = {
vga_mm_writeb,
vga_mm_writew,
vga_mm_writel,
},
},
.endianness = DEVICE_NATIVE_ENDIAN,
};
static void vga_mm_init(ISAVGAMMState *s, hwaddr vram_base,
hwaddr ctrl_base, int it_shift,
MemoryRegion *address_space)
{
MemoryRegion *s_ioport_ctrl, *vga_io_memory;
s->it_shift = it_shift;
s_ioport_ctrl = g_malloc(sizeof(*s_ioport_ctrl));
memory_region_init_io(s_ioport_ctrl, NULL, &vga_mm_ctrl_ops, s,
"vga-mm-ctrl", 0x100000);
memory_region_set_flush_coalesced(s_ioport_ctrl);
vga_io_memory = g_malloc(sizeof(*vga_io_memory));
/* XXX: endianness? */
memory_region_init_io(vga_io_memory, NULL, &vga_mem_ops, &s->vga,
"vga-mem", 0x20000);
vmstate_register(NULL, 0, &vmstate_vga_common, s);
memory_region_add_subregion(address_space, ctrl_base, s_ioport_ctrl);
s->vga.bank_offset = 0;
memory_region_add_subregion(address_space,
vram_base + 0x000a0000, vga_io_memory);
memory_region_set_coalescing(vga_io_memory);
}
int isa_vga_mm_init(hwaddr vram_base,
hwaddr ctrl_base, int it_shift,
MemoryRegion *address_space)
{
ISAVGAMMState *s;
s = g_malloc0(sizeof(*s));
s->vga.vram_size_mb = VGA_RAM_SIZE >> 20;
vga_common_init(&s->vga, NULL, true);
vga_mm_init(s, vram_base, ctrl_base, it_shift, address_space);
s->vga.con = graphic_console_init(NULL, 0, s->vga.hw_ops, s);
vga_init_vbe(&s->vga, NULL, address_space);
return 0;
}
| null | null | null | null | 122,356 |
31,344 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 31,344 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | /**
* (C) 1999-2003 Lars Knoll (knoll@kde.org)
* Copyright (C) 2004, 2006, 2007 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "third_party/blink/renderer/core/css/style_sheet_list.h"
#include "third_party/blink/renderer/core/css/style_engine.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/html_style_element.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
using namespace HTMLNames;
StyleSheetList* StyleSheetList::Create() {
DCHECK(RuntimeEnabledFeatures::ConstructableStylesheetsEnabled());
return new StyleSheetList();
}
StyleSheetList* StyleSheetList::Create(
const HeapVector<Member<CSSStyleSheet>>& style_sheet_vector,
ExceptionState& exception_state) {
if (!RuntimeEnabledFeatures::ConstructableStylesheetsEnabled()) {
exception_state.ThrowTypeError("Illegal constructor");
return nullptr;
}
return new StyleSheetList(style_sheet_vector);
}
StyleSheetList::StyleSheetList(
const HeapVector<Member<CSSStyleSheet>>& style_sheet_vector)
: style_sheet_vector_(style_sheet_vector) {}
StyleSheetList::StyleSheetList(TreeScope* tree_scope)
: tree_scope_(tree_scope) {
CHECK(tree_scope);
}
inline const HeapVector<TraceWrapperMember<StyleSheet>>&
StyleSheetList::StyleSheets() const {
return GetDocument()->GetStyleEngine().StyleSheetsForStyleSheetList(
*tree_scope_);
}
unsigned StyleSheetList::length() {
if (!tree_scope_)
return style_sheet_vector_.size();
return StyleSheets().size();
}
StyleSheet* StyleSheetList::item(unsigned index) {
if (!tree_scope_) {
return index < style_sheet_vector_.size() ? style_sheet_vector_[index].Get()
: nullptr;
}
const HeapVector<TraceWrapperMember<StyleSheet>>& sheets = StyleSheets();
return index < sheets.size() ? sheets[index].Get() : nullptr;
}
HTMLStyleElement* StyleSheetList::GetNamedItem(const AtomicString& name) const {
if (!tree_scope_)
return nullptr;
// IE also supports retrieving a stylesheet by name, using the name/id of the
// <style> tag (this is consistent with all the other collections) ### Bad
// implementation because returns a single element (are IDs always unique?)
// and doesn't look for name attribute. But unicity of stylesheet ids is good
// practice anyway ;)
// FIXME: We should figure out if we should change this or fix the spec.
Element* element = tree_scope_->getElementById(name);
return IsHTMLStyleElement(element) ? ToHTMLStyleElement(element) : nullptr;
}
CSSStyleSheet* StyleSheetList::AnonymousNamedGetter(const AtomicString& name) {
if (GetDocument()) {
UseCounter::Count(*GetDocument(),
WebFeature::kStyleSheetListAnonymousNamedGetter);
}
HTMLStyleElement* item = GetNamedItem(name);
if (!item)
return nullptr;
CSSStyleSheet* sheet = item->sheet();
if (sheet) {
UseCounter::Count(*GetDocument(),
WebFeature::kStyleSheetListNonNullAnonymousNamedGetter);
}
return sheet;
}
void StyleSheetList::Trace(blink::Visitor* visitor) {
visitor->Trace(tree_scope_);
visitor->Trace(style_sheet_vector_);
ScriptWrappable::Trace(visitor);
}
} // namespace blink
| null | null | null | null | 28,207 |
23,485 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 188,480 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | /*
* linux/drivers/video/n411.c -- Platform device for N411 EPD kit
*
* Copyright (C) 2008, Jaya Kumar
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive for
* more details.
*
* Layout is based on skeletonfb.c by James Simmons and Geert Uytterhoeven.
*
* This driver is written to be used with the Hecuba display controller
* board, and tested with the EInk 800x600 display in 1 bit mode.
* The interface between Hecuba and the host is TTL based GPIO. The
* GPIO requirements are 8 writable data lines and 6 lines for control.
* Only 4 of the controls are actually used here but 6 for future use.
* The driver requires the IO addresses for data and control GPIO at
* load time. It is also possible to use this display with a standard
* PC parallel port.
*
* General notes:
* - User must set dio_addr=0xIOADDR cio_addr=0xIOADDR c2io_addr=0xIOADDR
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/list.h>
#include <linux/uaccess.h>
#include <linux/irq.h>
#include <video/hecubafb.h>
static unsigned long dio_addr;
static unsigned long cio_addr;
static unsigned long c2io_addr;
static unsigned long splashval;
static unsigned int nosplash;
static unsigned char ctl;
static void n411_set_ctl(struct hecubafb_par *par, unsigned char bit, unsigned
char state)
{
switch (bit) {
case HCB_CD_BIT:
if (state)
ctl &= ~(HCB_CD_BIT);
else
ctl |= HCB_CD_BIT;
break;
case HCB_DS_BIT:
if (state)
ctl &= ~(HCB_DS_BIT);
else
ctl |= HCB_DS_BIT;
break;
}
outb(ctl, cio_addr);
}
static unsigned char n411_get_ctl(struct hecubafb_par *par)
{
return inb(c2io_addr);
}
static void n411_set_data(struct hecubafb_par *par, unsigned char value)
{
outb(value, dio_addr);
}
static void n411_wait_for_ack(struct hecubafb_par *par, int clear)
{
int timeout;
unsigned char tmp;
timeout = 500;
do {
tmp = n411_get_ctl(par);
if ((tmp & HCB_ACK_BIT) && (!clear))
return;
else if (!(tmp & HCB_ACK_BIT) && (clear))
return;
udelay(1);
} while (timeout--);
printk(KERN_ERR "timed out waiting for ack\n");
}
static int n411_init_control(struct hecubafb_par *par)
{
unsigned char tmp;
/* for init, we want the following setup to be set:
WUP = lo
ACK = hi
DS = hi
RW = hi
CD = lo
*/
/* write WUP to lo, DS to hi, RW to hi, CD to lo */
ctl = HCB_WUP_BIT | HCB_RW_BIT | HCB_CD_BIT ;
n411_set_ctl(par, HCB_DS_BIT, 1);
/* check ACK is not lo */
tmp = n411_get_ctl(par);
if (tmp & HCB_ACK_BIT) {
printk(KERN_ERR "Fail because ACK is already low\n");
return -ENXIO;
}
return 0;
}
static int n411_init_board(struct hecubafb_par *par)
{
int retval;
retval = n411_init_control(par);
if (retval)
return retval;
par->send_command(par, APOLLO_INIT_DISPLAY);
par->send_data(par, 0x81);
/* have to wait while display resets */
udelay(1000);
/* if we were told to splash the screen, we just clear it */
if (!nosplash) {
par->send_command(par, APOLLO_ERASE_DISPLAY);
par->send_data(par, splashval);
}
return 0;
}
static struct hecuba_board n411_board = {
.owner = THIS_MODULE,
.init = n411_init_board,
.set_ctl = n411_set_ctl,
.set_data = n411_set_data,
.wait_for_ack = n411_wait_for_ack,
};
static struct platform_device *n411_device;
static int __init n411_init(void)
{
int ret;
if (!dio_addr || !cio_addr || !c2io_addr) {
printk(KERN_WARNING "no IO addresses supplied\n");
return -EINVAL;
}
/* request our platform independent driver */
request_module("hecubafb");
n411_device = platform_device_alloc("hecubafb", -1);
if (!n411_device)
return -ENOMEM;
ret = platform_device_add_data(n411_device, &n411_board,
sizeof(n411_board));
if (ret)
goto put_plat_device;
/* this _add binds hecubafb to n411. hecubafb refcounts n411 */
ret = platform_device_add(n411_device);
if (ret)
goto put_plat_device;
return 0;
put_plat_device:
platform_device_put(n411_device);
return ret;
}
static void __exit n411_exit(void)
{
platform_device_unregister(n411_device);
}
module_init(n411_init);
module_exit(n411_exit);
module_param(nosplash, uint, 0);
MODULE_PARM_DESC(nosplash, "Disable doing the splash screen");
module_param(dio_addr, ulong, 0);
MODULE_PARM_DESC(dio_addr, "IO address for data, eg: 0x480");
module_param(cio_addr, ulong, 0);
MODULE_PARM_DESC(cio_addr, "IO address for control, eg: 0x400");
module_param(c2io_addr, ulong, 0);
MODULE_PARM_DESC(c2io_addr, "IO address for secondary control, eg: 0x408");
module_param(splashval, ulong, 0);
MODULE_PARM_DESC(splashval, "Splash pattern: 0x00 is black, 0x01 is white");
MODULE_DESCRIPTION("board driver for n411 hecuba/apollo epd kit");
MODULE_AUTHOR("Jaya Kumar");
MODULE_LICENSE("GPL");
| null | null | null | null | 96,827 |
53,400 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 53,400 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2014 The Chromium 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 <stddef.h>
#include <stdint.h>
#include <vector>
#include "base/bind.h"
#include "base/macros.h"
#include "base/test/simple_test_tick_clock.h"
#include "media/cast/net/cast_transport_config.h"
#include "media/cast/net/pacing/paced_sender.h"
#include "media/cast/net/rtcp/receiver_rtcp_session.h"
#include "media/cast/net/rtcp/rtcp_builder.h"
#include "media/cast/net/rtcp/rtcp_session.h"
#include "media/cast/net/rtcp/rtcp_utility.h"
#include "media/cast/net/rtcp/sender_rtcp_session.h"
#include "media/cast/test/skewed_tick_clock.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace media {
namespace cast {
namespace {
media::cast::RtcpTimeData CreateRtcpTimeData(base::TimeTicks now) {
media::cast::RtcpTimeData ret;
ret.timestamp = now;
media::cast::ConvertTimeTicksToNtp(now, &ret.ntp_seconds, &ret.ntp_fraction);
return ret;
}
using testing::_;
static const uint32_t kSenderSsrc = 0x10203;
static const uint32_t kReceiverSsrc = 0x40506;
static const int kInitialReceiverClockOffsetSeconds = -5;
static const uint16_t kTargetDelayMs = 100;
class FakeRtcpTransport : public PacedPacketSender {
public:
explicit FakeRtcpTransport(base::SimpleTestTickClock* clock)
: clock_(clock), packet_delay_(base::TimeDelta::FromMilliseconds(42)) {}
void set_rtcp_destination(RtcpSession* rtcp_session) {
rtcp_session_ = rtcp_session;
}
base::TimeDelta packet_delay() const { return packet_delay_; }
void set_packet_delay(base::TimeDelta delay) { packet_delay_ = delay; }
bool SendRtcpPacket(uint32_t ssrc, PacketRef packet) final {
clock_->Advance(packet_delay_);
rtcp_session_->IncomingRtcpPacket(&packet->data[0], packet->data.size());
return true;
}
bool SendPackets(const SendPacketVector& packets) final { return false; }
bool ResendPackets(const SendPacketVector& packets,
const DedupInfo& dedup_info) final {
return false;
}
void CancelSendingPacket(const PacketKey& packet_key) final {}
private:
base::SimpleTestTickClock* const clock_;
base::TimeDelta packet_delay_;
RtcpSession* rtcp_session_; // RTCP destination.
DISALLOW_COPY_AND_ASSIGN(FakeRtcpTransport);
};
} // namespace
class RtcpTest : public ::testing::Test, public RtcpObserver {
protected:
RtcpTest()
: sender_clock_(new base::SimpleTestTickClock()),
receiver_clock_(new test::SkewedTickClock(sender_clock_.get())),
rtp_sender_pacer_(sender_clock_.get()),
rtp_receiver_pacer_(sender_clock_.get()),
rtcp_at_rtp_sender_(sender_clock_.get(),
&rtp_sender_pacer_,
this,
kSenderSsrc,
kReceiverSsrc),
rtcp_at_rtp_receiver_(receiver_clock_.get(),
kReceiverSsrc,
kSenderSsrc),
received_pli_(false) {
sender_clock_->Advance(base::TimeTicks::Now() - base::TimeTicks());
receiver_clock_->SetSkew(
1.0, // No skew.
base::TimeDelta::FromSeconds(kInitialReceiverClockOffsetSeconds));
rtp_sender_pacer_.set_rtcp_destination(&rtcp_at_rtp_receiver_);
rtp_receiver_pacer_.set_rtcp_destination(&rtcp_at_rtp_sender_);
}
~RtcpTest() override = default;
// RtcpObserver implementation.
void OnReceivedCastMessage(const RtcpCastMessage& cast_message) override {
last_cast_message_ = cast_message;
}
void OnReceivedRtt(base::TimeDelta round_trip_time) override {
current_round_trip_time_ = round_trip_time;
}
void OnReceivedReceiverLog(const RtcpReceiverLogMessage& logs) override {
RtcpReceiverLogMessage().swap(last_logs_);
// Make a copy of the logs.
for (const RtcpReceiverFrameLogMessage& frame_log_msg : logs) {
last_logs_.push_back(
RtcpReceiverFrameLogMessage(frame_log_msg.rtp_timestamp_));
for (const RtcpReceiverEventLogMessage& event_log_msg :
frame_log_msg.event_log_messages_) {
RtcpReceiverEventLogMessage event_log;
event_log.type = event_log_msg.type;
event_log.event_timestamp = event_log_msg.event_timestamp;
event_log.delay_delta = event_log_msg.delay_delta;
event_log.packet_id = event_log_msg.packet_id;
last_logs_.back().event_log_messages_.push_back(event_log);
}
}
}
void OnReceivedPli() override { received_pli_ = true; }
PacketRef BuildRtcpPacketFromRtpReceiver(
const RtcpTimeData& time_data,
const RtcpCastMessage* cast_message,
const RtcpPliMessage* pli_message,
base::TimeDelta target_delay,
const ReceiverRtcpEventSubscriber::RtcpEvents* rtcp_events,
const RtpReceiverStatistics* rtp_receiver_statistics) {
RtcpBuilder builder(rtcp_at_rtp_receiver_.local_ssrc());
builder.Start();
RtcpReceiverReferenceTimeReport rrtr;
rrtr.ntp_seconds = time_data.ntp_seconds;
rrtr.ntp_fraction = time_data.ntp_fraction;
builder.AddRrtr(rrtr);
RtcpReportBlock report_block;
if (rtp_receiver_statistics) {
report_block.remote_ssrc = 0;
report_block.media_ssrc = rtcp_at_rtp_receiver_.remote_ssrc();
report_block.fraction_lost = rtp_receiver_statistics->fraction_lost;
report_block.cumulative_lost = rtp_receiver_statistics->cumulative_lost;
report_block.extended_high_sequence_number =
rtp_receiver_statistics->extended_high_sequence_number;
report_block.jitter = rtp_receiver_statistics->jitter;
report_block.last_sr = rtcp_at_rtp_receiver_.last_report_truncated_ntp();
base::TimeTicks last_report_received_time =
rtcp_at_rtp_receiver_.time_last_report_received();
if (!last_report_received_time.is_null()) {
uint32_t delay_seconds = 0;
uint32_t delay_fraction = 0;
base::TimeDelta delta = time_data.timestamp - last_report_received_time;
ConvertTimeToFractions(delta.InMicroseconds(), &delay_seconds,
&delay_fraction);
report_block.delay_since_last_sr =
ConvertToNtpDiff(delay_seconds, delay_fraction);
} else {
report_block.delay_since_last_sr = 0;
}
builder.AddRR(&report_block);
}
if (cast_message)
builder.AddCast(*cast_message, target_delay);
if (pli_message)
builder.AddPli(*pli_message);
if (rtcp_events)
builder.AddReceiverLog(*rtcp_events);
return builder.Finish();
}
std::unique_ptr<base::SimpleTestTickClock> sender_clock_;
std::unique_ptr<test::SkewedTickClock> receiver_clock_;
FakeRtcpTransport rtp_sender_pacer_;
FakeRtcpTransport rtp_receiver_pacer_;
SenderRtcpSession rtcp_at_rtp_sender_;
ReceiverRtcpSession rtcp_at_rtp_receiver_;
base::TimeDelta current_round_trip_time_;
RtcpCastMessage last_cast_message_;
RtcpReceiverLogMessage last_logs_;
bool received_pli_;
private:
DISALLOW_COPY_AND_ASSIGN(RtcpTest);
};
TEST_F(RtcpTest, LipSyncGleanedFromSenderReport) {
// Initially, expect no lip-sync info receiver-side without having first
// received a RTCP packet.
base::TimeTicks reference_time;
RtpTimeTicks rtp_timestamp;
ASSERT_FALSE(rtcp_at_rtp_receiver_.GetLatestLipSyncTimes(&rtp_timestamp,
&reference_time));
// Send a Sender Report to the receiver.
const base::TimeTicks reference_time_sent = sender_clock_->NowTicks();
const RtpTimeTicks rtp_timestamp_sent =
RtpTimeTicks().Expand(UINT32_C(0xbee5));
rtcp_at_rtp_sender_.SendRtcpReport(reference_time_sent, rtp_timestamp_sent, 1,
1);
// Now the receiver should have lip-sync info. Confirm that the lip-sync
// reference time is the same as that sent.
EXPECT_TRUE(rtcp_at_rtp_receiver_.GetLatestLipSyncTimes(&rtp_timestamp,
&reference_time));
const base::TimeTicks rolled_back_time =
(reference_time -
// Roll-back relative clock offset:
base::TimeDelta::FromSeconds(kInitialReceiverClockOffsetSeconds) -
// Roll-back packet transmission time (because RTT is not yet known):
rtp_sender_pacer_.packet_delay());
EXPECT_NEAR(0, (reference_time_sent - rolled_back_time).InMicroseconds(), 5);
EXPECT_EQ(rtp_timestamp_sent, rtp_timestamp);
}
TEST_F(RtcpTest, RoundTripTimesDeterminedFromReportPingPong) {
const int iterations = 12;
// Sender does not know the RTT yet.
ASSERT_EQ(base::TimeDelta(), rtcp_at_rtp_sender_.current_round_trip_time());
// Do a number of ping-pongs, checking how the round trip times are measured
// by the sender.
base::TimeDelta expected_rtt_according_to_sender;
for (int i = 0; i < iterations; ++i) {
const base::TimeDelta one_way_trip_time =
base::TimeDelta::FromMilliseconds(static_cast<int64_t>(1) << i);
rtp_sender_pacer_.set_packet_delay(one_way_trip_time);
rtp_receiver_pacer_.set_packet_delay(one_way_trip_time);
// Sender --> Receiver
base::TimeTicks reference_time_sent = sender_clock_->NowTicks();
const RtpTimeTicks rtp_timestamp_sent =
RtpTimeTicks().Expand<uint32_t>(0xbee5) + RtpTimeDelta::FromTicks(i);
rtcp_at_rtp_sender_.SendRtcpReport(reference_time_sent, rtp_timestamp_sent,
1, 1);
EXPECT_EQ(expected_rtt_according_to_sender,
rtcp_at_rtp_sender_.current_round_trip_time());
// Validate last reported callback value is same as that reported by method.
EXPECT_EQ(current_round_trip_time_,
rtcp_at_rtp_sender_.current_round_trip_time());
// Receiver --> Sender
RtpReceiverStatistics stats;
rtp_receiver_pacer_.SendRtcpPacket(
rtcp_at_rtp_receiver_.local_ssrc(),
BuildRtcpPacketFromRtpReceiver(
CreateRtcpTimeData(receiver_clock_->NowTicks()), nullptr, nullptr,
base::TimeDelta(), nullptr, &stats));
expected_rtt_according_to_sender = one_way_trip_time * 2;
EXPECT_EQ(expected_rtt_according_to_sender,
rtcp_at_rtp_sender_.current_round_trip_time());
}
}
TEST_F(RtcpTest, ReportCastFeedback) {
// Sender has sent all frames up to and including first+5.
rtcp_at_rtp_sender_.WillSendFrame(FrameId::first() + 5);
// ACK all frames up to and including first+5, except NACK a few in first+1
// and first+2.
RtcpCastMessage cast_message(kSenderSsrc);
cast_message.ack_frame_id = FrameId::first() + 5;
PacketIdSet missing_packets1 = {3, 4};
cast_message.missing_frames_and_packets[FrameId::first() + 1] =
missing_packets1;
PacketIdSet missing_packets2 = {5, 6};
cast_message.missing_frames_and_packets[FrameId::first() + 2] =
missing_packets2;
rtp_receiver_pacer_.SendRtcpPacket(
rtcp_at_rtp_receiver_.local_ssrc(),
BuildRtcpPacketFromRtpReceiver(
CreateRtcpTimeData(base::TimeTicks()), &cast_message, nullptr,
base::TimeDelta::FromMilliseconds(kTargetDelayMs), nullptr, nullptr));
EXPECT_EQ(last_cast_message_.ack_frame_id, cast_message.ack_frame_id);
EXPECT_EQ(last_cast_message_.target_delay_ms, kTargetDelayMs);
EXPECT_EQ(last_cast_message_.missing_frames_and_packets.size(),
cast_message.missing_frames_and_packets.size());
EXPECT_TRUE(
std::equal(cast_message.missing_frames_and_packets.begin(),
cast_message.missing_frames_and_packets.end(),
last_cast_message_.missing_frames_and_packets.begin()));
}
TEST_F(RtcpTest, ReportPli) {
RtcpPliMessage pli_message(kSenderSsrc);
rtp_receiver_pacer_.SendRtcpPacket(
rtcp_at_rtp_receiver_.local_ssrc(),
BuildRtcpPacketFromRtpReceiver(CreateRtcpTimeData(base::TimeTicks()),
nullptr, &pli_message, base::TimeDelta(),
nullptr, nullptr));
EXPECT_TRUE(received_pli_);
}
TEST_F(RtcpTest, DropLateRtcpPacket) {
// Sender has sent all frames up to and including first+2.
rtcp_at_rtp_sender_.WillSendFrame(FrameId::first() + 2);
// Receiver ACKs first+1.
RtcpCastMessage cast_message(kSenderSsrc);
cast_message.ack_frame_id = FrameId::first() + 1;
rtp_receiver_pacer_.SendRtcpPacket(
rtcp_at_rtp_receiver_.local_ssrc(),
BuildRtcpPacketFromRtpReceiver(
CreateRtcpTimeData(receiver_clock_->NowTicks()), &cast_message,
nullptr, base::TimeDelta::FromMilliseconds(kTargetDelayMs), nullptr,
nullptr));
// Receiver ACKs first+2, but with a too-old timestamp.
RtcpCastMessage late_cast_message(kSenderSsrc);
late_cast_message.ack_frame_id = FrameId::first() + 2;
rtp_receiver_pacer_.SendRtcpPacket(
rtcp_at_rtp_receiver_.local_ssrc(),
BuildRtcpPacketFromRtpReceiver(
CreateRtcpTimeData(receiver_clock_->NowTicks() -
base::TimeDelta::FromSeconds(10)),
&late_cast_message, nullptr, base::TimeDelta(), nullptr, nullptr));
// Validate data from second packet is dropped.
EXPECT_EQ(last_cast_message_.ack_frame_id, cast_message.ack_frame_id);
EXPECT_EQ(last_cast_message_.target_delay_ms, kTargetDelayMs);
// Re-send with fresh timestamp
late_cast_message.ack_frame_id = FrameId::first() + 2;
rtp_receiver_pacer_.SendRtcpPacket(
rtcp_at_rtp_receiver_.local_ssrc(),
BuildRtcpPacketFromRtpReceiver(
CreateRtcpTimeData(receiver_clock_->NowTicks()), &late_cast_message,
nullptr, base::TimeDelta(), nullptr, nullptr));
EXPECT_EQ(last_cast_message_.ack_frame_id, late_cast_message.ack_frame_id);
EXPECT_EQ(last_cast_message_.target_delay_ms, 0);
}
TEST_F(RtcpTest, ReportReceiverEvents) {
const RtpTimeTicks kRtpTimeStamp =
media::cast::RtpTimeTicks().Expand(UINT32_C(100));
const base::TimeTicks kEventTimestamp = receiver_clock_->NowTicks();
const base::TimeDelta kDelayDelta = base::TimeDelta::FromMilliseconds(100);
RtcpEvent event;
event.type = FRAME_ACK_SENT;
event.timestamp = kEventTimestamp;
event.delay_delta = kDelayDelta;
ReceiverRtcpEventSubscriber::RtcpEvents rtcp_events;
rtcp_events.push_back(std::make_pair(kRtpTimeStamp, event));
rtp_receiver_pacer_.SendRtcpPacket(
rtcp_at_rtp_receiver_.local_ssrc(),
BuildRtcpPacketFromRtpReceiver(
CreateRtcpTimeData(receiver_clock_->NowTicks()), nullptr, nullptr,
base::TimeDelta(), &rtcp_events, nullptr));
ASSERT_EQ(1UL, last_logs_.size());
RtcpReceiverFrameLogMessage frame_log = last_logs_.front();
EXPECT_EQ(frame_log.rtp_timestamp_, kRtpTimeStamp);
ASSERT_EQ(1UL, frame_log.event_log_messages_.size());
RtcpReceiverEventLogMessage log_msg = frame_log.event_log_messages_.back();
EXPECT_EQ(log_msg.type, event.type);
EXPECT_EQ(log_msg.delay_delta, event.delay_delta);
// Only 24 bits of event timestamp sent on wire.
uint32_t event_ts =
(event.timestamp - base::TimeTicks()).InMilliseconds() & 0xffffff;
uint32_t log_msg_ts =
(log_msg.event_timestamp - base::TimeTicks()).InMilliseconds() & 0xffffff;
EXPECT_EQ(log_msg_ts, event_ts);
}
} // namespace cast
} // namespace media
| null | null | null | null | 50,263 |
23,883 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 188,878 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | /*
* linux/drivers/video/console/fbcon_rotate.c -- Software Rotation
*
* Copyright (C) 2005 Antonino Daplas <adaplas @pol.net>
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive for
* more details.
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/fb.h>
#include <linux/vt_kern.h>
#include <linux/console.h>
#include <asm/types.h>
#include "fbcon.h"
#include "fbcon_rotate.h"
static int fbcon_rotate_font(struct fb_info *info, struct vc_data *vc)
{
struct fbcon_ops *ops = info->fbcon_par;
int len, err = 0;
int s_cellsize, d_cellsize, i;
const u8 *src;
u8 *dst;
if (vc->vc_font.data == ops->fontdata &&
ops->p->con_rotate == ops->cur_rotate)
goto finished;
src = ops->fontdata = vc->vc_font.data;
ops->cur_rotate = ops->p->con_rotate;
len = (!ops->p->userfont) ? 256 : FNTCHARCNT(src);
s_cellsize = ((vc->vc_font.width + 7)/8) *
vc->vc_font.height;
d_cellsize = s_cellsize;
if (ops->rotate == FB_ROTATE_CW ||
ops->rotate == FB_ROTATE_CCW)
d_cellsize = ((vc->vc_font.height + 7)/8) *
vc->vc_font.width;
if (info->fbops->fb_sync)
info->fbops->fb_sync(info);
if (ops->fd_size < d_cellsize * len) {
dst = kmalloc(d_cellsize * len, GFP_KERNEL);
if (dst == NULL) {
err = -ENOMEM;
goto finished;
}
ops->fd_size = d_cellsize * len;
kfree(ops->fontbuffer);
ops->fontbuffer = dst;
}
dst = ops->fontbuffer;
memset(dst, 0, ops->fd_size);
switch (ops->rotate) {
case FB_ROTATE_UD:
for (i = len; i--; ) {
rotate_ud(src, dst, vc->vc_font.width,
vc->vc_font.height);
src += s_cellsize;
dst += d_cellsize;
}
break;
case FB_ROTATE_CW:
for (i = len; i--; ) {
rotate_cw(src, dst, vc->vc_font.width,
vc->vc_font.height);
src += s_cellsize;
dst += d_cellsize;
}
break;
case FB_ROTATE_CCW:
for (i = len; i--; ) {
rotate_ccw(src, dst, vc->vc_font.width,
vc->vc_font.height);
src += s_cellsize;
dst += d_cellsize;
}
break;
}
finished:
return err;
}
void fbcon_set_rotate(struct fbcon_ops *ops)
{
ops->rotate_font = fbcon_rotate_font;
switch(ops->rotate) {
case FB_ROTATE_CW:
fbcon_rotate_cw(ops);
break;
case FB_ROTATE_UD:
fbcon_rotate_ud(ops);
break;
case FB_ROTATE_CCW:
fbcon_rotate_ccw(ops);
break;
}
}
EXPORT_SYMBOL(fbcon_set_rotate);
MODULE_AUTHOR("Antonino Daplas <adaplas@pol.net>");
MODULE_DESCRIPTION("Console Rotation Support");
MODULE_LICENSE("GPL");
| null | null | null | null | 97,225 |
21,617 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 186,612 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | #ifndef RTL8180_GRF5101_H
#define RTL8180_GRF5101_H
/*
* Radio tuning for GCT GRF5101 on RTL8180
*
* Copyright 2007 Andrea Merello <andrea.merello@gmail.com>
*
* Code from the BSD driver and the rtl8181 project have been
* very useful to understand certain things
*
* I want to thanks the Authors of such projects and the Ndiswrapper
* project Authors.
*
* A special Big Thanks also is for all people who donated me cards,
* making possible the creation of the original rtl8180 driver
* from which this code is derived!
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#define GRF5101_ANTENNA 0xA3
extern const struct rtl818x_rf_ops grf5101_rf_ops;
#endif /* RTL8180_GRF5101_H */
| null | null | null | null | 94,959 |
67,974 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 67,974 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2015 The Chromium 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 REMOTING_PROTOCOL_ICE_TRANSPORT_H_
#define REMOTING_PROTOCOL_ICE_TRANSPORT_H_
#include <list>
#include <map>
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/timer/timer.h"
#include "remoting/protocol/datagram_channel_factory.h"
#include "remoting/protocol/ice_transport_channel.h"
#include "remoting/protocol/jingle_messages.h"
#include "remoting/protocol/transport.h"
namespace remoting {
namespace protocol {
class ChannelMultiplexer;
class PseudoTcpChannelFactory;
class SecureChannelFactory;
class MessageChannelFactory;
class IceTransport : public Transport,
public IceTransportChannel::Delegate,
public DatagramChannelFactory {
public:
class EventHandler {
public:
// Called when transport route changes.
virtual void OnIceTransportRouteChange(const std::string& channel_name,
const TransportRoute& route) = 0;
// Called when there is an error connecting the session.
virtual void OnIceTransportError(ErrorCode error) = 0;
};
// |transport_context| must outlive the session.
IceTransport(scoped_refptr<TransportContext> transport_context,
EventHandler* event_handler);
~IceTransport() override;
MessageChannelFactory* GetChannelFactory();
MessageChannelFactory* GetMultiplexedChannelFactory();
// Transport interface.
void Start(Authenticator* authenticator,
SendTransportInfoCallback send_transport_info_callback) override;
bool ProcessTransportInfo(buzz::XmlElement* transport_info) override;
private:
typedef std::map<std::string, IceTransportChannel*> ChannelsMap;
// DatagramChannelFactory interface.
void CreateChannel(const std::string& name,
const ChannelCreatedCallback& callback) override;
void CancelChannelCreation(const std::string& name) override;
// Passes transport info to a new |channel| in case it was received before the
// channel was created.
void AddPendingRemoteTransportInfo(IceTransportChannel* channel);
// IceTransportChannel::Delegate interface.
void OnChannelIceCredentials(IceTransportChannel* transport,
const std::string& ufrag,
const std::string& password) override;
void OnChannelCandidate(IceTransportChannel* transport,
const cricket::Candidate& candidate) override;
void OnChannelRouteChange(IceTransportChannel* transport,
const TransportRoute& route) override;
void OnChannelFailed(IceTransportChannel* transport) override;
void OnChannelDeleted(IceTransportChannel* transport) override;
// Creates empty |pending_transport_info_message_| and schedules timer for
// SentTransportInfo() to sent the message later.
void EnsurePendingTransportInfoMessage();
// Sends transport-info message with candidates from |pending_candidates_|.
void SendTransportInfo();
// Callback passed to StreamMessageChannelFactoryAdapter to handle read/write
// errors on the data channels.
void OnChannelError(int error);
scoped_refptr<TransportContext> transport_context_;
EventHandler* event_handler_;
SendTransportInfoCallback send_transport_info_callback_;
ChannelsMap channels_;
std::unique_ptr<PseudoTcpChannelFactory> pseudotcp_channel_factory_;
std::unique_ptr<SecureChannelFactory> secure_channel_factory_;
std::unique_ptr<MessageChannelFactory> message_channel_factory_;
std::unique_ptr<ChannelMultiplexer> channel_multiplexer_;
std::unique_ptr<MessageChannelFactory> mux_channel_factory_;
// Pending remote transport info received before the local channels were
// created.
std::list<IceTransportInfo::IceCredentials> pending_remote_ice_credentials_;
std::list<IceTransportInfo::NamedCandidate> pending_remote_candidates_;
std::unique_ptr<IceTransportInfo> pending_transport_info_message_;
base::OneShotTimer transport_info_timer_;
base::WeakPtrFactory<IceTransport> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(IceTransport);
};
} // namespace protocol
} // namespace remoting
#endif // REMOTING_PROTOCOL_ICE_TRANSPORT_H_
| null | null | null | null | 64,837 |
17,403 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 17,403 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file contains UTF8 strings that we want as char arrays. To avoid
// different compilers, we use a script to convert the UTF8 strings into
// numeric literals (\x##).
#include "components/autofill/core/common/autofill_regex_constants.h"
namespace autofill {
/////////////////////////////////////////////////////////////////////////////
// address_field.cc
/////////////////////////////////////////////////////////////////////////////
const char kAttentionIgnoredRe[] = "attention|attn";
const char kRegionIgnoredRe[] =
"province|region|other"
"|provincia" // es
"|bairro|suburb"; // pt-BR, pt-PT
const char kAddressNameIgnoredRe[] = "address.*nickname|address.*label";
const char kCompanyRe[] =
"company|business|organization|organisation"
"|firma|firmenname" // de-DE
"|empresa" // es
"|societe|société" // fr-FR
"|ragione.?sociale" // it-IT
"|会社" // ja-JP
"|название.?компании" // ru
"|单位|公司" // zh-CN
"|회사|직장"; // ko-KR
const char kAddressLine1Re[] =
"^address$|address[_-]?line(one)?|address1|addr1|street"
"|(?:shipping|billing)address$"
"|strasse|straße|hausnummer|housenumber" // de-DE
"|house.?name" // en-GB
"|direccion|dirección" // es
"|adresse" // fr-FR
"|indirizzo" // it-IT
"|^住所$|住所1" // ja-JP
"|morada|endereço" // pt-BR, pt-PT
"|Адрес" // ru
"|地址" // zh-CN
"|^주소.?$|주소.?1"; // ko-KR
const char kAddressLine1LabelRe[] =
"address"
"|adresse" // fr-FR
"|indirizzo" // it-IT
"|住所" // ja-JP
"|地址" // zh-CN
"|주소"; // ko-KR
const char kAddressLine2Re[] =
"address[_-]?line(2|two)|address2|addr2|street|suite|unit"
"|adresszusatz|ergänzende.?angaben" // de-DE
"|direccion2|colonia|adicional" // es
"|addresssuppl|complementnom|appartement" // fr-FR
"|indirizzo2" // it-IT
"|住所2" // ja-JP
"|complemento|addrcomplement" // pt-BR, pt-PT
"|Улица" // ru
"|地址2" // zh-CN
"|주소.?2"; // ko-KR
const char kAddressLine2LabelRe[] =
"address|line"
"|adresse" // fr-FR
"|indirizzo" // it-IT
"|地址" // zh-CN
"|주소"; // ko-KR
const char kAddressLinesExtraRe[] =
"address.*line[3-9]|address[3-9]|addr[3-9]|street|line[3-9]"
"|municipio" // es
"|batiment|residence" // fr-FR
"|indirizzo[3-9]"; // it-IT
const char kAddressLookupRe[] = "lookup";
const char kCountryRe[] =
"country|countries"
"|país|pais" // es
"|国" // ja-JP
"|国家" // zh-CN
"|국가|나라"; // ko-KR
const char kCountryLocationRe[] = "location";
const char kZipCodeRe[] =
"zip|postal|post.*code|pcode"
"|pin.?code" // en-IN
"|postleitzahl" // de-DE
"|\\bcp\\b" // es
"|\\bcdp\\b" // fr-FR
"|\\bcap\\b" // it-IT
"|郵便番号" // ja-JP
"|codigo|codpos|\\bcep\\b" // pt-BR, pt-PT
"|Почтовый.?Индекс" // ru
"|邮政编码|邮编" // zh-CN
"|郵遞區號" // zh-TW
"|우편.?번호"; // ko-KR
const char kZip4Re[] =
"zip|^-$|post2"
"|codpos2"; // pt-BR, pt-PT
const char kCityRe[] =
"city|town"
"|\\bort\\b|stadt" // de-DE
"|suburb" // en-AU
"|ciudad|provincia|localidad|poblacion" // es
"|ville|commune" // fr-FR
"|localita" // it-IT
"|市区町村" // ja-JP
"|cidade" // pt-BR, pt-PT
"|Город" // ru
"|市" // zh-CN
"|分區" // zh-TW
"|^시[^도·・]|시[·・]?군[·・]?구"; // ko-KR
const char kStateRe[] =
"(?<!united )state|county|region|province"
"|land" // de-DE
"|county|principality" // en-UK
"|都道府県" // ja-JP
"|estado|provincia" // pt-BR, pt-PT
"|область" // ru
"|省" // zh-CN
"|地區" // zh-TW
"|^시[·・]?도"; // ko-KR
const char kSearchTermRe[] =
"search"
"|suche.*" // de-DE
"|搜索" // zh-CN zh-TW
"|探す|検索" // ja-JP to search
"|recherch.*" // fr-FR
"|busca" // pt-BR, pt-PT
"|جستجو" // fa
"|искать|найти|поиск"; // ru
/////////////////////////////////////////////////////////////////////////////
// credit_card_field.cc
/////////////////////////////////////////////////////////////////////////////
const char kNameOnCardRe[] =
"card.?(?:holder|owner)|name.*(\\b)?on(\\b)?.*card"
"|(?:card|cc).?name|cc.?full.?name"
"|karteninhaber" // de-DE
"|nombre.*tarjeta" // es
"|nom.*carte" // fr-FR
"|nome.*cart" // it-IT
"|名前" // ja-JP
"|Имя.*карты" // ru
"|信用卡开户名|开户名|持卡人姓名" // zh-CN
"|持卡人姓名"; // zh-TW
const char kNameOnCardContextualRe[] = "name";
const char kCardNumberRe[] =
"(add)?(?:card|cc|acct).?(?:number|#|no|num|field)"
"|(?<!telefon|haus)nummer" // de-DE
"|credito|numero|número" // es
"|numéro" // fr-FR
"|カード番号" // ja-JP
"|Номер.*карты" // ru
"|信用卡号|信用卡号码" // zh-CN
"|信用卡卡號" // zh-TW
"|카드"; // ko-KR
const char kCardCvcRe[] =
"verification|card.?identification|security.?code|card.?code"
"|security.?value"
"|security.?number|card.?pin|c-v-v"
"|(cvn|cvv|cvc|csc|cvd|cid|ccv)(field)?"
"|\\bcid\\b";
// "Expiration date" is the most common label here, but some pages have
// "Expires", "exp. date" or "exp. month" and "exp. year". We also look
// for the field names ccmonth and ccyear, which appear on at least 4 of
// our test pages.
// On at least one page (The China Shop2.html) we find only the labels
// "month" and "year". So for now we match these words directly; we'll
// see if this turns out to be too general.
// Toolbar Bug 51451: indeed, simply matching "month" is too general for
// https://rps.fidelity.com/ftgw/rps/RtlCust/CreatePIN/Init.
// Instead, we match only words beginning with "month".
const char kExpirationMonthRe[] =
"expir|exp.*mo|exp.*date|ccmonth|cardmonth|addmonth"
"|gueltig|gültig|monat" // de-DE
"|fecha" // es
"|date.*exp" // fr-FR
"|scadenza" // it-IT
"|有効期限" // ja-JP
"|validade" // pt-BR, pt-PT
"|Срок действия карты" // ru
"|月"; // zh-CN
const char kExpirationYearRe[] =
"exp|^/|(add)?year"
"|ablaufdatum|gueltig|gültig|jahr" // de-DE
"|fecha" // es
"|scadenza" // it-IT
"|有効期限" // ja-JP
"|validade" // pt-BR, pt-PT
"|Срок действия карты" // ru
"|年|有效期"; // zh-CN
// Used to match a expiration date field with a two digit year.
// The following conditions must be met:
// - Exactly two adjacent y's.
// - (optional) Exactly two adjacent m's before the y's.
// - (optional) Separated by white-space and/or a dash or slash.
// - (optional) Prepended with some text similar to "Expiration Date".
// Tested in components/autofill/core/common/autofill_regexes_unittest.cc
const char kExpirationDate2DigitYearRe[] =
"(?:exp.*date[^y\\n\\r]*|mm\\s*[-/]?\\s*)yy(?:[^y]|$)";
// Used to match a expiration date field with a four digit year.
// Same requirements as |kExpirationDate2DigitYearRe| except:
// - Exactly four adjacent y's.
// Tested in components/autofill/core/common/autofill_regexes_unittest.cc
const char kExpirationDate4DigitYearRe[] =
"(?:exp.*date[^y\\n\\r]*|mm\\s*[-/]?\\s*)yyyy(?:[^y]|$)";
// Used to match expiration date fields that do not specify a year length.
const char kExpirationDateRe[] =
"expir|exp.*date|^expfield$"
"|gueltig|gültig" // de-DE
"|fecha" // es
"|date.*exp" // fr-FR
"|scadenza" // it-IT
"|有効期限" // ja-JP
"|validade" // pt-BR, pt-PT
"|Срок действия карты"; // ru
const char kGiftCardRe[] = "gift.?card";
const char kDebitGiftCardRe[] =
"(?:visa|mastercard|discover|amex|american express).*gift.?card";
const char kDebitCardRe[] = "debit.*card";
/////////////////////////////////////////////////////////////////////////////
// email_field.cc
/////////////////////////////////////////////////////////////////////////////
const char kEmailRe[] =
"e.?mail"
"|courriel" // fr
"|メールアドレス" // ja-JP
"|Электронной.?Почты" // ru
"|邮件|邮箱" // zh-CN
"|電郵地址" // zh-TW
"|(?:이메일|전자.?우편|[Ee]-?mail)(.?주소)?"; // ko-KR
/////////////////////////////////////////////////////////////////////////////
// name_field.cc
/////////////////////////////////////////////////////////////////////////////
const char kNameIgnoredRe[] =
"user.?name|user.?id|nickname|maiden name|title|prefix|suffix"
"|vollständiger.?name" // de-DE
"|用户名" // zh-CN
"|(?:사용자.?)?아이디|사용자.?ID"; // ko-KR
const char kNameRe[] =
"^name|full.?name|your.?name|customer.?name|bill.?name|ship.?name"
"|name.*first.*last|firstandlastname"
"|nombre.*y.*apellidos" // es
"|^nom" // fr-FR
"|お名前|氏名" // ja-JP
"|^nome" // pt-BR, pt-PT
"|姓名" // zh-CN
"|성명"; // ko-KR
const char kNameSpecificRe[] =
"^name"
"|^nom" // fr-FR
"|^nome"; // pt-BR, pt-PT
const char kFirstNameRe[] =
"first.*name|initials|fname|first$|given.*name"
"|vorname" // de-DE
"|nombre" // es
"|forename|prénom|prenom" // fr-FR
"|名" // ja-JP
"|nome" // pt-BR, pt-PT
"|Имя" // ru
"|이름"; // ko-KR
const char kMiddleInitialRe[] = "middle.*initial|m\\.i\\.|mi$|\\bmi\\b";
const char kMiddleNameRe[] =
"middle.*name|mname|middle$"
"|apellido.?materno|lastlastname"; // es
const char kLastNameRe[] =
"last.*name|lname|surname|last$|secondname|family.*name"
"|nachname" // de-DE
"|apellido" // es
"|famille|^nom" // fr-FR
"|cognome" // it-IT
"|姓" // ja-JP
"|morada|apelidos|surename|sobrenome" // pt-BR, pt-PT
"|Фамилия" // ru
"|\\b성(?:[^명]|\\b)"; // ko-KR
/////////////////////////////////////////////////////////////////////////////
// phone_field.cc
/////////////////////////////////////////////////////////////////////////////
const char kPhoneRe[] =
"phone|mobile|contact.?number"
"|telefonnummer" // de-DE
"|telefono|teléfono" // es
"|telfixe" // fr-FR
"|電話" // ja-JP
"|telefone|telemovel" // pt-BR, pt-PT
"|телефон" // ru
"|电话" // zh-CN
"|(?:전화|핸드폰|휴대폰|휴대전화)(?:.?번호)?"; // ko-KR
const char kCountryCodeRe[] = "country.*code|ccode|_cc";
const char kAreaCodeNotextRe[] = "^\\($";
const char kAreaCodeRe[] =
"area.*code|acode|area"
"|지역.?번호"; // ko-KR
const char kPhonePrefixSeparatorRe[] = "^-$|^\\)$";
const char kPhoneSuffixSeparatorRe[] = "^-$";
const char kPhonePrefixRe[] =
"prefix|exchange"
"|preselection" // fr-FR
"|ddd"; // pt-BR, pt-PT
const char kPhoneSuffixRe[] = "suffix";
const char kPhoneExtensionRe[] =
"\\bext|ext\\b|extension"
"|ramal"; // pt-BR, pt-PT
/////////////////////////////////////////////////////////////////////////////
// validation.cc
/////////////////////////////////////////////////////////////////////////////
const char kUPIVirtualPaymentAddressRe[] =
"^\\w+@("
"airtel|" // My Airtel-Recharge, Bill, Bank
"allbank|" // Allahabad Bank UPI
"andb|" // Andhra Bank ONE
"axisbank|" // Axis Pay
"axisgo|" // Ola
"barodampay|" // Baroda MPay
"boi|" // BHIM BOI UPI
"centralbank|" // Cent UPI
"cnrb|" // Canara Bank UPI - Empower
"csbpay|" // CSB UPI
"dbs|" // digibank by DBS
"dcb|" // DCB Bank
"denabank|" // Dena Bank E-UPI
"fbl|" // Cointab
"federal|" // Lotza
"hdfcbank|" // HDFC Bank MobileBanking
"hsbc|" // HSBC Simply Pay
"icici|" // Pockets- ICICI Bank
"idbi|" // PayWiz
"idfcbank|" // IDFC Bank UPI App
"indianbank|" // Indian Bank UPI
"indus|" // Indus Pay
"iob|" // IOB UPI
"jkb|" // BHIM JK Bank UPI
"jsb|" // JetPay UPI
"kaypay|" // KayPay
"kbl|" // KBL Smartz
"kotak|" // kotak Mahindra Bank
"kvb|" // KVB Upay
"lvb|" // LVB UPay
"mahb|" // MAHAUPI
"obc|" // Oriental BHIM UPI
"okicici|" // Tez
"okhdfcbank|" // Tez
"okaxis|" // Tez
"paytm|" // Paytm
"pingpay|" // Samsung Pay
"pnb|" // PNB UPI
"pockets|" // Pockets- ICICI Bank
"psb|" // PSB UPI App
"rbl|" // RBL Pay
"sbi|" // SBI Pay
"scb|" // Standard Chartered
"sib|" // SIB M-Pay (UPI Pay)
"syndicate|" // Synd UPI
"tjsb|" // TranZapp
"ubi|" // United UPI
"uboi|" // Union Bank UPI
"uco|" // UCO UPI
"unionbank|" // Union Bank UPI
"united|" // United UPI
"upi|" // BHIM Bharat Interface for Money
"utbi|" // United UPI
"vijb|" // Vijaya UPI App
"ybl|" // Yes Pay
"yesbank" // NuPay
")$";
/////////////////////////////////////////////////////////////////////////////
// form_structure.cc
/////////////////////////////////////////////////////////////////////////////
const char kUrlSearchActionRe[] = "/search(/|((\\w*\\.\\w+)?$))";
} // namespace autofill
| null | null | null | null | 14,266 |
1,644 | null | train_val | 83ed75feba32e46f736fcce0d96a0445f29b96c2 | 163,488 | krb5 | 0 | https://github.com/krb5/krb5 | 2016-01-27 15:43:28-05:00 | /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/* kdc/kdc_preauth_encts.c - Encrypted timestamp kdcpreauth module */
/*
* Copyright (C) 1995, 2003, 2007, 2011 by the Massachusetts Institute of Technology.
* All rights reserved.
*
* Export of this software from the United States of America may
* require a specific license from the United States Government.
* It is the responsibility of any person or organization contemplating
* export to obtain such a license before exporting.
*
* WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
* distribute this software and its documentation for any purpose and
* without fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright notice and
* this permission notice appear in supporting documentation, and that
* the name of M.I.T. not be used in advertising or publicity pertaining
* to distribution of the software without specific, written prior
* permission. Furthermore if you modify this software you must label
* your software as modified software and not distribute it in such a
* fashion that it might be confused with the original M.I.T. software.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is" without express
* or implied warranty.
*/
#include <k5-int.h>
#include <krb5/kdcpreauth_plugin.h>
#include "kdc_util.h"
static void
enc_ts_get(krb5_context context, krb5_kdc_req *request,
krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock,
krb5_kdcpreauth_moddata moddata, krb5_preauthtype pa_type,
krb5_kdcpreauth_edata_respond_fn respond, void *arg)
{
krb5_keyblock *armor_key = cb->fast_armor(context, rock);
/* Encrypted timestamp must not be used with FAST, and requires a key. */
if (armor_key != NULL || !cb->have_client_keys(context, rock))
(*respond)(arg, ENOENT, NULL);
else
(*respond)(arg, 0, NULL);
}
static void
enc_ts_verify(krb5_context context, krb5_data *req_pkt, krb5_kdc_req *request,
krb5_enc_tkt_part *enc_tkt_reply, krb5_pa_data *pa,
krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock,
krb5_kdcpreauth_moddata moddata,
krb5_kdcpreauth_verify_respond_fn respond, void *arg)
{
krb5_pa_enc_ts * pa_enc = 0;
krb5_error_code retval;
krb5_data scratch;
krb5_data enc_ts_data;
krb5_enc_data *enc_data = 0;
krb5_keyblock key;
krb5_key_data * client_key;
krb5_int32 start;
krb5_timestamp timenow;
krb5_error_code decrypt_err = 0;
scratch.data = (char *)pa->contents;
scratch.length = pa->length;
enc_ts_data.data = 0;
if ((retval = decode_krb5_enc_data(&scratch, &enc_data)) != 0)
goto cleanup;
enc_ts_data.length = enc_data->ciphertext.length;
if ((enc_ts_data.data = (char *) malloc(enc_ts_data.length)) == NULL)
goto cleanup;
start = 0;
decrypt_err = 0;
while (1) {
if ((retval = krb5_dbe_search_enctype(context, rock->client,
&start, enc_data->enctype,
-1, 0, &client_key)))
goto cleanup;
if ((retval = krb5_dbe_decrypt_key_data(context, NULL, client_key,
&key, NULL)))
goto cleanup;
key.enctype = enc_data->enctype;
retval = krb5_c_decrypt(context, &key, KRB5_KEYUSAGE_AS_REQ_PA_ENC_TS,
0, enc_data, &enc_ts_data);
krb5_free_keyblock_contents(context, &key);
if (retval == 0)
break;
else
decrypt_err = retval;
}
if ((retval = decode_krb5_pa_enc_ts(&enc_ts_data, &pa_enc)) != 0)
goto cleanup;
if ((retval = krb5_timeofday(context, &timenow)) != 0)
goto cleanup;
if (labs(timenow - pa_enc->patimestamp) > context->clockskew) {
retval = KRB5KRB_AP_ERR_SKEW;
goto cleanup;
}
setflag(enc_tkt_reply->flags, TKT_FLG_PRE_AUTH);
retval = 0;
cleanup:
if (enc_data) {
krb5_free_data_contents(context, &enc_data->ciphertext);
free(enc_data);
}
krb5_free_data_contents(context, &enc_ts_data);
if (pa_enc)
free(pa_enc);
/*
* If we get NO_MATCHING_KEY and decryption previously failed, and
* we failed to find any other keys of the correct enctype after
* that failed decryption, it probably means that the password was
* incorrect.
*/
if (retval == KRB5_KDB_NO_MATCHING_KEY && decrypt_err != 0)
retval = decrypt_err;
(*respond)(arg, retval, NULL, NULL, NULL);
}
static krb5_preauthtype enc_ts_types[] = {
KRB5_PADATA_ENC_TIMESTAMP, 0 };
krb5_error_code
kdcpreauth_encrypted_timestamp_initvt(krb5_context context, int maj_ver,
int min_ver, krb5_plugin_vtable vtable)
{
krb5_kdcpreauth_vtable vt;
if (maj_ver != 1)
return KRB5_PLUGIN_VER_NOTSUPP;
vt = (krb5_kdcpreauth_vtable)vtable;
vt->name = "encrypted_timestamp";
vt->pa_type_list = enc_ts_types;
vt->edata = enc_ts_get;
vt->verify = enc_ts_verify;
return 0;
}
| null | null | null | null | 74,796 |
3,277 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 3,277 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2013 The Chromium 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 "storage/browser/fileapi/sandbox_origin_database_interface.h"
namespace storage {
SandboxOriginDatabaseInterface::OriginRecord::OriginRecord() = default;
SandboxOriginDatabaseInterface::OriginRecord::OriginRecord(
const std::string& origin_in, const base::FilePath& path_in)
: origin(origin_in), path(path_in) {
}
SandboxOriginDatabaseInterface::OriginRecord::~OriginRecord() = default;
} // namespace storage
| null | null | null | null | 140 |
46,192 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 46,192 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2014 The Chromium 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 "ash/wm/workspace/two_step_edge_cycler.h"
#include <cstdlib>
namespace ash {
namespace {
// We cycle to the second mode if any of the following happens while the mouse
// is on the edge of the workspace:
// . The user stops moving the mouse for |kMaxDelay| and then moves the mouse
// again in the preferred direction from the last paused location for at least
// |kMaxPixelsAfterPause| horizontal pixels.
// . The mouse moves |kMaxPixels| horizontal pixels in the preferred direction.
// . The mouse is moved |kMaxMoves| times since the last pause.
const int kMaxDelay = 400;
const int kMaxPixels = 100;
const int kMaxPixelsAfterPause = 10;
const int kMaxMoves = 25;
} // namespace
TwoStepEdgeCycler::TwoStepEdgeCycler(const gfx::Point& start,
TwoStepEdgeCycler::Direction direction)
: second_mode_(false),
time_last_move_(base::TimeTicks::Now()),
num_moves_(0),
start_x_(start.x()),
paused_x_(start.x()),
paused_(false),
direction_(direction) {}
TwoStepEdgeCycler::~TwoStepEdgeCycler() = default;
void TwoStepEdgeCycler::OnMove(const gfx::Point& location) {
if (second_mode_)
return;
if ((base::TimeTicks::Now() - time_last_move_).InMilliseconds() > kMaxDelay) {
paused_ = true;
paused_x_ = location.x();
num_moves_ = 0;
}
time_last_move_ = base::TimeTicks::Now();
int compare_x = paused_ ? paused_x_ : start_x_;
if (location.x() != compare_x &&
(location.x() < compare_x) != (direction_ == DIRECTION_LEFT)) {
return;
}
++num_moves_;
bool moved_in_the_same_direction_after_pause =
paused_ && std::abs(location.x() - paused_x_) >= kMaxPixelsAfterPause;
second_mode_ = moved_in_the_same_direction_after_pause ||
std::abs(location.x() - start_x_) >= kMaxPixels ||
num_moves_ >= kMaxMoves;
}
} // namespace ash
| null | null | null | null | 43,055 |
70,098 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 70,098 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright (c) 2012 The Chromium 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 "device/bluetooth/test/mock_bluetooth_device.h"
#include <memory>
#include <utility>
#include "base/strings/utf_string_conversions.h"
#include "device/bluetooth/bluetooth_remote_gatt_service.h"
#include "device/bluetooth/test/mock_bluetooth_adapter.h"
namespace device {
MockBluetoothDevice::MockBluetoothDevice(MockBluetoothAdapter* adapter,
uint32_t bluetooth_class,
const char* name,
const std::string& address,
bool paired,
bool connected)
: BluetoothDevice(adapter),
bluetooth_class_(bluetooth_class),
name_(name ? base::Optional<std::string>(name) : base::nullopt),
address_(address),
connected_(connected) {
ON_CALL(*this, GetBluetoothClass())
.WillByDefault(testing::Return(bluetooth_class_));
ON_CALL(*this, GetIdentifier())
.WillByDefault(testing::Return(address_ + "-Identifier"));
ON_CALL(*this, GetAddress())
.WillByDefault(testing::Return(address_));
ON_CALL(*this, GetVendorIDSource())
.WillByDefault(testing::Return(VENDOR_ID_UNKNOWN));
ON_CALL(*this, GetVendorID())
.WillByDefault(testing::Return(0));
ON_CALL(*this, GetProductID())
.WillByDefault(testing::Return(0));
ON_CALL(*this, GetDeviceID())
.WillByDefault(testing::Return(0));
ON_CALL(*this, GetName()).WillByDefault(testing::Return(name_));
ON_CALL(*this, GetNameForDisplay())
.WillByDefault(testing::Return(
base::UTF8ToUTF16(name_ ? name_.value() : "Unnamed Device")));
ON_CALL(*this, GetDeviceType())
.WillByDefault(testing::Return(BluetoothDeviceType::UNKNOWN));
ON_CALL(*this, IsPaired())
.WillByDefault(testing::Return(paired));
ON_CALL(*this, IsConnected())
.WillByDefault(testing::ReturnPointee(&connected_));
ON_CALL(*this, IsGattConnected())
.WillByDefault(testing::ReturnPointee(&connected_));
ON_CALL(*this, IsConnectable())
.WillByDefault(testing::Return(false));
ON_CALL(*this, IsConnecting())
.WillByDefault(testing::Return(false));
ON_CALL(*this, GetUUIDs()).WillByDefault(testing::ReturnPointee(&uuids_));
ON_CALL(*this, ExpectingPinCode())
.WillByDefault(testing::Return(false));
ON_CALL(*this, ExpectingPasskey())
.WillByDefault(testing::Return(false));
ON_CALL(*this, ExpectingConfirmation())
.WillByDefault(testing::Return(false));
}
MockBluetoothDevice::~MockBluetoothDevice() = default;
void MockBluetoothDevice::AddMockService(
std::unique_ptr<MockBluetoothGattService> mock_service) {
mock_services_.push_back(std::move(mock_service));
}
std::vector<BluetoothRemoteGattService*> MockBluetoothDevice::GetMockServices()
const {
std::vector<BluetoothRemoteGattService*> services;
for (const auto& service : mock_services_) {
services.push_back(service.get());
}
return services;
}
BluetoothRemoteGattService* MockBluetoothDevice::GetMockService(
const std::string& identifier) const {
for (const auto& service : mock_services_) {
if (service->GetIdentifier() == identifier)
return service.get();
}
return nullptr;
}
void MockBluetoothDevice::PushPendingCallback(const base::Closure& callback) {
pending_callbacks_.push(callback);
}
void MockBluetoothDevice::RunPendingCallbacks() {
while (!pending_callbacks_.empty()) {
pending_callbacks_.front().Run();
pending_callbacks_.pop();
}
}
} // namespace device
| null | null | null | null | 66,961 |
60,200 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 60,200 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright (c) 2012 The Chromium 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 CHROME_BROWSER_TAB_CONTENTS_NAVIGATION_METRICS_RECORDER_H_
#define CHROME_BROWSER_TAB_CONTENTS_NAVIGATION_METRICS_RECORDER_H_
#include "base/macros.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_user_data.h"
class NavigationMetricsRecorder
: public content::WebContentsObserver,
public content::WebContentsUserData<NavigationMetricsRecorder> {
public:
~NavigationMetricsRecorder() override;
private:
explicit NavigationMetricsRecorder(content::WebContents* web_contents);
friend class content::WebContentsUserData<NavigationMetricsRecorder>;
// content::WebContentsObserver overrides:
void DidFinishNavigation(
content::NavigationHandle* navigation_handle) override;
void RegisterSyntheticSigninIsolationTrial();
DISALLOW_COPY_AND_ASSIGN(NavigationMetricsRecorder);
};
#endif // CHROME_BROWSER_TAB_CONTENTS_NAVIGATION_METRICS_RECORDER_H_
| null | null | null | null | 57,063 |
50,061 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 50,061 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright (c) 2011 The Chromium 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 "ui/base/idle/idle.h"
#include "base/bind.h"
namespace ui {
namespace {
void CalculateIdleStateCallback(int idle_threshold,
IdleCallback notify,
int idle_time) {
if (idle_time >= idle_threshold)
notify.Run(IDLE_STATE_IDLE);
else
notify.Run(IDLE_STATE_ACTIVE);
}
} // namespace
void CalculateIdleState(int idle_threshold, IdleCallback notify) {
if (CheckIdleStateIsLocked()) {
notify.Run(IDLE_STATE_LOCKED);
return;
}
CalculateIdleTime(base::Bind(&CalculateIdleStateCallback,
idle_threshold,
notify));
}
} // namespace ui
| null | null | null | null | 46,924 |
40,877 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 40,877 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2015 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "snapshot/win/process_subrange_reader.h"
#include "base/logging.h"
#include "snapshot/win/process_reader_win.h"
namespace crashpad {
ProcessSubrangeReader::ProcessSubrangeReader()
: name_(),
range_(),
process_reader_(nullptr) {
}
ProcessSubrangeReader::~ProcessSubrangeReader() {
}
bool ProcessSubrangeReader::Initialize(ProcessReaderWin* process_reader,
WinVMAddress base,
WinVMSize size,
const std::string& name) {
INITIALIZATION_STATE_SET_INITIALIZING(initialized_);
if (!InitializeInternal(process_reader, base, size, name)) {
return false;
}
INITIALIZATION_STATE_SET_VALID(initialized_);
return true;
}
bool ProcessSubrangeReader::InitializeSubrange(
const ProcessSubrangeReader& that,
WinVMAddress base,
WinVMSize size,
const std::string& sub_name) {
INITIALIZATION_STATE_SET_INITIALIZING(initialized_);
INITIALIZATION_STATE_DCHECK_VALID(that.initialized_);
if (!InitializeInternal(
that.process_reader_, base, size, that.name_ + " " + sub_name)) {
return false;
}
if (!that.range_.ContainsRange(range_)) {
LOG(WARNING) << "range " << range_.AsString() << " outside of range "
<< that.range_.AsString() << " for " << name_;
return false;
}
INITIALIZATION_STATE_SET_VALID(initialized_);
return true;
}
bool ProcessSubrangeReader::ReadMemory(WinVMAddress address,
WinVMSize size,
void* into) const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
CheckedWinAddressRange read_range(process_reader_->Is64Bit(), address, size);
if (!read_range.IsValid()) {
LOG(WARNING) << "invalid read range " << read_range.AsString();
return false;
}
if (!range_.ContainsRange(read_range)) {
LOG(WARNING) << "attempt to read outside of " << name_ << " range "
<< range_.AsString() << " at range " << read_range.AsString();
return false;
}
return process_reader_->ReadMemory(address, size, into);
}
bool ProcessSubrangeReader::InitializeInternal(ProcessReaderWin* process_reader,
WinVMAddress base,
WinVMSize size,
const std::string& name) {
range_.SetRange(process_reader->Is64Bit(), base, size);
if (!range_.IsValid()) {
LOG(WARNING) << "invalid range " << range_.AsString() << " for " << name;
return false;
}
name_ = name;
process_reader_ = process_reader;
return true;
}
} // namespace crashpad
| null | null | null | null | 37,740 |
56,452 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 56,452 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2014 The Chromium 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 "chrome/browser/chromeos/login/users/avatar/user_image_sync_observer.h"
#include "base/bind.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/chromeos/login/screens/user_image_screen.h"
#include "chrome/browser/chromeos/login/users/avatar/user_image_manager.h"
#include "chrome/browser/chromeos/login/users/chrome_user_manager.h"
#include "chrome/browser/chromeos/login/users/default_user_image/default_user_images.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/prefs/pref_service_syncable_util.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/pref_change_registrar.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/sync_preferences/pref_service_syncable.h"
#include "components/user_manager/user.h"
#include "components/user_manager/user_manager.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/notification_service.h"
namespace chromeos {
namespace {
// A dictionary containing info about user image.
const char kUserImageInfo[] = "user_image_info";
// Path to value with image index.
const char kImageIndex[] = "image_index";
bool IsIndexSupported(int index) {
return default_user_image::IsValidIndex(index) ||
(index == user_manager::User::USER_IMAGE_PROFILE);
}
} // anonymous namespace
UserImageSyncObserver::Observer::~Observer() {}
UserImageSyncObserver::UserImageSyncObserver(const user_manager::User* user)
: user_(user),
prefs_(NULL),
is_synced_(false),
local_image_changed_(false) {
user_manager::UserManager::Get()->AddObserver(this);
notification_registrar_.reset(new content::NotificationRegistrar);
if (Profile* profile = ProfileHelper::Get()->GetProfileByUser(user)) {
OnProfileGained(profile);
} else {
notification_registrar_->Add(
this, chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED,
content::NotificationService::AllSources());
}
}
UserImageSyncObserver::~UserImageSyncObserver() {
if (!is_synced_ && prefs_)
prefs_->RemoveObserver(this);
if (pref_change_registrar_)
pref_change_registrar_->RemoveAll();
user_manager::UserManager::Get()->RemoveObserver(this);
}
// static
void UserImageSyncObserver::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry_) {
registry_->RegisterDictionaryPref(
kUserImageInfo, user_prefs::PrefRegistrySyncable::SYNCABLE_PRIORITY_PREF);
}
void UserImageSyncObserver::AddObserver(Observer* observer) {
observer_list_.AddObserver(observer);
}
void UserImageSyncObserver::RemoveObserver(Observer* observer) {
observer_list_.RemoveObserver(observer);
}
void UserImageSyncObserver::OnProfileGained(Profile* profile) {
prefs_ = PrefServiceSyncableFromProfile(profile);
pref_change_registrar_.reset(new PrefChangeRegistrar);
pref_change_registrar_->Init(prefs_);
pref_change_registrar_->Add(
kUserImageInfo, base::Bind(&UserImageSyncObserver::OnPreferenceChanged,
base::Unretained(this)));
is_synced_ = prefs_->IsPrioritySyncing();
if (!is_synced_) {
prefs_->AddObserver(this);
} else {
OnInitialSync();
}
}
void UserImageSyncObserver::OnInitialSync() {
int synced_index;
bool local_image_updated = false;
if (!GetSyncedImageIndex(&synced_index) || local_image_changed_) {
UpdateSyncedImageFromLocal();
} else if (IsIndexSupported(synced_index) && CanUpdateLocalImageNow()) {
UpdateLocalImageFromSynced();
local_image_updated = true;
}
for (auto& observer : observer_list_)
observer.OnInitialSync(local_image_updated);
}
void UserImageSyncObserver::OnPreferenceChanged(const std::string& pref_name) {
// OnPreferenceChanged can be called before OnIsSyncingChanged.
if (!is_synced_) {
is_synced_ = true;
prefs_->RemoveObserver(this);
OnInitialSync();
} else if (CanUpdateLocalImageNow()) {
UpdateLocalImageFromSynced();
}
}
void UserImageSyncObserver::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
DCHECK_EQ(chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED, type);
if (Profile* profile = ProfileHelper::Get()->GetProfileByUser(user_)) {
notification_registrar_->Remove(
this, chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED,
content::NotificationService::AllSources());
OnProfileGained(profile);
}
}
void UserImageSyncObserver::OnUserImageChanged(const user_manager::User& user) {
if (is_synced_)
UpdateSyncedImageFromLocal();
else
local_image_changed_ = true;
}
void UserImageSyncObserver::OnIsSyncingChanged() {
is_synced_ = prefs_->IsPrioritySyncing();
if (is_synced_) {
prefs_->RemoveObserver(this);
OnInitialSync();
}
}
void UserImageSyncObserver::UpdateSyncedImageFromLocal() {
int local_index = user_->image_index();
if (!IsIndexSupported(local_index)) {
local_index = user_manager::User::USER_IMAGE_INVALID;
}
int synced_index;
if (GetSyncedImageIndex(&synced_index) && (synced_index == local_index))
return;
DictionaryPrefUpdate update(prefs_, kUserImageInfo);
base::DictionaryValue* dict = update.Get();
dict->SetInteger(kImageIndex, local_index);
VLOG(1) << "Saved avatar index " << local_index << " to sync.";
}
void UserImageSyncObserver::UpdateLocalImageFromSynced() {
int synced_index;
GetSyncedImageIndex(&synced_index);
int local_index = user_->image_index();
if ((synced_index == local_index) || !IsIndexSupported(synced_index))
return;
UserImageManager* image_manager =
ChromeUserManager::Get()->GetUserImageManager(user_->GetAccountId());
if (synced_index == user_manager::User::USER_IMAGE_PROFILE) {
image_manager->SaveUserImageFromProfileImage();
} else {
image_manager->SaveUserDefaultImageIndex(synced_index);
}
VLOG(1) << "Loaded avatar index " << synced_index << " from sync.";
}
bool UserImageSyncObserver::GetSyncedImageIndex(int* index) {
*index = user_manager::User::USER_IMAGE_INVALID;
const base::DictionaryValue* dict = prefs_->GetDictionary(kUserImageInfo);
return dict && dict->GetInteger(kImageIndex, index);
}
bool UserImageSyncObserver::CanUpdateLocalImageNow() {
if (WizardController* wizard_controller =
WizardController::default_controller()) {
UserImageScreen* screen =
UserImageScreen::Get(wizard_controller->screen_manager());
if (wizard_controller->current_screen() == screen) {
if (screen->user_selected_image())
return false;
}
}
return true;
}
} // namespace chromeos
| null | null | null | null | 53,315 |
22,873 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 187,868 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | /*
* Blackfin On-Chip Serial Driver
*
* Copyright 2006-2011 Analog Devices Inc.
*
* Enter bugs at http://blackfin.uclinux.org/
*
* Licensed under the GPL-2 or later.
*/
#if defined(CONFIG_SERIAL_BFIN_CONSOLE) && defined(CONFIG_MAGIC_SYSRQ)
#define SUPPORT_SYSRQ
#endif
#define DRIVER_NAME "bfin-uart"
#define pr_fmt(fmt) DRIVER_NAME ": " fmt
#include <linux/module.h>
#include <linux/ioport.h>
#include <linux/gfp.h>
#include <linux/io.h>
#include <linux/init.h>
#include <linux/console.h>
#include <linux/sysrq.h>
#include <linux/platform_device.h>
#include <linux/tty.h>
#include <linux/tty_flip.h>
#include <linux/serial_core.h>
#include <linux/gpio.h>
#include <linux/irq.h>
#include <linux/kgdb.h>
#include <linux/slab.h>
#include <linux/dma-mapping.h>
#include <asm/portmux.h>
#include <asm/cacheflush.h>
#include <asm/dma.h>
#include <asm/bfin_serial.h>
#ifdef CONFIG_SERIAL_BFIN_MODULE
# undef CONFIG_EARLY_PRINTK
#endif
/* UART name and device definitions */
#define BFIN_SERIAL_DEV_NAME "ttyBF"
#define BFIN_SERIAL_MAJOR 204
#define BFIN_SERIAL_MINOR 64
static struct bfin_serial_port *bfin_serial_ports[BFIN_UART_NR_PORTS];
#if defined(CONFIG_KGDB_SERIAL_CONSOLE) || \
defined(CONFIG_KGDB_SERIAL_CONSOLE_MODULE)
# ifndef CONFIG_SERIAL_BFIN_PIO
# error KGDB only support UART in PIO mode.
# endif
static int kgdboc_port_line;
static int kgdboc_break_enabled;
#endif
/*
* Setup for console. Argument comes from the menuconfig
*/
#define DMA_RX_XCOUNT 512
#define DMA_RX_YCOUNT (PAGE_SIZE / DMA_RX_XCOUNT)
#define DMA_RX_FLUSH_JIFFIES (HZ / 50)
#ifdef CONFIG_SERIAL_BFIN_DMA
static void bfin_serial_dma_tx_chars(struct bfin_serial_port *uart);
#else
static void bfin_serial_tx_chars(struct bfin_serial_port *uart);
#endif
static void bfin_serial_reset_irda(struct uart_port *port);
#if defined(SERIAL_BFIN_CTSRTS) || \
defined(SERIAL_BFIN_HARD_CTSRTS)
static unsigned int bfin_serial_get_mctrl(struct uart_port *port)
{
struct bfin_serial_port *uart = (struct bfin_serial_port *)port;
if (uart->cts_pin < 0)
return TIOCM_CTS | TIOCM_DSR | TIOCM_CAR;
/* CTS PIN is negative assertive. */
if (UART_GET_CTS(uart))
return TIOCM_CTS | TIOCM_DSR | TIOCM_CAR;
else
return TIOCM_DSR | TIOCM_CAR;
}
static void bfin_serial_set_mctrl(struct uart_port *port, unsigned int mctrl)
{
struct bfin_serial_port *uart = (struct bfin_serial_port *)port;
if (uart->rts_pin < 0)
return;
/* RTS PIN is negative assertive. */
if (mctrl & TIOCM_RTS)
UART_ENABLE_RTS(uart);
else
UART_DISABLE_RTS(uart);
}
/*
* Handle any change of modem status signal.
*/
static irqreturn_t bfin_serial_mctrl_cts_int(int irq, void *dev_id)
{
struct bfin_serial_port *uart = dev_id;
struct uart_port *uport = &uart->port;
unsigned int status = bfin_serial_get_mctrl(uport);
#ifdef SERIAL_BFIN_HARD_CTSRTS
UART_CLEAR_SCTS(uart);
if (uport->hw_stopped) {
if (status) {
uport->hw_stopped = 0;
uart_write_wakeup(uport);
}
} else {
if (!status)
uport->hw_stopped = 1;
}
#else
uart_handle_cts_change(uport, status & TIOCM_CTS);
#endif
return IRQ_HANDLED;
}
#else
static unsigned int bfin_serial_get_mctrl(struct uart_port *port)
{
return TIOCM_CTS | TIOCM_DSR | TIOCM_CAR;
}
static void bfin_serial_set_mctrl(struct uart_port *port, unsigned int mctrl)
{
}
#endif
/*
* interrupts are disabled on entry
*/
static void bfin_serial_stop_tx(struct uart_port *port)
{
struct bfin_serial_port *uart = (struct bfin_serial_port *)port;
#ifdef CONFIG_SERIAL_BFIN_DMA
struct circ_buf *xmit = &uart->port.state->xmit;
#endif
while (!(UART_GET_LSR(uart) & TEMT))
cpu_relax();
#ifdef CONFIG_SERIAL_BFIN_DMA
disable_dma(uart->tx_dma_channel);
xmit->tail = (xmit->tail + uart->tx_count) & (UART_XMIT_SIZE - 1);
uart->port.icount.tx += uart->tx_count;
uart->tx_count = 0;
uart->tx_done = 1;
#else
#if defined(CONFIG_BF54x) || defined(CONFIG_BF60x)
/* Clear TFI bit */
UART_PUT_LSR(uart, TFI);
#endif
UART_CLEAR_IER(uart, ETBEI);
#endif
}
/*
* port is locked and interrupts are disabled
*/
static void bfin_serial_start_tx(struct uart_port *port)
{
struct bfin_serial_port *uart = (struct bfin_serial_port *)port;
struct tty_struct *tty = uart->port.state->port.tty;
/*
* To avoid losting RX interrupt, we reset IR function
* before sending data.
*/
if (tty->termios.c_line == N_IRDA)
bfin_serial_reset_irda(port);
#ifdef CONFIG_SERIAL_BFIN_DMA
if (uart->tx_done)
bfin_serial_dma_tx_chars(uart);
#else
UART_SET_IER(uart, ETBEI);
bfin_serial_tx_chars(uart);
#endif
}
/*
* Interrupts are enabled
*/
static void bfin_serial_stop_rx(struct uart_port *port)
{
struct bfin_serial_port *uart = (struct bfin_serial_port *)port;
UART_CLEAR_IER(uart, ERBFI);
}
#if ANOMALY_05000363 && defined(CONFIG_SERIAL_BFIN_PIO)
# define UART_GET_ANOMALY_THRESHOLD(uart) ((uart)->anomaly_threshold)
# define UART_SET_ANOMALY_THRESHOLD(uart, v) ((uart)->anomaly_threshold = (v))
#else
# define UART_GET_ANOMALY_THRESHOLD(uart) 0
# define UART_SET_ANOMALY_THRESHOLD(uart, v)
#endif
#ifdef CONFIG_SERIAL_BFIN_PIO
static void bfin_serial_rx_chars(struct bfin_serial_port *uart)
{
unsigned int status, ch, flg;
static u64 anomaly_start;
status = UART_GET_LSR(uart);
UART_CLEAR_LSR(uart);
ch = UART_GET_CHAR(uart);
uart->port.icount.rx++;
#if defined(CONFIG_KGDB_SERIAL_CONSOLE) || \
defined(CONFIG_KGDB_SERIAL_CONSOLE_MODULE)
if (kgdb_connected && kgdboc_port_line == uart->port.line
&& kgdboc_break_enabled)
if (ch == 0x3) {/* Ctrl + C */
kgdb_breakpoint();
return;
}
if (!uart->port.state)
return;
#endif
if (ANOMALY_05000363) {
/* The BF533 (and BF561) family of processors have a nice anomaly
* where they continuously generate characters for a "single" break.
* We have to basically ignore this flood until the "next" valid
* character comes across. Due to the nature of the flood, it is
* not possible to reliably catch bytes that are sent too quickly
* after this break. So application code talking to the Blackfin
* which sends a break signal must allow at least 1.5 character
* times after the end of the break for things to stabilize. This
* timeout was picked as it must absolutely be larger than 1
* character time +/- some percent. So 1.5 sounds good. All other
* Blackfin families operate properly. Woo.
*/
if (anomaly_start > 0) {
u64 curr, nsecs, threshold_ns;
if ((~ch & (~ch + 1)) & 0xff)
goto known_good_char;
curr = ktime_get_ns();
nsecs = curr - anomaly_start;
if (nsecs >> 32)
goto known_good_char;
threshold_ns = UART_GET_ANOMALY_THRESHOLD(uart)
* NSEC_PER_USEC;
if (nsecs > threshold_ns)
goto known_good_char;
if (ch)
anomaly_start = 0;
else
anomaly_start = curr;
return;
known_good_char:
status &= ~BI;
anomaly_start = 0;
}
}
if (status & BI) {
if (ANOMALY_05000363)
if (bfin_revid() < 5)
anomaly_start = ktime_get_ns();
uart->port.icount.brk++;
if (uart_handle_break(&uart->port))
goto ignore_char;
status &= ~(PE | FE);
}
if (status & PE)
uart->port.icount.parity++;
if (status & OE)
uart->port.icount.overrun++;
if (status & FE)
uart->port.icount.frame++;
status &= uart->port.read_status_mask;
if (status & BI)
flg = TTY_BREAK;
else if (status & PE)
flg = TTY_PARITY;
else if (status & FE)
flg = TTY_FRAME;
else
flg = TTY_NORMAL;
if (uart_handle_sysrq_char(&uart->port, ch))
goto ignore_char;
uart_insert_char(&uart->port, status, OE, ch, flg);
ignore_char:
tty_flip_buffer_push(&uart->port.state->port);
}
static void bfin_serial_tx_chars(struct bfin_serial_port *uart)
{
struct circ_buf *xmit = &uart->port.state->xmit;
if (uart_circ_empty(xmit) || uart_tx_stopped(&uart->port)) {
#if defined(CONFIG_BF54x) || defined(CONFIG_BF60x)
/* Clear TFI bit */
UART_PUT_LSR(uart, TFI);
#endif
/* Anomaly notes:
* 05000215 - we always clear ETBEI within last UART TX
* interrupt to end a string. It is always set
* when start a new tx.
*/
UART_CLEAR_IER(uart, ETBEI);
return;
}
if (uart->port.x_char) {
UART_PUT_CHAR(uart, uart->port.x_char);
uart->port.icount.tx++;
uart->port.x_char = 0;
}
while ((UART_GET_LSR(uart) & THRE) && xmit->tail != xmit->head) {
UART_PUT_CHAR(uart, xmit->buf[xmit->tail]);
xmit->tail = (xmit->tail + 1) & (UART_XMIT_SIZE - 1);
uart->port.icount.tx++;
}
if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
uart_write_wakeup(&uart->port);
}
static irqreturn_t bfin_serial_rx_int(int irq, void *dev_id)
{
struct bfin_serial_port *uart = dev_id;
while (UART_GET_LSR(uart) & DR)
bfin_serial_rx_chars(uart);
return IRQ_HANDLED;
}
static irqreturn_t bfin_serial_tx_int(int irq, void *dev_id)
{
struct bfin_serial_port *uart = dev_id;
spin_lock(&uart->port.lock);
if (UART_GET_LSR(uart) & THRE)
bfin_serial_tx_chars(uart);
spin_unlock(&uart->port.lock);
return IRQ_HANDLED;
}
#endif
#ifdef CONFIG_SERIAL_BFIN_DMA
static void bfin_serial_dma_tx_chars(struct bfin_serial_port *uart)
{
struct circ_buf *xmit = &uart->port.state->xmit;
uart->tx_done = 0;
if (uart_circ_empty(xmit) || uart_tx_stopped(&uart->port)) {
uart->tx_count = 0;
uart->tx_done = 1;
return;
}
if (uart->port.x_char) {
UART_PUT_CHAR(uart, uart->port.x_char);
uart->port.icount.tx++;
uart->port.x_char = 0;
}
uart->tx_count = CIRC_CNT(xmit->head, xmit->tail, UART_XMIT_SIZE);
if (uart->tx_count > (UART_XMIT_SIZE - xmit->tail))
uart->tx_count = UART_XMIT_SIZE - xmit->tail;
blackfin_dcache_flush_range((unsigned long)(xmit->buf+xmit->tail),
(unsigned long)(xmit->buf+xmit->tail+uart->tx_count));
set_dma_config(uart->tx_dma_channel,
set_bfin_dma_config(DIR_READ, DMA_FLOW_STOP,
INTR_ON_BUF,
DIMENSION_LINEAR,
DATA_SIZE_8,
DMA_SYNC_RESTART));
set_dma_start_addr(uart->tx_dma_channel, (unsigned long)(xmit->buf+xmit->tail));
set_dma_x_count(uart->tx_dma_channel, uart->tx_count);
set_dma_x_modify(uart->tx_dma_channel, 1);
SSYNC();
enable_dma(uart->tx_dma_channel);
UART_SET_IER(uart, ETBEI);
}
static void bfin_serial_dma_rx_chars(struct bfin_serial_port *uart)
{
int i, flg, status;
status = UART_GET_LSR(uart);
UART_CLEAR_LSR(uart);
uart->port.icount.rx +=
CIRC_CNT(uart->rx_dma_buf.head, uart->rx_dma_buf.tail,
UART_XMIT_SIZE);
if (status & BI) {
uart->port.icount.brk++;
if (uart_handle_break(&uart->port))
goto dma_ignore_char;
status &= ~(PE | FE);
}
if (status & PE)
uart->port.icount.parity++;
if (status & OE)
uart->port.icount.overrun++;
if (status & FE)
uart->port.icount.frame++;
status &= uart->port.read_status_mask;
if (status & BI)
flg = TTY_BREAK;
else if (status & PE)
flg = TTY_PARITY;
else if (status & FE)
flg = TTY_FRAME;
else
flg = TTY_NORMAL;
for (i = uart->rx_dma_buf.tail; ; i++) {
if (i >= UART_XMIT_SIZE)
i = 0;
if (i == uart->rx_dma_buf.head)
break;
if (!uart_handle_sysrq_char(&uart->port, uart->rx_dma_buf.buf[i]))
uart_insert_char(&uart->port, status, OE,
uart->rx_dma_buf.buf[i], flg);
}
dma_ignore_char:
tty_flip_buffer_push(&uart->port.state->port);
}
void bfin_serial_rx_dma_timeout(struct bfin_serial_port *uart)
{
int x_pos, pos;
unsigned long flags;
dma_disable_irq_nosync(uart->rx_dma_channel);
spin_lock_irqsave(&uart->rx_lock, flags);
/* 2D DMA RX buffer ring is used. Because curr_y_count and
* curr_x_count can't be read as an atomic operation,
* curr_y_count should be read before curr_x_count. When
* curr_x_count is read, curr_y_count may already indicate
* next buffer line. But, the position calculated here is
* still indicate the old line. The wrong position data may
* be smaller than current buffer tail, which cause garbages
* are received if it is not prohibit.
*/
uart->rx_dma_nrows = get_dma_curr_ycount(uart->rx_dma_channel);
x_pos = get_dma_curr_xcount(uart->rx_dma_channel);
uart->rx_dma_nrows = DMA_RX_YCOUNT - uart->rx_dma_nrows;
if (uart->rx_dma_nrows == DMA_RX_YCOUNT || x_pos == 0)
uart->rx_dma_nrows = 0;
x_pos = DMA_RX_XCOUNT - x_pos;
if (x_pos == DMA_RX_XCOUNT)
x_pos = 0;
pos = uart->rx_dma_nrows * DMA_RX_XCOUNT + x_pos;
/* Ignore receiving data if new position is in the same line of
* current buffer tail and small.
*/
if (pos > uart->rx_dma_buf.tail ||
uart->rx_dma_nrows < (uart->rx_dma_buf.tail/DMA_RX_XCOUNT)) {
uart->rx_dma_buf.head = pos;
bfin_serial_dma_rx_chars(uart);
uart->rx_dma_buf.tail = uart->rx_dma_buf.head;
}
spin_unlock_irqrestore(&uart->rx_lock, flags);
dma_enable_irq(uart->rx_dma_channel);
mod_timer(&(uart->rx_dma_timer), jiffies + DMA_RX_FLUSH_JIFFIES);
}
static irqreturn_t bfin_serial_dma_tx_int(int irq, void *dev_id)
{
struct bfin_serial_port *uart = dev_id;
struct circ_buf *xmit = &uart->port.state->xmit;
spin_lock(&uart->port.lock);
if (!(get_dma_curr_irqstat(uart->tx_dma_channel)&DMA_RUN)) {
disable_dma(uart->tx_dma_channel);
clear_dma_irqstat(uart->tx_dma_channel);
/* Anomaly notes:
* 05000215 - we always clear ETBEI within last UART TX
* interrupt to end a string. It is always set
* when start a new tx.
*/
UART_CLEAR_IER(uart, ETBEI);
uart->port.icount.tx += uart->tx_count;
if (!(xmit->tail == 0 && xmit->head == 0)) {
xmit->tail = (xmit->tail + uart->tx_count) & (UART_XMIT_SIZE - 1);
if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
uart_write_wakeup(&uart->port);
}
bfin_serial_dma_tx_chars(uart);
}
spin_unlock(&uart->port.lock);
return IRQ_HANDLED;
}
static irqreturn_t bfin_serial_dma_rx_int(int irq, void *dev_id)
{
struct bfin_serial_port *uart = dev_id;
unsigned int irqstat;
int x_pos, pos;
spin_lock(&uart->rx_lock);
irqstat = get_dma_curr_irqstat(uart->rx_dma_channel);
clear_dma_irqstat(uart->rx_dma_channel);
uart->rx_dma_nrows = get_dma_curr_ycount(uart->rx_dma_channel);
x_pos = get_dma_curr_xcount(uart->rx_dma_channel);
uart->rx_dma_nrows = DMA_RX_YCOUNT - uart->rx_dma_nrows;
if (uart->rx_dma_nrows == DMA_RX_YCOUNT || x_pos == 0)
uart->rx_dma_nrows = 0;
pos = uart->rx_dma_nrows * DMA_RX_XCOUNT;
if (pos > uart->rx_dma_buf.tail ||
uart->rx_dma_nrows < (uart->rx_dma_buf.tail/DMA_RX_XCOUNT)) {
uart->rx_dma_buf.head = pos;
bfin_serial_dma_rx_chars(uart);
uart->rx_dma_buf.tail = uart->rx_dma_buf.head;
}
spin_unlock(&uart->rx_lock);
return IRQ_HANDLED;
}
#endif
/*
* Return TIOCSER_TEMT when transmitter is not busy.
*/
static unsigned int bfin_serial_tx_empty(struct uart_port *port)
{
struct bfin_serial_port *uart = (struct bfin_serial_port *)port;
unsigned int lsr;
lsr = UART_GET_LSR(uart);
if (lsr & TEMT)
return TIOCSER_TEMT;
else
return 0;
}
static void bfin_serial_break_ctl(struct uart_port *port, int break_state)
{
struct bfin_serial_port *uart = (struct bfin_serial_port *)port;
u32 lcr = UART_GET_LCR(uart);
if (break_state)
lcr |= SB;
else
lcr &= ~SB;
UART_PUT_LCR(uart, lcr);
SSYNC();
}
static int bfin_serial_startup(struct uart_port *port)
{
struct bfin_serial_port *uart = (struct bfin_serial_port *)port;
#ifdef CONFIG_SERIAL_BFIN_DMA
dma_addr_t dma_handle;
if (request_dma(uart->rx_dma_channel, "BFIN_UART_RX") < 0) {
printk(KERN_NOTICE "Unable to attach Blackfin UART RX DMA channel\n");
return -EBUSY;
}
if (request_dma(uart->tx_dma_channel, "BFIN_UART_TX") < 0) {
printk(KERN_NOTICE "Unable to attach Blackfin UART TX DMA channel\n");
free_dma(uart->rx_dma_channel);
return -EBUSY;
}
set_dma_callback(uart->rx_dma_channel, bfin_serial_dma_rx_int, uart);
set_dma_callback(uart->tx_dma_channel, bfin_serial_dma_tx_int, uart);
uart->rx_dma_buf.buf = (unsigned char *)dma_alloc_coherent(NULL, PAGE_SIZE, &dma_handle, GFP_DMA);
uart->rx_dma_buf.head = 0;
uart->rx_dma_buf.tail = 0;
uart->rx_dma_nrows = 0;
set_dma_config(uart->rx_dma_channel,
set_bfin_dma_config(DIR_WRITE, DMA_FLOW_AUTO,
INTR_ON_ROW, DIMENSION_2D,
DATA_SIZE_8,
DMA_SYNC_RESTART));
set_dma_x_count(uart->rx_dma_channel, DMA_RX_XCOUNT);
set_dma_x_modify(uart->rx_dma_channel, 1);
set_dma_y_count(uart->rx_dma_channel, DMA_RX_YCOUNT);
set_dma_y_modify(uart->rx_dma_channel, 1);
set_dma_start_addr(uart->rx_dma_channel, (unsigned long)uart->rx_dma_buf.buf);
enable_dma(uart->rx_dma_channel);
uart->rx_dma_timer.data = (unsigned long)(uart);
uart->rx_dma_timer.function = (void *)bfin_serial_rx_dma_timeout;
uart->rx_dma_timer.expires = jiffies + DMA_RX_FLUSH_JIFFIES;
add_timer(&(uart->rx_dma_timer));
#else
# if defined(CONFIG_KGDB_SERIAL_CONSOLE) || \
defined(CONFIG_KGDB_SERIAL_CONSOLE_MODULE)
if (kgdboc_port_line == uart->port.line && kgdboc_break_enabled)
kgdboc_break_enabled = 0;
else {
# endif
if (request_irq(uart->rx_irq, bfin_serial_rx_int, 0,
"BFIN_UART_RX", uart)) {
printk(KERN_NOTICE "Unable to attach BlackFin UART RX interrupt\n");
return -EBUSY;
}
if (request_irq
(uart->tx_irq, bfin_serial_tx_int, 0,
"BFIN_UART_TX", uart)) {
printk(KERN_NOTICE "Unable to attach BlackFin UART TX interrupt\n");
free_irq(uart->rx_irq, uart);
return -EBUSY;
}
# ifdef CONFIG_BF54x
{
/*
* UART2 and UART3 on BF548 share interrupt PINs and DMA
* controllers with SPORT2 and SPORT3. UART rx and tx
* interrupts are generated in PIO mode only when configure
* their peripheral mapping registers properly, which means
* request corresponding DMA channels in PIO mode as well.
*/
unsigned uart_dma_ch_rx, uart_dma_ch_tx;
switch (uart->rx_irq) {
case IRQ_UART3_RX:
uart_dma_ch_rx = CH_UART3_RX;
uart_dma_ch_tx = CH_UART3_TX;
break;
case IRQ_UART2_RX:
uart_dma_ch_rx = CH_UART2_RX;
uart_dma_ch_tx = CH_UART2_TX;
break;
default:
uart_dma_ch_rx = uart_dma_ch_tx = 0;
break;
}
if (uart_dma_ch_rx &&
request_dma(uart_dma_ch_rx, "BFIN_UART_RX") < 0) {
printk(KERN_NOTICE"Fail to attach UART interrupt\n");
free_irq(uart->rx_irq, uart);
free_irq(uart->tx_irq, uart);
return -EBUSY;
}
if (uart_dma_ch_tx &&
request_dma(uart_dma_ch_tx, "BFIN_UART_TX") < 0) {
printk(KERN_NOTICE "Fail to attach UART interrupt\n");
free_dma(uart_dma_ch_rx);
free_irq(uart->rx_irq, uart);
free_irq(uart->tx_irq, uart);
return -EBUSY;
}
}
# endif
# if defined(CONFIG_KGDB_SERIAL_CONSOLE) || \
defined(CONFIG_KGDB_SERIAL_CONSOLE_MODULE)
}
# endif
#endif
#ifdef SERIAL_BFIN_CTSRTS
if (uart->cts_pin >= 0) {
if (request_irq(gpio_to_irq(uart->cts_pin),
bfin_serial_mctrl_cts_int,
IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING |
0, "BFIN_UART_CTS", uart)) {
uart->cts_pin = -1;
pr_info("Unable to attach BlackFin UART CTS interrupt. So, disable it.\n");
}
}
if (uart->rts_pin >= 0) {
if (gpio_request(uart->rts_pin, DRIVER_NAME)) {
pr_info("fail to request RTS PIN at GPIO_%d\n", uart->rts_pin);
uart->rts_pin = -1;
} else
gpio_direction_output(uart->rts_pin, 0);
}
#endif
#ifdef SERIAL_BFIN_HARD_CTSRTS
if (uart->cts_pin >= 0) {
if (request_irq(uart->status_irq, bfin_serial_mctrl_cts_int,
0, "BFIN_UART_MODEM_STATUS", uart)) {
uart->cts_pin = -1;
dev_info(port->dev, "Unable to attach BlackFin UART Modem Status interrupt.\n");
}
/* CTS RTS PINs are negative assertive. */
UART_PUT_MCR(uart, UART_GET_MCR(uart) | ACTS);
UART_SET_IER(uart, EDSSI);
}
#endif
UART_SET_IER(uart, ERBFI);
return 0;
}
static void bfin_serial_shutdown(struct uart_port *port)
{
struct bfin_serial_port *uart = (struct bfin_serial_port *)port;
#ifdef CONFIG_SERIAL_BFIN_DMA
disable_dma(uart->tx_dma_channel);
free_dma(uart->tx_dma_channel);
disable_dma(uart->rx_dma_channel);
free_dma(uart->rx_dma_channel);
del_timer(&(uart->rx_dma_timer));
dma_free_coherent(NULL, PAGE_SIZE, uart->rx_dma_buf.buf, 0);
#else
#ifdef CONFIG_BF54x
switch (uart->port.irq) {
case IRQ_UART3_RX:
free_dma(CH_UART3_RX);
free_dma(CH_UART3_TX);
break;
case IRQ_UART2_RX:
free_dma(CH_UART2_RX);
free_dma(CH_UART2_TX);
break;
default:
break;
}
#endif
free_irq(uart->rx_irq, uart);
free_irq(uart->tx_irq, uart);
#endif
#ifdef SERIAL_BFIN_CTSRTS
if (uart->cts_pin >= 0)
free_irq(gpio_to_irq(uart->cts_pin), uart);
if (uart->rts_pin >= 0)
gpio_free(uart->rts_pin);
#endif
#ifdef SERIAL_BFIN_HARD_CTSRTS
if (uart->cts_pin >= 0)
free_irq(uart->status_irq, uart);
#endif
}
static void
bfin_serial_set_termios(struct uart_port *port, struct ktermios *termios,
struct ktermios *old)
{
struct bfin_serial_port *uart = (struct bfin_serial_port *)port;
unsigned long flags;
unsigned int baud, quot;
unsigned int ier, lcr = 0;
unsigned long timeout;
#ifdef SERIAL_BFIN_CTSRTS
if (old == NULL && uart->cts_pin != -1)
termios->c_cflag |= CRTSCTS;
else if (uart->cts_pin == -1)
termios->c_cflag &= ~CRTSCTS;
#endif
switch (termios->c_cflag & CSIZE) {
case CS8:
lcr = WLS(8);
break;
case CS7:
lcr = WLS(7);
break;
case CS6:
lcr = WLS(6);
break;
case CS5:
lcr = WLS(5);
break;
default:
printk(KERN_ERR "%s: word length not supported\n",
__func__);
}
/* Anomaly notes:
* 05000231 - STOP bit is always set to 1 whatever the user is set.
*/
if (termios->c_cflag & CSTOPB) {
if (ANOMALY_05000231)
printk(KERN_WARNING "STOP bits other than 1 is not "
"supported in case of anomaly 05000231.\n");
else
lcr |= STB;
}
if (termios->c_cflag & PARENB)
lcr |= PEN;
if (!(termios->c_cflag & PARODD))
lcr |= EPS;
if (termios->c_cflag & CMSPAR)
lcr |= STP;
spin_lock_irqsave(&uart->port.lock, flags);
port->read_status_mask = OE;
if (termios->c_iflag & INPCK)
port->read_status_mask |= (FE | PE);
if (termios->c_iflag & (IGNBRK | BRKINT | PARMRK))
port->read_status_mask |= BI;
/*
* Characters to ignore
*/
port->ignore_status_mask = 0;
if (termios->c_iflag & IGNPAR)
port->ignore_status_mask |= FE | PE;
if (termios->c_iflag & IGNBRK) {
port->ignore_status_mask |= BI;
/*
* If we're ignoring parity and break indicators,
* ignore overruns too (for real raw support).
*/
if (termios->c_iflag & IGNPAR)
port->ignore_status_mask |= OE;
}
baud = uart_get_baud_rate(port, termios, old, 0, port->uartclk/16);
quot = uart_get_divisor(port, baud);
/* If discipline is not IRDA, apply ANOMALY_05000230 */
if (termios->c_line != N_IRDA)
quot -= ANOMALY_05000230;
UART_SET_ANOMALY_THRESHOLD(uart, USEC_PER_SEC / baud * 15);
/* Wait till the transfer buffer is empty */
timeout = jiffies + msecs_to_jiffies(10);
while (UART_GET_GCTL(uart) & UCEN && !(UART_GET_LSR(uart) & TEMT))
if (time_after(jiffies, timeout)) {
dev_warn(port->dev, "timeout waiting for TX buffer empty\n");
break;
}
/* Disable UART */
ier = UART_GET_IER(uart);
UART_PUT_GCTL(uart, UART_GET_GCTL(uart) & ~UCEN);
UART_DISABLE_INTS(uart);
/* Set DLAB in LCR to Access CLK */
UART_SET_DLAB(uart);
UART_PUT_CLK(uart, quot);
SSYNC();
/* Clear DLAB in LCR to Access THR RBR IER */
UART_CLEAR_DLAB(uart);
UART_PUT_LCR(uart, (UART_GET_LCR(uart) & ~LCR_MASK) | lcr);
/* Enable UART */
UART_ENABLE_INTS(uart, ier);
UART_PUT_GCTL(uart, UART_GET_GCTL(uart) | UCEN);
/* Port speed changed, update the per-port timeout. */
uart_update_timeout(port, termios->c_cflag, baud);
spin_unlock_irqrestore(&uart->port.lock, flags);
}
static const char *bfin_serial_type(struct uart_port *port)
{
struct bfin_serial_port *uart = (struct bfin_serial_port *)port;
return uart->port.type == PORT_BFIN ? "BFIN-UART" : NULL;
}
/*
* Release the memory region(s) being used by 'port'.
*/
static void bfin_serial_release_port(struct uart_port *port)
{
}
/*
* Request the memory region(s) being used by 'port'.
*/
static int bfin_serial_request_port(struct uart_port *port)
{
return 0;
}
/*
* Configure/autoconfigure the port.
*/
static void bfin_serial_config_port(struct uart_port *port, int flags)
{
struct bfin_serial_port *uart = (struct bfin_serial_port *)port;
if (flags & UART_CONFIG_TYPE &&
bfin_serial_request_port(&uart->port) == 0)
uart->port.type = PORT_BFIN;
}
/*
* Verify the new serial_struct (for TIOCSSERIAL).
* The only change we allow are to the flags and type, and
* even then only between PORT_BFIN and PORT_UNKNOWN
*/
static int
bfin_serial_verify_port(struct uart_port *port, struct serial_struct *ser)
{
return 0;
}
/*
* Enable the IrDA function if tty->ldisc.num is N_IRDA.
* In other cases, disable IrDA function.
*/
static void bfin_serial_set_ldisc(struct uart_port *port,
struct ktermios *termios)
{
struct bfin_serial_port *uart = (struct bfin_serial_port *)port;
unsigned int val;
switch (termios->c_line) {
case N_IRDA:
val = UART_GET_GCTL(uart);
val |= (UMOD_IRDA | RPOLC);
UART_PUT_GCTL(uart, val);
break;
default:
val = UART_GET_GCTL(uart);
val &= ~(UMOD_MASK | RPOLC);
UART_PUT_GCTL(uart, val);
}
}
static void bfin_serial_reset_irda(struct uart_port *port)
{
struct bfin_serial_port *uart = (struct bfin_serial_port *)port;
unsigned int val;
val = UART_GET_GCTL(uart);
val &= ~(UMOD_MASK | RPOLC);
UART_PUT_GCTL(uart, val);
SSYNC();
val |= (UMOD_IRDA | RPOLC);
UART_PUT_GCTL(uart, val);
SSYNC();
}
#ifdef CONFIG_CONSOLE_POLL
/* Anomaly notes:
* 05000099 - Because we only use THRE in poll_put and DR in poll_get,
* losing other bits of UART_LSR is not a problem here.
*/
static void bfin_serial_poll_put_char(struct uart_port *port, unsigned char chr)
{
struct bfin_serial_port *uart = (struct bfin_serial_port *)port;
while (!(UART_GET_LSR(uart) & THRE))
cpu_relax();
UART_CLEAR_DLAB(uart);
UART_PUT_CHAR(uart, (unsigned char)chr);
}
static int bfin_serial_poll_get_char(struct uart_port *port)
{
struct bfin_serial_port *uart = (struct bfin_serial_port *)port;
unsigned char chr;
while (!(UART_GET_LSR(uart) & DR))
cpu_relax();
UART_CLEAR_DLAB(uart);
chr = UART_GET_CHAR(uart);
return chr;
}
#endif
static struct uart_ops bfin_serial_pops = {
.tx_empty = bfin_serial_tx_empty,
.set_mctrl = bfin_serial_set_mctrl,
.get_mctrl = bfin_serial_get_mctrl,
.stop_tx = bfin_serial_stop_tx,
.start_tx = bfin_serial_start_tx,
.stop_rx = bfin_serial_stop_rx,
.break_ctl = bfin_serial_break_ctl,
.startup = bfin_serial_startup,
.shutdown = bfin_serial_shutdown,
.set_termios = bfin_serial_set_termios,
.set_ldisc = bfin_serial_set_ldisc,
.type = bfin_serial_type,
.release_port = bfin_serial_release_port,
.request_port = bfin_serial_request_port,
.config_port = bfin_serial_config_port,
.verify_port = bfin_serial_verify_port,
#ifdef CONFIG_CONSOLE_POLL
.poll_put_char = bfin_serial_poll_put_char,
.poll_get_char = bfin_serial_poll_get_char,
#endif
};
#if defined(CONFIG_SERIAL_BFIN_CONSOLE) || defined(CONFIG_EARLY_PRINTK)
/*
* If the port was already initialised (eg, by a boot loader),
* try to determine the current setup.
*/
static void __init
bfin_serial_console_get_options(struct bfin_serial_port *uart, int *baud,
int *parity, int *bits)
{
unsigned int status;
status = UART_GET_IER(uart) & (ERBFI | ETBEI);
if (status == (ERBFI | ETBEI)) {
/* ok, the port was enabled */
u32 lcr, clk;
lcr = UART_GET_LCR(uart);
*parity = 'n';
if (lcr & PEN) {
if (lcr & EPS)
*parity = 'e';
else
*parity = 'o';
}
*bits = ((lcr & WLS_MASK) >> WLS_OFFSET) + 5;
/* Set DLAB in LCR to Access CLK */
UART_SET_DLAB(uart);
clk = UART_GET_CLK(uart);
/* Clear DLAB in LCR to Access THR RBR IER */
UART_CLEAR_DLAB(uart);
*baud = get_sclk() / (16*clk);
}
pr_debug("%s:baud = %d, parity = %c, bits= %d\n", __func__, *baud, *parity, *bits);
}
static struct uart_driver bfin_serial_reg;
static void bfin_serial_console_putchar(struct uart_port *port, int ch)
{
struct bfin_serial_port *uart = (struct bfin_serial_port *)port;
while (!(UART_GET_LSR(uart) & THRE))
barrier();
UART_PUT_CHAR(uart, ch);
}
#endif /* defined (CONFIG_SERIAL_BFIN_CONSOLE) ||
defined (CONFIG_EARLY_PRINTK) */
#ifdef CONFIG_SERIAL_BFIN_CONSOLE
#define CLASS_BFIN_CONSOLE "bfin-console"
/*
* Interrupts are disabled on entering
*/
static void
bfin_serial_console_write(struct console *co, const char *s, unsigned int count)
{
struct bfin_serial_port *uart = bfin_serial_ports[co->index];
unsigned long flags;
spin_lock_irqsave(&uart->port.lock, flags);
uart_console_write(&uart->port, s, count, bfin_serial_console_putchar);
spin_unlock_irqrestore(&uart->port.lock, flags);
}
static int __init
bfin_serial_console_setup(struct console *co, char *options)
{
struct bfin_serial_port *uart;
int baud = 57600;
int bits = 8;
int parity = 'n';
# if defined(SERIAL_BFIN_CTSRTS) || \
defined(SERIAL_BFIN_HARD_CTSRTS)
int flow = 'r';
# else
int flow = 'n';
# endif
/*
* Check whether an invalid uart number has been specified, and
* if so, search for the first available port that does have
* console support.
*/
if (co->index < 0 || co->index >= BFIN_UART_NR_PORTS)
return -ENODEV;
uart = bfin_serial_ports[co->index];
if (!uart)
return -ENODEV;
if (options)
uart_parse_options(options, &baud, &parity, &bits, &flow);
else
bfin_serial_console_get_options(uart, &baud, &parity, &bits);
return uart_set_options(&uart->port, co, baud, parity, bits, flow);
}
static struct console bfin_serial_console = {
.name = BFIN_SERIAL_DEV_NAME,
.write = bfin_serial_console_write,
.device = uart_console_device,
.setup = bfin_serial_console_setup,
.flags = CON_PRINTBUFFER,
.index = -1,
.data = &bfin_serial_reg,
};
#define BFIN_SERIAL_CONSOLE (&bfin_serial_console)
#else
#define BFIN_SERIAL_CONSOLE NULL
#endif /* CONFIG_SERIAL_BFIN_CONSOLE */
#ifdef CONFIG_EARLY_PRINTK
static struct bfin_serial_port bfin_earlyprintk_port;
#define CLASS_BFIN_EARLYPRINTK "bfin-earlyprintk"
/*
* Interrupts are disabled on entering
*/
static void
bfin_earlyprintk_console_write(struct console *co, const char *s, unsigned int count)
{
unsigned long flags;
if (bfin_earlyprintk_port.port.line != co->index)
return;
spin_lock_irqsave(&bfin_earlyprintk_port.port.lock, flags);
uart_console_write(&bfin_earlyprintk_port.port, s, count,
bfin_serial_console_putchar);
spin_unlock_irqrestore(&bfin_earlyprintk_port.port.lock, flags);
}
/*
* This should have a .setup or .early_setup in it, but then things get called
* without the command line options, and the baud rate gets messed up - so
* don't let the common infrastructure play with things. (see calls to setup
* & earlysetup in ./kernel/printk.c:register_console()
*/
static struct console bfin_early_serial_console __initdata = {
.name = "early_BFuart",
.write = bfin_earlyprintk_console_write,
.device = uart_console_device,
.flags = CON_PRINTBUFFER,
.index = -1,
.data = &bfin_serial_reg,
};
#endif
static struct uart_driver bfin_serial_reg = {
.owner = THIS_MODULE,
.driver_name = DRIVER_NAME,
.dev_name = BFIN_SERIAL_DEV_NAME,
.major = BFIN_SERIAL_MAJOR,
.minor = BFIN_SERIAL_MINOR,
.nr = BFIN_UART_NR_PORTS,
.cons = BFIN_SERIAL_CONSOLE,
};
static int bfin_serial_suspend(struct platform_device *pdev, pm_message_t state)
{
struct bfin_serial_port *uart = platform_get_drvdata(pdev);
return uart_suspend_port(&bfin_serial_reg, &uart->port);
}
static int bfin_serial_resume(struct platform_device *pdev)
{
struct bfin_serial_port *uart = platform_get_drvdata(pdev);
return uart_resume_port(&bfin_serial_reg, &uart->port);
}
static int bfin_serial_probe(struct platform_device *pdev)
{
struct resource *res;
struct bfin_serial_port *uart = NULL;
int ret = 0;
if (pdev->id < 0 || pdev->id >= BFIN_UART_NR_PORTS) {
dev_err(&pdev->dev, "Wrong bfin uart platform device id.\n");
return -ENOENT;
}
if (bfin_serial_ports[pdev->id] == NULL) {
uart = kzalloc(sizeof(*uart), GFP_KERNEL);
if (!uart) {
dev_err(&pdev->dev,
"fail to malloc bfin_serial_port\n");
return -ENOMEM;
}
bfin_serial_ports[pdev->id] = uart;
#ifdef CONFIG_EARLY_PRINTK
if (!(bfin_earlyprintk_port.port.membase
&& bfin_earlyprintk_port.port.line == pdev->id)) {
/*
* If the peripheral PINs of current port is allocated
* in earlyprintk probe stage, don't do it again.
*/
#endif
ret = peripheral_request_list(
dev_get_platdata(&pdev->dev),
DRIVER_NAME);
if (ret) {
dev_err(&pdev->dev,
"fail to request bfin serial peripherals\n");
goto out_error_free_mem;
}
#ifdef CONFIG_EARLY_PRINTK
}
#endif
spin_lock_init(&uart->port.lock);
uart->port.uartclk = get_sclk();
uart->port.fifosize = BFIN_UART_TX_FIFO_SIZE;
uart->port.ops = &bfin_serial_pops;
uart->port.line = pdev->id;
uart->port.iotype = UPIO_MEM;
uart->port.flags = UPF_BOOT_AUTOCONF;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res == NULL) {
dev_err(&pdev->dev, "Cannot get IORESOURCE_MEM\n");
ret = -ENOENT;
goto out_error_free_peripherals;
}
uart->port.membase = ioremap(res->start, resource_size(res));
if (!uart->port.membase) {
dev_err(&pdev->dev, "Cannot map uart IO\n");
ret = -ENXIO;
goto out_error_free_peripherals;
}
uart->port.mapbase = res->start;
uart->tx_irq = platform_get_irq(pdev, 0);
if (uart->tx_irq < 0) {
dev_err(&pdev->dev, "No uart TX IRQ specified\n");
ret = -ENOENT;
goto out_error_unmap;
}
uart->rx_irq = platform_get_irq(pdev, 1);
if (uart->rx_irq < 0) {
dev_err(&pdev->dev, "No uart RX IRQ specified\n");
ret = -ENOENT;
goto out_error_unmap;
}
uart->port.irq = uart->rx_irq;
uart->status_irq = platform_get_irq(pdev, 2);
if (uart->status_irq < 0) {
dev_err(&pdev->dev, "No uart status IRQ specified\n");
ret = -ENOENT;
goto out_error_unmap;
}
#ifdef CONFIG_SERIAL_BFIN_DMA
spin_lock_init(&uart->rx_lock);
uart->tx_done = 1;
uart->tx_count = 0;
res = platform_get_resource(pdev, IORESOURCE_DMA, 0);
if (res == NULL) {
dev_err(&pdev->dev, "No uart TX DMA channel specified\n");
ret = -ENOENT;
goto out_error_unmap;
}
uart->tx_dma_channel = res->start;
res = platform_get_resource(pdev, IORESOURCE_DMA, 1);
if (res == NULL) {
dev_err(&pdev->dev, "No uart RX DMA channel specified\n");
ret = -ENOENT;
goto out_error_unmap;
}
uart->rx_dma_channel = res->start;
init_timer(&(uart->rx_dma_timer));
#endif
#if defined(SERIAL_BFIN_CTSRTS) || \
defined(SERIAL_BFIN_HARD_CTSRTS)
res = platform_get_resource(pdev, IORESOURCE_IO, 0);
if (res == NULL)
uart->cts_pin = -1;
else
uart->cts_pin = res->start;
res = platform_get_resource(pdev, IORESOURCE_IO, 1);
if (res == NULL)
uart->rts_pin = -1;
else
uart->rts_pin = res->start;
#endif
}
#ifdef CONFIG_SERIAL_BFIN_CONSOLE
if (!is_early_platform_device(pdev)) {
#endif
uart = bfin_serial_ports[pdev->id];
uart->port.dev = &pdev->dev;
dev_set_drvdata(&pdev->dev, uart);
ret = uart_add_one_port(&bfin_serial_reg, &uart->port);
#ifdef CONFIG_SERIAL_BFIN_CONSOLE
}
#endif
if (!ret)
return 0;
if (uart) {
out_error_unmap:
iounmap(uart->port.membase);
out_error_free_peripherals:
peripheral_free_list(dev_get_platdata(&pdev->dev));
out_error_free_mem:
kfree(uart);
bfin_serial_ports[pdev->id] = NULL;
}
return ret;
}
static int bfin_serial_remove(struct platform_device *pdev)
{
struct bfin_serial_port *uart = platform_get_drvdata(pdev);
dev_set_drvdata(&pdev->dev, NULL);
if (uart) {
uart_remove_one_port(&bfin_serial_reg, &uart->port);
iounmap(uart->port.membase);
peripheral_free_list(dev_get_platdata(&pdev->dev));
kfree(uart);
bfin_serial_ports[pdev->id] = NULL;
}
return 0;
}
static struct platform_driver bfin_serial_driver = {
.probe = bfin_serial_probe,
.remove = bfin_serial_remove,
.suspend = bfin_serial_suspend,
.resume = bfin_serial_resume,
.driver = {
.name = DRIVER_NAME,
},
};
#if defined(CONFIG_SERIAL_BFIN_CONSOLE)
static struct early_platform_driver early_bfin_serial_driver __initdata = {
.class_str = CLASS_BFIN_CONSOLE,
.pdrv = &bfin_serial_driver,
.requested_id = EARLY_PLATFORM_ID_UNSET,
};
static int __init bfin_serial_rs_console_init(void)
{
early_platform_driver_register(&early_bfin_serial_driver, DRIVER_NAME);
early_platform_driver_probe(CLASS_BFIN_CONSOLE, BFIN_UART_NR_PORTS, 0);
register_console(&bfin_serial_console);
return 0;
}
console_initcall(bfin_serial_rs_console_init);
#endif
#ifdef CONFIG_EARLY_PRINTK
/*
* Memory can't be allocated dynamically during earlyprink init stage.
* So, do individual probe for earlyprink with a static uart port variable.
*/
static int bfin_earlyprintk_probe(struct platform_device *pdev)
{
struct resource *res;
int ret;
if (pdev->id < 0 || pdev->id >= BFIN_UART_NR_PORTS) {
dev_err(&pdev->dev, "Wrong earlyprintk platform device id.\n");
return -ENOENT;
}
ret = peripheral_request_list(dev_get_platdata(&pdev->dev),
DRIVER_NAME);
if (ret) {
dev_err(&pdev->dev,
"fail to request bfin serial peripherals\n");
return ret;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res == NULL) {
dev_err(&pdev->dev, "Cannot get IORESOURCE_MEM\n");
ret = -ENOENT;
goto out_error_free_peripherals;
}
bfin_earlyprintk_port.port.membase = ioremap(res->start,
resource_size(res));
if (!bfin_earlyprintk_port.port.membase) {
dev_err(&pdev->dev, "Cannot map uart IO\n");
ret = -ENXIO;
goto out_error_free_peripherals;
}
bfin_earlyprintk_port.port.mapbase = res->start;
bfin_earlyprintk_port.port.line = pdev->id;
bfin_earlyprintk_port.port.uartclk = get_sclk();
bfin_earlyprintk_port.port.fifosize = BFIN_UART_TX_FIFO_SIZE;
spin_lock_init(&bfin_earlyprintk_port.port.lock);
return 0;
out_error_free_peripherals:
peripheral_free_list(dev_get_platdata(&pdev->dev));
return ret;
}
static struct platform_driver bfin_earlyprintk_driver = {
.probe = bfin_earlyprintk_probe,
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
},
};
static struct early_platform_driver early_bfin_earlyprintk_driver __initdata = {
.class_str = CLASS_BFIN_EARLYPRINTK,
.pdrv = &bfin_earlyprintk_driver,
.requested_id = EARLY_PLATFORM_ID_UNSET,
};
struct console __init *bfin_earlyserial_init(unsigned int port,
unsigned int cflag)
{
struct ktermios t;
char port_name[20];
if (port < 0 || port >= BFIN_UART_NR_PORTS)
return NULL;
/*
* Only probe resource of the given port in earlyprintk boot arg.
* The expected port id should be indicated in port name string.
*/
snprintf(port_name, 20, DRIVER_NAME ".%d", port);
early_platform_driver_register(&early_bfin_earlyprintk_driver,
port_name);
early_platform_driver_probe(CLASS_BFIN_EARLYPRINTK, 1, 0);
if (!bfin_earlyprintk_port.port.membase)
return NULL;
#ifdef CONFIG_SERIAL_BFIN_CONSOLE
/*
* If we are using early serial, don't let the normal console rewind
* log buffer, since that causes things to be printed multiple times
*/
bfin_serial_console.flags &= ~CON_PRINTBUFFER;
#endif
bfin_early_serial_console.index = port;
t.c_cflag = cflag;
t.c_iflag = 0;
t.c_oflag = 0;
t.c_lflag = ICANON;
t.c_line = port;
bfin_serial_set_termios(&bfin_earlyprintk_port.port, &t, &t);
return &bfin_early_serial_console;
}
#endif /* CONFIG_EARLY_PRINTK */
static int __init bfin_serial_init(void)
{
int ret;
pr_info("Blackfin serial driver\n");
ret = uart_register_driver(&bfin_serial_reg);
if (ret) {
pr_err("failed to register %s:%d\n",
bfin_serial_reg.driver_name, ret);
}
ret = platform_driver_register(&bfin_serial_driver);
if (ret) {
pr_err("fail to register bfin uart\n");
uart_unregister_driver(&bfin_serial_reg);
}
return ret;
}
static void __exit bfin_serial_exit(void)
{
platform_driver_unregister(&bfin_serial_driver);
uart_unregister_driver(&bfin_serial_reg);
}
module_init(bfin_serial_init);
module_exit(bfin_serial_exit);
MODULE_AUTHOR("Sonic Zhang, Aubrey Li");
MODULE_DESCRIPTION("Blackfin generic serial port driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS_CHARDEV_MAJOR(BFIN_SERIAL_MAJOR);
MODULE_ALIAS("platform:bfin-uart");
| null | null | null | null | 96,215 |
60,177 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 60,177 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2016 The Chromium 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 "chrome/browser/usb/usb_blocklist.h"
#include "components/variations/variations_params_manager.h"
#include "testing/gtest/include/gtest/gtest.h"
class UsbBlocklistTest : public testing::Test {
public:
UsbBlocklistTest() : blocklist_(UsbBlocklist::Get()) {}
const UsbBlocklist& list() { return blocklist_; }
void SetDynamicBlocklist(base::StringPiece list) {
params_manager_.ClearAllVariationParams();
std::map<std::string, std::string> params;
params["blocklist_additions"] = list.as_string();
params_manager_.SetVariationParams("WebUSBBlocklist", params);
blocklist_.ResetToDefaultValuesForTest();
}
private:
void TearDown() override {
// Because UsbBlocklist is a singleton it must be cleared after tests run
// to prevent leakage between tests.
params_manager_.ClearAllVariationParams();
blocklist_.ResetToDefaultValuesForTest();
}
variations::testing::VariationParamsManager params_manager_;
UsbBlocklist& blocklist_;
};
TEST_F(UsbBlocklistTest, BasicExclusions) {
SetDynamicBlocklist("18D1:58F0:0100");
EXPECT_TRUE(list().IsExcluded({0x18D1, 0x58F0, 0x0100}));
// An older device version is also blocked.
EXPECT_TRUE(list().IsExcluded({0x18D1, 0x58F0, 0x0090}));
// A newer device version is not blocked.
EXPECT_FALSE(list().IsExcluded({0x18D1, 0x58F0, 0x0200}));
// Other devices with nearby vendor and product IDs are not blocked.
EXPECT_FALSE(list().IsExcluded({0x18D1, 0x58F1, 0x0100}));
EXPECT_FALSE(list().IsExcluded({0x18D1, 0x58EF, 0x0100}));
EXPECT_FALSE(list().IsExcluded({0x18D0, 0x58F0, 0x0100}));
EXPECT_FALSE(list().IsExcluded({0x18D2, 0x58F0, 0x0100}));
}
TEST_F(UsbBlocklistTest, StringsWithNoValidEntries) {
SetDynamicBlocklist("");
EXPECT_EQ(0u, list().GetDynamicEntryCountForTest());
SetDynamicBlocklist("~!@#$%^&*()-_=+[]{}/*-");
EXPECT_EQ(0u, list().GetDynamicEntryCountForTest());
SetDynamicBlocklist(":");
EXPECT_EQ(0u, list().GetDynamicEntryCountForTest());
SetDynamicBlocklist("::");
EXPECT_EQ(0u, list().GetDynamicEntryCountForTest());
SetDynamicBlocklist(",");
EXPECT_EQ(0u, list().GetDynamicEntryCountForTest());
SetDynamicBlocklist(",,");
EXPECT_EQ(0u, list().GetDynamicEntryCountForTest());
SetDynamicBlocklist(",::,");
EXPECT_EQ(0u, list().GetDynamicEntryCountForTest());
SetDynamicBlocklist("1:2:3");
EXPECT_EQ(0u, list().GetDynamicEntryCountForTest());
SetDynamicBlocklist("18D1:2:3000");
EXPECT_EQ(0u, list().GetDynamicEntryCountForTest());
SetDynamicBlocklist("0000:0x00:0000");
EXPECT_EQ(0u, list().GetDynamicEntryCountForTest());
SetDynamicBlocklist("0000: 0:0000");
EXPECT_EQ(0u, list().GetDynamicEntryCountForTest());
SetDynamicBlocklist("000g:0000:0000");
EXPECT_EQ(0u, list().GetDynamicEntryCountForTest());
SetDynamicBlocklist("☯");
EXPECT_EQ(0u, list().GetDynamicEntryCountForTest());
}
TEST_F(UsbBlocklistTest, StringsWithOneValidEntry) {
SetDynamicBlocklist("18D1:58F0:0101");
EXPECT_EQ(1u, list().GetDynamicEntryCountForTest());
EXPECT_TRUE(list().IsExcluded({0x18D1, 0x58F0, 0x0101}));
SetDynamicBlocklist(" 18D1:58F0:0200 ");
EXPECT_EQ(1u, list().GetDynamicEntryCountForTest());
EXPECT_TRUE(list().IsExcluded({0x18D1, 0x58F0, 0x0200}));
SetDynamicBlocklist(", 18D1:58F0:0201, ");
EXPECT_EQ(1u, list().GetDynamicEntryCountForTest());
EXPECT_TRUE(list().IsExcluded({0x18D1, 0x58F0, 0x0201}));
SetDynamicBlocklist("18D1:58F0:0202, 0000:1:0000");
EXPECT_EQ(1u, list().GetDynamicEntryCountForTest());
EXPECT_TRUE(list().IsExcluded({0x18D1, 0x58F0, 0x0202}));
}
TEST_F(UsbBlocklistTest, StaticEntries) {
// Yubikey devices. https://crbug.com/818807
//
// The specific versions of these devices that we want to block are unknown.
// The device versions listed here are abitrary chosen to test that any device
// will be matched.
EXPECT_TRUE(list().IsExcluded({0x1050, 0x0010, 0x0100}));
EXPECT_TRUE(list().IsExcluded({0x1050, 0x0018, 0x0100}));
EXPECT_TRUE(list().IsExcluded({0x1050, 0x0030, 0x0100}));
EXPECT_TRUE(list().IsExcluded({0x1050, 0x0110, 0x0100}));
EXPECT_TRUE(list().IsExcluded({0x1050, 0x0111, 0x0100}));
EXPECT_TRUE(list().IsExcluded({0x1050, 0x0112, 0x0100}));
EXPECT_TRUE(list().IsExcluded({0x1050, 0x0113, 0x0100}));
EXPECT_TRUE(list().IsExcluded({0x1050, 0x0114, 0x0100}));
EXPECT_TRUE(list().IsExcluded({0x1050, 0x0115, 0x0100}));
EXPECT_TRUE(list().IsExcluded({0x1050, 0x0116, 0x0100}));
EXPECT_TRUE(list().IsExcluded({0x1050, 0x0120, 0x0100}));
EXPECT_TRUE(list().IsExcluded({0x1050, 0x0200, 0x0100}));
EXPECT_TRUE(list().IsExcluded({0x1050, 0x0211, 0x0100}));
EXPECT_TRUE(list().IsExcluded({0x1050, 0x0401, 0x0100}));
EXPECT_TRUE(list().IsExcluded({0x1050, 0x0402, 0x0100}));
EXPECT_TRUE(list().IsExcluded({0x1050, 0x0403, 0x0100}));
EXPECT_TRUE(list().IsExcluded({0x1050, 0x0404, 0x0100}));
EXPECT_TRUE(list().IsExcluded({0x1050, 0x0405, 0x0100}));
EXPECT_TRUE(list().IsExcluded({0x1050, 0x0406, 0x0100}));
EXPECT_TRUE(list().IsExcluded({0x1050, 0x0407, 0x0100}));
EXPECT_TRUE(list().IsExcluded({0x1050, 0x0410, 0x0100}));
// Check that various devices around the Yubikey range are not blocked.
EXPECT_FALSE(list().IsExcluded({0x104F, 0x0200, 0x0100}));
EXPECT_FALSE(list().IsExcluded({0x1051, 0x0200, 0x0100}));
}
| null | null | null | null | 57,040 |
53,747 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 53,747 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright (c) 2012 The Chromium 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 ANDROID_WEBVIEW_RENDERER_AW_RENDER_VIEW_EXT_H_
#define ANDROID_WEBVIEW_RENDERER_AW_RENDER_VIEW_EXT_H_
#include "base/timer/timer.h"
#include "content/public/renderer/render_view_observer.h"
#include "ui/gfx/geometry/size.h"
namespace android_webview {
// Render process side of AwRenderViewHostExt, this provides cross-process
// implementation of miscellaneous WebView functions that we need to poke
// WebKit directly to implement (and that aren't needed in the chrome app).
class AwRenderViewExt : public content::RenderViewObserver {
public:
static void RenderViewCreated(content::RenderView* render_view);
private:
AwRenderViewExt(content::RenderView* render_view);
~AwRenderViewExt() override;
// RenderViewObserver:
void DidCommitCompositorFrame() override;
void DidUpdateLayout() override;
void OnDestruct() override;
void CheckContentsSize();
void PostCheckContentsSize();
gfx::Size last_sent_contents_size_;
base::OneShotTimer check_contents_size_timer_;
DISALLOW_COPY_AND_ASSIGN(AwRenderViewExt);
};
} // namespace android_webview
#endif // ANDROID_WEBVIEW_RENDERER_AW_RENDER_VIEW_EXT_H_
| null | null | null | null | 50,610 |
43,654 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 208,649 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | /*
* USB Communications Device Class (CDC) definitions
*
* CDC says how to talk to lots of different types of network adapters,
* notably ethernet adapters and various modems. It's used mostly with
* firmware based USB peripherals.
*/
#ifndef __UAPI_LINUX_USB_CDC_H
#define __UAPI_LINUX_USB_CDC_H
#include <linux/types.h>
#define USB_CDC_SUBCLASS_ACM 0x02
#define USB_CDC_SUBCLASS_ETHERNET 0x06
#define USB_CDC_SUBCLASS_WHCM 0x08
#define USB_CDC_SUBCLASS_DMM 0x09
#define USB_CDC_SUBCLASS_MDLM 0x0a
#define USB_CDC_SUBCLASS_OBEX 0x0b
#define USB_CDC_SUBCLASS_EEM 0x0c
#define USB_CDC_SUBCLASS_NCM 0x0d
#define USB_CDC_SUBCLASS_MBIM 0x0e
#define USB_CDC_PROTO_NONE 0
#define USB_CDC_ACM_PROTO_AT_V25TER 1
#define USB_CDC_ACM_PROTO_AT_PCCA101 2
#define USB_CDC_ACM_PROTO_AT_PCCA101_WAKE 3
#define USB_CDC_ACM_PROTO_AT_GSM 4
#define USB_CDC_ACM_PROTO_AT_3G 5
#define USB_CDC_ACM_PROTO_AT_CDMA 6
#define USB_CDC_ACM_PROTO_VENDOR 0xff
#define USB_CDC_PROTO_EEM 7
#define USB_CDC_NCM_PROTO_NTB 1
#define USB_CDC_MBIM_PROTO_NTB 2
/*-------------------------------------------------------------------------*/
/*
* Class-Specific descriptors ... there are a couple dozen of them
*/
#define USB_CDC_HEADER_TYPE 0x00 /* header_desc */
#define USB_CDC_CALL_MANAGEMENT_TYPE 0x01 /* call_mgmt_descriptor */
#define USB_CDC_ACM_TYPE 0x02 /* acm_descriptor */
#define USB_CDC_UNION_TYPE 0x06 /* union_desc */
#define USB_CDC_COUNTRY_TYPE 0x07
#define USB_CDC_NETWORK_TERMINAL_TYPE 0x0a /* network_terminal_desc */
#define USB_CDC_ETHERNET_TYPE 0x0f /* ether_desc */
#define USB_CDC_WHCM_TYPE 0x11
#define USB_CDC_MDLM_TYPE 0x12 /* mdlm_desc */
#define USB_CDC_MDLM_DETAIL_TYPE 0x13 /* mdlm_detail_desc */
#define USB_CDC_DMM_TYPE 0x14
#define USB_CDC_OBEX_TYPE 0x15
#define USB_CDC_NCM_TYPE 0x1a
#define USB_CDC_MBIM_TYPE 0x1b
#define USB_CDC_MBIM_EXTENDED_TYPE 0x1c
/* "Header Functional Descriptor" from CDC spec 5.2.3.1 */
struct usb_cdc_header_desc {
__u8 bLength;
__u8 bDescriptorType;
__u8 bDescriptorSubType;
__le16 bcdCDC;
} __attribute__ ((packed));
/* "Call Management Descriptor" from CDC spec 5.2.3.2 */
struct usb_cdc_call_mgmt_descriptor {
__u8 bLength;
__u8 bDescriptorType;
__u8 bDescriptorSubType;
__u8 bmCapabilities;
#define USB_CDC_CALL_MGMT_CAP_CALL_MGMT 0x01
#define USB_CDC_CALL_MGMT_CAP_DATA_INTF 0x02
__u8 bDataInterface;
} __attribute__ ((packed));
/* "Abstract Control Management Descriptor" from CDC spec 5.2.3.3 */
struct usb_cdc_acm_descriptor {
__u8 bLength;
__u8 bDescriptorType;
__u8 bDescriptorSubType;
__u8 bmCapabilities;
} __attribute__ ((packed));
/* capabilities from 5.2.3.3 */
#define USB_CDC_COMM_FEATURE 0x01
#define USB_CDC_CAP_LINE 0x02
#define USB_CDC_CAP_BRK 0x04
#define USB_CDC_CAP_NOTIFY 0x08
/* "Union Functional Descriptor" from CDC spec 5.2.3.8 */
struct usb_cdc_union_desc {
__u8 bLength;
__u8 bDescriptorType;
__u8 bDescriptorSubType;
__u8 bMasterInterface0;
__u8 bSlaveInterface0;
/* ... and there could be other slave interfaces */
} __attribute__ ((packed));
/* "Country Selection Functional Descriptor" from CDC spec 5.2.3.9 */
struct usb_cdc_country_functional_desc {
__u8 bLength;
__u8 bDescriptorType;
__u8 bDescriptorSubType;
__u8 iCountryCodeRelDate;
__le16 wCountyCode0;
/* ... and there can be a lot of country codes */
} __attribute__ ((packed));
/* "Network Channel Terminal Functional Descriptor" from CDC spec 5.2.3.11 */
struct usb_cdc_network_terminal_desc {
__u8 bLength;
__u8 bDescriptorType;
__u8 bDescriptorSubType;
__u8 bEntityId;
__u8 iName;
__u8 bChannelIndex;
__u8 bPhysicalInterface;
} __attribute__ ((packed));
/* "Ethernet Networking Functional Descriptor" from CDC spec 5.2.3.16 */
struct usb_cdc_ether_desc {
__u8 bLength;
__u8 bDescriptorType;
__u8 bDescriptorSubType;
__u8 iMACAddress;
__le32 bmEthernetStatistics;
__le16 wMaxSegmentSize;
__le16 wNumberMCFilters;
__u8 bNumberPowerFilters;
} __attribute__ ((packed));
/* "Telephone Control Model Functional Descriptor" from CDC WMC spec 6.3..3 */
struct usb_cdc_dmm_desc {
__u8 bFunctionLength;
__u8 bDescriptorType;
__u8 bDescriptorSubtype;
__u16 bcdVersion;
__le16 wMaxCommand;
} __attribute__ ((packed));
/* "MDLM Functional Descriptor" from CDC WMC spec 6.7.2.3 */
struct usb_cdc_mdlm_desc {
__u8 bLength;
__u8 bDescriptorType;
__u8 bDescriptorSubType;
__le16 bcdVersion;
__u8 bGUID[16];
} __attribute__ ((packed));
/* "MDLM Detail Functional Descriptor" from CDC WMC spec 6.7.2.4 */
struct usb_cdc_mdlm_detail_desc {
__u8 bLength;
__u8 bDescriptorType;
__u8 bDescriptorSubType;
/* type is associated with mdlm_desc.bGUID */
__u8 bGuidDescriptorType;
__u8 bDetailData[0];
} __attribute__ ((packed));
/* "OBEX Control Model Functional Descriptor" */
struct usb_cdc_obex_desc {
__u8 bLength;
__u8 bDescriptorType;
__u8 bDescriptorSubType;
__le16 bcdVersion;
} __attribute__ ((packed));
/* "NCM Control Model Functional Descriptor" */
struct usb_cdc_ncm_desc {
__u8 bLength;
__u8 bDescriptorType;
__u8 bDescriptorSubType;
__le16 bcdNcmVersion;
__u8 bmNetworkCapabilities;
} __attribute__ ((packed));
/* "MBIM Control Model Functional Descriptor" */
struct usb_cdc_mbim_desc {
__u8 bLength;
__u8 bDescriptorType;
__u8 bDescriptorSubType;
__le16 bcdMBIMVersion;
__le16 wMaxControlMessage;
__u8 bNumberFilters;
__u8 bMaxFilterSize;
__le16 wMaxSegmentSize;
__u8 bmNetworkCapabilities;
} __attribute__ ((packed));
/* "MBIM Extended Functional Descriptor" from CDC MBIM spec 1.0 errata-1 */
struct usb_cdc_mbim_extended_desc {
__u8 bLength;
__u8 bDescriptorType;
__u8 bDescriptorSubType;
__le16 bcdMBIMExtendedVersion;
__u8 bMaxOutstandingCommandMessages;
__le16 wMTU;
} __attribute__ ((packed));
/*-------------------------------------------------------------------------*/
/*
* Class-Specific Control Requests (6.2)
*
* section 3.6.2.1 table 4 has the ACM profile, for modems.
* section 3.8.2 table 10 has the ethernet profile.
*
* Microsoft's RNDIS stack for Ethernet is a vendor-specific CDC ACM variant,
* heavily dependent on the encapsulated (proprietary) command mechanism.
*/
#define USB_CDC_SEND_ENCAPSULATED_COMMAND 0x00
#define USB_CDC_GET_ENCAPSULATED_RESPONSE 0x01
#define USB_CDC_REQ_SET_LINE_CODING 0x20
#define USB_CDC_REQ_GET_LINE_CODING 0x21
#define USB_CDC_REQ_SET_CONTROL_LINE_STATE 0x22
#define USB_CDC_REQ_SEND_BREAK 0x23
#define USB_CDC_SET_ETHERNET_MULTICAST_FILTERS 0x40
#define USB_CDC_SET_ETHERNET_PM_PATTERN_FILTER 0x41
#define USB_CDC_GET_ETHERNET_PM_PATTERN_FILTER 0x42
#define USB_CDC_SET_ETHERNET_PACKET_FILTER 0x43
#define USB_CDC_GET_ETHERNET_STATISTIC 0x44
#define USB_CDC_GET_NTB_PARAMETERS 0x80
#define USB_CDC_GET_NET_ADDRESS 0x81
#define USB_CDC_SET_NET_ADDRESS 0x82
#define USB_CDC_GET_NTB_FORMAT 0x83
#define USB_CDC_SET_NTB_FORMAT 0x84
#define USB_CDC_GET_NTB_INPUT_SIZE 0x85
#define USB_CDC_SET_NTB_INPUT_SIZE 0x86
#define USB_CDC_GET_MAX_DATAGRAM_SIZE 0x87
#define USB_CDC_SET_MAX_DATAGRAM_SIZE 0x88
#define USB_CDC_GET_CRC_MODE 0x89
#define USB_CDC_SET_CRC_MODE 0x8a
/* Line Coding Structure from CDC spec 6.2.13 */
struct usb_cdc_line_coding {
__le32 dwDTERate;
__u8 bCharFormat;
#define USB_CDC_1_STOP_BITS 0
#define USB_CDC_1_5_STOP_BITS 1
#define USB_CDC_2_STOP_BITS 2
__u8 bParityType;
#define USB_CDC_NO_PARITY 0
#define USB_CDC_ODD_PARITY 1
#define USB_CDC_EVEN_PARITY 2
#define USB_CDC_MARK_PARITY 3
#define USB_CDC_SPACE_PARITY 4
__u8 bDataBits;
} __attribute__ ((packed));
/* table 62; bits in multicast filter */
#define USB_CDC_PACKET_TYPE_PROMISCUOUS (1 << 0)
#define USB_CDC_PACKET_TYPE_ALL_MULTICAST (1 << 1) /* no filter */
#define USB_CDC_PACKET_TYPE_DIRECTED (1 << 2)
#define USB_CDC_PACKET_TYPE_BROADCAST (1 << 3)
#define USB_CDC_PACKET_TYPE_MULTICAST (1 << 4) /* filtered */
/*-------------------------------------------------------------------------*/
/*
* Class-Specific Notifications (6.3) sent by interrupt transfers
*
* section 3.8.2 table 11 of the CDC spec lists Ethernet notifications
* section 3.6.2.1 table 5 specifies ACM notifications, accepted by RNDIS
* RNDIS also defines its own bit-incompatible notifications
*/
#define USB_CDC_NOTIFY_NETWORK_CONNECTION 0x00
#define USB_CDC_NOTIFY_RESPONSE_AVAILABLE 0x01
#define USB_CDC_NOTIFY_SERIAL_STATE 0x20
#define USB_CDC_NOTIFY_SPEED_CHANGE 0x2a
struct usb_cdc_notification {
__u8 bmRequestType;
__u8 bNotificationType;
__le16 wValue;
__le16 wIndex;
__le16 wLength;
} __attribute__ ((packed));
struct usb_cdc_speed_change {
__le32 DLBitRRate; /* contains the downlink bit rate (IN pipe) */
__le32 ULBitRate; /* contains the uplink bit rate (OUT pipe) */
} __attribute__ ((packed));
/*-------------------------------------------------------------------------*/
/*
* Class Specific structures and constants
*
* CDC NCM NTB parameters structure, CDC NCM subclass 6.2.1
*
*/
struct usb_cdc_ncm_ntb_parameters {
__le16 wLength;
__le16 bmNtbFormatsSupported;
__le32 dwNtbInMaxSize;
__le16 wNdpInDivisor;
__le16 wNdpInPayloadRemainder;
__le16 wNdpInAlignment;
__le16 wPadding1;
__le32 dwNtbOutMaxSize;
__le16 wNdpOutDivisor;
__le16 wNdpOutPayloadRemainder;
__le16 wNdpOutAlignment;
__le16 wNtbOutMaxDatagrams;
} __attribute__ ((packed));
/*
* CDC NCM transfer headers, CDC NCM subclass 3.2
*/
#define USB_CDC_NCM_NTH16_SIGN 0x484D434E /* NCMH */
#define USB_CDC_NCM_NTH32_SIGN 0x686D636E /* ncmh */
struct usb_cdc_ncm_nth16 {
__le32 dwSignature;
__le16 wHeaderLength;
__le16 wSequence;
__le16 wBlockLength;
__le16 wNdpIndex;
} __attribute__ ((packed));
struct usb_cdc_ncm_nth32 {
__le32 dwSignature;
__le16 wHeaderLength;
__le16 wSequence;
__le32 dwBlockLength;
__le32 dwNdpIndex;
} __attribute__ ((packed));
/*
* CDC NCM datagram pointers, CDC NCM subclass 3.3
*/
#define USB_CDC_NCM_NDP16_CRC_SIGN 0x314D434E /* NCM1 */
#define USB_CDC_NCM_NDP16_NOCRC_SIGN 0x304D434E /* NCM0 */
#define USB_CDC_NCM_NDP32_CRC_SIGN 0x316D636E /* ncm1 */
#define USB_CDC_NCM_NDP32_NOCRC_SIGN 0x306D636E /* ncm0 */
#define USB_CDC_MBIM_NDP16_IPS_SIGN 0x00535049 /* IPS<sessionID> : IPS0 for now */
#define USB_CDC_MBIM_NDP32_IPS_SIGN 0x00737069 /* ips<sessionID> : ips0 for now */
#define USB_CDC_MBIM_NDP16_DSS_SIGN 0x00535344 /* DSS<sessionID> */
#define USB_CDC_MBIM_NDP32_DSS_SIGN 0x00737364 /* dss<sessionID> */
/* 16-bit NCM Datagram Pointer Entry */
struct usb_cdc_ncm_dpe16 {
__le16 wDatagramIndex;
__le16 wDatagramLength;
} __attribute__((__packed__));
/* 16-bit NCM Datagram Pointer Table */
struct usb_cdc_ncm_ndp16 {
__le32 dwSignature;
__le16 wLength;
__le16 wNextNdpIndex;
struct usb_cdc_ncm_dpe16 dpe16[0];
} __attribute__ ((packed));
/* 32-bit NCM Datagram Pointer Entry */
struct usb_cdc_ncm_dpe32 {
__le32 dwDatagramIndex;
__le32 dwDatagramLength;
} __attribute__((__packed__));
/* 32-bit NCM Datagram Pointer Table */
struct usb_cdc_ncm_ndp32 {
__le32 dwSignature;
__le16 wLength;
__le16 wReserved6;
__le32 dwNextNdpIndex;
__le32 dwReserved12;
struct usb_cdc_ncm_dpe32 dpe32[0];
} __attribute__ ((packed));
/* CDC NCM subclass 3.2.1 and 3.2.2 */
#define USB_CDC_NCM_NDP16_INDEX_MIN 0x000C
#define USB_CDC_NCM_NDP32_INDEX_MIN 0x0010
/* CDC NCM subclass 3.3.3 Datagram Formatting */
#define USB_CDC_NCM_DATAGRAM_FORMAT_CRC 0x30
#define USB_CDC_NCM_DATAGRAM_FORMAT_NOCRC 0X31
/* CDC NCM subclass 4.2 NCM Communications Interface Protocol Code */
#define USB_CDC_NCM_PROTO_CODE_NO_ENCAP_COMMANDS 0x00
#define USB_CDC_NCM_PROTO_CODE_EXTERN_PROTO 0xFE
/* CDC NCM subclass 5.2.1 NCM Functional Descriptor, bmNetworkCapabilities */
#define USB_CDC_NCM_NCAP_ETH_FILTER (1 << 0)
#define USB_CDC_NCM_NCAP_NET_ADDRESS (1 << 1)
#define USB_CDC_NCM_NCAP_ENCAP_COMMAND (1 << 2)
#define USB_CDC_NCM_NCAP_MAX_DATAGRAM_SIZE (1 << 3)
#define USB_CDC_NCM_NCAP_CRC_MODE (1 << 4)
#define USB_CDC_NCM_NCAP_NTB_INPUT_SIZE (1 << 5)
/* CDC NCM subclass Table 6-3: NTB Parameter Structure */
#define USB_CDC_NCM_NTB16_SUPPORTED (1 << 0)
#define USB_CDC_NCM_NTB32_SUPPORTED (1 << 1)
/* CDC NCM subclass Table 6-3: NTB Parameter Structure */
#define USB_CDC_NCM_NDP_ALIGN_MIN_SIZE 0x04
#define USB_CDC_NCM_NTB_MAX_LENGTH 0x1C
/* CDC NCM subclass 6.2.5 SetNtbFormat */
#define USB_CDC_NCM_NTB16_FORMAT 0x00
#define USB_CDC_NCM_NTB32_FORMAT 0x01
/* CDC NCM subclass 6.2.7 SetNtbInputSize */
#define USB_CDC_NCM_NTB_MIN_IN_SIZE 2048
#define USB_CDC_NCM_NTB_MIN_OUT_SIZE 2048
/* NTB Input Size Structure */
struct usb_cdc_ncm_ndp_input_size {
__le32 dwNtbInMaxSize;
__le16 wNtbInMaxDatagrams;
__le16 wReserved;
} __attribute__ ((packed));
/* CDC NCM subclass 6.2.11 SetCrcMode */
#define USB_CDC_NCM_CRC_NOT_APPENDED 0x00
#define USB_CDC_NCM_CRC_APPENDED 0x01
#endif /* __UAPI_LINUX_USB_CDC_H */
| null | null | null | null | 116,996 |
12,264 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 12,264 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2016 The Chromium 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 COMPONENTS_CERTIFICATE_TRANSPARENCY_PREF_NAMES_H_
#define COMPONENTS_CERTIFICATE_TRANSPARENCY_PREF_NAMES_H_
class PrefRegistrySimple;
namespace certificate_transparency {
namespace prefs {
// Registers the preferences related to Certificate Transparency policy
// in the given pref registry.
void RegisterPrefs(PrefRegistrySimple* registry);
// The set of hosts (as URLBlacklist-syntax filters) for which Certificate
// Transparency is required to be present.
extern const char kCTRequiredHosts[];
// The set of hosts (as URLBlacklist-syntax filters) for which Certificate
// Transparency information is allowed to be absent, even if it would
// otherwise be required (e.g. as part of security policy).
extern const char kCTExcludedHosts[];
// The set of subjectPublicKeyInfo hashes in the form of
// <hash-name>"/"<base64-hash-value>. If a certificate matches this SPKI, then
// Certificate Transparency information is allowed to be absent if one of the
// following conditions are met:
// 1) The matching certificate is a CA certificate (basicConstraints CA:TRUE)
// that has a nameConstraints extension with a permittedSubtrees that
// contains one or more directoryName entries, the directoryName has
// one or more organizationName attributes, and the leaf certificate also
// contains one or more organizationName attributes in the Subject.
// 2) The matching certificate contains one or more organizationName
// attributes in the Subject, and those attributes are identical in
// ordering, number of values, and byte-for-byte equality of values.
extern const char kCTExcludedSPKIs[];
// The set of subjectPublicKeyInfo hashes in the form of
// <hash-name>"/"<base64-hash-value>. If a certificate matches this SPKI, then
// Certificate Transparency information is allowed to be absent if:
// 1) The SPKI listed is a known as a publicly trusted root
// (see //net/data/ssl/root_stores)
// 2) The SPKI listed is not actively trusted in the current version of the
// ChromiumOS or Android root stores.
// (see '"legacy": true' in root_stores.json)
extern const char kCTExcludedLegacySPKIs[];
} // namespace prefs
} // namespace certificate_transparency
#endif // COMPONENTS_CERTIFICATE_TRANSPARENCY_PREF_NAMES_H_
| null | null | null | null | 9,127 |
24,005 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 24,005 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright (c) 2013 The Chromium 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 CONTENT_BROWSER_MEDIA_MIDI_HOST_H_
#define CONTENT_BROWSER_MEDIA_MIDI_HOST_H_
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include <vector>
#include "base/gtest_prod_util.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/synchronization/lock.h"
#include "content/common/content_export.h"
#include "content/public/browser/browser_message_filter.h"
#include "content/public/browser/browser_thread.h"
#include "media/midi/midi_manager.h"
#include "media/midi/midi_port_info.h"
#include "media/midi/midi_service.mojom.h"
namespace midi {
class MidiService;
class MidiMessageQueue;
} // namespace midi
namespace content {
class CONTENT_EXPORT MidiHost : public BrowserMessageFilter,
public midi::MidiManagerClient {
public:
// Called from UI thread from the owner of this object.
MidiHost(int renderer_process_id, midi::MidiService* midi_service);
// BrowserMessageFilter implementation.
void OnChannelClosing() override;
void OnDestruct() const override;
bool OnMessageReceived(const IPC::Message& message) override;
// MidiManagerClient implementation.
void CompleteStartSession(midi::mojom::Result result) override;
void AddInputPort(const midi::MidiPortInfo& info) override;
void AddOutputPort(const midi::MidiPortInfo& info) override;
void SetInputPortState(uint32_t port, midi::mojom::PortState state) override;
void SetOutputPortState(uint32_t port, midi::mojom::PortState state) override;
void ReceiveMidiData(uint32_t port,
const uint8_t* data,
size_t length,
base::TimeTicks timestamp) override;
void AccumulateMidiBytesSent(size_t n) override;
void Detach() override;
// Start session to access MIDI hardware.
void OnStartSession();
// Data to be sent to a MIDI output port.
void OnSendData(uint32_t port,
const std::vector<uint8_t>& data,
base::TimeTicks timestamp);
void OnEndSession();
protected:
~MidiHost() override;
private:
friend class base::DeleteHelper<MidiHost>;
friend class BrowserThread;
int renderer_process_id_;
// Represents if the renderer has a permission to send/receive MIDI SysEX
// messages.
bool has_sys_ex_permission_;
// Represents if a session is requested to start.
bool is_session_requested_;
// |midi_service_| manages a MidiManager instance that talks to
// platform-specific MIDI APIs. It can be nullptr after detached.
midi::MidiService* midi_service_;
// Buffers where data sent from each MIDI input port is stored.
std::vector<std::unique_ptr<midi::MidiMessageQueue>>
received_messages_queues_;
// Protects access to |received_messages_queues_|;
base::Lock messages_queues_lock_;
// The number of bytes sent to the platform-specific MIDI sending
// system, but not yet completed.
size_t sent_bytes_in_flight_;
// The number of bytes successfully sent since the last time
// we've acknowledged back to the renderer.
size_t bytes_sent_since_last_acknowledgement_;
// Protects access to |sent_bytes_in_flight_|.
base::Lock in_flight_lock_;
// How many output port exists.
uint32_t output_port_count_;
// Protects access to |output_port_count_|.
base::Lock output_port_count_lock_;
DISALLOW_COPY_AND_ASSIGN(MidiHost);
};
} // namespace content
#endif // CONTENT_BROWSER_MEDIA_MIDI_HOST_H_
| null | null | null | null | 20,868 |
25,345 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 25,345 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2014 The Chromium 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 "extensions/browser/extension_system_provider.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
namespace extensions {
ExtensionSystemProvider::ExtensionSystemProvider(
const char* name,
BrowserContextDependencyManager* manager)
: BrowserContextKeyedServiceFactory(name, manager) {}
ExtensionSystemProvider::~ExtensionSystemProvider() {}
} // namespace extensions
| null | null | null | null | 22,208 |
1,068 | 3,4,5,6,7,8,9,10,11,12 | train_val | b15c87071f906301bccc824ce013966ca93998c7 | 1,068 | Chrome | 1 | https://github.com/chromium/chromium | 2012-10-18 20:34:21+00:00 | void WorkerProcessLauncher::Core::OnChannelConnected(int32 peer_pid) {
DCHECK(caller_task_runner_->BelongsToCurrentThread());
// |peer_pid| is send by the client and cannot be trusted.
// GetNamedPipeClientProcessId() is not available on XP. The pipe's security
// descriptor is the only protection we currently have against malicious
// clients.
// If we'd like to be able to launch low-privileged workers and let them
// connect back, the pipe handle should be passed to the worker instead of
// the pipe name.
if (ipc_enabled_)
worker_delegate_->OnChannelConnected();
}
| CVE-2012-5156 | CWE-399 | https://github.com/chromium/chromium/commit/b15c87071f906301bccc824ce013966ca93998c7 | Medium | 1,068 |
32,767 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 32,767 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | /*
* Copyright (C) 2004, 2005, 2007 Nikolas Zimmermann <zimmermann@kde.org>
* Copyright (C) 2004, 2005, 2006 Rob Buis <buis@kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_FE_MERGE_ELEMENT_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_FE_MERGE_ELEMENT_H_
#include "third_party/blink/renderer/core/svg/svg_filter_primitive_standard_attributes.h"
namespace blink {
class SVGFEMergeElement final : public SVGFilterPrimitiveStandardAttributes {
DEFINE_WRAPPERTYPEINFO();
public:
DECLARE_NODE_FACTORY(SVGFEMergeElement);
private:
explicit SVGFEMergeElement(Document&);
FilterEffect* Build(SVGFilterBuilder*, Filter*) override;
bool TaintsOrigin(bool inputs_taint_origin) const override;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_FE_MERGE_ELEMENT_H_
| null | null | null | null | 29,630 |
18,269 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 18,269 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2018 The Chromium 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 COMPONENTS_DOWNLOAD_PUBLIC_COMMON_DOWNLOAD_INTERRUPT_REASONS_H_
#define COMPONENTS_DOWNLOAD_PUBLIC_COMMON_DOWNLOAD_INTERRUPT_REASONS_H_
#include <string>
#include "components/download/public/common/download_export.h"
namespace download {
enum DownloadInterruptReason {
DOWNLOAD_INTERRUPT_REASON_NONE = 0,
#define INTERRUPT_REASON(name, value) DOWNLOAD_INTERRUPT_REASON_##name = value,
#include "components/download/public/common/download_interrupt_reason_values.h"
#undef INTERRUPT_REASON
};
std::string COMPONENTS_DOWNLOAD_EXPORT
DownloadInterruptReasonToString(DownloadInterruptReason error);
} // namespace download
#endif // COMPONENTS_DOWNLOAD_PUBLIC_COMMON_DOWNLOAD_INTERRUPT_REASONS_H_
| null | null | null | null | 15,132 |
57,151 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 57,151 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2014 The Chromium 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 CHROME_BROWSER_CHROMEOS_APP_MODE_KIOSK_EXTERNAL_UPDATER_H_
#define CHROME_BROWSER_CHROMEOS_APP_MODE_KIOSK_EXTERNAL_UPDATER_H_
#include <map>
#include <memory>
#include <string>
#include <utility>
#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/sequenced_task_runner.h"
#include "chrome/browser/chromeos/app_mode/kiosk_external_update_validator.h"
#include "chromeos/disks/disk_mount_manager.h"
namespace chromeos {
class KioskExternalUpdateNotification;
// Observes the disk mount/unmount events, scans the usb stick for external
// kiosk app updates, validates the external crx, and updates the cache.
class KioskExternalUpdater : public disks::DiskMountManager::Observer,
public KioskExternalUpdateValidatorDelegate {
public:
enum ExternalUpdateErrorCode {
ERROR_NONE,
ERROR_NO_MANIFEST,
ERROR_INVALID_MANIFEST,
};
KioskExternalUpdater(
const scoped_refptr<base::SequencedTaskRunner>& backend_task_runner,
const base::FilePath& crx_cache_dir,
const base::FilePath& crx_unpack_dir);
~KioskExternalUpdater() override;
private:
enum ExternalUpdateStatus {
PENDING,
SUCCESS,
FAILED,
};
struct ExternalUpdate {
ExternalUpdate();
ExternalUpdate(const ExternalUpdate& other);
~ExternalUpdate();
std::string app_name;
extensions::CRXFileInfo external_crx;
ExternalUpdateStatus update_status;
base::string16 error;
};
// disks::DiskMountManager::Observer overrides.
void OnAutoMountableDiskEvent(
disks::DiskMountManager::DiskEvent event,
const disks::DiskMountManager::Disk& disk) override;
void OnBootDeviceDiskEvent(
disks::DiskMountManager::DiskEvent event,
const disks::DiskMountManager::Disk& disk) override;
void OnDeviceEvent(disks::DiskMountManager::DeviceEvent event,
const std::string& device_path) override;
void OnMountEvent(
disks::DiskMountManager::MountEvent event,
MountError error_code,
const disks::DiskMountManager::MountPointInfo& mount_info) override;
void OnFormatEvent(disks::DiskMountManager::FormatEvent event,
FormatError error_code,
const std::string& device_path) override;
void OnRenameEvent(disks::DiskMountManager::RenameEvent event,
RenameError error_code,
const std::string& device_path) override;
// KioskExternalUpdateValidatorDelegate overrides:
void OnExternalUpdateUnpackSuccess(const std::string& app_id,
const std::string& version,
const std::string& min_browser_version,
const base::FilePath& temp_dir) override;
void OnExternalUpdateUnpackFailure(const std::string& app_id) override;
// Processes the parsed external update manifest, check the
// ExternalUpdateErrorCode in |result| for any manifest parsing error.
using ParseManifestResult = std::pair<std::unique_ptr<base::DictionaryValue>,
ExternalUpdateErrorCode>;
void ProcessParsedManifest(const base::FilePath& external_update_dir,
const ParseManifestResult& result);
// Returns true if |external_update_| is interrupted before the updating
// completes.
bool CheckExternalUpdateInterrupted();
// Validates the external updates.
void ValidateExternalUpdates();
// Returns true if there are any external updates pending.
bool IsExternalUpdatePending() const;
// Returns true if all external updates specified in the manifest are
// completed successfully.
bool IsAllExternalUpdatesSucceeded() const;
// Returns true if the app with |app_id| should be updated to
// |external_extension|.
bool ShouldDoExternalUpdate(const std::string& app_id,
const std::string& version,
const std::string& min_browser_version);
// Installs the validated extension into cache.
// |crx_copied| indicates whether the |crx_file| is copied successfully.
void PutValidatedExtension(const std::string& app_id,
const base::FilePath& crx_file,
const std::string& version,
bool crx_copied);
// Called upon completion of installing the validated external extension into
// the local cache. |success| is true if the operation succeeded.
void OnPutValidatedExtension(const std::string& app_id, bool success);
void NotifyKioskUpdateProgress(const base::string16& message);
void MaybeValidateNextExternalUpdate();
// Notifies the kiosk update status with UI and KioskAppUpdateService, if
// there is no kiosk external updates pending.
void MayBeNotifyKioskAppUpdate();
void NotifyKioskAppUpdateAvailable();
// Dismisses the UI notification for kiosk updates.
void DismissKioskUpdateNotification();
// Return a detailed message for kiosk updating status.
base::string16 GetUpdateReportMessage() const;
// Task runner for executing file I/O tasks.
const scoped_refptr<base::SequencedTaskRunner> backend_task_runner_;
// The directory where kiosk crx files are cached.
const base::FilePath crx_cache_dir_;
// The directory used by SandBoxedUnpacker for unpack extensions.
const base::FilePath crx_unpack_dir_;
// The path where external crx files resides(usb stick mount path).
base::FilePath external_update_path_;
// map of app_id: ExternalUpdate
using ExternalUpdateMap = std::map<std::string, ExternalUpdate>;
ExternalUpdateMap external_updates_;
std::unique_ptr<KioskExternalUpdateNotification> notification_;
base::WeakPtrFactory<KioskExternalUpdater> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(KioskExternalUpdater);
};
} // namespace chromeos
#endif // CHROME_BROWSER_CHROMEOS_APP_MODE_KIOSK_EXTERNAL_UPDATER_H_
| null | null | null | null | 54,014 |
51,262 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 51,262 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2014 The Chromium 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 "base/macros.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/events/ozone/chromeos/cursor_controller.h"
namespace ui {
namespace {
const gfx::AcceleratedWidget kTestWindow = 1;
} // namespace
class CursorControllerTest : public testing::Test {
public:
CursorControllerTest() {}
~CursorControllerTest() override {}
void TearDown() override {
ui::CursorController::GetInstance()->ClearCursorConfigForWindow(
kTestWindow);
}
DISALLOW_COPY_AND_ASSIGN(CursorControllerTest);
};
TEST_F(CursorControllerTest, UnconfiguredIdentity) {
ui::CursorController* cursor_controller = CursorController::GetInstance();
// Check that unconfigured windows use identity.
gfx::Vector2dF delta(2.f, 3.f);
cursor_controller->ApplyCursorConfigForWindow(kTestWindow, &delta);
EXPECT_FLOAT_EQ(2.f, delta.x());
EXPECT_FLOAT_EQ(3.f, delta.y());
}
TEST_F(CursorControllerTest, ClearedIdentity) {
ui::CursorController* cursor_controller = CursorController::GetInstance();
// Check that configured & cleared windows use identity.
cursor_controller->SetCursorConfigForWindow(
kTestWindow, display::Display::ROTATE_180, 3.2f);
cursor_controller->ClearCursorConfigForWindow(kTestWindow);
gfx::Vector2dF delta(3.f, 5.f);
cursor_controller->ApplyCursorConfigForWindow(kTestWindow, &delta);
EXPECT_FLOAT_EQ(3.f, delta.x());
EXPECT_FLOAT_EQ(5.f, delta.y());
}
TEST_F(CursorControllerTest, RotatedHighDpi) {
ui::CursorController* cursor_controller = CursorController::GetInstance();
// Check that 90deg rotated highdpi window transforms correctly.
cursor_controller->SetCursorConfigForWindow(kTestWindow,
display::Display::ROTATE_90, 2.f);
gfx::Vector2dF delta(3.f, 5.f);
cursor_controller->ApplyCursorConfigForWindow(kTestWindow, &delta);
EXPECT_FLOAT_EQ(-10.f, delta.x());
EXPECT_FLOAT_EQ(6.f, delta.y());
}
} // namespace ui
| null | null | null | null | 48,125 |
13,151 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 178,146 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | #include <asm-generic/kdebug.h>
| null | null | null | null | 86,493 |
7,860 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 7,860 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2017 The Chromium 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 "net/cert/cert_verify_proc_mac.h"
#include <memory>
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/mac/mac_util.h"
#include "base/macros.h"
#include "net/base/net_errors.h"
#include "net/cert/cert_verifier.h"
#include "net/cert/cert_verify_result.h"
#include "net/cert/crl_set.h"
#include "net/cert/test_keychain_search_list_mac.h"
#include "net/cert/test_root_certs.h"
#include "net/cert/x509_certificate.h"
#include "net/cert/x509_util.h"
#include "net/test/cert_test_util.h"
#include "net/test/gtest_util.h"
#include "net/test/test_data_directory.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using net::test::IsError;
using net::test::IsOk;
namespace net {
namespace {
// Test that a CRLSet blocking one of the intermediates supplied by the server
// can be worked around by the chopping workaround for path building. (Once the
// supplied chain is chopped back to just the target, a better path can be
// found out-of-band. Normally that would be by AIA fetching, for the purposes
// of this test the better path is supplied by a test keychain.)
//
// In this test, there are two possible paths to validate a leaf (A):
// 1. A(B) -> B(C) -> C(E) -> E(E)
// 2. A(B) -> B(F) -> F(E) -> E(E)
//
// A(B) -> B(C) -> C(E) is supplied to the verifier.
// B(F) and F(E) are supplied in a test keychain.
// C is blocked by a CRLset.
//
// The verifier should rollback until it just tries A(B) alone, at which point
// it will pull B(F) & F(E) from the keychain and succeed.
TEST(CertVerifyProcMacTest, MacCRLIntermediate) {
if (base::mac::IsAtLeastOS10_12()) {
// TODO(crbug.com/671889): Investigate SecTrustSetKeychains issue on Sierra.
LOG(INFO) << "Skipping test, SecTrustSetKeychains does not work on 10.12";
return;
}
CertificateList path_2_certs;
ASSERT_TRUE(
LoadCertificateFiles({"multi-root-A-by-B.pem", "multi-root-B-by-C.pem",
"multi-root-C-by-E.pem", "multi-root-E-by-E.pem"},
&path_2_certs));
CertificateList path_3_certs;
ASSERT_TRUE(
LoadCertificateFiles({"multi-root-A-by-B.pem", "multi-root-B-by-F.pem",
"multi-root-F-by-E.pem", "multi-root-E-by-E.pem"},
&path_3_certs));
// Add E as trust anchor.
ScopedTestRoot test_root_E(path_3_certs[3].get()); // E-by-E
std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
intermediates.push_back(
x509_util::DupCryptoBuffer(path_2_certs[1]->cert_buffer())); // B-by-C
intermediates.push_back(
x509_util::DupCryptoBuffer(path_2_certs[2]->cert_buffer())); // C-by-E
scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromBuffer(
x509_util::DupCryptoBuffer(path_3_certs[0]->cert_buffer()),
std::move(intermediates));
ASSERT_TRUE(cert);
std::unique_ptr<TestKeychainSearchList> test_keychain_search_list(
TestKeychainSearchList::Create());
ASSERT_TRUE(test_keychain_search_list);
base::FilePath keychain_path(
GetTestCertsDirectory().AppendASCII("multi-root-BFE.keychain"));
// SecKeychainOpen does not fail if the file doesn't exist, so assert it here
// for easier debugging.
ASSERT_TRUE(base::PathExists(keychain_path));
SecKeychainRef keychain;
OSStatus status =
SecKeychainOpen(keychain_path.MaybeAsASCII().c_str(), &keychain);
ASSERT_EQ(errSecSuccess, status);
ASSERT_TRUE(keychain);
base::ScopedCFTypeRef<SecKeychainRef> scoped_keychain(keychain);
test_keychain_search_list->AddKeychain(keychain);
scoped_refptr<CRLSet> crl_set;
std::string crl_set_bytes;
// CRL which blocks C by SPKI.
EXPECT_TRUE(base::ReadFileToString(
GetTestCertsDirectory().AppendASCII("multi-root-crlset-C.raw"),
&crl_set_bytes));
ASSERT_TRUE(CRLSet::Parse(crl_set_bytes, &crl_set));
int flags = 0;
CertVerifyResult verify_result;
scoped_refptr<CertVerifyProc> verify_proc = new CertVerifyProcMac;
int error =
verify_proc->Verify(cert.get(), "127.0.0.1", std::string(), flags,
crl_set.get(), CertificateList(), &verify_result);
ASSERT_EQ(OK, error);
ASSERT_EQ(0U, verify_result.cert_status);
ASSERT_TRUE(verify_result.verified_cert.get());
const auto& verified_intermediates =
verify_result.verified_cert->intermediate_buffers();
ASSERT_EQ(3U, verified_intermediates.size());
scoped_refptr<X509Certificate> intermediate =
X509Certificate::CreateFromBuffer(
x509_util::DupCryptoBuffer(verified_intermediates[1].get()), {});
ASSERT_TRUE(intermediate);
scoped_refptr<X509Certificate> expected_intermediate = path_3_certs[2];
EXPECT_TRUE(expected_intermediate->Equals(intermediate.get()))
<< "Expected: " << expected_intermediate->subject().common_name
<< " issued by " << expected_intermediate->issuer().common_name
<< "; Got: " << intermediate->subject().common_name << " issued by "
<< intermediate->issuer().common_name;
}
// Test that if a keychain is present which trusts a less-desirable root (ex,
// one using SHA1), that the keychain reordering hack will cause the better
// root in the System Roots to be used instead.
TEST(CertVerifyProcMacTest, MacKeychainReordering) {
// Note: target cert expires Dec 30 23:59:59 2019 GMT
scoped_refptr<X509Certificate> cert = CreateCertificateChainFromFile(
GetTestCertsDirectory(), "gms.hongleong.com.my-verisign-chain.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_TRUE(cert);
// Create a test keychain search list that will Always Trust the SHA1
// cross-signed VeriSign Class 3 Public Primary Certification Authority - G5
std::unique_ptr<TestKeychainSearchList> test_keychain_search_list(
TestKeychainSearchList::Create());
ASSERT_TRUE(test_keychain_search_list);
base::FilePath keychain_path(GetTestCertsDirectory().AppendASCII(
"verisign_class3_g5_crosssigned-trusted.keychain"));
// SecKeychainOpen does not fail if the file doesn't exist, so assert it here
// for easier debugging.
ASSERT_TRUE(base::PathExists(keychain_path));
SecKeychainRef keychain;
OSStatus status =
SecKeychainOpen(keychain_path.MaybeAsASCII().c_str(), &keychain);
ASSERT_EQ(errSecSuccess, status);
ASSERT_TRUE(keychain);
base::ScopedCFTypeRef<SecKeychainRef> scoped_keychain(keychain);
test_keychain_search_list->AddKeychain(keychain);
int flags = 0;
CertVerifyResult verify_result;
scoped_refptr<CertVerifyProc> verify_proc = new CertVerifyProcMac;
int error = verify_proc->Verify(cert.get(), "gms.hongleong.com.my",
std::string(), flags, nullptr /* crl_set */,
CertificateList(), &verify_result);
ASSERT_EQ(OK, error);
EXPECT_FALSE(verify_result.has_sha1);
ASSERT_TRUE(verify_result.verified_cert.get());
const auto& verified_intermediates =
verify_result.verified_cert->intermediate_buffers();
ASSERT_EQ(2U, verified_intermediates.size());
}
// Test that the system root certificate keychain is in the expected location
// and can be opened. Other tests would fail if this was not true, but this
// test makes the reason for the failure obvious.
TEST(CertVerifyProcMacTest, MacSystemRootCertificateKeychainLocation) {
const char* root_keychain_path =
"/System/Library/Keychains/SystemRootCertificates.keychain";
ASSERT_TRUE(base::PathExists(base::FilePath(root_keychain_path)));
SecKeychainRef keychain;
OSStatus status = SecKeychainOpen(root_keychain_path, &keychain);
ASSERT_EQ(errSecSuccess, status);
CFRelease(keychain);
}
// Test that CertVerifyProcMac reacts appropriately when Apple's certificate
// verifier rejects a certificate with a fatal error. This is a regression
// test for https://crbug.com/472291.
// (Since 10.12, this causes a recoverable error instead of a fatal one.)
// TODO(mattm): Try to find a different way to cause a fatal error that works
// on 10.12.
TEST(CertVerifyProcMacTest, LargeKey) {
// Load root_ca_cert.pem into the test root store.
ScopedTestRoot test_root(
ImportCertFromFile(GetTestCertsDirectory(), "root_ca_cert.pem").get());
scoped_refptr<X509Certificate> cert(
ImportCertFromFile(GetTestCertsDirectory(), "large_key.pem"));
// Apple's verifier rejects this certificate as invalid because the
// RSA key is too large. If a future version of OS X changes this,
// large_key.pem may need to be regenerated with a larger key.
int flags = 0;
CertVerifyResult verify_result;
scoped_refptr<CertVerifyProc> verify_proc = new CertVerifyProcMac;
int error = verify_proc->Verify(cert.get(), "127.0.0.1", std::string(), flags,
NULL, CertificateList(), &verify_result);
EXPECT_THAT(error, IsError(ERR_CERT_INVALID));
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_INVALID);
}
} // namespace
} // namespace net
| null | null | null | null | 4,723 |
29,476 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 29,476 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | /*
** 2017 April 07
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
*/
#if defined(SQLITE_TEST)
#include "sqlite3expert.h"
#include <assert.h>
#include <string.h>
#if defined(INCLUDE_SQLITE_TCL_H)
# include "sqlite_tcl.h"
#else
# include "tcl.h"
# ifndef SQLITE_TCLAPI
# define SQLITE_TCLAPI
# endif
#endif
#ifndef SQLITE_OMIT_VIRTUALTABLE
/*
** Extract an sqlite3* db handle from the object passed as the second
** argument. If successful, set *pDb to point to the db handle and return
** TCL_OK. Otherwise, return TCL_ERROR.
*/
static int dbHandleFromObj(Tcl_Interp *interp, Tcl_Obj *pObj, sqlite3 **pDb){
Tcl_CmdInfo info;
if( 0==Tcl_GetCommandInfo(interp, Tcl_GetString(pObj), &info) ){
Tcl_AppendResult(interp, "no such handle: ", Tcl_GetString(pObj), 0);
return TCL_ERROR;
}
*pDb = *(sqlite3 **)info.objClientData;
return TCL_OK;
}
/*
** Tclcmd: $expert sql SQL
** $expert analyze
** $expert count
** $expert report STMT EREPORT
** $expert destroy
*/
static int SQLITE_TCLAPI testExpertCmd(
void *clientData,
Tcl_Interp *interp,
int objc,
Tcl_Obj *CONST objv[]
){
sqlite3expert *pExpert = (sqlite3expert*)clientData;
struct Subcmd {
const char *zSub;
int nArg;
const char *zMsg;
} aSub[] = {
{ "sql", 1, "TABLE", }, /* 0 */
{ "analyze", 0, "", }, /* 1 */
{ "count", 0, "", }, /* 2 */
{ "report", 2, "STMT EREPORT", }, /* 3 */
{ "destroy", 0, "", }, /* 4 */
{ 0 }
};
int iSub;
int rc = TCL_OK;
char *zErr = 0;
if( objc<2 ){
Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
return TCL_ERROR;
}
rc = Tcl_GetIndexFromObjStruct(interp,
objv[1], aSub, sizeof(aSub[0]), "sub-command", 0, &iSub
);
if( rc!=TCL_OK ) return rc;
if( objc!=2+aSub[iSub].nArg ){
Tcl_WrongNumArgs(interp, 2, objv, aSub[iSub].zMsg);
return TCL_ERROR;
}
switch( iSub ){
case 0: { /* sql */
char *zArg = Tcl_GetString(objv[2]);
rc = sqlite3_expert_sql(pExpert, zArg, &zErr);
break;
}
case 1: { /* analyze */
rc = sqlite3_expert_analyze(pExpert, &zErr);
break;
}
case 2: { /* count */
int n = sqlite3_expert_count(pExpert);
Tcl_SetObjResult(interp, Tcl_NewIntObj(n));
break;
}
case 3: { /* report */
const char *aEnum[] = {
"sql", "indexes", "plan", "candidates", 0
};
int iEnum;
int iStmt;
const char *zReport;
if( Tcl_GetIntFromObj(interp, objv[2], &iStmt)
|| Tcl_GetIndexFromObj(interp, objv[3], aEnum, "report", 0, &iEnum)
){
return TCL_ERROR;
}
assert( EXPERT_REPORT_SQL==1 );
assert( EXPERT_REPORT_INDEXES==2 );
assert( EXPERT_REPORT_PLAN==3 );
assert( EXPERT_REPORT_CANDIDATES==4 );
zReport = sqlite3_expert_report(pExpert, iStmt, 1+iEnum);
Tcl_SetObjResult(interp, Tcl_NewStringObj(zReport, -1));
break;
}
default: /* destroy */
assert( iSub==4 );
Tcl_DeleteCommand(interp, Tcl_GetString(objv[0]));
break;
}
if( rc!=TCL_OK ){
if( zErr ){
Tcl_SetObjResult(interp, Tcl_NewStringObj(zErr, -1));
}else{
extern const char *sqlite3ErrName(int);
Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3ErrName(rc), -1));
}
}
sqlite3_free(zErr);
return rc;
}
static void SQLITE_TCLAPI testExpertDel(void *clientData){
sqlite3expert *pExpert = (sqlite3expert*)clientData;
sqlite3_expert_destroy(pExpert);
}
/*
** sqlite3_expert_new DB
*/
static int SQLITE_TCLAPI test_sqlite3_expert_new(
void * clientData,
Tcl_Interp *interp,
int objc,
Tcl_Obj *CONST objv[]
){
static int iCmd = 0;
sqlite3 *db;
char *zCmd = 0;
char *zErr = 0;
sqlite3expert *pExpert;
int rc = TCL_OK;
if( objc!=2 ){
Tcl_WrongNumArgs(interp, 1, objv, "DB");
return TCL_ERROR;
}
if( dbHandleFromObj(interp, objv[1], &db) ){
return TCL_ERROR;
}
zCmd = sqlite3_mprintf("sqlite3expert%d", ++iCmd);
if( zCmd==0 ){
Tcl_AppendResult(interp, "out of memory", (char*)0);
return TCL_ERROR;
}
pExpert = sqlite3_expert_new(db, &zErr);
if( pExpert==0 ){
Tcl_AppendResult(interp, zErr, (char*)0);
rc = TCL_ERROR;
}else{
void *p = (void*)pExpert;
Tcl_CreateObjCommand(interp, zCmd, testExpertCmd, p, testExpertDel);
Tcl_SetObjResult(interp, Tcl_NewStringObj(zCmd, -1));
}
sqlite3_free(zCmd);
sqlite3_free(zErr);
return rc;
}
#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
int TestExpert_Init(Tcl_Interp *interp){
#ifndef SQLITE_OMIT_VIRTUALTABLE
struct Cmd {
const char *zCmd;
Tcl_ObjCmdProc *xProc;
} aCmd[] = {
{ "sqlite3_expert_new", test_sqlite3_expert_new },
};
int i;
for(i=0; i<sizeof(aCmd)/sizeof(struct Cmd); i++){
struct Cmd *p = &aCmd[i];
Tcl_CreateObjCommand(interp, p->zCmd, p->xProc, 0, 0);
}
#endif
return TCL_OK;
}
#endif
| null | null | null | null | 26,339 |
26,758 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 26,758 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright (c) 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ---
// Unittest for the TCMalloc implementation.
//
// * The test consists of a set of threads.
// * Each thread maintains a set of allocated objects, with
// a bound on the total amount of data in the set.
// * Each allocated object's contents are generated by
// hashing the object pointer, and a generation count
// in the object. This allows us to easily check for
// data corruption.
// * At any given step, the thread can do any of the following:
// a. Allocate an object
// b. Increment an object's generation count and update
// its contents.
// c. Pass the object to another thread
// d. Free an object
// Also, at the end of every step, object(s) are freed to maintain
// the memory upper-bound.
//
// If this test is compiled with -DDEBUGALLOCATION, then we don't
// run some tests that test the inner workings of tcmalloc and
// break on debugallocation: that certain allocations are aligned
// in a certain way (even though no standard requires it), and that
// realloc() tries to minimize copying (which debug allocators don't
// care about).
#include "config_for_unittests.h"
// Complicated ordering requirements. tcmalloc.h defines (indirectly)
// _POSIX_C_SOURCE, which it needs so stdlib.h defines posix_memalign.
// unistd.h, on the other hand, requires _POSIX_C_SOURCE to be unset,
// at least on FreeBSD, in order to define sbrk. The solution
// is to #include unistd.h first. This is safe because unistd.h
// doesn't sub-include stdlib.h, so we'll still get posix_memalign
// when we #include stdlib.h. Blah.
#ifdef HAVE_UNISTD_H
#include <unistd.h> // for testing sbrk hooks
#endif
#include "tcmalloc.h" // must come early, to pick up posix_memalign
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#if defined HAVE_STDINT_H
#include <stdint.h> // for intptr_t
#endif
#include <sys/types.h> // for size_t
#ifdef HAVE_FCNTL_H
#include <fcntl.h> // for open; used with mmap-hook test
#endif
#ifdef HAVE_MMAP
#include <sys/mman.h> // for testing mmap hooks
#endif
#ifdef HAVE_MALLOC_H
#include <malloc.h> // defines pvalloc/etc on cygwin
#endif
#include <assert.h>
#include <vector>
#include <algorithm>
#include <string>
#include <new>
#include "base/logging.h"
#include "base/simple_mutex.h"
#include "gperftools/malloc_hook.h"
#include "gperftools/malloc_extension.h"
#include "gperftools/tcmalloc.h"
#include "thread_cache.h"
#include "tests/testutil.h"
// Windows doesn't define pvalloc and a few other obsolete unix
// functions; nor does it define posix_memalign (which is not obsolete).
#if defined(_WIN32)
# define cfree free // don't bother to try to test these obsolete fns
# define valloc malloc
# define pvalloc malloc
// I'd like to map posix_memalign to _aligned_malloc, but _aligned_malloc
// must be paired with _aligned_free (not normal free), which is too
// invasive a change to how we allocate memory here. So just bail
static bool kOSSupportsMemalign = false;
static inline void* Memalign(size_t align, size_t size) {
//LOG(FATAL) << "memalign not supported on windows";
exit(1);
return NULL;
}
static inline int PosixMemalign(void** ptr, size_t align, size_t size) {
//LOG(FATAL) << "posix_memalign not supported on windows";
exit(1);
return -1;
}
// OS X defines posix_memalign in some OS versions but not others;
// it's confusing enough to check that it's easiest to just not to test.
#elif defined(__APPLE__)
static bool kOSSupportsMemalign = false;
static inline void* Memalign(size_t align, size_t size) {
//LOG(FATAL) << "memalign not supported on OS X";
exit(1);
return NULL;
}
static inline int PosixMemalign(void** ptr, size_t align, size_t size) {
//LOG(FATAL) << "posix_memalign not supported on OS X";
exit(1);
return -1;
}
#else
static bool kOSSupportsMemalign = true;
static inline void* Memalign(size_t align, size_t size) {
return memalign(align, size);
}
static inline int PosixMemalign(void** ptr, size_t align, size_t size) {
return posix_memalign(ptr, align, size);
}
#endif
// On systems (like freebsd) that don't define MAP_ANONYMOUS, use the old
// form of the name instead.
#ifndef MAP_ANONYMOUS
# define MAP_ANONYMOUS MAP_ANON
#endif
#define LOGSTREAM stdout
using std::vector;
using std::string;
DECLARE_double(tcmalloc_release_rate);
DECLARE_int32(max_free_queue_size); // in debugallocation.cc
DECLARE_int64(tcmalloc_sample_parameter);
namespace testing {
static const int FLAGS_numtests = 50000;
static const int FLAGS_log_every_n_tests = 50000; // log exactly once
// Testing parameters
static const int FLAGS_lgmaxsize = 16; // lg() of the max size object to alloc
static const int FLAGS_numthreads = 10; // Number of threads
static const int FLAGS_threadmb = 4; // Max memory size allocated by thread
static const int FLAGS_lg_max_memalign = 18; // lg of max alignment for memalign
static const double FLAGS_memalign_min_fraction = 0; // min expected%
static const double FLAGS_memalign_max_fraction = 0.4; // max expected%
static const double FLAGS_memalign_max_alignment_ratio = 6; // alignment/size
// Weights of different operations
static const int FLAGS_allocweight = 50; // Weight for picking allocation
static const int FLAGS_freeweight = 50; // Weight for picking free
static const int FLAGS_updateweight = 10; // Weight for picking update
static const int FLAGS_passweight = 1; // Weight for passing object
static const int kSizeBits = 8 * sizeof(size_t);
static const size_t kMaxSize = ~static_cast<size_t>(0);
static const size_t kMaxSignedSize = ((size_t(1) << (kSizeBits-1)) - 1);
static const size_t kNotTooBig = 100000;
// We want an allocation that is definitely more than main memory. OS
// X has special logic to discard very big allocs before even passing
// the request along to the user-defined memory allocator; we're not
// interested in testing their logic, so we have to make sure we're
// not *too* big.
static const size_t kTooBig = kMaxSize - 100000;
static int news_handled = 0;
// Global array of threads
class TesterThread;
static TesterThread** threads;
// To help with generating random numbers
class TestHarness {
private:
// Information kept per type
struct Type {
string name;
int type;
int weight;
};
public:
TestHarness(int seed)
: types_(new vector<Type>), total_weight_(0), num_tests_(0) {
srandom(seed);
}
~TestHarness() {
delete types_;
}
// Add operation type with specified weight. When starting a new
// iteration, an operation type is picked with probability
// proportional to its weight.
//
// "type" must be non-negative.
// "weight" must be non-negative.
void AddType(int type, int weight, const char* name);
// Call this to get the type of operation for the next iteration.
// It returns a random operation type from the set of registered
// operations. Returns -1 if tests should finish.
int PickType();
// If n == 0, returns the next pseudo-random number in the range [0 .. 0]
// If n != 0, returns the next pseudo-random number in the range [0 .. n)
int Uniform(int n) {
if (n == 0) {
return random() * 0;
} else {
return random() % n;
}
}
// Pick "base" uniformly from range [0,max_log] and then return
// "base" random bits. The effect is to pick a number in the range
// [0,2^max_log-1] with bias towards smaller numbers.
int Skewed(int max_log) {
const int base = random() % (max_log+1);
return random() % (1 << base);
}
private:
vector<Type>* types_; // Registered types
int total_weight_; // Total weight of all types
int num_tests_; // Num tests run so far
};
void TestHarness::AddType(int type, int weight, const char* name) {
Type t;
t.name = name;
t.type = type;
t.weight = weight;
types_->push_back(t);
total_weight_ += weight;
}
int TestHarness::PickType() {
if (num_tests_ >= FLAGS_numtests) return -1;
num_tests_++;
assert(total_weight_ > 0);
// This is a little skewed if total_weight_ doesn't divide 2^31, but it's close
int v = Uniform(total_weight_);
int i;
for (i = 0; i < types_->size(); i++) {
v -= (*types_)[i].weight;
if (v < 0) {
break;
}
}
assert(i < types_->size());
if ((num_tests_ % FLAGS_log_every_n_tests) == 0) {
fprintf(LOGSTREAM, " Test %d out of %d: %s\n",
num_tests_, FLAGS_numtests, (*types_)[i].name.c_str());
}
return (*types_)[i].type;
}
class AllocatorState : public TestHarness {
public:
explicit AllocatorState(int seed) : TestHarness(seed), memalign_fraction_(0) {
if (kOSSupportsMemalign) {
CHECK_GE(FLAGS_memalign_max_fraction, 0);
CHECK_LE(FLAGS_memalign_max_fraction, 1);
CHECK_GE(FLAGS_memalign_min_fraction, 0);
CHECK_LE(FLAGS_memalign_min_fraction, 1);
double delta = FLAGS_memalign_max_fraction - FLAGS_memalign_min_fraction;
CHECK_GE(delta, 0);
memalign_fraction_ = (Uniform(10000)/10000.0 * delta +
FLAGS_memalign_min_fraction);
//fprintf(LOGSTREAM, "memalign fraction: %f\n", memalign_fraction_);
}
}
virtual ~AllocatorState() {}
// Allocate memory. Randomly choose between malloc() or posix_memalign().
void* alloc(size_t size) {
if (Uniform(100) < memalign_fraction_ * 100) {
// Try a few times to find a reasonable alignment, or fall back on malloc.
for (int i = 0; i < 5; i++) {
size_t alignment = 1 << Uniform(FLAGS_lg_max_memalign);
if (alignment >= sizeof(intptr_t) &&
(size < sizeof(intptr_t) ||
alignment < FLAGS_memalign_max_alignment_ratio * size)) {
void *result = reinterpret_cast<void*>(static_cast<intptr_t>(0x1234));
int err = PosixMemalign(&result, alignment, size);
if (err != 0) {
CHECK_EQ(err, ENOMEM);
}
return err == 0 ? result : NULL;
}
}
}
return malloc(size);
}
private:
double memalign_fraction_;
};
// Info kept per thread
class TesterThread {
private:
// Info kept per allocated object
struct Object {
char* ptr; // Allocated pointer
int size; // Allocated size
int generation; // Generation counter of object contents
};
Mutex lock_; // For passing in another thread's obj
int id_; // My thread id
AllocatorState rnd_; // For generating random numbers
vector<Object> heap_; // This thread's heap
vector<Object> passed_; // Pending objects passed from others
size_t heap_size_; // Current heap size
int locks_ok_; // Number of OK TryLock() ops
int locks_failed_; // Number of failed TryLock() ops
// Type of operations
enum Type { ALLOC, FREE, UPDATE, PASS };
// ACM minimal standard random number generator. (re-entrant.)
class ACMRandom {
int32 seed_;
public:
explicit ACMRandom(int32 seed) { seed_ = seed; }
int32 Next() {
const int32 M = 2147483647L; // 2^31-1
const int32 A = 16807;
// In effect, we are computing seed_ = (seed_ * A) % M, where M = 2^31-1
uint32 lo = A * (int32)(seed_ & 0xFFFF);
uint32 hi = A * (int32)((uint32)seed_ >> 16);
lo += (hi & 0x7FFF) << 16;
if (lo > M) {
lo &= M;
++lo;
}
lo += hi >> 15;
if (lo > M) {
lo &= M;
++lo;
}
return (seed_ = (int32) lo);
}
};
public:
TesterThread(int id)
: id_(id),
rnd_(id+1),
heap_size_(0),
locks_ok_(0),
locks_failed_(0) {
}
virtual ~TesterThread() {
if (FLAGS_verbose)
fprintf(LOGSTREAM, "Thread %2d: locks %6d ok; %6d trylocks failed\n",
id_, locks_ok_, locks_failed_);
if (locks_ok_ + locks_failed_ >= 1000) {
CHECK_LE(locks_failed_, locks_ok_ / 2);
}
}
virtual void Run() {
rnd_.AddType(ALLOC, FLAGS_allocweight, "allocate");
rnd_.AddType(FREE, FLAGS_freeweight, "free");
rnd_.AddType(UPDATE, FLAGS_updateweight, "update");
rnd_.AddType(PASS, FLAGS_passweight, "pass");
while (true) {
AcquirePassedObjects();
switch (rnd_.PickType()) {
case ALLOC: AllocateObject(); break;
case FREE: FreeObject(); break;
case UPDATE: UpdateObject(); break;
case PASS: PassObject(); break;
case -1: goto done;
default: assert(NULL == "Unknown type");
}
ShrinkHeap();
}
done:
DeleteHeap();
}
// Allocate a new object
void AllocateObject() {
Object object;
object.size = rnd_.Skewed(FLAGS_lgmaxsize);
object.ptr = static_cast<char*>(rnd_.alloc(object.size));
CHECK(object.ptr);
object.generation = 0;
FillContents(&object);
heap_.push_back(object);
heap_size_ += object.size;
}
// Mutate a random object
void UpdateObject() {
if (heap_.empty()) return;
const int index = rnd_.Uniform(heap_.size());
CheckContents(heap_[index]);
heap_[index].generation++;
FillContents(&heap_[index]);
}
// Free a random object
void FreeObject() {
if (heap_.empty()) return;
const int index = rnd_.Uniform(heap_.size());
Object object = heap_[index];
CheckContents(object);
free(object.ptr);
heap_size_ -= object.size;
heap_[index] = heap_[heap_.size()-1];
heap_.pop_back();
}
// Delete all objects in the heap
void DeleteHeap() {
while (!heap_.empty()) {
FreeObject();
}
}
// Free objects until our heap is small enough
void ShrinkHeap() {
while (heap_size_ > FLAGS_threadmb << 20) {
assert(!heap_.empty());
FreeObject();
}
}
// Pass a random object to another thread
void PassObject() {
// Pick object to pass
if (heap_.empty()) return;
const int index = rnd_.Uniform(heap_.size());
Object object = heap_[index];
CheckContents(object);
// Pick thread to pass
const int tid = rnd_.Uniform(FLAGS_numthreads);
TesterThread* thread = threads[tid];
if (thread->lock_.TryLock()) {
// Pass the object
locks_ok_++;
thread->passed_.push_back(object);
thread->lock_.Unlock();
heap_size_ -= object.size;
heap_[index] = heap_[heap_.size()-1];
heap_.pop_back();
} else {
locks_failed_++;
}
}
// Grab any objects passed to this thread by another thread
void AcquirePassedObjects() {
// We do not create unnecessary contention by always using
// TryLock(). Plus we unlock immediately after swapping passed
// objects into a local vector.
vector<Object> copy;
{ // Locking scope
if (!lock_.TryLock()) {
locks_failed_++;
return;
}
locks_ok_++;
swap(copy, passed_);
lock_.Unlock();
}
for (int i = 0; i < copy.size(); ++i) {
const Object& object = copy[i];
CheckContents(object);
heap_.push_back(object);
heap_size_ += object.size;
}
}
// Fill object contents according to ptr/generation
void FillContents(Object* object) {
ACMRandom r(reinterpret_cast<intptr_t>(object->ptr) & 0x7fffffff);
for (int i = 0; i < object->generation; ++i) {
r.Next();
}
const char c = static_cast<char>(r.Next());
memset(object->ptr, c, object->size);
}
// Check object contents
void CheckContents(const Object& object) {
ACMRandom r(reinterpret_cast<intptr_t>(object.ptr) & 0x7fffffff);
for (int i = 0; i < object.generation; ++i) {
r.Next();
}
// For large objects, we just check a prefix/suffix
const char expected = static_cast<char>(r.Next());
const int limit1 = object.size < 32 ? object.size : 32;
const int start2 = limit1 > object.size - 32 ? limit1 : object.size - 32;
for (int i = 0; i < limit1; ++i) {
CHECK_EQ(object.ptr[i], expected);
}
for (int i = start2; i < object.size; ++i) {
CHECK_EQ(object.ptr[i], expected);
}
}
};
static void RunThread(int thread_id) {
threads[thread_id]->Run();
}
static void TryHugeAllocation(size_t s, AllocatorState* rnd) {
void* p = rnd->alloc(s);
CHECK(p == NULL); // huge allocation s should fail!
}
static void TestHugeAllocations(AllocatorState* rnd) {
// Check that asking for stuff tiny bit smaller than largest possible
// size returns NULL.
for (size_t i = 0; i < 70000; i += rnd->Uniform(20)) {
TryHugeAllocation(kMaxSize - i, rnd);
}
// Asking for memory sizes near signed/unsigned boundary (kMaxSignedSize)
// might work or not, depending on the amount of virtual memory.
#ifndef DEBUGALLOCATION // debug allocation takes forever for huge allocs
for (size_t i = 0; i < 100; i++) {
void* p = NULL;
p = rnd->alloc(kMaxSignedSize + i);
if (p) free(p); // if: free(NULL) is not necessarily defined
p = rnd->alloc(kMaxSignedSize - i);
if (p) free(p);
}
#endif
// Check that ReleaseFreeMemory has no visible effect (aka, does not
// crash the test):
MallocExtension* inst = MallocExtension::instance();
CHECK(inst);
inst->ReleaseFreeMemory();
}
static void TestCalloc(size_t n, size_t s, bool ok) {
char* p = reinterpret_cast<char*>(calloc(n, s));
if (FLAGS_verbose)
fprintf(LOGSTREAM, "calloc(%"PRIxS", %"PRIxS"): %p\n", n, s, p);
if (!ok) {
CHECK(p == NULL); // calloc(n, s) should not succeed
} else {
CHECK(p != NULL); // calloc(n, s) should succeed
for (int i = 0; i < n*s; i++) {
CHECK(p[i] == '\0');
}
free(p);
}
}
// This makes sure that reallocing a small number of bytes in either
// direction doesn't cause us to allocate new memory.
static void TestRealloc() {
#ifndef DEBUGALLOCATION // debug alloc doesn't try to minimize reallocs
// When sampling, we always allocate in units of page-size, which
// makes reallocs of small sizes do extra work (thus, failing these
// checks). Since sampling is random, we turn off sampling to make
// sure that doesn't happen to us here.
const int64 old_sample_parameter = FLAGS_tcmalloc_sample_parameter;
FLAGS_tcmalloc_sample_parameter = 0; // turn off sampling
int start_sizes[] = { 100, 1000, 10000, 100000 };
int deltas[] = { 1, -2, 4, -8, 16, -32, 64, -128 };
for (int s = 0; s < sizeof(start_sizes)/sizeof(*start_sizes); ++s) {
void* p = malloc(start_sizes[s]);
CHECK(p);
// The larger the start-size, the larger the non-reallocing delta.
for (int d = 0; d < (s+1) * 2; ++d) {
void* new_p = realloc(p, start_sizes[s] + deltas[d]);
CHECK(p == new_p); // realloc should not allocate new memory
}
// Test again, but this time reallocing smaller first.
for (int d = 0; d < s*2; ++d) {
void* new_p = realloc(p, start_sizes[s] - deltas[d]);
CHECK(p == new_p); // realloc should not allocate new memory
}
free(p);
}
FLAGS_tcmalloc_sample_parameter = old_sample_parameter;
#endif
}
static void TestNewHandler() throw (std::bad_alloc) {
++news_handled;
throw std::bad_alloc();
}
static void TestOneNew(void* (*func)(size_t)) {
// success test
try {
void* ptr = (*func)(kNotTooBig);
if (0 == ptr) {
fprintf(LOGSTREAM, "allocation should not have failed.\n");
abort();
}
} catch (...) {
fprintf(LOGSTREAM, "allocation threw unexpected exception.\n");
abort();
}
// failure test
// we should always receive a bad_alloc exception
try {
(*func)(kTooBig);
fprintf(LOGSTREAM, "allocation should have failed.\n");
abort();
} catch (const std::bad_alloc&) {
// correct
} catch (...) {
fprintf(LOGSTREAM, "allocation threw unexpected exception.\n");
abort();
}
}
static void TestNew(void* (*func)(size_t)) {
news_handled = 0;
// test without new_handler:
std::new_handler saved_handler = std::set_new_handler(0);
TestOneNew(func);
// test with new_handler:
std::set_new_handler(TestNewHandler);
TestOneNew(func);
if (news_handled != 1) {
fprintf(LOGSTREAM, "new_handler was not called.\n");
abort();
}
std::set_new_handler(saved_handler);
}
static void TestOneNothrowNew(void* (*func)(size_t, const std::nothrow_t&)) {
// success test
try {
void* ptr = (*func)(kNotTooBig, std::nothrow);
if (0 == ptr) {
fprintf(LOGSTREAM, "allocation should not have failed.\n");
abort();
}
} catch (...) {
fprintf(LOGSTREAM, "allocation threw unexpected exception.\n");
abort();
}
// failure test
// we should always receive a bad_alloc exception
try {
if ((*func)(kTooBig, std::nothrow) != 0) {
fprintf(LOGSTREAM, "allocation should have failed.\n");
abort();
}
} catch (...) {
fprintf(LOGSTREAM, "nothrow allocation threw unexpected exception.\n");
abort();
}
}
static void TestNothrowNew(void* (*func)(size_t, const std::nothrow_t&)) {
news_handled = 0;
// test without new_handler:
std::new_handler saved_handler = std::set_new_handler(0);
TestOneNothrowNew(func);
// test with new_handler:
std::set_new_handler(TestNewHandler);
TestOneNothrowNew(func);
if (news_handled != 1) {
fprintf(LOGSTREAM, "nothrow new_handler was not called.\n");
abort();
}
std::set_new_handler(saved_handler);
}
// These are used as callbacks by the sanity-check. Set* and Reset*
// register the hook that counts how many times the associated memory
// function is called. After each such call, call Verify* to verify
// that we used the tcmalloc version of the call, and not the libc.
// Note the ... in the hook signature: we don't care what arguments
// the hook takes.
#define MAKE_HOOK_CALLBACK(hook_type) \
static int g_##hook_type##_calls = 0; \
static void IncrementCallsTo##hook_type(...) { \
g_##hook_type##_calls++; \
} \
static void Verify##hook_type##WasCalled() { \
CHECK_GT(g_##hook_type##_calls, 0); \
g_##hook_type##_calls = 0; /* reset for next call */ \
} \
static void Set##hook_type() { \
CHECK(MallocHook::Add##hook_type( \
(MallocHook::hook_type)&IncrementCallsTo##hook_type)); \
} \
static void Reset##hook_type() { \
CHECK(MallocHook::Remove##hook_type( \
(MallocHook::hook_type)&IncrementCallsTo##hook_type)); \
}
// We do one for each hook typedef in malloc_hook.h
MAKE_HOOK_CALLBACK(NewHook);
MAKE_HOOK_CALLBACK(DeleteHook);
MAKE_HOOK_CALLBACK(MmapHook);
MAKE_HOOK_CALLBACK(MremapHook);
MAKE_HOOK_CALLBACK(MunmapHook);
MAKE_HOOK_CALLBACK(SbrkHook);
static void TestAlignmentForSize(int size) {
fprintf(LOGSTREAM, "Testing alignment of malloc(%d)\n", size);
static const int kNum = 100;
void* ptrs[kNum];
for (int i = 0; i < kNum; i++) {
ptrs[i] = malloc(size);
uintptr_t p = reinterpret_cast<uintptr_t>(ptrs[i]);
CHECK((p % sizeof(void*)) == 0);
CHECK((p % sizeof(double)) == 0);
// Must have 16-byte alignment for large enough objects
if (size >= 16) {
CHECK((p % 16) == 0);
}
}
for (int i = 0; i < kNum; i++) {
free(ptrs[i]);
}
}
static void TestMallocAlignment() {
for (int lg = 0; lg < 16; lg++) {
TestAlignmentForSize((1<<lg) - 1);
TestAlignmentForSize((1<<lg) + 0);
TestAlignmentForSize((1<<lg) + 1);
}
}
static void TestHugeThreadCache() {
fprintf(LOGSTREAM, "==== Testing huge thread cache\n");
// More than 2^16 to cause integer overflow of 16 bit counters.
static const int kNum = 70000;
char** array = new char*[kNum];
for (int i = 0; i < kNum; ++i) {
array[i] = new char[10];
}
for (int i = 0; i < kNum; ++i) {
delete[] array[i];
}
delete[] array;
}
namespace {
struct RangeCallbackState {
uintptr_t ptr;
base::MallocRange::Type expected_type;
size_t min_size;
bool matched;
};
static void RangeCallback(void* arg, const base::MallocRange* r) {
RangeCallbackState* state = reinterpret_cast<RangeCallbackState*>(arg);
if (state->ptr >= r->address &&
state->ptr < r->address + r->length) {
if (state->expected_type == base::MallocRange::FREE) {
// We are expecting r->type == FREE, but ReleaseMemory
// may have already moved us to UNMAPPED state instead (this happens in
// approximately 0.1% of executions). Accept either state.
CHECK(r->type == base::MallocRange::FREE ||
r->type == base::MallocRange::UNMAPPED);
} else {
CHECK_EQ(r->type, state->expected_type);
}
CHECK_GE(r->length, state->min_size);
state->matched = true;
}
}
// Check that at least one of the callbacks from Ranges() contains
// the specified address with the specified type, and has size
// >= min_size.
static void CheckRangeCallback(void* ptr, base::MallocRange::Type type,
size_t min_size) {
RangeCallbackState state;
state.ptr = reinterpret_cast<uintptr_t>(ptr);
state.expected_type = type;
state.min_size = min_size;
state.matched = false;
MallocExtension::instance()->Ranges(&state, RangeCallback);
CHECK(state.matched);
}
}
static void TestRanges() {
static const int MB = 1048576;
void* a = malloc(MB);
void* b = malloc(MB);
CheckRangeCallback(a, base::MallocRange::INUSE, MB);
CheckRangeCallback(b, base::MallocRange::INUSE, MB);
free(a);
CheckRangeCallback(a, base::MallocRange::FREE, MB);
CheckRangeCallback(b, base::MallocRange::INUSE, MB);
MallocExtension::instance()->ReleaseFreeMemory();
CheckRangeCallback(a, base::MallocRange::UNMAPPED, MB);
CheckRangeCallback(b, base::MallocRange::INUSE, MB);
free(b);
CheckRangeCallback(a, base::MallocRange::UNMAPPED, MB);
CheckRangeCallback(b, base::MallocRange::FREE, MB);
}
#ifndef DEBUGALLOCATION
static size_t GetUnmappedBytes() {
size_t bytes;
CHECK(MallocExtension::instance()->GetNumericProperty(
"tcmalloc.pageheap_unmapped_bytes", &bytes));
return bytes;
}
#endif
static void TestReleaseToSystem() {
// Debug allocation mode adds overhead to each allocation which
// messes up all the equality tests here. I just disable the
// teset in this mode. TODO(csilvers): get it to work for debugalloc?
#ifndef DEBUGALLOCATION
const double old_tcmalloc_release_rate = FLAGS_tcmalloc_release_rate;
FLAGS_tcmalloc_release_rate = 0;
static const int MB = 1048576;
void* a = malloc(MB);
void* b = malloc(MB);
MallocExtension::instance()->ReleaseFreeMemory();
size_t starting_bytes = GetUnmappedBytes();
// Calling ReleaseFreeMemory() a second time shouldn't do anything.
MallocExtension::instance()->ReleaseFreeMemory();
EXPECT_EQ(starting_bytes, GetUnmappedBytes());
// ReleaseToSystem shouldn't do anything either.
MallocExtension::instance()->ReleaseToSystem(MB);
EXPECT_EQ(starting_bytes, GetUnmappedBytes());
free(a);
// The span to release should be 1MB.
MallocExtension::instance()->ReleaseToSystem(MB/2);
EXPECT_EQ(starting_bytes + MB, GetUnmappedBytes());
// Should do nothing since the previous call released too much.
MallocExtension::instance()->ReleaseToSystem(MB/4);
EXPECT_EQ(starting_bytes + MB, GetUnmappedBytes());
free(b);
// Use up the extra MB/4 bytes from 'a' and also release 'b'.
MallocExtension::instance()->ReleaseToSystem(MB/2);
EXPECT_EQ(starting_bytes + 2*MB, GetUnmappedBytes());
// Should do nothing since the previous call released too much.
MallocExtension::instance()->ReleaseToSystem(MB/2);
EXPECT_EQ(starting_bytes + 2*MB, GetUnmappedBytes());
// Nothing else to release.
MallocExtension::instance()->ReleaseFreeMemory();
EXPECT_EQ(starting_bytes + 2*MB, GetUnmappedBytes());
a = malloc(MB);
free(a);
EXPECT_EQ(starting_bytes + MB, GetUnmappedBytes());
// Releasing less than a page should still trigger a release.
MallocExtension::instance()->ReleaseToSystem(1);
EXPECT_EQ(starting_bytes + 2*MB, GetUnmappedBytes());
FLAGS_tcmalloc_release_rate = old_tcmalloc_release_rate;
#endif // #ifndef DEBUGALLOCATION
}
// On MSVC10, in release mode, the optimizer convinces itself
// g_no_memory is never changed (I guess it doesn't realize OnNoMemory
// might be called). Work around this by setting the var volatile.
volatile bool g_no_memory = false;
std::new_handler g_old_handler = NULL;
static void OnNoMemory() {
g_no_memory = true;
std::set_new_handler(g_old_handler);
}
static void TestSetNewMode() {
int old_mode = tc_set_new_mode(1);
g_old_handler = std::set_new_handler(&OnNoMemory);
g_no_memory = false;
void* ret = malloc(kTooBig);
EXPECT_EQ(NULL, ret);
EXPECT_TRUE(g_no_memory);
g_old_handler = std::set_new_handler(&OnNoMemory);
g_no_memory = false;
ret = calloc(1, kTooBig);
EXPECT_EQ(NULL, ret);
EXPECT_TRUE(g_no_memory);
g_old_handler = std::set_new_handler(&OnNoMemory);
g_no_memory = false;
ret = realloc(NULL, kTooBig);
EXPECT_EQ(NULL, ret);
EXPECT_TRUE(g_no_memory);
if (kOSSupportsMemalign) {
// Not really important, but must be small enough such that
// kAlignment + kTooBig does not overflow.
const int kAlignment = 1 << 5;
g_old_handler = std::set_new_handler(&OnNoMemory);
g_no_memory = false;
ret = Memalign(kAlignment, kTooBig);
EXPECT_EQ(NULL, ret);
EXPECT_TRUE(g_no_memory);
g_old_handler = std::set_new_handler(&OnNoMemory);
g_no_memory = false;
EXPECT_EQ(ENOMEM,
PosixMemalign(&ret, kAlignment, kTooBig));
EXPECT_EQ(NULL, ret);
EXPECT_TRUE(g_no_memory);
}
tc_set_new_mode(old_mode);
}
static int RunAllTests(int argc, char** argv) {
// Optional argv[1] is the seed
AllocatorState rnd(argc > 1 ? atoi(argv[1]) : 100);
SetTestResourceLimit();
// TODO(odo): This test has been disabled because it is only by luck that it
// does not result in fragmentation. When tcmalloc makes an allocation which
// spans previously unused leaves of the pagemap it will allocate and fill in
// the leaves to cover the new allocation. The leaves happen to be 256MiB in
// the 64-bit build, and with the sbrk allocator these allocations just
// happen to fit in one leaf by luck. With other allocators (mmap,
// memfs_malloc when used with small pages) the allocations generally span
// two leaves and this results in a very bad fragmentation pattern with this
// code. The same failure can be forced with the sbrk allocator just by
// allocating something on the order of 128MiB prior to starting this test so
// that the test allocations straddle a 256MiB boundary.
// TODO(csilvers): port MemoryUsage() over so the test can use that
#if 0
# include <unistd.h> // for getpid()
// Allocate and deallocate blocks of increasing sizes to check if the alloc
// metadata fragments the memory. (Do not put other allocations/deallocations
// before this test, it may break).
{
size_t memory_usage = MemoryUsage(getpid());
fprintf(LOGSTREAM, "Testing fragmentation\n");
for ( int i = 200; i < 240; ++i ) {
int size = i << 20;
void *test1 = rnd.alloc(size);
CHECK(test1);
for ( int j = 0; j < size; j += (1 << 12) ) {
static_cast<char*>(test1)[j] = 1;
}
free(test1);
}
// There may still be a bit of fragmentation at the beginning, until we
// reach kPageMapBigAllocationThreshold bytes so we check for
// 200 + 240 + margin.
CHECK_LT(MemoryUsage(getpid()), memory_usage + (450 << 20) );
}
#endif
// Check that empty allocation works
fprintf(LOGSTREAM, "Testing empty allocation\n");
{
void* p1 = rnd.alloc(0);
CHECK(p1 != NULL);
void* p2 = rnd.alloc(0);
CHECK(p2 != NULL);
CHECK(p1 != p2);
free(p1);
free(p2);
}
// This code stresses some of the memory allocation via STL.
// It may call operator delete(void*, nothrow_t).
fprintf(LOGSTREAM, "Testing STL use\n");
{
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(0);
std::stable_sort(v.begin(), v.end());
}
// Test each of the memory-allocation functions once, just as a sanity-check
fprintf(LOGSTREAM, "Sanity-testing all the memory allocation functions\n");
{
// We use new-hook and delete-hook to verify we actually called the
// tcmalloc version of these routines, and not the libc version.
SetNewHook(); // defined as part of MAKE_HOOK_CALLBACK, above
SetDeleteHook(); // ditto
void* p1 = malloc(10);
CHECK(p1 != NULL); // force use of this variable
VerifyNewHookWasCalled();
// Also test the non-standard tc_malloc_size
size_t actual_p1_size = tc_malloc_size(p1);
CHECK_GE(actual_p1_size, 10);
CHECK_LT(actual_p1_size, 100000); // a reasonable upper-bound, I think
free(p1);
VerifyDeleteHookWasCalled();
p1 = calloc(10, 2);
CHECK(p1 != NULL);
VerifyNewHookWasCalled();
// We make sure we realloc to a big size, since some systems (OS
// X) will notice if the realloced size continues to fit into the
// malloc-block and make this a noop if so.
p1 = realloc(p1, 30000);
CHECK(p1 != NULL);
VerifyNewHookWasCalled();
VerifyDeleteHookWasCalled();
cfree(p1); // synonym for free
VerifyDeleteHookWasCalled();
if (kOSSupportsMemalign) {
CHECK_EQ(PosixMemalign(&p1, sizeof(p1), 40), 0);
CHECK(p1 != NULL);
VerifyNewHookWasCalled();
free(p1);
VerifyDeleteHookWasCalled();
p1 = Memalign(sizeof(p1) * 2, 50);
CHECK(p1 != NULL);
VerifyNewHookWasCalled();
free(p1);
VerifyDeleteHookWasCalled();
}
// Windows has _aligned_malloc. Let's test that that's captured too.
#if (defined(_MSC_VER) || defined(__MINGW32__)) && !defined(PERFTOOLS_NO_ALIGNED_MALLOC)
p1 = _aligned_malloc(sizeof(p1) * 2, 64);
CHECK(p1 != NULL);
VerifyNewHookWasCalled();
_aligned_free(p1);
VerifyDeleteHookWasCalled();
#endif
p1 = valloc(60);
CHECK(p1 != NULL);
VerifyNewHookWasCalled();
free(p1);
VerifyDeleteHookWasCalled();
p1 = pvalloc(70);
CHECK(p1 != NULL);
VerifyNewHookWasCalled();
free(p1);
VerifyDeleteHookWasCalled();
char* p2 = new char;
CHECK(p2 != NULL);
VerifyNewHookWasCalled();
delete p2;
VerifyDeleteHookWasCalled();
p2 = new char[100];
CHECK(p2 != NULL);
VerifyNewHookWasCalled();
delete[] p2;
VerifyDeleteHookWasCalled();
p2 = new(std::nothrow) char;
CHECK(p2 != NULL);
VerifyNewHookWasCalled();
delete p2;
VerifyDeleteHookWasCalled();
p2 = new(std::nothrow) char[100];
CHECK(p2 != NULL);
VerifyNewHookWasCalled();
delete[] p2;
VerifyDeleteHookWasCalled();
// Another way of calling operator new
p2 = static_cast<char*>(::operator new(100));
CHECK(p2 != NULL);
VerifyNewHookWasCalled();
::operator delete(p2);
VerifyDeleteHookWasCalled();
// Try to call nothrow's delete too. Compilers use this.
p2 = static_cast<char*>(::operator new(100, std::nothrow));
CHECK(p2 != NULL);
VerifyNewHookWasCalled();
::operator delete(p2, std::nothrow);
VerifyDeleteHookWasCalled();
// Try strdup(), which the system allocates but we must free. If
// all goes well, libc will use our malloc!
p2 = strdup("test");
CHECK(p2 != NULL);
VerifyNewHookWasCalled();
free(p2);
VerifyDeleteHookWasCalled();
// Test mmap too: both anonymous mmap and mmap of a file
// Note that for right now we only override mmap on linux
// systems, so those are the only ones for which we check.
SetMmapHook();
SetMremapHook();
SetMunmapHook();
#if defined(HAVE_MMAP) && defined(__linux) && \
(defined(__i386__) || defined(__x86_64__))
int size = 8192*2;
p1 = mmap(NULL, size, PROT_WRITE|PROT_READ, MAP_ANONYMOUS|MAP_PRIVATE,
-1, 0);
CHECK(p1 != NULL);
VerifyMmapHookWasCalled();
p1 = mremap(p1, size, size/2, 0);
CHECK(p1 != NULL);
VerifyMremapHookWasCalled();
size /= 2;
munmap(p1, size);
VerifyMunmapHookWasCalled();
int fd = open("/dev/zero", O_RDONLY);
CHECK_GE(fd, 0); // make sure the open succeeded
p1 = mmap(NULL, 8192, PROT_READ, MAP_SHARED, fd, 0);
CHECK(p1 != NULL);
VerifyMmapHookWasCalled();
munmap(p1, 8192);
VerifyMunmapHookWasCalled();
close(fd);
#else // this is just to quiet the compiler: make sure all fns are called
IncrementCallsToMmapHook();
IncrementCallsToMunmapHook();
IncrementCallsToMremapHook();
VerifyMmapHookWasCalled();
VerifyMremapHookWasCalled();
VerifyMunmapHookWasCalled();
#endif
// Test sbrk
SetSbrkHook();
#if defined(HAVE_SBRK) && defined(__linux) && \
(defined(__i386__) || defined(__x86_64__))
p1 = sbrk(8192);
CHECK(p1 != NULL);
VerifySbrkHookWasCalled();
p1 = sbrk(-8192);
CHECK(p1 != NULL);
VerifySbrkHookWasCalled();
// However, sbrk hook should *not* be called with sbrk(0)
p1 = sbrk(0);
CHECK(p1 != NULL);
CHECK_EQ(g_SbrkHook_calls, 0);
#else // this is just to quiet the compiler: make sure all fns are called
IncrementCallsToSbrkHook();
VerifySbrkHookWasCalled();
#endif
// Reset the hooks to what they used to be. These are all
// defined as part of MAKE_HOOK_CALLBACK, above.
ResetNewHook();
ResetDeleteHook();
ResetMmapHook();
ResetMremapHook();
ResetMunmapHook();
ResetSbrkHook();
}
// Check that "lots" of memory can be allocated
fprintf(LOGSTREAM, "Testing large allocation\n");
{
const int mb_to_allocate = 100;
void* p = rnd.alloc(mb_to_allocate << 20);
CHECK(p != NULL); // could not allocate
free(p);
}
TestMallocAlignment();
// Check calloc() with various arguments
fprintf(LOGSTREAM, "Testing calloc\n");
TestCalloc(0, 0, true);
TestCalloc(0, 1, true);
TestCalloc(1, 1, true);
TestCalloc(1<<10, 0, true);
TestCalloc(1<<20, 0, true);
TestCalloc(0, 1<<10, true);
TestCalloc(0, 1<<20, true);
TestCalloc(1<<20, 2, true);
TestCalloc(2, 1<<20, true);
TestCalloc(1000, 1000, true);
TestCalloc(kMaxSize, 2, false);
TestCalloc(2, kMaxSize, false);
TestCalloc(kMaxSize, kMaxSize, false);
TestCalloc(kMaxSignedSize, 3, false);
TestCalloc(3, kMaxSignedSize, false);
TestCalloc(kMaxSignedSize, kMaxSignedSize, false);
// Test that realloc doesn't always reallocate and copy memory.
fprintf(LOGSTREAM, "Testing realloc\n");
TestRealloc();
fprintf(LOGSTREAM, "Testing operator new(nothrow).\n");
TestNothrowNew(&::operator new);
fprintf(LOGSTREAM, "Testing operator new[](nothrow).\n");
TestNothrowNew(&::operator new[]);
fprintf(LOGSTREAM, "Testing operator new.\n");
TestNew(&::operator new);
fprintf(LOGSTREAM, "Testing operator new[].\n");
TestNew(&::operator new[]);
// Create threads
fprintf(LOGSTREAM, "Testing threaded allocation/deallocation (%d threads)\n",
FLAGS_numthreads);
threads = new TesterThread*[FLAGS_numthreads];
for (int i = 0; i < FLAGS_numthreads; ++i) {
threads[i] = new TesterThread(i);
}
// This runs all the tests at the same time, with a 1M stack size each
RunManyThreadsWithId(RunThread, FLAGS_numthreads, 1<<20);
for (int i = 0; i < FLAGS_numthreads; ++i) delete threads[i]; // Cleanup
// Do the memory intensive tests after threads are done, since exhausting
// the available address space can make pthread_create to fail.
// Check that huge allocations fail with NULL instead of crashing
fprintf(LOGSTREAM, "Testing huge allocations\n");
TestHugeAllocations(&rnd);
// Check that large allocations fail with NULL instead of crashing
#ifndef DEBUGALLOCATION // debug allocation takes forever for huge allocs
fprintf(LOGSTREAM, "Testing out of memory\n");
for (int s = 0; ; s += (10<<20)) {
void* large_object = rnd.alloc(s);
if (large_object == NULL) break;
free(large_object);
}
#endif
TestHugeThreadCache();
TestRanges();
TestReleaseToSystem();
TestSetNewMode();
return 0;
}
}
using testing::RunAllTests;
int main(int argc, char** argv) {
#ifdef DEBUGALLOCATION // debug allocation takes forever for huge allocs
FLAGS_max_free_queue_size = 0; // return freed blocks to tcmalloc immediately
#endif
RunAllTests(argc, argv);
// Test tc_version()
fprintf(LOGSTREAM, "Testing tc_version()\n");
int major;
int minor;
const char* patch;
char mmp[64];
const char* human_version = tc_version(&major, &minor, &patch);
snprintf(mmp, sizeof(mmp), "%d.%d%s", major, minor, patch);
CHECK(!strcmp(PACKAGE_STRING, human_version));
CHECK(!strcmp(PACKAGE_VERSION, mmp));
fprintf(LOGSTREAM, "PASS\n");
}
| null | null | null | null | 23,621 |
14,254 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 14,254 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2017 The Chromium 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 "ios/web/public/global_state/ios_global_state_configuration.h"
namespace ios_global_state {
scoped_refptr<base::SingleThreadTaskRunner>
GetSharedNetworkIOThreadTaskRunner() {
return nullptr;
}
} // namespace ios_global_state
| null | null | null | null | 11,117 |
41,438 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 41,438 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright (c) 2013 The Chromium 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 TOOLS_GN_NINJA_BINARY_TARGET_WRITER_H_
#define TOOLS_GN_NINJA_BINARY_TARGET_WRITER_H_
#include "base/macros.h"
#include "tools/gn/config_values.h"
#include "tools/gn/ninja_target_writer.h"
#include "tools/gn/toolchain.h"
#include "tools/gn/unique_vector.h"
struct EscapeOptions;
class SourceFileTypeSet;
// Writes a .ninja file for a binary target type (an executable, a shared
// library, or a static library).
class NinjaBinaryTargetWriter : public NinjaTargetWriter {
public:
class SourceFileTypeSet;
NinjaBinaryTargetWriter(const Target* target, std::ostream& out);
~NinjaBinaryTargetWriter() override;
void Run() override;
private:
typedef std::set<OutputFile> OutputFileSet;
// Writes all flags for the compiler: includes, defines, cflags, etc.
void WriteCompilerVars(const SourceFileTypeSet& used_types);
// Writes to the output stream a stamp rule for inputs, and
// returns the file to be appended to source rules that encodes the
// implicit dependencies for the current target. The returned OutputFile
// will be empty if there are no inputs.
OutputFile WriteInputsStampAndGetDep() const;
// has_precompiled_headers is set when this substitution matches a tool type
// that supports precompiled headers, and this target supports precompiled
// headers. It doesn't indicate if the tool has precompiled headers (this
// will be looked up by this function).
//
// The tool_type indicates the corresponding tool for flags that are
// tool-specific (e.g. "cflags_c"). For non-tool-specific flags (e.g.
// "defines") tool_type should be TYPE_NONE.
void WriteOneFlag(
SubstitutionType subst_enum,
bool has_precompiled_headers,
Toolchain::ToolType tool_type,
const std::vector<std::string>& (ConfigValues::* getter)() const,
EscapeOptions flag_escape_options);
// Writes build lines required for precompiled headers. Any generated
// object files will be appended to the |object_files|. Any generated
// non-object files (for instance, .gch files from a GCC toolchain, are
// appended to |other_files|).
//
// input_dep is the stamp file collecting the dependencies required before
// compiling this target. It will be empty if there are no input deps.
void WritePCHCommands(const SourceFileTypeSet& used_types,
const OutputFile& input_dep,
const std::vector<OutputFile>& order_only_deps,
std::vector<OutputFile>* object_files,
std::vector<OutputFile>* other_files);
// Writes a .pch compile build line for a language type.
void WritePCHCommand(SubstitutionType flag_type,
Toolchain::ToolType tool_type,
Tool::PrecompiledHeaderType header_type,
const OutputFile& input_dep,
const std::vector<OutputFile>& order_only_deps,
std::vector<OutputFile>* object_files,
std::vector<OutputFile>* other_files);
void WriteGCCPCHCommand(SubstitutionType flag_type,
Toolchain::ToolType tool_type,
const OutputFile& input_dep,
const std::vector<OutputFile>& order_only_deps,
std::vector<OutputFile>* gch_files);
void WriteWindowsPCHCommand(SubstitutionType flag_type,
Toolchain::ToolType tool_type,
const OutputFile& input_dep,
const std::vector<OutputFile>& order_only_deps,
std::vector<OutputFile>* object_files);
// pch_deps are additional dependencies to run before the rule. They are
// expected to abide by the naming conventions specified by GetPCHOutputFiles.
//
// order_only_dep are the dependencies that must be run before doing any
// compiles.
//
// The files produced by the compiler will be added to two output vectors.
void WriteSources(const std::vector<OutputFile>& pch_deps,
const OutputFile& input_dep,
const std::vector<OutputFile>& order_only_deps,
std::vector<OutputFile>* object_files,
std::vector<SourceFile>* other_files);
// Writes a build line.
void WriteCompilerBuildLine(const SourceFile& source,
const std::vector<OutputFile>& extra_deps,
const std::vector<OutputFile>& order_only_deps,
Toolchain::ToolType tool_type,
const std::vector<OutputFile>& outputs);
void WriteLinkerStuff(const std::vector<OutputFile>& object_files,
const std::vector<SourceFile>& other_files);
void WriteLinkerFlags(const SourceFile* optional_def_file);
void WriteLibs();
void WriteOutputSubstitutions();
void WriteSolibs(const std::vector<OutputFile>& solibs);
// Writes the stamp line for a source set. These are not linked.
void WriteSourceSetStamp(const std::vector<OutputFile>& object_files);
// Gets all target dependencies and classifies them, as well as accumulates
// object files from source sets we need to link.
void GetDeps(UniqueVector<OutputFile>* extra_object_files,
UniqueVector<const Target*>* linkable_deps,
UniqueVector<const Target*>* non_linkable_deps) const;
// Classifies the dependency as linkable or nonlinkable with the current
// target, adding it to the appropriate vector. If the dependency is a source
// set we should link in, the source set's object files will be appended to
// |extra_object_files|.
void ClassifyDependency(const Target* dep,
UniqueVector<OutputFile>* extra_object_files,
UniqueVector<const Target*>* linkable_deps,
UniqueVector<const Target*>* non_linkable_deps) const;
// Writes the implicit dependencies for the link or stamp line. This is
// the "||" and everything following it on the ninja line.
//
// The order-only dependencies are the non-linkable deps passed in as an
// argument, plus the data file depdencies in the target.
void WriteOrderOnlyDependencies(
const UniqueVector<const Target*>& non_linkable_deps);
// Returns the computed name of the Windows .pch file for the given
// tool type. The tool must support precompiled headers.
OutputFile GetWindowsPCHFile(Toolchain::ToolType tool_type) const;
// Checks for duplicates in the given list of output files. If any duplicates
// are found, throws an error and return false.
bool CheckForDuplicateObjectFiles(const std::vector<OutputFile>& files) const;
const Tool* tool_;
// Cached version of the prefix used for rule types for this toolchain.
std::string rule_prefix_;
DISALLOW_COPY_AND_ASSIGN(NinjaBinaryTargetWriter);
};
#endif // TOOLS_GN_NINJA_BINARY_TARGET_WRITER_H_
| null | null | null | null | 38,301 |
14,143 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 14,143 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2016 The Chromium 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 "components/offline_pages/core/background/mark_attempt_started_task.h"
#include <memory>
#include "base/bind.h"
#include "base/test/test_simple_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "components/offline_pages/core/background/request_queue_in_memory_store.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace offline_pages {
namespace {
const int64_t kRequestId1 = 42;
const int64_t kRequestId2 = 44;
const GURL kUrl1("http://example.com");
const ClientId kClientId1("download", "1234");
} // namespace
class MarkAttemptStartedTaskTest : public testing::Test {
public:
MarkAttemptStartedTaskTest();
~MarkAttemptStartedTaskTest() override;
void PumpLoop();
void InitializeStore(RequestQueueStore* store);
void AddItemToStore(RequestQueueStore* store);
void ChangeRequestsStateCallback(
std::unique_ptr<UpdateRequestsResult> result);
UpdateRequestsResult* last_result() const { return result_.get(); }
private:
void InitializeStoreDone(bool success);
void AddRequestDone(ItemActionStatus status);
std::unique_ptr<UpdateRequestsResult> result_;
scoped_refptr<base::TestSimpleTaskRunner> task_runner_;
base::ThreadTaskRunnerHandle task_runner_handle_;
};
MarkAttemptStartedTaskTest::MarkAttemptStartedTaskTest()
: task_runner_(new base::TestSimpleTaskRunner),
task_runner_handle_(task_runner_) {}
MarkAttemptStartedTaskTest::~MarkAttemptStartedTaskTest() {}
void MarkAttemptStartedTaskTest::PumpLoop() {
task_runner_->RunUntilIdle();
}
void MarkAttemptStartedTaskTest::InitializeStore(RequestQueueStore* store) {
store->Initialize(base::Bind(&MarkAttemptStartedTaskTest::InitializeStoreDone,
base::Unretained(this)));
PumpLoop();
}
void MarkAttemptStartedTaskTest::AddItemToStore(RequestQueueStore* store) {
base::Time creation_time = base::Time::Now();
SavePageRequest request_1(kRequestId1, kUrl1, kClientId1, creation_time,
true);
store->AddRequest(request_1,
base::Bind(&MarkAttemptStartedTaskTest::AddRequestDone,
base::Unretained(this)));
PumpLoop();
}
void MarkAttemptStartedTaskTest::ChangeRequestsStateCallback(
std::unique_ptr<UpdateRequestsResult> result) {
result_ = std::move(result);
}
void MarkAttemptStartedTaskTest::InitializeStoreDone(bool success) {
ASSERT_TRUE(success);
}
void MarkAttemptStartedTaskTest::AddRequestDone(ItemActionStatus status) {
ASSERT_EQ(ItemActionStatus::SUCCESS, status);
}
TEST_F(MarkAttemptStartedTaskTest, MarkAttemptStartedWhenStoreEmpty) {
RequestQueueInMemoryStore store;
InitializeStore(&store);
MarkAttemptStartedTask task(
&store, kRequestId1,
base::Bind(&MarkAttemptStartedTaskTest::ChangeRequestsStateCallback,
base::Unretained(this)));
task.Run();
PumpLoop();
ASSERT_TRUE(last_result());
EXPECT_EQ(1UL, last_result()->item_statuses.size());
EXPECT_EQ(kRequestId1, last_result()->item_statuses.at(0).first);
EXPECT_EQ(ItemActionStatus::NOT_FOUND,
last_result()->item_statuses.at(0).second);
EXPECT_EQ(0UL, last_result()->updated_items.size());
}
TEST_F(MarkAttemptStartedTaskTest, MarkAttemptStartedWhenExists) {
RequestQueueInMemoryStore store;
InitializeStore(&store);
AddItemToStore(&store);
MarkAttemptStartedTask task(
&store, kRequestId1,
base::Bind(&MarkAttemptStartedTaskTest::ChangeRequestsStateCallback,
base::Unretained(this)));
// Current time for verification.
base::Time before_time = base::Time::Now();
task.Run();
PumpLoop();
ASSERT_TRUE(last_result());
EXPECT_EQ(1UL, last_result()->item_statuses.size());
EXPECT_EQ(kRequestId1, last_result()->item_statuses.at(0).first);
EXPECT_EQ(ItemActionStatus::SUCCESS,
last_result()->item_statuses.at(0).second);
EXPECT_EQ(1UL, last_result()->updated_items.size());
EXPECT_LE(before_time,
last_result()->updated_items.at(0).last_attempt_time());
EXPECT_GE(base::Time::Now(),
last_result()->updated_items.at(0).last_attempt_time());
EXPECT_EQ(1, last_result()->updated_items.at(0).started_attempt_count());
EXPECT_EQ(SavePageRequest::RequestState::OFFLINING,
last_result()->updated_items.at(0).request_state());
}
TEST_F(MarkAttemptStartedTaskTest, MarkAttemptStartedWhenItemMissing) {
RequestQueueInMemoryStore store;
InitializeStore(&store);
AddItemToStore(&store);
MarkAttemptStartedTask task(
&store, kRequestId2,
base::Bind(&MarkAttemptStartedTaskTest::ChangeRequestsStateCallback,
base::Unretained(this)));
task.Run();
PumpLoop();
ASSERT_TRUE(last_result());
EXPECT_EQ(1UL, last_result()->item_statuses.size());
EXPECT_EQ(kRequestId2, last_result()->item_statuses.at(0).first);
EXPECT_EQ(ItemActionStatus::NOT_FOUND,
last_result()->item_statuses.at(0).second);
EXPECT_EQ(0UL, last_result()->updated_items.size());
}
} // namespace offline_pages
| null | null | null | null | 11,006 |
53,529 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 53,529 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2014 The Chromium 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 "media/cast/sender/vp8_encoder.h"
#include "base/logging.h"
#include "media/base/video_frame.h"
#include "media/cast/constants.h"
#include "third_party/libvpx/source/libvpx/vpx/vp8cx.h"
namespace media {
namespace cast {
namespace {
// After a pause in the video stream, what is the maximum duration amount to
// pass to the encoder for the next frame (in terms of 1/max_fps sized periods)?
// This essentially controls the encoded size of the first frame that follows a
// pause in the video stream.
const int kRestartFramePeriods = 3;
// The following constants are used to automactically tune the encoder
// parameters: |cpu_used| and |min_quantizer|.
// The |half-life| of the encoding speed accumulator.
// The smaller, the shorter of the time averaging window.
const int kEncodingSpeedAccHalfLife = 120000; // 0.12 second.
// The target encoder utilization signal. This is a trade-off between quality
// and less CPU usage. The range of this value is [0, 1]. Higher the value,
// better the quality and higher the CPU usage.
//
// For machines with more than two encoding threads.
const double kHiTargetEncoderUtilization = 0.7;
// For machines with two encoding threads.
const double kMidTargetEncoderUtilization = 0.6;
// For machines with single encoding thread.
const double kLoTargetEncoderUtilization = 0.5;
// This is the equivalent change on encoding speed for the change on each
// quantizer step.
const double kEquivalentEncodingSpeedStepPerQpStep = 1 / 20.0;
// Highest/lowest allowed encoding speed set to the encoder. The valid range
// is [4, 16]. Experiments show that with speed higher than 12, the saving of
// the encoding time is not worth the dropping of the quality. And with speed
// lower than 6, the increasing of quality is not worth the increasing of
// encoding time.
const int kHighestEncodingSpeed = 12;
const int kLowestEncodingSpeed = 6;
bool HasSufficientFeedback(
const FeedbackSignalAccumulator<base::TimeDelta>& accumulator) {
const base::TimeDelta amount_of_history =
accumulator.update_time() - accumulator.reset_time();
return amount_of_history.InMicroseconds() >= 250000; // 0.25 second.
}
} // namespace
Vp8Encoder::Vp8Encoder(const FrameSenderConfig& video_config)
: cast_config_(video_config),
target_encoder_utilization_(
video_config.video_codec_params.number_of_encode_threads > 2
? kHiTargetEncoderUtilization
: (video_config.video_codec_params.number_of_encode_threads > 1
? kMidTargetEncoderUtilization
: kLoTargetEncoderUtilization)),
key_frame_requested_(true),
bitrate_kbit_(cast_config_.start_bitrate / 1000),
next_frame_id_(FrameId::first()),
encoding_speed_acc_(
base::TimeDelta::FromMicroseconds(kEncodingSpeedAccHalfLife)),
encoding_speed_(kHighestEncodingSpeed) {
config_.g_timebase.den = 0; // Not initialized.
DCHECK_LE(cast_config_.video_codec_params.min_qp,
cast_config_.video_codec_params.max_cpu_saver_qp);
DCHECK_LE(cast_config_.video_codec_params.max_cpu_saver_qp,
cast_config_.video_codec_params.max_qp);
thread_checker_.DetachFromThread();
}
Vp8Encoder::~Vp8Encoder() {
DCHECK(thread_checker_.CalledOnValidThread());
if (is_initialized())
vpx_codec_destroy(&encoder_);
}
void Vp8Encoder::Initialize() {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(!is_initialized());
// The encoder will be created/configured when the first frame encode is
// requested.
}
void Vp8Encoder::ConfigureForNewFrameSize(const gfx::Size& frame_size) {
if (is_initialized()) {
// Workaround for VP8 bug: If the new size is strictly less-than-or-equal to
// the old size, in terms of area, the existing encoder instance can
// continue. Otherwise, completely tear-down and re-create a new encoder to
// avoid a shutdown crash.
if (frame_size.GetArea() <= gfx::Size(config_.g_w, config_.g_h).GetArea()) {
DVLOG(1) << "Continuing to use existing encoder at smaller frame size: "
<< gfx::Size(config_.g_w, config_.g_h).ToString() << " --> "
<< frame_size.ToString();
config_.g_w = frame_size.width();
config_.g_h = frame_size.height();
config_.rc_min_quantizer = cast_config_.video_codec_params.min_qp;
if (vpx_codec_enc_config_set(&encoder_, &config_) == VPX_CODEC_OK)
return;
DVLOG(1) << "libvpx rejected the attempt to use a smaller frame size in "
"the current instance.";
}
DVLOG(1) << "Destroying/Re-Creating encoder for larger frame size: "
<< gfx::Size(config_.g_w, config_.g_h).ToString() << " --> "
<< frame_size.ToString();
vpx_codec_destroy(&encoder_);
} else {
DVLOG(1) << "Creating encoder for the first frame; size: "
<< frame_size.ToString();
}
// Populate encoder configuration with default values.
CHECK_EQ(vpx_codec_enc_config_default(vpx_codec_vp8_cx(), &config_, 0),
VPX_CODEC_OK);
config_.g_threads = cast_config_.video_codec_params.number_of_encode_threads;
config_.g_w = frame_size.width();
config_.g_h = frame_size.height();
// Set the timebase to match that of base::TimeDelta.
config_.g_timebase.num = 1;
config_.g_timebase.den = base::Time::kMicrosecondsPerSecond;
// |g_pass| and |g_lag_in_frames| must be "one pass" and zero, respectively,
// in order for VP8 to support changing frame sizes during encoding:
config_.g_pass = VPX_RC_ONE_PASS;
config_.g_lag_in_frames = 0; // Immediate data output for each frame.
// Rate control settings.
config_.rc_dropframe_thresh = 0; // The encoder may not drop any frames.
config_.rc_resize_allowed = 0; // TODO(miu): Why not? Investigate this.
config_.rc_end_usage = VPX_CBR;
config_.rc_target_bitrate = bitrate_kbit_;
config_.rc_min_quantizer = cast_config_.video_codec_params.min_qp;
config_.rc_max_quantizer = cast_config_.video_codec_params.max_qp;
// TODO(miu): Revisit these now that the encoder is being successfully
// micro-managed.
config_.rc_undershoot_pct = 100;
config_.rc_overshoot_pct = 15;
// TODO(miu): Document why these rc_buf_*_sz values were chosen and/or
// research for better values. Should they be computed from the target
// playout delay?
config_.rc_buf_initial_sz = 500;
config_.rc_buf_optimal_sz = 600;
config_.rc_buf_sz = 1000;
config_.kf_mode = VPX_KF_DISABLED;
vpx_codec_flags_t flags = 0;
CHECK_EQ(vpx_codec_enc_init(&encoder_, vpx_codec_vp8_cx(), &config_, flags),
VPX_CODEC_OK);
// Raise the threshold for considering macroblocks as static. The default is
// zero, so this setting makes the encoder less sensitive to motion. This
// lowers the probability of needing to utilize more CPU to search for motion
// vectors.
CHECK_EQ(vpx_codec_control(&encoder_, VP8E_SET_STATIC_THRESHOLD, 1),
VPX_CODEC_OK);
// This cpu_used setting is a trade-off between cpu usage and encoded video
// quality. The default is zero, with increasingly less CPU to be used as the
// value is more negative or more positive. The encoder does some automatic
// adjust on encoding speed for positive values, however at least at this
// stage the experiments show that this automatic behaviour is not reliable on
// windows machines. We choose to set negative values instead to directly set
// the encoding speed to the encoder. Starting with the highest encoding speed
// to avoid large cpu usage from the beginning.
encoding_speed_ = kHighestEncodingSpeed;
CHECK_EQ(vpx_codec_control(&encoder_, VP8E_SET_CPUUSED, -encoding_speed_),
VPX_CODEC_OK);
}
void Vp8Encoder::Encode(const scoped_refptr<media::VideoFrame>& video_frame,
const base::TimeTicks& reference_time,
SenderEncodedFrame* encoded_frame) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(encoded_frame);
// Note: This is used to compute the |encoder_utilization| and so it uses the
// real-world clock instead of the CastEnvironment clock, the latter of which
// might be simulated.
const base::TimeTicks start_time = base::TimeTicks::Now();
// Initialize on-demand. Later, if the video frame size has changed, update
// the encoder configuration.
const gfx::Size frame_size = video_frame->visible_rect().size();
if (!is_initialized() || gfx::Size(config_.g_w, config_.g_h) != frame_size)
ConfigureForNewFrameSize(frame_size);
// Wrapper for vpx_codec_encode() to access the YUV data in the |video_frame|.
// Only the VISIBLE rectangle within |video_frame| is exposed to the codec.
vpx_image_t vpx_image;
vpx_image_t* const result = vpx_img_wrap(
&vpx_image,
VPX_IMG_FMT_I420,
frame_size.width(),
frame_size.height(),
1,
video_frame->data(VideoFrame::kYPlane));
DCHECK_EQ(result, &vpx_image);
vpx_image.planes[VPX_PLANE_Y] =
video_frame->visible_data(VideoFrame::kYPlane);
vpx_image.planes[VPX_PLANE_U] =
video_frame->visible_data(VideoFrame::kUPlane);
vpx_image.planes[VPX_PLANE_V] =
video_frame->visible_data(VideoFrame::kVPlane);
vpx_image.stride[VPX_PLANE_Y] = video_frame->stride(VideoFrame::kYPlane);
vpx_image.stride[VPX_PLANE_U] = video_frame->stride(VideoFrame::kUPlane);
vpx_image.stride[VPX_PLANE_V] = video_frame->stride(VideoFrame::kVPlane);
// The frame duration given to the VP8 codec affects a number of important
// behaviors, including: per-frame bandwidth, CPU time spent encoding,
// temporal quality trade-offs, and key/golden/alt-ref frame generation
// intervals. Bound the prediction to account for the fact that the frame
// rate can be highly variable, including long pauses in the video stream.
const base::TimeDelta minimum_frame_duration =
base::TimeDelta::FromSecondsD(1.0 / cast_config_.max_frame_rate);
const base::TimeDelta maximum_frame_duration =
base::TimeDelta::FromSecondsD(static_cast<double>(kRestartFramePeriods) /
cast_config_.max_frame_rate);
base::TimeDelta predicted_frame_duration;
if (!video_frame->metadata()->GetTimeDelta(
media::VideoFrameMetadata::FRAME_DURATION,
&predicted_frame_duration) ||
predicted_frame_duration <= base::TimeDelta()) {
// The source of the video frame did not provide the frame duration. Use
// the actual amount of time between the current and previous frame as a
// prediction for the next frame's duration.
predicted_frame_duration = video_frame->timestamp() - last_frame_timestamp_;
}
predicted_frame_duration =
std::max(minimum_frame_duration,
std::min(maximum_frame_duration, predicted_frame_duration));
last_frame_timestamp_ = video_frame->timestamp();
// Encode the frame. The presentation time stamp argument here is fixed to
// zero to force the encoder to base its single-frame bandwidth calculations
// entirely on |predicted_frame_duration| and the target bitrate setting being
// micro-managed via calls to UpdateRates().
CHECK_EQ(vpx_codec_encode(&encoder_, &vpx_image, 0,
predicted_frame_duration.InMicroseconds(),
key_frame_requested_ ? VPX_EFLAG_FORCE_KF : 0,
VPX_DL_REALTIME),
VPX_CODEC_OK)
<< "BUG: Invalid arguments passed to vpx_codec_encode().";
// Pull data from the encoder, populating a new EncodedFrame.
encoded_frame->frame_id = next_frame_id_++;
const vpx_codec_cx_pkt_t* pkt = NULL;
vpx_codec_iter_t iter = NULL;
while ((pkt = vpx_codec_get_cx_data(&encoder_, &iter)) != NULL) {
if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
continue;
if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) {
// TODO(hubbe): Replace "dependency" with a "bool is_key_frame".
encoded_frame->dependency = EncodedFrame::KEY;
encoded_frame->referenced_frame_id = encoded_frame->frame_id;
} else {
encoded_frame->dependency = EncodedFrame::DEPENDENT;
// Frame dependencies could theoretically be relaxed by looking for the
// VPX_FRAME_IS_DROPPABLE flag, but in recent testing (Oct 2014), this
// flag never seems to be set.
encoded_frame->referenced_frame_id = encoded_frame->frame_id - 1;
}
encoded_frame->rtp_timestamp =
RtpTimeTicks::FromTimeDelta(video_frame->timestamp(), kVideoFrequency);
encoded_frame->reference_time = reference_time;
encoded_frame->data.assign(
static_cast<const uint8_t*>(pkt->data.frame.buf),
static_cast<const uint8_t*>(pkt->data.frame.buf) + pkt->data.frame.sz);
break; // Done, since all data is provided in one CX_FRAME_PKT packet.
}
DCHECK(!encoded_frame->data.empty())
<< "BUG: Encoder must provide data since lagged encoding is disabled.";
// Compute encoder utilization as the real-world time elapsed divided by the
// frame duration.
const base::TimeDelta processing_time = base::TimeTicks::Now() - start_time;
encoded_frame->encoder_utilization =
processing_time.InSecondsF() / predicted_frame_duration.InSecondsF();
// Compute lossy utilization. The VP8 encoder took an estimated guess at what
// quantizer value would produce an encoded frame size as close to the target
// as possible. Now that the frame has been encoded and the number of bytes
// is known, the perfect quantizer value (i.e., the one that should have been
// used) can be determined. This perfect quantizer is then normalized and
// used as the lossy utilization.
const double actual_bitrate =
encoded_frame->data.size() * 8.0 / predicted_frame_duration.InSecondsF();
const double target_bitrate = 1000.0 * config_.rc_target_bitrate;
DCHECK_GT(target_bitrate, 0.0);
const double bitrate_utilization = actual_bitrate / target_bitrate;
int quantizer = -1;
CHECK_EQ(vpx_codec_control(&encoder_, VP8E_GET_LAST_QUANTIZER_64, &quantizer),
VPX_CODEC_OK);
const double perfect_quantizer = bitrate_utilization * std::max(0, quantizer);
// Side note: If it was possible for the encoder to encode within the target
// number of bytes, the |perfect_quantizer| will be in the range [0.0,63.0].
// If it was never possible, the value will be greater than 63.0.
encoded_frame->lossy_utilization = perfect_quantizer / 63.0;
DVLOG(2) << "VP8 encoded frame_id " << encoded_frame->frame_id
<< ", sized: " << encoded_frame->data.size()
<< ", encoder_utilization: " << encoded_frame->encoder_utilization
<< ", lossy_utilization: " << encoded_frame->lossy_utilization
<< " (quantizer chosen by the encoder was " << quantizer << ')';
if (encoded_frame->dependency == EncodedFrame::KEY) {
key_frame_requested_ = false;
}
if (encoded_frame->dependency == EncodedFrame::KEY) {
encoding_speed_acc_.Reset(kHighestEncodingSpeed, video_frame->timestamp());
} else {
// Equivalent encoding speed considering both cpu_used setting and
// quantizer.
double actual_encoding_speed =
encoding_speed_ +
kEquivalentEncodingSpeedStepPerQpStep *
std::max(0, quantizer - cast_config_.video_codec_params.min_qp);
double adjusted_encoding_speed = actual_encoding_speed *
encoded_frame->encoder_utilization /
target_encoder_utilization_;
encoding_speed_acc_.Update(adjusted_encoding_speed,
video_frame->timestamp());
}
if (HasSufficientFeedback(encoding_speed_acc_)) {
// Predict |encoding_speed_| and |min_quantizer| for next frame.
// When CPU is constrained, increase encoding speed and increase
// |min_quantizer| if needed.
double next_encoding_speed = encoding_speed_acc_.current();
int next_min_qp;
if (next_encoding_speed > kHighestEncodingSpeed) {
double remainder = next_encoding_speed - kHighestEncodingSpeed;
next_encoding_speed = kHighestEncodingSpeed;
next_min_qp =
static_cast<int>(remainder / kEquivalentEncodingSpeedStepPerQpStep +
cast_config_.video_codec_params.min_qp + 0.5);
next_min_qp = std::min(next_min_qp,
cast_config_.video_codec_params.max_cpu_saver_qp);
} else {
next_encoding_speed =
std::max<double>(kLowestEncodingSpeed, next_encoding_speed) + 0.5;
next_min_qp = cast_config_.video_codec_params.min_qp;
}
if (encoding_speed_ != static_cast<int>(next_encoding_speed)) {
encoding_speed_ = static_cast<int>(next_encoding_speed);
CHECK_EQ(vpx_codec_control(&encoder_, VP8E_SET_CPUUSED, -encoding_speed_),
VPX_CODEC_OK);
}
if (config_.rc_min_quantizer != static_cast<unsigned int>(next_min_qp)) {
config_.rc_min_quantizer = static_cast<unsigned int>(next_min_qp);
CHECK_EQ(vpx_codec_enc_config_set(&encoder_, &config_), VPX_CODEC_OK);
}
}
}
void Vp8Encoder::UpdateRates(uint32_t new_bitrate) {
DCHECK(thread_checker_.CalledOnValidThread());
if (!is_initialized())
return;
uint32_t new_bitrate_kbit = new_bitrate / 1000;
if (config_.rc_target_bitrate == new_bitrate_kbit)
return;
config_.rc_target_bitrate = bitrate_kbit_ = new_bitrate_kbit;
// Update encoder context.
if (vpx_codec_enc_config_set(&encoder_, &config_)) {
NOTREACHED() << "Invalid return value";
}
VLOG(1) << "VP8 new rc_target_bitrate: " << new_bitrate_kbit << " kbps";
}
void Vp8Encoder::GenerateKeyFrame() {
DCHECK(thread_checker_.CalledOnValidThread());
key_frame_requested_ = true;
}
} // namespace cast
} // namespace media
| null | null | null | null | 50,392 |
43,358 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 208,353 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | #ifndef _UAPI_LINUX_DCCP_H
#define _UAPI_LINUX_DCCP_H
#include <linux/types.h>
#include <asm/byteorder.h>
/**
* struct dccp_hdr - generic part of DCCP packet header
*
* @dccph_sport - Relevant port on the endpoint that sent this packet
* @dccph_dport - Relevant port on the other endpoint
* @dccph_doff - Data Offset from the start of the DCCP header, in 32-bit words
* @dccph_ccval - Used by the HC-Sender CCID
* @dccph_cscov - Parts of the packet that are covered by the Checksum field
* @dccph_checksum - Internet checksum, depends on dccph_cscov
* @dccph_x - 0 = 24 bit sequence number, 1 = 48
* @dccph_type - packet type, see DCCP_PKT_ prefixed macros
* @dccph_seq - sequence number high or low order 24 bits, depends on dccph_x
*/
struct dccp_hdr {
__be16 dccph_sport,
dccph_dport;
__u8 dccph_doff;
#if defined(__LITTLE_ENDIAN_BITFIELD)
__u8 dccph_cscov:4,
dccph_ccval:4;
#elif defined(__BIG_ENDIAN_BITFIELD)
__u8 dccph_ccval:4,
dccph_cscov:4;
#else
#error "Adjust your <asm/byteorder.h> defines"
#endif
__sum16 dccph_checksum;
#if defined(__LITTLE_ENDIAN_BITFIELD)
__u8 dccph_x:1,
dccph_type:4,
dccph_reserved:3;
#elif defined(__BIG_ENDIAN_BITFIELD)
__u8 dccph_reserved:3,
dccph_type:4,
dccph_x:1;
#else
#error "Adjust your <asm/byteorder.h> defines"
#endif
__u8 dccph_seq2;
__be16 dccph_seq;
};
/**
* struct dccp_hdr_ext - the low bits of a 48 bit seq packet
*
* @dccph_seq_low - low 24 bits of a 48 bit seq packet
*/
struct dccp_hdr_ext {
__be32 dccph_seq_low;
};
/**
* struct dccp_hdr_request - Connection initiation request header
*
* @dccph_req_service - Service to which the client app wants to connect
*/
struct dccp_hdr_request {
__be32 dccph_req_service;
};
/**
* struct dccp_hdr_ack_bits - acknowledgment bits common to most packets
*
* @dccph_resp_ack_nr_high - 48 bit ack number high order bits, contains GSR
* @dccph_resp_ack_nr_low - 48 bit ack number low order bits, contains GSR
*/
struct dccp_hdr_ack_bits {
__be16 dccph_reserved1;
__be16 dccph_ack_nr_high;
__be32 dccph_ack_nr_low;
};
/**
* struct dccp_hdr_response - Connection initiation response header
*
* @dccph_resp_ack - 48 bit Acknowledgment Number Subheader (5.3)
* @dccph_resp_service - Echoes the Service Code on a received DCCP-Request
*/
struct dccp_hdr_response {
struct dccp_hdr_ack_bits dccph_resp_ack;
__be32 dccph_resp_service;
};
/**
* struct dccp_hdr_reset - Unconditionally shut down a connection
*
* @dccph_reset_ack - 48 bit Acknowledgment Number Subheader (5.6)
* @dccph_reset_code - one of %dccp_reset_codes
* @dccph_reset_data - the Data 1 ... Data 3 fields from 5.6
*/
struct dccp_hdr_reset {
struct dccp_hdr_ack_bits dccph_reset_ack;
__u8 dccph_reset_code,
dccph_reset_data[3];
};
enum dccp_pkt_type {
DCCP_PKT_REQUEST = 0,
DCCP_PKT_RESPONSE,
DCCP_PKT_DATA,
DCCP_PKT_ACK,
DCCP_PKT_DATAACK,
DCCP_PKT_CLOSEREQ,
DCCP_PKT_CLOSE,
DCCP_PKT_RESET,
DCCP_PKT_SYNC,
DCCP_PKT_SYNCACK,
DCCP_PKT_INVALID,
};
#define DCCP_NR_PKT_TYPES DCCP_PKT_INVALID
static inline unsigned int dccp_packet_hdr_len(const __u8 type)
{
if (type == DCCP_PKT_DATA)
return 0;
if (type == DCCP_PKT_DATAACK ||
type == DCCP_PKT_ACK ||
type == DCCP_PKT_SYNC ||
type == DCCP_PKT_SYNCACK ||
type == DCCP_PKT_CLOSE ||
type == DCCP_PKT_CLOSEREQ)
return sizeof(struct dccp_hdr_ack_bits);
if (type == DCCP_PKT_REQUEST)
return sizeof(struct dccp_hdr_request);
if (type == DCCP_PKT_RESPONSE)
return sizeof(struct dccp_hdr_response);
return sizeof(struct dccp_hdr_reset);
}
enum dccp_reset_codes {
DCCP_RESET_CODE_UNSPECIFIED = 0,
DCCP_RESET_CODE_CLOSED,
DCCP_RESET_CODE_ABORTED,
DCCP_RESET_CODE_NO_CONNECTION,
DCCP_RESET_CODE_PACKET_ERROR,
DCCP_RESET_CODE_OPTION_ERROR,
DCCP_RESET_CODE_MANDATORY_ERROR,
DCCP_RESET_CODE_CONNECTION_REFUSED,
DCCP_RESET_CODE_BAD_SERVICE_CODE,
DCCP_RESET_CODE_TOO_BUSY,
DCCP_RESET_CODE_BAD_INIT_COOKIE,
DCCP_RESET_CODE_AGGRESSION_PENALTY,
DCCP_MAX_RESET_CODES /* Leave at the end! */
};
/* DCCP options */
enum {
DCCPO_PADDING = 0,
DCCPO_MANDATORY = 1,
DCCPO_MIN_RESERVED = 3,
DCCPO_MAX_RESERVED = 31,
DCCPO_CHANGE_L = 32,
DCCPO_CONFIRM_L = 33,
DCCPO_CHANGE_R = 34,
DCCPO_CONFIRM_R = 35,
DCCPO_NDP_COUNT = 37,
DCCPO_ACK_VECTOR_0 = 38,
DCCPO_ACK_VECTOR_1 = 39,
DCCPO_TIMESTAMP = 41,
DCCPO_TIMESTAMP_ECHO = 42,
DCCPO_ELAPSED_TIME = 43,
DCCPO_MAX = 45,
DCCPO_MIN_RX_CCID_SPECIFIC = 128, /* from sender to receiver */
DCCPO_MAX_RX_CCID_SPECIFIC = 191,
DCCPO_MIN_TX_CCID_SPECIFIC = 192, /* from receiver to sender */
DCCPO_MAX_TX_CCID_SPECIFIC = 255,
};
/* maximum size of a single TLV-encoded DCCP option (sans type/len bytes) */
#define DCCP_SINGLE_OPT_MAXLEN 253
/* DCCP CCIDS */
enum {
DCCPC_CCID2 = 2,
DCCPC_CCID3 = 3,
};
/* DCCP features (RFC 4340 section 6.4) */
enum dccp_feature_numbers {
DCCPF_RESERVED = 0,
DCCPF_CCID = 1,
DCCPF_SHORT_SEQNOS = 2,
DCCPF_SEQUENCE_WINDOW = 3,
DCCPF_ECN_INCAPABLE = 4,
DCCPF_ACK_RATIO = 5,
DCCPF_SEND_ACK_VECTOR = 6,
DCCPF_SEND_NDP_COUNT = 7,
DCCPF_MIN_CSUM_COVER = 8,
DCCPF_DATA_CHECKSUM = 9,
/* 10-127 reserved */
DCCPF_MIN_CCID_SPECIFIC = 128,
DCCPF_SEND_LEV_RATE = 192, /* RFC 4342, sec. 8.4 */
DCCPF_MAX_CCID_SPECIFIC = 255,
};
/* DCCP socket control message types for cmsg */
enum dccp_cmsg_type {
DCCP_SCM_PRIORITY = 1,
DCCP_SCM_QPOLICY_MAX = 0xFFFF,
/* ^-- Up to here reserved exclusively for qpolicy parameters */
DCCP_SCM_MAX
};
/* DCCP priorities for outgoing/queued packets */
enum dccp_packet_dequeueing_policy {
DCCPQ_POLICY_SIMPLE,
DCCPQ_POLICY_PRIO,
DCCPQ_POLICY_MAX
};
/* DCCP socket options */
#define DCCP_SOCKOPT_PACKET_SIZE 1 /* XXX deprecated, without effect */
#define DCCP_SOCKOPT_SERVICE 2
#define DCCP_SOCKOPT_CHANGE_L 3
#define DCCP_SOCKOPT_CHANGE_R 4
#define DCCP_SOCKOPT_GET_CUR_MPS 5
#define DCCP_SOCKOPT_SERVER_TIMEWAIT 6
#define DCCP_SOCKOPT_SEND_CSCOV 10
#define DCCP_SOCKOPT_RECV_CSCOV 11
#define DCCP_SOCKOPT_AVAILABLE_CCIDS 12
#define DCCP_SOCKOPT_CCID 13
#define DCCP_SOCKOPT_TX_CCID 14
#define DCCP_SOCKOPT_RX_CCID 15
#define DCCP_SOCKOPT_QPOLICY_ID 16
#define DCCP_SOCKOPT_QPOLICY_TXQLEN 17
#define DCCP_SOCKOPT_CCID_RX_INFO 128
#define DCCP_SOCKOPT_CCID_TX_INFO 192
/* maximum number of services provided on the same listening port */
#define DCCP_SERVICE_LIST_MAX_LEN 32
#endif /* _UAPI_LINUX_DCCP_H */
| null | null | null | null | 116,700 |
43,824 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 43,824 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2015 The Chromium 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 "base/trace_event/memory_dump_request_args.h"
#include "base/logging.h"
namespace base {
namespace trace_event {
// static
const char* MemoryDumpTypeToString(const MemoryDumpType& dump_type) {
switch (dump_type) {
case MemoryDumpType::PERIODIC_INTERVAL:
return "periodic_interval";
case MemoryDumpType::EXPLICITLY_TRIGGERED:
return "explicitly_triggered";
case MemoryDumpType::PEAK_MEMORY_USAGE:
return "peak_memory_usage";
case MemoryDumpType::SUMMARY_ONLY:
return "summary_only";
}
NOTREACHED();
return "unknown";
}
MemoryDumpType StringToMemoryDumpType(const std::string& str) {
if (str == "periodic_interval")
return MemoryDumpType::PERIODIC_INTERVAL;
if (str == "explicitly_triggered")
return MemoryDumpType::EXPLICITLY_TRIGGERED;
if (str == "peak_memory_usage")
return MemoryDumpType::PEAK_MEMORY_USAGE;
if (str == "summary_only")
return MemoryDumpType::SUMMARY_ONLY;
NOTREACHED();
return MemoryDumpType::LAST;
}
const char* MemoryDumpLevelOfDetailToString(
const MemoryDumpLevelOfDetail& level_of_detail) {
switch (level_of_detail) {
case MemoryDumpLevelOfDetail::BACKGROUND:
return "background";
case MemoryDumpLevelOfDetail::LIGHT:
return "light";
case MemoryDumpLevelOfDetail::DETAILED:
return "detailed";
}
NOTREACHED();
return "unknown";
}
MemoryDumpLevelOfDetail StringToMemoryDumpLevelOfDetail(
const std::string& str) {
if (str == "background")
return MemoryDumpLevelOfDetail::BACKGROUND;
if (str == "light")
return MemoryDumpLevelOfDetail::LIGHT;
if (str == "detailed")
return MemoryDumpLevelOfDetail::DETAILED;
NOTREACHED();
return MemoryDumpLevelOfDetail::LAST;
}
} // namespace trace_event
} // namespace base
| null | null | null | null | 40,687 |
722 | null | train_val | 04b570817b2b38e35675b17328239746212f4c3f | 153,779 | FFmpeg | 0 | https://github.com/FFmpeg/FFmpeg | 2018-06-01 01:23:12+05:30 | /*
* Copyright (c) 2015 Muhammad Faiz <mfcc64@gmail.com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVFILTER_SHOWCQT_H
#define AVFILTER_SHOWCQT_H
#include "libavcodec/avfft.h"
#include "avfilter.h"
#include "internal.h"
typedef struct Coeffs {
FFTSample *val;
int start, len;
} Coeffs;
typedef struct RGBFloat {
float r, g, b;
} RGBFloat;
typedef struct YUVFloat {
float y, u, v;
} YUVFloat;
typedef union {
RGBFloat rgb;
YUVFloat yuv;
} ColorFloat;
typedef struct ShowCQTContext {
const AVClass *class;
AVFilterContext *ctx;
AVFrame *axis_frame;
AVFrame *sono_frame;
enum AVPixelFormat format;
int sono_idx;
int sono_count;
int step;
AVRational step_frac;
int remaining_frac;
int remaining_fill;
int remaining_fill_max;
int64_t next_pts;
double *freq;
FFTContext *fft_ctx;
Coeffs *coeffs;
FFTComplex *fft_data;
FFTComplex *fft_result;
FFTComplex *cqt_result;
float *attack_data;
int fft_bits;
int fft_len;
int cqt_len;
int cqt_align;
ColorFloat *c_buf;
float *h_buf;
float *rcp_h_buf;
float *sono_v_buf;
float *bar_v_buf;
float cmatrix[3][3];
float cscheme_v[6];
/* callback */
void (*cqt_calc)(FFTComplex *dst, const FFTComplex *src, const Coeffs *coeffs,
int len, int fft_len);
void (*permute_coeffs)(float *v, int len);
void (*draw_bar)(AVFrame *out, const float *h, const float *rcp_h,
const ColorFloat *c, int bar_h, float bar_t);
void (*draw_axis)(AVFrame *out, AVFrame *axis, const ColorFloat *c, int off);
void (*draw_sono)(AVFrame *out, AVFrame *sono, int off, int idx);
void (*update_sono)(AVFrame *sono, const ColorFloat *c, int idx);
/* performance debugging */
int64_t fft_time;
int64_t cqt_time;
int64_t process_cqt_time;
int64_t update_sono_time;
int64_t alloc_time;
int64_t bar_time;
int64_t axis_time;
int64_t sono_time;
/* option */
int width, height;
AVRational rate;
int bar_h;
int axis_h;
int sono_h;
int fullhd; /* deprecated */
char *sono_v;
char *bar_v;
float sono_g;
float bar_g;
float bar_t;
double timeclamp;
double attack;
double basefreq;
double endfreq;
float coeffclamp; /* deprecated - ignored */
char *tlength;
int count;
int fcount;
char *fontfile;
char *font;
char *fontcolor;
char *axisfile;
int axis;
int csp;
char *cscheme;
} ShowCQTContext;
void ff_showcqt_init_x86(ShowCQTContext *s);
#endif
| null | null | null | null | 69,834 |
42,295 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 42,295 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright (c) 2011 The Chromium 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 "base/at_exit.h"
#include <stddef.h>
#include <ostream>
#include <utility>
#include "base/bind.h"
#include "base/callback.h"
#include "base/logging.h"
namespace base {
// Keep a stack of registered AtExitManagers. We always operate on the most
// recent, and we should never have more than one outside of testing (for a
// statically linked version of this library). Testing may use the shadow
// version of the constructor, and if we are building a dynamic library we may
// end up with multiple AtExitManagers on the same process. We don't protect
// this for thread-safe access, since it will only be modified in testing.
static AtExitManager* g_top_manager = nullptr;
static bool g_disable_managers = false;
AtExitManager::AtExitManager()
: processing_callbacks_(false), next_manager_(g_top_manager) {
// If multiple modules instantiate AtExitManagers they'll end up living in this
// module... they have to coexist.
#if !defined(COMPONENT_BUILD)
DCHECK(!g_top_manager);
#endif
g_top_manager = this;
}
AtExitManager::~AtExitManager() {
if (!g_top_manager) {
NOTREACHED() << "Tried to ~AtExitManager without an AtExitManager";
return;
}
DCHECK_EQ(this, g_top_manager);
if (!g_disable_managers)
ProcessCallbacksNow();
g_top_manager = next_manager_;
}
// static
void AtExitManager::RegisterCallback(AtExitCallbackType func, void* param) {
DCHECK(func);
RegisterTask(base::Bind(func, param));
}
// static
void AtExitManager::RegisterTask(base::Closure task) {
if (!g_top_manager) {
NOTREACHED() << "Tried to RegisterCallback without an AtExitManager";
return;
}
AutoLock lock(g_top_manager->lock_);
DCHECK(!g_top_manager->processing_callbacks_);
g_top_manager->stack_.push(std::move(task));
}
// static
void AtExitManager::ProcessCallbacksNow() {
if (!g_top_manager) {
NOTREACHED() << "Tried to ProcessCallbacksNow without an AtExitManager";
return;
}
// Callbacks may try to add new callbacks, so run them without holding
// |lock_|. This is an error and caught by the DCHECK in RegisterTask(), but
// handle it gracefully in release builds so we don't deadlock.
base::stack<base::Closure> tasks;
{
AutoLock lock(g_top_manager->lock_);
tasks.swap(g_top_manager->stack_);
g_top_manager->processing_callbacks_ = true;
}
// Relax the cross-thread access restriction to non-thread-safe RefCount.
// It's safe since all other threads should be terminated at this point.
ScopedAllowCrossThreadRefCountAccess allow_cross_thread_ref_count_access;
while (!tasks.empty()) {
base::Closure task = tasks.top();
task.Run();
tasks.pop();
}
// Expect that all callbacks have been run.
DCHECK(g_top_manager->stack_.empty());
}
void AtExitManager::DisableAllAtExitManagers() {
AutoLock lock(g_top_manager->lock_);
g_disable_managers = true;
}
AtExitManager::AtExitManager(bool shadow)
: processing_callbacks_(false), next_manager_(g_top_manager) {
DCHECK(shadow || !g_top_manager);
g_top_manager = this;
}
} // namespace base
| null | null | null | null | 39,158 |
37,622 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 37,622 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | /*
* Copyright (C) 2011 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "third_party/blink/renderer/platform/text/text_run.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/text/character.h"
namespace blink {
struct ExpectedTextRunSize {
DISALLOW_NEW();
const void* pointer;
int integers[2];
float floats[2];
uint32_t bitfields : 10;
TabSize tab_size;
};
static_assert(sizeof(TextRun) == sizeof(ExpectedTextRunSize),
"TextRun should have expected size");
void TextRun::SetText(const String& string) {
len_ = string.length();
if (!len_) {
data_.characters8 = nullptr;
is8_bit_ = true;
return;
}
is8_bit_ = string.Is8Bit();
if (is8_bit_)
data_.characters8 = string.Characters8();
else
data_.characters16 = string.Characters16();
}
std::unique_ptr<UChar[]> TextRun::NormalizedUTF16(
unsigned* result_length) const {
const UChar* source;
String string_for8_bit_run;
if (Is8Bit()) {
string_for8_bit_run =
String::Make16BitFrom8BitSource(Characters8(), length());
source = string_for8_bit_run.Characters16();
} else {
source = Characters16();
}
auto buffer = std::make_unique<UChar[]>(len_ + 1);
*result_length = 0;
bool error = false;
unsigned position = 0;
while (position < len_) {
UChar32 character;
U16_NEXT(source, position, len_, character);
// Don't normalize tabs as they are not treated as spaces for word-end.
if (NormalizeSpace() &&
Character::IsNormalizedCanvasSpaceCharacter(character)) {
character = kSpaceCharacter;
} else if (Character::TreatAsSpace(character) &&
character != kNoBreakSpaceCharacter) {
character = kSpaceCharacter;
} else if (!RuntimeEnabledFeatures::
RenderUnicodeControlCharactersEnabled() &&
Character::LegacyTreatAsZeroWidthSpaceInComplexScript(
character)) {
character = kZeroWidthSpaceCharacter;
} else if (Character::TreatAsZeroWidthSpaceInComplexScript(character)) {
character = kZeroWidthSpaceCharacter;
}
U16_APPEND(buffer, *result_length, len_, character, error);
DCHECK(!error);
}
DCHECK(*result_length <= len_);
return buffer;
}
unsigned TextRun::IndexOfSubRun(const TextRun& sub_run) const {
if (Is8Bit() == sub_run.Is8Bit() && sub_run.Bytes() >= Bytes()) {
size_t start_index = Is8Bit() ? sub_run.Characters8() - Characters8()
: sub_run.Characters16() - Characters16();
if (start_index + sub_run.length() <= length())
return start_index;
}
return std::numeric_limits<unsigned>::max();
}
} // namespace blink
| null | null | null | null | 34,485 |
29,154 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 194,149 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | /*
* Driver for the Analog Devices digital potentiometers
*
* Copyright (C) 2010 Michael Hennerich, Analog Devices Inc.
*
* Licensed under the GPL-2 or later.
*/
#ifndef _AD_DPOT_H_
#define _AD_DPOT_H_
#include <linux/types.h>
#define DPOT_CONF(features, wipers, max_pos, uid) \
(((features) << 18) | (((wipers) & 0xFF) << 10) | \
((max_pos & 0xF) << 6) | (uid & 0x3F))
#define DPOT_UID(conf) (conf & 0x3F)
#define DPOT_MAX_POS(conf) ((conf >> 6) & 0xF)
#define DPOT_WIPERS(conf) ((conf >> 10) & 0xFF)
#define DPOT_FEAT(conf) (conf >> 18)
#define BRDAC0 (1 << 0)
#define BRDAC1 (1 << 1)
#define BRDAC2 (1 << 2)
#define BRDAC3 (1 << 3)
#define BRDAC4 (1 << 4)
#define BRDAC5 (1 << 5)
#define MAX_RDACS 6
#define F_CMD_INC (1 << 0) /* Features INC/DEC ALL, 6dB */
#define F_CMD_EEP (1 << 1) /* Features EEPROM */
#define F_CMD_OTP (1 << 2) /* Features OTP */
#define F_CMD_TOL (1 << 3) /* RDACS feature Tolerance REG */
#define F_RDACS_RW (1 << 4) /* RDACS are Read/Write */
#define F_RDACS_WONLY (1 << 5) /* RDACS are Write only */
#define F_AD_APPDATA (1 << 6) /* RDAC Address append to data */
#define F_SPI_8BIT (1 << 7) /* All SPI XFERS are 8-bit */
#define F_SPI_16BIT (1 << 8) /* All SPI XFERS are 16-bit */
#define F_SPI_24BIT (1 << 9) /* All SPI XFERS are 24-bit */
#define F_RDACS_RW_TOL (F_RDACS_RW | F_CMD_EEP | F_CMD_TOL)
#define F_RDACS_RW_EEP (F_RDACS_RW | F_CMD_EEP)
#define F_SPI (F_SPI_8BIT | F_SPI_16BIT | F_SPI_24BIT)
enum dpot_devid {
AD5258_ID = DPOT_CONF(F_RDACS_RW_TOL, BRDAC0, 6, 0), /* I2C */
AD5259_ID = DPOT_CONF(F_RDACS_RW_TOL, BRDAC0, 8, 1),
AD5251_ID = DPOT_CONF(F_RDACS_RW_TOL | F_CMD_INC,
BRDAC1 | BRDAC3, 6, 2),
AD5252_ID = DPOT_CONF(F_RDACS_RW_TOL | F_CMD_INC,
BRDAC1 | BRDAC3, 8, 3),
AD5253_ID = DPOT_CONF(F_RDACS_RW_TOL | F_CMD_INC,
BRDAC0 | BRDAC1 | BRDAC2 | BRDAC3, 6, 4),
AD5254_ID = DPOT_CONF(F_RDACS_RW_TOL | F_CMD_INC,
BRDAC0 | BRDAC1 | BRDAC2 | BRDAC3, 8, 5),
AD5255_ID = DPOT_CONF(F_RDACS_RW_TOL | F_CMD_INC,
BRDAC0 | BRDAC1 | BRDAC2, 9, 6),
AD5160_ID = DPOT_CONF(F_RDACS_WONLY | F_AD_APPDATA | F_SPI_8BIT,
BRDAC0, 8, 7), /* SPI */
AD5161_ID = DPOT_CONF(F_RDACS_WONLY | F_AD_APPDATA | F_SPI_8BIT,
BRDAC0, 8, 8),
AD5162_ID = DPOT_CONF(F_RDACS_WONLY | F_AD_APPDATA | F_SPI_16BIT,
BRDAC0 | BRDAC1, 8, 9),
AD5165_ID = DPOT_CONF(F_RDACS_WONLY | F_AD_APPDATA | F_SPI_8BIT,
BRDAC0, 8, 10),
AD5200_ID = DPOT_CONF(F_RDACS_WONLY | F_AD_APPDATA | F_SPI_8BIT,
BRDAC0, 8, 11),
AD5201_ID = DPOT_CONF(F_RDACS_WONLY | F_AD_APPDATA | F_SPI_8BIT,
BRDAC0, 5, 12),
AD5203_ID = DPOT_CONF(F_RDACS_WONLY | F_AD_APPDATA | F_SPI_8BIT,
BRDAC0 | BRDAC1 | BRDAC2 | BRDAC3, 6, 13),
AD5204_ID = DPOT_CONF(F_RDACS_WONLY | F_AD_APPDATA | F_SPI_16BIT,
BRDAC0 | BRDAC1 | BRDAC2 | BRDAC3, 8, 14),
AD5206_ID = DPOT_CONF(F_RDACS_WONLY | F_AD_APPDATA | F_SPI_16BIT,
BRDAC0 | BRDAC1 | BRDAC2 | BRDAC3 | BRDAC4 | BRDAC5,
8, 15),
AD5207_ID = DPOT_CONF(F_RDACS_WONLY | F_AD_APPDATA | F_SPI_16BIT,
BRDAC0 | BRDAC1, 8, 16),
AD5231_ID = DPOT_CONF(F_RDACS_RW_EEP | F_CMD_INC | F_SPI_24BIT,
BRDAC0, 10, 17),
AD5232_ID = DPOT_CONF(F_RDACS_RW_EEP | F_CMD_INC | F_SPI_16BIT,
BRDAC0 | BRDAC1, 8, 18),
AD5233_ID = DPOT_CONF(F_RDACS_RW_EEP | F_CMD_INC | F_SPI_16BIT,
BRDAC0 | BRDAC1 | BRDAC2 | BRDAC3, 6, 19),
AD5235_ID = DPOT_CONF(F_RDACS_RW_EEP | F_CMD_INC | F_SPI_24BIT,
BRDAC0 | BRDAC1, 10, 20),
AD5260_ID = DPOT_CONF(F_RDACS_WONLY | F_AD_APPDATA | F_SPI_8BIT,
BRDAC0, 8, 21),
AD5262_ID = DPOT_CONF(F_RDACS_WONLY | F_AD_APPDATA | F_SPI_16BIT,
BRDAC0 | BRDAC1, 8, 22),
AD5263_ID = DPOT_CONF(F_RDACS_WONLY | F_AD_APPDATA | F_SPI_16BIT,
BRDAC0 | BRDAC1 | BRDAC2 | BRDAC3, 8, 23),
AD5290_ID = DPOT_CONF(F_RDACS_WONLY | F_AD_APPDATA | F_SPI_8BIT,
BRDAC0, 8, 24),
AD5291_ID = DPOT_CONF(F_RDACS_RW | F_SPI_16BIT | F_CMD_OTP,
BRDAC0, 8, 25),
AD5292_ID = DPOT_CONF(F_RDACS_RW | F_SPI_16BIT | F_CMD_OTP,
BRDAC0, 10, 26),
AD5293_ID = DPOT_CONF(F_RDACS_RW | F_SPI_16BIT, BRDAC0, 10, 27),
AD7376_ID = DPOT_CONF(F_RDACS_WONLY | F_AD_APPDATA | F_SPI_8BIT,
BRDAC0, 7, 28),
AD8400_ID = DPOT_CONF(F_RDACS_WONLY | F_AD_APPDATA | F_SPI_16BIT,
BRDAC0, 8, 29),
AD8402_ID = DPOT_CONF(F_RDACS_WONLY | F_AD_APPDATA | F_SPI_16BIT,
BRDAC0 | BRDAC1, 8, 30),
AD8403_ID = DPOT_CONF(F_RDACS_WONLY | F_AD_APPDATA | F_SPI_16BIT,
BRDAC0 | BRDAC1 | BRDAC2, 8, 31),
ADN2850_ID = DPOT_CONF(F_RDACS_RW_EEP | F_CMD_INC | F_SPI_24BIT,
BRDAC0 | BRDAC1, 10, 32),
AD5241_ID = DPOT_CONF(F_RDACS_RW, BRDAC0, 8, 33),
AD5242_ID = DPOT_CONF(F_RDACS_RW, BRDAC0 | BRDAC1, 8, 34),
AD5243_ID = DPOT_CONF(F_RDACS_RW, BRDAC0 | BRDAC1, 8, 35),
AD5245_ID = DPOT_CONF(F_RDACS_RW, BRDAC0, 8, 36),
AD5246_ID = DPOT_CONF(F_RDACS_RW, BRDAC0, 7, 37),
AD5247_ID = DPOT_CONF(F_RDACS_RW, BRDAC0, 7, 38),
AD5248_ID = DPOT_CONF(F_RDACS_RW, BRDAC0 | BRDAC1, 8, 39),
AD5280_ID = DPOT_CONF(F_RDACS_RW, BRDAC0, 8, 40),
AD5282_ID = DPOT_CONF(F_RDACS_RW, BRDAC0 | BRDAC1, 8, 41),
ADN2860_ID = DPOT_CONF(F_RDACS_RW_TOL | F_CMD_INC,
BRDAC0 | BRDAC1 | BRDAC2, 9, 42),
AD5273_ID = DPOT_CONF(F_RDACS_RW | F_CMD_OTP, BRDAC0, 6, 43),
AD5171_ID = DPOT_CONF(F_RDACS_RW | F_CMD_OTP, BRDAC0, 6, 44),
AD5170_ID = DPOT_CONF(F_RDACS_RW | F_CMD_OTP, BRDAC0, 8, 45),
AD5172_ID = DPOT_CONF(F_RDACS_RW | F_CMD_OTP, BRDAC0 | BRDAC1, 8, 46),
AD5173_ID = DPOT_CONF(F_RDACS_RW | F_CMD_OTP, BRDAC0 | BRDAC1, 8, 47),
AD5270_ID = DPOT_CONF(F_RDACS_RW | F_CMD_OTP | F_SPI_16BIT,
BRDAC0, 10, 48),
AD5271_ID = DPOT_CONF(F_RDACS_RW | F_CMD_OTP | F_SPI_16BIT,
BRDAC0, 8, 49),
AD5272_ID = DPOT_CONF(F_RDACS_RW | F_CMD_OTP, BRDAC0, 10, 50),
AD5274_ID = DPOT_CONF(F_RDACS_RW | F_CMD_OTP, BRDAC0, 8, 51),
};
#define DPOT_RDAC0 0
#define DPOT_RDAC1 1
#define DPOT_RDAC2 2
#define DPOT_RDAC3 3
#define DPOT_RDAC4 4
#define DPOT_RDAC5 5
#define DPOT_RDAC_MASK 0x1F
#define DPOT_REG_TOL 0x18
#define DPOT_TOL_RDAC0 (DPOT_REG_TOL | DPOT_RDAC0)
#define DPOT_TOL_RDAC1 (DPOT_REG_TOL | DPOT_RDAC1)
#define DPOT_TOL_RDAC2 (DPOT_REG_TOL | DPOT_RDAC2)
#define DPOT_TOL_RDAC3 (DPOT_REG_TOL | DPOT_RDAC3)
#define DPOT_TOL_RDAC4 (DPOT_REG_TOL | DPOT_RDAC4)
#define DPOT_TOL_RDAC5 (DPOT_REG_TOL | DPOT_RDAC5)
/* RDAC-to-EEPROM Interface Commands */
#define DPOT_ADDR_RDAC (0x0 << 5)
#define DPOT_ADDR_EEPROM (0x1 << 5)
#define DPOT_ADDR_OTP (0x1 << 6)
#define DPOT_ADDR_CMD (0x1 << 7)
#define DPOT_ADDR_OTP_EN (0x1 << 9)
#define DPOT_DEC_ALL_6DB (DPOT_ADDR_CMD | (0x4 << 3))
#define DPOT_INC_ALL_6DB (DPOT_ADDR_CMD | (0x9 << 3))
#define DPOT_DEC_ALL (DPOT_ADDR_CMD | (0x6 << 3))
#define DPOT_INC_ALL (DPOT_ADDR_CMD | (0xB << 3))
#define DPOT_SPI_RDAC 0xB0
#define DPOT_SPI_EEPROM 0x30
#define DPOT_SPI_READ_RDAC 0xA0
#define DPOT_SPI_READ_EEPROM 0x90
#define DPOT_SPI_DEC_ALL_6DB 0x50
#define DPOT_SPI_INC_ALL_6DB 0xD0
#define DPOT_SPI_DEC_ALL 0x70
#define DPOT_SPI_INC_ALL 0xF0
/* AD5291/2/3 use special commands */
#define DPOT_AD5291_RDAC 0x01
#define DPOT_AD5291_READ_RDAC 0x02
#define DPOT_AD5291_STORE_XTPM 0x03
#define DPOT_AD5291_CTRLREG 0x06
#define DPOT_AD5291_UNLOCK_CMD 0x03
/* AD5270/1/2/4 use special commands */
#define DPOT_AD5270_1_2_4_RDAC 0x01
#define DPOT_AD5270_1_2_4_READ_RDAC 0x02
#define DPOT_AD5270_1_2_4_STORE_XTPM 0x03
#define DPOT_AD5270_1_2_4_CTRLREG 0x07
#define DPOT_AD5270_1_2_4_UNLOCK_CMD 0x03
#define DPOT_AD5282_RDAC_AB 0x80
#define DPOT_AD5273_FUSE 0x80
#define DPOT_AD5170_2_3_FUSE 0x20
#define DPOT_AD5170_2_3_OW 0x08
#define DPOT_AD5172_3_A0 0x08
#define DPOT_AD5170_2FUSE 0x80
struct dpot_data;
struct ad_dpot_bus_ops {
int (*read_d8) (void *client);
int (*read_r8d8) (void *client, u8 reg);
int (*read_r8d16) (void *client, u8 reg);
int (*write_d8) (void *client, u8 val);
int (*write_r8d8) (void *client, u8 reg, u8 val);
int (*write_r8d16) (void *client, u8 reg, u16 val);
};
struct ad_dpot_bus_data {
void *client;
const struct ad_dpot_bus_ops *bops;
};
int ad_dpot_probe(struct device *dev, struct ad_dpot_bus_data *bdata,
unsigned long devid, const char *name);
int ad_dpot_remove(struct device *dev);
#endif
| null | null | null | null | 102,496 |
25,052 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 25,052 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2018 The Chromium 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 EXTENSIONS_COMMON_EXTENSION_UPDATER_UMA_H_
#define EXTENSIONS_COMMON_EXTENSION_UPDATER_UMA_H_
namespace extensions {
// These enum values are used in UMA, they should NOT be reordered.
enum class ExtensionUpdaterUpdateResult {
NO_UPDATE = 0,
UPDATE_SUCCESS = 1,
UPDATE_ERROR = 2,
UPDATE_RESULT_COUNT
};
} // namespace extensions
#endif // EXTENSIONS_COMMON_EXTENSION_UPDATER_UMA_H_
| null | null | null | null | 21,915 |
42,462 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 42,462 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright (c) 2012 The Chromium 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 BASE_THREADING_THREAD_ID_NAME_MANAGER_H_
#define BASE_THREADING_THREAD_ID_NAME_MANAGER_H_
#include <map>
#include <string>
#include "base/base_export.h"
#include "base/callback.h"
#include "base/macros.h"
#include "base/synchronization/lock.h"
#include "base/threading/platform_thread.h"
namespace base {
template <typename T>
struct DefaultSingletonTraits;
class BASE_EXPORT ThreadIdNameManager {
public:
static ThreadIdNameManager* GetInstance();
static const char* GetDefaultInternedString();
// Register the mapping between a thread |id| and |handle|.
void RegisterThread(PlatformThreadHandle::Handle handle, PlatformThreadId id);
// The callback is called on the thread, immediately after the name is set.
// |name| is a pointer to a C string that is guaranteed to remain valid for
// the duration of the process.
using SetNameCallback = base::RepeatingCallback<void(const char* name)>;
void InstallSetNameCallback(SetNameCallback callback);
// Set the name for the current thread.
void SetName(const std::string& name);
// Get the name for the given id.
const char* GetName(PlatformThreadId id);
// Unlike |GetName|, this method using TLS and avoids touching |lock_|.
const char* GetNameForCurrentThread();
// Remove the name for the given id.
void RemoveName(PlatformThreadHandle::Handle handle, PlatformThreadId id);
private:
friend struct DefaultSingletonTraits<ThreadIdNameManager>;
typedef std::map<PlatformThreadId, PlatformThreadHandle::Handle>
ThreadIdToHandleMap;
typedef std::map<PlatformThreadHandle::Handle, std::string*>
ThreadHandleToInternedNameMap;
typedef std::map<std::string, std::string*> NameToInternedNameMap;
ThreadIdNameManager();
~ThreadIdNameManager();
// lock_ protects the name_to_interned_name_, thread_id_to_handle_ and
// thread_handle_to_interned_name_ maps.
Lock lock_;
NameToInternedNameMap name_to_interned_name_;
ThreadIdToHandleMap thread_id_to_handle_;
ThreadHandleToInternedNameMap thread_handle_to_interned_name_;
// Treat the main process specially as there is no PlatformThreadHandle.
std::string* main_process_name_;
PlatformThreadId main_process_id_;
SetNameCallback set_name_callback_;
DISALLOW_COPY_AND_ASSIGN(ThreadIdNameManager);
};
} // namespace base
#endif // BASE_THREADING_THREAD_ID_NAME_MANAGER_H_
| null | null | null | null | 39,325 |
34,995 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 199,990 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | /*
* ImgTec IR Decoder found in PowerDown Controller.
*
* Copyright 2010-2014 Imagination Technologies Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#ifndef _IMG_IR_H_
#define _IMG_IR_H_
#include <linux/io.h>
#include <linux/spinlock.h>
#include "img-ir-raw.h"
#include "img-ir-hw.h"
/* registers */
/* relative to the start of the IR block of registers */
#define IMG_IR_CONTROL 0x00
#define IMG_IR_STATUS 0x04
#define IMG_IR_DATA_LW 0x08
#define IMG_IR_DATA_UP 0x0c
#define IMG_IR_LEAD_SYMB_TIMING 0x10
#define IMG_IR_S00_SYMB_TIMING 0x14
#define IMG_IR_S01_SYMB_TIMING 0x18
#define IMG_IR_S10_SYMB_TIMING 0x1c
#define IMG_IR_S11_SYMB_TIMING 0x20
#define IMG_IR_FREE_SYMB_TIMING 0x24
#define IMG_IR_POW_MOD_PARAMS 0x28
#define IMG_IR_POW_MOD_ENABLE 0x2c
#define IMG_IR_IRQ_MSG_DATA_LW 0x30
#define IMG_IR_IRQ_MSG_DATA_UP 0x34
#define IMG_IR_IRQ_MSG_MASK_LW 0x38
#define IMG_IR_IRQ_MSG_MASK_UP 0x3c
#define IMG_IR_IRQ_ENABLE 0x40
#define IMG_IR_IRQ_STATUS 0x44
#define IMG_IR_IRQ_CLEAR 0x48
#define IMG_IR_IRCORE_ID 0xf0
#define IMG_IR_CORE_REV 0xf4
#define IMG_IR_CORE_DES1 0xf8
#define IMG_IR_CORE_DES2 0xfc
/* field masks */
/* IMG_IR_CONTROL */
#define IMG_IR_DECODEN 0x40000000
#define IMG_IR_CODETYPE 0x30000000
#define IMG_IR_CODETYPE_SHIFT 28
#define IMG_IR_HDRTOG 0x08000000
#define IMG_IR_LDRDEC 0x04000000
#define IMG_IR_DECODINPOL 0x02000000 /* active high */
#define IMG_IR_BITORIEN 0x01000000 /* MSB first */
#define IMG_IR_D1VALIDSEL 0x00008000
#define IMG_IR_BITINV 0x00000040 /* don't invert */
#define IMG_IR_DECODEND2 0x00000010
#define IMG_IR_BITORIEND2 0x00000002 /* MSB first */
#define IMG_IR_BITINVD2 0x00000001 /* don't invert */
/* IMG_IR_STATUS */
#define IMG_IR_RXDVALD2 0x00001000
#define IMG_IR_IRRXD 0x00000400
#define IMG_IR_TOGSTATE 0x00000200
#define IMG_IR_RXDVAL 0x00000040
#define IMG_IR_RXDLEN 0x0000003f
#define IMG_IR_RXDLEN_SHIFT 0
/* IMG_IR_LEAD_SYMB_TIMING, IMG_IR_Sxx_SYMB_TIMING */
#define IMG_IR_PD_MAX 0xff000000
#define IMG_IR_PD_MAX_SHIFT 24
#define IMG_IR_PD_MIN 0x00ff0000
#define IMG_IR_PD_MIN_SHIFT 16
#define IMG_IR_W_MAX 0x0000ff00
#define IMG_IR_W_MAX_SHIFT 8
#define IMG_IR_W_MIN 0x000000ff
#define IMG_IR_W_MIN_SHIFT 0
/* IMG_IR_FREE_SYMB_TIMING */
#define IMG_IR_MAXLEN 0x0007e000
#define IMG_IR_MAXLEN_SHIFT 13
#define IMG_IR_MINLEN 0x00001f00
#define IMG_IR_MINLEN_SHIFT 8
#define IMG_IR_FT_MIN 0x000000ff
#define IMG_IR_FT_MIN_SHIFT 0
/* IMG_IR_POW_MOD_PARAMS */
#define IMG_IR_PERIOD_LEN 0x3f000000
#define IMG_IR_PERIOD_LEN_SHIFT 24
#define IMG_IR_PERIOD_DUTY 0x003f0000
#define IMG_IR_PERIOD_DUTY_SHIFT 16
#define IMG_IR_STABLE_STOP 0x00003f00
#define IMG_IR_STABLE_STOP_SHIFT 8
#define IMG_IR_STABLE_START 0x0000003f
#define IMG_IR_STABLE_START_SHIFT 0
/* IMG_IR_POW_MOD_ENABLE */
#define IMG_IR_POWER_OUT_EN 0x00000002
#define IMG_IR_POWER_MOD_EN 0x00000001
/* IMG_IR_IRQ_ENABLE, IMG_IR_IRQ_STATUS, IMG_IR_IRQ_CLEAR */
#define IMG_IR_IRQ_DEC2_ERR 0x00000080
#define IMG_IR_IRQ_DEC_ERR 0x00000040
#define IMG_IR_IRQ_ACT_LEVEL 0x00000020
#define IMG_IR_IRQ_FALL_EDGE 0x00000010
#define IMG_IR_IRQ_RISE_EDGE 0x00000008
#define IMG_IR_IRQ_DATA_MATCH 0x00000004
#define IMG_IR_IRQ_DATA2_VALID 0x00000002
#define IMG_IR_IRQ_DATA_VALID 0x00000001
#define IMG_IR_IRQ_ALL 0x000000ff
#define IMG_IR_IRQ_EDGE (IMG_IR_IRQ_FALL_EDGE | IMG_IR_IRQ_RISE_EDGE)
/* IMG_IR_CORE_ID */
#define IMG_IR_CORE_ID 0x00ff0000
#define IMG_IR_CORE_ID_SHIFT 16
#define IMG_IR_CORE_CONFIG 0x0000ffff
#define IMG_IR_CORE_CONFIG_SHIFT 0
/* IMG_IR_CORE_REV */
#define IMG_IR_DESIGNER 0xff000000
#define IMG_IR_DESIGNER_SHIFT 24
#define IMG_IR_MAJOR_REV 0x00ff0000
#define IMG_IR_MAJOR_REV_SHIFT 16
#define IMG_IR_MINOR_REV 0x0000ff00
#define IMG_IR_MINOR_REV_SHIFT 8
#define IMG_IR_MAINT_REV 0x000000ff
#define IMG_IR_MAINT_REV_SHIFT 0
struct device;
struct clk;
/**
* struct img_ir_priv - Private driver data.
* @dev: Platform device.
* @irq: IRQ number.
* @clk: Input clock.
* @sys_clk: System clock.
* @reg_base: Iomem base address of IR register block.
* @lock: Protects IR registers and variables in this struct.
* @raw: Driver data for raw decoder.
* @hw: Driver data for hardware decoder.
*/
struct img_ir_priv {
struct device *dev;
int irq;
struct clk *clk;
struct clk *sys_clk;
void __iomem *reg_base;
spinlock_t lock;
struct img_ir_priv_raw raw;
struct img_ir_priv_hw hw;
};
/* Hardware access */
static inline void img_ir_write(struct img_ir_priv *priv,
unsigned int reg_offs, unsigned int data)
{
iowrite32(data, priv->reg_base + reg_offs);
}
static inline unsigned int img_ir_read(struct img_ir_priv *priv,
unsigned int reg_offs)
{
return ioread32(priv->reg_base + reg_offs);
}
#endif /* _IMG_IR_H_ */
| null | null | null | null | 108,337 |
50,159 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 50,159 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2013 The Chromium 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 "ui/base/dragdrop/os_exchange_data_provider_aurax11.h"
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_task_environment.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/dragdrop/file_info.h"
#include "ui/events/platform/x11/x11_event_source_glib.h"
#include "ui/gfx/x/x11_atom_cache.h"
#include "url/gurl.h"
const char kFileURL[] = "file:///home/user/file.txt";
const char kFileName[] = "/home/user/file.txt";
const char kGoogleTitle[] = "Google";
const char kGoogleURL[] = "http://www.google.com/";
namespace ui {
class OSExchangeDataProviderAuraX11Test : public testing::Test {
public:
OSExchangeDataProviderAuraX11Test()
: scoped_task_environment_(
base::test::ScopedTaskEnvironment::MainThreadType::UI),
event_source(gfx::GetXDisplay()) {}
void AddURLList(const std::string& list_contents) {
std::string contents_copy = list_contents;
scoped_refptr<base::RefCountedMemory> mem(
base::RefCountedString::TakeString(&contents_copy));
provider.format_map_.Insert(gfx::GetAtom(ui::Clipboard::kMimeTypeURIList),
mem);
}
protected:
base::test::ScopedTaskEnvironment scoped_task_environment_;
X11EventSourceGlib event_source;
ui::OSExchangeDataProviderAuraX11 provider;
};
TEST_F(OSExchangeDataProviderAuraX11Test, MozillaURL) {
// Check that we can get titled entries.
provider.SetURL(GURL(kGoogleURL), base::ASCIIToUTF16(kGoogleTitle));
{
GURL out_gurl;
base::string16 out_str;
EXPECT_TRUE(provider.GetURLAndTitle(
OSExchangeData::DO_NOT_CONVERT_FILENAMES, &out_gurl, &out_str));
EXPECT_EQ(base::ASCIIToUTF16(kGoogleTitle), out_str);
EXPECT_EQ(kGoogleURL, out_gurl.spec());
}
// Check that we can get non-titled entries.
provider.SetURL(GURL(kGoogleURL), base::string16());
{
GURL out_gurl;
base::string16 out_str;
EXPECT_TRUE(provider.GetURLAndTitle(
OSExchangeData::DO_NOT_CONVERT_FILENAMES, &out_gurl, &out_str));
EXPECT_EQ(base::string16(), out_str);
EXPECT_EQ(kGoogleURL, out_gurl.spec());
}
}
TEST_F(OSExchangeDataProviderAuraX11Test, FilesArentURLs) {
AddURLList(kFileURL);
EXPECT_TRUE(provider.HasFile());
EXPECT_TRUE(provider.HasURL(ui::OSExchangeData::CONVERT_FILENAMES));
EXPECT_FALSE(provider.HasURL(ui::OSExchangeData::DO_NOT_CONVERT_FILENAMES));
}
TEST_F(OSExchangeDataProviderAuraX11Test, HTTPURLsArentFiles) {
AddURLList(kGoogleURL);
EXPECT_FALSE(provider.HasFile());
EXPECT_TRUE(provider.HasURL(ui::OSExchangeData::CONVERT_FILENAMES));
EXPECT_TRUE(provider.HasURL(ui::OSExchangeData::DO_NOT_CONVERT_FILENAMES));
}
TEST_F(OSExchangeDataProviderAuraX11Test, URIListWithBoth) {
AddURLList("file:///home/user/file.txt\nhttp://www.google.com");
EXPECT_TRUE(provider.HasFile());
EXPECT_TRUE(provider.HasURL(ui::OSExchangeData::CONVERT_FILENAMES));
EXPECT_TRUE(provider.HasURL(ui::OSExchangeData::DO_NOT_CONVERT_FILENAMES));
// We should only receive the file from GetFilenames().
std::vector<FileInfo> filenames;
EXPECT_TRUE(provider.GetFilenames(&filenames));
ASSERT_EQ(1u, filenames.size());
EXPECT_EQ(kFileName, filenames[0].path.value());
// We should only receive the URL here.
GURL out_gurl;
base::string16 out_str;
EXPECT_TRUE(provider.GetURLAndTitle(
OSExchangeData::DO_NOT_CONVERT_FILENAMES, &out_gurl, &out_str));
EXPECT_EQ(base::string16(), out_str);
EXPECT_EQ(kGoogleURL, out_gurl.spec());
}
TEST_F(OSExchangeDataProviderAuraX11Test, OnlyStringURLIsUnfiltered) {
const base::string16 file_url = base::UTF8ToUTF16(kFileURL);
provider.SetString(file_url);
EXPECT_TRUE(provider.HasString());
EXPECT_FALSE(provider.HasURL(ui::OSExchangeData::DO_NOT_CONVERT_FILENAMES));
}
TEST_F(OSExchangeDataProviderAuraX11Test, StringAndURIListFilterString) {
const base::string16 file_url = base::UTF8ToUTF16(kFileURL);
provider.SetString(file_url);
AddURLList(kFileURL);
EXPECT_FALSE(provider.HasString());
base::string16 out_str;
EXPECT_FALSE(provider.GetString(&out_str));
EXPECT_TRUE(provider.HasFile());
}
} // namespace ui
| null | null | null | null | 47,022 |
23,634 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 23,634 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2014 The Chromium 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 CONTENT_BROWSER_CACHE_STORAGE_CACHE_STORAGE_QUOTA_CLIENT_H_
#define CONTENT_BROWSER_CACHE_STORAGE_CACHE_STORAGE_QUOTA_CLIENT_H_
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "content/common/content_export.h"
#include "storage/browser/quota/quota_client.h"
#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
#include "url/origin.h"
namespace content {
class CacheStorageManager;
// CacheStorageQuotaClient is owned by the QuotaManager. There is one per
// CacheStorageManager, and therefore one per
// ServiceWorkerContextCore.
class CONTENT_EXPORT CacheStorageQuotaClient : public storage::QuotaClient {
public:
explicit CacheStorageQuotaClient(
base::WeakPtr<CacheStorageManager> cache_manager);
~CacheStorageQuotaClient() override;
// QuotaClient overrides
ID id() const override;
void OnQuotaManagerDestroyed() override;
void GetOriginUsage(const url::Origin& origin,
blink::mojom::StorageType type,
GetUsageCallback callback) override;
void GetOriginsForType(blink::mojom::StorageType type,
GetOriginsCallback callback) override;
void GetOriginsForHost(blink::mojom::StorageType type,
const std::string& host,
GetOriginsCallback callback) override;
void DeleteOriginData(const url::Origin& origin,
blink::mojom::StorageType type,
DeletionCallback callback) override;
bool DoesSupport(blink::mojom::StorageType type) const override;
private:
base::WeakPtr<CacheStorageManager> cache_manager_;
DISALLOW_COPY_AND_ASSIGN(CacheStorageQuotaClient);
};
} // namespace content
#endif // CONTENT_BROWSER_CACHE_STORAGE_CACHE_STORAGE_QUOTA_CLIENT_H_
| null | null | null | null | 20,497 |
8,825 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 8,825 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2014 The Chromium 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 "net/ssl/channel_id_service.h"
#include <memory>
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/task_runner.h"
#include "base/test/null_task_runner.h"
#include "base/test/scoped_task_environment.h"
#include "base/threading/thread_task_runner_handle.h"
#include "crypto/ec_private_key.h"
#include "net/base/net_errors.h"
#include "net/base/test_completion_callback.h"
#include "net/cert/asn1_util.h"
#include "net/cert/x509_certificate.h"
#include "net/ssl/default_channel_id_store.h"
#include "net/test/channel_id_test_util.h"
#include "net/test/gtest_util.h"
#include "net/test/net_test_suite.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using net::test::IsError;
using net::test::IsOk;
namespace net {
namespace {
void FailTest(int /* result */) {
FAIL();
}
class MockChannelIDStoreWithAsyncGet
: public DefaultChannelIDStore {
public:
MockChannelIDStoreWithAsyncGet()
: DefaultChannelIDStore(NULL), channel_id_count_(0) {}
int GetChannelID(const std::string& server_identifier,
std::unique_ptr<crypto::ECPrivateKey>* key_result,
const GetChannelIDCallback& callback) override;
void SetChannelID(std::unique_ptr<ChannelID> channel_id) override {
channel_id_count_ = 1;
}
int GetChannelIDCount() override { return channel_id_count_; }
void CallGetChannelIDCallbackWithResult(int err, crypto::ECPrivateKey* key);
private:
GetChannelIDCallback callback_;
std::string server_identifier_;
int channel_id_count_;
};
int MockChannelIDStoreWithAsyncGet::GetChannelID(
const std::string& server_identifier,
std::unique_ptr<crypto::ECPrivateKey>* key_result,
const GetChannelIDCallback& callback) {
server_identifier_ = server_identifier;
callback_ = callback;
// Reset the cert count, it'll get incremented in either SetChannelID or
// CallGetChannelIDCallbackWithResult.
channel_id_count_ = 0;
// Do nothing else: the results to be provided will be specified through
// CallGetChannelIDCallbackWithResult.
return ERR_IO_PENDING;
}
void MockChannelIDStoreWithAsyncGet::CallGetChannelIDCallbackWithResult(
int err,
crypto::ECPrivateKey* key) {
if (err == OK)
channel_id_count_ = 1;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(callback_, err, server_identifier_,
base::Passed(key ? key->Copy() : nullptr)));
}
class ChannelIDServiceTest : public testing::Test {
public:
ChannelIDServiceTest()
: service_(new ChannelIDService(new DefaultChannelIDStore(NULL))) {}
protected:
std::unique_ptr<ChannelIDService> service_;
};
TEST_F(ChannelIDServiceTest, GetDomainForHost) {
EXPECT_EQ("google.com",
ChannelIDService::GetDomainForHost("google.com"));
EXPECT_EQ("google.com",
ChannelIDService::GetDomainForHost("www.google.com"));
EXPECT_EQ("foo.appspot.com",
ChannelIDService::GetDomainForHost("foo.appspot.com"));
EXPECT_EQ("bar.appspot.com",
ChannelIDService::GetDomainForHost("foo.bar.appspot.com"));
EXPECT_EQ("appspot.com",
ChannelIDService::GetDomainForHost("appspot.com"));
EXPECT_EQ("google.com",
ChannelIDService::GetDomainForHost("www.mail.google.com"));
EXPECT_EQ("goto",
ChannelIDService::GetDomainForHost("goto"));
EXPECT_EQ("127.0.0.1",
ChannelIDService::GetDomainForHost("127.0.0.1"));
}
TEST_F(ChannelIDServiceTest, GetCacheMiss) {
std::string host("encrypted.google.com");
int error;
TestCompletionCallback callback;
ChannelIDService::Request request;
// Synchronous completion, because the store is initialized.
std::unique_ptr<crypto::ECPrivateKey> key;
EXPECT_EQ(0, service_->channel_id_count());
error = service_->GetChannelID(host, &key, callback.callback(), &request);
EXPECT_THAT(error, IsError(ERR_FILE_NOT_FOUND));
EXPECT_FALSE(request.is_active());
EXPECT_EQ(0, service_->channel_id_count());
EXPECT_FALSE(key);
}
TEST_F(ChannelIDServiceTest, CacheHit) {
std::string host("encrypted.google.com");
int error;
TestCompletionCallback callback;
ChannelIDService::Request request;
// Asynchronous completion.
std::unique_ptr<crypto::ECPrivateKey> key1;
EXPECT_EQ(0, service_->channel_id_count());
error = service_->GetOrCreateChannelID(host, &key1, callback.callback(),
&request);
EXPECT_THAT(error, IsError(ERR_IO_PENDING));
EXPECT_TRUE(request.is_active());
error = callback.WaitForResult();
EXPECT_THAT(error, IsOk());
EXPECT_EQ(1, service_->channel_id_count());
EXPECT_TRUE(key1);
EXPECT_FALSE(request.is_active());
// Synchronous completion.
std::unique_ptr<crypto::ECPrivateKey> key2;
error = service_->GetOrCreateChannelID(host, &key2, callback.callback(),
&request);
EXPECT_FALSE(request.is_active());
EXPECT_THAT(error, IsOk());
EXPECT_EQ(1, service_->channel_id_count());
EXPECT_TRUE(KeysEqual(key1.get(), key2.get()));
// Synchronous get.
std::unique_ptr<crypto::ECPrivateKey> key3;
error = service_->GetChannelID(host, &key3, callback.callback(), &request);
EXPECT_FALSE(request.is_active());
EXPECT_THAT(error, IsOk());
EXPECT_EQ(1, service_->channel_id_count());
EXPECT_TRUE(KeysEqual(key1.get(), key3.get()));
EXPECT_EQ(3u, service_->requests());
EXPECT_EQ(2u, service_->key_store_hits());
EXPECT_EQ(0u, service_->inflight_joins());
}
TEST_F(ChannelIDServiceTest, StoreChannelIDs) {
int error;
TestCompletionCallback callback;
ChannelIDService::Request request;
std::string host1("encrypted.google.com");
std::unique_ptr<crypto::ECPrivateKey> key1;
EXPECT_EQ(0, service_->channel_id_count());
error = service_->GetOrCreateChannelID(host1, &key1, callback.callback(),
&request);
EXPECT_THAT(error, IsError(ERR_IO_PENDING));
EXPECT_TRUE(request.is_active());
error = callback.WaitForResult();
EXPECT_THAT(error, IsOk());
EXPECT_EQ(1, service_->channel_id_count());
std::string host2("www.verisign.com");
std::unique_ptr<crypto::ECPrivateKey> key2;
error = service_->GetOrCreateChannelID(host2, &key2, callback.callback(),
&request);
EXPECT_THAT(error, IsError(ERR_IO_PENDING));
EXPECT_TRUE(request.is_active());
error = callback.WaitForResult();
EXPECT_THAT(error, IsOk());
EXPECT_EQ(2, service_->channel_id_count());
std::string host3("www.twitter.com");
std::unique_ptr<crypto::ECPrivateKey> key3;
error = service_->GetOrCreateChannelID(host3, &key3, callback.callback(),
&request);
EXPECT_THAT(error, IsError(ERR_IO_PENDING));
EXPECT_TRUE(request.is_active());
error = callback.WaitForResult();
EXPECT_THAT(error, IsOk());
EXPECT_EQ(3, service_->channel_id_count());
EXPECT_FALSE(KeysEqual(key1.get(), key2.get()));
EXPECT_FALSE(KeysEqual(key1.get(), key3.get()));
EXPECT_FALSE(KeysEqual(key2.get(), key3.get()));
}
// Tests an inflight join.
TEST_F(ChannelIDServiceTest, InflightJoin) {
std::string host("encrypted.google.com");
int error;
std::unique_ptr<crypto::ECPrivateKey> key1;
TestCompletionCallback callback1;
ChannelIDService::Request request1;
std::unique_ptr<crypto::ECPrivateKey> key2;
TestCompletionCallback callback2;
ChannelIDService::Request request2;
error = service_->GetOrCreateChannelID(host, &key1, callback1.callback(),
&request1);
EXPECT_THAT(error, IsError(ERR_IO_PENDING));
EXPECT_TRUE(request1.is_active());
// Should join with the original request.
error = service_->GetOrCreateChannelID(host, &key2, callback2.callback(),
&request2);
EXPECT_THAT(error, IsError(ERR_IO_PENDING));
EXPECT_TRUE(request2.is_active());
error = callback1.WaitForResult();
EXPECT_THAT(error, IsOk());
error = callback2.WaitForResult();
EXPECT_THAT(error, IsOk());
EXPECT_EQ(2u, service_->requests());
EXPECT_EQ(0u, service_->key_store_hits());
EXPECT_EQ(1u, service_->inflight_joins());
EXPECT_EQ(1u, service_->workers_created());
}
// Tests an inflight join of a Get request to a GetOrCreate request.
TEST_F(ChannelIDServiceTest, InflightJoinGetOrCreateAndGet) {
std::string host("encrypted.google.com");
int error;
std::unique_ptr<crypto::ECPrivateKey> key1;
TestCompletionCallback callback1;
ChannelIDService::Request request1;
std::unique_ptr<crypto::ECPrivateKey> key2;
TestCompletionCallback callback2;
ChannelIDService::Request request2;
error = service_->GetOrCreateChannelID(host, &key1, callback1.callback(),
&request1);
EXPECT_THAT(error, IsError(ERR_IO_PENDING));
EXPECT_TRUE(request1.is_active());
// Should join with the original request.
error = service_->GetChannelID(host, &key2, callback2.callback(), &request2);
EXPECT_THAT(error, IsError(ERR_IO_PENDING));
EXPECT_TRUE(request2.is_active());
error = callback1.WaitForResult();
EXPECT_THAT(error, IsOk());
error = callback2.WaitForResult();
EXPECT_THAT(error, IsOk());
EXPECT_TRUE(KeysEqual(key1.get(), key2.get()));
EXPECT_EQ(2u, service_->requests());
EXPECT_EQ(0u, service_->key_store_hits());
EXPECT_EQ(1u, service_->inflight_joins());
EXPECT_EQ(1u, service_->workers_created());
}
// Tests that the callback of a canceled request is never made.
TEST_F(ChannelIDServiceTest, CancelRequest) {
std::string host("encrypted.google.com");
std::unique_ptr<crypto::ECPrivateKey> key;
int error;
ChannelIDService::Request request;
error = service_->GetOrCreateChannelID(host, &key, base::Bind(&FailTest),
&request);
EXPECT_THAT(error, IsError(ERR_IO_PENDING));
EXPECT_TRUE(request.is_active());
request.Cancel();
EXPECT_FALSE(request.is_active());
// Wait for reply from ChannelIDServiceWorker to be posted back to the
// ChannelIDService.
NetTestSuite::GetScopedTaskEnvironment()->RunUntilIdle();
// Even though the original request was cancelled, the service will still
// store the result, it just doesn't call the callback.
EXPECT_EQ(1, service_->channel_id_count());
}
// Tests that destructing the Request cancels the request.
TEST_F(ChannelIDServiceTest, CancelRequestByHandleDestruction) {
std::string host("encrypted.google.com");
std::unique_ptr<crypto::ECPrivateKey> key;
int error;
std::unique_ptr<ChannelIDService::Request> request(
new ChannelIDService::Request());
error = service_->GetOrCreateChannelID(host, &key, base::Bind(&FailTest),
request.get());
EXPECT_THAT(error, IsError(ERR_IO_PENDING));
EXPECT_TRUE(request->is_active());
// Delete the Request object.
request.reset();
// Wait for reply from ChannelIDServiceWorker to be posted back to the
// ChannelIDService.
NetTestSuite::GetScopedTaskEnvironment()->RunUntilIdle();
// Even though the original request was cancelled, the service will still
// store the result, it just doesn't call the callback.
EXPECT_EQ(1, service_->channel_id_count());
}
TEST_F(ChannelIDServiceTest, DestructionWithPendingRequest) {
std::string host("encrypted.google.com");
std::unique_ptr<crypto::ECPrivateKey> key;
int error;
ChannelIDService::Request request;
error = service_->GetOrCreateChannelID(host, &key, base::Bind(&FailTest),
&request);
EXPECT_THAT(error, IsError(ERR_IO_PENDING));
EXPECT_TRUE(request.is_active());
// Cancel request and destroy the ChannelIDService.
request.Cancel();
service_.reset();
// ChannelIDServiceWorker should not post anything back to the
// non-existent ChannelIDService, but run the loop just to be sure it
// doesn't.
base::RunLoop().RunUntilIdle();
// If we got here without crashing or a valgrind error, it worked.
}
// Tests that making new requests when the ChannelIDService can no longer post
// tasks gracefully fails. This is a regression test for http://crbug.com/236387
TEST_F(ChannelIDServiceTest, RequestAfterPoolShutdown) {
service_->set_task_runner_for_testing(
base::MakeRefCounted<base::NullTaskRunner>());
// Make a request that will force synchronous completion.
std::string host("encrypted.google.com");
std::unique_ptr<crypto::ECPrivateKey> key;
int error;
ChannelIDService::Request request;
error = service_->GetOrCreateChannelID(host, &key, base::Bind(&FailTest),
&request);
// If we got here without crashing or a valgrind error, it worked.
ASSERT_THAT(error, IsError(ERR_IO_PENDING));
EXPECT_TRUE(request.is_active());
}
// Tests that simultaneous creation of different certs works.
TEST_F(ChannelIDServiceTest, SimultaneousCreation) {
int error;
std::string host1("encrypted.google.com");
std::unique_ptr<crypto::ECPrivateKey> key1;
TestCompletionCallback callback1;
ChannelIDService::Request request1;
std::string host2("foo.com");
std::unique_ptr<crypto::ECPrivateKey> key2;
TestCompletionCallback callback2;
ChannelIDService::Request request2;
std::string host3("bar.com");
std::unique_ptr<crypto::ECPrivateKey> key3;
TestCompletionCallback callback3;
ChannelIDService::Request request3;
error = service_->GetOrCreateChannelID(host1, &key1, callback1.callback(),
&request1);
EXPECT_THAT(error, IsError(ERR_IO_PENDING));
EXPECT_TRUE(request1.is_active());
error = service_->GetOrCreateChannelID(host2, &key2, callback2.callback(),
&request2);
EXPECT_THAT(error, IsError(ERR_IO_PENDING));
EXPECT_TRUE(request2.is_active());
error = service_->GetOrCreateChannelID(host3, &key3, callback3.callback(),
&request3);
EXPECT_THAT(error, IsError(ERR_IO_PENDING));
EXPECT_TRUE(request3.is_active());
error = callback1.WaitForResult();
EXPECT_THAT(error, IsOk());
EXPECT_TRUE(key1);
error = callback2.WaitForResult();
EXPECT_THAT(error, IsOk());
EXPECT_TRUE(key2);
error = callback3.WaitForResult();
EXPECT_THAT(error, IsOk());
EXPECT_TRUE(key3);
EXPECT_FALSE(KeysEqual(key1.get(), key2.get()));
EXPECT_FALSE(KeysEqual(key1.get(), key3.get()));
EXPECT_FALSE(KeysEqual(key2.get(), key3.get()));
EXPECT_EQ(3, service_->channel_id_count());
}
TEST_F(ChannelIDServiceTest, AsyncStoreGetOrCreateNoChannelIDsInStore) {
MockChannelIDStoreWithAsyncGet* mock_store =
new MockChannelIDStoreWithAsyncGet();
service_ =
std::unique_ptr<ChannelIDService>(new ChannelIDService(mock_store));
std::string host("encrypted.google.com");
int error;
TestCompletionCallback callback;
ChannelIDService::Request request;
// Asynchronous completion with no certs in the store.
std::unique_ptr<crypto::ECPrivateKey> key;
EXPECT_EQ(0, service_->channel_id_count());
error =
service_->GetOrCreateChannelID(host, &key, callback.callback(), &request);
EXPECT_THAT(error, IsError(ERR_IO_PENDING));
EXPECT_TRUE(request.is_active());
mock_store->CallGetChannelIDCallbackWithResult(ERR_FILE_NOT_FOUND, nullptr);
error = callback.WaitForResult();
EXPECT_THAT(error, IsOk());
EXPECT_EQ(1, service_->channel_id_count());
EXPECT_TRUE(key);
EXPECT_FALSE(request.is_active());
}
TEST_F(ChannelIDServiceTest, AsyncStoreGetNoChannelIDsInStore) {
MockChannelIDStoreWithAsyncGet* mock_store =
new MockChannelIDStoreWithAsyncGet();
service_ =
std::unique_ptr<ChannelIDService>(new ChannelIDService(mock_store));
std::string host("encrypted.google.com");
int error;
TestCompletionCallback callback;
ChannelIDService::Request request;
// Asynchronous completion with no certs in the store.
std::unique_ptr<crypto::ECPrivateKey> key;
EXPECT_EQ(0, service_->channel_id_count());
error = service_->GetChannelID(host, &key, callback.callback(), &request);
EXPECT_THAT(error, IsError(ERR_IO_PENDING));
EXPECT_TRUE(request.is_active());
mock_store->CallGetChannelIDCallbackWithResult(ERR_FILE_NOT_FOUND, nullptr);
error = callback.WaitForResult();
EXPECT_THAT(error, IsError(ERR_FILE_NOT_FOUND));
EXPECT_EQ(0, service_->channel_id_count());
EXPECT_EQ(0u, service_->workers_created());
EXPECT_FALSE(key);
EXPECT_FALSE(request.is_active());
}
TEST_F(ChannelIDServiceTest, AsyncStoreGetOrCreateOneCertInStore) {
MockChannelIDStoreWithAsyncGet* mock_store =
new MockChannelIDStoreWithAsyncGet();
service_ =
std::unique_ptr<ChannelIDService>(new ChannelIDService(mock_store));
std::string host("encrypted.google.com");
int error;
TestCompletionCallback callback;
ChannelIDService::Request request;
// Asynchronous completion with a cert in the store.
std::unique_ptr<crypto::ECPrivateKey> key;
EXPECT_EQ(0, service_->channel_id_count());
error =
service_->GetOrCreateChannelID(host, &key, callback.callback(), &request);
EXPECT_THAT(error, IsError(ERR_IO_PENDING));
EXPECT_TRUE(request.is_active());
std::unique_ptr<crypto::ECPrivateKey> expected_key(
crypto::ECPrivateKey::Create());
mock_store->CallGetChannelIDCallbackWithResult(OK, expected_key.get());
error = callback.WaitForResult();
EXPECT_THAT(error, IsOk());
EXPECT_EQ(1, service_->channel_id_count());
EXPECT_EQ(1u, service_->requests());
EXPECT_EQ(1u, service_->key_store_hits());
// Because the cert was found in the store, no new workers should have been
// created.
EXPECT_EQ(0u, service_->workers_created());
EXPECT_TRUE(key);
EXPECT_TRUE(KeysEqual(expected_key.get(), key.get()));
EXPECT_FALSE(request.is_active());
}
TEST_F(ChannelIDServiceTest, AsyncStoreGetOneCertInStore) {
MockChannelIDStoreWithAsyncGet* mock_store =
new MockChannelIDStoreWithAsyncGet();
service_ =
std::unique_ptr<ChannelIDService>(new ChannelIDService(mock_store));
std::string host("encrypted.google.com");
int error;
TestCompletionCallback callback;
ChannelIDService::Request request;
// Asynchronous completion with a cert in the store.
std::unique_ptr<crypto::ECPrivateKey> key;
std::string private_key, spki;
EXPECT_EQ(0, service_->channel_id_count());
error = service_->GetChannelID(host, &key, callback.callback(), &request);
EXPECT_THAT(error, IsError(ERR_IO_PENDING));
EXPECT_TRUE(request.is_active());
std::unique_ptr<crypto::ECPrivateKey> expected_key(
crypto::ECPrivateKey::Create());
mock_store->CallGetChannelIDCallbackWithResult(OK, expected_key.get());
error = callback.WaitForResult();
EXPECT_THAT(error, IsOk());
EXPECT_EQ(1, service_->channel_id_count());
EXPECT_EQ(1u, service_->requests());
EXPECT_EQ(1u, service_->key_store_hits());
// Because the cert was found in the store, no new workers should have been
// created.
EXPECT_EQ(0u, service_->workers_created());
EXPECT_TRUE(KeysEqual(expected_key.get(), key.get()));
EXPECT_FALSE(request.is_active());
}
TEST_F(ChannelIDServiceTest, AsyncStoreGetThenCreateNoCertsInStore) {
MockChannelIDStoreWithAsyncGet* mock_store =
new MockChannelIDStoreWithAsyncGet();
service_ =
std::unique_ptr<ChannelIDService>(new ChannelIDService(mock_store));
std::string host("encrypted.google.com");
int error;
// Asynchronous get with no certs in the store.
TestCompletionCallback callback1;
ChannelIDService::Request request1;
std::unique_ptr<crypto::ECPrivateKey> key1;
EXPECT_EQ(0, service_->channel_id_count());
error = service_->GetChannelID(host, &key1, callback1.callback(), &request1);
EXPECT_THAT(error, IsError(ERR_IO_PENDING));
EXPECT_TRUE(request1.is_active());
// Asynchronous get/create with no certs in the store.
TestCompletionCallback callback2;
ChannelIDService::Request request2;
std::unique_ptr<crypto::ECPrivateKey> key2;
EXPECT_EQ(0, service_->channel_id_count());
error = service_->GetOrCreateChannelID(host, &key2, callback2.callback(),
&request2);
EXPECT_THAT(error, IsError(ERR_IO_PENDING));
EXPECT_TRUE(request2.is_active());
mock_store->CallGetChannelIDCallbackWithResult(ERR_FILE_NOT_FOUND, nullptr);
// Even though the first request didn't ask to create a cert, it gets joined
// by the second, which does, so both succeed.
error = callback1.WaitForResult();
EXPECT_THAT(error, IsOk());
error = callback2.WaitForResult();
EXPECT_THAT(error, IsOk());
// One cert is created, one request is joined.
EXPECT_EQ(2U, service_->requests());
EXPECT_EQ(1, service_->channel_id_count());
EXPECT_EQ(1u, service_->workers_created());
EXPECT_EQ(1u, service_->inflight_joins());
EXPECT_TRUE(key1);
EXPECT_TRUE(KeysEqual(key1.get(), key2.get()));
EXPECT_FALSE(request1.is_active());
EXPECT_FALSE(request2.is_active());
}
} // namespace
} // namespace net
| null | null | null | null | 5,688 |
37,214 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 37,214 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright 2015 The Chromium 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 "third_party/blink/renderer/platform/scheduler/common/throttling/task_queue_throttler.h"
#include <cstdint>
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/optional.h"
#include "third_party/blink/renderer/platform/scheduler/base/real_time_domain.h"
#include "third_party/blink/renderer/platform/scheduler/common/throttling/budget_pool.h"
#include "third_party/blink/renderer/platform/scheduler/common/throttling/throttled_time_domain.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler.h"
namespace blink {
namespace scheduler {
namespace {
base::Optional<base::TimeTicks> NextTaskRunTime(LazyNow* lazy_now,
TaskQueue* queue) {
if (queue->HasTaskToRunImmediately())
return lazy_now->Now();
return queue->GetNextScheduledWakeUp();
}
template <class T>
T Min(const base::Optional<T>& optional, const T& value) {
if (!optional) {
return value;
}
return std::min(optional.value(), value);
}
template <class T>
base::Optional<T> Min(const base::Optional<T>& a, const base::Optional<T>& b) {
if (!b)
return a;
if (!a)
return b;
return std::min(a.value(), b.value());
}
template <class T>
T Max(const base::Optional<T>& optional, const T& value) {
if (!optional)
return value;
return std::max(optional.value(), value);
}
template <class T>
base::Optional<T> Max(const base::Optional<T>& a, const base::Optional<T>& b) {
if (!b)
return a;
if (!a)
return b;
return std::max(a.value(), b.value());
}
} // namespace
TaskQueueThrottler::TaskQueueThrottler(
RendererSchedulerImpl* renderer_scheduler,
TraceableVariableController* tracing_controller)
: control_task_queue_(renderer_scheduler->ControlTaskQueue()),
renderer_scheduler_(renderer_scheduler),
tracing_controller_(tracing_controller),
tick_clock_(renderer_scheduler->tick_clock()),
time_domain_(new ThrottledTimeDomain()),
allow_throttling_(true),
weak_factory_(this) {
pump_throttled_tasks_closure_.Reset(base::BindRepeating(
&TaskQueueThrottler::PumpThrottledTasks, weak_factory_.GetWeakPtr()));
forward_immediate_work_callback_ =
base::BindRepeating(&TaskQueueThrottler::OnQueueNextWakeUpChanged,
weak_factory_.GetWeakPtr());
renderer_scheduler_->RegisterTimeDomain(time_domain_.get());
}
TaskQueueThrottler::~TaskQueueThrottler() {
// It's possible for queues to be still throttled, so we need to tidy up
// before unregistering the time domain.
for (const TaskQueueMap::value_type& map_entry : queue_details_) {
TaskQueue* task_queue = map_entry.first;
if (IsThrottled(task_queue)) {
task_queue->SetTimeDomain(renderer_scheduler_->GetActiveTimeDomain());
task_queue->RemoveFence();
}
if (map_entry.second.throttling_ref_count != 0)
task_queue->SetObserver(nullptr);
}
renderer_scheduler_->UnregisterTimeDomain(time_domain_.get());
}
void TaskQueueThrottler::IncreaseThrottleRefCount(TaskQueue* task_queue) {
DCHECK_NE(task_queue, control_task_queue_.get());
std::pair<TaskQueueMap::iterator, bool> insert_result =
queue_details_.insert(std::make_pair(task_queue, Metadata()));
insert_result.first->second.throttling_ref_count++;
// If ref_count is 1, the task queue is newly throttled.
if (insert_result.first->second.throttling_ref_count != 1)
return;
TRACE_EVENT1("renderer.scheduler", "TaskQueueThrottler_TaskQueueThrottled",
"task_queue", task_queue);
task_queue->SetObserver(this);
if (!allow_throttling_)
return;
task_queue->SetTimeDomain(time_domain_.get());
// This blocks any tasks from |task_queue| until PumpThrottledTasks() to
// enforce task alignment.
task_queue->InsertFence(TaskQueue::InsertFencePosition::kBeginningOfTime);
if (!task_queue->IsQueueEnabled())
return;
if (!task_queue->IsEmpty()) {
LazyNow lazy_now(tick_clock_);
OnQueueNextWakeUpChanged(task_queue,
NextTaskRunTime(&lazy_now, task_queue).value());
}
}
void TaskQueueThrottler::DecreaseThrottleRefCount(TaskQueue* task_queue) {
TaskQueueMap::iterator iter = queue_details_.find(task_queue);
if (iter == queue_details_.end())
return;
if (iter->second.throttling_ref_count == 0)
return;
if (--iter->second.throttling_ref_count != 0)
return;
TRACE_EVENT1("renderer.scheduler", "TaskQueueThrottler_TaskQueueUnthrottled",
"task_queue", task_queue);
task_queue->SetObserver(nullptr);
MaybeDeleteQueueMetadata(iter);
if (!allow_throttling_)
return;
task_queue->SetTimeDomain(renderer_scheduler_->GetActiveTimeDomain());
task_queue->RemoveFence();
}
bool TaskQueueThrottler::IsThrottled(TaskQueue* task_queue) const {
if (!allow_throttling_)
return false;
auto find_it = queue_details_.find(task_queue);
if (find_it == queue_details_.end())
return false;
return find_it->second.throttling_ref_count > 0;
}
void TaskQueueThrottler::ShutdownTaskQueue(TaskQueue* task_queue) {
auto find_it = queue_details_.find(task_queue);
if (find_it == queue_details_.end())
return;
// Reset a time domain reference to a valid domain, otherwise it's possible
// to get a stale reference when deleting queue.
task_queue->SetTimeDomain(renderer_scheduler_->GetActiveTimeDomain());
task_queue->RemoveFence();
std::unordered_set<BudgetPool*> budget_pools = find_it->second.budget_pools;
for (BudgetPool* budget_pool : budget_pools) {
budget_pool->UnregisterQueue(task_queue);
}
// Iterator may have been deleted by BudgetPool::RemoveQueue, so don't
// use it here.
queue_details_.erase(task_queue);
// NOTE: Observer is automatically unregistered when unregistering task queue.
}
void TaskQueueThrottler::OnQueueNextWakeUpChanged(
TaskQueue* queue,
base::TimeTicks next_wake_up) {
if (!control_task_queue_->RunsTasksInCurrentSequence()) {
control_task_queue_->PostTask(
FROM_HERE, base::BindOnce(forward_immediate_work_callback_,
base::RetainedRef(queue), next_wake_up));
return;
}
TRACE_EVENT0("renderer.scheduler",
"TaskQueueThrottler::OnQueueNextWakeUpChanged");
// We don't expect this to get called for disabled queues, but we can't DCHECK
// because of the above thread hop. Just bail out if the queue is disabled.
if (!queue->IsQueueEnabled())
return;
base::TimeTicks now = tick_clock_->NowTicks();
next_wake_up = std::max(now, next_wake_up);
auto find_it = queue_details_.find(queue);
if (find_it == queue_details_.end())
return;
for (BudgetPool* budget_pool : find_it->second.budget_pools) {
budget_pool->OnQueueNextWakeUpChanged(queue, now, next_wake_up);
}
// TODO(altimin): This probably can be removed —- budget pools should
// schedule this.
base::TimeTicks next_allowed_run_time =
GetNextAllowedRunTime(queue, next_wake_up);
MaybeSchedulePumpThrottledTasks(
FROM_HERE, now, std::max(next_wake_up, next_allowed_run_time));
}
void TaskQueueThrottler::PumpThrottledTasks() {
TRACE_EVENT0("renderer.scheduler", "TaskQueueThrottler::PumpThrottledTasks");
pending_pump_throttled_tasks_runtime_.reset();
LazyNow lazy_now(tick_clock_);
for (const auto& pair : budget_pools_)
pair.first->OnWakeUp(lazy_now.Now());
for (const TaskQueueMap::value_type& map_entry : queue_details_) {
TaskQueue* task_queue = map_entry.first;
UpdateQueueThrottlingStateInternal(lazy_now.Now(), task_queue, true);
}
}
/* static */
base::TimeTicks TaskQueueThrottler::AlignedThrottledRunTime(
base::TimeTicks unthrottled_runtime) {
const base::TimeDelta one_second = base::TimeDelta::FromSeconds(1);
return unthrottled_runtime + one_second -
((unthrottled_runtime - base::TimeTicks()) % one_second);
}
void TaskQueueThrottler::MaybeSchedulePumpThrottledTasks(
const base::Location& from_here,
base::TimeTicks now,
base::TimeTicks unaligned_runtime) {
if (!allow_throttling_)
return;
// TODO(altimin): Consider removing alignment here.
base::TimeTicks runtime =
std::max(now, unaligned_runtime)
.SnappedToNextTick(base::TimeTicks(),
base::TimeDelta::FromSeconds(1));
DCHECK_LE(now, runtime);
// If there is a pending call to PumpThrottledTasks and it's sooner than
// |runtime| then return.
if (pending_pump_throttled_tasks_runtime_ &&
runtime >= pending_pump_throttled_tasks_runtime_.value()) {
return;
}
pending_pump_throttled_tasks_runtime_ = runtime;
pump_throttled_tasks_closure_.Cancel();
base::TimeDelta delay = pending_pump_throttled_tasks_runtime_.value() - now;
TRACE_EVENT1("renderer.scheduler",
"TaskQueueThrottler::MaybeSchedulePumpThrottledTasks",
"delay_till_next_pump_ms", delay.InMilliseconds());
control_task_queue_->PostDelayedTask(
from_here, pump_throttled_tasks_closure_.GetCallback(), delay);
}
CPUTimeBudgetPool* TaskQueueThrottler::CreateCPUTimeBudgetPool(
const char* name) {
CPUTimeBudgetPool* time_budget_pool = new CPUTimeBudgetPool(
name, this, tracing_controller_, tick_clock_->NowTicks());
budget_pools_[time_budget_pool] = base::WrapUnique(time_budget_pool);
return time_budget_pool;
}
WakeUpBudgetPool* TaskQueueThrottler::CreateWakeUpBudgetPool(const char* name) {
WakeUpBudgetPool* wake_up_budget_pool =
new WakeUpBudgetPool(name, this, tick_clock_->NowTicks());
budget_pools_[wake_up_budget_pool] = base::WrapUnique(wake_up_budget_pool);
return wake_up_budget_pool;
}
void TaskQueueThrottler::OnTaskRunTimeReported(TaskQueue* task_queue,
base::TimeTicks start_time,
base::TimeTicks end_time) {
if (!IsThrottled(task_queue))
return;
auto find_it = queue_details_.find(task_queue);
if (find_it == queue_details_.end())
return;
for (BudgetPool* budget_pool : find_it->second.budget_pools) {
budget_pool->RecordTaskRunTime(task_queue, start_time, end_time);
}
}
void TaskQueueThrottler::UpdateQueueThrottlingState(base::TimeTicks now,
TaskQueue* queue) {
UpdateQueueThrottlingStateInternal(now, queue, false);
}
void TaskQueueThrottler::UpdateQueueThrottlingStateInternal(base::TimeTicks now,
TaskQueue* queue,
bool is_wake_up) {
if (!queue->IsQueueEnabled() || !IsThrottled(queue)) {
return;
}
LazyNow lazy_now(now);
base::Optional<base::TimeTicks> next_desired_run_time =
NextTaskRunTime(&lazy_now, queue);
if (CanRunTasksAt(queue, now, is_wake_up)) {
// Unblock queue if we can run tasks immediately.
base::Optional<base::TimeTicks> unblock_until =
GetTimeTasksCanRunUntil(queue, now, is_wake_up);
DCHECK(unblock_until);
if (!unblock_until || unblock_until.value() > now) {
queue->InsertFenceAt(unblock_until.value());
} else if (unblock_until.value() == now) {
queue->InsertFence(TaskQueue::InsertFencePosition::kNow);
} else {
DCHECK_GE(unblock_until.value(), now);
}
// Throttled time domain does not schedule wake-ups without explicitly
// being told so.
if (next_desired_run_time && next_desired_run_time.value() != now &&
next_desired_run_time.value() < unblock_until) {
time_domain_->SetNextTaskRunTime(next_desired_run_time.value());
}
base::Optional<base::TimeTicks> next_wake_up =
queue->GetNextScheduledWakeUp();
// TODO(altimin, crbug.com/813218): Find a testcase to repro freezes
// mentioned in the bug.
if (next_wake_up) {
MaybeSchedulePumpThrottledTasks(
FROM_HERE, now, GetNextAllowedRunTime(queue, next_wake_up.value()));
}
return;
}
if (!next_desired_run_time)
return;
base::TimeTicks next_run_time =
GetNextAllowedRunTime(queue, next_desired_run_time.value());
// Insert a fence of an approriate type.
base::Optional<QueueBlockType> block_type = GetQueueBlockType(now, queue);
DCHECK(block_type);
switch (block_type.value()) {
case QueueBlockType::kAllTasks:
queue->InsertFence(TaskQueue::InsertFencePosition::kBeginningOfTime);
{
// Braces limit the scope for a declared variable. Does not compile
// otherwise.
TRACE_EVENT1(
"renderer.scheduler",
"TaskQueueThrottler::PumpThrottledTasks_ExpensiveTaskThrottled",
"throttle_time_in_seconds",
(next_run_time - next_desired_run_time.value()).InSecondsF());
}
break;
case QueueBlockType::kNewTasksOnly:
if (!queue->HasActiveFence()) {
// Insert a new non-fully blocking fence only when there is no fence
// already in order avoid undesired unblocking of old tasks.
queue->InsertFence(TaskQueue::InsertFencePosition::kNow);
}
break;
}
// Schedule a pump.
MaybeSchedulePumpThrottledTasks(FROM_HERE, now, next_run_time);
}
base::Optional<QueueBlockType> TaskQueueThrottler::GetQueueBlockType(
base::TimeTicks now,
TaskQueue* queue) {
auto find_it = queue_details_.find(queue);
if (find_it == queue_details_.end())
return base::nullopt;
bool has_new_tasks_only_block = false;
for (BudgetPool* budget_pool : find_it->second.budget_pools) {
if (!budget_pool->CanRunTasksAt(now, false)) {
if (budget_pool->GetBlockType() == QueueBlockType::kAllTasks)
return QueueBlockType::kAllTasks;
DCHECK_EQ(budget_pool->GetBlockType(), QueueBlockType::kNewTasksOnly);
has_new_tasks_only_block = true;
}
}
if (has_new_tasks_only_block)
return QueueBlockType::kNewTasksOnly;
return base::nullopt;
}
void TaskQueueThrottler::AsValueInto(base::trace_event::TracedValue* state,
base::TimeTicks now) const {
if (pending_pump_throttled_tasks_runtime_) {
state->SetDouble(
"next_throttled_tasks_pump_in_seconds",
(pending_pump_throttled_tasks_runtime_.value() - now).InSecondsF());
}
state->SetBoolean("allow_throttling", allow_throttling_);
state->BeginDictionary("time_budget_pools");
for (const auto& map_entry : budget_pools_) {
BudgetPool* pool = map_entry.first;
pool->AsValueInto(state, now);
}
state->EndDictionary();
state->BeginDictionary("queue_details");
for (const auto& map_entry : queue_details_) {
state->BeginDictionaryWithCopiedName(PointerToString(map_entry.first));
state->SetInteger("throttling_ref_count",
map_entry.second.throttling_ref_count);
state->EndDictionary();
}
state->EndDictionary();
}
void TaskQueueThrottler::AddQueueToBudgetPool(TaskQueue* queue,
BudgetPool* budget_pool) {
std::pair<TaskQueueMap::iterator, bool> insert_result =
queue_details_.insert(std::make_pair(queue, Metadata()));
Metadata& metadata = insert_result.first->second;
DCHECK(metadata.budget_pools.find(budget_pool) ==
metadata.budget_pools.end());
metadata.budget_pools.insert(budget_pool);
}
void TaskQueueThrottler::RemoveQueueFromBudgetPool(TaskQueue* queue,
BudgetPool* budget_pool) {
auto find_it = queue_details_.find(queue);
DCHECK(find_it != queue_details_.end() &&
find_it->second.budget_pools.find(budget_pool) !=
find_it->second.budget_pools.end());
find_it->second.budget_pools.erase(budget_pool);
MaybeDeleteQueueMetadata(find_it);
}
void TaskQueueThrottler::UnregisterBudgetPool(BudgetPool* budget_pool) {
budget_pools_.erase(budget_pool);
}
base::TimeTicks TaskQueueThrottler::GetNextAllowedRunTime(
TaskQueue* queue,
base::TimeTicks desired_run_time) {
base::TimeTicks next_run_time = desired_run_time;
auto find_it = queue_details_.find(queue);
if (find_it == queue_details_.end())
return next_run_time;
for (BudgetPool* budget_pool : find_it->second.budget_pools) {
next_run_time = std::max(
next_run_time, budget_pool->GetNextAllowedRunTime(desired_run_time));
}
return next_run_time;
}
bool TaskQueueThrottler::CanRunTasksAt(TaskQueue* queue,
base::TimeTicks moment,
bool is_wake_up) {
auto find_it = queue_details_.find(queue);
if (find_it == queue_details_.end())
return true;
for (BudgetPool* budget_pool : find_it->second.budget_pools) {
if (!budget_pool->CanRunTasksAt(moment, is_wake_up))
return false;
}
return true;
}
base::Optional<base::TimeTicks> TaskQueueThrottler::GetTimeTasksCanRunUntil(
TaskQueue* queue,
base::TimeTicks now,
bool is_wake_up) const {
base::Optional<base::TimeTicks> result;
auto find_it = queue_details_.find(queue);
if (find_it == queue_details_.end())
return result;
for (BudgetPool* budget_pool : find_it->second.budget_pools) {
result = Min(result, budget_pool->GetTimeTasksCanRunUntil(now, is_wake_up));
}
return result;
}
void TaskQueueThrottler::MaybeDeleteQueueMetadata(TaskQueueMap::iterator it) {
if (it->second.throttling_ref_count == 0 && it->second.budget_pools.empty())
queue_details_.erase(it);
}
void TaskQueueThrottler::DisableThrottling() {
if (!allow_throttling_)
return;
allow_throttling_ = false;
for (const auto& map_entry : queue_details_) {
if (map_entry.second.throttling_ref_count == 0)
continue;
TaskQueue* queue = map_entry.first;
queue->SetTimeDomain(renderer_scheduler_->GetActiveTimeDomain());
queue->RemoveFence();
}
pump_throttled_tasks_closure_.Cancel();
pending_pump_throttled_tasks_runtime_ = base::nullopt;
TRACE_EVENT0("renderer.scheduler", "TaskQueueThrottler_DisableThrottling");
}
void TaskQueueThrottler::EnableThrottling() {
if (allow_throttling_)
return;
allow_throttling_ = true;
LazyNow lazy_now(tick_clock_);
for (const auto& map_entry : queue_details_) {
if (map_entry.second.throttling_ref_count == 0)
continue;
TaskQueue* queue = map_entry.first;
// Throttling is enabled and task queue should be blocked immediately
// to enforce task alignment.
queue->InsertFence(TaskQueue::InsertFencePosition::kBeginningOfTime);
queue->SetTimeDomain(time_domain_.get());
UpdateQueueThrottlingState(lazy_now.Now(), queue);
}
TRACE_EVENT0("renderer.scheduler", "TaskQueueThrottler_EnableThrottling");
}
} // namespace scheduler
} // namespace blink
| null | null | null | null | 34,077 |
18,189 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 183,184 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | /*******************************************************************************
*
* Copyright (c) 2015-2016 Intel Corporation. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenFabrics.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#ifndef I40IW_VERBS_H
#define I40IW_VERBS_H
struct i40iw_ucontext {
struct ib_ucontext ibucontext;
struct i40iw_device *iwdev;
struct list_head cq_reg_mem_list;
spinlock_t cq_reg_mem_list_lock; /* memory list for cq's */
struct list_head qp_reg_mem_list;
spinlock_t qp_reg_mem_list_lock; /* memory list for qp's */
int abi_ver;
};
struct i40iw_pd {
struct ib_pd ibpd;
struct i40iw_sc_pd sc_pd;
atomic_t usecount;
};
struct i40iw_hmc_pble {
union {
u32 idx;
dma_addr_t addr;
};
};
struct i40iw_cq_mr {
struct i40iw_hmc_pble cq_pbl;
dma_addr_t shadow;
};
struct i40iw_qp_mr {
struct i40iw_hmc_pble sq_pbl;
struct i40iw_hmc_pble rq_pbl;
dma_addr_t shadow;
struct page *sq_page;
};
struct i40iw_pbl {
struct list_head list;
union {
struct i40iw_qp_mr qp_mr;
struct i40iw_cq_mr cq_mr;
};
bool pbl_allocated;
u64 user_base;
struct i40iw_pble_alloc pble_alloc;
struct i40iw_mr *iwmr;
};
#define MAX_SAVE_PAGE_ADDRS 4
struct i40iw_mr {
union {
struct ib_mr ibmr;
struct ib_mw ibmw;
struct ib_fmr ibfmr;
};
struct ib_umem *region;
u16 type;
u32 page_cnt;
u32 page_size;
u64 page_msk;
u32 npages;
u32 stag;
u64 length;
u64 pgaddrmem[MAX_SAVE_PAGE_ADDRS];
struct i40iw_pbl iwpbl;
};
struct i40iw_cq {
struct ib_cq ibcq;
struct i40iw_sc_cq sc_cq;
u16 cq_head;
u16 cq_size;
u16 cq_number;
bool user_mode;
u32 polled_completions;
u32 cq_mem_size;
struct i40iw_dma_mem kmem;
spinlock_t lock; /* for poll cq */
struct i40iw_pbl *iwpbl;
};
struct disconn_work {
struct work_struct work;
struct i40iw_qp *iwqp;
};
struct iw_cm_id;
struct ietf_mpa_frame;
struct i40iw_ud_file;
struct i40iw_qp_kmode {
struct i40iw_dma_mem dma_mem;
u64 *wrid_mem;
};
struct i40iw_qp {
struct ib_qp ibqp;
struct i40iw_sc_qp sc_qp;
struct i40iw_device *iwdev;
struct i40iw_cq *iwscq;
struct i40iw_cq *iwrcq;
struct i40iw_pd *iwpd;
struct i40iw_qp_host_ctx_info ctx_info;
struct i40iwarp_offload_info iwarp_info;
void *allocated_buffer;
atomic_t refcount;
struct iw_cm_id *cm_id;
void *cm_node;
struct ib_mr *lsmm_mr;
struct work_struct work;
enum ib_qp_state ibqp_state;
u32 iwarp_state;
u32 qp_mem_size;
u32 last_aeq;
atomic_t close_timer_started;
spinlock_t lock; /* for post work requests */
struct i40iw_qp_context *iwqp_context;
void *pbl_vbase;
dma_addr_t pbl_pbase;
struct page *page;
u8 active_conn:1;
u8 user_mode:1;
u8 hte_added:1;
u8 flush_issued:1;
u8 destroyed:1;
u8 sig_all:1;
u8 pau_mode:1;
u8 rsvd:1;
u16 term_sq_flush_code;
u16 term_rq_flush_code;
u8 hw_iwarp_state;
u8 hw_tcp_state;
struct i40iw_qp_kmode kqp;
struct i40iw_dma_mem host_ctx;
struct timer_list terminate_timer;
struct i40iw_pbl *iwpbl;
struct i40iw_dma_mem q2_ctx_mem;
struct i40iw_dma_mem ietf_mem;
struct completion sq_drained;
struct completion rq_drained;
};
#endif
| null | null | null | null | 91,531 |
27,411 | null | train_val | e4311ee51d1e2676001b2d8fcefd92bdd79aad85 | 192,406 | linux | 0 | https://github.com/torvalds/linux | 2017-05-12 08:32:58+10:00 | /* Driver for Realtek PCI-Express card reader
* Header file
*
* Copyright(c) 2009-2013 Realtek Semiconductor Corp. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see <http://www.gnu.org/licenses/>.
*
* Author:
* Wei WANG (wei_wang@realsil.com.cn)
* Micky Ching (micky_ching@realsil.com.cn)
*/
#ifndef __REALTEK_RTSX_TRACE_H
#define __REALTEK_RTSX_TRACE_H
struct rtsx_chip;
#ifdef _MSG_TRACE
void _rtsx_trace(struct rtsx_chip *chip, const char *file, const char *func,
int line);
#define rtsx_trace(chip) \
_rtsx_trace(chip, __FILE__, __func__, __LINE__)
#else
static inline void rtsx_trace(struct rtsx_chip *chip)
{
}
#endif
#endif /* __REALTEK_RTSX_TRACE_H */
| null | null | null | null | 100,753 |
64,493 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 64,493 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright (c) 2012 The Chromium 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 CHROME_BROWSER_UI_COCOA_DEV_TOOLS_CONTROLLER_H_
#define CHROME_BROWSER_UI_COCOA_DEV_TOOLS_CONTROLLER_H_
#import <Cocoa/Cocoa.h>
#include "base/mac/scoped_nsobject.h"
#include "chrome/browser/devtools/devtools_window.h"
@class FocusTracker;
@class DevToolsContainerView;
class Profile;
namespace content {
class WebContents;
}
// A class that handles updates of the devTools view within a browser window.
// It swaps in the relevant devTools contents for a given WebContents or removes
// the view, if there's no devTools contents to show.
@interface DevToolsController : NSObject {
@private
// A view hosting docked devTools contents.
base::scoped_nsobject<DevToolsContainerView> devToolsContainerView_;
base::scoped_nsobject<FocusTracker> focusTracker_;
}
- (id)init;
// This controller's view.
- (NSView*)view;
// Depending on |contents|'s state, decides whether the docked web inspector
// should be shown or hidden and adjusts inspected page position.
// Returns true iff layout has changed.
- (BOOL)updateDevToolsForWebContents:(content::WebContents*)contents
withProfile:(Profile*)profile;
@end
#endif // CHROME_BROWSER_UI_COCOA_DEV_TOOLS_CONTROLLER_H_
| null | null | null | null | 61,356 |
20,280 | null | train_val | 796a0e014bc3985709c0a35538d606ef1da31e1b | 20,280 | Chrome | 0 | https://github.com/chromium/chromium | 2018-04-07 23:43:03+00:00 | // Copyright (c) 2012 The Chromium 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 CONTENT_PUBLIC_BROWSER_WEB_UI_CONTROLLER_H_
#define CONTENT_PUBLIC_BROWSER_WEB_UI_CONTROLLER_H_
#include "base/strings/string16.h"
#include "content/common/content_export.h"
class GURL;
namespace base {
class ListValue;
}
namespace content {
class RenderFrameHost;
class WebUI;
// A WebUI page is controller by the embedder's WebUIController object. It
// manages the data source and message handlers.
class CONTENT_EXPORT WebUIController {
public:
explicit WebUIController(WebUI* web_ui) : web_ui_(web_ui) {}
virtual ~WebUIController() {}
// Allows the controller to override handling all messages from the page.
// Return true if the message handling was overridden.
virtual bool OverrideHandleWebUIMessage(const GURL& source_url,
const std::string& message,
const base::ListValue& args);
// Called when a RenderFrame is created. This is *not* called for every
// page load because in some cases a RenderFrame will be reused, for example
// when reloading or navigating to a same-site URL.
virtual void RenderFrameCreated(RenderFrameHost* render_frame_host) {}
WebUI* web_ui() const { return web_ui_; }
private:
WebUI* web_ui_;
};
} // namespace content
#endif // CONTENT_PUBLIC_BROWSER_WEB_UI_CONTROLLER_H_
| null | null | null | null | 17,143 |
Subsets and Splits
Top Projects by Commit Count
Reveals the most active projects based on the number of unique commits, highlighting which projects have the most development activity.
SQL Console for realvul/RealVul
Identifies the most frequent commit hashes for projects with a target value of 1, revealing key commits that may be significant for further analysis.
Top Vulnerable Commits by Project
Identifies the most frequently occurring vulnerable commit hashes for each project, providing insights into common vulnerabilities across different projects.
Project-wise Vulnerability Count
Counts the occurrences of each target value (0 and 1) per project, providing insight into the distribution of targets within different projects.
CWE Frequency in Train Set
Provides a count of vulnerabilities grouped by CWE ID, highlighting the most frequent types of vulnerabilities in the dataset.
SQL Console for realvul/RealVul
Counts the number of unique commits per project, providing a basic overview of project activity.