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
stringlengths
6
8
commit_link
stringlengths
73
97
severity
stringclasses
4 values
__index_level_0__
int64
0
124k
423
null
train_val
04b570817b2b38e35675b17328239746212f4c3f
153,480
FFmpeg
0
https://github.com/FFmpeg/FFmpeg
2018-06-01 01:23:12+05:30
/* * Copyright (c) 2016 Ronald S. Bultje <rsbultje@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 */ #include <string.h> #include "checkasm.h" #include "libavfilter/colorspacedsp.h" #include "libavutil/common.h" #include "libavutil/internal.h" #include "libavutil/intreadwrite.h" #define W 64 #define H 64 #define randomize_buffers() \ do { \ unsigned mask = bpp_mask[idepth]; \ int n, m; \ int bpp = 1 + (!!idepth); \ int buf_size = W * H * bpp; \ for (m = 0; m < 3; m++) { \ int ss = m ? ss_w + ss_h : 0; \ int plane_sz = buf_size >> ss; \ for (n = 0; n < plane_sz; n += 4) { \ unsigned r = rnd() & mask; \ AV_WN32A(&src[m][n], r); \ } \ } \ } while (0) static const char *format_string[] = { "444", "422", "420" }; static const unsigned bpp_mask[] = { 0xffffffff, 0x03ff03ff, 0x0fff0fff }; static void check_yuv2yuv(void) { declare_func(void, uint8_t *dst[3], ptrdiff_t dst_stride[3], uint8_t *src[3], ptrdiff_t src_stride[3], int w, int h, const int16_t coeff[3][3][8], const int16_t off[2][8]); ColorSpaceDSPContext dsp; int idepth, odepth, fmt, n; LOCAL_ALIGNED_32(uint8_t, src_y, [W * H * 2]); LOCAL_ALIGNED_32(uint8_t, src_u, [W * H * 2]); LOCAL_ALIGNED_32(uint8_t, src_v, [W * H * 2]); uint8_t *src[3] = { src_y, src_u, src_v }; LOCAL_ALIGNED_32(uint8_t, dst0_y, [W * H * 2]); LOCAL_ALIGNED_32(uint8_t, dst0_u, [W * H * 2]); LOCAL_ALIGNED_32(uint8_t, dst0_v, [W * H * 2]); LOCAL_ALIGNED_32(uint8_t, dst1_y, [W * H * 2]); LOCAL_ALIGNED_32(uint8_t, dst1_u, [W * H * 2]); LOCAL_ALIGNED_32(uint8_t, dst1_v, [W * H * 2]); uint8_t *dst0[3] = { dst0_y, dst0_u, dst0_v }, *dst1[3] = { dst1_y, dst1_u, dst1_v }; LOCAL_ALIGNED_32(int16_t, offset_buf, [16]); LOCAL_ALIGNED_32(int16_t, coeff_buf, [3 * 3 * 8]); int16_t (*offset)[8] = (int16_t(*)[8]) offset_buf; int16_t (*coeff)[3][8] = (int16_t(*)[3][8]) coeff_buf; ff_colorspacedsp_init(&dsp); for (n = 0; n < 8; n++) { offset[0][n] = offset[1][n] = 16; coeff[0][0][n] = (1 << 14) + (1 << 7) + 1; coeff[0][1][n] = (1 << 7) - 1; coeff[0][2][n] = -(1 << 8); coeff[1][0][n] = coeff[2][0][n] = 0; coeff[1][1][n] = (1 << 14) + (1 << 7); coeff[1][2][n] = -(1 << 7); coeff[2][2][n] = (1 << 14) - (1 << 6); coeff[2][1][n] = 1 << 6; } for (idepth = 0; idepth < 3; idepth++) { for (odepth = 0; odepth < 3; odepth++) { for (fmt = 0; fmt < 3; fmt++) { if (check_func(dsp.yuv2yuv[idepth][odepth][fmt], "ff_colorspacedsp_yuv2yuv_%sp%dto%d", format_string[fmt], idepth * 2 + 8, odepth * 2 + 8)) { int ss_w = !!fmt, ss_h = fmt == 2; int y_src_stride = W << !!idepth, y_dst_stride = W << !!odepth; int uv_src_stride = y_src_stride >> ss_w, uv_dst_stride = y_dst_stride >> ss_w; randomize_buffers(); call_ref(dst0, (ptrdiff_t[3]) { y_dst_stride, uv_dst_stride, uv_dst_stride }, src, (ptrdiff_t[3]) { y_src_stride, uv_src_stride, uv_src_stride }, W, H, coeff, offset); call_new(dst1, (ptrdiff_t[3]) { y_dst_stride, uv_dst_stride, uv_dst_stride }, src, (ptrdiff_t[3]) { y_src_stride, uv_src_stride, uv_src_stride }, W, H, coeff, offset); if (memcmp(dst0[0], dst1[0], y_dst_stride * H) || memcmp(dst0[1], dst1[1], uv_dst_stride * H >> ss_h) || memcmp(dst0[2], dst1[2], uv_dst_stride * H >> ss_h)) { fail(); } } } } } report("yuv2yuv"); } static void check_yuv2rgb(void) { declare_func(void, int16_t *dst[3], ptrdiff_t dst_stride, uint8_t *src[3], ptrdiff_t src_stride[3], int w, int h, const int16_t coeff[3][3][8], const int16_t off[8]); ColorSpaceDSPContext dsp; int idepth, fmt, n; LOCAL_ALIGNED_32(uint8_t, src_y, [W * H * 2]); LOCAL_ALIGNED_32(uint8_t, src_u, [W * H * 2]); LOCAL_ALIGNED_32(uint8_t, src_v, [W * H * 2]); uint8_t *src[3] = { src_y, src_u, src_v }; LOCAL_ALIGNED_32(int16_t, dst0_y, [W * H]); LOCAL_ALIGNED_32(int16_t, dst0_u, [W * H]); LOCAL_ALIGNED_32(int16_t, dst0_v, [W * H]); LOCAL_ALIGNED_32(int16_t, dst1_y, [W * H]); LOCAL_ALIGNED_32(int16_t, dst1_u, [W * H]); LOCAL_ALIGNED_32(int16_t, dst1_v, [W * H]); int16_t *dst0[3] = { dst0_y, dst0_u, dst0_v }, *dst1[3] = { dst1_y, dst1_u, dst1_v }; LOCAL_ALIGNED_32(int16_t, offset, [8]); LOCAL_ALIGNED_32(int16_t, coeff_buf, [3 * 3 * 8]); int16_t (*coeff)[3][8] = (int16_t(*)[3][8]) coeff_buf; ff_colorspacedsp_init(&dsp); for (n = 0; n < 8; n++) { offset[n] = 16; coeff[0][0][n] = coeff[1][0][n] = coeff[2][0][n] = (1 << 14) | 1; coeff[0][1][n] = coeff[2][2][n] = 0; coeff[0][2][n] = 1 << 13; coeff[1][1][n] = -(1 << 12); coeff[1][2][n] = 1 << 12; coeff[2][1][n] = 1 << 11; } for (idepth = 0; idepth < 3; idepth++) { for (fmt = 0; fmt < 3; fmt++) { if (check_func(dsp.yuv2rgb[idepth][fmt], "ff_colorspacedsp_yuv2rgb_%sp%d", format_string[fmt], idepth * 2 + 8)) { int ss_w = !!fmt, ss_h = fmt == 2; int y_src_stride = W << !!idepth; int uv_src_stride = y_src_stride >> ss_w; randomize_buffers(); call_ref(dst0, W, src, (ptrdiff_t[3]) { y_src_stride, uv_src_stride, uv_src_stride }, W, H, coeff, offset); call_new(dst1, W, src, (ptrdiff_t[3]) { y_src_stride, uv_src_stride, uv_src_stride }, W, H, coeff, offset); if (memcmp(dst0[0], dst1[0], W * H * sizeof(int16_t)) || memcmp(dst0[1], dst1[1], W * H * sizeof(int16_t)) || memcmp(dst0[2], dst1[2], W * H * sizeof(int16_t))) { fail(); } } } } report("yuv2rgb"); } #undef randomize_buffers #define randomize_buffers() \ do { \ int y, x, p; \ for (p = 0; p < 3; p++) { \ for (y = 0; y < H; y++) { \ for (x = 0; x < W; x++) { \ int r = rnd() & 0x7fff; \ r -= (32768 - 28672) >> 1; \ src[p][y * W + x] = r; \ } \ } \ } \ } while (0) static void check_rgb2yuv(void) { declare_func(void, uint8_t *dst[3], ptrdiff_t dst_stride[3], int16_t *src[3], ptrdiff_t src_stride, int w, int h, const int16_t coeff[3][3][8], const int16_t off[8]); ColorSpaceDSPContext dsp; int odepth, fmt, n; LOCAL_ALIGNED_32(int16_t, src_y, [W * H * 2]); LOCAL_ALIGNED_32(int16_t, src_u, [W * H * 2]); LOCAL_ALIGNED_32(int16_t, src_v, [W * H * 2]); int16_t *src[3] = { src_y, src_u, src_v }; LOCAL_ALIGNED_32(uint8_t, dst0_y, [W * H * 2]); LOCAL_ALIGNED_32(uint8_t, dst0_u, [W * H * 2]); LOCAL_ALIGNED_32(uint8_t, dst0_v, [W * H * 2]); LOCAL_ALIGNED_32(uint8_t, dst1_y, [W * H * 2]); LOCAL_ALIGNED_32(uint8_t, dst1_u, [W * H * 2]); LOCAL_ALIGNED_32(uint8_t, dst1_v, [W * H * 2]); uint8_t *dst0[3] = { dst0_y, dst0_u, dst0_v }, *dst1[3] = { dst1_y, dst1_u, dst1_v }; LOCAL_ALIGNED_32(int16_t, offset, [8]); LOCAL_ALIGNED_32(int16_t, coeff_buf, [3 * 3 * 8]); int16_t (*coeff)[3][8] = (int16_t(*)[3][8]) coeff_buf; ff_colorspacedsp_init(&dsp); for (n = 0; n < 8; n++) { offset[n] = 16; // these somewhat resemble bt601/smpte170m coefficients coeff[0][0][n] = lrint(0.3 * (1 << 14)); coeff[0][1][n] = lrint(0.6 * (1 << 14)); coeff[0][2][n] = lrint(0.1 * (1 << 14)); coeff[1][0][n] = lrint(-0.15 * (1 << 14)); coeff[1][1][n] = lrint(-0.35 * (1 << 14)); coeff[1][2][n] = lrint(0.5 * (1 << 14)); coeff[2][0][n] = lrint(0.5 * (1 << 14)); coeff[2][1][n] = lrint(-0.42 * (1 << 14)); coeff[2][2][n] = lrint(-0.08 * (1 << 14)); } for (odepth = 0; odepth < 3; odepth++) { for (fmt = 0; fmt < 3; fmt++) { if (check_func(dsp.rgb2yuv[odepth][fmt], "ff_colorspacedsp_rgb2yuv_%sp%d", format_string[fmt], odepth * 2 + 8)) { int ss_w = !!fmt, ss_h = fmt == 2; int y_dst_stride = W << !!odepth; int uv_dst_stride = y_dst_stride >> ss_w; randomize_buffers(); call_ref(dst0, (ptrdiff_t[3]) { y_dst_stride, uv_dst_stride, uv_dst_stride }, src, W, W, H, coeff, offset); call_new(dst1, (ptrdiff_t[3]) { y_dst_stride, uv_dst_stride, uv_dst_stride }, src, W, W, H, coeff, offset); if (memcmp(dst0[0], dst1[0], H * y_dst_stride) || memcmp(dst0[1], dst1[1], H * uv_dst_stride >> ss_h) || memcmp(dst0[2], dst1[2], H * uv_dst_stride >> ss_h)) { fail(); } } } } report("rgb2yuv"); } static void check_multiply3x3(void) { declare_func(void, int16_t *data[3], ptrdiff_t stride, int w, int h, const int16_t coeff[3][3][8]); ColorSpaceDSPContext dsp; LOCAL_ALIGNED_32(int16_t, dst0_y, [W * H]); LOCAL_ALIGNED_32(int16_t, dst0_u, [W * H]); LOCAL_ALIGNED_32(int16_t, dst0_v, [W * H]); LOCAL_ALIGNED_32(int16_t, dst1_y, [W * H]); LOCAL_ALIGNED_32(int16_t, dst1_u, [W * H]); LOCAL_ALIGNED_32(int16_t, dst1_v, [W * H]); int16_t *dst0[3] = { dst0_y, dst0_u, dst0_v }, *dst1[3] = { dst1_y, dst1_u, dst1_v }; int16_t **src = dst0; LOCAL_ALIGNED_32(int16_t, coeff_buf, [3 * 3 * 8]); int16_t (*coeff)[3][8] = (int16_t(*)[3][8]) coeff_buf; int n; ff_colorspacedsp_init(&dsp); for (n = 0; n < 8; n++) { coeff[0][0][n] = lrint(0.85 * (1 << 14)); coeff[0][1][n] = lrint(0.10 * (1 << 14)); coeff[0][2][n] = lrint(0.05 * (1 << 14)); coeff[1][0][n] = lrint(-0.1 * (1 << 14)); coeff[1][1][n] = lrint(0.95 * (1 << 14)); coeff[1][2][n] = lrint(0.15 * (1 << 14)); coeff[2][0][n] = lrint(-0.2 * (1 << 14)); coeff[2][1][n] = lrint(0.30 * (1 << 14)); coeff[2][2][n] = lrint(0.90 * (1 << 14)); } if (check_func(dsp.multiply3x3, "ff_colorspacedsp_multiply3x3")) { randomize_buffers(); memcpy(dst1_y, dst0_y, W * H * sizeof(*dst1_y)); memcpy(dst1_u, dst0_u, W * H * sizeof(*dst1_u)); memcpy(dst1_v, dst0_v, W * H * sizeof(*dst1_v)); call_ref(dst0, W, W, H, coeff); call_new(dst1, W, W, H, coeff); if (memcmp(dst0[0], dst1[0], H * W * sizeof(*dst0_y)) || memcmp(dst0[1], dst1[1], H * W * sizeof(*dst0_u)) || memcmp(dst0[2], dst1[2], H * W * sizeof(*dst0_v))) { fail(); } } report("multiply3x3"); } void checkasm_check_colorspace(void) { check_yuv2yuv(); check_yuv2rgb(); check_rgb2yuv(); check_multiply3x3(); }
null
null
null
null
69,535
12,766
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
12,766
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 "components/update_client/protocol_parser.h" #include <stddef.h> #include <algorithm> #include <memory> #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/version.h" #include "libxml/tree.h" #include "third_party/libxml/chromium/libxml_utils.h" namespace update_client { const char ProtocolParser::Result::kCohort[] = "cohort"; const char ProtocolParser::Result::kCohortHint[] = "cohorthint"; const char ProtocolParser::Result::kCohortName[] = "cohortname"; ProtocolParser::ProtocolParser() = default; ProtocolParser::~ProtocolParser() = default; ProtocolParser::Results::Results() = default; ProtocolParser::Results::Results(const Results& other) = default; ProtocolParser::Results::~Results() = default; ProtocolParser::Result::Result() = default; ProtocolParser::Result::Result(const Result& other) = default; ProtocolParser::Result::~Result() = default; ProtocolParser::Result::Manifest::Manifest() = default; ProtocolParser::Result::Manifest::Manifest(const Manifest& other) = default; ProtocolParser::Result::Manifest::~Manifest() = default; ProtocolParser::Result::Manifest::Package::Package() = default; ProtocolParser::Result::Manifest::Package::Package(const Package& other) = default; ProtocolParser::Result::Manifest::Package::~Package() = default; void ProtocolParser::ParseError(const char* details, ...) { va_list args; va_start(args, details); if (!errors_.empty()) { errors_ += "\r\n"; } base::StringAppendV(&errors_, details, args); va_end(args); } // Checks whether a given node's name matches |expected_name|. static bool TagNameEquals(const xmlNode* node, const char* expected_name) { return 0 == strcmp(expected_name, reinterpret_cast<const char*>(node->name)); } // Returns child nodes of |root| with name |name|. static std::vector<xmlNode*> GetChildren(xmlNode* root, const char* name) { std::vector<xmlNode*> result; for (xmlNode* child = root->children; child != nullptr; child = child->next) { if (!TagNameEquals(child, name)) { continue; } result.push_back(child); } return result; } // Returns the value of a named attribute, or the empty string. static std::string GetAttribute(xmlNode* node, const char* attribute_name) { const xmlChar* name = reinterpret_cast<const xmlChar*>(attribute_name); for (xmlAttr* attr = node->properties; attr != nullptr; attr = attr->next) { if (!xmlStrcmp(attr->name, name) && attr->children && attr->children->content) { return std::string( reinterpret_cast<const char*>(attr->children->content)); } } return std::string(); } // Returns the value of a named attribute, or nullptr . static std::unique_ptr<std::string> GetAttributePtr( xmlNode* node, const char* attribute_name) { const xmlChar* name = reinterpret_cast<const xmlChar*>(attribute_name); for (xmlAttr* attr = node->properties; attr != nullptr; attr = attr->next) { if (!xmlStrcmp(attr->name, name) && attr->children && attr->children->content) { return std::make_unique<std::string>( reinterpret_cast<const char*>(attr->children->content)); } } return nullptr; } // This is used for the xml parser to report errors. This assumes the context // is a pointer to a std::string where the error message should be appended. static void XmlErrorFunc(void* context, const char* message, ...) { va_list args; va_start(args, message); std::string* error = static_cast<std::string*>(context); base::StringAppendV(error, message, args); va_end(args); } // Utility class for cleaning up the xml document when leaving a scope. class ScopedXmlDocument { public: explicit ScopedXmlDocument(xmlDocPtr document) : document_(document) {} ~ScopedXmlDocument() { if (document_) xmlFreeDoc(document_); } xmlDocPtr get() { return document_; } private: xmlDocPtr document_; }; // Parses the <package> tag. bool ParsePackageTag(xmlNode* package, ProtocolParser::Result* result, std::string* error) { ProtocolParser::Result::Manifest::Package p; p.name = GetAttribute(package, "name"); if (p.name.empty()) { *error = "Missing name for package."; return false; } p.namediff = GetAttribute(package, "namediff"); // package_fingerprint is optional. It identifies the package, preferably // with a modified sha256 hash of the package in hex format. p.fingerprint = GetAttribute(package, "fp"); p.hash_sha256 = GetAttribute(package, "hash_sha256"); int size = 0; if (base::StringToInt(GetAttribute(package, "size"), &size)) { p.size = size; } p.hashdiff_sha256 = GetAttribute(package, "hashdiff_sha256"); int sizediff = 0; if (base::StringToInt(GetAttribute(package, "sizediff"), &sizediff)) { p.sizediff = sizediff; } result->manifest.packages.push_back(p); return true; } // Parses the <manifest> tag. bool ParseManifestTag(xmlNode* manifest, ProtocolParser::Result* result, std::string* error) { // Get the version. result->manifest.version = GetAttribute(manifest, "version"); if (result->manifest.version.empty()) { *error = "Missing version for manifest."; return false; } base::Version version(result->manifest.version); if (!version.IsValid()) { *error = "Invalid version: '"; *error += result->manifest.version; *error += "'."; return false; } // Get the minimum browser version (not required). result->manifest.browser_min_version = GetAttribute(manifest, "prodversionmin"); if (result->manifest.browser_min_version.length()) { base::Version browser_min_version(result->manifest.browser_min_version); if (!browser_min_version.IsValid()) { *error = "Invalid prodversionmin: '"; *error += result->manifest.browser_min_version; *error += "'."; return false; } } // Get the <packages> node. std::vector<xmlNode*> packages = GetChildren(manifest, "packages"); if (packages.empty()) { *error = "Missing packages tag on manifest."; return false; } // Parse each of the <package> tags. std::vector<xmlNode*> package = GetChildren(packages[0], "package"); for (size_t i = 0; i != package.size(); ++i) { if (!ParsePackageTag(package[i], result, error)) return false; } return true; } // Parses the <urls> tag and its children in the <updatecheck>. bool ParseUrlsTag(xmlNode* urls, ProtocolParser::Result* result, std::string* error) { // Get the url nodes. std::vector<xmlNode*> url = GetChildren(urls, "url"); if (url.empty()) { *error = "Missing url tags on urls."; return false; } // Get the list of urls for full and optionally, for diff updates. // There can only be either a codebase or a codebasediff attribute in a tag. for (size_t i = 0; i != url.size(); ++i) { // Find the url to the crx file. const GURL crx_url(GetAttribute(url[i], "codebase")); if (crx_url.is_valid()) { result->crx_urls.push_back(crx_url); continue; } const GURL crx_diffurl(GetAttribute(url[i], "codebasediff")); if (crx_diffurl.is_valid()) { result->crx_diffurls.push_back(crx_diffurl); continue; } } // Expect at least one url for full update. if (result->crx_urls.empty()) { *error = "Missing valid url for full update."; return false; } return true; } // Parses the <actions> tag. It picks up the "run" attribute of the first // "action" element in "actions". void ParseActionsTag(xmlNode* updatecheck, ProtocolParser::Result* result) { std::vector<xmlNode*> actions = GetChildren(updatecheck, "actions"); if (actions.empty()) return; std::vector<xmlNode*> action = GetChildren(actions.front(), "action"); if (action.empty()) return; result->action_run = GetAttribute(action.front(), "run"); } // Parses the <updatecheck> tag. bool ParseUpdateCheckTag(xmlNode* updatecheck, ProtocolParser::Result* result, std::string* error) { // Read the |status| attribute. result->status = GetAttribute(updatecheck, "status"); if (result->status.empty()) { *error = "Missing status on updatecheck node"; return false; } if (result->status == "noupdate") { ParseActionsTag(updatecheck, result); return true; } if (result->status == "ok") { std::vector<xmlNode*> urls = GetChildren(updatecheck, "urls"); if (urls.empty()) { *error = "Missing urls on updatecheck."; return false; } if (!ParseUrlsTag(urls[0], result, error)) { return false; } std::vector<xmlNode*> manifests = GetChildren(updatecheck, "manifest"); if (manifests.empty()) { *error = "Missing manifest on updatecheck."; return false; } ParseActionsTag(updatecheck, result); return ParseManifestTag(manifests[0], result, error); } // Return the |updatecheck| element status as a parsing error. *error = result->status; return false; } // Parses a single <app> tag. bool ParseAppTag(xmlNode* app, ProtocolParser::Result* result, std::string* error) { // Read cohort information. auto cohort = GetAttributePtr(app, "cohort"); static const char* attrs[] = {ProtocolParser::Result::kCohort, ProtocolParser::Result::kCohortHint, ProtocolParser::Result::kCohortName}; for (auto* attr : attrs) { auto value = GetAttributePtr(app, attr); if (value) result->cohort_attrs.insert({attr, *value}); } // Read the crx id. result->extension_id = GetAttribute(app, "appid"); if (result->extension_id.empty()) { *error = "Missing appid on app node"; return false; } // Get the <updatecheck> tag. std::vector<xmlNode*> updates = GetChildren(app, "updatecheck"); if (updates.empty()) { *error = "Missing updatecheck on app."; return false; } return ParseUpdateCheckTag(updates[0], result, error); } bool ProtocolParser::Parse(const std::string& response_xml) { results_.daystart_elapsed_seconds = kNoDaystart; results_.daystart_elapsed_days = kNoDaystart; results_.list.clear(); errors_.clear(); if (response_xml.empty()) { ParseError("Empty xml"); return false; } std::string xml_errors; ScopedXmlErrorFunc error_func(&xml_errors, &XmlErrorFunc); // Start up the xml parser with the manifest_xml contents. ScopedXmlDocument document( xmlParseDoc(reinterpret_cast<const xmlChar*>(response_xml.c_str()))); if (!document.get()) { ParseError("%s", xml_errors.c_str()); return false; } xmlNode* root = xmlDocGetRootElement(document.get()); if (!root) { ParseError("Missing root node"); return false; } if (!TagNameEquals(root, "response")) { ParseError("Missing response tag"); return false; } // Check for the response "protocol" attribute. const auto protocol = GetAttribute(root, "protocol"); if (protocol != kProtocolVersion) { ParseError( "Missing/incorrect protocol on response tag " "(expected '%s', found '%s')", kProtocolVersion, protocol.c_str()); return false; } // Parse the first <daystart> if it is present. std::vector<xmlNode*> daystarts = GetChildren(root, "daystart"); if (!daystarts.empty()) { xmlNode* first = daystarts[0]; std::string elapsed_seconds = GetAttribute(first, "elapsed_seconds"); int parsed_elapsed = kNoDaystart; if (base::StringToInt(elapsed_seconds, &parsed_elapsed)) { results_.daystart_elapsed_seconds = parsed_elapsed; } std::string elapsed_days = GetAttribute(first, "elapsed_days"); parsed_elapsed = kNoDaystart; if (base::StringToInt(elapsed_days, &parsed_elapsed)) { results_.daystart_elapsed_days = parsed_elapsed; } } // Parse each of the <app> tags. std::vector<xmlNode*> apps = GetChildren(root, "app"); for (size_t i = 0; i != apps.size(); ++i) { Result result; std::string error; if (ParseAppTag(apps[i], &result, &error)) { results_.list.push_back(result); } else { ParseError("%s", error.c_str()); } } return true; } } // namespace update_client
null
null
null
null
9,629
29,450
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
194,445
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Regulator driver for National Semiconductors LP3971 PMIC chip * * Copyright (C) 2009 Samsung Electronics * Author: Marek Szyprowski <m.szyprowski@samsung.com> * * Based on wm8350.c * * 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. * */ #include <linux/bug.h> #include <linux/err.h> #include <linux/i2c.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/regulator/driver.h> #include <linux/regulator/lp3971.h> #include <linux/slab.h> struct lp3971 { struct device *dev; struct mutex io_lock; struct i2c_client *i2c; }; static u8 lp3971_reg_read(struct lp3971 *lp3971, u8 reg); static int lp3971_set_bits(struct lp3971 *lp3971, u8 reg, u16 mask, u16 val); #define LP3971_SYS_CONTROL1_REG 0x07 /* System control register 1 initial value, bits 4 and 5 are EPROM programmable */ #define SYS_CONTROL1_INIT_VAL 0x40 #define SYS_CONTROL1_INIT_MASK 0xCF #define LP3971_BUCK_VOL_ENABLE_REG 0x10 #define LP3971_BUCK_VOL_CHANGE_REG 0x20 /* Voltage control registers shift: LP3971_BUCK1 -> 0 LP3971_BUCK2 -> 4 LP3971_BUCK3 -> 6 */ #define BUCK_VOL_CHANGE_SHIFT(x) (((!!x) << 2) | (x & ~0x01)) #define BUCK_VOL_CHANGE_FLAG_GO 0x01 #define BUCK_VOL_CHANGE_FLAG_TARGET 0x02 #define BUCK_VOL_CHANGE_FLAG_MASK 0x03 #define LP3971_BUCK1_BASE 0x23 #define LP3971_BUCK2_BASE 0x29 #define LP3971_BUCK3_BASE 0x32 static const int buck_base_addr[] = { LP3971_BUCK1_BASE, LP3971_BUCK2_BASE, LP3971_BUCK3_BASE, }; #define LP3971_BUCK_TARGET_VOL1_REG(x) (buck_base_addr[x]) #define LP3971_BUCK_TARGET_VOL2_REG(x) (buck_base_addr[x]+1) static const unsigned int buck_voltage_map[] = { 0, 800000, 850000, 900000, 950000, 1000000, 1050000, 1100000, 1150000, 1200000, 1250000, 1300000, 1350000, 1400000, 1450000, 1500000, 1550000, 1600000, 1650000, 1700000, 1800000, 1900000, 2500000, 2800000, 3000000, 3300000, }; #define BUCK_TARGET_VOL_MASK 0x3f #define LP3971_BUCK_RAMP_REG(x) (buck_base_addr[x]+2) #define LP3971_LDO_ENABLE_REG 0x12 #define LP3971_LDO_VOL_CONTR_BASE 0x39 /* Voltage control registers: LP3971_LDO1 -> LP3971_LDO_VOL_CONTR_BASE + 0 LP3971_LDO2 -> LP3971_LDO_VOL_CONTR_BASE + 0 LP3971_LDO3 -> LP3971_LDO_VOL_CONTR_BASE + 1 LP3971_LDO4 -> LP3971_LDO_VOL_CONTR_BASE + 1 LP3971_LDO5 -> LP3971_LDO_VOL_CONTR_BASE + 2 */ #define LP3971_LDO_VOL_CONTR_REG(x) (LP3971_LDO_VOL_CONTR_BASE + (x >> 1)) /* Voltage control registers shift: LP3971_LDO1 -> 0, LP3971_LDO2 -> 4 LP3971_LDO3 -> 0, LP3971_LDO4 -> 4 LP3971_LDO5 -> 0 */ #define LDO_VOL_CONTR_SHIFT(x) ((x & 1) << 2) #define LDO_VOL_CONTR_MASK 0x0f static const unsigned int ldo45_voltage_map[] = { 1000000, 1050000, 1100000, 1150000, 1200000, 1250000, 1300000, 1350000, 1400000, 1500000, 1800000, 1900000, 2500000, 2800000, 3000000, 3300000, }; static const unsigned int ldo123_voltage_map[] = { 1800000, 1900000, 2000000, 2100000, 2200000, 2300000, 2400000, 2500000, 2600000, 2700000, 2800000, 2900000, 3000000, 3100000, 3200000, 3300000, }; #define LDO_VOL_MIN_IDX 0x00 #define LDO_VOL_MAX_IDX 0x0f static int lp3971_ldo_is_enabled(struct regulator_dev *dev) { struct lp3971 *lp3971 = rdev_get_drvdata(dev); int ldo = rdev_get_id(dev) - LP3971_LDO1; u16 mask = 1 << (1 + ldo); u16 val; val = lp3971_reg_read(lp3971, LP3971_LDO_ENABLE_REG); return (val & mask) != 0; } static int lp3971_ldo_enable(struct regulator_dev *dev) { struct lp3971 *lp3971 = rdev_get_drvdata(dev); int ldo = rdev_get_id(dev) - LP3971_LDO1; u16 mask = 1 << (1 + ldo); return lp3971_set_bits(lp3971, LP3971_LDO_ENABLE_REG, mask, mask); } static int lp3971_ldo_disable(struct regulator_dev *dev) { struct lp3971 *lp3971 = rdev_get_drvdata(dev); int ldo = rdev_get_id(dev) - LP3971_LDO1; u16 mask = 1 << (1 + ldo); return lp3971_set_bits(lp3971, LP3971_LDO_ENABLE_REG, mask, 0); } static int lp3971_ldo_get_voltage_sel(struct regulator_dev *dev) { struct lp3971 *lp3971 = rdev_get_drvdata(dev); int ldo = rdev_get_id(dev) - LP3971_LDO1; u16 val, reg; reg = lp3971_reg_read(lp3971, LP3971_LDO_VOL_CONTR_REG(ldo)); val = (reg >> LDO_VOL_CONTR_SHIFT(ldo)) & LDO_VOL_CONTR_MASK; return val; } static int lp3971_ldo_set_voltage_sel(struct regulator_dev *dev, unsigned int selector) { struct lp3971 *lp3971 = rdev_get_drvdata(dev); int ldo = rdev_get_id(dev) - LP3971_LDO1; return lp3971_set_bits(lp3971, LP3971_LDO_VOL_CONTR_REG(ldo), LDO_VOL_CONTR_MASK << LDO_VOL_CONTR_SHIFT(ldo), selector << LDO_VOL_CONTR_SHIFT(ldo)); } static struct regulator_ops lp3971_ldo_ops = { .list_voltage = regulator_list_voltage_table, .map_voltage = regulator_map_voltage_ascend, .is_enabled = lp3971_ldo_is_enabled, .enable = lp3971_ldo_enable, .disable = lp3971_ldo_disable, .get_voltage_sel = lp3971_ldo_get_voltage_sel, .set_voltage_sel = lp3971_ldo_set_voltage_sel, }; static int lp3971_dcdc_is_enabled(struct regulator_dev *dev) { struct lp3971 *lp3971 = rdev_get_drvdata(dev); int buck = rdev_get_id(dev) - LP3971_DCDC1; u16 mask = 1 << (buck * 2); u16 val; val = lp3971_reg_read(lp3971, LP3971_BUCK_VOL_ENABLE_REG); return (val & mask) != 0; } static int lp3971_dcdc_enable(struct regulator_dev *dev) { struct lp3971 *lp3971 = rdev_get_drvdata(dev); int buck = rdev_get_id(dev) - LP3971_DCDC1; u16 mask = 1 << (buck * 2); return lp3971_set_bits(lp3971, LP3971_BUCK_VOL_ENABLE_REG, mask, mask); } static int lp3971_dcdc_disable(struct regulator_dev *dev) { struct lp3971 *lp3971 = rdev_get_drvdata(dev); int buck = rdev_get_id(dev) - LP3971_DCDC1; u16 mask = 1 << (buck * 2); return lp3971_set_bits(lp3971, LP3971_BUCK_VOL_ENABLE_REG, mask, 0); } static int lp3971_dcdc_get_voltage_sel(struct regulator_dev *dev) { struct lp3971 *lp3971 = rdev_get_drvdata(dev); int buck = rdev_get_id(dev) - LP3971_DCDC1; u16 reg; reg = lp3971_reg_read(lp3971, LP3971_BUCK_TARGET_VOL1_REG(buck)); reg &= BUCK_TARGET_VOL_MASK; return reg; } static int lp3971_dcdc_set_voltage_sel(struct regulator_dev *dev, unsigned int selector) { struct lp3971 *lp3971 = rdev_get_drvdata(dev); int buck = rdev_get_id(dev) - LP3971_DCDC1; int ret; ret = lp3971_set_bits(lp3971, LP3971_BUCK_TARGET_VOL1_REG(buck), BUCK_TARGET_VOL_MASK, selector); if (ret) return ret; ret = lp3971_set_bits(lp3971, LP3971_BUCK_VOL_CHANGE_REG, BUCK_VOL_CHANGE_FLAG_MASK << BUCK_VOL_CHANGE_SHIFT(buck), BUCK_VOL_CHANGE_FLAG_GO << BUCK_VOL_CHANGE_SHIFT(buck)); if (ret) return ret; return lp3971_set_bits(lp3971, LP3971_BUCK_VOL_CHANGE_REG, BUCK_VOL_CHANGE_FLAG_MASK << BUCK_VOL_CHANGE_SHIFT(buck), 0 << BUCK_VOL_CHANGE_SHIFT(buck)); } static struct regulator_ops lp3971_dcdc_ops = { .list_voltage = regulator_list_voltage_table, .map_voltage = regulator_map_voltage_ascend, .is_enabled = lp3971_dcdc_is_enabled, .enable = lp3971_dcdc_enable, .disable = lp3971_dcdc_disable, .get_voltage_sel = lp3971_dcdc_get_voltage_sel, .set_voltage_sel = lp3971_dcdc_set_voltage_sel, }; static const struct regulator_desc regulators[] = { { .name = "LDO1", .id = LP3971_LDO1, .ops = &lp3971_ldo_ops, .n_voltages = ARRAY_SIZE(ldo123_voltage_map), .volt_table = ldo123_voltage_map, .type = REGULATOR_VOLTAGE, .owner = THIS_MODULE, }, { .name = "LDO2", .id = LP3971_LDO2, .ops = &lp3971_ldo_ops, .n_voltages = ARRAY_SIZE(ldo123_voltage_map), .volt_table = ldo123_voltage_map, .type = REGULATOR_VOLTAGE, .owner = THIS_MODULE, }, { .name = "LDO3", .id = LP3971_LDO3, .ops = &lp3971_ldo_ops, .n_voltages = ARRAY_SIZE(ldo123_voltage_map), .volt_table = ldo123_voltage_map, .type = REGULATOR_VOLTAGE, .owner = THIS_MODULE, }, { .name = "LDO4", .id = LP3971_LDO4, .ops = &lp3971_ldo_ops, .n_voltages = ARRAY_SIZE(ldo45_voltage_map), .volt_table = ldo45_voltage_map, .type = REGULATOR_VOLTAGE, .owner = THIS_MODULE, }, { .name = "LDO5", .id = LP3971_LDO5, .ops = &lp3971_ldo_ops, .n_voltages = ARRAY_SIZE(ldo45_voltage_map), .volt_table = ldo45_voltage_map, .type = REGULATOR_VOLTAGE, .owner = THIS_MODULE, }, { .name = "DCDC1", .id = LP3971_DCDC1, .ops = &lp3971_dcdc_ops, .n_voltages = ARRAY_SIZE(buck_voltage_map), .volt_table = buck_voltage_map, .type = REGULATOR_VOLTAGE, .owner = THIS_MODULE, }, { .name = "DCDC2", .id = LP3971_DCDC2, .ops = &lp3971_dcdc_ops, .n_voltages = ARRAY_SIZE(buck_voltage_map), .volt_table = buck_voltage_map, .type = REGULATOR_VOLTAGE, .owner = THIS_MODULE, }, { .name = "DCDC3", .id = LP3971_DCDC3, .ops = &lp3971_dcdc_ops, .n_voltages = ARRAY_SIZE(buck_voltage_map), .volt_table = buck_voltage_map, .type = REGULATOR_VOLTAGE, .owner = THIS_MODULE, }, }; static int lp3971_i2c_read(struct i2c_client *i2c, char reg, int count, u16 *dest) { int ret; if (count != 1) return -EIO; ret = i2c_smbus_read_byte_data(i2c, reg); if (ret < 0) return ret; *dest = ret; return 0; } static int lp3971_i2c_write(struct i2c_client *i2c, char reg, int count, const u16 *src) { if (count != 1) return -EIO; return i2c_smbus_write_byte_data(i2c, reg, *src); } static u8 lp3971_reg_read(struct lp3971 *lp3971, u8 reg) { u16 val = 0; mutex_lock(&lp3971->io_lock); lp3971_i2c_read(lp3971->i2c, reg, 1, &val); dev_dbg(lp3971->dev, "reg read 0x%02x -> 0x%02x\n", (int)reg, (unsigned)val&0xff); mutex_unlock(&lp3971->io_lock); return val & 0xff; } static int lp3971_set_bits(struct lp3971 *lp3971, u8 reg, u16 mask, u16 val) { u16 tmp; int ret; mutex_lock(&lp3971->io_lock); ret = lp3971_i2c_read(lp3971->i2c, reg, 1, &tmp); if (ret == 0) { tmp = (tmp & ~mask) | val; ret = lp3971_i2c_write(lp3971->i2c, reg, 1, &tmp); dev_dbg(lp3971->dev, "reg write 0x%02x -> 0x%02x\n", (int)reg, (unsigned)val&0xff); } mutex_unlock(&lp3971->io_lock); return ret; } static int setup_regulators(struct lp3971 *lp3971, struct lp3971_platform_data *pdata) { int i, err; /* Instantiate the regulators */ for (i = 0; i < pdata->num_regulators; i++) { struct regulator_config config = { }; struct lp3971_regulator_subdev *reg = &pdata->regulators[i]; struct regulator_dev *rdev; config.dev = lp3971->dev; config.init_data = reg->initdata; config.driver_data = lp3971; rdev = devm_regulator_register(lp3971->dev, &regulators[reg->id], &config); if (IS_ERR(rdev)) { err = PTR_ERR(rdev); dev_err(lp3971->dev, "regulator init failed: %d\n", err); return err; } } return 0; } static int lp3971_i2c_probe(struct i2c_client *i2c, const struct i2c_device_id *id) { struct lp3971 *lp3971; struct lp3971_platform_data *pdata = dev_get_platdata(&i2c->dev); int ret; u16 val; if (!pdata) { dev_dbg(&i2c->dev, "No platform init data supplied\n"); return -ENODEV; } lp3971 = devm_kzalloc(&i2c->dev, sizeof(struct lp3971), GFP_KERNEL); if (lp3971 == NULL) return -ENOMEM; lp3971->i2c = i2c; lp3971->dev = &i2c->dev; mutex_init(&lp3971->io_lock); /* Detect LP3971 */ ret = lp3971_i2c_read(i2c, LP3971_SYS_CONTROL1_REG, 1, &val); if (ret == 0 && (val & SYS_CONTROL1_INIT_MASK) != SYS_CONTROL1_INIT_VAL) ret = -ENODEV; if (ret < 0) { dev_err(&i2c->dev, "failed to detect device\n"); return ret; } ret = setup_regulators(lp3971, pdata); if (ret < 0) return ret; i2c_set_clientdata(i2c, lp3971); return 0; } static const struct i2c_device_id lp3971_i2c_id[] = { { "lp3971", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, lp3971_i2c_id); static struct i2c_driver lp3971_i2c_driver = { .driver = { .name = "LP3971", }, .probe = lp3971_i2c_probe, .id_table = lp3971_i2c_id, }; module_i2c_driver(lp3971_i2c_driver); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Marek Szyprowski <m.szyprowski@samsung.com>"); MODULE_DESCRIPTION("LP3971 PMIC driver");
null
null
null
null
102,792
48,597
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
48,597
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 UI_VIEWS_MUS_MUS_PROPERTY_MIRROR_H_ #define UI_VIEWS_MUS_MUS_PROPERTY_MIRROR_H_ #include "ui/views/mus/mus_export.h" namespace aura { class Window; } namespace views { // Facilitates copying mus client window properties to their mash frame windows. class VIEWS_MUS_EXPORT MusPropertyMirror { public: virtual ~MusPropertyMirror() {} // Called when a property with the given |key| has changed for |window|. // |window| is what mus clients get when calling |widget->GetNativeWindow()|. // |root_window| is the top-level window representing the widget that is owned // by the window manager and that the window manager observes for changes. // Various ash features rely on property values of mus clients' root windows. virtual void MirrorPropertyFromWidgetWindowToRootWindow( aura::Window* window, aura::Window* root_window, const void* key) = 0; }; } // namespace views #endif // UI_VIEWS_MUS_MUS_PROPERTY_MIRROR_H_
null
null
null
null
45,460
1,448
null
train_val
1b0d3845b454eaaac0b2064c78926ca4d739a080
264,016
qemu
0
https://github.com/bonzini/qemu
2016-10-18 11:40:27+01:00
/* * QEMU Guest Agent common/cross-platform command implementations * * Copyright IBM Corp. 2012 * * Authors: * Michael Roth <mdroth@linux.vnet.ibm.com> * * This work is licensed under the terms of the GNU GPL, version 2 or later. * See the COPYING file in the top-level directory. */ #include "qemu/osdep.h" #include "qga/guest-agent-core.h" #include "qga-qmp-commands.h" #include "qapi/qmp/qerror.h" #include "qemu/base64.h" #include "qemu/cutils.h" #include "qemu/atomic.h" /* Maximum captured guest-exec out_data/err_data - 16MB */ #define GUEST_EXEC_MAX_OUTPUT (16*1024*1024) /* Allocation and I/O buffer for reading guest-exec out_data/err_data - 4KB */ #define GUEST_EXEC_IO_SIZE (4*1024) /* Note: in some situations, like with the fsfreeze, logging may be * temporarilly disabled. if it is necessary that a command be able * to log for accounting purposes, check ga_logging_enabled() beforehand, * and use the QERR_QGA_LOGGING_DISABLED to generate an error */ void slog(const gchar *fmt, ...) { va_list ap; va_start(ap, fmt); g_logv("syslog", G_LOG_LEVEL_INFO, fmt, ap); va_end(ap); } int64_t qmp_guest_sync_delimited(int64_t id, Error **errp) { ga_set_response_delimited(ga_state); return id; } int64_t qmp_guest_sync(int64_t id, Error **errp) { return id; } void qmp_guest_ping(Error **errp) { slog("guest-ping called"); } static void qmp_command_info(QmpCommand *cmd, void *opaque) { GuestAgentInfo *info = opaque; GuestAgentCommandInfo *cmd_info; GuestAgentCommandInfoList *cmd_info_list; cmd_info = g_new0(GuestAgentCommandInfo, 1); cmd_info->name = g_strdup(qmp_command_name(cmd)); cmd_info->enabled = qmp_command_is_enabled(cmd); cmd_info->success_response = qmp_has_success_response(cmd); cmd_info_list = g_new0(GuestAgentCommandInfoList, 1); cmd_info_list->value = cmd_info; cmd_info_list->next = info->supported_commands; info->supported_commands = cmd_info_list; } struct GuestAgentInfo *qmp_guest_info(Error **errp) { GuestAgentInfo *info = g_new0(GuestAgentInfo, 1); info->version = g_strdup(QEMU_VERSION); qmp_for_each_command(qmp_command_info, info); return info; } struct GuestExecIOData { guchar *data; gsize size; gsize length; bool closed; bool truncated; const char *name; }; typedef struct GuestExecIOData GuestExecIOData; struct GuestExecInfo { GPid pid; int64_t pid_numeric; gint status; bool has_output; bool finished; GuestExecIOData in; GuestExecIOData out; GuestExecIOData err; QTAILQ_ENTRY(GuestExecInfo) next; }; typedef struct GuestExecInfo GuestExecInfo; static struct { QTAILQ_HEAD(, GuestExecInfo) processes; } guest_exec_state = { .processes = QTAILQ_HEAD_INITIALIZER(guest_exec_state.processes), }; static int64_t gpid_to_int64(GPid pid) { #ifdef G_OS_WIN32 return GetProcessId(pid); #else return (int64_t)pid; #endif } static GuestExecInfo *guest_exec_info_add(GPid pid) { GuestExecInfo *gei; gei = g_new0(GuestExecInfo, 1); gei->pid = pid; gei->pid_numeric = gpid_to_int64(pid); QTAILQ_INSERT_TAIL(&guest_exec_state.processes, gei, next); return gei; } static GuestExecInfo *guest_exec_info_find(int64_t pid_numeric) { GuestExecInfo *gei; QTAILQ_FOREACH(gei, &guest_exec_state.processes, next) { if (gei->pid_numeric == pid_numeric) { return gei; } } return NULL; } GuestExecStatus *qmp_guest_exec_status(int64_t pid, Error **err) { GuestExecInfo *gei; GuestExecStatus *ges; slog("guest-exec-status called, pid: %u", (uint32_t)pid); gei = guest_exec_info_find(pid); if (gei == NULL) { error_setg(err, QERR_INVALID_PARAMETER, "pid"); return NULL; } ges = g_new0(GuestExecStatus, 1); bool finished = atomic_mb_read(&gei->finished); /* need to wait till output channels are closed * to be sure we captured all output at this point */ if (gei->has_output) { finished = finished && atomic_mb_read(&gei->out.closed); finished = finished && atomic_mb_read(&gei->err.closed); } ges->exited = finished; if (finished) { /* Glib has no portable way to parse exit status. * On UNIX, we can get either exit code from normal termination * or signal number. * On Windows, it is either the same exit code or the exception * value for an unhandled exception that caused the process * to terminate. * See MSDN for GetExitCodeProcess() and ntstatus.h for possible * well-known codes, e.g. C0000005 ACCESS_DENIED - analog of SIGSEGV * References: * https://msdn.microsoft.com/en-us/library/windows/desktop/ms683189(v=vs.85).aspx * https://msdn.microsoft.com/en-us/library/aa260331(v=vs.60).aspx */ #ifdef G_OS_WIN32 /* Additionally WIN32 does not provide any additional information * on whether the child exited or terminated via signal. * We use this simple range check to distinguish application exit code * (usually value less then 256) and unhandled exception code with * ntstatus (always value greater then 0xC0000005). */ if ((uint32_t)gei->status < 0xC0000000U) { ges->has_exitcode = true; ges->exitcode = gei->status; } else { ges->has_signal = true; ges->signal = gei->status; } #else if (WIFEXITED(gei->status)) { ges->has_exitcode = true; ges->exitcode = WEXITSTATUS(gei->status); } else if (WIFSIGNALED(gei->status)) { ges->has_signal = true; ges->signal = WTERMSIG(gei->status); } #endif if (gei->out.length > 0) { ges->has_out_data = true; ges->out_data = g_base64_encode(gei->out.data, gei->out.length); g_free(gei->out.data); ges->has_out_truncated = gei->out.truncated; } if (gei->err.length > 0) { ges->has_err_data = true; ges->err_data = g_base64_encode(gei->err.data, gei->err.length); g_free(gei->err.data); ges->has_err_truncated = gei->err.truncated; } QTAILQ_REMOVE(&guest_exec_state.processes, gei, next); g_free(gei); } return ges; } /* Get environment variables or arguments array for execve(). */ static char **guest_exec_get_args(const strList *entry, bool log) { const strList *it; int count = 1, i = 0; /* reserve for NULL terminator */ char **args; char *str; /* for logging array of arguments */ size_t str_size = 1; for (it = entry; it != NULL; it = it->next) { count++; str_size += 1 + strlen(it->value); } str = g_malloc(str_size); *str = 0; args = g_malloc(count * sizeof(char *)); for (it = entry; it != NULL; it = it->next) { args[i++] = it->value; pstrcat(str, str_size, it->value); if (it->next) { pstrcat(str, str_size, " "); } } args[i] = NULL; if (log) { slog("guest-exec called: \"%s\"", str); } g_free(str); return args; } static void guest_exec_child_watch(GPid pid, gint status, gpointer data) { GuestExecInfo *gei = (GuestExecInfo *)data; g_debug("guest_exec_child_watch called, pid: %d, status: %u", (int32_t)gpid_to_int64(pid), (uint32_t)status); gei->status = status; atomic_mb_set(&gei->finished, true); g_spawn_close_pid(pid); } /** Reset ignored signals back to default. */ static void guest_exec_task_setup(gpointer data) { #if !defined(G_OS_WIN32) struct sigaction sigact; memset(&sigact, 0, sizeof(struct sigaction)); sigact.sa_handler = SIG_DFL; if (sigaction(SIGPIPE, &sigact, NULL) != 0) { slog("sigaction() failed to reset child process's SIGPIPE: %s", strerror(errno)); } #endif } static gboolean guest_exec_input_watch(GIOChannel *ch, GIOCondition cond, gpointer p_) { GuestExecIOData *p = (GuestExecIOData *)p_; gsize bytes_written = 0; GIOStatus status; GError *gerr = NULL; /* nothing left to write */ if (p->size == p->length) { goto done; } status = g_io_channel_write_chars(ch, (gchar *)p->data + p->length, p->size - p->length, &bytes_written, &gerr); /* can be not 0 even if not G_IO_STATUS_NORMAL */ if (bytes_written != 0) { p->length += bytes_written; } /* continue write, our callback will be called again */ if (status == G_IO_STATUS_NORMAL || status == G_IO_STATUS_AGAIN) { return true; } if (gerr) { g_warning("qga: i/o error writing to input_data channel: %s", gerr->message); g_error_free(gerr); } done: g_io_channel_shutdown(ch, true, NULL); g_io_channel_unref(ch); atomic_mb_set(&p->closed, true); g_free(p->data); return false; } static gboolean guest_exec_output_watch(GIOChannel *ch, GIOCondition cond, gpointer p_) { GuestExecIOData *p = (GuestExecIOData *)p_; gsize bytes_read; GIOStatus gstatus; if (cond == G_IO_HUP || cond == G_IO_ERR) { goto close; } if (p->size == p->length) { gpointer t = NULL; if (!p->truncated && p->size < GUEST_EXEC_MAX_OUTPUT) { t = g_try_realloc(p->data, p->size + GUEST_EXEC_IO_SIZE); } if (t == NULL) { /* ignore truncated output */ gchar buf[GUEST_EXEC_IO_SIZE]; p->truncated = true; gstatus = g_io_channel_read_chars(ch, buf, sizeof(buf), &bytes_read, NULL); if (gstatus == G_IO_STATUS_EOF || gstatus == G_IO_STATUS_ERROR) { goto close; } return true; } p->size += GUEST_EXEC_IO_SIZE; p->data = t; } /* Calling read API once. * On next available data our callback will be called again */ gstatus = g_io_channel_read_chars(ch, (gchar *)p->data + p->length, p->size - p->length, &bytes_read, NULL); if (gstatus == G_IO_STATUS_EOF || gstatus == G_IO_STATUS_ERROR) { goto close; } p->length += bytes_read; return true; close: g_io_channel_shutdown(ch, true, NULL); g_io_channel_unref(ch); atomic_mb_set(&p->closed, true); return false; } GuestExec *qmp_guest_exec(const char *path, bool has_arg, strList *arg, bool has_env, strList *env, bool has_input_data, const char *input_data, bool has_capture_output, bool capture_output, Error **err) { GPid pid; GuestExec *ge = NULL; GuestExecInfo *gei; char **argv, **envp; strList arglist; gboolean ret; GError *gerr = NULL; gint in_fd, out_fd, err_fd; GIOChannel *in_ch, *out_ch, *err_ch; GSpawnFlags flags; bool has_output = (has_capture_output && capture_output); uint8_t *input = NULL; size_t ninput = 0; arglist.value = (char *)path; arglist.next = has_arg ? arg : NULL; if (has_input_data) { input = qbase64_decode(input_data, -1, &ninput, err); if (!input) { return NULL; } } argv = guest_exec_get_args(&arglist, true); envp = has_env ? guest_exec_get_args(env, false) : NULL; flags = G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD; #if GLIB_CHECK_VERSION(2, 33, 2) flags |= G_SPAWN_SEARCH_PATH_FROM_ENVP; #endif if (!has_output) { flags |= G_SPAWN_STDOUT_TO_DEV_NULL | G_SPAWN_STDERR_TO_DEV_NULL; } ret = g_spawn_async_with_pipes(NULL, argv, envp, flags, guest_exec_task_setup, NULL, &pid, has_input_data ? &in_fd : NULL, has_output ? &out_fd : NULL, has_output ? &err_fd : NULL, &gerr); if (!ret) { error_setg(err, QERR_QGA_COMMAND_FAILED, gerr->message); g_error_free(gerr); goto done; } ge = g_new0(GuestExec, 1); ge->pid = gpid_to_int64(pid); gei = guest_exec_info_add(pid); gei->has_output = has_output; g_child_watch_add(pid, guest_exec_child_watch, gei); if (has_input_data) { gei->in.data = input; gei->in.size = ninput; #ifdef G_OS_WIN32 in_ch = g_io_channel_win32_new_fd(in_fd); #else in_ch = g_io_channel_unix_new(in_fd); #endif g_io_channel_set_encoding(in_ch, NULL, NULL); g_io_channel_set_buffered(in_ch, false); g_io_channel_set_flags(in_ch, G_IO_FLAG_NONBLOCK, NULL); g_io_channel_set_close_on_unref(in_ch, true); g_io_add_watch(in_ch, G_IO_OUT, guest_exec_input_watch, &gei->in); } if (has_output) { #ifdef G_OS_WIN32 out_ch = g_io_channel_win32_new_fd(out_fd); err_ch = g_io_channel_win32_new_fd(err_fd); #else out_ch = g_io_channel_unix_new(out_fd); err_ch = g_io_channel_unix_new(err_fd); #endif g_io_channel_set_encoding(out_ch, NULL, NULL); g_io_channel_set_encoding(err_ch, NULL, NULL); g_io_channel_set_buffered(out_ch, false); g_io_channel_set_buffered(err_ch, false); g_io_channel_set_close_on_unref(out_ch, true); g_io_channel_set_close_on_unref(err_ch, true); g_io_add_watch(out_ch, G_IO_IN | G_IO_HUP, guest_exec_output_watch, &gei->out); g_io_add_watch(err_ch, G_IO_IN | G_IO_HUP, guest_exec_output_watch, &gei->err); } done: g_free(argv); g_free(envp); return ge; } /* Convert GuestFileWhence (either a raw integer or an enum value) into * the guest's SEEK_ constants. */ int ga_parse_whence(GuestFileWhence *whence, Error **errp) { /* Exploit the fact that we picked values to match QGA_SEEK_*. */ if (whence->type == QTYPE_QSTRING) { whence->type = QTYPE_QINT; whence->u.value = whence->u.name; } switch (whence->u.value) { case QGA_SEEK_SET: return SEEK_SET; case QGA_SEEK_CUR: return SEEK_CUR; case QGA_SEEK_END: return SEEK_END; } error_setg(errp, "invalid whence code %"PRId64, whence->u.value); return -1; }
null
null
null
null
122,140
61,895
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
61,895
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/supervised_user_whitelist_service.h" #include <stddef.h> #include <string> #include <utility> #include "base/command_line.h" #include "base/files/file_path.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/user_metrics.h" #include "base/metrics/user_metrics_action.h" #include "base/strings/string_split.h" #include "base/values.h" #include "chrome/browser/component_updater/supervised_user_whitelist_installer.h" #include "chrome/browser/supervised_user/supervised_user_site_list.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/sync/model/sync_change.h" #include "components/sync/model/sync_data.h" #include "components/sync/model/sync_error.h" #include "components/sync/model/sync_error_factory.h" #include "components/sync/model/sync_merge_result.h" #include "components/sync/protocol/sync.pb.h" const char kName[] = "name"; SupervisedUserWhitelistService::SupervisedUserWhitelistService( PrefService* prefs, component_updater::SupervisedUserWhitelistInstaller* installer, const std::string& client_id) : prefs_(prefs), installer_(installer), client_id_(client_id), weak_ptr_factory_(this) { DCHECK(prefs); } SupervisedUserWhitelistService::~SupervisedUserWhitelistService() { } // static void SupervisedUserWhitelistService::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { registry->RegisterDictionaryPref(prefs::kSupervisedUserWhitelists); } void SupervisedUserWhitelistService::Init() { const base::DictionaryValue* whitelists = prefs_->GetDictionary(prefs::kSupervisedUserWhitelists); for (base::DictionaryValue::Iterator it(*whitelists); !it.IsAtEnd(); it.Advance()) { registered_whitelists_.insert(it.key()); } UMA_HISTOGRAM_COUNTS_100("ManagedUsers.Whitelist.Count", whitelists->size()); // The installer can be null in some unit tests. if (!installer_) return; installer_->Subscribe( base::Bind(&SupervisedUserWhitelistService::OnWhitelistReady, weak_ptr_factory_.GetWeakPtr())); // Register whitelists specified on the command line. for (const auto& whitelist : GetWhitelistsFromCommandLine()) RegisterWhitelist(whitelist.first, whitelist.second, FROM_COMMAND_LINE); } void SupervisedUserWhitelistService::AddSiteListsChangedCallback( const SiteListsChangedCallback& callback) { site_lists_changed_callbacks_.push_back(callback); std::vector<scoped_refptr<SupervisedUserSiteList>> whitelists; GetLoadedWhitelists(&whitelists); callback.Run(whitelists); } // static std::map<std::string, std::string> SupervisedUserWhitelistService::GetWhitelistsFromCommandLine() { std::map<std::string, std::string> whitelists; const base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); std::string command_line_whitelists = command_line->GetSwitchValueASCII( switches::kInstallSupervisedUserWhitelists); std::vector<base::StringPiece> string_pieces = base::SplitStringPiece(command_line_whitelists, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); for (const base::StringPiece& whitelist : string_pieces) { std::string id; std::string name; size_t separator = whitelist.find(':'); if (separator != base::StringPiece::npos) { whitelist.substr(0, separator).CopyToString(&id); whitelist.substr(separator + 1).CopyToString(&name); } else { whitelist.CopyToString(&id); } const bool result = whitelists.insert(std::make_pair(id, name)).second; DCHECK(result); } return whitelists; } void SupervisedUserWhitelistService::LoadWhitelistForTesting( const std::string& id, const base::string16& title, const base::FilePath& path) { bool result = registered_whitelists_.insert(id).second; DCHECK(result); OnWhitelistReady(id, title, base::FilePath(), path); } void SupervisedUserWhitelistService::UnloadWhitelist(const std::string& id) { bool result = registered_whitelists_.erase(id) > 0u; DCHECK(result); loaded_whitelists_.erase(id); NotifyWhitelistsChanged(); } // static syncer::SyncData SupervisedUserWhitelistService::CreateWhitelistSyncData( const std::string& id, const std::string& name) { sync_pb::EntitySpecifics specifics; sync_pb::ManagedUserWhitelistSpecifics* whitelist = specifics.mutable_managed_user_whitelist(); whitelist->set_id(id); whitelist->set_name(name); return syncer::SyncData::CreateLocalData(id, name, specifics); } syncer::SyncMergeResult SupervisedUserWhitelistService::MergeDataAndStartSyncing( syncer::ModelType type, const syncer::SyncDataList& initial_sync_data, std::unique_ptr<syncer::SyncChangeProcessor> sync_processor, std::unique_ptr<syncer::SyncErrorFactory> error_handler) { DCHECK_EQ(syncer::SUPERVISED_USER_WHITELISTS, type); syncer::SyncChangeList change_list; syncer::SyncMergeResult result(syncer::SUPERVISED_USER_WHITELISTS); DictionaryPrefUpdate update(prefs_, prefs::kSupervisedUserWhitelists); base::DictionaryValue* pref_dict = update.Get(); result.set_num_items_before_association(pref_dict->size()); std::set<std::string> seen_ids; int num_items_added = 0; int num_items_modified = 0; for (const syncer::SyncData& sync_data : initial_sync_data) { DCHECK_EQ(syncer::SUPERVISED_USER_WHITELISTS, sync_data.GetDataType()); const sync_pb::ManagedUserWhitelistSpecifics& whitelist = sync_data.GetSpecifics().managed_user_whitelist(); std::string id = whitelist.id(); std::string name = whitelist.name(); seen_ids.insert(id); base::DictionaryValue* dict = nullptr; if (pref_dict->GetDictionary(id, &dict)) { std::string old_name; bool result = dict->GetString(kName, &old_name); DCHECK(result); if (name != old_name) { SetWhitelistProperties(dict, whitelist); num_items_modified++; } } else { num_items_added++; AddNewWhitelist(pref_dict, whitelist); } } std::set<std::string> ids_to_remove; for (base::DictionaryValue::Iterator it(*pref_dict); !it.IsAtEnd(); it.Advance()) { if (seen_ids.find(it.key()) == seen_ids.end()) ids_to_remove.insert(it.key()); } for (const std::string& id : ids_to_remove) RemoveWhitelist(pref_dict, id); // Notify if whitelists have been uninstalled. We will notify about newly // added whitelists later, when they are actually available // (in OnWhitelistLoaded). if (!ids_to_remove.empty()) NotifyWhitelistsChanged(); result.set_num_items_added(num_items_added); result.set_num_items_modified(num_items_modified); result.set_num_items_deleted(ids_to_remove.size()); result.set_num_items_after_association(pref_dict->size()); return result; } void SupervisedUserWhitelistService::StopSyncing(syncer::ModelType type) { DCHECK_EQ(syncer::SUPERVISED_USER_WHITELISTS, type); } syncer::SyncDataList SupervisedUserWhitelistService::GetAllSyncData( syncer::ModelType type) const { syncer::SyncDataList sync_data; const base::DictionaryValue* whitelists = prefs_->GetDictionary(prefs::kSupervisedUserWhitelists); for (base::DictionaryValue::Iterator it(*whitelists); !it.IsAtEnd(); it.Advance()) { const std::string& id = it.key(); const base::DictionaryValue* dict = nullptr; it.value().GetAsDictionary(&dict); std::string name; bool result = dict->GetString(kName, &name); DCHECK(result); sync_pb::EntitySpecifics specifics; sync_pb::ManagedUserWhitelistSpecifics* whitelist = specifics.mutable_managed_user_whitelist(); whitelist->set_id(id); whitelist->set_name(name); sync_data.push_back(syncer::SyncData::CreateLocalData(id, name, specifics)); } return sync_data; } syncer::SyncError SupervisedUserWhitelistService::ProcessSyncChanges( const base::Location& from_here, const syncer::SyncChangeList& change_list) { bool whitelists_removed = false; syncer::SyncError error; DictionaryPrefUpdate update(prefs_, prefs::kSupervisedUserWhitelists); base::DictionaryValue* pref_dict = update.Get(); for (const syncer::SyncChange& sync_change : change_list) { syncer::SyncData data = sync_change.sync_data(); DCHECK_EQ(syncer::SUPERVISED_USER_WHITELISTS, data.GetDataType()); const sync_pb::ManagedUserWhitelistSpecifics& whitelist = data.GetSpecifics().managed_user_whitelist(); std::string id = whitelist.id(); switch (sync_change.change_type()) { case syncer::SyncChange::ACTION_ADD: { DCHECK(!pref_dict->HasKey(id)) << id; AddNewWhitelist(pref_dict, whitelist); break; } case syncer::SyncChange::ACTION_UPDATE: { base::DictionaryValue* dict = nullptr; pref_dict->GetDictionaryWithoutPathExpansion(id, &dict); SetWhitelistProperties(dict, whitelist); break; } case syncer::SyncChange::ACTION_DELETE: { DCHECK(pref_dict->HasKey(id)) << id; RemoveWhitelist(pref_dict, id); whitelists_removed = true; break; } case syncer::SyncChange::ACTION_INVALID: { NOTREACHED(); break; } } } if (whitelists_removed) NotifyWhitelistsChanged(); return error; } void SupervisedUserWhitelistService::AddNewWhitelist( base::DictionaryValue* pref_dict, const sync_pb::ManagedUserWhitelistSpecifics& whitelist) { base::RecordAction(base::UserMetricsAction("ManagedUsers_Whitelist_Added")); RegisterWhitelist(whitelist.id(), whitelist.name(), FROM_SYNC); std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue); SetWhitelistProperties(dict.get(), whitelist); pref_dict->SetWithoutPathExpansion(whitelist.id(), std::move(dict)); } void SupervisedUserWhitelistService::SetWhitelistProperties( base::DictionaryValue* dict, const sync_pb::ManagedUserWhitelistSpecifics& whitelist) { dict->SetString(kName, whitelist.name()); } void SupervisedUserWhitelistService::RemoveWhitelist( base::DictionaryValue* pref_dict, const std::string& id) { base::RecordAction(base::UserMetricsAction("ManagedUsers_Whitelist_Removed")); pref_dict->RemoveWithoutPathExpansion(id, NULL); installer_->UnregisterWhitelist(client_id_, id); UnloadWhitelist(id); } void SupervisedUserWhitelistService::RegisterWhitelist(const std::string& id, const std::string& name, WhitelistSource source) { bool result = registered_whitelists_.insert(id).second; DCHECK(result); // Using an empty client ID for whitelists installed from the command line // causes the installer to not persist the installation, so the whitelist will // be removed the next time the browser is started without the command line // flag. installer_->RegisterWhitelist( source == FROM_COMMAND_LINE ? std::string() : client_id_, id, name); } void SupervisedUserWhitelistService::GetLoadedWhitelists( std::vector<scoped_refptr<SupervisedUserSiteList>>* whitelists) { for (const auto& whitelist : loaded_whitelists_) whitelists->push_back(whitelist.second); } void SupervisedUserWhitelistService::NotifyWhitelistsChanged() { std::vector<scoped_refptr<SupervisedUserSiteList>> whitelists; GetLoadedWhitelists(&whitelists); for (const auto& callback : site_lists_changed_callbacks_) callback.Run(whitelists); } void SupervisedUserWhitelistService::OnWhitelistReady( const std::string& id, const base::string16& title, const base::FilePath& large_icon_path, const base::FilePath& whitelist_path) { // If we did not register the whitelist or it has been unregistered in the // mean time, ignore it. if (registered_whitelists_.count(id) == 0u) return; SupervisedUserSiteList::Load( id, title, large_icon_path, whitelist_path, base::Bind(&SupervisedUserWhitelistService::OnWhitelistLoaded, weak_ptr_factory_.GetWeakPtr(), id, base::TimeTicks::Now())); } void SupervisedUserWhitelistService::OnWhitelistLoaded( const std::string& id, base::TimeTicks start_time, const scoped_refptr<SupervisedUserSiteList>& whitelist) { if (!whitelist) { LOG(WARNING) << "Couldn't load whitelist " << id; return; } UMA_HISTOGRAM_TIMES("ManagedUsers.Whitelist.TotalLoadDuration", base::TimeTicks::Now() - start_time); // If the whitelist has been unregistered in the mean time, ignore it. if (registered_whitelists_.count(id) == 0u) return; loaded_whitelists_[id] = whitelist; NotifyWhitelistsChanged(); }
null
null
null
null
58,758
27,779
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
27,779
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. // Mappings and Sequences of descriptors. // Used by Descriptor.fields_by_name, EnumDescriptor.values... // // They avoid the allocation of a full dictionary or a full list: they simply // store a pointer to the parent descriptor, use the C++ Descriptor methods (see // google/protobuf/descriptor.h) to retrieve other descriptors, and create // Python objects on the fly. // // The containers fully conform to abc.Mapping and abc.Sequence, and behave just // like read-only dictionaries and lists. // // Because the interface of C++ Descriptors is quite regular, this file actually // defines only three types, the exact behavior of a container is controlled by // a DescriptorContainerDef structure, which contains functions that uses the // public Descriptor API. // // Note: This DescriptorContainerDef is similar to the "virtual methods table" // that a C++ compiler generates for a class. We have to make it explicit // because the Python API is based on C, and does not play well with C++ // inheritance. #include <Python.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/pyext/descriptor_containers.h> #include <google/protobuf/pyext/descriptor_pool.h> #include <google/protobuf/pyext/descriptor.h> #include <google/protobuf/pyext/scoped_pyobject_ptr.h> #if PY_MAJOR_VERSION >= 3 #define PyString_FromStringAndSize PyUnicode_FromStringAndSize #define PyString_FromFormat PyUnicode_FromFormat #define PyInt_FromLong PyLong_FromLong #if PY_VERSION_HEX < 0x03030000 #error "Python 3.0 - 3.2 are not supported." #endif #define PyString_AsStringAndSize(ob, charpp, sizep) \ (PyUnicode_Check(ob)? \ ((*(charpp) = PyUnicode_AsUTF8AndSize(ob, (sizep))) == NULL? -1: 0): \ PyBytes_AsStringAndSize(ob, (charpp), (sizep))) #endif namespace google { namespace protobuf { namespace python { struct PyContainer; typedef int (*CountMethod)(PyContainer* self); typedef const void* (*GetByIndexMethod)(PyContainer* self, int index); typedef const void* (*GetByNameMethod)(PyContainer* self, const string& name); typedef const void* (*GetByCamelcaseNameMethod)(PyContainer* self, const string& name); typedef const void* (*GetByNumberMethod)(PyContainer* self, int index); typedef PyObject* (*NewObjectFromItemMethod)(const void* descriptor); typedef const string& (*GetItemNameMethod)(const void* descriptor); typedef const string& (*GetItemCamelcaseNameMethod)(const void* descriptor); typedef int (*GetItemNumberMethod)(const void* descriptor); typedef int (*GetItemIndexMethod)(const void* descriptor); struct DescriptorContainerDef { const char* mapping_name; // Returns the number of items in the container. CountMethod count_fn; // Retrieve item by index (usually the order of declaration in the proto file) // Used by sequences, but also iterators. 0 <= index < Count(). GetByIndexMethod get_by_index_fn; // Retrieve item by name (usually a call to some 'FindByName' method). // Used by "by_name" mappings. GetByNameMethod get_by_name_fn; // Retrieve item by camelcase name (usually a call to some // 'FindByCamelcaseName' method). Used by "by_camelcase_name" mappings. GetByCamelcaseNameMethod get_by_camelcase_name_fn; // Retrieve item by declared number (field tag, or enum value). // Used by "by_number" mappings. GetByNumberMethod get_by_number_fn; // Converts a item C++ descriptor to a Python object. Returns a new reference. NewObjectFromItemMethod new_object_from_item_fn; // Retrieve the name of an item. Used by iterators on "by_name" mappings. GetItemNameMethod get_item_name_fn; // Retrieve the camelcase name of an item. Used by iterators on // "by_camelcase_name" mappings. GetItemCamelcaseNameMethod get_item_camelcase_name_fn; // Retrieve the number of an item. Used by iterators on "by_number" mappings. GetItemNumberMethod get_item_number_fn; // Retrieve the index of an item for the container type. // Used by "__contains__". // If not set, "x in sequence" will do a linear search. GetItemIndexMethod get_item_index_fn; }; struct PyContainer { PyObject_HEAD // The proto2 descriptor this container belongs to the global DescriptorPool. const void* descriptor; // A pointer to a static structure with function pointers that control the // behavior of the container. Very similar to the table of virtual functions // of a C++ class. const DescriptorContainerDef* container_def; // The kind of container: list, or dict by name or value. enum ContainerKind { KIND_SEQUENCE, KIND_BYNAME, KIND_BYCAMELCASENAME, KIND_BYNUMBER, } kind; }; struct PyContainerIterator { PyObject_HEAD // The container we are iterating over. Own a reference. PyContainer* container; // The current index in the iterator. int index; // The kind of container: list, or dict by name or value. enum IterKind { KIND_ITERKEY, KIND_ITERVALUE, KIND_ITERITEM, KIND_ITERVALUE_REVERSED, // For sequences } kind; }; namespace descriptor { // Returns the C++ item descriptor for a given Python key. // When the descriptor is found, return true and set *item. // When the descriptor is not found, return true, but set *item to NULL. // On error, returns false with an exception set. static bool _GetItemByKey(PyContainer* self, PyObject* key, const void** item) { switch (self->kind) { case PyContainer::KIND_BYNAME: { char* name; Py_ssize_t name_size; if (PyString_AsStringAndSize(key, &name, &name_size) < 0) { if (PyErr_ExceptionMatches(PyExc_TypeError)) { // Not a string, cannot be in the container. PyErr_Clear(); *item = NULL; return true; } return false; } *item = self->container_def->get_by_name_fn( self, string(name, name_size)); return true; } case PyContainer::KIND_BYCAMELCASENAME: { char* camelcase_name; Py_ssize_t name_size; if (PyString_AsStringAndSize(key, &camelcase_name, &name_size) < 0) { if (PyErr_ExceptionMatches(PyExc_TypeError)) { // Not a string, cannot be in the container. PyErr_Clear(); *item = NULL; return true; } return false; } *item = self->container_def->get_by_camelcase_name_fn( self, string(camelcase_name, name_size)); return true; } case PyContainer::KIND_BYNUMBER: { Py_ssize_t number = PyNumber_AsSsize_t(key, NULL); if (number == -1 && PyErr_Occurred()) { if (PyErr_ExceptionMatches(PyExc_TypeError)) { // Not a number, cannot be in the container. PyErr_Clear(); *item = NULL; return true; } return false; } *item = self->container_def->get_by_number_fn(self, number); return true; } default: PyErr_SetNone(PyExc_NotImplementedError); return false; } } // Returns the key of the object at the given index. // Used when iterating over mappings. static PyObject* _NewKey_ByIndex(PyContainer* self, Py_ssize_t index) { const void* item = self->container_def->get_by_index_fn(self, index); switch (self->kind) { case PyContainer::KIND_BYNAME: { const string& name(self->container_def->get_item_name_fn(item)); return PyString_FromStringAndSize(name.c_str(), name.size()); } case PyContainer::KIND_BYCAMELCASENAME: { const string& name( self->container_def->get_item_camelcase_name_fn(item)); return PyString_FromStringAndSize(name.c_str(), name.size()); } case PyContainer::KIND_BYNUMBER: { int value = self->container_def->get_item_number_fn(item); return PyInt_FromLong(value); } default: PyErr_SetNone(PyExc_NotImplementedError); return NULL; } } // Returns the object at the given index. // Also used when iterating over mappings. static PyObject* _NewObj_ByIndex(PyContainer* self, Py_ssize_t index) { return self->container_def->new_object_from_item_fn( self->container_def->get_by_index_fn(self, index)); } static Py_ssize_t Length(PyContainer* self) { return self->container_def->count_fn(self); } // The DescriptorMapping type. static PyObject* Subscript(PyContainer* self, PyObject* key) { const void* item = NULL; if (!_GetItemByKey(self, key, &item)) { return NULL; } if (!item) { PyErr_SetObject(PyExc_KeyError, key); return NULL; } return self->container_def->new_object_from_item_fn(item); } static int AssSubscript(PyContainer* self, PyObject* key, PyObject* value) { if (_CalledFromGeneratedFile(0)) { return 0; } PyErr_Format(PyExc_TypeError, "'%.200s' object does not support item assignment", Py_TYPE(self)->tp_name); return -1; } static PyMappingMethods MappingMappingMethods = { (lenfunc)Length, // mp_length (binaryfunc)Subscript, // mp_subscript (objobjargproc)AssSubscript, // mp_ass_subscript }; static int Contains(PyContainer* self, PyObject* key) { const void* item = NULL; if (!_GetItemByKey(self, key, &item)) { return -1; } if (item) { return 1; } else { return 0; } } static PyObject* ContainerRepr(PyContainer* self) { const char* kind = ""; switch (self->kind) { case PyContainer::KIND_SEQUENCE: kind = "sequence"; break; case PyContainer::KIND_BYNAME: kind = "mapping by name"; break; case PyContainer::KIND_BYCAMELCASENAME: kind = "mapping by camelCase name"; break; case PyContainer::KIND_BYNUMBER: kind = "mapping by number"; break; } return PyString_FromFormat( "<%s %s>", self->container_def->mapping_name, kind); } extern PyTypeObject DescriptorMapping_Type; extern PyTypeObject DescriptorSequence_Type; // A sequence container can only be equal to another sequence container, or (for // backward compatibility) to a list containing the same items. // Returns 1 if equal, 0 if unequal, -1 on error. static int DescriptorSequence_Equal(PyContainer* self, PyObject* other) { // Check the identity of C++ pointers. if (PyObject_TypeCheck(other, &DescriptorSequence_Type)) { PyContainer* other_container = reinterpret_cast<PyContainer*>(other); if (self->descriptor == other_container->descriptor && self->container_def == other_container->container_def && self->kind == other_container->kind) { return 1; } else { return 0; } } // If other is a list if (PyList_Check(other)) { // return list(self) == other int size = Length(self); if (size != PyList_Size(other)) { return false; } for (int index = 0; index < size; index++) { ScopedPyObjectPtr value1(_NewObj_ByIndex(self, index)); if (value1 == NULL) { return -1; } PyObject* value2 = PyList_GetItem(other, index); if (value2 == NULL) { return -1; } int cmp = PyObject_RichCompareBool(value1.get(), value2, Py_EQ); if (cmp != 1) // error or not equal return cmp; } // All items were found and equal return 1; } // Any other object is different. return 0; } // A mapping container can only be equal to another mapping container, or (for // backward compatibility) to a dict containing the same items. // Returns 1 if equal, 0 if unequal, -1 on error. static int DescriptorMapping_Equal(PyContainer* self, PyObject* other) { // Check the identity of C++ pointers. if (PyObject_TypeCheck(other, &DescriptorMapping_Type)) { PyContainer* other_container = reinterpret_cast<PyContainer*>(other); if (self->descriptor == other_container->descriptor && self->container_def == other_container->container_def && self->kind == other_container->kind) { return 1; } else { return 0; } } // If other is a dict if (PyDict_Check(other)) { // equivalent to dict(self.items()) == other int size = Length(self); if (size != PyDict_Size(other)) { return false; } for (int index = 0; index < size; index++) { ScopedPyObjectPtr key(_NewKey_ByIndex(self, index)); if (key == NULL) { return -1; } ScopedPyObjectPtr value1(_NewObj_ByIndex(self, index)); if (value1 == NULL) { return -1; } PyObject* value2 = PyDict_GetItem(other, key.get()); if (value2 == NULL) { // Not found in the other dictionary return 0; } int cmp = PyObject_RichCompareBool(value1.get(), value2, Py_EQ); if (cmp != 1) // error or not equal return cmp; } // All items were found and equal return 1; } // Any other object is different. return 0; } static PyObject* RichCompare(PyContainer* self, PyObject* other, int opid) { if (opid != Py_EQ && opid != Py_NE) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } int result; if (self->kind == PyContainer::KIND_SEQUENCE) { result = DescriptorSequence_Equal(self, other); } else { result = DescriptorMapping_Equal(self, other); } if (result < 0) { return NULL; } if (result ^ (opid == Py_NE)) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } static PySequenceMethods MappingSequenceMethods = { 0, // sq_length 0, // sq_concat 0, // sq_repeat 0, // sq_item 0, // sq_slice 0, // sq_ass_item 0, // sq_ass_slice (objobjproc)Contains, // sq_contains }; static PyObject* Get(PyContainer* self, PyObject* args) { PyObject* key; PyObject* default_value = Py_None; if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &default_value)) { return NULL; } const void* item; if (!_GetItemByKey(self, key, &item)) { return NULL; } if (item == NULL) { Py_INCREF(default_value); return default_value; } return self->container_def->new_object_from_item_fn(item); } static PyObject* Keys(PyContainer* self, PyObject* args) { Py_ssize_t count = Length(self); ScopedPyObjectPtr list(PyList_New(count)); if (list == NULL) { return NULL; } for (Py_ssize_t index = 0; index < count; ++index) { PyObject* key = _NewKey_ByIndex(self, index); if (key == NULL) { return NULL; } PyList_SET_ITEM(list.get(), index, key); } return list.release(); } static PyObject* Values(PyContainer* self, PyObject* args) { Py_ssize_t count = Length(self); ScopedPyObjectPtr list(PyList_New(count)); if (list == NULL) { return NULL; } for (Py_ssize_t index = 0; index < count; ++index) { PyObject* value = _NewObj_ByIndex(self, index); if (value == NULL) { return NULL; } PyList_SET_ITEM(list.get(), index, value); } return list.release(); } static PyObject* Items(PyContainer* self, PyObject* args) { Py_ssize_t count = Length(self); ScopedPyObjectPtr list(PyList_New(count)); if (list == NULL) { return NULL; } for (Py_ssize_t index = 0; index < count; ++index) { ScopedPyObjectPtr obj(PyTuple_New(2)); if (obj == NULL) { return NULL; } PyObject* key = _NewKey_ByIndex(self, index); if (key == NULL) { return NULL; } PyTuple_SET_ITEM(obj.get(), 0, key); PyObject* value = _NewObj_ByIndex(self, index); if (value == NULL) { return NULL; } PyTuple_SET_ITEM(obj.get(), 1, value); PyList_SET_ITEM(list.get(), index, obj.release()); } return list.release(); } static PyObject* NewContainerIterator(PyContainer* mapping, PyContainerIterator::IterKind kind); static PyObject* Iter(PyContainer* self) { return NewContainerIterator(self, PyContainerIterator::KIND_ITERKEY); } static PyObject* IterKeys(PyContainer* self, PyObject* args) { return NewContainerIterator(self, PyContainerIterator::KIND_ITERKEY); } static PyObject* IterValues(PyContainer* self, PyObject* args) { return NewContainerIterator(self, PyContainerIterator::KIND_ITERVALUE); } static PyObject* IterItems(PyContainer* self, PyObject* args) { return NewContainerIterator(self, PyContainerIterator::KIND_ITERITEM); } static PyMethodDef MappingMethods[] = { { "get", (PyCFunction)Get, METH_VARARGS, }, { "keys", (PyCFunction)Keys, METH_NOARGS, }, { "values", (PyCFunction)Values, METH_NOARGS, }, { "items", (PyCFunction)Items, METH_NOARGS, }, { "iterkeys", (PyCFunction)IterKeys, METH_NOARGS, }, { "itervalues", (PyCFunction)IterValues, METH_NOARGS, }, { "iteritems", (PyCFunction)IterItems, METH_NOARGS, }, {NULL} }; PyTypeObject DescriptorMapping_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "DescriptorMapping", // tp_name sizeof(PyContainer), // tp_basicsize 0, // tp_itemsize 0, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare (reprfunc)ContainerRepr, // tp_repr 0, // tp_as_number &MappingSequenceMethods, // tp_as_sequence &MappingMappingMethods, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags 0, // tp_doc 0, // tp_traverse 0, // tp_clear (richcmpfunc)RichCompare, // tp_richcompare 0, // tp_weaklistoffset (getiterfunc)Iter, // tp_iter 0, // tp_iternext MappingMethods, // tp_methods 0, // tp_members 0, // tp_getset 0, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset 0, // tp_init 0, // tp_alloc 0, // tp_new 0, // tp_free }; // The DescriptorSequence type. static PyObject* GetItem(PyContainer* self, Py_ssize_t index) { if (index < 0) { index += Length(self); } if (index < 0 || index >= Length(self)) { PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } return _NewObj_ByIndex(self, index); } static PyObject * SeqSubscript(PyContainer* self, PyObject* item) { if (PyIndex_Check(item)) { Py_ssize_t index; index = PyNumber_AsSsize_t(item, PyExc_IndexError); if (index == -1 && PyErr_Occurred()) return NULL; return GetItem(self, index); } // Materialize the list and delegate the operation to it. ScopedPyObjectPtr list(PyObject_CallFunctionObjArgs( reinterpret_cast<PyObject*>(&PyList_Type), self, NULL)); if (list == NULL) { return NULL; } return Py_TYPE(list.get())->tp_as_mapping->mp_subscript(list.get(), item); } // Returns the position of the item in the sequence, of -1 if not found. // This function never fails. int Find(PyContainer* self, PyObject* item) { // The item can only be in one position: item.index. // Check that self[item.index] == item, it's faster than a linear search. // // This assumes that sequences are only defined by syntax of the .proto file: // a specific item belongs to only one sequence, depending on its position in // the .proto file definition. const void* descriptor_ptr = PyDescriptor_AsVoidPtr(item); if (descriptor_ptr == NULL) { // Not a descriptor, it cannot be in the list. return -1; } if (self->container_def->get_item_index_fn) { int index = self->container_def->get_item_index_fn(descriptor_ptr); if (index < 0 || index >= Length(self)) { // This index is not from this collection. return -1; } if (self->container_def->get_by_index_fn(self, index) != descriptor_ptr) { // The descriptor at this index is not the same. return -1; } // self[item.index] == item, so return the index. return index; } else { // Fall back to linear search. int length = Length(self); for (int index=0; index < length; index++) { if (self->container_def->get_by_index_fn(self, index) == descriptor_ptr) { return index; } } // Not found return -1; } } // Implements list.index(): the position of the item is in the sequence. static PyObject* Index(PyContainer* self, PyObject* item) { int position = Find(self, item); if (position < 0) { // Not found PyErr_SetNone(PyExc_ValueError); return NULL; } else { return PyInt_FromLong(position); } } // Implements "list.__contains__()": is the object in the sequence. static int SeqContains(PyContainer* self, PyObject* item) { int position = Find(self, item); if (position < 0) { return 0; } else { return 1; } } // Implements list.count(): number of occurrences of the item in the sequence. // An item can only appear once in a sequence. If it exists, return 1. static PyObject* Count(PyContainer* self, PyObject* item) { int position = Find(self, item); if (position < 0) { return PyInt_FromLong(0); } else { return PyInt_FromLong(1); } } static PyObject* Append(PyContainer* self, PyObject* args) { if (_CalledFromGeneratedFile(0)) { Py_RETURN_NONE; } PyErr_Format(PyExc_TypeError, "'%.200s' object is not a mutable sequence", Py_TYPE(self)->tp_name); return NULL; } static PyObject* Reversed(PyContainer* self, PyObject* args) { return NewContainerIterator(self, PyContainerIterator::KIND_ITERVALUE_REVERSED); } static PyMethodDef SeqMethods[] = { { "index", (PyCFunction)Index, METH_O, }, { "count", (PyCFunction)Count, METH_O, }, { "append", (PyCFunction)Append, METH_O, }, { "__reversed__", (PyCFunction)Reversed, METH_NOARGS, }, {NULL} }; static PySequenceMethods SeqSequenceMethods = { (lenfunc)Length, // sq_length 0, // sq_concat 0, // sq_repeat (ssizeargfunc)GetItem, // sq_item 0, // sq_slice 0, // sq_ass_item 0, // sq_ass_slice (objobjproc)SeqContains, // sq_contains }; static PyMappingMethods SeqMappingMethods = { (lenfunc)Length, // mp_length (binaryfunc)SeqSubscript, // mp_subscript 0, // mp_ass_subscript }; PyTypeObject DescriptorSequence_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "DescriptorSequence", // tp_name sizeof(PyContainer), // tp_basicsize 0, // tp_itemsize 0, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare (reprfunc)ContainerRepr, // tp_repr 0, // tp_as_number &SeqSequenceMethods, // tp_as_sequence &SeqMappingMethods, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags 0, // tp_doc 0, // tp_traverse 0, // tp_clear (richcmpfunc)RichCompare, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext SeqMethods, // tp_methods 0, // tp_members 0, // tp_getset 0, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset 0, // tp_init 0, // tp_alloc 0, // tp_new 0, // tp_free }; static PyObject* NewMappingByName( DescriptorContainerDef* container_def, const void* descriptor) { PyContainer* self = PyObject_New(PyContainer, &DescriptorMapping_Type); if (self == NULL) { return NULL; } self->descriptor = descriptor; self->container_def = container_def; self->kind = PyContainer::KIND_BYNAME; return reinterpret_cast<PyObject*>(self); } static PyObject* NewMappingByCamelcaseName( DescriptorContainerDef* container_def, const void* descriptor) { PyContainer* self = PyObject_New(PyContainer, &DescriptorMapping_Type); if (self == NULL) { return NULL; } self->descriptor = descriptor; self->container_def = container_def; self->kind = PyContainer::KIND_BYCAMELCASENAME; return reinterpret_cast<PyObject*>(self); } static PyObject* NewMappingByNumber( DescriptorContainerDef* container_def, const void* descriptor) { if (container_def->get_by_number_fn == NULL || container_def->get_item_number_fn == NULL) { PyErr_SetNone(PyExc_NotImplementedError); return NULL; } PyContainer* self = PyObject_New(PyContainer, &DescriptorMapping_Type); if (self == NULL) { return NULL; } self->descriptor = descriptor; self->container_def = container_def; self->kind = PyContainer::KIND_BYNUMBER; return reinterpret_cast<PyObject*>(self); } static PyObject* NewSequence( DescriptorContainerDef* container_def, const void* descriptor) { PyContainer* self = PyObject_New(PyContainer, &DescriptorSequence_Type); if (self == NULL) { return NULL; } self->descriptor = descriptor; self->container_def = container_def; self->kind = PyContainer::KIND_SEQUENCE; return reinterpret_cast<PyObject*>(self); } // Implement iterators over PyContainers. static void Iterator_Dealloc(PyContainerIterator* self) { Py_CLEAR(self->container); Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self)); } static PyObject* Iterator_Next(PyContainerIterator* self) { int count = self->container->container_def->count_fn(self->container); if (self->index >= count) { // Return NULL with no exception to indicate the end. return NULL; } int index = self->index; self->index += 1; switch (self->kind) { case PyContainerIterator::KIND_ITERKEY: return _NewKey_ByIndex(self->container, index); case PyContainerIterator::KIND_ITERVALUE: return _NewObj_ByIndex(self->container, index); case PyContainerIterator::KIND_ITERVALUE_REVERSED: return _NewObj_ByIndex(self->container, count - index - 1); case PyContainerIterator::KIND_ITERITEM: { PyObject* obj = PyTuple_New(2); if (obj == NULL) { return NULL; } PyObject* key = _NewKey_ByIndex(self->container, index); if (key == NULL) { Py_DECREF(obj); return NULL; } PyTuple_SET_ITEM(obj, 0, key); PyObject* value = _NewObj_ByIndex(self->container, index); if (value == NULL) { Py_DECREF(obj); return NULL; } PyTuple_SET_ITEM(obj, 1, value); return obj; } default: PyErr_SetNone(PyExc_NotImplementedError); return NULL; } } static PyTypeObject ContainerIterator_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "DescriptorContainerIterator", // tp_name sizeof(PyContainerIterator), // tp_basicsize 0, // tp_itemsize (destructor)Iterator_Dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags 0, // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset PyObject_SelfIter, // tp_iter (iternextfunc)Iterator_Next, // tp_iternext 0, // tp_methods 0, // tp_members 0, // tp_getset 0, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset 0, // tp_init 0, // tp_alloc 0, // tp_new 0, // tp_free }; static PyObject* NewContainerIterator(PyContainer* container, PyContainerIterator::IterKind kind) { PyContainerIterator* self = PyObject_New(PyContainerIterator, &ContainerIterator_Type); if (self == NULL) { return NULL; } Py_INCREF(container); self->container = container; self->kind = kind; self->index = 0; return reinterpret_cast<PyObject*>(self); } } // namespace descriptor // Now define the real collections! namespace message_descriptor { typedef const Descriptor* ParentDescriptor; static ParentDescriptor GetDescriptor(PyContainer* self) { return reinterpret_cast<ParentDescriptor>(self->descriptor); } namespace fields { typedef const FieldDescriptor* ItemDescriptor; static int Count(PyContainer* self) { return GetDescriptor(self)->field_count(); } static ItemDescriptor GetByName(PyContainer* self, const string& name) { return GetDescriptor(self)->FindFieldByName(name); } static ItemDescriptor GetByCamelcaseName(PyContainer* self, const string& name) { return GetDescriptor(self)->FindFieldByCamelcaseName(name); } static ItemDescriptor GetByNumber(PyContainer* self, int number) { return GetDescriptor(self)->FindFieldByNumber(number); } static ItemDescriptor GetByIndex(PyContainer* self, int index) { return GetDescriptor(self)->field(index); } static PyObject* NewObjectFromItem(ItemDescriptor item) { return PyFieldDescriptor_FromDescriptor(item); } static const string& GetItemName(ItemDescriptor item) { return item->name(); } static const string& GetItemCamelcaseName(ItemDescriptor item) { return item->camelcase_name(); } static int GetItemNumber(ItemDescriptor item) { return item->number(); } static int GetItemIndex(ItemDescriptor item) { return item->index(); } static DescriptorContainerDef ContainerDef = { "MessageFields", (CountMethod)Count, (GetByIndexMethod)GetByIndex, (GetByNameMethod)GetByName, (GetByCamelcaseNameMethod)GetByCamelcaseName, (GetByNumberMethod)GetByNumber, (NewObjectFromItemMethod)NewObjectFromItem, (GetItemNameMethod)GetItemName, (GetItemCamelcaseNameMethod)GetItemCamelcaseName, (GetItemNumberMethod)GetItemNumber, (GetItemIndexMethod)GetItemIndex, }; } // namespace fields PyObject* NewMessageFieldsByName(ParentDescriptor descriptor) { return descriptor::NewMappingByName(&fields::ContainerDef, descriptor); } PyObject* NewMessageFieldsByCamelcaseName(ParentDescriptor descriptor) { return descriptor::NewMappingByCamelcaseName(&fields::ContainerDef, descriptor); } PyObject* NewMessageFieldsByNumber(ParentDescriptor descriptor) { return descriptor::NewMappingByNumber(&fields::ContainerDef, descriptor); } PyObject* NewMessageFieldsSeq(ParentDescriptor descriptor) { return descriptor::NewSequence(&fields::ContainerDef, descriptor); } namespace nested_types { typedef const Descriptor* ItemDescriptor; static int Count(PyContainer* self) { return GetDescriptor(self)->nested_type_count(); } static ItemDescriptor GetByName(PyContainer* self, const string& name) { return GetDescriptor(self)->FindNestedTypeByName(name); } static ItemDescriptor GetByIndex(PyContainer* self, int index) { return GetDescriptor(self)->nested_type(index); } static PyObject* NewObjectFromItem(ItemDescriptor item) { return PyMessageDescriptor_FromDescriptor(item); } static const string& GetItemName(ItemDescriptor item) { return item->name(); } static int GetItemIndex(ItemDescriptor item) { return item->index(); } static DescriptorContainerDef ContainerDef = { "MessageNestedTypes", (CountMethod)Count, (GetByIndexMethod)GetByIndex, (GetByNameMethod)GetByName, (GetByCamelcaseNameMethod)NULL, (GetByNumberMethod)NULL, (NewObjectFromItemMethod)NewObjectFromItem, (GetItemNameMethod)GetItemName, (GetItemCamelcaseNameMethod)NULL, (GetItemNumberMethod)NULL, (GetItemIndexMethod)GetItemIndex, }; } // namespace nested_types PyObject* NewMessageNestedTypesSeq(ParentDescriptor descriptor) { return descriptor::NewSequence(&nested_types::ContainerDef, descriptor); } PyObject* NewMessageNestedTypesByName(ParentDescriptor descriptor) { return descriptor::NewMappingByName(&nested_types::ContainerDef, descriptor); } namespace enums { typedef const EnumDescriptor* ItemDescriptor; static int Count(PyContainer* self) { return GetDescriptor(self)->enum_type_count(); } static ItemDescriptor GetByName(PyContainer* self, const string& name) { return GetDescriptor(self)->FindEnumTypeByName(name); } static ItemDescriptor GetByIndex(PyContainer* self, int index) { return GetDescriptor(self)->enum_type(index); } static PyObject* NewObjectFromItem(ItemDescriptor item) { return PyEnumDescriptor_FromDescriptor(item); } static const string& GetItemName(ItemDescriptor item) { return item->name(); } static int GetItemIndex(ItemDescriptor item) { return item->index(); } static DescriptorContainerDef ContainerDef = { "MessageNestedEnums", (CountMethod)Count, (GetByIndexMethod)GetByIndex, (GetByNameMethod)GetByName, (GetByCamelcaseNameMethod)NULL, (GetByNumberMethod)NULL, (NewObjectFromItemMethod)NewObjectFromItem, (GetItemNameMethod)GetItemName, (GetItemCamelcaseNameMethod)NULL, (GetItemNumberMethod)NULL, (GetItemIndexMethod)GetItemIndex, }; } // namespace enums PyObject* NewMessageEnumsByName(ParentDescriptor descriptor) { return descriptor::NewMappingByName(&enums::ContainerDef, descriptor); } PyObject* NewMessageEnumsSeq(ParentDescriptor descriptor) { return descriptor::NewSequence(&enums::ContainerDef, descriptor); } namespace enumvalues { // This is the "enum_values_by_name" mapping, which collects values from all // enum types in a message. // // Note that the behavior of the C++ descriptor is different: it will search and // return the first value that matches the name, whereas the Python // implementation retrieves the last one. typedef const EnumValueDescriptor* ItemDescriptor; static int Count(PyContainer* self) { int count = 0; for (int i = 0; i < GetDescriptor(self)->enum_type_count(); ++i) { count += GetDescriptor(self)->enum_type(i)->value_count(); } return count; } static ItemDescriptor GetByName(PyContainer* self, const string& name) { return GetDescriptor(self)->FindEnumValueByName(name); } static ItemDescriptor GetByIndex(PyContainer* self, int index) { // This is not optimal, but the number of enums *types* in a given message // is small. This function is only used when iterating over the mapping. const EnumDescriptor* enum_type = NULL; int enum_type_count = GetDescriptor(self)->enum_type_count(); for (int i = 0; i < enum_type_count; ++i) { enum_type = GetDescriptor(self)->enum_type(i); int enum_value_count = enum_type->value_count(); if (index < enum_value_count) { // Found it! break; } index -= enum_value_count; } // The next statement cannot overflow, because this function is only called by // internal iterators which ensure that 0 <= index < Count(). return enum_type->value(index); } static PyObject* NewObjectFromItem(ItemDescriptor item) { return PyEnumValueDescriptor_FromDescriptor(item); } static const string& GetItemName(ItemDescriptor item) { return item->name(); } static DescriptorContainerDef ContainerDef = { "MessageEnumValues", (CountMethod)Count, (GetByIndexMethod)GetByIndex, (GetByNameMethod)GetByName, (GetByCamelcaseNameMethod)NULL, (GetByNumberMethod)NULL, (NewObjectFromItemMethod)NewObjectFromItem, (GetItemNameMethod)GetItemName, (GetItemCamelcaseNameMethod)NULL, (GetItemNumberMethod)NULL, (GetItemIndexMethod)NULL, }; } // namespace enumvalues PyObject* NewMessageEnumValuesByName(ParentDescriptor descriptor) { return descriptor::NewMappingByName(&enumvalues::ContainerDef, descriptor); } namespace extensions { typedef const FieldDescriptor* ItemDescriptor; static int Count(PyContainer* self) { return GetDescriptor(self)->extension_count(); } static ItemDescriptor GetByName(PyContainer* self, const string& name) { return GetDescriptor(self)->FindExtensionByName(name); } static ItemDescriptor GetByIndex(PyContainer* self, int index) { return GetDescriptor(self)->extension(index); } static PyObject* NewObjectFromItem(ItemDescriptor item) { return PyFieldDescriptor_FromDescriptor(item); } static const string& GetItemName(ItemDescriptor item) { return item->name(); } static int GetItemIndex(ItemDescriptor item) { return item->index(); } static DescriptorContainerDef ContainerDef = { "MessageExtensions", (CountMethod)Count, (GetByIndexMethod)GetByIndex, (GetByNameMethod)GetByName, (GetByCamelcaseNameMethod)NULL, (GetByNumberMethod)NULL, (NewObjectFromItemMethod)NewObjectFromItem, (GetItemNameMethod)GetItemName, (GetItemCamelcaseNameMethod)NULL, (GetItemNumberMethod)NULL, (GetItemIndexMethod)GetItemIndex, }; } // namespace extensions PyObject* NewMessageExtensionsByName(ParentDescriptor descriptor) { return descriptor::NewMappingByName(&extensions::ContainerDef, descriptor); } PyObject* NewMessageExtensionsSeq(ParentDescriptor descriptor) { return descriptor::NewSequence(&extensions::ContainerDef, descriptor); } namespace oneofs { typedef const OneofDescriptor* ItemDescriptor; static int Count(PyContainer* self) { return GetDescriptor(self)->oneof_decl_count(); } static ItemDescriptor GetByName(PyContainer* self, const string& name) { return GetDescriptor(self)->FindOneofByName(name); } static ItemDescriptor GetByIndex(PyContainer* self, int index) { return GetDescriptor(self)->oneof_decl(index); } static PyObject* NewObjectFromItem(ItemDescriptor item) { return PyOneofDescriptor_FromDescriptor(item); } static const string& GetItemName(ItemDescriptor item) { return item->name(); } static int GetItemIndex(ItemDescriptor item) { return item->index(); } static DescriptorContainerDef ContainerDef = { "MessageOneofs", (CountMethod)Count, (GetByIndexMethod)GetByIndex, (GetByNameMethod)GetByName, (GetByCamelcaseNameMethod)NULL, (GetByNumberMethod)NULL, (NewObjectFromItemMethod)NewObjectFromItem, (GetItemNameMethod)GetItemName, (GetItemCamelcaseNameMethod)NULL, (GetItemNumberMethod)NULL, (GetItemIndexMethod)GetItemIndex, }; } // namespace oneofs PyObject* NewMessageOneofsByName(ParentDescriptor descriptor) { return descriptor::NewMappingByName(&oneofs::ContainerDef, descriptor); } PyObject* NewMessageOneofsSeq(ParentDescriptor descriptor) { return descriptor::NewSequence(&oneofs::ContainerDef, descriptor); } } // namespace message_descriptor namespace enum_descriptor { typedef const EnumDescriptor* ParentDescriptor; static ParentDescriptor GetDescriptor(PyContainer* self) { return reinterpret_cast<ParentDescriptor>(self->descriptor); } namespace enumvalues { typedef const EnumValueDescriptor* ItemDescriptor; static int Count(PyContainer* self) { return GetDescriptor(self)->value_count(); } static ItemDescriptor GetByIndex(PyContainer* self, int index) { return GetDescriptor(self)->value(index); } static ItemDescriptor GetByName(PyContainer* self, const string& name) { return GetDescriptor(self)->FindValueByName(name); } static ItemDescriptor GetByNumber(PyContainer* self, int number) { return GetDescriptor(self)->FindValueByNumber(number); } static PyObject* NewObjectFromItem(ItemDescriptor item) { return PyEnumValueDescriptor_FromDescriptor(item); } static const string& GetItemName(ItemDescriptor item) { return item->name(); } static int GetItemNumber(ItemDescriptor item) { return item->number(); } static int GetItemIndex(ItemDescriptor item) { return item->index(); } static DescriptorContainerDef ContainerDef = { "EnumValues", (CountMethod)Count, (GetByIndexMethod)GetByIndex, (GetByNameMethod)GetByName, (GetByCamelcaseNameMethod)NULL, (GetByNumberMethod)GetByNumber, (NewObjectFromItemMethod)NewObjectFromItem, (GetItemNameMethod)GetItemName, (GetItemCamelcaseNameMethod)NULL, (GetItemNumberMethod)GetItemNumber, (GetItemIndexMethod)GetItemIndex, }; } // namespace enumvalues PyObject* NewEnumValuesByName(ParentDescriptor descriptor) { return descriptor::NewMappingByName(&enumvalues::ContainerDef, descriptor); } PyObject* NewEnumValuesByNumber(ParentDescriptor descriptor) { return descriptor::NewMappingByNumber(&enumvalues::ContainerDef, descriptor); } PyObject* NewEnumValuesSeq(ParentDescriptor descriptor) { return descriptor::NewSequence(&enumvalues::ContainerDef, descriptor); } } // namespace enum_descriptor namespace oneof_descriptor { typedef const OneofDescriptor* ParentDescriptor; static ParentDescriptor GetDescriptor(PyContainer* self) { return reinterpret_cast<ParentDescriptor>(self->descriptor); } namespace fields { typedef const FieldDescriptor* ItemDescriptor; static int Count(PyContainer* self) { return GetDescriptor(self)->field_count(); } static ItemDescriptor GetByIndex(PyContainer* self, int index) { return GetDescriptor(self)->field(index); } static PyObject* NewObjectFromItem(ItemDescriptor item) { return PyFieldDescriptor_FromDescriptor(item); } static int GetItemIndex(ItemDescriptor item) { return item->index_in_oneof(); } static DescriptorContainerDef ContainerDef = { "OneofFields", (CountMethod)Count, (GetByIndexMethod)GetByIndex, (GetByNameMethod)NULL, (GetByCamelcaseNameMethod)NULL, (GetByNumberMethod)NULL, (NewObjectFromItemMethod)NewObjectFromItem, (GetItemNameMethod)NULL, (GetItemCamelcaseNameMethod)NULL, (GetItemNumberMethod)NULL, (GetItemIndexMethod)GetItemIndex, }; } // namespace fields PyObject* NewOneofFieldsSeq(ParentDescriptor descriptor) { return descriptor::NewSequence(&fields::ContainerDef, descriptor); } } // namespace oneof_descriptor namespace service_descriptor { typedef const ServiceDescriptor* ParentDescriptor; static ParentDescriptor GetDescriptor(PyContainer* self) { return reinterpret_cast<ParentDescriptor>(self->descriptor); } namespace methods { typedef const MethodDescriptor* ItemDescriptor; static int Count(PyContainer* self) { return GetDescriptor(self)->method_count(); } static ItemDescriptor GetByName(PyContainer* self, const string& name) { return GetDescriptor(self)->FindMethodByName(name); } static ItemDescriptor GetByIndex(PyContainer* self, int index) { return GetDescriptor(self)->method(index); } static PyObject* NewObjectFromItem(ItemDescriptor item) { return PyMethodDescriptor_FromDescriptor(item); } static const string& GetItemName(ItemDescriptor item) { return item->name(); } static int GetItemIndex(ItemDescriptor item) { return item->index(); } static DescriptorContainerDef ContainerDef = { "ServiceMethods", (CountMethod)Count, (GetByIndexMethod)GetByIndex, (GetByNameMethod)GetByName, (GetByCamelcaseNameMethod)NULL, (GetByNumberMethod)NULL, (NewObjectFromItemMethod)NewObjectFromItem, (GetItemNameMethod)GetItemName, (GetItemCamelcaseNameMethod)NULL, (GetItemNumberMethod)NULL, (GetItemIndexMethod)GetItemIndex, }; } // namespace methods PyObject* NewServiceMethodsSeq(ParentDescriptor descriptor) { return descriptor::NewSequence(&methods::ContainerDef, descriptor); } PyObject* NewServiceMethodsByName(ParentDescriptor descriptor) { return descriptor::NewMappingByName(&methods::ContainerDef, descriptor); } } // namespace service_descriptor namespace file_descriptor { typedef const FileDescriptor* ParentDescriptor; static ParentDescriptor GetDescriptor(PyContainer* self) { return reinterpret_cast<ParentDescriptor>(self->descriptor); } namespace messages { typedef const Descriptor* ItemDescriptor; static int Count(PyContainer* self) { return GetDescriptor(self)->message_type_count(); } static ItemDescriptor GetByName(PyContainer* self, const string& name) { return GetDescriptor(self)->FindMessageTypeByName(name); } static ItemDescriptor GetByIndex(PyContainer* self, int index) { return GetDescriptor(self)->message_type(index); } static PyObject* NewObjectFromItem(ItemDescriptor item) { return PyMessageDescriptor_FromDescriptor(item); } static const string& GetItemName(ItemDescriptor item) { return item->name(); } static int GetItemIndex(ItemDescriptor item) { return item->index(); } static DescriptorContainerDef ContainerDef = { "FileMessages", (CountMethod)Count, (GetByIndexMethod)GetByIndex, (GetByNameMethod)GetByName, (GetByCamelcaseNameMethod)NULL, (GetByNumberMethod)NULL, (NewObjectFromItemMethod)NewObjectFromItem, (GetItemNameMethod)GetItemName, (GetItemCamelcaseNameMethod)NULL, (GetItemNumberMethod)NULL, (GetItemIndexMethod)GetItemIndex, }; } // namespace messages PyObject* NewFileMessageTypesByName(ParentDescriptor descriptor) { return descriptor::NewMappingByName(&messages::ContainerDef, descriptor); } namespace enums { typedef const EnumDescriptor* ItemDescriptor; static int Count(PyContainer* self) { return GetDescriptor(self)->enum_type_count(); } static ItemDescriptor GetByName(PyContainer* self, const string& name) { return GetDescriptor(self)->FindEnumTypeByName(name); } static ItemDescriptor GetByIndex(PyContainer* self, int index) { return GetDescriptor(self)->enum_type(index); } static PyObject* NewObjectFromItem(ItemDescriptor item) { return PyEnumDescriptor_FromDescriptor(item); } static const string& GetItemName(ItemDescriptor item) { return item->name(); } static int GetItemIndex(ItemDescriptor item) { return item->index(); } static DescriptorContainerDef ContainerDef = { "FileEnums", (CountMethod)Count, (GetByIndexMethod)GetByIndex, (GetByNameMethod)GetByName, (GetByCamelcaseNameMethod)NULL, (GetByNumberMethod)NULL, (NewObjectFromItemMethod)NewObjectFromItem, (GetItemNameMethod)GetItemName, (GetItemCamelcaseNameMethod)NULL, (GetItemNumberMethod)NULL, (GetItemIndexMethod)GetItemIndex, }; } // namespace enums PyObject* NewFileEnumTypesByName(ParentDescriptor descriptor) { return descriptor::NewMappingByName(&enums::ContainerDef, descriptor); } namespace extensions { typedef const FieldDescriptor* ItemDescriptor; static int Count(PyContainer* self) { return GetDescriptor(self)->extension_count(); } static ItemDescriptor GetByName(PyContainer* self, const string& name) { return GetDescriptor(self)->FindExtensionByName(name); } static ItemDescriptor GetByIndex(PyContainer* self, int index) { return GetDescriptor(self)->extension(index); } static PyObject* NewObjectFromItem(ItemDescriptor item) { return PyFieldDescriptor_FromDescriptor(item); } static const string& GetItemName(ItemDescriptor item) { return item->name(); } static int GetItemIndex(ItemDescriptor item) { return item->index(); } static DescriptorContainerDef ContainerDef = { "FileExtensions", (CountMethod)Count, (GetByIndexMethod)GetByIndex, (GetByNameMethod)GetByName, (GetByCamelcaseNameMethod)NULL, (GetByNumberMethod)NULL, (NewObjectFromItemMethod)NewObjectFromItem, (GetItemNameMethod)GetItemName, (GetItemCamelcaseNameMethod)NULL, (GetItemNumberMethod)NULL, (GetItemIndexMethod)GetItemIndex, }; } // namespace extensions PyObject* NewFileExtensionsByName(ParentDescriptor descriptor) { return descriptor::NewMappingByName(&extensions::ContainerDef, descriptor); } namespace services { typedef const ServiceDescriptor* ItemDescriptor; static int Count(PyContainer* self) { return GetDescriptor(self)->service_count(); } static ItemDescriptor GetByName(PyContainer* self, const string& name) { return GetDescriptor(self)->FindServiceByName(name); } static ItemDescriptor GetByIndex(PyContainer* self, int index) { return GetDescriptor(self)->service(index); } static PyObject* NewObjectFromItem(ItemDescriptor item) { return PyServiceDescriptor_FromDescriptor(item); } static const string& GetItemName(ItemDescriptor item) { return item->name(); } static int GetItemIndex(ItemDescriptor item) { return item->index(); } static DescriptorContainerDef ContainerDef = { "FileServices", (CountMethod)Count, (GetByIndexMethod)GetByIndex, (GetByNameMethod)GetByName, (GetByCamelcaseNameMethod)NULL, (GetByNumberMethod)NULL, (NewObjectFromItemMethod)NewObjectFromItem, (GetItemNameMethod)GetItemName, (GetItemCamelcaseNameMethod)NULL, (GetItemNumberMethod)NULL, (GetItemIndexMethod)GetItemIndex, }; } // namespace services PyObject* NewFileServicesByName(const FileDescriptor* descriptor) { return descriptor::NewMappingByName(&services::ContainerDef, descriptor); } namespace dependencies { typedef const FileDescriptor* ItemDescriptor; static int Count(PyContainer* self) { return GetDescriptor(self)->dependency_count(); } static ItemDescriptor GetByIndex(PyContainer* self, int index) { return GetDescriptor(self)->dependency(index); } static PyObject* NewObjectFromItem(ItemDescriptor item) { return PyFileDescriptor_FromDescriptor(item); } static DescriptorContainerDef ContainerDef = { "FileDependencies", (CountMethod)Count, (GetByIndexMethod)GetByIndex, (GetByNameMethod)NULL, (GetByCamelcaseNameMethod)NULL, (GetByNumberMethod)NULL, (NewObjectFromItemMethod)NewObjectFromItem, (GetItemNameMethod)NULL, (GetItemCamelcaseNameMethod)NULL, (GetItemNumberMethod)NULL, (GetItemIndexMethod)NULL, }; } // namespace dependencies PyObject* NewFileDependencies(const FileDescriptor* descriptor) { return descriptor::NewSequence(&dependencies::ContainerDef, descriptor); } namespace public_dependencies { typedef const FileDescriptor* ItemDescriptor; static int Count(PyContainer* self) { return GetDescriptor(self)->public_dependency_count(); } static ItemDescriptor GetByIndex(PyContainer* self, int index) { return GetDescriptor(self)->public_dependency(index); } static PyObject* NewObjectFromItem(ItemDescriptor item) { return PyFileDescriptor_FromDescriptor(item); } static DescriptorContainerDef ContainerDef = { "FilePublicDependencies", (CountMethod)Count, (GetByIndexMethod)GetByIndex, (GetByNameMethod)NULL, (GetByCamelcaseNameMethod)NULL, (GetByNumberMethod)NULL, (NewObjectFromItemMethod)NewObjectFromItem, (GetItemNameMethod)NULL, (GetItemCamelcaseNameMethod)NULL, (GetItemNumberMethod)NULL, (GetItemIndexMethod)NULL, }; } // namespace public_dependencies PyObject* NewFilePublicDependencies(const FileDescriptor* descriptor) { return descriptor::NewSequence(&public_dependencies::ContainerDef, descriptor); } } // namespace file_descriptor // Register all implementations bool InitDescriptorMappingTypes() { if (PyType_Ready(&descriptor::DescriptorMapping_Type) < 0) return false; if (PyType_Ready(&descriptor::DescriptorSequence_Type) < 0) return false; if (PyType_Ready(&descriptor::ContainerIterator_Type) < 0) return false; return true; } } // namespace python } // namespace protobuf } // namespace google
null
null
null
null
24,642
47,079
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
47,079
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 "cc/raster/texture_compressor_etc1_sse.h" #include <emmintrin.h> #include <stdint.h> #include "base/compiler_specific.h" #include "base/logging.h" // Using this header for common functions such as Color handling // and codeword table. #include "cc/raster/texture_compressor_etc1.h" namespace cc { namespace { inline uint32_t SetETC1MaxError(uint32_t avg_error) { // ETC1 codeword table is sorted in ascending order. // Our algorithm will try to identify the index that generates the minimum // error. // The min error calculated during ComputeLuminance main loop will converge // towards that value. // We use this threshold to determine when it doesn't make sense to iterate // further through the array. return avg_error + avg_error / 2 + 384; } struct __sse_data { // This is used to store raw data. uint8_t* block; // This is used to store 8 bit packed values. __m128i* packed; // This is used to store 32 bit zero extended values into 4x4 arrays. __m128i* blue; __m128i* green; __m128i* red; }; inline __m128i AddAndClamp(const __m128i x, const __m128i y) { static const __m128i color_max = _mm_set1_epi32(0xFF); return _mm_max_epi16(_mm_setzero_si128(), _mm_min_epi16(_mm_add_epi16(x, y), color_max)); } inline __m128i GetColorErrorSSE(const __m128i x, const __m128i y) { // Changed from _mm_mullo_epi32 (SSE4) to _mm_mullo_epi16 (SSE2). __m128i ret = _mm_sub_epi16(x, y); return _mm_mullo_epi16(ret, ret); } inline __m128i AddChannelError(const __m128i x, const __m128i y, const __m128i z) { return _mm_add_epi32(x, _mm_add_epi32(y, z)); } inline uint32_t SumSSE(const __m128i x) { __m128i sum = _mm_add_epi32(x, _mm_shuffle_epi32(x, 0x4E)); sum = _mm_add_epi32(sum, _mm_shuffle_epi32(sum, 0xB1)); return _mm_cvtsi128_si32(sum); } inline uint32_t GetVerticalError(const __sse_data* data, const __m128i* blue_avg, const __m128i* green_avg, const __m128i* red_avg, uint32_t* verror) { __m128i error = _mm_setzero_si128(); for (int i = 0; i < 4; i++) { error = _mm_add_epi32(error, GetColorErrorSSE(data->blue[i], blue_avg[0])); error = _mm_add_epi32(error, GetColorErrorSSE(data->green[i], green_avg[0])); error = _mm_add_epi32(error, GetColorErrorSSE(data->red[i], red_avg[0])); } error = _mm_add_epi32(error, _mm_shuffle_epi32(error, 0x4E)); verror[0] = _mm_cvtsi128_si32(error); verror[1] = _mm_cvtsi128_si32(_mm_shuffle_epi32(error, 0xB1)); return verror[0] + verror[1]; } inline uint32_t GetHorizontalError(const __sse_data* data, const __m128i* blue_avg, const __m128i* green_avg, const __m128i* red_avg, uint32_t* verror) { __m128i error = _mm_setzero_si128(); int first_index, second_index; for (int i = 0; i < 2; i++) { first_index = 2 * i; second_index = first_index + 1; error = _mm_add_epi32( error, GetColorErrorSSE(data->blue[first_index], blue_avg[i])); error = _mm_add_epi32( error, GetColorErrorSSE(data->blue[second_index], blue_avg[i])); error = _mm_add_epi32( error, GetColorErrorSSE(data->green[first_index], green_avg[i])); error = _mm_add_epi32( error, GetColorErrorSSE(data->green[second_index], green_avg[i])); error = _mm_add_epi32(error, GetColorErrorSSE(data->red[first_index], red_avg[i])); error = _mm_add_epi32( error, GetColorErrorSSE(data->red[second_index], red_avg[i])); } error = _mm_add_epi32(error, _mm_shuffle_epi32(error, 0x4E)); verror[0] = _mm_cvtsi128_si32(error); verror[1] = _mm_cvtsi128_si32(_mm_shuffle_epi32(error, 0xB1)); return verror[0] + verror[1]; } inline void GetAvgColors(const __sse_data* data, float* output, bool* __sse_use_diff) { __m128i sum[2], tmp; // TODO(radu.velea): _mm_avg_epu8 on packed data maybe. // Compute avg red value. // [S0 S0 S1 S1] sum[0] = _mm_add_epi32(data->red[0], data->red[1]); sum[0] = _mm_add_epi32(sum[0], _mm_shuffle_epi32(sum[0], 0xB1)); // [S2 S2 S3 S3] sum[1] = _mm_add_epi32(data->red[2], data->red[3]); sum[1] = _mm_add_epi32(sum[1], _mm_shuffle_epi32(sum[1], 0xB1)); float hred[2], vred[2]; hred[0] = (_mm_cvtsi128_si32( _mm_add_epi32(sum[0], _mm_shuffle_epi32(sum[0], 0x4E)))) / 8.0f; hred[1] = (_mm_cvtsi128_si32( _mm_add_epi32(sum[1], _mm_shuffle_epi32(sum[1], 0x4E)))) / 8.0f; tmp = _mm_add_epi32(sum[0], sum[1]); vred[0] = (_mm_cvtsi128_si32(tmp)) / 8.0f; vred[1] = (_mm_cvtsi128_si32(_mm_shuffle_epi32(tmp, 0x2))) / 8.0f; // Compute avg green value. // [S0 S0 S1 S1] sum[0] = _mm_add_epi32(data->green[0], data->green[1]); sum[0] = _mm_add_epi32(sum[0], _mm_shuffle_epi32(sum[0], 0xB1)); // [S2 S2 S3 S3] sum[1] = _mm_add_epi32(data->green[2], data->green[3]); sum[1] = _mm_add_epi32(sum[1], _mm_shuffle_epi32(sum[1], 0xB1)); float hgreen[2], vgreen[2]; hgreen[0] = (_mm_cvtsi128_si32( _mm_add_epi32(sum[0], _mm_shuffle_epi32(sum[0], 0x4E)))) / 8.0f; hgreen[1] = (_mm_cvtsi128_si32( _mm_add_epi32(sum[1], _mm_shuffle_epi32(sum[1], 0x4E)))) / 8.0f; tmp = _mm_add_epi32(sum[0], sum[1]); vgreen[0] = (_mm_cvtsi128_si32(tmp)) / 8.0f; vgreen[1] = (_mm_cvtsi128_si32(_mm_shuffle_epi32(tmp, 0x2))) / 8.0f; // Compute avg blue value. // [S0 S0 S1 S1] sum[0] = _mm_add_epi32(data->blue[0], data->blue[1]); sum[0] = _mm_add_epi32(sum[0], _mm_shuffle_epi32(sum[0], 0xB1)); // [S2 S2 S3 S3] sum[1] = _mm_add_epi32(data->blue[2], data->blue[3]); sum[1] = _mm_add_epi32(sum[1], _mm_shuffle_epi32(sum[1], 0xB1)); float hblue[2], vblue[2]; hblue[0] = (_mm_cvtsi128_si32( _mm_add_epi32(sum[0], _mm_shuffle_epi32(sum[0], 0x4E)))) / 8.0f; hblue[1] = (_mm_cvtsi128_si32( _mm_add_epi32(sum[1], _mm_shuffle_epi32(sum[1], 0x4E)))) / 8.0f; tmp = _mm_add_epi32(sum[0], sum[1]); vblue[0] = (_mm_cvtsi128_si32(tmp)) / 8.0f; vblue[1] = (_mm_cvtsi128_si32(_mm_shuffle_epi32(tmp, 0x2))) / 8.0f; // TODO(radu.velea): Return int's instead of floats, based on Quality. output[0] = vblue[0]; output[1] = vgreen[0]; output[2] = vred[0]; output[3] = vblue[1]; output[4] = vgreen[1]; output[5] = vred[1]; output[6] = hblue[0]; output[7] = hgreen[0]; output[8] = hred[0]; output[9] = hblue[1]; output[10] = hgreen[1]; output[11] = hred[1]; __m128i threshold_upper = _mm_set1_epi32(3); __m128i threshold_lower = _mm_set1_epi32(-4); __m128 factor_v = _mm_set1_ps(31.0f / 255.0f); __m128 rounding_v = _mm_set1_ps(0.5f); __m128 h_avg_0 = _mm_set_ps(hblue[0], hgreen[0], hred[0], 0); __m128 h_avg_1 = _mm_set_ps(hblue[1], hgreen[1], hred[1], 0); __m128 v_avg_0 = _mm_set_ps(vblue[0], vgreen[0], vred[0], 0); __m128 v_avg_1 = _mm_set_ps(vblue[1], vgreen[1], vred[1], 0); h_avg_0 = _mm_mul_ps(h_avg_0, factor_v); h_avg_1 = _mm_mul_ps(h_avg_1, factor_v); v_avg_0 = _mm_mul_ps(v_avg_0, factor_v); v_avg_1 = _mm_mul_ps(v_avg_1, factor_v); h_avg_0 = _mm_add_ps(h_avg_0, rounding_v); h_avg_1 = _mm_add_ps(h_avg_1, rounding_v); v_avg_0 = _mm_add_ps(v_avg_0, rounding_v); v_avg_1 = _mm_add_ps(v_avg_1, rounding_v); __m128i h_avg_0i = _mm_cvttps_epi32(h_avg_0); __m128i h_avg_1i = _mm_cvttps_epi32(h_avg_1); __m128i v_avg_0i = _mm_cvttps_epi32(v_avg_0); __m128i v_avg_1i = _mm_cvttps_epi32(v_avg_1); h_avg_0i = _mm_sub_epi32(h_avg_1i, h_avg_0i); v_avg_0i = _mm_sub_epi32(v_avg_1i, v_avg_0i); __sse_use_diff[0] = (0 == _mm_movemask_epi8(_mm_cmplt_epi32(v_avg_0i, threshold_lower))); __sse_use_diff[0] &= (0 == _mm_movemask_epi8(_mm_cmpgt_epi32(v_avg_0i, threshold_upper))); __sse_use_diff[1] = (0 == _mm_movemask_epi8(_mm_cmplt_epi32(h_avg_0i, threshold_lower))); __sse_use_diff[1] &= (0 == _mm_movemask_epi8(_mm_cmpgt_epi32(h_avg_0i, threshold_upper))); } void ComputeLuminance(uint8_t* block, const Color& base, const int sub_block_id, const uint8_t* idx_to_num_tab, const __sse_data* data, const uint32_t expected_error) { uint8_t best_tbl_idx = 0; uint32_t best_error = 0x7FFFFFFF; uint8_t best_mod_idx[8][8]; // [table][texel] const __m128i base_blue = _mm_set1_epi32(base.channels.b); const __m128i base_green = _mm_set1_epi32(base.channels.g); const __m128i base_red = _mm_set1_epi32(base.channels.r); __m128i test_red, test_blue, test_green, tmp, tmp_blue, tmp_green, tmp_red; __m128i block_error, mask; // This will have the minimum errors for each 4 pixels. __m128i first_half_min; __m128i second_half_min; // This will have the matching table index combo for each 4 pixels. __m128i first_half_pattern; __m128i second_half_pattern; const __m128i first_blue_data_block = data->blue[2 * sub_block_id]; const __m128i first_green_data_block = data->green[2 * sub_block_id]; const __m128i first_red_data_block = data->red[2 * sub_block_id]; const __m128i second_blue_data_block = data->blue[2 * sub_block_id + 1]; const __m128i second_green_data_block = data->green[2 * sub_block_id + 1]; const __m128i second_red_data_block = data->red[2 * sub_block_id + 1]; uint32_t min; // Fail early to increase speed. long delta = INT32_MAX; uint32_t last_min = INT32_MAX; const uint8_t shuffle_mask[] = { 0x1B, 0x4E, 0xB1, 0xE4}; // Important they are sorted ascending. for (unsigned int tbl_idx = 0; tbl_idx < 8; ++tbl_idx) { tmp = _mm_set_epi32( g_codeword_tables[tbl_idx][3], g_codeword_tables[tbl_idx][2], g_codeword_tables[tbl_idx][1], g_codeword_tables[tbl_idx][0]); test_blue = AddAndClamp(tmp, base_blue); test_green = AddAndClamp(tmp, base_green); test_red = AddAndClamp(tmp, base_red); first_half_min = _mm_set1_epi32(0x7FFFFFFF); second_half_min = _mm_set1_epi32(0x7FFFFFFF); first_half_pattern = _mm_setzero_si128(); second_half_pattern = _mm_setzero_si128(); for (uint8_t imm8 : shuffle_mask) { switch (imm8) { case 0x1B: tmp_blue = _mm_shuffle_epi32(test_blue, 0x1B); tmp_green = _mm_shuffle_epi32(test_green, 0x1B); tmp_red = _mm_shuffle_epi32(test_red, 0x1B); break; case 0x4E: tmp_blue = _mm_shuffle_epi32(test_blue, 0x4E); tmp_green = _mm_shuffle_epi32(test_green, 0x4E); tmp_red = _mm_shuffle_epi32(test_red, 0x4E); break; case 0xB1: tmp_blue = _mm_shuffle_epi32(test_blue, 0xB1); tmp_green = _mm_shuffle_epi32(test_green, 0xB1); tmp_red = _mm_shuffle_epi32(test_red, 0xB1); break; case 0xE4: tmp_blue = _mm_shuffle_epi32(test_blue, 0xE4); tmp_green = _mm_shuffle_epi32(test_green, 0xE4); tmp_red = _mm_shuffle_epi32(test_red, 0xE4); break; default: tmp_blue = test_blue; tmp_green = test_green; tmp_red = test_red; } tmp = _mm_set1_epi32(imm8); block_error = AddChannelError(GetColorErrorSSE(tmp_blue, first_blue_data_block), GetColorErrorSSE(tmp_green, first_green_data_block), GetColorErrorSSE(tmp_red, first_red_data_block)); // Save winning pattern. first_half_pattern = _mm_max_epi16( first_half_pattern, _mm_and_si128(tmp, _mm_cmpgt_epi32(first_half_min, block_error))); // Should use _mm_min_epi32(first_half_min, block_error); from SSE4 // otherwise we have a small performance penalty. mask = _mm_cmplt_epi32(block_error, first_half_min); first_half_min = _mm_add_epi32(_mm_and_si128(mask, block_error), _mm_andnot_si128(mask, first_half_min)); // Compute second part of the block. block_error = AddChannelError(GetColorErrorSSE(tmp_blue, second_blue_data_block), GetColorErrorSSE(tmp_green, second_green_data_block), GetColorErrorSSE(tmp_red, second_red_data_block)); // Save winning pattern. second_half_pattern = _mm_max_epi16( second_half_pattern, _mm_and_si128(tmp, _mm_cmpgt_epi32(second_half_min, block_error))); // Should use _mm_min_epi32(second_half_min, block_error); from SSE4 // otherwise we have a small performance penalty. mask = _mm_cmplt_epi32(block_error, second_half_min); second_half_min = _mm_add_epi32(_mm_and_si128(mask, block_error), _mm_andnot_si128(mask, second_half_min)); } first_half_min = _mm_add_epi32(first_half_min, second_half_min); first_half_min = _mm_add_epi32(first_half_min, _mm_shuffle_epi32(first_half_min, 0x4E)); first_half_min = _mm_add_epi32(first_half_min, _mm_shuffle_epi32(first_half_min, 0xB1)); min = _mm_cvtsi128_si32(first_half_min); delta = min - last_min; last_min = min; if (min < best_error) { best_tbl_idx = tbl_idx; best_error = min; best_mod_idx[tbl_idx][0] = (_mm_cvtsi128_si32(first_half_pattern) >> (0)) & 3; best_mod_idx[tbl_idx][4] = (_mm_cvtsi128_si32(second_half_pattern) >> (0)) & 3; best_mod_idx[tbl_idx][1] = (_mm_cvtsi128_si32(_mm_shuffle_epi32(first_half_pattern, 0x1)) >> (2)) & 3; best_mod_idx[tbl_idx][5] = (_mm_cvtsi128_si32(_mm_shuffle_epi32(second_half_pattern, 0x1)) >> (2)) & 3; best_mod_idx[tbl_idx][2] = (_mm_cvtsi128_si32(_mm_shuffle_epi32(first_half_pattern, 0x2)) >> (4)) & 3; best_mod_idx[tbl_idx][6] = (_mm_cvtsi128_si32(_mm_shuffle_epi32(second_half_pattern, 0x2)) >> (4)) & 3; best_mod_idx[tbl_idx][3] = (_mm_cvtsi128_si32(_mm_shuffle_epi32(first_half_pattern, 0x3)) >> (6)) & 3; best_mod_idx[tbl_idx][7] = (_mm_cvtsi128_si32(_mm_shuffle_epi32(second_half_pattern, 0x3)) >> (6)) & 3; if (best_error == 0) { break; } } else if (delta > 0 && expected_error < min) { // The error is growing and is well beyond expected threshold. break; } } WriteCodewordTable(block, sub_block_id, best_tbl_idx); uint32_t pix_data = 0; uint8_t mod_idx; uint8_t pix_idx; uint32_t lsb; uint32_t msb; int texel_num; for (unsigned int i = 0; i < 8; ++i) { mod_idx = best_mod_idx[best_tbl_idx][i]; pix_idx = g_mod_to_pix[mod_idx]; lsb = pix_idx & 0x1; msb = pix_idx >> 1; // Obtain the texel number as specified in the standard. texel_num = idx_to_num_tab[i]; pix_data |= msb << (texel_num + 16); pix_data |= lsb << (texel_num); } WritePixelData(block, pix_data); } void CompressBlock(uint8_t* dst, __sse_data* data) { // First 3 values are for vertical 1, second 3 vertical 2, third 3 horizontal // 1, last 3 // horizontal 2. float __sse_avg_colors[12] = { 0, }; bool use_differential[2] = {true, true}; GetAvgColors(data, __sse_avg_colors, use_differential); Color sub_block_avg[4]; // TODO(radu.velea): Remove floating point operations and use only int's + // normal rounding and shifts for reduced Quality. for (int i = 0, j = 1; i < 4; i += 2, j += 2) { if (use_differential[i / 2] == false) { sub_block_avg[i] = MakeColor444(&__sse_avg_colors[i * 3]); sub_block_avg[j] = MakeColor444(&__sse_avg_colors[j * 3]); } else { sub_block_avg[i] = MakeColor555(&__sse_avg_colors[i * 3]); sub_block_avg[j] = MakeColor555(&__sse_avg_colors[j * 3]); } } __m128i red_avg[2], green_avg[2], blue_avg[2]; // TODO(radu.velea): Perfect accuracy, maybe skip floating variables. blue_avg[0] = _mm_set_epi32(static_cast<int>(__sse_avg_colors[3]), static_cast<int>(__sse_avg_colors[3]), static_cast<int>(__sse_avg_colors[0]), static_cast<int>(__sse_avg_colors[0])); green_avg[0] = _mm_set_epi32(static_cast<int>(__sse_avg_colors[4]), static_cast<int>(__sse_avg_colors[4]), static_cast<int>(__sse_avg_colors[1]), static_cast<int>(__sse_avg_colors[1])); red_avg[0] = _mm_set_epi32(static_cast<int>(__sse_avg_colors[5]), static_cast<int>(__sse_avg_colors[5]), static_cast<int>(__sse_avg_colors[2]), static_cast<int>(__sse_avg_colors[2])); uint32_t vertical_error[2]; GetVerticalError(data, blue_avg, green_avg, red_avg, vertical_error); // TODO(radu.velea): Perfect accuracy, maybe skip floating variables. blue_avg[0] = _mm_set1_epi32(static_cast<int>(__sse_avg_colors[6])); blue_avg[1] = _mm_set1_epi32(static_cast<int>(__sse_avg_colors[9])); green_avg[0] = _mm_set1_epi32(static_cast<int>(__sse_avg_colors[7])); green_avg[1] = _mm_set1_epi32(static_cast<int>(__sse_avg_colors[10])); red_avg[0] = _mm_set1_epi32(static_cast<int>(__sse_avg_colors[8])); red_avg[1] = _mm_set1_epi32(static_cast<int>(__sse_avg_colors[11])); uint32_t horizontal_error[2]; GetHorizontalError(data, blue_avg, green_avg, red_avg, horizontal_error); bool flip = (horizontal_error[0] + horizontal_error[1]) < (vertical_error[0] + vertical_error[1]); uint32_t* expected_errors = flip ? horizontal_error : vertical_error; // Clear destination buffer so that we can "or" in the results. memset(dst, 0, 8); WriteDiff(dst, use_differential[!!flip]); WriteFlip(dst, flip); uint8_t sub_block_off_0 = flip ? 2 : 0; uint8_t sub_block_off_1 = sub_block_off_0 + 1; if (use_differential[!!flip]) { WriteColors555(dst, sub_block_avg[sub_block_off_0], sub_block_avg[sub_block_off_1]); } else { WriteColors444(dst, sub_block_avg[sub_block_off_0], sub_block_avg[sub_block_off_1]); } if (!flip) { // Transpose vertical data into horizontal lines. __m128i tmp; for (int i = 0; i < 4; i += 2) { tmp = data->blue[i]; data->blue[i] = _mm_add_epi32( _mm_move_epi64(data->blue[i]), _mm_shuffle_epi32(_mm_move_epi64(data->blue[i + 1]), 0x4E)); data->blue[i + 1] = _mm_add_epi32( _mm_move_epi64(_mm_shuffle_epi32(tmp, 0x4E)), _mm_shuffle_epi32( _mm_move_epi64(_mm_shuffle_epi32(data->blue[i + 1], 0x4E)), 0x4E)); tmp = data->green[i]; data->green[i] = _mm_add_epi32( _mm_move_epi64(data->green[i]), _mm_shuffle_epi32(_mm_move_epi64(data->green[i + 1]), 0x4E)); data->green[i + 1] = _mm_add_epi32( _mm_move_epi64(_mm_shuffle_epi32(tmp, 0x4E)), _mm_shuffle_epi32( _mm_move_epi64(_mm_shuffle_epi32(data->green[i + 1], 0x4E)), 0x4E)); tmp = data->red[i]; data->red[i] = _mm_add_epi32( _mm_move_epi64(data->red[i]), _mm_shuffle_epi32(_mm_move_epi64(data->red[i + 1]), 0x4E)); data->red[i + 1] = _mm_add_epi32( _mm_move_epi64(_mm_shuffle_epi32(tmp, 0x4E)), _mm_shuffle_epi32( _mm_move_epi64(_mm_shuffle_epi32(data->red[i + 1], 0x4E)), 0x4E)); } tmp = data->blue[1]; data->blue[1] = data->blue[2]; data->blue[2] = tmp; tmp = data->green[1]; data->green[1] = data->green[2]; data->green[2] = tmp; tmp = data->red[1]; data->red[1] = data->red[2]; data->red[2] = tmp; } // Compute luminance for the first sub block. ComputeLuminance(dst, sub_block_avg[sub_block_off_0], 0, g_idx_to_num[sub_block_off_0], data, SetETC1MaxError(expected_errors[0])); // Compute luminance for the second sub block. ComputeLuminance(dst, sub_block_avg[sub_block_off_1], 1, g_idx_to_num[sub_block_off_1], data, SetETC1MaxError(expected_errors[1])); } static void ExtractBlock(uint8_t* dst, const uint8_t* src, int width) { for (int j = 0; j < 4; ++j) { memcpy(&dst[j * 4 * 4], src, 4 * 4); src += width * 4; } } inline bool TransposeBlock(uint8_t* block, __m128i* transposed) { // This function transforms an incommig block of RGBA or GBRA pixels into 4 // registers, each containing the data corresponding for a single channel. // Ex: transposed[0] will have all the R values for a RGBA block, // transposed[1] will have G, etc. // The values are packed as 8 bit unsigned values in the SSE registers. // Before doing any work we check if the block is solid. __m128i tmp3, tmp2, tmp1, tmp0; __m128i test_solid = _mm_set1_epi32(*((uint32_t*)block)); uint16_t mask = 0xFFFF; // a0,a1,a2,...a7, ...a15 transposed[0] = _mm_loadu_si128((__m128i*)(block)); // b0, b1,b2,...b7.... b15 transposed[1] = _mm_loadu_si128((__m128i*)(block + 16)); // c0, c1,c2,...c7....c15 transposed[2] = _mm_loadu_si128((__m128i*)(block + 32)); // d0,d1,d2,...d7....d15 transposed[3] = _mm_loadu_si128((__m128i*)(block + 48)); for (int i = 0; i < 4; i++) { mask &= _mm_movemask_epi8(_mm_cmpeq_epi8(transposed[i], test_solid)); } if (mask == 0xFFFF) { // Block is solid, no need to do any more work. return false; } // a0,b0, a1,b1, a2,b2, a3,b3,....a7,b7 tmp0 = _mm_unpacklo_epi8(transposed[0], transposed[1]); // c0,d0, c1,d1, c2,d2, c3,d3,... c7,d7 tmp1 = _mm_unpacklo_epi8(transposed[2], transposed[3]); // a8,b8, a9,b9, a10,b10, a11,b11,...a15,b15 tmp2 = _mm_unpackhi_epi8(transposed[0], transposed[1]); // c8,d8, c9,d9, c10,d10, c11,d11,...c15,d15 tmp3 = _mm_unpackhi_epi8(transposed[2], transposed[3]); // a0,a8, b0,b8, a1,a9, b1,b9, ....a3,a11, b3,b11 transposed[0] = _mm_unpacklo_epi8(tmp0, tmp2); // a4,a12, b4,b12, a5,a13, b5,b13,....a7,a15,b7,b15 transposed[1] = _mm_unpackhi_epi8(tmp0, tmp2); // c0,c8, d0,d8, c1,c9, d1,d9.....d3,d11 transposed[2] = _mm_unpacklo_epi8(tmp1, tmp3); // c4,c12,d4,d12, c5,c13, d5,d13,....d7,d15 transposed[3] = _mm_unpackhi_epi8(tmp1, tmp3); // a0,a8, b0,b8, c0,c8, d0,d8, a1,a9, b1,b9, c1,c9, d1,d9 tmp0 = _mm_unpacklo_epi32(transposed[0], transposed[2]); // a2,a10, b2,b10, c2,c10, d2,d10, a3,a11, b3,b11, c3,c11, d3,d11 tmp1 = _mm_unpackhi_epi32(transposed[0], transposed[2]); // a4,a12, b4,b12, c4,c12, d4,d12, a5,a13, b5,b13, c5,c13, d5,d13 tmp2 = _mm_unpacklo_epi32(transposed[1], transposed[3]); // a6,a14, b6,b14, c6,c14, d6,d14, a7,a15, b7,b15, c7,c15, d7,d15 tmp3 = _mm_unpackhi_epi32(transposed[1], transposed[3]); // a0,a4, a8,a12, b0,b4, b8,b12, c0,c4, c8,c12, d0,d4, d8,d12 transposed[0] = _mm_unpacklo_epi8(tmp0, tmp2); // a1,a5, a9,a13, b1,b5, b9,b13, c1,c5, c9,c13, d1,d5, d9,d13 transposed[1] = _mm_unpackhi_epi8(tmp0, tmp2); // a2,a6, a10,a14, b2,b6, b10,b14, c2,c6, c10,c14, d2,d6, d10,d14 transposed[2] = _mm_unpacklo_epi8(tmp1, tmp3); // a3,a7, a11,a15, b3,b7, b11,b15, c3,c7, c11,c15, d3,d7, d11,d15 transposed[3] = _mm_unpackhi_epi8(tmp1, tmp3); return true; } inline void UnpackBlock(__m128i* packed, __m128i* red, __m128i* green, __m128i* blue, __m128i* alpha) { const __m128i zero = _mm_set1_epi8(0); __m128i tmp_low, tmp_high; // Unpack red. tmp_low = _mm_unpacklo_epi8(packed[0], zero); tmp_high = _mm_unpackhi_epi8(packed[0], zero); red[0] = _mm_unpacklo_epi16(tmp_low, zero); red[1] = _mm_unpackhi_epi16(tmp_low, zero); red[2] = _mm_unpacklo_epi16(tmp_high, zero); red[3] = _mm_unpackhi_epi16(tmp_high, zero); // Unpack green. tmp_low = _mm_unpacklo_epi8(packed[1], zero); tmp_high = _mm_unpackhi_epi8(packed[1], zero); green[0] = _mm_unpacklo_epi16(tmp_low, zero); green[1] = _mm_unpackhi_epi16(tmp_low, zero); green[2] = _mm_unpacklo_epi16(tmp_high, zero); green[3] = _mm_unpackhi_epi16(tmp_high, zero); // Unpack blue. tmp_low = _mm_unpacklo_epi8(packed[2], zero); tmp_high = _mm_unpackhi_epi8(packed[2], zero); blue[0] = _mm_unpacklo_epi16(tmp_low, zero); blue[1] = _mm_unpackhi_epi16(tmp_low, zero); blue[2] = _mm_unpacklo_epi16(tmp_high, zero); blue[3] = _mm_unpackhi_epi16(tmp_high, zero); // Unpack alpha - unused for ETC1. tmp_low = _mm_unpacklo_epi8(packed[3], zero); tmp_high = _mm_unpackhi_epi8(packed[3], zero); alpha[0] = _mm_unpacklo_epi16(tmp_low, zero); alpha[1] = _mm_unpackhi_epi16(tmp_low, zero); alpha[2] = _mm_unpacklo_epi16(tmp_high, zero); alpha[3] = _mm_unpackhi_epi16(tmp_high, zero); } inline void CompressSolid(uint8_t* dst, uint8_t* block) { // Clear destination buffer so that we can "or" in the results. memset(dst, 0, 8); const float src_color_float[3] = {static_cast<float>(block[0]), static_cast<float>(block[1]), static_cast<float>(block[2])}; const Color base = MakeColor555(src_color_float); const __m128i base_v = _mm_set_epi32(0, base.channels.r, base.channels.g, base.channels.b); const __m128i constant = _mm_set_epi32(0, block[2], block[1], block[0]); __m128i lum; __m128i colors[4]; static const __m128i rgb = _mm_set_epi32(0, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF); WriteDiff(dst, true); WriteFlip(dst, false); WriteColors555(dst, base, base); uint8_t best_tbl_idx = 0; uint8_t best_mod_idx = 0; uint32_t best_mod_err = INT32_MAX; for (unsigned int tbl_idx = 0; tbl_idx < 8; ++tbl_idx) { lum = _mm_set_epi32( g_codeword_tables[tbl_idx][3], g_codeword_tables[tbl_idx][2], g_codeword_tables[tbl_idx][1], g_codeword_tables[tbl_idx][0]); colors[0] = AddAndClamp(base_v, _mm_shuffle_epi32(lum, 0x0)); colors[1] = AddAndClamp(base_v, _mm_shuffle_epi32(lum, 0x55)); colors[2] = AddAndClamp(base_v, _mm_shuffle_epi32(lum, 0xAA)); colors[3] = AddAndClamp(base_v, _mm_shuffle_epi32(lum, 0xFF)); for (int i = 0; i < 4; i++) { uint32_t mod_err = SumSSE(GetColorErrorSSE(constant, _mm_and_si128(colors[i], rgb))); colors[i] = _mm_and_si128(colors[i], rgb); if (mod_err < best_mod_err) { best_tbl_idx = tbl_idx; best_mod_idx = i; best_mod_err = mod_err; if (mod_err == 0) { break; // We cannot do any better than this. } } } } WriteCodewordTable(dst, 0, best_tbl_idx); WriteCodewordTable(dst, 1, best_tbl_idx); uint8_t pix_idx = g_mod_to_pix[best_mod_idx]; uint32_t lsb = pix_idx & 0x1; uint32_t msb = pix_idx >> 1; uint32_t pix_data = 0; for (unsigned int i = 0; i < 2; ++i) { for (unsigned int j = 0; j < 8; ++j) { // Obtain the texel number as specified in the standard. int texel_num = g_idx_to_num[i][j]; pix_data |= msb << (texel_num + 16); pix_data |= lsb << (texel_num); } } WritePixelData(dst, pix_data); } } // namespace void TextureCompressorETC1SSE::Compress(const uint8_t* src, uint8_t* dst, int width, int height, Quality quality) { DCHECK_GE(width, 4); DCHECK_EQ((width & 3), 0); DCHECK_GE(height, 4); DCHECK_EQ((height & 3), 0); alignas(16) uint8_t block[64]; __m128i packed[4]; __m128i red[4], green[4], blue[4], alpha[4]; __sse_data data; for (int y = 0; y < height; y += 4, src += width * 4 * 4) { for (int x = 0; x < width; x += 4, dst += 8) { ExtractBlock(block, src + x * 4, width); if (TransposeBlock(block, packed) == false) { CompressSolid(dst, block); } else { UnpackBlock(packed, blue, green, red, alpha); data.block = block; data.packed = packed; data.red = red; data.blue = blue; data.green = green; CompressBlock(dst, &data); } } } } } // namespace cc
null
null
null
null
43,942
38,841
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
38,841
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* * Copyright (C) 2010, 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 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. */ #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_WEBAUDIO_DELAY_DSP_KERNEL_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_WEBAUDIO_DELAY_DSP_KERNEL_H_ #include "third_party/blink/renderer/modules/webaudio/delay_processor.h" #include "third_party/blink/renderer/platform/audio/audio_delay_dsp_kernel.h" namespace blink { class DelayProcessor; class DelayDSPKernel final : public AudioDelayDSPKernel { public: explicit DelayDSPKernel(DelayProcessor*); protected: bool HasSampleAccurateValues() override; void CalculateSampleAccurateValues(float* delay_times, size_t frames_to_process) override; double DelayTime(float sample_rate) override; void ProcessOnlyAudioParams(size_t frames_to_process) override; private: DelayProcessor* GetDelayProcessor() { return static_cast<DelayProcessor*>(Processor()); } }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_WEBAUDIO_DELAY_DSP_KERNEL_H_
null
null
null
null
35,704
11,448
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
176,443
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * syscalls.h - Linux syscall interfaces (arch-specific) * * Copyright (c) 2008 Jaswinder Singh Rajput * 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_SYSCALLS_H #define _ASM_TILE_SYSCALLS_H #include <linux/compiler.h> #include <linux/linkage.h> #include <linux/signal.h> #include <linux/types.h> #include <linux/compat.h> /* * Note that by convention, any syscall which requires the current * register set takes an additional "struct pt_regs *" pointer; a * _sys_xxx() trampoline in intvec*.S just sets up the pointer and * jumps to sys_xxx(). */ /* kernel/sys.c */ ssize_t sys32_readahead(int fd, u32 offset_lo, u32 offset_hi, u32 count); long sys32_fadvise64(int fd, u32 offset_lo, u32 offset_hi, u32 len, int advice); int sys32_fadvise64_64(int fd, u32 offset_lo, u32 offset_hi, u32 len_lo, u32 len_hi, int advice); long sys_cacheflush(unsigned long addr, unsigned long len, unsigned long flags); #ifndef __tilegx__ /* No mmap() in the 32-bit kernel. */ #define sys_mmap sys_mmap #endif #ifndef __tilegx__ /* mm/fault.c */ long sys_cmpxchg_badaddr(unsigned long address); #endif #ifdef CONFIG_COMPAT /* These four are not defined for 64-bit, but serve as "compat" syscalls. */ long sys_fcntl64(unsigned int fd, unsigned int cmd, unsigned long arg); long sys_fstat64(unsigned long fd, struct stat64 __user *statbuf); long sys_truncate64(const char __user *path, loff_t length); long sys_ftruncate64(unsigned int fd, loff_t length); #endif /* Provide versions of standard syscalls that use current_pt_regs(). */ long sys_rt_sigreturn(void); #define sys_rt_sigreturn sys_rt_sigreturn /* These are the intvec*.S trampolines. */ long _sys_rt_sigreturn(void); long _sys_clone(unsigned long clone_flags, unsigned long newsp, void __user *parent_tid, void __user *child_tid); #include <asm-generic/syscalls.h> #endif /* _ASM_TILE_SYSCALLS_H */
null
null
null
null
84,790
28,324
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
193,319
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* spk_priv.h * review functions for the speakup screen review package. * originally written by: Kirk Reiser and Andy Berdan. * * extensively modified by David Borowski. * * Copyright (C) 1998 Kirk Reiser. * Copyright (C) 2003 David Borowski. * * 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. */ #ifndef _SPEAKUP_KEYINFO_H #define _SPEAKUP_KEYINFO_H #define FIRST_SYNTH_VAR RATE /* 0 is reserved for no remap */ #define SPEAKUP_GOTO 0x01 #define SPEECH_KILL 0x02 #define SPEAKUP_QUIET 0x03 #define SPEAKUP_CUT 0x04 #define SPEAKUP_PASTE 0x05 #define SAY_FIRST_CHAR 0x06 #define SAY_LAST_CHAR 0x07 #define SAY_CHAR 0x08 #define SAY_PREV_CHAR 0x09 #define SAY_NEXT_CHAR 0x0a #define SAY_WORD 0x0b #define SAY_PREV_WORD 0x0c #define SAY_NEXT_WORD 0x0d #define SAY_LINE 0x0e #define SAY_PREV_LINE 0x0f #define SAY_NEXT_LINE 0x10 #define TOP_EDGE 0x11 #define BOTTOM_EDGE 0x12 #define LEFT_EDGE 0x13 #define RIGHT_EDGE 0x14 #define SPELL_PHONETIC 0x15 #define SPELL_WORD 0x16 #define SAY_SCREEN 0x17 #define SAY_POSITION 0x18 #define SAY_ATTRIBUTES 0x19 #define SPEAKUP_OFF 0x1a #define SPEAKUP_PARKED 0x1b #define SAY_LINE_INDENT 0x1c #define SAY_FROM_TOP 0x1d #define SAY_TO_BOTTOM 0x1e #define SAY_FROM_LEFT 0x1f #define SAY_TO_RIGHT 0x20 #define SAY_CHAR_NUM 0x21 #define EDIT_SOME 0x22 #define EDIT_MOST 0x23 #define SAY_PHONETIC_CHAR 0x24 #define EDIT_DELIM 0x25 #define EDIT_REPEAT 0x26 #define EDIT_EXNUM 0x27 #define SET_WIN 0x28 #define CLEAR_WIN 0x29 #define ENABLE_WIN 0x2a #define SAY_WIN 0x2b #define SPK_LOCK 0x2c #define SPEAKUP_HELP 0x2d #define TOGGLE_CURSORING 0x2e #define READ_ALL_DOC 0x2f #define SPKUP_MAX_FUNC 0x30 /* one greater than the last func handler */ #define SPK_KEY 0x80 #define FIRST_EDIT_BITS 0x22 #define FIRST_SET_VAR SPELL_DELAY #define VAR_START 0x40 /* increase if adding more than 0x3f functions */ /* keys for setting variables, must be ordered same as the enum for var_ids */ /* with dec being even and inc being 1 greater */ #define SPELL_DELAY_DEC (VAR_START + 0) #define SPELL_DELAY_INC (SPELL_DELAY_DEC + 1) #define PUNC_LEVEL_DEC (SPELL_DELAY_DEC + 2) #define PUNC_LEVEL_INC (PUNC_LEVEL_DEC + 1) #define READING_PUNC_DEC (PUNC_LEVEL_DEC + 2) #define READING_PUNC_INC (READING_PUNC_DEC + 1) #define ATTRIB_BLEEP_DEC (READING_PUNC_DEC + 2) #define ATTRIB_BLEEP_INC (ATTRIB_BLEEP_DEC + 1) #define BLEEPS_DEC (ATTRIB_BLEEP_DEC + 2) #define BLEEPS_INC (BLEEPS_DEC + 1) #define RATE_DEC (BLEEPS_DEC + 2) #define RATE_INC (RATE_DEC + 1) #define PITCH_DEC (RATE_DEC + 2) #define PITCH_INC (PITCH_DEC + 1) #define VOL_DEC (PITCH_DEC + 2) #define VOL_INC (VOL_DEC + 1) #define TONE_DEC (VOL_DEC + 2) #define TONE_INC (TONE_DEC + 1) #define PUNCT_DEC (TONE_DEC + 2) #define PUNCT_INC (PUNCT_DEC + 1) #define VOICE_DEC (PUNCT_DEC + 2) #define VOICE_INC (VOICE_DEC + 1) #endif
null
null
null
null
101,666
27,157
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
27,157
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* Copyright (C) 2007-2009 Xiph.Org Foundation Copyright (C) 2003-2008 Jean-Marc Valin Copyright (C) 2007-2008 CSIRO */ /** @file fixed_generic.h @brief Generic fixed-point operations */ /* 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. 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. */ #ifndef CELT_FIXED_GENERIC_MIPSR1_H #define CELT_FIXED_GENERIC_MIPSR1_H #undef MULT16_32_Q15_ADD static inline int MULT16_32_Q15_ADD(int a, int b, int c, int d) { int m; asm volatile("MULT $ac1, %0, %1" : : "r" ((int)a), "r" ((int)b)); asm volatile("madd $ac1, %0, %1" : : "r" ((int)c), "r" ((int)d)); asm volatile("EXTR.W %0,$ac1, %1" : "=r" (m): "i" (15)); return m; } #undef MULT16_32_Q15_SUB static inline int MULT16_32_Q15_SUB(int a, int b, int c, int d) { int m; asm volatile("MULT $ac1, %0, %1" : : "r" ((int)a), "r" ((int)b)); asm volatile("msub $ac1, %0, %1" : : "r" ((int)c), "r" ((int)d)); asm volatile("EXTR.W %0,$ac1, %1" : "=r" (m): "i" (15)); return m; } #undef MULT16_16_Q15_ADD static inline int MULT16_16_Q15_ADD(int a, int b, int c, int d) { int m; asm volatile("MULT $ac1, %0, %1" : : "r" ((int)a), "r" ((int)b)); asm volatile("madd $ac1, %0, %1" : : "r" ((int)c), "r" ((int)d)); asm volatile("EXTR.W %0,$ac1, %1" : "=r" (m): "i" (15)); return m; } #undef MULT16_16_Q15_SUB static inline int MULT16_16_Q15_SUB(int a, int b, int c, int d) { int m; asm volatile("MULT $ac1, %0, %1" : : "r" ((int)a), "r" ((int)b)); asm volatile("msub $ac1, %0, %1" : : "r" ((int)c), "r" ((int)d)); asm volatile("EXTR.W %0,$ac1, %1" : "=r" (m): "i" (15)); return m; } #undef MULT16_32_Q16 static inline int MULT16_32_Q16(int a, int b) { int c; asm volatile("MULT $ac1,%0, %1" : : "r" (a), "r" (b)); asm volatile("EXTR.W %0,$ac1, %1" : "=r" (c): "i" (16)); return c; } #undef MULT16_32_P16 static inline int MULT16_32_P16(int a, int b) { int c; asm volatile("MULT $ac1, %0, %1" : : "r" (a), "r" (b)); asm volatile("EXTR_R.W %0,$ac1, %1" : "=r" (c): "i" (16)); return c; } #undef MULT16_32_Q15 static inline int MULT16_32_Q15(int a, int b) { int c; asm volatile("MULT $ac1, %0, %1" : : "r" (a), "r" (b)); asm volatile("EXTR.W %0,$ac1, %1" : "=r" (c): "i" (15)); return c; } #undef MULT32_32_Q31 static inline int MULT32_32_Q31(int a, int b) { int r; asm volatile("MULT $ac1, %0, %1" : : "r" (a), "r" (b)); asm volatile("EXTR.W %0,$ac1, %1" : "=r" (r): "i" (31)); return r; } #undef PSHR32 static inline int PSHR32(int a, int shift) { int r; asm volatile ("SHRAV_R.W %0, %1, %2" :"=r" (r): "r" (a), "r" (shift)); return r; } #undef MULT16_16_P15 static inline int MULT16_16_P15(int a, int b) { int r; asm volatile ("mul %0, %1, %2" :"=r" (r): "r" (a), "r" (b)); asm volatile ("SHRA_R.W %0, %1, %2" : "+r" (r): "0" (r), "i"(15)); return r; } #endif /* CELT_FIXED_GENERIC_MIPSR1_H */
null
null
null
null
24,020
38,647
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
203,642
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
#ifndef LINUX_SLAB_H #define GFP_KERNEL 0 #define GFP_ATOMIC 0 #define __GFP_NOWARN 0 #define __GFP_ZERO 0 #endif
null
null
null
null
111,989
27,042
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
192,037
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
#ifndef _BCACHE_UTIL_H #define _BCACHE_UTIL_H #include <linux/blkdev.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/sched/clock.h> #include <linux/llist.h> #include <linux/ratelimit.h> #include <linux/vmalloc.h> #include <linux/workqueue.h> #include "closure.h" #define PAGE_SECTORS (PAGE_SIZE / 512) struct closure; #ifdef CONFIG_BCACHE_DEBUG #define EBUG_ON(cond) BUG_ON(cond) #define atomic_dec_bug(v) BUG_ON(atomic_dec_return(v) < 0) #define atomic_inc_bug(v, i) BUG_ON(atomic_inc_return(v) <= i) #else /* DEBUG */ #define EBUG_ON(cond) do { if (cond); } while (0) #define atomic_dec_bug(v) atomic_dec(v) #define atomic_inc_bug(v, i) atomic_inc(v) #endif #define DECLARE_HEAP(type, name) \ struct { \ size_t size, used; \ type *data; \ } name #define init_heap(heap, _size, gfp) \ ({ \ size_t _bytes; \ (heap)->used = 0; \ (heap)->size = (_size); \ _bytes = (heap)->size * sizeof(*(heap)->data); \ (heap)->data = NULL; \ if (_bytes < KMALLOC_MAX_SIZE) \ (heap)->data = kmalloc(_bytes, (gfp)); \ if ((!(heap)->data) && ((gfp) & GFP_KERNEL)) \ (heap)->data = vmalloc(_bytes); \ (heap)->data; \ }) #define free_heap(heap) \ do { \ kvfree((heap)->data); \ (heap)->data = NULL; \ } while (0) #define heap_swap(h, i, j) swap((h)->data[i], (h)->data[j]) #define heap_sift(h, i, cmp) \ do { \ size_t _r, _j = i; \ \ for (; _j * 2 + 1 < (h)->used; _j = _r) { \ _r = _j * 2 + 1; \ if (_r + 1 < (h)->used && \ cmp((h)->data[_r], (h)->data[_r + 1])) \ _r++; \ \ if (cmp((h)->data[_r], (h)->data[_j])) \ break; \ heap_swap(h, _r, _j); \ } \ } while (0) #define heap_sift_down(h, i, cmp) \ do { \ while (i) { \ size_t p = (i - 1) / 2; \ if (cmp((h)->data[i], (h)->data[p])) \ break; \ heap_swap(h, i, p); \ i = p; \ } \ } while (0) #define heap_add(h, d, cmp) \ ({ \ bool _r = !heap_full(h); \ if (_r) { \ size_t _i = (h)->used++; \ (h)->data[_i] = d; \ \ heap_sift_down(h, _i, cmp); \ heap_sift(h, _i, cmp); \ } \ _r; \ }) #define heap_pop(h, d, cmp) \ ({ \ bool _r = (h)->used; \ if (_r) { \ (d) = (h)->data[0]; \ (h)->used--; \ heap_swap(h, 0, (h)->used); \ heap_sift(h, 0, cmp); \ } \ _r; \ }) #define heap_peek(h) ((h)->used ? (h)->data[0] : NULL) #define heap_full(h) ((h)->used == (h)->size) #define DECLARE_FIFO(type, name) \ struct { \ size_t front, back, size, mask; \ type *data; \ } name #define fifo_for_each(c, fifo, iter) \ for (iter = (fifo)->front; \ c = (fifo)->data[iter], iter != (fifo)->back; \ iter = (iter + 1) & (fifo)->mask) #define __init_fifo(fifo, gfp) \ ({ \ size_t _allocated_size, _bytes; \ BUG_ON(!(fifo)->size); \ \ _allocated_size = roundup_pow_of_two((fifo)->size + 1); \ _bytes = _allocated_size * sizeof(*(fifo)->data); \ \ (fifo)->mask = _allocated_size - 1; \ (fifo)->front = (fifo)->back = 0; \ (fifo)->data = NULL; \ \ if (_bytes < KMALLOC_MAX_SIZE) \ (fifo)->data = kmalloc(_bytes, (gfp)); \ if ((!(fifo)->data) && ((gfp) & GFP_KERNEL)) \ (fifo)->data = vmalloc(_bytes); \ (fifo)->data; \ }) #define init_fifo_exact(fifo, _size, gfp) \ ({ \ (fifo)->size = (_size); \ __init_fifo(fifo, gfp); \ }) #define init_fifo(fifo, _size, gfp) \ ({ \ (fifo)->size = (_size); \ if ((fifo)->size > 4) \ (fifo)->size = roundup_pow_of_two((fifo)->size) - 1; \ __init_fifo(fifo, gfp); \ }) #define free_fifo(fifo) \ do { \ kvfree((fifo)->data); \ (fifo)->data = NULL; \ } while (0) #define fifo_used(fifo) (((fifo)->back - (fifo)->front) & (fifo)->mask) #define fifo_free(fifo) ((fifo)->size - fifo_used(fifo)) #define fifo_empty(fifo) (!fifo_used(fifo)) #define fifo_full(fifo) (!fifo_free(fifo)) #define fifo_front(fifo) ((fifo)->data[(fifo)->front]) #define fifo_back(fifo) \ ((fifo)->data[((fifo)->back - 1) & (fifo)->mask]) #define fifo_idx(fifo, p) (((p) - &fifo_front(fifo)) & (fifo)->mask) #define fifo_push_back(fifo, i) \ ({ \ bool _r = !fifo_full((fifo)); \ if (_r) { \ (fifo)->data[(fifo)->back++] = (i); \ (fifo)->back &= (fifo)->mask; \ } \ _r; \ }) #define fifo_pop_front(fifo, i) \ ({ \ bool _r = !fifo_empty((fifo)); \ if (_r) { \ (i) = (fifo)->data[(fifo)->front++]; \ (fifo)->front &= (fifo)->mask; \ } \ _r; \ }) #define fifo_push_front(fifo, i) \ ({ \ bool _r = !fifo_full((fifo)); \ if (_r) { \ --(fifo)->front; \ (fifo)->front &= (fifo)->mask; \ (fifo)->data[(fifo)->front] = (i); \ } \ _r; \ }) #define fifo_pop_back(fifo, i) \ ({ \ bool _r = !fifo_empty((fifo)); \ if (_r) { \ --(fifo)->back; \ (fifo)->back &= (fifo)->mask; \ (i) = (fifo)->data[(fifo)->back] \ } \ _r; \ }) #define fifo_push(fifo, i) fifo_push_back(fifo, (i)) #define fifo_pop(fifo, i) fifo_pop_front(fifo, (i)) #define fifo_swap(l, r) \ do { \ swap((l)->front, (r)->front); \ swap((l)->back, (r)->back); \ swap((l)->size, (r)->size); \ swap((l)->mask, (r)->mask); \ swap((l)->data, (r)->data); \ } while (0) #define fifo_move(dest, src) \ do { \ typeof(*((dest)->data)) _t; \ while (!fifo_full(dest) && \ fifo_pop(src, _t)) \ fifo_push(dest, _t); \ } while (0) /* * Simple array based allocator - preallocates a number of elements and you can * never allocate more than that, also has no locking. * * Handy because if you know you only need a fixed number of elements you don't * have to worry about memory allocation failure, and sometimes a mempool isn't * what you want. * * We treat the free elements as entries in a singly linked list, and the * freelist as a stack - allocating and freeing push and pop off the freelist. */ #define DECLARE_ARRAY_ALLOCATOR(type, name, size) \ struct { \ type *freelist; \ type data[size]; \ } name #define array_alloc(array) \ ({ \ typeof((array)->freelist) _ret = (array)->freelist; \ \ if (_ret) \ (array)->freelist = *((typeof((array)->freelist) *) _ret);\ \ _ret; \ }) #define array_free(array, ptr) \ do { \ typeof((array)->freelist) _ptr = ptr; \ \ *((typeof((array)->freelist) *) _ptr) = (array)->freelist; \ (array)->freelist = _ptr; \ } while (0) #define array_allocator_init(array) \ do { \ typeof((array)->freelist) _i; \ \ BUILD_BUG_ON(sizeof((array)->data[0]) < sizeof(void *)); \ (array)->freelist = NULL; \ \ for (_i = (array)->data; \ _i < (array)->data + ARRAY_SIZE((array)->data); \ _i++) \ array_free(array, _i); \ } while (0) #define array_freelist_empty(array) ((array)->freelist == NULL) #define ANYSINT_MAX(t) \ ((((t) 1 << (sizeof(t) * 8 - 2)) - (t) 1) * (t) 2 + (t) 1) int bch_strtoint_h(const char *, int *); int bch_strtouint_h(const char *, unsigned int *); int bch_strtoll_h(const char *, long long *); int bch_strtoull_h(const char *, unsigned long long *); static inline int bch_strtol_h(const char *cp, long *res) { #if BITS_PER_LONG == 32 return bch_strtoint_h(cp, (int *) res); #else return bch_strtoll_h(cp, (long long *) res); #endif } static inline int bch_strtoul_h(const char *cp, long *res) { #if BITS_PER_LONG == 32 return bch_strtouint_h(cp, (unsigned int *) res); #else return bch_strtoull_h(cp, (unsigned long long *) res); #endif } #define strtoi_h(cp, res) \ (__builtin_types_compatible_p(typeof(*res), int) \ ? bch_strtoint_h(cp, (void *) res) \ : __builtin_types_compatible_p(typeof(*res), long) \ ? bch_strtol_h(cp, (void *) res) \ : __builtin_types_compatible_p(typeof(*res), long long) \ ? bch_strtoll_h(cp, (void *) res) \ : __builtin_types_compatible_p(typeof(*res), unsigned int) \ ? bch_strtouint_h(cp, (void *) res) \ : __builtin_types_compatible_p(typeof(*res), unsigned long) \ ? bch_strtoul_h(cp, (void *) res) \ : __builtin_types_compatible_p(typeof(*res), unsigned long long)\ ? bch_strtoull_h(cp, (void *) res) : -EINVAL) #define strtoul_safe(cp, var) \ ({ \ unsigned long _v; \ int _r = kstrtoul(cp, 10, &_v); \ if (!_r) \ var = _v; \ _r; \ }) #define strtoul_safe_clamp(cp, var, min, max) \ ({ \ unsigned long _v; \ int _r = kstrtoul(cp, 10, &_v); \ if (!_r) \ var = clamp_t(typeof(var), _v, min, max); \ _r; \ }) #define snprint(buf, size, var) \ snprintf(buf, size, \ __builtin_types_compatible_p(typeof(var), int) \ ? "%i\n" : \ __builtin_types_compatible_p(typeof(var), unsigned) \ ? "%u\n" : \ __builtin_types_compatible_p(typeof(var), long) \ ? "%li\n" : \ __builtin_types_compatible_p(typeof(var), unsigned long)\ ? "%lu\n" : \ __builtin_types_compatible_p(typeof(var), int64_t) \ ? "%lli\n" : \ __builtin_types_compatible_p(typeof(var), uint64_t) \ ? "%llu\n" : \ __builtin_types_compatible_p(typeof(var), const char *) \ ? "%s\n" : "%i\n", var) ssize_t bch_hprint(char *buf, int64_t v); bool bch_is_zero(const char *p, size_t n); int bch_parse_uuid(const char *s, char *uuid); ssize_t bch_snprint_string_list(char *buf, size_t size, const char * const list[], size_t selected); ssize_t bch_read_string_list(const char *buf, const char * const list[]); struct time_stats { spinlock_t lock; /* * all fields are in nanoseconds, averages are ewmas stored left shifted * by 8 */ uint64_t max_duration; uint64_t average_duration; uint64_t average_frequency; uint64_t last; }; void bch_time_stats_update(struct time_stats *stats, uint64_t time); static inline unsigned local_clock_us(void) { return local_clock() >> 10; } #define NSEC_PER_ns 1L #define NSEC_PER_us NSEC_PER_USEC #define NSEC_PER_ms NSEC_PER_MSEC #define NSEC_PER_sec NSEC_PER_SEC #define __print_time_stat(stats, name, stat, units) \ sysfs_print(name ## _ ## stat ## _ ## units, \ div_u64((stats)->stat >> 8, NSEC_PER_ ## units)) #define sysfs_print_time_stats(stats, name, \ frequency_units, \ duration_units) \ do { \ __print_time_stat(stats, name, \ average_frequency, frequency_units); \ __print_time_stat(stats, name, \ average_duration, duration_units); \ sysfs_print(name ## _ ##max_duration ## _ ## duration_units, \ div_u64((stats)->max_duration, NSEC_PER_ ## duration_units));\ \ sysfs_print(name ## _last_ ## frequency_units, (stats)->last \ ? div_s64(local_clock() - (stats)->last, \ NSEC_PER_ ## frequency_units) \ : -1LL); \ } while (0) #define sysfs_time_stats_attribute(name, \ frequency_units, \ duration_units) \ read_attribute(name ## _average_frequency_ ## frequency_units); \ read_attribute(name ## _average_duration_ ## duration_units); \ read_attribute(name ## _max_duration_ ## duration_units); \ read_attribute(name ## _last_ ## frequency_units) #define sysfs_time_stats_attribute_list(name, \ frequency_units, \ duration_units) \ &sysfs_ ## name ## _average_frequency_ ## frequency_units, \ &sysfs_ ## name ## _average_duration_ ## duration_units, \ &sysfs_ ## name ## _max_duration_ ## duration_units, \ &sysfs_ ## name ## _last_ ## frequency_units, #define ewma_add(ewma, val, weight, factor) \ ({ \ (ewma) *= (weight) - 1; \ (ewma) += (val) << factor; \ (ewma) /= (weight); \ (ewma) >> factor; \ }) struct bch_ratelimit { /* Next time we want to do some work, in nanoseconds */ uint64_t next; /* * Rate at which we want to do work, in units per nanosecond * The units here correspond to the units passed to bch_next_delay() */ unsigned rate; }; static inline void bch_ratelimit_reset(struct bch_ratelimit *d) { d->next = local_clock(); } uint64_t bch_next_delay(struct bch_ratelimit *d, uint64_t done); #define __DIV_SAFE(n, d, zero) \ ({ \ typeof(n) _n = (n); \ typeof(d) _d = (d); \ _d ? _n / _d : zero; \ }) #define DIV_SAFE(n, d) __DIV_SAFE(n, d, 0) #define container_of_or_null(ptr, type, member) \ ({ \ typeof(ptr) _ptr = ptr; \ _ptr ? container_of(_ptr, type, member) : NULL; \ }) #define RB_INSERT(root, new, member, cmp) \ ({ \ __label__ dup; \ struct rb_node **n = &(root)->rb_node, *parent = NULL; \ typeof(new) this; \ int res, ret = -1; \ \ while (*n) { \ parent = *n; \ this = container_of(*n, typeof(*(new)), member); \ res = cmp(new, this); \ if (!res) \ goto dup; \ n = res < 0 \ ? &(*n)->rb_left \ : &(*n)->rb_right; \ } \ \ rb_link_node(&(new)->member, parent, n); \ rb_insert_color(&(new)->member, root); \ ret = 0; \ dup: \ ret; \ }) #define RB_SEARCH(root, search, member, cmp) \ ({ \ struct rb_node *n = (root)->rb_node; \ typeof(&(search)) this, ret = NULL; \ int res; \ \ while (n) { \ this = container_of(n, typeof(search), member); \ res = cmp(&(search), this); \ if (!res) { \ ret = this; \ break; \ } \ n = res < 0 \ ? n->rb_left \ : n->rb_right; \ } \ ret; \ }) #define RB_GREATER(root, search, member, cmp) \ ({ \ struct rb_node *n = (root)->rb_node; \ typeof(&(search)) this, ret = NULL; \ int res; \ \ while (n) { \ this = container_of(n, typeof(search), member); \ res = cmp(&(search), this); \ if (res < 0) { \ ret = this; \ n = n->rb_left; \ } else \ n = n->rb_right; \ } \ ret; \ }) #define RB_FIRST(root, type, member) \ container_of_or_null(rb_first(root), type, member) #define RB_LAST(root, type, member) \ container_of_or_null(rb_last(root), type, member) #define RB_NEXT(ptr, member) \ container_of_or_null(rb_next(&(ptr)->member), typeof(*ptr), member) #define RB_PREV(ptr, member) \ container_of_or_null(rb_prev(&(ptr)->member), typeof(*ptr), member) /* Does linear interpolation between powers of two */ static inline unsigned fract_exp_two(unsigned x, unsigned fract_bits) { unsigned fract = x & ~(~0 << fract_bits); x >>= fract_bits; x = 1 << x; x += (x * fract) >> fract_bits; return x; } void bch_bio_map(struct bio *bio, void *base); static inline sector_t bdev_sectors(struct block_device *bdev) { return bdev->bd_inode->i_size >> 9; } #define closure_bio_submit(bio, cl) \ do { \ closure_get(cl); \ generic_make_request(bio); \ } while (0) uint64_t bch_crc64_update(uint64_t, const void *, size_t); uint64_t bch_crc64(const void *, size_t); #endif /* _BCACHE_UTIL_H */
null
null
null
null
100,384
36,469
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
201,464
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Roccat Kone driver for Linux * * Copyright (c) 2010 Stefan Achatz <erazor_de@users.sourceforge.net> */ /* * 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. */ /* * Roccat Kone is a gamer mouse which consists of a mouse part and a keyboard * part. The keyboard part enables the mouse to execute stored macros with mixed * key- and button-events. * * TODO implement on-the-fly polling-rate change * The windows driver has the ability to change the polling rate of the * device on the press of a mousebutton. * Is it possible to remove and reinstall the urb in raw-event- or any * other handler, or to defer this action to be executed somewhere else? * * TODO is it possible to overwrite group for sysfs attributes via udev? */ #include <linux/device.h> #include <linux/input.h> #include <linux/hid.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/hid-roccat.h> #include "hid-ids.h" #include "hid-roccat-common.h" #include "hid-roccat-kone.h" static uint profile_numbers[5] = {0, 1, 2, 3, 4}; static void kone_profile_activated(struct kone_device *kone, uint new_profile) { kone->actual_profile = new_profile; kone->actual_dpi = kone->profiles[new_profile - 1].startup_dpi; } static void kone_profile_report(struct kone_device *kone, uint new_profile) { struct kone_roccat_report roccat_report; roccat_report.event = kone_mouse_event_switch_profile; roccat_report.value = new_profile; roccat_report.key = 0; roccat_report_event(kone->chrdev_minor, (uint8_t *)&roccat_report); } static int kone_receive(struct usb_device *usb_dev, uint usb_command, void *data, uint size) { char *buf; int len; buf = kmalloc(size, GFP_KERNEL); if (buf == NULL) return -ENOMEM; len = usb_control_msg(usb_dev, usb_rcvctrlpipe(usb_dev, 0), HID_REQ_GET_REPORT, USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_IN, usb_command, 0, buf, size, USB_CTRL_SET_TIMEOUT); memcpy(data, buf, size); kfree(buf); return ((len < 0) ? len : ((len != size) ? -EIO : 0)); } static int kone_send(struct usb_device *usb_dev, uint usb_command, void const *data, uint size) { char *buf; int len; buf = kmemdup(data, size, GFP_KERNEL); if (buf == NULL) return -ENOMEM; len = usb_control_msg(usb_dev, usb_sndctrlpipe(usb_dev, 0), HID_REQ_SET_REPORT, USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_OUT, usb_command, 0, buf, size, USB_CTRL_SET_TIMEOUT); kfree(buf); return ((len < 0) ? len : ((len != size) ? -EIO : 0)); } /* kone_class is used for creating sysfs attributes via roccat char device */ static struct class *kone_class; static void kone_set_settings_checksum(struct kone_settings *settings) { uint16_t checksum = 0; unsigned char *address = (unsigned char *)settings; int i; for (i = 0; i < sizeof(struct kone_settings) - 2; ++i, ++address) checksum += *address; settings->checksum = cpu_to_le16(checksum); } /* * Checks success after writing data to mouse * On success returns 0 * On failure returns errno */ static int kone_check_write(struct usb_device *usb_dev) { int retval; uint8_t data; do { /* * Mouse needs 50 msecs until it says ok, but there are * 30 more msecs needed for next write to work. */ msleep(80); retval = kone_receive(usb_dev, kone_command_confirm_write, &data, 1); if (retval) return retval; /* * value of 3 seems to mean something like * "not finished yet, but it looks good" * So check again after a moment. */ } while (data == 3); if (data == 1) /* everything alright */ return 0; /* unknown answer */ dev_err(&usb_dev->dev, "got retval %d when checking write\n", data); return -EIO; } /* * Reads settings from mouse and stores it in @buf * On success returns 0 * On failure returns errno */ static int kone_get_settings(struct usb_device *usb_dev, struct kone_settings *buf) { return kone_receive(usb_dev, kone_command_settings, buf, sizeof(struct kone_settings)); } /* * Writes settings from @buf to mouse * On success returns 0 * On failure returns errno */ static int kone_set_settings(struct usb_device *usb_dev, struct kone_settings const *settings) { int retval; retval = kone_send(usb_dev, kone_command_settings, settings, sizeof(struct kone_settings)); if (retval) return retval; return kone_check_write(usb_dev); } /* * Reads profile data from mouse and stores it in @buf * @number: profile number to read * On success returns 0 * On failure returns errno */ static int kone_get_profile(struct usb_device *usb_dev, struct kone_profile *buf, int number) { int len; if (number < 1 || number > 5) return -EINVAL; len = usb_control_msg(usb_dev, usb_rcvctrlpipe(usb_dev, 0), USB_REQ_CLEAR_FEATURE, USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_IN, kone_command_profile, number, buf, sizeof(struct kone_profile), USB_CTRL_SET_TIMEOUT); if (len != sizeof(struct kone_profile)) return -EIO; return 0; } /* * Writes profile data to mouse. * @number: profile number to write * On success returns 0 * On failure returns errno */ static int kone_set_profile(struct usb_device *usb_dev, struct kone_profile const *profile, int number) { int len; if (number < 1 || number > 5) return -EINVAL; len = usb_control_msg(usb_dev, usb_sndctrlpipe(usb_dev, 0), USB_REQ_SET_CONFIGURATION, USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_OUT, kone_command_profile, number, (void *)profile, sizeof(struct kone_profile), USB_CTRL_SET_TIMEOUT); if (len != sizeof(struct kone_profile)) return len; if (kone_check_write(usb_dev)) return -EIO; return 0; } /* * Reads value of "fast-clip-weight" and stores it in @result * On success returns 0 * On failure returns errno */ static int kone_get_weight(struct usb_device *usb_dev, int *result) { int retval; uint8_t data; retval = kone_receive(usb_dev, kone_command_weight, &data, 1); if (retval) return retval; *result = (int)data; return 0; } /* * Reads firmware_version of mouse and stores it in @result * On success returns 0 * On failure returns errno */ static int kone_get_firmware_version(struct usb_device *usb_dev, int *result) { int retval; uint16_t data; retval = kone_receive(usb_dev, kone_command_firmware_version, &data, 2); if (retval) return retval; *result = le16_to_cpu(data); return 0; } static ssize_t kone_sysfs_read_settings(struct file *fp, struct kobject *kobj, struct bin_attribute *attr, char *buf, loff_t off, size_t count) { struct device *dev = kobj_to_dev(kobj)->parent->parent; struct kone_device *kone = hid_get_drvdata(dev_get_drvdata(dev)); if (off >= sizeof(struct kone_settings)) return 0; if (off + count > sizeof(struct kone_settings)) count = sizeof(struct kone_settings) - off; mutex_lock(&kone->kone_lock); memcpy(buf, ((char const *)&kone->settings) + off, count); mutex_unlock(&kone->kone_lock); return count; } /* * Writing settings automatically activates startup_profile. * This function keeps values in kone_device up to date and assumes that in * case of error the old data is still valid */ static ssize_t kone_sysfs_write_settings(struct file *fp, struct kobject *kobj, struct bin_attribute *attr, char *buf, loff_t off, size_t count) { struct device *dev = kobj_to_dev(kobj)->parent->parent; struct kone_device *kone = hid_get_drvdata(dev_get_drvdata(dev)); struct usb_device *usb_dev = interface_to_usbdev(to_usb_interface(dev)); int retval = 0, difference, old_profile; /* I need to get my data in one piece */ if (off != 0 || count != sizeof(struct kone_settings)) return -EINVAL; mutex_lock(&kone->kone_lock); difference = memcmp(buf, &kone->settings, sizeof(struct kone_settings)); if (difference) { retval = kone_set_settings(usb_dev, (struct kone_settings const *)buf); if (retval) { mutex_unlock(&kone->kone_lock); return retval; } old_profile = kone->settings.startup_profile; memcpy(&kone->settings, buf, sizeof(struct kone_settings)); kone_profile_activated(kone, kone->settings.startup_profile); if (kone->settings.startup_profile != old_profile) kone_profile_report(kone, kone->settings.startup_profile); } mutex_unlock(&kone->kone_lock); return sizeof(struct kone_settings); } static BIN_ATTR(settings, 0660, kone_sysfs_read_settings, kone_sysfs_write_settings, sizeof(struct kone_settings)); static ssize_t kone_sysfs_read_profilex(struct file *fp, struct kobject *kobj, struct bin_attribute *attr, char *buf, loff_t off, size_t count) { struct device *dev = kobj_to_dev(kobj)->parent->parent; struct kone_device *kone = hid_get_drvdata(dev_get_drvdata(dev)); if (off >= sizeof(struct kone_profile)) return 0; if (off + count > sizeof(struct kone_profile)) count = sizeof(struct kone_profile) - off; mutex_lock(&kone->kone_lock); memcpy(buf, ((char const *)&kone->profiles[*(uint *)(attr->private)]) + off, count); mutex_unlock(&kone->kone_lock); return count; } /* Writes data only if different to stored data */ static ssize_t kone_sysfs_write_profilex(struct file *fp, struct kobject *kobj, struct bin_attribute *attr, char *buf, loff_t off, size_t count) { struct device *dev = kobj_to_dev(kobj)->parent->parent; struct kone_device *kone = hid_get_drvdata(dev_get_drvdata(dev)); struct usb_device *usb_dev = interface_to_usbdev(to_usb_interface(dev)); struct kone_profile *profile; int retval = 0, difference; /* I need to get my data in one piece */ if (off != 0 || count != sizeof(struct kone_profile)) return -EINVAL; profile = &kone->profiles[*(uint *)(attr->private)]; mutex_lock(&kone->kone_lock); difference = memcmp(buf, profile, sizeof(struct kone_profile)); if (difference) { retval = kone_set_profile(usb_dev, (struct kone_profile const *)buf, *(uint *)(attr->private) + 1); if (!retval) memcpy(profile, buf, sizeof(struct kone_profile)); } mutex_unlock(&kone->kone_lock); if (retval) return retval; return sizeof(struct kone_profile); } #define PROFILE_ATTR(number) \ static struct bin_attribute bin_attr_profile##number = { \ .attr = { .name = "profile" #number, .mode = 0660 }, \ .size = sizeof(struct kone_profile), \ .read = kone_sysfs_read_profilex, \ .write = kone_sysfs_write_profilex, \ .private = &profile_numbers[number-1], \ } PROFILE_ATTR(1); PROFILE_ATTR(2); PROFILE_ATTR(3); PROFILE_ATTR(4); PROFILE_ATTR(5); static ssize_t kone_sysfs_show_actual_profile(struct device *dev, struct device_attribute *attr, char *buf) { struct kone_device *kone = hid_get_drvdata(dev_get_drvdata(dev->parent->parent)); return snprintf(buf, PAGE_SIZE, "%d\n", kone->actual_profile); } static DEVICE_ATTR(actual_profile, 0440, kone_sysfs_show_actual_profile, NULL); static ssize_t kone_sysfs_show_actual_dpi(struct device *dev, struct device_attribute *attr, char *buf) { struct kone_device *kone = hid_get_drvdata(dev_get_drvdata(dev->parent->parent)); return snprintf(buf, PAGE_SIZE, "%d\n", kone->actual_dpi); } static DEVICE_ATTR(actual_dpi, 0440, kone_sysfs_show_actual_dpi, NULL); /* weight is read each time, since we don't get informed when it's changed */ static ssize_t kone_sysfs_show_weight(struct device *dev, struct device_attribute *attr, char *buf) { struct kone_device *kone; struct usb_device *usb_dev; int weight = 0; int retval; dev = dev->parent->parent; kone = hid_get_drvdata(dev_get_drvdata(dev)); usb_dev = interface_to_usbdev(to_usb_interface(dev)); mutex_lock(&kone->kone_lock); retval = kone_get_weight(usb_dev, &weight); mutex_unlock(&kone->kone_lock); if (retval) return retval; return snprintf(buf, PAGE_SIZE, "%d\n", weight); } static DEVICE_ATTR(weight, 0440, kone_sysfs_show_weight, NULL); static ssize_t kone_sysfs_show_firmware_version(struct device *dev, struct device_attribute *attr, char *buf) { struct kone_device *kone = hid_get_drvdata(dev_get_drvdata(dev->parent->parent)); return snprintf(buf, PAGE_SIZE, "%d\n", kone->firmware_version); } static DEVICE_ATTR(firmware_version, 0440, kone_sysfs_show_firmware_version, NULL); static ssize_t kone_sysfs_show_tcu(struct device *dev, struct device_attribute *attr, char *buf) { struct kone_device *kone = hid_get_drvdata(dev_get_drvdata(dev->parent->parent)); return snprintf(buf, PAGE_SIZE, "%d\n", kone->settings.tcu); } static int kone_tcu_command(struct usb_device *usb_dev, int number) { unsigned char value; value = number; return kone_send(usb_dev, kone_command_calibrate, &value, 1); } /* * Calibrating the tcu is the only action that changes settings data inside the * mouse, so this data needs to be reread */ static ssize_t kone_sysfs_set_tcu(struct device *dev, struct device_attribute *attr, char const *buf, size_t size) { struct kone_device *kone; struct usb_device *usb_dev; int retval; unsigned long state; dev = dev->parent->parent; kone = hid_get_drvdata(dev_get_drvdata(dev)); usb_dev = interface_to_usbdev(to_usb_interface(dev)); retval = kstrtoul(buf, 10, &state); if (retval) return retval; if (state != 0 && state != 1) return -EINVAL; mutex_lock(&kone->kone_lock); if (state == 1) { /* state activate */ retval = kone_tcu_command(usb_dev, 1); if (retval) goto exit_unlock; retval = kone_tcu_command(usb_dev, 2); if (retval) goto exit_unlock; ssleep(5); /* tcu needs this time for calibration */ retval = kone_tcu_command(usb_dev, 3); if (retval) goto exit_unlock; retval = kone_tcu_command(usb_dev, 0); if (retval) goto exit_unlock; retval = kone_tcu_command(usb_dev, 4); if (retval) goto exit_unlock; /* * Kone needs this time to settle things. * Reading settings too early will result in invalid data. * Roccat's driver waits 1 sec, maybe this time could be * shortened. */ ssleep(1); } /* calibration changes values in settings, so reread */ retval = kone_get_settings(usb_dev, &kone->settings); if (retval) goto exit_no_settings; /* only write settings back if activation state is different */ if (kone->settings.tcu != state) { kone->settings.tcu = state; kone_set_settings_checksum(&kone->settings); retval = kone_set_settings(usb_dev, &kone->settings); if (retval) { dev_err(&usb_dev->dev, "couldn't set tcu state\n"); /* * try to reread valid settings into buffer overwriting * first error code */ retval = kone_get_settings(usb_dev, &kone->settings); if (retval) goto exit_no_settings; goto exit_unlock; } /* calibration resets profile */ kone_profile_activated(kone, kone->settings.startup_profile); } retval = size; exit_no_settings: dev_err(&usb_dev->dev, "couldn't read settings\n"); exit_unlock: mutex_unlock(&kone->kone_lock); return retval; } static DEVICE_ATTR(tcu, 0660, kone_sysfs_show_tcu, kone_sysfs_set_tcu); static ssize_t kone_sysfs_show_startup_profile(struct device *dev, struct device_attribute *attr, char *buf) { struct kone_device *kone = hid_get_drvdata(dev_get_drvdata(dev->parent->parent)); return snprintf(buf, PAGE_SIZE, "%d\n", kone->settings.startup_profile); } static ssize_t kone_sysfs_set_startup_profile(struct device *dev, struct device_attribute *attr, char const *buf, size_t size) { struct kone_device *kone; struct usb_device *usb_dev; int retval; unsigned long new_startup_profile; dev = dev->parent->parent; kone = hid_get_drvdata(dev_get_drvdata(dev)); usb_dev = interface_to_usbdev(to_usb_interface(dev)); retval = kstrtoul(buf, 10, &new_startup_profile); if (retval) return retval; if (new_startup_profile < 1 || new_startup_profile > 5) return -EINVAL; mutex_lock(&kone->kone_lock); kone->settings.startup_profile = new_startup_profile; kone_set_settings_checksum(&kone->settings); retval = kone_set_settings(usb_dev, &kone->settings); if (retval) { mutex_unlock(&kone->kone_lock); return retval; } /* changing the startup profile immediately activates this profile */ kone_profile_activated(kone, new_startup_profile); kone_profile_report(kone, new_startup_profile); mutex_unlock(&kone->kone_lock); return size; } static DEVICE_ATTR(startup_profile, 0660, kone_sysfs_show_startup_profile, kone_sysfs_set_startup_profile); static struct attribute *kone_attrs[] = { /* * Read actual dpi settings. * Returns raw value for further processing. Refer to enum * kone_polling_rates to get real value. */ &dev_attr_actual_dpi.attr, &dev_attr_actual_profile.attr, /* * The mouse can be equipped with one of four supplied weights from 5 * to 20 grams which are recognized and its value can be read out. * This returns the raw value reported by the mouse for easy evaluation * by software. Refer to enum kone_weights to get corresponding real * weight. */ &dev_attr_weight.attr, /* * Prints firmware version stored in mouse as integer. * The raw value reported by the mouse is returned for easy evaluation, * to get the real version number the decimal point has to be shifted 2 * positions to the left. E.g. a value of 138 means 1.38. */ &dev_attr_firmware_version.attr, /* * Prints state of Tracking Control Unit as number where 0 = off and * 1 = on. Writing 0 deactivates tcu and writing 1 calibrates and * activates the tcu */ &dev_attr_tcu.attr, /* Prints and takes the number of the profile the mouse starts with */ &dev_attr_startup_profile.attr, NULL, }; static struct bin_attribute *kone_bin_attributes[] = { &bin_attr_settings, &bin_attr_profile1, &bin_attr_profile2, &bin_attr_profile3, &bin_attr_profile4, &bin_attr_profile5, NULL, }; static const struct attribute_group kone_group = { .attrs = kone_attrs, .bin_attrs = kone_bin_attributes, }; static const struct attribute_group *kone_groups[] = { &kone_group, NULL, }; static int kone_init_kone_device_struct(struct usb_device *usb_dev, struct kone_device *kone) { uint i; int retval; mutex_init(&kone->kone_lock); for (i = 0; i < 5; ++i) { retval = kone_get_profile(usb_dev, &kone->profiles[i], i + 1); if (retval) return retval; } retval = kone_get_settings(usb_dev, &kone->settings); if (retval) return retval; retval = kone_get_firmware_version(usb_dev, &kone->firmware_version); if (retval) return retval; kone_profile_activated(kone, kone->settings.startup_profile); return 0; } /* * Since IGNORE_MOUSE quirk moved to hid-apple, there is no way to bind only to * mousepart if usb_hid is compiled into the kernel and kone is compiled as * module. * Secial behaviour is bound only to mousepart since only mouseevents contain * additional notifications. */ static int kone_init_specials(struct hid_device *hdev) { struct usb_interface *intf = to_usb_interface(hdev->dev.parent); struct usb_device *usb_dev = interface_to_usbdev(intf); struct kone_device *kone; int retval; if (intf->cur_altsetting->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_MOUSE) { kone = kzalloc(sizeof(*kone), GFP_KERNEL); if (!kone) return -ENOMEM; hid_set_drvdata(hdev, kone); retval = kone_init_kone_device_struct(usb_dev, kone); if (retval) { hid_err(hdev, "couldn't init struct kone_device\n"); goto exit_free; } retval = roccat_connect(kone_class, hdev, sizeof(struct kone_roccat_report)); if (retval < 0) { hid_err(hdev, "couldn't init char dev\n"); /* be tolerant about not getting chrdev */ } else { kone->roccat_claimed = 1; kone->chrdev_minor = retval; } } else { hid_set_drvdata(hdev, NULL); } return 0; exit_free: kfree(kone); return retval; } static void kone_remove_specials(struct hid_device *hdev) { struct usb_interface *intf = to_usb_interface(hdev->dev.parent); struct kone_device *kone; if (intf->cur_altsetting->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_MOUSE) { kone = hid_get_drvdata(hdev); if (kone->roccat_claimed) roccat_disconnect(kone->chrdev_minor); kfree(hid_get_drvdata(hdev)); } } static int kone_probe(struct hid_device *hdev, const struct hid_device_id *id) { int retval; retval = hid_parse(hdev); if (retval) { hid_err(hdev, "parse failed\n"); goto exit; } retval = hid_hw_start(hdev, HID_CONNECT_DEFAULT); if (retval) { hid_err(hdev, "hw start failed\n"); goto exit; } retval = kone_init_specials(hdev); if (retval) { hid_err(hdev, "couldn't install mouse\n"); goto exit_stop; } return 0; exit_stop: hid_hw_stop(hdev); exit: return retval; } static void kone_remove(struct hid_device *hdev) { kone_remove_specials(hdev); hid_hw_stop(hdev); } /* handle special events and keep actual profile and dpi values up to date */ static void kone_keep_values_up_to_date(struct kone_device *kone, struct kone_mouse_event const *event) { switch (event->event) { case kone_mouse_event_switch_profile: kone->actual_dpi = kone->profiles[event->value - 1]. startup_dpi; case kone_mouse_event_osd_profile: kone->actual_profile = event->value; break; case kone_mouse_event_switch_dpi: case kone_mouse_event_osd_dpi: kone->actual_dpi = event->value; break; } } static void kone_report_to_chrdev(struct kone_device const *kone, struct kone_mouse_event const *event) { struct kone_roccat_report roccat_report; switch (event->event) { case kone_mouse_event_switch_profile: case kone_mouse_event_switch_dpi: case kone_mouse_event_osd_profile: case kone_mouse_event_osd_dpi: roccat_report.event = event->event; roccat_report.value = event->value; roccat_report.key = 0; roccat_report_event(kone->chrdev_minor, (uint8_t *)&roccat_report); break; case kone_mouse_event_call_overlong_macro: case kone_mouse_event_multimedia: if (event->value == kone_keystroke_action_press) { roccat_report.event = event->event; roccat_report.value = kone->actual_profile; roccat_report.key = event->macro_key; roccat_report_event(kone->chrdev_minor, (uint8_t *)&roccat_report); } break; } } /* * Is called for keyboard- and mousepart. * Only mousepart gets informations about special events in its extended event * structure. */ static int kone_raw_event(struct hid_device *hdev, struct hid_report *report, u8 *data, int size) { struct kone_device *kone = hid_get_drvdata(hdev); struct kone_mouse_event *event = (struct kone_mouse_event *)data; /* keyboard events are always processed by default handler */ if (size != sizeof(struct kone_mouse_event)) return 0; if (kone == NULL) return 0; /* * Firmware 1.38 introduced new behaviour for tilt and special buttons. * Pressed button is reported in each movement event. * Workaround sends only one event per press. */ if (memcmp(&kone->last_mouse_event.tilt, &event->tilt, 5)) memcpy(&kone->last_mouse_event, event, sizeof(struct kone_mouse_event)); else memset(&event->tilt, 0, 5); kone_keep_values_up_to_date(kone, event); if (kone->roccat_claimed) kone_report_to_chrdev(kone, event); return 0; /* always do further processing */ } static const struct hid_device_id kone_devices[] = { { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_KONE) }, { } }; MODULE_DEVICE_TABLE(hid, kone_devices); static struct hid_driver kone_driver = { .name = "kone", .id_table = kone_devices, .probe = kone_probe, .remove = kone_remove, .raw_event = kone_raw_event }; static int __init kone_init(void) { int retval; /* class name has to be same as driver name */ kone_class = class_create(THIS_MODULE, "kone"); if (IS_ERR(kone_class)) return PTR_ERR(kone_class); kone_class->dev_groups = kone_groups; retval = hid_register_driver(&kone_driver); if (retval) class_destroy(kone_class); return retval; } static void __exit kone_exit(void) { hid_unregister_driver(&kone_driver); class_destroy(kone_class); } module_init(kone_init); module_exit(kone_exit); MODULE_AUTHOR("Stefan Achatz"); MODULE_DESCRIPTION("USB Roccat Kone driver"); MODULE_LICENSE("GPL v2");
null
null
null
null
109,811
2,285
null
train_val
1b0d3845b454eaaac0b2064c78926ca4d739a080
264,853
qemu
0
https://github.com/bonzini/qemu
2016-10-18 11:40:27+01:00
/* * Copyright (c) 2006-2008 Openedhand Ltd. * Written by Andrzej Zaborowski <balrog@zabor.org> * * 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) version 3 of the License. * * 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/>. */ #include "qemu/osdep.h" #include "hw/hw.h" #include "hw/arm/sharpsl.h" #include "hw/sysbus.h" #undef REG_FMT #define REG_FMT "0x%02lx" /* SCOOP devices */ #define TYPE_SCOOP "scoop" #define SCOOP(obj) OBJECT_CHECK(ScoopInfo, (obj), TYPE_SCOOP) typedef struct ScoopInfo ScoopInfo; struct ScoopInfo { SysBusDevice parent_obj; qemu_irq handler[16]; MemoryRegion iomem; uint16_t status; uint16_t power; uint32_t gpio_level; uint32_t gpio_dir; uint32_t prev_level; uint16_t mcr; uint16_t cdr; uint16_t ccr; uint16_t irr; uint16_t imr; uint16_t isr; }; #define SCOOP_MCR 0x00 #define SCOOP_CDR 0x04 #define SCOOP_CSR 0x08 #define SCOOP_CPR 0x0c #define SCOOP_CCR 0x10 #define SCOOP_IRR_IRM 0x14 #define SCOOP_IMR 0x18 #define SCOOP_ISR 0x1c #define SCOOP_GPCR 0x20 #define SCOOP_GPWR 0x24 #define SCOOP_GPRR 0x28 static inline void scoop_gpio_handler_update(ScoopInfo *s) { uint32_t level, diff; int bit; level = s->gpio_level & s->gpio_dir; for (diff = s->prev_level ^ level; diff; diff ^= 1 << bit) { bit = ctz32(diff); qemu_set_irq(s->handler[bit], (level >> bit) & 1); } s->prev_level = level; } static uint64_t scoop_read(void *opaque, hwaddr addr, unsigned size) { ScoopInfo *s = (ScoopInfo *) opaque; switch (addr & 0x3f) { case SCOOP_MCR: return s->mcr; case SCOOP_CDR: return s->cdr; case SCOOP_CSR: return s->status; case SCOOP_CPR: return s->power; case SCOOP_CCR: return s->ccr; case SCOOP_IRR_IRM: return s->irr; case SCOOP_IMR: return s->imr; case SCOOP_ISR: return s->isr; case SCOOP_GPCR: return s->gpio_dir; case SCOOP_GPWR: case SCOOP_GPRR: return s->gpio_level; default: zaurus_printf("Bad register offset " REG_FMT "\n", (unsigned long)addr); } return 0; } static void scoop_write(void *opaque, hwaddr addr, uint64_t value, unsigned size) { ScoopInfo *s = (ScoopInfo *) opaque; value &= 0xffff; switch (addr & 0x3f) { case SCOOP_MCR: s->mcr = value; break; case SCOOP_CDR: s->cdr = value; break; case SCOOP_CPR: s->power = value; if (value & 0x80) s->power |= 0x8040; break; case SCOOP_CCR: s->ccr = value; break; case SCOOP_IRR_IRM: s->irr = value; break; case SCOOP_IMR: s->imr = value; break; case SCOOP_ISR: s->isr = value; break; case SCOOP_GPCR: s->gpio_dir = value; scoop_gpio_handler_update(s); break; case SCOOP_GPWR: case SCOOP_GPRR: /* GPRR is probably R/O in real HW */ s->gpio_level = value & s->gpio_dir; scoop_gpio_handler_update(s); break; default: zaurus_printf("Bad register offset " REG_FMT "\n", (unsigned long)addr); } } static const MemoryRegionOps scoop_ops = { .read = scoop_read, .write = scoop_write, .endianness = DEVICE_NATIVE_ENDIAN, }; static void scoop_gpio_set(void *opaque, int line, int level) { ScoopInfo *s = (ScoopInfo *) opaque; if (level) s->gpio_level |= (1 << line); else s->gpio_level &= ~(1 << line); } static void scoop_init(Object *obj) { DeviceState *dev = DEVICE(obj); ScoopInfo *s = SCOOP(obj); SysBusDevice *sbd = SYS_BUS_DEVICE(obj); s->status = 0x02; qdev_init_gpio_out(dev, s->handler, 16); qdev_init_gpio_in(dev, scoop_gpio_set, 16); memory_region_init_io(&s->iomem, obj, &scoop_ops, s, "scoop", 0x1000); sysbus_init_mmio(sbd, &s->iomem); } static int scoop_post_load(void *opaque, int version_id) { ScoopInfo *s = (ScoopInfo *) opaque; int i; uint32_t level; level = s->gpio_level & s->gpio_dir; for (i = 0; i < 16; i++) { qemu_set_irq(s->handler[i], (level >> i) & 1); } s->prev_level = level; return 0; } static bool is_version_0 (void *opaque, int version_id) { return version_id == 0; } static bool vmstate_scoop_validate(void *opaque, int version_id) { ScoopInfo *s = opaque; return !(s->prev_level & 0xffff0000) && !(s->gpio_level & 0xffff0000) && !(s->gpio_dir & 0xffff0000); } static const VMStateDescription vmstate_scoop_regs = { .name = "scoop", .version_id = 1, .minimum_version_id = 0, .post_load = scoop_post_load, .fields = (VMStateField[]) { VMSTATE_UINT16(status, ScoopInfo), VMSTATE_UINT16(power, ScoopInfo), VMSTATE_UINT32(gpio_level, ScoopInfo), VMSTATE_UINT32(gpio_dir, ScoopInfo), VMSTATE_UINT32(prev_level, ScoopInfo), VMSTATE_VALIDATE("irq levels are 16 bit", vmstate_scoop_validate), VMSTATE_UINT16(mcr, ScoopInfo), VMSTATE_UINT16(cdr, ScoopInfo), VMSTATE_UINT16(ccr, ScoopInfo), VMSTATE_UINT16(irr, ScoopInfo), VMSTATE_UINT16(imr, ScoopInfo), VMSTATE_UINT16(isr, ScoopInfo), VMSTATE_UNUSED_TEST(is_version_0, 2), VMSTATE_END_OF_LIST(), }, }; static void scoop_sysbus_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); dc->desc = "Scoop2 Sharp custom ASIC"; dc->vmsd = &vmstate_scoop_regs; } static const TypeInfo scoop_sysbus_info = { .name = TYPE_SCOOP, .parent = TYPE_SYS_BUS_DEVICE, .instance_size = sizeof(ScoopInfo), .instance_init = scoop_init, .class_init = scoop_sysbus_class_init, }; static void scoop_register_types(void) { type_register_static(&scoop_sysbus_info); } type_init(scoop_register_types) /* Write the bootloader parameters memory area. */ #define MAGIC_CHG(a, b, c, d) ((d << 24) | (c << 16) | (b << 8) | a) static struct QEMU_PACKED sl_param_info { uint32_t comadj_keyword; int32_t comadj; uint32_t uuid_keyword; char uuid[16]; uint32_t touch_keyword; int32_t touch_xp; int32_t touch_yp; int32_t touch_xd; int32_t touch_yd; uint32_t adadj_keyword; int32_t adadj; uint32_t phad_keyword; int32_t phadadj; } zaurus_bootparam = { .comadj_keyword = MAGIC_CHG('C', 'M', 'A', 'D'), .comadj = 125, .uuid_keyword = MAGIC_CHG('U', 'U', 'I', 'D'), .uuid = { -1 }, .touch_keyword = MAGIC_CHG('T', 'U', 'C', 'H'), .touch_xp = -1, .adadj_keyword = MAGIC_CHG('B', 'V', 'A', 'D'), .adadj = -1, .phad_keyword = MAGIC_CHG('P', 'H', 'A', 'D'), .phadadj = 0x01, }; void sl_bootparam_write(hwaddr ptr) { cpu_physical_memory_write(ptr, &zaurus_bootparam, sizeof(struct sl_param_info)); }
null
null
null
null
122,977
39,629
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
204,624
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Generic entry point for the idle threads */ #include <linux/sched.h> #include <linux/sched/idle.h> #include <linux/cpu.h> #include <linux/cpuidle.h> #include <linux/cpuhotplug.h> #include <linux/tick.h> #include <linux/mm.h> #include <linux/stackprotector.h> #include <linux/suspend.h> #include <asm/tlb.h> #include <trace/events/power.h> #include "sched.h" /* Linker adds these: start and end of __cpuidle functions */ extern char __cpuidle_text_start[], __cpuidle_text_end[]; /** * sched_idle_set_state - Record idle state for the current CPU. * @idle_state: State to record. */ void sched_idle_set_state(struct cpuidle_state *idle_state) { idle_set_state(this_rq(), idle_state); } static int __read_mostly cpu_idle_force_poll; void cpu_idle_poll_ctrl(bool enable) { if (enable) { cpu_idle_force_poll++; } else { cpu_idle_force_poll--; WARN_ON_ONCE(cpu_idle_force_poll < 0); } } #ifdef CONFIG_GENERIC_IDLE_POLL_SETUP static int __init cpu_idle_poll_setup(char *__unused) { cpu_idle_force_poll = 1; return 1; } __setup("nohlt", cpu_idle_poll_setup); static int __init cpu_idle_nopoll_setup(char *__unused) { cpu_idle_force_poll = 0; return 1; } __setup("hlt", cpu_idle_nopoll_setup); #endif static noinline int __cpuidle cpu_idle_poll(void) { rcu_idle_enter(); trace_cpu_idle_rcuidle(0, smp_processor_id()); local_irq_enable(); stop_critical_timings(); while (!tif_need_resched() && (cpu_idle_force_poll || tick_check_broadcast_expired())) cpu_relax(); start_critical_timings(); trace_cpu_idle_rcuidle(PWR_EVENT_EXIT, smp_processor_id()); rcu_idle_exit(); return 1; } /* Weak implementations for optional arch specific functions */ void __weak arch_cpu_idle_prepare(void) { } void __weak arch_cpu_idle_enter(void) { } void __weak arch_cpu_idle_exit(void) { } void __weak arch_cpu_idle_dead(void) { } void __weak arch_cpu_idle(void) { cpu_idle_force_poll = 1; local_irq_enable(); } /** * default_idle_call - Default CPU idle routine. * * To use when the cpuidle framework cannot be used. */ void __cpuidle default_idle_call(void) { if (current_clr_polling_and_test()) { local_irq_enable(); } else { stop_critical_timings(); arch_cpu_idle(); start_critical_timings(); } } static int call_cpuidle(struct cpuidle_driver *drv, struct cpuidle_device *dev, int next_state) { /* * The idle task must be scheduled, it is pointless to go to idle, just * update no idle residency and return. */ if (current_clr_polling_and_test()) { dev->last_residency = 0; local_irq_enable(); return -EBUSY; } /* * Enter the idle state previously returned by the governor decision. * This function will block until an interrupt occurs and will take * care of re-enabling the local interrupts */ return cpuidle_enter(drv, dev, next_state); } /** * cpuidle_idle_call - the main idle function * * NOTE: no locks or semaphores should be used here * * On archs that support TIF_POLLING_NRFLAG, is called with polling * set, and it returns with polling set. If it ever stops polling, it * must clear the polling bit. */ static void cpuidle_idle_call(void) { struct cpuidle_device *dev = cpuidle_get_device(); struct cpuidle_driver *drv = cpuidle_get_cpu_driver(dev); int next_state, entered_state; /* * Check if the idle task must be rescheduled. If it is the * case, exit the function after re-enabling the local irq. */ if (need_resched()) { local_irq_enable(); return; } /* * Tell the RCU framework we are entering an idle section, * so no more rcu read side critical sections and one more * step to the grace period */ rcu_idle_enter(); if (cpuidle_not_available(drv, dev)) { default_idle_call(); goto exit_idle; } /* * Suspend-to-idle ("freeze") is a system state in which all user space * has been frozen, all I/O devices have been suspended and the only * activity happens here and in iterrupts (if any). In that case bypass * the cpuidle governor and go stratight for the deepest idle state * available. Possibly also suspend the local tick and the entire * timekeeping to prevent timer interrupts from kicking us out of idle * until a proper wakeup interrupt happens. */ if (idle_should_freeze() || dev->use_deepest_state) { if (idle_should_freeze()) { entered_state = cpuidle_enter_freeze(drv, dev); if (entered_state > 0) { local_irq_enable(); goto exit_idle; } } next_state = cpuidle_find_deepest_state(drv, dev); call_cpuidle(drv, dev, next_state); } else { /* * Ask the cpuidle framework to choose a convenient idle state. */ next_state = cpuidle_select(drv, dev); entered_state = call_cpuidle(drv, dev, next_state); /* * Give the governor an opportunity to reflect on the outcome */ cpuidle_reflect(dev, entered_state); } exit_idle: __current_set_polling(); /* * It is up to the idle functions to reenable local interrupts */ if (WARN_ON_ONCE(irqs_disabled())) local_irq_enable(); rcu_idle_exit(); } /* * Generic idle loop implementation * * Called with polling cleared. */ static void do_idle(void) { /* * If the arch has a polling bit, we maintain an invariant: * * Our polling bit is clear if we're not scheduled (i.e. if rq->curr != * rq->idle). This means that, if rq->idle has the polling bit set, * then setting need_resched is guaranteed to cause the CPU to * reschedule. */ __current_set_polling(); tick_nohz_idle_enter(); while (!need_resched()) { check_pgt_cache(); rmb(); if (cpu_is_offline(smp_processor_id())) { cpuhp_report_idle_dead(); arch_cpu_idle_dead(); } local_irq_disable(); arch_cpu_idle_enter(); /* * In poll mode we reenable interrupts and spin. Also if we * detected in the wakeup from idle path that the tick * broadcast device expired for us, we don't want to go deep * idle as we know that the IPI is going to arrive right away. */ if (cpu_idle_force_poll || tick_check_broadcast_expired()) cpu_idle_poll(); else cpuidle_idle_call(); arch_cpu_idle_exit(); } /* * Since we fell out of the loop above, we know TIF_NEED_RESCHED must * be set, propagate it into PREEMPT_NEED_RESCHED. * * This is required because for polling idle loops we will not have had * an IPI to fold the state for us. */ preempt_set_need_resched(); tick_nohz_idle_exit(); __current_clr_polling(); /* * We promise to call sched_ttwu_pending() and reschedule if * need_resched() is set while polling is set. That means that clearing * polling needs to be visible before doing these things. */ smp_mb__after_atomic(); sched_ttwu_pending(); schedule_preempt_disabled(); } bool cpu_in_idle(unsigned long pc) { return pc >= (unsigned long)__cpuidle_text_start && pc < (unsigned long)__cpuidle_text_end; } struct idle_timer { struct hrtimer timer; int done; }; static enum hrtimer_restart idle_inject_timer_fn(struct hrtimer *timer) { struct idle_timer *it = container_of(timer, struct idle_timer, timer); WRITE_ONCE(it->done, 1); set_tsk_need_resched(current); return HRTIMER_NORESTART; } void play_idle(unsigned long duration_ms) { struct idle_timer it; /* * Only FIFO tasks can disable the tick since they don't need the forced * preemption. */ WARN_ON_ONCE(current->policy != SCHED_FIFO); WARN_ON_ONCE(current->nr_cpus_allowed != 1); WARN_ON_ONCE(!(current->flags & PF_KTHREAD)); WARN_ON_ONCE(!(current->flags & PF_NO_SETAFFINITY)); WARN_ON_ONCE(!duration_ms); rcu_sleep_check(); preempt_disable(); current->flags |= PF_IDLE; cpuidle_use_deepest_state(true); it.done = 0; hrtimer_init_on_stack(&it.timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); it.timer.function = idle_inject_timer_fn; hrtimer_start(&it.timer, ms_to_ktime(duration_ms), HRTIMER_MODE_REL_PINNED); while (!READ_ONCE(it.done)) do_idle(); cpuidle_use_deepest_state(false); current->flags &= ~PF_IDLE; preempt_fold_need_resched(); preempt_enable(); } EXPORT_SYMBOL_GPL(play_idle); void cpu_startup_entry(enum cpuhp_state state) { /* * This #ifdef needs to die, but it's too late in the cycle to * make this generic (arm and sh have never invoked the canary * init for the non boot cpus!). Will be fixed in 3.11 */ #ifdef CONFIG_X86 /* * If we're the non-boot CPU, nothing set the stack canary up * for us. The boot CPU already has it initialized but no harm * in doing it again. This is a good place for updating it, as * we wont ever return from this function (so the invalid * canaries already on the stack wont ever trigger). */ boot_init_stack_canary(); #endif arch_cpu_idle_prepare(); cpuhp_online_idle(state); while (1) do_idle(); }
null
null
null
null
112,971
57,536
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
57,536
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 "chrome/browser/chromeos/input_method/input_method_engine.h" #include <map> #include <memory> #include <utility> #include "ash/shell.h" #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/profiles/profile_manager.h" #include "ui/aura/window.h" #include "ui/aura/window_tree_host.h" #include "ui/base/ime/candidate_window.h" #include "ui/base/ime/chromeos/component_extension_ime_manager.h" #include "ui/base/ime/chromeos/extension_ime_util.h" #include "ui/base/ime/chromeos/ime_keymap.h" #include "ui/base/ime/composition_text.h" #include "ui/base/ime/ime_bridge.h" #include "ui/base/ime/text_input_flags.h" #include "ui/chromeos/ime/input_method_menu_item.h" #include "ui/chromeos/ime/input_method_menu_manager.h" #include "ui/events/event.h" #include "ui/events/event_sink.h" #include "ui/events/event_utils.h" #include "ui/events/keycodes/dom/dom_code.h" #include "ui/events/keycodes/dom/keycode_converter.h" #include "ui/keyboard/keyboard_controller.h" using input_method::InputMethodEngineBase; namespace chromeos { namespace { const char kErrorNotActive[] = "IME is not active"; const char kErrorWrongContext[] = "Context is not active"; const char kCandidateNotFound[] = "Candidate not found"; // The default entry number of a page in CandidateWindowProperty. const int kDefaultPageSize = 9; } // namespace InputMethodEngine::Candidate::Candidate() {} InputMethodEngine::Candidate::Candidate(const Candidate& other) = default; InputMethodEngine::Candidate::~Candidate() {} // When the default values are changed, please modify // CandidateWindow::CandidateWindowProperty defined in chromeos/ime/ too. InputMethodEngine::CandidateWindowProperty::CandidateWindowProperty() : page_size(kDefaultPageSize), is_cursor_visible(true), is_vertical(false), show_window_at_composition(false) {} InputMethodEngine::CandidateWindowProperty::~CandidateWindowProperty() {} InputMethodEngine::InputMethodEngine() : candidate_window_(new ui::CandidateWindow()), window_visible_(false) {} InputMethodEngine::~InputMethodEngine() {} const InputMethodEngine::CandidateWindowProperty& InputMethodEngine::GetCandidateWindowProperty() const { return candidate_window_property_; } void InputMethodEngine::SetCandidateWindowProperty( const CandidateWindowProperty& property) { // Type conversion from InputMethodEngine::CandidateWindowProperty to // CandidateWindow::CandidateWindowProperty defined in chromeos/ime/. ui::CandidateWindow::CandidateWindowProperty dest_property; dest_property.page_size = property.page_size; dest_property.is_cursor_visible = property.is_cursor_visible; dest_property.is_vertical = property.is_vertical; dest_property.show_window_at_composition = property.show_window_at_composition; dest_property.cursor_position = candidate_window_->GetProperty().cursor_position; dest_property.auxiliary_text = property.auxiliary_text; dest_property.is_auxiliary_text_visible = property.is_auxiliary_text_visible; candidate_window_->SetProperty(dest_property); candidate_window_property_ = property; if (IsActive()) { IMECandidateWindowHandlerInterface* cw_handler = ui::IMEBridge::Get()->GetCandidateWindowHandler(); if (cw_handler) cw_handler->UpdateLookupTable(*candidate_window_, window_visible_); } } bool InputMethodEngine::SetCandidateWindowVisible(bool visible, std::string* error) { if (!IsActive()) { *error = kErrorNotActive; return false; } window_visible_ = visible; IMECandidateWindowHandlerInterface* cw_handler = ui::IMEBridge::Get()->GetCandidateWindowHandler(); if (cw_handler) cw_handler->UpdateLookupTable(*candidate_window_, window_visible_); return true; } bool InputMethodEngine::SetCandidates( int context_id, const std::vector<Candidate>& candidates, std::string* error) { if (!IsActive()) { *error = kErrorNotActive; return false; } if (context_id != context_id_ || context_id_ == -1) { *error = kErrorWrongContext; return false; } // TODO: Nested candidates candidate_ids_.clear(); candidate_indexes_.clear(); candidate_window_->mutable_candidates()->clear(); for (std::vector<Candidate>::const_iterator ix = candidates.begin(); ix != candidates.end(); ++ix) { ui::CandidateWindow::Entry entry; entry.value = base::UTF8ToUTF16(ix->value); entry.label = base::UTF8ToUTF16(ix->label); entry.annotation = base::UTF8ToUTF16(ix->annotation); entry.description_title = base::UTF8ToUTF16(ix->usage.title); entry.description_body = base::UTF8ToUTF16(ix->usage.body); // Store a mapping from the user defined ID to the candidate index. candidate_indexes_[ix->id] = candidate_ids_.size(); candidate_ids_.push_back(ix->id); candidate_window_->mutable_candidates()->push_back(entry); } if (IsActive()) { IMECandidateWindowHandlerInterface* cw_handler = ui::IMEBridge::Get()->GetCandidateWindowHandler(); if (cw_handler) cw_handler->UpdateLookupTable(*candidate_window_, window_visible_); } return true; } bool InputMethodEngine::SetCursorPosition(int context_id, int candidate_id, std::string* error) { if (!IsActive()) { *error = kErrorNotActive; return false; } if (context_id != context_id_ || context_id_ == -1) { *error = kErrorWrongContext; return false; } std::map<int, int>::const_iterator position = candidate_indexes_.find(candidate_id); if (position == candidate_indexes_.end()) { *error = kCandidateNotFound; return false; } candidate_window_->set_cursor_position(position->second); IMECandidateWindowHandlerInterface* cw_handler = ui::IMEBridge::Get()->GetCandidateWindowHandler(); if (cw_handler) cw_handler->UpdateLookupTable(*candidate_window_, window_visible_); return true; } bool InputMethodEngine::SetMenuItems( const std::vector<input_method::InputMethodManager::MenuItem>& items) { return UpdateMenuItems(items); } bool InputMethodEngine::UpdateMenuItems( const std::vector<input_method::InputMethodManager::MenuItem>& items) { if (!IsActive()) return false; ui::ime::InputMethodMenuItemList menu_item_list; for (std::vector<input_method::InputMethodManager::MenuItem>::const_iterator item = items.begin(); item != items.end(); ++item) { ui::ime::InputMethodMenuItem property; MenuItemToProperty(*item, &property); menu_item_list.push_back(property); } ui::ime::InputMethodMenuManager::GetInstance() ->SetCurrentInputMethodMenuItemList(menu_item_list); input_method::InputMethodManager::Get()->NotifyImeMenuItemsChanged( active_component_id_, items); return true; } bool InputMethodEngine::IsActive() const { return !active_component_id_.empty(); } void InputMethodEngine::HideInputView() { keyboard::KeyboardController* keyboard_controller = keyboard::KeyboardController::GetInstance(); if (keyboard_controller) { keyboard_controller->HideKeyboard( keyboard::KeyboardController::HIDE_REASON_MANUAL); } } void InputMethodEngine::EnableInputView() { input_method::InputMethodManager::Get() ->GetActiveIMEState() ->EnableInputView(); keyboard::KeyboardController* keyboard_controller = keyboard::KeyboardController::GetInstance(); if (keyboard_controller) keyboard_controller->Reload(); } void InputMethodEngine::Enable(const std::string& component_id) { InputMethodEngineBase::Enable(component_id); EnableInputView(); } void InputMethodEngine::PropertyActivate(const std::string& property_name) { observer_->OnMenuItemActivated(active_component_id_, property_name); } void InputMethodEngine::CandidateClicked(uint32_t index) { if (index > candidate_ids_.size()) { return; } // Only left button click is supported at this moment. observer_->OnCandidateClicked(active_component_id_, candidate_ids_.at(index), InputMethodEngineBase::MOUSE_BUTTON_LEFT); } // TODO(uekawa): rename this method to a more reasonable name. void InputMethodEngine::MenuItemToProperty( const input_method::InputMethodManager::MenuItem& item, ui::ime::InputMethodMenuItem* property) { property->key = item.id; if (item.modified & MENU_ITEM_MODIFIED_LABEL) { property->label = item.label; } if (item.modified & MENU_ITEM_MODIFIED_VISIBLE) { // TODO(nona): Implement it. } if (item.modified & MENU_ITEM_MODIFIED_CHECKED) { property->is_selection_item_checked = item.checked; } if (item.modified & MENU_ITEM_MODIFIED_ENABLED) { // TODO(nona): implement sensitive entry(crbug.com/140192). } if (item.modified & MENU_ITEM_MODIFIED_STYLE) { if (!item.children.empty()) { // TODO(nona): Implement it. } else { switch (item.style) { case input_method::InputMethodManager::MENU_ITEM_STYLE_NONE: NOTREACHED(); break; case input_method::InputMethodManager::MENU_ITEM_STYLE_CHECK: // TODO(nona): Implement it. break; case input_method::InputMethodManager::MENU_ITEM_STYLE_RADIO: property->is_selection_item = true; break; case input_method::InputMethodManager::MENU_ITEM_STYLE_SEPARATOR: // TODO(nona): Implement it. break; } } } // TODO(nona): Support item.children. } void InputMethodEngine::UpdateComposition( const ui::CompositionText& composition_text, uint32_t cursor_pos, bool is_visible) { ui::IMEInputContextHandlerInterface* input_context = ui::IMEBridge::Get()->GetInputContextHandler(); if (input_context) input_context->UpdateCompositionText(composition_text, cursor_pos, is_visible); } void InputMethodEngine::CommitTextToInputContext(int context_id, const std::string& text) { ui::IMEBridge::Get()->GetInputContextHandler()->CommitText(text); // Records histograms for committed characters. if (!composition_text_->text.empty()) { base::string16 wtext = base::UTF8ToUTF16(text); UMA_HISTOGRAM_CUSTOM_COUNTS("InputMethod.CommitLength", wtext.length(), 1, 25, 25); composition_text_.reset(new ui::CompositionText()); } } bool InputMethodEngine::SendKeyEvent(ui::KeyEvent* event, const std::string& code) { DCHECK(event); if (event->key_code() == ui::VKEY_UNKNOWN) event->set_key_code(ui::DomKeycodeToKeyboardCode(code)); ui::EventSink* sink = ash::Shell::GetPrimaryRootWindow()->GetHost()->event_sink(); ui::EventDispatchDetails details = sink->OnEventFromSource(event); return !details.dispatcher_destroyed; } } // namespace chromeos
null
null
null
null
54,399
5,369
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
170,364
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * MIDI byte <-> sequencer event coder * * Copyright (C) 1998,99 Takashi Iwai <tiwai@suse.de>, * Jaroslav Kysela <perex@perex.cz> * * 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/slab.h> #include <linux/errno.h> #include <linux/string.h> #include <linux/module.h> #include <sound/core.h> #include <sound/seq_kernel.h> #include <sound/seq_midi_event.h> #include <sound/asoundef.h> MODULE_AUTHOR("Takashi Iwai <tiwai@suse.de>, Jaroslav Kysela <perex@perex.cz>"); MODULE_DESCRIPTION("MIDI byte <-> sequencer event coder"); MODULE_LICENSE("GPL"); /* event type, index into status_event[] */ /* from 0 to 6 are normal commands (note off, on, etc.) for 0x9?-0xe? */ #define ST_INVALID 7 #define ST_SPECIAL 8 #define ST_SYSEX ST_SPECIAL /* from 8 to 15 are events for 0xf0-0xf7 */ /* * prototypes */ static void note_event(struct snd_midi_event *dev, struct snd_seq_event *ev); static void one_param_ctrl_event(struct snd_midi_event *dev, struct snd_seq_event *ev); static void pitchbend_ctrl_event(struct snd_midi_event *dev, struct snd_seq_event *ev); static void two_param_ctrl_event(struct snd_midi_event *dev, struct snd_seq_event *ev); static void one_param_event(struct snd_midi_event *dev, struct snd_seq_event *ev); static void songpos_event(struct snd_midi_event *dev, struct snd_seq_event *ev); static void note_decode(struct snd_seq_event *ev, unsigned char *buf); static void one_param_decode(struct snd_seq_event *ev, unsigned char *buf); static void pitchbend_decode(struct snd_seq_event *ev, unsigned char *buf); static void two_param_decode(struct snd_seq_event *ev, unsigned char *buf); static void songpos_decode(struct snd_seq_event *ev, unsigned char *buf); /* * event list */ static struct status_event_list { int event; int qlen; void (*encode)(struct snd_midi_event *dev, struct snd_seq_event *ev); void (*decode)(struct snd_seq_event *ev, unsigned char *buf); } status_event[] = { /* 0x80 - 0xef */ {SNDRV_SEQ_EVENT_NOTEOFF, 2, note_event, note_decode}, {SNDRV_SEQ_EVENT_NOTEON, 2, note_event, note_decode}, {SNDRV_SEQ_EVENT_KEYPRESS, 2, note_event, note_decode}, {SNDRV_SEQ_EVENT_CONTROLLER, 2, two_param_ctrl_event, two_param_decode}, {SNDRV_SEQ_EVENT_PGMCHANGE, 1, one_param_ctrl_event, one_param_decode}, {SNDRV_SEQ_EVENT_CHANPRESS, 1, one_param_ctrl_event, one_param_decode}, {SNDRV_SEQ_EVENT_PITCHBEND, 2, pitchbend_ctrl_event, pitchbend_decode}, /* invalid */ {SNDRV_SEQ_EVENT_NONE, -1, NULL, NULL}, /* 0xf0 - 0xff */ {SNDRV_SEQ_EVENT_SYSEX, 1, NULL, NULL}, /* sysex: 0xf0 */ {SNDRV_SEQ_EVENT_QFRAME, 1, one_param_event, one_param_decode}, /* 0xf1 */ {SNDRV_SEQ_EVENT_SONGPOS, 2, songpos_event, songpos_decode}, /* 0xf2 */ {SNDRV_SEQ_EVENT_SONGSEL, 1, one_param_event, one_param_decode}, /* 0xf3 */ {SNDRV_SEQ_EVENT_NONE, -1, NULL, NULL}, /* 0xf4 */ {SNDRV_SEQ_EVENT_NONE, -1, NULL, NULL}, /* 0xf5 */ {SNDRV_SEQ_EVENT_TUNE_REQUEST, 0, NULL, NULL}, /* 0xf6 */ {SNDRV_SEQ_EVENT_NONE, -1, NULL, NULL}, /* 0xf7 */ {SNDRV_SEQ_EVENT_CLOCK, 0, NULL, NULL}, /* 0xf8 */ {SNDRV_SEQ_EVENT_NONE, -1, NULL, NULL}, /* 0xf9 */ {SNDRV_SEQ_EVENT_START, 0, NULL, NULL}, /* 0xfa */ {SNDRV_SEQ_EVENT_CONTINUE, 0, NULL, NULL}, /* 0xfb */ {SNDRV_SEQ_EVENT_STOP, 0, NULL, NULL}, /* 0xfc */ {SNDRV_SEQ_EVENT_NONE, -1, NULL, NULL}, /* 0xfd */ {SNDRV_SEQ_EVENT_SENSING, 0, NULL, NULL}, /* 0xfe */ {SNDRV_SEQ_EVENT_RESET, 0, NULL, NULL}, /* 0xff */ }; static int extra_decode_ctrl14(struct snd_midi_event *dev, unsigned char *buf, int len, struct snd_seq_event *ev); static int extra_decode_xrpn(struct snd_midi_event *dev, unsigned char *buf, int count, struct snd_seq_event *ev); static struct extra_event_list { int event; int (*decode)(struct snd_midi_event *dev, unsigned char *buf, int len, struct snd_seq_event *ev); } extra_event[] = { {SNDRV_SEQ_EVENT_CONTROL14, extra_decode_ctrl14}, {SNDRV_SEQ_EVENT_NONREGPARAM, extra_decode_xrpn}, {SNDRV_SEQ_EVENT_REGPARAM, extra_decode_xrpn}, }; /* * new/delete record */ int snd_midi_event_new(int bufsize, struct snd_midi_event **rdev) { struct snd_midi_event *dev; *rdev = NULL; dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (dev == NULL) return -ENOMEM; if (bufsize > 0) { dev->buf = kmalloc(bufsize, GFP_KERNEL); if (dev->buf == NULL) { kfree(dev); return -ENOMEM; } } dev->bufsize = bufsize; dev->lastcmd = 0xff; dev->type = ST_INVALID; spin_lock_init(&dev->lock); *rdev = dev; return 0; } void snd_midi_event_free(struct snd_midi_event *dev) { if (dev != NULL) { kfree(dev->buf); kfree(dev); } } /* * initialize record */ static inline void reset_encode(struct snd_midi_event *dev) { dev->read = 0; dev->qlen = 0; dev->type = ST_INVALID; } void snd_midi_event_reset_encode(struct snd_midi_event *dev) { unsigned long flags; spin_lock_irqsave(&dev->lock, flags); reset_encode(dev); spin_unlock_irqrestore(&dev->lock, flags); } void snd_midi_event_reset_decode(struct snd_midi_event *dev) { unsigned long flags; spin_lock_irqsave(&dev->lock, flags); dev->lastcmd = 0xff; spin_unlock_irqrestore(&dev->lock, flags); } #if 0 void snd_midi_event_init(struct snd_midi_event *dev) { snd_midi_event_reset_encode(dev); snd_midi_event_reset_decode(dev); } #endif /* 0 */ void snd_midi_event_no_status(struct snd_midi_event *dev, int on) { dev->nostat = on ? 1 : 0; } /* * resize buffer */ #if 0 int snd_midi_event_resize_buffer(struct snd_midi_event *dev, int bufsize) { unsigned char *new_buf, *old_buf; unsigned long flags; if (bufsize == dev->bufsize) return 0; new_buf = kmalloc(bufsize, GFP_KERNEL); if (new_buf == NULL) return -ENOMEM; spin_lock_irqsave(&dev->lock, flags); old_buf = dev->buf; dev->buf = new_buf; dev->bufsize = bufsize; reset_encode(dev); spin_unlock_irqrestore(&dev->lock, flags); kfree(old_buf); return 0; } #endif /* 0 */ /* * read bytes and encode to sequencer event if finished * return the size of encoded bytes */ long snd_midi_event_encode(struct snd_midi_event *dev, unsigned char *buf, long count, struct snd_seq_event *ev) { long result = 0; int rc; ev->type = SNDRV_SEQ_EVENT_NONE; while (count-- > 0) { rc = snd_midi_event_encode_byte(dev, *buf++, ev); result++; if (rc < 0) return rc; else if (rc > 0) return result; } return result; } /* * read one byte and encode to sequencer event: * return 1 if MIDI bytes are encoded to an event * 0 data is not finished * negative for error */ int snd_midi_event_encode_byte(struct snd_midi_event *dev, int c, struct snd_seq_event *ev) { int rc = 0; unsigned long flags; c &= 0xff; if (c >= MIDI_CMD_COMMON_CLOCK) { /* real-time event */ ev->type = status_event[ST_SPECIAL + c - 0xf0].event; ev->flags &= ~SNDRV_SEQ_EVENT_LENGTH_MASK; ev->flags |= SNDRV_SEQ_EVENT_LENGTH_FIXED; return ev->type != SNDRV_SEQ_EVENT_NONE; } spin_lock_irqsave(&dev->lock, flags); if ((c & 0x80) && (c != MIDI_CMD_COMMON_SYSEX_END || dev->type != ST_SYSEX)) { /* new command */ dev->buf[0] = c; if ((c & 0xf0) == 0xf0) /* system messages */ dev->type = (c & 0x0f) + ST_SPECIAL; else dev->type = (c >> 4) & 0x07; dev->read = 1; dev->qlen = status_event[dev->type].qlen; } else { if (dev->qlen > 0) { /* rest of command */ dev->buf[dev->read++] = c; if (dev->type != ST_SYSEX) dev->qlen--; } else { /* running status */ dev->buf[1] = c; dev->qlen = status_event[dev->type].qlen - 1; dev->read = 2; } } if (dev->qlen == 0) { ev->type = status_event[dev->type].event; ev->flags &= ~SNDRV_SEQ_EVENT_LENGTH_MASK; ev->flags |= SNDRV_SEQ_EVENT_LENGTH_FIXED; if (status_event[dev->type].encode) /* set data values */ status_event[dev->type].encode(dev, ev); if (dev->type >= ST_SPECIAL) dev->type = ST_INVALID; rc = 1; } else if (dev->type == ST_SYSEX) { if (c == MIDI_CMD_COMMON_SYSEX_END || dev->read >= dev->bufsize) { ev->flags &= ~SNDRV_SEQ_EVENT_LENGTH_MASK; ev->flags |= SNDRV_SEQ_EVENT_LENGTH_VARIABLE; ev->type = SNDRV_SEQ_EVENT_SYSEX; ev->data.ext.len = dev->read; ev->data.ext.ptr = dev->buf; if (c != MIDI_CMD_COMMON_SYSEX_END) dev->read = 0; /* continue to parse */ else reset_encode(dev); /* all parsed */ rc = 1; } } spin_unlock_irqrestore(&dev->lock, flags); return rc; } /* encode note event */ static void note_event(struct snd_midi_event *dev, struct snd_seq_event *ev) { ev->data.note.channel = dev->buf[0] & 0x0f; ev->data.note.note = dev->buf[1]; ev->data.note.velocity = dev->buf[2]; } /* encode one parameter controls */ static void one_param_ctrl_event(struct snd_midi_event *dev, struct snd_seq_event *ev) { ev->data.control.channel = dev->buf[0] & 0x0f; ev->data.control.value = dev->buf[1]; } /* encode pitch wheel change */ static void pitchbend_ctrl_event(struct snd_midi_event *dev, struct snd_seq_event *ev) { ev->data.control.channel = dev->buf[0] & 0x0f; ev->data.control.value = (int)dev->buf[2] * 128 + (int)dev->buf[1] - 8192; } /* encode midi control change */ static void two_param_ctrl_event(struct snd_midi_event *dev, struct snd_seq_event *ev) { ev->data.control.channel = dev->buf[0] & 0x0f; ev->data.control.param = dev->buf[1]; ev->data.control.value = dev->buf[2]; } /* encode one parameter value*/ static void one_param_event(struct snd_midi_event *dev, struct snd_seq_event *ev) { ev->data.control.value = dev->buf[1]; } /* encode song position */ static void songpos_event(struct snd_midi_event *dev, struct snd_seq_event *ev) { ev->data.control.value = (int)dev->buf[2] * 128 + (int)dev->buf[1]; } /* * decode from a sequencer event to midi bytes * return the size of decoded midi events */ long snd_midi_event_decode(struct snd_midi_event *dev, unsigned char *buf, long count, struct snd_seq_event *ev) { unsigned int cmd, type; if (ev->type == SNDRV_SEQ_EVENT_NONE) return -ENOENT; for (type = 0; type < ARRAY_SIZE(status_event); type++) { if (ev->type == status_event[type].event) goto __found; } for (type = 0; type < ARRAY_SIZE(extra_event); type++) { if (ev->type == extra_event[type].event) return extra_event[type].decode(dev, buf, count, ev); } return -ENOENT; __found: if (type >= ST_SPECIAL) cmd = 0xf0 + (type - ST_SPECIAL); else /* data.note.channel and data.control.channel is identical */ cmd = 0x80 | (type << 4) | (ev->data.note.channel & 0x0f); if (cmd == MIDI_CMD_COMMON_SYSEX) { snd_midi_event_reset_decode(dev); return snd_seq_expand_var_event(ev, count, buf, 1, 0); } else { int qlen; unsigned char xbuf[4]; unsigned long flags; spin_lock_irqsave(&dev->lock, flags); if ((cmd & 0xf0) == 0xf0 || dev->lastcmd != cmd || dev->nostat) { dev->lastcmd = cmd; spin_unlock_irqrestore(&dev->lock, flags); xbuf[0] = cmd; if (status_event[type].decode) status_event[type].decode(ev, xbuf + 1); qlen = status_event[type].qlen + 1; } else { spin_unlock_irqrestore(&dev->lock, flags); if (status_event[type].decode) status_event[type].decode(ev, xbuf + 0); qlen = status_event[type].qlen; } if (count < qlen) return -ENOMEM; memcpy(buf, xbuf, qlen); return qlen; } } /* decode note event */ static void note_decode(struct snd_seq_event *ev, unsigned char *buf) { buf[0] = ev->data.note.note & 0x7f; buf[1] = ev->data.note.velocity & 0x7f; } /* decode one parameter controls */ static void one_param_decode(struct snd_seq_event *ev, unsigned char *buf) { buf[0] = ev->data.control.value & 0x7f; } /* decode pitch wheel change */ static void pitchbend_decode(struct snd_seq_event *ev, unsigned char *buf) { int value = ev->data.control.value + 8192; buf[0] = value & 0x7f; buf[1] = (value >> 7) & 0x7f; } /* decode midi control change */ static void two_param_decode(struct snd_seq_event *ev, unsigned char *buf) { buf[0] = ev->data.control.param & 0x7f; buf[1] = ev->data.control.value & 0x7f; } /* decode song position */ static void songpos_decode(struct snd_seq_event *ev, unsigned char *buf) { buf[0] = ev->data.control.value & 0x7f; buf[1] = (ev->data.control.value >> 7) & 0x7f; } /* decode 14bit control */ static int extra_decode_ctrl14(struct snd_midi_event *dev, unsigned char *buf, int count, struct snd_seq_event *ev) { unsigned char cmd; int idx = 0; cmd = MIDI_CMD_CONTROL|(ev->data.control.channel & 0x0f); if (ev->data.control.param < 0x20) { if (count < 4) return -ENOMEM; if (dev->nostat && count < 6) return -ENOMEM; if (cmd != dev->lastcmd || dev->nostat) { if (count < 5) return -ENOMEM; buf[idx++] = dev->lastcmd = cmd; } buf[idx++] = ev->data.control.param; buf[idx++] = (ev->data.control.value >> 7) & 0x7f; if (dev->nostat) buf[idx++] = cmd; buf[idx++] = ev->data.control.param + 0x20; buf[idx++] = ev->data.control.value & 0x7f; } else { if (count < 2) return -ENOMEM; if (cmd != dev->lastcmd || dev->nostat) { if (count < 3) return -ENOMEM; buf[idx++] = dev->lastcmd = cmd; } buf[idx++] = ev->data.control.param & 0x7f; buf[idx++] = ev->data.control.value & 0x7f; } return idx; } /* decode reg/nonreg param */ static int extra_decode_xrpn(struct snd_midi_event *dev, unsigned char *buf, int count, struct snd_seq_event *ev) { unsigned char cmd; char *cbytes; static char cbytes_nrpn[4] = { MIDI_CTL_NONREG_PARM_NUM_MSB, MIDI_CTL_NONREG_PARM_NUM_LSB, MIDI_CTL_MSB_DATA_ENTRY, MIDI_CTL_LSB_DATA_ENTRY }; static char cbytes_rpn[4] = { MIDI_CTL_REGIST_PARM_NUM_MSB, MIDI_CTL_REGIST_PARM_NUM_LSB, MIDI_CTL_MSB_DATA_ENTRY, MIDI_CTL_LSB_DATA_ENTRY }; unsigned char bytes[4]; int idx = 0, i; if (count < 8) return -ENOMEM; if (dev->nostat && count < 12) return -ENOMEM; cmd = MIDI_CMD_CONTROL|(ev->data.control.channel & 0x0f); bytes[0] = (ev->data.control.param & 0x3f80) >> 7; bytes[1] = ev->data.control.param & 0x007f; bytes[2] = (ev->data.control.value & 0x3f80) >> 7; bytes[3] = ev->data.control.value & 0x007f; if (cmd != dev->lastcmd && !dev->nostat) { if (count < 9) return -ENOMEM; buf[idx++] = dev->lastcmd = cmd; } cbytes = ev->type == SNDRV_SEQ_EVENT_NONREGPARAM ? cbytes_nrpn : cbytes_rpn; for (i = 0; i < 4; i++) { if (dev->nostat) buf[idx++] = dev->lastcmd = cmd; buf[idx++] = cbytes[i]; buf[idx++] = bytes[i]; } return idx; } /* * exports */ EXPORT_SYMBOL(snd_midi_event_new); EXPORT_SYMBOL(snd_midi_event_free); EXPORT_SYMBOL(snd_midi_event_reset_encode); EXPORT_SYMBOL(snd_midi_event_reset_decode); EXPORT_SYMBOL(snd_midi_event_no_status); EXPORT_SYMBOL(snd_midi_event_encode); EXPORT_SYMBOL(snd_midi_event_encode_byte); EXPORT_SYMBOL(snd_midi_event_decode); static int __init alsa_seq_midi_event_init(void) { return 0; } static void __exit alsa_seq_midi_event_exit(void) { } module_init(alsa_seq_midi_event_init) module_exit(alsa_seq_midi_event_exit)
null
null
null
null
78,711
16,710
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
181,705
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * KFR2R09 board support code * * Copyright (C) 2009 Magnus Damm * * 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/init.h> #include <linux/platform_device.h> #include <linux/interrupt.h> #include <linux/mmc/host.h> #include <linux/mfd/tmio.h> #include <linux/mtd/physmap.h> #include <linux/mtd/onenand.h> #include <linux/delay.h> #include <linux/clk.h> #include <linux/gpio.h> #include <linux/input.h> #include <linux/input/sh_keysc.h> #include <linux/i2c.h> #include <linux/platform_data/lv5207lp.h> #include <linux/regulator/fixed.h> #include <linux/regulator/machine.h> #include <linux/usb/r8a66597.h> #include <linux/videodev2.h> #include <linux/sh_intc.h> #include <media/i2c/rj54n1cb0c.h> #include <media/soc_camera.h> #include <media/drv-intf/sh_mobile_ceu.h> #include <video/sh_mobile_lcdc.h> #include <asm/suspend.h> #include <asm/clock.h> #include <asm/machvec.h> #include <asm/io.h> #include <cpu/sh7724.h> #include <mach/kfr2r09.h> static struct mtd_partition kfr2r09_nor_flash_partitions[] = { { .name = "boot", .offset = 0, .size = (4 * 1024 * 1024), .mask_flags = MTD_WRITEABLE, /* Read-only */ }, { .name = "other", .offset = MTDPART_OFS_APPEND, .size = MTDPART_SIZ_FULL, }, }; static struct physmap_flash_data kfr2r09_nor_flash_data = { .width = 2, .parts = kfr2r09_nor_flash_partitions, .nr_parts = ARRAY_SIZE(kfr2r09_nor_flash_partitions), }; static struct resource kfr2r09_nor_flash_resources[] = { [0] = { .name = "NOR Flash", .start = 0x00000000, .end = 0x03ffffff, .flags = IORESOURCE_MEM, } }; static struct platform_device kfr2r09_nor_flash_device = { .name = "physmap-flash", .resource = kfr2r09_nor_flash_resources, .num_resources = ARRAY_SIZE(kfr2r09_nor_flash_resources), .dev = { .platform_data = &kfr2r09_nor_flash_data, }, }; static struct resource kfr2r09_nand_flash_resources[] = { [0] = { .name = "NAND Flash", .start = 0x10000000, .end = 0x1001ffff, .flags = IORESOURCE_MEM, } }; static struct platform_device kfr2r09_nand_flash_device = { .name = "onenand-flash", .resource = kfr2r09_nand_flash_resources, .num_resources = ARRAY_SIZE(kfr2r09_nand_flash_resources), }; static struct sh_keysc_info kfr2r09_sh_keysc_info = { .mode = SH_KEYSC_MODE_1, /* KEYOUT0->4, KEYIN0->4 */ .scan_timing = 3, .delay = 10, .keycodes = { KEY_PHONE, KEY_CLEAR, KEY_MAIL, KEY_WWW, KEY_ENTER, KEY_1, KEY_2, KEY_3, 0, KEY_UP, KEY_4, KEY_5, KEY_6, 0, KEY_LEFT, KEY_7, KEY_8, KEY_9, KEY_PROG1, KEY_RIGHT, KEY_S, KEY_0, KEY_P, KEY_PROG2, KEY_DOWN, 0, 0, 0, 0, 0 }, }; static struct resource kfr2r09_sh_keysc_resources[] = { [0] = { .name = "KEYSC", .start = 0x044b0000, .end = 0x044b000f, .flags = IORESOURCE_MEM, }, [1] = { .start = evt2irq(0xbe0), .flags = IORESOURCE_IRQ, }, }; static struct platform_device kfr2r09_sh_keysc_device = { .name = "sh_keysc", .id = 0, /* "keysc0" clock */ .num_resources = ARRAY_SIZE(kfr2r09_sh_keysc_resources), .resource = kfr2r09_sh_keysc_resources, .dev = { .platform_data = &kfr2r09_sh_keysc_info, }, }; static const struct fb_videomode kfr2r09_lcdc_modes[] = { { .name = "TX07D34VM0AAA", .xres = 240, .yres = 400, .left_margin = 0, .right_margin = 16, .hsync_len = 8, .upper_margin = 0, .lower_margin = 1, .vsync_len = 1, .sync = FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, }, }; static struct sh_mobile_lcdc_info kfr2r09_sh_lcdc_info = { .clock_source = LCDC_CLK_BUS, .ch[0] = { .chan = LCDC_CHAN_MAINLCD, .fourcc = V4L2_PIX_FMT_RGB565, .interface_type = SYS18, .clock_divider = 6, .flags = LCDC_FLAGS_DWPOL, .lcd_modes = kfr2r09_lcdc_modes, .num_modes = ARRAY_SIZE(kfr2r09_lcdc_modes), .panel_cfg = { .width = 35, .height = 58, .setup_sys = kfr2r09_lcd_setup, .start_transfer = kfr2r09_lcd_start, }, .sys_bus_cfg = { .ldmt2r = 0x07010904, .ldmt3r = 0x14012914, /* set 1s delay to encourage fsync() */ .deferred_io_msec = 1000, }, } }; static struct resource kfr2r09_sh_lcdc_resources[] = { [0] = { .name = "LCDC", .start = 0xfe940000, /* P4-only space */ .end = 0xfe942fff, .flags = IORESOURCE_MEM, }, [1] = { .start = evt2irq(0xf40), .flags = IORESOURCE_IRQ, }, }; static struct platform_device kfr2r09_sh_lcdc_device = { .name = "sh_mobile_lcdc_fb", .num_resources = ARRAY_SIZE(kfr2r09_sh_lcdc_resources), .resource = kfr2r09_sh_lcdc_resources, .dev = { .platform_data = &kfr2r09_sh_lcdc_info, }, }; static struct lv5207lp_platform_data kfr2r09_backlight_data = { .fbdev = &kfr2r09_sh_lcdc_device.dev, .def_value = 13, .max_value = 13, }; static struct i2c_board_info kfr2r09_backlight_board_info = { I2C_BOARD_INFO("lv5207lp", 0x75), .platform_data = &kfr2r09_backlight_data, }; static struct r8a66597_platdata kfr2r09_usb0_gadget_data = { .on_chip = 1, }; static struct resource kfr2r09_usb0_gadget_resources[] = { [0] = { .start = 0x04d80000, .end = 0x04d80123, .flags = IORESOURCE_MEM, }, [1] = { .start = evt2irq(0xa20), .end = evt2irq(0xa20), .flags = IORESOURCE_IRQ | IRQF_TRIGGER_LOW, }, }; static struct platform_device kfr2r09_usb0_gadget_device = { .name = "r8a66597_udc", .id = 0, .dev = { .dma_mask = NULL, /* not use dma */ .coherent_dma_mask = 0xffffffff, .platform_data = &kfr2r09_usb0_gadget_data, }, .num_resources = ARRAY_SIZE(kfr2r09_usb0_gadget_resources), .resource = kfr2r09_usb0_gadget_resources, }; static struct sh_mobile_ceu_info sh_mobile_ceu_info = { .flags = SH_CEU_FLAG_USE_8BIT_BUS, }; static struct resource kfr2r09_ceu_resources[] = { [0] = { .name = "CEU", .start = 0xfe910000, .end = 0xfe91009f, .flags = IORESOURCE_MEM, }, [1] = { .start = evt2irq(0x880), .end = evt2irq(0x880), .flags = IORESOURCE_IRQ, }, [2] = { /* place holder for contiguous memory */ }, }; static struct platform_device kfr2r09_ceu_device = { .name = "sh_mobile_ceu", .id = 0, /* "ceu0" clock */ .num_resources = ARRAY_SIZE(kfr2r09_ceu_resources), .resource = kfr2r09_ceu_resources, .dev = { .platform_data = &sh_mobile_ceu_info, }, }; static struct i2c_board_info kfr2r09_i2c_camera = { I2C_BOARD_INFO("rj54n1cb0c", 0x50), }; static struct clk *camera_clk; /* set VIO_CKO clock to 25MHz */ #define CEU_MCLK_FREQ 25000000 #define DRVCRB 0xA405018C static int camera_power(struct device *dev, int mode) { int ret; if (mode) { long rate; camera_clk = clk_get(NULL, "video_clk"); if (IS_ERR(camera_clk)) return PTR_ERR(camera_clk); rate = clk_round_rate(camera_clk, CEU_MCLK_FREQ); ret = clk_set_rate(camera_clk, rate); if (ret < 0) goto eclkrate; /* set DRVCRB * * use 1.8 V for VccQ_VIO * use 2.85V for VccQ_SR */ __raw_writew((__raw_readw(DRVCRB) & ~0x0003) | 0x0001, DRVCRB); /* reset clear */ ret = gpio_request(GPIO_PTB4, NULL); if (ret < 0) goto eptb4; ret = gpio_request(GPIO_PTB7, NULL); if (ret < 0) goto eptb7; ret = gpio_direction_output(GPIO_PTB4, 1); if (!ret) ret = gpio_direction_output(GPIO_PTB7, 1); if (ret < 0) goto egpioout; msleep(1); ret = clk_enable(camera_clk); /* start VIO_CKO */ if (ret < 0) goto eclkon; return 0; } ret = 0; clk_disable(camera_clk); eclkon: gpio_set_value(GPIO_PTB7, 0); egpioout: gpio_set_value(GPIO_PTB4, 0); gpio_free(GPIO_PTB7); eptb7: gpio_free(GPIO_PTB4); eptb4: eclkrate: clk_put(camera_clk); return ret; } static struct rj54n1_pdata rj54n1_priv = { .mclk_freq = CEU_MCLK_FREQ, .ioctl_high = false, }; static struct soc_camera_link rj54n1_link = { .power = camera_power, .board_info = &kfr2r09_i2c_camera, .i2c_adapter_id = 1, .priv = &rj54n1_priv, }; static struct platform_device kfr2r09_camera = { .name = "soc-camera-pdrv", .id = 0, .dev = { .platform_data = &rj54n1_link, }, }; /* Fixed 3.3V regulator to be used by SDHI0 */ static struct regulator_consumer_supply fixed3v3_power_consumers[] = { REGULATOR_SUPPLY("vmmc", "sh_mobile_sdhi.0"), REGULATOR_SUPPLY("vqmmc", "sh_mobile_sdhi.0"), }; static struct resource kfr2r09_sh_sdhi0_resources[] = { [0] = { .name = "SDHI0", .start = 0x04ce0000, .end = 0x04ce00ff, .flags = IORESOURCE_MEM, }, [1] = { .start = evt2irq(0xe80), .flags = IORESOURCE_IRQ, }, }; static struct tmio_mmc_data sh7724_sdhi0_data = { .chan_priv_tx = (void *)SHDMA_SLAVE_SDHI0_TX, .chan_priv_rx = (void *)SHDMA_SLAVE_SDHI0_RX, .flags = TMIO_MMC_WRPROTECT_DISABLE, .capabilities = MMC_CAP_SDIO_IRQ, }; static struct platform_device kfr2r09_sh_sdhi0_device = { .name = "sh_mobile_sdhi", .num_resources = ARRAY_SIZE(kfr2r09_sh_sdhi0_resources), .resource = kfr2r09_sh_sdhi0_resources, .dev = { .platform_data = &sh7724_sdhi0_data, }, }; static struct platform_device *kfr2r09_devices[] __initdata = { &kfr2r09_nor_flash_device, &kfr2r09_nand_flash_device, &kfr2r09_sh_keysc_device, &kfr2r09_sh_lcdc_device, &kfr2r09_ceu_device, &kfr2r09_camera, &kfr2r09_sh_sdhi0_device, }; #define BSC_CS0BCR 0xfec10004 #define BSC_CS0WCR 0xfec10024 #define BSC_CS4BCR 0xfec10010 #define BSC_CS4WCR 0xfec10030 #define PORT_MSELCRB 0xa4050182 #ifdef CONFIG_I2C static int kfr2r09_usb0_gadget_i2c_setup(void) { struct i2c_adapter *a; struct i2c_msg msg; unsigned char buf[2]; int ret; a = i2c_get_adapter(0); if (!a) return -ENODEV; /* set bit 1 (the second bit) of chip at 0x09, register 0x13 */ buf[0] = 0x13; msg.addr = 0x09; msg.buf = buf; msg.len = 1; msg.flags = 0; ret = i2c_transfer(a, &msg, 1); if (ret != 1) return -ENODEV; buf[0] = 0; msg.addr = 0x09; msg.buf = buf; msg.len = 1; msg.flags = I2C_M_RD; ret = i2c_transfer(a, &msg, 1); if (ret != 1) return -ENODEV; buf[1] = buf[0] | (1 << 1); buf[0] = 0x13; msg.addr = 0x09; msg.buf = buf; msg.len = 2; msg.flags = 0; ret = i2c_transfer(a, &msg, 1); if (ret != 1) return -ENODEV; return 0; } static int kfr2r09_serial_i2c_setup(void) { struct i2c_adapter *a; struct i2c_msg msg; unsigned char buf[2]; int ret; a = i2c_get_adapter(0); if (!a) return -ENODEV; /* set bit 6 (the 7th bit) of chip at 0x09, register 0x13 */ buf[0] = 0x13; msg.addr = 0x09; msg.buf = buf; msg.len = 1; msg.flags = 0; ret = i2c_transfer(a, &msg, 1); if (ret != 1) return -ENODEV; buf[0] = 0; msg.addr = 0x09; msg.buf = buf; msg.len = 1; msg.flags = I2C_M_RD; ret = i2c_transfer(a, &msg, 1); if (ret != 1) return -ENODEV; buf[1] = buf[0] | (1 << 6); buf[0] = 0x13; msg.addr = 0x09; msg.buf = buf; msg.len = 2; msg.flags = 0; ret = i2c_transfer(a, &msg, 1); if (ret != 1) return -ENODEV; return 0; } #else static int kfr2r09_usb0_gadget_i2c_setup(void) { return -ENODEV; } static int kfr2r09_serial_i2c_setup(void) { return -ENODEV; } #endif static int kfr2r09_usb0_gadget_setup(void) { int plugged_in; gpio_request(GPIO_PTN4, NULL); /* USB_DET */ gpio_direction_input(GPIO_PTN4); plugged_in = gpio_get_value(GPIO_PTN4); if (!plugged_in) return -ENODEV; /* no cable plugged in */ if (kfr2r09_usb0_gadget_i2c_setup() != 0) return -ENODEV; /* unable to configure using i2c */ __raw_writew((__raw_readw(PORT_MSELCRB) & ~0xc000) | 0x8000, PORT_MSELCRB); gpio_request(GPIO_FN_PDSTATUS, NULL); /* R-standby disables USB clock */ gpio_request(GPIO_PTV6, NULL); /* USBCLK_ON */ gpio_direction_output(GPIO_PTV6, 1); /* USBCLK_ON = H */ msleep(20); /* wait 20ms to let the clock settle */ clk_enable(clk_get(NULL, "usb0")); __raw_writew(0x0600, 0xa40501d4); return 0; } extern char kfr2r09_sdram_enter_start; extern char kfr2r09_sdram_enter_end; extern char kfr2r09_sdram_leave_start; extern char kfr2r09_sdram_leave_end; static int __init kfr2r09_devices_setup(void) { /* register board specific self-refresh code */ sh_mobile_register_self_refresh(SUSP_SH_STANDBY | SUSP_SH_SF | SUSP_SH_RSTANDBY, &kfr2r09_sdram_enter_start, &kfr2r09_sdram_enter_end, &kfr2r09_sdram_leave_start, &kfr2r09_sdram_leave_end); regulator_register_always_on(0, "fixed-3.3V", fixed3v3_power_consumers, ARRAY_SIZE(fixed3v3_power_consumers), 3300000); /* enable SCIF1 serial port for YC401 console support */ gpio_request(GPIO_FN_SCIF1_RXD, NULL); gpio_request(GPIO_FN_SCIF1_TXD, NULL); kfr2r09_serial_i2c_setup(); /* ECONTMSK(bit6=L10ONEN) set 1 */ gpio_request(GPIO_PTG3, NULL); /* HPON_ON */ gpio_direction_output(GPIO_PTG3, 1); /* HPON_ON = H */ /* setup NOR flash at CS0 */ __raw_writel(0x36db0400, BSC_CS0BCR); __raw_writel(0x00000500, BSC_CS0WCR); /* setup NAND flash at CS4 */ __raw_writel(0x36db0400, BSC_CS4BCR); __raw_writel(0x00000500, BSC_CS4WCR); /* setup KEYSC pins */ gpio_request(GPIO_FN_KEYOUT0, NULL); gpio_request(GPIO_FN_KEYOUT1, NULL); gpio_request(GPIO_FN_KEYOUT2, NULL); gpio_request(GPIO_FN_KEYOUT3, NULL); gpio_request(GPIO_FN_KEYOUT4_IN6, NULL); gpio_request(GPIO_FN_KEYIN0, NULL); gpio_request(GPIO_FN_KEYIN1, NULL); gpio_request(GPIO_FN_KEYIN2, NULL); gpio_request(GPIO_FN_KEYIN3, NULL); gpio_request(GPIO_FN_KEYIN4, NULL); gpio_request(GPIO_FN_KEYOUT5_IN5, NULL); /* setup LCDC pins for SYS panel */ gpio_request(GPIO_FN_LCDD17, NULL); gpio_request(GPIO_FN_LCDD16, NULL); gpio_request(GPIO_FN_LCDD15, NULL); gpio_request(GPIO_FN_LCDD14, NULL); gpio_request(GPIO_FN_LCDD13, NULL); gpio_request(GPIO_FN_LCDD12, NULL); gpio_request(GPIO_FN_LCDD11, NULL); gpio_request(GPIO_FN_LCDD10, NULL); gpio_request(GPIO_FN_LCDD9, NULL); gpio_request(GPIO_FN_LCDD8, NULL); gpio_request(GPIO_FN_LCDD7, NULL); gpio_request(GPIO_FN_LCDD6, NULL); gpio_request(GPIO_FN_LCDD5, NULL); gpio_request(GPIO_FN_LCDD4, NULL); gpio_request(GPIO_FN_LCDD3, NULL); gpio_request(GPIO_FN_LCDD2, NULL); gpio_request(GPIO_FN_LCDD1, NULL); gpio_request(GPIO_FN_LCDD0, NULL); gpio_request(GPIO_FN_LCDRS, NULL); /* LCD_RS */ gpio_request(GPIO_FN_LCDCS, NULL); /* LCD_CS/ */ gpio_request(GPIO_FN_LCDRD, NULL); /* LCD_RD/ */ gpio_request(GPIO_FN_LCDWR, NULL); /* LCD_WR/ */ gpio_request(GPIO_FN_LCDVSYN, NULL); /* LCD_VSYNC */ gpio_request(GPIO_PTE4, NULL); /* LCD_RST/ */ gpio_direction_output(GPIO_PTE4, 1); gpio_request(GPIO_PTF4, NULL); /* PROTECT/ */ gpio_direction_output(GPIO_PTF4, 1); gpio_request(GPIO_PTU0, NULL); /* LEDSTDBY/ */ gpio_direction_output(GPIO_PTU0, 1); /* setup USB function */ if (kfr2r09_usb0_gadget_setup() == 0) platform_device_register(&kfr2r09_usb0_gadget_device); /* CEU */ gpio_request(GPIO_FN_VIO_CKO, NULL); gpio_request(GPIO_FN_VIO0_CLK, NULL); gpio_request(GPIO_FN_VIO0_VD, NULL); gpio_request(GPIO_FN_VIO0_HD, NULL); gpio_request(GPIO_FN_VIO0_FLD, NULL); gpio_request(GPIO_FN_VIO0_D7, NULL); gpio_request(GPIO_FN_VIO0_D6, NULL); gpio_request(GPIO_FN_VIO0_D5, NULL); gpio_request(GPIO_FN_VIO0_D4, NULL); gpio_request(GPIO_FN_VIO0_D3, NULL); gpio_request(GPIO_FN_VIO0_D2, NULL); gpio_request(GPIO_FN_VIO0_D1, NULL); gpio_request(GPIO_FN_VIO0_D0, NULL); platform_resource_setup_memory(&kfr2r09_ceu_device, "ceu", 4 << 20); /* SDHI0 connected to yc304 */ gpio_request(GPIO_FN_SDHI0CD, NULL); gpio_request(GPIO_FN_SDHI0D3, NULL); gpio_request(GPIO_FN_SDHI0D2, NULL); gpio_request(GPIO_FN_SDHI0D1, NULL); gpio_request(GPIO_FN_SDHI0D0, NULL); gpio_request(GPIO_FN_SDHI0CMD, NULL); gpio_request(GPIO_FN_SDHI0CLK, NULL); i2c_register_board_info(0, &kfr2r09_backlight_board_info, 1); return platform_add_devices(kfr2r09_devices, ARRAY_SIZE(kfr2r09_devices)); } device_initcall(kfr2r09_devices_setup); /* Return the board specific boot mode pin configuration */ static int kfr2r09_mode_pins(void) { /* MD0=1, MD1=1, MD2=0: Clock Mode 3 * MD3=0: 16-bit Area0 Bus Width * MD5=1: Little Endian * MD8=1: Test Mode Disabled */ return MODE_PIN0 | MODE_PIN1 | MODE_PIN5 | MODE_PIN8; } /* * The Machine Vector */ static struct sh_machine_vector mv_kfr2r09 __initmv = { .mv_name = "kfr2r09", .mv_mode_pins = kfr2r09_mode_pins, };
null
null
null
null
90,052
1,045
null
train_val
1b0d3845b454eaaac0b2064c78926ca4d739a080
263,613
qemu
0
https://github.com/bonzini/qemu
2016-10-18 11:40:27+01:00
#include "io.h" int main(void) { long long rs, rt, dspreg, dspresult; rs = 0x123456789ABCDEFF; rt = 0x123456789ABCDEFF; dspresult = 0x03; __asm ("cmp.eq.pw %1, %2\n\t" "rddsp %0\n\t" : "=r"(dspreg) : "r"(rs), "r"(rt) ); dspreg = ((dspreg >> 24) & 0x03); if (dspreg != dspresult) { printf("1 cmp.eq.pw error\n"); return -1; } rs = 0x123456799ABCDEFe; rt = 0x123456789ABCDEFF; dspresult = 0x00; __asm ("cmp.eq.pw %1, %2\n\t" "rddsp %0\n\t" : "=r"(dspreg) : "r"(rs), "r"(rt) ); dspreg = ((dspreg >> 24) & 0x03); if (dspreg != dspresult) { printf("2 cmp.eq.pw error\n"); return -1; } return 0; }
null
null
null
null
121,737
7,803
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
172,798
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * cppc_msr.c: MSR Interface for CPPC * Copyright (c) 2016, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope 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 <acpi/cppc_acpi.h> #include <asm/msr.h> /* Refer to drivers/acpi/cppc_acpi.c for the description of functions */ bool cpc_ffh_supported(void) { return true; } int cpc_read_ffh(int cpunum, struct cpc_reg *reg, u64 *val) { int err; err = rdmsrl_safe_on_cpu(cpunum, reg->address, val); if (!err) { u64 mask = GENMASK_ULL(reg->bit_offset + reg->bit_width - 1, reg->bit_offset); *val &= mask; *val >>= reg->bit_offset; } return err; } int cpc_write_ffh(int cpunum, struct cpc_reg *reg, u64 val) { u64 rd_val; int err; err = rdmsrl_safe_on_cpu(cpunum, reg->address, &rd_val); if (!err) { u64 mask = GENMASK_ULL(reg->bit_offset + reg->bit_width - 1, reg->bit_offset); val <<= reg->bit_offset; val &= mask; rd_val &= ~mask; rd_val |= val; err = wrmsrl_safe_on_cpu(cpunum, reg->address, rd_val); } return err; }
null
null
null
null
81,145
16,569
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
16,569
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 COMPONENTS_INVALIDATION_IMPL_INVALIDATION_SWITCHES_H #define COMPONENTS_INVALIDATION_IMPL_INVALIDATION_SWITCHES_H namespace invalidation { namespace switches { extern const char kInvalidationUseGCMChannel[]; extern const char kSyncNotificationHostPort[]; extern const char kSyncAllowInsecureXmppConnection[]; } // namespace switches } // namespace invalidation #endif // COMPONENTS_INVALIDATION_IMPL_INVALIDATION_SWITCHES_H
null
null
null
null
13,432
34,666
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
199,661
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* cx231xx-core.c - driver for Conexant Cx23100/101/102 USB video capture devices Copyright (C) 2008 <srinivasa.deevi at conexant dot com> Based on em28xx driver 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cx231xx.h" #include <linux/init.h> #include <linux/list.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/vmalloc.h> #include <media/v4l2-common.h> #include <media/tuner.h> #include "cx231xx-reg.h" /* #define ENABLE_DEBUG_ISOC_FRAMES */ static unsigned int core_debug; module_param(core_debug, int, 0644); MODULE_PARM_DESC(core_debug, "enable debug messages [core]"); #define cx231xx_coredbg(fmt, arg...) do {\ if (core_debug) \ printk(KERN_INFO "%s %s :"fmt, \ dev->name, __func__ , ##arg); } while (0) static unsigned int reg_debug; module_param(reg_debug, int, 0644); MODULE_PARM_DESC(reg_debug, "enable debug messages [URB reg]"); static int alt = CX231XX_PINOUT; module_param(alt, int, 0644); MODULE_PARM_DESC(alt, "alternate setting to use for video endpoint"); #define cx231xx_isocdbg(fmt, arg...) do {\ if (core_debug) \ printk(KERN_INFO "%s %s :"fmt, \ dev->name, __func__ , ##arg); } while (0) /***************************************************************** * Device control list functions * ******************************************************************/ LIST_HEAD(cx231xx_devlist); static DEFINE_MUTEX(cx231xx_devlist_mutex); /* * cx231xx_realease_resources() * unregisters the v4l2,i2c and usb devices * called when the device gets disconected or at module unload */ void cx231xx_remove_from_devlist(struct cx231xx *dev) { if (dev == NULL) return; if (dev->udev == NULL) return; if (atomic_read(&dev->devlist_count) > 0) { mutex_lock(&cx231xx_devlist_mutex); list_del(&dev->devlist); atomic_dec(&dev->devlist_count); mutex_unlock(&cx231xx_devlist_mutex); } }; void cx231xx_add_into_devlist(struct cx231xx *dev) { mutex_lock(&cx231xx_devlist_mutex); list_add_tail(&dev->devlist, &cx231xx_devlist); atomic_inc(&dev->devlist_count); mutex_unlock(&cx231xx_devlist_mutex); }; static LIST_HEAD(cx231xx_extension_devlist); int cx231xx_register_extension(struct cx231xx_ops *ops) { struct cx231xx *dev = NULL; mutex_lock(&cx231xx_devlist_mutex); list_add_tail(&ops->next, &cx231xx_extension_devlist); list_for_each_entry(dev, &cx231xx_devlist, devlist) { ops->init(dev); dev_info(dev->dev, "%s initialized\n", ops->name); } mutex_unlock(&cx231xx_devlist_mutex); return 0; } EXPORT_SYMBOL(cx231xx_register_extension); void cx231xx_unregister_extension(struct cx231xx_ops *ops) { struct cx231xx *dev = NULL; mutex_lock(&cx231xx_devlist_mutex); list_for_each_entry(dev, &cx231xx_devlist, devlist) { ops->fini(dev); dev_info(dev->dev, "%s removed\n", ops->name); } list_del(&ops->next); mutex_unlock(&cx231xx_devlist_mutex); } EXPORT_SYMBOL(cx231xx_unregister_extension); void cx231xx_init_extension(struct cx231xx *dev) { struct cx231xx_ops *ops = NULL; mutex_lock(&cx231xx_devlist_mutex); if (!list_empty(&cx231xx_extension_devlist)) { list_for_each_entry(ops, &cx231xx_extension_devlist, next) { if (ops->init) ops->init(dev); } } mutex_unlock(&cx231xx_devlist_mutex); } void cx231xx_close_extension(struct cx231xx *dev) { struct cx231xx_ops *ops = NULL; mutex_lock(&cx231xx_devlist_mutex); if (!list_empty(&cx231xx_extension_devlist)) { list_for_each_entry(ops, &cx231xx_extension_devlist, next) { if (ops->fini) ops->fini(dev); } } mutex_unlock(&cx231xx_devlist_mutex); } /**************************************************************** * U S B related functions * *****************************************************************/ int cx231xx_send_usb_command(struct cx231xx_i2c *i2c_bus, struct cx231xx_i2c_xfer_data *req_data) { int status = 0; struct cx231xx *dev = i2c_bus->dev; struct VENDOR_REQUEST_IN ven_req; u8 saddr_len = 0; u8 _i2c_period = 0; u8 _i2c_nostop = 0; u8 _i2c_reserve = 0; if (dev->state & DEV_DISCONNECTED) return -ENODEV; /* Get the I2C period, nostop and reserve parameters */ _i2c_period = i2c_bus->i2c_period; _i2c_nostop = i2c_bus->i2c_nostop; _i2c_reserve = i2c_bus->i2c_reserve; saddr_len = req_data->saddr_len; /* Set wValue */ ven_req.wValue = (req_data->dev_addr << 9 | _i2c_period << 4 | saddr_len << 2 | _i2c_nostop << 1 | I2C_SYNC | _i2c_reserve << 6); /* set channel number */ if (req_data->direction & I2C_M_RD) { /* channel number, for read,spec required channel_num +4 */ ven_req.bRequest = i2c_bus->nr + 4; } else ven_req.bRequest = i2c_bus->nr; /* channel number, */ /* set index value */ switch (saddr_len) { case 0: ven_req.wIndex = 0; /* need check */ break; case 1: ven_req.wIndex = (req_data->saddr_dat & 0xff); break; case 2: ven_req.wIndex = req_data->saddr_dat; break; } /* set wLength value */ ven_req.wLength = req_data->buf_size; /* set bData value */ ven_req.bData = 0; /* set the direction */ if (req_data->direction) { ven_req.direction = USB_DIR_IN; memset(req_data->p_buffer, 0x00, ven_req.wLength); } else ven_req.direction = USB_DIR_OUT; /* set the buffer for read / write */ ven_req.pBuff = req_data->p_buffer; /* call common vendor command request */ status = cx231xx_send_vendor_cmd(dev, &ven_req); if (status < 0 && !dev->i2c_scan_running) { dev_err(dev->dev, "%s: failed with status -%d\n", __func__, status); } return status; } EXPORT_SYMBOL_GPL(cx231xx_send_usb_command); /* * Sends/Receives URB control messages, assuring to use a kalloced buffer * for all operations (dev->urb_buf), to avoid using stacked buffers, as * they aren't safe for usage with USB, due to DMA restrictions. * Also implements the debug code for control URB's. */ static int __usb_control_msg(struct cx231xx *dev, unsigned int pipe, __u8 request, __u8 requesttype, __u16 value, __u16 index, void *data, __u16 size, int timeout) { int rc, i; if (reg_debug) { printk(KERN_DEBUG "%s: (pipe 0x%08x): %s: %02x %02x %02x %02x %02x %02x %02x %02x ", dev->name, pipe, (requesttype & USB_DIR_IN) ? "IN" : "OUT", requesttype, request, value & 0xff, value >> 8, index & 0xff, index >> 8, size & 0xff, size >> 8); if (!(requesttype & USB_DIR_IN)) { printk(KERN_CONT ">>>"); for (i = 0; i < size; i++) printk(KERN_CONT " %02x", ((unsigned char *)data)[i]); } } /* Do the real call to usb_control_msg */ mutex_lock(&dev->ctrl_urb_lock); if (!(requesttype & USB_DIR_IN) && size) memcpy(dev->urb_buf, data, size); rc = usb_control_msg(dev->udev, pipe, request, requesttype, value, index, dev->urb_buf, size, timeout); if ((requesttype & USB_DIR_IN) && size) memcpy(data, dev->urb_buf, size); mutex_unlock(&dev->ctrl_urb_lock); if (reg_debug) { if (unlikely(rc < 0)) { printk(KERN_CONT "FAILED!\n"); return rc; } if ((requesttype & USB_DIR_IN)) { printk(KERN_CONT "<<<"); for (i = 0; i < size; i++) printk(KERN_CONT " %02x", ((unsigned char *)data)[i]); } printk(KERN_CONT "\n"); } return rc; } /* * cx231xx_read_ctrl_reg() * reads data from the usb device specifying bRequest and wValue */ int cx231xx_read_ctrl_reg(struct cx231xx *dev, u8 req, u16 reg, char *buf, int len) { u8 val = 0; int ret; int pipe = usb_rcvctrlpipe(dev->udev, 0); if (dev->state & DEV_DISCONNECTED) return -ENODEV; if (len > URB_MAX_CTRL_SIZE) return -EINVAL; switch (len) { case 1: val = ENABLE_ONE_BYTE; break; case 2: val = ENABLE_TWE_BYTE; break; case 3: val = ENABLE_THREE_BYTE; break; case 4: val = ENABLE_FOUR_BYTE; break; default: val = 0xFF; /* invalid option */ } if (val == 0xFF) return -EINVAL; ret = __usb_control_msg(dev, pipe, req, USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE, val, reg, buf, len, HZ); return ret; } int cx231xx_send_vendor_cmd(struct cx231xx *dev, struct VENDOR_REQUEST_IN *ven_req) { int ret; int pipe = 0; int unsend_size = 0; u8 *pdata; if (dev->state & DEV_DISCONNECTED) return -ENODEV; if ((ven_req->wLength > URB_MAX_CTRL_SIZE)) return -EINVAL; if (ven_req->direction) pipe = usb_rcvctrlpipe(dev->udev, 0); else pipe = usb_sndctrlpipe(dev->udev, 0); /* * If the cx23102 read more than 4 bytes with i2c bus, * need chop to 4 byte per request */ if ((ven_req->wLength > 4) && ((ven_req->bRequest == 0x4) || (ven_req->bRequest == 0x5) || (ven_req->bRequest == 0x6) || /* Internal Master 3 Bus can send * and receive only 4 bytes per time */ (ven_req->bRequest == 0x2))) { unsend_size = 0; pdata = ven_req->pBuff; unsend_size = ven_req->wLength; /* the first package */ ven_req->wValue = ven_req->wValue & 0xFFFB; ven_req->wValue = (ven_req->wValue & 0xFFBD) | 0x2; ret = __usb_control_msg(dev, pipe, ven_req->bRequest, ven_req->direction | USB_TYPE_VENDOR | USB_RECIP_DEVICE, ven_req->wValue, ven_req->wIndex, pdata, 0x0004, HZ); unsend_size = unsend_size - 4; /* the middle package */ ven_req->wValue = (ven_req->wValue & 0xFFBD) | 0x42; while (unsend_size - 4 > 0) { pdata = pdata + 4; ret = __usb_control_msg(dev, pipe, ven_req->bRequest, ven_req->direction | USB_TYPE_VENDOR | USB_RECIP_DEVICE, ven_req->wValue, ven_req->wIndex, pdata, 0x0004, HZ); unsend_size = unsend_size - 4; } /* the last package */ ven_req->wValue = (ven_req->wValue & 0xFFBD) | 0x40; pdata = pdata + 4; ret = __usb_control_msg(dev, pipe, ven_req->bRequest, ven_req->direction | USB_TYPE_VENDOR | USB_RECIP_DEVICE, ven_req->wValue, ven_req->wIndex, pdata, unsend_size, HZ); } else { ret = __usb_control_msg(dev, pipe, ven_req->bRequest, ven_req->direction | USB_TYPE_VENDOR | USB_RECIP_DEVICE, ven_req->wValue, ven_req->wIndex, ven_req->pBuff, ven_req->wLength, HZ); } return ret; } /* * cx231xx_write_ctrl_reg() * sends data to the usb device, specifying bRequest */ int cx231xx_write_ctrl_reg(struct cx231xx *dev, u8 req, u16 reg, char *buf, int len) { u8 val = 0; int ret; int pipe = usb_sndctrlpipe(dev->udev, 0); if (dev->state & DEV_DISCONNECTED) return -ENODEV; if ((len < 1) || (len > URB_MAX_CTRL_SIZE)) return -EINVAL; switch (len) { case 1: val = ENABLE_ONE_BYTE; break; case 2: val = ENABLE_TWE_BYTE; break; case 3: val = ENABLE_THREE_BYTE; break; case 4: val = ENABLE_FOUR_BYTE; break; default: val = 0xFF; /* invalid option */ } if (val == 0xFF) return -EINVAL; if (reg_debug) { int byte; cx231xx_isocdbg("(pipe 0x%08x): OUT: %02x %02x %02x %02x %02x %02x %02x %02x >>>", pipe, USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE, req, 0, val, reg & 0xff, reg >> 8, len & 0xff, len >> 8); for (byte = 0; byte < len; byte++) cx231xx_isocdbg(" %02x", (unsigned char)buf[byte]); cx231xx_isocdbg("\n"); } ret = __usb_control_msg(dev, pipe, req, USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE, val, reg, buf, len, HZ); return ret; } /**************************************************************** * USB Alternate Setting functions * *****************************************************************/ int cx231xx_set_video_alternate(struct cx231xx *dev) { int errCode, prev_alt = dev->video_mode.alt; unsigned int min_pkt_size = dev->width * 2 + 4; u32 usb_interface_index = 0; /* When image size is bigger than a certain value, the frame size should be increased, otherwise, only green screen will be received. */ if (dev->width * 2 * dev->height > 720 * 240 * 2) min_pkt_size *= 2; if (dev->width > 360) { /* resolutions: 720,704,640 */ dev->video_mode.alt = 3; } else if (dev->width > 180) { /* resolutions: 360,352,320,240 */ dev->video_mode.alt = 2; } else if (dev->width > 0) { /* resolutions: 180,176,160,128,88 */ dev->video_mode.alt = 1; } else { /* Change to alt0 BULK to release USB bandwidth */ dev->video_mode.alt = 0; } if (dev->USE_ISO == 0) dev->video_mode.alt = 0; cx231xx_coredbg("dev->video_mode.alt= %d\n", dev->video_mode.alt); /* Get the correct video interface Index */ usb_interface_index = dev->current_pcb_config.hs_config_info[0].interface_info. video_index + 1; if (dev->video_mode.alt != prev_alt) { cx231xx_coredbg("minimum isoc packet size: %u (alt=%d)\n", min_pkt_size, dev->video_mode.alt); if (dev->video_mode.alt_max_pkt_size != NULL) dev->video_mode.max_pkt_size = dev->video_mode.alt_max_pkt_size[dev->video_mode.alt]; cx231xx_coredbg("setting alternate %d with wMaxPacketSize=%u\n", dev->video_mode.alt, dev->video_mode.max_pkt_size); errCode = usb_set_interface(dev->udev, usb_interface_index, dev->video_mode.alt); if (errCode < 0) { dev_err(dev->dev, "cannot change alt number to %d (error=%i)\n", dev->video_mode.alt, errCode); return errCode; } } return 0; } int cx231xx_set_alt_setting(struct cx231xx *dev, u8 index, u8 alt) { int status = 0; u32 usb_interface_index = 0; u32 max_pkt_size = 0; switch (index) { case INDEX_TS1: usb_interface_index = dev->current_pcb_config.hs_config_info[0].interface_info. ts1_index + 1; dev->ts1_mode.alt = alt; if (dev->ts1_mode.alt_max_pkt_size != NULL) max_pkt_size = dev->ts1_mode.max_pkt_size = dev->ts1_mode.alt_max_pkt_size[dev->ts1_mode.alt]; break; case INDEX_TS2: usb_interface_index = dev->current_pcb_config.hs_config_info[0].interface_info. ts2_index + 1; break; case INDEX_AUDIO: usb_interface_index = dev->current_pcb_config.hs_config_info[0].interface_info. audio_index + 1; dev->adev.alt = alt; if (dev->adev.alt_max_pkt_size != NULL) max_pkt_size = dev->adev.max_pkt_size = dev->adev.alt_max_pkt_size[dev->adev.alt]; break; case INDEX_VIDEO: usb_interface_index = dev->current_pcb_config.hs_config_info[0].interface_info. video_index + 1; dev->video_mode.alt = alt; if (dev->video_mode.alt_max_pkt_size != NULL) max_pkt_size = dev->video_mode.max_pkt_size = dev->video_mode.alt_max_pkt_size[dev->video_mode. alt]; break; case INDEX_VANC: if (dev->board.no_alt_vanc) return 0; usb_interface_index = dev->current_pcb_config.hs_config_info[0].interface_info. vanc_index + 1; dev->vbi_mode.alt = alt; if (dev->vbi_mode.alt_max_pkt_size != NULL) max_pkt_size = dev->vbi_mode.max_pkt_size = dev->vbi_mode.alt_max_pkt_size[dev->vbi_mode.alt]; break; case INDEX_HANC: usb_interface_index = dev->current_pcb_config.hs_config_info[0].interface_info. hanc_index + 1; dev->sliced_cc_mode.alt = alt; if (dev->sliced_cc_mode.alt_max_pkt_size != NULL) max_pkt_size = dev->sliced_cc_mode.max_pkt_size = dev->sliced_cc_mode.alt_max_pkt_size[dev-> sliced_cc_mode. alt]; break; default: break; } if (alt > 0 && max_pkt_size == 0) { dev_err(dev->dev, "can't change interface %d alt no. to %d: Max. Pkt size = 0\n", usb_interface_index, alt); /*To workaround error number=-71 on EP0 for videograbber, need add following codes.*/ if (dev->board.no_alt_vanc) return -1; } cx231xx_coredbg("setting alternate %d with wMaxPacketSize=%u,Interface = %d\n", alt, max_pkt_size, usb_interface_index); if (usb_interface_index > 0) { status = usb_set_interface(dev->udev, usb_interface_index, alt); if (status < 0) { dev_err(dev->dev, "can't change interface %d alt no. to %d (err=%i)\n", usb_interface_index, alt, status); return status; } } return status; } EXPORT_SYMBOL_GPL(cx231xx_set_alt_setting); int cx231xx_gpio_set(struct cx231xx *dev, struct cx231xx_reg_seq *gpio) { int rc = 0; if (!gpio) return rc; /* Send GPIO reset sequences specified at board entry */ while (gpio->sleep >= 0) { rc = cx231xx_set_gpio_value(dev, gpio->bit, gpio->val); if (rc < 0) return rc; if (gpio->sleep > 0) msleep(gpio->sleep); gpio++; } return rc; } int cx231xx_demod_reset(struct cx231xx *dev) { u8 status = 0; u8 value[4] = { 0, 0, 0, 0 }; status = cx231xx_read_ctrl_reg(dev, VRT_GET_REGISTER, PWR_CTL_EN, value, 4); cx231xx_coredbg("reg0x%x=0x%x 0x%x 0x%x 0x%x\n", PWR_CTL_EN, value[0], value[1], value[2], value[3]); cx231xx_coredbg("Enter cx231xx_demod_reset()\n"); value[1] = (u8) 0x3; status = cx231xx_write_ctrl_reg(dev, VRT_SET_REGISTER, PWR_CTL_EN, value, 4); msleep(10); value[1] = (u8) 0x0; status = cx231xx_write_ctrl_reg(dev, VRT_SET_REGISTER, PWR_CTL_EN, value, 4); msleep(10); value[1] = (u8) 0x3; status = cx231xx_write_ctrl_reg(dev, VRT_SET_REGISTER, PWR_CTL_EN, value, 4); msleep(10); status = cx231xx_read_ctrl_reg(dev, VRT_GET_REGISTER, PWR_CTL_EN, value, 4); cx231xx_coredbg("reg0x%x=0x%x 0x%x 0x%x 0x%x\n", PWR_CTL_EN, value[0], value[1], value[2], value[3]); return status; } EXPORT_SYMBOL_GPL(cx231xx_demod_reset); int is_fw_load(struct cx231xx *dev) { return cx231xx_check_fw(dev); } EXPORT_SYMBOL_GPL(is_fw_load); int cx231xx_set_mode(struct cx231xx *dev, enum cx231xx_mode set_mode) { int errCode = 0; if (dev->mode == set_mode) return 0; if (set_mode == CX231XX_SUSPEND) { /* Set the chip in power saving mode */ dev->mode = set_mode; } /* Resource is locked */ if (dev->mode != CX231XX_SUSPEND) return -EINVAL; dev->mode = set_mode; if (dev->mode == CX231XX_DIGITAL_MODE)/* Set Digital power mode */ { /* set AGC mode to Digital */ switch (dev->model) { case CX231XX_BOARD_CNXT_CARRAERA: case CX231XX_BOARD_CNXT_RDE_250: case CX231XX_BOARD_CNXT_SHELBY: case CX231XX_BOARD_CNXT_RDU_250: errCode = cx231xx_set_agc_analog_digital_mux_select(dev, 0); break; case CX231XX_BOARD_CNXT_RDE_253S: case CX231XX_BOARD_CNXT_RDU_253S: case CX231XX_BOARD_PV_PLAYTV_USB_HYBRID: errCode = cx231xx_set_agc_analog_digital_mux_select(dev, 1); break; case CX231XX_BOARD_HAUPPAUGE_EXETER: case CX231XX_BOARD_HAUPPAUGE_930C_HD_1113xx: errCode = cx231xx_set_power_mode(dev, POLARIS_AVMODE_DIGITAL); break; default: break; } } else/* Set Analog Power mode */ { /* set AGC mode to Analog */ switch (dev->model) { case CX231XX_BOARD_CNXT_CARRAERA: case CX231XX_BOARD_CNXT_RDE_250: case CX231XX_BOARD_CNXT_SHELBY: case CX231XX_BOARD_CNXT_RDU_250: errCode = cx231xx_set_agc_analog_digital_mux_select(dev, 1); break; case CX231XX_BOARD_CNXT_RDE_253S: case CX231XX_BOARD_CNXT_RDU_253S: case CX231XX_BOARD_HAUPPAUGE_EXETER: case CX231XX_BOARD_HAUPPAUGE_930C_HD_1113xx: case CX231XX_BOARD_PV_PLAYTV_USB_HYBRID: case CX231XX_BOARD_HAUPPAUGE_USB2_FM_PAL: case CX231XX_BOARD_HAUPPAUGE_USB2_FM_NTSC: errCode = cx231xx_set_agc_analog_digital_mux_select(dev, 0); break; default: break; } } if (errCode < 0) { dev_err(dev->dev, "Failed to set devmode to %s: error: %i", dev->mode == CX231XX_DIGITAL_MODE ? "digital" : "analog", errCode); return errCode; } return 0; } EXPORT_SYMBOL_GPL(cx231xx_set_mode); int cx231xx_ep5_bulkout(struct cx231xx *dev, u8 *firmware, u16 size) { int errCode = 0; int actlen = -1; int ret = -ENOMEM; u32 *buffer; buffer = kzalloc(4096, GFP_KERNEL); if (buffer == NULL) return -ENOMEM; memcpy(&buffer[0], firmware, 4096); ret = usb_bulk_msg(dev->udev, usb_sndbulkpipe(dev->udev, 5), buffer, 4096, &actlen, 2000); if (ret) dev_err(dev->dev, "bulk message failed: %d (%d/%d)", ret, size, actlen); else { errCode = actlen != size ? -1 : 0; } kfree(buffer); return errCode; } /***************************************************************** * URB Streaming functions * ******************************************************************/ /* * IRQ callback, called by URB callback */ static void cx231xx_isoc_irq_callback(struct urb *urb) { struct cx231xx_dmaqueue *dma_q = urb->context; struct cx231xx_video_mode *vmode = container_of(dma_q, struct cx231xx_video_mode, vidq); struct cx231xx *dev = container_of(vmode, struct cx231xx, video_mode); int i; switch (urb->status) { case 0: /* success */ case -ETIMEDOUT: /* NAK */ break; case -ECONNRESET: /* kill */ case -ENOENT: case -ESHUTDOWN: return; default: /* error */ cx231xx_isocdbg("urb completion error %d.\n", urb->status); break; } /* Copy data from URB */ spin_lock(&dev->video_mode.slock); dev->video_mode.isoc_ctl.isoc_copy(dev, urb); spin_unlock(&dev->video_mode.slock); /* Reset urb buffers */ for (i = 0; i < urb->number_of_packets; i++) { urb->iso_frame_desc[i].status = 0; urb->iso_frame_desc[i].actual_length = 0; } urb->status = usb_submit_urb(urb, GFP_ATOMIC); if (urb->status) { cx231xx_isocdbg("urb resubmit failed (error=%i)\n", urb->status); } } /***************************************************************** * URB Streaming functions * ******************************************************************/ /* * IRQ callback, called by URB callback */ static void cx231xx_bulk_irq_callback(struct urb *urb) { struct cx231xx_dmaqueue *dma_q = urb->context; struct cx231xx_video_mode *vmode = container_of(dma_q, struct cx231xx_video_mode, vidq); struct cx231xx *dev = container_of(vmode, struct cx231xx, video_mode); switch (urb->status) { case 0: /* success */ case -ETIMEDOUT: /* NAK */ break; case -ECONNRESET: /* kill */ case -ENOENT: case -ESHUTDOWN: return; case -EPIPE: /* stall */ cx231xx_isocdbg("urb completion error - device is stalled.\n"); return; default: /* error */ cx231xx_isocdbg("urb completion error %d.\n", urb->status); break; } /* Copy data from URB */ spin_lock(&dev->video_mode.slock); dev->video_mode.bulk_ctl.bulk_copy(dev, urb); spin_unlock(&dev->video_mode.slock); /* Reset urb buffers */ urb->status = usb_submit_urb(urb, GFP_ATOMIC); if (urb->status) { cx231xx_isocdbg("urb resubmit failed (error=%i)\n", urb->status); } } /* * Stop and Deallocate URBs */ void cx231xx_uninit_isoc(struct cx231xx *dev) { struct cx231xx_dmaqueue *dma_q = &dev->video_mode.vidq; struct urb *urb; int i; bool broken_pipe = false; cx231xx_isocdbg("cx231xx: called cx231xx_uninit_isoc\n"); dev->video_mode.isoc_ctl.nfields = -1; for (i = 0; i < dev->video_mode.isoc_ctl.num_bufs; i++) { urb = dev->video_mode.isoc_ctl.urb[i]; if (urb) { if (!irqs_disabled()) usb_kill_urb(urb); else usb_unlink_urb(urb); if (dev->video_mode.isoc_ctl.transfer_buffer[i]) { usb_free_coherent(dev->udev, urb->transfer_buffer_length, dev->video_mode.isoc_ctl. transfer_buffer[i], urb->transfer_dma); } if (urb->status == -EPIPE) { broken_pipe = true; } usb_free_urb(urb); dev->video_mode.isoc_ctl.urb[i] = NULL; } dev->video_mode.isoc_ctl.transfer_buffer[i] = NULL; } if (broken_pipe) { cx231xx_isocdbg("Reset endpoint to recover broken pipe."); usb_reset_endpoint(dev->udev, dev->video_mode.end_point_addr); } kfree(dev->video_mode.isoc_ctl.urb); kfree(dev->video_mode.isoc_ctl.transfer_buffer); kfree(dma_q->p_left_data); dev->video_mode.isoc_ctl.urb = NULL; dev->video_mode.isoc_ctl.transfer_buffer = NULL; dev->video_mode.isoc_ctl.num_bufs = 0; dma_q->p_left_data = NULL; if (dev->mode_tv == 0) cx231xx_capture_start(dev, 0, Raw_Video); else cx231xx_capture_start(dev, 0, TS1_serial_mode); } EXPORT_SYMBOL_GPL(cx231xx_uninit_isoc); /* * Stop and Deallocate URBs */ void cx231xx_uninit_bulk(struct cx231xx *dev) { struct cx231xx_dmaqueue *dma_q = &dev->video_mode.vidq; struct urb *urb; int i; bool broken_pipe = false; cx231xx_isocdbg("cx231xx: called cx231xx_uninit_bulk\n"); dev->video_mode.bulk_ctl.nfields = -1; for (i = 0; i < dev->video_mode.bulk_ctl.num_bufs; i++) { urb = dev->video_mode.bulk_ctl.urb[i]; if (urb) { if (!irqs_disabled()) usb_kill_urb(urb); else usb_unlink_urb(urb); if (dev->video_mode.bulk_ctl.transfer_buffer[i]) { usb_free_coherent(dev->udev, urb->transfer_buffer_length, dev->video_mode.bulk_ctl. transfer_buffer[i], urb->transfer_dma); } if (urb->status == -EPIPE) { broken_pipe = true; } usb_free_urb(urb); dev->video_mode.bulk_ctl.urb[i] = NULL; } dev->video_mode.bulk_ctl.transfer_buffer[i] = NULL; } if (broken_pipe) { cx231xx_isocdbg("Reset endpoint to recover broken pipe."); usb_reset_endpoint(dev->udev, dev->video_mode.end_point_addr); } kfree(dev->video_mode.bulk_ctl.urb); kfree(dev->video_mode.bulk_ctl.transfer_buffer); kfree(dma_q->p_left_data); dev->video_mode.bulk_ctl.urb = NULL; dev->video_mode.bulk_ctl.transfer_buffer = NULL; dev->video_mode.bulk_ctl.num_bufs = 0; dma_q->p_left_data = NULL; if (dev->mode_tv == 0) cx231xx_capture_start(dev, 0, Raw_Video); else cx231xx_capture_start(dev, 0, TS1_serial_mode); } EXPORT_SYMBOL_GPL(cx231xx_uninit_bulk); /* * Allocate URBs and start IRQ */ int cx231xx_init_isoc(struct cx231xx *dev, int max_packets, int num_bufs, int max_pkt_size, int (*isoc_copy) (struct cx231xx *dev, struct urb *urb)) { struct cx231xx_dmaqueue *dma_q = &dev->video_mode.vidq; int i; int sb_size, pipe; struct urb *urb; int j, k; int rc; /* De-allocates all pending stuff */ cx231xx_uninit_isoc(dev); dma_q->p_left_data = kzalloc(4096, GFP_KERNEL); if (dma_q->p_left_data == NULL) return -ENOMEM; dev->video_mode.isoc_ctl.isoc_copy = isoc_copy; dev->video_mode.isoc_ctl.num_bufs = num_bufs; dma_q->pos = 0; dma_q->is_partial_line = 0; dma_q->last_sav = 0; dma_q->current_field = -1; dma_q->field1_done = 0; dma_q->lines_per_field = dev->height / 2; dma_q->bytes_left_in_line = dev->width << 1; dma_q->lines_completed = 0; dma_q->mpeg_buffer_done = 0; dma_q->left_data_count = 0; dma_q->mpeg_buffer_completed = 0; dma_q->add_ps_package_head = CX231XX_NEED_ADD_PS_PACKAGE_HEAD; dma_q->ps_head[0] = 0x00; dma_q->ps_head[1] = 0x00; dma_q->ps_head[2] = 0x01; dma_q->ps_head[3] = 0xBA; for (i = 0; i < 8; i++) dma_q->partial_buf[i] = 0; dev->video_mode.isoc_ctl.urb = kzalloc(sizeof(void *) * num_bufs, GFP_KERNEL); if (!dev->video_mode.isoc_ctl.urb) { dev_err(dev->dev, "cannot alloc memory for usb buffers\n"); return -ENOMEM; } dev->video_mode.isoc_ctl.transfer_buffer = kzalloc(sizeof(void *) * num_bufs, GFP_KERNEL); if (!dev->video_mode.isoc_ctl.transfer_buffer) { dev_err(dev->dev, "cannot allocate memory for usbtransfer\n"); kfree(dev->video_mode.isoc_ctl.urb); return -ENOMEM; } dev->video_mode.isoc_ctl.max_pkt_size = max_pkt_size; dev->video_mode.isoc_ctl.buf = NULL; sb_size = max_packets * dev->video_mode.isoc_ctl.max_pkt_size; if (dev->mode_tv == 1) dev->video_mode.end_point_addr = 0x81; else dev->video_mode.end_point_addr = 0x84; /* allocate urbs and transfer buffers */ for (i = 0; i < dev->video_mode.isoc_ctl.num_bufs; i++) { urb = usb_alloc_urb(max_packets, GFP_KERNEL); if (!urb) { cx231xx_uninit_isoc(dev); return -ENOMEM; } dev->video_mode.isoc_ctl.urb[i] = urb; dev->video_mode.isoc_ctl.transfer_buffer[i] = usb_alloc_coherent(dev->udev, sb_size, GFP_KERNEL, &urb->transfer_dma); if (!dev->video_mode.isoc_ctl.transfer_buffer[i]) { dev_err(dev->dev, "unable to allocate %i bytes for transfer buffer %i%s\n", sb_size, i, in_interrupt() ? " while in int" : ""); cx231xx_uninit_isoc(dev); return -ENOMEM; } memset(dev->video_mode.isoc_ctl.transfer_buffer[i], 0, sb_size); pipe = usb_rcvisocpipe(dev->udev, dev->video_mode.end_point_addr); usb_fill_int_urb(urb, dev->udev, pipe, dev->video_mode.isoc_ctl.transfer_buffer[i], sb_size, cx231xx_isoc_irq_callback, dma_q, 1); urb->number_of_packets = max_packets; urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP; k = 0; for (j = 0; j < max_packets; j++) { urb->iso_frame_desc[j].offset = k; urb->iso_frame_desc[j].length = dev->video_mode.isoc_ctl.max_pkt_size; k += dev->video_mode.isoc_ctl.max_pkt_size; } } init_waitqueue_head(&dma_q->wq); /* submit urbs and enables IRQ */ for (i = 0; i < dev->video_mode.isoc_ctl.num_bufs; i++) { rc = usb_submit_urb(dev->video_mode.isoc_ctl.urb[i], GFP_ATOMIC); if (rc) { dev_err(dev->dev, "submit of urb %i failed (error=%i)\n", i, rc); cx231xx_uninit_isoc(dev); return rc; } } if (dev->mode_tv == 0) cx231xx_capture_start(dev, 1, Raw_Video); else cx231xx_capture_start(dev, 1, TS1_serial_mode); return 0; } EXPORT_SYMBOL_GPL(cx231xx_init_isoc); /* * Allocate URBs and start IRQ */ int cx231xx_init_bulk(struct cx231xx *dev, int max_packets, int num_bufs, int max_pkt_size, int (*bulk_copy) (struct cx231xx *dev, struct urb *urb)) { struct cx231xx_dmaqueue *dma_q = &dev->video_mode.vidq; int i; int sb_size, pipe; struct urb *urb; int rc; dev->video_input = dev->video_input > 2 ? 2 : dev->video_input; cx231xx_coredbg("Setting Video mux to %d\n", dev->video_input); video_mux(dev, dev->video_input); /* De-allocates all pending stuff */ cx231xx_uninit_bulk(dev); dev->video_mode.bulk_ctl.bulk_copy = bulk_copy; dev->video_mode.bulk_ctl.num_bufs = num_bufs; dma_q->pos = 0; dma_q->is_partial_line = 0; dma_q->last_sav = 0; dma_q->current_field = -1; dma_q->field1_done = 0; dma_q->lines_per_field = dev->height / 2; dma_q->bytes_left_in_line = dev->width << 1; dma_q->lines_completed = 0; dma_q->mpeg_buffer_done = 0; dma_q->left_data_count = 0; dma_q->mpeg_buffer_completed = 0; dma_q->ps_head[0] = 0x00; dma_q->ps_head[1] = 0x00; dma_q->ps_head[2] = 0x01; dma_q->ps_head[3] = 0xBA; for (i = 0; i < 8; i++) dma_q->partial_buf[i] = 0; dev->video_mode.bulk_ctl.urb = kzalloc(sizeof(void *) * num_bufs, GFP_KERNEL); if (!dev->video_mode.bulk_ctl.urb) { dev_err(dev->dev, "cannot alloc memory for usb buffers\n"); return -ENOMEM; } dev->video_mode.bulk_ctl.transfer_buffer = kzalloc(sizeof(void *) * num_bufs, GFP_KERNEL); if (!dev->video_mode.bulk_ctl.transfer_buffer) { dev_err(dev->dev, "cannot allocate memory for usbtransfer\n"); kfree(dev->video_mode.bulk_ctl.urb); return -ENOMEM; } dev->video_mode.bulk_ctl.max_pkt_size = max_pkt_size; dev->video_mode.bulk_ctl.buf = NULL; sb_size = max_packets * dev->video_mode.bulk_ctl.max_pkt_size; if (dev->mode_tv == 1) dev->video_mode.end_point_addr = 0x81; else dev->video_mode.end_point_addr = 0x84; /* allocate urbs and transfer buffers */ for (i = 0; i < dev->video_mode.bulk_ctl.num_bufs; i++) { urb = usb_alloc_urb(0, GFP_KERNEL); if (!urb) { cx231xx_uninit_bulk(dev); return -ENOMEM; } dev->video_mode.bulk_ctl.urb[i] = urb; urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP; dev->video_mode.bulk_ctl.transfer_buffer[i] = usb_alloc_coherent(dev->udev, sb_size, GFP_KERNEL, &urb->transfer_dma); if (!dev->video_mode.bulk_ctl.transfer_buffer[i]) { dev_err(dev->dev, "unable to allocate %i bytes for transfer buffer %i%s\n", sb_size, i, in_interrupt() ? " while in int" : ""); cx231xx_uninit_bulk(dev); return -ENOMEM; } memset(dev->video_mode.bulk_ctl.transfer_buffer[i], 0, sb_size); pipe = usb_rcvbulkpipe(dev->udev, dev->video_mode.end_point_addr); usb_fill_bulk_urb(urb, dev->udev, pipe, dev->video_mode.bulk_ctl.transfer_buffer[i], sb_size, cx231xx_bulk_irq_callback, dma_q); } /* clear halt */ rc = usb_clear_halt(dev->udev, dev->video_mode.bulk_ctl.urb[0]->pipe); if (rc < 0) { dev_err(dev->dev, "failed to clear USB bulk endpoint stall/halt condition (error=%i)\n", rc); cx231xx_uninit_bulk(dev); return rc; } init_waitqueue_head(&dma_q->wq); /* submit urbs and enables IRQ */ for (i = 0; i < dev->video_mode.bulk_ctl.num_bufs; i++) { rc = usb_submit_urb(dev->video_mode.bulk_ctl.urb[i], GFP_ATOMIC); if (rc) { dev_err(dev->dev, "submit of urb %i failed (error=%i)\n", i, rc); cx231xx_uninit_bulk(dev); return rc; } } if (dev->mode_tv == 0) cx231xx_capture_start(dev, 1, Raw_Video); else cx231xx_capture_start(dev, 1, TS1_serial_mode); return 0; } EXPORT_SYMBOL_GPL(cx231xx_init_bulk); void cx231xx_stop_TS1(struct cx231xx *dev) { u8 val[4] = { 0, 0, 0, 0 }; val[0] = 0x00; val[1] = 0x03; val[2] = 0x00; val[3] = 0x00; cx231xx_write_ctrl_reg(dev, VRT_SET_REGISTER, TS_MODE_REG, val, 4); val[0] = 0x00; val[1] = 0x70; val[2] = 0x04; val[3] = 0x00; cx231xx_write_ctrl_reg(dev, VRT_SET_REGISTER, TS1_CFG_REG, val, 4); } /* EXPORT_SYMBOL_GPL(cx231xx_stop_TS1); */ void cx231xx_start_TS1(struct cx231xx *dev) { u8 val[4] = { 0, 0, 0, 0 }; val[0] = 0x03; val[1] = 0x03; val[2] = 0x00; val[3] = 0x00; cx231xx_write_ctrl_reg(dev, VRT_SET_REGISTER, TS_MODE_REG, val, 4); val[0] = 0x04; val[1] = 0xA3; val[2] = 0x3B; val[3] = 0x00; cx231xx_write_ctrl_reg(dev, VRT_SET_REGISTER, TS1_CFG_REG, val, 4); } /* EXPORT_SYMBOL_GPL(cx231xx_start_TS1); */ /***************************************************************** * Device Init/UnInit functions * ******************************************************************/ int cx231xx_dev_init(struct cx231xx *dev) { int errCode = 0; /* Initialize I2C bus */ /* External Master 1 Bus */ dev->i2c_bus[0].nr = 0; dev->i2c_bus[0].dev = dev; dev->i2c_bus[0].i2c_period = I2C_SPEED_100K; /* 100 KHz */ dev->i2c_bus[0].i2c_nostop = 0; dev->i2c_bus[0].i2c_reserve = 0; /* External Master 2 Bus */ dev->i2c_bus[1].nr = 1; dev->i2c_bus[1].dev = dev; dev->i2c_bus[1].i2c_period = I2C_SPEED_100K; /* 100 KHz */ dev->i2c_bus[1].i2c_nostop = 0; dev->i2c_bus[1].i2c_reserve = 0; /* Internal Master 3 Bus */ dev->i2c_bus[2].nr = 2; dev->i2c_bus[2].dev = dev; dev->i2c_bus[2].i2c_period = I2C_SPEED_100K; /* 100kHz */ dev->i2c_bus[2].i2c_nostop = 0; dev->i2c_bus[2].i2c_reserve = 0; /* register I2C buses */ errCode = cx231xx_i2c_register(&dev->i2c_bus[0]); if (errCode < 0) return errCode; errCode = cx231xx_i2c_register(&dev->i2c_bus[1]); if (errCode < 0) return errCode; errCode = cx231xx_i2c_register(&dev->i2c_bus[2]); if (errCode < 0) return errCode; errCode = cx231xx_i2c_mux_create(dev); if (errCode < 0) { dev_err(dev->dev, "%s: Failed to create I2C mux\n", __func__); return errCode; } errCode = cx231xx_i2c_mux_register(dev, 0); if (errCode < 0) return errCode; errCode = cx231xx_i2c_mux_register(dev, 1); if (errCode < 0) return errCode; /* scan the real bus segments in the order of physical port numbers */ cx231xx_do_i2c_scan(dev, I2C_0); cx231xx_do_i2c_scan(dev, I2C_1_MUX_1); cx231xx_do_i2c_scan(dev, I2C_2); cx231xx_do_i2c_scan(dev, I2C_1_MUX_3); /* init hardware */ /* Note : with out calling set power mode function, afe can not be set up correctly */ if (dev->board.external_av) { errCode = cx231xx_set_power_mode(dev, POLARIS_AVMODE_ENXTERNAL_AV); if (errCode < 0) { dev_err(dev->dev, "%s: Failed to set Power - errCode [%d]!\n", __func__, errCode); return errCode; } } else { errCode = cx231xx_set_power_mode(dev, POLARIS_AVMODE_ANALOGT_TV); if (errCode < 0) { dev_err(dev->dev, "%s: Failed to set Power - errCode [%d]!\n", __func__, errCode); return errCode; } } /* reset the Tuner, if it is a Xceive tuner */ if ((dev->board.tuner_type == TUNER_XC5000) || (dev->board.tuner_type == TUNER_XC2028)) cx231xx_gpio_set(dev, dev->board.tuner_gpio); /* initialize Colibri block */ errCode = cx231xx_afe_init_super_block(dev, 0x23c); if (errCode < 0) { dev_err(dev->dev, "%s: cx231xx_afe init super block - errCode [%d]!\n", __func__, errCode); return errCode; } errCode = cx231xx_afe_init_channels(dev); if (errCode < 0) { dev_err(dev->dev, "%s: cx231xx_afe init channels - errCode [%d]!\n", __func__, errCode); return errCode; } /* Set DIF in By pass mode */ errCode = cx231xx_dif_set_standard(dev, DIF_USE_BASEBAND); if (errCode < 0) { dev_err(dev->dev, "%s: cx231xx_dif set to By pass mode - errCode [%d]!\n", __func__, errCode); return errCode; } /* I2S block related functions */ errCode = cx231xx_i2s_blk_initialize(dev); if (errCode < 0) { dev_err(dev->dev, "%s: cx231xx_i2s block initialize - errCode [%d]!\n", __func__, errCode); return errCode; } /* init control pins */ errCode = cx231xx_init_ctrl_pin_status(dev); if (errCode < 0) { dev_err(dev->dev, "%s: cx231xx_init ctrl pins - errCode [%d]!\n", __func__, errCode); return errCode; } /* set AGC mode to Analog */ switch (dev->model) { case CX231XX_BOARD_CNXT_CARRAERA: case CX231XX_BOARD_CNXT_RDE_250: case CX231XX_BOARD_CNXT_SHELBY: case CX231XX_BOARD_CNXT_RDU_250: errCode = cx231xx_set_agc_analog_digital_mux_select(dev, 1); break; case CX231XX_BOARD_CNXT_RDE_253S: case CX231XX_BOARD_CNXT_RDU_253S: case CX231XX_BOARD_HAUPPAUGE_EXETER: case CX231XX_BOARD_HAUPPAUGE_930C_HD_1113xx: case CX231XX_BOARD_PV_PLAYTV_USB_HYBRID: case CX231XX_BOARD_HAUPPAUGE_USB2_FM_PAL: case CX231XX_BOARD_HAUPPAUGE_USB2_FM_NTSC: errCode = cx231xx_set_agc_analog_digital_mux_select(dev, 0); break; default: break; } if (errCode < 0) { dev_err(dev->dev, "%s: cx231xx_AGC mode to Analog - errCode [%d]!\n", __func__, errCode); return errCode; } /* set all alternate settings to zero initially */ cx231xx_set_alt_setting(dev, INDEX_VIDEO, 0); cx231xx_set_alt_setting(dev, INDEX_VANC, 0); cx231xx_set_alt_setting(dev, INDEX_HANC, 0); if (dev->board.has_dvb) cx231xx_set_alt_setting(dev, INDEX_TS1, 0); errCode = 0; return errCode; } EXPORT_SYMBOL_GPL(cx231xx_dev_init); void cx231xx_dev_uninit(struct cx231xx *dev) { /* Un Initialize I2C bus */ cx231xx_i2c_mux_unregister(dev); cx231xx_i2c_unregister(&dev->i2c_bus[2]); cx231xx_i2c_unregister(&dev->i2c_bus[1]); cx231xx_i2c_unregister(&dev->i2c_bus[0]); } EXPORT_SYMBOL_GPL(cx231xx_dev_uninit); /***************************************************************** * G P I O related functions * ******************************************************************/ int cx231xx_send_gpio_cmd(struct cx231xx *dev, u32 gpio_bit, u8 *gpio_val, u8 len, u8 request, u8 direction) { int status = 0; struct VENDOR_REQUEST_IN ven_req; /* Set wValue */ ven_req.wValue = (u16) (gpio_bit >> 16 & 0xffff); /* set request */ if (!request) { if (direction) ven_req.bRequest = VRT_GET_GPIO; /* 0x9 gpio */ else ven_req.bRequest = VRT_SET_GPIO; /* 0x8 gpio */ } else { if (direction) ven_req.bRequest = VRT_GET_GPIE; /* 0xb gpie */ else ven_req.bRequest = VRT_SET_GPIE; /* 0xa gpie */ } /* set index value */ ven_req.wIndex = (u16) (gpio_bit & 0xffff); /* set wLength value */ ven_req.wLength = len; /* set bData value */ ven_req.bData = 0; /* set the buffer for read / write */ ven_req.pBuff = gpio_val; /* set the direction */ if (direction) { ven_req.direction = USB_DIR_IN; memset(ven_req.pBuff, 0x00, ven_req.wLength); } else ven_req.direction = USB_DIR_OUT; /* call common vendor command request */ status = cx231xx_send_vendor_cmd(dev, &ven_req); if (status < 0) { dev_err(dev->dev, "%s: failed with status -%d\n", __func__, status); } return status; } EXPORT_SYMBOL_GPL(cx231xx_send_gpio_cmd); /***************************************************************** * C O N T R O L - Register R E A D / W R I T E functions * *****************************************************************/ int cx231xx_mode_register(struct cx231xx *dev, u16 address, u32 mode) { u8 value[4] = { 0x0, 0x0, 0x0, 0x0 }; u32 tmp = 0; int status = 0; status = cx231xx_read_ctrl_reg(dev, VRT_GET_REGISTER, address, value, 4); if (status < 0) return status; tmp = le32_to_cpu(*((__le32 *) value)); tmp |= mode; value[0] = (u8) tmp; value[1] = (u8) (tmp >> 8); value[2] = (u8) (tmp >> 16); value[3] = (u8) (tmp >> 24); status = cx231xx_write_ctrl_reg(dev, VRT_SET_REGISTER, address, value, 4); return status; } /***************************************************************** * I 2 C Internal C O N T R O L functions * *****************************************************************/ int cx231xx_read_i2c_master(struct cx231xx *dev, u8 dev_addr, u16 saddr, u8 saddr_len, u32 *data, u8 data_len, int master) { int status = 0; struct cx231xx_i2c_xfer_data req_data; u8 value[64] = "0"; if (saddr_len == 0) saddr = 0; else if (saddr_len == 1) saddr &= 0xff; /* prepare xfer_data struct */ req_data.dev_addr = dev_addr >> 1; req_data.direction = I2C_M_RD; req_data.saddr_len = saddr_len; req_data.saddr_dat = saddr; req_data.buf_size = data_len; req_data.p_buffer = (u8 *) value; /* usb send command */ if (master == 0) status = dev->cx231xx_send_usb_command(&dev->i2c_bus[0], &req_data); else if (master == 1) status = dev->cx231xx_send_usb_command(&dev->i2c_bus[1], &req_data); else if (master == 2) status = dev->cx231xx_send_usb_command(&dev->i2c_bus[2], &req_data); if (status >= 0) { /* Copy the data read back to main buffer */ if (data_len == 1) *data = value[0]; else if (data_len == 4) *data = value[0] | value[1] << 8 | value[2] << 16 | value[3] << 24; else if (data_len > 4) *data = value[saddr]; } return status; } int cx231xx_write_i2c_master(struct cx231xx *dev, u8 dev_addr, u16 saddr, u8 saddr_len, u32 data, u8 data_len, int master) { int status = 0; u8 value[4] = { 0, 0, 0, 0 }; struct cx231xx_i2c_xfer_data req_data; value[0] = (u8) data; value[1] = (u8) (data >> 8); value[2] = (u8) (data >> 16); value[3] = (u8) (data >> 24); if (saddr_len == 0) saddr = 0; else if (saddr_len == 1) saddr &= 0xff; /* prepare xfer_data struct */ req_data.dev_addr = dev_addr >> 1; req_data.direction = 0; req_data.saddr_len = saddr_len; req_data.saddr_dat = saddr; req_data.buf_size = data_len; req_data.p_buffer = value; /* usb send command */ if (master == 0) status = dev->cx231xx_send_usb_command(&dev->i2c_bus[0], &req_data); else if (master == 1) status = dev->cx231xx_send_usb_command(&dev->i2c_bus[1], &req_data); else if (master == 2) status = dev->cx231xx_send_usb_command(&dev->i2c_bus[2], &req_data); return status; } int cx231xx_read_i2c_data(struct cx231xx *dev, u8 dev_addr, u16 saddr, u8 saddr_len, u32 *data, u8 data_len) { int status = 0; struct cx231xx_i2c_xfer_data req_data; u8 value[4] = { 0, 0, 0, 0 }; if (saddr_len == 0) saddr = 0; else if (saddr_len == 1) saddr &= 0xff; /* prepare xfer_data struct */ req_data.dev_addr = dev_addr >> 1; req_data.direction = I2C_M_RD; req_data.saddr_len = saddr_len; req_data.saddr_dat = saddr; req_data.buf_size = data_len; req_data.p_buffer = (u8 *) value; /* usb send command */ status = dev->cx231xx_send_usb_command(&dev->i2c_bus[0], &req_data); if (status >= 0) { /* Copy the data read back to main buffer */ if (data_len == 1) *data = value[0]; else *data = value[0] | value[1] << 8 | value[2] << 16 | value[3] << 24; } return status; } int cx231xx_write_i2c_data(struct cx231xx *dev, u8 dev_addr, u16 saddr, u8 saddr_len, u32 data, u8 data_len) { int status = 0; u8 value[4] = { 0, 0, 0, 0 }; struct cx231xx_i2c_xfer_data req_data; value[0] = (u8) data; value[1] = (u8) (data >> 8); value[2] = (u8) (data >> 16); value[3] = (u8) (data >> 24); if (saddr_len == 0) saddr = 0; else if (saddr_len == 1) saddr &= 0xff; /* prepare xfer_data struct */ req_data.dev_addr = dev_addr >> 1; req_data.direction = 0; req_data.saddr_len = saddr_len; req_data.saddr_dat = saddr; req_data.buf_size = data_len; req_data.p_buffer = value; /* usb send command */ status = dev->cx231xx_send_usb_command(&dev->i2c_bus[0], &req_data); return status; } int cx231xx_reg_mask_write(struct cx231xx *dev, u8 dev_addr, u8 size, u16 register_address, u8 bit_start, u8 bit_end, u32 value) { int status = 0; u32 tmp; u32 mask = 0; int i; if (bit_start > (size - 1) || bit_end > (size - 1)) return -1; if (size == 8) { status = cx231xx_read_i2c_data(dev, dev_addr, register_address, 2, &tmp, 1); } else { status = cx231xx_read_i2c_data(dev, dev_addr, register_address, 2, &tmp, 4); } if (status < 0) return status; mask = 1 << bit_end; for (i = bit_end; i > bit_start && i > 0; i--) mask = mask + (1 << (i - 1)); value <<= bit_start; if (size == 8) { tmp &= ~mask; tmp |= value; tmp &= 0xff; status = cx231xx_write_i2c_data(dev, dev_addr, register_address, 2, tmp, 1); } else { tmp &= ~mask; tmp |= value; status = cx231xx_write_i2c_data(dev, dev_addr, register_address, 2, tmp, 4); } return status; } int cx231xx_read_modify_write_i2c_dword(struct cx231xx *dev, u8 dev_addr, u16 saddr, u32 mask, u32 value) { u32 temp; int status = 0; status = cx231xx_read_i2c_data(dev, dev_addr, saddr, 2, &temp, 4); if (status < 0) return status; temp &= ~mask; temp |= value; status = cx231xx_write_i2c_data(dev, dev_addr, saddr, 2, temp, 4); return status; } u32 cx231xx_set_field(u32 field_mask, u32 data) { u32 temp; for (temp = field_mask; (temp & 1) == 0; temp >>= 1) data <<= 1; return data; }
null
null
null
null
108,008
32,359
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
32,359
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* * Copyright (C) 2008 Nikolas Zimmermann <zimmermann@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_SCRIPT_SCRIPT_LOADER_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_SCRIPT_LOADER_H_ #include "third_party/blink/public/platform/web_url_request.h" #include "third_party/blink/renderer/bindings/core/v8/script_source_location_type.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/html/cross_origin_attribute.h" #include "third_party/blink/renderer/core/script/pending_script.h" #include "third_party/blink/renderer/core/script/script.h" #include "third_party/blink/renderer/core/script/script_runner.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/bindings/trace_wrapper_member.h" #include "third_party/blink/renderer/platform/loader/fetch/integrity_metadata.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h" #include "third_party/blink/renderer/platform/loader/fetch/script_fetch_options.h" #include "third_party/blink/renderer/platform/wtf/text/text_encoding.h" #include "third_party/blink/renderer/platform/wtf/text/text_position.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { class ScriptElementBase; class Script; class ScriptResource; class Modulator; class CORE_EXPORT ScriptLoader : public GarbageCollectedFinalized<ScriptLoader>, public PendingScriptClient, public TraceWrapperBase { USING_GARBAGE_COLLECTED_MIXIN(ScriptLoader); public: static ScriptLoader* Create(ScriptElementBase* element, bool created_by_parser, bool is_evaluated, bool created_during_document_write) { return new ScriptLoader(element, created_by_parser, is_evaluated, created_during_document_write); } ~ScriptLoader() override; virtual void Trace(blink::Visitor*); void TraceWrappers(const ScriptWrappableVisitor*) const override; const char* NameInHeapSnapshot() const override { return "ScriptLoader"; } enum LegacyTypeSupport { kDisallowLegacyTypeInTypeAttribute, kAllowLegacyTypeInTypeAttribute }; static bool IsValidScriptTypeAndLanguage( const String& type_attribute_value, const String& language_attribute_value, LegacyTypeSupport support_legacy_types, ScriptType& out_script_type); static bool BlockForNoModule(ScriptType, bool nomodule); static network::mojom::FetchCredentialsMode ModuleScriptCredentialsMode( CrossOriginAttributeValue); // https://html.spec.whatwg.org/multipage/scripting.html#prepare-a-script bool PrepareScript(const TextPosition& script_start_position = TextPosition::MinimumPosition(), LegacyTypeSupport = kDisallowLegacyTypeInTypeAttribute); // https://html.spec.whatwg.org/multipage/scripting.html#execute-the-script-block // The single entry point of script execution. // PendingScript::Dispose() is called in ExecuteScriptBlock(). void ExecuteScriptBlock(PendingScript*, const KURL&); // Gets a PendingScript for external script whose fetch is started in // FetchClassicScript()/FetchModuleScriptTree(). // This should be called only once. PendingScript* TakePendingScript(); // The entry point only for ScriptRunner that wraps ExecuteScriptBlock(). virtual void Execute(); bool IsScriptTypeSupported(LegacyTypeSupport, ScriptType& out_script_type) const; bool HaveFiredLoadEvent() const { return have_fired_load_; } bool WillBeParserExecuted() const { return will_be_parser_executed_; } bool ReadyToBeParserExecuted() const { return ready_to_be_parser_executed_; } bool WillExecuteWhenDocumentFinishedParsing() const { return will_execute_when_document_finished_parsing_; } void SetHaveFiredLoadEvent(bool have_fired_load) { have_fired_load_ = have_fired_load; } bool IsParserInserted() const { return parser_inserted_; } bool AlreadyStarted() const { return already_started_; } bool IsNonBlocking() const { return non_blocking_; } ScriptType GetScriptType() const { return script_type_; } // Helper functions used by our parent classes. void DidNotifySubtreeInsertionsToDocument(); void ChildrenChanged(); void HandleSourceAttribute(const String& source_url); void HandleAsyncAttribute(); virtual bool IsReady() const { return pending_script_ && pending_script_->IsReady(); } void SetFetchDocWrittenScriptDeferIdle(); // To support script streaming, the ScriptRunner may need to access the // PendingScript. This breaks the intended layering, so please use with // care. (Method is virtual to support testing.) virtual PendingScript* GetPendingScriptIfScriptIsAsync(); protected: ScriptLoader(ScriptElementBase*, bool created_by_parser, bool is_evaluated, bool created_during_document_write); private: bool IgnoresLoadRequest() const; bool IsScriptForEventSupported() const; // FetchClassicScript corresponds to Step 21.6 of // https://html.spec.whatwg.org/multipage/scripting.html#prepare-a-script // and must NOT be called from outside of PendingScript(). // // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-classic-script void FetchClassicScript(const KURL&, Document&, const ScriptFetchOptions&, const WTF::TextEncoding&); // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-module-script-tree void FetchModuleScriptTree(const KURL&, Modulator*, const ScriptFetchOptions&); void DispatchLoadEvent(); void DispatchErrorEvent(); // Clears the connection to the PendingScript. void DetachPendingScript(); // PendingScriptClient void PendingScriptFinished(PendingScript*) override; bool WasCreatedDuringDocumentWrite() { return created_during_document_write_; } Member<ScriptElementBase> element_; WTF::OrdinalNumber start_line_number_; // https://html.spec.whatwg.org/multipage/scripting.html#script-processing-model // "A script element has several associated pieces of state.": // https://html.spec.whatwg.org/multipage/scripting.html#already-started // "Initially, script elements must have this flag unset" bool already_started_ = false; // https://html.spec.whatwg.org/multipage/scripting.html#parser-inserted // "Initially, script elements must have this flag unset." bool parser_inserted_ = false; // https://html.spec.whatwg.org/multipage/scripting.html#non-blocking // "Initially, script elements must have this flag set." bool non_blocking_ = true; // https://html.spec.whatwg.org/multipage/scripting.html#ready-to-be-parser-executed // "Initially, script elements must have this flag unset" bool ready_to_be_parser_executed_ = false; // https://html.spec.whatwg.org/multipage/scripting.html#concept-script-type // "It is determined when the script is prepared" ScriptType script_type_ = ScriptType::kClassic; // https://html.spec.whatwg.org/multipage/scripting.html#concept-script-external // "It is determined when the script is prepared" bool is_external_script_ = false; bool have_fired_load_; // Same as "The parser will handle executing the script." bool will_be_parser_executed_; bool will_execute_when_document_finished_parsing_; const bool created_during_document_write_; ScriptRunner::AsyncExecutionType async_exec_type_; // A PendingScript is first created in PrepareScript() and stored in // |prepared_pending_script_|. // Later, TakePendingScript() is called, and its caller holds a reference // to the PendingScript instead and |prepared_pending_script_| is cleared. TraceWrapperMember<PendingScript> prepared_pending_script_; // If the script is controlled by ScriptRunner, then // ScriptLoader::pending_script_ holds a reference to the PendingScript and // ScriptLoader is its client. // Otherwise, HTMLParserScriptRunner or XMLParserScriptRunner holds the // reference and |pending_script_| here is null. TraceWrapperMember<PendingScript> pending_script_; // This is used only to keep the ScriptResource of a classic script alive // and thus to keep it on MemoryCache, even after script execution, as long // as ScriptLoader is alive. crbug.com/778799 Member<Resource> resource_keep_alive_; // The context document at the time when PrepareScript() is executed. // This is only used to check whether the script element is moved between // documents and thus doesn't retain a strong reference. WeakMember<Document> original_document_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_SCRIPT_LOADER_H_
null
null
null
null
29,222
7,347
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
7,347
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 "net/quic/core/congestion_control/bbr_sender.h" #include <algorithm> #include <map> #include <memory> #include "build/build_config.h" #include "net/quic/core/congestion_control/rtt_stats.h" #include "net/quic/core/quic_packets.h" #include "net/quic/core/quic_utils.h" #include "net/quic/platform/api/quic_logging.h" #include "net/quic/platform/api/quic_ptr_util.h" #include "net/quic/platform/api/quic_test.h" #include "net/quic/test_tools/mock_clock.h" #include "net/quic/test_tools/quic_config_peer.h" #include "net/quic/test_tools/quic_connection_peer.h" #include "net/quic/test_tools/quic_sent_packet_manager_peer.h" #include "net/quic/test_tools/quic_test_utils.h" #include "net/quic/test_tools/simulator/quic_endpoint.h" #include "net/quic/test_tools/simulator/simulator.h" #include "net/quic/test_tools/simulator/switch.h" namespace net { namespace test { // Use the initial CWND of 10, as 32 is too much for the test network. const uint32_t kInitialCongestionWindowPackets = 10; const uint32_t kDefaultWindowTCP = kInitialCongestionWindowPackets * kDefaultTCPMSS; // Test network parameters. Here, the topology of the network is: // // BBR sender // | // | <-- local link (10 Mbps, 2 ms delay) // | // Network switch // * <-- the bottleneck queue in the direction // | of the receiver // | // | <-- test link (4 Mbps, 30 ms delay) // | // | // Receiver // // The reason the bandwidths chosen are relatively low is the fact that the // connection simulator uses QuicTime for its internal clock, and as such has // the granularity of 1us, meaning that at bandwidth higher than 20 Mbps the // packets can start to land on the same timestamp. const QuicBandwidth kTestLinkBandwidth = QuicBandwidth::FromKBitsPerSecond(4000); const QuicBandwidth kLocalLinkBandwidth = QuicBandwidth::FromKBitsPerSecond(10000); const QuicTime::Delta kTestPropagationDelay = QuicTime::Delta::FromMilliseconds(30); const QuicTime::Delta kLocalPropagationDelay = QuicTime::Delta::FromMilliseconds(2); const QuicTime::Delta kTestTransferTime = kTestLinkBandwidth.TransferTime(kMaxPacketSize) + kLocalLinkBandwidth.TransferTime(kMaxPacketSize); const QuicTime::Delta kTestRtt = (kTestPropagationDelay + kLocalPropagationDelay + kTestTransferTime) * 2; const QuicByteCount kTestBdp = kTestRtt * kTestLinkBandwidth; class BbrSenderTest : public QuicTest { protected: BbrSenderTest() : simulator_(), bbr_sender_(&simulator_, "BBR sender", "Receiver", Perspective::IS_CLIENT, /*connection_id=*/42), competing_sender_(&simulator_, "Competing sender", "Competing receiver", Perspective::IS_CLIENT, /*connection_id=*/43), receiver_(&simulator_, "Receiver", "BBR sender", Perspective::IS_SERVER, /*connection_id=*/42), competing_receiver_(&simulator_, "Competing receiver", "Competing sender", Perspective::IS_SERVER, /*connection_id=*/43), receiver_multiplexer_("Receiver multiplexer", {&receiver_, &competing_receiver_}) { // These will be changed by the appropriate tests as necessary. SetQuicReloadableFlag(quic_bbr_add_tso_cwnd, false); rtt_stats_ = bbr_sender_.connection()->sent_packet_manager().GetRttStats(); sender_ = SetupBbrSender(&bbr_sender_); clock_ = simulator_.GetClock(); simulator_.set_random_generator(&random_); uint64_t seed = QuicRandom::GetInstance()->RandUint64(); random_.set_seed(seed); QUIC_LOG(INFO) << "BbrSenderTest simulator set up. Seed: " << seed; } simulator::Simulator simulator_; simulator::QuicEndpoint bbr_sender_; simulator::QuicEndpoint competing_sender_; simulator::QuicEndpoint receiver_; simulator::QuicEndpoint competing_receiver_; simulator::QuicEndpointMultiplexer receiver_multiplexer_; std::unique_ptr<simulator::Switch> switch_; std::unique_ptr<simulator::SymmetricLink> bbr_sender_link_; std::unique_ptr<simulator::SymmetricLink> competing_sender_link_; std::unique_ptr<simulator::SymmetricLink> receiver_link_; SimpleRandom random_; // Owned by different components of the connection. const QuicClock* clock_; const RttStats* rtt_stats_; BbrSender* sender_; // Enables BBR on |endpoint| and returns the associated BBR congestion // controller. BbrSender* SetupBbrSender(simulator::QuicEndpoint* endpoint) { const RttStats* rtt_stats = endpoint->connection()->sent_packet_manager().GetRttStats(); // Ownership of the sender will be overtaken by the endpoint. BbrSender* sender = new BbrSender( rtt_stats, QuicSentPacketManagerPeer::GetUnackedPacketMap( QuicConnectionPeer::GetSentPacketManager(endpoint->connection())), kInitialCongestionWindowPackets, kDefaultMaxCongestionWindowPackets, &random_); QuicConnectionPeer::SetSendAlgorithm(endpoint->connection(), sender); return sender; } // Creates a default setup, which is a network with a bottleneck between the // receiver and the switch. The switch has the buffers four times larger than // the bottleneck BDP, which should guarantee a lack of losses. void CreateDefaultSetup() { switch_ = QuicMakeUnique<simulator::Switch>(&simulator_, "Switch", 8, 2 * kTestBdp); bbr_sender_link_ = QuicMakeUnique<simulator::SymmetricLink>( &bbr_sender_, switch_->port(1), kLocalLinkBandwidth, kLocalPropagationDelay); receiver_link_ = QuicMakeUnique<simulator::SymmetricLink>( &receiver_, switch_->port(2), kTestLinkBandwidth, kTestPropagationDelay); } // Same as the default setup, except the buffer now is half of the BDP. void CreateSmallBufferSetup() { switch_ = QuicMakeUnique<simulator::Switch>(&simulator_, "Switch", 8, 0.5 * kTestBdp); bbr_sender_link_ = QuicMakeUnique<simulator::SymmetricLink>( &bbr_sender_, switch_->port(1), kLocalLinkBandwidth, kTestPropagationDelay); receiver_link_ = QuicMakeUnique<simulator::SymmetricLink>( &receiver_, switch_->port(2), kTestLinkBandwidth, kTestPropagationDelay); } // Creates the variation of the default setup in which there is another sender // that competes for the same bottleneck link. void CreateCompetitionSetup() { switch_ = QuicMakeUnique<simulator::Switch>(&simulator_, "Switch", 8, 2 * kTestBdp); // Add a small offset to the competing link in order to avoid // synchronization effects. const QuicTime::Delta small_offset = QuicTime::Delta::FromMicroseconds(3); bbr_sender_link_ = QuicMakeUnique<simulator::SymmetricLink>( &bbr_sender_, switch_->port(1), kLocalLinkBandwidth, kLocalPropagationDelay); competing_sender_link_ = QuicMakeUnique<simulator::SymmetricLink>( &competing_sender_, switch_->port(3), kLocalLinkBandwidth, kLocalPropagationDelay + small_offset); receiver_link_ = QuicMakeUnique<simulator::SymmetricLink>( &receiver_multiplexer_, switch_->port(2), kTestLinkBandwidth, kTestPropagationDelay); } // Creates a BBR vs BBR competition setup. void CreateBbrVsBbrSetup() { SetupBbrSender(&competing_sender_); CreateCompetitionSetup(); } void EnableAggregation(QuicByteCount aggregation_bytes, QuicTime::Delta aggregation_timeout) { // Enable aggregation on the path from the receiver to the sender. switch_->port_queue(1)->EnableAggregation(aggregation_bytes, aggregation_timeout); } void DoSimpleTransfer(QuicByteCount transfer_size, QuicTime::Delta deadline) { bbr_sender_.AddBytesToTransfer(transfer_size); // TODO(vasilvv): consider rewriting this to run until the receiver actually // receives the intended amount of bytes. bool simulator_result = simulator_.RunUntilOrTimeout( [this]() { return bbr_sender_.bytes_to_transfer() == 0; }, deadline); EXPECT_TRUE(simulator_result) << "Simple transfer failed. Bytes remaining: " << bbr_sender_.bytes_to_transfer(); QUIC_LOG(INFO) << "Simple transfer state: " << sender_->ExportDebugState(); } // Drive the simulator by sending enough data to enter PROBE_BW. void DriveOutOfStartup() { ASSERT_FALSE(sender_->ExportDebugState().is_at_full_bandwidth); DoSimpleTransfer(1024 * 1024, QuicTime::Delta::FromSeconds(15)); EXPECT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); ExpectApproxEq(kTestLinkBandwidth, sender_->ExportDebugState().max_bandwidth, 0.01f); } // Send |bytes|-sized bursts of data |number_of_bursts| times, waiting for // |wait_time| between each burst. void SendBursts(size_t number_of_bursts, QuicByteCount bytes, QuicTime::Delta wait_time) { ASSERT_EQ(0u, bbr_sender_.bytes_to_transfer()); for (size_t i = 0; i < number_of_bursts; i++) { bbr_sender_.AddBytesToTransfer(bytes); // Transfer data and wait for three seconds between each transfer. simulator_.RunFor(wait_time); // Ensure the connection did not time out. ASSERT_TRUE(bbr_sender_.connection()->connected()); ASSERT_TRUE(receiver_.connection()->connected()); } simulator_.RunFor(wait_time + kTestRtt); ASSERT_EQ(0u, bbr_sender_.bytes_to_transfer()); } void SetConnectionOption(QuicTag option) { QuicConfig config; QuicTagVector options; options.push_back(option); QuicConfigPeer::SetReceivedConnectionOptions(&config, options); sender_->SetFromConfig(config, Perspective::IS_SERVER); } }; // Test a simple long data transfer in the default setup. TEST_F(BbrSenderTest, SimpleTransfer) { // Adding TSO CWND causes packet loss before exiting startup. SetQuicReloadableFlag(quic_bbr_add_tso_cwnd, false); CreateDefaultSetup(); // At startup make sure we are at the default. EXPECT_EQ(kDefaultWindowTCP, sender_->GetCongestionWindow()); // At startup make sure we can send. EXPECT_TRUE(sender_->CanSend(0)); // Make sure we can send. EXPECT_TRUE(sender_->CanSend(0)); // And that window is un-affected. EXPECT_EQ(kDefaultWindowTCP, sender_->GetCongestionWindow()); // Verify that Sender is in slow start. EXPECT_TRUE(sender_->InSlowStart()); // Verify that pacing rate is based on the initial RTT. QuicBandwidth expected_pacing_rate = QuicBandwidth::FromBytesAndTimeDelta( 2.885 * kDefaultWindowTCP, rtt_stats_->initial_rtt()); ExpectApproxEq(expected_pacing_rate.ToBitsPerSecond(), sender_->PacingRate(0).ToBitsPerSecond(), 0.01f); ASSERT_GE(kTestBdp, kDefaultWindowTCP + kDefaultTCPMSS); DoSimpleTransfer(12 * 1024 * 1024, QuicTime::Delta::FromSeconds(30)); EXPECT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); EXPECT_EQ(0u, bbr_sender_.connection()->GetStats().packets_lost); EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited); // The margin here is quite high, since there exists a possibility that the // connection just exited high gain cycle. ExpectApproxEq(kTestRtt, rtt_stats_->smoothed_rtt(), 0.2f); } // Test a simple transfer in a situation when the buffer is less than BDP. TEST_F(BbrSenderTest, SimpleTransferSmallBuffer) { CreateSmallBufferSetup(); DoSimpleTransfer(12 * 1024 * 1024, QuicTime::Delta::FromSeconds(30)); EXPECT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); ExpectApproxEq(kTestLinkBandwidth, sender_->ExportDebugState().max_bandwidth, 0.01f); EXPECT_GE(bbr_sender_.connection()->GetStats().packets_lost, 0u); EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited); } // Test a simple long data transfer with 2 rtts of aggregation. TEST_F(BbrSenderTest, SimpleTransfer2RTTAggregationBytes) { SetQuicReloadableFlag(quic_bbr_add_tso_cwnd, false); CreateDefaultSetup(); // 2 RTTs of aggregation, with a max of 10kb. EnableAggregation(10 * 1024, 2 * kTestRtt); // Transfer 12MB. DoSimpleTransfer(12 * 1024 * 1024, QuicTime::Delta::FromSeconds(35)); EXPECT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); // It's possible to read a bandwidth as much as 50% too high with aggregation. EXPECT_LE(kTestLinkBandwidth * 0.99f, sender_->ExportDebugState().max_bandwidth); // TODO(ianswett): Tighten this bound once we understand why BBR is // overestimating bandwidth with aggregation. b/36022633 EXPECT_GE(kTestLinkBandwidth * 1.5f, sender_->ExportDebugState().max_bandwidth); // TODO(ianswett): Expect 0 packets are lost once BBR no longer measures // bandwidth higher than the link rate. // The margin here is high, because the aggregation greatly increases // smoothed rtt. EXPECT_GE(kTestRtt * 4, rtt_stats_->smoothed_rtt()); ExpectApproxEq(kTestRtt, rtt_stats_->min_rtt(), 0.2f); } // Test a simple long data transfer with 2 rtts of aggregation. TEST_F(BbrSenderTest, SimpleTransferAckDecimation) { // Decrease the CWND gain so extra CWND is required with stretch acks. FLAGS_quic_bbr_cwnd_gain = 1.0; sender_ = new BbrSender( rtt_stats_, QuicSentPacketManagerPeer::GetUnackedPacketMap( QuicConnectionPeer::GetSentPacketManager(bbr_sender_.connection())), kInitialCongestionWindowPackets, kDefaultMaxCongestionWindowPackets, &random_); QuicConnectionPeer::SetSendAlgorithm(bbr_sender_.connection(), sender_); // Enable Ack Decimation on the receiver. QuicConnectionPeer::SetAckMode(receiver_.connection(), QuicConnection::AckMode::ACK_DECIMATION); CreateDefaultSetup(); // Transfer 12MB. DoSimpleTransfer(12 * 1024 * 1024, QuicTime::Delta::FromSeconds(35)); EXPECT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); // It's possible to read a bandwidth as much as 50% too high with aggregation. EXPECT_LE(kTestLinkBandwidth * 0.99f, sender_->ExportDebugState().max_bandwidth); // TODO(ianswett): Tighten this bound once we understand why BBR is // overestimating bandwidth with aggregation. b/36022633 EXPECT_GE(kTestLinkBandwidth * 1.5f, sender_->ExportDebugState().max_bandwidth); // TODO(ianswett): Expect 0 packets are lost once BBR no longer measures // bandwidth higher than the link rate. EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited); // The margin here is high, because the aggregation greatly increases // smoothed rtt. EXPECT_GE(kTestRtt * 2, rtt_stats_->smoothed_rtt()); ExpectApproxEq(kTestRtt, rtt_stats_->min_rtt(), 0.1f); } // Test a simple long data transfer with 2 rtts of aggregation. TEST_F(BbrSenderTest, SimpleTransfer2RTTAggregationBytes4) { SetQuicReloadableFlag(quic_bbr_add_tso_cwnd, false); CreateDefaultSetup(); // Enable ack aggregation that forces the queue to be drained. SetConnectionOption(kBBR1); // 2 RTTs of aggregation, with a max of 10kb. EnableAggregation(10 * 1024, 2 * kTestRtt); // Transfer 12MB. DoSimpleTransfer(12 * 1024 * 1024, QuicTime::Delta::FromSeconds(35)); EXPECT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); // It's possible to read a bandwidth as much as 50% too high with aggregation. EXPECT_LE(kTestLinkBandwidth * 0.99f, sender_->ExportDebugState().max_bandwidth); // TODO(ianswett): Tighten this bound once we understand why BBR is // overestimating bandwidth with aggregation. b/36022633 EXPECT_GE(kTestLinkBandwidth * 1.5f, sender_->ExportDebugState().max_bandwidth); // TODO(ianswett): Expect 0 packets are lost once BBR no longer measures // bandwidth higher than the link rate. // The margin here is high, because the aggregation greatly increases // smoothed rtt. EXPECT_GE(kTestRtt * 3.5, rtt_stats_->smoothed_rtt()); ExpectApproxEq(kTestRtt, rtt_stats_->min_rtt(), 0.12f); } // Test a simple long data transfer with 2 rtts of aggregation. TEST_F(BbrSenderTest, SimpleTransferAckDecimation4) { // Decrease the CWND gain so extra CWND is required with stretch acks. FLAGS_quic_bbr_cwnd_gain = 1.0; sender_ = new BbrSender( rtt_stats_, QuicSentPacketManagerPeer::GetUnackedPacketMap( QuicConnectionPeer::GetSentPacketManager(bbr_sender_.connection())), kInitialCongestionWindowPackets, kDefaultMaxCongestionWindowPackets, &random_); QuicConnectionPeer::SetSendAlgorithm(bbr_sender_.connection(), sender_); // Enable Ack Decimation on the receiver. QuicConnectionPeer::SetAckMode(receiver_.connection(), QuicConnection::AckMode::ACK_DECIMATION); CreateDefaultSetup(); // Enable ack aggregation that forces the queue to be drained. SetConnectionOption(kBBR1); // Transfer 12MB. DoSimpleTransfer(12 * 1024 * 1024, QuicTime::Delta::FromSeconds(35)); EXPECT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); // It's possible to read a bandwidth as much as 50% too high with aggregation. EXPECT_LE(kTestLinkBandwidth * 0.99f, sender_->ExportDebugState().max_bandwidth); // TODO(ianswett): Tighten this bound once we understand why BBR is // overestimating bandwidth with aggregation. b/36022633 EXPECT_GE(kTestLinkBandwidth * 1.5f, sender_->ExportDebugState().max_bandwidth); // TODO(ianswett): Expect 0 packets are lost once BBR no longer measures // bandwidth higher than the link rate. EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited); // The margin here is high, because the aggregation greatly increases // smoothed rtt. EXPECT_GE(kTestRtt * 2, rtt_stats_->smoothed_rtt()); ExpectApproxEq(kTestRtt, rtt_stats_->min_rtt(), 0.1f); } // Test a simple long data transfer with 2 rtts of aggregation. TEST_F(BbrSenderTest, SimpleTransfer2RTTAggregationBytes20RTTWindow) { SetQuicReloadableFlag(quic_bbr_add_tso_cwnd, false); CreateDefaultSetup(); SetConnectionOption(kBBR4); // 2 RTTs of aggregation, with a max of 10kb. EnableAggregation(10 * 1024, 2 * kTestRtt); // Transfer 12MB. DoSimpleTransfer(12 * 1024 * 1024, QuicTime::Delta::FromSeconds(35)); EXPECT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); // It's possible to read a bandwidth as much as 50% too high with aggregation. EXPECT_LE(kTestLinkBandwidth * 0.99f, sender_->ExportDebugState().max_bandwidth); // TODO(ianswett): Tighten this bound once we understand why BBR is // overestimating bandwidth with aggregation. b/36022633 EXPECT_GE(kTestLinkBandwidth * 1.5f, sender_->ExportDebugState().max_bandwidth); // TODO(ianswett): Expect 0 packets are lost once BBR no longer measures // bandwidth higher than the link rate. // The margin here is high, because the aggregation greatly increases // smoothed rtt. EXPECT_GE(kTestRtt * 4, rtt_stats_->smoothed_rtt()); ExpectApproxEq(kTestRtt, rtt_stats_->min_rtt(), 0.12f); } // Test a simple long data transfer with 2 rtts of aggregation. TEST_F(BbrSenderTest, SimpleTransfer2RTTAggregationBytes40RTTWindow) { SetQuicReloadableFlag(quic_bbr_add_tso_cwnd, false); CreateDefaultSetup(); SetConnectionOption(kBBR5); // 2 RTTs of aggregation, with a max of 10kb. EnableAggregation(10 * 1024, 2 * kTestRtt); // Transfer 12MB. DoSimpleTransfer(12 * 1024 * 1024, QuicTime::Delta::FromSeconds(35)); EXPECT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); // It's possible to read a bandwidth as much as 50% too high with aggregation. EXPECT_LE(kTestLinkBandwidth * 0.99f, sender_->ExportDebugState().max_bandwidth); // TODO(ianswett): Tighten this bound once we understand why BBR is // overestimating bandwidth with aggregation. b/36022633 EXPECT_GE(kTestLinkBandwidth * 1.5f, sender_->ExportDebugState().max_bandwidth); // TODO(ianswett): Expect 0 packets are lost once BBR no longer measures // bandwidth higher than the link rate. // The margin here is high, because the aggregation greatly increases // smoothed rtt. EXPECT_GE(kTestRtt * 4, rtt_stats_->smoothed_rtt()); ExpectApproxEq(kTestRtt, rtt_stats_->min_rtt(), 0.12f); } // Test the number of losses incurred by the startup phase in a situation when // the buffer is less than BDP. TEST_F(BbrSenderTest, PacketLossOnSmallBufferStartup) { CreateSmallBufferSetup(); DriveOutOfStartup(); float loss_rate = static_cast<float>(bbr_sender_.connection()->GetStats().packets_lost) / bbr_sender_.connection()->GetStats().packets_sent; EXPECT_LE(loss_rate, 0.31); } // Ensures the code transitions loss recovery states correctly (NOT_IN_RECOVERY // -> CONSERVATION -> GROWTH -> NOT_IN_RECOVERY). TEST_F(BbrSenderTest, RecoveryStates) { // Set seed to the position where the gain cycling causes the sender go // into conservation upon entering PROBE_BW. // // TODO(vasilvv): there should be a better way to test this. random_.set_seed(UINT64_C(14719894707049085006)); const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(10); bool simulator_result; CreateSmallBufferSetup(); bbr_sender_.AddBytesToTransfer(100 * 1024 * 1024); ASSERT_EQ(BbrSender::NOT_IN_RECOVERY, sender_->ExportDebugState().recovery_state); simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().recovery_state != BbrSender::NOT_IN_RECOVERY; }, timeout); ASSERT_TRUE(simulator_result); ASSERT_EQ(BbrSender::CONSERVATION, sender_->ExportDebugState().recovery_state); simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().recovery_state != BbrSender::CONSERVATION; }, timeout); ASSERT_TRUE(simulator_result); ASSERT_EQ(BbrSender::GROWTH, sender_->ExportDebugState().recovery_state); simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().recovery_state != BbrSender::GROWTH; }, timeout); ASSERT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); ASSERT_EQ(BbrSender::NOT_IN_RECOVERY, sender_->ExportDebugState().recovery_state); ASSERT_TRUE(simulator_result); } // Ensures the code transitions loss recovery states correctly when in STARTUP // and the BBS2 connection option is used. // (NOT_IN_RECOVERY -> CONSERVATION -> GROWTH -> NOT_IN_RECOVERY). TEST_F(BbrSenderTest, StartupMediumRecoveryStates) { // Set seed to the position where the gain cycling causes the sender go // into conservation upon entering PROBE_BW. // // TODO(vasilvv): there should be a better way to test this. random_.set_seed(UINT64_C(14719894707049085006)); const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(10); bool simulator_result; CreateSmallBufferSetup(); SetConnectionOption(kBBS2); bbr_sender_.AddBytesToTransfer(100 * 1024 * 1024); ASSERT_EQ(BbrSender::NOT_IN_RECOVERY, sender_->ExportDebugState().recovery_state); simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().recovery_state != BbrSender::NOT_IN_RECOVERY; }, timeout); ASSERT_TRUE(simulator_result); ASSERT_EQ(BbrSender::MEDIUM_GROWTH, sender_->ExportDebugState().recovery_state); simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().recovery_state != BbrSender::MEDIUM_GROWTH; }, timeout); ASSERT_TRUE(simulator_result); ASSERT_EQ(BbrSender::GROWTH, sender_->ExportDebugState().recovery_state); simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().recovery_state != BbrSender::GROWTH; }, timeout); ASSERT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); ASSERT_EQ(BbrSender::NOT_IN_RECOVERY, sender_->ExportDebugState().recovery_state); ASSERT_TRUE(simulator_result); } // Ensures the code transitions loss recovery states correctly when in STARTUP // and the BBS3 connection option is used. // (NOT_IN_RECOVERY -> GROWTH -> NOT_IN_RECOVERY). TEST_F(BbrSenderTest, StartupGrowthRecoveryStates) { // Set seed to the position where the gain cycling causes the sender go // into conservation upon entering PROBE_BW. // // TODO(vasilvv): there should be a better way to test this. random_.set_seed(UINT64_C(14719894707049085006)); const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(10); bool simulator_result; CreateSmallBufferSetup(); SetConnectionOption(kBBS3); bbr_sender_.AddBytesToTransfer(100 * 1024 * 1024); ASSERT_EQ(BbrSender::NOT_IN_RECOVERY, sender_->ExportDebugState().recovery_state); simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().recovery_state != BbrSender::NOT_IN_RECOVERY; }, timeout); ASSERT_TRUE(simulator_result); ASSERT_EQ(BbrSender::GROWTH, sender_->ExportDebugState().recovery_state); simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().recovery_state != BbrSender::GROWTH; }, timeout); ASSERT_TRUE(simulator_result); ASSERT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); ASSERT_EQ(BbrSender::NOT_IN_RECOVERY, sender_->ExportDebugState().recovery_state); ASSERT_TRUE(simulator_result); } // Verify the behavior of the algorithm in the case when the connection sends // small bursts of data after sending continuously for a while. TEST_F(BbrSenderTest, ApplicationLimitedBursts) { CreateDefaultSetup(); DriveOutOfStartup(); EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited); SendBursts(20, 512, QuicTime::Delta::FromSeconds(3)); EXPECT_TRUE(sender_->ExportDebugState().last_sample_is_app_limited); ExpectApproxEq(kTestLinkBandwidth, sender_->ExportDebugState().max_bandwidth, 0.01f); } // Verify the behavior of the algorithm in the case when the connection sends // small bursts of data and then starts sending continuously. TEST_F(BbrSenderTest, ApplicationLimitedBurstsWithoutPrior) { CreateDefaultSetup(); SendBursts(40, 512, QuicTime::Delta::FromSeconds(3)); EXPECT_TRUE(sender_->ExportDebugState().last_sample_is_app_limited); DriveOutOfStartup(); ExpectApproxEq(kTestLinkBandwidth, sender_->ExportDebugState().max_bandwidth, 0.01f); EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited); } // Verify that the DRAIN phase works correctly. TEST_F(BbrSenderTest, Drain) { CreateDefaultSetup(); const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(10); // Get the queue at the bottleneck, which is the outgoing queue at the port to // which the receiver is connected. const simulator::Queue* queue = switch_->port_queue(2); bool simulator_result; // We have no intention of ever finishing this transfer. bbr_sender_.AddBytesToTransfer(100 * 1024 * 1024); // Run the startup, and verify that it fills up the queue. ASSERT_EQ(BbrSender::STARTUP, sender_->ExportDebugState().mode); simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().mode != BbrSender::STARTUP; }, timeout); ASSERT_TRUE(simulator_result); ASSERT_EQ(BbrSender::DRAIN, sender_->ExportDebugState().mode); // BBR uses CWND gain of 2.88 during STARTUP, hence it will fill the buffer // with approximately 1.88 BDPs. Here, we use 1.5 to give some margin for // error. EXPECT_GE(queue->bytes_queued(), 1.5 * kTestBdp); // Observe increased RTT due to bufferbloat. const QuicTime::Delta queueing_delay = kTestLinkBandwidth.TransferTime(queue->bytes_queued()); ExpectApproxEq(kTestRtt + queueing_delay, rtt_stats_->latest_rtt(), 0.1f); // Transition to the drain phase and verify that it makes the queue // have at most a BDP worth of packets. simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().mode != BbrSender::DRAIN; }, timeout); ASSERT_TRUE(simulator_result); ASSERT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); EXPECT_LE(queue->bytes_queued(), kTestBdp); // Wait for a few round trips and ensure we're in appropriate phase of gain // cycling before taking an RTT measurement. const QuicRoundTripCount start_round_trip = sender_->ExportDebugState().round_trip_count; simulator_result = simulator_.RunUntilOrTimeout( [this, start_round_trip]() { QuicRoundTripCount rounds_passed = sender_->ExportDebugState().round_trip_count - start_round_trip; return rounds_passed >= 4 && sender_->ExportDebugState().gain_cycle_index == 7; }, timeout); ASSERT_TRUE(simulator_result); // Observe the bufferbloat go away. ExpectApproxEq(kTestRtt, rtt_stats_->smoothed_rtt(), 0.1f); } // Verify that the connection enters and exits PROBE_RTT correctly. TEST_F(BbrSenderTest, ProbeRtt) { CreateDefaultSetup(); DriveOutOfStartup(); // We have no intention of ever finishing this transfer. bbr_sender_.AddBytesToTransfer(100 * 1024 * 1024); // Wait until the connection enters PROBE_RTT. const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(12); bool simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().mode == BbrSender::PROBE_RTT; }, timeout); ASSERT_TRUE(simulator_result); ASSERT_EQ(BbrSender::PROBE_RTT, sender_->ExportDebugState().mode); // Exit PROBE_RTT. const QuicTime probe_rtt_start = clock_->Now(); const QuicTime::Delta time_to_exit_probe_rtt = kTestRtt + QuicTime::Delta::FromMilliseconds(200); simulator_.RunFor(1.5 * time_to_exit_probe_rtt); EXPECT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); EXPECT_GE(sender_->ExportDebugState().min_rtt_timestamp, probe_rtt_start); } // Verify that the connection enters and exits PROBE_RTT correctly. TEST_F(BbrSenderTest, ProbeRttBDPBasedCWNDTarget) { CreateDefaultSetup(); SetQuicReloadableFlag(quic_bbr_less_probe_rtt, true); SetConnectionOption(kBBR6); DriveOutOfStartup(); // We have no intention of ever finishing this transfer. bbr_sender_.AddBytesToTransfer(100 * 1024 * 1024); // Wait until the connection enters PROBE_RTT. const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(12); bool simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().mode == BbrSender::PROBE_RTT; }, timeout); ASSERT_TRUE(simulator_result); ASSERT_EQ(BbrSender::PROBE_RTT, sender_->ExportDebugState().mode); // Exit PROBE_RTT. const QuicTime probe_rtt_start = clock_->Now(); const QuicTime::Delta time_to_exit_probe_rtt = kTestRtt + QuicTime::Delta::FromMilliseconds(200); simulator_.RunFor(1.5 * time_to_exit_probe_rtt); EXPECT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); EXPECT_GE(sender_->ExportDebugState().min_rtt_timestamp, probe_rtt_start); } // Verify that the connection enters does not enter PROBE_RTT. TEST_F(BbrSenderTest, ProbeRttSkippedAfterAppLimitedAndStableRtt) { CreateDefaultSetup(); SetQuicReloadableFlag(quic_bbr_less_probe_rtt, true); SetConnectionOption(kBBR7); DriveOutOfStartup(); // We have no intention of ever finishing this transfer. bbr_sender_.AddBytesToTransfer(100 * 1024 * 1024); // Wait until the connection enters PROBE_RTT. const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(12); bool simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().mode == BbrSender::PROBE_RTT; }, timeout); ASSERT_FALSE(simulator_result); ASSERT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); } // Verify that the connection enters does not enter PROBE_RTT. TEST_F(BbrSenderTest, ProbeRttSkippedAfterAppLimited) { CreateDefaultSetup(); SetQuicReloadableFlag(quic_bbr_less_probe_rtt, true); SetConnectionOption(kBBR8); DriveOutOfStartup(); // We have no intention of ever finishing this transfer. bbr_sender_.AddBytesToTransfer(100 * 1024 * 1024); // Wait until the connection enters PROBE_RTT. const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(12); bool simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().mode == BbrSender::PROBE_RTT; }, timeout); ASSERT_FALSE(simulator_result); ASSERT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); } // Ensure that a connection that is app-limited and is at sufficiently low // bandwidth will not exit high gain phase, and similarly ensure that the // connection will exit low gain early if the number of bytes in flight is low. TEST_F(BbrSenderTest, InFlightAwareGainCycling) { CreateDefaultSetup(); DriveOutOfStartup(); const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5); bool simulator_result; // Start a few cycles prior to the high gain one. simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().gain_cycle_index == 6; }, timeout); // Send at 10% of available rate. Run for 3 seconds, checking in the middle // and at the end. The pacing gain should be high throughout. QuicBandwidth target_bandwidth = 0.1f * kTestLinkBandwidth; QuicTime::Delta burst_interval = QuicTime::Delta::FromMilliseconds(300); for (int i = 0; i < 2; i++) { SendBursts(5, target_bandwidth * burst_interval, burst_interval); EXPECT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); EXPECT_EQ(0, sender_->ExportDebugState().gain_cycle_index); ExpectApproxEq(kTestLinkBandwidth, sender_->ExportDebugState().max_bandwidth, 0.01f); } // Now that in-flight is almost zero and the pacing gain is still above 1, // send approximately 1.25 BDPs worth of data. This should cause the // PROBE_BW mode to enter low gain cycle, and exit it earlier than one min_rtt // due to running out of data to send. bbr_sender_.AddBytesToTransfer(1.3 * kTestBdp); simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().gain_cycle_index == 1; }, timeout); ASSERT_TRUE(simulator_result); simulator_.RunFor(0.75 * sender_->ExportDebugState().min_rtt); EXPECT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); EXPECT_EQ(2, sender_->ExportDebugState().gain_cycle_index); } // Ensure that the pacing rate does not drop at startup. TEST_F(BbrSenderTest, NoBandwidthDropOnStartup) { CreateDefaultSetup(); const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5); bool simulator_result; QuicBandwidth initial_rate = QuicBandwidth::FromBytesAndTimeDelta( kInitialCongestionWindowPackets * kDefaultTCPMSS, rtt_stats_->initial_rtt()); EXPECT_GE(sender_->PacingRate(0), initial_rate); // Send a packet. bbr_sender_.AddBytesToTransfer(1000); simulator_result = simulator_.RunUntilOrTimeout( [this]() { return receiver_.bytes_received() == 1000; }, timeout); ASSERT_TRUE(simulator_result); EXPECT_GE(sender_->PacingRate(0), initial_rate); // Wait for a while. simulator_.RunFor(QuicTime::Delta::FromSeconds(2)); EXPECT_GE(sender_->PacingRate(0), initial_rate); // Send another packet. bbr_sender_.AddBytesToTransfer(1000); simulator_result = simulator_.RunUntilOrTimeout( [this]() { return receiver_.bytes_received() == 2000; }, timeout); ASSERT_TRUE(simulator_result); EXPECT_GE(sender_->PacingRate(0), initial_rate); } // Test exiting STARTUP earlier due to the 1RTT connection option. TEST_F(BbrSenderTest, SimpleTransfer1RTTStartup) { CreateDefaultSetup(); SetConnectionOption(k1RTT); EXPECT_EQ(1u, sender_->num_startup_rtts()); // Run until the full bandwidth is reached and check how many rounds it was. bbr_sender_.AddBytesToTransfer(12 * 1024 * 1024); QuicRoundTripCount max_bw_round = 0; QuicBandwidth max_bw(QuicBandwidth::Zero()); bool simulator_result = simulator_.RunUntilOrTimeout( [this, &max_bw, &max_bw_round]() { if (max_bw < sender_->ExportDebugState().max_bandwidth) { max_bw = sender_->ExportDebugState().max_bandwidth; max_bw_round = sender_->ExportDebugState().round_trip_count; } return sender_->ExportDebugState().is_at_full_bandwidth; }, QuicTime::Delta::FromSeconds(5)); ASSERT_TRUE(simulator_result); EXPECT_EQ(BbrSender::DRAIN, sender_->ExportDebugState().mode); EXPECT_EQ(1u, sender_->ExportDebugState().round_trip_count - max_bw_round); EXPECT_EQ(1u, sender_->ExportDebugState().rounds_without_bandwidth_gain); EXPECT_EQ(0u, bbr_sender_.connection()->GetStats().packets_lost); EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited); } // Test exiting STARTUP earlier due to the 2RTT connection option. TEST_F(BbrSenderTest, SimpleTransfer2RTTStartup) { // Adding TSO CWND causes packet loss before exiting startup. SetQuicReloadableFlag(quic_bbr_add_tso_cwnd, false); CreateDefaultSetup(); SetConnectionOption(k2RTT); EXPECT_EQ(2u, sender_->num_startup_rtts()); // Run until the full bandwidth is reached and check how many rounds it was. bbr_sender_.AddBytesToTransfer(12 * 1024 * 1024); QuicRoundTripCount max_bw_round = 0; QuicBandwidth max_bw(QuicBandwidth::Zero()); bool simulator_result = simulator_.RunUntilOrTimeout( [this, &max_bw, &max_bw_round]() { if (max_bw < sender_->ExportDebugState().max_bandwidth) { max_bw = sender_->ExportDebugState().max_bandwidth; max_bw_round = sender_->ExportDebugState().round_trip_count; } return sender_->ExportDebugState().is_at_full_bandwidth; }, QuicTime::Delta::FromSeconds(5)); ASSERT_TRUE(simulator_result); EXPECT_EQ(BbrSender::DRAIN, sender_->ExportDebugState().mode); EXPECT_EQ(2u, sender_->ExportDebugState().round_trip_count - max_bw_round); EXPECT_EQ(2u, sender_->ExportDebugState().rounds_without_bandwidth_gain); EXPECT_EQ(0u, bbr_sender_.connection()->GetStats().packets_lost); EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited); } // Test exiting STARTUP earlier upon loss due to the LRTT connection option. TEST_F(BbrSenderTest, SimpleTransferLRTTStartup) { CreateDefaultSetup(); SetConnectionOption(kLRTT); EXPECT_EQ(3u, sender_->num_startup_rtts()); // Run until the full bandwidth is reached and check how many rounds it was. bbr_sender_.AddBytesToTransfer(12 * 1024 * 1024); QuicRoundTripCount max_bw_round = 0; QuicBandwidth max_bw(QuicBandwidth::Zero()); bool simulator_result = simulator_.RunUntilOrTimeout( [this, &max_bw, &max_bw_round]() { if (max_bw < sender_->ExportDebugState().max_bandwidth) { max_bw = sender_->ExportDebugState().max_bandwidth; max_bw_round = sender_->ExportDebugState().round_trip_count; } return sender_->ExportDebugState().is_at_full_bandwidth; }, QuicTime::Delta::FromSeconds(5)); ASSERT_TRUE(simulator_result); EXPECT_EQ(BbrSender::DRAIN, sender_->ExportDebugState().mode); EXPECT_EQ(3u, sender_->ExportDebugState().round_trip_count - max_bw_round); EXPECT_EQ(3u, sender_->ExportDebugState().rounds_without_bandwidth_gain); EXPECT_EQ(0u, bbr_sender_.connection()->GetStats().packets_lost); EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited); } // Test exiting STARTUP earlier upon loss due to the LRTT connection option. TEST_F(BbrSenderTest, SimpleTransferLRTTStartupSmallBuffer) { CreateSmallBufferSetup(); SetConnectionOption(kLRTT); EXPECT_EQ(3u, sender_->num_startup_rtts()); // Run until the full bandwidth is reached and check how many rounds it was. bbr_sender_.AddBytesToTransfer(12 * 1024 * 1024); QuicRoundTripCount max_bw_round = 0; QuicBandwidth max_bw(QuicBandwidth::Zero()); bool simulator_result = simulator_.RunUntilOrTimeout( [this, &max_bw, &max_bw_round]() { if (max_bw < sender_->ExportDebugState().max_bandwidth) { max_bw = sender_->ExportDebugState().max_bandwidth; max_bw_round = sender_->ExportDebugState().round_trip_count; } return sender_->ExportDebugState().is_at_full_bandwidth; }, QuicTime::Delta::FromSeconds(5)); ASSERT_TRUE(simulator_result); EXPECT_EQ(BbrSender::DRAIN, sender_->ExportDebugState().mode); EXPECT_GE(2u, sender_->ExportDebugState().round_trip_count - max_bw_round); EXPECT_EQ(1u, sender_->ExportDebugState().rounds_without_bandwidth_gain); EXPECT_NE(0u, bbr_sender_.connection()->GetStats().packets_lost); EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited); } // Test slower pacing after loss in STARTUP due to the BBRS connection option. TEST_F(BbrSenderTest, SimpleTransferSlowerStartup) { // Adding TSO CWND causes packet loss before exiting startup. SetQuicReloadableFlag(quic_bbr_add_tso_cwnd, false); CreateSmallBufferSetup(); SetConnectionOption(kBBRS); EXPECT_EQ(3u, sender_->num_startup_rtts()); // Run until the full bandwidth is reached and check how many rounds it was. bbr_sender_.AddBytesToTransfer(12 * 1024 * 1024); QuicRoundTripCount max_bw_round = 0; QuicBandwidth max_bw(QuicBandwidth::Zero()); bool simulator_result = simulator_.RunUntilOrTimeout( [this, &max_bw, &max_bw_round]() { if (max_bw < sender_->ExportDebugState().max_bandwidth) { max_bw = sender_->ExportDebugState().max_bandwidth; max_bw_round = sender_->ExportDebugState().round_trip_count; } // Expect the pacing rate in STARTUP to decrease once packet loss // is observed, but the CWND does not. if (bbr_sender_.connection()->GetStats().packets_lost > 0 && !sender_->ExportDebugState().is_at_full_bandwidth) { EXPECT_EQ(1.5f * max_bw, sender_->PacingRate(0)); } return sender_->ExportDebugState().is_at_full_bandwidth; }, QuicTime::Delta::FromSeconds(5)); ASSERT_TRUE(simulator_result); EXPECT_EQ(BbrSender::DRAIN, sender_->ExportDebugState().mode); EXPECT_GE(3u, sender_->ExportDebugState().round_trip_count - max_bw_round); EXPECT_EQ(3u, sender_->ExportDebugState().rounds_without_bandwidth_gain); EXPECT_NE(0u, bbr_sender_.connection()->GetStats().packets_lost); EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited); } // Ensures no change in congestion window in STARTUP after loss. TEST_F(BbrSenderTest, SimpleTransferNoConservationInStartup) { // Adding TSO CWND causes packet loss before exiting startup. SetQuicReloadableFlag(quic_bbr_add_tso_cwnd, false); CreateSmallBufferSetup(); SetConnectionOption(kBBS1); // Run until the full bandwidth is reached and check how many rounds it was. bbr_sender_.AddBytesToTransfer(12 * 1024 * 1024); bool used_conservation_cwnd = false; bool simulator_result = simulator_.RunUntilOrTimeout( [this, &used_conservation_cwnd]() { if (!sender_->ExportDebugState().is_at_full_bandwidth && sender_->GetCongestionWindow() < sender_->ExportDebugState().congestion_window) { used_conservation_cwnd = true; } return sender_->ExportDebugState().is_at_full_bandwidth; }, QuicTime::Delta::FromSeconds(5)); ASSERT_TRUE(simulator_result); EXPECT_FALSE(used_conservation_cwnd); EXPECT_EQ(BbrSender::DRAIN, sender_->ExportDebugState().mode); EXPECT_EQ(3u, sender_->ExportDebugState().rounds_without_bandwidth_gain); EXPECT_NE(0u, bbr_sender_.connection()->GetStats().packets_lost); EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited); } // Test that two BBR flows started slightly apart from each other terminate. TEST_F(BbrSenderTest, SimpleCompetition) { const QuicByteCount transfer_size = 10 * 1024 * 1024; const QuicTime::Delta transfer_time = kTestLinkBandwidth.TransferTime(transfer_size); CreateBbrVsBbrSetup(); // Transfer 10% of data in first transfer. bbr_sender_.AddBytesToTransfer(transfer_size); bool simulator_result = simulator_.RunUntilOrTimeout( [this, transfer_size]() { return receiver_.bytes_received() >= 0.1 * transfer_size; }, transfer_time); ASSERT_TRUE(simulator_result); // Start the second transfer and wait until both finish. competing_sender_.AddBytesToTransfer(transfer_size); simulator_result = simulator_.RunUntilOrTimeout( [this, transfer_size]() { return receiver_.bytes_received() == transfer_size && competing_receiver_.bytes_received() == transfer_size; }, 3 * transfer_time); ASSERT_TRUE(simulator_result); } // Test that BBR can resume bandwidth from cached network parameters. TEST_F(BbrSenderTest, ResumeConnectionState) { CreateDefaultSetup(); sender_->AdjustNetworkParameters(kTestLinkBandwidth, kTestRtt); EXPECT_EQ(kTestLinkBandwidth, sender_->ExportDebugState().max_bandwidth); EXPECT_EQ(kTestLinkBandwidth, sender_->BandwidthEstimate()); ExpectApproxEq(kTestRtt, sender_->ExportDebugState().min_rtt, 0.01f); DriveOutOfStartup(); } // Test with a min CWND of 1 instead of 4 packets. TEST_F(BbrSenderTest, ProbeRTTMinCWND1) { SetQuicReloadableFlag(quic_one_tlp, true); CreateDefaultSetup(); SetConnectionOption(kMIN1); DriveOutOfStartup(); // We have no intention of ever finishing this transfer. bbr_sender_.AddBytesToTransfer(100 * 1024 * 1024); // Wait until the connection enters PROBE_RTT. const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(12); bool simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().mode == BbrSender::PROBE_RTT; }, timeout); ASSERT_TRUE(simulator_result); ASSERT_EQ(BbrSender::PROBE_RTT, sender_->ExportDebugState().mode); // The PROBE_RTT CWND should be 1 if the min CWND is 1. EXPECT_EQ(kDefaultTCPMSS, sender_->GetCongestionWindow()); // Exit PROBE_RTT. const QuicTime probe_rtt_start = clock_->Now(); const QuicTime::Delta time_to_exit_probe_rtt = kTestRtt + QuicTime::Delta::FromMilliseconds(200); simulator_.RunFor(1.5 * time_to_exit_probe_rtt); EXPECT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); EXPECT_GE(sender_->ExportDebugState().min_rtt_timestamp, probe_rtt_start); } } // namespace test } // namespace net
null
null
null
null
4,210
19,088
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
19,088
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_LOCATION_LOCATION_SETTINGS_DIALOG_CONTEXT_H_ #define COMPONENTS_LOCATION_LOCATION_SETTINGS_DIALOG_CONTEXT_H_ // An enum to describe the context in which a system location setting prompt // is triggered to allow the prompt UI to be customized to the given context. // GENERATED_JAVA_ENUM_PACKAGE: org.chromium.components.location enum LocationSettingsDialogContext { // Default context. DEFAULT = 1, // Prompt triggered in the context of a search. SEARCH = 2, }; #endif // COMPONENTS_LOCATION_LOCATION_SETTINGS_DIALOG_CONTEXT_H_
null
null
null
null
15,951
470
26,28
train_val
19190765882e272a6a2162c89acdb29110f7e3cf
470
Chrome
1
https://github.com/chromium/chromium
2011-09-21 22:56:29+00:00
void ProcessCommitResponseCommand::UpdateServerFieldsAfterCommit( const sync_pb::SyncEntity& committed_entry, const CommitResponse_EntryResponse& entry_response, syncable::MutableEntry* local_entry) { // We just committed an entry successfully, and now we want to make our view // of the server state consistent with the server state. We must be careful; // |entry_response| and |committed_entry| have some identically named // fields. We only want to consider fields from |committed_entry| when there // is not an overriding field in the |entry_response|. We do not want to // update the server data from the local data in the entry -- it's possible // that the local data changed during the commit, and even if not, the server // has the last word on the values of several properties. local_entry->Put(SERVER_IS_DEL, committed_entry.deleted()); if (committed_entry.deleted()) { // Don't clobber any other fields of deleted objects. return; } local_entry->Put(syncable::SERVER_IS_DIR, (committed_entry.folder() || committed_entry.bookmarkdata().bookmark_folder())); local_entry->Put(syncable::SERVER_SPECIFICS, committed_entry.specifics()); local_entry->Put(syncable::SERVER_MTIME, ProtoTimeToTime(committed_entry.mtime())); local_entry->Put(syncable::SERVER_CTIME, ProtoTimeToTime(committed_entry.ctime())); local_entry->Put(syncable::SERVER_POSITION_IN_PARENT, entry_response.position_in_parent()); // TODO(nick): The server doesn't set entry_response.server_parent_id in // practice; to update SERVER_PARENT_ID appropriately here we'd need to // get the post-commit ID of the parent indicated by // committed_entry.parent_id_string(). That should be inferrable from the // information we have, but it's a bit convoluted to pull it out directly. // Getting this right is important: SERVER_PARENT_ID gets fed back into // old_parent_id during the next commit. local_entry->Put(syncable::SERVER_PARENT_ID, local_entry->Get(syncable::PARENT_ID)); local_entry->Put(syncable::SERVER_NON_UNIQUE_NAME, GetResultingPostCommitName(committed_entry, entry_response)); if (local_entry->Get(IS_UNAPPLIED_UPDATE)) { // This shouldn't happen; an unapplied update shouldn't be committed, and // if it were, the commit should have failed. But if it does happen: we've // just overwritten the update info, so clear the flag. local_entry->Put(IS_UNAPPLIED_UPDATE, false); } }
null
null
https://github.com/chromium/chromium/commit/19190765882e272a6a2162c89acdb29110f7e3cf
null
470
37,885
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
202,880
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* For debugging general purposes */ #ifndef __PERF_DEBUG_H #define __PERF_DEBUG_H #include <stdbool.h> #include <string.h> #include "event.h" #include "../ui/helpline.h" #include "../ui/progress.h" #include "../ui/util.h" extern int verbose; extern bool quiet, dump_trace; extern int debug_ordered_events; extern int debug_data_convert; #ifndef pr_fmt #define pr_fmt(fmt) fmt #endif #define pr_err(fmt, ...) \ eprintf(0, verbose, pr_fmt(fmt), ##__VA_ARGS__) #define pr_warning(fmt, ...) \ eprintf(0, verbose, pr_fmt(fmt), ##__VA_ARGS__) #define pr_info(fmt, ...) \ eprintf(0, verbose, pr_fmt(fmt), ##__VA_ARGS__) #define pr_debug(fmt, ...) \ eprintf(1, verbose, pr_fmt(fmt), ##__VA_ARGS__) #define pr_debugN(n, fmt, ...) \ eprintf(n, verbose, pr_fmt(fmt), ##__VA_ARGS__) #define pr_debug2(fmt, ...) pr_debugN(2, pr_fmt(fmt), ##__VA_ARGS__) #define pr_debug3(fmt, ...) pr_debugN(3, pr_fmt(fmt), ##__VA_ARGS__) #define pr_debug4(fmt, ...) pr_debugN(4, pr_fmt(fmt), ##__VA_ARGS__) #define pr_time_N(n, var, t, fmt, ...) \ eprintf_time(n, var, t, fmt, ##__VA_ARGS__) #define pr_oe_time(t, fmt, ...) pr_time_N(1, debug_ordered_events, t, pr_fmt(fmt), ##__VA_ARGS__) #define pr_oe_time2(t, fmt, ...) pr_time_N(2, debug_ordered_events, t, pr_fmt(fmt), ##__VA_ARGS__) #define STRERR_BUFSIZE 128 /* For the buffer size of str_error_r */ int dump_printf(const char *fmt, ...) __attribute__((format(printf, 1, 2))); void trace_event(union perf_event *event); int ui__error(const char *format, ...) __attribute__((format(printf, 1, 2))); int ui__warning(const char *format, ...) __attribute__((format(printf, 1, 2))); void pr_stat(const char *fmt, ...); int eprintf(int level, int var, const char *fmt, ...) __attribute__((format(printf, 3, 4))); int eprintf_time(int level, int var, u64 t, const char *fmt, ...) __attribute__((format(printf, 4, 5))); int veprintf(int level, int var, const char *fmt, va_list args); int perf_debug_option(const char *str); void perf_debug_setup(void); int perf_quiet_option(void); #endif /* __PERF_DEBUG_H */
null
null
null
null
111,227
19,976
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
19,976
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_RENDERER_DOCUMENT_STATE_H_ #define CONTENT_PUBLIC_RENDERER_DOCUMENT_STATE_H_ #include <memory> #include <string> #include "base/logging.h" #include "base/supports_user_data.h" #include "base/time/time.h" #include "content/common/content_export.h" #include "net/http/http_response_info.h" #include "third_party/blink/public/web/web_document_loader.h" #include "url/gurl.h" namespace content { class NavigationState; // The RenderView stores an instance of this class in the "extra data" of each // WebDocumentLoader (see RenderView::DidCreateDataSource). class CONTENT_EXPORT DocumentState : public blink::WebDocumentLoader::ExtraData, public base::SupportsUserData { public: DocumentState(); ~DocumentState() override; static DocumentState* FromDocumentLoader( blink::WebDocumentLoader* document_loader) { return static_cast<DocumentState*>(document_loader->GetExtraData()); } // Indicator if SPDY was used as part of this page load. bool was_fetched_via_spdy() const { return was_fetched_via_spdy_; } void set_was_fetched_via_spdy(bool value) { was_fetched_via_spdy_ = value; } bool was_alpn_negotiated() const { return was_alpn_negotiated_; } void set_was_alpn_negotiated(bool value) { was_alpn_negotiated_ = value; } const std::string& alpn_negotiated_protocol() const { return alpn_negotiated_protocol_; } void set_alpn_negotiated_protocol(const std::string& value) { alpn_negotiated_protocol_ = value; } bool was_alternate_protocol_available() const { return was_alternate_protocol_available_; } void set_was_alternate_protocol_available(bool value) { was_alternate_protocol_available_ = value; } net::HttpResponseInfo::ConnectionInfo connection_info() const { return connection_info_; } void set_connection_info( net::HttpResponseInfo::ConnectionInfo connection_info) { connection_info_ = connection_info; } // For LoadDataWithBaseURL navigations, |was_load_data_with_base_url_request_| // is set to true and |data_url_| is set to the data URL of the navigation. // Otherwise, |was_load_data_with_base_url_request_| is false and |data_url_| // is empty. void set_was_load_data_with_base_url_request(bool value) { was_load_data_with_base_url_request_ = value; } bool was_load_data_with_base_url_request() const { return was_load_data_with_base_url_request_; } const GURL& data_url() const { return data_url_; } void set_data_url(const GURL& data_url) { data_url_ = data_url; } NavigationState* navigation_state() { return navigation_state_.get(); } void set_navigation_state(NavigationState* navigation_state); bool can_load_local_resources() const { return can_load_local_resources_; } void set_can_load_local_resources(bool can_load) { can_load_local_resources_ = can_load; } private: bool was_fetched_via_spdy_; bool was_alpn_negotiated_; std::string alpn_negotiated_protocol_; bool was_alternate_protocol_available_; net::HttpResponseInfo::ConnectionInfo connection_info_; bool was_load_data_with_base_url_request_; GURL data_url_; std::unique_ptr<NavigationState> navigation_state_; bool can_load_local_resources_; }; } // namespace content #endif // CONTENT_PUBLIC_RENDERER_DOCUMENT_STATE_H_
null
null
null
null
16,839
32,490
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
32,490
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 "third_party/blink/renderer/core/loader/text_resource_decoder_builder.h" #include <memory> #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/core/testing/dummy_page_holder.h" namespace blink { static const WTF::TextEncoding DefaultEncodingForUrlAndContentType( const char* url, const char* content_type) { std::unique_ptr<DummyPageHolder> page_holder = DummyPageHolder::Create(IntSize(0, 0)); Document& document = page_holder->GetDocument(); document.SetURL(KURL(NullURL(), url)); return BuildTextResourceDecoderFor(&document, content_type, g_null_atom) ->Encoding(); } static const WTF::TextEncoding DefaultEncodingForURL(const char* url) { return DefaultEncodingForUrlAndContentType(url, "text/html"); } TEST(TextResourceDecoderBuilderTest, defaultEncodingForJsonIsUTF8) { EXPECT_EQ(WTF::TextEncoding("UTF-8"), DefaultEncodingForUrlAndContentType( "https://udarenieru.ru/1.2/dealers/", "application/json")); } TEST(TextResourceDecoderBuilderTest, defaultEncodingComesFromTopLevelDomain) { EXPECT_EQ(WTF::TextEncoding("Shift_JIS"), DefaultEncodingForURL("http://tsubotaa.la.coocan.jp")); EXPECT_EQ(WTF::TextEncoding("windows-1251"), DefaultEncodingForURL("http://udarenieru.ru/index.php")); } TEST(TextResourceDecoderBuilderTest, NoCountryDomainURLDefaultsToLatin1Encoding) { // Latin1 encoding is set in |TextResourceDecoder::defaultEncoding()|. EXPECT_EQ(WTF::Latin1Encoding(), DefaultEncodingForURL("http://arstechnica.com/about-us")); } } // namespace blink
null
null
null
null
29,353
19,428
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
19,428
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 "components/variations/metrics.h" #include "base/metrics/histogram_macros.h" namespace variations { #if defined(OS_ANDROID) void RecordFirstRunSeedImportResult(FirstRunSeedImportResult result) { UMA_HISTOGRAM_ENUMERATION("Variations.FirstRunResult", result, FirstRunSeedImportResult::ENUM_SIZE); } #endif // OS_ANDROID void RecordLoadSeedResult(LoadSeedResult state) { UMA_HISTOGRAM_ENUMERATION("Variations.SeedLoadResult", state, LoadSeedResult::ENUM_SIZE); } void RecordLoadSafeSeedResult(LoadSeedResult state) { UMA_HISTOGRAM_ENUMERATION("Variations.SafeMode.LoadSafeSeed.Result", state, LoadSeedResult::ENUM_SIZE); } void RecordStoreSeedResult(StoreSeedResult result) { UMA_HISTOGRAM_ENUMERATION("Variations.SeedStoreResult", result, StoreSeedResult::ENUM_SIZE); } } // namespace variations
null
null
null
null
16,291
9,239
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
174,234
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * opp2xxx.h - macros for old-style OMAP2xxx "OPP" definitions * * Copyright (C) 2005-2009 Texas Instruments, Inc. * Copyright (C) 2004-2009 Nokia Corporation * * Richard Woodruff <r-woodruff2@ti.com> * * The OMAP2 processor can be run at several discrete 'PRCM configurations'. * These configurations are characterized by voltage and speed for clocks. * The device is only validated for certain combinations. One way to express * these combinations is via the 'ratio's' which the clocks operate with * respect to each other. These ratio sets are for a given voltage/DPLL * setting. All configurations can be described by a DPLL setting and a ratio * There are 3 ratio sets for the 2430 and X ratio sets for 2420. * * 2430 differs from 2420 in that there are no more phase synchronizers used. * They both have a slightly different clock domain setup. 2420(iva1,dsp) vs * 2430 (iva2.1, NOdsp, mdm) * * XXX Missing voltage data. * * THe format described in this file is deprecated. Once a reasonable * OPP API exists, the data in this file should be converted to use it. * * This is technically part of the OMAP2xxx clock code. */ #ifndef __ARCH_ARM_MACH_OMAP2_OPP2XXX_H #define __ARCH_ARM_MACH_OMAP2_OPP2XXX_H /** * struct prcm_config - define clock rates on a per-OPP basis (24xx) * * Key dividers which make up a PRCM set. Ratio's for a PRCM are mandated. * xtal_speed, dpll_speed, mpu_speed, CM_CLKSEL_MPU,CM_CLKSEL_DSP * CM_CLKSEL_GFX, CM_CLKSEL1_CORE, CM_CLKSEL1_PLL CM_CLKSEL2_PLL, CM_CLKSEL_MDM * * This is deprecated. As soon as we have a decent OPP API, we should * move all this stuff to it. */ struct prcm_config { unsigned long xtal_speed; /* crystal rate */ unsigned long dpll_speed; /* dpll: out*xtal*M/(N-1)table_recalc */ unsigned long mpu_speed; /* speed of MPU */ unsigned long cm_clksel_mpu; /* mpu divider */ unsigned long cm_clksel_dsp; /* dsp+iva1 div(2420), iva2.1(2430) */ unsigned long cm_clksel_gfx; /* gfx dividers */ unsigned long cm_clksel1_core; /* major subsystem dividers */ unsigned long cm_clksel1_pll; /* m,n */ unsigned long cm_clksel2_pll; /* dpllx1 or x2 out */ unsigned long cm_clksel_mdm; /* modem dividers 2430 only */ unsigned long base_sdrc_rfr; /* base refresh timing for a set */ unsigned short flags; }; /* Core fields for cm_clksel, not ratio governed */ #define RX_CLKSEL_DSS1 (0x10 << 8) #define RX_CLKSEL_DSS2 (0x0 << 13) #define RX_CLKSEL_SSI (0x5 << 20) /*------------------------------------------------------------------------- * Voltage/DPLL ratios *-------------------------------------------------------------------------*/ /* 2430 Ratio's, 2430-Ratio Config 1 */ #define R1_CLKSEL_L3 (4 << 0) #define R1_CLKSEL_L4 (2 << 5) #define R1_CLKSEL_USB (4 << 25) #define R1_CM_CLKSEL1_CORE_VAL (R1_CLKSEL_USB | RX_CLKSEL_SSI | \ RX_CLKSEL_DSS2 | RX_CLKSEL_DSS1 | \ R1_CLKSEL_L4 | R1_CLKSEL_L3) #define R1_CLKSEL_MPU (2 << 0) #define R1_CM_CLKSEL_MPU_VAL R1_CLKSEL_MPU #define R1_CLKSEL_DSP (2 << 0) #define R1_CLKSEL_DSP_IF (2 << 5) #define R1_CM_CLKSEL_DSP_VAL (R1_CLKSEL_DSP | R1_CLKSEL_DSP_IF) #define R1_CLKSEL_GFX (2 << 0) #define R1_CM_CLKSEL_GFX_VAL R1_CLKSEL_GFX #define R1_CLKSEL_MDM (4 << 0) #define R1_CM_CLKSEL_MDM_VAL R1_CLKSEL_MDM /* 2430-Ratio Config 2 */ #define R2_CLKSEL_L3 (6 << 0) #define R2_CLKSEL_L4 (2 << 5) #define R2_CLKSEL_USB (2 << 25) #define R2_CM_CLKSEL1_CORE_VAL (R2_CLKSEL_USB | RX_CLKSEL_SSI | \ RX_CLKSEL_DSS2 | RX_CLKSEL_DSS1 | \ R2_CLKSEL_L4 | R2_CLKSEL_L3) #define R2_CLKSEL_MPU (2 << 0) #define R2_CM_CLKSEL_MPU_VAL R2_CLKSEL_MPU #define R2_CLKSEL_DSP (2 << 0) #define R2_CLKSEL_DSP_IF (3 << 5) #define R2_CM_CLKSEL_DSP_VAL (R2_CLKSEL_DSP | R2_CLKSEL_DSP_IF) #define R2_CLKSEL_GFX (2 << 0) #define R2_CM_CLKSEL_GFX_VAL R2_CLKSEL_GFX #define R2_CLKSEL_MDM (6 << 0) #define R2_CM_CLKSEL_MDM_VAL R2_CLKSEL_MDM /* 2430-Ratio Bootm (BYPASS) */ #define RB_CLKSEL_L3 (1 << 0) #define RB_CLKSEL_L4 (1 << 5) #define RB_CLKSEL_USB (1 << 25) #define RB_CM_CLKSEL1_CORE_VAL (RB_CLKSEL_USB | RX_CLKSEL_SSI | \ RX_CLKSEL_DSS2 | RX_CLKSEL_DSS1 | \ RB_CLKSEL_L4 | RB_CLKSEL_L3) #define RB_CLKSEL_MPU (1 << 0) #define RB_CM_CLKSEL_MPU_VAL RB_CLKSEL_MPU #define RB_CLKSEL_DSP (1 << 0) #define RB_CLKSEL_DSP_IF (1 << 5) #define RB_CM_CLKSEL_DSP_VAL (RB_CLKSEL_DSP | RB_CLKSEL_DSP_IF) #define RB_CLKSEL_GFX (1 << 0) #define RB_CM_CLKSEL_GFX_VAL RB_CLKSEL_GFX #define RB_CLKSEL_MDM (1 << 0) #define RB_CM_CLKSEL_MDM_VAL RB_CLKSEL_MDM /* 2420 Ratio Equivalents */ #define RXX_CLKSEL_VLYNQ (0x12 << 15) #define RXX_CLKSEL_SSI (0x8 << 20) /* 2420-PRCM III 532MHz core */ #define RIII_CLKSEL_L3 (4 << 0) /* 133MHz */ #define RIII_CLKSEL_L4 (2 << 5) /* 66.5MHz */ #define RIII_CLKSEL_USB (4 << 25) /* 33.25MHz */ #define RIII_CM_CLKSEL1_CORE_VAL (RIII_CLKSEL_USB | RXX_CLKSEL_SSI | \ RXX_CLKSEL_VLYNQ | RX_CLKSEL_DSS2 | \ RX_CLKSEL_DSS1 | RIII_CLKSEL_L4 | \ RIII_CLKSEL_L3) #define RIII_CLKSEL_MPU (2 << 0) /* 266MHz */ #define RIII_CM_CLKSEL_MPU_VAL RIII_CLKSEL_MPU #define RIII_CLKSEL_DSP (3 << 0) /* c5x - 177.3MHz */ #define RIII_CLKSEL_DSP_IF (2 << 5) /* c5x - 88.67MHz */ #define RIII_SYNC_DSP (1 << 7) /* Enable sync */ #define RIII_CLKSEL_IVA (6 << 8) /* iva1 - 88.67MHz */ #define RIII_SYNC_IVA (1 << 13) /* Enable sync */ #define RIII_CM_CLKSEL_DSP_VAL (RIII_SYNC_IVA | RIII_CLKSEL_IVA | \ RIII_SYNC_DSP | RIII_CLKSEL_DSP_IF | \ RIII_CLKSEL_DSP) #define RIII_CLKSEL_GFX (2 << 0) /* 66.5MHz */ #define RIII_CM_CLKSEL_GFX_VAL RIII_CLKSEL_GFX /* 2420-PRCM II 600MHz core */ #define RII_CLKSEL_L3 (6 << 0) /* 100MHz */ #define RII_CLKSEL_L4 (2 << 5) /* 50MHz */ #define RII_CLKSEL_USB (2 << 25) /* 50MHz */ #define RII_CM_CLKSEL1_CORE_VAL (RII_CLKSEL_USB | RXX_CLKSEL_SSI | \ RXX_CLKSEL_VLYNQ | RX_CLKSEL_DSS2 | \ RX_CLKSEL_DSS1 | RII_CLKSEL_L4 | \ RII_CLKSEL_L3) #define RII_CLKSEL_MPU (2 << 0) /* 300MHz */ #define RII_CM_CLKSEL_MPU_VAL RII_CLKSEL_MPU #define RII_CLKSEL_DSP (3 << 0) /* c5x - 200MHz */ #define RII_CLKSEL_DSP_IF (2 << 5) /* c5x - 100MHz */ #define RII_SYNC_DSP (0 << 7) /* Bypass sync */ #define RII_CLKSEL_IVA (3 << 8) /* iva1 - 200MHz */ #define RII_SYNC_IVA (0 << 13) /* Bypass sync */ #define RII_CM_CLKSEL_DSP_VAL (RII_SYNC_IVA | RII_CLKSEL_IVA | \ RII_SYNC_DSP | RII_CLKSEL_DSP_IF | \ RII_CLKSEL_DSP) #define RII_CLKSEL_GFX (2 << 0) /* 50MHz */ #define RII_CM_CLKSEL_GFX_VAL RII_CLKSEL_GFX /* 2420-PRCM I 660MHz core */ #define RI_CLKSEL_L3 (4 << 0) /* 165MHz */ #define RI_CLKSEL_L4 (2 << 5) /* 82.5MHz */ #define RI_CLKSEL_USB (4 << 25) /* 41.25MHz */ #define RI_CM_CLKSEL1_CORE_VAL (RI_CLKSEL_USB | \ RXX_CLKSEL_SSI | RXX_CLKSEL_VLYNQ | \ RX_CLKSEL_DSS2 | RX_CLKSEL_DSS1 | \ RI_CLKSEL_L4 | RI_CLKSEL_L3) #define RI_CLKSEL_MPU (2 << 0) /* 330MHz */ #define RI_CM_CLKSEL_MPU_VAL RI_CLKSEL_MPU #define RI_CLKSEL_DSP (3 << 0) /* c5x - 220MHz */ #define RI_CLKSEL_DSP_IF (2 << 5) /* c5x - 110MHz */ #define RI_SYNC_DSP (1 << 7) /* Activate sync */ #define RI_CLKSEL_IVA (4 << 8) /* iva1 - 165MHz */ #define RI_SYNC_IVA (0 << 13) /* Bypass sync */ #define RI_CM_CLKSEL_DSP_VAL (RI_SYNC_IVA | RI_CLKSEL_IVA | \ RI_SYNC_DSP | RI_CLKSEL_DSP_IF | \ RI_CLKSEL_DSP) #define RI_CLKSEL_GFX (1 << 0) /* 165MHz */ #define RI_CM_CLKSEL_GFX_VAL RI_CLKSEL_GFX /* 2420-PRCM VII (boot) */ #define RVII_CLKSEL_L3 (1 << 0) #define RVII_CLKSEL_L4 (1 << 5) #define RVII_CLKSEL_DSS1 (1 << 8) #define RVII_CLKSEL_DSS2 (0 << 13) #define RVII_CLKSEL_VLYNQ (1 << 15) #define RVII_CLKSEL_SSI (1 << 20) #define RVII_CLKSEL_USB (1 << 25) #define RVII_CM_CLKSEL1_CORE_VAL (RVII_CLKSEL_USB | RVII_CLKSEL_SSI | \ RVII_CLKSEL_VLYNQ | \ RVII_CLKSEL_DSS2 | RVII_CLKSEL_DSS1 | \ RVII_CLKSEL_L4 | RVII_CLKSEL_L3) #define RVII_CLKSEL_MPU (1 << 0) /* all divide by 1 */ #define RVII_CM_CLKSEL_MPU_VAL RVII_CLKSEL_MPU #define RVII_CLKSEL_DSP (1 << 0) #define RVII_CLKSEL_DSP_IF (1 << 5) #define RVII_SYNC_DSP (0 << 7) #define RVII_CLKSEL_IVA (1 << 8) #define RVII_SYNC_IVA (0 << 13) #define RVII_CM_CLKSEL_DSP_VAL (RVII_SYNC_IVA | RVII_CLKSEL_IVA | \ RVII_SYNC_DSP | RVII_CLKSEL_DSP_IF | \ RVII_CLKSEL_DSP) #define RVII_CLKSEL_GFX (1 << 0) #define RVII_CM_CLKSEL_GFX_VAL RVII_CLKSEL_GFX /*------------------------------------------------------------------------- * 2430 Target modes: Along with each configuration the CPU has several * modes which goes along with them. Modes mainly are the addition of * describe DPLL combinations to go along with a ratio. *-------------------------------------------------------------------------*/ /* Hardware governed */ #define MX_48M_SRC (0 << 3) #define MX_54M_SRC (0 << 5) #define MX_APLLS_CLIKIN_12 (3 << 23) #define MX_APLLS_CLIKIN_13 (2 << 23) #define MX_APLLS_CLIKIN_19_2 (0 << 23) /* * 2430 - standalone, 2*ref*M/(n+1), M/N is for exactness not relock speed * #5a (ratio1) baseport-target, target DPLL = 266*2 = 532MHz */ #define M5A_DPLL_MULT_12 (133 << 12) #define M5A_DPLL_DIV_12 (5 << 8) #define M5A_CM_CLKSEL1_PLL_12_VAL (MX_48M_SRC | MX_54M_SRC | \ M5A_DPLL_DIV_12 | M5A_DPLL_MULT_12 | \ MX_APLLS_CLIKIN_12) #define M5A_DPLL_MULT_13 (61 << 12) #define M5A_DPLL_DIV_13 (2 << 8) #define M5A_CM_CLKSEL1_PLL_13_VAL (MX_48M_SRC | MX_54M_SRC | \ M5A_DPLL_DIV_13 | M5A_DPLL_MULT_13 | \ MX_APLLS_CLIKIN_13) #define M5A_DPLL_MULT_19 (55 << 12) #define M5A_DPLL_DIV_19 (3 << 8) #define M5A_CM_CLKSEL1_PLL_19_VAL (MX_48M_SRC | MX_54M_SRC | \ M5A_DPLL_DIV_19 | M5A_DPLL_MULT_19 | \ MX_APLLS_CLIKIN_19_2) /* #5b (ratio1) target DPLL = 200*2 = 400MHz */ #define M5B_DPLL_MULT_12 (50 << 12) #define M5B_DPLL_DIV_12 (2 << 8) #define M5B_CM_CLKSEL1_PLL_12_VAL (MX_48M_SRC | MX_54M_SRC | \ M5B_DPLL_DIV_12 | M5B_DPLL_MULT_12 | \ MX_APLLS_CLIKIN_12) #define M5B_DPLL_MULT_13 (200 << 12) #define M5B_DPLL_DIV_13 (12 << 8) #define M5B_CM_CLKSEL1_PLL_13_VAL (MX_48M_SRC | MX_54M_SRC | \ M5B_DPLL_DIV_13 | M5B_DPLL_MULT_13 | \ MX_APLLS_CLIKIN_13) #define M5B_DPLL_MULT_19 (125 << 12) #define M5B_DPLL_DIV_19 (31 << 8) #define M5B_CM_CLKSEL1_PLL_19_VAL (MX_48M_SRC | MX_54M_SRC | \ M5B_DPLL_DIV_19 | M5B_DPLL_MULT_19 | \ MX_APLLS_CLIKIN_19_2) /* * #4 (ratio2), DPLL = 399*2 = 798MHz, L3=133MHz */ #define M4_DPLL_MULT_12 (133 << 12) #define M4_DPLL_DIV_12 (3 << 8) #define M4_CM_CLKSEL1_PLL_12_VAL (MX_48M_SRC | MX_54M_SRC | \ M4_DPLL_DIV_12 | M4_DPLL_MULT_12 | \ MX_APLLS_CLIKIN_12) #define M4_DPLL_MULT_13 (399 << 12) #define M4_DPLL_DIV_13 (12 << 8) #define M4_CM_CLKSEL1_PLL_13_VAL (MX_48M_SRC | MX_54M_SRC | \ M4_DPLL_DIV_13 | M4_DPLL_MULT_13 | \ MX_APLLS_CLIKIN_13) #define M4_DPLL_MULT_19 (145 << 12) #define M4_DPLL_DIV_19 (6 << 8) #define M4_CM_CLKSEL1_PLL_19_VAL (MX_48M_SRC | MX_54M_SRC | \ M4_DPLL_DIV_19 | M4_DPLL_MULT_19 | \ MX_APLLS_CLIKIN_19_2) /* * #3 (ratio2) baseport-target, target DPLL = 330*2 = 660MHz */ #define M3_DPLL_MULT_12 (55 << 12) #define M3_DPLL_DIV_12 (1 << 8) #define M3_CM_CLKSEL1_PLL_12_VAL (MX_48M_SRC | MX_54M_SRC | \ M3_DPLL_DIV_12 | M3_DPLL_MULT_12 | \ MX_APLLS_CLIKIN_12) #define M3_DPLL_MULT_13 (76 << 12) #define M3_DPLL_DIV_13 (2 << 8) #define M3_CM_CLKSEL1_PLL_13_VAL (MX_48M_SRC | MX_54M_SRC | \ M3_DPLL_DIV_13 | M3_DPLL_MULT_13 | \ MX_APLLS_CLIKIN_13) #define M3_DPLL_MULT_19 (17 << 12) #define M3_DPLL_DIV_19 (0 << 8) #define M3_CM_CLKSEL1_PLL_19_VAL (MX_48M_SRC | MX_54M_SRC | \ M3_DPLL_DIV_19 | M3_DPLL_MULT_19 | \ MX_APLLS_CLIKIN_19_2) /* * #2 (ratio1) DPLL = 330*2 = 660MHz, L3=165MHz */ #define M2_DPLL_MULT_12 (55 << 12) #define M2_DPLL_DIV_12 (1 << 8) #define M2_CM_CLKSEL1_PLL_12_VAL (MX_48M_SRC | MX_54M_SRC | \ M2_DPLL_DIV_12 | M2_DPLL_MULT_12 | \ MX_APLLS_CLIKIN_12) /* Speed changes - Used 658.7MHz instead of 660MHz for LP-Refresh M=76 N=2, * relock time issue */ /* Core frequency changed from 330/165 to 329/164 MHz*/ #define M2_DPLL_MULT_13 (76 << 12) #define M2_DPLL_DIV_13 (2 << 8) #define M2_CM_CLKSEL1_PLL_13_VAL (MX_48M_SRC | MX_54M_SRC | \ M2_DPLL_DIV_13 | M2_DPLL_MULT_13 | \ MX_APLLS_CLIKIN_13) #define M2_DPLL_MULT_19 (17 << 12) #define M2_DPLL_DIV_19 (0 << 8) #define M2_CM_CLKSEL1_PLL_19_VAL (MX_48M_SRC | MX_54M_SRC | \ M2_DPLL_DIV_19 | M2_DPLL_MULT_19 | \ MX_APLLS_CLIKIN_19_2) /* boot (boot) */ #define MB_DPLL_MULT (1 << 12) #define MB_DPLL_DIV (0 << 8) #define MB_CM_CLKSEL1_PLL_12_VAL (MX_48M_SRC | MX_54M_SRC | \ MB_DPLL_DIV | MB_DPLL_MULT | \ MX_APLLS_CLIKIN_12) #define MB_CM_CLKSEL1_PLL_13_VAL (MX_48M_SRC | MX_54M_SRC | \ MB_DPLL_DIV | MB_DPLL_MULT | \ MX_APLLS_CLIKIN_13) #define MB_CM_CLKSEL1_PLL_19_VAL (MX_48M_SRC | MX_54M_SRC | \ MB_DPLL_DIV | MB_DPLL_MULT | \ MX_APLLS_CLIKIN_19) /* * 2430 - chassis (sedna) * 165 (ratio1) same as above #2 * 150 (ratio1) * 133 (ratio2) same as above #4 * 110 (ratio2) same as above #3 * 104 (ratio2) * boot (boot) */ /* PRCM I target DPLL = 2*330MHz = 660MHz */ #define MI_DPLL_MULT_12 (55 << 12) #define MI_DPLL_DIV_12 (1 << 8) #define MI_CM_CLKSEL1_PLL_12_VAL (MX_48M_SRC | MX_54M_SRC | \ MI_DPLL_DIV_12 | MI_DPLL_MULT_12 | \ MX_APLLS_CLIKIN_12) /* * 2420 Equivalent - mode registers * PRCM II , target DPLL = 2*300MHz = 600MHz */ #define MII_DPLL_MULT_12 (50 << 12) #define MII_DPLL_DIV_12 (1 << 8) #define MII_CM_CLKSEL1_PLL_12_VAL (MX_48M_SRC | MX_54M_SRC | \ MII_DPLL_DIV_12 | MII_DPLL_MULT_12 | \ MX_APLLS_CLIKIN_12) #define MII_DPLL_MULT_13 (300 << 12) #define MII_DPLL_DIV_13 (12 << 8) #define MII_CM_CLKSEL1_PLL_13_VAL (MX_48M_SRC | MX_54M_SRC | \ MII_DPLL_DIV_13 | MII_DPLL_MULT_13 | \ MX_APLLS_CLIKIN_13) /* PRCM III target DPLL = 2*266 = 532MHz*/ #define MIII_DPLL_MULT_12 (133 << 12) #define MIII_DPLL_DIV_12 (5 << 8) #define MIII_CM_CLKSEL1_PLL_12_VAL (MX_48M_SRC | MX_54M_SRC | \ MIII_DPLL_DIV_12 | \ MIII_DPLL_MULT_12 | MX_APLLS_CLIKIN_12) #define MIII_DPLL_MULT_13 (266 << 12) #define MIII_DPLL_DIV_13 (12 << 8) #define MIII_CM_CLKSEL1_PLL_13_VAL (MX_48M_SRC | MX_54M_SRC | \ MIII_DPLL_DIV_13 | \ MIII_DPLL_MULT_13 | MX_APLLS_CLIKIN_13) /* PRCM VII (boot bypass) */ #define MVII_CM_CLKSEL1_PLL_12_VAL MB_CM_CLKSEL1_PLL_12_VAL #define MVII_CM_CLKSEL1_PLL_13_VAL MB_CM_CLKSEL1_PLL_13_VAL /* High and low operation value */ #define MX_CLKSEL2_PLL_2x_VAL (2 << 0) #define MX_CLKSEL2_PLL_1x_VAL (1 << 0) /* MPU speed defines */ #define S12M 12000000 #define S13M 13000000 #define S19M 19200000 #define S26M 26000000 #define S100M 100000000 #define S133M 133000000 #define S150M 150000000 #define S164M 164000000 #define S165M 165000000 #define S199M 199000000 #define S200M 200000000 #define S266M 266000000 #define S300M 300000000 #define S329M 329000000 #define S330M 330000000 #define S399M 399000000 #define S400M 400000000 #define S532M 532000000 #define S600M 600000000 #define S658M 658000000 #define S660M 660000000 #define S798M 798000000 extern const struct prcm_config omap2420_rate_table[]; #ifdef CONFIG_SOC_OMAP2430 extern const struct prcm_config omap2430_rate_table[]; #else #define omap2430_rate_table NULL #endif extern const struct prcm_config *rate_table; extern const struct prcm_config *curr_prcm_set; #endif
null
null
null
null
82,581
16,080
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
181,075
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Copyright (C) 2005 MIPS Technologies, Inc. All rights reserved. * * This program is free software; you can distribute 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 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 _ASM_MIPS_BOARDS_SIM_H #define _ASM_MIPS_BOARDS_SIM_H #define STATS_ON 1 #define STATS_OFF 2 #define STATS_CLEAR 3 #define STATS_DUMP 4 #define TRACE_ON 5 #define TRACE_OFF 6 #define simcfg(code) \ ({ \ __asm__ __volatile__( \ "sltiu $0,$0, %0" \ ::"i"(code) \ ); \ }) #endif
null
null
null
null
89,422
24,627
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
24,627
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 "extensions/shell/browser/shell_keep_alive_requester.h" #include <memory> #include "apps/app_lifetime_monitor_factory.h" #include "base/macros.h" #include "components/keep_alive_registry/keep_alive_registry.h" #include "content/public/browser/browser_context.h" #include "extensions/browser/disable_reason.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extensions_test.h" #include "extensions/common/extension.h" #include "extensions/common/extension_builder.h" #include "extensions/common/extension_id.h" namespace extensions { class ShellKeepAliveRequesterTest : public ExtensionsTest { protected: ShellKeepAliveRequesterTest() = default; ~ShellKeepAliveRequesterTest() override = default; void SetUp() override { // Register factory so it's created with the BrowserContext. apps::AppLifetimeMonitorFactory::GetInstance(); ExtensionsTest::SetUp(); keep_alive_requester_ = std::make_unique<ShellKeepAliveRequester>(browser_context()); } void TearDown() override { keep_alive_requester_.reset(); ExtensionsTest::TearDown(); } protected: std::unique_ptr<ShellKeepAliveRequester> keep_alive_requester_; private: DISALLOW_COPY_AND_ASSIGN(ShellKeepAliveRequesterTest); }; // Tests with an extension. TEST_F(ShellKeepAliveRequesterTest, Extension) { scoped_refptr<const Extension> extension = ExtensionBuilder("extension", ExtensionBuilder::Type::EXTENSION).Build(); // No keep-alive is used for extensions that aren't platform apps. keep_alive_requester_->OnExtensionLoaded(browser_context(), extension.get()); EXPECT_FALSE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); ExtensionPrefs::Get(browser_context()) ->AddDisableReason(extension->id(), disable_reason::DISABLE_RELOAD); keep_alive_requester_->OnExtensionUnloaded(browser_context(), extension.get(), UnloadedExtensionReason::DISABLE); EXPECT_FALSE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); } // Tests with a platform app. TEST_F(ShellKeepAliveRequesterTest, PlatformApp) { scoped_refptr<const Extension> extension = ExtensionBuilder("platform_app", ExtensionBuilder::Type::PLATFORM_APP) .Build(); keep_alive_requester_->OnExtensionLoaded(browser_context(), extension.get()); // Expect a keep-alive while waiting for the app to launch a window. EXPECT_TRUE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); keep_alive_requester_->OnAppActivated(browser_context(), extension->id()); EXPECT_FALSE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); // No keep-alives are registered if the extension stops running. keep_alive_requester_->OnAppStop(browser_context(), extension->id()); EXPECT_FALSE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); } // Tests with a platform app that doesn't open a window. TEST_F(ShellKeepAliveRequesterTest, PlatformAppNoWindow) { scoped_refptr<const Extension> extension = ExtensionBuilder("platform_app", ExtensionBuilder::Type::PLATFORM_APP) .Build(); keep_alive_requester_->OnExtensionLoaded(browser_context(), extension.get()); // Expect a keep-alive while waiting for the app to launch a window. EXPECT_TRUE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); // Eventually, the app's background host is destroyed. keep_alive_requester_->OnAppStop(browser_context(), extension->id()); EXPECT_FALSE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); } // Tests with a platform app that is reloaded. TEST_F(ShellKeepAliveRequesterTest, PlatformAppReload) { scoped_refptr<const Extension> extension = ExtensionBuilder("platform_app", ExtensionBuilder::Type::PLATFORM_APP) .Build(); keep_alive_requester_->OnExtensionLoaded(browser_context(), extension.get()); // Expect a keep-alive while waiting for the app to launch a window. EXPECT_TRUE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); keep_alive_requester_->OnAppActivated(browser_context(), extension->id()); EXPECT_FALSE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); // Disable the app for a reload. keep_alive_requester_->StartTrackingReload(extension.get()); ExtensionPrefs::Get(browser_context()) ->AddDisableReason(extension->id(), disable_reason::DISABLE_RELOAD); keep_alive_requester_->OnAppStop(browser_context(), extension->id()); keep_alive_requester_->OnExtensionUnloaded(browser_context(), extension.get(), UnloadedExtensionReason::DISABLE); // Expect a keep-alive while waiting for the app to finish reloading. EXPECT_TRUE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); keep_alive_requester_->OnExtensionLoaded(browser_context(), extension.get()); keep_alive_requester_->StopTrackingReload(extension->id()); // Expect a keep-alive while waiting for the app to launch a window again. EXPECT_TRUE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); keep_alive_requester_->OnAppActivated(browser_context(), extension->id()); EXPECT_FALSE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); } // Tests with a platform app that is reloaded, but fails to load. TEST_F(ShellKeepAliveRequesterTest, PlatformAppReloadFailure) { scoped_refptr<const Extension> extension = ExtensionBuilder("platform_app", ExtensionBuilder::Type::PLATFORM_APP) .Build(); keep_alive_requester_->OnExtensionLoaded(browser_context(), extension.get()); // Expect a keep-alive while waiting for the app to launch a window. EXPECT_TRUE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); keep_alive_requester_->OnAppActivated(browser_context(), extension->id()); EXPECT_FALSE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); // Disable the app for a reload. keep_alive_requester_->StartTrackingReload(extension.get()); keep_alive_requester_->OnAppStop(browser_context(), extension->id()); ExtensionPrefs::Get(browser_context()) ->AddDisableReason(extension->id(), disable_reason::DISABLE_RELOAD); keep_alive_requester_->OnExtensionUnloaded(browser_context(), extension.get(), UnloadedExtensionReason::DISABLE); // Expect a keep-alive while waiting for the app to finish reloading that is // removed when the app fails to load. EXPECT_TRUE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); keep_alive_requester_->StopTrackingReload(extension->id()); EXPECT_FALSE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); } // Tests with a platform app that reloads before opening a window. TEST_F(ShellKeepAliveRequesterTest, PlatformAppNoWindowReload) { scoped_refptr<const Extension> extension = ExtensionBuilder("platform_app", ExtensionBuilder::Type::PLATFORM_APP) .Build(); keep_alive_requester_->OnExtensionLoaded(browser_context(), extension.get()); // Expect a keep-alive while waiting for the app to launch a window. EXPECT_TRUE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); // Disable the app for a reload. keep_alive_requester_->StartTrackingReload(extension.get()); keep_alive_requester_->OnAppStop(browser_context(), extension->id()); ExtensionPrefs::Get(browser_context()) ->AddDisableReason(extension->id(), disable_reason::DISABLE_RELOAD); keep_alive_requester_->OnExtensionUnloaded(browser_context(), extension.get(), UnloadedExtensionReason::DISABLE); // Expect a keep-alive while waiting for the app to finish reloading. EXPECT_TRUE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); keep_alive_requester_->OnExtensionLoaded(browser_context(), extension.get()); keep_alive_requester_->StopTrackingReload(extension->id()); // Expect a keep-alive while waiting for the app to launch a window. EXPECT_TRUE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); keep_alive_requester_->OnAppActivated(browser_context(), extension->id()); EXPECT_FALSE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); } // Tests with a platform app that is reloaded, but doesn't open a window again. TEST_F(ShellKeepAliveRequesterTest, PlatformAppReloadNoWindow) { scoped_refptr<const Extension> extension = ExtensionBuilder("platform_app", ExtensionBuilder::Type::PLATFORM_APP) .Build(); keep_alive_requester_->OnExtensionLoaded(browser_context(), extension.get()); // Expect a keep-alive while waiting for the app to launch a window. EXPECT_TRUE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); keep_alive_requester_->OnAppActivated(browser_context(), extension->id()); EXPECT_FALSE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); // Disable the app for a reload. keep_alive_requester_->StartTrackingReload(extension.get()); keep_alive_requester_->OnAppStop(browser_context(), extension->id()); ExtensionPrefs::Get(browser_context()) ->AddDisableReason(extension->id(), disable_reason::DISABLE_RELOAD); keep_alive_requester_->OnExtensionUnloaded(browser_context(), extension.get(), UnloadedExtensionReason::DISABLE); // Expect a keep-alive while waiting for the app to finish reloading. EXPECT_TRUE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); keep_alive_requester_->OnExtensionLoaded(browser_context(), extension.get()); keep_alive_requester_->StopTrackingReload(extension->id()); // Expect a keep-alive while waiting for the app to launch a window again. EXPECT_TRUE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); // Eventually the app stops. keep_alive_requester_->OnAppStop(browser_context(), extension->id()); EXPECT_FALSE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); } } // namespace extensions
null
null
null
null
21,490
27,752
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
27,752
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. #import <Foundation/Foundation.h> #import "GPBBootstrap.h" @class GPBEnumDescriptor; @class GPBMessage; @class GPBInt32Array; /** * Verifies that a given value can be represented by an enum type. * */ typedef BOOL (*GPBEnumValidationFunc)(int32_t); /** * Fetches an EnumDescriptor. * */ typedef GPBEnumDescriptor *(*GPBEnumDescriptorFunc)(void); /** * Magic value used at runtime to indicate an enum value that wasn't know at * compile time. * */ enum { kGPBUnrecognizedEnumeratorValue = (int32_t)0xFBADBEEF, }; /** * A union for storing all possible Protobuf values. Note that owner is * responsible for memory management of object types. * */ typedef union { BOOL valueBool; int32_t valueInt32; int64_t valueInt64; uint32_t valueUInt32; uint64_t valueUInt64; float valueFloat; double valueDouble; GPB_UNSAFE_UNRETAINED NSData *valueData; GPB_UNSAFE_UNRETAINED NSString *valueString; GPB_UNSAFE_UNRETAINED GPBMessage *valueMessage; int32_t valueEnum; } GPBGenericValue; /** * Enum listing the possible data types that a field can contain. * * @note Do not change the order of this enum (or add things to it) without * thinking about it very carefully. There are several things that depend * on the order. * */ typedef NS_ENUM(uint8_t, GPBDataType) { /** Field contains boolean value(s). */ GPBDataTypeBool = 0, /** Field contains unsigned 4 byte value(s). */ GPBDataTypeFixed32, /** Field contains signed 4 byte value(s). */ GPBDataTypeSFixed32, /** Field contains float value(s). */ GPBDataTypeFloat, /** Field contains unsigned 8 byte value(s). */ GPBDataTypeFixed64, /** Field contains signed 8 byte value(s). */ GPBDataTypeSFixed64, /** Field contains double value(s). */ GPBDataTypeDouble, /** * Field contains variable length value(s). Inefficient for encoding negative * numbers – if your field is likely to have negative values, use * GPBDataTypeSInt32 instead. **/ GPBDataTypeInt32, /** * Field contains variable length value(s). Inefficient for encoding negative * numbers – if your field is likely to have negative values, use * GPBDataTypeSInt64 instead. **/ GPBDataTypeInt64, /** Field contains signed variable length integer value(s). */ GPBDataTypeSInt32, /** Field contains signed variable length integer value(s). */ GPBDataTypeSInt64, /** Field contains unsigned variable length integer value(s). */ GPBDataTypeUInt32, /** Field contains unsigned variable length integer value(s). */ GPBDataTypeUInt64, /** Field contains an arbitrary sequence of bytes. */ GPBDataTypeBytes, /** Field contains UTF-8 encoded or 7-bit ASCII text. */ GPBDataTypeString, /** Field contains message type(s). */ GPBDataTypeMessage, /** Field contains message type(s). */ GPBDataTypeGroup, /** Field contains enum value(s). */ GPBDataTypeEnum, }; enum { /** * A count of the number of types in GPBDataType. Separated out from the * GPBDataType enum to avoid warnings regarding not handling GPBDataType_Count * in switch statements. **/ GPBDataType_Count = GPBDataTypeEnum + 1 }; /** An extension range. */ typedef struct GPBExtensionRange { /** Inclusive. */ uint32_t start; /** Exclusive. */ uint32_t end; } GPBExtensionRange;
null
null
null
null
24,615
3,528
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
168,523
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * This file is part of UBIFS. * * Copyright (C) 2006-2008 Nokia Corporation. * * 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., 51 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Authors: Artem Bityutskiy (Битюцкий Артём) * Adrian Hunter */ /* * This file implements UBIFS extended attributes support. * * Extended attributes are implemented as regular inodes with attached data, * which limits extended attribute size to UBIFS block size (4KiB). Names of * extended attributes are described by extended attribute entries (xentries), * which are almost identical to directory entries, but have different key type. * * In other words, the situation with extended attributes is very similar to * directories. Indeed, any inode (but of course not xattr inodes) may have a * number of associated xentries, just like directory inodes have associated * directory entries. Extended attribute entries store the name of the extended * attribute, the host inode number, and the extended attribute inode number. * Similarly, direntries store the name, the parent and the target inode * numbers. Thus, most of the common UBIFS mechanisms may be re-used for * extended attributes. * * The number of extended attributes is not limited, but there is Linux * limitation on the maximum possible size of the list of all extended * attributes associated with an inode (%XATTR_LIST_MAX), so UBIFS makes sure * the sum of all extended attribute names of the inode does not exceed that * limit. * * Extended attributes are synchronous, which means they are written to the * flash media synchronously and there is no write-back for extended attribute * inodes. The extended attribute values are not stored in compressed form on * the media. * * Since extended attributes are represented by regular inodes, they are cached * in the VFS inode cache. The xentries are cached in the LNC cache (see * tnc.c). * * ACL support is not implemented. */ #include "ubifs.h" #include <linux/fs.h> #include <linux/slab.h> #include <linux/xattr.h> /* * Limit the number of extended attributes per inode so that the total size * (@xattr_size) is guaranteeded to fit in an 'unsigned int'. */ #define MAX_XATTRS_PER_INODE 65535 /* * Extended attribute type constants. * * USER_XATTR: user extended attribute ("user.*") * TRUSTED_XATTR: trusted extended attribute ("trusted.*) * SECURITY_XATTR: security extended attribute ("security.*") */ enum { USER_XATTR, TRUSTED_XATTR, SECURITY_XATTR, }; static const struct inode_operations empty_iops; static const struct file_operations empty_fops; /** * create_xattr - create an extended attribute. * @c: UBIFS file-system description object * @host: host inode * @nm: extended attribute name * @value: extended attribute value * @size: size of extended attribute value * * This is a helper function which creates an extended attribute of name @nm * and value @value for inode @host. The host inode is also updated on flash * because the ctime and extended attribute accounting data changes. This * function returns zero in case of success and a negative error code in case * of failure. */ static int create_xattr(struct ubifs_info *c, struct inode *host, const struct fscrypt_name *nm, const void *value, int size) { int err, names_len; struct inode *inode; struct ubifs_inode *ui, *host_ui = ubifs_inode(host); struct ubifs_budget_req req = { .new_ino = 1, .new_dent = 1, .new_ino_d = ALIGN(size, 8), .dirtied_ino = 1, .dirtied_ino_d = ALIGN(host_ui->data_len, 8) }; if (host_ui->xattr_cnt >= MAX_XATTRS_PER_INODE) { ubifs_err(c, "inode %lu already has too many xattrs (%d), cannot create more", host->i_ino, host_ui->xattr_cnt); return -ENOSPC; } /* * Linux limits the maximum size of the extended attribute names list * to %XATTR_LIST_MAX. This means we should not allow creating more * extended attributes if the name list becomes larger. This limitation * is artificial for UBIFS, though. */ names_len = host_ui->xattr_names + host_ui->xattr_cnt + fname_len(nm) + 1; if (names_len > XATTR_LIST_MAX) { ubifs_err(c, "cannot add one more xattr name to inode %lu, total names length would become %d, max. is %d", host->i_ino, names_len, XATTR_LIST_MAX); return -ENOSPC; } err = ubifs_budget_space(c, &req); if (err) return err; inode = ubifs_new_inode(c, host, S_IFREG | S_IRWXUGO); if (IS_ERR(inode)) { err = PTR_ERR(inode); goto out_budg; } /* Re-define all operations to be "nothing" */ inode->i_mapping->a_ops = &empty_aops; inode->i_op = &empty_iops; inode->i_fop = &empty_fops; inode->i_flags |= S_SYNC | S_NOATIME | S_NOCMTIME | S_NOQUOTA; ui = ubifs_inode(inode); ui->xattr = 1; ui->flags |= UBIFS_XATTR_FL; ui->data = kmemdup(value, size, GFP_NOFS); if (!ui->data) { err = -ENOMEM; goto out_free; } inode->i_size = ui->ui_size = size; ui->data_len = size; mutex_lock(&host_ui->ui_mutex); host->i_ctime = ubifs_current_time(host); host_ui->xattr_cnt += 1; host_ui->xattr_size += CALC_DENT_SIZE(fname_len(nm)); host_ui->xattr_size += CALC_XATTR_BYTES(size); host_ui->xattr_names += fname_len(nm); /* * We handle UBIFS_XATTR_NAME_ENCRYPTION_CONTEXT here because we * have to set the UBIFS_CRYPT_FL flag on the host inode. * To avoid multiple updates of the same inode in the same operation, * let's do it here. */ if (strcmp(fname_name(nm), UBIFS_XATTR_NAME_ENCRYPTION_CONTEXT) == 0) host_ui->flags |= UBIFS_CRYPT_FL; err = ubifs_jnl_update(c, host, nm, inode, 0, 1); if (err) goto out_cancel; mutex_unlock(&host_ui->ui_mutex); ubifs_release_budget(c, &req); insert_inode_hash(inode); iput(inode); return 0; out_cancel: host_ui->xattr_cnt -= 1; host_ui->xattr_size -= CALC_DENT_SIZE(fname_len(nm)); host_ui->xattr_size -= CALC_XATTR_BYTES(size); host_ui->xattr_names -= fname_len(nm); host_ui->flags &= ~UBIFS_CRYPT_FL; mutex_unlock(&host_ui->ui_mutex); out_free: make_bad_inode(inode); iput(inode); out_budg: ubifs_release_budget(c, &req); return err; } /** * change_xattr - change an extended attribute. * @c: UBIFS file-system description object * @host: host inode * @inode: extended attribute inode * @value: extended attribute value * @size: size of extended attribute value * * This helper function changes the value of extended attribute @inode with new * data from @value. Returns zero in case of success and a negative error code * in case of failure. */ static int change_xattr(struct ubifs_info *c, struct inode *host, struct inode *inode, const void *value, int size) { int err; struct ubifs_inode *host_ui = ubifs_inode(host); struct ubifs_inode *ui = ubifs_inode(inode); void *buf = NULL; int old_size; struct ubifs_budget_req req = { .dirtied_ino = 2, .dirtied_ino_d = ALIGN(size, 8) + ALIGN(host_ui->data_len, 8) }; ubifs_assert(ui->data_len == inode->i_size); err = ubifs_budget_space(c, &req); if (err) return err; buf = kmemdup(value, size, GFP_NOFS); if (!buf) { err = -ENOMEM; goto out_free; } mutex_lock(&ui->ui_mutex); kfree(ui->data); ui->data = buf; inode->i_size = ui->ui_size = size; old_size = ui->data_len; ui->data_len = size; mutex_unlock(&ui->ui_mutex); mutex_lock(&host_ui->ui_mutex); host->i_ctime = ubifs_current_time(host); host_ui->xattr_size -= CALC_XATTR_BYTES(old_size); host_ui->xattr_size += CALC_XATTR_BYTES(size); /* * It is important to write the host inode after the xattr inode * because if the host inode gets synchronized (via 'fsync()'), then * the extended attribute inode gets synchronized, because it goes * before the host inode in the write-buffer. */ err = ubifs_jnl_change_xattr(c, inode, host); if (err) goto out_cancel; mutex_unlock(&host_ui->ui_mutex); ubifs_release_budget(c, &req); return 0; out_cancel: host_ui->xattr_size -= CALC_XATTR_BYTES(size); host_ui->xattr_size += CALC_XATTR_BYTES(old_size); mutex_unlock(&host_ui->ui_mutex); make_bad_inode(inode); out_free: ubifs_release_budget(c, &req); return err; } static struct inode *iget_xattr(struct ubifs_info *c, ino_t inum) { struct inode *inode; inode = ubifs_iget(c->vfs_sb, inum); if (IS_ERR(inode)) { ubifs_err(c, "dead extended attribute entry, error %d", (int)PTR_ERR(inode)); return inode; } if (ubifs_inode(inode)->xattr) return inode; ubifs_err(c, "corrupt extended attribute entry"); iput(inode); return ERR_PTR(-EINVAL); } int ubifs_xattr_set(struct inode *host, const char *name, const void *value, size_t size, int flags) { struct inode *inode; struct ubifs_info *c = host->i_sb->s_fs_info; struct fscrypt_name nm = { .disk_name = FSTR_INIT((char *)name, strlen(name))}; struct ubifs_dent_node *xent; union ubifs_key key; int err; /* * Creating an encryption context is done unlocked since we * operate on a new inode which is not visible to other users * at this point. */ if (strcmp(name, UBIFS_XATTR_NAME_ENCRYPTION_CONTEXT) != 0) ubifs_assert(inode_is_locked(host)); if (size > UBIFS_MAX_INO_DATA) return -ERANGE; if (fname_len(&nm) > UBIFS_MAX_NLEN) return -ENAMETOOLONG; xent = kmalloc(UBIFS_MAX_XENT_NODE_SZ, GFP_NOFS); if (!xent) return -ENOMEM; /* * The extended attribute entries are stored in LNC, so multiple * look-ups do not involve reading the flash. */ xent_key_init(c, &key, host->i_ino, &nm); err = ubifs_tnc_lookup_nm(c, &key, xent, &nm); if (err) { if (err != -ENOENT) goto out_free; if (flags & XATTR_REPLACE) /* We are asked not to create the xattr */ err = -ENODATA; else err = create_xattr(c, host, &nm, value, size); goto out_free; } if (flags & XATTR_CREATE) { /* We are asked not to replace the xattr */ err = -EEXIST; goto out_free; } inode = iget_xattr(c, le64_to_cpu(xent->inum)); if (IS_ERR(inode)) { err = PTR_ERR(inode); goto out_free; } err = change_xattr(c, host, inode, value, size); iput(inode); out_free: kfree(xent); return err; } ssize_t ubifs_xattr_get(struct inode *host, const char *name, void *buf, size_t size) { struct inode *inode; struct ubifs_info *c = host->i_sb->s_fs_info; struct fscrypt_name nm = { .disk_name = FSTR_INIT((char *)name, strlen(name))}; struct ubifs_inode *ui; struct ubifs_dent_node *xent; union ubifs_key key; int err; if (fname_len(&nm) > UBIFS_MAX_NLEN) return -ENAMETOOLONG; xent = kmalloc(UBIFS_MAX_XENT_NODE_SZ, GFP_NOFS); if (!xent) return -ENOMEM; xent_key_init(c, &key, host->i_ino, &nm); err = ubifs_tnc_lookup_nm(c, &key, xent, &nm); if (err) { if (err == -ENOENT) err = -ENODATA; goto out_unlock; } inode = iget_xattr(c, le64_to_cpu(xent->inum)); if (IS_ERR(inode)) { err = PTR_ERR(inode); goto out_unlock; } ui = ubifs_inode(inode); ubifs_assert(inode->i_size == ui->data_len); ubifs_assert(ubifs_inode(host)->xattr_size > ui->data_len); mutex_lock(&ui->ui_mutex); if (buf) { /* If @buf is %NULL we are supposed to return the length */ if (ui->data_len > size) { ubifs_err(c, "buffer size %zd, xattr len %d", size, ui->data_len); err = -ERANGE; goto out_iput; } memcpy(buf, ui->data, ui->data_len); } err = ui->data_len; out_iput: mutex_unlock(&ui->ui_mutex); iput(inode); out_unlock: kfree(xent); return err; } static bool xattr_visible(const char *name) { /* File encryption related xattrs are for internal use only */ if (strcmp(name, UBIFS_XATTR_NAME_ENCRYPTION_CONTEXT) == 0) return false; /* Show trusted namespace only for "power" users */ if (strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) == 0 && !capable(CAP_SYS_ADMIN)) return false; return true; } ssize_t ubifs_listxattr(struct dentry *dentry, char *buffer, size_t size) { union ubifs_key key; struct inode *host = d_inode(dentry); struct ubifs_info *c = host->i_sb->s_fs_info; struct ubifs_inode *host_ui = ubifs_inode(host); struct ubifs_dent_node *xent, *pxent = NULL; int err, len, written = 0; struct fscrypt_name nm = {0}; dbg_gen("ino %lu ('%pd'), buffer size %zd", host->i_ino, dentry, size); len = host_ui->xattr_names + host_ui->xattr_cnt; if (!buffer) /* * We should return the minimum buffer size which will fit a * null-terminated list of all the extended attribute names. */ return len; if (len > size) return -ERANGE; lowest_xent_key(c, &key, host->i_ino); while (1) { xent = ubifs_tnc_next_ent(c, &key, &nm); if (IS_ERR(xent)) { err = PTR_ERR(xent); break; } fname_name(&nm) = xent->name; fname_len(&nm) = le16_to_cpu(xent->nlen); if (xattr_visible(xent->name)) { memcpy(buffer + written, fname_name(&nm), fname_len(&nm) + 1); written += fname_len(&nm) + 1; } kfree(pxent); pxent = xent; key_read(c, &xent->key, &key); } kfree(pxent); if (err != -ENOENT) { ubifs_err(c, "cannot find next direntry, error %d", err); return err; } ubifs_assert(written <= size); return written; } static int remove_xattr(struct ubifs_info *c, struct inode *host, struct inode *inode, const struct fscrypt_name *nm) { int err; struct ubifs_inode *host_ui = ubifs_inode(host); struct ubifs_inode *ui = ubifs_inode(inode); struct ubifs_budget_req req = { .dirtied_ino = 2, .mod_dent = 1, .dirtied_ino_d = ALIGN(host_ui->data_len, 8) }; ubifs_assert(ui->data_len == inode->i_size); err = ubifs_budget_space(c, &req); if (err) return err; mutex_lock(&host_ui->ui_mutex); host->i_ctime = ubifs_current_time(host); host_ui->xattr_cnt -= 1; host_ui->xattr_size -= CALC_DENT_SIZE(fname_len(nm)); host_ui->xattr_size -= CALC_XATTR_BYTES(ui->data_len); host_ui->xattr_names -= fname_len(nm); err = ubifs_jnl_delete_xattr(c, host, inode, nm); if (err) goto out_cancel; mutex_unlock(&host_ui->ui_mutex); ubifs_release_budget(c, &req); return 0; out_cancel: host_ui->xattr_cnt += 1; host_ui->xattr_size += CALC_DENT_SIZE(fname_len(nm)); host_ui->xattr_size += CALC_XATTR_BYTES(ui->data_len); host_ui->xattr_names += fname_len(nm); mutex_unlock(&host_ui->ui_mutex); ubifs_release_budget(c, &req); make_bad_inode(inode); return err; } static int ubifs_xattr_remove(struct inode *host, const char *name) { struct inode *inode; struct ubifs_info *c = host->i_sb->s_fs_info; struct fscrypt_name nm = { .disk_name = FSTR_INIT((char *)name, strlen(name))}; struct ubifs_dent_node *xent; union ubifs_key key; int err; ubifs_assert(inode_is_locked(host)); if (fname_len(&nm) > UBIFS_MAX_NLEN) return -ENAMETOOLONG; xent = kmalloc(UBIFS_MAX_XENT_NODE_SZ, GFP_NOFS); if (!xent) return -ENOMEM; xent_key_init(c, &key, host->i_ino, &nm); err = ubifs_tnc_lookup_nm(c, &key, xent, &nm); if (err) { if (err == -ENOENT) err = -ENODATA; goto out_free; } inode = iget_xattr(c, le64_to_cpu(xent->inum)); if (IS_ERR(inode)) { err = PTR_ERR(inode); goto out_free; } ubifs_assert(inode->i_nlink == 1); clear_nlink(inode); err = remove_xattr(c, host, inode, &nm); if (err) set_nlink(inode, 1); /* If @i_nlink is 0, 'iput()' will delete the inode */ iput(inode); out_free: kfree(xent); return err; } static int init_xattrs(struct inode *inode, const struct xattr *xattr_array, void *fs_info) { const struct xattr *xattr; char *name; int err = 0; for (xattr = xattr_array; xattr->name != NULL; xattr++) { name = kmalloc(XATTR_SECURITY_PREFIX_LEN + strlen(xattr->name) + 1, GFP_NOFS); if (!name) { err = -ENOMEM; break; } strcpy(name, XATTR_SECURITY_PREFIX); strcpy(name + XATTR_SECURITY_PREFIX_LEN, xattr->name); err = ubifs_xattr_set(inode, name, xattr->value, xattr->value_len, 0); kfree(name); if (err < 0) break; } return err; } int ubifs_init_security(struct inode *dentry, struct inode *inode, const struct qstr *qstr) { int err; err = security_inode_init_security(inode, dentry, qstr, &init_xattrs, 0); if (err) { struct ubifs_info *c = dentry->i_sb->s_fs_info; ubifs_err(c, "cannot initialize security for inode %lu, error %d", inode->i_ino, err); } return err; } static int xattr_get(const struct xattr_handler *handler, struct dentry *dentry, struct inode *inode, const char *name, void *buffer, size_t size) { dbg_gen("xattr '%s', ino %lu ('%pd'), buf size %zd", name, inode->i_ino, dentry, size); name = xattr_full_name(handler, name); return ubifs_xattr_get(inode, name, buffer, size); } static int xattr_set(const struct xattr_handler *handler, struct dentry *dentry, struct inode *inode, const char *name, const void *value, size_t size, int flags) { dbg_gen("xattr '%s', host ino %lu ('%pd'), size %zd", name, inode->i_ino, dentry, size); name = xattr_full_name(handler, name); if (value) return ubifs_xattr_set(inode, name, value, size, flags); else return ubifs_xattr_remove(inode, name); } static const struct xattr_handler ubifs_user_xattr_handler = { .prefix = XATTR_USER_PREFIX, .get = xattr_get, .set = xattr_set, }; static const struct xattr_handler ubifs_trusted_xattr_handler = { .prefix = XATTR_TRUSTED_PREFIX, .get = xattr_get, .set = xattr_set, }; static const struct xattr_handler ubifs_security_xattr_handler = { .prefix = XATTR_SECURITY_PREFIX, .get = xattr_get, .set = xattr_set, }; const struct xattr_handler *ubifs_xattr_handlers[] = { &ubifs_user_xattr_handler, &ubifs_trusted_xattr_handler, &ubifs_security_xattr_handler, NULL };
null
null
null
null
76,870
42,385
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
42,385
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 "base/observer_list.h" #include "base/observer_list_threadsafe.h" #include <memory> #include <utility> #include <vector> #include "base/bind.h" #include "base/compiler_specific.h" #include "base/location.h" #include "base/memory/weak_ptr.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/sequenced_task_runner.h" #include "base/single_thread_task_runner.h" #include "base/synchronization/waitable_event.h" #include "base/task_scheduler/post_task.h" #include "base/task_scheduler/task_scheduler.h" #include "base/test/scoped_task_environment.h" #include "base/threading/platform_thread.h" #include "base/threading/thread_restrictions.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace base { namespace { class Foo { public: virtual void Observe(int x) = 0; virtual ~Foo() = default; virtual int GetValue() const { return 0; } }; class Adder : public Foo { public: explicit Adder(int scaler) : total(0), scaler_(scaler) {} ~Adder() override = default; void Observe(int x) override { total += x * scaler_; } int GetValue() const override { return total; } int total; private: int scaler_; }; class Disrupter : public Foo { public: Disrupter(ObserverList<Foo>* list, Foo* doomed, bool remove_self) : list_(list), doomed_(doomed), remove_self_(remove_self) {} Disrupter(ObserverList<Foo>* list, Foo* doomed) : Disrupter(list, doomed, false) {} Disrupter(ObserverList<Foo>* list, bool remove_self) : Disrupter(list, nullptr, remove_self) {} ~Disrupter() override = default; void Observe(int x) override { if (remove_self_) list_->RemoveObserver(this); if (doomed_) list_->RemoveObserver(doomed_); } void SetDoomed(Foo* doomed) { doomed_ = doomed; } private: ObserverList<Foo>* list_; Foo* doomed_; bool remove_self_; }; template <typename ObserverListType> class AddInObserve : public Foo { public: explicit AddInObserve(ObserverListType* observer_list) : observer_list(observer_list), to_add_() {} void SetToAdd(Foo* to_add) { to_add_ = to_add; } void Observe(int x) override { if (to_add_) { observer_list->AddObserver(to_add_); to_add_ = nullptr; } } ObserverListType* observer_list; Foo* to_add_; }; static const int kThreadRunTime = 2000; // ms to run the multi-threaded test. // A thread for use in the ThreadSafeObserver test // which will add and remove itself from the notification // list repeatedly. class AddRemoveThread : public PlatformThread::Delegate, public Foo { public: AddRemoveThread(ObserverListThreadSafe<Foo>* list, bool notify, WaitableEvent* ready) : list_(list), loop_(nullptr), in_list_(false), start_(Time::Now()), count_observes_(0), count_addtask_(0), do_notifies_(notify), ready_(ready), weak_factory_(this) {} ~AddRemoveThread() override = default; void ThreadMain() override { loop_ = new MessageLoop(); // Fire up a message loop. loop_->task_runner()->PostTask( FROM_HERE, base::BindOnce(&AddRemoveThread::AddTask, weak_factory_.GetWeakPtr())); ready_->Signal(); // After ready_ is signaled, loop_ is only accessed by the main test thread // (i.e. not this thread) in particular by Quit() which causes Run() to // return, and we "control" loop_ again. RunLoop().Run(); delete loop_; loop_ = reinterpret_cast<MessageLoop*>(0xdeadbeef); delete this; } // This task just keeps posting to itself in an attempt // to race with the notifier. void AddTask() { count_addtask_++; if ((Time::Now() - start_).InMilliseconds() > kThreadRunTime) { VLOG(1) << "DONE!"; return; } if (!in_list_) { list_->AddObserver(this); in_list_ = true; } if (do_notifies_) { list_->Notify(FROM_HERE, &Foo::Observe, 10); } loop_->task_runner()->PostTask( FROM_HERE, base::BindOnce(&AddRemoveThread::AddTask, weak_factory_.GetWeakPtr())); } // This function is only callable from the main thread. void Quit() { loop_->task_runner()->PostTask(FROM_HERE, MessageLoop::QuitWhenIdleClosure()); } void Observe(int x) override { count_observes_++; // If we're getting called after we removed ourselves from // the list, that is very bad! DCHECK(in_list_); // This callback should fire on the appropriate thread EXPECT_EQ(loop_, MessageLoop::current()); list_->RemoveObserver(this); in_list_ = false; } private: ObserverListThreadSafe<Foo>* list_; MessageLoop* loop_; bool in_list_; // Are we currently registered for notifications. // in_list_ is only used on |this| thread. Time start_; // The time we started the test. int count_observes_; // Number of times we observed. int count_addtask_; // Number of times thread AddTask was called bool do_notifies_; // Whether these threads should do notifications. WaitableEvent* ready_; base::WeakPtrFactory<AddRemoveThread> weak_factory_; }; } // namespace TEST(ObserverListTest, BasicTest) { ObserverList<Foo> observer_list; const ObserverList<Foo>& const_observer_list = observer_list; { const ObserverList<Foo>::const_iterator it1 = const_observer_list.begin(); EXPECT_EQ(it1, const_observer_list.end()); // Iterator copy. const ObserverList<Foo>::const_iterator it2 = it1; EXPECT_EQ(it2, it1); // Iterator assignment. ObserverList<Foo>::const_iterator it3; it3 = it2; EXPECT_EQ(it3, it1); EXPECT_EQ(it3, it2); // Self assignment. it3 = it3; EXPECT_EQ(it3, it1); EXPECT_EQ(it3, it2); } { const ObserverList<Foo>::iterator it1 = observer_list.begin(); EXPECT_EQ(it1, observer_list.end()); // Iterator copy. const ObserverList<Foo>::iterator it2 = it1; EXPECT_EQ(it2, it1); // Iterator assignment. ObserverList<Foo>::iterator it3; it3 = it2; EXPECT_EQ(it3, it1); EXPECT_EQ(it3, it2); // Self assignment. it3 = it3; EXPECT_EQ(it3, it1); EXPECT_EQ(it3, it2); } Adder a(1), b(-1), c(1), d(-1), e(-1); Disrupter evil(&observer_list, &c); observer_list.AddObserver(&a); observer_list.AddObserver(&b); EXPECT_TRUE(const_observer_list.HasObserver(&a)); EXPECT_FALSE(const_observer_list.HasObserver(&c)); { const ObserverList<Foo>::const_iterator it1 = const_observer_list.begin(); EXPECT_NE(it1, const_observer_list.end()); // Iterator copy. const ObserverList<Foo>::const_iterator it2 = it1; EXPECT_EQ(it2, it1); EXPECT_NE(it2, const_observer_list.end()); // Iterator assignment. ObserverList<Foo>::const_iterator it3; it3 = it2; EXPECT_EQ(it3, it1); EXPECT_EQ(it3, it2); // Self assignment. it3 = it3; EXPECT_EQ(it3, it1); EXPECT_EQ(it3, it2); // Iterator post increment. ObserverList<Foo>::const_iterator it4 = it3++; EXPECT_EQ(it4, it1); EXPECT_EQ(it4, it2); EXPECT_NE(it4, it3); } { const ObserverList<Foo>::iterator it1 = observer_list.begin(); EXPECT_NE(it1, observer_list.end()); // Iterator copy. const ObserverList<Foo>::iterator it2 = it1; EXPECT_EQ(it2, it1); EXPECT_NE(it2, observer_list.end()); // Iterator assignment. ObserverList<Foo>::iterator it3; it3 = it2; EXPECT_EQ(it3, it1); EXPECT_EQ(it3, it2); // Self assignment. it3 = it3; EXPECT_EQ(it3, it1); EXPECT_EQ(it3, it2); // Iterator post increment. ObserverList<Foo>::iterator it4 = it3++; EXPECT_EQ(it4, it1); EXPECT_EQ(it4, it2); EXPECT_NE(it4, it3); } for (auto& observer : observer_list) observer.Observe(10); observer_list.AddObserver(&evil); observer_list.AddObserver(&c); observer_list.AddObserver(&d); // Removing an observer not in the list should do nothing. observer_list.RemoveObserver(&e); for (auto& observer : observer_list) observer.Observe(10); EXPECT_EQ(20, a.total); EXPECT_EQ(-20, b.total); EXPECT_EQ(0, c.total); EXPECT_EQ(-10, d.total); EXPECT_EQ(0, e.total); } TEST(ObserverListTest, CompactsWhenNoActiveIterator) { ObserverList<const Foo> ol; const ObserverList<const Foo>& col = ol; const Adder a(1); const Adder b(2); const Adder c(3); ol.AddObserver(&a); ol.AddObserver(&b); EXPECT_TRUE(col.HasObserver(&a)); EXPECT_FALSE(col.HasObserver(&c)); EXPECT_TRUE(col.might_have_observers()); using It = ObserverList<const Foo>::const_iterator; { It it = col.begin(); EXPECT_NE(it, col.end()); It ita = it; EXPECT_EQ(ita, it); EXPECT_NE(++it, col.end()); EXPECT_NE(ita, it); It itb = it; EXPECT_EQ(itb, it); EXPECT_EQ(++it, col.end()); EXPECT_TRUE(col.might_have_observers()); EXPECT_EQ(&*ita, &a); EXPECT_EQ(&*itb, &b); ol.RemoveObserver(&a); EXPECT_TRUE(col.might_have_observers()); EXPECT_FALSE(col.HasObserver(&a)); EXPECT_EQ(&*itb, &b); ol.RemoveObserver(&b); EXPECT_TRUE(col.might_have_observers()); EXPECT_FALSE(col.HasObserver(&a)); EXPECT_FALSE(col.HasObserver(&b)); it = It(); ita = It(); EXPECT_TRUE(col.might_have_observers()); ita = itb; itb = It(); EXPECT_TRUE(col.might_have_observers()); ita = It(); EXPECT_FALSE(col.might_have_observers()); } ol.AddObserver(&a); ol.AddObserver(&b); EXPECT_TRUE(col.might_have_observers()); ol.Clear(); EXPECT_FALSE(col.might_have_observers()); ol.AddObserver(&a); ol.AddObserver(&b); EXPECT_TRUE(col.might_have_observers()); { const It it = col.begin(); ol.Clear(); EXPECT_TRUE(col.might_have_observers()); } EXPECT_FALSE(col.might_have_observers()); } TEST(ObserverListTest, DisruptSelf) { ObserverList<Foo> observer_list; Adder a(1), b(-1), c(1), d(-1); Disrupter evil(&observer_list, true); observer_list.AddObserver(&a); observer_list.AddObserver(&b); for (auto& observer : observer_list) observer.Observe(10); observer_list.AddObserver(&evil); observer_list.AddObserver(&c); observer_list.AddObserver(&d); for (auto& observer : observer_list) observer.Observe(10); EXPECT_EQ(20, a.total); EXPECT_EQ(-20, b.total); EXPECT_EQ(10, c.total); EXPECT_EQ(-10, d.total); } TEST(ObserverListTest, DisruptBefore) { ObserverList<Foo> observer_list; Adder a(1), b(-1), c(1), d(-1); Disrupter evil(&observer_list, &b); observer_list.AddObserver(&a); observer_list.AddObserver(&b); observer_list.AddObserver(&evil); observer_list.AddObserver(&c); observer_list.AddObserver(&d); for (auto& observer : observer_list) observer.Observe(10); for (auto& observer : observer_list) observer.Observe(10); EXPECT_EQ(20, a.total); EXPECT_EQ(-10, b.total); EXPECT_EQ(20, c.total); EXPECT_EQ(-20, d.total); } TEST(ObserverListThreadSafeTest, BasicTest) { MessageLoop loop; scoped_refptr<ObserverListThreadSafe<Foo> > observer_list( new ObserverListThreadSafe<Foo>); Adder a(1); Adder b(-1); Adder c(1); Adder d(-1); observer_list->AddObserver(&a); observer_list->AddObserver(&b); observer_list->Notify(FROM_HERE, &Foo::Observe, 10); RunLoop().RunUntilIdle(); observer_list->AddObserver(&c); observer_list->AddObserver(&d); observer_list->Notify(FROM_HERE, &Foo::Observe, 10); observer_list->RemoveObserver(&c); RunLoop().RunUntilIdle(); EXPECT_EQ(20, a.total); EXPECT_EQ(-20, b.total); EXPECT_EQ(0, c.total); EXPECT_EQ(-10, d.total); } TEST(ObserverListThreadSafeTest, RemoveObserver) { MessageLoop loop; scoped_refptr<ObserverListThreadSafe<Foo> > observer_list( new ObserverListThreadSafe<Foo>); Adder a(1), b(1); // A workaround for the compiler bug. See http://crbug.com/121960. EXPECT_NE(&a, &b); // Should do nothing. observer_list->RemoveObserver(&a); observer_list->RemoveObserver(&b); observer_list->Notify(FROM_HERE, &Foo::Observe, 10); RunLoop().RunUntilIdle(); EXPECT_EQ(0, a.total); EXPECT_EQ(0, b.total); observer_list->AddObserver(&a); // Should also do nothing. observer_list->RemoveObserver(&b); observer_list->Notify(FROM_HERE, &Foo::Observe, 10); RunLoop().RunUntilIdle(); EXPECT_EQ(10, a.total); EXPECT_EQ(0, b.total); } TEST(ObserverListThreadSafeTest, WithoutSequence) { scoped_refptr<ObserverListThreadSafe<Foo> > observer_list( new ObserverListThreadSafe<Foo>); Adder a(1), b(1), c(1); // No sequence, so these should not be added. observer_list->AddObserver(&a); observer_list->AddObserver(&b); { // Add c when there's a sequence. MessageLoop loop; observer_list->AddObserver(&c); observer_list->Notify(FROM_HERE, &Foo::Observe, 10); RunLoop().RunUntilIdle(); EXPECT_EQ(0, a.total); EXPECT_EQ(0, b.total); EXPECT_EQ(10, c.total); // Now add a when there's a sequence. observer_list->AddObserver(&a); // Remove c when there's a sequence. observer_list->RemoveObserver(&c); // Notify again. observer_list->Notify(FROM_HERE, &Foo::Observe, 20); RunLoop().RunUntilIdle(); EXPECT_EQ(20, a.total); EXPECT_EQ(0, b.total); EXPECT_EQ(10, c.total); } // Removing should always succeed with or without a sequence. observer_list->RemoveObserver(&a); // Notifying should not fail but should also be a no-op. MessageLoop loop; observer_list->AddObserver(&b); observer_list->Notify(FROM_HERE, &Foo::Observe, 30); RunLoop().RunUntilIdle(); EXPECT_EQ(20, a.total); EXPECT_EQ(30, b.total); EXPECT_EQ(10, c.total); } class FooRemover : public Foo { public: explicit FooRemover(ObserverListThreadSafe<Foo>* list) : list_(list) {} ~FooRemover() override = default; void AddFooToRemove(Foo* foo) { foos_.push_back(foo); } void Observe(int x) override { std::vector<Foo*> tmp; tmp.swap(foos_); for (std::vector<Foo*>::iterator it = tmp.begin(); it != tmp.end(); ++it) { list_->RemoveObserver(*it); } } private: const scoped_refptr<ObserverListThreadSafe<Foo> > list_; std::vector<Foo*> foos_; }; TEST(ObserverListThreadSafeTest, RemoveMultipleObservers) { MessageLoop loop; scoped_refptr<ObserverListThreadSafe<Foo> > observer_list( new ObserverListThreadSafe<Foo>); FooRemover a(observer_list.get()); Adder b(1); observer_list->AddObserver(&a); observer_list->AddObserver(&b); a.AddFooToRemove(&a); a.AddFooToRemove(&b); observer_list->Notify(FROM_HERE, &Foo::Observe, 1); RunLoop().RunUntilIdle(); } // A test driver for a multi-threaded notification loop. Runs a number // of observer threads, each of which constantly adds/removes itself // from the observer list. Optionally, if cross_thread_notifies is set // to true, the observer threads will also trigger notifications to // all observers. static void ThreadSafeObserverHarness(int num_threads, bool cross_thread_notifies) { MessageLoop loop; scoped_refptr<ObserverListThreadSafe<Foo> > observer_list( new ObserverListThreadSafe<Foo>); Adder a(1); Adder b(-1); observer_list->AddObserver(&a); observer_list->AddObserver(&b); std::vector<AddRemoveThread*> threaded_observer; std::vector<base::PlatformThreadHandle> threads(num_threads); std::vector<std::unique_ptr<base::WaitableEvent>> ready; threaded_observer.reserve(num_threads); ready.reserve(num_threads); for (int index = 0; index < num_threads; index++) { ready.push_back(std::make_unique<WaitableEvent>( WaitableEvent::ResetPolicy::MANUAL, WaitableEvent::InitialState::NOT_SIGNALED)); threaded_observer.push_back(new AddRemoveThread( observer_list.get(), cross_thread_notifies, ready.back().get())); EXPECT_TRUE( PlatformThread::Create(0, threaded_observer.back(), &threads[index])); } ASSERT_EQ(static_cast<size_t>(num_threads), threaded_observer.size()); ASSERT_EQ(static_cast<size_t>(num_threads), ready.size()); // This makes sure that threaded_observer has gotten to set loop_, so that we // can call Quit() below safe-ish-ly. for (int i = 0; i < num_threads; ++i) ready[i]->Wait(); Time start = Time::Now(); while (true) { if ((Time::Now() - start).InMilliseconds() > kThreadRunTime) break; observer_list->Notify(FROM_HERE, &Foo::Observe, 10); RunLoop().RunUntilIdle(); } for (int index = 0; index < num_threads; index++) { threaded_observer[index]->Quit(); PlatformThread::Join(threads[index]); } } TEST(ObserverListThreadSafeTest, CrossThreadObserver) { // Use 7 observer threads. Notifications only come from // the main thread. ThreadSafeObserverHarness(7, false); } TEST(ObserverListThreadSafeTest, CrossThreadNotifications) { // Use 3 observer threads. Notifications will fire from // the main thread and all 3 observer threads. ThreadSafeObserverHarness(3, true); } TEST(ObserverListThreadSafeTest, OutlivesMessageLoop) { MessageLoop* loop = new MessageLoop; scoped_refptr<ObserverListThreadSafe<Foo> > observer_list( new ObserverListThreadSafe<Foo>); Adder a(1); observer_list->AddObserver(&a); delete loop; // Test passes if we don't crash here. observer_list->Notify(FROM_HERE, &Foo::Observe, 1); } namespace { class SequenceVerificationObserver : public Foo { public: explicit SequenceVerificationObserver( scoped_refptr<SequencedTaskRunner> task_runner) : task_runner_(std::move(task_runner)) {} ~SequenceVerificationObserver() override = default; void Observe(int x) override { called_on_valid_sequence_ = task_runner_->RunsTasksInCurrentSequence(); } bool called_on_valid_sequence() const { return called_on_valid_sequence_; } private: const scoped_refptr<SequencedTaskRunner> task_runner_; bool called_on_valid_sequence_ = false; DISALLOW_COPY_AND_ASSIGN(SequenceVerificationObserver); }; } // namespace // Verify that observers are notified on the correct sequence. TEST(ObserverListThreadSafeTest, NotificationOnValidSequence) { test::ScopedTaskEnvironment scoped_task_environment; auto task_runner_1 = CreateSequencedTaskRunnerWithTraits(TaskTraits()); auto task_runner_2 = CreateSequencedTaskRunnerWithTraits(TaskTraits()); auto observer_list = MakeRefCounted<ObserverListThreadSafe<Foo>>(); SequenceVerificationObserver observer_1(task_runner_1); SequenceVerificationObserver observer_2(task_runner_2); task_runner_1->PostTask(FROM_HERE, BindOnce(&ObserverListThreadSafe<Foo>::AddObserver, observer_list, Unretained(&observer_1))); task_runner_2->PostTask(FROM_HERE, BindOnce(&ObserverListThreadSafe<Foo>::AddObserver, observer_list, Unretained(&observer_2))); TaskScheduler::GetInstance()->FlushForTesting(); observer_list->Notify(FROM_HERE, &Foo::Observe, 1); TaskScheduler::GetInstance()->FlushForTesting(); EXPECT_TRUE(observer_1.called_on_valid_sequence()); EXPECT_TRUE(observer_2.called_on_valid_sequence()); } // Verify that when an observer is added to a NOTIFY_ALL ObserverListThreadSafe // from a notification, it is itself notified. TEST(ObserverListThreadSafeTest, AddObserverFromNotificationNotifyAll) { test::ScopedTaskEnvironment scoped_task_environment; auto observer_list = MakeRefCounted<ObserverListThreadSafe<Foo>>(); Adder observer_added_from_notification(1); AddInObserve<ObserverListThreadSafe<Foo>> initial_observer( observer_list.get()); initial_observer.SetToAdd(&observer_added_from_notification); observer_list->AddObserver(&initial_observer); observer_list->Notify(FROM_HERE, &Foo::Observe, 1); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, observer_added_from_notification.GetValue()); } namespace { class RemoveWhileNotificationIsRunningObserver : public Foo { public: RemoveWhileNotificationIsRunningObserver() : notification_running_(WaitableEvent::ResetPolicy::AUTOMATIC, WaitableEvent::InitialState::NOT_SIGNALED), barrier_(WaitableEvent::ResetPolicy::AUTOMATIC, WaitableEvent::InitialState::NOT_SIGNALED) {} ~RemoveWhileNotificationIsRunningObserver() override = default; void Observe(int x) override { notification_running_.Signal(); ScopedAllowBaseSyncPrimitivesForTesting allow_base_sync_primitives; barrier_.Wait(); } void WaitForNotificationRunning() { notification_running_.Wait(); } void Unblock() { barrier_.Signal(); } private: WaitableEvent notification_running_; WaitableEvent barrier_; DISALLOW_COPY_AND_ASSIGN(RemoveWhileNotificationIsRunningObserver); }; } // namespace // Verify that there is no crash when an observer is removed while it is being // notified. TEST(ObserverListThreadSafeTest, RemoveWhileNotificationIsRunning) { auto observer_list = MakeRefCounted<ObserverListThreadSafe<Foo>>(); RemoveWhileNotificationIsRunningObserver observer; WaitableEvent task_running(WaitableEvent::ResetPolicy::AUTOMATIC, WaitableEvent::InitialState::NOT_SIGNALED); WaitableEvent barrier(WaitableEvent::ResetPolicy::AUTOMATIC, WaitableEvent::InitialState::NOT_SIGNALED); // This must be after the declaration of |barrier| so that tasks posted to // TaskScheduler can safely use |barrier|. test::ScopedTaskEnvironment scoped_task_environment; CreateSequencedTaskRunnerWithTraits({})->PostTask( FROM_HERE, base::BindOnce(&ObserverListThreadSafe<Foo>::AddObserver, observer_list, Unretained(&observer))); TaskScheduler::GetInstance()->FlushForTesting(); observer_list->Notify(FROM_HERE, &Foo::Observe, 1); observer.WaitForNotificationRunning(); observer_list->RemoveObserver(&observer); observer.Unblock(); } TEST(ObserverListTest, Existing) { ObserverList<Foo> observer_list(ObserverListPolicy::EXISTING_ONLY); Adder a(1); AddInObserve<ObserverList<Foo> > b(&observer_list); Adder c(1); b.SetToAdd(&c); observer_list.AddObserver(&a); observer_list.AddObserver(&b); for (auto& observer : observer_list) observer.Observe(1); EXPECT_FALSE(b.to_add_); // B's adder should not have been notified because it was added during // notification. EXPECT_EQ(0, c.total); // Notify again to make sure b's adder is notified. for (auto& observer : observer_list) observer.Observe(1); EXPECT_EQ(1, c.total); } // Same as above, but for ObserverListThreadSafe TEST(ObserverListThreadSafeTest, Existing) { MessageLoop loop; scoped_refptr<ObserverListThreadSafe<Foo>> observer_list( new ObserverListThreadSafe<Foo>(ObserverListPolicy::EXISTING_ONLY)); Adder a(1); AddInObserve<ObserverListThreadSafe<Foo> > b(observer_list.get()); Adder c(1); b.SetToAdd(&c); observer_list->AddObserver(&a); observer_list->AddObserver(&b); observer_list->Notify(FROM_HERE, &Foo::Observe, 1); RunLoop().RunUntilIdle(); EXPECT_FALSE(b.to_add_); // B's adder should not have been notified because it was added during // notification. EXPECT_EQ(0, c.total); // Notify again to make sure b's adder is notified. observer_list->Notify(FROM_HERE, &Foo::Observe, 1); RunLoop().RunUntilIdle(); EXPECT_EQ(1, c.total); } class AddInClearObserve : public Foo { public: explicit AddInClearObserve(ObserverList<Foo>* list) : list_(list), added_(false), adder_(1) {} void Observe(int /* x */) override { list_->Clear(); list_->AddObserver(&adder_); added_ = true; } bool added() const { return added_; } const Adder& adder() const { return adder_; } private: ObserverList<Foo>* const list_; bool added_; Adder adder_; }; TEST(ObserverListTest, ClearNotifyAll) { ObserverList<Foo> observer_list; AddInClearObserve a(&observer_list); observer_list.AddObserver(&a); for (auto& observer : observer_list) observer.Observe(1); EXPECT_TRUE(a.added()); EXPECT_EQ(1, a.adder().total) << "Adder should observe once and have sum of 1."; } TEST(ObserverListTest, ClearNotifyExistingOnly) { ObserverList<Foo> observer_list(ObserverListPolicy::EXISTING_ONLY); AddInClearObserve a(&observer_list); observer_list.AddObserver(&a); for (auto& observer : observer_list) observer.Observe(1); EXPECT_TRUE(a.added()); EXPECT_EQ(0, a.adder().total) << "Adder should not observe, so sum should still be 0."; } class ListDestructor : public Foo { public: explicit ListDestructor(ObserverList<Foo>* list) : list_(list) {} ~ListDestructor() override = default; void Observe(int x) override { delete list_; } private: ObserverList<Foo>* list_; }; TEST(ObserverListTest, IteratorOutlivesList) { ObserverList<Foo>* observer_list = new ObserverList<Foo>; ListDestructor a(observer_list); observer_list->AddObserver(&a); for (auto& observer : *observer_list) observer.Observe(0); // There are no EXPECT* statements for this test, if we catch // use-after-free errors for observer_list (eg with ASan) then // this test has failed. See http://crbug.com/85296. } TEST(ObserverListTest, BasicStdIterator) { using FooList = ObserverList<Foo>; FooList observer_list; // An optimization: begin() and end() do not involve weak pointers on // empty list. EXPECT_FALSE(observer_list.begin().list_); EXPECT_FALSE(observer_list.end().list_); // Iterate over empty list: no effect, no crash. for (auto& i : observer_list) i.Observe(10); Adder a(1), b(-1), c(1), d(-1); observer_list.AddObserver(&a); observer_list.AddObserver(&b); observer_list.AddObserver(&c); observer_list.AddObserver(&d); for (FooList::iterator i = observer_list.begin(), e = observer_list.end(); i != e; ++i) i->Observe(1); EXPECT_EQ(1, a.total); EXPECT_EQ(-1, b.total); EXPECT_EQ(1, c.total); EXPECT_EQ(-1, d.total); // Check an iteration over a 'const view' for a given container. const FooList& const_list = observer_list; for (FooList::const_iterator i = const_list.begin(), e = const_list.end(); i != e; ++i) { EXPECT_EQ(1, std::abs(i->GetValue())); } for (const auto& o : const_list) EXPECT_EQ(1, std::abs(o.GetValue())); } TEST(ObserverListTest, StdIteratorRemoveItself) { ObserverList<Foo> observer_list; Adder a(1), b(-1), c(1), d(-1); Disrupter disrupter(&observer_list, true); observer_list.AddObserver(&a); observer_list.AddObserver(&b); observer_list.AddObserver(&disrupter); observer_list.AddObserver(&c); observer_list.AddObserver(&d); for (auto& o : observer_list) o.Observe(1); for (auto& o : observer_list) o.Observe(10); EXPECT_EQ(11, a.total); EXPECT_EQ(-11, b.total); EXPECT_EQ(11, c.total); EXPECT_EQ(-11, d.total); } TEST(ObserverListTest, StdIteratorRemoveBefore) { ObserverList<Foo> observer_list; Adder a(1), b(-1), c(1), d(-1); Disrupter disrupter(&observer_list, &b); observer_list.AddObserver(&a); observer_list.AddObserver(&b); observer_list.AddObserver(&disrupter); observer_list.AddObserver(&c); observer_list.AddObserver(&d); for (auto& o : observer_list) o.Observe(1); for (auto& o : observer_list) o.Observe(10); EXPECT_EQ(11, a.total); EXPECT_EQ(-1, b.total); EXPECT_EQ(11, c.total); EXPECT_EQ(-11, d.total); } TEST(ObserverListTest, StdIteratorRemoveAfter) { ObserverList<Foo> observer_list; Adder a(1), b(-1), c(1), d(-1); Disrupter disrupter(&observer_list, &c); observer_list.AddObserver(&a); observer_list.AddObserver(&b); observer_list.AddObserver(&disrupter); observer_list.AddObserver(&c); observer_list.AddObserver(&d); for (auto& o : observer_list) o.Observe(1); for (auto& o : observer_list) o.Observe(10); EXPECT_EQ(11, a.total); EXPECT_EQ(-11, b.total); EXPECT_EQ(0, c.total); EXPECT_EQ(-11, d.total); } TEST(ObserverListTest, StdIteratorRemoveAfterFront) { ObserverList<Foo> observer_list; Adder a(1), b(-1), c(1), d(-1); Disrupter disrupter(&observer_list, &a); observer_list.AddObserver(&a); observer_list.AddObserver(&disrupter); observer_list.AddObserver(&b); observer_list.AddObserver(&c); observer_list.AddObserver(&d); for (auto& o : observer_list) o.Observe(1); for (auto& o : observer_list) o.Observe(10); EXPECT_EQ(1, a.total); EXPECT_EQ(-11, b.total); EXPECT_EQ(11, c.total); EXPECT_EQ(-11, d.total); } TEST(ObserverListTest, StdIteratorRemoveBeforeBack) { ObserverList<Foo> observer_list; Adder a(1), b(-1), c(1), d(-1); Disrupter disrupter(&observer_list, &d); observer_list.AddObserver(&a); observer_list.AddObserver(&b); observer_list.AddObserver(&c); observer_list.AddObserver(&disrupter); observer_list.AddObserver(&d); for (auto& o : observer_list) o.Observe(1); for (auto& o : observer_list) o.Observe(10); EXPECT_EQ(11, a.total); EXPECT_EQ(-11, b.total); EXPECT_EQ(11, c.total); EXPECT_EQ(0, d.total); } TEST(ObserverListTest, StdIteratorRemoveFront) { using FooList = ObserverList<Foo>; FooList observer_list; Adder a(1), b(-1), c(1), d(-1); Disrupter disrupter(&observer_list, true); observer_list.AddObserver(&disrupter); observer_list.AddObserver(&a); observer_list.AddObserver(&b); observer_list.AddObserver(&c); observer_list.AddObserver(&d); bool test_disruptor = true; for (FooList::iterator i = observer_list.begin(), e = observer_list.end(); i != e; ++i) { i->Observe(1); // Check that second call to i->Observe() would crash here. if (test_disruptor) { EXPECT_FALSE(i.GetCurrent()); test_disruptor = false; } } for (auto& o : observer_list) o.Observe(10); EXPECT_EQ(11, a.total); EXPECT_EQ(-11, b.total); EXPECT_EQ(11, c.total); EXPECT_EQ(-11, d.total); } TEST(ObserverListTest, StdIteratorRemoveBack) { ObserverList<Foo> observer_list; Adder a(1), b(-1), c(1), d(-1); Disrupter disrupter(&observer_list, true); observer_list.AddObserver(&a); observer_list.AddObserver(&b); observer_list.AddObserver(&c); observer_list.AddObserver(&d); observer_list.AddObserver(&disrupter); for (auto& o : observer_list) o.Observe(1); for (auto& o : observer_list) o.Observe(10); EXPECT_EQ(11, a.total); EXPECT_EQ(-11, b.total); EXPECT_EQ(11, c.total); EXPECT_EQ(-11, d.total); } TEST(ObserverListTest, NestedLoop) { ObserverList<Foo> observer_list; Adder a(1), b(-1), c(1), d(-1); Disrupter disrupter(&observer_list, true); observer_list.AddObserver(&disrupter); observer_list.AddObserver(&a); observer_list.AddObserver(&b); observer_list.AddObserver(&c); observer_list.AddObserver(&d); for (auto& o : observer_list) { o.Observe(10); for (auto& o : observer_list) o.Observe(1); } EXPECT_EQ(15, a.total); EXPECT_EQ(-15, b.total); EXPECT_EQ(15, c.total); EXPECT_EQ(-15, d.total); } TEST(ObserverListTest, NonCompactList) { ObserverList<Foo> observer_list; Adder a(1), b(-1); Disrupter disrupter1(&observer_list, true); Disrupter disrupter2(&observer_list, true); // Disrupt itself and another one. disrupter1.SetDoomed(&disrupter2); observer_list.AddObserver(&disrupter1); observer_list.AddObserver(&disrupter2); observer_list.AddObserver(&a); observer_list.AddObserver(&b); for (auto& o : observer_list) { // Get the { nullptr, nullptr, &a, &b } non-compact list // on the first inner pass. o.Observe(10); for (auto& o : observer_list) o.Observe(1); } EXPECT_EQ(13, a.total); EXPECT_EQ(-13, b.total); } TEST(ObserverListTest, BecomesEmptyThanNonEmpty) { ObserverList<Foo> observer_list; Adder a(1), b(-1); Disrupter disrupter1(&observer_list, true); Disrupter disrupter2(&observer_list, true); // Disrupt itself and another one. disrupter1.SetDoomed(&disrupter2); observer_list.AddObserver(&disrupter1); observer_list.AddObserver(&disrupter2); bool add_observers = true; for (auto& o : observer_list) { // Get the { nullptr, nullptr } empty list on the first inner pass. o.Observe(10); for (auto& o : observer_list) o.Observe(1); if (add_observers) { observer_list.AddObserver(&a); observer_list.AddObserver(&b); add_observers = false; } } EXPECT_EQ(12, a.total); EXPECT_EQ(-12, b.total); } TEST(ObserverListTest, AddObserverInTheLastObserve) { using FooList = ObserverList<Foo>; FooList observer_list; AddInObserve<FooList> a(&observer_list); Adder b(-1); a.SetToAdd(&b); observer_list.AddObserver(&a); auto it = observer_list.begin(); while (it != observer_list.end()) { auto& observer = *it; // Intentionally increment the iterator before calling Observe(). The // ObserverList starts with only one observer, and it == observer_list.end() // should be true after the next line. ++it; // However, the first Observe() call will add a second observer: at this // point, it != observer_list.end() should be true, and Observe() should be // called on the newly added observer on the next iteration of the loop. observer.Observe(10); } EXPECT_EQ(-10, b.total); } class MockLogAssertHandler { public: MOCK_METHOD4( HandleLogAssert, void(const char*, int, const base::StringPiece, const base::StringPiece)); }; #if DCHECK_IS_ON() TEST(ObserverListTest, NonReentrantObserverList) { using ::testing::_; ObserverList<Foo, /*check_empty=*/false, /*allow_reentrancy=*/false> non_reentrant_observer_list; Adder a(1); non_reentrant_observer_list.AddObserver(&a); ::testing::StrictMock<MockLogAssertHandler> handler; EXPECT_CALL(handler, HandleLogAssert(_, _, _, _)).Times(1); { logging::ScopedLogAssertHandler scoped_handler_b(base::BindRepeating( &MockLogAssertHandler::HandleLogAssert, base::Unretained(&handler))); for (const Foo& a : non_reentrant_observer_list) { for (const Foo& b : non_reentrant_observer_list) { std::ignore = a; std::ignore = b; } } } } TEST(ObserverListTest, ReentrantObserverList) { using ::testing::_; ReentrantObserverList<Foo> reentrant_observer_list; Adder a(1); reentrant_observer_list.AddObserver(&a); bool passed = false; for (const Foo& a : reentrant_observer_list) { for (const Foo& b : reentrant_observer_list) { std::ignore = a; std::ignore = b; passed = true; } } EXPECT_TRUE(passed); } #endif } // namespace base
null
null
null
null
39,248
2,170
null
train_val
04b570817b2b38e35675b17328239746212f4c3f
155,227
FFmpeg
0
https://github.com/FFmpeg/FFmpeg
2018-06-01 01:23:12+05:30
/* * Copyright (c) 2012 Andrew D'Addesio * Copyright (c) 2013-2014 Mozilla Corporation * * 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 */ /** * @file * Opus decoder/parser shared code */ #include <stdint.h> #include "libavutil/error.h" #include "libavutil/ffmath.h" #include "opus_celt.h" #include "opustab.h" #include "vorbis.h" static const uint16_t opus_frame_duration[32] = { 480, 960, 1920, 2880, 480, 960, 1920, 2880, 480, 960, 1920, 2880, 480, 960, 480, 960, 120, 240, 480, 960, 120, 240, 480, 960, 120, 240, 480, 960, 120, 240, 480, 960, }; /** * Read a 1- or 2-byte frame length */ static inline int xiph_lacing_16bit(const uint8_t **ptr, const uint8_t *end) { int val; if (*ptr >= end) return AVERROR_INVALIDDATA; val = *(*ptr)++; if (val >= 252) { if (*ptr >= end) return AVERROR_INVALIDDATA; val += 4 * *(*ptr)++; } return val; } /** * Read a multi-byte length (used for code 3 packet padding size) */ static inline int xiph_lacing_full(const uint8_t **ptr, const uint8_t *end) { int val = 0; int next; while (1) { if (*ptr >= end || val > INT_MAX - 254) return AVERROR_INVALIDDATA; next = *(*ptr)++; val += next; if (next < 255) break; else val--; } return val; } /** * Parse Opus packet info from raw packet data */ int ff_opus_parse_packet(OpusPacket *pkt, const uint8_t *buf, int buf_size, int self_delimiting) { const uint8_t *ptr = buf; const uint8_t *end = buf + buf_size; int padding = 0; int frame_bytes, i; if (buf_size < 1) goto fail; /* TOC byte */ i = *ptr++; pkt->code = (i ) & 0x3; pkt->stereo = (i >> 2) & 0x1; pkt->config = (i >> 3) & 0x1F; /* code 2 and code 3 packets have at least 1 byte after the TOC */ if (pkt->code >= 2 && buf_size < 2) goto fail; switch (pkt->code) { case 0: /* 1 frame */ pkt->frame_count = 1; pkt->vbr = 0; if (self_delimiting) { int len = xiph_lacing_16bit(&ptr, end); if (len < 0 || len > end - ptr) goto fail; end = ptr + len; buf_size = end - buf; } frame_bytes = end - ptr; if (frame_bytes > MAX_FRAME_SIZE) goto fail; pkt->frame_offset[0] = ptr - buf; pkt->frame_size[0] = frame_bytes; break; case 1: /* 2 frames, equal size */ pkt->frame_count = 2; pkt->vbr = 0; if (self_delimiting) { int len = xiph_lacing_16bit(&ptr, end); if (len < 0 || 2 * len > end - ptr) goto fail; end = ptr + 2 * len; buf_size = end - buf; } frame_bytes = end - ptr; if (frame_bytes & 1 || frame_bytes >> 1 > MAX_FRAME_SIZE) goto fail; pkt->frame_offset[0] = ptr - buf; pkt->frame_size[0] = frame_bytes >> 1; pkt->frame_offset[1] = pkt->frame_offset[0] + pkt->frame_size[0]; pkt->frame_size[1] = frame_bytes >> 1; break; case 2: /* 2 frames, different sizes */ pkt->frame_count = 2; pkt->vbr = 1; /* read 1st frame size */ frame_bytes = xiph_lacing_16bit(&ptr, end); if (frame_bytes < 0) goto fail; if (self_delimiting) { int len = xiph_lacing_16bit(&ptr, end); if (len < 0 || len + frame_bytes > end - ptr) goto fail; end = ptr + frame_bytes + len; buf_size = end - buf; } pkt->frame_offset[0] = ptr - buf; pkt->frame_size[0] = frame_bytes; /* calculate 2nd frame size */ frame_bytes = end - ptr - pkt->frame_size[0]; if (frame_bytes < 0 || frame_bytes > MAX_FRAME_SIZE) goto fail; pkt->frame_offset[1] = pkt->frame_offset[0] + pkt->frame_size[0]; pkt->frame_size[1] = frame_bytes; break; case 3: /* 1 to 48 frames, can be different sizes */ i = *ptr++; pkt->frame_count = (i ) & 0x3F; padding = (i >> 6) & 0x01; pkt->vbr = (i >> 7) & 0x01; if (pkt->frame_count == 0 || pkt->frame_count > MAX_FRAMES) goto fail; /* read padding size */ if (padding) { padding = xiph_lacing_full(&ptr, end); if (padding < 0) goto fail; } /* read frame sizes */ if (pkt->vbr) { /* for VBR, all frames except the final one have their size coded in the bitstream. the last frame size is implicit. */ int total_bytes = 0; for (i = 0; i < pkt->frame_count - 1; i++) { frame_bytes = xiph_lacing_16bit(&ptr, end); if (frame_bytes < 0) goto fail; pkt->frame_size[i] = frame_bytes; total_bytes += frame_bytes; } if (self_delimiting) { int len = xiph_lacing_16bit(&ptr, end); if (len < 0 || len + total_bytes + padding > end - ptr) goto fail; end = ptr + total_bytes + len + padding; buf_size = end - buf; } frame_bytes = end - ptr - padding; if (total_bytes > frame_bytes) goto fail; pkt->frame_offset[0] = ptr - buf; for (i = 1; i < pkt->frame_count; i++) pkt->frame_offset[i] = pkt->frame_offset[i-1] + pkt->frame_size[i-1]; pkt->frame_size[pkt->frame_count-1] = frame_bytes - total_bytes; } else { /* for CBR, the remaining packet bytes are divided evenly between the frames */ if (self_delimiting) { frame_bytes = xiph_lacing_16bit(&ptr, end); if (frame_bytes < 0 || pkt->frame_count * frame_bytes + padding > end - ptr) goto fail; end = ptr + pkt->frame_count * frame_bytes + padding; buf_size = end - buf; } else { frame_bytes = end - ptr - padding; if (frame_bytes % pkt->frame_count || frame_bytes / pkt->frame_count > MAX_FRAME_SIZE) goto fail; frame_bytes /= pkt->frame_count; } pkt->frame_offset[0] = ptr - buf; pkt->frame_size[0] = frame_bytes; for (i = 1; i < pkt->frame_count; i++) { pkt->frame_offset[i] = pkt->frame_offset[i-1] + pkt->frame_size[i-1]; pkt->frame_size[i] = frame_bytes; } } } pkt->packet_size = buf_size; pkt->data_size = pkt->packet_size - padding; /* total packet duration cannot be larger than 120ms */ pkt->frame_duration = opus_frame_duration[pkt->config]; if (pkt->frame_duration * pkt->frame_count > MAX_PACKET_DUR) goto fail; /* set mode and bandwidth */ if (pkt->config < 12) { pkt->mode = OPUS_MODE_SILK; pkt->bandwidth = pkt->config >> 2; } else if (pkt->config < 16) { pkt->mode = OPUS_MODE_HYBRID; pkt->bandwidth = OPUS_BANDWIDTH_SUPERWIDEBAND + (pkt->config >= 14); } else { pkt->mode = OPUS_MODE_CELT; pkt->bandwidth = (pkt->config - 16) >> 2; /* skip medium band */ if (pkt->bandwidth) pkt->bandwidth++; } return 0; fail: memset(pkt, 0, sizeof(*pkt)); return AVERROR_INVALIDDATA; } static int channel_reorder_vorbis(int nb_channels, int channel_idx) { return ff_vorbis_channel_layout_offsets[nb_channels - 1][channel_idx]; } static int channel_reorder_unknown(int nb_channels, int channel_idx) { return channel_idx; } av_cold int ff_opus_parse_extradata(AVCodecContext *avctx, OpusContext *s) { static const uint8_t default_channel_map[2] = { 0, 1 }; int (*channel_reorder)(int, int) = channel_reorder_unknown; const uint8_t *extradata, *channel_map; int extradata_size; int version, channels, map_type, streams, stereo_streams, i, j; uint64_t layout; if (!avctx->extradata) { if (avctx->channels > 2) { av_log(avctx, AV_LOG_ERROR, "Multichannel configuration without extradata.\n"); return AVERROR(EINVAL); } extradata = opus_default_extradata; extradata_size = sizeof(opus_default_extradata); } else { extradata = avctx->extradata; extradata_size = avctx->extradata_size; } if (extradata_size < 19) { av_log(avctx, AV_LOG_ERROR, "Invalid extradata size: %d\n", extradata_size); return AVERROR_INVALIDDATA; } version = extradata[8]; if (version > 15) { avpriv_request_sample(avctx, "Extradata version %d", version); return AVERROR_PATCHWELCOME; } avctx->delay = AV_RL16(extradata + 10); channels = avctx->extradata ? extradata[9] : (avctx->channels == 1) ? 1 : 2; if (!channels) { av_log(avctx, AV_LOG_ERROR, "Zero channel count specified in the extradata\n"); return AVERROR_INVALIDDATA; } s->gain_i = AV_RL16(extradata + 16); if (s->gain_i) s->gain = ff_exp10(s->gain_i / (20.0 * 256)); map_type = extradata[18]; if (!map_type) { if (channels > 2) { av_log(avctx, AV_LOG_ERROR, "Channel mapping 0 is only specified for up to 2 channels\n"); return AVERROR_INVALIDDATA; } layout = (channels == 1) ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO; streams = 1; stereo_streams = channels - 1; channel_map = default_channel_map; } else if (map_type == 1 || map_type == 2 || map_type == 255) { if (extradata_size < 21 + channels) { av_log(avctx, AV_LOG_ERROR, "Invalid extradata size: %d\n", extradata_size); return AVERROR_INVALIDDATA; } streams = extradata[19]; stereo_streams = extradata[20]; if (!streams || stereo_streams > streams || streams + stereo_streams > 255) { av_log(avctx, AV_LOG_ERROR, "Invalid stream/stereo stream count: %d/%d\n", streams, stereo_streams); return AVERROR_INVALIDDATA; } if (map_type == 1) { if (channels > 8) { av_log(avctx, AV_LOG_ERROR, "Channel mapping 1 is only specified for up to 8 channels\n"); return AVERROR_INVALIDDATA; } layout = ff_vorbis_channel_layouts[channels - 1]; channel_reorder = channel_reorder_vorbis; } else if (map_type == 2) { int ambisonic_order = ff_sqrt(channels) - 1; if (channels != ((ambisonic_order + 1) * (ambisonic_order + 1)) && channels != ((ambisonic_order + 1) * (ambisonic_order + 1) + 2)) { av_log(avctx, AV_LOG_ERROR, "Channel mapping 2 is only specified for channel counts" " which can be written as (n + 1)^2 or (n + 1)^2 + 2" " for nonnegative integer n\n"); return AVERROR_INVALIDDATA; } if (channels > 227) { av_log(avctx, AV_LOG_ERROR, "Too many channels\n"); return AVERROR_INVALIDDATA; } layout = 0; } else layout = 0; channel_map = extradata + 21; } else { avpriv_request_sample(avctx, "Mapping type %d", map_type); return AVERROR_PATCHWELCOME; } s->channel_maps = av_mallocz_array(channels, sizeof(*s->channel_maps)); if (!s->channel_maps) return AVERROR(ENOMEM); for (i = 0; i < channels; i++) { ChannelMap *map = &s->channel_maps[i]; uint8_t idx = channel_map[channel_reorder(channels, i)]; if (idx == 255) { map->silence = 1; continue; } else if (idx >= streams + stereo_streams) { av_log(avctx, AV_LOG_ERROR, "Invalid channel map for output channel %d: %d\n", i, idx); av_freep(&s->channel_maps); return AVERROR_INVALIDDATA; } /* check that we did not see this index yet */ map->copy = 0; for (j = 0; j < i; j++) if (channel_map[channel_reorder(channels, j)] == idx) { map->copy = 1; map->copy_idx = j; break; } if (idx < 2 * stereo_streams) { map->stream_idx = idx / 2; map->channel_idx = idx & 1; } else { map->stream_idx = idx - stereo_streams; map->channel_idx = 0; } } avctx->channels = channels; avctx->channel_layout = layout; s->nb_streams = streams; s->nb_stereo_streams = stereo_streams; return 0; } void ff_celt_quant_bands(CeltFrame *f, OpusRangeCoder *rc) { float lowband_scratch[8 * 22]; float norm1[2 * 8 * 100]; float *norm2 = norm1 + 8 * 100; int totalbits = (f->framebits << 3) - f->anticollapse_needed; int update_lowband = 1; int lowband_offset = 0; int i, j; for (i = f->start_band; i < f->end_band; i++) { uint32_t cm[2] = { (1 << f->blocks) - 1, (1 << f->blocks) - 1 }; int band_offset = ff_celt_freq_bands[i] << f->size; int band_size = ff_celt_freq_range[i] << f->size; float *X = f->block[0].coeffs + band_offset; float *Y = (f->channels == 2) ? f->block[1].coeffs + band_offset : NULL; float *norm_loc1, *norm_loc2; int consumed = opus_rc_tell_frac(rc); int effective_lowband = -1; int b = 0; /* Compute how many bits we want to allocate to this band */ if (i != f->start_band) f->remaining -= consumed; f->remaining2 = totalbits - consumed - 1; if (i <= f->coded_bands - 1) { int curr_balance = f->remaining / FFMIN(3, f->coded_bands-i); b = av_clip_uintp2(FFMIN(f->remaining2 + 1, f->pulses[i] + curr_balance), 14); } if ((ff_celt_freq_bands[i] - ff_celt_freq_range[i] >= ff_celt_freq_bands[f->start_band] || i == f->start_band + 1) && (update_lowband || lowband_offset == 0)) lowband_offset = i; if (i == f->start_band + 1) { /* Special Hybrid Folding (RFC 8251 section 9). Copy the first band into the second to ensure the second band never has to use the LCG. */ int count = (ff_celt_freq_range[i] - ff_celt_freq_range[i-1]) << f->size; memcpy(&norm1[band_offset], &norm1[band_offset - count], count * sizeof(float)); if (f->channels == 2) memcpy(&norm2[band_offset], &norm2[band_offset - count], count * sizeof(float)); } /* Get a conservative estimate of the collapse_mask's for the bands we're going to be folding from. */ if (lowband_offset != 0 && (f->spread != CELT_SPREAD_AGGRESSIVE || f->blocks > 1 || f->tf_change[i] < 0)) { int foldstart, foldend; /* This ensures we never repeat spectral content within one band */ effective_lowband = FFMAX(ff_celt_freq_bands[f->start_band], ff_celt_freq_bands[lowband_offset] - ff_celt_freq_range[i]); foldstart = lowband_offset; while (ff_celt_freq_bands[--foldstart] > effective_lowband); foldend = lowband_offset - 1; while (++foldend < i && ff_celt_freq_bands[foldend] < effective_lowband + ff_celt_freq_range[i]); cm[0] = cm[1] = 0; for (j = foldstart; j < foldend; j++) { cm[0] |= f->block[0].collapse_masks[j]; cm[1] |= f->block[f->channels - 1].collapse_masks[j]; } } if (f->dual_stereo && i == f->intensity_stereo) { /* Switch off dual stereo to do intensity */ f->dual_stereo = 0; for (j = ff_celt_freq_bands[f->start_band] << f->size; j < band_offset; j++) norm1[j] = (norm1[j] + norm2[j]) / 2; } norm_loc1 = effective_lowband != -1 ? norm1 + (effective_lowband << f->size) : NULL; norm_loc2 = effective_lowband != -1 ? norm2 + (effective_lowband << f->size) : NULL; if (f->dual_stereo) { cm[0] = f->pvq->quant_band(f->pvq, f, rc, i, X, NULL, band_size, b >> 1, f->blocks, norm_loc1, f->size, norm1 + band_offset, 0, 1.0f, lowband_scratch, cm[0]); cm[1] = f->pvq->quant_band(f->pvq, f, rc, i, Y, NULL, band_size, b >> 1, f->blocks, norm_loc2, f->size, norm2 + band_offset, 0, 1.0f, lowband_scratch, cm[1]); } else { cm[0] = f->pvq->quant_band(f->pvq, f, rc, i, X, Y, band_size, b >> 0, f->blocks, norm_loc1, f->size, norm1 + band_offset, 0, 1.0f, lowband_scratch, cm[0] | cm[1]); cm[1] = cm[0]; } f->block[0].collapse_masks[i] = (uint8_t)cm[0]; f->block[f->channels - 1].collapse_masks[i] = (uint8_t)cm[1]; f->remaining += f->pulses[i] + consumed; /* Update the folding position only as long as we have 1 bit/sample depth */ update_lowband = (b > band_size << 3); } } #define NORMC(bits) ((bits) << (f->channels - 1) << f->size >> 2) void ff_celt_bitalloc(CeltFrame *f, OpusRangeCoder *rc, int encode) { int i, j, low, high, total, done, bandbits, remaining, tbits_8ths; int skip_startband = f->start_band; int skip_bit = 0; int intensitystereo_bit = 0; int dualstereo_bit = 0; int dynalloc = 6; int extrabits = 0; int boost[CELT_MAX_BANDS] = { 0 }; int trim_offset[CELT_MAX_BANDS]; int threshold[CELT_MAX_BANDS]; int bits1[CELT_MAX_BANDS]; int bits2[CELT_MAX_BANDS]; /* Spread */ if (opus_rc_tell(rc) + 4 <= f->framebits) { if (encode) ff_opus_rc_enc_cdf(rc, f->spread, ff_celt_model_spread); else f->spread = ff_opus_rc_dec_cdf(rc, ff_celt_model_spread); } else { f->spread = CELT_SPREAD_NORMAL; } /* Initialize static allocation caps */ for (i = 0; i < CELT_MAX_BANDS; i++) f->caps[i] = NORMC((ff_celt_static_caps[f->size][f->channels - 1][i] + 64) * ff_celt_freq_range[i]); /* Band boosts */ tbits_8ths = f->framebits << 3; for (i = f->start_band; i < f->end_band; i++) { int quanta = ff_celt_freq_range[i] << (f->channels - 1) << f->size; int b_dynalloc = dynalloc; int boost_amount = f->alloc_boost[i]; quanta = FFMIN(quanta << 3, FFMAX(6 << 3, quanta)); while (opus_rc_tell_frac(rc) + (b_dynalloc << 3) < tbits_8ths && boost[i] < f->caps[i]) { int is_boost; if (encode) { is_boost = boost_amount--; ff_opus_rc_enc_log(rc, is_boost, b_dynalloc); } else { is_boost = ff_opus_rc_dec_log(rc, b_dynalloc); } if (!is_boost) break; boost[i] += quanta; tbits_8ths -= quanta; b_dynalloc = 1; } if (boost[i]) dynalloc = FFMAX(dynalloc - 1, 2); } /* Allocation trim */ if (opus_rc_tell_frac(rc) + (6 << 3) <= tbits_8ths) if (encode) ff_opus_rc_enc_cdf(rc, f->alloc_trim, ff_celt_model_alloc_trim); else f->alloc_trim = ff_opus_rc_dec_cdf(rc, ff_celt_model_alloc_trim); /* Anti-collapse bit reservation */ tbits_8ths = (f->framebits << 3) - opus_rc_tell_frac(rc) - 1; f->anticollapse_needed = 0; if (f->transient && f->size >= 2 && tbits_8ths >= ((f->size + 2) << 3)) f->anticollapse_needed = 1 << 3; tbits_8ths -= f->anticollapse_needed; /* Band skip bit reservation */ if (tbits_8ths >= 1 << 3) skip_bit = 1 << 3; tbits_8ths -= skip_bit; /* Intensity/dual stereo bit reservation */ if (f->channels == 2) { intensitystereo_bit = ff_celt_log2_frac[f->end_band - f->start_band]; if (intensitystereo_bit <= tbits_8ths) { tbits_8ths -= intensitystereo_bit; if (tbits_8ths >= 1 << 3) { dualstereo_bit = 1 << 3; tbits_8ths -= 1 << 3; } } else { intensitystereo_bit = 0; } } /* Trim offsets */ for (i = f->start_band; i < f->end_band; i++) { int trim = f->alloc_trim - 5 - f->size; int band = ff_celt_freq_range[i] * (f->end_band - i - 1); int duration = f->size + 3; int scale = duration + f->channels - 1; /* PVQ minimum allocation threshold, below this value the band is * skipped */ threshold[i] = FFMAX(3 * ff_celt_freq_range[i] << duration >> 4, f->channels << 3); trim_offset[i] = trim * (band << scale) >> 6; if (ff_celt_freq_range[i] << f->size == 1) trim_offset[i] -= f->channels << 3; } /* Bisection */ low = 1; high = CELT_VECTORS - 1; while (low <= high) { int center = (low + high) >> 1; done = total = 0; for (i = f->end_band - 1; i >= f->start_band; i--) { bandbits = NORMC(ff_celt_freq_range[i] * ff_celt_static_alloc[center][i]); if (bandbits) bandbits = FFMAX(bandbits + trim_offset[i], 0); bandbits += boost[i]; if (bandbits >= threshold[i] || done) { done = 1; total += FFMIN(bandbits, f->caps[i]); } else if (bandbits >= f->channels << 3) { total += f->channels << 3; } } if (total > tbits_8ths) high = center - 1; else low = center + 1; } high = low--; /* Bisection */ for (i = f->start_band; i < f->end_band; i++) { bits1[i] = NORMC(ff_celt_freq_range[i] * ff_celt_static_alloc[low][i]); bits2[i] = high >= CELT_VECTORS ? f->caps[i] : NORMC(ff_celt_freq_range[i] * ff_celt_static_alloc[high][i]); if (bits1[i]) bits1[i] = FFMAX(bits1[i] + trim_offset[i], 0); if (bits2[i]) bits2[i] = FFMAX(bits2[i] + trim_offset[i], 0); if (low) bits1[i] += boost[i]; bits2[i] += boost[i]; if (boost[i]) skip_startband = i; bits2[i] = FFMAX(bits2[i] - bits1[i], 0); } /* Bisection */ low = 0; high = 1 << CELT_ALLOC_STEPS; for (i = 0; i < CELT_ALLOC_STEPS; i++) { int center = (low + high) >> 1; done = total = 0; for (j = f->end_band - 1; j >= f->start_band; j--) { bandbits = bits1[j] + (center * bits2[j] >> CELT_ALLOC_STEPS); if (bandbits >= threshold[j] || done) { done = 1; total += FFMIN(bandbits, f->caps[j]); } else if (bandbits >= f->channels << 3) total += f->channels << 3; } if (total > tbits_8ths) high = center; else low = center; } /* Bisection */ done = total = 0; for (i = f->end_band - 1; i >= f->start_band; i--) { bandbits = bits1[i] + (low * bits2[i] >> CELT_ALLOC_STEPS); if (bandbits >= threshold[i] || done) done = 1; else bandbits = (bandbits >= f->channels << 3) ? f->channels << 3 : 0; bandbits = FFMIN(bandbits, f->caps[i]); f->pulses[i] = bandbits; total += bandbits; } /* Band skipping */ for (f->coded_bands = f->end_band; ; f->coded_bands--) { int allocation; j = f->coded_bands - 1; if (j == skip_startband) { /* all remaining bands are not skipped */ tbits_8ths += skip_bit; break; } /* determine the number of bits available for coding "do not skip" markers */ remaining = tbits_8ths - total; bandbits = remaining / (ff_celt_freq_bands[j+1] - ff_celt_freq_bands[f->start_band]); remaining -= bandbits * (ff_celt_freq_bands[j+1] - ff_celt_freq_bands[f->start_band]); allocation = f->pulses[j] + bandbits * ff_celt_freq_range[j]; allocation += FFMAX(remaining - (ff_celt_freq_bands[j] - ff_celt_freq_bands[f->start_band]), 0); /* a "do not skip" marker is only coded if the allocation is * above the chosen threshold */ if (allocation >= FFMAX(threshold[j], (f->channels + 1) << 3)) { int do_not_skip; if (encode) { do_not_skip = f->coded_bands <= f->skip_band_floor; ff_opus_rc_enc_log(rc, do_not_skip, 1); } else { do_not_skip = ff_opus_rc_dec_log(rc, 1); } if (do_not_skip) break; total += 1 << 3; allocation -= 1 << 3; } /* the band is skipped, so reclaim its bits */ total -= f->pulses[j]; if (intensitystereo_bit) { total -= intensitystereo_bit; intensitystereo_bit = ff_celt_log2_frac[j - f->start_band]; total += intensitystereo_bit; } total += f->pulses[j] = (allocation >= f->channels << 3) ? f->channels << 3 : 0; } /* IS start band */ if (encode) { if (intensitystereo_bit) { f->intensity_stereo = FFMIN(f->intensity_stereo, f->coded_bands); ff_opus_rc_enc_uint(rc, f->intensity_stereo, f->coded_bands + 1 - f->start_band); } } else { f->intensity_stereo = f->dual_stereo = 0; if (intensitystereo_bit) f->intensity_stereo = f->start_band + ff_opus_rc_dec_uint(rc, f->coded_bands + 1 - f->start_band); } /* DS flag */ if (f->intensity_stereo <= f->start_band) tbits_8ths += dualstereo_bit; /* no intensity stereo means no dual stereo */ else if (dualstereo_bit) if (encode) ff_opus_rc_enc_log(rc, f->dual_stereo, 1); else f->dual_stereo = ff_opus_rc_dec_log(rc, 1); /* Supply the remaining bits in this frame to lower bands */ remaining = tbits_8ths - total; bandbits = remaining / (ff_celt_freq_bands[f->coded_bands] - ff_celt_freq_bands[f->start_band]); remaining -= bandbits * (ff_celt_freq_bands[f->coded_bands] - ff_celt_freq_bands[f->start_band]); for (i = f->start_band; i < f->coded_bands; i++) { const int bits = FFMIN(remaining, ff_celt_freq_range[i]); f->pulses[i] += bits + bandbits * ff_celt_freq_range[i]; remaining -= bits; } /* Finally determine the allocation */ for (i = f->start_band; i < f->coded_bands; i++) { int N = ff_celt_freq_range[i] << f->size; int prev_extra = extrabits; f->pulses[i] += extrabits; if (N > 1) { int dof; /* degrees of freedom */ int temp; /* dof * channels * log(dof) */ int fine_bits; int max_bits; int offset; /* fine energy quantization offset, i.e. * extra bits assigned over the standard * totalbits/dof */ extrabits = FFMAX(f->pulses[i] - f->caps[i], 0); f->pulses[i] -= extrabits; /* intensity stereo makes use of an extra degree of freedom */ dof = N * f->channels + (f->channels == 2 && N > 2 && !f->dual_stereo && i < f->intensity_stereo); temp = dof * (ff_celt_log_freq_range[i] + (f->size << 3)); offset = (temp >> 1) - dof * CELT_FINE_OFFSET; if (N == 2) /* dof=2 is the only case that doesn't fit the model */ offset += dof << 1; /* grant an additional bias for the first and second pulses */ if (f->pulses[i] + offset < 2 * (dof << 3)) offset += temp >> 2; else if (f->pulses[i] + offset < 3 * (dof << 3)) offset += temp >> 3; fine_bits = (f->pulses[i] + offset + (dof << 2)) / (dof << 3); max_bits = FFMIN((f->pulses[i] >> 3) >> (f->channels - 1), CELT_MAX_FINE_BITS); max_bits = FFMAX(max_bits, 0); f->fine_bits[i] = av_clip(fine_bits, 0, max_bits); /* If fine_bits was rounded down or capped, * give priority for the final fine energy pass */ f->fine_priority[i] = (f->fine_bits[i] * (dof << 3) >= f->pulses[i] + offset); /* the remaining bits are assigned to PVQ */ f->pulses[i] -= f->fine_bits[i] << (f->channels - 1) << 3; } else { /* all bits go to fine energy except for the sign bit */ extrabits = FFMAX(f->pulses[i] - (f->channels << 3), 0); f->pulses[i] -= extrabits; f->fine_bits[i] = 0; f->fine_priority[i] = 1; } /* hand back a limited number of extra fine energy bits to this band */ if (extrabits > 0) { int fineextra = FFMIN(extrabits >> (f->channels + 2), CELT_MAX_FINE_BITS - f->fine_bits[i]); f->fine_bits[i] += fineextra; fineextra <<= f->channels + 2; f->fine_priority[i] = (fineextra >= extrabits - prev_extra); extrabits -= fineextra; } } f->remaining = extrabits; /* skipped bands dedicate all of their bits for fine energy */ for (; i < f->end_band; i++) { f->fine_bits[i] = f->pulses[i] >> (f->channels - 1) >> 3; f->pulses[i] = 0; f->fine_priority[i] = f->fine_bits[i] < 1; } }
null
null
null
null
71,282
29,750
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
194,745
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * adutux - driver for ADU devices from Ontrak Control Systems * This is an experimental driver. Use at your own risk. * This driver is not supported by Ontrak Control Systems. * * Copyright (c) 2003 John Homppi (SCO, leave this notice here) * * 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. * * derived from the Lego USB Tower driver 0.56: * Copyright (c) 2003 David Glance <davidgsf@sourceforge.net> * 2001 Juergen Stuber <stuber@loria.fr> * that was derived from USB Skeleton driver - 0.5 * Copyright (c) 2001 Greg Kroah-Hartman (greg@kroah.com) * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/sched/signal.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/usb.h> #include <linux/mutex.h> #include <linux/uaccess.h> /* Version Information */ #define DRIVER_VERSION "v0.0.13" #define DRIVER_AUTHOR "John Homppi" #define DRIVER_DESC "adutux (see www.ontrak.net)" /* Define these values to match your device */ #define ADU_VENDOR_ID 0x0a07 #define ADU_PRODUCT_ID 0x0064 /* table of devices that work with this driver */ static const struct usb_device_id device_table[] = { { USB_DEVICE(ADU_VENDOR_ID, ADU_PRODUCT_ID) }, /* ADU100 */ { USB_DEVICE(ADU_VENDOR_ID, ADU_PRODUCT_ID+20) }, /* ADU120 */ { USB_DEVICE(ADU_VENDOR_ID, ADU_PRODUCT_ID+30) }, /* ADU130 */ { USB_DEVICE(ADU_VENDOR_ID, ADU_PRODUCT_ID+100) }, /* ADU200 */ { USB_DEVICE(ADU_VENDOR_ID, ADU_PRODUCT_ID+108) }, /* ADU208 */ { USB_DEVICE(ADU_VENDOR_ID, ADU_PRODUCT_ID+118) }, /* ADU218 */ { } /* Terminating entry */ }; MODULE_DEVICE_TABLE(usb, device_table); #ifdef CONFIG_USB_DYNAMIC_MINORS #define ADU_MINOR_BASE 0 #else #define ADU_MINOR_BASE 67 #endif /* we can have up to this number of device plugged in at once */ #define MAX_DEVICES 16 #define COMMAND_TIMEOUT (2*HZ) /* 60 second timeout for a command */ /* * The locking scheme is a vanilla 3-lock: * adu_device.buflock: A spinlock, covers what IRQs touch. * adutux_mutex: A Static lock to cover open_count. It would also cover * any globals, but we don't have them in 2.6. * adu_device.mtx: A mutex to hold across sleepers like copy_from_user. * It covers all of adu_device, except the open_count * and what .buflock covers. */ /* Structure to hold all of our device specific stuff */ struct adu_device { struct mutex mtx; struct usb_device *udev; /* save off the usb device pointer */ struct usb_interface *interface; unsigned int minor; /* the starting minor number for this device */ char serial_number[8]; int open_count; /* number of times this port has been opened */ char *read_buffer_primary; int read_buffer_length; char *read_buffer_secondary; int secondary_head; int secondary_tail; spinlock_t buflock; wait_queue_head_t read_wait; wait_queue_head_t write_wait; char *interrupt_in_buffer; struct usb_endpoint_descriptor *interrupt_in_endpoint; struct urb *interrupt_in_urb; int read_urb_finished; char *interrupt_out_buffer; struct usb_endpoint_descriptor *interrupt_out_endpoint; struct urb *interrupt_out_urb; int out_urb_finished; }; static DEFINE_MUTEX(adutux_mutex); static struct usb_driver adu_driver; static inline void adu_debug_data(struct device *dev, const char *function, int size, const unsigned char *data) { dev_dbg(dev, "%s - length = %d, data = %*ph\n", function, size, size, data); } /** * adu_abort_transfers * aborts transfers and frees associated data structures */ static void adu_abort_transfers(struct adu_device *dev) { unsigned long flags; if (dev->udev == NULL) return; /* shutdown transfer */ /* XXX Anchor these instead */ spin_lock_irqsave(&dev->buflock, flags); if (!dev->read_urb_finished) { spin_unlock_irqrestore(&dev->buflock, flags); usb_kill_urb(dev->interrupt_in_urb); } else spin_unlock_irqrestore(&dev->buflock, flags); spin_lock_irqsave(&dev->buflock, flags); if (!dev->out_urb_finished) { spin_unlock_irqrestore(&dev->buflock, flags); usb_kill_urb(dev->interrupt_out_urb); } else spin_unlock_irqrestore(&dev->buflock, flags); } static void adu_delete(struct adu_device *dev) { /* free data structures */ usb_free_urb(dev->interrupt_in_urb); usb_free_urb(dev->interrupt_out_urb); kfree(dev->read_buffer_primary); kfree(dev->read_buffer_secondary); kfree(dev->interrupt_in_buffer); kfree(dev->interrupt_out_buffer); kfree(dev); } static void adu_interrupt_in_callback(struct urb *urb) { struct adu_device *dev = urb->context; int status = urb->status; adu_debug_data(&dev->udev->dev, __func__, urb->actual_length, urb->transfer_buffer); spin_lock(&dev->buflock); if (status != 0) { if ((status != -ENOENT) && (status != -ECONNRESET) && (status != -ESHUTDOWN)) { dev_dbg(&dev->udev->dev, "%s : nonzero status received: %d\n", __func__, status); } goto exit; } if (urb->actual_length > 0 && dev->interrupt_in_buffer[0] != 0x00) { if (dev->read_buffer_length < (4 * usb_endpoint_maxp(dev->interrupt_in_endpoint)) - (urb->actual_length)) { memcpy (dev->read_buffer_primary + dev->read_buffer_length, dev->interrupt_in_buffer, urb->actual_length); dev->read_buffer_length += urb->actual_length; dev_dbg(&dev->udev->dev,"%s reading %d\n", __func__, urb->actual_length); } else { dev_dbg(&dev->udev->dev,"%s : read_buffer overflow\n", __func__); } } exit: dev->read_urb_finished = 1; spin_unlock(&dev->buflock); /* always wake up so we recover from errors */ wake_up_interruptible(&dev->read_wait); } static void adu_interrupt_out_callback(struct urb *urb) { struct adu_device *dev = urb->context; int status = urb->status; adu_debug_data(&dev->udev->dev, __func__, urb->actual_length, urb->transfer_buffer); if (status != 0) { if ((status != -ENOENT) && (status != -ECONNRESET)) { dev_dbg(&dev->udev->dev, "%s :nonzero status received: %d\n", __func__, status); } return; } spin_lock(&dev->buflock); dev->out_urb_finished = 1; wake_up(&dev->write_wait); spin_unlock(&dev->buflock); } static int adu_open(struct inode *inode, struct file *file) { struct adu_device *dev = NULL; struct usb_interface *interface; int subminor; int retval; subminor = iminor(inode); retval = mutex_lock_interruptible(&adutux_mutex); if (retval) goto exit_no_lock; interface = usb_find_interface(&adu_driver, subminor); if (!interface) { pr_err("%s - error, can't find device for minor %d\n", __func__, subminor); retval = -ENODEV; goto exit_no_device; } dev = usb_get_intfdata(interface); if (!dev || !dev->udev) { retval = -ENODEV; goto exit_no_device; } /* check that nobody else is using the device */ if (dev->open_count) { retval = -EBUSY; goto exit_no_device; } ++dev->open_count; dev_dbg(&dev->udev->dev, "%s: open count %d\n", __func__, dev->open_count); /* save device in the file's private structure */ file->private_data = dev; /* initialize in direction */ dev->read_buffer_length = 0; /* fixup first read by having urb waiting for it */ usb_fill_int_urb(dev->interrupt_in_urb, dev->udev, usb_rcvintpipe(dev->udev, dev->interrupt_in_endpoint->bEndpointAddress), dev->interrupt_in_buffer, usb_endpoint_maxp(dev->interrupt_in_endpoint), adu_interrupt_in_callback, dev, dev->interrupt_in_endpoint->bInterval); dev->read_urb_finished = 0; if (usb_submit_urb(dev->interrupt_in_urb, GFP_KERNEL)) dev->read_urb_finished = 1; /* we ignore failure */ /* end of fixup for first read */ /* initialize out direction */ dev->out_urb_finished = 1; retval = 0; exit_no_device: mutex_unlock(&adutux_mutex); exit_no_lock: return retval; } static void adu_release_internal(struct adu_device *dev) { /* decrement our usage count for the device */ --dev->open_count; dev_dbg(&dev->udev->dev, "%s : open count %d\n", __func__, dev->open_count); if (dev->open_count <= 0) { adu_abort_transfers(dev); dev->open_count = 0; } } static int adu_release(struct inode *inode, struct file *file) { struct adu_device *dev; int retval = 0; if (file == NULL) { retval = -ENODEV; goto exit; } dev = file->private_data; if (dev == NULL) { retval = -ENODEV; goto exit; } mutex_lock(&adutux_mutex); /* not interruptible */ if (dev->open_count <= 0) { dev_dbg(&dev->udev->dev, "%s : device not opened\n", __func__); retval = -ENODEV; goto unlock; } adu_release_internal(dev); if (dev->udev == NULL) { /* the device was unplugged before the file was released */ if (!dev->open_count) /* ... and we're the last user */ adu_delete(dev); } unlock: mutex_unlock(&adutux_mutex); exit: return retval; } static ssize_t adu_read(struct file *file, __user char *buffer, size_t count, loff_t *ppos) { struct adu_device *dev; size_t bytes_read = 0; size_t bytes_to_read = count; int i; int retval = 0; int timeout = 0; int should_submit = 0; unsigned long flags; DECLARE_WAITQUEUE(wait, current); dev = file->private_data; if (mutex_lock_interruptible(&dev->mtx)) return -ERESTARTSYS; /* verify that the device wasn't unplugged */ if (dev->udev == NULL) { retval = -ENODEV; pr_err("No device or device unplugged %d\n", retval); goto exit; } /* verify that some data was requested */ if (count == 0) { dev_dbg(&dev->udev->dev, "%s : read request of 0 bytes\n", __func__); goto exit; } timeout = COMMAND_TIMEOUT; dev_dbg(&dev->udev->dev, "%s : about to start looping\n", __func__); while (bytes_to_read) { int data_in_secondary = dev->secondary_tail - dev->secondary_head; dev_dbg(&dev->udev->dev, "%s : while, data_in_secondary=%d, status=%d\n", __func__, data_in_secondary, dev->interrupt_in_urb->status); if (data_in_secondary) { /* drain secondary buffer */ int amount = bytes_to_read < data_in_secondary ? bytes_to_read : data_in_secondary; i = copy_to_user(buffer, dev->read_buffer_secondary+dev->secondary_head, amount); if (i) { retval = -EFAULT; goto exit; } dev->secondary_head += (amount - i); bytes_read += (amount - i); bytes_to_read -= (amount - i); } else { /* we check the primary buffer */ spin_lock_irqsave (&dev->buflock, flags); if (dev->read_buffer_length) { /* we secure access to the primary */ char *tmp; dev_dbg(&dev->udev->dev, "%s : swap, read_buffer_length = %d\n", __func__, dev->read_buffer_length); tmp = dev->read_buffer_secondary; dev->read_buffer_secondary = dev->read_buffer_primary; dev->read_buffer_primary = tmp; dev->secondary_head = 0; dev->secondary_tail = dev->read_buffer_length; dev->read_buffer_length = 0; spin_unlock_irqrestore(&dev->buflock, flags); /* we have a free buffer so use it */ should_submit = 1; } else { /* even the primary was empty - we may need to do IO */ if (!dev->read_urb_finished) { /* somebody is doing IO */ spin_unlock_irqrestore(&dev->buflock, flags); dev_dbg(&dev->udev->dev, "%s : submitted already\n", __func__); } else { /* we must initiate input */ dev_dbg(&dev->udev->dev, "%s : initiate input\n", __func__); dev->read_urb_finished = 0; spin_unlock_irqrestore(&dev->buflock, flags); usb_fill_int_urb(dev->interrupt_in_urb, dev->udev, usb_rcvintpipe(dev->udev, dev->interrupt_in_endpoint->bEndpointAddress), dev->interrupt_in_buffer, usb_endpoint_maxp(dev->interrupt_in_endpoint), adu_interrupt_in_callback, dev, dev->interrupt_in_endpoint->bInterval); retval = usb_submit_urb(dev->interrupt_in_urb, GFP_KERNEL); if (retval) { dev->read_urb_finished = 1; if (retval == -ENOMEM) { retval = bytes_read ? bytes_read : -ENOMEM; } dev_dbg(&dev->udev->dev, "%s : submit failed\n", __func__); goto exit; } } /* we wait for I/O to complete */ set_current_state(TASK_INTERRUPTIBLE); add_wait_queue(&dev->read_wait, &wait); spin_lock_irqsave(&dev->buflock, flags); if (!dev->read_urb_finished) { spin_unlock_irqrestore(&dev->buflock, flags); timeout = schedule_timeout(COMMAND_TIMEOUT); } else { spin_unlock_irqrestore(&dev->buflock, flags); set_current_state(TASK_RUNNING); } remove_wait_queue(&dev->read_wait, &wait); if (timeout <= 0) { dev_dbg(&dev->udev->dev, "%s : timeout\n", __func__); retval = bytes_read ? bytes_read : -ETIMEDOUT; goto exit; } if (signal_pending(current)) { dev_dbg(&dev->udev->dev, "%s : signal pending\n", __func__); retval = bytes_read ? bytes_read : -EINTR; goto exit; } } } } retval = bytes_read; /* if the primary buffer is empty then use it */ spin_lock_irqsave(&dev->buflock, flags); if (should_submit && dev->read_urb_finished) { dev->read_urb_finished = 0; spin_unlock_irqrestore(&dev->buflock, flags); usb_fill_int_urb(dev->interrupt_in_urb, dev->udev, usb_rcvintpipe(dev->udev, dev->interrupt_in_endpoint->bEndpointAddress), dev->interrupt_in_buffer, usb_endpoint_maxp(dev->interrupt_in_endpoint), adu_interrupt_in_callback, dev, dev->interrupt_in_endpoint->bInterval); if (usb_submit_urb(dev->interrupt_in_urb, GFP_KERNEL) != 0) dev->read_urb_finished = 1; /* we ignore failure */ } else { spin_unlock_irqrestore(&dev->buflock, flags); } exit: /* unlock the device */ mutex_unlock(&dev->mtx); return retval; } static ssize_t adu_write(struct file *file, const __user char *buffer, size_t count, loff_t *ppos) { DECLARE_WAITQUEUE(waita, current); struct adu_device *dev; size_t bytes_written = 0; size_t bytes_to_write; size_t buffer_size; unsigned long flags; int retval; dev = file->private_data; retval = mutex_lock_interruptible(&dev->mtx); if (retval) goto exit_nolock; /* verify that the device wasn't unplugged */ if (dev->udev == NULL) { retval = -ENODEV; pr_err("No device or device unplugged %d\n", retval); goto exit; } /* verify that we actually have some data to write */ if (count == 0) { dev_dbg(&dev->udev->dev, "%s : write request of 0 bytes\n", __func__); goto exit; } while (count > 0) { add_wait_queue(&dev->write_wait, &waita); set_current_state(TASK_INTERRUPTIBLE); spin_lock_irqsave(&dev->buflock, flags); if (!dev->out_urb_finished) { spin_unlock_irqrestore(&dev->buflock, flags); mutex_unlock(&dev->mtx); if (signal_pending(current)) { dev_dbg(&dev->udev->dev, "%s : interrupted\n", __func__); set_current_state(TASK_RUNNING); retval = -EINTR; goto exit_onqueue; } if (schedule_timeout(COMMAND_TIMEOUT) == 0) { dev_dbg(&dev->udev->dev, "%s - command timed out.\n", __func__); retval = -ETIMEDOUT; goto exit_onqueue; } remove_wait_queue(&dev->write_wait, &waita); retval = mutex_lock_interruptible(&dev->mtx); if (retval) { retval = bytes_written ? bytes_written : retval; goto exit_nolock; } dev_dbg(&dev->udev->dev, "%s : in progress, count = %zd\n", __func__, count); } else { spin_unlock_irqrestore(&dev->buflock, flags); set_current_state(TASK_RUNNING); remove_wait_queue(&dev->write_wait, &waita); dev_dbg(&dev->udev->dev, "%s : sending, count = %zd\n", __func__, count); /* write the data into interrupt_out_buffer from userspace */ buffer_size = usb_endpoint_maxp(dev->interrupt_out_endpoint); bytes_to_write = count > buffer_size ? buffer_size : count; dev_dbg(&dev->udev->dev, "%s : buffer_size = %zd, count = %zd, bytes_to_write = %zd\n", __func__, buffer_size, count, bytes_to_write); if (copy_from_user(dev->interrupt_out_buffer, buffer, bytes_to_write) != 0) { retval = -EFAULT; goto exit; } /* send off the urb */ usb_fill_int_urb( dev->interrupt_out_urb, dev->udev, usb_sndintpipe(dev->udev, dev->interrupt_out_endpoint->bEndpointAddress), dev->interrupt_out_buffer, bytes_to_write, adu_interrupt_out_callback, dev, dev->interrupt_out_endpoint->bInterval); dev->interrupt_out_urb->actual_length = bytes_to_write; dev->out_urb_finished = 0; retval = usb_submit_urb(dev->interrupt_out_urb, GFP_KERNEL); if (retval < 0) { dev->out_urb_finished = 1; dev_err(&dev->udev->dev, "Couldn't submit " "interrupt_out_urb %d\n", retval); goto exit; } buffer += bytes_to_write; count -= bytes_to_write; bytes_written += bytes_to_write; } } mutex_unlock(&dev->mtx); return bytes_written; exit: mutex_unlock(&dev->mtx); exit_nolock: return retval; exit_onqueue: remove_wait_queue(&dev->write_wait, &waita); return retval; } /* file operations needed when we register this driver */ static const struct file_operations adu_fops = { .owner = THIS_MODULE, .read = adu_read, .write = adu_write, .open = adu_open, .release = adu_release, .llseek = noop_llseek, }; /* * usb class driver info in order to get a minor number from the usb core, * and to have the device registered with devfs and the driver core */ static struct usb_class_driver adu_class = { .name = "usb/adutux%d", .fops = &adu_fops, .minor_base = ADU_MINOR_BASE, }; /** * adu_probe * * Called by the usb core when a new device is connected that it thinks * this driver might be interested in. */ static int adu_probe(struct usb_interface *interface, const struct usb_device_id *id) { struct usb_device *udev = interface_to_usbdev(interface); struct adu_device *dev = NULL; struct usb_host_interface *iface_desc; struct usb_endpoint_descriptor *endpoint; int retval = -ENODEV; int in_end_size; int out_end_size; int i; if (udev == NULL) { dev_err(&interface->dev, "udev is NULL.\n"); goto exit; } /* allocate memory for our device state and initialize it */ dev = kzalloc(sizeof(struct adu_device), GFP_KERNEL); if (!dev) { retval = -ENOMEM; goto exit; } mutex_init(&dev->mtx); spin_lock_init(&dev->buflock); dev->udev = udev; init_waitqueue_head(&dev->read_wait); init_waitqueue_head(&dev->write_wait); iface_desc = &interface->altsetting[0]; /* set up the endpoint information */ for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) { endpoint = &iface_desc->endpoint[i].desc; if (usb_endpoint_is_int_in(endpoint)) dev->interrupt_in_endpoint = endpoint; if (usb_endpoint_is_int_out(endpoint)) dev->interrupt_out_endpoint = endpoint; } if (dev->interrupt_in_endpoint == NULL) { dev_err(&interface->dev, "interrupt in endpoint not found\n"); goto error; } if (dev->interrupt_out_endpoint == NULL) { dev_err(&interface->dev, "interrupt out endpoint not found\n"); goto error; } in_end_size = usb_endpoint_maxp(dev->interrupt_in_endpoint); out_end_size = usb_endpoint_maxp(dev->interrupt_out_endpoint); dev->read_buffer_primary = kmalloc((4 * in_end_size), GFP_KERNEL); if (!dev->read_buffer_primary) { retval = -ENOMEM; goto error; } /* debug code prime the buffer */ memset(dev->read_buffer_primary, 'a', in_end_size); memset(dev->read_buffer_primary + in_end_size, 'b', in_end_size); memset(dev->read_buffer_primary + (2 * in_end_size), 'c', in_end_size); memset(dev->read_buffer_primary + (3 * in_end_size), 'd', in_end_size); dev->read_buffer_secondary = kmalloc((4 * in_end_size), GFP_KERNEL); if (!dev->read_buffer_secondary) { retval = -ENOMEM; goto error; } /* debug code prime the buffer */ memset(dev->read_buffer_secondary, 'e', in_end_size); memset(dev->read_buffer_secondary + in_end_size, 'f', in_end_size); memset(dev->read_buffer_secondary + (2 * in_end_size), 'g', in_end_size); memset(dev->read_buffer_secondary + (3 * in_end_size), 'h', in_end_size); dev->interrupt_in_buffer = kmalloc(in_end_size, GFP_KERNEL); if (!dev->interrupt_in_buffer) goto error; /* debug code prime the buffer */ memset(dev->interrupt_in_buffer, 'i', in_end_size); dev->interrupt_in_urb = usb_alloc_urb(0, GFP_KERNEL); if (!dev->interrupt_in_urb) goto error; dev->interrupt_out_buffer = kmalloc(out_end_size, GFP_KERNEL); if (!dev->interrupt_out_buffer) goto error; dev->interrupt_out_urb = usb_alloc_urb(0, GFP_KERNEL); if (!dev->interrupt_out_urb) goto error; if (!usb_string(udev, udev->descriptor.iSerialNumber, dev->serial_number, sizeof(dev->serial_number))) { dev_err(&interface->dev, "Could not retrieve serial number\n"); goto error; } dev_dbg(&interface->dev,"serial_number=%s", dev->serial_number); /* we can register the device now, as it is ready */ usb_set_intfdata(interface, dev); retval = usb_register_dev(interface, &adu_class); if (retval) { /* something prevented us from registering this driver */ dev_err(&interface->dev, "Not able to get a minor for this device.\n"); usb_set_intfdata(interface, NULL); goto error; } dev->minor = interface->minor; /* let the user know what node this device is now attached to */ dev_info(&interface->dev, "ADU%d %s now attached to /dev/usb/adutux%d\n", le16_to_cpu(udev->descriptor.idProduct), dev->serial_number, (dev->minor - ADU_MINOR_BASE)); exit: return retval; error: adu_delete(dev); return retval; } /** * adu_disconnect * * Called by the usb core when the device is removed from the system. */ static void adu_disconnect(struct usb_interface *interface) { struct adu_device *dev; int minor; dev = usb_get_intfdata(interface); mutex_lock(&dev->mtx); /* not interruptible */ dev->udev = NULL; /* poison */ minor = dev->minor; usb_deregister_dev(interface, &adu_class); mutex_unlock(&dev->mtx); mutex_lock(&adutux_mutex); usb_set_intfdata(interface, NULL); /* if the device is not opened, then we clean up right now */ if (!dev->open_count) adu_delete(dev); mutex_unlock(&adutux_mutex); } /* usb specific object needed to register this driver with the usb subsystem */ static struct usb_driver adu_driver = { .name = "adutux", .probe = adu_probe, .disconnect = adu_disconnect, .id_table = device_table, }; module_usb_driver(adu_driver); MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL");
null
null
null
null
103,092
70,604
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
70,604
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 <algorithm> #include "base/logging.h" #include "skia/ext/convolver.h" #include "skia/ext/convolver_SSE2.h" #include "skia/ext/convolver_mips_dspr2.h" #include "skia/ext/convolver_neon.h" #include "third_party/skia/include/core/SkSize.h" #include "third_party/skia/include/core/SkTypes.h" namespace skia { namespace { // Converts the argument to an 8-bit unsigned value by clamping to the range // 0-255. inline unsigned char ClampTo8(int a) { if (static_cast<unsigned>(a) < 256) return a; // Avoid the extra check in the common case. if (a < 0) return 0; return 255; } // Takes the value produced by accumulating element-wise product of image with // a kernel and brings it back into range. // All of the filter scaling factors are in fixed point with kShiftBits bits of // fractional part. inline unsigned char BringBackTo8(int a, bool take_absolute) { a >>= ConvolutionFilter1D::kShiftBits; if (take_absolute) a = std::abs(a); return ClampTo8(a); } // Stores a list of rows in a circular buffer. The usage is you write into it // by calling AdvanceRow. It will keep track of which row in the buffer it // should use next, and the total number of rows added. class CircularRowBuffer { public: // The number of pixels in each row is given in |source_row_pixel_width|. // The maximum number of rows needed in the buffer is |max_y_filter_size| // (we only need to store enough rows for the biggest filter). // // We use the |first_input_row| to compute the coordinates of all of the // following rows returned by Advance(). CircularRowBuffer(int dest_row_pixel_width, int max_y_filter_size, int first_input_row) : row_byte_width_(dest_row_pixel_width * 4), num_rows_(max_y_filter_size), next_row_(0), next_row_coordinate_(first_input_row) { buffer_.resize(row_byte_width_ * max_y_filter_size); row_addresses_.resize(num_rows_); } // Moves to the next row in the buffer, returning a pointer to the beginning // of it. unsigned char* AdvanceRow() { unsigned char* row = &buffer_[next_row_ * row_byte_width_]; next_row_coordinate_++; // Set the pointer to the next row to use, wrapping around if necessary. next_row_++; if (next_row_ == num_rows_) next_row_ = 0; return row; } // Returns a pointer to an "unrolled" array of rows. These rows will start // at the y coordinate placed into |*first_row_index| and will continue in // order for the maximum number of rows in this circular buffer. // // The |first_row_index_| may be negative. This means the circular buffer // starts before the top of the image (it hasn't been filled yet). unsigned char* const* GetRowAddresses(int* first_row_index) { // Example for a 4-element circular buffer holding coords 6-9. // Row 0 Coord 8 // Row 1 Coord 9 // Row 2 Coord 6 <- next_row_ = 2, next_row_coordinate_ = 10. // Row 3 Coord 7 // // The "next" row is also the first (lowest) coordinate. This computation // may yield a negative value, but that's OK, the math will work out // since the user of this buffer will compute the offset relative // to the first_row_index and the negative rows will never be used. *first_row_index = next_row_coordinate_ - num_rows_; int cur_row = next_row_; for (int i = 0; i < num_rows_; i++) { row_addresses_[i] = &buffer_[cur_row * row_byte_width_]; // Advance to the next row, wrapping if necessary. cur_row++; if (cur_row == num_rows_) cur_row = 0; } return &row_addresses_[0]; } private: // The buffer storing the rows. They are packed, each one row_byte_width_. std::vector<unsigned char> buffer_; // Number of bytes per row in the |buffer_|. int row_byte_width_; // The number of rows available in the buffer. int num_rows_; // The next row index we should write into. This wraps around as the // circular buffer is used. int next_row_; // The y coordinate of the |next_row_|. This is incremented each time a // new row is appended and does not wrap. int next_row_coordinate_; // Buffer used by GetRowAddresses(). std::vector<unsigned char*> row_addresses_; }; // Convolves horizontally along a single row. The row data is given in // |src_data| and continues for the num_values() of the filter. template<bool has_alpha> void ConvolveHorizontally(const unsigned char* src_data, const ConvolutionFilter1D& filter, unsigned char* out_row) { // Loop over each pixel on this row in the output image. int num_values = filter.num_values(); for (int out_x = 0; out_x < num_values; out_x++) { // Get the filter that determines the current output pixel. int filter_offset, filter_length; const ConvolutionFilter1D::Fixed* filter_values = filter.FilterForValue(out_x, &filter_offset, &filter_length); // Compute the first pixel in this row that the filter affects. It will // touch |filter_length| pixels (4 bytes each) after this. const unsigned char* row_to_filter = &src_data[filter_offset * 4]; // Apply the filter to the row to get the destination pixel in |accum|. int accum[4] = {0}; for (int filter_x = 0; filter_x < filter_length; filter_x++) { ConvolutionFilter1D::Fixed cur_filter = filter_values[filter_x]; accum[0] += cur_filter * row_to_filter[filter_x * 4 + 0]; accum[1] += cur_filter * row_to_filter[filter_x * 4 + 1]; accum[2] += cur_filter * row_to_filter[filter_x * 4 + 2]; if (has_alpha) accum[3] += cur_filter * row_to_filter[filter_x * 4 + 3]; } // Bring this value back in range. All of the filter scaling factors // are in fixed point with kShiftBits bits of fractional part. accum[0] >>= ConvolutionFilter1D::kShiftBits; accum[1] >>= ConvolutionFilter1D::kShiftBits; accum[2] >>= ConvolutionFilter1D::kShiftBits; if (has_alpha) accum[3] >>= ConvolutionFilter1D::kShiftBits; // Store the new pixel. out_row[out_x * 4 + 0] = ClampTo8(accum[0]); out_row[out_x * 4 + 1] = ClampTo8(accum[1]); out_row[out_x * 4 + 2] = ClampTo8(accum[2]); if (has_alpha) out_row[out_x * 4 + 3] = ClampTo8(accum[3]); } } // Does vertical convolution to produce one output row. The filter values and // length are given in the first two parameters. These are applied to each // of the rows pointed to in the |source_data_rows| array, with each row // being |pixel_width| wide. // // The output must have room for |pixel_width * 4| bytes. template<bool has_alpha> void ConvolveVertically(const ConvolutionFilter1D::Fixed* filter_values, int filter_length, unsigned char* const* source_data_rows, int pixel_width, unsigned char* out_row) { // We go through each column in the output and do a vertical convolution, // generating one output pixel each time. for (int out_x = 0; out_x < pixel_width; out_x++) { // Compute the number of bytes over in each row that the current column // we're convolving starts at. The pixel will cover the next 4 bytes. int byte_offset = out_x * 4; // Apply the filter to one column of pixels. int accum[4] = {0}; for (int filter_y = 0; filter_y < filter_length; filter_y++) { ConvolutionFilter1D::Fixed cur_filter = filter_values[filter_y]; accum[0] += cur_filter * source_data_rows[filter_y][byte_offset + 0]; accum[1] += cur_filter * source_data_rows[filter_y][byte_offset + 1]; accum[2] += cur_filter * source_data_rows[filter_y][byte_offset + 2]; if (has_alpha) accum[3] += cur_filter * source_data_rows[filter_y][byte_offset + 3]; } // Bring this value back in range. All of the filter scaling factors // are in fixed point with kShiftBits bits of precision. accum[0] >>= ConvolutionFilter1D::kShiftBits; accum[1] >>= ConvolutionFilter1D::kShiftBits; accum[2] >>= ConvolutionFilter1D::kShiftBits; if (has_alpha) accum[3] >>= ConvolutionFilter1D::kShiftBits; // Store the new pixel. out_row[byte_offset + 0] = ClampTo8(accum[0]); out_row[byte_offset + 1] = ClampTo8(accum[1]); out_row[byte_offset + 2] = ClampTo8(accum[2]); if (has_alpha) { unsigned char alpha = ClampTo8(accum[3]); // Make sure the alpha channel doesn't come out smaller than any of the // color channels. We use premultipled alpha channels, so this should // never happen, but rounding errors will cause this from time to time. // These "impossible" colors will cause overflows (and hence random pixel // values) when the resulting bitmap is drawn to the screen. // // We only need to do this when generating the final output row (here). int max_color_channel = std::max(out_row[byte_offset + 0], std::max(out_row[byte_offset + 1], out_row[byte_offset + 2])); if (alpha < max_color_channel) out_row[byte_offset + 3] = max_color_channel; else out_row[byte_offset + 3] = alpha; } else { // No alpha channel, the image is opaque. out_row[byte_offset + 3] = 0xff; } } } void ConvolveVertically(const ConvolutionFilter1D::Fixed* filter_values, int filter_length, unsigned char* const* source_data_rows, int pixel_width, unsigned char* out_row, bool source_has_alpha) { if (source_has_alpha) { ConvolveVertically<true>(filter_values, filter_length, source_data_rows, pixel_width, out_row); } else { ConvolveVertically<false>(filter_values, filter_length, source_data_rows, pixel_width, out_row); } } } // namespace // ConvolutionFilter1D --------------------------------------------------------- ConvolutionFilter1D::ConvolutionFilter1D() : max_filter_(0) { } ConvolutionFilter1D::~ConvolutionFilter1D() = default; void ConvolutionFilter1D::AddFilter(int filter_offset, const float* filter_values, int filter_length) { SkASSERT(filter_length > 0); std::vector<Fixed> fixed_values; fixed_values.reserve(filter_length); for (int i = 0; i < filter_length; ++i) fixed_values.push_back(FloatToFixed(filter_values[i])); AddFilter(filter_offset, &fixed_values[0], filter_length); } void ConvolutionFilter1D::AddFilter(int filter_offset, const Fixed* filter_values, int filter_length) { // It is common for leading/trailing filter values to be zeros. In such // cases it is beneficial to only store the central factors. // For a scaling to 1/4th in each dimension using a Lanczos-2 filter on // a 1080p image this optimization gives a ~10% speed improvement. int filter_size = filter_length; int first_non_zero = 0; while (first_non_zero < filter_length && filter_values[first_non_zero] == 0) first_non_zero++; if (first_non_zero < filter_length) { // Here we have at least one non-zero factor. int last_non_zero = filter_length - 1; while (last_non_zero >= 0 && filter_values[last_non_zero] == 0) last_non_zero--; filter_offset += first_non_zero; filter_length = last_non_zero + 1 - first_non_zero; SkASSERT(filter_length > 0); for (int i = first_non_zero; i <= last_non_zero; i++) filter_values_.push_back(filter_values[i]); } else { // Here all the factors were zeroes. filter_length = 0; } FilterInstance instance; // We pushed filter_length elements onto filter_values_ instance.data_location = (static_cast<int>(filter_values_.size()) - filter_length); instance.offset = filter_offset; instance.trimmed_length = filter_length; instance.length = filter_size; filters_.push_back(instance); max_filter_ = std::max(max_filter_, filter_length); } const ConvolutionFilter1D::Fixed* ConvolutionFilter1D::GetSingleFilter( int* specified_filter_length, int* filter_offset, int* filter_length) const { const FilterInstance& filter = filters_[0]; *filter_offset = filter.offset; *filter_length = filter.trimmed_length; *specified_filter_length = filter.length; if (filter.trimmed_length == 0) return NULL; return &filter_values_[filter.data_location]; } typedef void (*ConvolveVertically_pointer)( const ConvolutionFilter1D::Fixed* filter_values, int filter_length, unsigned char* const* source_data_rows, int pixel_width, unsigned char* out_row, bool has_alpha); typedef void (*Convolve4RowsHorizontally_pointer)( const unsigned char* src_data[4], const ConvolutionFilter1D& filter, unsigned char* out_row[4]); typedef void (*ConvolveHorizontally_pointer)( const unsigned char* src_data, const ConvolutionFilter1D& filter, unsigned char* out_row, bool has_alpha); struct ConvolveProcs { // This is how many extra pixels may be read by the // conolve*horizontally functions. int extra_horizontal_reads; ConvolveVertically_pointer convolve_vertically; Convolve4RowsHorizontally_pointer convolve_4rows_horizontally; ConvolveHorizontally_pointer convolve_horizontally; }; void SetupSIMD(ConvolveProcs *procs) { #ifdef SIMD_SSE2 procs->extra_horizontal_reads = 3; procs->convolve_vertically = &ConvolveVertically_SSE2; procs->convolve_4rows_horizontally = &Convolve4RowsHorizontally_SSE2; procs->convolve_horizontally = &ConvolveHorizontally_SSE2; #elif defined SIMD_MIPS_DSPR2 procs->extra_horizontal_reads = 3; procs->convolve_vertically = &ConvolveVertically_mips_dspr2; procs->convolve_horizontally = &ConvolveHorizontally_mips_dspr2; #elif defined SIMD_NEON procs->extra_horizontal_reads = 3; procs->convolve_vertically = &ConvolveVertically_Neon; procs->convolve_4rows_horizontally = &Convolve4RowsHorizontally_Neon; procs->convolve_horizontally = &ConvolveHorizontally_Neon; #endif } void BGRAConvolve2D(const unsigned char* source_data, int source_byte_row_stride, bool source_has_alpha, const ConvolutionFilter1D& filter_x, const ConvolutionFilter1D& filter_y, int output_byte_row_stride, unsigned char* output, bool use_simd_if_possible) { ConvolveProcs simd; simd.extra_horizontal_reads = 0; simd.convolve_vertically = NULL; simd.convolve_4rows_horizontally = NULL; simd.convolve_horizontally = NULL; if (use_simd_if_possible) { SetupSIMD(&simd); } int max_y_filter_size = filter_y.max_filter(); // The next row in the input that we will generate a horizontally // convolved row for. If the filter doesn't start at the beginning of the // image (this is the case when we are only resizing a subset), then we // don't want to generate any output rows before that. Compute the starting // row for convolution as the first pixel for the first vertical filter. int filter_offset, filter_length; const ConvolutionFilter1D::Fixed* filter_values = filter_y.FilterForValue(0, &filter_offset, &filter_length); int next_x_row = filter_offset; // We loop over each row in the input doing a horizontal convolution. This // will result in a horizontally convolved image. We write the results into // a circular buffer of convolved rows and do vertical convolution as rows // are available. This prevents us from having to store the entire // intermediate image and helps cache coherency. // We will need four extra rows to allow horizontal convolution could be done // simultaneously. We also padding each row in row buffer to be aligned-up to // 16 bytes. // TODO(jiesun): We do not use aligned load from row buffer in vertical // convolution pass yet. Somehow Windows does not like it. int row_buffer_width = (filter_x.num_values() + 15) & ~0xF; int row_buffer_height = max_y_filter_size + (simd.convolve_4rows_horizontally ? 4 : 0); CircularRowBuffer row_buffer(row_buffer_width, row_buffer_height, filter_offset); // Loop over every possible output row, processing just enough horizontal // convolutions to run each subsequent vertical convolution. SkASSERT(output_byte_row_stride >= filter_x.num_values() * 4); int num_output_rows = filter_y.num_values(); // We need to check which is the last line to convolve before we advance 4 // lines in one iteration. int last_filter_offset, last_filter_length; // SSE2 can access up to 3 extra pixels past the end of the // buffer. At the bottom of the image, we have to be careful // not to access data past the end of the buffer. Normally // we fall back to the C++ implementation for the last row. // If the last row is less than 3 pixels wide, we may have to fall // back to the C++ version for more rows. Compute how many // rows we need to avoid the SSE implementation for here. filter_x.FilterForValue(filter_x.num_values() - 1, &last_filter_offset, &last_filter_length); int avoid_simd_rows = 1 + simd.extra_horizontal_reads / (last_filter_offset + last_filter_length); filter_y.FilterForValue(num_output_rows - 1, &last_filter_offset, &last_filter_length); for (int out_y = 0; out_y < num_output_rows; out_y++) { filter_values = filter_y.FilterForValue(out_y, &filter_offset, &filter_length); // Generate output rows until we have enough to run the current filter. while (next_x_row < filter_offset + filter_length) { if (simd.convolve_4rows_horizontally && next_x_row + 3 < last_filter_offset + last_filter_length - avoid_simd_rows) { const unsigned char* src[4]; unsigned char* out_row[4]; for (int i = 0; i < 4; ++i) { src[i] = &source_data[(next_x_row + i) * source_byte_row_stride]; out_row[i] = row_buffer.AdvanceRow(); } simd.convolve_4rows_horizontally(src, filter_x, out_row); next_x_row += 4; } else { // Check if we need to avoid SSE2 for this row. if (simd.convolve_horizontally && next_x_row < last_filter_offset + last_filter_length - avoid_simd_rows) { simd.convolve_horizontally( &source_data[next_x_row * source_byte_row_stride], filter_x, row_buffer.AdvanceRow(), source_has_alpha); } else { if (source_has_alpha) { ConvolveHorizontally<true>( &source_data[next_x_row * source_byte_row_stride], filter_x, row_buffer.AdvanceRow()); } else { ConvolveHorizontally<false>( &source_data[next_x_row * source_byte_row_stride], filter_x, row_buffer.AdvanceRow()); } } next_x_row++; } } // Compute where in the output image this row of final data will go. unsigned char* cur_output_row = &output[out_y * output_byte_row_stride]; // Get the list of rows that the circular buffer has, in order. int first_row_in_circular_buffer; unsigned char* const* rows_to_convolve = row_buffer.GetRowAddresses(&first_row_in_circular_buffer); // Now compute the start of the subset of those rows that the filter // needs. unsigned char* const* first_row_for_filter = &rows_to_convolve[filter_offset - first_row_in_circular_buffer]; if (simd.convolve_vertically) { simd.convolve_vertically(filter_values, filter_length, first_row_for_filter, filter_x.num_values(), cur_output_row, source_has_alpha); } else { ConvolveVertically(filter_values, filter_length, first_row_for_filter, filter_x.num_values(), cur_output_row, source_has_alpha); } } } void SingleChannelConvolveX1D(const unsigned char* source_data, int source_byte_row_stride, int input_channel_index, int input_channel_count, const ConvolutionFilter1D& filter, const SkISize& image_size, unsigned char* output, int output_byte_row_stride, int output_channel_index, int output_channel_count, bool absolute_values) { int filter_offset, filter_length, filter_size; // Very much unlike BGRAConvolve2D, here we expect to have the same filter // for all pixels. const ConvolutionFilter1D::Fixed* filter_values = filter.GetSingleFilter(&filter_size, &filter_offset, &filter_length); if (filter_values == NULL || image_size.width() < filter_size) { NOTREACHED(); return; } int centrepoint = filter_length / 2; if (filter_size - filter_offset != 2 * filter_offset) { // This means the original filter was not symmetrical AND // got clipped from one side more than from the other. centrepoint = filter_size / 2 - filter_offset; } const unsigned char* source_data_row = source_data; unsigned char* output_row = output; for (int r = 0; r < image_size.height(); ++r) { unsigned char* target_byte = output_row + output_channel_index; // Process the lead part, padding image to the left with the first pixel. int c = 0; for (; c < centrepoint; ++c, target_byte += output_channel_count) { int accval = 0; int i = 0; int pixel_byte_index = input_channel_index; for (; i < centrepoint - c; ++i) // Padding part. accval += filter_values[i] * source_data_row[pixel_byte_index]; for (; i < filter_length; ++i, pixel_byte_index += input_channel_count) accval += filter_values[i] * source_data_row[pixel_byte_index]; *target_byte = BringBackTo8(accval, absolute_values); } // Now for the main event. for (; c < image_size.width() - centrepoint; ++c, target_byte += output_channel_count) { int accval = 0; int pixel_byte_index = (c - centrepoint) * input_channel_count + input_channel_index; for (int i = 0; i < filter_length; ++i, pixel_byte_index += input_channel_count) { accval += filter_values[i] * source_data_row[pixel_byte_index]; } *target_byte = BringBackTo8(accval, absolute_values); } for (; c < image_size.width(); ++c, target_byte += output_channel_count) { int accval = 0; int overlap_taps = image_size.width() - c + centrepoint; int pixel_byte_index = (c - centrepoint) * input_channel_count + input_channel_index; int i = 0; for (; i < overlap_taps - 1; ++i, pixel_byte_index += input_channel_count) accval += filter_values[i] * source_data_row[pixel_byte_index]; for (; i < filter_length; ++i) accval += filter_values[i] * source_data_row[pixel_byte_index]; *target_byte = BringBackTo8(accval, absolute_values); } source_data_row += source_byte_row_stride; output_row += output_byte_row_stride; } } void SingleChannelConvolveY1D(const unsigned char* source_data, int source_byte_row_stride, int input_channel_index, int input_channel_count, const ConvolutionFilter1D& filter, const SkISize& image_size, unsigned char* output, int output_byte_row_stride, int output_channel_index, int output_channel_count, bool absolute_values) { int filter_offset, filter_length, filter_size; // Very much unlike BGRAConvolve2D, here we expect to have the same filter // for all pixels. const ConvolutionFilter1D::Fixed* filter_values = filter.GetSingleFilter(&filter_size, &filter_offset, &filter_length); if (filter_values == NULL || image_size.height() < filter_size) { NOTREACHED(); return; } int centrepoint = filter_length / 2; if (filter_size - filter_offset != 2 * filter_offset) { // This means the original filter was not symmetrical AND // got clipped from one side more than from the other. centrepoint = filter_size / 2 - filter_offset; } for (int c = 0; c < image_size.width(); ++c) { unsigned char* target_byte = output + c * output_channel_count + output_channel_index; int r = 0; for (; r < centrepoint; ++r, target_byte += output_byte_row_stride) { int accval = 0; int i = 0; int pixel_byte_index = c * input_channel_count + input_channel_index; for (; i < centrepoint - r; ++i) // Padding part. accval += filter_values[i] * source_data[pixel_byte_index]; for (; i < filter_length; ++i, pixel_byte_index += source_byte_row_stride) accval += filter_values[i] * source_data[pixel_byte_index]; *target_byte = BringBackTo8(accval, absolute_values); } for (; r < image_size.height() - centrepoint; ++r, target_byte += output_byte_row_stride) { int accval = 0; int pixel_byte_index = (r - centrepoint) * source_byte_row_stride + c * input_channel_count + input_channel_index; for (int i = 0; i < filter_length; ++i, pixel_byte_index += source_byte_row_stride) { accval += filter_values[i] * source_data[pixel_byte_index]; } *target_byte = BringBackTo8(accval, absolute_values); } for (; r < image_size.height(); ++r, target_byte += output_byte_row_stride) { int accval = 0; int overlap_taps = image_size.height() - r + centrepoint; int pixel_byte_index = (r - centrepoint) * source_byte_row_stride + c * input_channel_count + input_channel_index; int i = 0; for (; i < overlap_taps - 1; ++i, pixel_byte_index += source_byte_row_stride) { accval += filter_values[i] * source_data[pixel_byte_index]; } for (; i < filter_length; ++i) accval += filter_values[i] * source_data[pixel_byte_index]; *target_byte = BringBackTo8(accval, absolute_values); } } } void SetUpGaussianConvolutionKernel(ConvolutionFilter1D* filter, float kernel_sigma, bool derivative) { DCHECK(filter != NULL); DCHECK_GT(kernel_sigma, 0.0); const int tail_length = static_cast<int>(4.0f * kernel_sigma + 0.5f); const int kernel_size = tail_length * 2 + 1; const float sigmasq = kernel_sigma * kernel_sigma; std::vector<float> kernel_weights(kernel_size, 0.0); float kernel_sum = 1.0f; kernel_weights[tail_length] = 1.0f; for (int ii = 1; ii <= tail_length; ++ii) { float v = std::exp(-0.5f * ii * ii / sigmasq); kernel_weights[tail_length + ii] = v; kernel_weights[tail_length - ii] = v; kernel_sum += 2.0f * v; } for (int i = 0; i < kernel_size; ++i) kernel_weights[i] /= kernel_sum; if (derivative) { kernel_weights[tail_length] = 0.0; for (int ii = 1; ii <= tail_length; ++ii) { float v = sigmasq * kernel_weights[tail_length + ii] / ii; kernel_weights[tail_length + ii] = v; kernel_weights[tail_length - ii] = -v; } } filter->AddFilter(0, &kernel_weights[0], kernel_weights.size()); } } // namespace skia
null
null
null
null
67,467
7,337
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
7,337
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 NET_QUIC_CORE_FRAMES_QUIC_IETF_MAX_STREAM_ID_FRAME_H_ #define NET_QUIC_CORE_FRAMES_QUIC_IETF_MAX_STREAM_ID_FRAME_H_ #include <ostream> #include "net/quic/core/frames/quic_control_frame.h" namespace net { // IETF format max-stream id frame. // This frame is used by the sender to inform the peer of the largest // stream id that the peer may open and that the sender will accept. struct QUIC_EXPORT_PRIVATE QuicIetfMaxStreamIdFrame : public QuicControlFrame { QuicIetfMaxStreamIdFrame(); QuicIetfMaxStreamIdFrame(QuicControlFrameId control_frame_id, QuicStreamId max_stream_id); friend QUIC_EXPORT_PRIVATE std::ostream& operator<<( std::ostream& os, const QuicIetfMaxStreamIdFrame& frame); // The maximum stream id to support. QuicStreamId max_stream_id; }; } // namespace net #endif // NET_QUIC_CORE_FRAMES_QUIC_IETF_MAX_STREAM_ID_FRAME_H_
null
null
null
null
4,200
29,322
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
29,322
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* * Copyright (c) 2004-2015 Erik Doernenburg and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use these files 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. */ #import <OCMock/OCMock.h> @interface OCMExpectationRecorder : OCMStubRecorder - (id)never; @end
null
null
null
null
26,185
40,959
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
40,959
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. #ifndef CRASHPAD_SNAPSHOT_MINIDUMP_MODULE_SNAPSHOT_MINIDUMP_H_ #define CRASHPAD_SNAPSHOT_MINIDUMP_MODULE_SNAPSHOT_MINIDUMP_H_ #include <windows.h> #include <dbghelp.h> #include <stdint.h> #include <sys/types.h> #include <map> #include <string> #include <vector> #include "base/macros.h" #include "snapshot/annotation_snapshot.h" #include "snapshot/module_snapshot.h" #include "util/file/file_reader.h" #include "util/misc/initialization_state_dcheck.h" namespace crashpad { namespace internal { //! \brief A ModuleSnapshot based on a module in a minidump file. class ModuleSnapshotMinidump final : public ModuleSnapshot { public: ModuleSnapshotMinidump(); ~ModuleSnapshotMinidump() override; //! \brief Initializes the object. //! //! \param[in] file_reader A file reader corresponding to a minidump file. //! The file reader must support seeking. //! \param[in] minidump_module_rva The file offset in \a file_reader at which //! the module’s MINIDUMP_MODULE structure is located. //! \param[in] minidump_crashpad_module_info_location The location in \a //! file_reader at which the module’s corresponding //! MinidumpModuleCrashpadInfo structure is located. If no such //! corresponding structure is available for a module, this may be //! `nullptr`. //! //! \return `true` if the snapshot could be created, `false` otherwise with //! an appropriate message logged. bool Initialize(FileReaderInterface* file_reader, RVA minidump_module_rva, const MINIDUMP_LOCATION_DESCRIPTOR* minidump_crashpad_module_info_location); // ModuleSnapshot: std::string Name() const override; uint64_t Address() const override; uint64_t Size() const override; time_t Timestamp() const override; void FileVersion(uint16_t* version_0, uint16_t* version_1, uint16_t* version_2, uint16_t* version_3) const override; void SourceVersion(uint16_t* version_0, uint16_t* version_1, uint16_t* version_2, uint16_t* version_3) const override; ModuleType GetModuleType() const override; void UUIDAndAge(crashpad::UUID* uuid, uint32_t* age) const override; std::string DebugFileName() const override; std::vector<std::string> AnnotationsVector() const override; std::map<std::string, std::string> AnnotationsSimpleMap() const override; std::vector<AnnotationSnapshot> AnnotationObjects() const override; std::set<CheckedRange<uint64_t>> ExtraMemoryRanges() const override; std::vector<const UserMinidumpStream*> CustomMinidumpStreams() const override; private: // Initializes data carried in a MinidumpModuleCrashpadInfo structure on // behalf of Initialize(). bool InitializeModuleCrashpadInfo(FileReaderInterface* file_reader, const MINIDUMP_LOCATION_DESCRIPTOR* minidump_module_crashpad_info_location); MINIDUMP_MODULE minidump_module_; std::vector<std::string> annotations_vector_; std::map<std::string, std::string> annotations_simple_map_; std::vector<AnnotationSnapshot> annotation_objects_; InitializationStateDcheck initialized_; DISALLOW_COPY_AND_ASSIGN(ModuleSnapshotMinidump); }; } // namespace internal } // namespace crashpad #endif // CRASHPAD_SNAPSHOT_MINIDUMP_MODULE_SNAPSHOT_MINIDUMP_H_
null
null
null
null
37,822
60,092
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
60,092
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 CHROME_BROWSER_OFFLINE_PAGES_ANDROID_OFFLINE_PAGE_BRIDGE_H_ #define CHROME_BROWSER_OFFLINE_PAGES_ANDROID_OFFLINE_PAGE_BRIDGE_H_ #include <stdint.h> #include "base/android/jni_android.h" #include "base/android/jni_weak_ref.h" #include "base/android/scoped_java_ref.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/supports_user_data.h" #include "components/offline_pages/core/offline_page_item.h" #include "components/offline_pages/core/offline_page_model.h" namespace content { class BrowserContext; class WebContents; } namespace offline_pages { namespace android { /** * Bridge between C++ and Java for exposing native implementation of offline * pages model in managed code. */ class OfflinePageBridge : public OfflinePageModel::Observer, public base::SupportsUserData::Data { public: static base::android::ScopedJavaLocalRef<jobject> ConvertToJavaOfflinePage( JNIEnv* env, const OfflinePageItem& offline_page); static std::string GetEncodedOriginApp( const content::WebContents* web_contents); OfflinePageBridge(JNIEnv* env, content::BrowserContext* browser_context, OfflinePageModel* offline_page_model); ~OfflinePageBridge() override; // OfflinePageModel::Observer implementation. void OfflinePageModelLoaded(OfflinePageModel* model) override; void OfflinePageAdded(OfflinePageModel* model, const OfflinePageItem& added_page) override; void OfflinePageDeleted( const OfflinePageModel::DeletedPageInfo& page_info) override; void GetAllPages(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jobject>& j_result_obj, const base::android::JavaParamRef<jobject>& j_callback_obj); void GetPageByOfflineId( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, jlong offline_id, const base::android::JavaParamRef<jobject>& j_callback_obj); void DeletePagesByClientId( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jobjectArray>& j_namespaces_array, const base::android::JavaParamRef<jobjectArray>& j_ids_array, const base::android::JavaParamRef<jobject>& j_callback_obj); void DeletePagesByClientIdAndOrigin( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jobjectArray>& j_namespaces_array, const base::android::JavaParamRef<jobjectArray>& j_ids_array, const base::android::JavaParamRef<jstring>& j_origin, const base::android::JavaParamRef<jobject>& j_callback_obj); void DeletePagesByOfflineId( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jlongArray>& j_offline_ids_array, const base::android::JavaParamRef<jobject>& j_callback_obj); void GetPagesByClientId( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jobject>& j_result_obj, const base::android::JavaParamRef<jobjectArray>& j_namespaces_array, const base::android::JavaParamRef<jobjectArray>& j_ids_array, const base::android::JavaParamRef<jobject>& j_callback_obj); void GetPagesByRequestOrigin( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jobject>& j_result_obj, const base::android::JavaParamRef<jstring>& j_request_origin, const base::android::JavaParamRef<jobject>& j_callback_obj); void GetPagesByNamespace( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jobject>& j_result_obj, const base::android::JavaParamRef<jstring>& j_namespace, const base::android::JavaParamRef<jobject>& j_callback_obj); void SelectPageForOnlineUrl( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jstring>& j_online_url, int tab_id, const base::android::JavaParamRef<jobject>& j_callback_obj); void SavePage(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jobject>& j_callback_obj, const base::android::JavaParamRef<jobject>& j_web_contents, const base::android::JavaParamRef<jstring>& j_namespace, const base::android::JavaParamRef<jstring>& j_client_id, const base::android::JavaParamRef<jstring>& j_origin); void SavePageLater(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jobject>& j_callback_obj, const base::android::JavaParamRef<jstring>& url, const base::android::JavaParamRef<jstring>& j_namespace, const base::android::JavaParamRef<jstring>& j_client_id, const base::android::JavaParamRef<jstring>& j_origin, jboolean user_requested); void PublishInternalPageByOfflineId( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const jlong j_offline_id, const base::android::JavaParamRef<jobject>& j_published_callback); void PublishInternalPageByGuid( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jstring>& j_guid, const base::android::JavaParamRef<jobject>& j_published_callback); jboolean IsShowingOfflinePreview( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jobject>& j_web_contents); jboolean IsShowingDownloadButtonInErrorPage( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jobject>& j_web_contents); base::android::ScopedJavaLocalRef<jstring> GetOfflinePageHeaderForReload( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jobject>& j_web_contents); void GetRequestsInQueue( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jobject>& j_callback_obj); void RemoveRequestsFromQueue( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jlongArray>& j_request_ids_array, const base::android::JavaParamRef<jobject>& j_callback_obj); void RegisterRecentTab(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, int tab_id); void WillCloseTab(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jobject>& j_web_contents); void UnregisterRecentTab(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, int tab_id); void ScheduleDownload( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jobject>& j_web_contents, const base::android::JavaParamRef<jstring>& j_namespace, const base::android::JavaParamRef<jstring>& j_url, int ui_action, const base::android::JavaParamRef<jstring>& j_origin); base::android::ScopedJavaGlobalRef<jobject> java_ref() { return java_ref_; } jboolean IsOfflinePage( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jobject>& j_web_contents); jboolean IsInPrivateDirectory( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jstring>& j_file_path); base::android::ScopedJavaLocalRef<jobject> GetOfflinePage( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jobject>& j_web_contents); void CheckForNewOfflineContent( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const jlong j_timestamp_millis, const base::android::JavaParamRef<jobject>& j_callback_obj); void GetLaunchUrlByOfflineId( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, jlong j_offline_id, const base::android::JavaParamRef<jobject>& j_callback_obj); void GetLoadUrlParamsForOpeningMhtmlFileOrContent( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jstring>& j_url, const base::android::JavaParamRef<jobject>& j_callback_obj); jboolean IsShowingTrustedOfflinePage( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jobject>& j_web_contents); void AcquireFileAccessPermission( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jobject>& j_web_contents, const base::android::JavaParamRef<jobject>& j_callback_obj); private: void GetPageByOfflineIdDone( const base::android::ScopedJavaGlobalRef<jobject>& j_callback_obj, const OfflinePageItem* offline_page); void GetSizeAndComputeDigestDone( const base::android::ScopedJavaGlobalRef<jobject>& j_callback_obj, const GURL& intent_url, std::pair<int64_t, std::string> size_and_digest); void GetPageBySizeAndDigestDone( const base::android::ScopedJavaGlobalRef<jobject>& j_callback_obj, const GURL& intent_url, const OfflinePageItem* offline_page); void NotifyIfDoneLoading() const; base::android::ScopedJavaLocalRef<jobject> CreateClientId( JNIEnv* env, const ClientId& clientId) const; void PublishInternalArchive( const base::android::ScopedJavaGlobalRef<jobject>& j_callback_obj, const OfflinePageItem* offline_page); base::android::ScopedJavaGlobalRef<jobject> java_ref_; // Not owned. content::BrowserContext* browser_context_; // Not owned. OfflinePageModel* offline_page_model_; base::WeakPtrFactory<OfflinePageBridge> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(OfflinePageBridge); }; } // namespace android } // namespace offline_pages #endif // CHROME_BROWSER_OFFLINE_PAGES_ANDROID_OFFLINE_PAGE_BRIDGE_H_
null
null
null
null
56,955
21,567
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
21,567
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_RENDERER_MEDIA_STREAM_MEDIA_STREAM_VIDEO_SOURCE_H_ #define CONTENT_RENDERER_MEDIA_STREAM_MEDIA_STREAM_VIDEO_SOURCE_H_ #include <memory> #include <vector> #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/message_loop/message_loop.h" #include "base/optional.h" #include "base/sequence_checker.h" #include "content/common/content_export.h" #include "content/common/media/video_capture.h" #include "content/renderer/media/stream/media_stream_source.h" #include "content/renderer/media/stream/secure_display_link_tracker.h" #include "media/base/video_frame.h" #include "media/capture/video_capture_types.h" #include "third_party/blink/public/platform/web_media_constraints.h" #include "third_party/blink/public/platform/web_media_stream_source.h" #include "third_party/blink/public/platform/web_media_stream_track.h" namespace content { class MediaStreamVideoTrack; class VideoTrackAdapter; struct VideoTrackAdapterSettings; // MediaStreamVideoSource is an interface used for sending video frames to a // MediaStreamVideoTrack. // http://dev.w3.org/2011/webrtc/editor/getusermedia.html // The purpose of this base class is to be able to implement different // MediaStreaVideoSources such as local video capture, video sources received // on a PeerConnection or a source created in NaCl. // All methods calls will be done from the main render thread. class CONTENT_EXPORT MediaStreamVideoSource : public MediaStreamSource { public: enum { // Default resolution. If no constraints are specified and the delegate // support it, this is the resolution that will be used. kDefaultWidth = 640, kDefaultHeight = 480, kDefaultFrameRate = 30, kUnknownFrameRate = 0, }; enum class RestartResult { IS_RUNNING, IS_STOPPED, INVALID_STATE }; // RestartCallback is used for both the StopForRestart and Restart operations. using RestartCallback = base::OnceCallback<void(RestartResult)>; MediaStreamVideoSource(); ~MediaStreamVideoSource() override; // Returns the MediaStreamVideoSource object owned by |source|. static MediaStreamVideoSource* GetVideoSource( const blink::WebMediaStreamSource& source); // Puts |track| in the registered tracks list. void AddTrack(MediaStreamVideoTrack* track, const VideoTrackAdapterSettings& track_adapter_settings, const VideoCaptureDeliverFrameCB& frame_callback, const ConstraintsCallback& callback); void RemoveTrack(MediaStreamVideoTrack* track, base::OnceClosure callback); // Reconfigures this MediaStreamVideoSource to use |adapter_settings| on // |track|, as long as |track| is connected to this source. // Do not invoke if |track| is connected to a different source, as the // internal state of |track| might become inconsistent with that of its // source. void ReconfigureTrack(MediaStreamVideoTrack* track, const VideoTrackAdapterSettings& adapter_settings); // Tries to temporarily stop this source so that it can be later restarted // with a different video format. Unlike MediaStreamVideoSource::StopSource(), // a temporary stop for restart does not change the ready state of the source. // Once the attempt to temporarily stop the source is completed, |callback| // is invoked with IS_STOPPED if the source actually stopped, or IS_RUNNING // if the source did not stop and is still running. // This method can only be called after a source has started. This can be // verified by checking that the IsRunning() method returns true. // Any attempt to invoke StopForRestart() before the source has started // results in no action and |callback| invoked with INVALID_STATE. void StopForRestart(RestartCallback callback); // Tries to restart a source that was previously temporarily stopped using the // supplied |new_format|. This method can be invoked only after a successful // call to StopForRestart(). // Once the attempt to restart the source is completed, |callback| is invoked // with IS_RUNNING if the source restarted and IS_STOPPED if the source // remained stopped. Note that it is not guaranteed that the source actually // restarts using |new_format| as its configuration. After a successful // restart, the actual configured format for the source (if available) can be // obtained with a call to GetCurrentFormat(). // Note also that, since frames are delivered on a different thread, it is // possible that frames using the old format are delivered for a while after // a successful restart. Code relying on Restart() cannot assume that new // frames are guaranteed to arrive in the new format until the first frame in // the new format is received. // This method can only be called after a successful stop for restart (i.e., // after the callback passed to StopForRestart() is invoked with a value of // IS_STOPPED). Any attempt to invoke Restart() when the source is not in this // state results in no action and |callback| invoked with INVALID_STATE. void Restart(const media::VideoCaptureFormat& new_format, RestartCallback callback); // Called by |track| to notify the source whether it has any paths to a // consuming endpoint. void UpdateHasConsumers(MediaStreamVideoTrack* track, bool has_consumers); void UpdateCapturingLinkSecure(MediaStreamVideoTrack* track, bool is_secure); // Request underlying source to capture a new frame. virtual void RequestRefreshFrame() {} // Enables or disables an heuristic to detect frames from rotated devices. void SetDeviceRotationDetection(bool enabled); // Returns the task runner where video frames will be delivered on. base::SingleThreadTaskRunner* io_task_runner() const; // Implementations must return the capture format if available. // Implementations supporting devices of type MEDIA_DEVICE_VIDEO_CAPTURE // must return a value. virtual base::Optional<media::VideoCaptureFormat> GetCurrentFormat() const; // Implementations must return the capture parameters if available. // Implementations supporting devices of type MEDIA_DEVICE_VIDEO_CAPTURE // must return a value. The format in the returned VideoCaptureParams must // coincide with the value returned by GetCurrentFormat(). virtual base::Optional<media::VideoCaptureParams> GetCurrentCaptureParams() const; bool IsRunning() const { return state_ == STARTED; } size_t NumTracks() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return tracks_.size(); } base::WeakPtr<MediaStreamVideoSource> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } protected: void DoStopSource() override; // Sets ready state and notifies the ready state to all registered tracks. virtual void SetReadyState(blink::WebMediaStreamSource::ReadyState state); // Sets muted state and notifies it to all registered tracks. virtual void SetMutedState(bool state); // An implementation must start capturing frames after this method is called. // When the source has started or failed to start OnStartDone must be called. // An implementation must call |frame_callback| on the IO thread with the // captured frames. virtual void StartSourceImpl( const VideoCaptureDeliverFrameCB& frame_callback) = 0; void OnStartDone(MediaStreamRequestResult result); // A subclass that supports restart must override this method such that it // immediately stop producing video frames after this method is called. // The stop is intended to be temporary and to be followed by a restart. Thus, // connected tracks should not be disconnected or notified about the source no // longer producing frames. Once the source is stopped, the implementation // must invoke OnStopForRestartDone() with true. If the source cannot stop, // OnStopForRestartDone() must invoked with false. // It can be assumed that this method is invoked only when the source is // running. // Note that if this method is overridden, RestartSourceImpl() must also be // overridden following the respective contract. Otherwise, behavior is // undefined. // The default implementation does not support restart and just calls // OnStopForRestartDone() with false. virtual void StopSourceForRestartImpl(); // This method should be called by implementations once an attempt to stop // for restart using StopSourceForRestartImpl() is completed. // |did_stop_for_restart| must true if the source is stopped and false if // the source is running. void OnStopForRestartDone(bool did_stop_for_restart); // A subclass that supports restart must override this method such that it // tries to start producing frames after this method is called. If successful, // the source should return to the same state as if it was started normally // and invoke OnRestartDone() with true. The implementation should preferably // restart to produce frames with the format specified in |new_format|. // However, if this is not possible, the implementation is allowed to restart // using a different format. In this case OnRestartDone() should be invoked // with true as well. If it is impossible to restart the source with any // format, the source should remain stopped and OnRestartDone() should be // invoked with false. // This method can only be invoked when the source is temporarily stopped // after a successful OnStopForRestartDone(). Otherwise behavior is undefined. // Note that if this method is overridden, StopSourceForRestartImpl() must // also be overridden following the respective contract. Otherwise, behavior // is undefined. virtual void RestartSourceImpl(const media::VideoCaptureFormat& new_format); // This method should be called by implementations once an attempt to restart // the source completes. |did_restart| must be true if the source is running // and false if the source is stopped. void OnRestartDone(bool did_restart); // An implementation must immediately stop producing video frames after this // method has been called. After this method has been called, // MediaStreamVideoSource may be deleted. virtual void StopSourceImpl() = 0; // Optionally overridden by subclasses to act on whether there are any // consumers present. When none are present, the source can stop delivering // frames, giving it the option of running in an "idle" state to minimize // resource usage. virtual void OnHasConsumers(bool has_consumers) {} // Optionally overridden by subclasses to act on whether the capturing link // has become secure or insecure. virtual void OnCapturingLinkSecured(bool is_secure) {} enum State { NEW, STARTING, STOPPING_FOR_RESTART, STOPPED_FOR_RESTART, RESTARTING, STARTED, ENDED }; State state() const { return state_; } SEQUENCE_CHECKER(sequence_checker_); private: // Trigger all cached callbacks from AddTrack. AddTrack is successful // if the capture delegate has started and the constraints provided in // AddTrack match the format that was used to start the device. // Note that it must be ok to delete the MediaStreamVideoSource object // in the context of the callback. If gUM fails, the implementation will // simply drop the references to the blink source and track which will lead // to this object being deleted. void FinalizeAddPendingTracks(); // Actually adds |track| to this source, provided the source has started. void FinalizeAddTrack(MediaStreamVideoTrack* track, const VideoCaptureDeliverFrameCB& frame_callback, const VideoTrackAdapterSettings& adapter_settings); void StartFrameMonitoring(); void UpdateTrackSettings(MediaStreamVideoTrack* track, const VideoTrackAdapterSettings& adapter_settings); void DidRemoveLastTrack(base::OnceClosure callback, RestartResult result); State state_; struct PendingTrackInfo { PendingTrackInfo( MediaStreamVideoTrack* track, const VideoCaptureDeliverFrameCB& frame_callback, std::unique_ptr<VideoTrackAdapterSettings> adapter_settings, const ConstraintsCallback& callback); PendingTrackInfo(PendingTrackInfo&& other); PendingTrackInfo& operator=(PendingTrackInfo&& other); ~PendingTrackInfo(); MediaStreamVideoTrack* track; VideoCaptureDeliverFrameCB frame_callback; // TODO(guidou): Make |adapter_settings| a regular field instead of a // unique_ptr. std::unique_ptr<VideoTrackAdapterSettings> adapter_settings; ConstraintsCallback callback; }; std::vector<PendingTrackInfo> pending_tracks_; // |restart_callback_| is used for notifying both StopForRestart and Restart, // since it is impossible to have a situation where there can be callbacks // for both at the same time. RestartCallback restart_callback_; // |track_adapter_| delivers video frames to the tracks on the IO-thread. const scoped_refptr<VideoTrackAdapter> track_adapter_; // Tracks that currently are connected to this source. std::vector<MediaStreamVideoTrack*> tracks_; // Tracks that have no paths to a consuming endpoint, and so do not need // frames delivered from the source. This is a subset of |tracks_|. std::vector<MediaStreamVideoTrack*> suspended_tracks_; // This is used for tracking if all connected video sinks are secure. SecureDisplayLinkTracker<MediaStreamVideoTrack> secure_tracker_; // This flag enables a heuristic to detect device rotation based on frame // size. bool enable_device_rotation_detection_ = false; // NOTE: Weak pointers must be invalidated before all other member variables. base::WeakPtrFactory<MediaStreamVideoSource> weak_factory_; DISALLOW_COPY_AND_ASSIGN(MediaStreamVideoSource); }; } // namespace content #endif // CONTENT_RENDERER_MEDIA_STREAM_MEDIA_STREAM_VIDEO_SOURCE_H_
null
null
null
null
18,430
17,016
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
17,016
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 COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_SOFTWARE_OUTPUT_DEVICE_X11_H_ #define COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_SOFTWARE_OUTPUT_DEVICE_X11_H_ #include "base/macros.h" #include "base/threading/thread_checker.h" #include "components/viz/service/display/software_output_device.h" #include "components/viz/service/viz_service_export.h" #include "ui/gfx/native_widget_types.h" #include "ui/gfx/x/x11.h" #include "ui/gfx/x/x11_types.h" namespace viz { class VIZ_SERVICE_EXPORT SoftwareOutputDeviceX11 : public SoftwareOutputDevice { public: explicit SoftwareOutputDeviceX11(gfx::AcceleratedWidget widget); ~SoftwareOutputDeviceX11() override; void EndPaint() override; private: gfx::AcceleratedWidget widget_; XDisplay* display_; GC gc_; XWindowAttributes attributes_; THREAD_CHECKER(thread_checker_); DISALLOW_COPY_AND_ASSIGN(SoftwareOutputDeviceX11); }; } // namespace viz #endif // COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_SOFTWARE_OUTPUT_DEVICE_X11_H_
null
null
null
null
13,879
25,933
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
190,928
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * VCE_3_0 Register documentation * * Copyright (C) 2014 Advanced Micro Devices, Inc. * * 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 COPYRIGHT HOLDER(S) 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 VCE_3_0_SH_MASK_H #define VCE_3_0_SH_MASK_H #define VCE_STATUS__JOB_BUSY_MASK 0x1 #define VCE_STATUS__JOB_BUSY__SHIFT 0x0 #define VCE_STATUS__VCPU_REPORT_MASK 0xfe #define VCE_STATUS__VCPU_REPORT__SHIFT 0x1 #define VCE_STATUS__UENC_BUSY_MASK 0x100 #define VCE_STATUS__UENC_BUSY__SHIFT 0x8 #define VCE_STATUS__VCE_CONFIGURATION_MASK 0xc00000 #define VCE_STATUS__VCE_CONFIGURATION__SHIFT 0x16 #define VCE_STATUS__VCE_INSTANCE_ID_MASK 0x3000000 #define VCE_STATUS__VCE_INSTANCE_ID__SHIFT 0x18 #define VCE_VCPU_CNTL__CLK_EN_MASK 0x1 #define VCE_VCPU_CNTL__CLK_EN__SHIFT 0x0 #define VCE_VCPU_CNTL__RBBM_SOFT_RESET_MASK 0x40000 #define VCE_VCPU_CNTL__RBBM_SOFT_RESET__SHIFT 0x12 #define VCE_VCPU_CACHE_OFFSET0__OFFSET_MASK 0xfffffff #define VCE_VCPU_CACHE_OFFSET0__OFFSET__SHIFT 0x0 #define VCE_VCPU_CACHE_SIZE0__SIZE_MASK 0xffffff #define VCE_VCPU_CACHE_SIZE0__SIZE__SHIFT 0x0 #define VCE_VCPU_CACHE_OFFSET1__OFFSET_MASK 0xfffffff #define VCE_VCPU_CACHE_OFFSET1__OFFSET__SHIFT 0x0 #define VCE_VCPU_CACHE_SIZE1__SIZE_MASK 0xffffff #define VCE_VCPU_CACHE_SIZE1__SIZE__SHIFT 0x0 #define VCE_VCPU_CACHE_OFFSET2__OFFSET_MASK 0xfffffff #define VCE_VCPU_CACHE_OFFSET2__OFFSET__SHIFT 0x0 #define VCE_VCPU_CACHE_SIZE2__SIZE_MASK 0xffffff #define VCE_VCPU_CACHE_SIZE2__SIZE__SHIFT 0x0 #define VCE_SOFT_RESET__ECPU_SOFT_RESET_MASK 0x1 #define VCE_SOFT_RESET__ECPU_SOFT_RESET__SHIFT 0x0 #define VCE_RB_BASE_LO2__RB_BASE_LO_MASK 0xffffffc0 #define VCE_RB_BASE_LO2__RB_BASE_LO__SHIFT 0x6 #define VCE_RB_BASE_HI2__RB_BASE_HI_MASK 0xffffffff #define VCE_RB_BASE_HI2__RB_BASE_HI__SHIFT 0x0 #define VCE_RB_SIZE2__RB_SIZE_MASK 0x7ffff0 #define VCE_RB_SIZE2__RB_SIZE__SHIFT 0x4 #define VCE_RB_RPTR2__RB_RPTR_MASK 0x7ffff0 #define VCE_RB_RPTR2__RB_RPTR__SHIFT 0x4 #define VCE_RB_WPTR2__RB_WPTR_MASK 0x7ffff0 #define VCE_RB_WPTR2__RB_WPTR__SHIFT 0x4 #define VCE_RB_BASE_LO__RB_BASE_LO_MASK 0xffffffc0 #define VCE_RB_BASE_LO__RB_BASE_LO__SHIFT 0x6 #define VCE_RB_BASE_HI__RB_BASE_HI_MASK 0xffffffff #define VCE_RB_BASE_HI__RB_BASE_HI__SHIFT 0x0 #define VCE_RB_SIZE__RB_SIZE_MASK 0x7ffff0 #define VCE_RB_SIZE__RB_SIZE__SHIFT 0x4 #define VCE_RB_RPTR__RB_RPTR_MASK 0x7ffff0 #define VCE_RB_RPTR__RB_RPTR__SHIFT 0x4 #define VCE_RB_WPTR__RB_WPTR_MASK 0x7ffff0 #define VCE_RB_WPTR__RB_WPTR__SHIFT 0x4 #define VCE_RB_ARB_CTRL__VCE_CGTT_OVERRIDE_MASK 0x10000 #define VCE_RB_ARB_CTRL__VCE_CGTT_OVERRIDE__SHIFT 0x10 #define VCE_RB_BASE_LO3__RB_BASE_LO_MASK 0xffffffc0 #define VCE_RB_BASE_LO3__RB_BASE_LO__SHIFT 0x6 #define VCE_RB_BASE_HI3__RB_BASE_HI_MASK 0xffffffff #define VCE_RB_BASE_HI3__RB_BASE_HI__SHIFT 0x0 #define VCE_RB_SIZE3__RB_SIZE_MASK 0x7ffff0 #define VCE_RB_SIZE3__RB_SIZE__SHIFT 0x4 #define VCE_RB_RPTR3__RB_RPTR_MASK 0x7ffff0 #define VCE_RB_RPTR3__RB_RPTR__SHIFT 0x4 #define VCE_RB_WPTR3__RB_WPTR_MASK 0x7ffff0 #define VCE_RB_WPTR3__RB_WPTR__SHIFT 0x4 #define VCE_UENC_DMA_DCLK_CTRL__WRDMCLK_FORCEON_MASK 0x1 #define VCE_UENC_DMA_DCLK_CTRL__WRDMCLK_FORCEON__SHIFT 0x0 #define VCE_UENC_DMA_DCLK_CTRL__RDDMCLK_FORCEON_MASK 0x2 #define VCE_UENC_DMA_DCLK_CTRL__RDDMCLK_FORCEON__SHIFT 0x1 #define VCE_UENC_DMA_DCLK_CTRL__REGCLK_FORCEON_MASK 0x4 #define VCE_UENC_DMA_DCLK_CTRL__REGCLK_FORCEON__SHIFT 0x2 #define VCE_SYS_INT_EN__VCE_SYS_INT_TRAP_INTERRUPT_EN_MASK 0x8 #define VCE_SYS_INT_EN__VCE_SYS_INT_TRAP_INTERRUPT_EN__SHIFT 0x3 #define VCE_SYS_INT_STATUS__VCE_SYS_INT_TRAP_INTERRUPT_INT_MASK 0x8 #define VCE_SYS_INT_STATUS__VCE_SYS_INT_TRAP_INTERRUPT_INT__SHIFT 0x3 #define VCE_SYS_INT_ACK__VCE_SYS_INT_TRAP_INTERRUPT_ACK_MASK 0x8 #define VCE_SYS_INT_ACK__VCE_SYS_INT_TRAP_INTERRUPT_ACK__SHIFT 0x3 #define VCE_LMI_VCPU_CACHE_40BIT_BAR__BAR_MASK 0xffffffff #define VCE_LMI_VCPU_CACHE_40BIT_BAR__BAR__SHIFT 0x0 #define VCE_LMI_CTRL2__STALL_ARB_UMC_MASK 0x100 #define VCE_LMI_CTRL2__STALL_ARB_UMC__SHIFT 0x8 #define VCE_LMI_SWAP_CNTL3__RD_MC_CID_SWAP_MASK 0x3 #define VCE_LMI_SWAP_CNTL3__RD_MC_CID_SWAP__SHIFT 0x0 #define VCE_LMI_CTRL__VCPU_DATA_COHERENCY_EN_MASK 0x200000 #define VCE_LMI_CTRL__VCPU_DATA_COHERENCY_EN__SHIFT 0x15 #define VCE_LMI_SWAP_CNTL__VCPU_W_MC_SWAP_MASK 0x3 #define VCE_LMI_SWAP_CNTL__VCPU_W_MC_SWAP__SHIFT 0x0 #define VCE_LMI_SWAP_CNTL__WR_MC_CID_SWAP_MASK 0x3ffc #define VCE_LMI_SWAP_CNTL__WR_MC_CID_SWAP__SHIFT 0x2 #define VCE_LMI_SWAP_CNTL1__VCPU_R_MC_SWAP_MASK 0x3 #define VCE_LMI_SWAP_CNTL1__VCPU_R_MC_SWAP__SHIFT 0x0 #define VCE_LMI_SWAP_CNTL1__RD_MC_CID_SWAP_MASK 0x3ffc #define VCE_LMI_SWAP_CNTL1__RD_MC_CID_SWAP__SHIFT 0x2 #define VCE_LMI_SWAP_CNTL2__WR_MC_CID_SWAP_MASK 0xff #define VCE_LMI_SWAP_CNTL2__WR_MC_CID_SWAP__SHIFT 0x0 #define VCE_LMI_CACHE_CTRL__VCPU_EN_MASK 0x1 #define VCE_LMI_CACHE_CTRL__VCPU_EN__SHIFT 0x0 #endif /* VCE_3_0_SH_MASK_H */
null
null
null
null
99,275
30,388
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
195,383
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
#include <linux/pm_qos.h> static inline void device_pm_init_common(struct device *dev) { if (!dev->power.early_init) { spin_lock_init(&dev->power.lock); dev->power.qos = NULL; dev->power.early_init = true; } } #ifdef CONFIG_PM static inline void pm_runtime_early_init(struct device *dev) { dev->power.disable_depth = 1; device_pm_init_common(dev); } extern void pm_runtime_init(struct device *dev); extern void pm_runtime_reinit(struct device *dev); extern void pm_runtime_remove(struct device *dev); #define WAKE_IRQ_DEDICATED_ALLOCATED BIT(0) #define WAKE_IRQ_DEDICATED_MANAGED BIT(1) #define WAKE_IRQ_DEDICATED_MASK (WAKE_IRQ_DEDICATED_ALLOCATED | \ WAKE_IRQ_DEDICATED_MANAGED) struct wake_irq { struct device *dev; unsigned int status; int irq; }; extern void dev_pm_arm_wake_irq(struct wake_irq *wirq); extern void dev_pm_disarm_wake_irq(struct wake_irq *wirq); extern void dev_pm_enable_wake_irq_check(struct device *dev, bool can_change_status); extern void dev_pm_disable_wake_irq_check(struct device *dev); #ifdef CONFIG_PM_SLEEP extern int device_wakeup_attach_irq(struct device *dev, struct wake_irq *wakeirq); extern void device_wakeup_detach_irq(struct device *dev); extern void device_wakeup_arm_wake_irqs(void); extern void device_wakeup_disarm_wake_irqs(void); #else static inline int device_wakeup_attach_irq(struct device *dev, struct wake_irq *wakeirq) { return 0; } static inline void device_wakeup_detach_irq(struct device *dev) { } static inline void device_wakeup_arm_wake_irqs(void) { } static inline void device_wakeup_disarm_wake_irqs(void) { } #endif /* CONFIG_PM_SLEEP */ /* * sysfs.c */ extern int dpm_sysfs_add(struct device *dev); extern void dpm_sysfs_remove(struct device *dev); extern void rpm_sysfs_remove(struct device *dev); extern int wakeup_sysfs_add(struct device *dev); extern void wakeup_sysfs_remove(struct device *dev); extern int pm_qos_sysfs_add_resume_latency(struct device *dev); extern void pm_qos_sysfs_remove_resume_latency(struct device *dev); extern int pm_qos_sysfs_add_flags(struct device *dev); extern void pm_qos_sysfs_remove_flags(struct device *dev); extern int pm_qos_sysfs_add_latency_tolerance(struct device *dev); extern void pm_qos_sysfs_remove_latency_tolerance(struct device *dev); #else /* CONFIG_PM */ static inline void pm_runtime_early_init(struct device *dev) { device_pm_init_common(dev); } static inline void pm_runtime_init(struct device *dev) {} static inline void pm_runtime_reinit(struct device *dev) {} static inline void pm_runtime_remove(struct device *dev) {} static inline int dpm_sysfs_add(struct device *dev) { return 0; } static inline void dpm_sysfs_remove(struct device *dev) {} static inline void rpm_sysfs_remove(struct device *dev) {} static inline int wakeup_sysfs_add(struct device *dev) { return 0; } static inline void wakeup_sysfs_remove(struct device *dev) {} static inline int pm_qos_sysfs_add(struct device *dev) { return 0; } static inline void pm_qos_sysfs_remove(struct device *dev) {} static inline void dev_pm_arm_wake_irq(struct wake_irq *wirq) { } static inline void dev_pm_disarm_wake_irq(struct wake_irq *wirq) { } static inline void dev_pm_enable_wake_irq_check(struct device *dev, bool can_change_status) { } static inline void dev_pm_disable_wake_irq_check(struct device *dev) { } #endif #ifdef CONFIG_PM_SLEEP /* kernel/power/main.c */ extern int pm_async_enabled; /* drivers/base/power/main.c */ extern struct list_head dpm_list; /* The active device list */ static inline struct device *to_device(struct list_head *entry) { return container_of(entry, struct device, power.entry); } extern void device_pm_sleep_init(struct device *dev); extern void device_pm_add(struct device *); extern void device_pm_remove(struct device *); extern void device_pm_move_before(struct device *, struct device *); extern void device_pm_move_after(struct device *, struct device *); extern void device_pm_move_last(struct device *); extern void device_pm_check_callbacks(struct device *dev); static inline bool device_pm_initialized(struct device *dev) { return dev->power.in_dpm_list; } #else /* !CONFIG_PM_SLEEP */ static inline void device_pm_sleep_init(struct device *dev) {} static inline void device_pm_add(struct device *dev) {} static inline void device_pm_remove(struct device *dev) { pm_runtime_remove(dev); } static inline void device_pm_move_before(struct device *deva, struct device *devb) {} static inline void device_pm_move_after(struct device *deva, struct device *devb) {} static inline void device_pm_move_last(struct device *dev) {} static inline void device_pm_check_callbacks(struct device *dev) {} static inline bool device_pm_initialized(struct device *dev) { return device_is_registered(dev); } #endif /* !CONFIG_PM_SLEEP */ static inline void device_pm_init(struct device *dev) { device_pm_init_common(dev); device_pm_sleep_init(dev); pm_runtime_init(dev); }
null
null
null
null
103,730
41,078
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
41,078
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2017 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 "minidump/minidump_byte_array_writer.h" #include <memory> #include "base/format_macros.h" #include "base/strings/stringprintf.h" #include "gtest/gtest.h" #include "minidump/test/minidump_writable_test_util.h" #include "util/file/string_file.h" namespace crashpad { namespace test { namespace { TEST(MinidumpByteArrayWriter, Write) { const std::vector<uint8_t> kTests[] = { {'h', 'e', 'l', 'l', 'o'}, {0x42, 0x99, 0x00, 0xbe}, {0x00}, {}, }; for (size_t i = 0; i < arraysize(kTests); ++i) { SCOPED_TRACE(base::StringPrintf("index %" PRIuS, i)); StringFile string_file; crashpad::MinidumpByteArrayWriter writer; writer.set_data(kTests[i]); EXPECT_TRUE(writer.WriteEverything(&string_file)); ASSERT_EQ(string_file.string().size(), sizeof(MinidumpByteArray) + kTests[i].size()); auto byte_array = std::make_unique<MinidumpByteArray>(); EXPECT_EQ(string_file.Seek(0, SEEK_SET), 0); string_file.Read(byte_array.get(), sizeof(*byte_array)); EXPECT_EQ(byte_array->length, kTests[i].size()); std::vector<uint8_t> data(byte_array->length); string_file.Read(data.data(), byte_array->length); EXPECT_EQ(data, kTests[i]); } } TEST(MinidumpByteArrayWriter, SetData) { const std::vector<uint8_t> kTests[] = { {1, 2, 3, 4, 5}, {0x0}, {}, }; for (size_t i = 0; i < arraysize(kTests); ++i) { SCOPED_TRACE(base::StringPrintf("index %" PRIuS, i)); crashpad::MinidumpByteArrayWriter writer; writer.set_data(kTests[i].data(), kTests[i].size()); EXPECT_EQ(writer.data(), kTests[i]); } } } // namespace } // namespace test } // namespace crashpad
null
null
null
null
37,941
46,463
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
46,463
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 ASH_SYSTEM_UNIFIED_FEATURE_PODS_CONTAINER_VIEW_H_ #define ASH_SYSTEM_UNIFIED_FEATURE_PODS_CONTAINER_VIEW_H_ #include "ash/ash_export.h" #include "ui/views/view.h" namespace ash { // Container of feature pods buttons in the middle of UnifiedSystemTrayView. // The container has number of buttons placed in plane at regular distances such // as 3x2. FeaturePodButtons implements these individual buttons. // The container will also implement collapsed state where all the buttons are // horizontally placed. class ASH_EXPORT FeaturePodsContainerView : public views::View { public: FeaturePodsContainerView(); ~FeaturePodsContainerView() override; // Change the expanded state. 0.0 if collapsed, and 1.0 if expanded. // Otherwise, it shows intermediate state. If collapsed, all the buttons are // horizontally placed. void SetExpandedAmount(double expanded_amount); // Overridden views::View: gfx::Size CalculatePreferredSize() const override; void ChildVisibilityChanged(View* child) override; void Layout() override; private: void UpdateChildVisibility(); // Calculate the current position of the button from |visible_index| and // |expanded_amount_|. gfx::Point GetButtonPosition(int visible_index) const; // Update |collapsed_state_padding_|. void UpdateCollapsedSidePadding(); // The last |expanded_amount| passed to SetExpandedAmount(). double expanded_amount_ = 1.0; // Horizontal side padding in dip for collapsed state. int collapsed_side_padding_ = 0; bool changing_visibility_ = false; DISALLOW_COPY_AND_ASSIGN(FeaturePodsContainerView); }; } // namespace ash #endif // ASH_SYSTEM_UNIFIED_FEATURE_PODS_CONTAINER_VIEW_H_
null
null
null
null
43,326
40,333
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
40,333
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* * Summary: Windows configuration header * Description: Windows configuration header * * Copy: See Copyright for the status of this software. * * Author: Igor Zlatkovic */ #ifndef __LIBXSLT_WIN32_CONFIG__ #define __LIBXSLT_WIN32_CONFIG__ #define HAVE_CTYPE_H 1 #define HAVE_STDLIB_H 1 #define HAVE_STDARG_H 1 #define HAVE_MALLOC_H 1 #define HAVE_TIME_H 1 #define HAVE_LOCALTIME 1 #define HAVE_GMTIME 1 #define HAVE_TIME 1 #define HAVE_MATH_H 1 #define HAVE_FCNTL_H 1 #include <io.h> #define HAVE_ISINF #define HAVE_ISNAN #include <math.h> #if defined _MSC_VER || defined __MINGW32__ /* MS C-runtime has functions which can be used in order to determine if a given floating-point variable contains NaN, (+-)INF. These are preferred, because floating-point technology is considered propriatary by MS and we can assume that their functions know more about their oddities than we do. */ #include <float.h> /* Bjorn Reese figured a quite nice construct for isinf() using the _fpclass() function. */ #ifndef isinf #define isinf(d) ((_fpclass(d) == _FPCLASS_PINF) ? 1 \ : ((_fpclass(d) == _FPCLASS_NINF) ? -1 : 0)) #endif /* _isnan(x) returns nonzero if (x == NaN) and zero otherwise. */ #ifndef isnan #define isnan(d) (_isnan(d)) #endif #else /* _MSC_VER */ static int isinf (double d) { int expon = 0; double val = frexp (d, &expon); if (expon == 1025) { if (val == 0.5) { return 1; } else if (val == -0.5) { return -1; } else { return 0; } } else { return 0; } } static int isnan (double d) { int expon = 0; double val = frexp (d, &expon); if (expon == 1025) { if (val == 0.5) { return 0; } else if (val == -0.5) { return 0; } else { return 1; } } else { return 0; } } #endif /* _MSC_VER */ #include <direct.h> /* snprintf emulation taken from http://stackoverflow.com/a/8712996/1956010 */ #if defined(_MSC_VER) && _MSC_VER < 1900 #include <stdarg.h> #include <stdio.h> #define snprintf c99_snprintf #define vsnprintf c99_vsnprintf __inline int c99_vsnprintf(char *outBuf, size_t size, const char *format, va_list ap) { int count = -1; if (size != 0) count = _vsnprintf_s(outBuf, size, _TRUNCATE, format, ap); if (count == -1) count = _vscprintf(format, ap); return count; } __inline int c99_snprintf(char *outBuf, size_t size, const char *format, ...) { int count; va_list ap; va_start(ap, format); count = c99_vsnprintf(outBuf, size, format, ap); va_end(ap); return count; } #endif /* defined(_MSC_VER) && _MSC_VER < 1900 */ #define HAVE_SYS_STAT_H #define HAVE__STAT #define HAVE_STRING_H #include <libxml/xmlversion.h> #ifndef ATTRIBUTE_UNUSED #define ATTRIBUTE_UNUSED #endif #define _WINSOCKAPI_ #endif /* __LIBXSLT_WIN32_CONFIG__ */
null
null
null
null
37,196
18,399
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
18,399
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 "components/download/internal/background_service/blob_task_proxy.h" #include <utility> #include "base/guid.h" #include "base/task_runner_util.h" #include "base/threading/thread_task_runner_handle.h" #include "storage/browser/blob/blob_data_builder.h" #include "storage/browser/blob/blob_data_handle.h" #include "storage/browser/blob/blob_storage_context.h" namespace download { // static std::unique_ptr<BlobTaskProxy> BlobTaskProxy::Create( BlobContextGetter blob_context_getter, scoped_refptr<base::SingleThreadTaskRunner> io_task_runner) { return std::make_unique<BlobTaskProxy>(blob_context_getter, io_task_runner); } BlobTaskProxy::BlobTaskProxy( BlobContextGetter blob_context_getter, scoped_refptr<base::SingleThreadTaskRunner> io_task_runner) : main_task_runner_(base::ThreadTaskRunnerHandle::Get()), io_task_runner_(io_task_runner), weak_ptr_factory_(this) { // Unretained the raw pointer because owner on UI thread should destroy this // object on IO thread. io_task_runner_->PostTask( FROM_HERE, base::BindOnce(&BlobTaskProxy::InitializeOnIO, base::Unretained(this), blob_context_getter)); } BlobTaskProxy::~BlobTaskProxy() { io_task_runner_->BelongsToCurrentThread(); } void BlobTaskProxy::InitializeOnIO(BlobContextGetter blob_context_getter) { io_task_runner_->BelongsToCurrentThread(); blob_storage_context_ = blob_context_getter.Run(); } void BlobTaskProxy::SaveAsBlob(std::unique_ptr<std::string> data, BlobDataHandleCallback callback) { // Unretained the raw pointer because owner on UI thread should destroy this // object on IO thread. io_task_runner_->PostTask( FROM_HERE, base::BindOnce(&BlobTaskProxy::SaveAsBlobOnIO, base::Unretained(this), std::move(data), std::move(callback))); } void BlobTaskProxy::SaveAsBlobOnIO(std::unique_ptr<std::string> data, BlobDataHandleCallback callback) { io_task_runner_->BelongsToCurrentThread(); // Build blob data. This has to do a copy into blob's internal storage. std::string blob_uuid = base::GenerateGUID(); auto builder = std::make_unique<storage::BlobDataBuilder>(blob_uuid); builder->AppendData(*data.get()); blob_data_handle_ = blob_storage_context_->AddFinishedBlob(std::move(builder)); // Wait for blob data construction complete. auto cb = base::BindOnce(&BlobTaskProxy::BlobSavedOnIO, weak_ptr_factory_.GetWeakPtr(), std::move(callback)); blob_data_handle_->RunOnConstructionComplete(std::move(cb)); } void BlobTaskProxy::BlobSavedOnIO(BlobDataHandleCallback callback, storage::BlobStatus status) { io_task_runner_->BelongsToCurrentThread(); // Relay BlobDataHandle and |status| back to main thread. auto cb = base::BindOnce(std::move(callback), std::move(blob_data_handle_), status); main_task_runner_->PostTask(FROM_HERE, std::move(cb)); } } // namespace download
null
null
null
null
15,262
740
null
train_val
83ed75feba32e46f736fcce0d96a0445f29b96c2
162,584
krb5
0
https://github.com/krb5/krb5
2016-01-27 15:43:28-05:00
/* ccapi/server/ccs_pipe.h */ /* * Copyright 2006 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. */ #ifndef CCS_PIPE_H #define CCS_PIPE_H #include "ccs_types.h" cc_int32 ccs_pipe_valid (ccs_pipe_t in_pipe); cc_int32 ccs_pipe_compare (ccs_pipe_t in_pipe, ccs_pipe_t in_compare_to_pipe, cc_uint32 *out_equal); cc_int32 ccs_pipe_copy (ccs_pipe_t *out_pipe, ccs_pipe_t in_pipe); cc_int32 ccs_pipe_release (ccs_pipe_t io_pipe); #endif /* CCS_PIPE_H */
null
null
null
null
73,892
711
null
train_val
04b570817b2b38e35675b17328239746212f4c3f
153,768
FFmpeg
0
https://github.com/FFmpeg/FFmpeg
2018-06-01 01:23:12+05:30
/* * Copyright (c) 2016 Paul B Mahol * * 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 */ /** * @file * SpectrumSynth filter * @todo support float pixel format */ #include "libavcodec/avfft.h" #include "libavutil/avassert.h" #include "libavutil/channel_layout.h" #include "libavutil/ffmath.h" #include "libavutil/opt.h" #include "libavutil/parseutils.h" #include "avfilter.h" #include "formats.h" #include "audio.h" #include "video.h" #include "internal.h" #include "window_func.h" enum MagnitudeScale { LINEAR, LOG, NB_SCALES }; enum SlideMode { REPLACE, SCROLL, FULLFRAME, RSCROLL, NB_SLIDES }; enum Orientation { VERTICAL, HORIZONTAL, NB_ORIENTATIONS }; typedef struct SpectrumSynthContext { const AVClass *class; int sample_rate; int channels; int scale; int sliding; int win_func; float overlap; int orientation; AVFrame *magnitude, *phase; FFTContext *fft; ///< Fast Fourier Transform context int fft_bits; ///< number of bits (FFT window size = 1<<fft_bits) FFTComplex **fft_data; ///< bins holder for each (displayed) channels int win_size; int size; int nb_freq; int hop_size; int start, end; int xpos; int xend; int64_t pts; float factor; AVFrame *buffer; float *window_func_lut; ///< Window function LUT } SpectrumSynthContext; #define OFFSET(x) offsetof(SpectrumSynthContext, x) #define A AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_AUDIO_PARAM #define V AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM static const AVOption spectrumsynth_options[] = { { "sample_rate", "set sample rate", OFFSET(sample_rate), AV_OPT_TYPE_INT, {.i64 = 44100}, 15, INT_MAX, A }, { "channels", "set channels", OFFSET(channels), AV_OPT_TYPE_INT, {.i64 = 1}, 1, 8, A }, { "scale", "set input amplitude scale", OFFSET(scale), AV_OPT_TYPE_INT, {.i64 = LOG}, 0, NB_SCALES-1, V, "scale" }, { "lin", "linear", 0, AV_OPT_TYPE_CONST, {.i64=LINEAR}, 0, 0, V, "scale" }, { "log", "logarithmic", 0, AV_OPT_TYPE_CONST, {.i64=LOG}, 0, 0, V, "scale" }, { "slide", "set input sliding mode", OFFSET(sliding), AV_OPT_TYPE_INT, {.i64 = FULLFRAME}, 0, NB_SLIDES-1, V, "slide" }, { "replace", "consume old columns with new", 0, AV_OPT_TYPE_CONST, {.i64=REPLACE}, 0, 0, V, "slide" }, { "scroll", "consume only most right column", 0, AV_OPT_TYPE_CONST, {.i64=SCROLL}, 0, 0, V, "slide" }, { "fullframe", "consume full frames", 0, AV_OPT_TYPE_CONST, {.i64=FULLFRAME}, 0, 0, V, "slide" }, { "rscroll", "consume only most left column", 0, AV_OPT_TYPE_CONST, {.i64=RSCROLL}, 0, 0, V, "slide" }, { "win_func", "set window function", OFFSET(win_func), AV_OPT_TYPE_INT, {.i64 = 0}, 0, NB_WFUNC-1, A, "win_func" }, { "rect", "Rectangular", 0, AV_OPT_TYPE_CONST, {.i64=WFUNC_RECT}, 0, 0, A, "win_func" }, { "bartlett", "Bartlett", 0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BARTLETT}, 0, 0, A, "win_func" }, { "hann", "Hann", 0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING}, 0, 0, A, "win_func" }, { "hanning", "Hanning", 0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING}, 0, 0, A, "win_func" }, { "hamming", "Hamming", 0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HAMMING}, 0, 0, A, "win_func" }, { "sine", "Sine", 0, AV_OPT_TYPE_CONST, {.i64=WFUNC_SINE}, 0, 0, A, "win_func" }, { "overlap", "set window overlap", OFFSET(overlap), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0, 1, A }, { "orientation", "set orientation", OFFSET(orientation), AV_OPT_TYPE_INT, {.i64=VERTICAL}, 0, NB_ORIENTATIONS-1, V, "orientation" }, { "vertical", NULL, 0, AV_OPT_TYPE_CONST, {.i64=VERTICAL}, 0, 0, V, "orientation" }, { "horizontal", NULL, 0, AV_OPT_TYPE_CONST, {.i64=HORIZONTAL}, 0, 0, V, "orientation" }, { NULL } }; AVFILTER_DEFINE_CLASS(spectrumsynth); static int query_formats(AVFilterContext *ctx) { SpectrumSynthContext *s = ctx->priv; AVFilterFormats *formats = NULL; AVFilterChannelLayouts *layout = NULL; AVFilterLink *magnitude = ctx->inputs[0]; AVFilterLink *phase = ctx->inputs[1]; AVFilterLink *outlink = ctx->outputs[0]; static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE }; static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY16, AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUV444P16, AV_PIX_FMT_NONE }; int ret, sample_rates[] = { 48000, -1 }; formats = ff_make_format_list(sample_fmts); if ((ret = ff_formats_ref (formats, &outlink->in_formats )) < 0 || (ret = ff_add_channel_layout (&layout, FF_COUNT2LAYOUT(s->channels))) < 0 || (ret = ff_channel_layouts_ref (layout , &outlink->in_channel_layouts)) < 0) return ret; sample_rates[0] = s->sample_rate; formats = ff_make_format_list(sample_rates); if (!formats) return AVERROR(ENOMEM); if ((ret = ff_formats_ref(formats, &outlink->in_samplerates)) < 0) return ret; formats = ff_make_format_list(pix_fmts); if (!formats) return AVERROR(ENOMEM); if ((ret = ff_formats_ref(formats, &magnitude->out_formats)) < 0) return ret; formats = ff_make_format_list(pix_fmts); if (!formats) return AVERROR(ENOMEM); if ((ret = ff_formats_ref(formats, &phase->out_formats)) < 0) return ret; return 0; } static int config_output(AVFilterLink *outlink) { AVFilterContext *ctx = outlink->src; SpectrumSynthContext *s = ctx->priv; int width = ctx->inputs[0]->w; int height = ctx->inputs[0]->h; AVRational time_base = ctx->inputs[0]->time_base; AVRational frame_rate = ctx->inputs[0]->frame_rate; int i, ch, fft_bits; float factor, overlap; outlink->sample_rate = s->sample_rate; outlink->time_base = (AVRational){1, s->sample_rate}; if (width != ctx->inputs[1]->w || height != ctx->inputs[1]->h) { av_log(ctx, AV_LOG_ERROR, "Magnitude and Phase sizes differ (%dx%d vs %dx%d).\n", width, height, ctx->inputs[1]->w, ctx->inputs[1]->h); return AVERROR_INVALIDDATA; } else if (av_cmp_q(time_base, ctx->inputs[1]->time_base) != 0) { av_log(ctx, AV_LOG_ERROR, "Magnitude and Phase time bases differ (%d/%d vs %d/%d).\n", time_base.num, time_base.den, ctx->inputs[1]->time_base.num, ctx->inputs[1]->time_base.den); return AVERROR_INVALIDDATA; } else if (av_cmp_q(frame_rate, ctx->inputs[1]->frame_rate) != 0) { av_log(ctx, AV_LOG_ERROR, "Magnitude and Phase framerates differ (%d/%d vs %d/%d).\n", frame_rate.num, frame_rate.den, ctx->inputs[1]->frame_rate.num, ctx->inputs[1]->frame_rate.den); return AVERROR_INVALIDDATA; } s->size = s->orientation == VERTICAL ? height / s->channels : width / s->channels; s->xend = s->orientation == VERTICAL ? width : height; for (fft_bits = 1; 1 << fft_bits < 2 * s->size; fft_bits++); s->win_size = 1 << fft_bits; s->nb_freq = 1 << (fft_bits - 1); s->fft = av_fft_init(fft_bits, 1); if (!s->fft) { av_log(ctx, AV_LOG_ERROR, "Unable to create FFT context. " "The window size might be too high.\n"); return AVERROR(EINVAL); } s->fft_data = av_calloc(s->channels, sizeof(*s->fft_data)); if (!s->fft_data) return AVERROR(ENOMEM); for (ch = 0; ch < s->channels; ch++) { s->fft_data[ch] = av_calloc(s->win_size, sizeof(**s->fft_data)); if (!s->fft_data[ch]) return AVERROR(ENOMEM); } s->buffer = ff_get_audio_buffer(outlink, s->win_size * 2); if (!s->buffer) return AVERROR(ENOMEM); /* pre-calc windowing function */ s->window_func_lut = av_realloc_f(s->window_func_lut, s->win_size, sizeof(*s->window_func_lut)); if (!s->window_func_lut) return AVERROR(ENOMEM); generate_window_func(s->window_func_lut, s->win_size, s->win_func, &overlap); if (s->overlap == 1) s->overlap = overlap; s->hop_size = (1 - s->overlap) * s->win_size; for (factor = 0, i = 0; i < s->win_size; i++) { factor += s->window_func_lut[i] * s->window_func_lut[i]; } s->factor = (factor / s->win_size) / FFMAX(1 / (1 - s->overlap) - 1, 1); return 0; } static int request_frame(AVFilterLink *outlink) { AVFilterContext *ctx = outlink->src; SpectrumSynthContext *s = ctx->priv; int ret; if (!s->magnitude) { ret = ff_request_frame(ctx->inputs[0]); if (ret < 0) return ret; } if (!s->phase) { ret = ff_request_frame(ctx->inputs[1]); if (ret < 0) return ret; } return 0; } static void read16_fft_bin(SpectrumSynthContext *s, int x, int y, int f, int ch) { const int m_linesize = s->magnitude->linesize[0]; const int p_linesize = s->phase->linesize[0]; const uint16_t *m = (uint16_t *)(s->magnitude->data[0] + y * m_linesize); const uint16_t *p = (uint16_t *)(s->phase->data[0] + y * p_linesize); float magnitude, phase; switch (s->scale) { case LINEAR: magnitude = m[x] / (double)UINT16_MAX; break; case LOG: magnitude = ff_exp10(((m[x] / (double)UINT16_MAX) - 1.) * 6.); break; default: av_assert0(0); } phase = ((p[x] / (double)UINT16_MAX) * 2. - 1.) * M_PI; s->fft_data[ch][f].re = magnitude * cos(phase); s->fft_data[ch][f].im = magnitude * sin(phase); } static void read8_fft_bin(SpectrumSynthContext *s, int x, int y, int f, int ch) { const int m_linesize = s->magnitude->linesize[0]; const int p_linesize = s->phase->linesize[0]; const uint8_t *m = (uint8_t *)(s->magnitude->data[0] + y * m_linesize); const uint8_t *p = (uint8_t *)(s->phase->data[0] + y * p_linesize); float magnitude, phase; switch (s->scale) { case LINEAR: magnitude = m[x] / (double)UINT8_MAX; break; case LOG: magnitude = ff_exp10(((m[x] / (double)UINT8_MAX) - 1.) * 6.); break; default: av_assert0(0); } phase = ((p[x] / (double)UINT8_MAX) * 2. - 1.) * M_PI; s->fft_data[ch][f].re = magnitude * cos(phase); s->fft_data[ch][f].im = magnitude * sin(phase); } static void read_fft_data(AVFilterContext *ctx, int x, int h, int ch) { SpectrumSynthContext *s = ctx->priv; AVFilterLink *inlink = ctx->inputs[0]; int start = h * (s->channels - ch) - 1; int end = h * (s->channels - ch - 1); int y, f; switch (s->orientation) { case VERTICAL: switch (inlink->format) { case AV_PIX_FMT_YUV444P16: case AV_PIX_FMT_GRAY16: for (y = start, f = 0; y >= end; y--, f++) { read16_fft_bin(s, x, y, f, ch); } break; case AV_PIX_FMT_YUVJ444P: case AV_PIX_FMT_YUV444P: case AV_PIX_FMT_GRAY8: for (y = start, f = 0; y >= end; y--, f++) { read8_fft_bin(s, x, y, f, ch); } break; } break; case HORIZONTAL: switch (inlink->format) { case AV_PIX_FMT_YUV444P16: case AV_PIX_FMT_GRAY16: for (y = end, f = 0; y <= start; y++, f++) { read16_fft_bin(s, y, x, f, ch); } break; case AV_PIX_FMT_YUVJ444P: case AV_PIX_FMT_YUV444P: case AV_PIX_FMT_GRAY8: for (y = end, f = 0; y <= start; y++, f++) { read8_fft_bin(s, y, x, f, ch); } break; } break; } } static void synth_window(AVFilterContext *ctx, int x) { SpectrumSynthContext *s = ctx->priv; const int h = s->size; int nb = s->win_size; int y, f, ch; for (ch = 0; ch < s->channels; ch++) { read_fft_data(ctx, x, h, ch); for (y = h; y <= s->nb_freq; y++) { s->fft_data[ch][y].re = 0; s->fft_data[ch][y].im = 0; } for (y = s->nb_freq + 1, f = s->nb_freq - 1; y < nb; y++, f--) { s->fft_data[ch][y].re = s->fft_data[ch][f].re; s->fft_data[ch][y].im = -s->fft_data[ch][f].im; } av_fft_permute(s->fft, s->fft_data[ch]); av_fft_calc(s->fft, s->fft_data[ch]); } } static int try_push_frame(AVFilterContext *ctx, int x) { SpectrumSynthContext *s = ctx->priv; AVFilterLink *outlink = ctx->outputs[0]; const float factor = s->factor; int ch, n, i, ret; int start, end; AVFrame *out; synth_window(ctx, x); for (ch = 0; ch < s->channels; ch++) { float *buf = (float *)s->buffer->extended_data[ch]; int j, k; start = s->start; end = s->end; k = end; for (i = 0, j = start; j < k && i < s->win_size; i++, j++) { buf[j] += s->fft_data[ch][i].re; } for (; i < s->win_size; i++, j++) { buf[j] = s->fft_data[ch][i].re; } start += s->hop_size; end = j; if (start >= s->win_size) { start -= s->win_size; end -= s->win_size; if (ch == s->channels - 1) { float *dst; int c; out = ff_get_audio_buffer(outlink, s->win_size); if (!out) { av_frame_free(&s->magnitude); av_frame_free(&s->phase); return AVERROR(ENOMEM); } out->pts = s->pts; s->pts += s->win_size; for (c = 0; c < s->channels; c++) { dst = (float *)out->extended_data[c]; buf = (float *)s->buffer->extended_data[c]; for (n = 0; n < s->win_size; n++) { dst[n] = buf[n] * factor; } memmove(buf, buf + s->win_size, s->win_size * 4); } ret = ff_filter_frame(outlink, out); if (ret < 0) return ret; } } } s->start = start; s->end = end; return 0; } static int try_push_frames(AVFilterContext *ctx) { SpectrumSynthContext *s = ctx->priv; int ret, x; if (!(s->magnitude && s->phase)) return 0; switch (s->sliding) { case REPLACE: ret = try_push_frame(ctx, s->xpos); s->xpos++; if (s->xpos >= s->xend) s->xpos = 0; break; case SCROLL: s->xpos = s->xend - 1; ret = try_push_frame(ctx, s->xpos); break; case RSCROLL: s->xpos = 0; ret = try_push_frame(ctx, s->xpos); break; case FULLFRAME: for (x = 0; x < s->xend; x++) { ret = try_push_frame(ctx, x); if (ret < 0) break; } break; default: av_assert0(0); } av_frame_free(&s->magnitude); av_frame_free(&s->phase); return ret; } static int filter_frame_magnitude(AVFilterLink *inlink, AVFrame *magnitude) { AVFilterContext *ctx = inlink->dst; SpectrumSynthContext *s = ctx->priv; s->magnitude = magnitude; return try_push_frames(ctx); } static int filter_frame_phase(AVFilterLink *inlink, AVFrame *phase) { AVFilterContext *ctx = inlink->dst; SpectrumSynthContext *s = ctx->priv; s->phase = phase; return try_push_frames(ctx); } static av_cold void uninit(AVFilterContext *ctx) { SpectrumSynthContext *s = ctx->priv; int i; av_frame_free(&s->magnitude); av_frame_free(&s->phase); av_frame_free(&s->buffer); av_fft_end(s->fft); if (s->fft_data) { for (i = 0; i < s->channels; i++) av_freep(&s->fft_data[i]); } av_freep(&s->fft_data); av_freep(&s->window_func_lut); } static const AVFilterPad spectrumsynth_inputs[] = { { .name = "magnitude", .type = AVMEDIA_TYPE_VIDEO, .filter_frame = filter_frame_magnitude, .needs_fifo = 1, }, { .name = "phase", .type = AVMEDIA_TYPE_VIDEO, .filter_frame = filter_frame_phase, .needs_fifo = 1, }, { NULL } }; static const AVFilterPad spectrumsynth_outputs[] = { { .name = "default", .type = AVMEDIA_TYPE_AUDIO, .config_props = config_output, .request_frame = request_frame, }, { NULL } }; AVFilter ff_vaf_spectrumsynth = { .name = "spectrumsynth", .description = NULL_IF_CONFIG_SMALL("Convert input spectrum videos to audio output."), .uninit = uninit, .query_formats = query_formats, .priv_size = sizeof(SpectrumSynthContext), .inputs = spectrumsynth_inputs, .outputs = spectrumsynth_outputs, .priv_class = &spectrumsynth_class, };
null
null
null
null
69,823
2,574
null
train_val
1b0d3845b454eaaac0b2064c78926ca4d739a080
265,142
qemu
0
https://github.com/bonzini/qemu
2016-10-18 11:40:27+01:00
#include "qemu/osdep.h" #include "qemu-common.h" #include "qemu/main-loop.h" void qemu_set_fd_handler(int fd, IOHandler *fd_read, IOHandler *fd_write, void *opaque) { abort(); } void aio_set_fd_handler(AioContext *ctx, int fd, bool is_external, IOHandler *io_read, IOHandler *io_write, void *opaque) { abort(); }
null
null
null
null
123,266
31,760
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
196,755
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* $Id: avm_a1.c,v 2.15.2.4 2004/01/13 21:46:03 keil Exp $ * * low level stuff for AVM A1 (Fritz) isdn cards * * Author Karsten Keil * Copyright by Karsten Keil <keil@isdn4linux.de> * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * */ #include <linux/init.h> #include "hisax.h" #include "isac.h" #include "hscx.h" #include "isdnl1.h" static const char *avm_revision = "$Revision: 2.15.2.4 $"; #define AVM_A1_STAT_ISAC 0x01 #define AVM_A1_STAT_HSCX 0x02 #define AVM_A1_STAT_TIMER 0x04 #define byteout(addr, val) outb(val, addr) #define bytein(addr) inb(addr) static inline u_char readreg(unsigned int adr, u_char off) { return (bytein(adr + off)); } static inline void writereg(unsigned int adr, u_char off, u_char data) { byteout(adr + off, data); } static inline void read_fifo(unsigned int adr, u_char *data, int size) { insb(adr, data, size); } static void write_fifo(unsigned int adr, u_char *data, int size) { outsb(adr, data, size); } /* Interface functions */ static u_char ReadISAC(struct IsdnCardState *cs, u_char offset) { return (readreg(cs->hw.avm.isac, offset)); } static void WriteISAC(struct IsdnCardState *cs, u_char offset, u_char value) { writereg(cs->hw.avm.isac, offset, value); } static void ReadISACfifo(struct IsdnCardState *cs, u_char *data, int size) { read_fifo(cs->hw.avm.isacfifo, data, size); } static void WriteISACfifo(struct IsdnCardState *cs, u_char *data, int size) { write_fifo(cs->hw.avm.isacfifo, data, size); } static u_char ReadHSCX(struct IsdnCardState *cs, int hscx, u_char offset) { return (readreg(cs->hw.avm.hscx[hscx], offset)); } static void WriteHSCX(struct IsdnCardState *cs, int hscx, u_char offset, u_char value) { writereg(cs->hw.avm.hscx[hscx], offset, value); } /* * fast interrupt HSCX stuff goes here */ #define READHSCX(cs, nr, reg) readreg(cs->hw.avm.hscx[nr], reg) #define WRITEHSCX(cs, nr, reg, data) writereg(cs->hw.avm.hscx[nr], reg, data) #define READHSCXFIFO(cs, nr, ptr, cnt) read_fifo(cs->hw.avm.hscxfifo[nr], ptr, cnt) #define WRITEHSCXFIFO(cs, nr, ptr, cnt) write_fifo(cs->hw.avm.hscxfifo[nr], ptr, cnt) #include "hscx_irq.c" static irqreturn_t avm_a1_interrupt(int intno, void *dev_id) { struct IsdnCardState *cs = dev_id; u_char val, sval; u_long flags; spin_lock_irqsave(&cs->lock, flags); while (((sval = bytein(cs->hw.avm.cfg_reg)) & 0xf) != 0x7) { if (!(sval & AVM_A1_STAT_TIMER)) { byteout(cs->hw.avm.cfg_reg, 0x1E); sval = bytein(cs->hw.avm.cfg_reg); } else if (cs->debug & L1_DEB_INTSTAT) debugl1(cs, "avm IntStatus %x", sval); if (!(sval & AVM_A1_STAT_HSCX)) { val = readreg(cs->hw.avm.hscx[1], HSCX_ISTA); if (val) hscx_int_main(cs, val); } if (!(sval & AVM_A1_STAT_ISAC)) { val = readreg(cs->hw.avm.isac, ISAC_ISTA); if (val) isac_interrupt(cs, val); } } writereg(cs->hw.avm.hscx[0], HSCX_MASK, 0xFF); writereg(cs->hw.avm.hscx[1], HSCX_MASK, 0xFF); writereg(cs->hw.avm.isac, ISAC_MASK, 0xFF); writereg(cs->hw.avm.isac, ISAC_MASK, 0x0); writereg(cs->hw.avm.hscx[0], HSCX_MASK, 0x0); writereg(cs->hw.avm.hscx[1], HSCX_MASK, 0x0); spin_unlock_irqrestore(&cs->lock, flags); return IRQ_HANDLED; } static inline void release_ioregs(struct IsdnCardState *cs, int mask) { release_region(cs->hw.avm.cfg_reg, 8); if (mask & 1) release_region(cs->hw.avm.isac + 32, 32); if (mask & 2) release_region(cs->hw.avm.isacfifo, 1); if (mask & 4) release_region(cs->hw.avm.hscx[0] + 32, 32); if (mask & 8) release_region(cs->hw.avm.hscxfifo[0], 1); if (mask & 0x10) release_region(cs->hw.avm.hscx[1] + 32, 32); if (mask & 0x20) release_region(cs->hw.avm.hscxfifo[1], 1); } static int AVM_card_msg(struct IsdnCardState *cs, int mt, void *arg) { u_long flags; switch (mt) { case CARD_RESET: return (0); case CARD_RELEASE: release_ioregs(cs, 0x3f); return (0); case CARD_INIT: spin_lock_irqsave(&cs->lock, flags); inithscxisac(cs, 1); byteout(cs->hw.avm.cfg_reg, 0x16); byteout(cs->hw.avm.cfg_reg, 0x1E); inithscxisac(cs, 2); spin_unlock_irqrestore(&cs->lock, flags); return (0); case CARD_TEST: return (0); } return (0); } int setup_avm_a1(struct IsdnCard *card) { u_char val; struct IsdnCardState *cs = card->cs; char tmp[64]; strcpy(tmp, avm_revision); printk(KERN_INFO "HiSax: AVM driver Rev. %s\n", HiSax_getrev(tmp)); if (cs->typ != ISDN_CTYPE_A1) return (0); cs->hw.avm.cfg_reg = card->para[1] + 0x1800; cs->hw.avm.isac = card->para[1] + 0x1400 - 0x20; cs->hw.avm.hscx[0] = card->para[1] + 0x400 - 0x20; cs->hw.avm.hscx[1] = card->para[1] + 0xc00 - 0x20; cs->hw.avm.isacfifo = card->para[1] + 0x1000; cs->hw.avm.hscxfifo[0] = card->para[1]; cs->hw.avm.hscxfifo[1] = card->para[1] + 0x800; cs->irq = card->para[0]; if (!request_region(cs->hw.avm.cfg_reg, 8, "avm cfg")) { printk(KERN_WARNING "HiSax: AVM A1 config port %x-%x already in use\n", cs->hw.avm.cfg_reg, cs->hw.avm.cfg_reg + 8); return (0); } if (!request_region(cs->hw.avm.isac + 32, 32, "HiSax isac")) { printk(KERN_WARNING "HiSax: AVM A1 isac ports %x-%x already in use\n", cs->hw.avm.isac + 32, cs->hw.avm.isac + 64); release_ioregs(cs, 0); return (0); } if (!request_region(cs->hw.avm.isacfifo, 1, "HiSax isac fifo")) { printk(KERN_WARNING "HiSax: AVM A1 isac fifo port %x already in use\n", cs->hw.avm.isacfifo); release_ioregs(cs, 1); return (0); } if (!request_region(cs->hw.avm.hscx[0] + 32, 32, "HiSax hscx A")) { printk(KERN_WARNING "HiSax: AVM A1 hscx A ports %x-%x already in use\n", cs->hw.avm.hscx[0] + 32, cs->hw.avm.hscx[0] + 64); release_ioregs(cs, 3); return (0); } if (!request_region(cs->hw.avm.hscxfifo[0], 1, "HiSax hscx A fifo")) { printk(KERN_WARNING "HiSax: AVM A1 hscx A fifo port %x already in use\n", cs->hw.avm.hscxfifo[0]); release_ioregs(cs, 7); return (0); } if (!request_region(cs->hw.avm.hscx[1] + 32, 32, "HiSax hscx B")) { printk(KERN_WARNING "HiSax: AVM A1 hscx B ports %x-%x already in use\n", cs->hw.avm.hscx[1] + 32, cs->hw.avm.hscx[1] + 64); release_ioregs(cs, 0xf); return (0); } if (!request_region(cs->hw.avm.hscxfifo[1], 1, "HiSax hscx B fifo")) { printk(KERN_WARNING "HiSax: AVM A1 hscx B fifo port %x already in use\n", cs->hw.avm.hscxfifo[1]); release_ioregs(cs, 0x1f); return (0); } byteout(cs->hw.avm.cfg_reg, 0x0); HZDELAY(HZ / 5 + 1); byteout(cs->hw.avm.cfg_reg, 0x1); HZDELAY(HZ / 5 + 1); byteout(cs->hw.avm.cfg_reg, 0x0); HZDELAY(HZ / 5 + 1); val = cs->irq; if (val == 9) val = 2; byteout(cs->hw.avm.cfg_reg + 1, val); HZDELAY(HZ / 5 + 1); byteout(cs->hw.avm.cfg_reg, 0x0); HZDELAY(HZ / 5 + 1); val = bytein(cs->hw.avm.cfg_reg); printk(KERN_INFO "AVM A1: Byte at %x is %x\n", cs->hw.avm.cfg_reg, val); val = bytein(cs->hw.avm.cfg_reg + 3); printk(KERN_INFO "AVM A1: Byte at %x is %x\n", cs->hw.avm.cfg_reg + 3, val); val = bytein(cs->hw.avm.cfg_reg + 2); printk(KERN_INFO "AVM A1: Byte at %x is %x\n", cs->hw.avm.cfg_reg + 2, val); val = bytein(cs->hw.avm.cfg_reg); printk(KERN_INFO "AVM A1: Byte at %x is %x\n", cs->hw.avm.cfg_reg, val); printk(KERN_INFO "HiSax: AVM A1 config irq:%d cfg:0x%X\n", cs->irq, cs->hw.avm.cfg_reg); printk(KERN_INFO "HiSax: isac:0x%X/0x%X\n", cs->hw.avm.isac + 32, cs->hw.avm.isacfifo); printk(KERN_INFO "HiSax: hscx A:0x%X/0x%X hscx B:0x%X/0x%X\n", cs->hw.avm.hscx[0] + 32, cs->hw.avm.hscxfifo[0], cs->hw.avm.hscx[1] + 32, cs->hw.avm.hscxfifo[1]); cs->readisac = &ReadISAC; cs->writeisac = &WriteISAC; cs->readisacfifo = &ReadISACfifo; cs->writeisacfifo = &WriteISACfifo; cs->BC_Read_Reg = &ReadHSCX; cs->BC_Write_Reg = &WriteHSCX; cs->BC_Send_Data = &hscx_fill_fifo; setup_isac(cs); cs->cardmsg = &AVM_card_msg; cs->irq_func = &avm_a1_interrupt; ISACVersion(cs, "AVM A1:"); if (HscxVersion(cs, "AVM A1:")) { printk(KERN_WARNING "AVM A1: wrong HSCX versions check IO address\n"); release_ioregs(cs, 0x3f); return (0); } return (1); }
null
null
null
null
105,102
44,163
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
44,163
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 PPAPI_CPP_SIZE_H_ #define PPAPI_CPP_SIZE_H_ #include "ppapi/c/pp_size.h" #include "ppapi/cpp/logging.h" /// @file /// This file defines the API to create a size based on width /// and height. namespace pp { /// A size of an object based on width and height. class Size { public: /// The default constructor. Initializes the width and height to 0. Size() { size_.width = 0; size_.height = 0; } /// A constructor accepting a pointer to a <code>PP_Size</code> and /// converting the <code>PP_Size</code> to a <code>Size</code>. This is an /// implicit conversion constructor. /// /// @param[in] s A pointer to a <code>PP_Size</code>. Size(const PP_Size& s) { // Implicit. // Want the >= 0 checking of the setter. set_width(s.width); set_height(s.height); } /// A constructor accepting two int values for width and height and /// converting them to a <code>Size</code>. /// /// @param[in] w An int value representing a width. /// @param[in] h An int value representing a height. Size(int w, int h) { // Want the >= 0 checking of the setter. set_width(w); set_height(h); } /// Destructor. ~Size() { } /// PP_Size() allows implicit conversion of a <code>Size</code> to a /// <code>PP_Size</code>. /// /// @return A Size. operator PP_Size() { return size_; } /// Getter function for returning the internal <code>PP_Size</code> struct. /// /// @return A const reference to the internal <code>PP_Size</code> struct. const PP_Size& pp_size() const { return size_; } /// Getter function for returning the internal <code>PP_Size</code> struct. /// /// @return A mutable reference to the <code>PP_Size</code> struct. PP_Size& pp_size() { return size_; } /// Getter function for returning the value of width. /// /// @return The value of width for this <code>Size</code>. int width() const { return size_.width; } /// Setter function for setting the value of width. /// /// @param[in] w A new width value. void set_width(int w) { if (w < 0) { PP_DCHECK(w >= 0); w = 0; } size_.width = w; } /// Getter function for returning the value of height. /// /// @return The value of height for this <code>Size</code>. int height() const { return size_.height; } /// Setter function for setting the value of height. /// /// @param[in] h A new height value. void set_height(int h) { if (h < 0) { PP_DCHECK(h >= 0); h = 0; } size_.height = h; } /// GetArea() determines the area (width * height). /// /// @return The area. int GetArea() const { return width() * height(); } /// SetSize() sets the value of width and height. /// /// @param[in] w A new width value. /// @param[in] h A new height value. void SetSize(int w, int h) { set_width(w); set_height(h); } /// Enlarge() enlarges the size of an object. /// /// @param[in] w A width to add the current width. /// @param[in] h A height to add to the current height. void Enlarge(int w, int h) { set_width(width() + w); set_height(height() + h); } /// IsEmpty() determines if the size is zero. /// /// @return true if the size is zero. bool IsEmpty() const { // Size doesn't allow negative dimensions, so testing for 0 is enough. return (width() == 0) || (height() == 0); } private: PP_Size size_; }; /// A size of an object based on width and height. class FloatSize { public: /// The default constructor. Initializes the width and height to 0.0f. FloatSize() { size_.width = 0.0f; size_.height = 0.0f; } /// A constructor accepting a pointer to a <code>PP_FloatSize</code> and /// converting the <code>PP_FloatSize</code> to a <code>FloatSize</code>. /// This is an implicit conversion constructor. /// /// @param[in] s A pointer to a <code>PP_FloatSize</code>. FloatSize(const PP_FloatSize& s) { // Implicit. // Want the >= 0 checking of the setter. set_width(s.width); set_height(s.height); } /// A constructor accepting two float values for width and height and /// converting them to a <code>FloatSize</code>. /// /// @param[in] w An float value representing a width. /// @param[in] h An float value representing a height. FloatSize(float w, float h) { // Want the >= 0.0f checking of the setter. set_width(w); set_height(h); } /// Destructor. ~FloatSize() { } /// PP_FloatSize() allows implicit conversion of a <code>FloatSize</code> to a /// <code>PP_FloatSize</code>. /// /// @return A Size. operator PP_FloatSize() { return size_; } /// Getter function for returning the internal <code>PP_FloatSize</code> /// struct. /// /// @return A const reference to the internal <code>PP_FloatSize</code> /// struct. const PP_FloatSize& pp_float_size() const { return size_; } /// Getter function for returning the internal <code>PP_FloatSize</code> /// struct. /// /// @return A mutable reference to the <code>PP_FloatSize</code> struct. PP_FloatSize& pp_float_size() { return size_; } /// Getter function for returning the value of width. /// /// @return The value of width for this <code>FloatSize</code>. float width() const { return size_.width; } /// Setter function for setting the value of width. /// /// @param[in] w A new width value. void set_width(float w) { if (w < 0.0f) { PP_DCHECK(w >= 0.0f); w = 0.0f; } size_.width = w; } /// Getter function for returning the value of height. /// /// @return The value of height for this <code>FloatSize</code>. float height() const { return size_.height; } /// Setter function for setting the value of height. /// /// @param[in] h A new height value. void set_height(float h) { if (h < 0.0f) { PP_DCHECK(h >= 0.0f); h = 0.0f; } size_.height = h; } /// GetArea() determines the area (width * height). /// /// @return The area. float GetArea() const { return width() * height(); } /// SetSize() sets the value of width and height. /// /// @param[in] w A new width value. /// @param[in] h A new height value. void SetSize(float w, float h) { set_width(w); set_height(h); } /// Enlarge() enlarges the size of an object. /// /// @param[in] w A width to add the current width. /// @param[in] h A height to add to the current height. void Enlarge(float w, float h) { set_width(width() + w); set_height(height() + h); } /// IsEmpty() determines if the size is zero. /// /// @return true if the size is zero. bool IsEmpty() const { // Size doesn't allow negative dimensions, so testing for 0.0f is enough. return (width() == 0.0f) || (height() == 0.0f); } private: PP_FloatSize size_; }; } // namespace pp /// This function determines whether the width and height values of two sizes /// are equal. /// /// @param[in] lhs The <code>Size</code> on the left-hand side of the equation. /// @param[in] rhs The <code>Size</code> on the right-hand side of the /// equation. /// /// @return true if they are equal, false if unequal. inline bool operator==(const pp::Size& lhs, const pp::Size& rhs) { return lhs.width() == rhs.width() && lhs.height() == rhs.height(); } /// This function determines whether two <code>Sizes</code> are not equal. /// /// @param[in] lhs The <code>Size</code> on the left-hand side of the equation. /// @param[in] rhs The <code>Size</code> on the right-hand side of the equation. /// /// @return true if the <code>Size</code> of lhs are equal to the /// <code>Size</code> of rhs, otherwise false. inline bool operator!=(const pp::Size& lhs, const pp::Size& rhs) { return !(lhs == rhs); } /// This function determines whether the width and height values of two sizes /// are equal. /// /// @param[in] lhs The <code>FloatSize</code> on the left-hand side of the /// equation. /// @param[in] rhs The <code>FloatSize</code> on the right-hand side of the /// equation. /// /// @return true if they are equal, false if unequal. inline bool operator==(const pp::FloatSize& lhs, const pp::FloatSize& rhs) { return lhs.width() == rhs.width() && lhs.height() == rhs.height(); } /// This function determines whether two <code>FloatSizes</code> are not equal. /// /// @param[in] lhs The <code>FloatSize</code> on the left-hand side of the /// equation. /// @param[in] rhs The <code>FloatSize</code> on the right-hand side of the /// equation. /// /// @return true if the <code>FloatSize</code> of lhs are equal to the /// <code>FloatSize</code> of rhs, otherwise false. inline bool operator!=(const pp::FloatSize& lhs, const pp::FloatSize& rhs) { return !(lhs == rhs); } #endif // PPAPI_CPP_SIZE_H_
null
null
null
null
41,026
47,584
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
47,584
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 CC_RESOURCES_LAYER_TREE_RESOURCE_PROVIDER_H_ #define CC_RESOURCES_LAYER_TREE_RESOURCE_PROVIDER_H_ #include "cc/resources/resource_provider.h" #include "components/viz/common/display/renderer_settings.h" #include "components/viz/common/resources/resource_settings.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/gpu/GrBackendSurface.h" #include "third_party/skia/include/gpu/GrContext.h" namespace viz { class SharedBitmapManager; } // namespace viz namespace gpu { struct Capabilities; class GpuMemoryBufferManager; namespace raster { class RasterInterface; } } // namespace gpu namespace cc { // This class is not thread-safe and can only be called from the thread it was // created on (in practice, the impl thread). class CC_EXPORT LayerTreeResourceProvider : public ResourceProvider { public: LayerTreeResourceProvider( viz::ContextProvider* compositor_context_provider, viz::SharedBitmapManager* shared_bitmap_manager, gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager, bool delegated_sync_points_required, const viz::ResourceSettings& resource_settings); ~LayerTreeResourceProvider() override; static gpu::SyncToken GenerateSyncTokenHelper(gpu::gles2::GLES2Interface* gl); static gpu::SyncToken GenerateSyncTokenHelper( gpu::raster::RasterInterface* ri); // Gets the most recent sync token from the indicated resources. gpu::SyncToken GetSyncTokenForResources(const ResourceIdArray& resource_ids); // Prepares resources to be transfered to the parent, moving them to // mailboxes and serializing meta-data into TransferableResources. // Resources are not removed from the ResourceProvider, but are marked as // "in use". void PrepareSendToParent( const ResourceIdArray& resource_ids, std::vector<viz::TransferableResource>* transferable_resources); // Receives resources from the parent, moving them from mailboxes. ResourceIds // passed are in the child namespace. // NOTE: if the sync_token is set on any viz::TransferableResource, this will // wait on it. void ReceiveReturnsFromParent( const std::vector<viz::ReturnedResource>& transferable_resources); viz::ResourceId CreateGpuTextureResource(const gfx::Size& size, viz::ResourceTextureHint hint, viz::ResourceFormat format, const gfx::ColorSpace& color_space); viz::ResourceId CreateGpuMemoryBufferResource( const gfx::Size& size, viz::ResourceTextureHint hint, viz::ResourceFormat format, gfx::BufferUsage usage, const gfx::ColorSpace& color_space); viz::ResourceId CreateBitmapResource(const gfx::Size& size, const gfx::ColorSpace& color_space, viz::ResourceFormat format); void DeleteResource(viz::ResourceId id); // Receives a resource from an external client that can be used in compositor // frames, via the returned ResourceId. viz::ResourceId ImportResource(const viz::TransferableResource&, std::unique_ptr<viz::SingleReleaseCallback>); // Removes an imported resource, which will call the ReleaseCallback given // originally, once the resource is no longer in use by any compositor frame. void RemoveImportedResource(viz::ResourceId); // Update pixels from image, copying source_rect (in image) to dest_offset (in // the resource). void CopyToResource(viz::ResourceId id, const uint8_t* image, const gfx::Size& image_size); // For tests only! This prevents detecting uninitialized reads. // Use SetPixels or LockForWrite to allocate implicitly. void AllocateForTesting(viz::ResourceId id); // For tests only! void CreateForTesting(viz::ResourceId id); // Verify that the ResourceId is valid and is known to this class, for debug // checks. void ValidateResource(viz::ResourceId id) const; // Checks whether a resource is in use by a consumer. bool InUseByConsumer(viz::ResourceId id); // Indicates if we can currently lock this resource for write. bool CanLockForWrite(viz::ResourceId id); // In the case of GPU resources, we may need to flush the GL context to ensure // that texture deletions are seen in a timely fashion. This function should // be called after texture deletions that may happen during an idle state. void FlushPendingDeletions() const; GLenum GetImageTextureTarget(const gpu::Capabilities& caps, gfx::BufferUsage usage, viz::ResourceFormat format) const; bool IsTextureFormatSupported(viz::ResourceFormat format) const; // Returns true if the provided |format| can be used as a render buffer. // Note that render buffer support implies texture support. bool IsRenderBufferFormatSupported(viz::ResourceFormat format) const; bool use_sync_query() const { return settings_.use_sync_query; } int max_texture_size() const { return settings_.max_texture_size; } // Use this format for making resources that will be rastered and uploaded to // from software bitmaps. viz::ResourceFormat best_texture_format() const { return settings_.best_texture_format; } // Use this format for making resources that will be rastered to on the Gpu. viz::ResourceFormat best_render_buffer_format() const { return settings_.best_render_buffer_format; } viz::ResourceFormat YuvResourceFormat(int bits) const; gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager() { return gpu_memory_buffer_manager_; } bool IsLost(viz::ResourceId id); void LoseResourceForTesting(viz::ResourceId id); void EnableReadLockFencesForTesting(viz::ResourceId id); // The following lock classes are part of the ResourceProvider API and are // needed to read and write the resource contents. The user must ensure // that they only use GL locks on GL resources, etc, and this is enforced // by assertions. class CC_EXPORT ScopedWriteLockGpu { public: ScopedWriteLockGpu(LayerTreeResourceProvider* resource_provider, viz::ResourceId resource_id); ~ScopedWriteLockGpu(); GLenum target() const { return target_; } viz::ResourceFormat format() const { return format_; } const gfx::Size& size() const { return size_; } const gfx::ColorSpace& color_space_for_raster() const { return color_space_; } SkColorType ColorType() const; void set_allocated() { allocated_ = true; } void set_sync_token(const gpu::SyncToken& sync_token) { sync_token_ = sync_token; has_sync_token_ = true; } void set_synchronized() { synchronized_ = true; } void set_generate_mipmap() { generate_mipmap_ = true; } // Creates mailbox on compositor context that can be consumed on another // context. void CreateMailbox(); protected: LayerTreeResourceProvider* const resource_provider_; const viz::ResourceId resource_id_; // The following are copied from the resource. gfx::Size size_; gfx::BufferUsage usage_; viz::ResourceFormat format_; gfx::ColorSpace color_space_; GLuint texture_id_; GLenum target_; viz::ResourceTextureHint hint_; gpu::Mailbox mailbox_; bool is_overlay_; bool allocated_; // Set by the user. gpu::SyncToken sync_token_; bool has_sync_token_ = false; bool synchronized_ = false; bool generate_mipmap_ = false; private: DISALLOW_COPY_AND_ASSIGN(ScopedWriteLockGpu); }; class CC_EXPORT ScopedWriteLockGL : public ScopedWriteLockGpu { public: ScopedWriteLockGL(LayerTreeResourceProvider* resource_provider, viz::ResourceId resource_id); ~ScopedWriteLockGL(); // Returns texture id on compositor context, allocating if necessary. GLuint GetTexture(); private: void LazyAllocate(gpu::gles2::GLES2Interface* gl, GLuint texture_id); DISALLOW_COPY_AND_ASSIGN(ScopedWriteLockGL); }; class CC_EXPORT ScopedWriteLockRaster : public ScopedWriteLockGpu { public: ScopedWriteLockRaster(LayerTreeResourceProvider* resource_provider, viz::ResourceId resource_id); ~ScopedWriteLockRaster(); // Creates a texture id, allocating if necessary, on the given context. The // texture id must be deleted by the caller. GLuint ConsumeTexture(gpu::raster::RasterInterface* ri); private: void LazyAllocate(gpu::raster::RasterInterface* gl, GLuint texture_id); DISALLOW_COPY_AND_ASSIGN(ScopedWriteLockRaster); }; class CC_EXPORT ScopedWriteLockGpuMemoryBuffer { public: ScopedWriteLockGpuMemoryBuffer(LayerTreeResourceProvider* resource_provider, viz::ResourceId resource_id); ~ScopedWriteLockGpuMemoryBuffer(); gfx::GpuMemoryBuffer* GetGpuMemoryBuffer(); const gfx::ColorSpace& color_space_for_raster() const { return color_space_; } private: LayerTreeResourceProvider* const resource_provider_; const viz::ResourceId resource_id_; gfx::Size size_; viz::ResourceFormat format_; gfx::BufferUsage usage_; gfx::ColorSpace color_space_; std::unique_ptr<gfx::GpuMemoryBuffer> gpu_memory_buffer_; DISALLOW_COPY_AND_ASSIGN(ScopedWriteLockGpuMemoryBuffer); }; class CC_EXPORT ScopedWriteLockSoftware { public: ScopedWriteLockSoftware(LayerTreeResourceProvider* resource_provider, viz::ResourceId resource_id); ~ScopedWriteLockSoftware(); SkBitmap& sk_bitmap() { return sk_bitmap_; } bool valid() const { return !!sk_bitmap_.getPixels(); } const gfx::ColorSpace& color_space_for_raster() const { return color_space_; } private: LayerTreeResourceProvider* const resource_provider_; const viz::ResourceId resource_id_; gfx::ColorSpace color_space_; SkBitmap sk_bitmap_; DISALLOW_COPY_AND_ASSIGN(ScopedWriteLockSoftware); }; class CC_EXPORT ScopedSkSurface { public: ScopedSkSurface(GrContext* gr_context, GLuint texture_id, GLenum texture_target, const gfx::Size& size, viz::ResourceFormat format, bool can_use_lcd_text, int msaa_sample_count); ~ScopedSkSurface(); SkSurface* surface() const { return surface_.get(); } static SkSurfaceProps ComputeSurfaceProps(bool can_use_lcd_text); private: sk_sp<SkSurface> surface_; DISALLOW_COPY_AND_ASSIGN(ScopedSkSurface); }; protected: viz::internal::Resource* LockForWrite(viz::ResourceId id); void UnlockForWrite(viz::internal::Resource* resource); void CreateMailbox(viz::internal::Resource* resource); private: // Holds const settings for the ResourceProvider. Never changed after init. struct Settings { Settings(viz::ContextProvider* compositor_context_provider, bool delegated_sync_points_needed, const viz::ResourceSettings& resource_settings); int max_texture_size = 0; bool use_texture_storage = false; bool use_texture_format_bgra = false; bool use_texture_usage_hint = false; bool use_texture_npot = false; bool use_sync_query = false; bool use_texture_storage_image = false; viz::ResourceType default_resource_type = viz::ResourceType::kTexture; viz::ResourceFormat yuv_resource_format = viz::LUMINANCE_8; viz::ResourceFormat yuv_highbit_resource_format = viz::LUMINANCE_8; viz::ResourceFormat best_texture_format = viz::RGBA_8888; viz::ResourceFormat best_render_buffer_format = viz::RGBA_8888; bool use_gpu_memory_buffer_resources = false; bool delegated_sync_points_required = false; } const settings_; // base::trace_event::MemoryDumpProvider implementation. bool OnMemoryDump(const base::trace_event::MemoryDumpArgs& args, base::trace_event::ProcessMemoryDump* pmd) override; gfx::ColorSpace GetResourceColorSpaceForRaster( const viz::internal::Resource* resource) const; void CreateTexture(viz::internal::Resource* resource); void CreateAndBindImage(viz::internal::Resource* resource); void TransferResource(viz::internal::Resource* source, viz::ResourceId id, viz::TransferableResource* resource); viz::SharedBitmapManager* shared_bitmap_manager_; struct ImportedResource; base::flat_map<viz::ResourceId, ImportedResource> imported_resources_; gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager_; viz::ResourceId next_id_; DISALLOW_COPY_AND_ASSIGN(LayerTreeResourceProvider); }; } // namespace cc #endif // CC_RESOURCES_LAYER_TREE_RESOURCE_PROVIDER_H_
null
null
null
null
44,447
59,195
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
59,195
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 CHROME_BROWSER_EXTENSIONS_API_TABS_APP_WINDOW_CONTROLLER_H_ #define CHROME_BROWSER_EXTENSIONS_API_TABS_APP_WINDOW_CONTROLLER_H_ #include <memory> #include <string> #include "base/macros.h" #include "chrome/browser/extensions/window_controller.h" class Profile; namespace extensions { class AppWindow; class AppBaseWindow; // A extensions::WindowController specific to extensions::AppWindow. class AppWindowController : public WindowController { public: AppWindowController(AppWindow* window, std::unique_ptr<AppBaseWindow> base_window, Profile* profile); ~AppWindowController() override; // extensions::WindowController: int GetWindowId() const override; std::string GetWindowTypeText() const override; bool CanClose(Reason* reason) const override; void SetFullscreenMode(bool is_fullscreen, const GURL& extension_url) const override; Browser* GetBrowser() const override; bool IsVisibleToTabsAPIForExtension( const Extension* extension, bool allow_dev_tools_windows) const override; private: AppWindow* app_window_; // Owns us. std::unique_ptr<AppBaseWindow> base_window_; DISALLOW_COPY_AND_ASSIGN(AppWindowController); }; } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_API_TABS_APP_WINDOW_CONTROLLER_H_
null
null
null
null
56,058
41,826
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
206,821
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Platform data for LPC32xx SoC MLC NAND controller * * Copyright © 2012 Roland Stigge * * 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. */ #ifndef __LINUX_MTD_LPC32XX_MLC_H #define __LINUX_MTD_LPC32XX_MLC_H #include <linux/dmaengine.h> struct lpc32xx_mlc_platform_data { bool (*dma_filter)(struct dma_chan *chan, void *filter_param); }; #endif /* __LINUX_MTD_LPC32XX_MLC_H */
null
null
null
null
115,168
1,005
1,2,3,4,5,6,7,8,9
train_val
d65b01ca819881a507b5e60c25a2f9caff58cd57
1,005
Chrome
1
https://github.com/chromium/chromium
2012-09-05 18:15:24+00:00
AvailableSpaceQueryTask( QuotaManager* manager, const AvailableSpaceCallback& callback) : QuotaThreadTask(manager, manager->db_thread_), profile_path_(manager->profile_path_), space_(-1), get_disk_space_fn_(manager->get_disk_space_fn_), callback_(callback) { DCHECK(get_disk_space_fn_); }
CVE-2012-5112
CWE-399
https://github.com/chromium/chromium/commit/d65b01ca819881a507b5e60c25a2f9caff58cd57
Low
1,005
12,880
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
177,875
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * include/asm-ppc/rheap.h * * Header file for the implementation of a remote heap. * * Author: Pantelis Antoniou <panto@intracom.gr> * * 2004 (c) INTRACOM S.A. Greece. This file is licensed under * the terms of the GNU General Public License version 2. This program * is licensed "as is" without any warranty of any kind, whether express * or implied. */ #ifndef __ASM_PPC_RHEAP_H__ #define __ASM_PPC_RHEAP_H__ #include <linux/list.h> typedef struct _rh_block { struct list_head list; unsigned long start; int size; const char *owner; } rh_block_t; typedef struct _rh_info { unsigned int alignment; int max_blocks; int empty_slots; rh_block_t *block; struct list_head empty_list; struct list_head free_list; struct list_head taken_list; unsigned int flags; } rh_info_t; #define RHIF_STATIC_INFO 0x1 #define RHIF_STATIC_BLOCK 0x2 typedef struct _rh_stats { unsigned long start; int size; const char *owner; } rh_stats_t; #define RHGS_FREE 0 #define RHGS_TAKEN 1 /* Create a remote heap dynamically */ extern rh_info_t *rh_create(unsigned int alignment); /* Destroy a remote heap, created by rh_create() */ extern void rh_destroy(rh_info_t * info); /* Initialize in place a remote info block */ extern void rh_init(rh_info_t * info, unsigned int alignment, int max_blocks, rh_block_t * block); /* Attach a free region to manage */ extern int rh_attach_region(rh_info_t * info, unsigned long start, int size); /* Detach a free region */ extern unsigned long rh_detach_region(rh_info_t * info, unsigned long start, int size); /* Allocate the given size from the remote heap (with alignment) */ extern unsigned long rh_alloc_align(rh_info_t * info, int size, int alignment, const char *owner); /* Allocate the given size from the remote heap */ extern unsigned long rh_alloc(rh_info_t * info, int size, const char *owner); /* Allocate the given size from the given address */ extern unsigned long rh_alloc_fixed(rh_info_t * info, unsigned long start, int size, const char *owner); /* Free the allocated area */ extern int rh_free(rh_info_t * info, unsigned long start); /* Get stats for debugging purposes */ extern int rh_get_stats(rh_info_t * info, int what, int max_stats, rh_stats_t * stats); /* Simple dump of remote heap info */ extern void rh_dump(rh_info_t * info); /* Set owner of taken block */ extern int rh_set_owner(rh_info_t * info, unsigned long start, const char *owner); #endif /* __ASM_PPC_RHEAP_H__ */
null
null
null
null
86,222
62,313
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
62,313
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/task_manager/mock_web_contents_task_manager.h" #include "base/stl_util.h" #include "build/build_config.h" #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/resource_reporter/resource_reporter.h" #endif // defined(OS_CHROMEOS) namespace task_manager { MockWebContentsTaskManager::MockWebContentsTaskManager() {} MockWebContentsTaskManager::~MockWebContentsTaskManager() {} void MockWebContentsTaskManager::TaskAdded(Task* task) { DCHECK(task); DCHECK(!base::ContainsValue(tasks_, task)); tasks_.push_back(task); } void MockWebContentsTaskManager::TaskRemoved(Task* task) { DCHECK(task); DCHECK(base::ContainsValue(tasks_, task)); tasks_.erase(std::find(tasks_.begin(), tasks_.end(), task)); } void MockWebContentsTaskManager::StartObserving() { #if defined(OS_CHROMEOS) // On ChromeOS, the ResourceReporter needs to be turned off so as not to // interfere with the tests. chromeos::ResourceReporter::GetInstance()->StopMonitoring(); #endif // defined(OS_CHROMEOS) provider_.SetObserver(this); } void MockWebContentsTaskManager::StopObserving() { provider_.ClearObserver(); } } // namespace task_manager
null
null
null
null
59,176
38,709
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
38,709
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* * Copyright (C) 2012 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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. */ #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_SPEECH_SPEECH_GRAMMAR_LIST_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_SPEECH_SPEECH_GRAMMAR_LIST_H_ #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/modules/speech/speech_grammar.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/heap/handle.h" namespace blink { class ScriptState; class MODULES_EXPORT SpeechGrammarList final : public ScriptWrappable { DEFINE_WRAPPERTYPEINFO(); public: static SpeechGrammarList* Create(); unsigned length() const { return grammars_.size(); } SpeechGrammar* item(unsigned) const; void addFromUri(ScriptState*, const String& src, double weight = 1.0); void addFromString(const String&, double weight = 1.0); void Trace(blink::Visitor*); private: SpeechGrammarList(); HeapVector<Member<SpeechGrammar>> grammars_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_SPEECH_SPEECH_GRAMMAR_LIST_H_
null
null
null
null
35,572
267
21
train_val
12f09ccb4612734a53e47ed5302e0479c10a50f8
165,262
linux
1
https://github.com/torvalds/linux
2011-07-22 09:37:46+00:00
struct se_portal_group *tcm_loop_make_naa_tpg( struct se_wwn *wwn, struct config_group *group, const char *name) { struct tcm_loop_hba *tl_hba = container_of(wwn, struct tcm_loop_hba, tl_hba_wwn); struct tcm_loop_tpg *tl_tpg; char *tpgt_str, *end_ptr; int ret; unsigned short int tpgt; tpgt_str = strstr(name, "tpgt_"); if (!tpgt_str) { printk(KERN_ERR "Unable to locate \"tpgt_#\" directory" " group\n"); return ERR_PTR(-EINVAL); } tpgt_str += 5; /* Skip ahead of "tpgt_" */ tpgt = (unsigned short int) simple_strtoul(tpgt_str, &end_ptr, 0); if (tpgt > TL_TPGS_PER_HBA) { printk(KERN_ERR "Passed tpgt: %hu exceeds TL_TPGS_PER_HBA:" " %u\n", tpgt, TL_TPGS_PER_HBA); return ERR_PTR(-EINVAL); } tl_tpg = &tl_hba->tl_hba_tpgs[tpgt]; tl_tpg->tl_hba = tl_hba; tl_tpg->tl_tpgt = tpgt; /* * Register the tl_tpg as a emulated SAS TCM Target Endpoint */ ret = core_tpg_register(&tcm_loop_fabric_configfs->tf_ops, wwn, &tl_tpg->tl_se_tpg, tl_tpg, TRANSPORT_TPG_TYPE_NORMAL); if (ret < 0) return ERR_PTR(-ENOMEM); printk(KERN_INFO "TCM_Loop_ConfigFS: Allocated Emulated %s" " Target Port %s,t,0x%04x\n", tcm_loop_dump_proto_id(tl_hba), config_item_name(&wwn->wwn_group.cg_item), tpgt); return &tl_tpg->tl_se_tpg; }
CVE-2011-5327
CWE-119
https://github.com/torvalds/linux/commit/12f09ccb4612734a53e47ed5302e0479c10a50f8
Low
3,156
44,866
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
44,866
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 PPAPI_SHARED_IMPL_PPAPI_GLOBALS_H_ #define PPAPI_SHARED_IMPL_PPAPI_GLOBALS_H_ #include <string> #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/threading/thread_local.h" // For testing purposes only. #include "ppapi/c/pp_instance.h" #include "ppapi/c/pp_module.h" #include "ppapi/c/ppb_console.h" #include "ppapi/shared_impl/api_id.h" #include "ppapi/shared_impl/ppapi_shared_export.h" namespace base { class SingleThreadTaskRunner; class TaskRunner; } namespace ppapi { class CallbackTracker; class MessageLoopShared; class ResourceTracker; class VarTracker; namespace thunk { class PPB_Instance_API; class ResourceCreationAPI; } // Abstract base class class PPAPI_SHARED_EXPORT PpapiGlobals { public: // Must be created on the main thread. PpapiGlobals(); // This constructor is to be used only for making a PpapiGlobal for testing // purposes. This avoids setting the global static ppapi_globals_. For unit // tests that use this feature, the "test" PpapiGlobals should be constructed // using this method. See SetPpapiGlobalsOnThreadForTest for more information. struct PerThreadForTest {}; explicit PpapiGlobals(PerThreadForTest); virtual ~PpapiGlobals(); // Getter for the global singleton. static PpapiGlobals* Get(); // This allows us to set a given PpapiGlobals object as the PpapiGlobals for // a given thread. After setting the PpapiGlobals for a thread, Get() will // return that PpapiGlobals when Get() is called on that thread. Other threads // are unaffected. This allows us to have tests which use >1 PpapiGlobals in // the same process, e.g. for having 1 thread emulate the "host" and 1 thread // emulate the "plugin". // // PpapiGlobals object must have been constructed using the "PerThreadForTest" // parameter. static void SetPpapiGlobalsOnThreadForTest(PpapiGlobals* ptr); // Retrieves the corresponding tracker. virtual ResourceTracker* GetResourceTracker() = 0; virtual VarTracker* GetVarTracker() = 0; virtual CallbackTracker* GetCallbackTrackerForInstance( PP_Instance instance) = 0; // Logs the given string to the JS console. If "source" is empty, the name of // the current module will be used, if it can be determined. virtual void LogWithSource(PP_Instance instance, PP_LogLevel level, const std::string& source, const std::string& value) = 0; // Like LogWithSource but broadcasts the log to all instances of the given // module. The module may be 0 to specify that all consoles possibly // associated with the calling code should be notified. This allows us to // log errors for things like bad resource IDs where we may not have an // associated instance. // // Note that in the plugin process, the module parameter is ignored since // there is only one possible one. virtual void BroadcastLogWithSource(PP_Module module, PP_LogLevel level, const std::string& source, const std::string& value) = 0; // Returns the given API object associated with the given instance, or NULL // if the instance is invalid. virtual thunk::PPB_Instance_API* GetInstanceAPI(PP_Instance instance) = 0; virtual thunk::ResourceCreationAPI* GetResourceCreationAPI( PP_Instance instance) = 0; // Returns the PP_Module associated with the given PP_Instance, or 0 on // failure. virtual PP_Module GetModuleForInstance(PP_Instance instance) = 0; // Returns the base::SingleThreadTaskRunner for the main thread. This is set // in the constructor, so PpapiGlobals must be created on the main thread. base::SingleThreadTaskRunner* GetMainThreadMessageLoop(); // In tests, the PpapiGlobals object persists across tests but the MLP pointer // it hangs on will go stale and the next PPAPI test will crash because of // thread checks. This resets the pointer to be the current MLP object. void ResetMainThreadMessageLoopForTesting(); // Return the MessageLoopShared of the current thread, if any. This will // always return NULL on the host side, where PPB_MessageLoop is not // supported. virtual MessageLoopShared* GetCurrentMessageLoop() = 0; // Returns a task runner for file operations that may block. // TODO(bbudge) Move this to PluginGlobals when we no longer support // in-process plugins. virtual base::TaskRunner* GetFileTaskRunner() = 0; // Returns the command line for the process. virtual std::string GetCmdLine() = 0; // Preloads the font on Windows, does nothing on other platforms. // TODO(brettw) remove this by passing the instance into the API so we don't // have to have it on the globals. virtual void PreCacheFontForFlash(const void* logfontw) = 0; virtual bool IsHostGlobals() const; virtual bool IsPluginGlobals() const; private: // Return the thread-local pointer which is used only for unit testing. It // should always be NULL when running in production. It allows separate // threads to have distinct "globals". static PpapiGlobals* GetThreadLocalPointer(); scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_; DISALLOW_COPY_AND_ASSIGN(PpapiGlobals); }; } // namespace ppapi #endif // PPAPI_SHARED_IMPL_PPAPI_GLOBALS_H_
null
null
null
null
41,729
894
null
train_val
c536b6be1a72aefd632d5530106a67c516cb9f4b
257,281
openssl
0
https://github.com/openssl/openssl
2016-09-22 23:12:38+01:00
/* * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stddef.h> #include <openssl/ct.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/safestack.h> /* * From RFC6962: opaque SerializedSCT<1..2^16-1>; struct { SerializedSCT * sct_list <1..2^16-1>; } SignedCertificateTimestampList; */ # define MAX_SCT_SIZE 65535 # define MAX_SCT_LIST_SIZE MAX_SCT_SIZE /* * Macros to read and write integers in network-byte order. */ #define n2s(c,s) ((s=(((unsigned int)((c)[0]))<< 8)| \ (((unsigned int)((c)[1])) )),c+=2) #define s2n(s,c) ((c[0]=(unsigned char)(((s)>> 8)&0xff), \ c[1]=(unsigned char)(((s) )&0xff)),c+=2) #define l2n3(l,c) ((c[0]=(unsigned char)(((l)>>16)&0xff), \ c[1]=(unsigned char)(((l)>> 8)&0xff), \ c[2]=(unsigned char)(((l) )&0xff)),c+=3) #define n2l8(c,l) (l =((uint64_t)(*((c)++)))<<56, \ l|=((uint64_t)(*((c)++)))<<48, \ l|=((uint64_t)(*((c)++)))<<40, \ l|=((uint64_t)(*((c)++)))<<32, \ l|=((uint64_t)(*((c)++)))<<24, \ l|=((uint64_t)(*((c)++)))<<16, \ l|=((uint64_t)(*((c)++)))<< 8, \ l|=((uint64_t)(*((c)++)))) #define l2n8(l,c) (*((c)++)=(unsigned char)(((l)>>56)&0xff), \ *((c)++)=(unsigned char)(((l)>>48)&0xff), \ *((c)++)=(unsigned char)(((l)>>40)&0xff), \ *((c)++)=(unsigned char)(((l)>>32)&0xff), \ *((c)++)=(unsigned char)(((l)>>24)&0xff), \ *((c)++)=(unsigned char)(((l)>>16)&0xff), \ *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ *((c)++)=(unsigned char)(((l) )&0xff)) /* Signed Certificate Timestamp */ struct sct_st { sct_version_t version; /* If version is not SCT_VERSION_V1, this contains the encoded SCT */ unsigned char *sct; size_t sct_len; /* If version is SCT_VERSION_V1, fields below contain components of the SCT */ unsigned char *log_id; size_t log_id_len; /* * Note, we cannot distinguish between an unset timestamp, and one * that is set to 0. However since CT didn't exist in 1970, no real * SCT should ever be set as such. */ uint64_t timestamp; unsigned char *ext; size_t ext_len; unsigned char hash_alg; unsigned char sig_alg; unsigned char *sig; size_t sig_len; /* Log entry type */ ct_log_entry_type_t entry_type; /* Where this SCT was found, e.g. certificate, OCSP response, etc. */ sct_source_t source; /* The result of the last attempt to validate this SCT. */ sct_validation_status_t validation_status; }; /* Miscellaneous data that is useful when verifying an SCT */ struct sct_ctx_st { /* Public key */ EVP_PKEY *pkey; /* Hash of public key */ unsigned char *pkeyhash; size_t pkeyhashlen; /* For pre-certificate: issuer public key hash */ unsigned char *ihash; size_t ihashlen; /* certificate encoding */ unsigned char *certder; size_t certderlen; /* pre-certificate encoding */ unsigned char *preder; size_t prederlen; }; /* Context when evaluating whether a Certificate Transparency policy is met */ struct ct_policy_eval_ctx_st { X509 *cert; X509 *issuer; CTLOG_STORE *log_store; }; /* * Creates a new context for verifying an SCT. */ SCT_CTX *SCT_CTX_new(void); /* * Deletes an SCT verification context. */ void SCT_CTX_free(SCT_CTX *sctx); /* * Sets the certificate that the SCT was created for. * If *cert does not have a poison extension, presigner must be NULL. * If *cert does not have a poison extension, it may have a single SCT * (NID_ct_precert_scts) extension. * If either *cert or *presigner have an AKID (NID_authority_key_identifier) * extension, both must have one. * Returns 1 on success, 0 on failure. */ __owur int SCT_CTX_set1_cert(SCT_CTX *sctx, X509 *cert, X509 *presigner); /* * Sets the issuer of the certificate that the SCT was created for. * This is just a convenience method to save extracting the public key and * calling SCT_CTX_set1_issuer_pubkey(). * Issuer must not be NULL. * Returns 1 on success, 0 on failure. */ __owur int SCT_CTX_set1_issuer(SCT_CTX *sctx, const X509 *issuer); /* * Sets the public key of the issuer of the certificate that the SCT was created * for. * The public key must not be NULL. * Returns 1 on success, 0 on failure. */ __owur int SCT_CTX_set1_issuer_pubkey(SCT_CTX *sctx, X509_PUBKEY *pubkey); /* * Sets the public key of the CT log that the SCT is from. * Returns 1 on success, 0 on failure. */ __owur int SCT_CTX_set1_pubkey(SCT_CTX *sctx, X509_PUBKEY *pubkey); /* * Verifies an SCT with the given context. * Returns 1 if the SCT verifies successfully; any other value indicates * failure. See EVP_DigestVerifyFinal() for the meaning of those values. */ __owur int SCT_CTX_verify(const SCT_CTX *sctx, const SCT *sct); /* * Does this SCT have the minimum fields populated to be usable? * Returns 1 if so, 0 otherwise. */ __owur int SCT_is_complete(const SCT *sct); /* * Does this SCT have the signature-related fields populated? * Returns 1 if so, 0 otherwise. * This checks that the signature and hash algorithms are set to supported * values and that the signature field is set. */ __owur int SCT_signature_is_complete(const SCT *sct); /* * TODO(RJPercival): Create an SCT_signature struct and make i2o_SCT_signature * and o2i_SCT_signature conform to the i2d/d2i conventions. */ /* * Serialize (to TLS format) an |sct| signature and write it to |out|. * If |out| is null, no signature will be output but the length will be returned. * If |out| points to a null pointer, a string will be allocated to hold the * TLS-format signature. It is the responsibility of the caller to free it. * If |out| points to an allocated string, the signature will be written to it. * The length of the signature in TLS format will be returned. */ __owur int i2o_SCT_signature(const SCT *sct, unsigned char **out); /* * Parses an SCT signature in TLS format and populates the |sct| with it. * |in| should be a pointer to a string containing the TLS-format signature. * |in| will be advanced to the end of the signature if parsing succeeds. * |len| should be the length of the signature in |in|. * Returns the number of bytes parsed, or a negative integer if an error occurs. * If an error occurs, the SCT's signature NID may be updated whilst the * signature field itself remains unset. */ __owur int o2i_SCT_signature(SCT *sct, const unsigned char **in, size_t len); /* * Handlers for Certificate Transparency X509v3/OCSP extensions */ extern const X509V3_EXT_METHOD v3_ct_scts[3];
null
null
null
null
118,726
43,217
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
208,212
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Global definitions for the Ethernet IEEE 802.3 interface. * * Version: @(#)if_ether.h 1.0.1a 02/08/94 * * Author: Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Donald Becker, <becker@super.org> * Alan Cox, <alan@lxorguk.ukuu.org.uk> * Steve Whitehouse, <gw7rrm@eeshack3.swan.ac.uk> * * 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 _UAPI_LINUX_IF_ETHER_H #define _UAPI_LINUX_IF_ETHER_H #include <linux/types.h> /* * IEEE 802.3 Ethernet magic constants. The frame sizes omit the preamble * and FCS/CRC (frame check sequence). */ #define ETH_ALEN 6 /* Octets in one ethernet addr */ #define ETH_HLEN 14 /* Total octets in header. */ #define ETH_ZLEN 60 /* Min. octets in frame sans FCS */ #define ETH_DATA_LEN 1500 /* Max. octets in payload */ #define ETH_FRAME_LEN 1514 /* Max. octets in frame sans FCS */ #define ETH_FCS_LEN 4 /* Octets in the FCS */ #define ETH_MIN_MTU 68 /* Min IPv4 MTU per RFC791 */ #define ETH_MAX_MTU 0xFFFFU /* 65535, same as IP_MAX_MTU */ /* * These are the defined Ethernet Protocol ID's. */ #define ETH_P_LOOP 0x0060 /* Ethernet Loopback packet */ #define ETH_P_PUP 0x0200 /* Xerox PUP packet */ #define ETH_P_PUPAT 0x0201 /* Xerox PUP Addr Trans packet */ #define ETH_P_TSN 0x22F0 /* TSN (IEEE 1722) packet */ #define ETH_P_IP 0x0800 /* Internet Protocol packet */ #define ETH_P_X25 0x0805 /* CCITT X.25 */ #define ETH_P_ARP 0x0806 /* Address Resolution packet */ #define ETH_P_BPQ 0x08FF /* G8BPQ AX.25 Ethernet Packet [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_IEEEPUP 0x0a00 /* Xerox IEEE802.3 PUP packet */ #define ETH_P_IEEEPUPAT 0x0a01 /* Xerox IEEE802.3 PUP Addr Trans packet */ #define ETH_P_BATMAN 0x4305 /* B.A.T.M.A.N.-Advanced packet [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_DEC 0x6000 /* DEC Assigned proto */ #define ETH_P_DNA_DL 0x6001 /* DEC DNA Dump/Load */ #define ETH_P_DNA_RC 0x6002 /* DEC DNA Remote Console */ #define ETH_P_DNA_RT 0x6003 /* DEC DNA Routing */ #define ETH_P_LAT 0x6004 /* DEC LAT */ #define ETH_P_DIAG 0x6005 /* DEC Diagnostics */ #define ETH_P_CUST 0x6006 /* DEC Customer use */ #define ETH_P_SCA 0x6007 /* DEC Systems Comms Arch */ #define ETH_P_TEB 0x6558 /* Trans Ether Bridging */ #define ETH_P_RARP 0x8035 /* Reverse Addr Res packet */ #define ETH_P_ATALK 0x809B /* Appletalk DDP */ #define ETH_P_AARP 0x80F3 /* Appletalk AARP */ #define ETH_P_8021Q 0x8100 /* 802.1Q VLAN Extended Header */ #define ETH_P_IPX 0x8137 /* IPX over DIX */ #define ETH_P_IPV6 0x86DD /* IPv6 over bluebook */ #define ETH_P_PAUSE 0x8808 /* IEEE Pause frames. See 802.3 31B */ #define ETH_P_SLOW 0x8809 /* Slow Protocol. See 802.3ad 43B */ #define ETH_P_WCCP 0x883E /* Web-cache coordination protocol * defined in draft-wilson-wrec-wccp-v2-00.txt */ #define ETH_P_MPLS_UC 0x8847 /* MPLS Unicast traffic */ #define ETH_P_MPLS_MC 0x8848 /* MPLS Multicast traffic */ #define ETH_P_ATMMPOA 0x884c /* MultiProtocol Over ATM */ #define ETH_P_PPP_DISC 0x8863 /* PPPoE discovery messages */ #define ETH_P_PPP_SES 0x8864 /* PPPoE session messages */ #define ETH_P_LINK_CTL 0x886c /* HPNA, wlan link local tunnel */ #define ETH_P_ATMFATE 0x8884 /* Frame-based ATM Transport * over Ethernet */ #define ETH_P_PAE 0x888E /* Port Access Entity (IEEE 802.1X) */ #define ETH_P_AOE 0x88A2 /* ATA over Ethernet */ #define ETH_P_8021AD 0x88A8 /* 802.1ad Service VLAN */ #define ETH_P_802_EX1 0x88B5 /* 802.1 Local Experimental 1. */ #define ETH_P_TIPC 0x88CA /* TIPC */ #define ETH_P_MACSEC 0x88E5 /* 802.1ae MACsec */ #define ETH_P_8021AH 0x88E7 /* 802.1ah Backbone Service Tag */ #define ETH_P_MVRP 0x88F5 /* 802.1Q MVRP */ #define ETH_P_1588 0x88F7 /* IEEE 1588 Timesync */ #define ETH_P_NCSI 0x88F8 /* NCSI protocol */ #define ETH_P_PRP 0x88FB /* IEC 62439-3 PRP/HSRv0 */ #define ETH_P_FCOE 0x8906 /* Fibre Channel over Ethernet */ #define ETH_P_IBOE 0x8915 /* Infiniband over Ethernet */ #define ETH_P_TDLS 0x890D /* TDLS */ #define ETH_P_FIP 0x8914 /* FCoE Initialization Protocol */ #define ETH_P_80221 0x8917 /* IEEE 802.21 Media Independent Handover Protocol */ #define ETH_P_HSR 0x892F /* IEC 62439-3 HSRv1 */ #define ETH_P_LOOPBACK 0x9000 /* Ethernet loopback packet, per IEEE 802.3 */ #define ETH_P_QINQ1 0x9100 /* deprecated QinQ VLAN [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_QINQ2 0x9200 /* deprecated QinQ VLAN [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_QINQ3 0x9300 /* deprecated QinQ VLAN [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_EDSA 0xDADA /* Ethertype DSA [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_AF_IUCV 0xFBFB /* IBM af_iucv [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_802_3_MIN 0x0600 /* If the value in the ethernet type is less than this value * then the frame is Ethernet II. Else it is 802.3 */ /* * Non DIX types. Won't clash for 1500 types. */ #define ETH_P_802_3 0x0001 /* Dummy type for 802.3 frames */ #define ETH_P_AX25 0x0002 /* Dummy protocol id for AX.25 */ #define ETH_P_ALL 0x0003 /* Every packet (be careful!!!) */ #define ETH_P_802_2 0x0004 /* 802.2 frames */ #define ETH_P_SNAP 0x0005 /* Internal only */ #define ETH_P_DDCMP 0x0006 /* DEC DDCMP: Internal only */ #define ETH_P_WAN_PPP 0x0007 /* Dummy type for WAN PPP frames*/ #define ETH_P_PPP_MP 0x0008 /* Dummy type for PPP MP frames */ #define ETH_P_LOCALTALK 0x0009 /* Localtalk pseudo type */ #define ETH_P_CAN 0x000C /* CAN: Controller Area Network */ #define ETH_P_CANFD 0x000D /* CANFD: CAN flexible data rate*/ #define ETH_P_PPPTALK 0x0010 /* Dummy type for Atalk over PPP*/ #define ETH_P_TR_802_2 0x0011 /* 802.2 frames */ #define ETH_P_MOBITEX 0x0015 /* Mobitex (kaz@cafe.net) */ #define ETH_P_CONTROL 0x0016 /* Card specific control frames */ #define ETH_P_IRDA 0x0017 /* Linux-IrDA */ #define ETH_P_ECONET 0x0018 /* Acorn Econet */ #define ETH_P_HDLC 0x0019 /* HDLC frames */ #define ETH_P_ARCNET 0x001A /* 1A for ArcNet :-) */ #define ETH_P_DSA 0x001B /* Distributed Switch Arch. */ #define ETH_P_TRAILER 0x001C /* Trailer switch tagging */ #define ETH_P_PHONET 0x00F5 /* Nokia Phonet frames */ #define ETH_P_IEEE802154 0x00F6 /* IEEE802.15.4 frame */ #define ETH_P_CAIF 0x00F7 /* ST-Ericsson CAIF protocol */ #define ETH_P_XDSA 0x00F8 /* Multiplexed DSA protocol */ /* * This is an Ethernet frame header. */ struct ethhdr { unsigned char h_dest[ETH_ALEN]; /* destination eth addr */ unsigned char h_source[ETH_ALEN]; /* source ether addr */ __be16 h_proto; /* packet type ID field */ } __attribute__((packed)); #endif /* _UAPI_LINUX_IF_ETHER_H */
null
null
null
null
116,559
8,744
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
173,739
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * linux/arch/arm/mach-s3c64xx/mach-smartq7.c * * Copyright (C) 2010 Maurus Cuelenaere * * 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. * */ #include <linux/fb.h> #include <linux/gpio.h> #include <linux/gpio_keys.h> #include <linux/init.h> #include <linux/input.h> #include <linux/leds.h> #include <linux/platform_device.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <video/samsung_fimd.h> #include <mach/irqs.h> #include <mach/map.h> #include <mach/regs-gpio.h> #include <mach/gpio-samsung.h> #include <plat/cpu.h> #include <plat/devs.h> #include <plat/fb.h> #include <plat/gpio-cfg.h> #include <plat/samsung-time.h> #include "common.h" #include "mach-smartq.h" static struct gpio_led smartq7_leds[] = { { .name = "smartq7:red", .active_low = 1, .gpio = S3C64XX_GPN(8), }, { .name = "smartq7:green", .active_low = 1, .gpio = S3C64XX_GPN(9), }, }; static struct gpio_led_platform_data smartq7_led_data = { .num_leds = ARRAY_SIZE(smartq7_leds), .leds = smartq7_leds, }; static struct platform_device smartq7_leds_device = { .name = "leds-gpio", .id = -1, .dev.platform_data = &smartq7_led_data, }; /* Labels according to the SmartQ manual */ static struct gpio_keys_button smartq7_buttons[] = { { .gpio = S3C64XX_GPL(14), .code = KEY_POWER, .desc = "Power", .active_low = 1, .debounce_interval = 5, .type = EV_KEY, }, { .gpio = S3C64XX_GPN(2), .code = KEY_FN, .desc = "Function", .active_low = 1, .debounce_interval = 5, .type = EV_KEY, }, { .gpio = S3C64XX_GPN(3), .code = KEY_KPMINUS, .desc = "Minus", .active_low = 1, .debounce_interval = 5, .type = EV_KEY, }, { .gpio = S3C64XX_GPN(4), .code = KEY_KPPLUS, .desc = "Plus", .active_low = 1, .debounce_interval = 5, .type = EV_KEY, }, { .gpio = S3C64XX_GPN(12), .code = KEY_ENTER, .desc = "Enter", .active_low = 1, .debounce_interval = 5, .type = EV_KEY, }, { .gpio = S3C64XX_GPN(15), .code = KEY_ESC, .desc = "Cancel", .active_low = 1, .debounce_interval = 5, .type = EV_KEY, }, }; static struct gpio_keys_platform_data smartq7_buttons_data = { .buttons = smartq7_buttons, .nbuttons = ARRAY_SIZE(smartq7_buttons), }; static struct platform_device smartq7_buttons_device = { .name = "gpio-keys", .id = 0, .num_resources = 0, .dev = { .platform_data = &smartq7_buttons_data, } }; static struct s3c_fb_pd_win smartq7_fb_win0 = { .max_bpp = 32, .default_bpp = 16, .xres = 800, .yres = 480, }; static struct fb_videomode smartq7_lcd_timing = { .left_margin = 3, .right_margin = 5, .upper_margin = 1, .lower_margin = 20, .hsync_len = 10, .vsync_len = 3, .xres = 800, .yres = 480, .refresh = 80, }; static struct s3c_fb_platdata smartq7_lcd_pdata __initdata = { .setup_gpio = s3c64xx_fb_gpio_setup_24bpp, .vtiming = &smartq7_lcd_timing, .win[0] = &smartq7_fb_win0, .vidcon0 = VIDCON0_VIDOUT_RGB | VIDCON0_PNRMODE_RGB, .vidcon1 = VIDCON1_INV_HSYNC | VIDCON1_INV_VSYNC | VIDCON1_INV_VCLK, }; static struct platform_device *smartq7_devices[] __initdata = { &smartq7_leds_device, &smartq7_buttons_device, }; static void __init smartq7_machine_init(void) { s3c_fb_set_platdata(&smartq7_lcd_pdata); smartq_machine_init(); platform_add_devices(smartq7_devices, ARRAY_SIZE(smartq7_devices)); } MACHINE_START(SMARTQ7, "SmartQ 7") /* Maintainer: Maurus Cuelenaere <mcuelenaere AT gmail DOT com> */ .atag_offset = 0x100, .nr_irqs = S3C64XX_NR_IRQS, .init_irq = s3c6410_init_irq, .map_io = smartq_map_io, .init_machine = smartq7_machine_init, .init_time = samsung_timer_init, .restart = s3c64xx_restart, MACHINE_END
null
null
null
null
82,086
25,216
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
190,211
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Copyright 2008 Stuart Bennett * * 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 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 __NOUVEAU_HW_H__ #define __NOUVEAU_HW_H__ #include <drm/drmP.h> #include "disp.h" #include "nvreg.h" #include <subdev/bios/pll.h> #define MASK(field) ( \ (0xffffffff >> (31 - ((1 ? field) - (0 ? field)))) << (0 ? field)) #define XLATE(src, srclowbit, outfield) ( \ (((src) >> (srclowbit)) << (0 ? outfield)) & MASK(outfield)) void NVWriteVgaSeq(struct drm_device *, int head, uint8_t index, uint8_t value); uint8_t NVReadVgaSeq(struct drm_device *, int head, uint8_t index); void NVWriteVgaGr(struct drm_device *, int head, uint8_t index, uint8_t value); uint8_t NVReadVgaGr(struct drm_device *, int head, uint8_t index); void NVSetOwner(struct drm_device *, int owner); void NVBlankScreen(struct drm_device *, int head, bool blank); int nouveau_hw_get_pllvals(struct drm_device *, enum nvbios_pll_type plltype, struct nvkm_pll_vals *pllvals); int nouveau_hw_pllvals_to_clk(struct nvkm_pll_vals *pllvals); int nouveau_hw_get_clock(struct drm_device *, enum nvbios_pll_type plltype); void nouveau_hw_save_vga_fonts(struct drm_device *, bool save); void nouveau_hw_save_state(struct drm_device *, int head, struct nv04_mode_state *state); void nouveau_hw_load_state(struct drm_device *, int head, struct nv04_mode_state *state); void nouveau_hw_load_state_palette(struct drm_device *, int head, struct nv04_mode_state *state); /* nouveau_calc.c */ extern void nouveau_calc_arb(struct drm_device *, int vclk, int bpp, int *burst, int *lwm); static inline uint32_t NVReadCRTC(struct drm_device *dev, int head, uint32_t reg) { struct nvif_object *device = &nouveau_drm(dev)->client.device.object; uint32_t val; if (head) reg += NV_PCRTC0_SIZE; val = nvif_rd32(device, reg); return val; } static inline void NVWriteCRTC(struct drm_device *dev, int head, uint32_t reg, uint32_t val) { struct nvif_object *device = &nouveau_drm(dev)->client.device.object; if (head) reg += NV_PCRTC0_SIZE; nvif_wr32(device, reg, val); } static inline uint32_t NVReadRAMDAC(struct drm_device *dev, int head, uint32_t reg) { struct nvif_object *device = &nouveau_drm(dev)->client.device.object; uint32_t val; if (head) reg += NV_PRAMDAC0_SIZE; val = nvif_rd32(device, reg); return val; } static inline void NVWriteRAMDAC(struct drm_device *dev, int head, uint32_t reg, uint32_t val) { struct nvif_object *device = &nouveau_drm(dev)->client.device.object; if (head) reg += NV_PRAMDAC0_SIZE; nvif_wr32(device, reg, val); } static inline uint8_t nv_read_tmds(struct drm_device *dev, int or, int dl, uint8_t address) { int ramdac = (or & DCB_OUTPUT_C) >> 2; NVWriteRAMDAC(dev, ramdac, NV_PRAMDAC_FP_TMDS_CONTROL + dl * 8, NV_PRAMDAC_FP_TMDS_CONTROL_WRITE_DISABLE | address); return NVReadRAMDAC(dev, ramdac, NV_PRAMDAC_FP_TMDS_DATA + dl * 8); } static inline void nv_write_tmds(struct drm_device *dev, int or, int dl, uint8_t address, uint8_t data) { int ramdac = (or & DCB_OUTPUT_C) >> 2; NVWriteRAMDAC(dev, ramdac, NV_PRAMDAC_FP_TMDS_DATA + dl * 8, data); NVWriteRAMDAC(dev, ramdac, NV_PRAMDAC_FP_TMDS_CONTROL + dl * 8, address); } static inline void NVWriteVgaCrtc(struct drm_device *dev, int head, uint8_t index, uint8_t value) { struct nvif_object *device = &nouveau_drm(dev)->client.device.object; nvif_wr08(device, NV_PRMCIO_CRX__COLOR + head * NV_PRMCIO_SIZE, index); nvif_wr08(device, NV_PRMCIO_CR__COLOR + head * NV_PRMCIO_SIZE, value); } static inline uint8_t NVReadVgaCrtc(struct drm_device *dev, int head, uint8_t index) { struct nvif_object *device = &nouveau_drm(dev)->client.device.object; uint8_t val; nvif_wr08(device, NV_PRMCIO_CRX__COLOR + head * NV_PRMCIO_SIZE, index); val = nvif_rd08(device, NV_PRMCIO_CR__COLOR + head * NV_PRMCIO_SIZE); return val; } /* CR57 and CR58 are a fun pair of regs. CR57 provides an index (0-0xf) for CR58 * I suspect they in fact do nothing, but are merely a way to carry useful * per-head variables around * * Known uses: * CR57 CR58 * 0x00 index to the appropriate dcb entry (or 7f for inactive) * 0x02 dcb entry's "or" value (or 00 for inactive) * 0x03 bit0 set for dual link (LVDS, possibly elsewhere too) * 0x08 or 0x09 pxclk in MHz * 0x0f laptop panel info - low nibble for PEXTDEV_BOOT_0 strap * high nibble for xlat strap value */ static inline void NVWriteVgaCrtc5758(struct drm_device *dev, int head, uint8_t index, uint8_t value) { NVWriteVgaCrtc(dev, head, NV_CIO_CRE_57, index); NVWriteVgaCrtc(dev, head, NV_CIO_CRE_58, value); } static inline uint8_t NVReadVgaCrtc5758(struct drm_device *dev, int head, uint8_t index) { NVWriteVgaCrtc(dev, head, NV_CIO_CRE_57, index); return NVReadVgaCrtc(dev, head, NV_CIO_CRE_58); } static inline uint8_t NVReadPRMVIO(struct drm_device *dev, int head, uint32_t reg) { struct nvif_object *device = &nouveau_drm(dev)->client.device.object; struct nouveau_drm *drm = nouveau_drm(dev); uint8_t val; /* Only NV4x have two pvio ranges; other twoHeads cards MUST call * NVSetOwner for the relevant head to be programmed */ if (head && drm->client.device.info.family == NV_DEVICE_INFO_V0_CURIE) reg += NV_PRMVIO_SIZE; val = nvif_rd08(device, reg); return val; } static inline void NVWritePRMVIO(struct drm_device *dev, int head, uint32_t reg, uint8_t value) { struct nvif_object *device = &nouveau_drm(dev)->client.device.object; struct nouveau_drm *drm = nouveau_drm(dev); /* Only NV4x have two pvio ranges; other twoHeads cards MUST call * NVSetOwner for the relevant head to be programmed */ if (head && drm->client.device.info.family == NV_DEVICE_INFO_V0_CURIE) reg += NV_PRMVIO_SIZE; nvif_wr08(device, reg, value); } static inline void NVSetEnablePalette(struct drm_device *dev, int head, bool enable) { struct nvif_object *device = &nouveau_drm(dev)->client.device.object; nvif_rd08(device, NV_PRMCIO_INP0__COLOR + head * NV_PRMCIO_SIZE); nvif_wr08(device, NV_PRMCIO_ARX + head * NV_PRMCIO_SIZE, enable ? 0 : 0x20); } static inline bool NVGetEnablePalette(struct drm_device *dev, int head) { struct nvif_object *device = &nouveau_drm(dev)->client.device.object; nvif_rd08(device, NV_PRMCIO_INP0__COLOR + head * NV_PRMCIO_SIZE); return !(nvif_rd08(device, NV_PRMCIO_ARX + head * NV_PRMCIO_SIZE) & 0x20); } static inline void NVWriteVgaAttr(struct drm_device *dev, int head, uint8_t index, uint8_t value) { struct nvif_object *device = &nouveau_drm(dev)->client.device.object; if (NVGetEnablePalette(dev, head)) index &= ~0x20; else index |= 0x20; nvif_rd08(device, NV_PRMCIO_INP0__COLOR + head * NV_PRMCIO_SIZE); nvif_wr08(device, NV_PRMCIO_ARX + head * NV_PRMCIO_SIZE, index); nvif_wr08(device, NV_PRMCIO_AR__WRITE + head * NV_PRMCIO_SIZE, value); } static inline uint8_t NVReadVgaAttr(struct drm_device *dev, int head, uint8_t index) { struct nvif_object *device = &nouveau_drm(dev)->client.device.object; uint8_t val; if (NVGetEnablePalette(dev, head)) index &= ~0x20; else index |= 0x20; nvif_rd08(device, NV_PRMCIO_INP0__COLOR + head * NV_PRMCIO_SIZE); nvif_wr08(device, NV_PRMCIO_ARX + head * NV_PRMCIO_SIZE, index); val = nvif_rd08(device, NV_PRMCIO_AR__READ + head * NV_PRMCIO_SIZE); return val; } static inline void NVVgaSeqReset(struct drm_device *dev, int head, bool start) { NVWriteVgaSeq(dev, head, NV_VIO_SR_RESET_INDEX, start ? 0x1 : 0x3); } static inline void NVVgaProtect(struct drm_device *dev, int head, bool protect) { uint8_t seq1 = NVReadVgaSeq(dev, head, NV_VIO_SR_CLOCK_INDEX); if (protect) { NVVgaSeqReset(dev, head, true); NVWriteVgaSeq(dev, head, NV_VIO_SR_CLOCK_INDEX, seq1 | 0x20); } else { /* Reenable sequencer, then turn on screen */ NVWriteVgaSeq(dev, head, NV_VIO_SR_CLOCK_INDEX, seq1 & ~0x20); /* reenable display */ NVVgaSeqReset(dev, head, false); } NVSetEnablePalette(dev, head, protect); } static inline bool nv_heads_tied(struct drm_device *dev) { struct nvif_object *device = &nouveau_drm(dev)->client.device.object; struct nouveau_drm *drm = nouveau_drm(dev); if (drm->client.device.info.chipset == 0x11) return !!(nvif_rd32(device, NV_PBUS_DEBUG_1) & (1 << 28)); return NVReadVgaCrtc(dev, 0, NV_CIO_CRE_44) & 0x4; } /* makes cr0-7 on the specified head read-only */ static inline bool nv_lock_vga_crtc_base(struct drm_device *dev, int head, bool lock) { uint8_t cr11 = NVReadVgaCrtc(dev, head, NV_CIO_CR_VRE_INDEX); bool waslocked = cr11 & 0x80; if (lock) cr11 |= 0x80; else cr11 &= ~0x80; NVWriteVgaCrtc(dev, head, NV_CIO_CR_VRE_INDEX, cr11); return waslocked; } static inline void nv_lock_vga_crtc_shadow(struct drm_device *dev, int head, int lock) { /* shadow lock: connects 0x60?3d? regs to "real" 0x3d? regs * bit7: unlocks HDT, HBS, HBE, HRS, HRE, HEB * bit6: seems to have some effect on CR09 (double scan, VBS_9) * bit5: unlocks HDE * bit4: unlocks VDE * bit3: unlocks VDT, OVL, VRS, ?VRE?, VBS, VBE, LSR, EBR * bit2: same as bit 1 of 0x60?804 * bit0: same as bit 0 of 0x60?804 */ uint8_t cr21 = lock; if (lock < 0) /* 0xfa is generic "unlock all" mask */ cr21 = NVReadVgaCrtc(dev, head, NV_CIO_CRE_21) | 0xfa; NVWriteVgaCrtc(dev, head, NV_CIO_CRE_21, cr21); } /* renders the extended crtc regs (cr19+) on all crtcs impervious: * immutable and unreadable */ static inline bool NVLockVgaCrtcs(struct drm_device *dev, bool lock) { struct nouveau_drm *drm = nouveau_drm(dev); bool waslocked = !NVReadVgaCrtc(dev, 0, NV_CIO_SR_LOCK_INDEX); NVWriteVgaCrtc(dev, 0, NV_CIO_SR_LOCK_INDEX, lock ? NV_CIO_SR_LOCK_VALUE : NV_CIO_SR_UNLOCK_RW_VALUE); /* NV11 has independently lockable extended crtcs, except when tied */ if (drm->client.device.info.chipset == 0x11 && !nv_heads_tied(dev)) NVWriteVgaCrtc(dev, 1, NV_CIO_SR_LOCK_INDEX, lock ? NV_CIO_SR_LOCK_VALUE : NV_CIO_SR_UNLOCK_RW_VALUE); return waslocked; } /* nv04 cursor max dimensions of 32x32 (A1R5G5B5) */ #define NV04_CURSOR_SIZE 32 /* limit nv10 cursors to 64x64 (ARGB8) (we could go to 64x255) */ #define NV10_CURSOR_SIZE 64 static inline int nv_cursor_width(struct drm_device *dev) { struct nouveau_drm *drm = nouveau_drm(dev); return drm->client.device.info.family >= NV_DEVICE_INFO_V0_CELSIUS ? NV10_CURSOR_SIZE : NV04_CURSOR_SIZE; } static inline void nv_fix_nv40_hw_cursor(struct drm_device *dev, int head) { /* on some nv40 (such as the "true" (in the NV_PFB_BOOT_0 sense) nv40, * the gf6800gt) a hardware bug requires a write to PRAMDAC_CURSOR_POS * for changes to the CRTC CURCTL regs to take effect, whether changing * the pixmap location, or just showing/hiding the cursor */ uint32_t curpos = NVReadRAMDAC(dev, head, NV_PRAMDAC_CU_START_POS); NVWriteRAMDAC(dev, head, NV_PRAMDAC_CU_START_POS, curpos); } static inline void nv_set_crtc_base(struct drm_device *dev, int head, uint32_t offset) { struct nouveau_drm *drm = nouveau_drm(dev); NVWriteCRTC(dev, head, NV_PCRTC_START, offset); if (drm->client.device.info.family == NV_DEVICE_INFO_V0_TNT) { /* * Hilarious, the 24th bit doesn't want to stick to * PCRTC_START... */ int cre_heb = NVReadVgaCrtc(dev, head, NV_CIO_CRE_HEB__INDEX); NVWriteVgaCrtc(dev, head, NV_CIO_CRE_HEB__INDEX, (cre_heb & ~0x40) | ((offset >> 18) & 0x40)); } } static inline void nv_show_cursor(struct drm_device *dev, int head, bool show) { struct nouveau_drm *drm = nouveau_drm(dev); uint8_t *curctl1 = &nv04_display(dev)->mode_reg.crtc_reg[head].CRTC[NV_CIO_CRE_HCUR_ADDR1_INDEX]; if (show) *curctl1 |= MASK(NV_CIO_CRE_HCUR_ADDR1_ENABLE); else *curctl1 &= ~MASK(NV_CIO_CRE_HCUR_ADDR1_ENABLE); NVWriteVgaCrtc(dev, head, NV_CIO_CRE_HCUR_ADDR1_INDEX, *curctl1); if (drm->client.device.info.family == NV_DEVICE_INFO_V0_CURIE) nv_fix_nv40_hw_cursor(dev, head); } static inline uint32_t nv_pitch_align(struct drm_device *dev, uint32_t width, int bpp) { struct nouveau_drm *drm = nouveau_drm(dev); int mask; if (bpp == 15) bpp = 16; if (bpp == 24) bpp = 8; /* Alignment requirements taken from the Haiku driver */ if (drm->client.device.info.family == NV_DEVICE_INFO_V0_TNT) mask = 128 / bpp - 1; else mask = 512 / bpp - 1; return (width + mask) & ~mask; } #endif /* __NOUVEAU_HW_H__ */
null
null
null
null
98,558
29,721
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
194,716
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * * Includes for cdc-acm.c * * Mainly take from usbnet's cdc-ether part * */ /* * CMSPAR, some architectures can't have space and mark parity. */ #ifndef CMSPAR #define CMSPAR 0 #endif /* * Major and minor numbers. */ #define ACM_TTY_MAJOR 166 #define ACM_TTY_MINORS 256 /* * Requests. */ #define USB_RT_ACM (USB_TYPE_CLASS | USB_RECIP_INTERFACE) /* * Output control lines. */ #define ACM_CTRL_DTR 0x01 #define ACM_CTRL_RTS 0x02 /* * Input control lines and line errors. */ #define ACM_CTRL_DCD 0x01 #define ACM_CTRL_DSR 0x02 #define ACM_CTRL_BRK 0x04 #define ACM_CTRL_RI 0x08 #define ACM_CTRL_FRAMING 0x10 #define ACM_CTRL_PARITY 0x20 #define ACM_CTRL_OVERRUN 0x40 /* * Internal driver structures. */ /* * The only reason to have several buffers is to accommodate assumptions * in line disciplines. They ask for empty space amount, receive our URB size, * and proceed to issue several 1-character writes, assuming they will fit. * The very first write takes a complete URB. Fortunately, this only happens * when processing onlcr, so we only need 2 buffers. These values must be * powers of 2. */ #define ACM_NW 16 #define ACM_NR 16 struct acm_wb { unsigned char *buf; dma_addr_t dmah; int len; int use; struct urb *urb; struct acm *instance; }; struct acm_rb { int size; unsigned char *base; dma_addr_t dma; int index; struct acm *instance; }; struct acm { struct usb_device *dev; /* the corresponding usb device */ struct usb_interface *control; /* control interface */ struct usb_interface *data; /* data interface */ unsigned in, out; /* i/o pipes */ struct tty_port port; /* our tty port data */ struct urb *ctrlurb; /* urbs */ u8 *ctrl_buffer; /* buffers of urbs */ dma_addr_t ctrl_dma; /* dma handles of buffers */ u8 *country_codes; /* country codes from device */ unsigned int country_code_size; /* size of this buffer */ unsigned int country_rel_date; /* release date of version */ struct acm_wb wb[ACM_NW]; unsigned long read_urbs_free; struct urb *read_urbs[ACM_NR]; struct acm_rb read_buffers[ACM_NR]; struct acm_wb *putbuffer; /* for acm_tty_put_char() */ int rx_buflimit; spinlock_t read_lock; int write_used; /* number of non-empty write buffers */ int transmitting; spinlock_t write_lock; struct mutex mutex; bool disconnected; unsigned long flags; # define EVENT_TTY_WAKEUP 0 # define EVENT_RX_STALL 1 struct usb_cdc_line_coding line; /* bits, stop, parity */ struct work_struct work; /* work queue entry for line discipline waking up */ unsigned int ctrlin; /* input control lines (DCD, DSR, RI, break, overruns) */ unsigned int ctrlout; /* output control lines (DTR, RTS) */ struct async_icount iocount; /* counters for control line changes */ struct async_icount oldcount; /* for comparison of counter */ wait_queue_head_t wioctl; /* for ioctl */ unsigned int writesize; /* max packet size for the output bulk endpoint */ unsigned int readsize,ctrlsize; /* buffer sizes for freeing */ unsigned int minor; /* acm minor number */ unsigned char clocal; /* termios CLOCAL */ unsigned int ctrl_caps; /* control capabilities from the class specific header */ unsigned int susp_count; /* number of suspended interfaces */ unsigned int combined_interfaces:1; /* control and data collapsed */ unsigned int throttled:1; /* actually throttled */ unsigned int throttle_req:1; /* throttle requested */ u8 bInterval; struct usb_anchor delayed; /* writes queued for a device about to be woken */ unsigned long quirks; }; #define CDC_DATA_INTERFACE_TYPE 0x0a /* constants describing various quirks and errors */ #define NO_UNION_NORMAL BIT(0) #define SINGLE_RX_URB BIT(1) #define NO_CAP_LINE BIT(2) #define NO_DATA_INTERFACE BIT(4) #define IGNORE_DEVICE BIT(5) #define QUIRK_CONTROL_LINE_STATE BIT(6) #define CLEAR_HALT_CONDITIONS BIT(7) #define SEND_ZERO_PACKET BIT(8)
null
null
null
null
103,063
29,778
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
194,773
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * sisusb - usb kernel driver for SiS315(E) based USB2VGA dongles * * VGA text mode console part * * Copyright (C) 2005 by Thomas Winischhofer, Vienna, Austria * * If distributed as part of the Linux kernel, this code is licensed under the * terms of the GPL v2. * * Otherwise, the following license terms apply: * * * 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. * * 3) The name of the author may not be used to endorse or promote products * * derived from this software without specific psisusbr written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESSED 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 AUTHOR 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: Thomas Winischhofer <thomas@winischhofer.net> * * Portions based on vgacon.c which are * Created 28 Sep 1997 by Geert Uytterhoeven * Rewritten by Martin Mares <mj@ucw.cz>, July 1998 * based on code Copyright (C) 1991, 1992 Linus Torvalds * 1995 Jay Estabrook * * A note on using in_atomic() in here: We can't handle console * calls from non-schedulable context due to our USB-dependend * nature. For now, this driver just ignores any calls if it * detects this state. * */ #include <linux/mutex.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/signal.h> #include <linux/fs.h> #include <linux/usb.h> #include <linux/tty.h> #include <linux/console.h> #include <linux/string.h> #include <linux/kd.h> #include <linux/init.h> #include <linux/vt_kern.h> #include <linux/selection.h> #include <linux/spinlock.h> #include <linux/kref.h> #include <linux/ioport.h> #include <linux/interrupt.h> #include <linux/vmalloc.h> #include "sisusb.h" #include "sisusb_init.h" #ifdef INCL_SISUSB_CON #define sisusbcon_writew(val, addr) (*(addr) = (val)) #define sisusbcon_readw(addr) (*(addr)) #define sisusbcon_memmovew(d, s, c) memmove(d, s, c) #define sisusbcon_memcpyw(d, s, c) memcpy(d, s, c) /* vc_data -> sisusb conversion table */ static struct sisusb_usb_data *mysisusbs[MAX_NR_CONSOLES]; /* Forward declaration */ static const struct consw sisusb_con; static inline void sisusbcon_memsetw(u16 *s, u16 c, unsigned int count) { count /= 2; while (count--) sisusbcon_writew(c, s++); } static inline void sisusb_initialize(struct sisusb_usb_data *sisusb) { /* Reset cursor and start address */ if (sisusb_setidxreg(sisusb, SISCR, 0x0c, 0x00)) return; if (sisusb_setidxreg(sisusb, SISCR, 0x0d, 0x00)) return; if (sisusb_setidxreg(sisusb, SISCR, 0x0e, 0x00)) return; sisusb_setidxreg(sisusb, SISCR, 0x0f, 0x00); } static inline void sisusbcon_set_start_address(struct sisusb_usb_data *sisusb, struct vc_data *c) { sisusb->cur_start_addr = (c->vc_visible_origin - sisusb->scrbuf) / 2; sisusb_setidxreg(sisusb, SISCR, 0x0c, (sisusb->cur_start_addr >> 8)); sisusb_setidxreg(sisusb, SISCR, 0x0d, (sisusb->cur_start_addr & 0xff)); } void sisusb_set_cursor(struct sisusb_usb_data *sisusb, unsigned int location) { if (sisusb->sisusb_cursor_loc == location) return; sisusb->sisusb_cursor_loc = location; /* Hardware bug: Text cursor appears twice or not at all * at some positions. Work around it with the cursor skew * bits. */ if ((location & 0x0007) == 0x0007) { sisusb->bad_cursor_pos = 1; location--; if (sisusb_setidxregandor(sisusb, SISCR, 0x0b, 0x1f, 0x20)) return; } else if (sisusb->bad_cursor_pos) { if (sisusb_setidxregand(sisusb, SISCR, 0x0b, 0x1f)) return; sisusb->bad_cursor_pos = 0; } if (sisusb_setidxreg(sisusb, SISCR, 0x0e, (location >> 8))) return; sisusb_setidxreg(sisusb, SISCR, 0x0f, (location & 0xff)); } static inline struct sisusb_usb_data * sisusb_get_sisusb(unsigned short console) { return mysisusbs[console]; } static inline int sisusb_sisusb_valid(struct sisusb_usb_data *sisusb) { if (!sisusb->present || !sisusb->ready || !sisusb->sisusb_dev) return 0; return 1; } static struct sisusb_usb_data * sisusb_get_sisusb_lock_and_check(unsigned short console) { struct sisusb_usb_data *sisusb; /* We can't handle console calls in non-schedulable * context due to our locks and the USB transport. * So we simply ignore them. This should only affect * some calls to printk. */ if (in_atomic()) return NULL; sisusb = sisusb_get_sisusb(console); if (!sisusb) return NULL; mutex_lock(&sisusb->lock); if (!sisusb_sisusb_valid(sisusb) || !sisusb->havethisconsole[console]) { mutex_unlock(&sisusb->lock); return NULL; } return sisusb; } static int sisusb_is_inactive(struct vc_data *c, struct sisusb_usb_data *sisusb) { if (sisusb->is_gfx || sisusb->textmodedestroyed || c->vc_mode != KD_TEXT) return 1; return 0; } /* con_startup console interface routine */ static const char * sisusbcon_startup(void) { return "SISUSBCON"; } /* con_init console interface routine */ static void sisusbcon_init(struct vc_data *c, int init) { struct sisusb_usb_data *sisusb; int cols, rows; /* This is called by do_take_over_console(), * ie by us/under our control. It is * only called after text mode and fonts * are set up/restored. */ sisusb = sisusb_get_sisusb(c->vc_num); if (!sisusb) return; mutex_lock(&sisusb->lock); if (!sisusb_sisusb_valid(sisusb)) { mutex_unlock(&sisusb->lock); return; } c->vc_can_do_color = 1; c->vc_complement_mask = 0x7700; c->vc_hi_font_mask = sisusb->current_font_512 ? 0x0800 : 0; sisusb->haveconsole = 1; sisusb->havethisconsole[c->vc_num] = 1; /* We only support 640x400 */ c->vc_scan_lines = 400; c->vc_font.height = sisusb->current_font_height; /* We only support width = 8 */ cols = 80; rows = c->vc_scan_lines / c->vc_font.height; /* Increment usage count for our sisusb. * Doing so saves us from upping/downing * the disconnect semaphore; we can't * lose our sisusb until this is undone * in con_deinit. For all other console * interface functions, it suffices to * use sisusb->lock and do a quick check * of sisusb for device disconnection. */ kref_get(&sisusb->kref); if (!*c->vc_uni_pagedir_loc) con_set_default_unimap(c); mutex_unlock(&sisusb->lock); if (init) { c->vc_cols = cols; c->vc_rows = rows; } else vc_resize(c, cols, rows); } /* con_deinit console interface routine */ static void sisusbcon_deinit(struct vc_data *c) { struct sisusb_usb_data *sisusb; int i; /* This is called by do_take_over_console() * and others, ie not under our control. */ sisusb = sisusb_get_sisusb(c->vc_num); if (!sisusb) return; mutex_lock(&sisusb->lock); /* Clear ourselves in mysisusbs */ mysisusbs[c->vc_num] = NULL; sisusb->havethisconsole[c->vc_num] = 0; /* Free our font buffer if all consoles are gone */ if (sisusb->font_backup) { for(i = 0; i < MAX_NR_CONSOLES; i++) { if (sisusb->havethisconsole[c->vc_num]) break; } if (i == MAX_NR_CONSOLES) { vfree(sisusb->font_backup); sisusb->font_backup = NULL; } } mutex_unlock(&sisusb->lock); /* decrement the usage count on our sisusb */ kref_put(&sisusb->kref, sisusb_delete); } /* interface routine */ static u8 sisusbcon_build_attr(struct vc_data *c, u8 color, u8 intensity, u8 blink, u8 underline, u8 reverse, u8 unused) { u8 attr = color; if (underline) attr = (attr & 0xf0) | c->vc_ulcolor; else if (intensity == 0) attr = (attr & 0xf0) | c->vc_halfcolor; if (reverse) attr = ((attr) & 0x88) | ((((attr) >> 4) | ((attr) << 4)) & 0x77); if (blink) attr ^= 0x80; if (intensity == 2) attr ^= 0x08; return attr; } /* Interface routine */ static void sisusbcon_invert_region(struct vc_data *vc, u16 *p, int count) { /* Invert a region. This is called with a pointer * to the console's internal screen buffer. So we * simply do the inversion there and rely on * a call to putc(s) to update the real screen. */ while (count--) { u16 a = sisusbcon_readw(p); a = ((a) & 0x88ff) | (((a) & 0x7000) >> 4) | (((a) & 0x0700) << 4); sisusbcon_writew(a, p++); } } #define SISUSB_VADDR(x,y) \ ((u16 *)c->vc_origin + \ (y) * sisusb->sisusb_num_columns + \ (x)) #define SISUSB_HADDR(x,y) \ ((u16 *)(sisusb->vrambase + (c->vc_origin - sisusb->scrbuf)) + \ (y) * sisusb->sisusb_num_columns + \ (x)) /* Interface routine */ static void sisusbcon_putc(struct vc_data *c, int ch, int y, int x) { struct sisusb_usb_data *sisusb; sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num); if (!sisusb) return; /* sisusb->lock is down */ if (sisusb_is_inactive(c, sisusb)) { mutex_unlock(&sisusb->lock); return; } sisusb_copy_memory(sisusb, (char *)SISUSB_VADDR(x, y), (long)SISUSB_HADDR(x, y), 2); mutex_unlock(&sisusb->lock); } /* Interface routine */ static void sisusbcon_putcs(struct vc_data *c, const unsigned short *s, int count, int y, int x) { struct sisusb_usb_data *sisusb; u16 *dest; int i; sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num); if (!sisusb) return; /* sisusb->lock is down */ /* Need to put the characters into the buffer ourselves, * because the vt does this AFTER calling us. */ dest = SISUSB_VADDR(x, y); for (i = count; i > 0; i--) sisusbcon_writew(sisusbcon_readw(s++), dest++); if (sisusb_is_inactive(c, sisusb)) { mutex_unlock(&sisusb->lock); return; } sisusb_copy_memory(sisusb, (char *)SISUSB_VADDR(x, y), (long)SISUSB_HADDR(x, y), count * 2); mutex_unlock(&sisusb->lock); } /* Interface routine */ static void sisusbcon_clear(struct vc_data *c, int y, int x, int height, int width) { struct sisusb_usb_data *sisusb; u16 eattr = c->vc_video_erase_char; int i, length, cols; u16 *dest; if (width <= 0 || height <= 0) return; sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num); if (!sisusb) return; /* sisusb->lock is down */ /* Need to clear buffer ourselves, because the vt does * this AFTER calling us. */ dest = SISUSB_VADDR(x, y); cols = sisusb->sisusb_num_columns; if (width > cols) width = cols; if (x == 0 && width >= c->vc_cols) { sisusbcon_memsetw(dest, eattr, height * cols * 2); } else { for (i = height; i > 0; i--, dest += cols) sisusbcon_memsetw(dest, eattr, width * 2); } if (sisusb_is_inactive(c, sisusb)) { mutex_unlock(&sisusb->lock); return; } length = ((height * cols) - x - (cols - width - x)) * 2; sisusb_copy_memory(sisusb, (unsigned char *)SISUSB_VADDR(x, y), (long)SISUSB_HADDR(x, y), length); mutex_unlock(&sisusb->lock); } /* interface routine */ static int sisusbcon_switch(struct vc_data *c) { struct sisusb_usb_data *sisusb; int length; /* Returnvalue 0 means we have fully restored screen, * and vt doesn't need to call do_update_region(). * Returnvalue != 0 naturally means the opposite. */ sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num); if (!sisusb) return 0; /* sisusb->lock is down */ /* Don't write to screen if in gfx mode */ if (sisusb_is_inactive(c, sisusb)) { mutex_unlock(&sisusb->lock); return 0; } /* That really should not happen. It would mean we are * being called while the vc is using its private buffer * as origin. */ if (c->vc_origin == (unsigned long)c->vc_screenbuf) { mutex_unlock(&sisusb->lock); dev_dbg(&sisusb->sisusb_dev->dev, "ASSERT ORIGIN != SCREENBUF!\n"); return 0; } /* Check that we don't copy too much */ length = min((int)c->vc_screenbuf_size, (int)(sisusb->scrbuf + sisusb->scrbuf_size - c->vc_origin)); /* Restore the screen contents */ sisusbcon_memcpyw((u16 *)c->vc_origin, (u16 *)c->vc_screenbuf, length); sisusb_copy_memory(sisusb, (unsigned char *)c->vc_origin, (long)SISUSB_HADDR(0, 0), length); mutex_unlock(&sisusb->lock); return 0; } /* interface routine */ static void sisusbcon_save_screen(struct vc_data *c) { struct sisusb_usb_data *sisusb; int length; /* Save the current screen contents to vc's private * buffer. */ sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num); if (!sisusb) return; /* sisusb->lock is down */ if (sisusb_is_inactive(c, sisusb)) { mutex_unlock(&sisusb->lock); return; } /* Check that we don't copy too much */ length = min((int)c->vc_screenbuf_size, (int)(sisusb->scrbuf + sisusb->scrbuf_size - c->vc_origin)); /* Save the screen contents to vc's private buffer */ sisusbcon_memcpyw((u16 *)c->vc_screenbuf, (u16 *)c->vc_origin, length); mutex_unlock(&sisusb->lock); } /* interface routine */ static void sisusbcon_set_palette(struct vc_data *c, const unsigned char *table) { struct sisusb_usb_data *sisusb; int i, j; /* Return value not used by vt */ if (!con_is_visible(c)) return; sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num); if (!sisusb) return; /* sisusb->lock is down */ if (sisusb_is_inactive(c, sisusb)) { mutex_unlock(&sisusb->lock); return; } for (i = j = 0; i < 16; i++) { if (sisusb_setreg(sisusb, SISCOLIDX, table[i])) break; if (sisusb_setreg(sisusb, SISCOLDATA, c->vc_palette[j++] >> 2)) break; if (sisusb_setreg(sisusb, SISCOLDATA, c->vc_palette[j++] >> 2)) break; if (sisusb_setreg(sisusb, SISCOLDATA, c->vc_palette[j++] >> 2)) break; } mutex_unlock(&sisusb->lock); } /* interface routine */ static int sisusbcon_blank(struct vc_data *c, int blank, int mode_switch) { struct sisusb_usb_data *sisusb; u8 sr1, cr17, pmreg, cr63; int ret = 0; sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num); if (!sisusb) return 0; /* sisusb->lock is down */ if (mode_switch) sisusb->is_gfx = blank ? 1 : 0; if (sisusb_is_inactive(c, sisusb)) { mutex_unlock(&sisusb->lock); return 0; } switch (blank) { case 1: /* Normal blanking: Clear screen */ case -1: sisusbcon_memsetw((u16 *)c->vc_origin, c->vc_video_erase_char, c->vc_screenbuf_size); sisusb_copy_memory(sisusb, (unsigned char *)c->vc_origin, (u32)(sisusb->vrambase + (c->vc_origin - sisusb->scrbuf)), c->vc_screenbuf_size); sisusb->con_blanked = 1; ret = 1; break; default: /* VESA blanking */ switch (blank) { case 0: /* Unblank */ sr1 = 0x00; cr17 = 0x80; pmreg = 0x00; cr63 = 0x00; ret = 1; sisusb->con_blanked = 0; break; case VESA_VSYNC_SUSPEND + 1: sr1 = 0x20; cr17 = 0x80; pmreg = 0x80; cr63 = 0x40; break; case VESA_HSYNC_SUSPEND + 1: sr1 = 0x20; cr17 = 0x80; pmreg = 0x40; cr63 = 0x40; break; case VESA_POWERDOWN + 1: sr1 = 0x20; cr17 = 0x00; pmreg = 0xc0; cr63 = 0x40; break; default: mutex_unlock(&sisusb->lock); return -EINVAL; } sisusb_setidxregandor(sisusb, SISSR, 0x01, ~0x20, sr1); sisusb_setidxregandor(sisusb, SISCR, 0x17, 0x7f, cr17); sisusb_setidxregandor(sisusb, SISSR, 0x1f, 0x3f, pmreg); sisusb_setidxregandor(sisusb, SISCR, 0x63, 0xbf, cr63); } mutex_unlock(&sisusb->lock); return ret; } /* interface routine */ static void sisusbcon_scrolldelta(struct vc_data *c, int lines) { struct sisusb_usb_data *sisusb; sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num); if (!sisusb) return; /* sisusb->lock is down */ if (sisusb_is_inactive(c, sisusb)) { mutex_unlock(&sisusb->lock); return; } vc_scrolldelta_helper(c, lines, sisusb->con_rolled_over, (void *)sisusb->scrbuf, sisusb->scrbuf_size); sisusbcon_set_start_address(sisusb, c); mutex_unlock(&sisusb->lock); } /* Interface routine */ static void sisusbcon_cursor(struct vc_data *c, int mode) { struct sisusb_usb_data *sisusb; int from, to, baseline; sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num); if (!sisusb) return; /* sisusb->lock is down */ if (sisusb_is_inactive(c, sisusb)) { mutex_unlock(&sisusb->lock); return; } if (c->vc_origin != c->vc_visible_origin) { c->vc_visible_origin = c->vc_origin; sisusbcon_set_start_address(sisusb, c); } if (mode == CM_ERASE) { sisusb_setidxregor(sisusb, SISCR, 0x0a, 0x20); sisusb->sisusb_cursor_size_to = -1; mutex_unlock(&sisusb->lock); return; } sisusb_set_cursor(sisusb, (c->vc_pos - sisusb->scrbuf) / 2); baseline = c->vc_font.height - (c->vc_font.height < 10 ? 1 : 2); switch (c->vc_cursor_type & 0x0f) { case CUR_BLOCK: from = 1; to = c->vc_font.height; break; case CUR_TWO_THIRDS: from = c->vc_font.height / 3; to = baseline; break; case CUR_LOWER_HALF: from = c->vc_font.height / 2; to = baseline; break; case CUR_LOWER_THIRD: from = (c->vc_font.height * 2) / 3; to = baseline; break; case CUR_NONE: from = 31; to = 30; break; default: case CUR_UNDERLINE: from = baseline - 1; to = baseline; break; } if (sisusb->sisusb_cursor_size_from != from || sisusb->sisusb_cursor_size_to != to) { sisusb_setidxreg(sisusb, SISCR, 0x0a, from); sisusb_setidxregandor(sisusb, SISCR, 0x0b, 0xe0, to); sisusb->sisusb_cursor_size_from = from; sisusb->sisusb_cursor_size_to = to; } mutex_unlock(&sisusb->lock); } static bool sisusbcon_scroll_area(struct vc_data *c, struct sisusb_usb_data *sisusb, unsigned int t, unsigned int b, enum con_scroll dir, unsigned int lines) { int cols = sisusb->sisusb_num_columns; int length = ((b - t) * cols) * 2; u16 eattr = c->vc_video_erase_char; /* sisusb->lock is down */ /* Scroll an area which does not match the * visible screen's dimensions. This needs * to be done separately, as it does not * use hardware panning. */ switch (dir) { case SM_UP: sisusbcon_memmovew(SISUSB_VADDR(0, t), SISUSB_VADDR(0, t + lines), (b - t - lines) * cols * 2); sisusbcon_memsetw(SISUSB_VADDR(0, b - lines), eattr, lines * cols * 2); break; case SM_DOWN: sisusbcon_memmovew(SISUSB_VADDR(0, t + lines), SISUSB_VADDR(0, t), (b - t - lines) * cols * 2); sisusbcon_memsetw(SISUSB_VADDR(0, t), eattr, lines * cols * 2); break; } sisusb_copy_memory(sisusb, (char *)SISUSB_VADDR(0, t), (long)SISUSB_HADDR(0, t), length); mutex_unlock(&sisusb->lock); return 1; } /* Interface routine */ static bool sisusbcon_scroll(struct vc_data *c, unsigned int t, unsigned int b, enum con_scroll dir, unsigned int lines) { struct sisusb_usb_data *sisusb; u16 eattr = c->vc_video_erase_char; int copyall = 0; unsigned long oldorigin; unsigned int delta = lines * c->vc_size_row; u32 originoffset; /* Returning != 0 means we have done the scrolling successfully. * Returning 0 makes vt do the scrolling on its own. * Note that con_scroll is only called if the console is * visible. In that case, the origin should be our buffer, * not the vt's private one. */ if (!lines) return true; sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num); if (!sisusb) return false; /* sisusb->lock is down */ if (sisusb_is_inactive(c, sisusb)) { mutex_unlock(&sisusb->lock); return false; } /* Special case */ if (t || b != c->vc_rows) return sisusbcon_scroll_area(c, sisusb, t, b, dir, lines); if (c->vc_origin != c->vc_visible_origin) { c->vc_visible_origin = c->vc_origin; sisusbcon_set_start_address(sisusb, c); } /* limit amount to maximum realistic size */ if (lines > c->vc_rows) lines = c->vc_rows; oldorigin = c->vc_origin; switch (dir) { case SM_UP: if (c->vc_scr_end + delta >= sisusb->scrbuf + sisusb->scrbuf_size) { sisusbcon_memcpyw((u16 *)sisusb->scrbuf, (u16 *)(oldorigin + delta), c->vc_screenbuf_size - delta); c->vc_origin = sisusb->scrbuf; sisusb->con_rolled_over = oldorigin - sisusb->scrbuf; copyall = 1; } else c->vc_origin += delta; sisusbcon_memsetw( (u16 *)(c->vc_origin + c->vc_screenbuf_size - delta), eattr, delta); break; case SM_DOWN: if (oldorigin - delta < sisusb->scrbuf) { sisusbcon_memmovew((u16 *)(sisusb->scrbuf + sisusb->scrbuf_size - c->vc_screenbuf_size + delta), (u16 *)oldorigin, c->vc_screenbuf_size - delta); c->vc_origin = sisusb->scrbuf + sisusb->scrbuf_size - c->vc_screenbuf_size; sisusb->con_rolled_over = 0; copyall = 1; } else c->vc_origin -= delta; c->vc_scr_end = c->vc_origin + c->vc_screenbuf_size; scr_memsetw((u16 *)(c->vc_origin), eattr, delta); break; } originoffset = (u32)(c->vc_origin - sisusb->scrbuf); if (copyall) sisusb_copy_memory(sisusb, (char *)c->vc_origin, (u32)(sisusb->vrambase + originoffset), c->vc_screenbuf_size); else if (dir == SM_UP) sisusb_copy_memory(sisusb, (char *)c->vc_origin + c->vc_screenbuf_size - delta, (u32)sisusb->vrambase + originoffset + c->vc_screenbuf_size - delta, delta); else sisusb_copy_memory(sisusb, (char *)c->vc_origin, (u32)(sisusb->vrambase + originoffset), delta); c->vc_scr_end = c->vc_origin + c->vc_screenbuf_size; c->vc_visible_origin = c->vc_origin; sisusbcon_set_start_address(sisusb, c); c->vc_pos = c->vc_pos - oldorigin + c->vc_origin; mutex_unlock(&sisusb->lock); return true; } /* Interface routine */ static int sisusbcon_set_origin(struct vc_data *c) { struct sisusb_usb_data *sisusb; /* Returning != 0 means we were successful. * Returning 0 will vt make to use its own * screenbuffer as the origin. */ sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num); if (!sisusb) return 0; /* sisusb->lock is down */ if (sisusb_is_inactive(c, sisusb) || sisusb->con_blanked) { mutex_unlock(&sisusb->lock); return 0; } c->vc_origin = c->vc_visible_origin = sisusb->scrbuf; sisusbcon_set_start_address(sisusb, c); sisusb->con_rolled_over = 0; mutex_unlock(&sisusb->lock); return 1; } /* Interface routine */ static int sisusbcon_resize(struct vc_data *c, unsigned int newcols, unsigned int newrows, unsigned int user) { struct sisusb_usb_data *sisusb; int fh; sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num); if (!sisusb) return -ENODEV; fh = sisusb->current_font_height; mutex_unlock(&sisusb->lock); /* We are quite unflexible as regards resizing. The vt code * handles sizes where the line length isn't equal the pitch * quite badly. As regards the rows, our panning tricks only * work well if the number of rows equals the visible number * of rows. */ if (newcols != 80 || c->vc_scan_lines / fh != newrows) return -EINVAL; return 0; } int sisusbcon_do_font_op(struct sisusb_usb_data *sisusb, int set, int slot, u8 *arg, int cmapsz, int ch512, int dorecalc, struct vc_data *c, int fh, int uplock) { int font_select = 0x00, i, err = 0; u32 offset = 0; u8 dummy; /* sisusb->lock is down */ /* * The default font is kept in slot 0. * A user font is loaded in slot 2 (256 ch) * or 2+3 (512 ch). */ if ((slot != 0 && slot != 2) || !fh) { if (uplock) mutex_unlock(&sisusb->lock); return -EINVAL; } if (set) sisusb->font_slot = slot; /* Default font is always 256 */ if (slot == 0) ch512 = 0; else offset = 4 * cmapsz; font_select = (slot == 0) ? 0x00 : (ch512 ? 0x0e : 0x0a); err |= sisusb_setidxreg(sisusb, SISSR, 0x00, 0x01); /* Reset */ err |= sisusb_setidxreg(sisusb, SISSR, 0x02, 0x04); /* Write to plane 2 */ err |= sisusb_setidxreg(sisusb, SISSR, 0x04, 0x07); /* Memory mode a0-bf */ err |= sisusb_setidxreg(sisusb, SISSR, 0x00, 0x03); /* Reset */ if (err) goto font_op_error; err |= sisusb_setidxreg(sisusb, SISGR, 0x04, 0x03); /* Select plane read 2 */ err |= sisusb_setidxreg(sisusb, SISGR, 0x05, 0x00); /* Disable odd/even */ err |= sisusb_setidxreg(sisusb, SISGR, 0x06, 0x00); /* Address range a0-bf */ if (err) goto font_op_error; if (arg) { if (set) for (i = 0; i < cmapsz; i++) { err |= sisusb_writeb(sisusb, sisusb->vrambase + offset + i, arg[i]); if (err) break; } else for (i = 0; i < cmapsz; i++) { err |= sisusb_readb(sisusb, sisusb->vrambase + offset + i, &arg[i]); if (err) break; } /* * In 512-character mode, the character map is not contiguous if * we want to remain EGA compatible -- which we do */ if (ch512) { if (set) for (i = 0; i < cmapsz; i++) { err |= sisusb_writeb(sisusb, sisusb->vrambase + offset + (2 * cmapsz) + i, arg[cmapsz + i]); if (err) break; } else for (i = 0; i < cmapsz; i++) { err |= sisusb_readb(sisusb, sisusb->vrambase + offset + (2 * cmapsz) + i, &arg[cmapsz + i]); if (err) break; } } } if (err) goto font_op_error; err |= sisusb_setidxreg(sisusb, SISSR, 0x00, 0x01); /* Reset */ err |= sisusb_setidxreg(sisusb, SISSR, 0x02, 0x03); /* Write to planes 0+1 */ err |= sisusb_setidxreg(sisusb, SISSR, 0x04, 0x03); /* Memory mode a0-bf */ if (set) sisusb_setidxreg(sisusb, SISSR, 0x03, font_select); err |= sisusb_setidxreg(sisusb, SISSR, 0x00, 0x03); /* Reset end */ if (err) goto font_op_error; err |= sisusb_setidxreg(sisusb, SISGR, 0x04, 0x00); /* Select plane read 0 */ err |= sisusb_setidxreg(sisusb, SISGR, 0x05, 0x10); /* Enable odd/even */ err |= sisusb_setidxreg(sisusb, SISGR, 0x06, 0x06); /* Address range b8-bf */ if (err) goto font_op_error; if ((set) && (ch512 != sisusb->current_font_512)) { /* Font is shared among all our consoles. * And so is the hi_font_mask. */ for (i = 0; i < MAX_NR_CONSOLES; i++) { struct vc_data *d = vc_cons[i].d; if (d && d->vc_sw == &sisusb_con) d->vc_hi_font_mask = ch512 ? 0x0800 : 0; } sisusb->current_font_512 = ch512; /* color plane enable register: 256-char: enable intensity bit 512-char: disable intensity bit */ sisusb_getreg(sisusb, SISINPSTAT, &dummy); sisusb_setreg(sisusb, SISAR, 0x12); sisusb_setreg(sisusb, SISAR, ch512 ? 0x07 : 0x0f); sisusb_getreg(sisusb, SISINPSTAT, &dummy); sisusb_setreg(sisusb, SISAR, 0x20); sisusb_getreg(sisusb, SISINPSTAT, &dummy); } if (dorecalc) { /* * Adjust the screen to fit a font of a certain height */ unsigned char ovr, vde, fsr; int rows = 0, maxscan = 0; if (c) { /* Number of video rows */ rows = c->vc_scan_lines / fh; /* Scan lines to actually display-1 */ maxscan = rows * fh - 1; /*printk(KERN_DEBUG "sisusb recalc rows %d maxscan %d fh %d sl %d\n", rows, maxscan, fh, c->vc_scan_lines);*/ sisusb_getidxreg(sisusb, SISCR, 0x07, &ovr); vde = maxscan & 0xff; ovr = (ovr & 0xbd) | ((maxscan & 0x100) >> 7) | ((maxscan & 0x200) >> 3); sisusb_setidxreg(sisusb, SISCR, 0x07, ovr); sisusb_setidxreg(sisusb, SISCR, 0x12, vde); } sisusb_getidxreg(sisusb, SISCR, 0x09, &fsr); fsr = (fsr & 0xe0) | (fh - 1); sisusb_setidxreg(sisusb, SISCR, 0x09, fsr); sisusb->current_font_height = fh; sisusb->sisusb_cursor_size_from = -1; sisusb->sisusb_cursor_size_to = -1; } if (uplock) mutex_unlock(&sisusb->lock); if (dorecalc && c) { int rows = c->vc_scan_lines / fh; /* Now adjust our consoles' size */ for (i = 0; i < MAX_NR_CONSOLES; i++) { struct vc_data *vc = vc_cons[i].d; if (vc && vc->vc_sw == &sisusb_con) { if (con_is_visible(vc)) { vc->vc_sw->con_cursor(vc, CM_DRAW); } vc->vc_font.height = fh; vc_resize(vc, 0, rows); } } } return 0; font_op_error: if (uplock) mutex_unlock(&sisusb->lock); return -EIO; } /* Interface routine */ static int sisusbcon_font_set(struct vc_data *c, struct console_font *font, unsigned flags) { struct sisusb_usb_data *sisusb; unsigned charcount = font->charcount; if (font->width != 8 || (charcount != 256 && charcount != 512)) return -EINVAL; sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num); if (!sisusb) return -ENODEV; /* sisusb->lock is down */ /* Save the user-provided font into a buffer. This * is used for restoring text mode after quitting * from X and for the con_getfont routine. */ if (sisusb->font_backup) { if (sisusb->font_backup_size < charcount) { vfree(sisusb->font_backup); sisusb->font_backup = NULL; } } if (!sisusb->font_backup) sisusb->font_backup = vmalloc(charcount * 32); if (sisusb->font_backup) { memcpy(sisusb->font_backup, font->data, charcount * 32); sisusb->font_backup_size = charcount; sisusb->font_backup_height = font->height; sisusb->font_backup_512 = (charcount == 512) ? 1 : 0; } /* do_font_op ups sisusb->lock */ return sisusbcon_do_font_op(sisusb, 1, 2, font->data, 8192, (charcount == 512), (!(flags & KD_FONT_FLAG_DONT_RECALC)) ? 1 : 0, c, font->height, 1); } /* Interface routine */ static int sisusbcon_font_get(struct vc_data *c, struct console_font *font) { struct sisusb_usb_data *sisusb; sisusb = sisusb_get_sisusb_lock_and_check(c->vc_num); if (!sisusb) return -ENODEV; /* sisusb->lock is down */ font->width = 8; font->height = c->vc_font.height; font->charcount = 256; if (!font->data) { mutex_unlock(&sisusb->lock); return 0; } if (!sisusb->font_backup) { mutex_unlock(&sisusb->lock); return -ENODEV; } /* Copy 256 chars only, like vgacon */ memcpy(font->data, sisusb->font_backup, 256 * 32); mutex_unlock(&sisusb->lock); return 0; } /* * The console `switch' structure for the sisusb console */ static const struct consw sisusb_con = { .owner = THIS_MODULE, .con_startup = sisusbcon_startup, .con_init = sisusbcon_init, .con_deinit = sisusbcon_deinit, .con_clear = sisusbcon_clear, .con_putc = sisusbcon_putc, .con_putcs = sisusbcon_putcs, .con_cursor = sisusbcon_cursor, .con_scroll = sisusbcon_scroll, .con_switch = sisusbcon_switch, .con_blank = sisusbcon_blank, .con_font_set = sisusbcon_font_set, .con_font_get = sisusbcon_font_get, .con_set_palette = sisusbcon_set_palette, .con_scrolldelta = sisusbcon_scrolldelta, .con_build_attr = sisusbcon_build_attr, .con_invert_region = sisusbcon_invert_region, .con_set_origin = sisusbcon_set_origin, .con_save_screen = sisusbcon_save_screen, .con_resize = sisusbcon_resize, }; /* Our very own dummy console driver */ static const char *sisusbdummycon_startup(void) { return "SISUSBVGADUMMY"; } static void sisusbdummycon_init(struct vc_data *vc, int init) { vc->vc_can_do_color = 1; if (init) { vc->vc_cols = 80; vc->vc_rows = 25; } else vc_resize(vc, 80, 25); } static int sisusbdummycon_dummy(void) { return 0; } #define SISUSBCONDUMMY (void *)sisusbdummycon_dummy static const struct consw sisusb_dummy_con = { .owner = THIS_MODULE, .con_startup = sisusbdummycon_startup, .con_init = sisusbdummycon_init, .con_deinit = SISUSBCONDUMMY, .con_clear = SISUSBCONDUMMY, .con_putc = SISUSBCONDUMMY, .con_putcs = SISUSBCONDUMMY, .con_cursor = SISUSBCONDUMMY, .con_scroll = SISUSBCONDUMMY, .con_switch = SISUSBCONDUMMY, .con_blank = SISUSBCONDUMMY, .con_font_set = SISUSBCONDUMMY, .con_font_get = SISUSBCONDUMMY, .con_font_default = SISUSBCONDUMMY, .con_font_copy = SISUSBCONDUMMY, }; int sisusb_console_init(struct sisusb_usb_data *sisusb, int first, int last) { int i, ret; mutex_lock(&sisusb->lock); /* Erm.. that should not happen */ if (sisusb->haveconsole || !sisusb->SiS_Pr) { mutex_unlock(&sisusb->lock); return 1; } sisusb->con_first = first; sisusb->con_last = last; if (first > last || first > MAX_NR_CONSOLES || last > MAX_NR_CONSOLES) { mutex_unlock(&sisusb->lock); return 1; } /* If gfxcore not initialized or no consoles given, quit graciously */ if (!sisusb->gfxinit || first < 1 || last < 1) { mutex_unlock(&sisusb->lock); return 0; } sisusb->sisusb_cursor_loc = -1; sisusb->sisusb_cursor_size_from = -1; sisusb->sisusb_cursor_size_to = -1; /* Set up text mode (and upload default font) */ if (sisusb_reset_text_mode(sisusb, 1)) { mutex_unlock(&sisusb->lock); dev_err(&sisusb->sisusb_dev->dev, "Failed to set up text mode\n"); return 1; } /* Initialize some gfx registers */ sisusb_initialize(sisusb); for (i = first - 1; i <= last - 1; i++) { /* Save sisusb for our interface routines */ mysisusbs[i] = sisusb; } /* Initial console setup */ sisusb->sisusb_num_columns = 80; /* Use a 32K buffer (matches b8000-bffff area) */ sisusb->scrbuf_size = 32 * 1024; /* Allocate screen buffer */ if (!(sisusb->scrbuf = (unsigned long)vmalloc(sisusb->scrbuf_size))) { mutex_unlock(&sisusb->lock); dev_err(&sisusb->sisusb_dev->dev, "Failed to allocate screen buffer\n"); return 1; } mutex_unlock(&sisusb->lock); /* Now grab the desired console(s) */ console_lock(); ret = do_take_over_console(&sisusb_con, first - 1, last - 1, 0); console_unlock(); if (!ret) sisusb->haveconsole = 1; else { for (i = first - 1; i <= last - 1; i++) mysisusbs[i] = NULL; } return ret; } void sisusb_console_exit(struct sisusb_usb_data *sisusb) { int i; /* This is called if the device is disconnected * and while disconnect and lock semaphores * are up. This should be save because we * can't lose our sisusb any other way but by * disconnection (and hence, the disconnect * sema is for protecting all other access * functions from disconnection, not the * other way round). */ /* Now what do we do in case of disconnection: * One alternative would be to simply call * give_up_console(). Nah, not a good idea. * give_up_console() is obviously buggy as it * only discards the consw pointer from the * driver_map, but doesn't adapt vc->vc_sw * of the affected consoles. Hence, the next * call to any of the console functions will * eventually take a trip to oops county. * Also, give_up_console for some reason * doesn't decrement our module refcount. * Instead, we switch our consoles to a private * dummy console. This, of course, keeps our * refcount up as well, but it works perfectly. */ if (sisusb->haveconsole) { for (i = 0; i < MAX_NR_CONSOLES; i++) if (sisusb->havethisconsole[i]) { console_lock(); do_take_over_console(&sisusb_dummy_con, i, i, 0); console_unlock(); /* At this point, con_deinit for all our * consoles is executed by do_take_over_console(). */ } sisusb->haveconsole = 0; } vfree((void *)sisusb->scrbuf); sisusb->scrbuf = 0; vfree(sisusb->font_backup); sisusb->font_backup = NULL; } void __init sisusb_init_concode(void) { int i; for (i = 0; i < MAX_NR_CONSOLES; i++) mysisusbs[i] = NULL; } #endif /* INCL_CON */
null
null
null
null
103,120
4,367
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
169,362
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* -*- mode: c; c-basic-offset: 8; -*- * vim: noexpandtab sw=8 ts=8 sts=0: * * acl.h * * Copyright (C) 2004, 2008 Oracle. 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 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 OCFS2_ACL_H #define OCFS2_ACL_H #include <linux/posix_acl_xattr.h> struct ocfs2_acl_entry { __le16 e_tag; __le16 e_perm; __le32 e_id; }; struct posix_acl *ocfs2_iop_get_acl(struct inode *inode, int type); int ocfs2_iop_set_acl(struct inode *inode, struct posix_acl *acl, int type); int ocfs2_set_acl(handle_t *handle, struct inode *inode, struct buffer_head *di_bh, int type, struct posix_acl *acl, struct ocfs2_alloc_context *meta_ac, struct ocfs2_alloc_context *data_ac); extern int ocfs2_acl_chmod(struct inode *, struct buffer_head *); extern int ocfs2_init_acl(handle_t *, struct inode *, struct inode *, struct buffer_head *, struct buffer_head *, struct ocfs2_alloc_context *, struct ocfs2_alloc_context *); #endif /* OCFS2_ACL_H */
null
null
null
null
77,709
6,583
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
171,578
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Copyright (C) 2004-2006 Atmel Corporation * * 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. */ #ifndef _UAPI__ASM_AVR32_TERMIOS_H #define _UAPI__ASM_AVR32_TERMIOS_H #include <asm/termbits.h> #include <asm/ioctls.h> struct winsize { unsigned short ws_row; unsigned short ws_col; unsigned short ws_xpixel; unsigned short ws_ypixel; }; #define NCC 8 struct termio { unsigned short c_iflag; /* input mode flags */ unsigned short c_oflag; /* output mode flags */ unsigned short c_cflag; /* control mode flags */ unsigned short c_lflag; /* local mode flags */ unsigned char c_line; /* line discipline */ unsigned char c_cc[NCC]; /* control characters */ }; /* modem lines */ #define TIOCM_LE 0x001 #define TIOCM_DTR 0x002 #define TIOCM_RTS 0x004 #define TIOCM_ST 0x008 #define TIOCM_SR 0x010 #define TIOCM_CTS 0x020 #define TIOCM_CAR 0x040 #define TIOCM_RNG 0x080 #define TIOCM_DSR 0x100 #define TIOCM_CD TIOCM_CAR #define TIOCM_RI TIOCM_RNG #define TIOCM_OUT1 0x2000 #define TIOCM_OUT2 0x4000 #define TIOCM_LOOP 0x8000 /* ioctl (fd, TIOCSERGETLSR, &result) where result may be as below */ #endif /* _UAPI__ASM_AVR32_TERMIOS_H */
null
null
null
null
79,925
31,281
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
31,281
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/timing/performance_navigation_timing.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/mojom/page/page_visibility_state.mojom-blink.h" #include "third_party/blink/renderer/core/testing/page_test_base.h" namespace blink { class PerformanceNavigationTimingTest : public PageTestBase { protected: AtomicString GetNavigationType(NavigationType type, Document* document) { return PerformanceNavigationTiming::GetNavigationType(type, document); } }; TEST_F(PerformanceNavigationTimingTest, GetNavigationType) { GetPage().SetVisibilityState(mojom::PageVisibilityState::kPrerender, false); AtomicString returned_type = GetNavigationType(kNavigationTypeBackForward, &GetDocument()); EXPECT_EQ(returned_type, "prerender"); GetPage().SetVisibilityState(mojom::PageVisibilityState::kHidden, false); returned_type = GetNavigationType(kNavigationTypeBackForward, &GetDocument()); EXPECT_EQ(returned_type, "back_forward"); GetPage().SetVisibilityState(mojom::PageVisibilityState::kVisible, false); returned_type = GetNavigationType(kNavigationTypeFormResubmitted, &GetDocument()); EXPECT_EQ(returned_type, "navigate"); } } // namespace blink
null
null
null
null
28,144
61,930
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
61,930
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_SUPERVISED_USER_LEGACY_SUPERVISED_USER_PREF_MAPPING_SERVICE_FACTORY_H_ #define CHROME_BROWSER_SUPERVISED_USER_LEGACY_SUPERVISED_USER_PREF_MAPPING_SERVICE_FACTORY_H_ #include "base/memory/singleton.h" #include "chrome/browser/supervised_user/supervised_users.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" class SupervisedUserPrefMappingService; class SupervisedUserPrefMappingServiceFactory : public BrowserContextKeyedServiceFactory { public: static SupervisedUserPrefMappingService* GetForBrowserContext( content::BrowserContext* profile); static SupervisedUserPrefMappingServiceFactory* GetInstance(); private: friend struct base::DefaultSingletonTraits< SupervisedUserPrefMappingServiceFactory>; SupervisedUserPrefMappingServiceFactory(); ~SupervisedUserPrefMappingServiceFactory() override; // BrowserContextKeyedServiceFactory: KeyedService* BuildServiceInstanceFor( content::BrowserContext* profile) const override; }; #endif // CHROME_BROWSER_SUPERVISED_USER_LEGACY_SUPERVISED_USER_PREF_MAPPING_SERVICE_FACTORY_H_
null
null
null
null
58,793
1,612
1,2,6,7
train_val
0e3d721470add955c056e3051614f58c7220e85b
1,612
Chrome
1
https://github.com/chromium/chromium
2015-06-02 03:10:03+00:00
SynchronousCompositorImpl::SynchronousCompositorImpl(WebContents* contents) : compositor_client_(NULL), output_surface_(NULL), begin_frame_source_(nullptr), contents_(contents), routing_id_(contents->GetRoutingID()), input_handler_(NULL), is_active_(false), renderer_needs_begin_frames_(false), weak_ptr_factory_(this) { DCHECK(contents); DCHECK_NE(routing_id_, MSG_ROUTING_NONE); }
null
null
https://github.com/chromium/chromium/commit/0e3d721470add955c056e3051614f58c7220e85b
null
1,612
2,893
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
167,888
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
#undef TRACE_SYSTEM #define TRACE_SYSTEM cfg80211 #if !defined(__RDEV_OPS_TRACE) || defined(TRACE_HEADER_MULTI_READ) #define __RDEV_OPS_TRACE #include <linux/tracepoint.h> #include <linux/rtnetlink.h> #include <linux/etherdevice.h> #include <net/cfg80211.h> #include "core.h" #define MAC_ENTRY(entry_mac) __array(u8, entry_mac, ETH_ALEN) #define MAC_ASSIGN(entry_mac, given_mac) do { \ if (given_mac) \ memcpy(__entry->entry_mac, given_mac, ETH_ALEN); \ else \ eth_zero_addr(__entry->entry_mac); \ } while (0) #define MAC_PR_FMT "%pM" #define MAC_PR_ARG(entry_mac) (__entry->entry_mac) #define MAXNAME 32 #define WIPHY_ENTRY __array(char, wiphy_name, 32) #define WIPHY_ASSIGN strlcpy(__entry->wiphy_name, wiphy_name(wiphy), MAXNAME) #define WIPHY_PR_FMT "%s" #define WIPHY_PR_ARG __entry->wiphy_name #define WDEV_ENTRY __field(u32, id) #define WDEV_ASSIGN (__entry->id) = (!IS_ERR_OR_NULL(wdev) \ ? wdev->identifier : 0) #define WDEV_PR_FMT "wdev(%u)" #define WDEV_PR_ARG (__entry->id) #define NETDEV_ENTRY __array(char, name, IFNAMSIZ) \ __field(int, ifindex) #define NETDEV_ASSIGN \ do { \ memcpy(__entry->name, netdev->name, IFNAMSIZ); \ (__entry->ifindex) = (netdev->ifindex); \ } while (0) #define NETDEV_PR_FMT "netdev:%s(%d)" #define NETDEV_PR_ARG __entry->name, __entry->ifindex #define MESH_CFG_ENTRY __field(u16, dot11MeshRetryTimeout) \ __field(u16, dot11MeshConfirmTimeout) \ __field(u16, dot11MeshHoldingTimeout) \ __field(u16, dot11MeshMaxPeerLinks) \ __field(u8, dot11MeshMaxRetries) \ __field(u8, dot11MeshTTL) \ __field(u8, element_ttl) \ __field(bool, auto_open_plinks) \ __field(u32, dot11MeshNbrOffsetMaxNeighbor) \ __field(u8, dot11MeshHWMPmaxPREQretries) \ __field(u32, path_refresh_time) \ __field(u32, dot11MeshHWMPactivePathTimeout) \ __field(u16, min_discovery_timeout) \ __field(u16, dot11MeshHWMPpreqMinInterval) \ __field(u16, dot11MeshHWMPperrMinInterval) \ __field(u16, dot11MeshHWMPnetDiameterTraversalTime) \ __field(u8, dot11MeshHWMPRootMode) \ __field(u16, dot11MeshHWMPRannInterval) \ __field(bool, dot11MeshGateAnnouncementProtocol) \ __field(bool, dot11MeshForwarding) \ __field(s32, rssi_threshold) \ __field(u16, ht_opmode) \ __field(u32, dot11MeshHWMPactivePathToRootTimeout) \ __field(u16, dot11MeshHWMProotInterval) \ __field(u16, dot11MeshHWMPconfirmationInterval) #define MESH_CFG_ASSIGN \ do { \ __entry->dot11MeshRetryTimeout = conf->dot11MeshRetryTimeout; \ __entry->dot11MeshConfirmTimeout = \ conf->dot11MeshConfirmTimeout; \ __entry->dot11MeshHoldingTimeout = \ conf->dot11MeshHoldingTimeout; \ __entry->dot11MeshMaxPeerLinks = conf->dot11MeshMaxPeerLinks; \ __entry->dot11MeshMaxRetries = conf->dot11MeshMaxRetries; \ __entry->dot11MeshTTL = conf->dot11MeshTTL; \ __entry->element_ttl = conf->element_ttl; \ __entry->auto_open_plinks = conf->auto_open_plinks; \ __entry->dot11MeshNbrOffsetMaxNeighbor = \ conf->dot11MeshNbrOffsetMaxNeighbor; \ __entry->dot11MeshHWMPmaxPREQretries = \ conf->dot11MeshHWMPmaxPREQretries; \ __entry->path_refresh_time = conf->path_refresh_time; \ __entry->dot11MeshHWMPactivePathTimeout = \ conf->dot11MeshHWMPactivePathTimeout; \ __entry->min_discovery_timeout = conf->min_discovery_timeout; \ __entry->dot11MeshHWMPpreqMinInterval = \ conf->dot11MeshHWMPpreqMinInterval; \ __entry->dot11MeshHWMPperrMinInterval = \ conf->dot11MeshHWMPperrMinInterval; \ __entry->dot11MeshHWMPnetDiameterTraversalTime = \ conf->dot11MeshHWMPnetDiameterTraversalTime; \ __entry->dot11MeshHWMPRootMode = conf->dot11MeshHWMPRootMode; \ __entry->dot11MeshHWMPRannInterval = \ conf->dot11MeshHWMPRannInterval; \ __entry->dot11MeshGateAnnouncementProtocol = \ conf->dot11MeshGateAnnouncementProtocol; \ __entry->dot11MeshForwarding = conf->dot11MeshForwarding; \ __entry->rssi_threshold = conf->rssi_threshold; \ __entry->ht_opmode = conf->ht_opmode; \ __entry->dot11MeshHWMPactivePathToRootTimeout = \ conf->dot11MeshHWMPactivePathToRootTimeout; \ __entry->dot11MeshHWMProotInterval = \ conf->dot11MeshHWMProotInterval; \ __entry->dot11MeshHWMPconfirmationInterval = \ conf->dot11MeshHWMPconfirmationInterval; \ } while (0) #define CHAN_ENTRY __field(enum nl80211_band, band) \ __field(u16, center_freq) #define CHAN_ASSIGN(chan) \ do { \ if (chan) { \ __entry->band = chan->band; \ __entry->center_freq = chan->center_freq; \ } else { \ __entry->band = 0; \ __entry->center_freq = 0; \ } \ } while (0) #define CHAN_PR_FMT "band: %d, freq: %u" #define CHAN_PR_ARG __entry->band, __entry->center_freq #define CHAN_DEF_ENTRY __field(enum nl80211_band, band) \ __field(u32, control_freq) \ __field(u32, width) \ __field(u32, center_freq1) \ __field(u32, center_freq2) #define CHAN_DEF_ASSIGN(chandef) \ do { \ if ((chandef) && (chandef)->chan) { \ __entry->band = (chandef)->chan->band; \ __entry->control_freq = \ (chandef)->chan->center_freq; \ __entry->width = (chandef)->width; \ __entry->center_freq1 = (chandef)->center_freq1;\ __entry->center_freq2 = (chandef)->center_freq2;\ } else { \ __entry->band = 0; \ __entry->control_freq = 0; \ __entry->width = 0; \ __entry->center_freq1 = 0; \ __entry->center_freq2 = 0; \ } \ } while (0) #define CHAN_DEF_PR_FMT \ "band: %d, control freq: %u, width: %d, cf1: %u, cf2: %u" #define CHAN_DEF_PR_ARG __entry->band, __entry->control_freq, \ __entry->width, __entry->center_freq1, \ __entry->center_freq2 #define SINFO_ENTRY __field(int, generation) \ __field(u32, connected_time) \ __field(u32, inactive_time) \ __field(u32, rx_bytes) \ __field(u32, tx_bytes) \ __field(u32, rx_packets) \ __field(u32, tx_packets) \ __field(u32, tx_retries) \ __field(u32, tx_failed) \ __field(u32, rx_dropped_misc) \ __field(u32, beacon_loss_count) \ __field(u16, llid) \ __field(u16, plid) \ __field(u8, plink_state) #define SINFO_ASSIGN \ do { \ __entry->generation = sinfo->generation; \ __entry->connected_time = sinfo->connected_time; \ __entry->inactive_time = sinfo->inactive_time; \ __entry->rx_bytes = sinfo->rx_bytes; \ __entry->tx_bytes = sinfo->tx_bytes; \ __entry->rx_packets = sinfo->rx_packets; \ __entry->tx_packets = sinfo->tx_packets; \ __entry->tx_retries = sinfo->tx_retries; \ __entry->tx_failed = sinfo->tx_failed; \ __entry->rx_dropped_misc = sinfo->rx_dropped_misc; \ __entry->beacon_loss_count = sinfo->beacon_loss_count; \ __entry->llid = sinfo->llid; \ __entry->plid = sinfo->plid; \ __entry->plink_state = sinfo->plink_state; \ } while (0) #define BOOL_TO_STR(bo) (bo) ? "true" : "false" #define QOS_MAP_ENTRY __field(u8, num_des) \ __array(u8, dscp_exception, \ 2 * IEEE80211_QOS_MAP_MAX_EX) \ __array(u8, up, IEEE80211_QOS_MAP_LEN_MIN) #define QOS_MAP_ASSIGN(qos_map) \ do { \ if ((qos_map)) { \ __entry->num_des = (qos_map)->num_des; \ memcpy(__entry->dscp_exception, \ &(qos_map)->dscp_exception, \ 2 * IEEE80211_QOS_MAP_MAX_EX); \ memcpy(__entry->up, &(qos_map)->up, \ IEEE80211_QOS_MAP_LEN_MIN); \ } else { \ __entry->num_des = 0; \ memset(__entry->dscp_exception, 0, \ 2 * IEEE80211_QOS_MAP_MAX_EX); \ memset(__entry->up, 0, \ IEEE80211_QOS_MAP_LEN_MIN); \ } \ } while (0) /************************************************************* * rdev->ops traces * *************************************************************/ TRACE_EVENT(rdev_suspend, TP_PROTO(struct wiphy *wiphy, struct cfg80211_wowlan *wow), TP_ARGS(wiphy, wow), TP_STRUCT__entry( WIPHY_ENTRY __field(bool, any) __field(bool, disconnect) __field(bool, magic_pkt) __field(bool, gtk_rekey_failure) __field(bool, eap_identity_req) __field(bool, four_way_handshake) __field(bool, rfkill_release) __field(bool, valid_wow) ), TP_fast_assign( WIPHY_ASSIGN; if (wow) { __entry->any = wow->any; __entry->disconnect = wow->disconnect; __entry->magic_pkt = wow->magic_pkt; __entry->gtk_rekey_failure = wow->gtk_rekey_failure; __entry->eap_identity_req = wow->eap_identity_req; __entry->four_way_handshake = wow->four_way_handshake; __entry->rfkill_release = wow->rfkill_release; __entry->valid_wow = true; } else { __entry->valid_wow = false; } ), TP_printk(WIPHY_PR_FMT ", wow%s - any: %d, disconnect: %d, " "magic pkt: %d, gtk rekey failure: %d, eap identify req: %d, " "four way handshake: %d, rfkill release: %d.", WIPHY_PR_ARG, __entry->valid_wow ? "" : "(Not configured!)", __entry->any, __entry->disconnect, __entry->magic_pkt, __entry->gtk_rekey_failure, __entry->eap_identity_req, __entry->four_way_handshake, __entry->rfkill_release) ); TRACE_EVENT(rdev_return_int, TP_PROTO(struct wiphy *wiphy, int ret), TP_ARGS(wiphy, ret), TP_STRUCT__entry( WIPHY_ENTRY __field(int, ret) ), TP_fast_assign( WIPHY_ASSIGN; __entry->ret = ret; ), TP_printk(WIPHY_PR_FMT ", returned: %d", WIPHY_PR_ARG, __entry->ret) ); TRACE_EVENT(rdev_scan, TP_PROTO(struct wiphy *wiphy, struct cfg80211_scan_request *request), TP_ARGS(wiphy, request), TP_STRUCT__entry( WIPHY_ENTRY ), TP_fast_assign( WIPHY_ASSIGN; ), TP_printk(WIPHY_PR_FMT, WIPHY_PR_ARG) ); DECLARE_EVENT_CLASS(wiphy_only_evt, TP_PROTO(struct wiphy *wiphy), TP_ARGS(wiphy), TP_STRUCT__entry( WIPHY_ENTRY ), TP_fast_assign( WIPHY_ASSIGN; ), TP_printk(WIPHY_PR_FMT, WIPHY_PR_ARG) ); DEFINE_EVENT(wiphy_only_evt, rdev_resume, TP_PROTO(struct wiphy *wiphy), TP_ARGS(wiphy) ); DEFINE_EVENT(wiphy_only_evt, rdev_return_void, TP_PROTO(struct wiphy *wiphy), TP_ARGS(wiphy) ); DEFINE_EVENT(wiphy_only_evt, rdev_get_antenna, TP_PROTO(struct wiphy *wiphy), TP_ARGS(wiphy) ); DEFINE_EVENT(wiphy_only_evt, rdev_rfkill_poll, TP_PROTO(struct wiphy *wiphy), TP_ARGS(wiphy) ); DECLARE_EVENT_CLASS(wiphy_enabled_evt, TP_PROTO(struct wiphy *wiphy, bool enabled), TP_ARGS(wiphy, enabled), TP_STRUCT__entry( WIPHY_ENTRY __field(bool, enabled) ), TP_fast_assign( WIPHY_ASSIGN; __entry->enabled = enabled; ), TP_printk(WIPHY_PR_FMT ", %senabled ", WIPHY_PR_ARG, __entry->enabled ? "" : "not ") ); DEFINE_EVENT(wiphy_enabled_evt, rdev_set_wakeup, TP_PROTO(struct wiphy *wiphy, bool enabled), TP_ARGS(wiphy, enabled) ); TRACE_EVENT(rdev_add_virtual_intf, TP_PROTO(struct wiphy *wiphy, char *name, enum nl80211_iftype type), TP_ARGS(wiphy, name, type), TP_STRUCT__entry( WIPHY_ENTRY __string(vir_intf_name, name ? name : "<noname>") __field(enum nl80211_iftype, type) ), TP_fast_assign( WIPHY_ASSIGN; __assign_str(vir_intf_name, name ? name : "<noname>"); __entry->type = type; ), TP_printk(WIPHY_PR_FMT ", virtual intf name: %s, type: %d", WIPHY_PR_ARG, __get_str(vir_intf_name), __entry->type) ); DECLARE_EVENT_CLASS(wiphy_wdev_evt, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev), TP_ARGS(wiphy, wdev), TP_STRUCT__entry( WIPHY_ENTRY WDEV_ENTRY ), TP_fast_assign( WIPHY_ASSIGN; WDEV_ASSIGN; ), TP_printk(WIPHY_PR_FMT ", " WDEV_PR_FMT, WIPHY_PR_ARG, WDEV_PR_ARG) ); DEFINE_EVENT(wiphy_wdev_evt, rdev_return_wdev, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev), TP_ARGS(wiphy, wdev) ); DEFINE_EVENT(wiphy_wdev_evt, rdev_del_virtual_intf, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev), TP_ARGS(wiphy, wdev) ); TRACE_EVENT(rdev_change_virtual_intf, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, enum nl80211_iftype type), TP_ARGS(wiphy, netdev, type), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY __field(enum nl80211_iftype, type) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; __entry->type = type; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", type: %d", WIPHY_PR_ARG, NETDEV_PR_ARG, __entry->type) ); DECLARE_EVENT_CLASS(key_handle, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, u8 key_index, bool pairwise, const u8 *mac_addr), TP_ARGS(wiphy, netdev, key_index, pairwise, mac_addr), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(mac_addr) __field(u8, key_index) __field(bool, pairwise) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MAC_ASSIGN(mac_addr, mac_addr); __entry->key_index = key_index; __entry->pairwise = pairwise; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", key_index: %u, pairwise: %s, mac addr: " MAC_PR_FMT, WIPHY_PR_ARG, NETDEV_PR_ARG, __entry->key_index, BOOL_TO_STR(__entry->pairwise), MAC_PR_ARG(mac_addr)) ); DEFINE_EVENT(key_handle, rdev_add_key, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, u8 key_index, bool pairwise, const u8 *mac_addr), TP_ARGS(wiphy, netdev, key_index, pairwise, mac_addr) ); DEFINE_EVENT(key_handle, rdev_get_key, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, u8 key_index, bool pairwise, const u8 *mac_addr), TP_ARGS(wiphy, netdev, key_index, pairwise, mac_addr) ); DEFINE_EVENT(key_handle, rdev_del_key, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, u8 key_index, bool pairwise, const u8 *mac_addr), TP_ARGS(wiphy, netdev, key_index, pairwise, mac_addr) ); TRACE_EVENT(rdev_set_default_key, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, u8 key_index, bool unicast, bool multicast), TP_ARGS(wiphy, netdev, key_index, unicast, multicast), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY __field(u8, key_index) __field(bool, unicast) __field(bool, multicast) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; __entry->key_index = key_index; __entry->unicast = unicast; __entry->multicast = multicast; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", key index: %u, unicast: %s, multicast: %s", WIPHY_PR_ARG, NETDEV_PR_ARG, __entry->key_index, BOOL_TO_STR(__entry->unicast), BOOL_TO_STR(__entry->multicast)) ); TRACE_EVENT(rdev_set_default_mgmt_key, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, u8 key_index), TP_ARGS(wiphy, netdev, key_index), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY __field(u8, key_index) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; __entry->key_index = key_index; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", key index: %u", WIPHY_PR_ARG, NETDEV_PR_ARG, __entry->key_index) ); TRACE_EVENT(rdev_start_ap, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_ap_settings *settings), TP_ARGS(wiphy, netdev, settings), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY CHAN_DEF_ENTRY __field(int, beacon_interval) __field(int, dtim_period) __array(char, ssid, IEEE80211_MAX_SSID_LEN + 1) __field(enum nl80211_hidden_ssid, hidden_ssid) __field(u32, wpa_ver) __field(bool, privacy) __field(enum nl80211_auth_type, auth_type) __field(int, inactivity_timeout) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; CHAN_DEF_ASSIGN(&settings->chandef); __entry->beacon_interval = settings->beacon_interval; __entry->dtim_period = settings->dtim_period; __entry->hidden_ssid = settings->hidden_ssid; __entry->wpa_ver = settings->crypto.wpa_versions; __entry->privacy = settings->privacy; __entry->auth_type = settings->auth_type; __entry->inactivity_timeout = settings->inactivity_timeout; memset(__entry->ssid, 0, IEEE80211_MAX_SSID_LEN + 1); memcpy(__entry->ssid, settings->ssid, settings->ssid_len); ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", AP settings - ssid: %s, " CHAN_DEF_PR_FMT ", beacon interval: %d, dtim period: %d, " "hidden ssid: %d, wpa versions: %u, privacy: %s, " "auth type: %d, inactivity timeout: %d", WIPHY_PR_ARG, NETDEV_PR_ARG, __entry->ssid, CHAN_DEF_PR_ARG, __entry->beacon_interval, __entry->dtim_period, __entry->hidden_ssid, __entry->wpa_ver, BOOL_TO_STR(__entry->privacy), __entry->auth_type, __entry->inactivity_timeout) ); TRACE_EVENT(rdev_change_beacon, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_beacon_data *info), TP_ARGS(wiphy, netdev, info), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY __dynamic_array(u8, head, info ? info->head_len : 0) __dynamic_array(u8, tail, info ? info->tail_len : 0) __dynamic_array(u8, beacon_ies, info ? info->beacon_ies_len : 0) __dynamic_array(u8, proberesp_ies, info ? info->proberesp_ies_len : 0) __dynamic_array(u8, assocresp_ies, info ? info->assocresp_ies_len : 0) __dynamic_array(u8, probe_resp, info ? info->probe_resp_len : 0) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; if (info) { if (info->head) memcpy(__get_dynamic_array(head), info->head, info->head_len); if (info->tail) memcpy(__get_dynamic_array(tail), info->tail, info->tail_len); if (info->beacon_ies) memcpy(__get_dynamic_array(beacon_ies), info->beacon_ies, info->beacon_ies_len); if (info->proberesp_ies) memcpy(__get_dynamic_array(proberesp_ies), info->proberesp_ies, info->proberesp_ies_len); if (info->assocresp_ies) memcpy(__get_dynamic_array(assocresp_ies), info->assocresp_ies, info->assocresp_ies_len); if (info->probe_resp) memcpy(__get_dynamic_array(probe_resp), info->probe_resp, info->probe_resp_len); } ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT, WIPHY_PR_ARG, NETDEV_PR_ARG) ); DECLARE_EVENT_CLASS(wiphy_netdev_evt, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev), TP_ARGS(wiphy, netdev), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT, WIPHY_PR_ARG, NETDEV_PR_ARG) ); DEFINE_EVENT(wiphy_netdev_evt, rdev_stop_ap, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev), TP_ARGS(wiphy, netdev) ); DEFINE_EVENT(wiphy_netdev_evt, rdev_sched_scan_stop, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev), TP_ARGS(wiphy, netdev) ); DEFINE_EVENT(wiphy_netdev_evt, rdev_set_rekey_data, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev), TP_ARGS(wiphy, netdev) ); DEFINE_EVENT(wiphy_netdev_evt, rdev_get_mesh_config, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev), TP_ARGS(wiphy, netdev) ); DEFINE_EVENT(wiphy_netdev_evt, rdev_leave_mesh, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev), TP_ARGS(wiphy, netdev) ); DEFINE_EVENT(wiphy_netdev_evt, rdev_leave_ibss, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev), TP_ARGS(wiphy, netdev) ); DEFINE_EVENT(wiphy_netdev_evt, rdev_leave_ocb, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev), TP_ARGS(wiphy, netdev) ); DEFINE_EVENT(wiphy_netdev_evt, rdev_flush_pmksa, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev), TP_ARGS(wiphy, netdev) ); DECLARE_EVENT_CLASS(station_add_change, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, u8 *mac, struct station_parameters *params), TP_ARGS(wiphy, netdev, mac, params), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(sta_mac) __field(u32, sta_flags_mask) __field(u32, sta_flags_set) __field(u32, sta_modify_mask) __field(int, listen_interval) __field(u16, capability) __field(u16, aid) __field(u8, plink_action) __field(u8, plink_state) __field(u8, uapsd_queues) __field(u8, max_sp) __field(u8, opmode_notif) __field(bool, opmode_notif_used) __array(u8, ht_capa, (int)sizeof(struct ieee80211_ht_cap)) __array(u8, vht_capa, (int)sizeof(struct ieee80211_vht_cap)) __array(char, vlan, IFNAMSIZ) __dynamic_array(u8, supported_rates, params->supported_rates_len) __dynamic_array(u8, ext_capab, params->ext_capab_len) __dynamic_array(u8, supported_channels, params->supported_channels_len) __dynamic_array(u8, supported_oper_classes, params->supported_oper_classes_len) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MAC_ASSIGN(sta_mac, mac); __entry->sta_flags_mask = params->sta_flags_mask; __entry->sta_flags_set = params->sta_flags_set; __entry->sta_modify_mask = params->sta_modify_mask; __entry->listen_interval = params->listen_interval; __entry->aid = params->aid; __entry->plink_action = params->plink_action; __entry->plink_state = params->plink_state; __entry->uapsd_queues = params->uapsd_queues; memset(__entry->ht_capa, 0, sizeof(struct ieee80211_ht_cap)); if (params->ht_capa) memcpy(__entry->ht_capa, params->ht_capa, sizeof(struct ieee80211_ht_cap)); memset(__entry->vht_capa, 0, sizeof(struct ieee80211_vht_cap)); if (params->vht_capa) memcpy(__entry->vht_capa, params->vht_capa, sizeof(struct ieee80211_vht_cap)); memset(__entry->vlan, 0, sizeof(__entry->vlan)); if (params->vlan) memcpy(__entry->vlan, params->vlan->name, IFNAMSIZ); if (params->supported_rates && params->supported_rates_len) memcpy(__get_dynamic_array(supported_rates), params->supported_rates, params->supported_rates_len); if (params->ext_capab && params->ext_capab_len) memcpy(__get_dynamic_array(ext_capab), params->ext_capab, params->ext_capab_len); if (params->supported_channels && params->supported_channels_len) memcpy(__get_dynamic_array(supported_channels), params->supported_channels, params->supported_channels_len); if (params->supported_oper_classes && params->supported_oper_classes_len) memcpy(__get_dynamic_array(supported_oper_classes), params->supported_oper_classes, params->supported_oper_classes_len); __entry->max_sp = params->max_sp; __entry->capability = params->capability; __entry->opmode_notif = params->opmode_notif; __entry->opmode_notif_used = params->opmode_notif_used; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", station mac: " MAC_PR_FMT ", station flags mask: %u, station flags set: %u, " "station modify mask: %u, listen interval: %d, aid: %u, " "plink action: %u, plink state: %u, uapsd queues: %u, vlan:%s", WIPHY_PR_ARG, NETDEV_PR_ARG, MAC_PR_ARG(sta_mac), __entry->sta_flags_mask, __entry->sta_flags_set, __entry->sta_modify_mask, __entry->listen_interval, __entry->aid, __entry->plink_action, __entry->plink_state, __entry->uapsd_queues, __entry->vlan) ); DEFINE_EVENT(station_add_change, rdev_add_station, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, u8 *mac, struct station_parameters *params), TP_ARGS(wiphy, netdev, mac, params) ); DEFINE_EVENT(station_add_change, rdev_change_station, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, u8 *mac, struct station_parameters *params), TP_ARGS(wiphy, netdev, mac, params) ); DECLARE_EVENT_CLASS(wiphy_netdev_mac_evt, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, const u8 *mac), TP_ARGS(wiphy, netdev, mac), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(sta_mac) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MAC_ASSIGN(sta_mac, mac); ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", mac: " MAC_PR_FMT, WIPHY_PR_ARG, NETDEV_PR_ARG, MAC_PR_ARG(sta_mac)) ); DECLARE_EVENT_CLASS(station_del, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct station_del_parameters *params), TP_ARGS(wiphy, netdev, params), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(sta_mac) __field(u8, subtype) __field(u16, reason_code) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MAC_ASSIGN(sta_mac, params->mac); __entry->subtype = params->subtype; __entry->reason_code = params->reason_code; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", station mac: " MAC_PR_FMT ", subtype: %u, reason_code: %u", WIPHY_PR_ARG, NETDEV_PR_ARG, MAC_PR_ARG(sta_mac), __entry->subtype, __entry->reason_code) ); DEFINE_EVENT(station_del, rdev_del_station, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct station_del_parameters *params), TP_ARGS(wiphy, netdev, params) ); DEFINE_EVENT(wiphy_netdev_mac_evt, rdev_get_station, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, const u8 *mac), TP_ARGS(wiphy, netdev, mac) ); DEFINE_EVENT(wiphy_netdev_mac_evt, rdev_del_mpath, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, const u8 *mac), TP_ARGS(wiphy, netdev, mac) ); DEFINE_EVENT(wiphy_netdev_mac_evt, rdev_set_wds_peer, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, const u8 *mac), TP_ARGS(wiphy, netdev, mac) ); TRACE_EVENT(rdev_dump_station, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, int idx, u8 *mac), TP_ARGS(wiphy, netdev, idx, mac), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(sta_mac) __field(int, idx) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MAC_ASSIGN(sta_mac, mac); __entry->idx = idx; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", station mac: " MAC_PR_FMT ", idx: %d", WIPHY_PR_ARG, NETDEV_PR_ARG, MAC_PR_ARG(sta_mac), __entry->idx) ); TRACE_EVENT(rdev_return_int_station_info, TP_PROTO(struct wiphy *wiphy, int ret, struct station_info *sinfo), TP_ARGS(wiphy, ret, sinfo), TP_STRUCT__entry( WIPHY_ENTRY __field(int, ret) SINFO_ENTRY ), TP_fast_assign( WIPHY_ASSIGN; __entry->ret = ret; SINFO_ASSIGN; ), TP_printk(WIPHY_PR_FMT ", returned %d" , WIPHY_PR_ARG, __entry->ret) ); DECLARE_EVENT_CLASS(mpath_evt, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, u8 *dst, u8 *next_hop), TP_ARGS(wiphy, netdev, dst, next_hop), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(dst) MAC_ENTRY(next_hop) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MAC_ASSIGN(dst, dst); MAC_ASSIGN(next_hop, next_hop); ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", destination: " MAC_PR_FMT ", next hop: " MAC_PR_FMT, WIPHY_PR_ARG, NETDEV_PR_ARG, MAC_PR_ARG(dst), MAC_PR_ARG(next_hop)) ); DEFINE_EVENT(mpath_evt, rdev_add_mpath, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, u8 *dst, u8 *next_hop), TP_ARGS(wiphy, netdev, dst, next_hop) ); DEFINE_EVENT(mpath_evt, rdev_change_mpath, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, u8 *dst, u8 *next_hop), TP_ARGS(wiphy, netdev, dst, next_hop) ); DEFINE_EVENT(mpath_evt, rdev_get_mpath, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, u8 *dst, u8 *next_hop), TP_ARGS(wiphy, netdev, dst, next_hop) ); TRACE_EVENT(rdev_dump_mpath, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, int idx, u8 *dst, u8 *next_hop), TP_ARGS(wiphy, netdev, idx, dst, next_hop), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(dst) MAC_ENTRY(next_hop) __field(int, idx) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MAC_ASSIGN(dst, dst); MAC_ASSIGN(next_hop, next_hop); __entry->idx = idx; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", index: %d, destination: " MAC_PR_FMT ", next hop: " MAC_PR_FMT, WIPHY_PR_ARG, NETDEV_PR_ARG, __entry->idx, MAC_PR_ARG(dst), MAC_PR_ARG(next_hop)) ); TRACE_EVENT(rdev_get_mpp, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, u8 *dst, u8 *mpp), TP_ARGS(wiphy, netdev, dst, mpp), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(dst) MAC_ENTRY(mpp) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MAC_ASSIGN(dst, dst); MAC_ASSIGN(mpp, mpp); ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", destination: " MAC_PR_FMT ", mpp: " MAC_PR_FMT, WIPHY_PR_ARG, NETDEV_PR_ARG, MAC_PR_ARG(dst), MAC_PR_ARG(mpp)) ); TRACE_EVENT(rdev_dump_mpp, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, int idx, u8 *dst, u8 *mpp), TP_ARGS(wiphy, netdev, idx, mpp, dst), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(dst) MAC_ENTRY(mpp) __field(int, idx) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MAC_ASSIGN(dst, dst); MAC_ASSIGN(mpp, mpp); __entry->idx = idx; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", index: %d, destination: " MAC_PR_FMT ", mpp: " MAC_PR_FMT, WIPHY_PR_ARG, NETDEV_PR_ARG, __entry->idx, MAC_PR_ARG(dst), MAC_PR_ARG(mpp)) ); TRACE_EVENT(rdev_return_int_mpath_info, TP_PROTO(struct wiphy *wiphy, int ret, struct mpath_info *pinfo), TP_ARGS(wiphy, ret, pinfo), TP_STRUCT__entry( WIPHY_ENTRY __field(int, ret) __field(int, generation) __field(u32, filled) __field(u32, frame_qlen) __field(u32, sn) __field(u32, metric) __field(u32, exptime) __field(u32, discovery_timeout) __field(u8, discovery_retries) __field(u8, flags) ), TP_fast_assign( WIPHY_ASSIGN; __entry->ret = ret; __entry->generation = pinfo->generation; __entry->filled = pinfo->filled; __entry->frame_qlen = pinfo->frame_qlen; __entry->sn = pinfo->sn; __entry->metric = pinfo->metric; __entry->exptime = pinfo->exptime; __entry->discovery_timeout = pinfo->discovery_timeout; __entry->discovery_retries = pinfo->discovery_retries; __entry->flags = pinfo->flags; ), TP_printk(WIPHY_PR_FMT ", returned %d. mpath info - generation: %d, " "filled: %u, frame qlen: %u, sn: %u, metric: %u, exptime: %u," " discovery timeout: %u, discovery retries: %u, flags: %u", WIPHY_PR_ARG, __entry->ret, __entry->generation, __entry->filled, __entry->frame_qlen, __entry->sn, __entry->metric, __entry->exptime, __entry->discovery_timeout, __entry->discovery_retries, __entry->flags) ); TRACE_EVENT(rdev_return_int_mesh_config, TP_PROTO(struct wiphy *wiphy, int ret, struct mesh_config *conf), TP_ARGS(wiphy, ret, conf), TP_STRUCT__entry( WIPHY_ENTRY MESH_CFG_ENTRY __field(int, ret) ), TP_fast_assign( WIPHY_ASSIGN; MESH_CFG_ASSIGN; __entry->ret = ret; ), TP_printk(WIPHY_PR_FMT ", returned: %d", WIPHY_PR_ARG, __entry->ret) ); TRACE_EVENT(rdev_update_mesh_config, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, u32 mask, const struct mesh_config *conf), TP_ARGS(wiphy, netdev, mask, conf), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MESH_CFG_ENTRY __field(u32, mask) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MESH_CFG_ASSIGN; __entry->mask = mask; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", mask: %u", WIPHY_PR_ARG, NETDEV_PR_ARG, __entry->mask) ); TRACE_EVENT(rdev_join_mesh, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, const struct mesh_config *conf, const struct mesh_setup *setup), TP_ARGS(wiphy, netdev, conf, setup), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MESH_CFG_ENTRY ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MESH_CFG_ASSIGN; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT, WIPHY_PR_ARG, NETDEV_PR_ARG) ); TRACE_EVENT(rdev_change_bss, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct bss_parameters *params), TP_ARGS(wiphy, netdev, params), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY __field(int, use_cts_prot) __field(int, use_short_preamble) __field(int, use_short_slot_time) __field(int, ap_isolate) __field(int, ht_opmode) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; __entry->use_cts_prot = params->use_cts_prot; __entry->use_short_preamble = params->use_short_preamble; __entry->use_short_slot_time = params->use_short_slot_time; __entry->ap_isolate = params->ap_isolate; __entry->ht_opmode = params->ht_opmode; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", use cts prot: %d, " "use short preamble: %d, use short slot time: %d, " "ap isolate: %d, ht opmode: %d", WIPHY_PR_ARG, NETDEV_PR_ARG, __entry->use_cts_prot, __entry->use_short_preamble, __entry->use_short_slot_time, __entry->ap_isolate, __entry->ht_opmode) ); TRACE_EVENT(rdev_set_txq_params, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct ieee80211_txq_params *params), TP_ARGS(wiphy, netdev, params), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY __field(enum nl80211_ac, ac) __field(u16, txop) __field(u16, cwmin) __field(u16, cwmax) __field(u8, aifs) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; __entry->ac = params->ac; __entry->txop = params->txop; __entry->cwmin = params->cwmin; __entry->cwmax = params->cwmax; __entry->aifs = params->aifs; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", ac: %d, txop: %u, cwmin: %u, cwmax: %u, aifs: %u", WIPHY_PR_ARG, NETDEV_PR_ARG, __entry->ac, __entry->txop, __entry->cwmin, __entry->cwmax, __entry->aifs) ); TRACE_EVENT(rdev_libertas_set_mesh_channel, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct ieee80211_channel *chan), TP_ARGS(wiphy, netdev, chan), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY CHAN_ENTRY ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; CHAN_ASSIGN(chan); ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", " CHAN_PR_FMT, WIPHY_PR_ARG, NETDEV_PR_ARG, CHAN_PR_ARG) ); TRACE_EVENT(rdev_set_monitor_channel, TP_PROTO(struct wiphy *wiphy, struct cfg80211_chan_def *chandef), TP_ARGS(wiphy, chandef), TP_STRUCT__entry( WIPHY_ENTRY CHAN_DEF_ENTRY ), TP_fast_assign( WIPHY_ASSIGN; CHAN_DEF_ASSIGN(chandef); ), TP_printk(WIPHY_PR_FMT ", " CHAN_DEF_PR_FMT, WIPHY_PR_ARG, CHAN_DEF_PR_ARG) ); TRACE_EVENT(rdev_auth, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_auth_request *req), TP_ARGS(wiphy, netdev, req), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(bssid) __field(enum nl80211_auth_type, auth_type) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; if (req->bss) MAC_ASSIGN(bssid, req->bss->bssid); else eth_zero_addr(__entry->bssid); __entry->auth_type = req->auth_type; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", auth type: %d, bssid: " MAC_PR_FMT, WIPHY_PR_ARG, NETDEV_PR_ARG, __entry->auth_type, MAC_PR_ARG(bssid)) ); TRACE_EVENT(rdev_assoc, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_assoc_request *req), TP_ARGS(wiphy, netdev, req), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(bssid) MAC_ENTRY(prev_bssid) __field(bool, use_mfp) __field(u32, flags) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; if (req->bss) MAC_ASSIGN(bssid, req->bss->bssid); else eth_zero_addr(__entry->bssid); MAC_ASSIGN(prev_bssid, req->prev_bssid); __entry->use_mfp = req->use_mfp; __entry->flags = req->flags; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", bssid: " MAC_PR_FMT ", previous bssid: " MAC_PR_FMT ", use mfp: %s, flags: %u", WIPHY_PR_ARG, NETDEV_PR_ARG, MAC_PR_ARG(bssid), MAC_PR_ARG(prev_bssid), BOOL_TO_STR(__entry->use_mfp), __entry->flags) ); TRACE_EVENT(rdev_deauth, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_deauth_request *req), TP_ARGS(wiphy, netdev, req), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(bssid) __field(u16, reason_code) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MAC_ASSIGN(bssid, req->bssid); __entry->reason_code = req->reason_code; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", bssid: " MAC_PR_FMT ", reason: %u", WIPHY_PR_ARG, NETDEV_PR_ARG, MAC_PR_ARG(bssid), __entry->reason_code) ); TRACE_EVENT(rdev_disassoc, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_disassoc_request *req), TP_ARGS(wiphy, netdev, req), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(bssid) __field(u16, reason_code) __field(bool, local_state_change) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; if (req->bss) MAC_ASSIGN(bssid, req->bss->bssid); else eth_zero_addr(__entry->bssid); __entry->reason_code = req->reason_code; __entry->local_state_change = req->local_state_change; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", bssid: " MAC_PR_FMT ", reason: %u, local state change: %s", WIPHY_PR_ARG, NETDEV_PR_ARG, MAC_PR_ARG(bssid), __entry->reason_code, BOOL_TO_STR(__entry->local_state_change)) ); TRACE_EVENT(rdev_mgmt_tx_cancel_wait, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev, u64 cookie), TP_ARGS(wiphy, wdev, cookie), TP_STRUCT__entry( WIPHY_ENTRY WDEV_ENTRY __field(u64, cookie) ), TP_fast_assign( WIPHY_ASSIGN; WDEV_ASSIGN; __entry->cookie = cookie; ), TP_printk(WIPHY_PR_FMT ", " WDEV_PR_FMT ", cookie: %llu ", WIPHY_PR_ARG, WDEV_PR_ARG, __entry->cookie) ); TRACE_EVENT(rdev_set_power_mgmt, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, bool enabled, int timeout), TP_ARGS(wiphy, netdev, enabled, timeout), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY __field(bool, enabled) __field(int, timeout) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; __entry->enabled = enabled; __entry->timeout = timeout; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", %senabled, timeout: %d ", WIPHY_PR_ARG, NETDEV_PR_ARG, __entry->enabled ? "" : "not ", __entry->timeout) ); TRACE_EVENT(rdev_connect, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_connect_params *sme), TP_ARGS(wiphy, netdev, sme), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(bssid) __array(char, ssid, IEEE80211_MAX_SSID_LEN + 1) __field(enum nl80211_auth_type, auth_type) __field(bool, privacy) __field(u32, wpa_versions) __field(u32, flags) MAC_ENTRY(prev_bssid) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MAC_ASSIGN(bssid, sme->bssid); memset(__entry->ssid, 0, IEEE80211_MAX_SSID_LEN + 1); memcpy(__entry->ssid, sme->ssid, sme->ssid_len); __entry->auth_type = sme->auth_type; __entry->privacy = sme->privacy; __entry->wpa_versions = sme->crypto.wpa_versions; __entry->flags = sme->flags; MAC_ASSIGN(prev_bssid, sme->prev_bssid); ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", bssid: " MAC_PR_FMT ", ssid: %s, auth type: %d, privacy: %s, wpa versions: %u, " "flags: %u, previous bssid: " MAC_PR_FMT, WIPHY_PR_ARG, NETDEV_PR_ARG, MAC_PR_ARG(bssid), __entry->ssid, __entry->auth_type, BOOL_TO_STR(__entry->privacy), __entry->wpa_versions, __entry->flags, MAC_PR_ARG(prev_bssid)) ); TRACE_EVENT(rdev_update_connect_params, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_connect_params *sme, u32 changed), TP_ARGS(wiphy, netdev, sme, changed), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY __field(u32, changed) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; __entry->changed = changed; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", parameters changed: %u", WIPHY_PR_ARG, NETDEV_PR_ARG, __entry->changed) ); TRACE_EVENT(rdev_set_cqm_rssi_config, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, s32 rssi_thold, u32 rssi_hyst), TP_ARGS(wiphy, netdev, rssi_thold, rssi_hyst), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY __field(s32, rssi_thold) __field(u32, rssi_hyst) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; __entry->rssi_thold = rssi_thold; __entry->rssi_hyst = rssi_hyst; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", rssi_thold: %d, rssi_hyst: %u ", WIPHY_PR_ARG, NETDEV_PR_ARG, __entry->rssi_thold, __entry->rssi_hyst) ); TRACE_EVENT(rdev_set_cqm_txe_config, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, u32 rate, u32 pkts, u32 intvl), TP_ARGS(wiphy, netdev, rate, pkts, intvl), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY __field(u32, rate) __field(u32, pkts) __field(u32, intvl) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; __entry->rate = rate; __entry->pkts = pkts; __entry->intvl = intvl; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", rate: %u, packets: %u, interval: %u", WIPHY_PR_ARG, NETDEV_PR_ARG, __entry->rate, __entry->pkts, __entry->intvl) ); TRACE_EVENT(rdev_disconnect, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, u16 reason_code), TP_ARGS(wiphy, netdev, reason_code), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY __field(u16, reason_code) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; __entry->reason_code = reason_code; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", reason code: %u", WIPHY_PR_ARG, NETDEV_PR_ARG, __entry->reason_code) ); TRACE_EVENT(rdev_join_ibss, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_ibss_params *params), TP_ARGS(wiphy, netdev, params), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(bssid) __array(char, ssid, IEEE80211_MAX_SSID_LEN + 1) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MAC_ASSIGN(bssid, params->bssid); memset(__entry->ssid, 0, IEEE80211_MAX_SSID_LEN + 1); memcpy(__entry->ssid, params->ssid, params->ssid_len); ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", bssid: " MAC_PR_FMT ", ssid: %s", WIPHY_PR_ARG, NETDEV_PR_ARG, MAC_PR_ARG(bssid), __entry->ssid) ); TRACE_EVENT(rdev_join_ocb, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, const struct ocb_setup *setup), TP_ARGS(wiphy, netdev, setup), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT, WIPHY_PR_ARG, NETDEV_PR_ARG) ); TRACE_EVENT(rdev_set_wiphy_params, TP_PROTO(struct wiphy *wiphy, u32 changed), TP_ARGS(wiphy, changed), TP_STRUCT__entry( WIPHY_ENTRY __field(u32, changed) ), TP_fast_assign( WIPHY_ASSIGN; __entry->changed = changed; ), TP_printk(WIPHY_PR_FMT ", changed: %u", WIPHY_PR_ARG, __entry->changed) ); DEFINE_EVENT(wiphy_wdev_evt, rdev_get_tx_power, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev), TP_ARGS(wiphy, wdev) ); TRACE_EVENT(rdev_set_tx_power, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev, enum nl80211_tx_power_setting type, int mbm), TP_ARGS(wiphy, wdev, type, mbm), TP_STRUCT__entry( WIPHY_ENTRY WDEV_ENTRY __field(enum nl80211_tx_power_setting, type) __field(int, mbm) ), TP_fast_assign( WIPHY_ASSIGN; WDEV_ASSIGN; __entry->type = type; __entry->mbm = mbm; ), TP_printk(WIPHY_PR_FMT ", " WDEV_PR_FMT ", type: %u, mbm: %d", WIPHY_PR_ARG, WDEV_PR_ARG,__entry->type, __entry->mbm) ); TRACE_EVENT(rdev_return_int_int, TP_PROTO(struct wiphy *wiphy, int func_ret, int func_fill), TP_ARGS(wiphy, func_ret, func_fill), TP_STRUCT__entry( WIPHY_ENTRY __field(int, func_ret) __field(int, func_fill) ), TP_fast_assign( WIPHY_ASSIGN; __entry->func_ret = func_ret; __entry->func_fill = func_fill; ), TP_printk(WIPHY_PR_FMT ", function returns: %d, function filled: %d", WIPHY_PR_ARG, __entry->func_ret, __entry->func_fill) ); #ifdef CONFIG_NL80211_TESTMODE TRACE_EVENT(rdev_testmode_cmd, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev), TP_ARGS(wiphy, wdev), TP_STRUCT__entry( WIPHY_ENTRY WDEV_ENTRY ), TP_fast_assign( WIPHY_ASSIGN; WDEV_ASSIGN; ), TP_printk(WIPHY_PR_FMT WDEV_PR_FMT, WIPHY_PR_ARG, WDEV_PR_ARG) ); TRACE_EVENT(rdev_testmode_dump, TP_PROTO(struct wiphy *wiphy), TP_ARGS(wiphy), TP_STRUCT__entry( WIPHY_ENTRY ), TP_fast_assign( WIPHY_ASSIGN; ), TP_printk(WIPHY_PR_FMT, WIPHY_PR_ARG) ); #endif /* CONFIG_NL80211_TESTMODE */ TRACE_EVENT(rdev_set_bitrate_mask, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, const u8 *peer, const struct cfg80211_bitrate_mask *mask), TP_ARGS(wiphy, netdev, peer, mask), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(peer) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MAC_ASSIGN(peer, peer); ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", peer: " MAC_PR_FMT, WIPHY_PR_ARG, NETDEV_PR_ARG, MAC_PR_ARG(peer)) ); TRACE_EVENT(rdev_mgmt_frame_register, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev, u16 frame_type, bool reg), TP_ARGS(wiphy, wdev, frame_type, reg), TP_STRUCT__entry( WIPHY_ENTRY WDEV_ENTRY __field(u16, frame_type) __field(bool, reg) ), TP_fast_assign( WIPHY_ASSIGN; WDEV_ASSIGN; __entry->frame_type = frame_type; __entry->reg = reg; ), TP_printk(WIPHY_PR_FMT ", " WDEV_PR_FMT ", frame_type: 0x%.2x, reg: %s ", WIPHY_PR_ARG, WDEV_PR_ARG, __entry->frame_type, __entry->reg ? "true" : "false") ); TRACE_EVENT(rdev_return_int_tx_rx, TP_PROTO(struct wiphy *wiphy, int ret, u32 tx, u32 rx), TP_ARGS(wiphy, ret, tx, rx), TP_STRUCT__entry( WIPHY_ENTRY __field(int, ret) __field(u32, tx) __field(u32, rx) ), TP_fast_assign( WIPHY_ASSIGN; __entry->ret = ret; __entry->tx = tx; __entry->rx = rx; ), TP_printk(WIPHY_PR_FMT ", returned %d, tx: %u, rx: %u", WIPHY_PR_ARG, __entry->ret, __entry->tx, __entry->rx) ); TRACE_EVENT(rdev_return_void_tx_rx, TP_PROTO(struct wiphy *wiphy, u32 tx, u32 tx_max, u32 rx, u32 rx_max), TP_ARGS(wiphy, tx, tx_max, rx, rx_max), TP_STRUCT__entry( WIPHY_ENTRY __field(u32, tx) __field(u32, tx_max) __field(u32, rx) __field(u32, rx_max) ), TP_fast_assign( WIPHY_ASSIGN; __entry->tx = tx; __entry->tx_max = tx_max; __entry->rx = rx; __entry->rx_max = rx_max; ), TP_printk(WIPHY_PR_FMT ", tx: %u, tx_max: %u, rx: %u, rx_max: %u ", WIPHY_PR_ARG, __entry->tx, __entry->tx_max, __entry->rx, __entry->rx_max) ); DECLARE_EVENT_CLASS(tx_rx_evt, TP_PROTO(struct wiphy *wiphy, u32 tx, u32 rx), TP_ARGS(wiphy, rx, tx), TP_STRUCT__entry( WIPHY_ENTRY __field(u32, tx) __field(u32, rx) ), TP_fast_assign( WIPHY_ASSIGN; __entry->tx = tx; __entry->rx = rx; ), TP_printk(WIPHY_PR_FMT ", tx: %u, rx: %u ", WIPHY_PR_ARG, __entry->tx, __entry->rx) ); DEFINE_EVENT(tx_rx_evt, rdev_set_antenna, TP_PROTO(struct wiphy *wiphy, u32 tx, u32 rx), TP_ARGS(wiphy, rx, tx) ); TRACE_EVENT(rdev_sched_scan_start, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_sched_scan_request *request), TP_ARGS(wiphy, netdev, request), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT, WIPHY_PR_ARG, NETDEV_PR_ARG) ); TRACE_EVENT(rdev_tdls_mgmt, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, u8 *peer, u8 action_code, u8 dialog_token, u16 status_code, u32 peer_capability, bool initiator, const u8 *buf, size_t len), TP_ARGS(wiphy, netdev, peer, action_code, dialog_token, status_code, peer_capability, initiator, buf, len), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(peer) __field(u8, action_code) __field(u8, dialog_token) __field(u16, status_code) __field(u32, peer_capability) __field(bool, initiator) __dynamic_array(u8, buf, len) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MAC_ASSIGN(peer, peer); __entry->action_code = action_code; __entry->dialog_token = dialog_token; __entry->status_code = status_code; __entry->peer_capability = peer_capability; __entry->initiator = initiator; memcpy(__get_dynamic_array(buf), buf, len); ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", " MAC_PR_FMT ", action_code: %u, " "dialog_token: %u, status_code: %u, peer_capability: %u " "initiator: %s buf: %#.2x ", WIPHY_PR_ARG, NETDEV_PR_ARG, MAC_PR_ARG(peer), __entry->action_code, __entry->dialog_token, __entry->status_code, __entry->peer_capability, BOOL_TO_STR(__entry->initiator), ((u8 *)__get_dynamic_array(buf))[0]) ); TRACE_EVENT(rdev_dump_survey, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, int idx), TP_ARGS(wiphy, netdev, idx), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY __field(int, idx) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; __entry->idx = idx; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", index: %d", WIPHY_PR_ARG, NETDEV_PR_ARG, __entry->idx) ); TRACE_EVENT(rdev_return_int_survey_info, TP_PROTO(struct wiphy *wiphy, int ret, struct survey_info *info), TP_ARGS(wiphy, ret, info), TP_STRUCT__entry( WIPHY_ENTRY CHAN_ENTRY __field(int, ret) __field(u64, time) __field(u64, time_busy) __field(u64, time_ext_busy) __field(u64, time_rx) __field(u64, time_tx) __field(u64, time_scan) __field(u32, filled) __field(s8, noise) ), TP_fast_assign( WIPHY_ASSIGN; CHAN_ASSIGN(info->channel); __entry->ret = ret; __entry->time = info->time; __entry->time_busy = info->time_busy; __entry->time_ext_busy = info->time_ext_busy; __entry->time_rx = info->time_rx; __entry->time_tx = info->time_tx; __entry->time_scan = info->time_scan; __entry->filled = info->filled; __entry->noise = info->noise; ), TP_printk(WIPHY_PR_FMT ", returned: %d, " CHAN_PR_FMT ", channel time: %llu, channel time busy: %llu, " "channel time extension busy: %llu, channel time rx: %llu, " "channel time tx: %llu, scan time: %llu, filled: %u, noise: %d", WIPHY_PR_ARG, __entry->ret, CHAN_PR_ARG, __entry->time, __entry->time_busy, __entry->time_ext_busy, __entry->time_rx, __entry->time_tx, __entry->time_scan, __entry->filled, __entry->noise) ); TRACE_EVENT(rdev_tdls_oper, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, u8 *peer, enum nl80211_tdls_operation oper), TP_ARGS(wiphy, netdev, peer, oper), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(peer) __field(enum nl80211_tdls_operation, oper) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MAC_ASSIGN(peer, peer); __entry->oper = oper; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", " MAC_PR_FMT ", oper: %d", WIPHY_PR_ARG, NETDEV_PR_ARG, MAC_PR_ARG(peer), __entry->oper) ); DECLARE_EVENT_CLASS(rdev_pmksa, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_pmksa *pmksa), TP_ARGS(wiphy, netdev, pmksa), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(bssid) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MAC_ASSIGN(bssid, pmksa->bssid); ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", bssid: " MAC_PR_FMT, WIPHY_PR_ARG, NETDEV_PR_ARG, MAC_PR_ARG(bssid)) ); TRACE_EVENT(rdev_probe_client, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, const u8 *peer), TP_ARGS(wiphy, netdev, peer), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(peer) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MAC_ASSIGN(peer, peer); ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", " MAC_PR_FMT, WIPHY_PR_ARG, NETDEV_PR_ARG, MAC_PR_ARG(peer)) ); DEFINE_EVENT(rdev_pmksa, rdev_set_pmksa, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_pmksa *pmksa), TP_ARGS(wiphy, netdev, pmksa) ); DEFINE_EVENT(rdev_pmksa, rdev_del_pmksa, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_pmksa *pmksa), TP_ARGS(wiphy, netdev, pmksa) ); TRACE_EVENT(rdev_remain_on_channel, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev, struct ieee80211_channel *chan, unsigned int duration), TP_ARGS(wiphy, wdev, chan, duration), TP_STRUCT__entry( WIPHY_ENTRY WDEV_ENTRY CHAN_ENTRY __field(unsigned int, duration) ), TP_fast_assign( WIPHY_ASSIGN; WDEV_ASSIGN; CHAN_ASSIGN(chan); __entry->duration = duration; ), TP_printk(WIPHY_PR_FMT ", " WDEV_PR_FMT ", " CHAN_PR_FMT ", duration: %u", WIPHY_PR_ARG, WDEV_PR_ARG, CHAN_PR_ARG, __entry->duration) ); TRACE_EVENT(rdev_return_int_cookie, TP_PROTO(struct wiphy *wiphy, int ret, u64 cookie), TP_ARGS(wiphy, ret, cookie), TP_STRUCT__entry( WIPHY_ENTRY __field(int, ret) __field(u64, cookie) ), TP_fast_assign( WIPHY_ASSIGN; __entry->ret = ret; __entry->cookie = cookie; ), TP_printk(WIPHY_PR_FMT ", returned %d, cookie: %llu", WIPHY_PR_ARG, __entry->ret, __entry->cookie) ); TRACE_EVENT(rdev_cancel_remain_on_channel, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev, u64 cookie), TP_ARGS(wiphy, wdev, cookie), TP_STRUCT__entry( WIPHY_ENTRY WDEV_ENTRY __field(u64, cookie) ), TP_fast_assign( WIPHY_ASSIGN; WDEV_ASSIGN; __entry->cookie = cookie; ), TP_printk(WIPHY_PR_FMT ", " WDEV_PR_FMT ", cookie: %llu", WIPHY_PR_ARG, WDEV_PR_ARG, __entry->cookie) ); TRACE_EVENT(rdev_mgmt_tx, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev, struct cfg80211_mgmt_tx_params *params), TP_ARGS(wiphy, wdev, params), TP_STRUCT__entry( WIPHY_ENTRY WDEV_ENTRY CHAN_ENTRY __field(bool, offchan) __field(unsigned int, wait) __field(bool, no_cck) __field(bool, dont_wait_for_ack) ), TP_fast_assign( WIPHY_ASSIGN; WDEV_ASSIGN; CHAN_ASSIGN(params->chan); __entry->offchan = params->offchan; __entry->wait = params->wait; __entry->no_cck = params->no_cck; __entry->dont_wait_for_ack = params->dont_wait_for_ack; ), TP_printk(WIPHY_PR_FMT ", " WDEV_PR_FMT ", " CHAN_PR_FMT ", offchan: %s," " wait: %u, no cck: %s, dont wait for ack: %s", WIPHY_PR_ARG, WDEV_PR_ARG, CHAN_PR_ARG, BOOL_TO_STR(__entry->offchan), __entry->wait, BOOL_TO_STR(__entry->no_cck), BOOL_TO_STR(__entry->dont_wait_for_ack)) ); TRACE_EVENT(rdev_set_noack_map, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, u16 noack_map), TP_ARGS(wiphy, netdev, noack_map), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY __field(u16, noack_map) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; __entry->noack_map = noack_map; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", noack_map: %u", WIPHY_PR_ARG, NETDEV_PR_ARG, __entry->noack_map) ); DEFINE_EVENT(wiphy_wdev_evt, rdev_get_channel, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev), TP_ARGS(wiphy, wdev) ); TRACE_EVENT(rdev_return_chandef, TP_PROTO(struct wiphy *wiphy, int ret, struct cfg80211_chan_def *chandef), TP_ARGS(wiphy, ret, chandef), TP_STRUCT__entry( WIPHY_ENTRY __field(int, ret) CHAN_DEF_ENTRY ), TP_fast_assign( WIPHY_ASSIGN; if (ret == 0) CHAN_DEF_ASSIGN(chandef); else CHAN_DEF_ASSIGN((struct cfg80211_chan_def *)NULL); __entry->ret = ret; ), TP_printk(WIPHY_PR_FMT ", " CHAN_DEF_PR_FMT ", ret: %d", WIPHY_PR_ARG, CHAN_DEF_PR_ARG, __entry->ret) ); DEFINE_EVENT(wiphy_wdev_evt, rdev_start_p2p_device, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev), TP_ARGS(wiphy, wdev) ); DEFINE_EVENT(wiphy_wdev_evt, rdev_stop_p2p_device, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev), TP_ARGS(wiphy, wdev) ); TRACE_EVENT(rdev_start_nan, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev, struct cfg80211_nan_conf *conf), TP_ARGS(wiphy, wdev, conf), TP_STRUCT__entry( WIPHY_ENTRY WDEV_ENTRY __field(u8, master_pref) __field(u8, bands); ), TP_fast_assign( WIPHY_ASSIGN; WDEV_ASSIGN; __entry->master_pref = conf->master_pref; __entry->bands = conf->bands; ), TP_printk(WIPHY_PR_FMT ", " WDEV_PR_FMT ", master preference: %u, bands: 0x%0x", WIPHY_PR_ARG, WDEV_PR_ARG, __entry->master_pref, __entry->bands) ); TRACE_EVENT(rdev_nan_change_conf, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev, struct cfg80211_nan_conf *conf, u32 changes), TP_ARGS(wiphy, wdev, conf, changes), TP_STRUCT__entry( WIPHY_ENTRY WDEV_ENTRY __field(u8, master_pref) __field(u8, bands); __field(u32, changes); ), TP_fast_assign( WIPHY_ASSIGN; WDEV_ASSIGN; __entry->master_pref = conf->master_pref; __entry->bands = conf->bands; __entry->changes = changes; ), TP_printk(WIPHY_PR_FMT ", " WDEV_PR_FMT ", master preference: %u, bands: 0x%0x, changes: %x", WIPHY_PR_ARG, WDEV_PR_ARG, __entry->master_pref, __entry->bands, __entry->changes) ); DEFINE_EVENT(wiphy_wdev_evt, rdev_stop_nan, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev), TP_ARGS(wiphy, wdev) ); TRACE_EVENT(rdev_add_nan_func, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev, const struct cfg80211_nan_func *func), TP_ARGS(wiphy, wdev, func), TP_STRUCT__entry( WIPHY_ENTRY WDEV_ENTRY __field(u8, func_type) __field(u64, cookie) ), TP_fast_assign( WIPHY_ASSIGN; WDEV_ASSIGN; __entry->func_type = func->type; __entry->cookie = func->cookie ), TP_printk(WIPHY_PR_FMT ", " WDEV_PR_FMT ", type=%u, cookie=%llu", WIPHY_PR_ARG, WDEV_PR_ARG, __entry->func_type, __entry->cookie) ); TRACE_EVENT(rdev_del_nan_func, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev, u64 cookie), TP_ARGS(wiphy, wdev, cookie), TP_STRUCT__entry( WIPHY_ENTRY WDEV_ENTRY __field(u64, cookie) ), TP_fast_assign( WIPHY_ASSIGN; WDEV_ASSIGN; __entry->cookie = cookie; ), TP_printk(WIPHY_PR_FMT ", " WDEV_PR_FMT ", cookie=%llu", WIPHY_PR_ARG, WDEV_PR_ARG, __entry->cookie) ); TRACE_EVENT(rdev_set_mac_acl, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_acl_data *params), TP_ARGS(wiphy, netdev, params), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY __field(u32, acl_policy) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; __entry->acl_policy = params->acl_policy; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", acl policy: %d", WIPHY_PR_ARG, NETDEV_PR_ARG, __entry->acl_policy) ); TRACE_EVENT(rdev_update_ft_ies, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_update_ft_ies_params *ftie), TP_ARGS(wiphy, netdev, ftie), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY __field(u16, md) __dynamic_array(u8, ie, ftie->ie_len) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; __entry->md = ftie->md; memcpy(__get_dynamic_array(ie), ftie->ie, ftie->ie_len); ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", md: 0x%x", WIPHY_PR_ARG, NETDEV_PR_ARG, __entry->md) ); TRACE_EVENT(rdev_crit_proto_start, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev, enum nl80211_crit_proto_id protocol, u16 duration), TP_ARGS(wiphy, wdev, protocol, duration), TP_STRUCT__entry( WIPHY_ENTRY WDEV_ENTRY __field(u16, proto) __field(u16, duration) ), TP_fast_assign( WIPHY_ASSIGN; WDEV_ASSIGN; __entry->proto = protocol; __entry->duration = duration; ), TP_printk(WIPHY_PR_FMT ", " WDEV_PR_FMT ", proto=%x, duration=%u", WIPHY_PR_ARG, WDEV_PR_ARG, __entry->proto, __entry->duration) ); TRACE_EVENT(rdev_crit_proto_stop, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev), TP_ARGS(wiphy, wdev), TP_STRUCT__entry( WIPHY_ENTRY WDEV_ENTRY ), TP_fast_assign( WIPHY_ASSIGN; WDEV_ASSIGN; ), TP_printk(WIPHY_PR_FMT ", " WDEV_PR_FMT, WIPHY_PR_ARG, WDEV_PR_ARG) ); TRACE_EVENT(rdev_channel_switch, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_csa_settings *params), TP_ARGS(wiphy, netdev, params), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY CHAN_DEF_ENTRY __field(bool, radar_required) __field(bool, block_tx) __field(u8, count) __dynamic_array(u16, bcn_ofs, params->n_counter_offsets_beacon) __dynamic_array(u16, pres_ofs, params->n_counter_offsets_presp) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; CHAN_DEF_ASSIGN(&params->chandef); __entry->radar_required = params->radar_required; __entry->block_tx = params->block_tx; __entry->count = params->count; memcpy(__get_dynamic_array(bcn_ofs), params->counter_offsets_beacon, params->n_counter_offsets_beacon * sizeof(u16)); /* probe response offsets are optional */ if (params->n_counter_offsets_presp) memcpy(__get_dynamic_array(pres_ofs), params->counter_offsets_presp, params->n_counter_offsets_presp * sizeof(u16)); ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", " CHAN_DEF_PR_FMT ", block_tx: %d, count: %u, radar_required: %d", WIPHY_PR_ARG, NETDEV_PR_ARG, CHAN_DEF_PR_ARG, __entry->block_tx, __entry->count, __entry->radar_required) ); TRACE_EVENT(rdev_set_qos_map, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_qos_map *qos_map), TP_ARGS(wiphy, netdev, qos_map), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY QOS_MAP_ENTRY ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; QOS_MAP_ASSIGN(qos_map); ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", num_des: %u", WIPHY_PR_ARG, NETDEV_PR_ARG, __entry->num_des) ); TRACE_EVENT(rdev_set_ap_chanwidth, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_chan_def *chandef), TP_ARGS(wiphy, netdev, chandef), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY CHAN_DEF_ENTRY ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; CHAN_DEF_ASSIGN(chandef); ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", " CHAN_DEF_PR_FMT, WIPHY_PR_ARG, NETDEV_PR_ARG, CHAN_DEF_PR_ARG) ); TRACE_EVENT(rdev_add_tx_ts, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, u8 tsid, const u8 *peer, u8 user_prio, u16 admitted_time), TP_ARGS(wiphy, netdev, tsid, peer, user_prio, admitted_time), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(peer) __field(u8, tsid) __field(u8, user_prio) __field(u16, admitted_time) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MAC_ASSIGN(peer, peer); __entry->tsid = tsid; __entry->user_prio = user_prio; __entry->admitted_time = admitted_time; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", " MAC_PR_FMT ", TSID %d, UP %d, time %d", WIPHY_PR_ARG, NETDEV_PR_ARG, MAC_PR_ARG(peer), __entry->tsid, __entry->user_prio, __entry->admitted_time) ); TRACE_EVENT(rdev_del_tx_ts, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, u8 tsid, const u8 *peer), TP_ARGS(wiphy, netdev, tsid, peer), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(peer) __field(u8, tsid) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MAC_ASSIGN(peer, peer); __entry->tsid = tsid; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", " MAC_PR_FMT ", TSID %d", WIPHY_PR_ARG, NETDEV_PR_ARG, MAC_PR_ARG(peer), __entry->tsid) ); TRACE_EVENT(rdev_tdls_channel_switch, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, const u8 *addr, u8 oper_class, struct cfg80211_chan_def *chandef), TP_ARGS(wiphy, netdev, addr, oper_class, chandef), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(addr) __field(u8, oper_class) CHAN_DEF_ENTRY ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MAC_ASSIGN(addr, addr); CHAN_DEF_ASSIGN(chandef); ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", " MAC_PR_FMT " oper class %d, " CHAN_DEF_PR_FMT, WIPHY_PR_ARG, NETDEV_PR_ARG, MAC_PR_ARG(addr), __entry->oper_class, CHAN_DEF_PR_ARG) ); TRACE_EVENT(rdev_tdls_cancel_channel_switch, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, const u8 *addr), TP_ARGS(wiphy, netdev, addr), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(addr) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MAC_ASSIGN(addr, addr); ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", " MAC_PR_FMT, WIPHY_PR_ARG, NETDEV_PR_ARG, MAC_PR_ARG(addr)) ); /************************************************************* * cfg80211 exported functions traces * *************************************************************/ TRACE_EVENT(cfg80211_return_bool, TP_PROTO(bool ret), TP_ARGS(ret), TP_STRUCT__entry( __field(bool, ret) ), TP_fast_assign( __entry->ret = ret; ), TP_printk("returned %s", BOOL_TO_STR(__entry->ret)) ); DECLARE_EVENT_CLASS(cfg80211_netdev_mac_evt, TP_PROTO(struct net_device *netdev, const u8 *macaddr), TP_ARGS(netdev, macaddr), TP_STRUCT__entry( NETDEV_ENTRY MAC_ENTRY(macaddr) ), TP_fast_assign( NETDEV_ASSIGN; MAC_ASSIGN(macaddr, macaddr); ), TP_printk(NETDEV_PR_FMT ", mac: " MAC_PR_FMT, NETDEV_PR_ARG, MAC_PR_ARG(macaddr)) ); DEFINE_EVENT(cfg80211_netdev_mac_evt, cfg80211_notify_new_peer_candidate, TP_PROTO(struct net_device *netdev, const u8 *macaddr), TP_ARGS(netdev, macaddr) ); DECLARE_EVENT_CLASS(netdev_evt_only, TP_PROTO(struct net_device *netdev), TP_ARGS(netdev), TP_STRUCT__entry( NETDEV_ENTRY ), TP_fast_assign( NETDEV_ASSIGN; ), TP_printk(NETDEV_PR_FMT , NETDEV_PR_ARG) ); DEFINE_EVENT(netdev_evt_only, cfg80211_send_rx_auth, TP_PROTO(struct net_device *netdev), TP_ARGS(netdev) ); TRACE_EVENT(cfg80211_send_rx_assoc, TP_PROTO(struct net_device *netdev, struct cfg80211_bss *bss), TP_ARGS(netdev, bss), TP_STRUCT__entry( NETDEV_ENTRY MAC_ENTRY(bssid) CHAN_ENTRY ), TP_fast_assign( NETDEV_ASSIGN; MAC_ASSIGN(bssid, bss->bssid); CHAN_ASSIGN(bss->channel); ), TP_printk(NETDEV_PR_FMT ", " MAC_PR_FMT ", " CHAN_PR_FMT, NETDEV_PR_ARG, MAC_PR_ARG(bssid), CHAN_PR_ARG) ); DECLARE_EVENT_CLASS(netdev_frame_event, TP_PROTO(struct net_device *netdev, const u8 *buf, int len), TP_ARGS(netdev, buf, len), TP_STRUCT__entry( NETDEV_ENTRY __dynamic_array(u8, frame, len) ), TP_fast_assign( NETDEV_ASSIGN; memcpy(__get_dynamic_array(frame), buf, len); ), TP_printk(NETDEV_PR_FMT ", ftype:0x%.2x", NETDEV_PR_ARG, le16_to_cpup((__le16 *)__get_dynamic_array(frame))) ); DEFINE_EVENT(netdev_frame_event, cfg80211_rx_unprot_mlme_mgmt, TP_PROTO(struct net_device *netdev, const u8 *buf, int len), TP_ARGS(netdev, buf, len) ); DEFINE_EVENT(netdev_frame_event, cfg80211_rx_mlme_mgmt, TP_PROTO(struct net_device *netdev, const u8 *buf, int len), TP_ARGS(netdev, buf, len) ); TRACE_EVENT(cfg80211_tx_mlme_mgmt, TP_PROTO(struct net_device *netdev, const u8 *buf, int len), TP_ARGS(netdev, buf, len), TP_STRUCT__entry( NETDEV_ENTRY __dynamic_array(u8, frame, len) ), TP_fast_assign( NETDEV_ASSIGN; memcpy(__get_dynamic_array(frame), buf, len); ), TP_printk(NETDEV_PR_FMT ", ftype:0x%.2x", NETDEV_PR_ARG, le16_to_cpup((__le16 *)__get_dynamic_array(frame))) ); DECLARE_EVENT_CLASS(netdev_mac_evt, TP_PROTO(struct net_device *netdev, const u8 *mac), TP_ARGS(netdev, mac), TP_STRUCT__entry( NETDEV_ENTRY MAC_ENTRY(mac) ), TP_fast_assign( NETDEV_ASSIGN; MAC_ASSIGN(mac, mac) ), TP_printk(NETDEV_PR_FMT ", mac: " MAC_PR_FMT, NETDEV_PR_ARG, MAC_PR_ARG(mac)) ); DEFINE_EVENT(netdev_mac_evt, cfg80211_send_auth_timeout, TP_PROTO(struct net_device *netdev, const u8 *mac), TP_ARGS(netdev, mac) ); DEFINE_EVENT(netdev_mac_evt, cfg80211_send_assoc_timeout, TP_PROTO(struct net_device *netdev, const u8 *mac), TP_ARGS(netdev, mac) ); TRACE_EVENT(cfg80211_michael_mic_failure, TP_PROTO(struct net_device *netdev, const u8 *addr, enum nl80211_key_type key_type, int key_id, const u8 *tsc), TP_ARGS(netdev, addr, key_type, key_id, tsc), TP_STRUCT__entry( NETDEV_ENTRY MAC_ENTRY(addr) __field(enum nl80211_key_type, key_type) __field(int, key_id) __array(u8, tsc, 6) ), TP_fast_assign( NETDEV_ASSIGN; MAC_ASSIGN(addr, addr); __entry->key_type = key_type; __entry->key_id = key_id; if (tsc) memcpy(__entry->tsc, tsc, 6); ), TP_printk(NETDEV_PR_FMT ", " MAC_PR_FMT ", key type: %d, key id: %d, tsc: %pm", NETDEV_PR_ARG, MAC_PR_ARG(addr), __entry->key_type, __entry->key_id, __entry->tsc) ); TRACE_EVENT(cfg80211_ready_on_channel, TP_PROTO(struct wireless_dev *wdev, u64 cookie, struct ieee80211_channel *chan, unsigned int duration), TP_ARGS(wdev, cookie, chan, duration), TP_STRUCT__entry( WDEV_ENTRY __field(u64, cookie) CHAN_ENTRY __field(unsigned int, duration) ), TP_fast_assign( WDEV_ASSIGN; __entry->cookie = cookie; CHAN_ASSIGN(chan); __entry->duration = duration; ), TP_printk(WDEV_PR_FMT ", cookie: %llu, " CHAN_PR_FMT ", duration: %u", WDEV_PR_ARG, __entry->cookie, CHAN_PR_ARG, __entry->duration) ); TRACE_EVENT(cfg80211_ready_on_channel_expired, TP_PROTO(struct wireless_dev *wdev, u64 cookie, struct ieee80211_channel *chan), TP_ARGS(wdev, cookie, chan), TP_STRUCT__entry( WDEV_ENTRY __field(u64, cookie) CHAN_ENTRY ), TP_fast_assign( WDEV_ASSIGN; __entry->cookie = cookie; CHAN_ASSIGN(chan); ), TP_printk(WDEV_PR_FMT ", cookie: %llu, " CHAN_PR_FMT, WDEV_PR_ARG, __entry->cookie, CHAN_PR_ARG) ); TRACE_EVENT(cfg80211_new_sta, TP_PROTO(struct net_device *netdev, const u8 *mac_addr, struct station_info *sinfo), TP_ARGS(netdev, mac_addr, sinfo), TP_STRUCT__entry( NETDEV_ENTRY MAC_ENTRY(mac_addr) SINFO_ENTRY ), TP_fast_assign( NETDEV_ASSIGN; MAC_ASSIGN(mac_addr, mac_addr); SINFO_ASSIGN; ), TP_printk(NETDEV_PR_FMT ", " MAC_PR_FMT, NETDEV_PR_ARG, MAC_PR_ARG(mac_addr)) ); DEFINE_EVENT(cfg80211_netdev_mac_evt, cfg80211_del_sta, TP_PROTO(struct net_device *netdev, const u8 *macaddr), TP_ARGS(netdev, macaddr) ); TRACE_EVENT(cfg80211_rx_mgmt, TP_PROTO(struct wireless_dev *wdev, int freq, int sig_mbm), TP_ARGS(wdev, freq, sig_mbm), TP_STRUCT__entry( WDEV_ENTRY __field(int, freq) __field(int, sig_mbm) ), TP_fast_assign( WDEV_ASSIGN; __entry->freq = freq; __entry->sig_mbm = sig_mbm; ), TP_printk(WDEV_PR_FMT ", freq: %d, sig mbm: %d", WDEV_PR_ARG, __entry->freq, __entry->sig_mbm) ); TRACE_EVENT(cfg80211_mgmt_tx_status, TP_PROTO(struct wireless_dev *wdev, u64 cookie, bool ack), TP_ARGS(wdev, cookie, ack), TP_STRUCT__entry( WDEV_ENTRY __field(u64, cookie) __field(bool, ack) ), TP_fast_assign( WDEV_ASSIGN; __entry->cookie = cookie; __entry->ack = ack; ), TP_printk(WDEV_PR_FMT", cookie: %llu, ack: %s", WDEV_PR_ARG, __entry->cookie, BOOL_TO_STR(__entry->ack)) ); TRACE_EVENT(cfg80211_cqm_rssi_notify, TP_PROTO(struct net_device *netdev, enum nl80211_cqm_rssi_threshold_event rssi_event, s32 rssi_level), TP_ARGS(netdev, rssi_event, rssi_level), TP_STRUCT__entry( NETDEV_ENTRY __field(enum nl80211_cqm_rssi_threshold_event, rssi_event) __field(s32, rssi_level) ), TP_fast_assign( NETDEV_ASSIGN; __entry->rssi_event = rssi_event; __entry->rssi_level = rssi_level; ), TP_printk(NETDEV_PR_FMT ", rssi event: %d, level: %d", NETDEV_PR_ARG, __entry->rssi_event, __entry->rssi_level) ); TRACE_EVENT(cfg80211_reg_can_beacon, TP_PROTO(struct wiphy *wiphy, struct cfg80211_chan_def *chandef, enum nl80211_iftype iftype, bool check_no_ir), TP_ARGS(wiphy, chandef, iftype, check_no_ir), TP_STRUCT__entry( WIPHY_ENTRY CHAN_DEF_ENTRY __field(enum nl80211_iftype, iftype) __field(bool, check_no_ir) ), TP_fast_assign( WIPHY_ASSIGN; CHAN_DEF_ASSIGN(chandef); __entry->iftype = iftype; __entry->check_no_ir = check_no_ir; ), TP_printk(WIPHY_PR_FMT ", " CHAN_DEF_PR_FMT ", iftype=%d check_no_ir=%s", WIPHY_PR_ARG, CHAN_DEF_PR_ARG, __entry->iftype, BOOL_TO_STR(__entry->check_no_ir)) ); TRACE_EVENT(cfg80211_chandef_dfs_required, TP_PROTO(struct wiphy *wiphy, struct cfg80211_chan_def *chandef), TP_ARGS(wiphy, chandef), TP_STRUCT__entry( WIPHY_ENTRY CHAN_DEF_ENTRY ), TP_fast_assign( WIPHY_ASSIGN; CHAN_DEF_ASSIGN(chandef); ), TP_printk(WIPHY_PR_FMT ", " CHAN_DEF_PR_FMT, WIPHY_PR_ARG, CHAN_DEF_PR_ARG) ); TRACE_EVENT(cfg80211_ch_switch_notify, TP_PROTO(struct net_device *netdev, struct cfg80211_chan_def *chandef), TP_ARGS(netdev, chandef), TP_STRUCT__entry( NETDEV_ENTRY CHAN_DEF_ENTRY ), TP_fast_assign( NETDEV_ASSIGN; CHAN_DEF_ASSIGN(chandef); ), TP_printk(NETDEV_PR_FMT ", " CHAN_DEF_PR_FMT, NETDEV_PR_ARG, CHAN_DEF_PR_ARG) ); TRACE_EVENT(cfg80211_ch_switch_started_notify, TP_PROTO(struct net_device *netdev, struct cfg80211_chan_def *chandef), TP_ARGS(netdev, chandef), TP_STRUCT__entry( NETDEV_ENTRY CHAN_DEF_ENTRY ), TP_fast_assign( NETDEV_ASSIGN; CHAN_DEF_ASSIGN(chandef); ), TP_printk(NETDEV_PR_FMT ", " CHAN_DEF_PR_FMT, NETDEV_PR_ARG, CHAN_DEF_PR_ARG) ); TRACE_EVENT(cfg80211_radar_event, TP_PROTO(struct wiphy *wiphy, struct cfg80211_chan_def *chandef), TP_ARGS(wiphy, chandef), TP_STRUCT__entry( WIPHY_ENTRY CHAN_DEF_ENTRY ), TP_fast_assign( WIPHY_ASSIGN; CHAN_DEF_ASSIGN(chandef); ), TP_printk(WIPHY_PR_FMT ", " CHAN_DEF_PR_FMT, WIPHY_PR_ARG, CHAN_DEF_PR_ARG) ); TRACE_EVENT(cfg80211_cac_event, TP_PROTO(struct net_device *netdev, enum nl80211_radar_event evt), TP_ARGS(netdev, evt), TP_STRUCT__entry( NETDEV_ENTRY __field(enum nl80211_radar_event, evt) ), TP_fast_assign( NETDEV_ASSIGN; __entry->evt = evt; ), TP_printk(NETDEV_PR_FMT ", event: %d", NETDEV_PR_ARG, __entry->evt) ); DECLARE_EVENT_CLASS(cfg80211_rx_evt, TP_PROTO(struct net_device *netdev, const u8 *addr), TP_ARGS(netdev, addr), TP_STRUCT__entry( NETDEV_ENTRY MAC_ENTRY(addr) ), TP_fast_assign( NETDEV_ASSIGN; MAC_ASSIGN(addr, addr); ), TP_printk(NETDEV_PR_FMT ", " MAC_PR_FMT, NETDEV_PR_ARG, MAC_PR_ARG(addr)) ); DEFINE_EVENT(cfg80211_rx_evt, cfg80211_rx_spurious_frame, TP_PROTO(struct net_device *netdev, const u8 *addr), TP_ARGS(netdev, addr) ); DEFINE_EVENT(cfg80211_rx_evt, cfg80211_rx_unexpected_4addr_frame, TP_PROTO(struct net_device *netdev, const u8 *addr), TP_ARGS(netdev, addr) ); TRACE_EVENT(cfg80211_ibss_joined, TP_PROTO(struct net_device *netdev, const u8 *bssid, struct ieee80211_channel *channel), TP_ARGS(netdev, bssid, channel), TP_STRUCT__entry( NETDEV_ENTRY MAC_ENTRY(bssid) CHAN_ENTRY ), TP_fast_assign( NETDEV_ASSIGN; MAC_ASSIGN(bssid, bssid); CHAN_ASSIGN(channel); ), TP_printk(NETDEV_PR_FMT ", bssid: " MAC_PR_FMT ", " CHAN_PR_FMT, NETDEV_PR_ARG, MAC_PR_ARG(bssid), CHAN_PR_ARG) ); TRACE_EVENT(cfg80211_probe_status, TP_PROTO(struct net_device *netdev, const u8 *addr, u64 cookie, bool acked), TP_ARGS(netdev, addr, cookie, acked), TP_STRUCT__entry( NETDEV_ENTRY MAC_ENTRY(addr) __field(u64, cookie) __field(bool, acked) ), TP_fast_assign( NETDEV_ASSIGN; MAC_ASSIGN(addr, addr); __entry->cookie = cookie; __entry->acked = acked; ), TP_printk(NETDEV_PR_FMT " addr:" MAC_PR_FMT ", cookie: %llu, acked: %s", NETDEV_PR_ARG, MAC_PR_ARG(addr), __entry->cookie, BOOL_TO_STR(__entry->acked)) ); TRACE_EVENT(cfg80211_cqm_pktloss_notify, TP_PROTO(struct net_device *netdev, const u8 *peer, u32 num_packets), TP_ARGS(netdev, peer, num_packets), TP_STRUCT__entry( NETDEV_ENTRY MAC_ENTRY(peer) __field(u32, num_packets) ), TP_fast_assign( NETDEV_ASSIGN; MAC_ASSIGN(peer, peer); __entry->num_packets = num_packets; ), TP_printk(NETDEV_PR_FMT ", peer: " MAC_PR_FMT ", num of lost packets: %u", NETDEV_PR_ARG, MAC_PR_ARG(peer), __entry->num_packets) ); DEFINE_EVENT(cfg80211_netdev_mac_evt, cfg80211_gtk_rekey_notify, TP_PROTO(struct net_device *netdev, const u8 *macaddr), TP_ARGS(netdev, macaddr) ); TRACE_EVENT(cfg80211_pmksa_candidate_notify, TP_PROTO(struct net_device *netdev, int index, const u8 *bssid, bool preauth), TP_ARGS(netdev, index, bssid, preauth), TP_STRUCT__entry( NETDEV_ENTRY __field(int, index) MAC_ENTRY(bssid) __field(bool, preauth) ), TP_fast_assign( NETDEV_ASSIGN; __entry->index = index; MAC_ASSIGN(bssid, bssid); __entry->preauth = preauth; ), TP_printk(NETDEV_PR_FMT ", index:%d, bssid: " MAC_PR_FMT ", pre auth: %s", NETDEV_PR_ARG, __entry->index, MAC_PR_ARG(bssid), BOOL_TO_STR(__entry->preauth)) ); TRACE_EVENT(cfg80211_report_obss_beacon, TP_PROTO(struct wiphy *wiphy, const u8 *frame, size_t len, int freq, int sig_dbm), TP_ARGS(wiphy, frame, len, freq, sig_dbm), TP_STRUCT__entry( WIPHY_ENTRY __field(int, freq) __field(int, sig_dbm) ), TP_fast_assign( WIPHY_ASSIGN; __entry->freq = freq; __entry->sig_dbm = sig_dbm; ), TP_printk(WIPHY_PR_FMT ", freq: %d, sig_dbm: %d", WIPHY_PR_ARG, __entry->freq, __entry->sig_dbm) ); TRACE_EVENT(cfg80211_tdls_oper_request, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, const u8 *peer, enum nl80211_tdls_operation oper, u16 reason_code), TP_ARGS(wiphy, netdev, peer, oper, reason_code), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY MAC_ENTRY(peer) __field(enum nl80211_tdls_operation, oper) __field(u16, reason_code) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; MAC_ASSIGN(peer, peer); __entry->oper = oper; __entry->reason_code = reason_code; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", peer: " MAC_PR_FMT ", oper: %d, reason_code %u", WIPHY_PR_ARG, NETDEV_PR_ARG, MAC_PR_ARG(peer), __entry->oper, __entry->reason_code) ); TRACE_EVENT(cfg80211_scan_done, TP_PROTO(struct cfg80211_scan_request *request, struct cfg80211_scan_info *info), TP_ARGS(request, info), TP_STRUCT__entry( __field(u32, n_channels) __dynamic_array(u8, ie, request ? request->ie_len : 0) __array(u32, rates, NUM_NL80211_BANDS) __field(u32, wdev_id) MAC_ENTRY(wiphy_mac) __field(bool, no_cck) __field(bool, aborted) __field(u64, scan_start_tsf) MAC_ENTRY(tsf_bssid) ), TP_fast_assign( if (request) { memcpy(__get_dynamic_array(ie), request->ie, request->ie_len); memcpy(__entry->rates, request->rates, NUM_NL80211_BANDS); __entry->wdev_id = request->wdev ? request->wdev->identifier : 0; if (request->wiphy) MAC_ASSIGN(wiphy_mac, request->wiphy->perm_addr); __entry->no_cck = request->no_cck; } if (info) { __entry->aborted = info->aborted; __entry->scan_start_tsf = info->scan_start_tsf; MAC_ASSIGN(tsf_bssid, info->tsf_bssid); } ), TP_printk("aborted: %s, scan start (TSF): %llu, tsf_bssid: " MAC_PR_FMT, BOOL_TO_STR(__entry->aborted), (unsigned long long)__entry->scan_start_tsf, MAC_PR_ARG(tsf_bssid)) ); DEFINE_EVENT(wiphy_only_evt, cfg80211_sched_scan_results, TP_PROTO(struct wiphy *wiphy), TP_ARGS(wiphy) ); DEFINE_EVENT(wiphy_only_evt, cfg80211_sched_scan_stopped, TP_PROTO(struct wiphy *wiphy), TP_ARGS(wiphy) ); TRACE_EVENT(cfg80211_get_bss, TP_PROTO(struct wiphy *wiphy, struct ieee80211_channel *channel, const u8 *bssid, const u8 *ssid, size_t ssid_len, enum ieee80211_bss_type bss_type, enum ieee80211_privacy privacy), TP_ARGS(wiphy, channel, bssid, ssid, ssid_len, bss_type, privacy), TP_STRUCT__entry( WIPHY_ENTRY CHAN_ENTRY MAC_ENTRY(bssid) __dynamic_array(u8, ssid, ssid_len) __field(enum ieee80211_bss_type, bss_type) __field(enum ieee80211_privacy, privacy) ), TP_fast_assign( WIPHY_ASSIGN; CHAN_ASSIGN(channel); MAC_ASSIGN(bssid, bssid); memcpy(__get_dynamic_array(ssid), ssid, ssid_len); __entry->bss_type = bss_type; __entry->privacy = privacy; ), TP_printk(WIPHY_PR_FMT ", " CHAN_PR_FMT ", " MAC_PR_FMT ", buf: %#.2x, bss_type: %d, privacy: %d", WIPHY_PR_ARG, CHAN_PR_ARG, MAC_PR_ARG(bssid), ((u8 *)__get_dynamic_array(ssid))[0], __entry->bss_type, __entry->privacy) ); TRACE_EVENT(cfg80211_inform_bss_frame, TP_PROTO(struct wiphy *wiphy, struct cfg80211_inform_bss *data, struct ieee80211_mgmt *mgmt, size_t len), TP_ARGS(wiphy, data, mgmt, len), TP_STRUCT__entry( WIPHY_ENTRY CHAN_ENTRY __field(enum nl80211_bss_scan_width, scan_width) __dynamic_array(u8, mgmt, len) __field(s32, signal) __field(u64, ts_boottime) __field(u64, parent_tsf) MAC_ENTRY(parent_bssid) ), TP_fast_assign( WIPHY_ASSIGN; CHAN_ASSIGN(data->chan); __entry->scan_width = data->scan_width; if (mgmt) memcpy(__get_dynamic_array(mgmt), mgmt, len); __entry->signal = data->signal; __entry->ts_boottime = data->boottime_ns; __entry->parent_tsf = data->parent_tsf; MAC_ASSIGN(parent_bssid, data->parent_bssid); ), TP_printk(WIPHY_PR_FMT ", " CHAN_PR_FMT "(scan_width: %d) signal: %d, tsb:%llu, detect_tsf:%llu, tsf_bssid: " MAC_PR_FMT, WIPHY_PR_ARG, CHAN_PR_ARG, __entry->scan_width, __entry->signal, (unsigned long long)__entry->ts_boottime, (unsigned long long)__entry->parent_tsf, MAC_PR_ARG(parent_bssid)) ); DECLARE_EVENT_CLASS(cfg80211_bss_evt, TP_PROTO(struct cfg80211_bss *pub), TP_ARGS(pub), TP_STRUCT__entry( MAC_ENTRY(bssid) CHAN_ENTRY ), TP_fast_assign( MAC_ASSIGN(bssid, pub->bssid); CHAN_ASSIGN(pub->channel); ), TP_printk(MAC_PR_FMT ", " CHAN_PR_FMT, MAC_PR_ARG(bssid), CHAN_PR_ARG) ); DEFINE_EVENT(cfg80211_bss_evt, cfg80211_return_bss, TP_PROTO(struct cfg80211_bss *pub), TP_ARGS(pub) ); TRACE_EVENT(cfg80211_return_uint, TP_PROTO(unsigned int ret), TP_ARGS(ret), TP_STRUCT__entry( __field(unsigned int, ret) ), TP_fast_assign( __entry->ret = ret; ), TP_printk("ret: %d", __entry->ret) ); TRACE_EVENT(cfg80211_return_u32, TP_PROTO(u32 ret), TP_ARGS(ret), TP_STRUCT__entry( __field(u32, ret) ), TP_fast_assign( __entry->ret = ret; ), TP_printk("ret: %u", __entry->ret) ); TRACE_EVENT(cfg80211_report_wowlan_wakeup, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev, struct cfg80211_wowlan_wakeup *wakeup), TP_ARGS(wiphy, wdev, wakeup), TP_STRUCT__entry( WIPHY_ENTRY WDEV_ENTRY __field(bool, non_wireless) __field(bool, disconnect) __field(bool, magic_pkt) __field(bool, gtk_rekey_failure) __field(bool, eap_identity_req) __field(bool, four_way_handshake) __field(bool, rfkill_release) __field(s32, pattern_idx) __field(u32, packet_len) __dynamic_array(u8, packet, wakeup ? wakeup->packet_present_len : 0) ), TP_fast_assign( WIPHY_ASSIGN; WDEV_ASSIGN; __entry->non_wireless = !wakeup; __entry->disconnect = wakeup ? wakeup->disconnect : false; __entry->magic_pkt = wakeup ? wakeup->magic_pkt : false; __entry->gtk_rekey_failure = wakeup ? wakeup->gtk_rekey_failure : false; __entry->eap_identity_req = wakeup ? wakeup->eap_identity_req : false; __entry->four_way_handshake = wakeup ? wakeup->four_way_handshake : false; __entry->rfkill_release = wakeup ? wakeup->rfkill_release : false; __entry->pattern_idx = wakeup ? wakeup->pattern_idx : false; __entry->packet_len = wakeup ? wakeup->packet_len : false; if (wakeup && wakeup->packet && wakeup->packet_present_len) memcpy(__get_dynamic_array(packet), wakeup->packet, wakeup->packet_present_len); ), TP_printk(WIPHY_PR_FMT ", " WDEV_PR_FMT, WIPHY_PR_ARG, WDEV_PR_ARG) ); TRACE_EVENT(cfg80211_ft_event, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_ft_event_params *ft_event), TP_ARGS(wiphy, netdev, ft_event), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY __dynamic_array(u8, ies, ft_event->ies_len) MAC_ENTRY(target_ap) __dynamic_array(u8, ric_ies, ft_event->ric_ies_len) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; if (ft_event->ies) memcpy(__get_dynamic_array(ies), ft_event->ies, ft_event->ies_len); MAC_ASSIGN(target_ap, ft_event->target_ap); if (ft_event->ric_ies) memcpy(__get_dynamic_array(ric_ies), ft_event->ric_ies, ft_event->ric_ies_len); ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", target_ap: " MAC_PR_FMT, WIPHY_PR_ARG, NETDEV_PR_ARG, MAC_PR_ARG(target_ap)) ); TRACE_EVENT(cfg80211_stop_iface, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev), TP_ARGS(wiphy, wdev), TP_STRUCT__entry( WIPHY_ENTRY WDEV_ENTRY ), TP_fast_assign( WIPHY_ASSIGN; WDEV_ASSIGN; ), TP_printk(WIPHY_PR_FMT ", " WDEV_PR_FMT, WIPHY_PR_ARG, WDEV_PR_ARG) ); TRACE_EVENT(rdev_start_radar_detection, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_chan_def *chandef, u32 cac_time_ms), TP_ARGS(wiphy, netdev, chandef, cac_time_ms), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY CHAN_DEF_ENTRY __field(u32, cac_time_ms) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; CHAN_DEF_ASSIGN(chandef); __entry->cac_time_ms = cac_time_ms; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", " CHAN_DEF_PR_FMT ", cac_time_ms=%u", WIPHY_PR_ARG, NETDEV_PR_ARG, CHAN_DEF_PR_ARG, __entry->cac_time_ms) ); TRACE_EVENT(rdev_set_mcast_rate, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, int mcast_rate[NUM_NL80211_BANDS]), TP_ARGS(wiphy, netdev, mcast_rate), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY __array(int, mcast_rate, NUM_NL80211_BANDS) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; memcpy(__entry->mcast_rate, mcast_rate, sizeof(int) * NUM_NL80211_BANDS); ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", " "mcast_rates [2.4GHz=0x%x, 5.2GHz=0x%x, 60GHz=0x%x]", WIPHY_PR_ARG, NETDEV_PR_ARG, __entry->mcast_rate[NL80211_BAND_2GHZ], __entry->mcast_rate[NL80211_BAND_5GHZ], __entry->mcast_rate[NL80211_BAND_60GHZ]) ); TRACE_EVENT(rdev_set_coalesce, TP_PROTO(struct wiphy *wiphy, struct cfg80211_coalesce *coalesce), TP_ARGS(wiphy, coalesce), TP_STRUCT__entry( WIPHY_ENTRY __field(int, n_rules) ), TP_fast_assign( WIPHY_ASSIGN; __entry->n_rules = coalesce ? coalesce->n_rules : 0; ), TP_printk(WIPHY_PR_FMT ", n_rules=%d", WIPHY_PR_ARG, __entry->n_rules) ); DEFINE_EVENT(wiphy_wdev_evt, rdev_abort_scan, TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev), TP_ARGS(wiphy, wdev) ); TRACE_EVENT(rdev_set_multicast_to_unicast, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, const bool enabled), TP_ARGS(wiphy, netdev, enabled), TP_STRUCT__entry( WIPHY_ENTRY NETDEV_ENTRY __field(bool, enabled) ), TP_fast_assign( WIPHY_ASSIGN; NETDEV_ASSIGN; __entry->enabled = enabled; ), TP_printk(WIPHY_PR_FMT ", " NETDEV_PR_FMT ", unicast: %s", WIPHY_PR_ARG, NETDEV_PR_ARG, BOOL_TO_STR(__entry->enabled)) ); #endif /* !__RDEV_OPS_TRACE || TRACE_HEADER_MULTI_READ */ #undef TRACE_INCLUDE_PATH #define TRACE_INCLUDE_PATH . #undef TRACE_INCLUDE_FILE #define TRACE_INCLUDE_FILE trace #include <trace/define_trace.h>
null
null
null
null
76,236
2,175
1
train_val
3ff403eecdd23a39853a4ebca52023fbba6c5d00
2,175
Chrome
1
https://github.com/chromium/chromium
2017-08-07 04:22:48+00:00
bool MessageLoop::NestableTasksAllowed() const { return nestable_tasks_allowed_; }
CVE-2015-1294
null
https://github.com/chromium/chromium/commit/3ff403eecdd23a39853a4ebca52023fbba6c5d00
Low
2,175
5,816
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
170,811
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * rt298.c -- RT298 ALSA SoC audio codec driver * * Copyright 2015 Realtek Semiconductor Corp. * Author: Bard Liao <bardliao@realtek.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. */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/pm.h> #include <linux/i2c.h> #include <linux/platform_device.h> #include <linux/spi/spi.h> #include <linux/dmi.h> #include <linux/acpi.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/soc.h> #include <sound/soc-dapm.h> #include <sound/initval.h> #include <sound/tlv.h> #include <sound/jack.h> #include <linux/workqueue.h> #include <sound/rt298.h> #include "rl6347a.h" #include "rt298.h" #define RT298_VENDOR_ID 0x10ec0298 struct rt298_priv { struct reg_default *index_cache; int index_cache_size; struct regmap *regmap; struct snd_soc_codec *codec; struct rt298_platform_data pdata; struct i2c_client *i2c; struct snd_soc_jack *jack; struct delayed_work jack_detect_work; int sys_clk; int clk_id; int is_hp_in; }; static const struct reg_default rt298_index_def[] = { { 0x01, 0xa5a8 }, { 0x02, 0x8e95 }, { 0x03, 0x0002 }, { 0x04, 0xaf67 }, { 0x08, 0x200f }, { 0x09, 0xd010 }, { 0x0a, 0x0100 }, { 0x0b, 0x0000 }, { 0x0d, 0x2800 }, { 0x0f, 0x0022 }, { 0x19, 0x0217 }, { 0x20, 0x0020 }, { 0x33, 0x0208 }, { 0x46, 0x0300 }, { 0x49, 0x4004 }, { 0x4f, 0x50c9 }, { 0x50, 0x3000 }, { 0x63, 0x1b02 }, { 0x67, 0x1111 }, { 0x68, 0x1016 }, { 0x69, 0x273f }, }; #define INDEX_CACHE_SIZE ARRAY_SIZE(rt298_index_def) static const struct reg_default rt298_reg[] = { { 0x00170500, 0x00000400 }, { 0x00220000, 0x00000031 }, { 0x00239000, 0x0000007f }, { 0x0023a000, 0x0000007f }, { 0x00270500, 0x00000400 }, { 0x00370500, 0x00000400 }, { 0x00870500, 0x00000400 }, { 0x00920000, 0x00000031 }, { 0x00935000, 0x000000c3 }, { 0x00936000, 0x000000c3 }, { 0x00970500, 0x00000400 }, { 0x00b37000, 0x00000097 }, { 0x00b37200, 0x00000097 }, { 0x00b37300, 0x00000097 }, { 0x00c37000, 0x00000000 }, { 0x00c37100, 0x00000080 }, { 0x01270500, 0x00000400 }, { 0x01370500, 0x00000400 }, { 0x01371f00, 0x411111f0 }, { 0x01439000, 0x00000080 }, { 0x0143a000, 0x00000080 }, { 0x01470700, 0x00000000 }, { 0x01470500, 0x00000400 }, { 0x01470c00, 0x00000000 }, { 0x01470100, 0x00000000 }, { 0x01837000, 0x00000000 }, { 0x01870500, 0x00000400 }, { 0x02050000, 0x00000000 }, { 0x02139000, 0x00000080 }, { 0x0213a000, 0x00000080 }, { 0x02170100, 0x00000000 }, { 0x02170500, 0x00000400 }, { 0x02170700, 0x00000000 }, { 0x02270100, 0x00000000 }, { 0x02370100, 0x00000000 }, { 0x01870700, 0x00000020 }, { 0x00830000, 0x000000c3 }, { 0x00930000, 0x000000c3 }, { 0x01270700, 0x00000000 }, }; static bool rt298_volatile_register(struct device *dev, unsigned int reg) { switch (reg) { case 0 ... 0xff: case RT298_GET_PARAM(AC_NODE_ROOT, AC_PAR_VENDOR_ID): case RT298_GET_HP_SENSE: case RT298_GET_MIC1_SENSE: case RT298_PROC_COEF: case VERB_CMD(AC_VERB_GET_EAPD_BTLENABLE, RT298_MIC1, 0): case VERB_CMD(AC_VERB_GET_EAPD_BTLENABLE, RT298_SPK_OUT, 0): case VERB_CMD(AC_VERB_GET_EAPD_BTLENABLE, RT298_HP_OUT, 0): return true; default: return false; } } static bool rt298_readable_register(struct device *dev, unsigned int reg) { switch (reg) { case 0 ... 0xff: case RT298_GET_PARAM(AC_NODE_ROOT, AC_PAR_VENDOR_ID): case RT298_GET_HP_SENSE: case RT298_GET_MIC1_SENSE: case RT298_SET_AUDIO_POWER: case RT298_SET_HPO_POWER: case RT298_SET_SPK_POWER: case RT298_SET_DMIC1_POWER: case RT298_SPK_MUX: case RT298_HPO_MUX: case RT298_ADC0_MUX: case RT298_ADC1_MUX: case RT298_SET_MIC1: case RT298_SET_PIN_HPO: case RT298_SET_PIN_SPK: case RT298_SET_PIN_DMIC1: case RT298_SPK_EAPD: case RT298_SET_AMP_GAIN_HPO: case RT298_SET_DMIC2_DEFAULT: case RT298_DACL_GAIN: case RT298_DACR_GAIN: case RT298_ADCL_GAIN: case RT298_ADCR_GAIN: case RT298_MIC_GAIN: case RT298_SPOL_GAIN: case RT298_SPOR_GAIN: case RT298_HPOL_GAIN: case RT298_HPOR_GAIN: case RT298_F_DAC_SWITCH: case RT298_F_RECMIX_SWITCH: case RT298_REC_MIC_SWITCH: case RT298_REC_I2S_SWITCH: case RT298_REC_LINE_SWITCH: case RT298_REC_BEEP_SWITCH: case RT298_DAC_FORMAT: case RT298_ADC_FORMAT: case RT298_COEF_INDEX: case RT298_PROC_COEF: case RT298_SET_AMP_GAIN_ADC_IN1: case RT298_SET_AMP_GAIN_ADC_IN2: case RT298_SET_POWER(RT298_DAC_OUT1): case RT298_SET_POWER(RT298_DAC_OUT2): case RT298_SET_POWER(RT298_ADC_IN1): case RT298_SET_POWER(RT298_ADC_IN2): case RT298_SET_POWER(RT298_DMIC2): case RT298_SET_POWER(RT298_MIC1): case VERB_CMD(AC_VERB_GET_EAPD_BTLENABLE, RT298_MIC1, 0): case VERB_CMD(AC_VERB_GET_EAPD_BTLENABLE, RT298_SPK_OUT, 0): case VERB_CMD(AC_VERB_GET_EAPD_BTLENABLE, RT298_HP_OUT, 0): return true; default: return false; } } #ifdef CONFIG_PM static void rt298_index_sync(struct snd_soc_codec *codec) { struct rt298_priv *rt298 = snd_soc_codec_get_drvdata(codec); int i; for (i = 0; i < INDEX_CACHE_SIZE; i++) { snd_soc_write(codec, rt298->index_cache[i].reg, rt298->index_cache[i].def); } } #endif static int rt298_support_power_controls[] = { RT298_DAC_OUT1, RT298_DAC_OUT2, RT298_ADC_IN1, RT298_ADC_IN2, RT298_MIC1, RT298_DMIC1, RT298_DMIC2, RT298_SPK_OUT, RT298_HP_OUT, }; #define RT298_POWER_REG_LEN ARRAY_SIZE(rt298_support_power_controls) static int rt298_jack_detect(struct rt298_priv *rt298, bool *hp, bool *mic) { struct snd_soc_dapm_context *dapm; unsigned int val, buf; *hp = false; *mic = false; if (!rt298->codec) return -EINVAL; dapm = snd_soc_codec_get_dapm(rt298->codec); if (rt298->pdata.cbj_en) { regmap_read(rt298->regmap, RT298_GET_HP_SENSE, &buf); *hp = buf & 0x80000000; if (*hp == rt298->is_hp_in) return -1; rt298->is_hp_in = *hp; if (*hp) { /* power on HV,VERF */ regmap_update_bits(rt298->regmap, RT298_DC_GAIN, 0x200, 0x200); snd_soc_dapm_force_enable_pin(dapm, "HV"); snd_soc_dapm_force_enable_pin(dapm, "VREF"); /* power LDO1 */ snd_soc_dapm_force_enable_pin(dapm, "LDO1"); snd_soc_dapm_sync(dapm); regmap_update_bits(rt298->regmap, RT298_POWER_CTRL1, 0x1001, 0); regmap_update_bits(rt298->regmap, RT298_POWER_CTRL2, 0x4, 0x4); regmap_write(rt298->regmap, RT298_SET_MIC1, 0x24); msleep(50); regmap_update_bits(rt298->regmap, RT298_CBJ_CTRL1, 0xfcc0, 0xd400); msleep(300); regmap_read(rt298->regmap, RT298_CBJ_CTRL2, &val); if (0x0070 == (val & 0x0070)) { *mic = true; } else { regmap_update_bits(rt298->regmap, RT298_CBJ_CTRL1, 0xfcc0, 0xe400); msleep(300); regmap_read(rt298->regmap, RT298_CBJ_CTRL2, &val); if (0x0070 == (val & 0x0070)) *mic = true; else *mic = false; } regmap_update_bits(rt298->regmap, RT298_DC_GAIN, 0x200, 0x0); } else { *mic = false; regmap_write(rt298->regmap, RT298_SET_MIC1, 0x20); regmap_update_bits(rt298->regmap, RT298_CBJ_CTRL1, 0x0400, 0x0000); } } else { regmap_read(rt298->regmap, RT298_GET_HP_SENSE, &buf); *hp = buf & 0x80000000; regmap_read(rt298->regmap, RT298_GET_MIC1_SENSE, &buf); *mic = buf & 0x80000000; } snd_soc_dapm_disable_pin(dapm, "HV"); snd_soc_dapm_disable_pin(dapm, "VREF"); if (!*hp) snd_soc_dapm_disable_pin(dapm, "LDO1"); snd_soc_dapm_sync(dapm); pr_debug("*hp = %d *mic = %d\n", *hp, *mic); return 0; } static void rt298_jack_detect_work(struct work_struct *work) { struct rt298_priv *rt298 = container_of(work, struct rt298_priv, jack_detect_work.work); int status = 0; bool hp = false; bool mic = false; if (rt298_jack_detect(rt298, &hp, &mic) < 0) return; if (hp == true) status |= SND_JACK_HEADPHONE; if (mic == true) status |= SND_JACK_MICROPHONE; snd_soc_jack_report(rt298->jack, status, SND_JACK_MICROPHONE | SND_JACK_HEADPHONE); } int rt298_mic_detect(struct snd_soc_codec *codec, struct snd_soc_jack *jack) { struct rt298_priv *rt298 = snd_soc_codec_get_drvdata(codec); struct snd_soc_dapm_context *dapm; bool hp = false; bool mic = false; int status = 0; /* If jack in NULL, disable HS jack */ if (!jack) { regmap_update_bits(rt298->regmap, RT298_IRQ_CTRL, 0x2, 0x0); dapm = snd_soc_codec_get_dapm(codec); snd_soc_dapm_disable_pin(dapm, "LDO1"); snd_soc_dapm_sync(dapm); return 0; } rt298->jack = jack; regmap_update_bits(rt298->regmap, RT298_IRQ_CTRL, 0x2, 0x2); rt298_jack_detect(rt298, &hp, &mic); if (hp == true) status |= SND_JACK_HEADPHONE; if (mic == true) status |= SND_JACK_MICROPHONE; snd_soc_jack_report(rt298->jack, status, SND_JACK_MICROPHONE | SND_JACK_HEADPHONE); return 0; } EXPORT_SYMBOL_GPL(rt298_mic_detect); static int is_mclk_mode(struct snd_soc_dapm_widget *source, struct snd_soc_dapm_widget *sink) { struct snd_soc_codec *codec = snd_soc_dapm_to_codec(source->dapm); struct rt298_priv *rt298 = snd_soc_codec_get_drvdata(codec); if (rt298->clk_id == RT298_SCLK_S_MCLK) return 1; else return 0; } static const DECLARE_TLV_DB_SCALE(out_vol_tlv, -6350, 50, 0); static const DECLARE_TLV_DB_SCALE(mic_vol_tlv, 0, 1000, 0); static const struct snd_kcontrol_new rt298_snd_controls[] = { SOC_DOUBLE_R_TLV("DAC0 Playback Volume", RT298_DACL_GAIN, RT298_DACR_GAIN, 0, 0x7f, 0, out_vol_tlv), SOC_DOUBLE_R_TLV("ADC0 Capture Volume", RT298_ADCL_GAIN, RT298_ADCR_GAIN, 0, 0x7f, 0, out_vol_tlv), SOC_SINGLE_TLV("AMIC Volume", RT298_MIC_GAIN, 0, 0x3, 0, mic_vol_tlv), SOC_DOUBLE_R("Speaker Playback Switch", RT298_SPOL_GAIN, RT298_SPOR_GAIN, RT298_MUTE_SFT, 1, 1), }; /* Digital Mixer */ static const struct snd_kcontrol_new rt298_front_mix[] = { SOC_DAPM_SINGLE("DAC Switch", RT298_F_DAC_SWITCH, RT298_MUTE_SFT, 1, 1), SOC_DAPM_SINGLE("RECMIX Switch", RT298_F_RECMIX_SWITCH, RT298_MUTE_SFT, 1, 1), }; /* Analog Input Mixer */ static const struct snd_kcontrol_new rt298_rec_mix[] = { SOC_DAPM_SINGLE("Mic1 Switch", RT298_REC_MIC_SWITCH, RT298_MUTE_SFT, 1, 1), SOC_DAPM_SINGLE("I2S Switch", RT298_REC_I2S_SWITCH, RT298_MUTE_SFT, 1, 1), SOC_DAPM_SINGLE("Line1 Switch", RT298_REC_LINE_SWITCH, RT298_MUTE_SFT, 1, 1), SOC_DAPM_SINGLE("Beep Switch", RT298_REC_BEEP_SWITCH, RT298_MUTE_SFT, 1, 1), }; static const struct snd_kcontrol_new spo_enable_control = SOC_DAPM_SINGLE("Switch", RT298_SET_PIN_SPK, RT298_SET_PIN_SFT, 1, 0); static const struct snd_kcontrol_new hpol_enable_control = SOC_DAPM_SINGLE_AUTODISABLE("Switch", RT298_HPOL_GAIN, RT298_MUTE_SFT, 1, 1); static const struct snd_kcontrol_new hpor_enable_control = SOC_DAPM_SINGLE_AUTODISABLE("Switch", RT298_HPOR_GAIN, RT298_MUTE_SFT, 1, 1); /* ADC0 source */ static const char * const rt298_adc_src[] = { "Mic", "RECMIX", "Dmic" }; static const int rt298_adc_values[] = { 0, 4, 5, }; static SOC_VALUE_ENUM_SINGLE_DECL( rt298_adc0_enum, RT298_ADC0_MUX, RT298_ADC_SEL_SFT, RT298_ADC_SEL_MASK, rt298_adc_src, rt298_adc_values); static const struct snd_kcontrol_new rt298_adc0_mux = SOC_DAPM_ENUM("ADC 0 source", rt298_adc0_enum); static SOC_VALUE_ENUM_SINGLE_DECL( rt298_adc1_enum, RT298_ADC1_MUX, RT298_ADC_SEL_SFT, RT298_ADC_SEL_MASK, rt298_adc_src, rt298_adc_values); static const struct snd_kcontrol_new rt298_adc1_mux = SOC_DAPM_ENUM("ADC 1 source", rt298_adc1_enum); static const char * const rt298_dac_src[] = { "Front", "Surround" }; /* HP-OUT source */ static SOC_ENUM_SINGLE_DECL(rt298_hpo_enum, RT298_HPO_MUX, 0, rt298_dac_src); static const struct snd_kcontrol_new rt298_hpo_mux = SOC_DAPM_ENUM("HPO source", rt298_hpo_enum); /* SPK-OUT source */ static SOC_ENUM_SINGLE_DECL(rt298_spo_enum, RT298_SPK_MUX, 0, rt298_dac_src); static const struct snd_kcontrol_new rt298_spo_mux = SOC_DAPM_ENUM("SPO source", rt298_spo_enum); static int rt298_spk_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = snd_soc_dapm_to_codec(w->dapm); switch (event) { case SND_SOC_DAPM_POST_PMU: snd_soc_write(codec, RT298_SPK_EAPD, RT298_SET_EAPD_HIGH); break; case SND_SOC_DAPM_PRE_PMD: snd_soc_write(codec, RT298_SPK_EAPD, RT298_SET_EAPD_LOW); break; default: return 0; } return 0; } static int rt298_set_dmic1_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = snd_soc_dapm_to_codec(w->dapm); switch (event) { case SND_SOC_DAPM_POST_PMU: snd_soc_write(codec, RT298_SET_PIN_DMIC1, 0x20); break; case SND_SOC_DAPM_PRE_PMD: snd_soc_write(codec, RT298_SET_PIN_DMIC1, 0); break; default: return 0; } return 0; } static int rt298_adc_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = snd_soc_dapm_to_codec(w->dapm); unsigned int nid; nid = (w->reg >> 20) & 0xff; switch (event) { case SND_SOC_DAPM_POST_PMU: snd_soc_update_bits(codec, VERB_CMD(AC_VERB_SET_AMP_GAIN_MUTE, nid, 0), 0x7080, 0x7000); /* If MCLK doesn't exist, reset AD filter */ if (!(snd_soc_read(codec, RT298_VAD_CTRL) & 0x200)) { pr_info("NO MCLK\n"); switch (nid) { case RT298_ADC_IN1: snd_soc_update_bits(codec, RT298_D_FILTER_CTRL, 0x2, 0x2); mdelay(10); snd_soc_update_bits(codec, RT298_D_FILTER_CTRL, 0x2, 0x0); break; case RT298_ADC_IN2: snd_soc_update_bits(codec, RT298_D_FILTER_CTRL, 0x4, 0x4); mdelay(10); snd_soc_update_bits(codec, RT298_D_FILTER_CTRL, 0x4, 0x0); break; } } break; case SND_SOC_DAPM_PRE_PMD: snd_soc_update_bits(codec, VERB_CMD(AC_VERB_SET_AMP_GAIN_MUTE, nid, 0), 0x7080, 0x7080); break; default: return 0; } return 0; } static int rt298_mic1_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = snd_soc_dapm_to_codec(w->dapm); switch (event) { case SND_SOC_DAPM_PRE_PMU: snd_soc_update_bits(codec, RT298_A_BIAS_CTRL3, 0xc000, 0x8000); snd_soc_update_bits(codec, RT298_A_BIAS_CTRL2, 0xc000, 0x8000); break; case SND_SOC_DAPM_POST_PMD: snd_soc_update_bits(codec, RT298_A_BIAS_CTRL3, 0xc000, 0x0000); snd_soc_update_bits(codec, RT298_A_BIAS_CTRL2, 0xc000, 0x0000); break; default: return 0; } return 0; } static const struct snd_soc_dapm_widget rt298_dapm_widgets[] = { SND_SOC_DAPM_SUPPLY_S("HV", 1, RT298_POWER_CTRL1, 12, 1, NULL, 0), SND_SOC_DAPM_SUPPLY("VREF", RT298_POWER_CTRL1, 0, 1, NULL, 0), SND_SOC_DAPM_SUPPLY_S("BG_MBIAS", 1, RT298_POWER_CTRL2, 1, 0, NULL, 0), SND_SOC_DAPM_SUPPLY_S("LDO1", 1, RT298_POWER_CTRL2, 2, 0, NULL, 0), SND_SOC_DAPM_SUPPLY_S("LDO2", 1, RT298_POWER_CTRL2, 3, 0, NULL, 0), SND_SOC_DAPM_SUPPLY_S("VREF1", 1, RT298_POWER_CTRL2, 4, 1, NULL, 0), SND_SOC_DAPM_SUPPLY_S("LV", 2, RT298_POWER_CTRL1, 13, 1, NULL, 0), SND_SOC_DAPM_SUPPLY("MCLK MODE", RT298_PLL_CTRL1, 5, 0, NULL, 0), SND_SOC_DAPM_SUPPLY("MIC1 Input Buffer", SND_SOC_NOPM, 0, 0, rt298_mic1_event, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), /* Input Lines */ SND_SOC_DAPM_INPUT("DMIC1 Pin"), SND_SOC_DAPM_INPUT("DMIC2 Pin"), SND_SOC_DAPM_INPUT("MIC1"), SND_SOC_DAPM_INPUT("LINE1"), SND_SOC_DAPM_INPUT("Beep"), /* DMIC */ SND_SOC_DAPM_PGA_E("DMIC1", RT298_SET_POWER(RT298_DMIC1), 0, 1, NULL, 0, rt298_set_dmic1_event, SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMU), SND_SOC_DAPM_PGA("DMIC2", RT298_SET_POWER(RT298_DMIC2), 0, 1, NULL, 0), SND_SOC_DAPM_SUPPLY("DMIC Receiver", SND_SOC_NOPM, 0, 0, NULL, 0), /* REC Mixer */ SND_SOC_DAPM_MIXER("RECMIX", SND_SOC_NOPM, 0, 0, rt298_rec_mix, ARRAY_SIZE(rt298_rec_mix)), /* ADCs */ SND_SOC_DAPM_ADC("ADC 0", NULL, SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_ADC("ADC 1", NULL, SND_SOC_NOPM, 0, 0), /* ADC Mux */ SND_SOC_DAPM_MUX_E("ADC 0 Mux", RT298_SET_POWER(RT298_ADC_IN1), 0, 1, &rt298_adc0_mux, rt298_adc_event, SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMU), SND_SOC_DAPM_MUX_E("ADC 1 Mux", RT298_SET_POWER(RT298_ADC_IN2), 0, 1, &rt298_adc1_mux, rt298_adc_event, SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMU), /* Audio Interface */ SND_SOC_DAPM_AIF_IN("AIF1RX", "AIF1 Playback", 0, SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_AIF_OUT("AIF1TX", "AIF1 Capture", 0, SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_AIF_IN("AIF2RX", "AIF2 Playback", 0, SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_AIF_OUT("AIF2TX", "AIF2 Capture", 0, SND_SOC_NOPM, 0, 0), /* Output Side */ /* DACs */ SND_SOC_DAPM_DAC("DAC 0", NULL, SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_DAC("DAC 1", NULL, SND_SOC_NOPM, 0, 0), /* Output Mux */ SND_SOC_DAPM_MUX("SPK Mux", SND_SOC_NOPM, 0, 0, &rt298_spo_mux), SND_SOC_DAPM_MUX("HPO Mux", SND_SOC_NOPM, 0, 0, &rt298_hpo_mux), SND_SOC_DAPM_SUPPLY("HP Power", RT298_SET_PIN_HPO, RT298_SET_PIN_SFT, 0, NULL, 0), /* Output Mixer */ SND_SOC_DAPM_MIXER("Front", RT298_SET_POWER(RT298_DAC_OUT1), 0, 1, rt298_front_mix, ARRAY_SIZE(rt298_front_mix)), SND_SOC_DAPM_PGA("Surround", RT298_SET_POWER(RT298_DAC_OUT2), 0, 1, NULL, 0), /* Output Pga */ SND_SOC_DAPM_SWITCH_E("SPO", SND_SOC_NOPM, 0, 0, &spo_enable_control, rt298_spk_event, SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMU), SND_SOC_DAPM_SWITCH("HPO L", SND_SOC_NOPM, 0, 0, &hpol_enable_control), SND_SOC_DAPM_SWITCH("HPO R", SND_SOC_NOPM, 0, 0, &hpor_enable_control), /* Output Lines */ SND_SOC_DAPM_OUTPUT("SPOL"), SND_SOC_DAPM_OUTPUT("SPOR"), SND_SOC_DAPM_OUTPUT("HPO Pin"), SND_SOC_DAPM_OUTPUT("SPDIF"), }; static const struct snd_soc_dapm_route rt298_dapm_routes[] = { {"ADC 0", NULL, "MCLK MODE", is_mclk_mode}, {"ADC 1", NULL, "MCLK MODE", is_mclk_mode}, {"Front", NULL, "MCLK MODE", is_mclk_mode}, {"Surround", NULL, "MCLK MODE", is_mclk_mode}, {"HP Power", NULL, "LDO1"}, {"HP Power", NULL, "LDO2"}, {"HP Power", NULL, "LV"}, {"HP Power", NULL, "VREF1"}, {"HP Power", NULL, "BG_MBIAS"}, {"MIC1", NULL, "LDO1"}, {"MIC1", NULL, "LDO2"}, {"MIC1", NULL, "HV"}, {"MIC1", NULL, "LV"}, {"MIC1", NULL, "VREF"}, {"MIC1", NULL, "VREF1"}, {"MIC1", NULL, "BG_MBIAS"}, {"MIC1", NULL, "MIC1 Input Buffer"}, {"SPO", NULL, "LDO1"}, {"SPO", NULL, "LDO2"}, {"SPO", NULL, "HV"}, {"SPO", NULL, "LV"}, {"SPO", NULL, "VREF"}, {"SPO", NULL, "VREF1"}, {"SPO", NULL, "BG_MBIAS"}, {"DMIC1", NULL, "DMIC1 Pin"}, {"DMIC2", NULL, "DMIC2 Pin"}, {"DMIC1", NULL, "DMIC Receiver"}, {"DMIC2", NULL, "DMIC Receiver"}, {"RECMIX", "Beep Switch", "Beep"}, {"RECMIX", "Line1 Switch", "LINE1"}, {"RECMIX", "Mic1 Switch", "MIC1"}, {"ADC 0 Mux", "Dmic", "DMIC1"}, {"ADC 0 Mux", "RECMIX", "RECMIX"}, {"ADC 0 Mux", "Mic", "MIC1"}, {"ADC 1 Mux", "Dmic", "DMIC2"}, {"ADC 1 Mux", "RECMIX", "RECMIX"}, {"ADC 1 Mux", "Mic", "MIC1"}, {"ADC 0", NULL, "ADC 0 Mux"}, {"ADC 1", NULL, "ADC 1 Mux"}, {"AIF1TX", NULL, "ADC 0"}, {"AIF2TX", NULL, "ADC 1"}, {"DAC 0", NULL, "AIF1RX"}, {"DAC 1", NULL, "AIF2RX"}, {"Front", "DAC Switch", "DAC 0"}, {"Front", "RECMIX Switch", "RECMIX"}, {"Surround", NULL, "DAC 1"}, {"SPK Mux", "Front", "Front"}, {"SPK Mux", "Surround", "Surround"}, {"HPO Mux", "Front", "Front"}, {"HPO Mux", "Surround", "Surround"}, {"SPO", "Switch", "SPK Mux"}, {"HPO L", "Switch", "HPO Mux"}, {"HPO R", "Switch", "HPO Mux"}, {"HPO L", NULL, "HP Power"}, {"HPO R", NULL, "HP Power"}, {"SPOL", NULL, "SPO"}, {"SPOR", NULL, "SPO"}, {"HPO Pin", NULL, "HPO L"}, {"HPO Pin", NULL, "HPO R"}, }; static int rt298_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct snd_soc_codec *codec = dai->codec; struct rt298_priv *rt298 = snd_soc_codec_get_drvdata(codec); unsigned int val = 0; int d_len_code; switch (params_rate(params)) { /* bit 14 0:48K 1:44.1K */ case 44100: case 48000: break; default: dev_err(codec->dev, "Unsupported sample rate %d\n", params_rate(params)); return -EINVAL; } switch (rt298->sys_clk) { case 12288000: case 24576000: if (params_rate(params) != 48000) { dev_err(codec->dev, "Sys_clk is not matched (%d %d)\n", params_rate(params), rt298->sys_clk); return -EINVAL; } break; case 11289600: case 22579200: if (params_rate(params) != 44100) { dev_err(codec->dev, "Sys_clk is not matched (%d %d)\n", params_rate(params), rt298->sys_clk); return -EINVAL; } break; } if (params_channels(params) <= 16) { /* bit 3:0 Number of Channel */ val |= (params_channels(params) - 1); } else { dev_err(codec->dev, "Unsupported channels %d\n", params_channels(params)); return -EINVAL; } d_len_code = 0; switch (params_width(params)) { /* bit 6:4 Bits per Sample */ case 16: d_len_code = 0; val |= (0x1 << 4); break; case 32: d_len_code = 2; val |= (0x4 << 4); break; case 20: d_len_code = 1; val |= (0x2 << 4); break; case 24: d_len_code = 2; val |= (0x3 << 4); break; case 8: d_len_code = 3; break; default: return -EINVAL; } snd_soc_update_bits(codec, RT298_I2S_CTRL1, 0x0018, d_len_code << 3); dev_dbg(codec->dev, "format val = 0x%x\n", val); snd_soc_update_bits(codec, RT298_DAC_FORMAT, 0x407f, val); snd_soc_update_bits(codec, RT298_ADC_FORMAT, 0x407f, val); return 0; } static int rt298_set_dai_fmt(struct snd_soc_dai *dai, unsigned int fmt) { struct snd_soc_codec *codec = dai->codec; switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) { case SND_SOC_DAIFMT_CBM_CFM: snd_soc_update_bits(codec, RT298_I2S_CTRL1, 0x800, 0x800); break; case SND_SOC_DAIFMT_CBS_CFS: snd_soc_update_bits(codec, RT298_I2S_CTRL1, 0x800, 0x0); break; default: return -EINVAL; } switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { case SND_SOC_DAIFMT_I2S: snd_soc_update_bits(codec, RT298_I2S_CTRL1, 0x300, 0x0); break; case SND_SOC_DAIFMT_LEFT_J: snd_soc_update_bits(codec, RT298_I2S_CTRL1, 0x300, 0x1 << 8); break; case SND_SOC_DAIFMT_DSP_A: snd_soc_update_bits(codec, RT298_I2S_CTRL1, 0x300, 0x2 << 8); break; case SND_SOC_DAIFMT_DSP_B: snd_soc_update_bits(codec, RT298_I2S_CTRL1, 0x300, 0x3 << 8); break; default: return -EINVAL; } /* bit 15 Stream Type 0:PCM 1:Non-PCM */ snd_soc_update_bits(codec, RT298_DAC_FORMAT, 0x8000, 0); snd_soc_update_bits(codec, RT298_ADC_FORMAT, 0x8000, 0); return 0; } static int rt298_set_dai_sysclk(struct snd_soc_dai *dai, int clk_id, unsigned int freq, int dir) { struct snd_soc_codec *codec = dai->codec; struct rt298_priv *rt298 = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s freq=%d\n", __func__, freq); if (RT298_SCLK_S_MCLK == clk_id) { snd_soc_update_bits(codec, RT298_I2S_CTRL2, 0x0100, 0x0); snd_soc_update_bits(codec, RT298_PLL_CTRL1, 0x20, 0x20); } else { snd_soc_update_bits(codec, RT298_I2S_CTRL2, 0x0100, 0x0100); snd_soc_update_bits(codec, RT298_PLL_CTRL1, 0x20, 0x0); } switch (freq) { case 19200000: if (RT298_SCLK_S_MCLK == clk_id) { dev_err(codec->dev, "Should not use MCLK\n"); return -EINVAL; } snd_soc_update_bits(codec, RT298_I2S_CTRL2, 0x40, 0x40); break; case 24000000: if (RT298_SCLK_S_MCLK == clk_id) { dev_err(codec->dev, "Should not use MCLK\n"); return -EINVAL; } snd_soc_update_bits(codec, RT298_I2S_CTRL2, 0x40, 0x0); break; case 12288000: case 11289600: snd_soc_update_bits(codec, RT298_I2S_CTRL2, 0x8, 0x0); snd_soc_update_bits(codec, RT298_CLK_DIV, 0xfc1e, 0x0004); break; case 24576000: case 22579200: snd_soc_update_bits(codec, RT298_I2S_CTRL2, 0x8, 0x8); snd_soc_update_bits(codec, RT298_CLK_DIV, 0xfc1e, 0x5406); break; default: dev_err(codec->dev, "Unsupported system clock\n"); return -EINVAL; } rt298->sys_clk = freq; rt298->clk_id = clk_id; return 0; } static int rt298_set_bclk_ratio(struct snd_soc_dai *dai, unsigned int ratio) { struct snd_soc_codec *codec = dai->codec; dev_dbg(codec->dev, "%s ratio=%d\n", __func__, ratio); if (50 == ratio) snd_soc_update_bits(codec, RT298_I2S_CTRL1, 0x1000, 0x1000); else snd_soc_update_bits(codec, RT298_I2S_CTRL1, 0x1000, 0x0); return 0; } static int rt298_set_bias_level(struct snd_soc_codec *codec, enum snd_soc_bias_level level) { switch (level) { case SND_SOC_BIAS_PREPARE: if (SND_SOC_BIAS_STANDBY == snd_soc_codec_get_bias_level(codec)) { snd_soc_write(codec, RT298_SET_AUDIO_POWER, AC_PWRST_D0); snd_soc_update_bits(codec, 0x0d, 0x200, 0x200); snd_soc_update_bits(codec, 0x52, 0x80, 0x0); mdelay(20); snd_soc_update_bits(codec, 0x0d, 0x200, 0x0); snd_soc_update_bits(codec, 0x52, 0x80, 0x80); } break; case SND_SOC_BIAS_STANDBY: snd_soc_write(codec, RT298_SET_AUDIO_POWER, AC_PWRST_D3); break; default: break; } return 0; } static irqreturn_t rt298_irq(int irq, void *data) { struct rt298_priv *rt298 = data; bool hp = false; bool mic = false; int ret, status = 0; ret = rt298_jack_detect(rt298, &hp, &mic); /* Clear IRQ */ regmap_update_bits(rt298->regmap, RT298_IRQ_CTRL, 0x1, 0x1); if (ret == 0) { if (hp == true) status |= SND_JACK_HEADPHONE; if (mic == true) status |= SND_JACK_MICROPHONE; snd_soc_jack_report(rt298->jack, status, SND_JACK_MICROPHONE | SND_JACK_HEADPHONE); pm_wakeup_event(&rt298->i2c->dev, 300); } return IRQ_HANDLED; } static int rt298_probe(struct snd_soc_codec *codec) { struct rt298_priv *rt298 = snd_soc_codec_get_drvdata(codec); rt298->codec = codec; if (rt298->i2c->irq) { regmap_update_bits(rt298->regmap, RT298_IRQ_CTRL, 0x2, 0x2); INIT_DELAYED_WORK(&rt298->jack_detect_work, rt298_jack_detect_work); schedule_delayed_work(&rt298->jack_detect_work, msecs_to_jiffies(1250)); } return 0; } static int rt298_remove(struct snd_soc_codec *codec) { struct rt298_priv *rt298 = snd_soc_codec_get_drvdata(codec); cancel_delayed_work_sync(&rt298->jack_detect_work); return 0; } #ifdef CONFIG_PM static int rt298_suspend(struct snd_soc_codec *codec) { struct rt298_priv *rt298 = snd_soc_codec_get_drvdata(codec); rt298->is_hp_in = -1; regcache_cache_only(rt298->regmap, true); regcache_mark_dirty(rt298->regmap); return 0; } static int rt298_resume(struct snd_soc_codec *codec) { struct rt298_priv *rt298 = snd_soc_codec_get_drvdata(codec); regcache_cache_only(rt298->regmap, false); rt298_index_sync(codec); regcache_sync(rt298->regmap); return 0; } #else #define rt298_suspend NULL #define rt298_resume NULL #endif #define RT298_STEREO_RATES (SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000) #define RT298_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE | \ SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S8) static const struct snd_soc_dai_ops rt298_aif_dai_ops = { .hw_params = rt298_hw_params, .set_fmt = rt298_set_dai_fmt, .set_sysclk = rt298_set_dai_sysclk, .set_bclk_ratio = rt298_set_bclk_ratio, }; static struct snd_soc_dai_driver rt298_dai[] = { { .name = "rt298-aif1", .id = RT298_AIF1, .playback = { .stream_name = "AIF1 Playback", .channels_min = 1, .channels_max = 2, .rates = RT298_STEREO_RATES, .formats = RT298_FORMATS, }, .capture = { .stream_name = "AIF1 Capture", .channels_min = 1, .channels_max = 2, .rates = RT298_STEREO_RATES, .formats = RT298_FORMATS, }, .ops = &rt298_aif_dai_ops, .symmetric_rates = 1, }, { .name = "rt298-aif2", .id = RT298_AIF2, .playback = { .stream_name = "AIF2 Playback", .channels_min = 1, .channels_max = 2, .rates = RT298_STEREO_RATES, .formats = RT298_FORMATS, }, .capture = { .stream_name = "AIF2 Capture", .channels_min = 1, .channels_max = 2, .rates = RT298_STEREO_RATES, .formats = RT298_FORMATS, }, .ops = &rt298_aif_dai_ops, .symmetric_rates = 1, }, }; static struct snd_soc_codec_driver soc_codec_dev_rt298 = { .probe = rt298_probe, .remove = rt298_remove, .suspend = rt298_suspend, .resume = rt298_resume, .set_bias_level = rt298_set_bias_level, .idle_bias_off = true, .component_driver = { .controls = rt298_snd_controls, .num_controls = ARRAY_SIZE(rt298_snd_controls), .dapm_widgets = rt298_dapm_widgets, .num_dapm_widgets = ARRAY_SIZE(rt298_dapm_widgets), .dapm_routes = rt298_dapm_routes, .num_dapm_routes = ARRAY_SIZE(rt298_dapm_routes), }, }; static const struct regmap_config rt298_regmap = { .reg_bits = 32, .val_bits = 32, .max_register = 0x02370100, .volatile_reg = rt298_volatile_register, .readable_reg = rt298_readable_register, .reg_write = rl6347a_hw_write, .reg_read = rl6347a_hw_read, .cache_type = REGCACHE_RBTREE, .reg_defaults = rt298_reg, .num_reg_defaults = ARRAY_SIZE(rt298_reg), }; static const struct i2c_device_id rt298_i2c_id[] = { {"rt298", 0}, {} }; MODULE_DEVICE_TABLE(i2c, rt298_i2c_id); static const struct acpi_device_id rt298_acpi_match[] = { { "INT343A", 0 }, {}, }; MODULE_DEVICE_TABLE(acpi, rt298_acpi_match); static const struct dmi_system_id force_combo_jack_table[] = { { .ident = "Intel Broxton P", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Intel Corp"), DMI_MATCH(DMI_PRODUCT_NAME, "Broxton P") } }, { .ident = "Intel Gemini Lake", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Intel Corp"), DMI_MATCH(DMI_PRODUCT_NAME, "Geminilake") } }, { } }; static int rt298_i2c_probe(struct i2c_client *i2c, const struct i2c_device_id *id) { struct rt298_platform_data *pdata = dev_get_platdata(&i2c->dev); struct rt298_priv *rt298; struct device *dev = &i2c->dev; const struct acpi_device_id *acpiid; int i, ret; rt298 = devm_kzalloc(&i2c->dev, sizeof(*rt298), GFP_KERNEL); if (NULL == rt298) return -ENOMEM; rt298->regmap = devm_regmap_init(&i2c->dev, NULL, i2c, &rt298_regmap); if (IS_ERR(rt298->regmap)) { ret = PTR_ERR(rt298->regmap); dev_err(&i2c->dev, "Failed to allocate register map: %d\n", ret); return ret; } regmap_read(rt298->regmap, RT298_GET_PARAM(AC_NODE_ROOT, AC_PAR_VENDOR_ID), &ret); if (ret != RT298_VENDOR_ID) { dev_err(&i2c->dev, "Device with ID register %#x is not rt298\n", ret); return -ENODEV; } rt298->index_cache = devm_kmemdup(&i2c->dev, rt298_index_def, sizeof(rt298_index_def), GFP_KERNEL); if (!rt298->index_cache) return -ENOMEM; rt298->index_cache_size = INDEX_CACHE_SIZE; rt298->i2c = i2c; i2c_set_clientdata(i2c, rt298); /* restore codec default */ for (i = 0; i < INDEX_CACHE_SIZE; i++) regmap_write(rt298->regmap, rt298->index_cache[i].reg, rt298->index_cache[i].def); for (i = 0; i < ARRAY_SIZE(rt298_reg); i++) regmap_write(rt298->regmap, rt298_reg[i].reg, rt298_reg[i].def); if (pdata) rt298->pdata = *pdata; /* enable jack combo mode on supported devices */ acpiid = acpi_match_device(dev->driver->acpi_match_table, dev); if (acpiid && acpiid->driver_data) { rt298->pdata = *(struct rt298_platform_data *) acpiid->driver_data; } if (dmi_check_system(force_combo_jack_table)) { rt298->pdata.cbj_en = true; rt298->pdata.gpio2_en = false; } /* VREF Charging */ regmap_update_bits(rt298->regmap, 0x04, 0x80, 0x80); regmap_update_bits(rt298->regmap, 0x1b, 0x860, 0x860); /* Vref2 */ regmap_update_bits(rt298->regmap, 0x08, 0x20, 0x20); regmap_write(rt298->regmap, RT298_SET_AUDIO_POWER, AC_PWRST_D3); for (i = 0; i < RT298_POWER_REG_LEN; i++) regmap_write(rt298->regmap, RT298_SET_POWER(rt298_support_power_controls[i]), AC_PWRST_D1); if (!rt298->pdata.cbj_en) { regmap_write(rt298->regmap, RT298_CBJ_CTRL2, 0x0000); regmap_write(rt298->regmap, RT298_MIC1_DET_CTRL, 0x0816); regmap_update_bits(rt298->regmap, RT298_CBJ_CTRL1, 0xf000, 0xb000); } else { regmap_update_bits(rt298->regmap, RT298_CBJ_CTRL1, 0xf000, 0x5000); } mdelay(10); if (!rt298->pdata.gpio2_en) regmap_write(rt298->regmap, RT298_SET_DMIC2_DEFAULT, 0x40); else regmap_write(rt298->regmap, RT298_SET_DMIC2_DEFAULT, 0); mdelay(10); regmap_write(rt298->regmap, RT298_MISC_CTRL1, 0x0000); regmap_update_bits(rt298->regmap, RT298_WIND_FILTER_CTRL, 0x0082, 0x0082); regmap_write(rt298->regmap, RT298_UNSOLICITED_INLINE_CMD, 0x81); regmap_write(rt298->regmap, RT298_UNSOLICITED_HP_OUT, 0x82); regmap_write(rt298->regmap, RT298_UNSOLICITED_MIC1, 0x84); regmap_update_bits(rt298->regmap, RT298_IRQ_FLAG_CTRL, 0x2, 0x2); rt298->is_hp_in = -1; if (rt298->i2c->irq) { ret = request_threaded_irq(rt298->i2c->irq, NULL, rt298_irq, IRQF_TRIGGER_HIGH | IRQF_ONESHOT, "rt298", rt298); if (ret != 0) { dev_err(&i2c->dev, "Failed to reguest IRQ: %d\n", ret); return ret; } } ret = snd_soc_register_codec(&i2c->dev, &soc_codec_dev_rt298, rt298_dai, ARRAY_SIZE(rt298_dai)); return ret; } static int rt298_i2c_remove(struct i2c_client *i2c) { struct rt298_priv *rt298 = i2c_get_clientdata(i2c); if (i2c->irq) free_irq(i2c->irq, rt298); snd_soc_unregister_codec(&i2c->dev); return 0; } static struct i2c_driver rt298_i2c_driver = { .driver = { .name = "rt298", .acpi_match_table = ACPI_PTR(rt298_acpi_match), }, .probe = rt298_i2c_probe, .remove = rt298_i2c_remove, .id_table = rt298_i2c_id, }; module_i2c_driver(rt298_i2c_driver); MODULE_DESCRIPTION("ASoC RT298 driver"); MODULE_AUTHOR("Bard Liao <bardliao@realtek.com>"); MODULE_LICENSE("GPL");
null
null
null
null
79,158
39,270
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
204,265
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* mpicoder.c - Coder for the external representation of MPIs * Copyright (C) 1998, 1999 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG 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. * * GnuPG 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/bitops.h> #include <linux/count_zeros.h> #include <linux/byteorder/generic.h> #include <linux/scatterlist.h> #include <linux/string.h> #include "mpi-internal.h" #define MAX_EXTERN_MPI_BITS 16384 /** * mpi_read_raw_data - Read a raw byte stream as a positive integer * @xbuffer: The data to read * @nbytes: The amount of data to read */ MPI mpi_read_raw_data(const void *xbuffer, size_t nbytes) { const uint8_t *buffer = xbuffer; int i, j; unsigned nbits, nlimbs; mpi_limb_t a; MPI val = NULL; while (nbytes > 0 && buffer[0] == 0) { buffer++; nbytes--; } nbits = nbytes * 8; if (nbits > MAX_EXTERN_MPI_BITS) { pr_info("MPI: mpi too large (%u bits)\n", nbits); return NULL; } if (nbytes > 0) nbits -= count_leading_zeros(buffer[0]) - (BITS_PER_LONG - 8); nlimbs = DIV_ROUND_UP(nbytes, BYTES_PER_MPI_LIMB); val = mpi_alloc(nlimbs); if (!val) return NULL; val->nbits = nbits; val->sign = 0; val->nlimbs = nlimbs; if (nbytes > 0) { i = BYTES_PER_MPI_LIMB - nbytes % BYTES_PER_MPI_LIMB; i %= BYTES_PER_MPI_LIMB; for (j = nlimbs; j > 0; j--) { a = 0; for (; i < BYTES_PER_MPI_LIMB; i++) { a <<= 8; a |= *buffer++; } i = 0; val->d[j - 1] = a; } } return val; } EXPORT_SYMBOL_GPL(mpi_read_raw_data); MPI mpi_read_from_buffer(const void *xbuffer, unsigned *ret_nread) { const uint8_t *buffer = xbuffer; unsigned int nbits, nbytes; MPI val; if (*ret_nread < 2) return ERR_PTR(-EINVAL); nbits = buffer[0] << 8 | buffer[1]; if (nbits > MAX_EXTERN_MPI_BITS) { pr_info("MPI: mpi too large (%u bits)\n", nbits); return ERR_PTR(-EINVAL); } nbytes = DIV_ROUND_UP(nbits, 8); if (nbytes + 2 > *ret_nread) { pr_info("MPI: mpi larger than buffer nbytes=%u ret_nread=%u\n", nbytes, *ret_nread); return ERR_PTR(-EINVAL); } val = mpi_read_raw_data(buffer + 2, nbytes); if (!val) return ERR_PTR(-ENOMEM); *ret_nread = nbytes + 2; return val; } EXPORT_SYMBOL_GPL(mpi_read_from_buffer); static int count_lzeros(MPI a) { mpi_limb_t alimb; int i, lzeros = 0; for (i = a->nlimbs - 1; i >= 0; i--) { alimb = a->d[i]; if (alimb == 0) { lzeros += sizeof(mpi_limb_t); } else { lzeros += count_leading_zeros(alimb) / 8; break; } } return lzeros; } /** * mpi_read_buffer() - read MPI to a bufer provided by user (msb first) * * @a: a multi precision integer * @buf: bufer to which the output will be written to. Needs to be at * leaset mpi_get_size(a) long. * @buf_len: size of the buf. * @nbytes: receives the actual length of the data written on success and * the data to-be-written on -EOVERFLOW in case buf_len was too * small. * @sign: if not NULL, it will be set to the sign of a. * * Return: 0 on success or error code in case of error */ int mpi_read_buffer(MPI a, uint8_t *buf, unsigned buf_len, unsigned *nbytes, int *sign) { uint8_t *p; #if BYTES_PER_MPI_LIMB == 4 __be32 alimb; #elif BYTES_PER_MPI_LIMB == 8 __be64 alimb; #else #error please implement for this limb size. #endif unsigned int n = mpi_get_size(a); int i, lzeros; if (!buf || !nbytes) return -EINVAL; if (sign) *sign = a->sign; lzeros = count_lzeros(a); if (buf_len < n - lzeros) { *nbytes = n - lzeros; return -EOVERFLOW; } p = buf; *nbytes = n - lzeros; for (i = a->nlimbs - 1 - lzeros / BYTES_PER_MPI_LIMB, lzeros %= BYTES_PER_MPI_LIMB; i >= 0; i--) { #if BYTES_PER_MPI_LIMB == 4 alimb = cpu_to_be32(a->d[i]); #elif BYTES_PER_MPI_LIMB == 8 alimb = cpu_to_be64(a->d[i]); #else #error please implement for this limb size. #endif memcpy(p, (u8 *)&alimb + lzeros, BYTES_PER_MPI_LIMB - lzeros); p += BYTES_PER_MPI_LIMB - lzeros; lzeros = 0; } return 0; } EXPORT_SYMBOL_GPL(mpi_read_buffer); /* * mpi_get_buffer() - Returns an allocated buffer with the MPI (msb first). * Caller must free the return string. * This function does return a 0 byte buffer with nbytes set to zero if the * value of A is zero. * * @a: a multi precision integer. * @nbytes: receives the length of this buffer. * @sign: if not NULL, it will be set to the sign of the a. * * Return: Pointer to MPI buffer or NULL on error */ void *mpi_get_buffer(MPI a, unsigned *nbytes, int *sign) { uint8_t *buf; unsigned int n; int ret; if (!nbytes) return NULL; n = mpi_get_size(a); if (!n) n++; buf = kmalloc(n, GFP_KERNEL); if (!buf) return NULL; ret = mpi_read_buffer(a, buf, n, nbytes, sign); if (ret) { kfree(buf); return NULL; } return buf; } EXPORT_SYMBOL_GPL(mpi_get_buffer); /** * mpi_write_to_sgl() - Funnction exports MPI to an sgl (msb first) * * This function works in the same way as the mpi_read_buffer, but it * takes an sgl instead of u8 * buf. * * @a: a multi precision integer * @sgl: scatterlist to write to. Needs to be at least * mpi_get_size(a) long. * @nbytes: the number of bytes to write. Leading bytes will be * filled with zero. * @sign: if not NULL, it will be set to the sign of a. * * Return: 0 on success or error code in case of error */ int mpi_write_to_sgl(MPI a, struct scatterlist *sgl, unsigned nbytes, int *sign) { u8 *p, *p2; #if BYTES_PER_MPI_LIMB == 4 __be32 alimb; #elif BYTES_PER_MPI_LIMB == 8 __be64 alimb; #else #error please implement for this limb size. #endif unsigned int n = mpi_get_size(a); struct sg_mapping_iter miter; int i, x, buf_len; int nents; if (sign) *sign = a->sign; if (nbytes < n) return -EOVERFLOW; nents = sg_nents_for_len(sgl, nbytes); if (nents < 0) return -EINVAL; sg_miter_start(&miter, sgl, nents, SG_MITER_ATOMIC | SG_MITER_TO_SG); sg_miter_next(&miter); buf_len = miter.length; p2 = miter.addr; while (nbytes > n) { i = min_t(unsigned, nbytes - n, buf_len); memset(p2, 0, i); p2 += i; nbytes -= i; buf_len -= i; if (!buf_len) { sg_miter_next(&miter); buf_len = miter.length; p2 = miter.addr; } } for (i = a->nlimbs - 1; i >= 0; i--) { #if BYTES_PER_MPI_LIMB == 4 alimb = a->d[i] ? cpu_to_be32(a->d[i]) : 0; #elif BYTES_PER_MPI_LIMB == 8 alimb = a->d[i] ? cpu_to_be64(a->d[i]) : 0; #else #error please implement for this limb size. #endif p = (u8 *)&alimb; for (x = 0; x < sizeof(alimb); x++) { *p2++ = *p++; if (!--buf_len) { sg_miter_next(&miter); buf_len = miter.length; p2 = miter.addr; } } } sg_miter_stop(&miter); return 0; } EXPORT_SYMBOL_GPL(mpi_write_to_sgl); /* * mpi_read_raw_from_sgl() - Function allocates an MPI and populates it with * data from the sgl * * This function works in the same way as the mpi_read_raw_data, but it * takes an sgl instead of void * buffer. i.e. it allocates * a new MPI and reads the content of the sgl to the MPI. * * @sgl: scatterlist to read from * @nbytes: number of bytes to read * * Return: Pointer to a new MPI or NULL on error */ MPI mpi_read_raw_from_sgl(struct scatterlist *sgl, unsigned int nbytes) { struct sg_mapping_iter miter; unsigned int nbits, nlimbs; int x, j, z, lzeros, ents; unsigned int len; const u8 *buff; mpi_limb_t a; MPI val = NULL; ents = sg_nents_for_len(sgl, nbytes); if (ents < 0) return NULL; sg_miter_start(&miter, sgl, ents, SG_MITER_ATOMIC | SG_MITER_FROM_SG); lzeros = 0; len = 0; while (nbytes > 0) { while (len && !*buff) { lzeros++; len--; buff++; } if (len && *buff) break; sg_miter_next(&miter); buff = miter.addr; len = miter.length; nbytes -= lzeros; lzeros = 0; } miter.consumed = lzeros; sg_miter_stop(&miter); nbytes -= lzeros; nbits = nbytes * 8; if (nbits > MAX_EXTERN_MPI_BITS) { pr_info("MPI: mpi too large (%u bits)\n", nbits); return NULL; } if (nbytes > 0) nbits -= count_leading_zeros(*buff) - (BITS_PER_LONG - 8); nlimbs = DIV_ROUND_UP(nbytes, BYTES_PER_MPI_LIMB); val = mpi_alloc(nlimbs); if (!val) return NULL; val->nbits = nbits; val->sign = 0; val->nlimbs = nlimbs; if (nbytes == 0) return val; j = nlimbs - 1; a = 0; z = BYTES_PER_MPI_LIMB - nbytes % BYTES_PER_MPI_LIMB; z %= BYTES_PER_MPI_LIMB; while (sg_miter_next(&miter)) { buff = miter.addr; len = miter.length; for (x = 0; x < len; x++) { a <<= 8; a |= *buff++; if (((z + x + 1) % BYTES_PER_MPI_LIMB) == 0) { val->d[j--] = a; a = 0; } } z += x; } return val; } EXPORT_SYMBOL_GPL(mpi_read_raw_from_sgl);
null
null
null
null
112,612
43,713
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
208,708
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* ip6tables module for matching the Hop Limit value * Maciej Soltysiak <solt@dns.toxicfilms.tv> * Based on HW's ttl module */ #ifndef _IP6T_HL_H #define _IP6T_HL_H #include <linux/types.h> enum { IP6T_HL_EQ = 0, /* equals */ IP6T_HL_NE, /* not equals */ IP6T_HL_LT, /* less than */ IP6T_HL_GT, /* greater than */ }; struct ip6t_hl_info { __u8 mode; __u8 hop_limit; }; #endif
null
null
null
null
117,055
456
null
train_val
1b0d3845b454eaaac0b2064c78926ca4d739a080
263,024
qemu
0
https://github.com/bonzini/qemu
2016-10-18 11:40:27+01:00
/* * Copyright (c) 1982, 1986, 1993 * The Regents of the University of California. 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. * 3. Neither the name of the University 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 REGENTS 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 REGENTS 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. * * @(#)tcp.h 8.1 (Berkeley) 6/10/93 * tcp.h,v 1.3 1994/08/21 05:27:34 paul Exp */ #ifndef TCP_H #define TCP_H typedef uint32_t tcp_seq; #define PR_SLOWHZ 2 /* 2 slow timeouts per second (approx) */ #define PR_FASTHZ 5 /* 5 fast timeouts per second (not important) */ #define TCP_SNDSPACE 8192 #define TCP_RCVSPACE 8192 /* * TCP header. * Per RFC 793, September, 1981. */ #define tcphdr slirp_tcphdr struct tcphdr { uint16_t th_sport; /* source port */ uint16_t th_dport; /* destination port */ tcp_seq th_seq; /* sequence number */ tcp_seq th_ack; /* acknowledgement number */ #ifdef HOST_WORDS_BIGENDIAN uint8_t th_off:4, /* data offset */ th_x2:4; /* (unused) */ #else uint8_t th_x2:4, /* (unused) */ th_off:4; /* data offset */ #endif uint8_t th_flags; uint16_t th_win; /* window */ uint16_t th_sum; /* checksum */ uint16_t th_urp; /* urgent pointer */ }; #include "tcp_var.h" #ifndef TH_FIN #define TH_FIN 0x01 #define TH_SYN 0x02 #define TH_RST 0x04 #define TH_PUSH 0x08 #define TH_ACK 0x10 #define TH_URG 0x20 #endif #ifndef TCPOPT_EOL #define TCPOPT_EOL 0 #define TCPOPT_NOP 1 #define TCPOPT_MAXSEG 2 #define TCPOPT_WINDOW 3 #define TCPOPT_SACK_PERMITTED 4 /* Experimental */ #define TCPOPT_SACK 5 /* Experimental */ #define TCPOPT_TIMESTAMP 8 #define TCPOPT_TSTAMP_HDR \ (TCPOPT_NOP<<24|TCPOPT_NOP<<16|TCPOPT_TIMESTAMP<<8|TCPOLEN_TIMESTAMP) #endif #ifndef TCPOLEN_MAXSEG #define TCPOLEN_MAXSEG 4 #define TCPOLEN_WINDOW 3 #define TCPOLEN_SACK_PERMITTED 2 #define TCPOLEN_TIMESTAMP 10 #define TCPOLEN_TSTAMP_APPA (TCPOLEN_TIMESTAMP+2) /* appendix A */ #endif /* * Default maximum segment size for TCP. * With an IP MSS of 576, this is 536, * but 512 is probably more convenient. * This should be defined as MIN(512, IP_MSS - sizeof (struct tcpiphdr)). * * We make this 1460 because we only care about Ethernet in the qemu context. */ #undef TCP_MSS #define TCP_MSS 1460 #undef TCP6_MSS #define TCP6_MSS 1440 #undef TCP_MAXWIN #define TCP_MAXWIN 65535 /* largest value for (unscaled) window */ #undef TCP_MAX_WINSHIFT #define TCP_MAX_WINSHIFT 14 /* maximum window shift */ /* * User-settable options (used with setsockopt). * * We don't use the system headers on unix because we have conflicting * local structures. We can't avoid the system definitions on Windows, * so we undefine them. */ #undef TCP_NODELAY #define TCP_NODELAY 0x01 /* don't delay send to coalesce packets */ #undef TCP_MAXSEG /* * TCP FSM state definitions. * Per RFC793, September, 1981. */ #define TCP_NSTATES 11 #define TCPS_CLOSED 0 /* closed */ #define TCPS_LISTEN 1 /* listening for connection */ #define TCPS_SYN_SENT 2 /* active, have sent syn */ #define TCPS_SYN_RECEIVED 3 /* have send and received syn */ /* states < TCPS_ESTABLISHED are those where connections not established */ #define TCPS_ESTABLISHED 4 /* established */ #define TCPS_CLOSE_WAIT 5 /* rcvd fin, waiting for close */ /* states > TCPS_CLOSE_WAIT are those where user has closed */ #define TCPS_FIN_WAIT_1 6 /* have closed, sent fin */ #define TCPS_CLOSING 7 /* closed xchd FIN; await FIN ACK */ #define TCPS_LAST_ACK 8 /* had fin and close; await FIN ACK */ /* states > TCPS_CLOSE_WAIT && < TCPS_FIN_WAIT_2 await ACK of FIN */ #define TCPS_FIN_WAIT_2 9 /* have closed, fin is acked */ #define TCPS_TIME_WAIT 10 /* in 2*msl quiet wait after close */ #define TCPS_HAVERCVDSYN(s) ((s) >= TCPS_SYN_RECEIVED) #define TCPS_HAVEESTABLISHED(s) ((s) >= TCPS_ESTABLISHED) #define TCPS_HAVERCVDFIN(s) ((s) >= TCPS_TIME_WAIT) /* * TCP sequence numbers are 32 bit integers operated * on with modular arithmetic. These macros can be * used to compare such integers. */ #define SEQ_LT(a,b) ((int)((a)-(b)) < 0) #define SEQ_LEQ(a,b) ((int)((a)-(b)) <= 0) #define SEQ_GT(a,b) ((int)((a)-(b)) > 0) #define SEQ_GEQ(a,b) ((int)((a)-(b)) >= 0) /* * Macros to initialize tcp sequence numbers for * send and receive from initial send and receive * sequence numbers. */ #define tcp_rcvseqinit(tp) \ (tp)->rcv_adv = (tp)->rcv_nxt = (tp)->irs + 1 #define tcp_sendseqinit(tp) \ (tp)->snd_una = (tp)->snd_nxt = (tp)->snd_max = (tp)->snd_up = (tp)->iss #define TCP_ISSINCR (125*1024) /* increment for tcp_iss each second */ #endif
null
null
null
null
121,148
19,839
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
19,839
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 "content/public/test/test_notification_tracker.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_types.h" namespace content { TestNotificationTracker::Event::Event() : type(NOTIFICATION_ALL), source(NotificationService::AllSources()), details(NotificationService::NoDetails()) { } TestNotificationTracker::Event::Event(int t, NotificationSource s, NotificationDetails d) : type(t), source(s), details(d) { } TestNotificationTracker::TestNotificationTracker() { } TestNotificationTracker::~TestNotificationTracker() { } void TestNotificationTracker::ListenFor( int type, const NotificationSource& source) { registrar_.Add(this, type, source); } void TestNotificationTracker::Reset() { events_.clear(); } bool TestNotificationTracker::Check1AndReset(int type) { if (size() != 1) { Reset(); return false; } bool success = events_[0].type == type; Reset(); return success; } bool TestNotificationTracker::Check2AndReset(int type1, int type2) { if (size() != 2) { Reset(); return false; } bool success = events_[0].type == type1 && events_[1].type == type2; Reset(); return success; } bool TestNotificationTracker::Check3AndReset(int type1, int type2, int type3) { if (size() != 3) { Reset(); return false; } bool success = events_[0].type == type1 && events_[1].type == type2 && events_[2].type == type3; Reset(); return success; } void TestNotificationTracker::Observe( int type, const NotificationSource& source, const NotificationDetails& details) { events_.push_back(Event(type, source, details)); } } // namespace content
null
null
null
null
16,702
18,153
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
18,153
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 "components/policy/core/common/cloud/cloud_policy_core.h" #include <utility> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/logging.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" #include "components/policy/core/common/cloud/cloud_policy_refresh_scheduler.h" #include "components/policy/core/common/cloud/cloud_policy_service.h" #include "components/policy/core/common/cloud/cloud_policy_store.h" #include "components/policy/core/common/remote_commands/remote_commands_factory.h" #include "components/policy/core/common/remote_commands/remote_commands_service.h" #include "components/prefs/pref_service.h" namespace policy { CloudPolicyCore::Observer::~Observer() {} void CloudPolicyCore::Observer::OnRemoteCommandsServiceStarted( CloudPolicyCore* core) { } CloudPolicyCore::CloudPolicyCore( const std::string& policy_type, const std::string& settings_entity_id, CloudPolicyStore* store, const scoped_refptr<base::SequencedTaskRunner>& task_runner) : policy_type_(policy_type), settings_entity_id_(settings_entity_id), store_(store), task_runner_(task_runner) {} CloudPolicyCore::~CloudPolicyCore() {} void CloudPolicyCore::Connect(std::unique_ptr<CloudPolicyClient> client) { CHECK(!client_); CHECK(client); client_ = std::move(client); service_.reset(new CloudPolicyService(policy_type_, settings_entity_id_, client_.get(), store_)); for (auto& observer : observers_) observer.OnCoreConnected(this); } void CloudPolicyCore::Disconnect() { if (client_) for (auto& observer : observers_) observer.OnCoreDisconnecting(this); refresh_delay_.reset(); refresh_scheduler_.reset(); remote_commands_service_.reset(); service_.reset(); client_.reset(); } void CloudPolicyCore::StartRemoteCommandsService( std::unique_ptr<RemoteCommandsFactory> factory) { DCHECK(client_); DCHECK(factory); remote_commands_service_.reset( new RemoteCommandsService(std::move(factory), client_.get())); // Do an initial remote commands fetch immediately. remote_commands_service_->FetchRemoteCommands(); for (auto& observer : observers_) observer.OnRemoteCommandsServiceStarted(this); } void CloudPolicyCore::RefreshSoon() { if (refresh_scheduler_) refresh_scheduler_->RefreshSoon(); } void CloudPolicyCore::StartRefreshScheduler() { if (!refresh_scheduler_) { refresh_scheduler_.reset( new CloudPolicyRefreshScheduler(client_.get(), store_, task_runner_)); UpdateRefreshDelayFromPref(); for (auto& observer : observers_) observer.OnRefreshSchedulerStarted(this); } } void CloudPolicyCore::TrackRefreshDelayPref( PrefService* pref_service, const std::string& refresh_pref_name) { refresh_delay_.reset(new IntegerPrefMember()); refresh_delay_->Init(refresh_pref_name, pref_service, base::Bind(&CloudPolicyCore::UpdateRefreshDelayFromPref, base::Unretained(this))); UpdateRefreshDelayFromPref(); } void CloudPolicyCore::AddObserver(CloudPolicyCore::Observer* observer) { observers_.AddObserver(observer); } void CloudPolicyCore::RemoveObserver(CloudPolicyCore::Observer* observer) { observers_.RemoveObserver(observer); } void CloudPolicyCore::UpdateRefreshDelayFromPref() { if (refresh_scheduler_ && refresh_delay_) refresh_scheduler_->SetDesiredRefreshDelay(refresh_delay_->GetValue()); } } // namespace policy
null
null
null
null
15,016
2,095
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
167,090
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/**************************************************************************** * ip_conntrack_helper_h323_asn1.c - BER and PER decoding library for H.323 * conntrack/NAT module. * * Copyright (c) 2006 by Jing Min Zhao <zhaojingmin@users.sourceforge.net> * * This source code is licensed under General Public License version 2. * * See ip_conntrack_helper_h323_asn1.h for details. * ****************************************************************************/ #ifdef __KERNEL__ #include <linux/kernel.h> #else #include <stdio.h> #endif #include <linux/netfilter/nf_conntrack_h323_asn1.h> /* Trace Flag */ #ifndef H323_TRACE #define H323_TRACE 0 #endif #if H323_TRACE #define TAB_SIZE 4 #define IFTHEN(cond, act) if(cond){act;} #ifdef __KERNEL__ #define PRINT printk #else #define PRINT printf #endif #define FNAME(name) name, #else #define IFTHEN(cond, act) #define PRINT(fmt, args...) #define FNAME(name) #endif /* ASN.1 Types */ #define NUL 0 #define BOOL 1 #define OID 2 #define INT 3 #define ENUM 4 #define BITSTR 5 #define NUMSTR 6 #define NUMDGT 6 #define TBCDSTR 6 #define OCTSTR 7 #define PRTSTR 7 #define IA5STR 7 #define GENSTR 7 #define BMPSTR 8 #define SEQ 9 #define SET 9 #define SEQOF 10 #define SETOF 10 #define CHOICE 11 /* Constraint Types */ #define FIXD 0 /* #define BITS 1-8 */ #define BYTE 9 #define WORD 10 #define CONS 11 #define SEMI 12 #define UNCO 13 /* ASN.1 Type Attributes */ #define SKIP 0 #define STOP 1 #define DECODE 2 #define EXT 4 #define OPEN 8 #define OPT 16 /* ASN.1 Field Structure */ typedef struct field_t { #if H323_TRACE char *name; #endif unsigned char type; unsigned char sz; unsigned char lb; unsigned char ub; unsigned short attr; unsigned short offset; const struct field_t *fields; } field_t; /* Bit Stream */ typedef struct { unsigned char *buf; unsigned char *beg; unsigned char *end; unsigned char *cur; unsigned int bit; } bitstr_t; /* Tool Functions */ #define INC_BIT(bs) if((++(bs)->bit)>7){(bs)->cur++;(bs)->bit=0;} #define INC_BITS(bs,b) if(((bs)->bit+=(b))>7){(bs)->cur+=(bs)->bit>>3;(bs)->bit&=7;} #define BYTE_ALIGN(bs) if((bs)->bit){(bs)->cur++;(bs)->bit=0;} #define CHECK_BOUND(bs,n) if((bs)->cur+(n)>(bs)->end)return(H323_ERROR_BOUND) static unsigned int get_len(bitstr_t *bs); static unsigned int get_bit(bitstr_t *bs); static unsigned int get_bits(bitstr_t *bs, unsigned int b); static unsigned int get_bitmap(bitstr_t *bs, unsigned int b); static unsigned int get_uint(bitstr_t *bs, int b); /* Decoder Functions */ static int decode_nul(bitstr_t *bs, const struct field_t *f, char *base, int level); static int decode_bool(bitstr_t *bs, const struct field_t *f, char *base, int level); static int decode_oid(bitstr_t *bs, const struct field_t *f, char *base, int level); static int decode_int(bitstr_t *bs, const struct field_t *f, char *base, int level); static int decode_enum(bitstr_t *bs, const struct field_t *f, char *base, int level); static int decode_bitstr(bitstr_t *bs, const struct field_t *f, char *base, int level); static int decode_numstr(bitstr_t *bs, const struct field_t *f, char *base, int level); static int decode_octstr(bitstr_t *bs, const struct field_t *f, char *base, int level); static int decode_bmpstr(bitstr_t *bs, const struct field_t *f, char *base, int level); static int decode_seq(bitstr_t *bs, const struct field_t *f, char *base, int level); static int decode_seqof(bitstr_t *bs, const struct field_t *f, char *base, int level); static int decode_choice(bitstr_t *bs, const struct field_t *f, char *base, int level); /* Decoder Functions Vector */ typedef int (*decoder_t)(bitstr_t *, const struct field_t *, char *, int); static const decoder_t Decoders[] = { decode_nul, decode_bool, decode_oid, decode_int, decode_enum, decode_bitstr, decode_numstr, decode_octstr, decode_bmpstr, decode_seq, decode_seqof, decode_choice, }; /**************************************************************************** * H.323 Types ****************************************************************************/ #include "nf_conntrack_h323_types.c" /**************************************************************************** * Functions ****************************************************************************/ /* Assume bs is aligned && v < 16384 */ static unsigned int get_len(bitstr_t *bs) { unsigned int v; v = *bs->cur++; if (v & 0x80) { v &= 0x3f; v <<= 8; v += *bs->cur++; } return v; } /****************************************************************************/ static unsigned int get_bit(bitstr_t *bs) { unsigned int b = (*bs->cur) & (0x80 >> bs->bit); INC_BIT(bs); return b; } /****************************************************************************/ /* Assume b <= 8 */ static unsigned int get_bits(bitstr_t *bs, unsigned int b) { unsigned int v, l; v = (*bs->cur) & (0xffU >> bs->bit); l = b + bs->bit; if (l < 8) { v >>= 8 - l; bs->bit = l; } else if (l == 8) { bs->cur++; bs->bit = 0; } else { /* l > 8 */ v <<= 8; v += *(++bs->cur); v >>= 16 - l; bs->bit = l - 8; } return v; } /****************************************************************************/ /* Assume b <= 32 */ static unsigned int get_bitmap(bitstr_t *bs, unsigned int b) { unsigned int v, l, shift, bytes; if (!b) return 0; l = bs->bit + b; if (l < 8) { v = (unsigned int)(*bs->cur) << (bs->bit + 24); bs->bit = l; } else if (l == 8) { v = (unsigned int)(*bs->cur++) << (bs->bit + 24); bs->bit = 0; } else { for (bytes = l >> 3, shift = 24, v = 0; bytes; bytes--, shift -= 8) v |= (unsigned int)(*bs->cur++) << shift; if (l < 32) { v |= (unsigned int)(*bs->cur) << shift; v <<= bs->bit; } else if (l > 32) { v <<= bs->bit; v |= (*bs->cur) >> (8 - bs->bit); } bs->bit = l & 0x7; } v &= 0xffffffff << (32 - b); return v; } /**************************************************************************** * Assume bs is aligned and sizeof(unsigned int) == 4 ****************************************************************************/ static unsigned int get_uint(bitstr_t *bs, int b) { unsigned int v = 0; switch (b) { case 4: v |= *bs->cur++; v <<= 8; case 3: v |= *bs->cur++; v <<= 8; case 2: v |= *bs->cur++; v <<= 8; case 1: v |= *bs->cur++; break; } return v; } /****************************************************************************/ static int decode_nul(bitstr_t *bs, const struct field_t *f, char *base, int level) { PRINT("%*.s%s\n", level * TAB_SIZE, " ", f->name); return H323_ERROR_NONE; } /****************************************************************************/ static int decode_bool(bitstr_t *bs, const struct field_t *f, char *base, int level) { PRINT("%*.s%s\n", level * TAB_SIZE, " ", f->name); INC_BIT(bs); CHECK_BOUND(bs, 0); return H323_ERROR_NONE; } /****************************************************************************/ static int decode_oid(bitstr_t *bs, const struct field_t *f, char *base, int level) { int len; PRINT("%*.s%s\n", level * TAB_SIZE, " ", f->name); BYTE_ALIGN(bs); CHECK_BOUND(bs, 1); len = *bs->cur++; bs->cur += len; CHECK_BOUND(bs, 0); return H323_ERROR_NONE; } /****************************************************************************/ static int decode_int(bitstr_t *bs, const struct field_t *f, char *base, int level) { unsigned int len; PRINT("%*.s%s", level * TAB_SIZE, " ", f->name); switch (f->sz) { case BYTE: /* Range == 256 */ BYTE_ALIGN(bs); bs->cur++; break; case WORD: /* 257 <= Range <= 64K */ BYTE_ALIGN(bs); bs->cur += 2; break; case CONS: /* 64K < Range < 4G */ len = get_bits(bs, 2) + 1; BYTE_ALIGN(bs); if (base && (f->attr & DECODE)) { /* timeToLive */ unsigned int v = get_uint(bs, len) + f->lb; PRINT(" = %u", v); *((unsigned int *)(base + f->offset)) = v; } bs->cur += len; break; case UNCO: BYTE_ALIGN(bs); CHECK_BOUND(bs, 2); len = get_len(bs); bs->cur += len; break; default: /* 2 <= Range <= 255 */ INC_BITS(bs, f->sz); break; } PRINT("\n"); CHECK_BOUND(bs, 0); return H323_ERROR_NONE; } /****************************************************************************/ static int decode_enum(bitstr_t *bs, const struct field_t *f, char *base, int level) { PRINT("%*.s%s\n", level * TAB_SIZE, " ", f->name); if ((f->attr & EXT) && get_bit(bs)) { INC_BITS(bs, 7); } else { INC_BITS(bs, f->sz); } CHECK_BOUND(bs, 0); return H323_ERROR_NONE; } /****************************************************************************/ static int decode_bitstr(bitstr_t *bs, const struct field_t *f, char *base, int level) { unsigned int len; PRINT("%*.s%s\n", level * TAB_SIZE, " ", f->name); BYTE_ALIGN(bs); switch (f->sz) { case FIXD: /* fixed length > 16 */ len = f->lb; break; case WORD: /* 2-byte length */ CHECK_BOUND(bs, 2); len = (*bs->cur++) << 8; len += (*bs->cur++) + f->lb; break; case SEMI: CHECK_BOUND(bs, 2); len = get_len(bs); break; default: len = 0; break; } bs->cur += len >> 3; bs->bit = len & 7; CHECK_BOUND(bs, 0); return H323_ERROR_NONE; } /****************************************************************************/ static int decode_numstr(bitstr_t *bs, const struct field_t *f, char *base, int level) { unsigned int len; PRINT("%*.s%s\n", level * TAB_SIZE, " ", f->name); /* 2 <= Range <= 255 */ len = get_bits(bs, f->sz) + f->lb; BYTE_ALIGN(bs); INC_BITS(bs, (len << 2)); CHECK_BOUND(bs, 0); return H323_ERROR_NONE; } /****************************************************************************/ static int decode_octstr(bitstr_t *bs, const struct field_t *f, char *base, int level) { unsigned int len; PRINT("%*.s%s", level * TAB_SIZE, " ", f->name); switch (f->sz) { case FIXD: /* Range == 1 */ if (f->lb > 2) { BYTE_ALIGN(bs); if (base && (f->attr & DECODE)) { /* The IP Address */ IFTHEN(f->lb == 4, PRINT(" = %d.%d.%d.%d:%d", bs->cur[0], bs->cur[1], bs->cur[2], bs->cur[3], bs->cur[4] * 256 + bs->cur[5])); *((unsigned int *)(base + f->offset)) = bs->cur - bs->buf; } } len = f->lb; break; case BYTE: /* Range == 256 */ BYTE_ALIGN(bs); CHECK_BOUND(bs, 1); len = (*bs->cur++) + f->lb; break; case SEMI: BYTE_ALIGN(bs); CHECK_BOUND(bs, 2); len = get_len(bs) + f->lb; break; default: /* 2 <= Range <= 255 */ len = get_bits(bs, f->sz) + f->lb; BYTE_ALIGN(bs); break; } bs->cur += len; PRINT("\n"); CHECK_BOUND(bs, 0); return H323_ERROR_NONE; } /****************************************************************************/ static int decode_bmpstr(bitstr_t *bs, const struct field_t *f, char *base, int level) { unsigned int len; PRINT("%*.s%s\n", level * TAB_SIZE, " ", f->name); switch (f->sz) { case BYTE: /* Range == 256 */ BYTE_ALIGN(bs); CHECK_BOUND(bs, 1); len = (*bs->cur++) + f->lb; break; default: /* 2 <= Range <= 255 */ len = get_bits(bs, f->sz) + f->lb; BYTE_ALIGN(bs); break; } bs->cur += len << 1; CHECK_BOUND(bs, 0); return H323_ERROR_NONE; } /****************************************************************************/ static int decode_seq(bitstr_t *bs, const struct field_t *f, char *base, int level) { unsigned int ext, bmp, i, opt, len = 0, bmp2, bmp2_len; int err; const struct field_t *son; unsigned char *beg = NULL; PRINT("%*.s%s\n", level * TAB_SIZE, " ", f->name); /* Decode? */ base = (base && (f->attr & DECODE)) ? base + f->offset : NULL; /* Extensible? */ ext = (f->attr & EXT) ? get_bit(bs) : 0; /* Get fields bitmap */ bmp = get_bitmap(bs, f->sz); if (base) *(unsigned int *)base = bmp; /* Decode the root components */ for (i = opt = 0, son = f->fields; i < f->lb; i++, son++) { if (son->attr & STOP) { PRINT("%*.s%s\n", (level + 1) * TAB_SIZE, " ", son->name); return H323_ERROR_STOP; } if (son->attr & OPT) { /* Optional component */ if (!((0x80000000U >> (opt++)) & bmp)) /* Not exist */ continue; } /* Decode */ if (son->attr & OPEN) { /* Open field */ CHECK_BOUND(bs, 2); len = get_len(bs); CHECK_BOUND(bs, len); if (!base || !(son->attr & DECODE)) { PRINT("%*.s%s\n", (level + 1) * TAB_SIZE, " ", son->name); bs->cur += len; continue; } beg = bs->cur; /* Decode */ if ((err = (Decoders[son->type]) (bs, son, base, level + 1)) < H323_ERROR_NONE) return err; bs->cur = beg + len; bs->bit = 0; } else if ((err = (Decoders[son->type]) (bs, son, base, level + 1)) < H323_ERROR_NONE) return err; } /* No extension? */ if (!ext) return H323_ERROR_NONE; /* Get the extension bitmap */ bmp2_len = get_bits(bs, 7) + 1; CHECK_BOUND(bs, (bmp2_len + 7) >> 3); bmp2 = get_bitmap(bs, bmp2_len); bmp |= bmp2 >> f->sz; if (base) *(unsigned int *)base = bmp; BYTE_ALIGN(bs); /* Decode the extension components */ for (opt = 0; opt < bmp2_len; opt++, i++, son++) { /* Check Range */ if (i >= f->ub) { /* Newer Version? */ CHECK_BOUND(bs, 2); len = get_len(bs); CHECK_BOUND(bs, len); bs->cur += len; continue; } if (son->attr & STOP) { PRINT("%*.s%s\n", (level + 1) * TAB_SIZE, " ", son->name); return H323_ERROR_STOP; } if (!((0x80000000 >> opt) & bmp2)) /* Not present */ continue; CHECK_BOUND(bs, 2); len = get_len(bs); CHECK_BOUND(bs, len); if (!base || !(son->attr & DECODE)) { PRINT("%*.s%s\n", (level + 1) * TAB_SIZE, " ", son->name); bs->cur += len; continue; } beg = bs->cur; if ((err = (Decoders[son->type]) (bs, son, base, level + 1)) < H323_ERROR_NONE) return err; bs->cur = beg + len; bs->bit = 0; } return H323_ERROR_NONE; } /****************************************************************************/ static int decode_seqof(bitstr_t *bs, const struct field_t *f, char *base, int level) { unsigned int count, effective_count = 0, i, len = 0; int err; const struct field_t *son; unsigned char *beg = NULL; PRINT("%*.s%s\n", level * TAB_SIZE, " ", f->name); /* Decode? */ base = (base && (f->attr & DECODE)) ? base + f->offset : NULL; /* Decode item count */ switch (f->sz) { case BYTE: BYTE_ALIGN(bs); CHECK_BOUND(bs, 1); count = *bs->cur++; break; case WORD: BYTE_ALIGN(bs); CHECK_BOUND(bs, 2); count = *bs->cur++; count <<= 8; count += *bs->cur++; break; case SEMI: BYTE_ALIGN(bs); CHECK_BOUND(bs, 2); count = get_len(bs); break; default: count = get_bits(bs, f->sz); break; } count += f->lb; /* Write Count */ if (base) { effective_count = count > f->ub ? f->ub : count; *(unsigned int *)base = effective_count; base += sizeof(unsigned int); } /* Decode nested field */ son = f->fields; if (base) base -= son->offset; for (i = 0; i < count; i++) { if (son->attr & OPEN) { BYTE_ALIGN(bs); len = get_len(bs); CHECK_BOUND(bs, len); if (!base || !(son->attr & DECODE)) { PRINT("%*.s%s\n", (level + 1) * TAB_SIZE, " ", son->name); bs->cur += len; continue; } beg = bs->cur; if ((err = (Decoders[son->type]) (bs, son, i < effective_count ? base : NULL, level + 1)) < H323_ERROR_NONE) return err; bs->cur = beg + len; bs->bit = 0; } else if ((err = (Decoders[son->type]) (bs, son, i < effective_count ? base : NULL, level + 1)) < H323_ERROR_NONE) return err; if (base) base += son->offset; } return H323_ERROR_NONE; } /****************************************************************************/ static int decode_choice(bitstr_t *bs, const struct field_t *f, char *base, int level) { unsigned int type, ext, len = 0; int err; const struct field_t *son; unsigned char *beg = NULL; PRINT("%*.s%s\n", level * TAB_SIZE, " ", f->name); /* Decode? */ base = (base && (f->attr & DECODE)) ? base + f->offset : NULL; /* Decode the choice index number */ if ((f->attr & EXT) && get_bit(bs)) { ext = 1; type = get_bits(bs, 7) + f->lb; } else { ext = 0; type = get_bits(bs, f->sz); if (type >= f->lb) return H323_ERROR_RANGE; } /* Write Type */ if (base) *(unsigned int *)base = type; /* Check Range */ if (type >= f->ub) { /* Newer version? */ BYTE_ALIGN(bs); len = get_len(bs); CHECK_BOUND(bs, len); bs->cur += len; return H323_ERROR_NONE; } /* Transfer to son level */ son = &f->fields[type]; if (son->attr & STOP) { PRINT("%*.s%s\n", (level + 1) * TAB_SIZE, " ", son->name); return H323_ERROR_STOP; } if (ext || (son->attr & OPEN)) { BYTE_ALIGN(bs); len = get_len(bs); CHECK_BOUND(bs, len); if (!base || !(son->attr & DECODE)) { PRINT("%*.s%s\n", (level + 1) * TAB_SIZE, " ", son->name); bs->cur += len; return H323_ERROR_NONE; } beg = bs->cur; if ((err = (Decoders[son->type]) (bs, son, base, level + 1)) < H323_ERROR_NONE) return err; bs->cur = beg + len; bs->bit = 0; } else if ((err = (Decoders[son->type]) (bs, son, base, level + 1)) < H323_ERROR_NONE) return err; return H323_ERROR_NONE; } /****************************************************************************/ int DecodeRasMessage(unsigned char *buf, size_t sz, RasMessage *ras) { static const struct field_t ras_message = { FNAME("RasMessage") CHOICE, 5, 24, 32, DECODE | EXT, 0, _RasMessage }; bitstr_t bs; bs.buf = bs.beg = bs.cur = buf; bs.end = buf + sz; bs.bit = 0; return decode_choice(&bs, &ras_message, (char *) ras, 0); } /****************************************************************************/ static int DecodeH323_UserInformation(unsigned char *buf, unsigned char *beg, size_t sz, H323_UserInformation *uuie) { static const struct field_t h323_userinformation = { FNAME("H323-UserInformation") SEQ, 1, 2, 2, DECODE | EXT, 0, _H323_UserInformation }; bitstr_t bs; bs.buf = buf; bs.beg = bs.cur = beg; bs.end = beg + sz; bs.bit = 0; return decode_seq(&bs, &h323_userinformation, (char *) uuie, 0); } /****************************************************************************/ int DecodeMultimediaSystemControlMessage(unsigned char *buf, size_t sz, MultimediaSystemControlMessage * mscm) { static const struct field_t multimediasystemcontrolmessage = { FNAME("MultimediaSystemControlMessage") CHOICE, 2, 4, 4, DECODE | EXT, 0, _MultimediaSystemControlMessage }; bitstr_t bs; bs.buf = bs.beg = bs.cur = buf; bs.end = buf + sz; bs.bit = 0; return decode_choice(&bs, &multimediasystemcontrolmessage, (char *) mscm, 0); } /****************************************************************************/ int DecodeQ931(unsigned char *buf, size_t sz, Q931 *q931) { unsigned char *p = buf; int len; if (!p || sz < 1) return H323_ERROR_BOUND; /* Protocol Discriminator */ if (*p != 0x08) { PRINT("Unknown Protocol Discriminator\n"); return H323_ERROR_RANGE; } p++; sz--; /* CallReferenceValue */ if (sz < 1) return H323_ERROR_BOUND; len = *p++; sz--; if (sz < len) return H323_ERROR_BOUND; p += len; sz -= len; /* Message Type */ if (sz < 2) return H323_ERROR_BOUND; q931->MessageType = *p++; sz--; PRINT("MessageType = %02X\n", q931->MessageType); if (*p & 0x80) { p++; sz--; } /* Decode Information Elements */ while (sz > 0) { if (*p == 0x7e) { /* UserUserIE */ if (sz < 3) break; p++; len = *p++ << 8; len |= *p++; sz -= 3; if (sz < len) break; p++; len--; return DecodeH323_UserInformation(buf, p, len, &q931->UUIE); } p++; sz--; if (sz < 1) break; len = *p++; if (sz < len) break; p += len; sz -= len; } PRINT("Q.931 UUIE not found\n"); return H323_ERROR_BOUND; }
null
null
null
null
75,438
41,388
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
206,383
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Copyright (C) 2015, Intel Corporation * Author: Jiang Liu <jiang.liu@linux.intel.com> * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope 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 _LINUX_RESOURCE_EXT_H #define _LINUX_RESOURCE_EXT_H #include <linux/types.h> #include <linux/list.h> #include <linux/ioport.h> #include <linux/slab.h> /* Represent resource window for bridge devices */ struct resource_win { struct resource res; /* In master (CPU) address space */ resource_size_t offset; /* Translation offset for bridge */ }; /* * Common resource list management data structure and interfaces to support * ACPI, PNP and PCI host bridge etc. */ struct resource_entry { struct list_head node; struct resource *res; /* In master (CPU) address space */ resource_size_t offset; /* Translation offset for bridge */ struct resource __res; /* Default storage for res */ }; extern struct resource_entry * resource_list_create_entry(struct resource *res, size_t extra_size); extern void resource_list_free(struct list_head *head); static inline void resource_list_add(struct resource_entry *entry, struct list_head *head) { list_add(&entry->node, head); } static inline void resource_list_add_tail(struct resource_entry *entry, struct list_head *head) { list_add_tail(&entry->node, head); } static inline void resource_list_del(struct resource_entry *entry) { list_del(&entry->node); } static inline void resource_list_free_entry(struct resource_entry *entry) { kfree(entry); } static inline void resource_list_destroy_entry(struct resource_entry *entry) { resource_list_del(entry); resource_list_free_entry(entry); } #define resource_list_for_each_entry(entry, list) \ list_for_each_entry((entry), (list), node) #define resource_list_for_each_entry_safe(entry, tmp, list) \ list_for_each_entry_safe((entry), (tmp), (list), node) #endif /* _LINUX_RESOURCE_EXT_H */
null
null
null
null
114,730
15,081
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
180,076
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Just-In-Time compiler for BPF filters on MIPS * * Copyright (c) 2014 Imagination Technologies Ltd. * Author: Markos Chandras <markos.chandras@imgtec.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; version 2 of the License. */ #ifndef BPF_JIT_MIPS_OP_H #define BPF_JIT_MIPS_OP_H /* Registers used by JIT */ #define MIPS_R_ZERO 0 #define MIPS_R_V0 2 #define MIPS_R_A0 4 #define MIPS_R_A1 5 #define MIPS_R_T4 12 #define MIPS_R_T5 13 #define MIPS_R_T6 14 #define MIPS_R_T7 15 #define MIPS_R_S0 16 #define MIPS_R_S1 17 #define MIPS_R_S2 18 #define MIPS_R_S3 19 #define MIPS_R_S4 20 #define MIPS_R_S5 21 #define MIPS_R_S6 22 #define MIPS_R_S7 23 #define MIPS_R_SP 29 #define MIPS_R_RA 31 /* Conditional codes */ #define MIPS_COND_EQ 0x1 #define MIPS_COND_GE (0x1 << 1) #define MIPS_COND_GT (0x1 << 2) #define MIPS_COND_NE (0x1 << 3) #define MIPS_COND_ALL (0x1 << 4) /* Conditionals on X register or K immediate */ #define MIPS_COND_X (0x1 << 5) #define MIPS_COND_K (0x1 << 6) #define r_ret MIPS_R_V0 /* * Use 2 scratch registers to avoid pipeline interlocks. * There is no overhead during epilogue and prologue since * any of the $s0-$s6 registers will only be preserved if * they are going to actually be used. */ #define r_skb_hl MIPS_R_S0 /* skb header length */ #define r_skb_data MIPS_R_S1 /* skb actual data */ #define r_off MIPS_R_S2 #define r_A MIPS_R_S3 #define r_X MIPS_R_S4 #define r_skb MIPS_R_S5 #define r_M MIPS_R_S6 #define r_skb_len MIPS_R_S7 #define r_s0 MIPS_R_T4 /* scratch reg 1 */ #define r_s1 MIPS_R_T5 /* scratch reg 2 */ #define r_tmp_imm MIPS_R_T6 /* No need to preserve this */ #define r_tmp MIPS_R_T7 /* No need to preserve this */ #define r_zero MIPS_R_ZERO #define r_sp MIPS_R_SP #define r_ra MIPS_R_RA #ifndef __ASSEMBLY__ /* Declare ASM helpers */ #define DECLARE_LOAD_FUNC(func) \ extern u8 func(unsigned long *skb, int offset); \ extern u8 func##_negative(unsigned long *skb, int offset); \ extern u8 func##_positive(unsigned long *skb, int offset) DECLARE_LOAD_FUNC(sk_load_word); DECLARE_LOAD_FUNC(sk_load_half); DECLARE_LOAD_FUNC(sk_load_byte); #endif #endif /* BPF_JIT_MIPS_OP_H */
null
null
null
null
88,423
17,029
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
182,024
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
#ifndef __ASM_SH_REBOOT_H #define __ASM_SH_REBOOT_H #include <linux/kdebug.h> struct pt_regs; struct machine_ops { void (*restart)(char *cmd); void (*halt)(void); void (*power_off)(void); void (*shutdown)(void); void (*crash_shutdown)(struct pt_regs *); }; extern struct machine_ops machine_ops; /* arch/sh/kernel/machine_kexec.c */ void native_machine_crash_shutdown(struct pt_regs *regs); #endif /* __ASM_SH_REBOOT_H */
null
null
null
null
90,371
29,605
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
29,605
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* ** 2003 January 11 ** ** 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. ** ************************************************************************* ** This file contains code used to implement the sqlite3_set_authorizer() ** API. This facility is an optional feature of the library. Embedded ** systems that do not need this facility may omit it by recompiling ** the library with -DSQLITE_OMIT_AUTHORIZATION=1 */ #include "sqliteInt.h" /* ** All of the code in this file may be omitted by defining a single ** macro. */ #ifndef SQLITE_OMIT_AUTHORIZATION /* ** Set or clear the access authorization function. ** ** The access authorization function is be called during the compilation ** phase to verify that the user has read and/or write access permission on ** various fields of the database. The first argument to the auth function ** is a copy of the 3rd argument to this routine. The second argument ** to the auth function is one of these constants: ** ** SQLITE_CREATE_INDEX ** SQLITE_CREATE_TABLE ** SQLITE_CREATE_TEMP_INDEX ** SQLITE_CREATE_TEMP_TABLE ** SQLITE_CREATE_TEMP_TRIGGER ** SQLITE_CREATE_TEMP_VIEW ** SQLITE_CREATE_TRIGGER ** SQLITE_CREATE_VIEW ** SQLITE_DELETE ** SQLITE_DROP_INDEX ** SQLITE_DROP_TABLE ** SQLITE_DROP_TEMP_INDEX ** SQLITE_DROP_TEMP_TABLE ** SQLITE_DROP_TEMP_TRIGGER ** SQLITE_DROP_TEMP_VIEW ** SQLITE_DROP_TRIGGER ** SQLITE_DROP_VIEW ** SQLITE_INSERT ** SQLITE_PRAGMA ** SQLITE_READ ** SQLITE_SELECT ** SQLITE_TRANSACTION ** SQLITE_UPDATE ** ** The third and fourth arguments to the auth function are the name of ** the table and the column that are being accessed. The auth function ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY ** means that the SQL statement will never-run - the sqlite3_exec() call ** will return with an error. SQLITE_IGNORE means that the SQL statement ** should run but attempts to read the specified column will return NULL ** and attempts to write the column will be ignored. ** ** Setting the auth function to NULL disables this hook. The default ** setting of the auth function is NULL. */ int sqlite3_set_authorizer( sqlite3 *db, int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), void *pArg ){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); db->xAuth = (sqlite3_xauth)xAuth; db->pAuthArg = pArg; sqlite3ExpirePreparedStatements(db); sqlite3_mutex_leave(db->mutex); return SQLITE_OK; } /* ** Write an error message into pParse->zErrMsg that explains that the ** user-supplied authorization function returned an illegal value. */ static void sqliteAuthBadReturnCode(Parse *pParse){ sqlite3ErrorMsg(pParse, "authorizer malfunction"); pParse->rc = SQLITE_ERROR; } /* ** Invoke the authorization callback for permission to read column zCol from ** table zTab in database zDb. This function assumes that an authorization ** callback has been registered (i.e. that sqlite3.xAuth is not NULL). ** ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE ** is treated as SQLITE_DENY. In this case an error is left in pParse. */ int sqlite3AuthReadCol( Parse *pParse, /* The parser context */ const char *zTab, /* Table name */ const char *zCol, /* Column name */ int iDb /* Index of containing database. */ ){ sqlite3 *db = pParse->db; /* Database handle */ char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */ int rc; /* Auth callback return code */ if( db->init.busy ) return SQLITE_OK; rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext #ifdef SQLITE_USER_AUTHENTICATION ,db->auth.zAuthUser #endif ); if( rc==SQLITE_DENY ){ char *z = sqlite3_mprintf("%s.%s", zTab, zCol); if( db->nDb>2 || iDb!=0 ) z = sqlite3_mprintf("%s.%z", zDb, z); sqlite3ErrorMsg(pParse, "access to %z is prohibited", z); pParse->rc = SQLITE_AUTH; }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){ sqliteAuthBadReturnCode(pParse); } return rc; } /* ** The pExpr should be a TK_COLUMN expression. The table referred to ** is in pTabList or else it is the NEW or OLD table of a trigger. ** Check to see if it is OK to read this particular column. ** ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY, ** then generate an error. */ void sqlite3AuthRead( Parse *pParse, /* The parser context */ Expr *pExpr, /* The expression to check authorization on */ Schema *pSchema, /* The schema of the expression */ SrcList *pTabList /* All table that pExpr might refer to */ ){ sqlite3 *db = pParse->db; Table *pTab = 0; /* The table being read */ const char *zCol; /* Name of the column of the table */ int iSrc; /* Index in pTabList->a[] of table being read */ int iDb; /* The index of the database the expression refers to */ int iCol; /* Index of column in table */ if( db->xAuth==0 ) return; iDb = sqlite3SchemaToIndex(pParse->db, pSchema); if( iDb<0 ){ /* An attempt to read a column out of a subquery or other ** temporary table. */ return; } assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER ); if( pExpr->op==TK_TRIGGER ){ pTab = pParse->pTriggerTab; }else{ assert( pTabList ); for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){ if( pExpr->iTable==pTabList->a[iSrc].iCursor ){ pTab = pTabList->a[iSrc].pTab; break; } } } iCol = pExpr->iColumn; if( NEVER(pTab==0) ) return; if( iCol>=0 ){ assert( iCol<pTab->nCol ); zCol = pTab->aCol[iCol].zName; }else if( pTab->iPKey>=0 ){ assert( pTab->iPKey<pTab->nCol ); zCol = pTab->aCol[pTab->iPKey].zName; }else{ zCol = "ROWID"; } assert( iDb>=0 && iDb<db->nDb ); if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){ pExpr->op = TK_NULL; } } /* ** Do an authorization check using the code and arguments given. Return ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY ** is returned, then the error count and error message in pParse are ** modified appropriately. */ int sqlite3AuthCheck( Parse *pParse, int code, const char *zArg1, const char *zArg2, const char *zArg3 ){ sqlite3 *db = pParse->db; int rc; /* Don't do any authorization checks if the database is initialising ** or if the parser is being invoked from within sqlite3_declare_vtab. */ if( db->init.busy || IN_DECLARE_VTAB ){ return SQLITE_OK; } if( db->xAuth==0 ){ return SQLITE_OK; } /* EVIDENCE-OF: R-43249-19882 The third through sixth parameters to the ** callback are either NULL pointers or zero-terminated strings that ** contain additional details about the action to be authorized. ** ** The following testcase() macros show that any of the 3rd through 6th ** parameters can be either NULL or a string. */ testcase( zArg1==0 ); testcase( zArg2==0 ); testcase( zArg3==0 ); testcase( pParse->zAuthContext==0 ); rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext #ifdef SQLITE_USER_AUTHENTICATION ,db->auth.zAuthUser #endif ); if( rc==SQLITE_DENY ){ sqlite3ErrorMsg(pParse, "not authorized"); pParse->rc = SQLITE_AUTH; }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){ rc = SQLITE_DENY; sqliteAuthBadReturnCode(pParse); } return rc; } /* ** Push an authorization context. After this routine is called, the ** zArg3 argument to authorization callbacks will be zContext until ** popped. Or if pParse==0, this routine is a no-op. */ void sqlite3AuthContextPush( Parse *pParse, AuthContext *pContext, const char *zContext ){ assert( pParse ); pContext->pParse = pParse; pContext->zAuthContext = pParse->zAuthContext; pParse->zAuthContext = zContext; } /* ** Pop an authorization context that was previously pushed ** by sqlite3AuthContextPush */ void sqlite3AuthContextPop(AuthContext *pContext){ if( pContext->pParse ){ pContext->pParse->zAuthContext = pContext->zAuthContext; pContext->pParse = 0; } } #endif /* SQLITE_OMIT_AUTHORIZATION */
null
null
null
null
26,468
12,048
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
12,048
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 COMPONENTS_BOOKMARKS_BROWSER_BOOKMARK_STORAGE_H_ #define COMPONENTS_BOOKMARKS_BROWSER_BOOKMARK_STORAGE_H_ #include <stdint.h> #include <memory> #include <string> #include <vector> #include "base/callback_forward.h" #include "base/files/file_path.h" #include "base/files/important_file_writer.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "components/bookmarks/browser/bookmark_node.h" #include "components/bookmarks/browser/titled_url_index.h" namespace base { class SequencedTaskRunner; } namespace bookmarks { class BookmarkModel; // A list of BookmarkPermanentNodes that owns them. using BookmarkPermanentNodeList = std::vector<std::unique_ptr<BookmarkPermanentNode>>; // A callback that generates a BookmarkPermanentNodeList, given a max ID to // use. The max ID argument will be updated after any new nodes have been // created and assigned IDs. using LoadExtraCallback = base::Callback<BookmarkPermanentNodeList(int64_t*)>; // BookmarkLoadDetails is used by BookmarkStorage when loading bookmarks. // BookmarkModel creates a BookmarkLoadDetails and passes it (including // ownership) to BookmarkStorage. BookmarkStorage loads the bookmarks (and // index) in the background thread, then calls back to the BookmarkModel (on // the main thread) when loading is done, passing ownership back to the // BookmarkModel. While loading BookmarkModel does not maintain references to // the contents of the BookmarkLoadDetails, this ensures we don't have any // threading problems. class BookmarkLoadDetails { public: BookmarkLoadDetails(BookmarkPermanentNode* bb_node, BookmarkPermanentNode* other_folder_node, BookmarkPermanentNode* mobile_folder_node, const LoadExtraCallback& load_extra_callback, TitledUrlIndex* index, int64_t max_id); ~BookmarkLoadDetails(); void LoadExtraNodes(); BookmarkPermanentNode* bb_node() { return bb_node_.get(); } std::unique_ptr<BookmarkPermanentNode> owned_bb_node() { return std::move(bb_node_); } BookmarkPermanentNode* mobile_folder_node() { return mobile_folder_node_.get(); } std::unique_ptr<BookmarkPermanentNode> owned_mobile_folder_node() { return std::move(mobile_folder_node_); } BookmarkPermanentNode* other_folder_node() { return other_folder_node_.get(); } std::unique_ptr<BookmarkPermanentNode> owned_other_folder_node() { return std::move(other_folder_node_); } const BookmarkPermanentNodeList& extra_nodes() { return extra_nodes_; } BookmarkPermanentNodeList owned_extra_nodes() { return std::move(extra_nodes_); } TitledUrlIndex* index() { return index_.get(); } std::unique_ptr<TitledUrlIndex> owned_index() { return std::move(index_); } const BookmarkNode::MetaInfoMap& model_meta_info_map() const { return model_meta_info_map_; } void set_model_meta_info_map(const BookmarkNode::MetaInfoMap& meta_info_map) { model_meta_info_map_ = meta_info_map; } int64_t model_sync_transaction_version() const { return model_sync_transaction_version_; } void set_model_sync_transaction_version(int64_t sync_transaction_version) { model_sync_transaction_version_ = sync_transaction_version; } // Max id of the nodes. void set_max_id(int64_t max_id) { max_id_ = max_id; } int64_t max_id() const { return max_id_; } // Computed checksum. void set_computed_checksum(const std::string& value) { computed_checksum_ = value; } const std::string& computed_checksum() const { return computed_checksum_; } // Stored checksum. void set_stored_checksum(const std::string& value) { stored_checksum_ = value; } const std::string& stored_checksum() const { return stored_checksum_; } // Whether ids were reassigned. IDs are reassigned during decoding if the // checksum of the file doesn't match, some IDs are missing or not // unique. Basically, if the user modified the bookmarks directly we'll // reassign the ids to ensure they are unique. void set_ids_reassigned(bool value) { ids_reassigned_ = value; } bool ids_reassigned() const { return ids_reassigned_; } private: std::unique_ptr<BookmarkPermanentNode> bb_node_; std::unique_ptr<BookmarkPermanentNode> other_folder_node_; std::unique_ptr<BookmarkPermanentNode> mobile_folder_node_; LoadExtraCallback load_extra_callback_; BookmarkPermanentNodeList extra_nodes_; std::unique_ptr<TitledUrlIndex> index_; BookmarkNode::MetaInfoMap model_meta_info_map_; int64_t model_sync_transaction_version_; int64_t max_id_; std::string computed_checksum_; std::string stored_checksum_; bool ids_reassigned_; DISALLOW_COPY_AND_ASSIGN(BookmarkLoadDetails); }; // BookmarkStorage handles reading/write the bookmark bar model. The // BookmarkModel uses the BookmarkStorage to load bookmarks from disk, as well // as notifying the BookmarkStorage every time the model changes. // // Internally BookmarkStorage uses BookmarkCodec to do the actual read/write. class BookmarkStorage : public base::ImportantFileWriter::DataSerializer { public: // Creates a BookmarkStorage for the specified model. The data will be loaded // from and saved to a location derived from |profile_path|. The IO code will // be executed as a task in |sequenced_task_runner|. BookmarkStorage(BookmarkModel* model, const base::FilePath& profile_path, base::SequencedTaskRunner* sequenced_task_runner); ~BookmarkStorage() override; // Loads the bookmarks into the model, notifying the model when done. This // takes ownership of |details| and send the |OnLoadFinished| callback from // a task in |task_runner|. See BookmarkLoadDetails for details. void LoadBookmarks( std::unique_ptr<BookmarkLoadDetails> details, const scoped_refptr<base::SequencedTaskRunner>& task_runner); // Schedules saving the bookmark bar model to disk. void ScheduleSave(); // Notification the bookmark bar model is going to be deleted. If there is // a pending save, it is saved immediately. void BookmarkModelDeleted(); // Callback from backend after loading the bookmark file. void OnLoadFinished(std::unique_ptr<BookmarkLoadDetails> details); // ImportantFileWriter::DataSerializer implementation. bool SerializeData(std::string* output) override; private: // The state of the bookmark file backup. We lazily backup this file in order // to reduce disk writes until absolutely necessary. Will also leave the // backup unchanged if the browser starts & quits w/o changing bookmarks. enum BackupState { // No attempt has yet been made to backup the bookmarks file. BACKUP_NONE, // A request to backup the bookmarks file has been posted, but not yet // fulfilled. BACKUP_DISPATCHED, // The bookmarks file has been backed up (or at least attempted). BACKUP_ATTEMPTED }; // Serializes the data and schedules save using ImportantFileWriter. // Returns true on successful serialization. bool SaveNow(); // Callback from backend after creation of backup file. void OnBackupFinished(); // The model. The model is NULL once BookmarkModelDeleted has been invoked. BookmarkModel* model_; // Helper to write bookmark data safely. base::ImportantFileWriter writer_; // The state of the backup file creation which is created lazily just before // the first scheduled save. BackupState backup_state_ = BACKUP_NONE; // Sequenced task runner where file I/O operations will be performed at. scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner_; base::WeakPtrFactory<BookmarkStorage> weak_factory_; DISALLOW_COPY_AND_ASSIGN(BookmarkStorage); }; } // namespace bookmarks #endif // COMPONENTS_BOOKMARKS_BROWSER_BOOKMARK_STORAGE_H_
null
null
null
null
8,911
34,310
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
34,310
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 "third_party/blink/renderer/core/paint/box_reflection_utils.h" #include "third_party/blink/renderer/core/layout/layout_box.h" #include "third_party/blink/renderer/core/paint/nine_piece_image_painter.h" #include "third_party/blink/renderer/core/paint/paint_layer.h" #include "third_party/blink/renderer/platform/geometry/float_rect.h" #include "third_party/blink/renderer/platform/geometry/layout_point.h" #include "third_party/blink/renderer/platform/geometry/layout_rect.h" #include "third_party/blink/renderer/platform/graphics/box_reflection.h" #include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_record_builder.h" #include "third_party/blink/renderer/platform/length_functions.h" namespace blink { BoxReflection BoxReflectionForPaintLayer(const PaintLayer& layer, const ComputedStyle& style) { const StyleReflection* reflect_style = style.BoxReflect(); LayoutRect frame_layout_rect = ToLayoutBox(layer.GetLayoutObject()).FrameRect(); FloatRect frame_rect(frame_layout_rect); BoxReflection::ReflectionDirection direction = BoxReflection::kVerticalReflection; float offset = 0; switch (reflect_style->Direction()) { case kReflectionAbove: direction = BoxReflection::kVerticalReflection; offset = -FloatValueForLength(reflect_style->Offset(), frame_rect.Height()); break; case kReflectionBelow: direction = BoxReflection::kVerticalReflection; offset = 2 * frame_rect.Height() + FloatValueForLength(reflect_style->Offset(), frame_rect.Height()); break; case kReflectionLeft: direction = BoxReflection::kHorizontalReflection; offset = -FloatValueForLength(reflect_style->Offset(), frame_rect.Width()); break; case kReflectionRight: direction = BoxReflection::kHorizontalReflection; offset = 2 * frame_rect.Width() + FloatValueForLength(reflect_style->Offset(), frame_rect.Width()); break; } const NinePieceImage& mask_nine_piece = reflect_style->Mask(); if (!mask_nine_piece.HasImage()) return BoxReflection(direction, offset, nullptr, FloatRect()); LayoutRect mask_rect(LayoutPoint(), frame_layout_rect.Size()); LayoutRect mask_bounding_rect(mask_rect); mask_bounding_rect.Expand(style.ImageOutsets(mask_nine_piece)); PaintRecordBuilder builder; { GraphicsContext& context = builder.Context(); DrawingRecorder recorder(context, layer.GetLayoutObject(), DisplayItem::kReflectionMask); Node* node = nullptr; const LayoutObject* layout_object = &layer.GetLayoutObject(); for (; layout_object && !node; layout_object = layout_object->Parent()) node = layout_object->GeneratingNode(); NinePieceImagePainter::Paint(builder.Context(), layer.GetLayoutObject(), layer.GetLayoutObject().GetDocument(), node, mask_rect, style, mask_nine_piece); } return BoxReflection(direction, offset, builder.EndRecording(), FloatRect(mask_bounding_rect)); } } // namespace blink
null
null
null
null
31,173
6,469
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
6,469
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_NETWORK_NETWORK_DEVICE_HANDLER_IMPL_H_ #define CHROMEOS_NETWORK_NETWORK_DEVICE_HANDLER_IMPL_H_ #include <map> #include <string> #include "base/callback.h" #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "chromeos/chromeos_export.h" #include "chromeos/network/network_device_handler.h" #include "chromeos/network/network_handler.h" #include "chromeos/network/network_handler_callbacks.h" #include "chromeos/network/network_state_handler_observer.h" namespace chromeos { class NetworkStateHandler; class CHROMEOS_EXPORT NetworkDeviceHandlerImpl : public NetworkDeviceHandler, public NetworkStateHandlerObserver { public: ~NetworkDeviceHandlerImpl() override; // NetworkDeviceHandler overrides void GetDeviceProperties( const std::string& device_path, const network_handler::DictionaryResultCallback& callback, const network_handler::ErrorCallback& error_callback) const override; void SetDeviceProperty( const std::string& device_path, const std::string& property_name, const base::Value& value, const base::Closure& callback, const network_handler::ErrorCallback& error_callback) override; void RequestRefreshIPConfigs( const std::string& device_path, const base::Closure& callback, const network_handler::ErrorCallback& error_callback) override; void RegisterCellularNetwork( const std::string& device_path, const std::string& network_id, const base::Closure& callback, const network_handler::ErrorCallback& error_callback) override; void SetCarrier( const std::string& device_path, const std::string& carrier, const base::Closure& callback, const network_handler::ErrorCallback& error_callback) override; void RequirePin( const std::string& device_path, bool require_pin, const std::string& pin, const base::Closure& callback, const network_handler::ErrorCallback& error_callback) override; void EnterPin(const std::string& device_path, const std::string& pin, const base::Closure& callback, const network_handler::ErrorCallback& error_callback) override; void UnblockPin( const std::string& device_path, const std::string& puk, const std::string& new_pin, const base::Closure& callback, const network_handler::ErrorCallback& error_callback) override; void ChangePin(const std::string& device_path, const std::string& old_pin, const std::string& new_pin, const base::Closure& callback, const network_handler::ErrorCallback& error_callback) override; void SetCellularAllowRoaming(bool allow_roaming) override; void SetMACAddressRandomizationEnabled(bool enabled) override; void SetWifiTDLSEnabled( const std::string& ip_or_mac_address, bool enabled, const network_handler::StringResultCallback& callback, const network_handler::ErrorCallback& error_callback) override; void GetWifiTDLSStatus( const std::string& ip_or_mac_address, const network_handler::StringResultCallback& callback, const network_handler::ErrorCallback& error_callback) override; void AddWifiWakeOnPacketConnection( const net::IPEndPoint& ip_endpoint, const base::Closure& callback, const network_handler::ErrorCallback& error_callback) override; void RemoveWifiWakeOnPacketConnection( const net::IPEndPoint& ip_endpoint, const base::Closure& callback, const network_handler::ErrorCallback& error_callback) override; void RemoveAllWifiWakeOnPacketConnections( const base::Closure& callback, const network_handler::ErrorCallback& error_callback) override; // NetworkStateHandlerObserver overrides void DeviceListChanged() override; private: friend class NetworkHandler; friend class NetworkDeviceHandlerTest; // When there's no Wi-Fi device or there is one but we haven't asked if // MAC address randomization is supported yet, the value of the member // |mac_addr_randomizaton_supported_| will be |NOT_REQUESTED|. When we // try to apply the |mac_addr_randomization_enabled_| value we will // check whether it is supported and change to one of the other two // values. enum class MACAddressRandomizationSupport { NOT_REQUESTED, SUPPORTED, UNSUPPORTED }; NetworkDeviceHandlerImpl(); void Init(NetworkStateHandler* network_state_handler); // Apply the current value of |cellular_allow_roaming_| to all existing // cellular devices of Shill. void ApplyCellularAllowRoamingToShill(); // Apply the current value of |mac_addr_randomization_enabled_| to wifi // devices. void ApplyMACAddressRandomizationToShill(); // Sets the value of |mac_addr_randomization_supported_| based on // whether shill thinks it is supported on the wifi device. If it is // supported, also apply |mac_addr_randomization_enabled_| to the // shill device. void HandleMACAddressRandomization(const std::string& device_path, const base::DictionaryValue& properties); // Get the DeviceState for the wifi device, if any. const DeviceState* GetWifiDeviceState( const network_handler::ErrorCallback& error_callback); NetworkStateHandler* network_state_handler_ = nullptr; bool cellular_allow_roaming_ = false; MACAddressRandomizationSupport mac_addr_randomization_supported_ = MACAddressRandomizationSupport::NOT_REQUESTED; bool mac_addr_randomization_enabled_ = false; base::WeakPtrFactory<NetworkDeviceHandlerImpl> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(NetworkDeviceHandlerImpl); }; } // namespace chromeos #endif // CHROMEOS_NETWORK_NETWORK_DEVICE_HANDLER_IMPL_H_
null
null
null
null
3,332
68,020
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
68,020
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 REMOTING_PROTOCOL_FAKE_AUTHENTICATOR_H_ #define REMOTING_PROTOCOL_FAKE_AUTHENTICATOR_H_ #include "base/callback.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "remoting/protocol/authenticator.h" #include "remoting/protocol/channel_authenticator.h" namespace remoting { namespace protocol { class FakeChannelAuthenticator : public ChannelAuthenticator { public: FakeChannelAuthenticator(bool accept, bool async); ~FakeChannelAuthenticator() override; // ChannelAuthenticator interface. void SecureAndAuthenticate(std::unique_ptr<P2PStreamSocket> socket, const DoneCallback& done_callback) override; private: void OnAuthBytesWritten(int result); void OnAuthBytesRead(int result); void CallDoneCallback(); const int result_; const bool async_; std::unique_ptr<P2PStreamSocket> socket_; DoneCallback done_callback_; bool did_read_bytes_ = false; bool did_write_bytes_ = false; base::WeakPtrFactory<FakeChannelAuthenticator> weak_factory_; DISALLOW_COPY_AND_ASSIGN(FakeChannelAuthenticator); }; class FakeAuthenticator : public Authenticator { public: enum Type { HOST, CLIENT, }; enum Action { ACCEPT, REJECT, REJECT_CHANNEL }; struct Config { Config(); Config(Action action); Config(int round_trips, Action action, bool async); int round_trips = 1; Action action = Action::ACCEPT; bool async = true; }; FakeAuthenticator(Type type, Config config, const std::string& local_id, const std::string& remote_id); // Special constructor for authenticators in ACCEPTED or REJECTED state that // don't exchange any messages. FakeAuthenticator(Action action); ~FakeAuthenticator() override; // Set the number of messages that the authenticator needs to process before // started() returns true. Default to 0. void set_messages_till_started(int messages); // Sets auth key to be returned by GetAuthKey(). Must be called when // |round_trips| is set to 0. void set_auth_key(const std::string& auth_key) { auth_key_ = auth_key; } // When pause_message_index is set the authenticator will pause in // PROCESSING_MESSAGE state after that message, until // TakeResumeClosure().Run() is called. void set_pause_message_index(int pause_message_index) { pause_message_index_ = pause_message_index; } void Resume(); // Authenticator interface. State state() const override; bool started() const override; RejectionReason rejection_reason() const override; void ProcessMessage(const buzz::XmlElement* message, const base::Closure& resume_callback) override; std::unique_ptr<buzz::XmlElement> GetNextMessage() override; const std::string& GetAuthKey() const override; std::unique_ptr<ChannelAuthenticator> CreateChannelAuthenticator() const override; protected: const Type type_; const Config config_; const std::string local_id_; const std::string remote_id_; // Total number of messages that have been processed. int messages_ = 0; // Number of messages that the authenticator needs to process before started() // returns true. Default to 0. int messages_till_started_ = 0; int pause_message_index_ = -1; base::Closure resume_closure_; std::string auth_key_; DISALLOW_COPY_AND_ASSIGN(FakeAuthenticator); }; class FakeHostAuthenticatorFactory : public AuthenticatorFactory { public: FakeHostAuthenticatorFactory(int messages_till_start, FakeAuthenticator::Config config); ~FakeHostAuthenticatorFactory() override; // AuthenticatorFactory interface. std::unique_ptr<Authenticator> CreateAuthenticator( const std::string& local_jid, const std::string& remote_jid) override; private: const int messages_till_started_; const FakeAuthenticator::Config config_; DISALLOW_COPY_AND_ASSIGN(FakeHostAuthenticatorFactory); }; } // namespace protocol } // namespace remoting #endif // REMOTING_PROTOCOL_FAKE_AUTHENTICATOR_H_
null
null
null
null
64,883
1,152
null
train_val
1b0d3845b454eaaac0b2064c78926ca4d739a080
263,720
qemu
0
https://github.com/bonzini/qemu
2016-10-18 11:40:27+01:00
#include<stdio.h> #include<assert.h> int main() { int rd, rs, rt; int result; rs = 0x12345678; rt = 0x87654321; result = 0x456709AB; __asm ("subqh.ph %0, %1, %2\n\t" : "=r"(rd) : "r"(rs), "r"(rt) ); assert(rd == result); return 0; }
null
null
null
null
121,844
56,678
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
56,678
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 "chrome/browser/chromeos/login/screens/user_image_screen.h" #include <string> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/compiler_specific.h" #include "base/location.h" #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "base/threading/thread_task_runner_handle.h" #include "base/timer/timer.h" #include "base/values.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chromeos/accessibility/accessibility_manager.h" #include "chrome/browser/chromeos/camera_presence_notifier.h" #include "chrome/browser/chromeos/login/screen_manager.h" #include "chrome/browser/chromeos/login/screens/base_screen_delegate.h" #include "chrome/browser/chromeos/login/screens/user_image_view.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/policy/profile_policy_connector.h" #include "chrome/browser/policy/profile_policy_connector_factory.h" #include "chrome/browser/profiles/profile.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_namespace.h" #include "components/policy/core/common/policy_service.h" #include "components/policy/policy_constants.h" #include "components/user_manager/user.h" #include "components/user_manager/user_image/user_image.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/webui/web_ui_util.h" #include "ui/gfx/image/image_skia.h" using content::BrowserThread; namespace chromeos { namespace { constexpr const char kContextKeyIsCameraPresent[] = "isCameraPresent"; constexpr const char kContextKeyProfilePictureDataURL[] = "profilePictureDataURL"; constexpr const char kContextKeyIsProfilePictureAvailable[] = "isProfilePictureAvailable"; constexpr const char kContextKeySelectedImageIndex[] = "selectedImageIndex"; constexpr const char kContextKeySelectedImageURL[] = "selectedImageURL"; // Time histogram suffix for profile image download. const char kProfileDownloadReason[] = "OOBE"; // Maximum amount of time to wait for the user image to sync. // The screen is shown iff sync failed or time limit exceeded. const int kSyncTimeoutSeconds = 10; } // namespace // static UserImageScreen* UserImageScreen::Get(ScreenManager* manager) { return static_cast<UserImageScreen*>( manager->GetScreen(OobeScreen::SCREEN_USER_IMAGE_PICKER)); } UserImageScreen::UserImageScreen(BaseScreenDelegate* base_screen_delegate, UserImageView* view) : BaseScreen(base_screen_delegate, OobeScreen::SCREEN_USER_IMAGE_PICKER), view_(view) { if (view_) view_->Bind(this); user_manager::UserManager::Get()->AddObserver(this); GetContextEditor().SetString(kContextKeyProfilePictureDataURL, std::string()); } UserImageScreen::~UserImageScreen() { user_manager::UserManager::Get()->RemoveObserver(this); CameraPresenceNotifier::GetInstance()->RemoveObserver(this); if (view_) view_->Unbind(); } void UserImageScreen::OnScreenReady() { is_screen_ready_ = true; if (!IsWaitingForSync()) HideCurtain(); } void UserImageScreen::OnPhotoTaken(const std::string& raw_data) { DCHECK_CURRENTLY_ON(BrowserThread::UI); user_photo_ = gfx::ImageSkia(); std::vector<unsigned char> photo_data(raw_data.begin(), raw_data.end()); user_photo_data_ = base::RefCountedBytes::TakeVector(&photo_data); ImageDecoder::Cancel(this); ImageDecoder::Start(this, raw_data); } void UserImageScreen::OnImageSelected(const std::string& image_type, const std::string& image_url, bool is_user_selection) { if (is_user_selection) user_has_selected_image_ = true; if (image_type == "default") { int user_image_index = user_manager::User::USER_IMAGE_INVALID; if (image_url.empty() || !default_user_image::IsDefaultImageUrl(image_url, &user_image_index)) { LOG(ERROR) << "Unexpected default image url: " << image_url; return; } selected_image_ = user_image_index; } else if (image_type == "camera" || image_type == "old") { selected_image_ = user_manager::User::USER_IMAGE_EXTERNAL; } else if (image_type == "profile") { selected_image_ = user_manager::User::USER_IMAGE_PROFILE; } else { NOTREACHED() << "Unexpected image type: " << image_type; } } void UserImageScreen::OnImageAccepted() { UserImageManager* image_manager = GetUserImageManager(); int uma_index = 0; switch (selected_image_) { case user_manager::User::USER_IMAGE_EXTERNAL: { // Photo decoding may not have been finished yet. if (user_photo_.isNull()) { accept_photo_after_decoding_ = true; return; } std::unique_ptr<user_manager::UserImage> user_image = std::make_unique<user_manager::UserImage>( user_photo_, user_photo_data_.get(), user_manager::UserImage::FORMAT_PNG); user_image->MarkAsSafe(); image_manager->SaveUserImage(std::move(user_image)); uma_index = default_user_image::kHistogramImageFromCamera; } break; case user_manager::User::USER_IMAGE_PROFILE: image_manager->SaveUserImageFromProfileImage(); uma_index = default_user_image::kHistogramImageFromProfile; break; default: DCHECK(default_user_image::IsValidIndex(selected_image_)); image_manager->SaveUserDefaultImageIndex(selected_image_); uma_index = default_user_image::GetDefaultImageHistogramValue(selected_image_); break; } if (user_has_selected_image_) { UMA_HISTOGRAM_EXACT_LINEAR("UserImage.FirstTimeChoice", uma_index, default_user_image::kHistogramImagesCount); } ExitScreen(); } void UserImageScreen::OnViewDestroyed(UserImageView* view) { if (view_ == view) view_ = nullptr; } void UserImageScreen::Show() { if (!view_) return; DCHECK(!policy_registrar_); if (Profile* profile = ProfileHelper::Get()->GetProfileByUser(GetUser())) { policy::PolicyService* policy_service = policy::ProfilePolicyConnectorFactory::GetForBrowserContext(profile) ->policy_service(); if (policy_service ->GetPolicies(policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string())) .Get(policy::key::kUserAvatarImage)) { // If the user image is managed by policy, skip the screen because the // user is not allowed to override a policy-set image. ExitScreen(); return; } // Listen for policy changes. If at any point, the user image becomes // managed by policy, the screen will close. policy_registrar_.reset(new policy::PolicyChangeRegistrar( policy_service, policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string()))); policy_registrar_->Observe( policy::key::kUserAvatarImage, base::Bind(&UserImageScreen::OnUserImagePolicyChanged, base::Unretained(this))); } else { NOTREACHED(); } // If we have a synced image then we will exit this screen, so do not check // for a synced image if we are force showing the screen for testing. if (!ForceShowOobeScreen(OobeScreen::SCREEN_USER_IMAGE_PICKER) && GetUser()->CanSyncImage()) { if (UserImageSyncObserver* sync_observer = GetSyncObserver()) { sync_waiting_start_time_ = base::Time::Now(); // We have synced image already. if (sync_observer->is_synced()) { ReportSyncResult(SyncResult::SUCCEEDED); ExitScreen(); return; } sync_observer->AddObserver(this); sync_timer_.reset(new base::Timer( FROM_HERE, base::TimeDelta::FromSeconds(kSyncTimeoutSeconds), base::Bind(&UserImageScreen::OnSyncTimeout, base::Unretained(this)), false)); sync_timer_->Reset(); } } CameraPresenceNotifier::GetInstance()->AddObserver(this); view_->Show(); selected_image_ = GetUser()->image_index(); GetContextEditor().SetInteger(kContextKeySelectedImageIndex, selected_image_); GetContextEditor().SetString( kContextKeySelectedImageURL, default_user_image::GetDefaultImageUrl(selected_image_)); const user_manager::User* user = GetUser(); // Active Directory accounts do not use a profile image so skip the download // and inform the UI that no profile image exists. if (user && user->IsActiveDirectoryUser()) { GetContextEditor().SetBoolean(kContextKeyIsProfilePictureAvailable, false); } else { // Start fetching the profile image. GetUserImageManager()->DownloadProfileImage(kProfileDownloadReason); } } void UserImageScreen::Hide() { CameraPresenceNotifier::GetInstance()->RemoveObserver(this); user_manager::UserManager::Get()->RemoveObserver(this); policy_registrar_.reset(); sync_timer_.reset(); if (UserImageSyncObserver* sync_observer = GetSyncObserver()) sync_observer->RemoveObserver(this); if (view_) view_->Hide(); } void UserImageScreen::OnCameraPresenceCheckDone(bool is_camera_present) { GetContextEditor().SetBoolean(kContextKeyIsCameraPresent, is_camera_present); } void UserImageScreen::OnImageDecoded(const SkBitmap& decoded_image) { user_photo_ = gfx::ImageSkia::CreateFrom1xBitmap(decoded_image); if (accept_photo_after_decoding_) OnImageAccepted(); } void UserImageScreen::OnDecodeImageFailed() { NOTREACHED() << "Failed to decode PNG image from WebUI"; } void UserImageScreen::OnUserImageChanged(const user_manager::User& user) { GetContextEditor().SetInteger(kContextKeySelectedImageIndex, GetUser()->image_index()); GetContextEditor().SetString( kContextKeySelectedImageURL, default_user_image::GetDefaultImageUrl(GetUser()->image_index())); } void UserImageScreen::OnUserProfileImageUpdateFailed( const user_manager::User& user) { // User has a default profile image or fetching profile image has failed. GetContextEditor().SetString(kContextKeyProfilePictureDataURL, std::string()); } void UserImageScreen::OnUserProfileImageUpdated( const user_manager::User& user, const gfx::ImageSkia& profile_image) { // We've got a new profile image. GetContextEditor().SetString( kContextKeyProfilePictureDataURL, webui::GetBitmapDataUrl(*profile_image.bitmap())); } void UserImageScreen::OnInitialSync(bool local_image_updated) { DCHECK(sync_timer_); ReportSyncResult(SyncResult::SUCCEEDED); if (!local_image_updated) { sync_timer_.reset(); GetSyncObserver()->RemoveObserver(this); if (is_screen_ready_) HideCurtain(); return; } ExitScreen(); } void UserImageScreen::OnSyncTimeout() { ReportSyncResult(SyncResult::TIMED_OUT); sync_timer_.reset(); GetSyncObserver()->RemoveObserver(this); if (is_screen_ready_) HideCurtain(); } bool UserImageScreen::IsWaitingForSync() const { return sync_timer_.get() && sync_timer_->IsRunning(); } void UserImageScreen::OnUserImagePolicyChanged(const base::Value* previous, const base::Value* current) { if (current) { base::ThreadTaskRunnerHandle::Get()->DeleteSoon( FROM_HERE, policy_registrar_.release()); ExitScreen(); } } const user_manager::User* UserImageScreen::GetUser() { return user_manager::UserManager::Get()->GetActiveUser(); } UserImageManager* UserImageScreen::GetUserImageManager() { return ChromeUserManager::Get()->GetUserImageManager( GetUser()->GetAccountId()); } UserImageSyncObserver* UserImageScreen::GetSyncObserver() { return GetUserImageManager()->GetSyncObserver(); } void UserImageScreen::HideCurtain() { // Skip user image selection for ephemeral users. if (user_manager::UserManager::Get()->IsUserNonCryptohomeDataEphemeral( GetUser()->GetAccountId())) { ExitScreen(); } if (view_) view_->HideCurtain(); } void UserImageScreen::ExitScreen() { policy_registrar_.reset(); sync_timer_.reset(); if (UserImageSyncObserver* sync_observer = GetSyncObserver()) sync_observer->RemoveObserver(this); Finish(ScreenExitCode::USER_IMAGE_SELECTED); } void UserImageScreen::ReportSyncResult(SyncResult timed_out) const { base::TimeDelta duration = base::Time::Now() - sync_waiting_start_time_; UMA_HISTOGRAM_TIMES("Login.NewUserPriorityPrefsSyncTime", duration); UMA_HISTOGRAM_ENUMERATION("Login.NewUserPriorityPrefsSyncResult", static_cast<int>(timed_out), static_cast<int>(SyncResult::COUNT)); } } // namespace chromeos
null
null
null
null
53,541
24,207
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
24,207
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 <stddef.h> #include <stdint.h> #include <memory> #include <set> #include "base/command_line.h" #include "base/json/json_reader.h" #include "base/location.h" #include "base/memory/ref_counted.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "build/build_config.h" #include "content/browser/child_process_security_policy_impl.h" #include "content/browser/frame_host/navigation_handle_impl.h" #include "content/browser/frame_host/render_frame_host_impl.h" #include "content/browser/frame_host/render_frame_proxy_host.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/site_instance_impl.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/browser/webui/web_ui_controller_factory_registry.h" #include "content/browser/webui/web_ui_impl.h" #include "content/common/content_constants_internal.h" #include "content/common/input_messages.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/resource_dispatcher_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_ui_message_handler.h" #include "content/public/common/bindings_policy.h" #include "content/public/common/browser_side_navigation_policy.h" #include "content/public/common/content_switches.h" #include "content/public/common/page_state.h" #include "content/public/common/url_constants.h" #include "content/public/common/web_preferences.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" #include "content/public/test/test_frame_navigation_observer.h" #include "content/public/test/test_navigation_observer.h" #include "content/public/test/test_utils.h" #include "content/shell/browser/shell.h" #include "content/test/content_browser_test_utils_internal.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/controllable_http_response.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/request_handler_util.h" #include "testing/gmock/include/gmock/gmock-matchers.h" using base::ASCIIToUTF16; namespace content { namespace { const char kOpenUrlViaClickTargetFunc[] = "(function(url) {\n" " var lnk = document.createElement(\"a\");\n" " lnk.href = url;\n" " lnk.target = \"_blank\";\n" " document.body.appendChild(lnk);\n" " lnk.click();\n" "})"; // Adds a link with given url and target=_blank, and clicks on it. void OpenUrlViaClickTarget(const ToRenderFrameHost& adapter, const GURL& url) { EXPECT_TRUE(ExecuteScript(adapter, std::string(kOpenUrlViaClickTargetFunc) + "(\"" + url.spec() + "\");")); } class TestWebUIMessageHandler : public WebUIMessageHandler { public: using WebUIMessageHandler::AllowJavascript; using WebUIMessageHandler::IsJavascriptAllowed; protected: void RegisterMessages() override {} }; // This class implements waiting for RenderFrameHost destruction. It relies on // the fact that RenderFrameDeleted event is fired when RenderFrameHost is // destroyed. // Note: RenderFrameDeleted is also fired when the process associated with the // RenderFrameHost crashes, so this cannot be used in cases where process dying // is expected. class RenderFrameHostDestructionObserver : public WebContentsObserver { public: explicit RenderFrameHostDestructionObserver(RenderFrameHost* rfh) : WebContentsObserver(WebContents::FromRenderFrameHost(rfh)), message_loop_runner_(new MessageLoopRunner), deleted_(false), render_frame_host_(rfh) {} ~RenderFrameHostDestructionObserver() override {} bool deleted() const { return deleted_; } void Wait() { if (deleted_) return; message_loop_runner_->Run(); } // WebContentsObserver implementation: void RenderFrameDeleted(RenderFrameHost* rfh) override { if (rfh == render_frame_host_) { CHECK(!deleted_); deleted_ = true; } if (deleted_ && message_loop_runner_->loop_running()) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, message_loop_runner_->QuitClosure()); } } private: scoped_refptr<MessageLoopRunner> message_loop_runner_; bool deleted_; RenderFrameHost* render_frame_host_; }; } // anonymous namespace class RenderFrameHostManagerTest : public ContentBrowserTest { public: RenderFrameHostManagerTest() : foo_com_("foo.com") { replace_host_.SetHostStr(foo_com_); } static void GetFilePathWithHostAndPortReplacement( const std::string& original_file_path, const net::HostPortPair& host_port_pair, std::string* replacement_path) { base::StringPairs replacement_text; replacement_text.push_back( make_pair("REPLACE_WITH_HOST_AND_PORT", host_port_pair.ToString())); net::test_server::GetFilePathWithReplacements( original_file_path, replacement_text, replacement_path); } void SetUpCommandLine(base::CommandLine* command_line) override { const char kBlinkPageLifecycleFeature[] = "PageLifecycle"; command_line->AppendSwitchASCII(switches::kEnableBlinkFeatures, kBlinkPageLifecycleFeature); } void SetUpOnMainThread() override { // Support multiple sites on the test server. host_resolver()->AddRule("*", "127.0.0.1"); } void StartServer() { ASSERT_TRUE(embedded_test_server()->Start()); foo_host_port_ = embedded_test_server()->host_port_pair(); foo_host_port_.set_host(foo_com_); } void StartEmbeddedServer() { SetupCrossSiteRedirector(embedded_test_server()); ASSERT_TRUE(embedded_test_server()->Start()); } // Returns a URL on foo.com with the given path. GURL GetCrossSiteURL(const std::string& path) { GURL cross_site_url(embedded_test_server()->GetURL(path)); return cross_site_url.ReplaceComponents(replace_host_); } void NavigateToPageWithLinks(Shell* shell) { EXPECT_TRUE(NavigateToURL( shell, embedded_test_server()->GetURL("/click-noreferrer-links.html"))); // Rewrite selected links on the page to be actual cross-site (bar.com) // URLs. This does not use the /cross-site/ redirector, since that creates // links that initially look same-site. std::string script = "setOriginForLinks('http://bar.com:" + embedded_test_server()->base_url().port() + "/');"; EXPECT_TRUE(ExecuteScript(shell, script)); } protected: std::string foo_com_; GURL::Replacements replace_host_; net::HostPortPair foo_host_port_; }; // Web pages should not have script access to the swapped out page. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, NoScriptAccessAfterSwapOut) { StartEmbeddedServer(); // Load a page with links that open in a new window. NavigateToPageWithLinks(shell()); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance.get() != nullptr); // Open a same-site link in a new window. ShellAddedObserver new_shell_observer; bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell(), "window.domAutomationController.send(clickSameSiteTargetedLink());", &success)); EXPECT_TRUE(success); Shell* new_shell = new_shell_observer.GetShell(); // Wait for the navigation in the new window to finish, if it hasn't. WaitForLoadStop(new_shell->web_contents()); EXPECT_EQ("/navigate_opener.html", new_shell->web_contents()->GetLastCommittedURL().path()); // Should have the same SiteInstance. EXPECT_EQ(orig_site_instance, new_shell->web_contents()->GetSiteInstance()); // We should have access to the opened window's location. success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell(), "window.domAutomationController.send(testScriptAccessToWindow());", &success)); EXPECT_TRUE(success); // Now navigate the new window to a different site. EXPECT_TRUE(NavigateToURLInSameBrowsingInstance( new_shell, embedded_test_server()->GetURL("foo.com", "/title1.html"))); scoped_refptr<SiteInstance> new_site_instance( new_shell->web_contents()->GetSiteInstance()); EXPECT_NE(orig_site_instance, new_site_instance); // We should no longer have script access to the opened window's location. success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell(), "window.domAutomationController.send(testScriptAccessToWindow());", &success)); EXPECT_FALSE(success); // We now navigate the window to an about:blank page. success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell(), "window.domAutomationController.send(clickBlankTargetedLink());", &success)); EXPECT_TRUE(success); // Wait for the navigation in the new window to finish. WaitForLoadStop(new_shell->web_contents()); GURL blank_url(url::kAboutBlankURL); EXPECT_EQ(blank_url, new_shell->web_contents()->GetLastCommittedURL()); EXPECT_EQ(orig_site_instance, new_shell->web_contents()->GetSiteInstance()); // We should have access to the opened window's location. success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell(), "window.domAutomationController.send(testScriptAccessToWindow());", &success)); EXPECT_TRUE(success); } // Test for crbug.com/24447. Following a cross-site link with rel=noreferrer // and target=_blank should create a new SiteInstance. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, SwapProcessWithRelNoreferrerAndTargetBlank) { StartEmbeddedServer(); NavigateToPageWithLinks(shell()); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance.get() != nullptr); // Test clicking a rel=noreferrer + target=blank link. ShellAddedObserver new_shell_observer; bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell(), "window.domAutomationController.send(clickNoRefTargetBlankLink());", &success)); EXPECT_TRUE(success); // Wait for the window to open. Shell* new_shell = new_shell_observer.GetShell(); EXPECT_EQ("/title2.html", new_shell->web_contents()->GetVisibleURL().path()); // Check that `window.opener` is not set. success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( new_shell, "window.domAutomationController.send(window.opener == null);", &success)); EXPECT_TRUE(success); // Wait for the cross-site transition in the new tab to finish. WaitForLoadStop(new_shell->web_contents()); // Should have a new SiteInstance. scoped_refptr<SiteInstance> noref_blank_site_instance( new_shell->web_contents()->GetSiteInstance()); EXPECT_NE(orig_site_instance, noref_blank_site_instance); } // Same as above, but for 'noopener' IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, SwapProcessWithRelNoopenerAndTargetBlank) { StartEmbeddedServer(); NavigateToPageWithLinks(shell()); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance.get() != nullptr); // Test clicking a rel=noreferrer + target=blank link. ShellAddedObserver new_shell_observer; bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell(), "window.domAutomationController.send(clickNoOpenerTargetBlankLink());", &success)); EXPECT_TRUE(success); // Wait for the window to open. Shell* new_shell = new_shell_observer.GetShell(); EXPECT_EQ("/title2.html", new_shell->web_contents()->GetVisibleURL().path()); // Check that `window.opener` is not set. success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( new_shell, "window.domAutomationController.send(window.opener == null);", &success)); EXPECT_TRUE(success); // Wait for the cross-site transition in the new tab to finish. WaitForLoadStop(new_shell->web_contents()); // Check that the referrer is set correctly. std::string expected_referrer = embedded_test_server()->GetURL("/click-noreferrer-links.html").spec(); success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( new_shell, "window.domAutomationController.send(document.referrer == '" + expected_referrer + "');", &success)); EXPECT_TRUE(success); // Should have a new SiteInstance. scoped_refptr<SiteInstance> noopener_blank_site_instance( new_shell->web_contents()->GetSiteInstance()); EXPECT_NE(orig_site_instance, noopener_blank_site_instance); } // 'noopener' also works from 'window.open' IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, SwapProcessWithWindowOpenAndNoopener) { StartEmbeddedServer(); NavigateToPageWithLinks(shell()); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance.get()); // Test opening a window with the 'noopener' feature. ShellAddedObserver new_shell_observer; bool hasWindowReference = true; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell(), "window.domAutomationController.send(" " openWindowWithTargetAndFeatures('/title2.html', '', 'noopener')" ");", &hasWindowReference)); // We should not get a reference to the opened window. EXPECT_FALSE(hasWindowReference); // Wait for the window to open. Shell* new_shell = new_shell_observer.GetShell(); // Wait for the cross-site transition in the new tab to finish. WaitForLoadStop(new_shell->web_contents()); EXPECT_EQ("/title2.html", new_shell->web_contents()->GetLastCommittedURL().path()); // Check that `window.opener` is not set. bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( new_shell, "window.domAutomationController.send(window.opener == null);", &success)); EXPECT_TRUE(success); // Check that the referrer is set correctly. std::string expected_referrer = embedded_test_server()->GetURL("/click-noreferrer-links.html").spec(); success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( new_shell, "window.domAutomationController.send(document.referrer == '" + expected_referrer + "');", &success)); EXPECT_TRUE(success); // Should have a new SiteInstance. scoped_refptr<SiteInstance> noopener_blank_site_instance( new_shell->web_contents()->GetSiteInstance()); EXPECT_NE(orig_site_instance, noopener_blank_site_instance); } // As of crbug.com/69267, we create a new BrowsingInstance (and SiteInstance) // for rel=noreferrer links in new windows, even to same site pages and named // targets. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, SwapProcessWithSameSiteRelNoreferrer) { StartEmbeddedServer(); // Load a page with links that open in a new window. NavigateToPageWithLinks(shell()); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance.get() != nullptr); // Test clicking a same-site rel=noreferrer + target=foo link. ShellAddedObserver new_shell_observer; bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell(), "window.domAutomationController.send(clickSameSiteNoRefTargetedLink());", &success)); EXPECT_TRUE(success); // Wait for the window to open. Shell* new_shell = new_shell_observer.GetShell(); // Opens in new window. EXPECT_EQ("/title2.html", new_shell->web_contents()->GetVisibleURL().path()); // Check that `window.opener` is not set. success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( new_shell, "window.domAutomationController.send(window.opener == null);", &success)); EXPECT_TRUE(success); // Wait for the cross-site transition in the new tab to finish. WaitForLoadStop(new_shell->web_contents()); // Should have a new SiteInstance (in a new BrowsingInstance). scoped_refptr<SiteInstance> noref_blank_site_instance( new_shell->web_contents()->GetSiteInstance()); EXPECT_NE(orig_site_instance, noref_blank_site_instance); } // Same as above, but for 'noopener' IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, SwapProcessWithSameSiteRelNoopener) { StartEmbeddedServer(); // Load a page with links that open in a new window. NavigateToPageWithLinks(shell()); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance.get() != nullptr); // Test clicking a same-site rel=noopener + target=foo link. ShellAddedObserver new_shell_observer; bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool(shell(), "window.domAutomationController.send(" "clickSameSiteNoOpenerTargetedLink())" ";", &success)); EXPECT_TRUE(success); // Wait for the window to open. Shell* new_shell = new_shell_observer.GetShell(); // Opens in new window. EXPECT_EQ("/title2.html", new_shell->web_contents()->GetVisibleURL().path()); // Check that `window.opener` is not set. success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( new_shell, "window.domAutomationController.send(window.opener == null);", &success)); EXPECT_TRUE(success); // Wait for the cross-site transition in the new tab to finish. WaitForLoadStop(new_shell->web_contents()); // Should have a new SiteInstance (in a new BrowsingInstance). scoped_refptr<SiteInstance> noref_blank_site_instance( new_shell->web_contents()->GetSiteInstance()); EXPECT_NE(orig_site_instance, noref_blank_site_instance); } // Test for crbug.com/24447. Following a cross-site link with just // target=_blank should not create a new SiteInstance, unless we // are running in --site-per-process mode. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, DontSwapProcessWithOnlyTargetBlank) { StartEmbeddedServer(); // Load a page with links that open in a new window. NavigateToPageWithLinks(shell()); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance.get() != nullptr); // Test clicking a target=blank link. ShellAddedObserver new_shell_observer; bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell(), "window.domAutomationController.send(clickTargetBlankLink());", &success)); EXPECT_TRUE(success); // Wait for the window to open. Shell* new_shell = new_shell_observer.GetShell(); // Wait for the cross-site transition in the new tab to finish. EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents())); EXPECT_EQ("/title2.html", new_shell->web_contents()->GetLastCommittedURL().path()); // Should have the same SiteInstance unless we're in site-per-process mode. scoped_refptr<SiteInstance> blank_site_instance( new_shell->web_contents()->GetSiteInstance()); if (AreAllSitesIsolatedForTesting()) EXPECT_NE(orig_site_instance, blank_site_instance); else EXPECT_EQ(orig_site_instance, blank_site_instance); } // Test for crbug.com/24447. Following a cross-site link with rel=noreferrer // and no target=_blank should not create a new SiteInstance. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, DontSwapProcessWithOnlyRelNoreferrer) { StartEmbeddedServer(); // Load a page with links that open in a new window. NavigateToPageWithLinks(shell()); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance.get() != nullptr); // Test clicking a rel=noreferrer link. bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell(), "window.domAutomationController.send(clickNoRefLink());", &success)); EXPECT_TRUE(success); // Wait for the cross-site transition in the current tab to finish. WaitForLoadStop(shell()->web_contents()); // Opens in same window. EXPECT_EQ(1u, Shell::windows().size()); EXPECT_EQ("/title2.html", shell()->web_contents()->GetLastCommittedURL().path()); // Should have the same SiteInstance unless we're in site-per-process mode. scoped_refptr<SiteInstance> noref_site_instance( shell()->web_contents()->GetSiteInstance()); if (AreAllSitesIsolatedForTesting()) EXPECT_NE(orig_site_instance, noref_site_instance); else EXPECT_EQ(orig_site_instance, noref_site_instance); } // Same as above, but for 'noopener' IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, DontSwapProcessWithOnlyRelNoOpener) { StartEmbeddedServer(); // Load a page with links that open in a new window. NavigateToPageWithLinks(shell()); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance.get() != nullptr); // Test clicking a rel=noreferrer link. bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell(), "window.domAutomationController.send(clickNoRefLink());", &success)); EXPECT_TRUE(success); // Wait for the cross-site transition in the current tab to finish. WaitForLoadStop(shell()->web_contents()); // Opens in same window. EXPECT_EQ(1u, Shell::windows().size()); EXPECT_EQ("/title2.html", shell()->web_contents()->GetLastCommittedURL().path()); // Should have the same SiteInstance unless we're in site-per-process mode. scoped_refptr<SiteInstance> noref_site_instance( shell()->web_contents()->GetSiteInstance()); if (AreAllSitesIsolatedForTesting()) EXPECT_NE(orig_site_instance, noref_site_instance); else EXPECT_EQ(orig_site_instance, noref_site_instance); } // Test for crbug.com/116192. Targeted links should still work after the // named target window has swapped processes. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, AllowTargetedNavigationsAfterSwap) { StartEmbeddedServer(); // Load a page with links that open in a new window. NavigateToPageWithLinks(shell()); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance.get() != nullptr); // Test clicking a target=foo link. ShellAddedObserver new_shell_observer; bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell(), "window.domAutomationController.send(clickSameSiteTargetedLink());", &success)); EXPECT_TRUE(success); Shell* new_shell = new_shell_observer.GetShell(); // Wait for the navigation in the new tab to finish, if it hasn't. WaitForLoadStop(new_shell->web_contents()); EXPECT_EQ("/navigate_opener.html", new_shell->web_contents()->GetLastCommittedURL().path()); // Should have the same SiteInstance. scoped_refptr<SiteInstance> blank_site_instance( new_shell->web_contents()->GetSiteInstance()); EXPECT_EQ(orig_site_instance, blank_site_instance); // Now navigate the new tab to a different site. GURL cross_site_url( embedded_test_server()->GetURL("foo.com", "/title1.html")); EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, cross_site_url)); scoped_refptr<SiteInstance> new_site_instance( new_shell->web_contents()->GetSiteInstance()); EXPECT_NE(orig_site_instance, new_site_instance); // Clicking the original link in the first tab should cause us to swap back. TestNavigationObserver navigation_observer(new_shell->web_contents()); EXPECT_TRUE(ExecuteScriptAndExtractBool( shell(), "window.domAutomationController.send(clickSameSiteTargetedLink());", &success)); EXPECT_TRUE(success); navigation_observer.Wait(); // Should have swapped back and shown the new window again. scoped_refptr<SiteInstance> revisit_site_instance( new_shell->web_contents()->GetSiteInstance()); EXPECT_EQ(orig_site_instance, revisit_site_instance); // If it navigates away to another process, the original window should // still be able to close it (using a cross-process close message). EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, cross_site_url)); EXPECT_EQ(new_site_instance.get(), new_shell->web_contents()->GetSiteInstance()); WebContentsDestroyedWatcher close_watcher(new_shell->web_contents()); EXPECT_TRUE(ExecuteScriptAndExtractBool( shell(), "window.domAutomationController.send(testCloseWindow());", &success)); EXPECT_TRUE(success); close_watcher.Wait(); } // Test that setting the opener to null in a window affects cross-process // navigations, including those to existing entries. http://crbug.com/156669. // This test crashes under ThreadSanitizer, http://crbug.com/356758. #if defined(THREAD_SANITIZER) #define MAYBE_DisownOpener DISABLED_DisownOpener #else #define MAYBE_DisownOpener DisownOpener #endif IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, MAYBE_DisownOpener) { StartEmbeddedServer(); // Load a page with links that open in a new window. NavigateToPageWithLinks(shell()); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance.get() != nullptr); // Test clicking a target=_blank link. ShellAddedObserver new_shell_observer; bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell(), "window.domAutomationController.send(clickSameSiteTargetBlankLink());", &success)); EXPECT_TRUE(success); Shell* new_shell = new_shell_observer.GetShell(); EXPECT_TRUE(new_shell->web_contents()->HasOpener()); // Wait for the navigation in the new tab to finish, if it hasn't. WaitForLoadStop(new_shell->web_contents()); EXPECT_EQ("/title2.html", new_shell->web_contents()->GetLastCommittedURL().path()); // Should have the same SiteInstance. scoped_refptr<SiteInstance> blank_site_instance( new_shell->web_contents()->GetSiteInstance()); EXPECT_EQ(orig_site_instance, blank_site_instance); // Now navigate the new tab to a different site. GURL cross_site_url( embedded_test_server()->GetURL("foo.com", "/title1.html")); EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, cross_site_url)); scoped_refptr<SiteInstance> new_site_instance( new_shell->web_contents()->GetSiteInstance()); EXPECT_NE(orig_site_instance, new_site_instance); EXPECT_TRUE(new_shell->web_contents()->HasOpener()); // Now disown the opener. EXPECT_TRUE(ExecuteScript(new_shell, "window.opener = null;")); EXPECT_FALSE(new_shell->web_contents()->HasOpener()); // Go back and ensure the opener is still null. { TestNavigationObserver back_nav_load_observer(new_shell->web_contents()); new_shell->web_contents()->GetController().GoBack(); back_nav_load_observer.Wait(); } success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( new_shell, "window.domAutomationController.send(window.opener == null);", &success)); EXPECT_TRUE(success); EXPECT_FALSE(new_shell->web_contents()->HasOpener()); // Now navigate forward again (creating a new process) and check opener. NavigateToURL(new_shell, cross_site_url); success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( new_shell, "window.domAutomationController.send(window.opener == null);", &success)); EXPECT_TRUE(success); EXPECT_FALSE(new_shell->web_contents()->HasOpener()); } // Test that subframes can disown their openers. http://crbug.com/225528. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, DisownSubframeOpener) { const GURL frame_url("data:text/html,<iframe name=\"foo\"></iframe>"); NavigateToURL(shell(), frame_url); // Give the frame an opener using window.open. EXPECT_TRUE(ExecuteScript(shell(), "window.open('about:blank','foo');")); // Check that the browser process updates the subframe's opener. FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root(); EXPECT_EQ(root, root->child_at(0)->opener()); EXPECT_EQ(nullptr, root->child_at(0)->original_opener()); // Now disown the frame's opener. Shouldn't crash. EXPECT_TRUE(ExecuteScript(shell(), "window.frames[0].opener = null;")); // Check that the subframe's opener in the browser process is disowned. EXPECT_EQ(nullptr, root->child_at(0)->opener()); EXPECT_EQ(nullptr, root->child_at(0)->original_opener()); } // Check that window.name is preserved for top frames when they navigate // cross-process. See https://crbug.com/504164. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, PreserveTopFrameWindowNameOnCrossProcessNavigations) { StartEmbeddedServer(); GURL main_url(embedded_test_server()->GetURL("/title1.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance.get() != nullptr); // Open a popup using window.open with a 'foo' window.name. Shell* new_shell = OpenPopup(shell(), GURL(url::kAboutBlankURL), "foo"); EXPECT_TRUE(new_shell); // The window.name for the new popup should be "foo". std::string name; EXPECT_TRUE(ExecuteScriptAndExtractString( new_shell, "window.domAutomationController.send(window.name);", &name)); EXPECT_EQ("foo", name); // Now navigate the new tab to a different site. GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title2.html")); EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, foo_url)); scoped_refptr<SiteInstance> new_site_instance( new_shell->web_contents()->GetSiteInstance()); EXPECT_NE(orig_site_instance, new_site_instance); // window.name should still be "foo". name = ""; EXPECT_TRUE(ExecuteScriptAndExtractString( new_shell, "window.domAutomationController.send(window.name);", &name)); EXPECT_EQ("foo", name); // Open another popup from the 'foo' popup and navigate it cross-site. Shell* new_shell2 = OpenPopup(new_shell, GURL(url::kAboutBlankURL), "bar"); EXPECT_TRUE(new_shell2); GURL bar_url(embedded_test_server()->GetURL("bar.com", "/title3.html")); EXPECT_TRUE(NavigateToURLFromRenderer(new_shell2, bar_url)); // Check that the new popup's window.opener has name "foo", which verifies // that new swapped-out RenderViews also propagate window.name. This has to // be done via window.open, since window.name isn't readable cross-origin. bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( new_shell2, "window.domAutomationController.send(" " window.opener === window.open('','foo'));", &success)); EXPECT_TRUE(success); } // Test for crbug.com/99202. PostMessage calls should still work after // navigating the source and target windows to different sites. // Specifically: // 1) Create 3 windows (opener, "foo", and _blank) and send "foo" cross-process. // 2) Fail to post a message from "foo" to opener with the wrong target origin. // 3) Post a message from "foo" to opener, which replies back to "foo". // 4) Post a message from _blank to "foo". // 5) Post a message from "foo" to a subframe of opener, which replies back. // 6) Post a message from _blank to a subframe of "foo". IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, SupportCrossProcessPostMessage) { StartEmbeddedServer(); // Load a page with links that open in a new window. NavigateToPageWithLinks(shell()); // Get the original SiteInstance and RVHM for later comparison. WebContents* opener_contents = shell()->web_contents(); scoped_refptr<SiteInstance> orig_site_instance( opener_contents->GetSiteInstance()); EXPECT_TRUE(orig_site_instance.get() != nullptr); RenderFrameHostManager* opener_manager = static_cast<WebContentsImpl*>( opener_contents)->GetRenderManagerForTesting(); // 1) Open two more windows, one named. These initially have openers but no // reference to each other. We will later post a message between them. // First, a named target=foo window. ShellAddedObserver new_shell_observer; bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( opener_contents, "window.domAutomationController.send(clickSameSiteTargetedLink());", &success)); EXPECT_TRUE(success); Shell* new_shell = new_shell_observer.GetShell(); // Wait for the navigation in the new window to finish, if it hasn't, then // send it to post_message.html on a different site. WebContents* foo_contents = new_shell->web_contents(); WaitForLoadStop(foo_contents); EXPECT_EQ("/navigate_opener.html", foo_contents->GetLastCommittedURL().path()); EXPECT_TRUE(NavigateToURLInSameBrowsingInstance( new_shell, embedded_test_server()->GetURL("foo.com", "/post_message.html"))); scoped_refptr<SiteInstance> foo_site_instance( foo_contents->GetSiteInstance()); EXPECT_NE(orig_site_instance, foo_site_instance); // Second, a target=_blank window. ShellAddedObserver new_shell_observer2; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell(), "window.domAutomationController.send(clickSameSiteTargetBlankLink());", &success)); EXPECT_TRUE(success); // Wait for the navigation in the new window to finish, if it hasn't, then // send it to post_message.html on the original site. Shell* new_shell2 = new_shell_observer2.GetShell(); WebContents* new_contents = new_shell2->web_contents(); WaitForLoadStop(new_contents); EXPECT_EQ("/title2.html", new_contents->GetLastCommittedURL().path()); EXPECT_TRUE(NavigateToURLInSameBrowsingInstance( new_shell2, embedded_test_server()->GetURL("/post_message.html"))); EXPECT_EQ(orig_site_instance.get(), new_contents->GetSiteInstance()); RenderFrameHostManager* new_manager = static_cast<WebContentsImpl*>(new_contents)->GetRenderManagerForTesting(); // We now have three windows. The opener should have a swapped out RVH // for the new SiteInstance, but the _blank window should not. EXPECT_EQ(3u, Shell::windows().size()); EXPECT_TRUE( opener_manager->GetSwappedOutRenderViewHost(foo_site_instance.get())); EXPECT_FALSE( new_manager->GetSwappedOutRenderViewHost(foo_site_instance.get())); // 2) Fail to post a message from the foo window to the opener if the target // origin is wrong. We won't see an error, but we can check for the right // number of received messages below. EXPECT_TRUE(ExecuteScriptAndExtractBool( foo_contents, "window.domAutomationController.send(postToOpener('msg'," " 'http://google.com'));", &success)); EXPECT_TRUE(success); ASSERT_FALSE( opener_manager->GetSwappedOutRenderViewHost(orig_site_instance.get())); // 3) Post a message from the foo window to the opener. The opener will // reply, causing the foo window to update its own title. base::string16 expected_title = ASCIIToUTF16("msg"); TitleWatcher title_watcher(foo_contents, expected_title); EXPECT_TRUE(ExecuteScriptAndExtractBool( foo_contents, "window.domAutomationController.send(postToOpener('msg','*'));", &success)); EXPECT_TRUE(success); ASSERT_FALSE( opener_manager->GetSwappedOutRenderViewHost(orig_site_instance.get())); ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle()); // We should have received only 1 message in the opener and "foo" tabs, // and updated the title. int opener_received_messages = 0; EXPECT_TRUE(ExecuteScriptAndExtractInt( opener_contents, "window.domAutomationController.send(window.receivedMessages);", &opener_received_messages)); int foo_received_messages = 0; EXPECT_TRUE(ExecuteScriptAndExtractInt( foo_contents, "window.domAutomationController.send(window.receivedMessages);", &foo_received_messages)); EXPECT_EQ(1, foo_received_messages); EXPECT_EQ(1, opener_received_messages); EXPECT_EQ(ASCIIToUTF16("msg"), foo_contents->GetTitle()); // 4) Now post a message from the _blank window to the foo window. The // foo window will update its title and will not reply. expected_title = ASCIIToUTF16("msg2"); TitleWatcher title_watcher2(foo_contents, expected_title); EXPECT_TRUE(ExecuteScriptAndExtractBool( new_contents, "window.domAutomationController.send(postToFoo('msg2'));", &success)); EXPECT_TRUE(success); ASSERT_EQ(expected_title, title_watcher2.WaitAndGetTitle()); // This postMessage should have created a swapped out RVH for the new // SiteInstance in the target=_blank window. EXPECT_TRUE( new_manager->GetSwappedOutRenderViewHost(foo_site_instance.get())); // TODO(nasko): Test subframe targeting of postMessage once // http://crbug.com/153701 is fixed. } // Test for crbug.com/278336. MessagePorts should work cross-process. Messages // which contain Transferables that need to be forwarded between processes via // RenderFrameProxy::willCheckAndDispatchMessageEvent should work. // Specifically: // 1) Create 2 windows (opener and "foo") and send "foo" cross-process. // 2) Post a message containing a message port from opener to "foo". // 3) Post a message from "foo" back to opener via the passed message port. // The test will be enabled when the feature implementation lands. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, SupportCrossProcessPostMessageWithMessagePort) { StartEmbeddedServer(); // Load a page with links that open in a new window. NavigateToPageWithLinks(shell()); // Get the original SiteInstance and RVHM for later comparison. WebContents* opener_contents = shell()->web_contents(); scoped_refptr<SiteInstance> orig_site_instance( opener_contents->GetSiteInstance()); EXPECT_TRUE(orig_site_instance.get() != nullptr); RenderFrameHostManager* opener_manager = static_cast<WebContentsImpl*>( opener_contents)->GetRenderManagerForTesting(); // 1) Open a named target=foo window. We will later post a message between the // opener and the new window. ShellAddedObserver new_shell_observer; bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( opener_contents, "window.domAutomationController.send(clickSameSiteTargetedLink());", &success)); EXPECT_TRUE(success); Shell* new_shell = new_shell_observer.GetShell(); // Wait for the navigation in the new window to finish, if it hasn't, then // send it to post_message.html on a different site. WebContents* foo_contents = new_shell->web_contents(); WaitForLoadStop(foo_contents); EXPECT_EQ("/navigate_opener.html", foo_contents->GetLastCommittedURL().path()); EXPECT_TRUE(NavigateToURLInSameBrowsingInstance( new_shell, embedded_test_server()->GetURL("foo.com", "/post_message.html"))); scoped_refptr<SiteInstance> foo_site_instance( foo_contents->GetSiteInstance()); EXPECT_NE(orig_site_instance, foo_site_instance); // We now have two windows. The opener should have a swapped out RVH // for the new SiteInstance. EXPECT_EQ(2u, Shell::windows().size()); EXPECT_TRUE( opener_manager->GetSwappedOutRenderViewHost(foo_site_instance.get())); // 2) Post a message containing a MessagePort from opener to the the foo // window. The foo window will reply via the passed port, causing the opener // to update its own title. base::string16 expected_title = ASCIIToUTF16("msg-back-via-port"); TitleWatcher title_observer(opener_contents, expected_title); EXPECT_TRUE(ExecuteScriptAndExtractBool( opener_contents, "window.domAutomationController.send(postWithPortToFoo());", &success)); EXPECT_TRUE(success); ASSERT_FALSE( opener_manager->GetSwappedOutRenderViewHost(orig_site_instance.get())); ASSERT_EQ(expected_title, title_observer.WaitAndGetTitle()); // Check message counts. int opener_received_messages_via_port = 0; EXPECT_TRUE(ExecuteScriptAndExtractInt( opener_contents, "window.domAutomationController.send(window.receivedMessagesViaPort);", &opener_received_messages_via_port)); int foo_received_messages = 0; EXPECT_TRUE(ExecuteScriptAndExtractInt( foo_contents, "window.domAutomationController.send(window.receivedMessages);", &foo_received_messages)); int foo_received_messages_with_port = 0; EXPECT_TRUE(ExecuteScriptAndExtractInt( foo_contents, "window.domAutomationController.send(window.receivedMessagesWithPort);", &foo_received_messages_with_port)); EXPECT_EQ(1, foo_received_messages); EXPECT_EQ(1, foo_received_messages_with_port); EXPECT_EQ(1, opener_received_messages_via_port); EXPECT_EQ(ASCIIToUTF16("msg-with-port"), foo_contents->GetTitle()); EXPECT_EQ(ASCIIToUTF16("msg-back-via-port"), opener_contents->GetTitle()); } // Test for crbug.com/116192. Navigations to a window's opener should // still work after a process swap. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, AllowTargetedNavigationsInOpenerAfterSwap) { StartEmbeddedServer(); // Load a page with links that open in a new window. NavigateToPageWithLinks(shell()); // Get the original tab and SiteInstance for later comparison. WebContents* orig_contents = shell()->web_contents(); scoped_refptr<SiteInstance> orig_site_instance( orig_contents->GetSiteInstance()); EXPECT_TRUE(orig_site_instance.get() != nullptr); // Test clicking a target=foo link. ShellAddedObserver new_shell_observer; bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( orig_contents, "window.domAutomationController.send(clickSameSiteTargetedLink());", &success)); EXPECT_TRUE(success); Shell* new_shell = new_shell_observer.GetShell(); // Wait for the navigation in the new window to finish, if it hasn't. WaitForLoadStop(new_shell->web_contents()); EXPECT_EQ("/navigate_opener.html", new_shell->web_contents()->GetLastCommittedURL().path()); // Should have the same SiteInstance. scoped_refptr<SiteInstance> blank_site_instance( new_shell->web_contents()->GetSiteInstance()); EXPECT_EQ(orig_site_instance, blank_site_instance); // Now navigate the original (opener) tab to a different site. EXPECT_TRUE(NavigateToURLInSameBrowsingInstance( shell(), embedded_test_server()->GetURL("foo.com", "/title1.html"))); scoped_refptr<SiteInstance> new_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_NE(orig_site_instance, new_site_instance); // The opened tab should be able to navigate the opener back to its process. TestNavigationObserver navigation_observer(orig_contents); EXPECT_TRUE(ExecuteScriptAndExtractBool( new_shell, "window.domAutomationController.send(navigateOpener());", &success)); EXPECT_TRUE(success); navigation_observer.Wait(); // Should have swapped back into this process. scoped_refptr<SiteInstance> revisit_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_EQ(orig_site_instance, revisit_site_instance); } // Test that subframes do not crash when sending a postMessage to the top frame // from an unload handler while the top frame is being swapped out as part of // navigating cross-process. https://crbug.com/475651. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, PostMessageFromSubframeUnloadHandler) { StartEmbeddedServer(); GURL frame_url(embedded_test_server()->GetURL("/post_message.html")); GURL main_url("data:text/html,<iframe name='foo' src='" + frame_url.spec() + "'></iframe>"); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_NE(nullptr, orig_site_instance.get()); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root(); ASSERT_EQ(1U, root->child_count()); EXPECT_EQ(frame_url, root->child_at(0)->current_url()); // Register an unload handler that sends a postMessage to the top frame. EXPECT_TRUE(ExecuteScript(root->child_at(0), "registerUnload();")); // Navigate the top frame cross-site. This will cause the top frame to be // swapped out and run unload handlers, and the original renderer process // should then terminate since it's not rendering any other frames. RenderProcessHostWatcher exit_observer( root->current_frame_host()->GetProcess(), RenderProcessHostWatcher::WATCH_FOR_HOST_DESTRUCTION); EXPECT_TRUE(NavigateToURL( shell(), embedded_test_server()->GetURL("foo.com", "/title1.html"))); scoped_refptr<SiteInstance> new_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_NE(orig_site_instance, new_site_instance); // Ensure that the original renderer process exited cleanly without crashing. exit_observer.Wait(); EXPECT_TRUE(exit_observer.did_exit_normally()); } // Test that opening a new window in the same SiteInstance and then navigating // both windows to a different SiteInstance allows the first process to exit. // See http://crbug.com/126333. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, ProcessExitWithSwappedOutViews) { StartEmbeddedServer(); // Load a page with links that open in a new window. NavigateToPageWithLinks(shell()); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance.get() != nullptr); // Test clicking a target=foo link. ShellAddedObserver new_shell_observer; bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell(), "window.domAutomationController.send(clickSameSiteTargetedLink());", &success)); EXPECT_TRUE(success); Shell* new_shell = new_shell_observer.GetShell(); // Wait for the navigation in the new window to finish, if it hasn't. WaitForLoadStop(new_shell->web_contents()); EXPECT_EQ("/navigate_opener.html", new_shell->web_contents()->GetLastCommittedURL().path()); // Should have the same SiteInstance. scoped_refptr<SiteInstance> opened_site_instance( new_shell->web_contents()->GetSiteInstance()); EXPECT_EQ(orig_site_instance, opened_site_instance); // Now navigate the opened window to a different site. GURL cross_site_url( embedded_test_server()->GetURL("foo.com", "/title1.html")); EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, cross_site_url)); scoped_refptr<SiteInstance> new_site_instance( new_shell->web_contents()->GetSiteInstance()); EXPECT_NE(orig_site_instance, new_site_instance); // The original process should still be alive, since it is still used in the // first window. RenderProcessHost* orig_process = orig_site_instance->GetProcess(); EXPECT_TRUE(orig_process->HasConnection()); // Navigate the first window to a different site as well. The original // process should exit, since all of its views are now swapped out. RenderProcessHostWatcher exit_observer( orig_process, RenderProcessHostWatcher::WATCH_FOR_HOST_DESTRUCTION); EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(shell(), cross_site_url)); exit_observer.Wait(); scoped_refptr<SiteInstance> new_site_instance2( shell()->web_contents()->GetSiteInstance()); EXPECT_EQ(new_site_instance, new_site_instance2); } // Test for crbug.com/76666. A cross-site navigation that fails with a 204 // error should not make us ignore future renderer-initiated navigations. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, ClickLinkAfter204Error) { StartServer(); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance.get() != nullptr); // Load a cross-site page that fails with a 204 error. EXPECT_TRUE( NavigateToURLAndExpectNoCommit(shell(), GetCrossSiteURL("/nocontent"))); // We should still be looking at the normal page. Because we started from a // blank new tab, the typed URL will still be visible until the user clears it // manually. The last committed URL will be the previous page. scoped_refptr<SiteInstance> post_nav_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_EQ(orig_site_instance, post_nav_site_instance); EXPECT_EQ("/nocontent", shell()->web_contents()->GetVisibleURL().path()); EXPECT_FALSE( shell()->web_contents()->GetController().GetLastCommittedEntry()); // Renderer-initiated navigations should work. base::string16 expected_title = ASCIIToUTF16("Title Of Awesomeness"); TitleWatcher title_watcher(shell()->web_contents(), expected_title); GURL url = embedded_test_server()->GetURL("/title2.html"); EXPECT_TRUE(ExecuteScript( shell(), base::StringPrintf("location.href = '%s'", url.spec().c_str()))); ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle()); // Opens in same tab. EXPECT_EQ(1u, Shell::windows().size()); EXPECT_EQ("/title2.html", shell()->web_contents()->GetLastCommittedURL().path()); // Should have the same SiteInstance. scoped_refptr<SiteInstance> new_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_EQ(orig_site_instance, new_site_instance); } // A collection of tests to prevent URL spoofs when showing pending URLs above // initial empty documents, ensuring that the URL reverts to about:blank if the // document is accessed. See https://crbug.com/9682. class RenderFrameHostManagerSpoofingTest : public RenderFrameHostManagerTest { public: void SetUpInProcessBrowserTestFixture() override { base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); base::CommandLine new_command_line(command_line->GetProgram()); base::CommandLine::SwitchMap switches = command_line->GetSwitches(); // Injecting the DOM automation controller causes false positives, since it // triggers the DidAccessInitialDocument() callback by mutating the global // object. switches.erase(switches::kDomAutomationController); for (const auto& it : switches) new_command_line.AppendSwitchNative(it.first, it.second); *command_line = new_command_line; } protected: // Custom ExecuteScript() helper that doesn't depend on DOM automation // controller. This is used to guarantee the script has completed execution, // but the spoofing tests synchronize execution using window title changes. void ExecuteScript(const ToRenderFrameHost& adapter, const char* script) { adapter.render_frame_host()->ExecuteJavaScriptForTests( base::UTF8ToUTF16(script)); } }; // Helper to wait until a WebContent's NavigationController has a visible entry. class VisibleEntryWaiter : public WebContentsObserver { public: explicit VisibleEntryWaiter(WebContents* web_contents) : WebContentsObserver(web_contents) {} void Wait() { if (web_contents()->GetController().GetVisibleEntry()) return; run_loop_.Run(); } // WebContentsObserver overrides: void DidStartNavigation(NavigationHandle* navigation_handle) override { run_loop_.Quit(); } private: base::RunLoop run_loop_; }; // Sanity test that a newly opened window shows the pending URL if the initial // empty document is not modified. This is intentionally structured as similarly // as possible to the subsequent ShowLoadingURLUntil*Spoof tests: it performs // the same operations as the subsequent tests except DOM modification. This // should help catch instances where the subsequent tests incorrectly pass due // to a side effect of the test infrastructure. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerSpoofingTest, ShowLoadingURLIfNotModified) { ASSERT_TRUE(embedded_test_server()->Start()); // Load a page that can open a URL that won't commit in a new window. NavigateToURL(shell(), embedded_test_server()->GetURL("/click-nocontent-link.html")); WebContents* orig_contents = shell()->web_contents(); // Click a /nocontent link that opens in a new window but never commits. ShellAddedObserver new_shell_observer; ExecuteScript(orig_contents, "clickNoContentTargetedLink();"); // Wait for the window to open. Shell* new_shell = new_shell_observer.GetShell(); WebContents* contents = new_shell->web_contents(); // Make sure the new window has started the provisional load, so the // associated navigation controller will have a visible entry. { VisibleEntryWaiter waiter(contents); waiter.Wait(); } // Ensure the destination URL is visible, because it is considered the // initial navigation. EXPECT_TRUE(contents->GetController().IsInitialNavigation()); EXPECT_EQ("/nocontent", contents->GetController().GetVisibleEntry()->GetURL().path()); // Now get another reference to the window object, but don't otherwise access // it. This is to ensure that DidAccessInitialDocument() notifications are not // incorrectly generated when nothing is modified. base::string16 expected_title = ASCIIToUTF16("Modified Title"); TitleWatcher title_watcher(orig_contents, expected_title); ExecuteScript(orig_contents, "getNewWindowReference();"); ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle()); // The destination URL should still be visible, since nothing was modified. EXPECT_TRUE(contents->GetController().IsInitialNavigation()); EXPECT_EQ("/nocontent", contents->GetController().GetVisibleEntry()->GetURL().path()); } // Test for crbug.com/9682. We should show the URL for a pending renderer- // initiated navigation in a new tab, until the content of the initial // about:blank page is modified by another window. At that point, we should // revert to showing about:blank to prevent a URL spoof. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerSpoofingTest, ShowLoadingURLUntilSpoof) { ASSERT_TRUE(embedded_test_server()->Start()); // Load a page that can open a URL that won't commit in a new window. NavigateToURL(shell(), embedded_test_server()->GetURL("/click-nocontent-link.html")); WebContents* orig_contents = shell()->web_contents(); // Click a /nocontent link that opens in a new window but never commits. ShellAddedObserver new_shell_observer; ExecuteScript(orig_contents, "clickNoContentTargetedLink();"); // Wait for the window to open. Shell* new_shell = new_shell_observer.GetShell(); WebContents* contents = new_shell->web_contents(); // Make sure the new window has started the provisional load, so the // associated navigation controller will have a visible entry. { VisibleEntryWaiter waiter(contents); waiter.Wait(); } // Ensure the destination URL is visible, because it is considered the // initial navigation. EXPECT_TRUE(contents->GetController().IsInitialNavigation()); EXPECT_EQ("/nocontent", contents->GetController().GetVisibleEntry()->GetURL().path()); // Now modify the contents of the new window from the opener. This will also // modify the title of the document to give us something to listen for. base::string16 expected_title = ASCIIToUTF16("Modified Title"); TitleWatcher title_watcher(orig_contents, expected_title); ExecuteScript(orig_contents, "modifyNewWindow();"); ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle()); // At this point, we should no longer be showing the destination URL. // The visible entry should be null, resulting in about:blank in the address // bar. EXPECT_FALSE(contents->GetController().GetVisibleEntry()); } // Similar but using document.open(): once a Document is opened, subsequent // document.write() calls can insert arbitrary content into the target Document. // Since this could result in URL spoofing, the pending URL should no longer be // shown in the omnibox. // // Note: document.write() implicitly invokes document.open() if the Document has // not already been opened, so there's no need to test document.write() // separately. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerSpoofingTest, ShowLoadingURLUntilDocumentOpenSpoof) { ASSERT_TRUE(embedded_test_server()->Start()); // Load a page that can open a URL that won't commit in a new window. NavigateToURL(shell(), embedded_test_server()->GetURL("/click-nocontent-link.html")); WebContents* orig_contents = shell()->web_contents(); // Click a /nocontent link that opens in a new window but never commits. ShellAddedObserver new_shell_observer; ExecuteScript(orig_contents, "clickNoContentTargetedLink();"); // Wait for the window to open. Shell* new_shell = new_shell_observer.GetShell(); WebContents* contents = new_shell->web_contents(); // Make sure the new window has started the provisional load, so the // associated navigation controller will have a visible entry. { VisibleEntryWaiter waiter(contents); waiter.Wait(); } // Ensure the destination URL is visible, because it is considered the // initial navigation. EXPECT_TRUE(contents->GetController().IsInitialNavigation()); EXPECT_EQ("/nocontent", contents->GetController().GetVisibleEntry()->GetURL().path()); // Now modify the contents of the new window from the opener. This will also // modify the title of the document to give us something to listen for. base::string16 expected_title = ASCIIToUTF16("Modified Title"); TitleWatcher title_watcher(orig_contents, expected_title); ExecuteScript(orig_contents, "modifyNewWindowWithDocumentOpen();"); ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle()); // At this point, we should no longer be showing the destination URL. // The visible entry should be null, resulting in about:blank in the address // bar. EXPECT_FALSE(contents->GetController().GetVisibleEntry()); } IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, WasDiscardedWhenNavigationInterruptsReload) { EXPECT_TRUE(embedded_test_server()->Start()); GURL discarded_url(embedded_test_server()->GetURL("a.com", "/title1.html")); EXPECT_TRUE(NavigateToURL(shell(), discarded_url)); // Discard the page. shell()->web_contents()->SetWasDiscarded(true); // Reload the discarded page, but pretend that it's slow to commit. TestNavigationManager first_reload(shell()->web_contents(), discarded_url); shell()->web_contents()->GetController().Reload( ReloadType::ORIGINAL_REQUEST_URL, false); EXPECT_TRUE(first_reload.WaitForRequestStart()); // Before the response is received, simulate user navigating to another URL. GURL second_url(embedded_test_server()->GetURL("b.com", "/title1.html")); TestNavigationManager second_navigation(shell()->web_contents(), second_url); shell()->LoadURL(second_url); second_navigation.WaitForNavigationFinished(); const char kDiscardedStateJS[] = "window.domAutomationController.send(window.document.wasDiscarded);"; bool discarded_result; EXPECT_TRUE(content::ExecuteScriptAndExtractBool(shell(), kDiscardedStateJS, &discarded_result)); EXPECT_FALSE(discarded_result); } // Ensures that a pending navigation's URL is no longer visible after the // speculative RFH is discarded due to a concurrent renderer-initiated // navigation. See https://crbug.com/760342. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, ResetVisibleURLOnCrossProcessNavigationInterrupted) { const std::string kVictimPath = "/victim.html"; const std::string kAttackPath = "/attack.html"; net::test_server::ControllableHttpResponse victim_response( embedded_test_server(), kVictimPath); net::test_server::ControllableHttpResponse attack_response( embedded_test_server(), kAttackPath); EXPECT_TRUE(embedded_test_server()->Start()); const GURL kVictimURL = embedded_test_server()->GetURL("a.com", kVictimPath); const GURL kAttackURL = embedded_test_server()->GetURL("b.com", kAttackPath); // First navigate to the attacker page. This page will be cross-site compared // to the next navigations we will attempt. const GURL kAttackInitialURL = embedded_test_server()->GetURL("b.com", "/title1.html"); NavigateToURL(shell(), kAttackInitialURL); EXPECT_EQ(kAttackInitialURL, shell()->web_contents()->GetVisibleURL()); // Now, start a browser-initiated cross-site navigation to a new page that // will hang at ready to commit stage. TestNavigationManager victim_navigation(shell()->web_contents(), kVictimURL); shell()->LoadURL(kVictimURL); EXPECT_TRUE(victim_navigation.WaitForRequestStart()); victim_navigation.ResumeNavigation(); victim_response.WaitForRequest(); victim_response.Send( "HTTP/1.1 200 OK\r\n" "Content-Type: text/html; charset=utf-8\r\n" "\r\n"); EXPECT_TRUE(victim_navigation.WaitForResponse()); victim_navigation.ResumeNavigation(); // The navigation is ready to commit: it has been handed to the speculative // RenderFrameHost for commit. RenderFrameHostImpl* speculative_rfh = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root() ->render_manager() ->speculative_frame_host(); CHECK(speculative_rfh); EXPECT_TRUE(speculative_rfh->is_loading()); // Since we have a browser-initiated pending navigation, the navigation URL is // showing in the address bar. EXPECT_EQ(kVictimURL, shell()->web_contents()->GetVisibleURL()); // The attacker page requests a navigation to a new document while the // browser-initiated navigation hasn't committed yet. TestNavigationManager attack_navigation(shell()->web_contents(), kAttackURL); EXPECT_TRUE(ExecuteScriptWithoutUserGesture( shell()->web_contents(), "location.href = \"" + kAttackURL.spec() + "\";")); EXPECT_TRUE(attack_navigation.WaitForRequestStart()); // This deletes the speculative RenderFrameHost that was supposed to commit // the browser-initiated navigation. speculative_rfh = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root() ->render_manager() ->speculative_frame_host(); EXPECT_FALSE(speculative_rfh); // The URL of the browser-initiated navigation should no longer be shown in // the address bar since the RenderFrameHost that was supposed to commit it // has been discarded. Instead, we should be showing the URL of the current // page as we do not show the URL of pending navigations when they are // renderer-initiated. EXPECT_NE(kVictimURL, shell()->web_contents()->GetVisibleURL()); EXPECT_EQ(kAttackInitialURL, shell()->web_contents()->GetVisibleURL()); // The attacker navigation results in a 204. attack_navigation.ResumeNavigation(); attack_response.WaitForRequest(); attack_response.Send( "HTTP/1.1 204 OK\r\n" "Connection: close\r\n" "\r\n"); attack_navigation.WaitForNavigationFinished(); speculative_rfh = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root() ->render_manager() ->speculative_frame_host(); EXPECT_FALSE(speculative_rfh); // We are still showing the URL of the current page. EXPECT_EQ(kAttackInitialURL, shell()->web_contents()->GetVisibleURL()); } // Ensures that deleting a speculative RenderFrameHost trying to commit a // navigation to the pending NavigationEntry will not crash if it happens // because a new navigation to the same pending NavigationEntry started. This is // a regression test for crbug.com/796135. IN_PROC_BROWSER_TEST_F( RenderFrameHostManagerTest, DeleteSpeculativeRFHPendingCommitOfPendingEntryOnInterrupted1) { const std::string kOriginalPath = "/original.html"; const std::string kFirstRedirectPath = "/redirect1.html"; const std::string kSecondRedirectPath = "/reidrect2.html"; net::test_server::ControllableHttpResponse original_response1( embedded_test_server(), kOriginalPath); net::test_server::ControllableHttpResponse original_response2( embedded_test_server(), kOriginalPath); net::test_server::ControllableHttpResponse original_response3( embedded_test_server(), kOriginalPath); net::test_server::ControllableHttpResponse first_redirect_response( embedded_test_server(), kFirstRedirectPath); net::test_server::ControllableHttpResponse second_redirect_response( embedded_test_server(), kSecondRedirectPath); EXPECT_TRUE(embedded_test_server()->Start()); const GURL kOriginalURL = embedded_test_server()->GetURL("a.com", kOriginalPath); const GURL kFirstRedirectURL = embedded_test_server()->GetURL("b.com", kFirstRedirectPath); const GURL kSecondRedirectURL = embedded_test_server()->GetURL("c.com", kSecondRedirectPath); // First navigate to the initial URL. This page will have a cross-site // redirect. shell()->LoadURL(kOriginalURL); original_response1.WaitForRequest(); original_response1.Send( "HTTP/1.1 302 FOUND\r\n" "Location: " + kFirstRedirectURL.spec() + "\r\n" "\r\n"); original_response1.Done(); first_redirect_response.WaitForRequest(); first_redirect_response.Send( "HTTP/1.1 200 OK\r\n" "Content-Type: text/html; charset=utf-8\r\n" "\r\n"); first_redirect_response.Send( "<html>" "<body></body>" "</html>"); first_redirect_response.Done(); EXPECT_TRUE(WaitForLoadStop(shell()->web_contents())); EXPECT_EQ(kFirstRedirectURL, shell()->web_contents()->GetVisibleURL()); // Now reload the original request, but redirect to yet another site. TestNavigationManager first_reload(shell()->web_contents(), kOriginalURL); shell()->web_contents()->GetController().Reload( ReloadType::ORIGINAL_REQUEST_URL, false); EXPECT_TRUE(first_reload.WaitForRequestStart()); first_reload.ResumeNavigation(); original_response2.WaitForRequest(); original_response2.Send( "HTTP/1.1 302 FOUND\r\n" "Location: " + kSecondRedirectURL.spec() + "\r\n" "\r\n"); original_response2.Done(); second_redirect_response.WaitForRequest(); second_redirect_response.Send( "HTTP/1.1 200 OK\r\n" "Content-Type: text/html; charset=utf-8\r\n" "\r\n"); EXPECT_TRUE(first_reload.WaitForResponse()); first_reload.ResumeNavigation(); // The navigation is ready to commit: it has been handed to the speculative // RenderFrameHost for commit. RenderFrameHostImpl* speculative_rfh = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root() ->render_manager() ->speculative_frame_host(); CHECK(speculative_rfh); EXPECT_TRUE(speculative_rfh->is_loading()); // The user requests a new reload while the previous reload hasn't committed // yet. The navigation start deletes the speculative RenderFrameHost that was // supposed to commit the browser-initiated navigation. This should not crash. TestNavigationManager second_reload(shell()->web_contents(), kOriginalURL); shell()->web_contents()->GetController().Reload( ReloadType::ORIGINAL_REQUEST_URL, false); EXPECT_TRUE(second_reload.WaitForRequestStart()); speculative_rfh = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root() ->render_manager() ->speculative_frame_host(); EXPECT_FALSE(speculative_rfh); // The second reload results in a 204. second_reload.ResumeNavigation(); original_response3.WaitForRequest(); original_response3.Send( "HTTP/1.1 204 OK\r\n" "Connection: close\r\n" "\r\n"); second_reload.WaitForNavigationFinished(); speculative_rfh = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root() ->render_manager() ->speculative_frame_host(); EXPECT_FALSE(speculative_rfh); } // Ensures that deleting a speculative RenderFrameHost trying to commit a // navigation to the pending NavigationEntry will not crash if it happens // because a new navigation to the same pending NavigationEntry started. This // is a variant of the previous test, where we destroy the speculative // RenderFrameHost to create another speculative RenderFrameHost.This is a // regression test for crbug.com/796135. IN_PROC_BROWSER_TEST_F( RenderFrameHostManagerTest, DeleteSpeculativeRFHPendingCommitOfPendingEntryOnInterrupted2) { const std::string kOriginalPath = "/original.html"; const std::string kRedirectPath = "/redirect.html"; net::test_server::ControllableHttpResponse original_response1( embedded_test_server(), kOriginalPath); net::test_server::ControllableHttpResponse original_response2( embedded_test_server(), kOriginalPath); net::test_server::ControllableHttpResponse redirect_response( embedded_test_server(), kRedirectPath); EXPECT_TRUE(embedded_test_server()->Start()); const GURL kOriginalURL = embedded_test_server()->GetURL("a.com", kOriginalPath); const GURL kRedirectURL = embedded_test_server()->GetURL("b.com", kRedirectPath); const GURL kCrossSiteURL = embedded_test_server()->GetURL("c.com", "/title1.html"); // First navigate to the initial URL. shell()->LoadURL(kOriginalURL); original_response1.WaitForRequest(); original_response1.Send( "HTTP/1.1 200 OK\r\n" "Content-Type: text/html; charset=utf-8\r\n" "Cache-Control: no-cache, no-store, must-revalidate\r\n" "Pragma: no-cache\r\n" "\r\n"); original_response1.Send( "<html>" "<body></body>" "</html>"); original_response1.Done(); EXPECT_TRUE(WaitForLoadStop(shell()->web_contents())); EXPECT_EQ(kOriginalURL, shell()->web_contents()->GetVisibleURL()); // Navigate cross-site. NavigateToURL(shell(), kCrossSiteURL); // Now go back to the original request, which will do a cross-site redirect. TestNavigationManager first_back(shell()->web_contents(), kOriginalURL); shell()->GoBackOrForward(-1); EXPECT_TRUE(first_back.WaitForRequestStart()); first_back.ResumeNavigation(); original_response2.WaitForRequest(); original_response2.Send( "HTTP/1.1 302 FOUND\r\n" "Location: " + kRedirectURL.spec() + "\r\n" "\r\n"); original_response2.Done(); redirect_response.WaitForRequest(); redirect_response.Send( "HTTP/1.1 200 OK\r\n" "Content-Type: text/html; charset=utf-8\r\n" "\r\n"); EXPECT_TRUE(first_back.WaitForResponse()); first_back.ResumeNavigation(); // The navigation is ready to commit: it has been handed to the speculative // RenderFrameHost for commit. RenderFrameHostImpl* speculative_rfh = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root() ->render_manager() ->speculative_frame_host(); CHECK(speculative_rfh); EXPECT_TRUE(speculative_rfh->is_loading()); int site_instance_id = speculative_rfh->GetSiteInstance()->GetId(); // The user starts a navigation towards the redirected URL, for which we have // a speculative RenderFrameHost. This shouldn't delete the speculative // RenderFrameHost. TestNavigationManager navigation_to_redirect(shell()->web_contents(), kRedirectURL); shell()->LoadURL(kRedirectURL); EXPECT_TRUE(navigation_to_redirect.WaitForRequestStart()); speculative_rfh = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root() ->render_manager() ->speculative_frame_host(); CHECK(speculative_rfh); EXPECT_EQ(site_instance_id, speculative_rfh->GetSiteInstance()->GetId()); // The user requests to go back again while the previous back hasn't committed // yet. This should delete the speculative RenderFrameHost trying to commit // the back, and re-create a new speculative RenderFrameHost. This shouldn't // crash. TestNavigationManager second_back(shell()->web_contents(), kOriginalURL); shell()->GoBackOrForward(-1); EXPECT_TRUE(second_back.WaitForRequestStart()); speculative_rfh = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root() ->render_manager() ->speculative_frame_host(); CHECK(speculative_rfh); EXPECT_NE(site_instance_id, speculative_rfh->GetSiteInstance()->GetId()); } // Test for crbug.com/9682. We should not show the URL for a pending renderer- // initiated navigation in a new tab if it is not the initial navigation. In // this case, the renderer will not notify us of a modification, so we cannot // show the pending URL without allowing a spoof. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, DontShowLoadingURLIfNotInitialNav) { ASSERT_TRUE(embedded_test_server()->Start()); // Load a page that can open a URL that won't commit in a new window. NavigateToURL(shell(), embedded_test_server()->GetURL("/click-nocontent-link.html")); WebContents* orig_contents = shell()->web_contents(); // Click a /nocontent link that opens in a new window but never commits. // By using an onclick handler that first creates the window, the slow // navigation is not considered an initial navigation. ShellAddedObserver new_shell_observer; bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( orig_contents, "window.domAutomationController.send(" "clickNoContentScriptedTargetedLink());", &success)); EXPECT_TRUE(success); // Wait for the window to open. Shell* new_shell = new_shell_observer.GetShell(); // Ensure the destination URL is not visible, because it is not the initial // navigation. WebContents* contents = new_shell->web_contents(); EXPECT_FALSE(contents->GetController().IsInitialNavigation()); EXPECT_FALSE(contents->GetController().GetVisibleEntry()); } // Crashes under ThreadSanitizer, http://crbug.com/356758. #if defined(THREAD_SANITIZER) #define MAYBE_BackForwardNotStale DISABLED_BackForwardNotStale #else #define MAYBE_BackForwardNotStale BackForwardNotStale #endif // Test for http://crbug.com/93427. Ensure that cross-site navigations // do not cause back/forward navigations to be considered stale by the // renderer. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, MAYBE_BackForwardNotStale) { StartEmbeddedServer(); NavigateToURL(shell(), GURL(url::kAboutBlankURL)); // Visit a page on first site. NavigateToURL(shell(), embedded_test_server()->GetURL("/title1.html")); // Visit three pages on second site. NavigateToURL(shell(), embedded_test_server()->GetURL("foo.com", "/title1.html")); NavigateToURL(shell(), embedded_test_server()->GetURL("foo.com", "/title2.html")); NavigateToURL(shell(), embedded_test_server()->GetURL("foo.com", "/title3.html")); // History is now [blank, A1, B1, B2, *B3]. WebContents* contents = shell()->web_contents(); EXPECT_EQ(5, contents->GetController().GetEntryCount()); // Open another window in same process to keep this process alive. Shell* new_shell = CreateBrowser(); NavigateToURL(new_shell, embedded_test_server()->GetURL("foo.com", "/title1.html")); // Go back three times to first site. { TestNavigationObserver back_nav_load_observer(shell()->web_contents()); shell()->web_contents()->GetController().GoBack(); back_nav_load_observer.Wait(); } { TestNavigationObserver back_nav_load_observer(shell()->web_contents()); shell()->web_contents()->GetController().GoBack(); back_nav_load_observer.Wait(); } { TestNavigationObserver back_nav_load_observer(shell()->web_contents()); shell()->web_contents()->GetController().GoBack(); back_nav_load_observer.Wait(); } // Now go forward twice to B2. Shouldn't be left spinning. { TestNavigationObserver forward_nav_load_observer(shell()->web_contents()); shell()->web_contents()->GetController().GoForward(); forward_nav_load_observer.Wait(); } { TestNavigationObserver forward_nav_load_observer(shell()->web_contents()); shell()->web_contents()->GetController().GoForward(); forward_nav_load_observer.Wait(); } // Go back twice to first site. { TestNavigationObserver back_nav_load_observer(shell()->web_contents()); shell()->web_contents()->GetController().GoBack(); back_nav_load_observer.Wait(); } { TestNavigationObserver back_nav_load_observer(shell()->web_contents()); shell()->web_contents()->GetController().GoBack(); back_nav_load_observer.Wait(); } // Now go forward directly to B3. Shouldn't be left spinning. { TestNavigationObserver forward_nav_load_observer(shell()->web_contents()); shell()->web_contents()->GetController().GoToIndex(4); forward_nav_load_observer.Wait(); } } // This class ensures that all the given RenderViewHosts have properly been // shutdown. class RenderViewHostDestructionObserver : public WebContentsObserver { public: explicit RenderViewHostDestructionObserver(WebContents* web_contents) : WebContentsObserver(web_contents) {} ~RenderViewHostDestructionObserver() override {} void EnsureRVHGetsDestructed(RenderViewHost* rvh) { watched_render_view_hosts_.insert(rvh); } size_t GetNumberOfWatchedRenderViewHosts() const { return watched_render_view_hosts_.size(); } private: // WebContentsObserver implementation: void RenderViewDeleted(RenderViewHost* rvh) override { watched_render_view_hosts_.erase(rvh); } std::set<RenderViewHost*> watched_render_view_hosts_; }; // Crashes under ThreadSanitizer, http://crbug.com/356758. #if defined(THREAD_SANITIZER) #define MAYBE_LeakingRenderViewHosts DISABLED_LeakingRenderViewHosts #else #define MAYBE_LeakingRenderViewHosts LeakingRenderViewHosts #endif // Test for crbug.com/90867. Make sure we don't leak render view hosts since // they may cause crashes or memory corruptions when trying to call dead // delegate_. This test also verifies crbug.com/117420 and crbug.com/143255 to // ensure that a separate SiteInstance is created when navigating to view-source // URLs, regardless of current URL. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, MAYBE_LeakingRenderViewHosts) { StartEmbeddedServer(); // Observe the created render_view_host's to make sure they will not leak. RenderViewHostDestructionObserver rvh_observers(shell()->web_contents()); GURL navigated_url(embedded_test_server()->GetURL("/title2.html")); GURL view_source_url(kViewSourceScheme + std::string(":") + navigated_url.spec()); // Let's ensure that when we start with a blank window, navigating away to a // view-source URL, we create a new SiteInstance. RenderViewHost* blank_rvh = shell()->web_contents()->GetRenderViewHost(); SiteInstance* blank_site_instance = blank_rvh->GetSiteInstance(); EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), GURL::EmptyGURL()); EXPECT_EQ(blank_site_instance->GetSiteURL(), GURL::EmptyGURL()); rvh_observers.EnsureRVHGetsDestructed(blank_rvh); // Now navigate to the view-source URL and ensure we got a different // SiteInstance and RenderViewHost. NavigateToURL(shell(), view_source_url); EXPECT_NE(blank_rvh, shell()->web_contents()->GetRenderViewHost()); EXPECT_NE(blank_site_instance, shell()->web_contents()-> GetRenderViewHost()->GetSiteInstance()); rvh_observers.EnsureRVHGetsDestructed( shell()->web_contents()->GetRenderViewHost()); // Load a random page and then navigate to view-source: of it. // This used to cause two RVH instances for the same SiteInstance, which // was a problem. This is no longer the case. NavigateToURL(shell(), navigated_url); SiteInstance* site_instance1 = shell()->web_contents()-> GetRenderViewHost()->GetSiteInstance(); rvh_observers.EnsureRVHGetsDestructed( shell()->web_contents()->GetRenderViewHost()); NavigateToURL(shell(), view_source_url); rvh_observers.EnsureRVHGetsDestructed( shell()->web_contents()->GetRenderViewHost()); SiteInstance* site_instance2 = shell()->web_contents()-> GetRenderViewHost()->GetSiteInstance(); // Ensure that view-source navigations force a new SiteInstance. EXPECT_NE(site_instance1, site_instance2); // Now navigate to a different instance so that we swap out again. NavigateToURL(shell(), embedded_test_server()->GetURL("foo.com", "/title2.html")); rvh_observers.EnsureRVHGetsDestructed( shell()->web_contents()->GetRenderViewHost()); // This used to leak a render view host. shell()->Close(); RunAllPendingInMessageLoop(); // Needed on ChromeOS. EXPECT_EQ(0U, rvh_observers.GetNumberOfWatchedRenderViewHosts()); } // Test for crbug.com/143155. Frame tree updates during unload should not // interrupt the intended navigation. // Specifically: // 1) Open 2 tabs in an HTTP SiteInstance, with a subframe in the opener. // 2) Send the second tab to a different foo.com SiteInstance. // This created a swapped out opener for the first tab in the foo process. // 3) Navigate the first tab to the foo.com SiteInstance, and have the first // tab's unload handler remove its frame. // In older versions of Chrome, this caused an update to the frame tree that // resulted in showing an internal page rather than the real page. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, DontPreemptNavigationWithFrameTreeUpdate) { StartEmbeddedServer(); // 1. Load a page that deletes its iframe during unload. NavigateToURL(shell(), embedded_test_server()->GetURL("/remove_frame_on_unload.html")); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( shell()->web_contents()->GetSiteInstance()); // Open a same-site page in a new window. ShellAddedObserver new_shell_observer; bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell(), "window.domAutomationController.send(openWindow());", &success)); EXPECT_TRUE(success); Shell* new_shell = new_shell_observer.GetShell(); // Wait for the navigation in the new window to finish, if it hasn't. WaitForLoadStop(new_shell->web_contents()); EXPECT_EQ("/title1.html", new_shell->web_contents()->GetLastCommittedURL().path()); // Should have the same SiteInstance. EXPECT_EQ(orig_site_instance.get(), new_shell->web_contents()->GetSiteInstance()); // 2. Send the second tab to a different process. GURL cross_site_url( embedded_test_server()->GetURL("foo.com", "/title1.html")); EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, cross_site_url)); scoped_refptr<SiteInstance> new_site_instance( new_shell->web_contents()->GetSiteInstance()); EXPECT_NE(orig_site_instance, new_site_instance); // 3. Send the first tab to the second tab's process. EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(shell(), cross_site_url)); // Make sure it ends up at the right page. WaitForLoadStop(shell()->web_contents()); EXPECT_EQ(cross_site_url, shell()->web_contents()->GetLastCommittedURL()); EXPECT_EQ(new_site_instance, shell()->web_contents()->GetSiteInstance()); } // Ensure that renderer-side debug URLs do not cause a process swap, since they // are meant to run in the current page. We had a bug where we expected a // BrowsingInstance swap to occur on pages like view-source and extensions, // which broke chrome://crash and javascript: URLs. // See http://crbug.com/335503. // The test fails on Mac OSX with ASAN. // See http://crbug.com/699062. #if defined(OS_MACOSX) && defined(THREAD_SANITIZER) #define MAYBE_RendererDebugURLsDontSwap DISABLED_RendererDebugURLsDontSwap #else #define MAYBE_RendererDebugURLsDontSwap RendererDebugURLsDontSwap #endif IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, MAYBE_RendererDebugURLsDontSwap) { StartEmbeddedServer(); GURL original_url(embedded_test_server()->GetURL("/title2.html")); GURL view_source_url(kViewSourceScheme + std::string(":") + original_url.spec()); NavigateToURL(shell(), view_source_url); // Check that javascript: URLs work. base::string16 expected_title = ASCIIToUTF16("msg"); TitleWatcher title_watcher(shell()->web_contents(), expected_title); shell()->LoadURL(GURL("javascript:document.title='msg'")); ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle()); // Crash the renderer of the view-source page. RenderProcessHostWatcher crash_observer( shell()->web_contents(), RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); EXPECT_TRUE( NavigateToURLAndExpectNoCommit(shell(), GURL(kChromeUICrashURL))); crash_observer.Wait(); } // Ensure that renderer-side debug URLs don't take effect on crashed renderers. // Otherwise, we might try to load an unprivileged about:blank page into a // WebUI-enabled RenderProcessHost, failing a safety check in InitRenderView. // See http://crbug.com/334214. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, IgnoreRendererDebugURLsWhenCrashed) { // Visit a WebUI page with bindings. GURL webui_url = GURL(std::string(kChromeUIScheme) + "://" + std::string(kChromeUIGpuHost)); NavigateToURL(shell(), webui_url); EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings( shell()->web_contents()->GetMainFrame()->GetProcess()->GetID())); // Crash the renderer of the WebUI page. RenderProcessHostWatcher crash_observer( shell()->web_contents(), RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); EXPECT_TRUE( NavigateToURLAndExpectNoCommit(shell(), GURL(kChromeUICrashURL))); crash_observer.Wait(); // Load the crash URL again but don't wait for any action. If it is not // ignored this time, we will fail the WebUI CHECK in InitRenderView. shell()->LoadURL(GURL(kChromeUICrashURL)); // Ensure that such URLs can still work as the initial navigation of a tab. // We postpone the initial navigation of the tab using an empty GURL, so that // we can add a watcher for crashes. Shell* shell2 = Shell::CreateNewWindow(shell()->web_contents()->GetBrowserContext(), GURL(), nullptr, gfx::Size()); RenderProcessHostWatcher crash_observer2( shell2->web_contents(), RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); EXPECT_TRUE( NavigateToURLAndExpectNoCommit(shell2, GURL(kChromeUIKillURL))); crash_observer2.Wait(); } // Ensure that pending_and_current_web_ui_ is cleared when a URL commits. // Otherwise it might get picked up by InitRenderView when granting bindings // to other RenderViewHosts. See http://crbug.com/330811. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, ClearPendingWebUIOnCommit) { // Visit a WebUI page with bindings. GURL webui_url(GURL(std::string(kChromeUIScheme) + "://" + std::string(kChromeUIGpuHost))); NavigateToURL(shell(), webui_url); EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings( shell()->web_contents()->GetMainFrame()->GetProcess()->GetID())); WebContentsImpl* web_contents = static_cast<WebContentsImpl*>( shell()->web_contents()); FrameTreeNode* root = web_contents->GetFrameTree()->root(); WebUIImpl* webui = root->current_frame_host()->web_ui(); EXPECT_TRUE(webui); EXPECT_FALSE( web_contents->GetRenderManagerForTesting()->GetNavigatingWebUI()); // Navigate to another WebUI URL that reuses the WebUI object. Make sure we // clear GetNavigatingWebUI() when it commits. GURL webui_url2(webui_url.spec() + "#foo"); NavigateToURL(shell(), webui_url2); EXPECT_EQ(webui, root->current_frame_host()->web_ui()); EXPECT_FALSE( web_contents->GetRenderManagerForTesting()->GetNavigatingWebUI()); } class RFHMProcessPerTabTest : public RenderFrameHostManagerTest { public: RFHMProcessPerTabTest() {} void SetUpCommandLine(base::CommandLine* command_line) override { command_line->AppendSwitch(switches::kProcessPerTab); } }; // Test that we still swap processes for BrowsingInstance changes even in // --process-per-tab mode. See http://crbug.com/343017. // Disabled on Android: http://crbug.com/345873. // Crashes under ThreadSanitizer, http://crbug.com/356758. #if defined(OS_ANDROID) || defined(THREAD_SANITIZER) #define MAYBE_BackFromWebUI DISABLED_BackFromWebUI #else #define MAYBE_BackFromWebUI BackFromWebUI #endif IN_PROC_BROWSER_TEST_F(RFHMProcessPerTabTest, MAYBE_BackFromWebUI) { StartEmbeddedServer(); GURL original_url(embedded_test_server()->GetURL("/title2.html")); NavigateToURL(shell(), original_url); // Visit a WebUI page with bindings. GURL webui_url(GURL(std::string(kChromeUIScheme) + "://" + std::string(kChromeUIGpuHost))); NavigateToURL(shell(), webui_url); EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings( shell()->web_contents()->GetMainFrame()->GetProcess()->GetID())); // Go back and ensure we have no WebUI bindings. TestNavigationObserver back_nav_load_observer(shell()->web_contents()); shell()->web_contents()->GetController().GoBack(); back_nav_load_observer.Wait(); EXPECT_EQ(original_url, shell()->web_contents()->GetLastCommittedURL()); EXPECT_FALSE(ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings( shell()->web_contents()->GetMainFrame()->GetProcess()->GetID())); } // crbug.com/372360 // The test loads url1, opens a link pointing to url2 in a new tab, and // navigates the new tab to url1. // The following is needed for the bug to happen: // - url1 must require webui bindings; // - navigating to url2 in the site instance of url1 should not swap // browsing instances, but should require a new site instance. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, WebUIGetsBindings) { GURL url1(std::string(kChromeUIScheme) + "://" + std::string(kChromeUIGpuHost)); GURL url2(std::string(kChromeUIScheme) + "://" + std::string(kChromeUIAccessibilityHost)); // Visit a WebUI page with bindings. NavigateToURL(shell(), url1); EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings( shell()->web_contents()->GetMainFrame()->GetProcess()->GetID())); SiteInstance* site_instance1 = shell()->web_contents()->GetSiteInstance(); // Open a new tab. Initially it gets a render view in the original tab's // current site instance. TestNavigationObserver nav_observer(nullptr); nav_observer.StartWatchingNewWebContents(); ShellAddedObserver shao; OpenUrlViaClickTarget(shell(), url2); nav_observer.Wait(); Shell* new_shell = shao.GetShell(); WebContentsImpl* new_web_contents = static_cast<WebContentsImpl*>( new_shell->web_contents()); SiteInstance* site_instance2 = new_web_contents->GetSiteInstance(); EXPECT_NE(site_instance2, site_instance1); EXPECT_TRUE(site_instance2->IsRelatedSiteInstance(site_instance1)); RenderViewHost* initial_rvh = new_web_contents-> GetRenderManagerForTesting()->GetSwappedOutRenderViewHost(site_instance1); ASSERT_TRUE(initial_rvh); // Navigate to url1 and check bindings. EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, url1)); // The navigation should have used the first SiteInstance, otherwise // |initial_rvh| did not have a chance to be used. EXPECT_EQ(new_web_contents->GetSiteInstance(), site_instance1); EXPECT_EQ(BINDINGS_POLICY_WEB_UI, new_web_contents->GetMainFrame()->GetEnabledBindings()); } // crbug.com/424526 // The test loads a WebUI page in process-per-tab mode, then navigates to a // blank page and then to a regular page. The bug reproduces if blank page is // visited in between WebUI and regular page. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, ForceSwapAfterWebUIBindings) { base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kProcessPerTab); StartEmbeddedServer(); const GURL web_ui_url(std::string(kChromeUIScheme) + "://" + std::string(kChromeUIGpuHost)); EXPECT_TRUE(NavigateToURL(shell(), web_ui_url)); EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings( shell()->web_contents()->GetMainFrame()->GetProcess()->GetID())); // Capture the SiteInstance before navigating to about:blank to ensure // it doesn't change. scoped_refptr<SiteInstance> orig_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL))); EXPECT_NE(orig_site_instance, shell()->web_contents()->GetSiteInstance()); GURL regular_page_url(embedded_test_server()->GetURL("/title2.html")); EXPECT_TRUE(NavigateToURL(shell(), regular_page_url)); EXPECT_FALSE(ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings( shell()->web_contents()->GetMainFrame()->GetProcess()->GetID())); } // crbug.com/615274 // This test ensures that after an RFH is swapped out, the associated WebUI // instance is no longer allowed to send JavaScript messages. This is necessary // because WebUI currently (and unusually) always sends JavaScript messages to // the current main frame, rather than the RFH that owns the WebUI. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, WebUIJavascriptDisallowedAfterSwapOut) { StartEmbeddedServer(); const GURL web_ui_url(std::string(kChromeUIScheme) + "://" + std::string(kChromeUIGpuHost)); EXPECT_TRUE(NavigateToURL(shell(), web_ui_url)); RenderFrameHostImpl* rfh = static_cast<WebContentsImpl*>(shell()->web_contents())->GetMainFrame(); // Set up a slow unload handler to force the RFH to linger in the swapped // out but not-yet-deleted state. EXPECT_TRUE( ExecuteScript(rfh, "window.onunload=function(e){ while(1); };\n")); WebUIImpl* web_ui = rfh->web_ui(); EXPECT_TRUE(web_ui->CanCallJavascript()); auto handler_owner = std::make_unique<TestWebUIMessageHandler>(); TestWebUIMessageHandler* handler = handler_owner.get(); web_ui->AddMessageHandler(std::move(handler_owner)); EXPECT_FALSE(handler->IsJavascriptAllowed()); handler->AllowJavascript(); EXPECT_TRUE(handler->IsJavascriptAllowed()); rfh->DisableSwapOutTimerForTesting(); RenderFrameHostDestructionObserver rfh_observer(rfh); // Navigate, but wait for commit, not the actual load to finish. SiteInstanceImpl* web_ui_site_instance = rfh->GetSiteInstance(); FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root(); TestFrameNavigationObserver commit_observer(root); shell()->LoadURL(GURL(url::kAboutBlankURL)); commit_observer.WaitForCommit(); EXPECT_NE(web_ui_site_instance, shell()->web_contents()->GetSiteInstance()); EXPECT_TRUE( root->render_manager()->GetRenderFrameProxyHost(web_ui_site_instance)); // The previous RFH should still be pending deletion, as we wait for either // the SwapOut ACK or a timeout. ASSERT_TRUE(rfh->IsRenderFrameLive()); ASSERT_FALSE(rfh->is_active()); // We specifically want verify behavior between swap-out and RFH destruction. ASSERT_FALSE(rfh_observer.deleted()); EXPECT_FALSE(handler->IsJavascriptAllowed()); } // Test for http://crbug.com/703303. Ensures that the renderer process does not // try to select files whose paths cannot be converted to WebStrings. This // check is done in the renderer because it is hard to predict which paths will // turn into empty WebStrings, and the behavior varies by platform. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, DontSelectInvalidFiles) { StartServer(); // Use a file path with an invalid encoding, such that it can't be converted // to a WebString (on all platforms but Windows). base::FilePath file; EXPECT_TRUE(PathService::Get(base::DIR_TEMP, &file)); file = file.Append(FILE_PATH_LITERAL("foo\337bar")); // Navigate and try to get page to reference this file in its PageState. GURL url1(embedded_test_server()->GetURL("/file_input.html")); NavigateToURL(shell(), url1); int process_id = shell()->web_contents()->GetMainFrame()->GetProcess()->GetID(); std::unique_ptr<FileChooserDelegate> delegate(new FileChooserDelegate(file)); shell()->web_contents()->SetDelegate(delegate.get()); EXPECT_TRUE( ExecuteScript(shell(), "document.getElementById('fileinput').click();")); EXPECT_TRUE(delegate->file_chosen()); // The browser process grants access to the file whether or not the renderer // process realizes that it can't use it. This is ok, since the user actually // did select the file from the chooser. EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile( process_id, file)); // Disable the swap out timer so we wait for the UpdateState message. static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetMainFrame() ->DisableSwapOutTimerForTesting(); // Navigate to a different process and wait for the old process to exit. RenderProcessHostWatcher exit_observer( shell()->web_contents()->GetMainFrame()->GetProcess(), RenderProcessHostWatcher::WATCH_FOR_HOST_DESTRUCTION); NavigateToURL(shell(), GetCrossSiteURL("/title1.html")); exit_observer.Wait(); EXPECT_FALSE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile( shell()->web_contents()->GetMainFrame()->GetProcess()->GetID(), file)); // The renderer process should not have been killed. This is the important // part of the test. If this fails, then we didn't get a PageState to check // below, so use an assert (since the test can't meaningfully proceed). ASSERT_TRUE(exit_observer.did_exit_normally()); // Ensure that the file did not end up in the PageState of the previous entry, // except on Windows where the path is valid and WebString can handle it. NavigationEntry* prev_entry = shell()->web_contents()->GetController().GetEntryAtIndex(0); EXPECT_EQ(url1, prev_entry->GetURL()); const std::vector<base::FilePath>& files = prev_entry->GetPageState().GetReferencedFiles(); #if defined(OS_WIN) EXPECT_EQ(1U, files.size()); #else EXPECT_EQ(0U, files.size()); #endif } // Test for http://crbug.com/262948. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, RestoreFileAccessForHistoryNavigation) { StartServer(); base::FilePath file; EXPECT_TRUE(PathService::Get(base::DIR_TEMP, &file)); file = file.AppendASCII("bar"); // Navigate to url and get it to reference a file in its PageState. GURL url1(embedded_test_server()->GetURL("/file_input.html")); NavigateToURL(shell(), url1); int process_id = shell()->web_contents()->GetMainFrame()->GetProcess()->GetID(); std::unique_ptr<FileChooserDelegate> delegate(new FileChooserDelegate(file)); shell()->web_contents()->SetDelegate(delegate.get()); EXPECT_TRUE( ExecuteScript(shell(), "document.getElementById('fileinput').click();")); EXPECT_TRUE(delegate->file_chosen()); EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile( process_id, file)); // Disable the swap out timer so we wait for the UpdateState message. static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetMainFrame() ->DisableSwapOutTimerForTesting(); // Navigate to a different process without access to the file, and wait for // the old process to exit. RenderProcessHostWatcher exit_observer( shell()->web_contents()->GetMainFrame()->GetProcess(), RenderProcessHostWatcher::WATCH_FOR_HOST_DESTRUCTION); NavigateToURL(shell(), GetCrossSiteURL("/title1.html")); exit_observer.Wait(); EXPECT_FALSE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile( shell()->web_contents()->GetMainFrame()->GetProcess()->GetID(), file)); // Ensure that the file ended up in the PageState of the previous entry. NavigationEntry* prev_entry = shell()->web_contents()->GetController().GetEntryAtIndex(0); EXPECT_EQ(url1, prev_entry->GetURL()); const std::vector<base::FilePath>& files = prev_entry->GetPageState().GetReferencedFiles(); ASSERT_EQ(1U, files.size()); EXPECT_EQ(file, files.at(0)); // Go back, ending up in a different RenderProcessHost than before. TestNavigationObserver back_nav_load_observer(shell()->web_contents()); shell()->web_contents()->GetController().GoBack(); back_nav_load_observer.Wait(); EXPECT_NE(process_id, shell()->web_contents()->GetMainFrame()->GetProcess()->GetID()); // Ensure that the file access still exists in the new process ID. EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile( shell()->web_contents()->GetMainFrame()->GetProcess()->GetID(), file)); // Navigate to a same site page to trigger a PageState update and ensure the // renderer is not killed. EXPECT_TRUE( NavigateToURL(shell(), embedded_test_server()->GetURL("/title2.html"))); } // Test for http://crbug.com/441966. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, RestoreSubframeFileAccessForHistoryNavigation) { StartServer(); base::FilePath file; EXPECT_TRUE(PathService::Get(base::DIR_TEMP, &file)); file = file.AppendASCII("bar"); // Navigate to url and get it to reference a file in its PageState. GURL url1(embedded_test_server()->GetURL("/file_input_subframe.html")); NavigateToURL(shell(), url1); WebContentsImpl* wc = static_cast<WebContentsImpl*>(shell()->web_contents()); FrameTreeNode* root = wc->GetFrameTree()->root(); int process_id = shell()->web_contents()->GetMainFrame()->GetProcess()->GetID(); std::unique_ptr<FileChooserDelegate> delegate(new FileChooserDelegate(file)); shell()->web_contents()->SetDelegate(delegate.get()); EXPECT_TRUE(ExecuteScript(root->child_at(0), "document.getElementById('fileinput').click();")); EXPECT_TRUE(delegate->file_chosen()); EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile( process_id, file)); // Disable the swap out timer so we wait for the UpdateState message. root->current_frame_host()->DisableSwapOutTimerForTesting(); // Do an in-page navigation in the child to make sure we hear a PageState with // the chosen file before the subframe's FrameTreeNode is deleted. In // practice, we'll get the PageState 1 second after the file is chosen. // TODO(creis): Remove this in-page navigation once we keep track of // FrameTreeNodes that are pending deletion. See https://crbug.com/609963. { TestNavigationObserver nav_observer(shell()->web_contents()); std::string script = "location.href='#foo';"; EXPECT_TRUE(ExecuteScript(root->child_at(0), script)); nav_observer.Wait(); } // Navigate to a different process without access to the file, and wait for // the old process to exit. RenderProcessHostWatcher exit_observer( shell()->web_contents()->GetMainFrame()->GetProcess(), RenderProcessHostWatcher::WATCH_FOR_HOST_DESTRUCTION); NavigateToURL(shell(), GetCrossSiteURL("/title1.html")); exit_observer.Wait(); EXPECT_FALSE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile( shell()->web_contents()->GetMainFrame()->GetProcess()->GetID(), file)); // Ensure that the file ended up in the PageState of the previous entry. NavigationEntry* prev_entry = shell()->web_contents()->GetController().GetEntryAtIndex(0); EXPECT_EQ(url1, prev_entry->GetURL()); const std::vector<base::FilePath>& files = prev_entry->GetPageState().GetReferencedFiles(); ASSERT_EQ(1U, files.size()); EXPECT_EQ(file, files.at(0)); // Go back, ending up in a different RenderProcessHost than before. TestNavigationObserver back_nav_load_observer(shell()->web_contents()); shell()->web_contents()->GetController().GoToIndex(0); back_nav_load_observer.Wait(); EXPECT_NE(process_id, shell()->web_contents()->GetMainFrame()->GetProcess()->GetID()); // Ensure that the file access still exists in the new process ID. EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile( shell()->web_contents()->GetMainFrame()->GetProcess()->GetID(), file)); // Do another in-page navigation in the child to make sure we hear a PageState // with the chosen file. // TODO(creis): Remove this in-page navigation once we keep track of // FrameTreeNodes that are pending deletion. See https://crbug.com/609963. { TestNavigationObserver nav_observer(shell()->web_contents()); std::string script = "location.href='#foo';"; EXPECT_TRUE(ExecuteScript(root->child_at(0), script)); nav_observer.Wait(); } // Also try cloning the tab by creating a new NavigationEntry with the same // PageState. This exercises a different path, by combining the frame // specific PageStates into a full-tree PageState and converting back. There // was a bug where this caused us to lose the list of referenced files. See // https://crbug.com/620261. std::unique_ptr<NavigationEntryImpl> cloned_entry = NavigationEntryImpl::FromNavigationEntry( NavigationControllerImpl::CreateNavigationEntry( url1, Referrer(), ui::PAGE_TRANSITION_RELOAD, false, std::string(), shell()->web_contents()->GetBrowserContext())); prev_entry = shell()->web_contents()->GetController().GetEntryAtIndex(0); cloned_entry->SetPageState(prev_entry->GetPageState()); const std::vector<base::FilePath>& cloned_files = cloned_entry->GetPageState().GetReferencedFiles(); ASSERT_EQ(1U, cloned_files.size()); EXPECT_EQ(file, cloned_files.at(0)); std::vector<std::unique_ptr<NavigationEntry>> entries; entries.push_back(std::move(cloned_entry)); Shell* new_shell = Shell::CreateNewWindow(shell()->web_contents()->GetBrowserContext(), GURL::EmptyGURL(), nullptr, gfx::Size()); FrameTreeNode* new_root = static_cast<WebContentsImpl*>(new_shell->web_contents()) ->GetFrameTree() ->root(); NavigationControllerImpl& new_controller = static_cast<NavigationControllerImpl&>( new_shell->web_contents()->GetController()); new_controller.Restore(entries.size() - 1, RestoreType::LAST_SESSION_EXITED_CLEANLY, &entries); ASSERT_EQ(0u, entries.size()); { TestNavigationObserver restore_observer(new_shell->web_contents()); new_controller.LoadIfNecessary(); restore_observer.Wait(); } ASSERT_EQ(1U, new_root->child_count()); EXPECT_EQ(url1, new_root->current_url()); // Ensure that the file access exists in the new process ID. EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile( new_root->current_frame_host()->GetProcess()->GetID(), file)); // Also, extract the file from the renderer process to ensure that the // response made it over successfully and the proper filename is set. std::string file_name; EXPECT_TRUE(ExecuteScriptAndExtractString( new_root->child_at(0), "window.domAutomationController.send(" "document.getElementById('fileinput').files[0].name);", &file_name)); EXPECT_EQ("bar", file_name); // Navigate to a same site page to trigger a PageState update and ensure the // renderer is not killed. EXPECT_TRUE( NavigateToURL(new_shell, embedded_test_server()->GetURL("/title2.html"))); } // Ensures that no RenderFrameHost/RenderViewHost objects are leaked when // doing a simple cross-process navigation. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, CleanupOnCrossProcessNavigation) { StartEmbeddedServer(); // Do an initial navigation and capture objects we expect to be cleaned up // on cross-process navigation. GURL start_url = embedded_test_server()->GetURL("/title1.html"); NavigateToURL(shell(), start_url); FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root(); int32_t orig_site_instance_id = root->current_frame_host()->GetSiteInstance()->GetId(); int initial_process_id = root->current_frame_host()->GetSiteInstance()->GetProcess()->GetID(); int initial_rfh_id = root->current_frame_host()->GetRoutingID(); int initial_rvh_id = root->current_frame_host()->render_view_host()->GetRoutingID(); // Navigate cross-process and ensure that cleanup is performed as expected. GURL cross_site_url = embedded_test_server()->GetURL("foo.com", "/title2.html"); RenderFrameHostDestructionObserver rfh_observer(root->current_frame_host()); NavigateToURL(shell(), cross_site_url); rfh_observer.Wait(); EXPECT_NE(orig_site_instance_id, root->current_frame_host()->GetSiteInstance()->GetId()); EXPECT_FALSE(RenderFrameHost::FromID(initial_process_id, initial_rfh_id)); EXPECT_FALSE(RenderViewHost::FromID(initial_process_id, initial_rvh_id)); } // Ensure that the opener chain proxies and RVHs are properly reinitialized if // a tab crashes and reloads. See https://crbug.com/505090. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, ReinitializeOpenerChainAfterCrashAndReload) { StartEmbeddedServer(); GURL main_url = embedded_test_server()->GetURL("/title1.html"); EXPECT_TRUE(NavigateToURL(shell(), main_url)); FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root(); scoped_refptr<SiteInstance> orig_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance); // Open a popup and navigate it cross-site. Shell* new_shell = OpenPopup(shell(), GURL(url::kAboutBlankURL), "foo"); EXPECT_TRUE(new_shell); FrameTreeNode* popup_root = static_cast<WebContentsImpl*>(new_shell->web_contents()) ->GetFrameTree() ->root(); GURL cross_site_url = embedded_test_server()->GetURL("foo.com", "/title2.html"); EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, cross_site_url)); scoped_refptr<SiteInstance> foo_site_instance( new_shell->web_contents()->GetSiteInstance()); EXPECT_NE(foo_site_instance, orig_site_instance); // Kill the popup's process. RenderProcessHost* popup_process = popup_root->current_frame_host()->GetProcess(); RenderProcessHostWatcher crash_observer( popup_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); popup_process->Shutdown(0); crash_observer.Wait(); EXPECT_FALSE(popup_root->current_frame_host()->IsRenderFrameLive()); EXPECT_FALSE( popup_root->current_frame_host()->render_view_host()->IsRenderViewLive()); // The swapped-out RVH and proxy for the opener page in the foo.com // SiteInstance should not be live. RenderFrameHostManager* opener_manager = root->render_manager(); RenderViewHostImpl* opener_rvh = opener_manager->GetSwappedOutRenderViewHost(foo_site_instance.get()); EXPECT_TRUE(opener_rvh); EXPECT_FALSE(opener_rvh->IsRenderViewLive()); RenderFrameProxyHost* opener_rfph = opener_manager->GetRenderFrameProxyHost(foo_site_instance.get()); EXPECT_TRUE(opener_rfph); EXPECT_FALSE(opener_rfph->is_render_frame_proxy_live()); // Re-navigate the popup to the same URL and check that this recreates the // opener's swapped out RVH and proxy in the foo.com SiteInstance. EXPECT_TRUE(NavigateToURL(new_shell, cross_site_url)); EXPECT_TRUE(opener_rvh->IsRenderViewLive()); EXPECT_TRUE(opener_rfph->is_render_frame_proxy_live()); } // Test that when a frame's opener is updated via window.open, the browser // process and the frame's proxies in other processes find out about the new // opener. Open two popups in different processes, set one popup's opener to // the other popup, and ensure that the opener is updated in all processes. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, UpdateOpener) { StartEmbeddedServer(); GURL main_url = embedded_test_server()->GetURL("/post_message.html"); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root(); scoped_refptr<SiteInstance> orig_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance); // Open a cross-site popup named "foo" and a same-site popup named "bar". Shell* foo_shell = OpenPopup(shell(), GURL(url::kAboutBlankURL), "foo"); EXPECT_TRUE(foo_shell); GURL foo_url(embedded_test_server()->GetURL("foo.com", "/post_message.html")); EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(foo_shell, foo_url)); GURL bar_url(embedded_test_server()->GetURL( "/frame_tree/page_with_post_message_frames.html")); Shell* bar_shell = OpenPopup(shell(), bar_url, "bar"); EXPECT_TRUE(bar_shell); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), foo_shell->web_contents()->GetSiteInstance()); EXPECT_EQ(shell()->web_contents()->GetSiteInstance(), bar_shell->web_contents()->GetSiteInstance()); // Initially, both popups' openers should point to main window. FrameTreeNode* foo_root = static_cast<WebContentsImpl*>(foo_shell->web_contents()) ->GetFrameTree() ->root(); FrameTreeNode* bar_root = static_cast<WebContentsImpl*>(bar_shell->web_contents()) ->GetFrameTree() ->root(); EXPECT_EQ(root, foo_root->opener()); EXPECT_EQ(root, foo_root->original_opener()); EXPECT_EQ(root, bar_root->opener()); EXPECT_EQ(root, bar_root->original_opener()); // From the bar process, use window.open to update foo's opener to point to // bar. This is allowed since bar is same-origin with foo's opener. Use // window.open with an empty URL, which should return a reference to the // target frame without navigating it. bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( bar_shell, "window.domAutomationController.send(!!window.open('','foo'));", &success)); EXPECT_TRUE(success); EXPECT_FALSE(foo_shell->web_contents()->IsLoading()); EXPECT_EQ(foo_url, foo_root->current_url()); // Check that updated opener propagated to the browser process. EXPECT_EQ(bar_root, foo_root->opener()); EXPECT_EQ(root, foo_root->original_opener()); // Check that foo's opener was updated in foo's process. Send a postMessage // to the opener and check that the right window (bar_shell) receives it. base::string16 expected_title = ASCIIToUTF16("opener-msg"); TitleWatcher title_watcher(bar_shell->web_contents(), expected_title); success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( foo_shell, "window.domAutomationController.send(postToOpener('opener-msg', '*'));", &success)); EXPECT_TRUE(success); EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle()); // Check that a non-null assignment to the opener doesn't change the opener // in the browser process. EXPECT_TRUE(ExecuteScript(foo_shell, "window.opener = window;")); EXPECT_EQ(bar_root, foo_root->opener()); EXPECT_EQ(root, foo_root->original_opener()); } // Tests that when a popup is opened, which is then navigated cross-process and // back, it can be still accessed through the original window reference in // JavaScript. See https://crbug.com/537657 IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, PopupKeepsWindowReferenceCrossProcesAndBack) { StartEmbeddedServer(); // Load a page with links that open in a new window. NavigateToPageWithLinks(shell()); // Click a target=foo link to open a popup. ShellAddedObserver new_shell_observer; bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell(), "window.domAutomationController.send(clickSameSiteTargetedLink());", &success)); EXPECT_TRUE(success); Shell* new_shell = new_shell_observer.GetShell(); EXPECT_TRUE(new_shell->web_contents()->HasOpener()); // Wait for the navigation in the popup to finish, if it hasn't. WaitForLoadStop(new_shell->web_contents()); EXPECT_EQ("/navigate_opener.html", new_shell->web_contents()->GetLastCommittedURL().path()); // Capture the window reference, so we can check that accessing its location // works after navigating cross-process and back. GURL expected_url = new_shell->web_contents()->GetLastCommittedURL(); EXPECT_TRUE(ExecuteScript(shell(), "saveWindowReference();")); // Now navigate the popup to a different site and then go back. NavigateToURL(new_shell, embedded_test_server()->GetURL("foo.com", "/title1.html")); TestNavigationObserver back_nav_load_observer(new_shell->web_contents()); new_shell->web_contents()->GetController().GoBack(); back_nav_load_observer.Wait(); // Check that the location.href window attribute is accessible and is correct. std::string result; EXPECT_TRUE(ExecuteScriptAndExtractString( shell(), "window.domAutomationController.send(getLastOpenedWindowLocation());", &result)); EXPECT_EQ(expected_url.spec(), result); } // Tests that going back to the same SiteInstance as a pending RenderFrameHost // doesn't create a duplicate RenderFrameProxyHost. For example: // 1. Navigate to a page on the opener site - a.com // 2. Navigate to a page on site b.com // 3. Start a navigation to another page on a.com, but commit is delayed. // 4. Go back. // See https://crbug.com/541619. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, PopupPendingAndBackToSameSiteInstance) { StartEmbeddedServer(); GURL main_url(embedded_test_server()->GetURL("a.com", "/title1.html")); NavigateToURL(shell(), main_url); // Open a popup to navigate. Shell* new_shell = OpenPopup(shell(), GURL(url::kAboutBlankURL), "foo"); EXPECT_EQ(shell()->web_contents()->GetSiteInstance(), new_shell->web_contents()->GetSiteInstance()); // Navigate the popup to a different site. NavigateToURL(new_shell, embedded_test_server()->GetURL("b.com", "/title2.html")); // Navigate again to the original site, but to a page that will take a while // to commit. GURL same_site_url(embedded_test_server()->GetURL("a.com", "/title3.html")); NavigationStallDelegate stall_delegate(same_site_url); ResourceDispatcherHost::Get()->SetDelegate(&stall_delegate); new_shell->LoadURL(same_site_url); // Going back in history should work and the test should not crash. TestNavigationObserver back_nav_load_observer(new_shell->web_contents()); new_shell->web_contents()->GetController().GoBack(); back_nav_load_observer.Wait(); ResourceDispatcherHost::Get()->SetDelegate(nullptr); } // Tests that InputMsg type IPCs are ignored by swapped out RenderViews. It // uses the SetFocus IPC, as RenderView has a CHECK to ensure that condition // never happens. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, InputMsgToSwappedOutRVHIsIgnored) { StartEmbeddedServer(); EXPECT_TRUE(NavigateToURL( shell(), embedded_test_server()->GetURL("a.com", "/title1.html"))); // Open a popup to navigate cross-process. Shell* new_shell = OpenPopup(shell(), GURL(url::kAboutBlankURL), "foo"); EXPECT_EQ(shell()->web_contents()->GetSiteInstance(), new_shell->web_contents()->GetSiteInstance()); // Keep a pointer to the RenderViewHost, which will be in swapped out // state after navigating cross-process. This is how this test is causing // a swapped out RenderView to receive InputMsg IPC message. WebContentsImpl* new_web_contents = static_cast<WebContentsImpl*>(new_shell->web_contents()); FrameTreeNode* new_root = new_web_contents->GetFrameTree()->root(); RenderViewHostImpl* rvh = new_web_contents->GetRenderViewHost(); // Navigate the popup to a different site, so the |rvh| is swapped out. EXPECT_TRUE(NavigateToURL( new_shell, embedded_test_server()->GetURL("b.com", "/title2.html"))); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), new_shell->web_contents()->GetSiteInstance()); EXPECT_EQ(rvh, new_root->render_manager()->GetSwappedOutRenderViewHost( shell()->web_contents()->GetSiteInstance())); // Setup a process observer to ensure there is no crash and send the IPC // message. RenderProcessHostWatcher watcher( rvh->GetProcess(), RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); rvh->GetWidget()->GetWidgetInputHandler()->SetFocus(true); // The test must wait for a process to exit, but if the IPC message is // properly ignored, there will be no crash. Therefore, navigate the // original window to the same site as the popup, which will just exit the // process cleanly. EXPECT_TRUE(NavigateToURL( shell(), embedded_test_server()->GetURL("b.com", "/title3.html"))); watcher.Wait(); EXPECT_TRUE(watcher.did_exit_normally()); } // Tests that navigating cross-process and reusing an existing RenderViewHost // (whose process has been killed/crashed) recreates properly the RenderView and // RenderFrameProxy on the renderer side. // See https://crbug.com/544271 IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, RenderViewInitAfterProcessKill) { StartEmbeddedServer(); EXPECT_TRUE(NavigateToURL( shell(), embedded_test_server()->GetURL("a.com", "/title1.html"))); // Open a popup to navigate. Shell* new_shell = OpenPopup(shell(), GURL(url::kAboutBlankURL), "foo"); FrameTreeNode* popup_root = static_cast<WebContentsImpl*>(new_shell->web_contents()) ->GetFrameTree() ->root(); EXPECT_EQ(shell()->web_contents()->GetSiteInstance(), new_shell->web_contents()->GetSiteInstance()); // Navigate the popup to a different site. EXPECT_TRUE(NavigateToURL( new_shell, embedded_test_server()->GetURL("b.com", "/title2.html"))); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), new_shell->web_contents()->GetSiteInstance()); // Kill the process hosting the popup. RenderProcessHost* process = popup_root->current_frame_host()->GetProcess(); RenderProcessHostWatcher crash_observer( process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); process->Shutdown(0); crash_observer.Wait(); EXPECT_FALSE(popup_root->current_frame_host()->IsRenderFrameLive()); EXPECT_FALSE( popup_root->current_frame_host()->render_view_host()->IsRenderViewLive()); // Navigate the main tab to the site of the popup. This will cause the // RenderView for b.com in the main tab to be recreated. If the issue // is not fixed, this will result in process crash and failing test. EXPECT_TRUE(NavigateToURL( shell(), embedded_test_server()->GetURL("b.com", "/title3.html"))); } // Ensure that we don't crash the renderer in CreateRenderView if a proxy goes // away between swapout and the next navigation. See https://crbug.com/581912. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, CreateRenderViewAfterProcessKillAndClosedProxy) { StartEmbeddedServer(); FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root(); // Give an initial page an unload handler that never completes. EXPECT_TRUE(NavigateToURL( shell(), embedded_test_server()->GetURL("a.com", "/title1.html"))); EXPECT_TRUE( ExecuteScript(root, "window.onunload=function(e){ while(1); };\n")); // Open a popup in the same process. Shell* new_shell = OpenPopup(shell(), GURL(url::kAboutBlankURL), "foo"); FrameTreeNode* popup_root = static_cast<WebContentsImpl*>(new_shell->web_contents()) ->GetFrameTree() ->root(); EXPECT_EQ(shell()->web_contents()->GetSiteInstance(), new_shell->web_contents()->GetSiteInstance()); // Navigate the first tab to a different site, and only wait for commit, not // load stop. RenderFrameHostImpl* rfh_a = root->current_frame_host(); rfh_a->DisableSwapOutTimerForTesting(); SiteInstanceImpl* site_instance_a = rfh_a->GetSiteInstance(); TestFrameNavigationObserver commit_observer(root); shell()->LoadURL(embedded_test_server()->GetURL("b.com", "/title2.html")); commit_observer.WaitForCommit(); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), new_shell->web_contents()->GetSiteInstance()); EXPECT_TRUE(root->render_manager()->GetRenderFrameProxyHost(site_instance_a)); // The previous RFH should still be pending deletion, as we wait for either // the SwapOut ACK or a timeout. ASSERT_TRUE(rfh_a->IsRenderFrameLive()); ASSERT_FALSE(rfh_a->is_active()); // The corresponding RVH should still be referenced by the proxy and the old // frame. RenderViewHostImpl* rvh_a = rfh_a->render_view_host(); EXPECT_EQ(2, rvh_a->ref_count()); // Kill the old process. RenderProcessHost* process = rfh_a->GetProcess(); RenderProcessHostWatcher crash_observer( process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); process->Shutdown(0); crash_observer.Wait(); EXPECT_FALSE(popup_root->current_frame_host()->IsRenderFrameLive()); // |rfh_a| is now deleted, thanks to the bug fix. // With |rfh_a| gone, the RVH should only be referenced by the (dead) proxy. EXPECT_EQ(1, rvh_a->ref_count()); EXPECT_TRUE(root->render_manager()->GetRenderFrameProxyHost(site_instance_a)); EXPECT_FALSE(root->render_manager() ->GetRenderFrameProxyHost(site_instance_a) ->is_render_frame_proxy_live()); // Close the popup so there is no proxy for a.com in the original tab. new_shell->Close(); EXPECT_FALSE( root->render_manager()->GetRenderFrameProxyHost(site_instance_a)); // This should delete the RVH as well. EXPECT_FALSE(root->frame_tree()->GetRenderViewHost(site_instance_a)); // Go back in the main frame from b.com to a.com. In https://crbug.com/581912, // the browser process would crash here because there was no main frame // routing ID or proxy in RVHI::CreateRenderView. { TestNavigationObserver back_nav_load_observer(shell()->web_contents()); shell()->web_contents()->GetController().GoBack(); back_nav_load_observer.Wait(); } } // Ensure that we don't crash in RenderViewImpl::Init if a proxy is created // after swapout and before navigation. See https://crbug.com/544755. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, RenderViewInitAfterNewProxyAndProcessKill) { StartEmbeddedServer(); FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root(); // Give an initial page an unload handler that never completes. EXPECT_TRUE(NavigateToURL( shell(), embedded_test_server()->GetURL("a.com", "/title1.html"))); EXPECT_TRUE( ExecuteScript(root, "window.onunload=function(e){ while(1); };\n")); // Navigate the tab to a different site, and only wait for commit, not load // stop. RenderFrameHostImpl* rfh_a = root->current_frame_host(); rfh_a->DisableSwapOutTimerForTesting(); SiteInstanceImpl* site_instance_a = rfh_a->GetSiteInstance(); TestFrameNavigationObserver commit_observer(root); shell()->LoadURL(embedded_test_server()->GetURL("b.com", "/title2.html")); commit_observer.WaitForCommit(); EXPECT_NE(site_instance_a, shell()->web_contents()->GetSiteInstance()); // The previous RFH should still be pending deletion, as we wait for either // the SwapOut ACK or a timeout. ASSERT_TRUE(rfh_a->IsRenderFrameLive()); ASSERT_FALSE(rfh_a->is_active()); // When the previous RFH was swapped out, it should have still gotten a // replacement proxy even though it's the last active frame in the process. EXPECT_TRUE(root->render_manager()->GetRenderFrameProxyHost(site_instance_a)); // Open a popup in the new B process. Shell* new_shell = OpenPopup(shell(), GURL(url::kAboutBlankURL), "foo"); EXPECT_EQ(shell()->web_contents()->GetSiteInstance(), new_shell->web_contents()->GetSiteInstance()); // Navigate the popup to the original site, but don't wait for commit (which // won't happen). This should reuse the proxy in the original tab, which at // this point exists alongside the RFH pending deletion. new_shell->LoadURL(embedded_test_server()->GetURL("a.com", "/title2.html")); EXPECT_TRUE(root->render_manager()->GetRenderFrameProxyHost(site_instance_a)); // Kill the old process. RenderProcessHost* process = rfh_a->GetProcess(); RenderProcessHostWatcher crash_observer( process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); process->Shutdown(0); crash_observer.Wait(); // |rfh_a| is now deleted, thanks to the bug fix. // Go back in the main frame from b.com to a.com. { TestNavigationObserver back_nav_load_observer(shell()->web_contents()); shell()->web_contents()->GetController().GoBack(); back_nav_load_observer.Wait(); } // In https://crbug.com/581912, the renderer process would crash here because // there was a frame, view, and proxy (and is_swapped_out was true). EXPECT_EQ(site_instance_a, root->current_frame_host()->GetSiteInstance()); EXPECT_TRUE(root->current_frame_host()->IsRenderFrameLive()); EXPECT_TRUE(new_shell->web_contents()->GetMainFrame()->IsRenderFrameLive()); } // Ensure that we use the same pending RenderFrameHost if a second navigation to // its site occurs before it commits. Otherwise the renderer process will have // two competing pending RenderFrames that both try to swap with the same // RenderFrameProxy. See https://crbug.com/545900. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, ConsecutiveNavigationsToSite) { StartEmbeddedServer(); EXPECT_TRUE(NavigateToURL( shell(), embedded_test_server()->GetURL("a.com", "/title1.html"))); // Open a popup and navigate it to b.com to keep the b.com process alive. Shell* new_shell = OpenPopup(shell(), GURL(url::kAboutBlankURL), "popup"); NavigateToURL(new_shell, embedded_test_server()->GetURL("b.com", "/title3.html")); // Start a cross-site navigation to the same site but don't commit. GURL cross_site_url(embedded_test_server()->GetURL("b.com", "/title1.html")); NavigationStallDelegate stall_delegate(cross_site_url); ResourceDispatcherHost::Get()->SetDelegate(&stall_delegate); shell()->LoadURL(cross_site_url); WebContentsImpl* web_contents = static_cast<WebContentsImpl*>( shell()->web_contents()); RenderFrameHostImpl* next_rfh = web_contents->GetRenderManagerForTesting()->speculative_frame_host(); ASSERT_TRUE(next_rfh); // Navigate to the same new site and verify that we commit in the same RFH. GURL cross_site_url2(embedded_test_server()->GetURL("b.com", "/title2.html")); TestNavigationObserver navigation_observer(web_contents, 1); shell()->LoadURL(cross_site_url2); EXPECT_EQ( next_rfh, web_contents->GetRenderManagerForTesting()->speculative_frame_host()); navigation_observer.Wait(); EXPECT_EQ(cross_site_url2, web_contents->GetLastCommittedURL()); EXPECT_EQ(next_rfh, web_contents->GetMainFrame()); EXPECT_FALSE( web_contents->GetRenderManagerForTesting()->speculative_frame_host()); ResourceDispatcherHost::Get()->SetDelegate(nullptr); } // Check that if a sandboxed subframe opens a cross-process popup such that the // popup's opener won't be set, the popup still inherits the subframe's sandbox // flags. This matters for rel=noopener and rel=noreferrer links, as well as // for some situations in non-site-per-process mode where the popup would // normally maintain the opener, but loses it due to being placed in a new // process and not creating subframe proxies. The latter might happen when // opening the default search provider site. See https://crbug.com/576204. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, CrossProcessPopupInheritsSandboxFlagsWithNoOpener) { StartEmbeddedServer(); FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root(); GURL main_url(embedded_test_server()->GetURL("a.com", "/title1.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // Add a sandboxed about:blank iframe. { std::string script = "var frame = document.createElement('iframe');\n" "frame.sandbox = 'allow-scripts allow-popups';\n" "document.body.appendChild(frame);\n"; EXPECT_TRUE(ExecuteScript(shell(), script)); } // Navigate iframe to a page with target=_blank links, and rewrite the links // to point to valid cross-site URLs. GURL frame_url( embedded_test_server()->GetURL("a.com", "/click-noreferrer-links.html")); NavigateFrameToURL(root->child_at(0), frame_url); std::string script = "setOriginForLinks('http://b.com:" + embedded_test_server()->base_url().port() + "/');"; EXPECT_TRUE(ExecuteScript(root->child_at(0), script)); // Helper to click on the 'rel=noreferrer target=_blank' and 'rel=noopener // target=_blank' links. Checks that these links open a popup that ends up // in a new SiteInstance even without site-per-process and then verifies that // the popup is still sandboxed. auto click_link_and_verify_popup = [this, root](std::string link_opening_script) { ShellAddedObserver new_shell_observer; bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( root->child_at(0), "window.domAutomationController.send(" + link_opening_script + ")", &success)); EXPECT_TRUE(success); Shell* new_shell = new_shell_observer.GetShell(); EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents())); EXPECT_NE(new_shell->web_contents()->GetSiteInstance(), shell()->web_contents()->GetSiteInstance()); // Check that the popup is sandboxed by checking its document.origin, which // should be unique. std::string origin; EXPECT_TRUE(ExecuteScriptAndExtractString( new_shell, "domAutomationController.send(document.origin)", &origin)); EXPECT_EQ("null", origin); }; click_link_and_verify_popup("clickNoOpenerTargetBlankLink()"); click_link_and_verify_popup("clickNoRefTargetBlankLink()"); } // When two frames are same-origin but cross-process, they should behave as if // they are not same-origin and should not crash. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, SameOriginFramesInDifferentProcesses) { StartEmbeddedServer(); // Load a page with links that open in a new window. NavigateToURL(shell(), embedded_test_server()->GetURL( "a.com", "/click-noreferrer-links.html")); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( shell()->web_contents()->GetSiteInstance()); EXPECT_NE(nullptr, orig_site_instance.get()); // Test clicking a target=foo link. ShellAddedObserver new_shell_observer; bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell(), "window.domAutomationController.send(clickSameSiteTargetedLink());" "saveWindowReference();", &success)); EXPECT_TRUE(success); Shell* new_shell = new_shell_observer.GetShell(); // Wait for the navigation in the new tab to finish, if it hasn't. WaitForLoadStop(new_shell->web_contents()); EXPECT_EQ("/navigate_opener.html", new_shell->web_contents()->GetLastCommittedURL().path()); // Do a cross-site navigation that winds up same-site. The same-site // navigation to a.com will commit in a different process than the original // a.com window. NavigateToURL(new_shell, embedded_test_server()->GetURL( "b.com", "/cross-site/a.com/title1.html")); // The SiteInstance for the navigation is determined after the redirect. // So both windows will actually be in the same process. EXPECT_EQ(shell()->web_contents()->GetSiteInstance(), new_shell->web_contents()->GetSiteInstance()); std::string result; EXPECT_TRUE(ExecuteScriptAndExtractString( shell(), "window.domAutomationController.send((function() {\n" " try {\n" " return getLastOpenedWindowLocation();\n" " } catch (e) {\n" " return e.toString();\n" " }\n" "})())", &result)); EXPECT_THAT(result, ::testing::MatchesRegex("http://a.com:\\d+/title1.html")); } // Test coverage for attempts to open subframe links in new windows, to prevent // incorrect invariant checks. See https://crbug.com/605055. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, CtrlClickSubframeLink) { StartEmbeddedServer(); // Load a page with a subframe link. NavigateToURL(shell(), embedded_test_server()->GetURL( "/ctrl-click-subframe-link.html")); // Simulate a ctrl click on the link. This won't actually create a new Shell // because Shell::OpenURLFromTab only supports CURRENT_TAB, but it's enough to // trigger the crash from https://crbug.com/605055. EXPECT_TRUE(ExecuteScript( shell(), "window.domAutomationController.send(ctrlClickLink());")); } // Ensure that we don't update the wrong NavigationEntry's title after an // ignored commit during a cross-process navigation. // See https://crbug.com/577449. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, UnloadPushStateOnCrossProcessNavigation) { StartEmbeddedServer(); WebContentsImpl* web_contents = static_cast<WebContentsImpl*>(shell()->web_contents()); FrameTreeNode* root = web_contents->GetFrameTree()->root(); // Give an initial page an unload handler that does a pushState, which will be // ignored by the browser process. It then does a title update which is // meant for a NavigationEntry that will never be created. EXPECT_TRUE(NavigateToURL( shell(), embedded_test_server()->GetURL("a.com", "/title2.html"))); EXPECT_TRUE(ExecuteScript(root, "window.onunload=function(e){" "history.pushState({}, 'foo', 'foo');" "document.title='foo'; };\n")); base::string16 title = web_contents->GetTitle(); NavigationEntryImpl* entry = web_contents->GetController().GetEntryAtIndex(0); // Navigate the first tab to a different site and wait for the old process to // complete its unload handler and exit. RenderFrameHostImpl* rfh_a = root->current_frame_host(); rfh_a->DisableSwapOutTimerForTesting(); RenderProcessHostWatcher exit_observer( rfh_a->GetProcess(), RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); TestNavigationObserver commit_observer(web_contents); shell()->LoadURL(embedded_test_server()->GetURL("b.com", "/title1.html")); commit_observer.Wait(); exit_observer.Wait(); // Ensure the entry's title hasn't changed after the ignored commit. EXPECT_EQ(title, entry->GetTitle()); } // Ensure that document hosted on file: URL can successfully execute pushState // with arbitrary origin, when universal access setting is enabled. // TODO(nasko): The test is disabled on Mac, since universal access from file // scheme behaves differently. #if defined(OS_MACOSX) #define MAYBE_EnsureUniversalAccessFromFileSchemeSucceeds \ DISABLED_EnsureUniversalAccessFromFileSchemeSucceeds #else #define MAYBE_EnsureUniversalAccessFromFileSchemeSucceeds \ EnsureUniversalAccessFromFileSchemeSucceeds #endif IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, MAYBE_EnsureUniversalAccessFromFileSchemeSucceeds) { StartEmbeddedServer(); WebContentsImpl* web_contents = static_cast<WebContentsImpl*>(shell()->web_contents()); FrameTreeNode* root = web_contents->GetFrameTree()->root(); WebPreferences prefs = web_contents->GetRenderViewHost()->GetWebkitPreferences(); prefs.allow_universal_access_from_file_urls = true; web_contents->GetRenderViewHost()->UpdateWebkitPreferences(prefs); GURL file_url = GetTestUrl("", "title1.html"); ASSERT_TRUE(NavigateToURL(shell(), file_url)); EXPECT_EQ(1, web_contents->GetController().GetEntryCount()); EXPECT_TRUE(ExecuteScript( root, "window.history.pushState({}, '', 'https://chromium.org');")); EXPECT_EQ(2, web_contents->GetController().GetEntryCount()); EXPECT_TRUE(web_contents->GetMainFrame()->IsRenderFrameLive()); } // Ensure that navigating back from a sad tab to an existing process works // correctly. See https://crbug.com/591984. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, NavigateBackToExistingProcessFromSadTab) { StartEmbeddedServer(); EXPECT_TRUE(NavigateToURL( shell(), embedded_test_server()->GetURL("a.com", "/title1.html"))); // Open a popup and navigate it to b.com. Shell* popup = OpenPopup( shell(), embedded_test_server()->GetURL("a.com", "/title2.html"), "foo"); EXPECT_TRUE(NavigateToURL( popup, embedded_test_server()->GetURL("b.com", "/title3.html"))); // Kill the b.com process. RenderProcessHost* b_process = popup->web_contents()->GetMainFrame()->GetProcess(); RenderProcessHostWatcher crash_observer( b_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); b_process->Shutdown(0); crash_observer.Wait(); // The popup should now be showing the sad tab. Main tab should not be. EXPECT_NE(base::TERMINATION_STATUS_STILL_RUNNING, popup->web_contents()->GetCrashedStatus()); EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING, shell()->web_contents()->GetCrashedStatus()); // Go back in the popup from b.com to a.com/title2.html. TestNavigationObserver back_observer(popup->web_contents()); popup->web_contents()->GetController().GoBack(); back_observer.Wait(); // In the bug, after the back navigation the popup was still showing // the sad tab. Ensure this is not the case. EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING, popup->web_contents()->GetCrashedStatus()); EXPECT_TRUE(popup->web_contents()->GetMainFrame()->IsRenderFrameLive()); EXPECT_EQ(popup->web_contents()->GetMainFrame()->GetSiteInstance(), shell()->web_contents()->GetMainFrame()->GetSiteInstance()); } // Verify that GetLastCommittedOrigin() is correct for the full lifetime of a // RenderFrameHost, including when it's pending, current, and pending deletion. // This is checked both for main frames and subframes. // See https://crbug.com/590035. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, LastCommittedOrigin) { StartEmbeddedServer(); GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); EXPECT_TRUE(NavigateToURL(shell(), url_a)); WebContentsImpl* web_contents = static_cast<WebContentsImpl*>(shell()->web_contents()); FrameTreeNode* root = web_contents->GetFrameTree()->root(); RenderFrameHostImpl* rfh_a = root->current_frame_host(); rfh_a->DisableSwapOutTimerForTesting(); EXPECT_EQ(url::Origin::Create(url_a), rfh_a->GetLastCommittedOrigin()); EXPECT_EQ(rfh_a, web_contents->GetMainFrame()); // Start a navigation to a b.com URL, and don't wait for commit. GURL url_b(embedded_test_server()->GetURL("b.com", "/title2.html")); TestFrameNavigationObserver commit_observer(root); RenderFrameDeletedObserver deleted_observer(rfh_a); shell()->LoadURL(url_b); // The speculative RFH shouln't have a last committed origin (the default // value is a unique origin). The current RFH shouldn't change its last // committed origin before commit. RenderFrameHostImpl* rfh_b = root->render_manager()->speculative_frame_host(); EXPECT_EQ("null", rfh_b->GetLastCommittedOrigin().Serialize()); EXPECT_EQ(url::Origin::Create(url_a), rfh_a->GetLastCommittedOrigin()); // Verify that the last committed origin is set for the b.com RHF once it // commits. commit_observer.WaitForCommit(); EXPECT_EQ(url::Origin::Create(url_b), rfh_b->GetLastCommittedOrigin()); EXPECT_EQ(rfh_b, web_contents->GetMainFrame()); // The old RFH should now be pending deletion. Verify it still has correct // last committed origin. EXPECT_EQ(url::Origin::Create(url_a), rfh_a->GetLastCommittedOrigin()); EXPECT_FALSE(rfh_a->is_active()); // Wait for |rfh_a| to be deleted and double-check |rfh_b|'s origin. deleted_observer.WaitUntilDeleted(); EXPECT_EQ(url::Origin::Create(url_b), rfh_b->GetLastCommittedOrigin()); // Navigate to a same-origin page with an about:blank iframe. The iframe // should also have a b.com origin. GURL url_b_with_frame(embedded_test_server()->GetURL( "b.com", "/navigation_controller/page_with_iframe.html")); EXPECT_TRUE(NavigateToURL(shell(), url_b_with_frame)); EXPECT_EQ(rfh_b, web_contents->GetMainFrame()); EXPECT_EQ(url::Origin::Create(url_b), rfh_b->GetLastCommittedOrigin()); FrameTreeNode* child = root->child_at(0); RenderFrameHostImpl* child_rfh_b = root->child_at(0)->current_frame_host(); child_rfh_b->DisableSwapOutTimerForTesting(); EXPECT_EQ(url::Origin::Create(url_b), child_rfh_b->GetLastCommittedOrigin()); // Navigate subframe to c.com. Wait for commit but not full load, and then // verify the subframe's origin. GURL url_c(embedded_test_server()->GetURL("c.com", "/title3.html")); { TestFrameNavigationObserver commit_observer(root->child_at(0)); EXPECT_TRUE( ExecuteScript(child, "location.href = '" + url_c.spec() + "';")); commit_observer.WaitForCommit(); } EXPECT_EQ(url::Origin::Create(url_c), child->current_frame_host()->GetLastCommittedOrigin()); // With OOPIFs, this navigation used a cross-process transfer. Ensure that // the iframe's old RFH still has correct origin, even though it's pending // deletion. if (AreAllSitesIsolatedForTesting()) { EXPECT_FALSE(child_rfh_b->is_active()); EXPECT_NE(child_rfh_b, child->current_frame_host()); EXPECT_EQ(url::Origin::Create(url_b), child_rfh_b->GetLastCommittedOrigin()); } } // Ensure that loading a page with cross-site coreferencing iframes does not // cause an infinite number of nested iframes to be created. // See https://crbug.com/650332. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, CoReferencingFrames) { // Load a page with a cross-site coreferencing iframe. "Coreferencing" here // refers to two separate pages that contain subframes with URLs to each // other. StartEmbeddedServer(); GURL url_1( embedded_test_server()->GetURL("a.com", "/coreferencingframe_1.html")); EXPECT_TRUE(NavigateToURL(shell(), url_1)); WebContentsImpl* web_contents = static_cast<WebContentsImpl*>(shell()->web_contents()); FrameTreeNode* root = web_contents->GetFrameTree()->root(); // The FrameTree contains two successful instances of each site plus an // unsuccessfully-navigated third instance of B with a blank URL. When not in // site-per-process mode, the FrameTreeVisualizer depicts all nodes as // referencing Site A because iframes are identified with their root site. if (AreAllSitesIsolatedForTesting()) { EXPECT_EQ( " Site A ------------ proxies for B\n" " +--Site B ------- proxies for A\n" " +--Site A -- proxies for B\n" " +--Site B -- proxies for A\n" " +--Site B -- proxies for A\n" "Where A = http://a.com/\n" " B = http://b.com/", FrameTreeVisualizer().DepictFrameTree(root)); } else { EXPECT_EQ( " Site A\n" " +--Site A\n" " +--Site A\n" " +--Site A\n" " +--Site A\n" "Where A = http://a.com/", FrameTreeVisualizer().DepictFrameTree(root)); } FrameTreeNode* bottom_child = root->child_at(0)->child_at(0)->child_at(0)->child_at(0); EXPECT_TRUE(bottom_child->current_url().is_empty()); EXPECT_FALSE(bottom_child->has_committed_real_load()); } // Ensures that nested subframes with the same URL but different fragments can // only be nested once. See https://crbug.com/650332. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, SelfReferencingFragmentFrames) { StartEmbeddedServer(); GURL url( embedded_test_server()->GetURL("a.com", "/page_with_iframe.html#123")); EXPECT_TRUE(NavigateToURL(shell(), url)); WebContentsImpl* web_contents = static_cast<WebContentsImpl*>(shell()->web_contents()); FrameTreeNode* root = web_contents->GetFrameTree()->root(); FrameTreeNode* child = root->child_at(0); // ExecuteScript is used here and once more below because it is important to // use renderer-initiated navigations since browser-initiated navigations are // bypassed in the self-referencing navigation check. TestFrameNavigationObserver observer1(child); EXPECT_TRUE( ExecuteScript(child, "location.href = '" + url.spec() + "456" + "';")); observer1.Wait(); FrameTreeNode* grandchild = child->child_at(0); GURL expected_url(embedded_test_server()->GetURL("a.com", "/title1.html")); EXPECT_EQ(expected_url, grandchild->current_url()); // This navigation should be blocked. GURL blocked_url(embedded_test_server()->GetURL( "a.com", "/page_with_iframe.html#123456789")); TestNavigationManager manager(web_contents, blocked_url); EXPECT_TRUE(ExecuteScript(grandchild, "location.href = '" + blocked_url.spec() + "';")); // Wait for WillStartRequest and verify that the request is aborted before // starting it. EXPECT_FALSE(manager.WaitForRequestStart()); WaitForLoadStop(web_contents); // The FrameTree contains two successful instances of the url plus an // unsuccessfully-navigated third instance with a blank URL. EXPECT_EQ( " Site A\n" " +--Site A\n" " +--Site A\n" "Where A = http://a.com/", FrameTreeVisualizer().DepictFrameTree(root)); // The URL of the grandchild has not changed. EXPECT_EQ(expected_url, grandchild->current_url()); } // Ensure that loading a page with a meta refresh iframe does not cause an // infinite number of nested iframes to be created. This test loads a page with // an about:blank iframe where the page injects html containing a meta refresh // into the iframe. This test then checks that this does not cause infinite // nested iframes to be created. See https://crbug.com/527367. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, SelfReferencingMetaRefreshFrames) { // Load a page with a blank iframe. StartEmbeddedServer(); GURL url(embedded_test_server()->GetURL( "a.com", "/page_with_meta_refresh_frame.html")); NavigateToURLBlockUntilNavigationsComplete(shell(), url, 3); WebContentsImpl* web_contents = static_cast<WebContentsImpl*>(shell()->web_contents()); FrameTreeNode* root = web_contents->GetFrameTree()->root(); // The third navigation should fail and be cancelled, leaving a FrameTree with // a height of 2. EXPECT_EQ( " Site A\n" " +--Site A\n" " +--Site A\n" "Where A = http://a.com/", FrameTreeVisualizer().DepictFrameTree(root)); EXPECT_EQ(GURL(url::kAboutBlankURL), root->child_at(0)->child_at(0)->current_url()); EXPECT_FALSE(root->child_at(0)->child_at(0)->has_committed_real_load()); } // Ensure that navigating a subframe to the same URL as its parent twice in a // row is not blocked by the self-reference check. // See https://crbug.com/650332. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, SelfReferencingSameURLRenavigation) { StartEmbeddedServer(); GURL first_url( embedded_test_server()->GetURL("a.com", "/page_with_iframe.html")); GURL second_url(first_url.spec() + "#123"); EXPECT_TRUE(NavigateToURL(shell(), first_url)); WebContentsImpl* web_contents = static_cast<WebContentsImpl*>(shell()->web_contents()); FrameTreeNode* root = web_contents->GetFrameTree()->root(); FrameTreeNode* child = root->child_at(0); TestFrameNavigationObserver observer1(child); EXPECT_TRUE( ExecuteScript(child, "location.href = '" + second_url.spec() + "';")); observer1.Wait(); EXPECT_EQ(child->current_url(), second_url); TestFrameNavigationObserver observer2(child); // This navigation shouldn't be blocked. Blocking should only occur when more // than one ancestor has the same URL (excluding fragments), and the // navigating frame's current URL shouldn't count toward that. EXPECT_TRUE( ExecuteScript(child, "location.href = '" + first_url.spec() + "';")); observer2.Wait(); EXPECT_EQ(child->current_url(), first_url); } // Ensures that POST requests bypass self-referential URL checks. See // https://crbug.com/710008. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, SelfReferencingFramesWithPOST) { StartEmbeddedServer(); GURL url(embedded_test_server()->GetURL("a.com", "/page_with_iframe.html")); EXPECT_TRUE(NavigateToURL(shell(), url)); WebContentsImpl* web_contents = static_cast<WebContentsImpl*>(shell()->web_contents()); FrameTreeNode* root = web_contents->GetFrameTree()->root(); FrameTreeNode* child = root->child_at(0); GURL child_url(embedded_test_server()->GetURL("a.com", "/title1.html")); EXPECT_EQ(url, root->current_url()); EXPECT_EQ(child_url, child->current_url()); // Navigate the child frame to the same URL as parent via POST. std::string script = "var f = document.createElement('form');\n" "f.method = 'POST';\n" "f.action = '/page_with_iframe.html';\n" "document.body.appendChild(f);\n" "f.submit();"; { TestFrameNavigationObserver observer(child); EXPECT_TRUE(ExecuteScript(child, script)); observer.Wait(); } FrameTreeNode* grandchild = child->child_at(0); EXPECT_EQ(url, child->current_url()); EXPECT_EQ(child_url, grandchild->current_url()); // Now navigate the grandchild to the same URL as its two ancestors. This // should be allowed since it uses POST; it was blocked prior to // fixing https://crbug.com/710008. { TestFrameNavigationObserver observer(grandchild); EXPECT_TRUE(ExecuteScript(grandchild, script)); observer.Wait(); } EXPECT_EQ(url, grandchild->current_url()); ASSERT_EQ(1U, grandchild->child_count()); EXPECT_EQ(child_url, grandchild->child_at(0)->current_url()); } // Ensures that we don't reset a speculative RFH if a JavaScript URL is loaded // while there's an ongoing cross-process navigation. See // https://crbug.com/793432. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, JavaScriptLoadDoesntResetSpeculativeRFH) { EXPECT_TRUE(embedded_test_server()->Start()); GURL site1 = embedded_test_server()->GetURL("a.com", "/title1.html"); GURL site2 = embedded_test_server()->GetURL("b.com", "/title2.html"); NavigateToURL(shell(), site1); TestNavigationManager cross_site_navigation(shell()->web_contents(), site2); shell()->LoadURL(site2); EXPECT_TRUE(cross_site_navigation.WaitForRequestStart()); RenderFrameHostImpl* speculative_rfh = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root() ->render_manager() ->speculative_frame_host(); CHECK(speculative_rfh); shell()->web_contents()->GetController().LoadURL( GURL("javascript:(0)"), Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); cross_site_navigation.ResumeNavigation(); // No crash means everything worked! } // Test that unrelated browsing contexts cannot find each other's windows, // even when they end up using the same renderer process (e.g. because of // hitting a process limit). See also https://crbug.com/718489. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, ProcessReuseVsBrowsingInstance) { // Set max renderers to 1 to force reusing a renderer process between two // unrelated tabs. RenderProcessHost::SetMaxRendererProcessCount(1); // Navigate 2 tabs to a web page (regular web pages can share renderers // among themselves without any restrictions, unlike extensions, apps, etc.). ASSERT_TRUE(embedded_test_server()->Start()); GURL url1(embedded_test_server()->GetURL("/title1.html")); EXPECT_TRUE(NavigateToURL(shell(), url1)); RenderFrameHost* tab1 = shell()->web_contents()->GetMainFrame(); EXPECT_EQ(url1, tab1->GetLastCommittedURL()); GURL url2(embedded_test_server()->GetURL("/title2.html")); Shell* shell2 = Shell::CreateNewWindow( shell()->web_contents()->GetBrowserContext(), url2, nullptr, gfx::Size()); EXPECT_TRUE(NavigateToURL(shell2, url2)); RenderFrameHost* tab2 = shell2->web_contents()->GetMainFrame(); EXPECT_EQ(url2, tab2->GetLastCommittedURL()); // Sanity-check test setup: 2 frames share a renderer process, but are not in // a related browsing instance. if (!AreAllSitesIsolatedForTesting()) EXPECT_EQ(tab1->GetProcess(), tab2->GetProcess()); EXPECT_FALSE( tab1->GetSiteInstance()->IsRelatedSiteInstance(tab2->GetSiteInstance())); // Name the 2 frames. EXPECT_TRUE(ExecuteScript(tab1, "window.name = 'tab1';")); EXPECT_TRUE(ExecuteScript(tab2, "window.name = 'tab2';")); // Verify that |tab1| cannot find named frames belonging to |tab2| (i.e. that // window.open will end up creating a new tab rather than returning the old // |tab2| tab). WebContentsAddedObserver new_contents_observer; std::string location_of_opened_window; EXPECT_TRUE(ExecuteScriptAndExtractString( tab1, "var w = window.open('', 'tab2');\n" "window.domAutomationController.send(w.location.href);", &location_of_opened_window)); EXPECT_EQ(url::kAboutBlankURL, location_of_opened_window); EXPECT_TRUE(new_contents_observer.GetWebContents()); } // Verify that cross-site main frame navigations will swap BrowsingInstances // for certain browser-initiated navigations, such as user typing the URL into // the address bar. This helps avoid unneeded process sharing and should // happen even if the current frame has an opener. See // https://crbug.com/803367. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, BrowserInitiatedNavigationsSwapBrowsingInstance) { ASSERT_TRUE(embedded_test_server()->Start()); // Start with a page on a.com. GURL a_url(embedded_test_server()->GetURL("a.com", "/title1.html")); EXPECT_TRUE(NavigateToURL(shell(), a_url)); scoped_refptr<SiteInstance> a_site_instance( shell()->web_contents()->GetSiteInstance()); // Open a popup for b.com. This should stay in the current BrowsingInstance. GURL b_url(embedded_test_server()->GetURL("b.com", "/title1.html")); Shell* popup = OpenPopup(shell(), b_url, "foo"); EXPECT_TRUE(WaitForLoadStop(popup->web_contents())); scoped_refptr<SiteInstance> b_site_instance( popup->web_contents()->GetSiteInstance()); EXPECT_TRUE(a_site_instance->IsRelatedSiteInstance(b_site_instance.get())); // Same-site browser-initiated navigations shouldn't swap BrowsingInstances // or SiteInstances. EXPECT_TRUE(NavigateToURL( popup, embedded_test_server()->GetURL("b.com", "/title2.html"))); EXPECT_EQ(b_site_instance, popup->web_contents()->GetSiteInstance()); // A cross-site browser-initiated navigation should swap BrowsingInstances, // despite having an opener in the same site as the destination URL. EXPECT_TRUE(NavigateToURL( popup, embedded_test_server()->GetURL("a.com", "/title3.html"))); EXPECT_NE(b_site_instance, popup->web_contents()->GetSiteInstance()); EXPECT_NE(a_site_instance, popup->web_contents()->GetSiteInstance()); EXPECT_FALSE(a_site_instance->IsRelatedSiteInstance( popup->web_contents()->GetSiteInstance())); EXPECT_FALSE(b_site_instance->IsRelatedSiteInstance( popup->web_contents()->GetSiteInstance())); // Perform several cross-site browser-initiated navigations in the popup, all // using page transitions that allow BrowsingInstance swaps: auto transitions_that_swap_browsing_instances = { ui::PAGE_TRANSITION_TYPED, /* user typing URL into address bar */ ui::PAGE_TRANSITION_AUTO_BOOKMARK, /* user clicking on a bookmark */ ui::PAGE_TRANSITION_GENERATED, /* search query */ ui::PAGE_TRANSITION_KEYWORD, /* search within a site from address bar */ }; int current_site = 0; for (auto transition : transitions_that_swap_browsing_instances) { GURL cross_site_url(embedded_test_server()->GetURL( base::StringPrintf("site%d.com", current_site++), "/title1.html")); scoped_refptr<SiteInstance> prev_instance( popup->web_contents()->GetSiteInstance()); SCOPED_TRACE(base::StringPrintf( "... expected BrowsingInstance swap for '%s' transition to %s", ui::PageTransitionGetCoreTransitionString(transition), cross_site_url.spec().c_str())); TestNavigationObserver observer(popup->web_contents()); NavigationController::LoadURLParams params(cross_site_url); params.transition_type = transition; popup->web_contents()->GetController().LoadURLWithParams(params); observer.Wait(); // This should swap BrowsingInstances. scoped_refptr<SiteInstance> curr_instance( popup->web_contents()->GetSiteInstance()); EXPECT_NE(a_site_instance, curr_instance); EXPECT_FALSE(a_site_instance->IsRelatedSiteInstance(curr_instance.get())); EXPECT_NE(prev_instance, curr_instance); EXPECT_FALSE(prev_instance->IsRelatedSiteInstance(curr_instance.get())); } // Ensure that other page transitions don't cause a BrowsingInstance swap. auto transitions_that_dont_swap_browsing_instances = { ui::PAGE_TRANSITION_LINK, ui::PAGE_TRANSITION_AUTO_TOPLEVEL, ui::PAGE_TRANSITION_FORM_SUBMIT, }; scoped_refptr<SiteInstance> curr_instance( popup->web_contents()->GetSiteInstance()); for (auto transition : transitions_that_dont_swap_browsing_instances) { GURL cross_site_url(embedded_test_server()->GetURL( base::StringPrintf("site%d.com", current_site++), "/title1.html")); SCOPED_TRACE(base::StringPrintf( "... expected no BrowsingInstance swap for '%s' transition to %s", ui::PageTransitionGetCoreTransitionString(transition), cross_site_url.spec().c_str())); TestNavigationObserver observer(popup->web_contents()); NavigationController::LoadURLParams params(cross_site_url); params.transition_type = transition; popup->web_contents()->GetController().LoadURLWithParams(params); observer.Wait(); // This should stay in the current BrowsingInstance. EXPECT_TRUE(curr_instance->IsRelatedSiteInstance( popup->web_contents()->GetSiteInstance())); } } // Ensure that these two browser-initiated navigations: // foo.com -> about:blank -> foo.com // stay in the same SiteInstance. This isn't technically required for // correctness, but some tests (e.g., testEnsureHotFromScratch from // telemetry_unittests) currently depend on this behavior. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, NavigateToAndFromAboutBlank) { ASSERT_TRUE(embedded_test_server()->Start()); GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title1.html")); EXPECT_TRUE(NavigateToURL(shell(), foo_url)); scoped_refptr<SiteInstance> site_instance( shell()->web_contents()->GetSiteInstance()); // Navigate to about:blank from address bar. This stays in the foo.com // SiteInstance. EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL))); EXPECT_EQ(site_instance, shell()->web_contents()->GetSiteInstance()); // Perform a browser-initiated navigation to foo.com. This should also stay // in the original foo.com SiteInstance and BrowsingInstance. EXPECT_TRUE(NavigateToURL(shell(), foo_url)); EXPECT_EQ(site_instance, shell()->web_contents()->GetSiteInstance()); } // Check that with the following sequence of navigations: // foo.com -(1)-> bar.com -(2)-> about:blank -(3)-> foo.com // where (1) is renderer-initiated and (2)+(3) are browser-initiated, the last // navigation goes back to the first SiteInstance without --site-per-process, // and to a new SiteInstance and BrowsingInstance with --site-per-process. IN_PROC_BROWSER_TEST_F(RenderFrameHostManagerTest, NavigateToFooThenBarThenAboutBlankThenFoo) { ASSERT_TRUE(embedded_test_server()->Start()); GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title1.html")); EXPECT_TRUE(NavigateToURL(shell(), foo_url)); scoped_refptr<SiteInstance> site_instance( shell()->web_contents()->GetSiteInstance()); // Do a renderer-initiated navigation to bar.com, then navigate to // about:blank from address bar, then back to foo.com. GURL bar_url(embedded_test_server()->GetURL("bar.com", "/title1.html")); EXPECT_TRUE(NavigateToURLFromRenderer(shell(), bar_url)); EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL))); EXPECT_TRUE(NavigateToURL(shell(), foo_url)); // This should again go back to the original foo.com SiteInstance without // --site-per-process, as in that case both the bar.com and // about:blank navigation will stay in the foo.com SiteInstance, and the // final navigation to foo.com will be considered same-site with the current // SiteInstance. // // With --site-per-process, bar.com should get its own SiteInstance, the // about:blank navigation will stay in it, and thus the final foo.com // navigation should be considered cross-site from the current SiteInstance. // Since this is a browser-initiated, cross-site navigation, it will swap // BrowsingInstances, and create a new foo.com SiteInstance, distinct from // the initial one. if (!AreAllSitesIsolatedForTesting()) { EXPECT_EQ(site_instance, shell()->web_contents()->GetSiteInstance()); } else { EXPECT_NE(site_instance, shell()->web_contents()->GetSiteInstance()); EXPECT_FALSE(site_instance->IsRelatedSiteInstance( shell()->web_contents()->GetSiteInstance())); EXPECT_EQ(site_instance->GetSiteURL(), shell()->web_contents()->GetSiteInstance()->GetSiteURL()); } } } // namespace content
null
null
null
null
21,070
8,890
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
8,890
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 NET_HTTP2_HTTP2_CONSTANTS_TEST_UTIL_H_ #define NET_HTTP2_HTTP2_CONSTANTS_TEST_UTIL_H_ #include <vector> #include "net/http2/http2_constants.h" namespace net { namespace test { // Returns a vector of all supported RST_STREAM and GOAWAY error codes. std::vector<Http2ErrorCode> AllHttp2ErrorCodes(); // Returns a vector of all supported parameters in SETTINGS frames. std::vector<Http2SettingsParameter> AllHttp2SettingsParameters(); // Returns a mask of flags supported for the specified frame type. Returns // zero for unknown frame types. uint8_t KnownFlagsMaskForFrameType(Http2FrameType type); // Returns a mask of flag bits known to be invalid for the frame type. // For unknown frame types, the mask is zero; i.e., we don't know that any // are invalid. uint8_t InvalidFlagMaskForFrameType(Http2FrameType type); } // namespace test } // namespace net #endif // NET_HTTP2_HTTP2_CONSTANTS_TEST_UTIL_H_
null
null
null
null
5,753
23,311
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
23,311
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 "content/browser/loader/source_stream_to_data_pipe.h" #include "base/bind.h" #include "net/filter/source_stream.h" namespace content { SourceStreamToDataPipe::SourceStreamToDataPipe( std::unique_ptr<net::SourceStream> source, mojo::ScopedDataPipeProducerHandle dest, base::OnceCallback<void(int)> completion_callback) : source_(std::move(source)), dest_(std::move(dest)), completion_callback_(std::move(completion_callback)), writable_handle_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL, base::SequencedTaskRunnerHandle::Get()), weak_factory_(this) { writable_handle_watcher_.Watch( dest_.get(), MOJO_HANDLE_SIGNAL_WRITABLE, base::BindRepeating(&SourceStreamToDataPipe::OnDataPipeWritable, base::Unretained(this))); } SourceStreamToDataPipe::~SourceStreamToDataPipe() = default; void SourceStreamToDataPipe::Start() { ReadMore(); } void SourceStreamToDataPipe::ReadMore() { DCHECK(!pending_write_.get()); uint32_t num_bytes; MojoResult mojo_result = network::NetToMojoPendingBuffer::BeginWrite( &dest_, &pending_write_, &num_bytes); if (mojo_result == MOJO_RESULT_SHOULD_WAIT) { // The pipe is full. We need to wait for it to have more space. writable_handle_watcher_.ArmOrNotify(); return; } else if (mojo_result == MOJO_RESULT_FAILED_PRECONDITION) { // The data pipe consumer handle has been closed. OnComplete(net::ERR_ABORTED); return; } else if (mojo_result != MOJO_RESULT_OK) { // The body stream is in a bad state. Bail out. OnComplete(net::ERR_UNEXPECTED); return; } scoped_refptr<net::IOBuffer> buffer( new network::NetToMojoIOBuffer(pending_write_.get())); int result = source_->Read(buffer.get(), base::checked_cast<int>(num_bytes), base::BindRepeating(&SourceStreamToDataPipe::DidRead, base::Unretained(this))); if (result != net::ERR_IO_PENDING) DidRead(result); } void SourceStreamToDataPipe::DidRead(int result) { DCHECK(pending_write_); if (result < 0) { // An error case. OnComplete(result); return; } if (result == 0) { pending_write_->Complete(0); OnComplete(net::OK); return; } dest_ = pending_write_->Complete(result); pending_write_ = nullptr; base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&SourceStreamToDataPipe::ReadMore, weak_factory_.GetWeakPtr())); } void SourceStreamToDataPipe::OnDataPipeWritable(MojoResult result) { if (result == MOJO_RESULT_FAILED_PRECONDITION) { OnComplete(net::ERR_ABORTED); return; } DCHECK_EQ(result, MOJO_RESULT_OK) << result; ReadMore(); } void SourceStreamToDataPipe::OnComplete(int result) { // Resets the watchers, pipes and the exchange handler, so that // we will never be called back. writable_handle_watcher_.Cancel(); pending_write_ = nullptr; // Closes the data pipe if this was holding it. dest_.reset(); std::move(completion_callback_).Run(result); } } // namespace content
null
null
null
null
20,174