repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
akurtakov/Pydev
plugins/org.python.pydev.parser/src/org/python/pydev/parser/jython/ast/decoratorsType.java
5723
// Autogenerated AST node package org.python.pydev.parser.jython.ast; import org.python.pydev.parser.jython.SimpleNode; import java.util.Arrays; public final class decoratorsType extends SimpleNode { public exprType func; public exprType[] args; public keywordType[] keywords; public exprType starargs; public exprType kwargs; public boolean isCall; public decoratorsType(exprType func, exprType[] args, keywordType[] keywords, exprType starargs, exprType kwargs, boolean isCall) { this.func = func; this.args = args; this.keywords = keywords; this.starargs = starargs; this.kwargs = kwargs; this.isCall = isCall; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((func == null) ? 0 : func.hashCode()); result = prime * result + Arrays.hashCode(args); result = prime * result + Arrays.hashCode(keywords); result = prime * result + ((starargs == null) ? 0 : starargs.hashCode()); result = prime * result + ((kwargs == null) ? 0 : kwargs.hashCode()); result = prime * result + (isCall ? 17 : 137); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; decoratorsType other = (decoratorsType) obj; if (func == null) { if (other.func != null) return false;} else if (!func.equals(other.func)) return false; if (!Arrays.equals(args, other.args)) return false; if (!Arrays.equals(keywords, other.keywords)) return false; if (starargs == null) { if (other.starargs != null) return false;} else if (!starargs.equals(other.starargs)) return false; if (kwargs == null) { if (other.kwargs != null) return false;} else if (!kwargs.equals(other.kwargs)) return false; if(this.isCall != other.isCall) return false; return true; } @Override public decoratorsType createCopy() { return createCopy(true); } @Override public decoratorsType createCopy(boolean copyComments) { exprType[] new0; if(this.args != null){ new0 = new exprType[this.args.length]; for(int i=0;i<this.args.length;i++){ new0[i] = (exprType) (this.args[i] != null? this.args[i].createCopy(copyComments):null); } }else{ new0 = this.args; } keywordType[] new1; if(this.keywords != null){ new1 = new keywordType[this.keywords.length]; for(int i=0;i<this.keywords.length;i++){ new1[i] = (keywordType) (this.keywords[i] != null? this.keywords[i].createCopy(copyComments):null); } }else{ new1 = this.keywords; } decoratorsType temp = new decoratorsType(func!=null?(exprType)func.createCopy(copyComments):null, new0, new1, starargs!=null?(exprType)starargs.createCopy(copyComments):null, kwargs!=null?(exprType)kwargs.createCopy(copyComments):null, isCall); temp.beginLine = this.beginLine; temp.beginColumn = this.beginColumn; if(this.specialsBefore != null && copyComments){ for(Object o:this.specialsBefore){ if(o instanceof commentType){ commentType commentType = (commentType) o; temp.getSpecialsBefore().add(commentType.createCopy(copyComments)); } } } if(this.specialsAfter != null && copyComments){ for(Object o:this.specialsAfter){ if(o instanceof commentType){ commentType commentType = (commentType) o; temp.getSpecialsAfter().add(commentType.createCopy(copyComments)); } } } return temp; } @Override public String toString() { StringBuffer sb = new StringBuffer("decorators["); sb.append("func="); sb.append(dumpThis(this.func)); sb.append(", "); sb.append("args="); sb.append(dumpThis(this.args)); sb.append(", "); sb.append("keywords="); sb.append(dumpThis(this.keywords)); sb.append(", "); sb.append("starargs="); sb.append(dumpThis(this.starargs)); sb.append(", "); sb.append("kwargs="); sb.append(dumpThis(this.kwargs)); sb.append(", "); sb.append("isCall="); sb.append(dumpThis(this.isCall)); sb.append("]"); return sb.toString(); } @Override public Object accept(VisitorIF visitor) throws Exception { if (visitor instanceof VisitorBase) { ((VisitorBase) visitor).traverse(this); } else { traverse(visitor); } return null; } @Override public void traverse(VisitorIF visitor) throws Exception { if (func != null) { func.accept(visitor); } if (args != null) { for (int i = 0; i < args.length; i++) { if (args[i] != null) { args[i].accept(visitor); } } } if (keywords != null) { for (int i = 0; i < keywords.length; i++) { if (keywords[i] != null) { keywords[i].accept(visitor); } } } if (starargs != null) { starargs.accept(visitor); } if (kwargs != null) { kwargs.accept(visitor); } } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.logstash.collector.1.0/src/com/ibm/ws/logstash/collector/v10/LogstashCollector10.java
1247
/******************************************************************************* * Copyright (c) 2016 IBM Corporation and others. * 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 * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.logstash.collector.v10; import org.osgi.framework.Version; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import com.ibm.ws.logstash.collector.LogstashRuntimeVersion; @Component(name = LogstashCollector10.COMPONENT_NAME, service = { LogstashRuntimeVersion.class }, configurationPolicy = ConfigurationPolicy.IGNORE, property = { "service.vendor=IBM" }) public class LogstashCollector10 implements LogstashRuntimeVersion { public static final String COMPONENT_NAME = "com.ibm.ws.logstash.collector.v10.LogstashCollector10"; @Override public Version getVersion() { return VERSION_1_0; } }
epl-1.0
christ66/coverity-plugin
src/main/java/com/coverity/ws/v9/UpdateStreamDefects.java
2691
package com.coverity.ws.v9; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for updateStreamDefects complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="updateStreamDefects"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="streamDefectIds" type="{http://ws.coverity.com/v9}streamDefectIdDataObj" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="defectStateSpec" type="{http://ws.coverity.com/v9}defectStateSpecDataObj" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "updateStreamDefects", propOrder = { "streamDefectIds", "defectStateSpec" }) public class UpdateStreamDefects { protected List<StreamDefectIdDataObj> streamDefectIds; protected DefectStateSpecDataObj defectStateSpec; /** * Gets the value of the streamDefectIds property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the streamDefectIds property. * * <p> * For example, to add a new item, do as follows: * <pre> * getStreamDefectIds().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link StreamDefectIdDataObj } * * */ public List<StreamDefectIdDataObj> getStreamDefectIds() { if (streamDefectIds == null) { streamDefectIds = new ArrayList<StreamDefectIdDataObj>(); } return this.streamDefectIds; } /** * Gets the value of the defectStateSpec property. * * @return * possible object is * {@link DefectStateSpecDataObj } * */ public DefectStateSpecDataObj getDefectStateSpec() { return defectStateSpec; } /** * Sets the value of the defectStateSpec property. * * @param value * allowed object is * {@link DefectStateSpecDataObj } * */ public void setDefectStateSpec(DefectStateSpecDataObj value) { this.defectStateSpec = value; } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.jpa.tests.spec10.entity_fat.common/test-applications/entity/src/com/ibm/ws/jpa/fvt/entity/testlogic/enums/DatatypeSupportEntityEnum.java
3918
/******************************************************************************* * Copyright (c) 2021 IBM Corporation and others. * 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 * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.jpa.fvt.entity.testlogic.enums; import com.ibm.ws.testtooling.testlogic.JPAEntityClassEnum; public enum DatatypeSupportEntityEnum implements JPAEntityClassEnum { DatatypeSupportPropertyTestEntity { @Override public String getEntityClassName() { return "com.ibm.ws.jpa.fvt.entity.entities.datatype.annotation.DatatypeSupportPropertyTestEntity"; } @Override public String getEntityName() { return "DatatypeSupportPropertyTestEntity"; } }, DatatypeSupportTestEntity { @Override public String getEntityClassName() { return "com.ibm.ws.jpa.fvt.entity.entities.datatype.annotation.DatatypeSupportTestEntity"; } @Override public String getEntityName() { return "DatatypeSupportTestEntity"; } }, SerializableDatatypeSupportPropertyTestEntity { @Override public String getEntityClassName() { return "com.ibm.ws.jpa.fvt.entity.entities.datatype.annotation.SerializableDatatypeSupportPropertyTestEntity"; } @Override public String getEntityName() { return "SerializableDatatypeSupportPropertyTestEntity"; } }, SerializableDatatypeSupportTestEntity { @Override public String getEntityClassName() { return "com.ibm.ws.jpa.fvt.entity.entities.datatype.annotation.SerializableDatatypeSupportTestEntity"; } @Override public String getEntityName() { return "SerializableDatatypeSupportTestEntity"; } }, XMLDatatypeSupportPropertyTestEntity { @Override public String getEntityClassName() { return "com.ibm.ws.jpa.fvt.entity.entities.datatype.xml.XMLDatatypeSupportPropertyTestEntity"; } @Override public String getEntityName() { return "XMLDatatypeSupportPropertyTestEntity"; } }, XMLDatatypeSupportTestEntity { @Override public String getEntityClassName() { return "com.ibm.ws.jpa.fvt.entity.entities.datatype.xml.XMLDatatypeSupportPropertyTestEntity"; } @Override public String getEntityName() { return "XMLDatatypeSupportPropertyTestEntity"; } }, SerializableXMLDatatypeSupportPropertyTestEntity { @Override public String getEntityClassName() { return "com.ibm.ws.jpa.fvt.entity.entities.datatype.xml.SerializableXMLDatatypeSupportPropertyTestEntity"; } @Override public String getEntityName() { return "SerializableXMLDatatypeSupportPropertyTestEntity"; } }, SerializableXMLDatatypeSupportTestEntity { @Override public String getEntityClassName() { return "com.ibm.ws.jpa.fvt.entity.entities.datatype.xml.SerializableXMLDatatypeSupportTestEntity"; } @Override public String getEntityName() { return "SerializableXMLDatatypeSupportTestEntity"; } }; @Override public abstract String getEntityClassName(); @Override public abstract String getEntityName(); public static DatatypeSupportEntityEnum resolveEntityByName(String entityName) { return DatatypeSupportEntityEnum.valueOf(entityName); } }
epl-1.0
dlindhol/LaTiS
src/main/scala/latis/dm/Variable3.scala
6589
package latis.dm import latis.metadata._ import latis.data.Data import java.util.UUID import latis.data.value._ trait Variable3 { def metadata: VariableMetadata3 } abstract class AVariable3(md: VariableMetadata3) extends Variable3 { def metadata: VariableMetadata3 = md // def getMetadata(name: String): Option[String] = metadata.get(name) // // def getType: String = metadata.getOrElse("type", "undefined") //TODO: require type? // // lazy val getId: String = getMetadata("id") match { // case Some(id) => id // case None => UUID.randomUUID.toString.take(8) // //TODO: what about the orig id in the metadata!? // // move to smart constructor // } // // def hasName(name: String): Boolean = metadata.hasName(name) } //---- Scalar ----------------------------------------------------------------- trait Scalar3[T] extends Variable3 { def value: T } //value can be lazy val or def abstract class AScalar3[T](_value: => T)(metadata: ScalarMetadata) extends AVariable3(metadata) with Scalar3[T] { //hang onto value after first eval def value: T = v private lazy val v = _value } object Scalar3 { //Ambiguous due to type erasure Function0[T] // def apply(_value: => Long)(md: ScalarMetadata): Integer3 = new Scalar3(_value)(md) with Integer3 // def apply(_value: => Double)(md: ScalarMetadata): Real3 = new Scalar3(_value)(md) with Real3 // def apply(_value: => String)(md: ScalarMetadata): Text3 = new Scalar3(_value)(md) with Text3 def apply[T](value: => T)(md: ScalarMetadata) = md.getType match { //def apply(value: Any)(md: ScalarMetadata) = md.getType match { //TODO: implicit evidence for Long...? case "integer" => new AScalar3(value.asInstanceOf[Long])(md) with Integer3 case "real" => new AScalar3(value.asInstanceOf[Double])(md) with Real3 case "text" => new AScalar3(value.asInstanceOf[String])(md) with Text3 case _ => ??? } //matching specific type is preferred, avoid cast //def unapply(s: Scalar3[_]): Option[Any] = Option(s.value) } trait Integer3 extends Scalar3[Long] object Integer3 { // def apply(l: Long): Integer3 = { // val props = Seq("id" -> "unknown", "type" -> "integer").toMap // val md = ScalarMetadata(props) // new Scalar3(l)(md) with Integer3 // } def unapply(s: Integer3): Option[Long] = Option(s.value) /* * TODO: convert type from native form * e.g. AsciiAdapter might still have it as a string * use a pattern match in Scalar that uses type from md? * construct as one of these types (based on md type) * even if it returns other type * e.g. Interger3(StringValue("1")) * Note, the only thing that knows the native type is the Data * so we can't drop Data and just use Any * or should the extraction function include the conversion? * Do we even need Data? * Spark uses Any (but specifies types in schema) * * How will this work with Time * still need Real... as traits * * With lazy value arg we will need a new instance of Sample3 for each sample * otherwise all samples will end up with the same value * what is the cost of wrapping all samples? * The earlier approach of using a function would work * but that adds complications to operations * if backed by "getNext" in adapter, we can call only once * but it does seem dicey to reuse the same Sample instance * getNext could be wrapped by another lazy function in some cases * cases where it can't? * sliding iterator for interpolation? * each element becomes a List[Sample] * parallelization * would a distinction between inner and outer Functions help? * the inner is expected to be memoized (for now, at least) * live with new Sample instances for now * no worse than before * * Should we be able to read then write ascii (string) without parsing values? * writer would ask for the format it wants * just like binary writer wants bytes * match Scalar then call getString or getBytes...? * otherwise it would match on Integer, Real,... * would only work if no ops * seems like an optimization to save for later */ } //TODO: is it worth trying this approach? //trait Real3 { this: Scalar3[Double] => } trait Real3 extends Scalar3[Double] object Real3 { def unapply(s: Real3): Option[Double] = Option(s.value) } trait Text3 extends Scalar3[String] object Text3 { //def unapply(s: Scalar3[_]): Option[String] = Option(s.value.asInstanceOf[String]) def unapply(s: Text3): Option[String] = Option(s.value) } trait Index3 extends Scalar3[Int] object Index3 { def apply(): Index3 = { var index = -1 def f: Int = { index += 1 index } val props = Seq("id" -> "index", "type" -> "index").toMap val md = ScalarMetadata(props) new AScalar3[Int](f)(md) with Index3 } def unapply(s: Index3): Option[Int] = Option(s.value) } //---- Tuple ------------------------------------------------------------------ class Tuple3(val variables: Seq[Variable3]) (metadata: TupleMetadata) extends AVariable3(metadata) { lazy val arity = variables.length } object Tuple3 { def apply(variables: Seq[Variable3])(properties: Map[String,String] = Map.empty) = { val md = TupleMetadata(variables.map(_.metadata))(properties) new Tuple3(variables)(md) } def unapplySeq(tuple: Tuple3): Option[Seq[Variable3]] = Option(tuple.variables) } //---- Function --------------------------------------------------------------- //TODO: continuous function //class Function3(f: Variable3 => Variable3) abstract class Function3(metadata: FunctionMetadata) extends AVariable3(metadata) { //def apply(arg: Variable3): Variable3 = f(arg) } //trait SampledFunction3 { this: Function3 => //class SampledFunction3(f: Variable3 => Variable3) //TODO: implicit Interpolation, or encapsulate in "f"? class SampledFunction3(iterable: Iterable[Sample3]) (metadata: FunctionMetadata) extends Function3(metadata) { def iterator: Iterator[Sample3] = iterable.iterator } /* * TODO: consider inner SampledFunction * no need for iterator? * avoid traversable once problem? */ object SampledFunction3 { def apply(samples: Iterable[Sample3])(metadata: FunctionMetadata) = { new SampledFunction3(samples)(metadata) } def apply(samples: Iterator[Sample3])(metadata: FunctionMetadata) = { val it = new Iterable[Sample3]() { def iterator = samples } new SampledFunction3(it)(metadata) } def unapply(f: SampledFunction3) = Option(f.iterator) } case class Sample3(domain: Variable3, range: Variable3)
epl-1.0
SmithAndr/egit
org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/history/FormatJob.java
3809
/******************************************************************************* * Copyright (C) 2011, Jens Baumgart <[email protected]> * Copyright (C) 2011, Stefan Lay <[email protected]> * Copyright (C) 2015, Thomas Wolf <[email protected]> * * 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.eclipse.egit.ui.internal.history; import java.io.IOException; import java.util.Collection; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.JobFamilies; import org.eclipse.egit.ui.internal.UIText; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revplot.PlotCommit; class FormatJob extends Job { @Override public boolean belongsTo(Object family) { if (JobFamilies.FORMAT_COMMIT_INFO.equals(family)) return true; return super.belongsTo(family); } private Object lock = new Object(); // guards formatRequest and formatResult private FormatRequest formatRequest; private FormatResult formatResult; FormatJob(FormatRequest formatRequest) { super(UIText.FormatJob_buildingCommitInfo); this.formatRequest = formatRequest; } FormatResult getFormatResult() { synchronized(lock) { return formatResult; } } @Override protected IStatus run(IProgressMonitor monitor) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } FormatResult commitInfo; CommitInfoBuilder builder; try { synchronized(lock) { SWTCommit commit = (SWTCommit)formatRequest.getCommit(); commit.parseBody(); builder = new CommitInfoBuilder(formatRequest.getRepository(), commit, formatRequest.isFill(), formatRequest.getAllRefs()); } commitInfo = builder.format(monitor); } catch (IOException e) { return Activator.createErrorStatus(e.getMessage(), e); } if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } synchronized(lock) { formatResult = commitInfo; } return Status.OK_STATUS; } static class FormatRequest { public Collection<Ref> getAllRefs() { return allRefs; } public void setAllRefs(Collection<Ref> allRefs) { this.allRefs = allRefs; } private Repository repository; private PlotCommit<?> commit; private boolean fill; private Collection<Ref> allRefs; FormatRequest(Repository repository, PlotCommit<?> commit, boolean fill, Collection<Ref> allRefs) { this.repository = repository; this.commit = commit; this.fill = fill; this.allRefs = allRefs; } public Repository getRepository() { return repository; } public PlotCommit<?> getCommit() { return commit; } public boolean isFill() { return fill; } } static class FormatResult{ private final String commitInfo; private final List<GitCommitReference> knownLinks; private final int headerEnd; private final int footerStart; FormatResult(String commmitInfo, List<GitCommitReference> links, int headerEnd, int footerStart) { this.commitInfo = commmitInfo; this.knownLinks = links; this.headerEnd = headerEnd; this.footerStart = footerStart; } public String getCommitInfo() { return commitInfo; } public List<GitCommitReference> getKnownLinks() { return knownLinks; } public int getHeaderEnd() { return headerEnd; } public int getFooterStart() { return footerStart; } } }
epl-1.0
my76128/controller
opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGenerator.java
11935
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. 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.opendaylight.controller.config.yangjmxgenerator.plugin; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.apache.maven.project.MavenProject; import org.opendaylight.controller.config.spi.ModuleFactory; import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry; import org.opendaylight.controller.config.yangjmxgenerator.PackageTranslator; import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry; import org.opendaylight.controller.config.yangjmxgenerator.TypeProviderWrapper; import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator; import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class interfaces with yang-maven-plugin. Gets parsed yang modules in * {@link SchemaContext}, and parameters form the plugin configuration, and * writes service interfaces and/or modules. */ public class JMXGenerator implements BasicCodeGenerator, MavenProjectAware { private static final class NamespaceMapping { private final String namespace, packageName; public NamespaceMapping(final String namespace, final String packagename) { this.namespace = namespace; this.packageName = packagename; } } @VisibleForTesting static final String NAMESPACE_TO_PACKAGE_DIVIDER = "=="; @VisibleForTesting static final String NAMESPACE_TO_PACKAGE_PREFIX = "namespaceToPackage"; @VisibleForTesting static final String MODULE_FACTORY_FILE_BOOLEAN = "moduleFactoryFile"; private static final Logger LOG = LoggerFactory.getLogger(JMXGenerator.class); private static final Pattern NAMESPACE_MAPPING_PATTERN = Pattern.compile("(.+)" + NAMESPACE_TO_PACKAGE_DIVIDER + "(.+)"); private PackageTranslator packageTranslator; private final CodeWriter codeWriter; private Map<String, String> namespaceToPackageMapping; private File resourceBaseDir; private File projectBaseDir; private boolean generateModuleFactoryFile = true; public JMXGenerator() { this(new CodeWriter()); } public JMXGenerator(final CodeWriter codeWriter) { this.codeWriter = codeWriter; } @Override public Collection<File> generateSources(final SchemaContext context, final File outputBaseDir, final Set<Module> yangModulesInCurrentMavenModule) { Preconditions.checkArgument(context != null, "Null context received"); Preconditions.checkArgument(outputBaseDir != null, "Null outputBaseDir received"); Preconditions .checkArgument(namespaceToPackageMapping != null && !namespaceToPackageMapping.isEmpty(), "No namespace to package mapping provided in additionalConfiguration"); packageTranslator = new PackageTranslator(namespaceToPackageMapping); if (!outputBaseDir.exists()) { outputBaseDir.mkdirs(); } GeneratedFilesTracker generatedFiles = new GeneratedFilesTracker(); // create SIE structure qNamesToSIEs Map<QName, ServiceInterfaceEntry> qNamesToSIEs = new HashMap<>(); Map<IdentitySchemaNode, ServiceInterfaceEntry> knownSEITracker = new HashMap<>(); for (Module module : context.getModules()) { String packageName = packageTranslator.getPackageName(module); Map<QName, ServiceInterfaceEntry> namesToSIEntries = ServiceInterfaceEntry .create(module, packageName, knownSEITracker); for (Entry<QName, ServiceInterfaceEntry> sieEntry : namesToSIEntries .entrySet()) { // merge value into qNamesToSIEs if (qNamesToSIEs.containsKey(sieEntry.getKey()) == false) { qNamesToSIEs.put(sieEntry.getKey(), sieEntry.getValue()); } else { throw new IllegalStateException( "Cannot add two SIE with same qname " + sieEntry.getValue()); } } if (yangModulesInCurrentMavenModule.contains(module)) { // write this sie to disk for (ServiceInterfaceEntry sie : namesToSIEntries.values()) { try { generatedFiles.addFile(codeWriter.writeSie(sie, outputBaseDir)); } catch (Exception e) { throw new RuntimeException( "Error occurred during SIE source generate phase", e); } } } } File mainBaseDir = concatFolders(projectBaseDir, "src", "main", "java"); Preconditions.checkNotNull(resourceBaseDir, "resource base dir attribute was null"); StringBuilder fullyQualifiedNamesOfFactories = new StringBuilder(); // create MBEs for (Module module : yangModulesInCurrentMavenModule) { String packageName = packageTranslator.getPackageName(module); Map<String /* MB identity local name */, ModuleMXBeanEntry> namesToMBEs = ModuleMXBeanEntry .create(module, qNamesToSIEs, context, new TypeProviderWrapper(new TypeProviderImpl(context)), packageName); for (Entry<String, ModuleMXBeanEntry> mbeEntry : namesToMBEs .entrySet()) { ModuleMXBeanEntry mbe = mbeEntry.getValue(); try { List<File> files1 = codeWriter.writeMbe(mbe, outputBaseDir, mainBaseDir); generatedFiles.addFile(files1); } catch (Exception e) { throw new RuntimeException( "Error occurred during MBE source generate phase", e); } fullyQualifiedNamesOfFactories.append(mbe .getFullyQualifiedName(mbe.getStubFactoryName())); fullyQualifiedNamesOfFactories.append("\n"); } } // create ModuleFactory file if needed if (fullyQualifiedNamesOfFactories.length() > 0 && generateModuleFactoryFile) { File serviceLoaderFile = JMXGenerator.concatFolders( resourceBaseDir, "META-INF", "services", ModuleFactory.class.getName()); // if this file does not exist, create empty file serviceLoaderFile.getParentFile().mkdirs(); try { serviceLoaderFile.createNewFile(); FileUtils.write(serviceLoaderFile, fullyQualifiedNamesOfFactories.toString()); } catch (IOException e) { String message = "Cannot write to " + serviceLoaderFile; LOG.error(message); throw new RuntimeException(message, e); } } return generatedFiles.getFiles(); } @VisibleForTesting static File concatFolders(final File projectBaseDir, final String... folderNames) { StringBuilder b = new StringBuilder(); for (String folder : folderNames) { b.append(folder); b.append(File.separator); } return new File(projectBaseDir, b.toString()); } @Override public void setAdditionalConfig(final Map<String, String> additionalCfg) { LOG.debug("{}: Additional configuration received: {}", getClass().getCanonicalName(), additionalCfg); this.namespaceToPackageMapping = extractNamespaceMapping(additionalCfg); this.generateModuleFactoryFile = extractModuleFactoryBoolean(additionalCfg); } private boolean extractModuleFactoryBoolean( final Map<String, String> additionalCfg) { String bool = additionalCfg.get(MODULE_FACTORY_FILE_BOOLEAN); if (bool == null) { return true; } if ("false".equals(bool)) { return false; } return true; } private static Map<String, String> extractNamespaceMapping( final Map<String, String> additionalCfg) { Map<String, String> namespaceToPackage = Maps.newHashMap(); for (String key : additionalCfg.keySet()) { if (key.startsWith(NAMESPACE_TO_PACKAGE_PREFIX)) { String mapping = additionalCfg.get(key); NamespaceMapping mappingResolved = extractNamespaceMapping(mapping); namespaceToPackage.put(mappingResolved.namespace, mappingResolved.packageName); } } return namespaceToPackage; } private static NamespaceMapping extractNamespaceMapping(final String mapping) { Matcher matcher = NAMESPACE_MAPPING_PATTERN.matcher(mapping); Preconditions.checkArgument(matcher.matches(), "Namespace to package mapping:%s is in invalid format, requested format is: %s", mapping, NAMESPACE_MAPPING_PATTERN); return new NamespaceMapping(matcher.group(1), matcher.group(2)); } @Override public void setResourceBaseDir(final File resourceDir) { this.resourceBaseDir = resourceDir; } @Override public void setMavenProject(final MavenProject project) { this.projectBaseDir = project.getBasedir(); LOG.debug("{}: project base dir: {}", getClass().getCanonicalName(), projectBaseDir); } @VisibleForTesting static class GeneratedFilesTracker { private final Set<File> files = Sets.newHashSet(); void addFile(final File file) { if (files.contains(file)) { List<File> undeletedFiles = Lists.newArrayList(); for (File presentFile : files) { if (presentFile.delete() == false) { undeletedFiles.add(presentFile); } } if (undeletedFiles.isEmpty() == false) { LOG.error( "Illegal state occurred: Unable to delete already generated files, undeleted files: {}", undeletedFiles); } throw new IllegalStateException( "Name conflict in generated files, file" + file + " present twice"); } files.add(file); } void addFile(final Collection<File> files) { for (File file : files) { addFile(file); } } public Set<File> getFiles() { return files; } } }
epl-1.0
zmaril/mcc
operators.md
1556
Taken from [here](https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B) C++ only removed as well (which is why some numbers have been skipped) Precedence Operator Description Associativity 2 ++ Postfix increment Left-to-right -- Postfix decrement () Function call [] Array subscripting . Element selection by reference -> Element selection through pointer 3 ++ Prefix increment Right-to-left -- Prefix decrement + Unary plus - Unary minus ! Logical NOT ~ Bitwise NOT (One's Complement) (type) Type cast * Indirection (dereference) & Address-of sizeof Size-of 5 * Multiplication Left-to-right / Division % Modulo (remainder) 6 + Addition Left-to-right - Subtraction 7 << Bitwise left shift Left-to-right >> Bitwise right shift 8 < Less than Left-to-right <= Less than or equal to > Greater than >= Greater than or equal to 9 == Equal to Left-to-right != Not equal to 10 & Bitwise AND Left-to-right 11 ^ Bitwise XOR (exclusive or) Left-to-right 12 | Bitwise OR (inclusive or) Left-to-right 13 && Logical AND Left-to-right 14 || Logical OR Left-to-right 15 ?: Ternary conditional (see ?:) Right-to-left 16 = Direct assignment Right-to-left += Assignment by sum -= Assignment by difference *= Assignment by product /= Assignment by quotient %= Assignment by remainder <<= Assignment by bitwise left shift >>= Assignment by bitwise right shift &= Assignment by bitwise AND ^= Assignment by bitwise XOR |= Assignment by bitwise OR 18 lowest , Comma Left-to-right
epl-1.0
eclipse/hawkbit
hawkbit-rest/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java
26380
/** * Copyright (c) 2015 Bosch Software Innovations GmbH and others. * * 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.eclipse.hawkbit.mgmt.rest.resource; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.hasSize; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.RandomStringUtils; import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.repository.model.NamedEntity; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.eclipse.hawkbit.repository.test.util.WithUser; import org.eclipse.hawkbit.rest.util.JsonBuilder; import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.json.JSONObject; import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MvcResult; import com.jayway.jsonpath.JsonPath; import io.qameta.allure.Description; import io.qameta.allure.Feature; import io.qameta.allure.Story; /** * Test for {@link MgmtSoftwareModuleTypeResource}. * */ @Feature("Component Tests - Management API") @Story("Software Module Type Resource") public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiIntegrationTest { @Test @WithUser(principal = "uploadTester", allSpPermissions = true) @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests.") public void getSoftwareModuleTypes() throws Exception { final SoftwareModuleType testType = createTestType(); mvc.perform(get("/rest/v1/softwaremoduletypes").accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.content.[?(@.key=='" + osType.getKey() + "')].name", contains(osType.getName()))) .andExpect(jsonPath("$.content.[?(@.key=='" + osType.getKey() + "')].description", contains(osType.getDescription()))) .andExpect(jsonPath("$.content.[?(@.key=='" + osType.getKey() + "')].colour").doesNotExist()) .andExpect(jsonPath("$.content.[?(@.key=='" + osType.getKey() + "')].maxAssignments", contains(1))) .andExpect(jsonPath("$.content.[?(@.key=='" + osType.getKey() + "')].key", contains("os"))) .andExpect(jsonPath("$.content.[?(@.key=='" + runtimeType.getKey() + "')].name", contains(runtimeType.getName()))) .andExpect(jsonPath("$.content.[?(@.key=='" + runtimeType.getKey() + "')].description", contains(runtimeType.getDescription()))) .andExpect(jsonPath("$.content.[?(@.key=='" + runtimeType.getKey() + "')].maxAssignments", contains(1))) .andExpect(jsonPath("$.content.[?(@.key=='" + runtimeType.getKey() + "')].key", contains("runtime"))) .andExpect( jsonPath("$.content.[?(@.key=='" + appType.getKey() + "')].name", contains(appType.getName()))) .andExpect(jsonPath("$.content.[?(@.key=='" + appType.getKey() + "')].description", contains(appType.getDescription()))) .andExpect(jsonPath("$.content.[?(@.key=='" + appType.getKey() + "')].colour").doesNotExist()) .andExpect(jsonPath("$.content.[?(@.key=='" + appType.getKey() + "')].maxAssignments", contains(Integer.MAX_VALUE))) .andExpect(jsonPath("$.content.[?(@.key=='" + appType.getKey() + "')].key", contains("application"))) .andExpect(jsonPath("$.content.[?(@.key=='test123')].id", contains(testType.getId().intValue()))) .andExpect(jsonPath("$.content.[?(@.key=='test123')].name", contains("TestName123"))) .andExpect(jsonPath("$.content.[?(@.key=='test123')].description", contains("Desc1234"))) .andExpect(jsonPath("$.content.[?(@.key=='test123')].colour", contains("colour"))) .andExpect(jsonPath("$.content.[?(@.key=='test123')].createdBy", contains("uploadTester"))) .andExpect(jsonPath("$.content.[?(@.key=='test123')].createdAt", contains(testType.getCreatedAt()))) .andExpect(jsonPath("$.content.[?(@.key=='test123')].lastModifiedBy", contains("uploadTester"))) .andExpect(jsonPath("$.content.[?(@.key=='test123')].lastModifiedAt", contains(testType.getLastModifiedAt()))) .andExpect(jsonPath("$.content.[?(@.key=='test123')].maxAssignments", contains(5))) .andExpect(jsonPath("$.content.[?(@.key=='test123')].key", contains("test123"))) .andExpect(jsonPath("$.total", equalTo(4))); } private SoftwareModuleType createTestType() { SoftwareModuleType testType = softwareModuleTypeManagement.create(entityFactory.softwareModuleType().create() .key("test123").name("TestName123").description("Desc123").colour("colour").maxAssignments(5)); testType = softwareModuleTypeManagement .update(entityFactory.softwareModuleType().update(testType.getId()).description("Desc1234")); return testType; } @Test @WithUser(principal = "uploadTester", allSpPermissions = true) @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests with sorting by MAXASSIGNMENTS field.") public void getSoftwareModuleTypesSortedByMaxAssignments() throws Exception { final SoftwareModuleType testType = createTestType(); // descending mvc.perform(get("/rest/v1/softwaremoduletypes").accept(MediaType.APPLICATION_JSON) .param(MgmtRestConstants.REQUEST_PARAMETER_SORTING, "MAXASSIGNMENTS:DESC")) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.content.[1].id", equalTo(testType.getId().intValue()))) .andExpect(jsonPath("$.content.[1].name", equalTo("TestName123"))) .andExpect(jsonPath("$.content.[1].description", equalTo("Desc1234"))) .andExpect(jsonPath("$.content.[1].colour", equalTo("colour"))) .andExpect(jsonPath("$.content.[1].createdBy", equalTo("uploadTester"))) .andExpect(jsonPath("$.content.[1].createdAt", equalTo(testType.getCreatedAt()))) .andExpect(jsonPath("$.content.[1].lastModifiedBy", equalTo("uploadTester"))) .andExpect(jsonPath("$.content.[1].lastModifiedAt", equalTo(testType.getLastModifiedAt()))) .andExpect(jsonPath("$.content.[1].maxAssignments", equalTo(5))) .andExpect(jsonPath("$.content.[1].key", equalTo("test123"))) .andExpect(jsonPath("$.total", equalTo(4))); // ascending mvc.perform(get("/rest/v1/softwaremoduletypes").accept(MediaType.APPLICATION_JSON) .param(MgmtRestConstants.REQUEST_PARAMETER_SORTING, "MAXASSIGNMENTS:ASC")) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.content.[2].id", equalTo(testType.getId().intValue()))) .andExpect(jsonPath("$.content.[2].name", equalTo("TestName123"))) .andExpect(jsonPath("$.content.[2].description", equalTo("Desc1234"))) .andExpect(jsonPath("$.content.[2].createdBy", equalTo("uploadTester"))) .andExpect(jsonPath("$.content.[2].createdAt", equalTo(testType.getCreatedAt()))) .andExpect(jsonPath("$.content.[2].lastModifiedBy", equalTo("uploadTester"))) .andExpect(jsonPath("$.content.[2].lastModifiedAt", equalTo(testType.getLastModifiedAt()))) .andExpect(jsonPath("$.content.[2].maxAssignments", equalTo(5))) .andExpect(jsonPath("$.content.[2].key", equalTo("test123"))) .andExpect(jsonPath("$.total", equalTo(4))); } @Test @WithUser(principal = "uploadTester", allSpPermissions = true) @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes POST requests when max assignment is smaller than 1") public void createSoftwareModuleTypesInvalidAssignmentBadRequest() throws Exception { final List<SoftwareModuleType> types = new ArrayList<>(); types.add(entityFactory.softwareModuleType().create().key("test-1").name("TestName-1").maxAssignments(-1) .build()); mvc.perform(post("/rest/v1/softwaremoduletypes/").content(JsonBuilder.softwareModuleTypes(types)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()); types.clear(); types.add(entityFactory.softwareModuleType().create().key("test0").name("TestName0").maxAssignments(0).build()); mvc.perform(post("/rest/v1/softwaremoduletypes/").content(JsonBuilder.softwareModuleTypes(types)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()); } @Test @WithUser(principal = "uploadTester", allSpPermissions = true) @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes POST requests.") public void createSoftwareModuleTypes() throws Exception { final List<SoftwareModuleType> types = Arrays.asList( entityFactory.softwareModuleType().create().key("test1").name("TestName1").description("Desc1") .colour("col1‚").maxAssignments(1).build(), entityFactory.softwareModuleType().create().key("test2").name("TestName2").description("Desc2") .colour("col2‚").maxAssignments(2).build(), entityFactory.softwareModuleType().create().key("test3").name("TestName3").description("Desc3") .colour("col3‚").maxAssignments(3).build()); final MvcResult mvcResult = mvc .perform(post("/rest/v1/softwaremoduletypes/").content(JsonBuilder.softwareModuleTypes(types)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("[0].name", equalTo("TestName1"))).andExpect(jsonPath("[0].key", equalTo("test1"))) .andExpect(jsonPath("[0].description", equalTo("Desc1"))) .andExpect(jsonPath("[0].createdBy", equalTo("uploadTester"))) .andExpect(jsonPath("[0].maxAssignments", equalTo(1))) .andExpect(jsonPath("[1].name", equalTo("TestName2"))).andExpect(jsonPath("[1].key", equalTo("test2"))) .andExpect(jsonPath("[1].description", equalTo("Desc2"))) .andExpect(jsonPath("[1].createdBy", equalTo("uploadTester"))) .andExpect(jsonPath("[1].maxAssignments", equalTo(2))) .andExpect(jsonPath("[2].name", equalTo("TestName3"))).andExpect(jsonPath("[2].key", equalTo("test3"))) .andExpect(jsonPath("[2].description", equalTo("Desc3"))) .andExpect(jsonPath("[2].createdBy", equalTo("uploadTester"))) .andExpect(jsonPath("[2].createdAt", not(equalTo(0)))) .andExpect(jsonPath("[2].maxAssignments", equalTo(3))).andReturn(); final SoftwareModuleType created1 = softwareModuleTypeManagement.getByKey("test1").get(); final SoftwareModuleType created2 = softwareModuleTypeManagement.getByKey("test2").get(); final SoftwareModuleType created3 = softwareModuleTypeManagement.getByKey("test3").get(); assertThat( JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString()) .isEqualTo("http://localhost/rest/v1/softwaremoduletypes/" + created1.getId()); assertThat( JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString()) .isEqualTo("http://localhost/rest/v1/softwaremoduletypes/" + created2.getId()); assertThat( JsonPath.compile("[2]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString()) .isEqualTo("http://localhost/rest/v1/softwaremoduletypes/" + created3.getId()); assertThat(softwareModuleTypeManagement.count()).isEqualTo(6); } @Test @WithUser(principal = "uploadTester", allSpPermissions = true) @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} GET requests.") public void getSoftwareModuleType() throws Exception { final SoftwareModuleType testType = createTestType(); mvc.perform(get("/rest/v1/softwaremoduletypes/{smtId}", testType.getId()).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.name", equalTo("TestName123"))) .andExpect(jsonPath("$.description", equalTo("Desc1234"))) .andExpect(jsonPath("$.colour", equalTo("colour"))) .andExpect(jsonPath("$.maxAssignments", equalTo(5))) .andExpect(jsonPath("$.createdBy", equalTo("uploadTester"))) .andExpect(jsonPath("$.createdAt", equalTo(testType.getCreatedAt()))) .andExpect(jsonPath("$.lastModifiedBy", equalTo("uploadTester"))) .andExpect(jsonPath("$.lastModifiedAt", equalTo(testType.getLastModifiedAt()))) .andExpect(jsonPath("$.deleted", equalTo(testType.isDeleted()))); } @Test @WithUser(principal = "uploadTester", allSpPermissions = true) @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} DELETE requests (hard delete scenario).") public void deleteSoftwareModuleTypeUnused() throws Exception { final SoftwareModuleType testType = createTestType(); assertThat(softwareModuleTypeManagement.count()).isEqualTo(4); mvc.perform(delete("/rest/v1/softwaremoduletypes/{smId}", testType.getId())).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()); assertThat(softwareModuleTypeManagement.count()).isEqualTo(3); } @Test @Description("Ensures that module type deletion request to API on an entity that does not exist results in NOT_FOUND.") public void deleteSoftwareModuleTypeThatDoesNotExistLeadsToNotFound() throws Exception { mvc.perform(delete("/rest/v1/softwaremoduletypes/1234")).andDo(MockMvcResultPrinter.print()) .andExpect(status().isNotFound()); } @Test @WithUser(principal = "uploadTester", allSpPermissions = true) @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} DELETE requests (soft delete scenario).") public void deleteSoftwareModuleTypeUsed() throws Exception { final SoftwareModuleType testType = createTestType(); softwareModuleManagement .create(entityFactory.softwareModule().create().type(testType).name("name").version("version")); assertThat(softwareModuleTypeManagement.count()).isEqualTo(4); mvc.perform(get("/rest/v1/softwaremoduletypes/{smtId}", testType.getId())).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()).andExpect(jsonPath("$.deleted", equalTo(false))); mvc.perform(delete("/rest/v1/softwaremoduletypes/{smtId}", testType.getId())) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); mvc.perform(get("/rest/v1/softwaremoduletypes/{smtId}", testType.getId())).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()).andExpect(jsonPath("$.deleted", equalTo(true))); assertThat(softwareModuleTypeManagement.count()).isEqualTo(3); } @Test @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} PUT requests.") public void updateSoftwareModuleTypeColourDescriptionAndNameUntouched() throws Exception { final SoftwareModuleType testType = createTestType(); final String body = new JSONObject().put("id", testType.getId()).put("description", "foobardesc") .put("colour", "updatedColour").put("name", "nameShouldNotBeChanged").toString(); mvc.perform(put("/rest/v1/softwaremoduletypes/{smId}", testType.getId()).content(body) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("$.id", equalTo(testType.getId().intValue()))) .andExpect(jsonPath("$.description", equalTo("foobardesc"))) .andExpect(jsonPath("$.colour", equalTo("updatedColour"))) .andExpect(jsonPath("$.name", equalTo("TestName123"))).andReturn(); } @Test @Description("Tests the update of the deletion flag. It is verfied that the software module type can't be marked as deleted through update operation.") public void updateSoftwareModuleTypeDeletedFlag() throws Exception { SoftwareModuleType testType = createTestType(); final String body = new JSONObject().put("id", testType.getId()).put("deleted", true).toString(); mvc.perform(put("/rest/v1/softwaremoduletypes/{smtId}", testType.getId()).content(body) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("$.id", equalTo(testType.getId().intValue()))) .andExpect(jsonPath("$.lastModifiedAt", equalTo(testType.getLastModifiedAt()))) .andExpect(jsonPath("$.deleted", equalTo(false))); testType = softwareModuleTypeManagement.get(testType.getId()).get(); assertThat(testType.getLastModifiedAt()).isEqualTo(testType.getLastModifiedAt()); assertThat(testType.isDeleted()).isEqualTo(false); } @Test @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests with paging.") public void getSoftwareModuleTypesWithoutAddtionalRequestParameters() throws Exception { final int types = 3; mvc.perform(get(MgmtRestConstants.SOFTWAREMODULETYPE_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()) .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types))) .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(types))) .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(types))); } @Test @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests with paging.") public void getSoftwareModuleTypesWithPagingLimitRequestParameter() throws Exception { final int types = 3; final int limitSize = 1; mvc.perform(get(MgmtRestConstants.SOFTWAREMODULETYPE_V1_REQUEST_MAPPING) .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize))) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types))) .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize))) .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize))); } @Test @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests with paging.") public void getSoftwareModuleTypesWithPagingLimitAndOffsetRequestParameter() throws Exception { final int types = 3; final int offsetParam = 2; final int expectedSize = types - offsetParam; mvc.perform(get(MgmtRestConstants.SOFTWAREMODULETYPE_V1_REQUEST_MAPPING) .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam)) .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(types))) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types))) .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize))) .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize))); } @Test @Description("Ensures that the server is behaving as expected on invalid requests (wrong media type, wrong ID etc.).") public void invalidRequestsOnSoftwaremoduleTypesResource() throws Exception { final SoftwareModuleType testType = createTestType(); final List<SoftwareModuleType> types = Arrays.asList(testType); // SM does not exist mvc.perform(get("/rest/v1/softwaremoduletypes/12345678")).andDo(MockMvcResultPrinter.print()) .andExpect(status().isNotFound()); mvc.perform(delete("/rest/v1/softwaremoduletypes/12345678")).andDo(MockMvcResultPrinter.print()) .andExpect(status().isNotFound()); // bad request - no content mvc.perform(post("/rest/v1/softwaremoduletypes").contentType(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()); // bad request - bad content mvc.perform(post("/rest/v1/softwaremoduletypes").content("sdfjsdlkjfskdjf".getBytes()) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isBadRequest()); mvc.perform(post("/rest/v1/softwaremoduletypes").content( "[{\"description\":\"Desc123\",\"id\":9223372036854775807,\"key\":\"test123\",\"maxAssignments\":5}]") .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isBadRequest()); final SoftwareModuleType toLongName = entityFactory.softwareModuleType().create().key("test123") .name(RandomStringUtils.randomAlphanumeric(NamedEntity.NAME_MAX_SIZE + 1)).build(); mvc.perform( post("/rest/v1/softwaremoduletypes").content(JsonBuilder.softwareModuleTypes(Arrays.asList(toLongName))) .contentType(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()); // unsupported media type mvc.perform(post("/rest/v1/softwaremoduletypes").content(JsonBuilder.softwareModuleTypes(types)) .contentType(MediaType.APPLICATION_OCTET_STREAM)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isUnsupportedMediaType()); // not allowed methods mvc.perform(put("/rest/v1/softwaremoduletypes")).andDo(MockMvcResultPrinter.print()) .andExpect(status().isMethodNotAllowed()); mvc.perform(delete("/rest/v1/softwaremoduletypes")).andDo(MockMvcResultPrinter.print()) .andExpect(status().isMethodNotAllowed()); } @Test @Description("Search erquest of software module types.") public void searchSoftwareModuleTypeRsql() throws Exception { softwareModuleTypeManagement.create(entityFactory.softwareModuleType().create().key("test123") .name("TestName123").description("Desc123").maxAssignments(5)); softwareModuleTypeManagement.create(entityFactory.softwareModuleType().create().key("test1234") .name("TestName1234").description("Desc1234").maxAssignments(5)); final String rsqlFindLikeDs1OrDs2 = "name==TestName123,name==TestName1234"; mvc.perform(get("/rest/v1/softwaremoduletypes?q=" + rsqlFindLikeDs1OrDs2)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()).andExpect(jsonPath("size", equalTo(2))) .andExpect(jsonPath("total", equalTo(2))).andExpect(jsonPath("content[0].name", equalTo("TestName123"))) .andExpect(jsonPath("content[1].name", equalTo("TestName1234"))); } private void createSoftwareModulesAlphabetical(final int amount) { char character = 'a'; for (int index = 0; index < amount; index++) { final String str = String.valueOf(character); softwareModuleManagement.create(entityFactory.softwareModule().create().type(osType).name(str) .description(str).vendor(str).version(str)); character++; } } }
epl-1.0
Cooperate-Project/Cooperate
bundles/de.cooperateproject.modeling.textual.common/src/de/cooperateproject/modeling/textual/common/naming/NameSwitch.java
2176
package de.cooperateproject.modeling.textual.common.naming; import java.util.List; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EReference; import org.eclipse.uml2.uml.NamedElement; import org.eclipse.xtext.nodemodel.INode; import org.eclipse.xtext.nodemodel.util.NodeModelUtils; import de.cooperateproject.modeling.textual.common.metamodel.textualCommons.PackageImport; import de.cooperateproject.modeling.textual.common.metamodel.textualCommons.TextualCommonsPackage; import de.cooperateproject.modeling.textual.common.metamodel.textualCommons.util.TextualCommonsSwitch; public class NameSwitch extends TextualCommonsSwitch<String> { @Override public String casePackageImport(PackageImport object) { return determineNameOfReferencedNamedElement(object, TextualCommonsPackage.Literals.UML_REFERENCING_ELEMENT__REFERENCED_ELEMENT); } @Override public String caseNamedElement( de.cooperateproject.modeling.textual.common.metamodel.textualCommons.NamedElement object) { Object result = object.eGet(TextualCommonsPackage.Literals.NAMED_ELEMENT__NAME, false); if (result != null) { return (String) result; } return determineNameOfReferencedNamedElement(object, TextualCommonsPackage.Literals.UML_REFERENCING_ELEMENT__REFERENCED_ELEMENT); } private String determineNameOfReferencedNamedElement(EObject object, EReference umlReference) { List<INode> nodes = NodeModelUtils.findNodesForFeature(object, umlReference); if (!nodes.isEmpty()) { return normalizeNodeName(NodeModelUtils.getTokenText(nodes.get(0))); } Object referencedElement = object.eGet(umlReference, false); if (referencedElement instanceof NamedElement) { return ((NamedElement) referencedElement).getName(); } return null; } private static String normalizeNodeName(String nodeName) { if (nodeName != null && nodeName.matches("\\\".*\\\"")) { return nodeName.subSequence(1, nodeName.length() - 1).toString(); } return nodeName; } }
epl-1.0
akurtakov/Pydev
plugins/org.python.pydev.debug/src/org/python/pydev/debug/ui/launching/AbstractLaunchConfigurationDelegate.java
5817
/** * Copyright (c) 2005-2013 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Eclipse Public License (EPL). * Please see the license.txt included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ /* * Author: atotic * Created: Aug 16, 2003 */ package org.python.pydev.debug.ui.launching; import java.io.IOException; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchManager; import org.eclipse.debug.core.model.ILaunchConfigurationDelegate; import org.eclipse.debug.core.model.LaunchConfigurationDelegate; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.swt.widgets.Display; import org.python.pydev.core.MisconfigurationException; import org.python.pydev.core.log.Log; import org.python.pydev.debug.core.Constants; import org.python.pydev.debug.core.PydevDebugPlugin; import org.python.pydev.shared_core.SharedCorePlugin; import org.python.pydev.shared_ui.EditorUtils; /** * * Launcher for the python scripts. * * <p>The code is pretty much copied from ExternalTools' ProgramLaunchDelegate. * <p>I would have subclassed, but ProgramLaunchDelegate hides important internals * * Based on org.eclipse.ui.externaltools.internal.program.launchConfigurations.ProgramLaunchDelegate * * Build order based on org.eclipse.jdt.launching.AbstractJavaLaunchConfigurationDelegate */ public abstract class AbstractLaunchConfigurationDelegate extends LaunchConfigurationDelegate implements ILaunchConfigurationDelegate { private IProject[] fOrderedProjects; /** * We need to reimplement this method (otherwise, all the projects in the workspace will be rebuilt, and not only * the ones referenced in the configuration). */ @Override protected IProject[] getBuildOrder(ILaunchConfiguration configuration, String mode) throws CoreException { return fOrderedProjects; } /* * (non-Javadoc) * * @see org.eclipse.debug.core.model.ILaunchConfigurationDelegate2#preLaunchCheck(org.eclipse.debug.core.ILaunchConfiguration, * java.lang.String, org.eclipse.core.runtime.IProgressMonitor) */ @Override public boolean preLaunchCheck(ILaunchConfiguration configuration, String mode, IProgressMonitor monitor) throws CoreException { // build project list fOrderedProjects = null; String projName = configuration.getAttribute(Constants.ATTR_PROJECT, ""); if (projName.length() > 0) { IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projName); if (project != null) { fOrderedProjects = computeReferencedBuildOrder(new IProject[] { project }); } } // do generic launch checks return super.preLaunchCheck(configuration, mode, monitor); } /** * Launches the python process. * * Modelled after Ant & Java runners * see WorkbenchLaunchConfigurationDelegate::launch */ @Override public void launch(ILaunchConfiguration conf, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { if (monitor == null) { monitor = new NullProgressMonitor(); } monitor.beginTask("Preparing configuration", 3); try { PythonRunnerConfig runConfig = new PythonRunnerConfig(conf, mode, getRunnerConfigRun(conf, mode, launch)); monitor.worked(1); try { PythonRunner.run(runConfig, launch, monitor); } catch (IOException e) { Log.log(e); finishLaunchWithError(launch); throw new CoreException(PydevDebugPlugin.makeStatus(IStatus.ERROR, "Unexpected IO Exception in Pydev debugger", null)); } } catch (final InvalidRunException e) { handleError(launch, e); } catch (final MisconfigurationException e) { handleError(launch, e); } } private void handleError(ILaunch launch, final Exception e) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { ErrorDialog.openError(EditorUtils.getShell(), "Invalid launch configuration", "Unable to make launch because launch configuration is not valid", SharedCorePlugin.makeStatus(IStatus.ERROR, e.getMessage(), e)); } }); finishLaunchWithError(launch); } private void finishLaunchWithError(ILaunch launch) { try { launch.terminate(); ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); launchManager.removeLaunch(launch); } catch (Throwable x) { Log.log(x); } } /** * @return the mode we should use to run it... * * @see PythonRunnerConfig#RUN_REGULAR * @see PythonRunnerConfig#RUN_COVERAGE * @see PythonRunnerConfig#RUN_UNITTEST * @see PythonRunnerConfig#RUN_JYTHON_UNITTEST * @see PythonRunnerConfig#RUN_JYTHON * @see PythonRunnerConfig#RUN_IRONPYTHON * @see PythonRunnerConfig#RUN_IRONPYTHON_UNITTEST */ protected abstract String getRunnerConfigRun(ILaunchConfiguration conf, String mode, ILaunch launch); }
epl-1.0
kgibm/open-liberty
dev/com.ibm.ws.resource/test/com/ibm/ws/resource/internal/ResourceRefConfigTest.java
27596
/******************************************************************************* * Copyright (c) 2011, 2013 IBM Corporation and others. * 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 * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.resource.internal; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.sql.Connection; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.Assert; import org.junit.Test; import com.ibm.ws.javaee.dd.common.ResourceRef; import com.ibm.ws.resource.ResourceRefConfig; import com.ibm.ws.resource.ResourceRefInfo.Property; public class ResourceRefConfigTest { private static ResourceRefConfigImpl serializeAndDeserialize(ResourceRefConfigImpl rrc) throws IOException, ClassNotFoundException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(rrc); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); return (ResourceRefConfigImpl) ois.readObject(); } private static ResourceRefConfigImpl[] serializeAndDeserializePair(ResourceRefConfigImpl rrc) throws IOException, ClassNotFoundException { return new ResourceRefConfigImpl[] { rrc, serializeAndDeserialize(rrc) }; } @Test public void testCtor() throws Exception { for (ResourceRefConfigImpl rrc : serializeAndDeserializePair(new ResourceRefConfigImpl(null, null))) { Assert.assertEquals(null, rrc.getName()); Assert.assertEquals(null, rrc.getType()); } for (ResourceRefConfigImpl rrc : serializeAndDeserializePair(new ResourceRefConfigImpl("name", "type"))) { Assert.assertEquals("name", rrc.getName()); Assert.assertEquals("type", rrc.getType()); } } @Test public void testToString() { // Ensure it doesn't throw. new ResourceRefConfigImpl(null, null).toString(); } @Test public void testDescription() throws Exception { ResourceRefConfigImpl rrc = new ResourceRefConfigImpl(null, null); for (ResourceRefConfigImpl rrcCopy : serializeAndDeserializePair(rrc)) { Assert.assertNull(rrcCopy.getDescription()); } rrc.setDescription("desc"); for (ResourceRefConfigImpl rrcCopy : serializeAndDeserializePair(rrc)) { Assert.assertEquals("desc", rrcCopy.getDescription()); } } @Test public void testType() throws Exception { ResourceRefConfigImpl rrc = new ResourceRefConfigImpl(null, null); rrc.setType("type"); for (ResourceRefConfigImpl rrcCopy : serializeAndDeserializePair(rrc)) { Assert.assertEquals("type", rrcCopy.getType()); } } @Test public void testAuth() throws Exception { ResourceRefConfigImpl rrc = new ResourceRefConfigImpl(null, null); for (ResourceRefConfigImpl rrcCopy : serializeAndDeserializePair(rrc)) { Assert.assertEquals(ResourceRef.AUTH_APPLICATION, rrcCopy.getAuth()); } rrc.setResAuthType(ResourceRef.AUTH_CONTAINER); for (ResourceRefConfigImpl rrcCopy : serializeAndDeserializePair(rrc)) { Assert.assertEquals(ResourceRef.AUTH_CONTAINER, rrcCopy.getAuth()); } } @Test public void testSharingScope() throws Exception { ResourceRefConfigImpl rrc = new ResourceRefConfigImpl(null, null); for (ResourceRefConfigImpl rrcCopy : serializeAndDeserializePair(rrc)) { Assert.assertEquals(ResourceRef.SHARING_SCOPE_SHAREABLE, rrcCopy.getSharingScope()); } rrc.setSharingScope(ResourceRef.SHARING_SCOPE_UNSHAREABLE); for (ResourceRefConfigImpl rrcCopy : serializeAndDeserializePair(rrc)) { Assert.assertEquals(ResourceRef.SHARING_SCOPE_UNSHAREABLE, rrcCopy.getSharingScope()); } } @Test public void testBindigName() throws Exception { ResourceRefConfigImpl rrc = new ResourceRefConfigImpl(null, null); for (ResourceRefConfigImpl rrcCopy : serializeAndDeserializePair(rrc)) { Assert.assertNull(rrcCopy.getJNDIName()); } rrc.setJNDIName("bind"); for (ResourceRefConfigImpl rrcCopy : serializeAndDeserializePair(rrc)) { Assert.assertEquals("bind", rrcCopy.getJNDIName()); } } @Test public void testLoginConfigurationName() throws Exception { ResourceRefConfigImpl rrc = new ResourceRefConfigImpl(null, null); for (ResourceRefConfigImpl rrcCopy : serializeAndDeserializePair(rrc)) { Assert.assertNull(rrcCopy.getLoginConfigurationName()); } rrc.setLoginConfigurationName("lcn"); for (ResourceRefConfigImpl rrcCopy : serializeAndDeserializePair(rrc)) { Assert.assertEquals("lcn", rrcCopy.getLoginConfigurationName()); } } @Test public void testLoginProperties() throws Exception { ResourceRefConfigImpl rrc = new ResourceRefConfigImpl(null, null); for (ResourceRefConfigImpl rrcCopy : serializeAndDeserializePair(rrc)) { Assert.assertEquals(Collections.emptyList(), rrcCopy.getLoginPropertyList()); } rrc.addLoginProperty("n1", "v1"); for (ResourceRefConfigImpl rrcCopy : serializeAndDeserializePair(rrc)) { Assert.assertEquals(1, rrcCopy.getLoginPropertyList().size()); Assert.assertEquals("n1", rrcCopy.getLoginPropertyList().get(0).getName()); Assert.assertEquals("v1", rrcCopy.getLoginPropertyList().get(0).getValue()); } rrc.addLoginProperty("n2", "v2"); for (ResourceRefConfigImpl rrcCopy : serializeAndDeserializePair(rrc)) { Assert.assertEquals(2, rrcCopy.getLoginPropertyList().size()); Assert.assertEquals("n2", rrcCopy.getLoginPropertyList().get(1).getName()); Assert.assertEquals("v2", rrcCopy.getLoginPropertyList().get(1).getValue()); } rrc.clearLoginProperties(); for (ResourceRefConfigImpl rrcCopy : serializeAndDeserializePair(rrc)) { Assert.assertEquals(Collections.emptyList(), rrcCopy.getLoginPropertyList()); } } @Test public void testIsolationLevel() throws Exception { ResourceRefConfigImpl rrc = new ResourceRefConfigImpl(null, null); for (ResourceRefConfigImpl rrcCopy : serializeAndDeserializePair(rrc)) { Assert.assertEquals(Connection.TRANSACTION_NONE, rrcCopy.getIsolationLevel()); } for (int isoLevel : new int[] { Connection.TRANSACTION_READ_COMMITTED, Connection.TRANSACTION_READ_UNCOMMITTED, Connection.TRANSACTION_REPEATABLE_READ, Connection.TRANSACTION_SERIALIZABLE }) { rrc.setIsolationLevel(isoLevel); for (ResourceRefConfigImpl rrcCopy : serializeAndDeserializePair(rrc)) { Assert.assertEquals(isoLevel, rrcCopy.getIsolationLevel()); } } } @Test public void testCommitPriority() throws Exception { ResourceRefConfigImpl rrc = new ResourceRefConfigImpl(null, null); for (ResourceRefConfigImpl rrcCopy : serializeAndDeserializePair(rrc)) { Assert.assertEquals(0, rrcCopy.getCommitPriority()); } rrc.setCommitPriority(1); for (ResourceRefConfigImpl rrcCopy : serializeAndDeserializePair(rrc)) { Assert.assertEquals(1, rrcCopy.getCommitPriority()); } } @Test public void testBranchCoupling() throws Exception { ResourceRefConfigImpl rrc = new ResourceRefConfigImpl(null, null); for (ResourceRefConfigImpl rrcCopy : serializeAndDeserializePair(rrc)) { Assert.assertEquals(ResourceRefConfig.BRANCH_COUPLING_UNSET, rrcCopy.getBranchCoupling()); } for (int bc : new int[] { ResourceRefConfig.BRANCH_COUPLING_LOOSE, ResourceRefConfig.BRANCH_COUPLING_TIGHT }) { rrc.setBranchCoupling(bc); for (ResourceRefConfigImpl rrcCopy : serializeAndDeserializePair(rrc)) { Assert.assertEquals(bc, rrcCopy.getBranchCoupling()); } } } @Test public void testBranchCouplingMerge() throws Exception { ResourceRefConfigImpl rrc = new ResourceRefConfigImpl("baseref", "type"); ResourceRefConfigImpl[] mrrcs = new ResourceRefConfigImpl[2]; mrrcs[0] = new ResourceRefConfigImpl("ref2", "type"); mrrcs[0].setBranchCoupling(ResourceRefConfig.BRANCH_COUPLING_TIGHT); mrrcs[1] = serializeAndDeserialize(mrrcs[0]); List<ResourceRefConfig.MergeConflict> conflicts = merge(rrc, mrrcs); // assert no conflicts Assert.assertEquals(0, conflicts.size()); mrrcs[1].setBranchCoupling(ResourceRefConfig.BRANCH_COUPLING_LOOSE); conflicts = merge(rrc, mrrcs); // assert conflict Assert.assertEquals(1, conflicts.size()); ResourceRefConfig.MergeConflict conflict = conflicts.get(0); Assert.assertEquals("branch-coupling", conflict.getAttributeName()); Assert.assertEquals("TIGHT", conflict.getValue1()); Assert.assertEquals("LOOSE", conflict.getValue2()); // assert resulting config (first value should be used) Assert.assertEquals(ResourceRefConfig.BRANCH_COUPLING_TIGHT, rrc.getBranchCoupling()); } @Test public void testCommitPriorityMerge() throws Exception { ResourceRefConfigImpl rrc = new ResourceRefConfigImpl("baseref", "type"); ResourceRefConfigImpl[] mrrcs = new ResourceRefConfigImpl[2]; mrrcs[0] = new ResourceRefConfigImpl("ref2", "type"); mrrcs[0].setCommitPriority(1); mrrcs[1] = serializeAndDeserialize(mrrcs[0]); List<ResourceRefConfig.MergeConflict> conflicts = merge(rrc, mrrcs); // assert no conflicts Assert.assertEquals(0, conflicts.size()); mrrcs[1].setCommitPriority(2); conflicts = merge(rrc, mrrcs); // assert conflict Assert.assertEquals(1, conflicts.size()); ResourceRefConfig.MergeConflict conflict = conflicts.get(0); Assert.assertEquals("commit-priority", conflict.getAttributeName()); Assert.assertEquals("1", conflict.getValue1()); Assert.assertEquals("2", conflict.getValue2()); // assert resulting config (first value should be used) Assert.assertEquals(1, rrc.getCommitPriority()); } @Test public void testIsolationLevelMerge() throws Exception { ResourceRefConfigImpl rrc = new ResourceRefConfigImpl("baseref", "type"); ResourceRefConfigImpl[] mrrcs = new ResourceRefConfigImpl[2]; mrrcs[0] = new ResourceRefConfigImpl("ref2", "type"); mrrcs[0].setIsolationLevel(Connection.TRANSACTION_SERIALIZABLE); mrrcs[1] = serializeAndDeserialize(mrrcs[0]); List<ResourceRefConfig.MergeConflict> conflicts = merge(rrc, mrrcs); // assert no conflicts Assert.assertEquals(0, conflicts.size()); mrrcs[1].setIsolationLevel(Connection.TRANSACTION_NONE); conflicts = merge(rrc, mrrcs); // assert conflicts Assert.assertEquals(1, conflicts.size()); ResourceRefConfig.MergeConflict conflict = conflicts.get(0); Assert.assertEquals("isolation-level", conflict.getAttributeName()); Assert.assertEquals("TRANSACTION_SERIALIZABLE", conflict.getValue1()); Assert.assertEquals("TRANSACTION_NONE", conflict.getValue2()); // assert resulting config (first value should be used) Assert.assertEquals(Connection.TRANSACTION_SERIALIZABLE, rrc.getIsolationLevel()); } @Test public void testBindingNameMerge() throws Exception { ResourceRefConfigImpl rrc = new ResourceRefConfigImpl("baseref", "type"); ResourceRefConfigImpl[] mrrcs = new ResourceRefConfigImpl[2]; mrrcs[0] = new ResourceRefConfigImpl("ref2", "type"); mrrcs[0].setJNDIName("jndiName0"); mrrcs[1] = serializeAndDeserialize(mrrcs[0]); List<ResourceRefConfig.MergeConflict> conflicts = merge(rrc, mrrcs); // assert no conflicts Assert.assertEquals(0, conflicts.size()); mrrcs[1].setJNDIName("jndiName1"); conflicts = merge(rrc, mrrcs); // assert conflicts Assert.assertEquals(1, conflicts.size()); ResourceRefConfig.MergeConflict conflict = conflicts.get(0); Assert.assertEquals("binding-name", conflict.getAttributeName()); Assert.assertEquals("jndiName0", conflict.getValue1()); Assert.assertEquals("jndiName1", conflict.getValue2()); // assert resulting config (first value should be used) Assert.assertEquals("jndiName0", rrc.getJNDIName()); } @Test public void testLoginConfigurationNameMerge() throws Exception { ResourceRefConfigImpl rrc = new ResourceRefConfigImpl("baseref", "type"); ResourceRefConfigImpl[] mrrcs = new ResourceRefConfigImpl[2]; mrrcs[0] = new ResourceRefConfigImpl("ref2", "type"); mrrcs[0].setLoginConfigurationName("loginCfg0"); mrrcs[1] = serializeAndDeserialize(mrrcs[0]); List<ResourceRefConfig.MergeConflict> conflicts = merge(rrc, mrrcs); // assert no conflicts Assert.assertEquals(0, conflicts.size()); mrrcs[1].setLoginConfigurationName("loginCfg1"); // assert conflicts conflicts = merge(rrc, mrrcs); Assert.assertEquals(1, conflicts.size()); ResourceRefConfig.MergeConflict conflict = conflicts.get(0); Assert.assertEquals("custom-login-configuration", conflict.getAttributeName()); Assert.assertEquals("loginCfg0", conflict.getValue1()); Assert.assertEquals("loginCfg1", conflict.getValue2()); // assert resulting config (first value should be used) Assert.assertEquals("loginCfg0", rrc.getLoginConfigurationName()); } @Test public void testAuthenticationAliasNameMerge() throws Exception { final String AUTHENTICATION_ALIAS_LOGIN_NAME = "DefaultPrincipalMapping"; ResourceRefConfigImpl rrc = new ResourceRefConfigImpl("baseref", "type"); ResourceRefConfigImpl[] mrrcs = new ResourceRefConfigImpl[2]; mrrcs[0] = new ResourceRefConfigImpl("ref2", "type"); mrrcs[0].addLoginProperty(AUTHENTICATION_ALIAS_LOGIN_NAME, "bob"); mrrcs[1] = serializeAndDeserialize(mrrcs[0]); List<ResourceRefConfig.MergeConflict> conflicts = merge(rrc, mrrcs); // assert no conflicts Assert.assertEquals(0, conflicts.size()); mrrcs[1].addLoginProperty(AUTHENTICATION_ALIAS_LOGIN_NAME, "joe"); // assert conflicts conflicts = merge(rrc, mrrcs); Assert.assertEquals(1, conflicts.size()); ResourceRefConfig.MergeConflict conflict = conflicts.get(0); Assert.assertEquals("authentication-alias", conflict.getAttributeName()); Assert.assertEquals("bob", conflict.getValue1()); Assert.assertEquals("joe", conflict.getValue2()); // assert resulting config (first value should be used) Property prop = rrc.getLoginPropertyList().get(0); Assert.assertNotNull(prop); Assert.assertEquals(AUTHENTICATION_ALIAS_LOGIN_NAME, prop.getName()); Assert.assertEquals("bob", prop.getValue()); } @Test public void testLoginPropertyMerge() throws Exception { ResourceRefConfigImpl rrc = new ResourceRefConfigImpl("baseref", "type"); ResourceRefConfigImpl[] mrrcs = new ResourceRefConfigImpl[2]; mrrcs[0] = new ResourceRefConfigImpl("ref2", "type"); mrrcs[0].addLoginProperty("prop1", "bob"); mrrcs[0].addLoginProperty("prop2", "bob2"); mrrcs[1] = serializeAndDeserialize(mrrcs[0]); List<ResourceRefConfig.MergeConflict> conflicts = merge(rrc, mrrcs); // assert no conflicts Assert.assertEquals(0, conflicts.size()); mrrcs[1].addLoginProperty("prop1", "joe"); // assert conflict conflicts = merge(rrc, mrrcs); Assert.assertEquals(1, conflicts.size()); ResourceRefConfig.MergeConflict conflict = conflicts.get(0); Assert.assertEquals("custom-login-configuration prop1", conflict.getAttributeName()); Assert.assertEquals("bob", conflict.getValue1()); Assert.assertEquals("joe", conflict.getValue2()); // assert resulting config (first value should be used) Property prop = rrc.getLoginPropertyList().get(0); Assert.assertNotNull(prop); Assert.assertEquals("prop1", prop.getName()); Assert.assertEquals("bob", prop.getValue()); } @Test public void testMultiMergeConflict() throws Exception { ResourceRefConfigImpl rrc = new ResourceRefConfigImpl("baseref", "type"); ResourceRefConfigImpl[] mrrcs = new ResourceRefConfigImpl[3]; mrrcs[0] = new ResourceRefConfigImpl("ref2", "type"); mrrcs[0].setLoginConfigurationName("loginCfg0"); mrrcs[1] = serializeAndDeserialize(mrrcs[0]); mrrcs[2] = serializeAndDeserialize(mrrcs[0]); List<ResourceRefConfig.MergeConflict> conflicts = merge(rrc, mrrcs); // assert no conflicts Assert.assertEquals(0, conflicts.size()); mrrcs[1].setLoginConfigurationName("loginCfg1"); mrrcs[2].setLoginConfigurationName("loginCfg2"); // assert conflicts conflicts = merge(rrc, mrrcs); Assert.assertEquals(2, conflicts.size()); ResourceRefConfig.MergeConflict conflict = conflicts.get(0); Assert.assertEquals("custom-login-configuration", conflict.getAttributeName()); Assert.assertEquals("loginCfg0", conflict.getValue1()); Assert.assertEquals("loginCfg1", conflict.getValue2()); conflict = conflicts.get(1); Assert.assertEquals("custom-login-configuration", conflict.getAttributeName()); Assert.assertEquals("loginCfg0", conflict.getValue1()); Assert.assertEquals("loginCfg2", conflict.getValue2()); // assert resulting config (first value should be used) Assert.assertEquals("loginCfg0", rrc.getLoginConfigurationName()); } private List<ResourceRefConfig.MergeConflict> merge(ResourceRefConfig rrc, ResourceRefConfig[] rrcs) { List<ResourceRefConfig.MergeConflict> conflicts = new ArrayList<ResourceRefConfig.MergeConflict>(); rrc.mergeBindingsAndExtensions(rrcs, conflicts); return conflicts; } @Test public void testCompareDefaults() throws Exception { ResourceRefConfigImpl rrc1 = new ResourceRefConfigImpl("name", "type"); ResourceRefConfigImpl rrc2 = new ResourceRefConfigImpl("name", "type"); List<ResourceRefConfig.MergeConflict> conflicts = rrc1.compareBindingsAndExtensions(rrc2); Assert.assertTrue(conflicts.toString(), conflicts.isEmpty()); } @Test public void testCompareSetDefaults() throws Exception { ResourceRefConfigImpl rrc1 = new ResourceRefConfigImpl("name", "type"); ResourceRefConfigImpl rrc2 = new ResourceRefConfigImpl("name", "type"); rrc2.setLoginConfigurationName(null); rrc2.setIsolationLevel(Connection.TRANSACTION_NONE); rrc2.setCommitPriority(0); List<ResourceRefConfig.MergeConflict> conflicts = rrc1.compareBindingsAndExtensions(rrc2); Assert.assertTrue(conflicts.toString(), conflicts.isEmpty()); } @Test public void testCompareEqual() throws Exception { List<ResourceRefConfigImpl> rrcs = new ArrayList<ResourceRefConfigImpl>(); for (int i = 0; i < 2; i++) { ResourceRefConfigImpl rrc = new ResourceRefConfigImpl("name", "type"); rrc.setLoginConfigurationName("lcn"); rrc.addLoginProperty("name1", "value1"); rrc.addLoginProperty("name2", "value2"); rrc.setIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ); rrc.setCommitPriority(1); rrc.setBranchCoupling(ResourceRefConfig.BRANCH_COUPLING_LOOSE); rrcs.add(rrc); } List<ResourceRefConfig.MergeConflict> conflicts = rrcs.get(0).compareBindingsAndExtensions(rrcs.get(1)); Assert.assertTrue(conflicts.toString(), conflicts.isEmpty()); } private static void assertCompareConflict(ResourceRefConfig rrc1, ResourceRefConfig rrc2, String attributeName, Object value1, Object value2) { List<ResourceRefConfig.MergeConflict> conflicts = rrc1.compareBindingsAndExtensions(rrc2); Assert.assertEquals(conflicts.toString(), 1, conflicts.size()); ResourceRefConfig.MergeConflict conflict = conflicts.get(0); Assert.assertEquals(conflict.toString(), attributeName, conflict.getAttributeName()); Assert.assertEquals(conflict.toString(), 0, conflict.getIndex1()); Assert.assertEquals(conflict.toString(), value1, conflict.getValue1()); Assert.assertEquals(conflict.toString(), 1, conflict.getIndex2()); Assert.assertEquals(conflict.toString(), value2, conflict.getValue2()); } @Test public void testCompareLoginConfigurationNameConflict() throws Exception { ResourceRefConfigImpl rrc1 = new ResourceRefConfigImpl("name", "type"); ResourceRefConfigImpl rrc2 = new ResourceRefConfigImpl("name", "type"); rrc2.setLoginConfigurationName("lcn"); assertCompareConflict(rrc1, rrc2, "custom-login-configuration", "null", "lcn"); rrc1 = new ResourceRefConfigImpl("name", "type"); rrc1.setLoginConfigurationName("lcn"); rrc2 = new ResourceRefConfigImpl("name", "type"); assertCompareConflict(rrc1, rrc2, "custom-login-configuration", "lcn", "null"); rrc1 = new ResourceRefConfigImpl("name", "type"); rrc1.setLoginConfigurationName("lcn1"); rrc2 = new ResourceRefConfigImpl("name", "type"); rrc2.setLoginConfigurationName("lcn2"); assertCompareConflict(rrc1, rrc2, "custom-login-configuration", "lcn1", "lcn2"); } @Test public void testCompareLoginPropertyConflict() throws Exception { ResourceRefConfigImpl rrc1 = new ResourceRefConfigImpl("name", "type"); ResourceRefConfigImpl rrc2 = new ResourceRefConfigImpl("name", "type"); rrc2.addLoginProperty("name", "value"); assertCompareConflict(rrc1, rrc2, "custom-login-configuration name", "null", "value"); rrc1 = new ResourceRefConfigImpl("name", "type"); rrc1.addLoginProperty("name", "value"); rrc2 = new ResourceRefConfigImpl("name", "type"); assertCompareConflict(rrc1, rrc2, "custom-login-configuration name", "value", "null"); rrc1 = new ResourceRefConfigImpl("name", "type"); rrc1.addLoginProperty("name", "value1"); rrc2 = new ResourceRefConfigImpl("name", "type"); rrc2.addLoginProperty("name", "value2"); assertCompareConflict(rrc1, rrc2, "custom-login-configuration name", "value1", "value2"); rrc1 = new ResourceRefConfigImpl("name", "type"); rrc1.addLoginProperty("name1", "value"); rrc2 = new ResourceRefConfigImpl("name", "type"); rrc2.addLoginProperty("name2", "value"); List<ResourceRefConfig.MergeConflict> conflicts = rrc1.compareBindingsAndExtensions(rrc2); Assert.assertEquals(conflicts.toString(), 2, conflicts.size()); for (int i = 0; i < 2; i++) { ResourceRefConfig.MergeConflict conflict = conflicts.get(i); Assert.assertEquals(conflict.toString(), "custom-login-configuration name" + (i + 1), conflict.getAttributeName()); Assert.assertEquals(conflict.toString(), 0, conflict.getIndex1()); Assert.assertEquals(conflict.toString(), i == 0 ? "value" : "null", conflict.getValue1()); Assert.assertEquals(conflict.toString(), 1, conflict.getIndex2()); Assert.assertEquals(conflict.toString(), i == 0 ? "null" : "value", conflict.getValue2()); } } @Test public void testCompareIsolationLevelConflict() throws Exception { ResourceRefConfigImpl rrc1 = new ResourceRefConfigImpl("name", "type"); ResourceRefConfigImpl rrc2 = new ResourceRefConfigImpl("name", "type"); rrc2.setIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ); assertCompareConflict(rrc1, rrc2, "isolation-level", "TRANSACTION_NONE", "TRANSACTION_REPEATABLE_READ"); rrc1 = new ResourceRefConfigImpl("name", "type"); rrc1.setIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ); rrc2 = new ResourceRefConfigImpl("name", "type"); assertCompareConflict(rrc1, rrc2, "isolation-level", "TRANSACTION_REPEATABLE_READ", "TRANSACTION_NONE"); rrc1 = new ResourceRefConfigImpl("name", "type"); rrc1.setIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ); rrc2 = new ResourceRefConfigImpl("name", "type"); rrc2.setIsolationLevel(Connection.TRANSACTION_SERIALIZABLE); assertCompareConflict(rrc1, rrc2, "isolation-level", "TRANSACTION_REPEATABLE_READ", "TRANSACTION_SERIALIZABLE"); } @Test public void testCompareCommitPriorityConflict() throws Exception { ResourceRefConfigImpl rrc1 = new ResourceRefConfigImpl("name", "type"); ResourceRefConfigImpl rrc2 = new ResourceRefConfigImpl("name", "type"); rrc2.setCommitPriority(1); assertCompareConflict(rrc1, rrc2, "commit-priority", "0", "1"); rrc1 = new ResourceRefConfigImpl("name", "type"); rrc1.setCommitPriority(1); rrc2 = new ResourceRefConfigImpl("name", "type"); assertCompareConflict(rrc1, rrc2, "commit-priority", "1", "0"); rrc1 = new ResourceRefConfigImpl("name", "type"); rrc1.setCommitPriority(1); rrc2 = new ResourceRefConfigImpl("name", "type"); rrc2.setCommitPriority(2); assertCompareConflict(rrc1, rrc2, "commit-priority", "1", "2"); } @Test public void testCompareBranchCouplingConflict() throws Exception { ResourceRefConfigImpl rrc1 = new ResourceRefConfigImpl("name", "type"); ResourceRefConfigImpl rrc2 = new ResourceRefConfigImpl("name", "type"); rrc2.setBranchCoupling(ResourceRefConfig.BRANCH_COUPLING_LOOSE); assertCompareConflict(rrc1, rrc2, "branch-coupling", "null", "LOOSE"); rrc1 = new ResourceRefConfigImpl("name", "type"); rrc1.setBranchCoupling(ResourceRefConfig.BRANCH_COUPLING_LOOSE); rrc2 = new ResourceRefConfigImpl("name", "type"); assertCompareConflict(rrc1, rrc2, "branch-coupling", "LOOSE", "null"); rrc1 = new ResourceRefConfigImpl("name", "type"); rrc1.setBranchCoupling(ResourceRefConfig.BRANCH_COUPLING_LOOSE); rrc2 = new ResourceRefConfigImpl("name", "type"); rrc2.setBranchCoupling(ResourceRefConfig.BRANCH_COUPLING_TIGHT); assertCompareConflict(rrc1, rrc2, "branch-coupling", "LOOSE", "TIGHT"); } }
epl-1.0
opendaylight/opflex
libopflex/comms/test/handlers/error_response/endpoint_unresolve.cpp
586
/* * Copyright (c) 2014 Cisco Systems, Inc. and others. 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 */ /* This must be included before anything else */ #if HAVE_CONFIG_H # include <config.h> #endif #include <yajr/rpc/methods.hpp> namespace yajr { namespace rpc { template<> void InbErr<&yajr::rpc::method::endpoint_unresolve>::process() const { LOG(ERROR); } } }
epl-1.0
jarrah42/eavp
org.eclipse.eavp.viz.modeling/src/org/eclipse/eavp/viz/modeling/factory/IControllerProviderFactory.java
1456
/******************************************************************************* * Copyright (c) 2015 UT-Battelle, LLC. * 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 * * Contributors: * Robert Smith *******************************************************************************/ package org.eclipse.eavp.viz.modeling.factory; import org.eclipse.eavp.viz.modeling.base.IMesh; /** * A interface for classes which serve IControllerProviders. An * IControllerFactory takes as input an IMesh and returns an IControllerProvider * which is capable of processing that IMesh. An IControllerFactory * implementation should be specific as to what kind of view and/or controller * its IControllerProviders create, as the same IMesh may be valid for use with * multiple separate implementations of IView and IController. * * @author Robert Smith * */ public interface IControllerProviderFactory { /** * Creates a controller and associated view for the given model. * * @param model * The model for which a controller will be created * @return The new controller, which contains the input model and the new * view */ public IControllerProvider createProvider(IMesh model); }
epl-1.0
eclipse/hawkbit
hawkbit-rest/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiCancelActionTest.java
34040
/** * Copyright (c) 2015 Bosch Software Innovations GmbH and others. * * 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.eclipse.hawkbit.ddi.rest.resource; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.startsWith; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.ArrayList; import java.util.List; import org.eclipse.hawkbit.ddi.rest.api.DdiRestConstants; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.test.util.TestdataFactory; import org.eclipse.hawkbit.rest.util.JsonBuilder; import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.junit.jupiter.api.Test; import org.springframework.hateoas.MediaTypes; import org.springframework.http.MediaType; import org.springframework.integration.json.JsonPathUtils; import io.qameta.allure.Description; import io.qameta.allure.Feature; import io.qameta.allure.Story; /** * Test cancel action from the controller. */ @Feature("Component Tests - Direct Device Integration API") @Story("Cancel Action Resource") class DdiCancelActionTest extends AbstractDDiApiIntegrationTest { @Test @Description("Tests that the cancel action resource can be used with CBOR.") void cancelActionCbor() throws Exception { final DistributionSet ds = testdataFactory.createDistributionSet(""); testdataFactory.createTarget(); final Long actionId = getFirstAssignedActionId( assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID)); final Action cancelAction = deploymentManagement.cancelAction(actionId); // check that we can get the cancel action as CBOR final byte[] result = mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId(), tenantAware.getCurrentTenant()).accept(DdiRestConstants.MEDIA_TYPE_CBOR)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(DdiRestConstants.MEDIA_TYPE_CBOR)) .andReturn().getResponse().getContentAsByteArray(); assertThat(JsonPathUtils.<String>evaluate(cborToJson(result), "$.id")).isEqualTo(String.valueOf(cancelAction.getId())); assertThat(JsonPathUtils.<String>evaluate(cborToJson(result), "$.cancelAction.stopId")).isEqualTo(String.valueOf(actionId)); // and submit feedback as CBOR mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()).content( jsonToCbor(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "proceeding"))) .contentType(DdiRestConstants.MEDIA_TYPE_CBOR).accept(DdiRestConstants.MEDIA_TYPE_CBOR)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); } @Test @Description("Test of the controller can continue a started update even after a cancel command if it so desires.") void rootRsCancelActionButContinueAnyway() throws Exception { // prepare test data final DistributionSet ds = testdataFactory.createDistributionSet(""); final Target savedTarget = testdataFactory.createTarget(); final Long actionId = getFirstAssignedActionId( assignDistributionSet(ds.getId(), savedTarget.getControllerId())); final Action cancelAction = deploymentManagement.cancelAction(actionId); // controller rejects cancelation mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "rejected")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); final long current = System.currentTimeMillis(); // get update action anyway mvc.perform( get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/deploymentBase/" + actionId, tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id", equalTo(String.valueOf(actionId)))) .andExpect(jsonPath("$.deployment.download", equalTo("forced"))) .andExpect(jsonPath("$.deployment.update", equalTo("forced"))) .andExpect(jsonPath("$.deployment.chunks[?(@.part=='jvm')].version", contains(ds.findFirstModuleByType(runtimeType).get().getVersion()))) .andExpect(jsonPath("$.deployment.chunks[?(@.part=='os')].version", contains(ds.findFirstModuleByType(osType).get().getVersion()))) .andExpect(jsonPath("$.deployment.chunks[?(@.part=='bApp')].version", contains(ds.findFirstModuleByType(appType).get().getVersion()))); // and finish it mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/deploymentBase/" + actionId + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.deploymentActionFeedback(actionId.toString(), "closed", "success")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); // check database after test assertThat(deploymentManagement.getAssignedDistributionSet(TestdataFactory.DEFAULT_CONTROLLER_ID).get()) .isEqualTo(ds); assertThat(deploymentManagement.getInstalledDistributionSet(TestdataFactory.DEFAULT_CONTROLLER_ID).get()) .isEqualTo(ds); assertThat( targetManagement.getByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get().getInstallationDate()) .isGreaterThanOrEqualTo(current); } @Test @Description("Test for cancel operation of a update action.") void rootRsCancelAction() throws Exception { final DistributionSet ds = testdataFactory.createDistributionSet(""); final Target savedTarget = testdataFactory.createTarget(); final Long actionId = getFirstAssignedActionId( assignDistributionSet(ds.getId(), savedTarget.getControllerId())); final long timeBeforeFirstPoll = System.currentTimeMillis(); mvc.perform(get("/{tenant}/controller/v1/{controller}", tenantAware.getCurrentTenant(), TestdataFactory.DEFAULT_CONTROLLER_ID).accept(MediaTypes.HAL_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaTypes.HAL_JSON)) .andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00"))) .andExpect(jsonPath("$._links.deploymentBase.href", startsWith("http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/deploymentBase/" + actionId))); final long timeAfterFirstPoll = System.currentTimeMillis() + 1; assertThat(targetManagement.getByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get().getLastTargetQuery()) .isBetween(timeBeforeFirstPoll, timeAfterFirstPoll); // Retrieved is reported List<Action> activeActionsByTarget = deploymentManagement .findActiveActionsByTarget(PAGE, savedTarget.getControllerId()).getContent(); assertThat(activeActionsByTarget).hasSize(1); assertThat(activeActionsByTarget.get(0).getStatus()).isEqualTo(Status.RUNNING); final Action cancelAction = deploymentManagement.cancelAction(actionId); activeActionsByTarget = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId()) .getContent(); // the canceled action should still be active! assertThat(cancelAction.isActive()).isTrue(); assertThat(activeActionsByTarget).hasSize(1); assertThat(activeActionsByTarget.get(0).getStatus()).isEqualTo(Status.CANCELING); final long timeBefore2ndPoll = System.currentTimeMillis(); mvc.perform(get("/{tenant}/controller/v1/{controller}", tenantAware.getCurrentTenant(), TestdataFactory.DEFAULT_CONTROLLER_ID)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaTypes.HAL_JSON)) .andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00"))) .andExpect(jsonPath("$._links.cancelAction.href", equalTo("http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId()))); final long timeAfter2ndPoll = System.currentTimeMillis() + 1; assertThat(targetManagement.getByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get().getLastTargetQuery()) .isBetween(timeBefore2ndPoll, timeAfter2ndPoll); mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId(), tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id", equalTo(String.valueOf(cancelAction.getId())))) .andExpect(jsonPath("$.cancelAction.stopId", equalTo(String.valueOf(actionId)))); assertThat(targetManagement.getByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get().getLastTargetQuery()) .isLessThanOrEqualTo(System.currentTimeMillis()); // controller confirmed cancelled action, should not be active anymore mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON) .content(JsonBuilder.cancelActionFeedback(actionId.toString(), "closed")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); activeActionsByTarget = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId()) .getContent(); assertThat(activeActionsByTarget).isEmpty(); final Action canceledAction = deploymentManagement.findAction(cancelAction.getId()).get(); assertThat(canceledAction.isActive()).isFalse(); assertThat(canceledAction.getStatus()).isEqualTo(Status.CANCELED); } @Test @Description("Tests various bad requests and if the server handles them as expected.") void badCancelAction() throws Exception { // not allowed methods mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/1", tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print()) .andExpect(status().isMethodNotAllowed()); mvc.perform(put("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/1", tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print()) .andExpect(status().isMethodNotAllowed()); mvc.perform(delete("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/1", tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print()) .andExpect(status().isMethodNotAllowed()); // non existing target mvc.perform(get("/{tenant}/controller/v1/34534543/cancelAction/1", tenantAware.getCurrentTenant()) .accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isNotFound()); createCancelAction("34534543"); // wrong media type mvc.perform(get("/{tenant}/controller/v1/34534543/cancelAction/1", tenantAware.getCurrentTenant()) .accept(MediaType.APPLICATION_ATOM_XML)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isNotAcceptable()); } private Action createCancelAction(final String targetid) { final DistributionSet ds = testdataFactory.createDistributionSet(targetid); final Target savedTarget = testdataFactory.createTarget(targetid); final List<Target> toAssign = new ArrayList<>(); toAssign.add(savedTarget); final Long actionId = getFirstAssignedActionId(assignDistributionSet(ds, toAssign)); return deploymentManagement.cancelAction(actionId); } @Test @Description("Tests the feedback channel of the cancel operation.") void rootRsCancelActionFeedback() throws Exception { final DistributionSet ds = testdataFactory.createDistributionSet(""); final Target savedTarget = testdataFactory.createTarget(); final Long actionId = getFirstAssignedActionId( assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID)); // cancel action manually final Action cancelAction = deploymentManagement.cancelAction(actionId); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(2); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1); mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "proceeding")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(3); mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "resumed")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(4); mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "scheduled")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(5); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1); // cancellation canceled -> should remove the action from active assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1); mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "canceled")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(6); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1); // cancellation rejected -> action still active until controller close // it // with finished or // error assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1); mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "rejected")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(7); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1); // update closed -> should remove the action from active mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/deploymentBase/" + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(8); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).isEmpty(); } @Test @Description("Tests the feeback chanel of for multiple open cancel operations on the same target.") void multipleCancelActionFeedback() throws Exception { final DistributionSet ds = testdataFactory.createDistributionSet("", true); final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true); final DistributionSet ds3 = testdataFactory.createDistributionSet("3", true); final Target savedTarget = testdataFactory.createTarget(); final Long actionId = getFirstAssignedActionId( assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID)); final Long actionId2 = getFirstAssignedActionId( assignDistributionSet(ds2.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID)); final Long actionId3 = getFirstAssignedActionId( assignDistributionSet(ds3.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID)); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(3); // 3 update actions, 0 cancel actions assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(3); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(3); final Action cancelAction = deploymentManagement.cancelAction(actionId); final Action cancelAction2 = deploymentManagement.cancelAction(actionId2); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(3); assertThat(deploymentManagement.countActionsByTarget(savedTarget.getControllerId())).isEqualTo(3); mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId(), tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.id", equalTo(String.valueOf(cancelAction.getId())))) .andExpect(jsonPath("$.cancelAction.stopId", equalTo(String.valueOf(actionId)))); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(6); mvc.perform(get("/{tenant}/controller/v1/{controllerId}", tenantAware.getCurrentTenant(), TestdataFactory.DEFAULT_CONTROLLER_ID)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaTypes.HAL_JSON)) .andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00"))) .andExpect(jsonPath("$._links.cancelAction.href", equalTo("http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId()))); // now lets return feedback for the first cancelation mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(7); // 1 update actions, 1 cancel actions assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(2); assertThat(deploymentManagement.countActionsByTarget(savedTarget.getControllerId())).isEqualTo(3); mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction2.getId(), tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id", equalTo(String.valueOf(cancelAction2.getId())))) .andExpect(jsonPath("$.cancelAction.stopId", equalTo(String.valueOf(actionId2)))); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(8); mvc.perform(get("/{tenant}/controller/v1/{controller}", tenantAware.getCurrentTenant(), TestdataFactory.DEFAULT_CONTROLLER_ID)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaTypes.HAL_JSON)) .andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00"))) .andExpect(jsonPath("$._links.cancelAction.href", equalTo("http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction2.getId()))); // now lets return feedback for the second cancelation mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction2.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction2.getId().toString(), "closed")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(9); assertThat(deploymentManagement.getAssignedDistributionSet(TestdataFactory.DEFAULT_CONTROLLER_ID).get()) .isEqualTo(ds3); mvc.perform( get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/deploymentBase/" + actionId3, tenantAware.getCurrentTenant())) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(10); // 1 update actions, 0 cancel actions assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1); final Action cancelAction3 = deploymentManagement.cancelAction(actionId3); // action is in cancelling state assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1); assertThat(deploymentManagement.countActionsByTarget(savedTarget.getControllerId())).isEqualTo(3); assertThat(deploymentManagement.getAssignedDistributionSet(TestdataFactory.DEFAULT_CONTROLLER_ID).get()) .isEqualTo(ds3); mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction3.getId(), tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id", equalTo(String.valueOf(cancelAction3.getId())))) .andExpect(jsonPath("$.cancelAction.stopId", equalTo(String.valueOf(actionId3)))); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(12); // now lets return feedback for the third cancelation mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction3.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction3.getId().toString(), "closed")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(13); // final status assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).isEmpty(); assertThat(deploymentManagement.countActionsByTarget(savedTarget.getControllerId())).isEqualTo(3); } @Test @Description("Tests the feeback channel closing for too many feedbacks, i.e. denial of service prevention.") void tooMuchCancelActionFeedback() throws Exception { testdataFactory.createTarget(); final DistributionSet ds = testdataFactory.createDistributionSet(""); final Long actionId = getFirstAssignedActionId( assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID)); final Action cancelAction = deploymentManagement.cancelAction(actionId); final String feedback = JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "proceeding"); // assignDistributionSet creates an ActionStatus and cancel action // stores an action status, so // only 97 action status left for (int i = 0; i < 98; i++) { mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()).content(feedback) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); } mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()).content(feedback) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isForbidden()); } @Test @Description("test the correct rejection of various invalid feedback requests") void badCancelActionFeedback() throws Exception { final Action cancelAction = createCancelAction(TestdataFactory.DEFAULT_CONTROLLER_ID); createCancelAction("4715"); // not allowed methods mvc.perform(put("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed()); mvc.perform(delete("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant())) .andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed()); mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant())) .andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed()); // bad content type mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed")) .contentType(MediaType.APPLICATION_ATOM_XML).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isUnsupportedMediaType()); // bad body mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "546456456")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()); // non existing target mvc.perform(post("/{tenant}/controller/v1/12345/cancelAction/" + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound()); // invalid action mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback("sdfsdfsdfs", "closed")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()); // finaly, get it right :) mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.ui/resources/WEB-CONTENT/unittest/toolbox/toolboxTests.js
14570
/******************************************************************************* * Copyright (c) 2015 IBM Corporation and others. * 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 * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ define(["intern!tdd","intern/chai!assert","dojo/Deferred","js/toolbox/toolbox"], function(tdd,assert,Deferred,toolbox) { var server, testBookmark, testFeatureTool; with(assert) { /** * Defines the 'toolbox' module test suite. */ tdd.suite("Toolbox Tests", function() { tdd.before(function() { testBookmark = { id: "myTool", type:"bookmark", name:"myTool", url:"ibm.com", icon:"default.png" }; testToolEntry = { id: "myFeature-1.0", type:"featureTool", }; }); tdd.beforeEach(function() { // Mock the admin center server since it is not available in a unittest server = sinon.fakeServer.create(); }); tdd.afterEach(function() { server.restore(); }); tdd.test("ToolEntry - create from ToolEntry", function() { var tool = new Toolbox.ToolEntry(testToolEntry); console.log("DEBUG", tool); assert.equal(tool.id, testToolEntry.id, "ToolEntry was not constructed with correct value for 'id'"); assert.equal(tool.type, testToolEntry.type, "ToolEntry was not constructed with correct value for 'type'"); assert.isUndefined(tool.name, "ToolEntry should not have a name"); }); tdd.test("ToolEntry - create from Bookmark", function() { var tool = new Toolbox.ToolEntry(testBookmark); console.log("DEBUG", tool); assert.equal(tool.id, testBookmark.id, "ToolEntry was not constructed with correct value for 'id'"); assert.equal(tool.type, testBookmark.type, "ToolEntry was not constructed with correct value for 'type'"); assert.isUndefined(tool.name, "ToolEntry should not have a name even though it was created from an Object that had a name"); }); tdd.test("Bookmark - create", function() { var tool = new Toolbox.Bookmark(testBookmark); assert.isUndefined(tool.id, "Tool was constructed with an 'id'"); assert.isUndefined(tool.type, "Tool was constructed with an 'type'"); assert.equal(tool.name, testBookmark.name, "Tool was not constructed with correct value for 'name'"); assert.equal(tool.url, testBookmark.url, "Tool was not constructed with correct value for 'url'"); assert.equal(tool.icon, testBookmark.icon, "Tool was not constructed with correct value for 'icon'"); }); tdd.test("Toolbox - construct", function() { var tb = new Toolbox(); assert.isTrue(tb instanceof Toolbox, "Unable to construct Toolbox"); }); tdd.test("Toolbox - get instance", function() { var tb = toolbox.getToolbox(); assert.isTrue(tb instanceof Toolbox, "Unable to get instance of Toolbox"); }); tdd.test("Toolbox - get instance is same instance", function() { var tbNew = new Toolbox(); var tbInst = toolbox.getToolbox(); assert.isFalse(tbInst === tbNew, "The 'singleton' instance of Toolbox should not match a 'new' instance of Toolbox"); assert.isTrue(tbInst === toolbox.getToolbox(), "The 'singleton' instance of Toolbox should match the previous return for the singleton"); }); tdd.test("toolbox.getToolEntries - returns Deferred", function() { assert.isTrue(toolbox.getToolbox().getToolEntries() instanceof Deferred, "Toolbox.getToolEntries should return a Deferred"); }); tdd.test("toolbox.getToolEntries - resolves with Array (no Tools)", function() { var dfd = this.async(1000); toolbox.getToolbox().getToolEntries().then(dfd.callback(function(tools) { assert.isTrue(tools instanceof Array, "Toolbox.getToolEntries should resolve with an Array"); }), function(err) { dfd.reject(err); }); server.respondWith("GET", "/ibm/api/adminCenter/v1/toolbox/toolEntries", [200, { "Content-Type": "application/json" },'{"toolEntries":[]}']); server.respond(); return dfd; }); tdd.test("toolbox.getToolEntries - resolves with Array of Tool objects", function() { var dfd = this.async(1000); toolbox.getToolbox().getToolEntries().then(dfd.callback(function(tools) { assert.isTrue(tools instanceof Array, "Toolbox.getToolEntries should resolve with an Array"); assert.equal(tools.length, 1, "Expected exactly 1 tool back from the mock response"); var tool = tools[0]; assert.equal(tool.id, testToolEntry.id, "Tool was not constructed with correct value for 'id'"); assert.equal(tool.type, testToolEntry.type, "Tool was not constructed with correct value for 'type'"); }), function(err) { dfd.reject(err); }); server.respondWith("GET", "/ibm/api/adminCenter/v1/toolbox/toolEntries", [200, { "Content-Type": "application/json" },'['+JSON.stringify(testToolEntry)+']']); server.respond(); return dfd; }); tdd.test("toolbox.getTool - returns Deferred", function() { assert.isTrue(toolbox.getToolbox().getTool('myTool') instanceof Deferred, "Toolbox.getTool should return a Deferred"); }); tdd.test("toolbox.getTool - returns a Tool", function() { var dfd = this.async(1000); toolbox.getToolbox().getTool('myTool').then(dfd.callback(function(tool) { assert.equal(tool.id, testBookmark.id, "Returned tool did not have correct value for 'id'"); assert.equal(tool.type, testBookmark.type, "Returned tool did not have correct value for 'type'"); assert.equal(tool.name, testBookmark.name, "Returned tool did not have correct value for 'name'"); assert.equal(tool.url, testBookmark.url, "Returned tool did not have correct value for 'url'"); assert.equal(tool.icon, testBookmark.icon, "Returned tool did not have correct value for 'icon'"); }), function(err) { dfd.reject(err); }); server.respondWith("GET", "/ibm/api/adminCenter/v1/toolbox/toolEntries/myTool", [200, { "Content-Type": "application/json" }, JSON.stringify(testBookmark)]); server.respond(); return dfd; }); tdd.test("Toolbox.getTool - filtered Tool", function() { var dfd = this.async(1000); toolbox.getToolbox().getTool('myTool', 'name,url').then(dfd.callback(function(tool) { assert.equal(tool.id, null, "Returned tool was filtered and should not have an 'id'"); assert.equal(tool.type, null, "Returned tool was filtered and should not have a 'type'"); assert.equal(tool.name, testBookmark.name, "Returned tool did not have correct value for 'name'"); assert.equal(tool.url, testBookmark.url, "Returned tool did not have correct value for 'url'"); assert.equal(tool.icon, null, "Returned tool was filtered and should not have an 'icon'"); }), function(err) { dfd.reject(err); }); server.respondWith("GET", "/ibm/api/adminCenter/v1/toolbox/toolEntries/myTool?fields=name,url", [200, { "Content-Type": "application/json" }, '{"name":"'+testBookmark.name+'","url":"'+testBookmark.url+'"}']); server.respond(); return dfd; }); tdd.test("Toolbox.getTool - no provided Tool ID", function() { try { toolbox.getToolbox().getTool(); assert.isTrue(false, "Toolbox.getTool should throw an error when no tool ID is provided"); } catch(err) { // Pass } }); tdd.test("Toolbox.addToolEntry - returns Deferred", function() { assert.isTrue(toolbox.getToolbox().addToolEntry(testBookmark) instanceof Deferred, "Toolbox.addToolEntry should return a Deferred"); }); tdd.test("Toolbox.addToolEntry - returns the created ToolEntry", function() { var dfd = this.async(1000); toolbox.getToolbox().addToolEntry(testBookmark).then(dfd.callback(function(tool) { assert.equal(tool.id, testBookmark.id, "Returned tool did not have correct value for 'id'"); assert.equal(tool.type, testBookmark.type, "Returned tool did not have correct value for 'type'"); assert.equal(tool.name, testBookmark.name, "Returned tool did not have correct value for 'name'"); assert.equal(tool.url, testBookmark.url, "Returned tool did not have correct value for 'url'"); assert.equal(tool.icon, testBookmark.icon, "Returned tool did not have correct value for 'icon'"); }), function(err) { dfd.reject(err); }); server.respondWith("POST", "/ibm/api/adminCenter/v1/toolbox/toolEntries", [201, { "Content-Type": "application/json" }, JSON.stringify(testBookmark)]); server.respond(); return dfd; }); tdd.test("Toolbox.addToolEntry - no provided ToolEntry props", function() { try { toolbox.getToolbox().addToolEntry(); assert.isTrue(false, "Toolbox.addToolEntry should throw an error when no tool ID is provided"); } catch(err) { // Pass } }); tdd.test("Toolbox.addBookmark - returns Deferred", function() { assert.isTrue(toolbox.getToolbox().addBookmark(testBookmark) instanceof Deferred, "Toolbox.addBookmark should return a Deferred"); }); tdd.test("Toolbox.addBookmark - returns the created Bookmark", function() { var dfd = this.async(1000); toolbox.getToolbox().addBookmark(testBookmark).then(dfd.callback(function(tool) { assert.equal(tool.id, testBookmark.id, "Returned tool did not have correct value for 'id'"); assert.equal(tool.type, testBookmark.type, "Returned tool did not have correct value for 'type'"); assert.equal(tool.name, testBookmark.name, "Returned tool did not have correct value for 'name'"); assert.equal(tool.url, testBookmark.url, "Returned tool did not have correct value for 'url'"); assert.equal(tool.icon, testBookmark.icon, "Returned tool did not have correct value for 'icon'"); }), function(err) { dfd.reject(err); }); server.respondWith("POST", "/ibm/api/adminCenter/v1/toolbox/bookmarks", [201, { "Content-Type": "application/json" }, JSON.stringify(testBookmark)]); server.respond(); return dfd; }); tdd.test("Toolbox.addBookmark - no provided Bookmark props", function() { try { toolbox.getToolbox().addBookmark(); assert.isTrue(false, "Toolbox.addBookmark should throw an error when no tool ID is provided"); } catch(err) { // Pass } }); tdd.test("Toolbox.deleteTool - returns Deferred", function() { assert.isTrue(toolbox.getToolbox().deleteTool('myTool') instanceof Deferred, "Toolbox.deleteTool should return a Deferred"); }); tdd.test("Toolbox.deleteTool - returns the deleted entry's JSON", function() { var dfd = this.async(1000); toolbox.getToolbox().deleteTool(testBookmark.id).then(dfd.callback(function(tool) { assert.equal(tool.id, testBookmark.id, "Returned tool did not have correct value for 'id'"); assert.equal(tool.type, testBookmark.type, "Returned tool did not have correct value for 'type'"); assert.equal(tool.name, testBookmark.name, "Returned tool did not have correct value for 'name'"); assert.equal(tool.url, testBookmark.url, "Returned tool did not have correct value for 'url'"); assert.equal(tool.icon, testBookmark.icon, "Returned tool did not have correct value for 'icon'"); }), function(err) { dfd.reject(err); }); server.respondWith("DELETE", "/ibm/api/adminCenter/v1/toolbox/toolEntries/myTool", [200, { "Content-Type": "application/json" }, JSON.stringify(testBookmark)]); server.respond(); return dfd; }); tdd.test("Toolbox.deleteTool - no provided Tool ID", function() { try { toolbox.getToolbox().deleteTool(); assert.isTrue(false, "Toolbox.deleteTool should throw an error when no tool ID is provided"); } catch(err) { // Pass } }); }); } });
epl-1.0
stzilli/kapua
simulator-kura/src/main/java/org/eclipse/kapua/kura/simulator/Simulator.java
2615
/******************************************************************************* * Copyright (c) 2017, 2021 Red Hat Inc and others * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat Inc - initial API and implementation *******************************************************************************/ package org.eclipse.kapua.kura.simulator; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.eclipse.kapua.kura.simulator.app.Application; import org.eclipse.kapua.kura.simulator.app.ApplicationController; import org.eclipse.kapua.kura.simulator.birth.BirthCertificateModule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A default Kura simulator */ public class Simulator implements AutoCloseable { private static final Logger logger = LoggerFactory.getLogger(Simulator.class); protected final Transport transport; protected List<Module> modules = new LinkedList<>(); public Simulator(final GatewayConfiguration configuration, final Transport transport, final Set<Application> applications) { this.transport = transport; // set up callbacks this.transport.whenConnected(this::connected); this.transport.whenDisconnected(this::disconnected); // set up application controller final ApplicationController applicationController = new ApplicationController(transport, applications); modules.add(applicationController); // set up builder modules.add(new BirthCertificateModule(configuration, applicationController::getApplicationIds)); // finally connect this.transport.connect(); } @Override public void close() { // we don't close the transport here } protected void connected() { logger.info("Connected ... sending birth certificate ..."); for (final Module module : modules) { try { module.connected(transport); } catch (final Exception e) { logger.warn("Failed to call module: {}", module, e); } } } protected void disconnected() { for (final Module module : modules) { try { module.disconnected(transport); } catch (final Exception e) { logger.warn("Failed to call module: {}", module, e); } } } }
epl-1.0
ohio813/MultiPatch
xdelta/testing/regtest.cc
23901
/* -*- Mode: C++ -*- */ #include "test.h" #include "random.h" #include "sizes.h" template <typename Constants> class Regtest { public: typedef typename Constants::Sizes Sizes; struct Options { size_t encode_srcwin_maxsz; }; #include "segment.h" #include "modify.h" #include "file.h" #include "cmp.h" #include "delta.h" void InMemoryEncodeDecode(const FileSpec &source_file, const FileSpec &target_file, Block *coded_data, const Options &options = Options()) { xd3_stream encode_stream; xd3_config encode_config; xd3_source encode_source; xd3_stream decode_stream; xd3_config decode_config; xd3_source decode_source; xoff_t verified_bytes = 0; xoff_t encoded_bytes = 0; if (coded_data) { coded_data->Reset(); } memset(&encode_stream, 0, sizeof (encode_stream)); memset(&encode_source, 0, sizeof (encode_source)); memset(&decode_stream, 0, sizeof (decode_stream)); memset(&decode_source, 0, sizeof (decode_source)); xd3_init_config(&encode_config, XD3_ADLER32); xd3_init_config(&decode_config, XD3_ADLER32); encode_config.winsize = Constants::WINDOW_SIZE; encode_config.srcwin_maxsz = options.encode_srcwin_maxsz; // TODO! the smatcher setup isn't working, // if (options.large_cksum_step) { // encode_config.smatch_cfg = XD3_SMATCH_SOFT; // encode_config.smatcher_soft.large_step = options.large_cksum_step; // } // if (options.large_cksum_size) { // encode_config.smatch_cfg = XD3_SMATCH_SOFT; // encode_config.smatcher_soft.large_look = options.large_cksum_size; // } CHECK_EQ(0, xd3_config_stream (&encode_stream, &encode_config)); CHECK_EQ(0, xd3_config_stream (&decode_stream, &decode_config)); encode_source.blksize = Constants::BLOCK_SIZE; decode_source.blksize = Constants::BLOCK_SIZE; xd3_set_source (&encode_stream, &encode_source); xd3_set_source (&decode_stream, &decode_source); BlockIterator source_iterator(source_file, Constants::BLOCK_SIZE); BlockIterator target_iterator(target_file, Constants::READ_SIZE); Block encode_source_block, decode_source_block; Block decoded_block, target_block; bool encoding = true; bool done = false; bool done_after_input = false; IF_DEBUG1 (DP(RINT "source %"Q"u[%"Q"u] target %"Q"u[%lu] winsize %lu\n", source_file.Size(), Constants::BLOCK_SIZE, target_file.Size(), Constants::READ_SIZE, Constants::WINDOW_SIZE)); while (!done) { target_iterator.Get(&target_block); xoff_t blks = target_iterator.Blocks(); IF_DEBUG2(DP(RINT "target in %s: %llu..%llu %"Q"u(%"Q"u) verified %"Q"u\n", encoding ? "encoding" : "decoding", target_iterator.Offset(), target_iterator.Offset() + target_block.Size(), target_iterator.Blkno(), blks, verified_bytes)); if (blks == 0 || target_iterator.Blkno() == (blks - 1)) { xd3_set_flags(&encode_stream, XD3_FLUSH | encode_stream.flags); } xd3_avail_input(&encode_stream, target_block.Data(), target_block.Size()); encoded_bytes += target_block.Size(); process: int ret; const char *msg; if (encoding) { ret = xd3_encode_input(&encode_stream); msg = encode_stream.msg; } else { ret = xd3_decode_input(&decode_stream); msg = decode_stream.msg; } IF_DEBUG1(DP(RINT "%s = %s %s\n", encoding ? "E " : " D", xd3_strerror(ret), msg == NULL ? "" : msg)); switch (ret) { case XD3_OUTPUT: if (encoding) { if (coded_data != NULL) { // Optional encoded-output to the caller coded_data->Append(encode_stream.next_out, encode_stream.avail_out); } // Feed this data to the decoder. xd3_avail_input(&decode_stream, encode_stream.next_out, encode_stream.avail_out); xd3_consume_output(&encode_stream); encoding = false; } else { decoded_block.Append(decode_stream.next_out, decode_stream.avail_out); xd3_consume_output(&decode_stream); } goto process; case XD3_GETSRCBLK: { xd3_source *src = (encoding ? &encode_source : &decode_source); Block *block = (encoding ? &encode_source_block : &decode_source_block); if (encoding) { IF_DEBUG1(DP(RINT "[srcblock] %"Q"u last srcpos %"Q"u " "encodepos %"Q"u\n", encode_source.getblkno, encode_stream.match_last_srcpos, encode_stream.input_position + encode_stream.total_in)); } source_iterator.SetBlock(src->getblkno); source_iterator.Get(block); src->curblkno = src->getblkno; src->onblk = block->Size(); src->curblk = block->Data(); goto process; } case XD3_INPUT: if (!encoding) { encoding = true; goto process; } else { if (done_after_input) { done = true; continue; } if (target_block.Size() < target_iterator.BlockSize()) { encoding = false; } else { target_iterator.Next(); } continue; } case XD3_WINFINISH: if (encoding) { if (encode_stream.flags & XD3_FLUSH) { done_after_input = true; } encoding = false; } else { CHECK_EQ(0, CmpDifferentBlockBytesAtOffset(decoded_block, target_file, verified_bytes)); verified_bytes += decoded_block.Size(); decoded_block.Reset(); encoding = true; } goto process; case XD3_WINSTART: case XD3_GOTHEADER: goto process; default: CHECK_EQ(0, ret); CHECK_EQ(-1, ret); } } CHECK_EQ(target_file.Size(), encoded_bytes); CHECK_EQ(target_file.Size(), verified_bytes); CHECK_EQ(0, xd3_close_stream(&decode_stream)); CHECK_EQ(0, xd3_close_stream(&encode_stream)); xd3_free_stream(&encode_stream); xd3_free_stream(&decode_stream); } ////////////////////////////////////////////////////////////////////// void TestRandomNumbers() { MTRandom rand; int rounds = 1<<20; uint64_t usum = 0; uint64_t esum = 0; for (int i = 0; i < rounds; i++) { usum += rand.Rand32(); esum += rand.ExpRand32(1024); } double allowed_error = 0.01; uint32_t umean = usum / rounds; uint32_t emean = esum / rounds; uint32_t uexpect = UINT32_MAX / 2; uint32_t eexpect = 1024; if (umean < uexpect * (1.0 - allowed_error) || umean > uexpect * (1.0 + allowed_error)) { cerr << "uniform mean error: " << umean << " != " << uexpect << endl; abort(); } if (emean < eexpect * (1.0 - allowed_error) || emean > eexpect * (1.0 + allowed_error)) { cerr << "exponential mean error: " << emean << " != " << eexpect << endl; abort(); } } void TestRandomFile() { MTRandom rand1; FileSpec spec1(&rand1); BlockIterator bi(spec1); spec1.GenerateFixedSize(0); CHECK_EQ(0, spec1.Size()); CHECK_EQ(0, spec1.Segments()); CHECK_EQ(0, spec1.Blocks()); bi.SetBlock(0); CHECK_EQ(0, bi.BytesOnBlock()); spec1.GenerateFixedSize(1); CHECK_EQ(1, spec1.Size()); CHECK_EQ(1, spec1.Segments()); CHECK_EQ(1, spec1.Blocks()); bi.SetBlock(0); CHECK_EQ(1, bi.BytesOnBlock()); spec1.GenerateFixedSize(Constants::BLOCK_SIZE); CHECK_EQ(Constants::BLOCK_SIZE, spec1.Size()); CHECK_EQ(1, spec1.Segments()); CHECK_EQ(1, spec1.Blocks()); bi.SetBlock(0); CHECK_EQ(Constants::BLOCK_SIZE, bi.BytesOnBlock()); bi.SetBlock(1); CHECK_EQ(0, bi.BytesOnBlock()); spec1.GenerateFixedSize(Constants::BLOCK_SIZE + 1); CHECK_EQ(Constants::BLOCK_SIZE + 1, spec1.Size()); CHECK_EQ(2, spec1.Segments()); CHECK_EQ(2, spec1.Blocks()); bi.SetBlock(0); CHECK_EQ(Constants::BLOCK_SIZE, bi.BytesOnBlock()); bi.SetBlock(1); CHECK_EQ(1, bi.BytesOnBlock()); spec1.GenerateFixedSize(Constants::BLOCK_SIZE * 2); CHECK_EQ(Constants::BLOCK_SIZE * 2, spec1.Size()); CHECK_EQ(2, spec1.Segments()); CHECK_EQ(2, spec1.Blocks()); bi.SetBlock(0); CHECK_EQ(Constants::BLOCK_SIZE, bi.BytesOnBlock()); bi.SetBlock(1); CHECK_EQ(Constants::BLOCK_SIZE, bi.BytesOnBlock()); } void TestFirstByte() { MTRandom rand; FileSpec spec0(&rand); FileSpec spec1(&rand); spec0.GenerateFixedSize(0); spec1.GenerateFixedSize(1); CHECK_EQ(0, CmpDifferentBytes(spec0, spec0)); CHECK_EQ(0, CmpDifferentBytes(spec1, spec1)); CHECK_EQ(1, CmpDifferentBytes(spec0, spec1)); CHECK_EQ(1, CmpDifferentBytes(spec1, spec0)); spec0.GenerateFixedSize(1); spec0.ModifyTo(Modify1stByte(), &spec1); CHECK_EQ(1, CmpDifferentBytes(spec0, spec1)); spec0.GenerateFixedSize(Constants::BLOCK_SIZE + 1); spec0.ModifyTo(Modify1stByte(), &spec1); CHECK_EQ(1, CmpDifferentBytes(spec0, spec1)); SizeIterator<size_t, Sizes> si(&rand, Constants::TEST_ROUNDS); for (; !si.Done(); si.Next()) { size_t size = si.Get(); if (size == 0) { continue; } spec0.GenerateFixedSize(size); spec0.ModifyTo(Modify1stByte(), &spec1); InMemoryEncodeDecode(spec0, spec1, NULL); } } void TestModifyMutator() { MTRandom rand; FileSpec spec0(&rand); FileSpec spec1(&rand); spec0.GenerateFixedSize(Constants::BLOCK_SIZE * 3); struct { size_t size; size_t addr; } test_cases[] = { { Constants::BLOCK_SIZE, 0 }, { Constants::BLOCK_SIZE / 2, 1 }, { Constants::BLOCK_SIZE, 1 }, { Constants::BLOCK_SIZE * 2, 1 }, }; for (size_t i = 0; i < SIZEOF_ARRAY(test_cases); i++) { ChangeList cl1; cl1.push_back(Change(Change::MODIFY, test_cases[i].size, test_cases[i].addr)); spec0.ModifyTo(ChangeListMutator(cl1), &spec1); CHECK_EQ(spec0.Size(), spec1.Size()); size_t diff = CmpDifferentBytes(spec0, spec1); CHECK_LE(diff, test_cases[i].size); // There is a 1/256 probability of the changed byte matching the // original value. The following allows double the probability to // pass. CHECK_GE(diff, test_cases[i].size - (2 * test_cases[i].size / 256)); InMemoryEncodeDecode(spec0, spec1, NULL); } } void TestAddMutator() { MTRandom rand; FileSpec spec0(&rand); FileSpec spec1(&rand); spec0.GenerateFixedSize(Constants::BLOCK_SIZE * 2); // TODO: fix this test (for all block sizes)! it's broken because // the same byte could be added? struct { size_t size; size_t addr; size_t expected_adds; } test_cases[] = { { 1, 0, 2 /* 1st byte, last byte (short block) */ }, { 1, 1, 3 /* 1st 2 bytes, last byte */ }, { 1, Constants::BLOCK_SIZE - 1, 2 /* changed, last */ }, { 1, Constants::BLOCK_SIZE, 2 /* changed, last */ }, { 1, Constants::BLOCK_SIZE + 1, 3 /* changed + 1st of 2nd block, last */ }, { 1, 2 * Constants::BLOCK_SIZE, 1 /* last byte */ }, }; for (size_t i = 0; i < SIZEOF_ARRAY(test_cases); i++) { ChangeList cl1; cl1.push_back(Change(Change::ADD, test_cases[i].size, test_cases[i].addr)); spec0.ModifyTo(ChangeListMutator(cl1), &spec1); CHECK_EQ(spec0.Size() + test_cases[i].size, spec1.Size()); Block coded; InMemoryEncodeDecode(spec0, spec1, &coded); Delta delta(coded); CHECK_EQ(test_cases[i].expected_adds, delta.AddedBytes()); } } void TestDeleteMutator() { MTRandom rand; FileSpec spec0(&rand); FileSpec spec1(&rand); spec0.GenerateFixedSize(Constants::BLOCK_SIZE * 4); struct { size_t size; size_t addr; } test_cases[] = { // Note: an entry { Constants::BLOCK_SIZE, 0 }, // does not work because the xd3_srcwin_move_point logic won't // find a copy if it occurs >= double its size into the file. { Constants::BLOCK_SIZE / 2, 0 }, { Constants::BLOCK_SIZE / 2, Constants::BLOCK_SIZE / 2 }, { Constants::BLOCK_SIZE, Constants::BLOCK_SIZE / 2 }, { Constants::BLOCK_SIZE * 2, Constants::BLOCK_SIZE * 3 / 2 }, { Constants::BLOCK_SIZE, Constants::BLOCK_SIZE * 2 }, }; for (size_t i = 0; i < SIZEOF_ARRAY(test_cases); i++) { ChangeList cl1; cl1.push_back(Change(Change::DELETE, test_cases[i].size, test_cases[i].addr)); spec0.ModifyTo(ChangeListMutator(cl1), &spec1); CHECK_EQ(spec0.Size() - test_cases[i].size, spec1.Size()); Block coded; InMemoryEncodeDecode(spec0, spec1, &coded); Delta delta(coded); CHECK_EQ(0, delta.AddedBytes()); } } void TestCopyMutator() { MTRandom rand; FileSpec spec0(&rand); FileSpec spec1(&rand); spec0.GenerateFixedSize(Constants::BLOCK_SIZE * 3); struct { size_t size; size_t from; size_t to; } test_cases[] = { // Copy is difficult to write tests for because where Xdelta finds // copies, it does not enter checksums. So these tests copy data from // later to earlier so that checksumming will start. { Constants::BLOCK_SIZE / 2, Constants::BLOCK_SIZE / 2, 0 }, { Constants::BLOCK_SIZE, 2 * Constants::BLOCK_SIZE, Constants::BLOCK_SIZE, }, }; for (size_t i = 0; i < SIZEOF_ARRAY(test_cases); i++) { ChangeList cl1; cl1.push_back(Change(Change::COPY, test_cases[i].size, test_cases[i].from, test_cases[i].to)); spec0.ModifyTo(ChangeListMutator(cl1), &spec1); CHECK_EQ(spec0.Size() + test_cases[i].size, spec1.Size()); Block coded; InMemoryEncodeDecode(spec0, spec1, &coded); Delta delta(coded); CHECK_EQ(0, delta.AddedBytes()); } } void TestMoveMutator() { MTRandom rand; FileSpec spec0(&rand); FileSpec spec1(&rand); spec0.GenerateFixedSize(Constants::BLOCK_SIZE * 3); struct { size_t size; size_t from; size_t to; } test_cases[] = { // This is easier to test than Copy but has the same trouble as Delete. { Constants::BLOCK_SIZE / 2, Constants::BLOCK_SIZE / 2, 0 }, { Constants::BLOCK_SIZE / 2, 0, Constants::BLOCK_SIZE / 2 }, { Constants::BLOCK_SIZE, Constants::BLOCK_SIZE, 2 * Constants::BLOCK_SIZE }, { Constants::BLOCK_SIZE, 2 * Constants::BLOCK_SIZE, Constants::BLOCK_SIZE }, { Constants::BLOCK_SIZE * 3 / 2, Constants::BLOCK_SIZE, Constants::BLOCK_SIZE * 3 / 2 }, // This is a no-op { Constants::BLOCK_SIZE, Constants::BLOCK_SIZE * 2, 3 * Constants::BLOCK_SIZE }, }; for (size_t i = 0; i < SIZEOF_ARRAY(test_cases); i++) { ChangeList cl1; cl1.push_back(Change(Change::MOVE, test_cases[i].size, test_cases[i].from, test_cases[i].to)); spec0.ModifyTo(ChangeListMutator(cl1), &spec1); CHECK_EQ(spec0.Size(), spec1.Size()); Block coded; InMemoryEncodeDecode(spec0, spec1, &coded); Delta delta(coded); CHECK_EQ(0, delta.AddedBytes()); } } void TestOverwriteMutator() { MTRandom rand; FileSpec spec0(&rand); FileSpec spec1(&rand); spec0.GenerateFixedSize(Constants::BLOCK_SIZE); ChangeList cl1; cl1.push_back(Change(Change::OVERWRITE, 10, 0, 20)); spec0.ModifyTo(ChangeListMutator(cl1), &spec1); CHECK_EQ(spec0.Size(), spec1.Size()); Block b0, b1; BlockIterator(spec0).Get(&b0); BlockIterator(spec1).Get(&b1); CHECK(memcmp(b0.Data(), b1.Data() + 20, 10) == 0); CHECK(memcmp(b0.Data(), b1.Data(), 20) == 0); CHECK(memcmp(b0.Data() + 30, b1.Data() + 30, Constants::BLOCK_SIZE - 30) == 0); cl1.clear(); cl1.push_back(Change(Change::OVERWRITE, 10, 20, (xoff_t)0)); spec0.ModifyTo(ChangeListMutator(cl1), &spec1); CHECK_EQ(spec0.Size(), spec1.Size()); BlockIterator(spec0).Get(&b0); BlockIterator(spec1).Get(&b1); CHECK(memcmp(b0.Data() + 20, b1.Data(), 10) == 0); CHECK(memcmp(b0.Data() + 10, b1.Data() + 10, Constants::BLOCK_SIZE - 10) == 0); } // Note: this test is written to expose a problem, but the problem was // only exposed with BLOCK_SIZE = 128. void TestNonBlockingProgress() { MTRandom rand; FileSpec spec0(&rand); FileSpec spec1(&rand); FileSpec spec2(&rand); spec0.GenerateFixedSize(Constants::BLOCK_SIZE * 3); // This is a lazy target match Change ct(Change::OVERWRITE, 22, Constants::BLOCK_SIZE + 50, Constants::BLOCK_SIZE + 20); // This is a source match just after the block boundary, shorter // than the lazy target match. Change cs1(Change::OVERWRITE, 16, Constants::BLOCK_SIZE + 51, Constants::BLOCK_SIZE - 1); // This overwrites the original source bytes. Change cs2(Change::MODIFY, 108, Constants::BLOCK_SIZE + 20); // This changes the first blocks Change c1st(Change::MODIFY, Constants::BLOCK_SIZE - 2, 0); ChangeList csl; csl.push_back(cs1); csl.push_back(cs2); csl.push_back(c1st); spec0.ModifyTo(ChangeListMutator(csl), &spec1); ChangeList ctl; ctl.push_back(ct); ctl.push_back(c1st); spec0.ModifyTo(ChangeListMutator(ctl), &spec2); InMemoryEncodeDecode(spec1, spec2, NULL); } void TestEmptyInMemory() { MTRandom rand; FileSpec spec0(&rand); FileSpec spec1(&rand); Block block; spec0.GenerateFixedSize(0); spec1.GenerateFixedSize(0); InMemoryEncodeDecode(spec0, spec1, &block); Delta delta(block); CHECK_LT(0, block.Size()); CHECK_EQ(1, delta.Windows()); } void TestBlockInMemory() { MTRandom rand; FileSpec spec0(&rand); FileSpec spec1(&rand); Block block; spec0.GenerateFixedSize(Constants::BLOCK_SIZE); spec1.GenerateFixedSize(Constants::BLOCK_SIZE); InMemoryEncodeDecode(spec0, spec1, &block); Delta delta(block); CHECK_EQ(spec1.Blocks(Constants::WINDOW_SIZE), delta.Windows()); } void TestFifoCopyDiscipline() { MTRandom rand; FileSpec spec0(&rand); FileSpec spec1(&rand); spec0.GenerateFixedSize(Constants::BLOCK_SIZE * 4); // Create a half-block copy, 2.5 blocks apart. With 64-byte blocks, // the file in spec0 copies @ 384 from spec1 @ 64. ChangeList cl1; cl1.push_back(Change(Change::MODIFY, Constants::BLOCK_SIZE / 2, 0)); cl1.push_back(Change(Change::OVERWRITE, Constants::BLOCK_SIZE / 2, Constants::BLOCK_SIZE * 3, Constants::BLOCK_SIZE / 2)); cl1.push_back(Change(Change::MODIFY, Constants::BLOCK_SIZE * 3, Constants::BLOCK_SIZE)); spec0.ModifyTo(ChangeListMutator(cl1), &spec1); Options options1; options1.encode_srcwin_maxsz = Constants::BLOCK_SIZE * 4; Block block1; InMemoryEncodeDecode(spec1, spec0, &block1, options1); Delta delta1(block1); CHECK_EQ(4 * Constants::BLOCK_SIZE - Constants::BLOCK_SIZE / 2, delta1.AddedBytes()); Options options2; options2.encode_srcwin_maxsz = Constants::BLOCK_SIZE * 3; Block block2; InMemoryEncodeDecode(spec1, spec0, &block2, options2); Delta delta2(block2); CHECK_EQ(4 * Constants::BLOCK_SIZE, delta2.AddedBytes()); } void FourWayMergeTest(const FileSpec &spec0, const FileSpec &spec1, const FileSpec &spec2, const FileSpec &spec3) { Block delta01, delta12, delta23; InMemoryEncodeDecode(spec0, spec1, &delta01); InMemoryEncodeDecode(spec1, spec2, &delta12); InMemoryEncodeDecode(spec2, spec3, &delta23); TmpFile f0, f1, f2, f3, d01, d12, d23; spec0.WriteTmpFile(&f0); spec1.WriteTmpFile(&f1); spec2.WriteTmpFile(&f2); spec2.WriteTmpFile(&f3); delta01.WriteTmpFile(&d01); delta12.WriteTmpFile(&d12); delta23.WriteTmpFile(&d23); // Merge 2 ExtFile out; vector<const char*> mcmd; mcmd.push_back("xdelta3"); mcmd.push_back("merge"); mcmd.push_back("-m"); mcmd.push_back(d01.Name()); mcmd.push_back(d12.Name()); mcmd.push_back(out.Name()); mcmd.push_back(NULL); //DP(RINT "Running one merge: %s\n", CommandToString(mcmd).c_str()); CHECK_EQ(0, xd3_main_cmdline(mcmd.size() - 1, const_cast<char**>(&mcmd[0]))); ExtFile recon; vector<const char*> tcmd; tcmd.push_back("xdelta3"); tcmd.push_back("-d"); tcmd.push_back("-s"); tcmd.push_back(f0.Name()); tcmd.push_back(out.Name()); tcmd.push_back(recon.Name()); tcmd.push_back(NULL); //DP(RINT "Running one recon! %s\n", CommandToString(tcmd).c_str()); CHECK_EQ(0, xd3_main_cmdline(tcmd.size() - 1, const_cast<char**>(&tcmd[0]))); //DP(RINT "Should equal! %s\n", f2.Name()); CHECK(recon.EqualsSpec(spec2)); /* TODO: we've only done 3-way merges, try 4-way. */ } void TestMergeCommand1() { /* Repeat random-input testing for a number of iterations. * Test 2, 3, and 4-file scenarios (i.e., 1, 2, and 3-delta merges). */ MTRandom rand; FileSpec spec0(&rand); FileSpec spec1(&rand); FileSpec spec2(&rand); FileSpec spec3(&rand); SizeIterator<size_t, Sizes> si0(&rand, 10); for (; !si0.Done(); si0.Next()) { size_t size0 = si0.Get(); SizeIterator<size_t, Sizes> si1(&rand, 10); for (; !si1.Done(); si1.Next()) { size_t change1 = si1.Get(); if (change1 == 0) { continue; } DP(RINT "S0 = %lu\n", size0); DP(RINT "C1 = %lu\n", change1); size_t add1_pos = size0 ? rand.Rand32() % size0 : 0; size_t del2_pos = size0 ? rand.Rand32() % size0 : 0; spec0.GenerateFixedSize(size0); ChangeList cl1, cl2, cl3; size_t change3 = change1; size_t change3_pos; if (change3 >= size0) { change3 = size0; change3_pos = 0; } else { change3_pos = rand.Rand32() % (size0 - change3); } cl1.push_back(Change(Change::ADD, change1, add1_pos)); cl2.push_back(Change(Change::DELETE, change1, del2_pos)); cl3.push_back(Change(Change::MODIFY, change3, change3_pos)); spec0.ModifyTo(ChangeListMutator(cl1), &spec1); spec1.ModifyTo(ChangeListMutator(cl2), &spec2); spec2.ModifyTo(ChangeListMutator(cl3), &spec3); FourWayMergeTest(spec0, spec1, spec2, spec3); FourWayMergeTest(spec3, spec2, spec1, spec0); } } } void TestMergeCommand2() { /* Same as above, different mutation pattern. */ /* TODO: run this with large sizes too */ /* TODO: run this with small sizes too */ MTRandom rand; FileSpec spec0(&rand); FileSpec spec1(&rand); FileSpec spec2(&rand); FileSpec spec3(&rand); SizeIterator<size_t, Sizes> si0(&rand, 10); for (; !si0.Done(); si0.Next()) { size_t size0 = si0.Get(); SizeIterator<size_t, Sizes> si1(&rand, 10); for (; !si1.Done(); si1.Next()) { size_t size1 = si1.Get(); SizeIterator<size_t, Sizes> si2(&rand, 10); for (; !si2.Done(); si2.Next()) { size_t size2 = si2.Get(); SizeIterator<size_t, Sizes> si3(&rand, 10); for (; !si3.Done(); si3.Next()) { size_t size3 = si3.Get(); // We're only interested in three sizes, strictly decreasing. */ if (size3 >= size2 || size2 >= size1 || size1 >= size0) { continue; } DP(RINT "S0 = %lu\n", size0); DP(RINT "S1 = %lu\n", size1); DP(RINT "S2 = %lu\n", size2); DP(RINT "S3 = %lu\n", size3); spec0.GenerateFixedSize(size0); ChangeList cl1, cl2, cl3; cl1.push_back(Change(Change::DELETE, size0 - size1, 0)); cl2.push_back(Change(Change::DELETE, size0 - size2, 0)); cl3.push_back(Change(Change::DELETE, size0 - size3, 0)); spec0.ModifyTo(ChangeListMutator(cl1), &spec1); spec0.ModifyTo(ChangeListMutator(cl2), &spec2); spec0.ModifyTo(ChangeListMutator(cl3), &spec3); FourWayMergeTest(spec0, spec1, spec2, spec3); FourWayMergeTest(spec3, spec2, spec1, spec0); } } } } } }; // class Regtest<Constants> #define TEST(x) cerr << #x << "..." << endl; regtest.x() // These tests are primarily tests of the testing framework itself. template <class T> void UnitTest() { Regtest<T> regtest; TEST(TestRandomNumbers); TEST(TestRandomFile); TEST(TestFirstByte); TEST(TestModifyMutator); TEST(TestAddMutator); TEST(TestDeleteMutator); TEST(TestCopyMutator); TEST(TestMoveMutator); TEST(TestOverwriteMutator); } // These are Xdelta tests. template <class T> void MainTest() { cerr << "Blocksize: " << T::BLOCK_SIZE << endl; Regtest<T> regtest; TEST(TestEmptyInMemory); TEST(TestBlockInMemory); TEST(TestNonBlockingProgress); TEST(TestFifoCopyDiscipline); TEST(TestMergeCommand1); TEST(TestMergeCommand2); } #undef TEST // Run the unittests, followed by xdelta tests for various constants. int main(int argc, char **argv) { UnitTest<SmallBlock>(); MainTest<SmallBlock>(); MainTest<MixedBlock>(); MainTest<PrimeBlock>(); MainTest<OversizeBlock>(); MainTest<LargeBlock>(); return 0; }
gpl-2.0
ImbalanceGaming/imbalance-gaming-laravel
database/migrations/2016_03_14_011932_create_module_section_table.php
887
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateModuleSectionTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('module_section', function (Blueprint $table) { $table->increments('id'); $table->string('name')->unique(); $table->string('description')->nullable(); $table->integer('module_id')->unsigned(); }); Schema::table('module_section', function($table) { $table->foreign('module_id') ->references('id')->on('module') ->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('module_section'); } }
gpl-2.0
jayde02/freeradius-server
src/main/modules.c
44927
/* * modules.c Radius module support. * * Version: $Id$ * * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA * * Copyright 2003,2006 The FreeRADIUS server project * Copyright 2000 Alan DeKok <[email protected]> * Copyright 2000 Alan Curry <[email protected]> */ RCSID("$Id$") #include <freeradius-devel/radiusd.h> #include <freeradius-devel/modpriv.h> #include <freeradius-devel/modcall.h> #include <freeradius-devel/parser.h> #include <freeradius-devel/rad_assert.h> extern bool check_config; typedef struct indexed_modcallable { rlm_components_t comp; int idx; modcallable *modulelist; } indexed_modcallable; typedef struct virtual_server_t { char const *name; time_t created; int can_free; CONF_SECTION *cs; rbtree_t *components; modcallable *mc[RLM_COMPONENT_COUNT]; CONF_SECTION *subcs[RLM_COMPONENT_COUNT]; struct virtual_server_t *next; } virtual_server_t; /* * Keep a hash of virtual servers, so that we can reload them. */ #define VIRTUAL_SERVER_HASH_SIZE (256) static virtual_server_t *virtual_servers[VIRTUAL_SERVER_HASH_SIZE]; static rbtree_t *module_tree = NULL; static rbtree_t *instance_tree = NULL; struct fr_module_hup_t { module_instance_t *mi; time_t when; void *insthandle; fr_module_hup_t *next; }; /* * Ordered by component */ const section_type_value_t section_type_value[RLM_COMPONENT_COUNT] = { { "authenticate", "Auth-Type", PW_AUTH_TYPE }, { "authorize", "Autz-Type", PW_AUTZ_TYPE }, { "preacct", "Pre-Acct-Type", PW_PRE_ACCT_TYPE }, { "accounting", "Acct-Type", PW_ACCT_TYPE }, { "session", "Session-Type", PW_SESSION_TYPE }, { "pre-proxy", "Pre-Proxy-Type", PW_PRE_PROXY_TYPE }, { "post-proxy", "Post-Proxy-Type", PW_POST_PROXY_TYPE }, { "post-auth", "Post-Auth-Type", PW_POST_AUTH_TYPE } #ifdef WITH_COA , { "recv-coa", "Recv-CoA-Type", PW_RECV_COA_TYPE }, { "send-coa", "Send-CoA-Type", PW_SEND_COA_TYPE } #endif }; #ifndef RTLD_NOW #define RTLD_NOW (0) #endif #ifndef RTLD_LOCAL #define RTLD_LOCAL (0) #endif #ifdef __APPLE__ #define LT_SHREXT ".dylib" #define LD_LIBRARY_PATH "DYLD_FALLBACK_LIBRARY_PATH" #elif defined (WIN32) #define LT_SHREXT ".dll" #else #define LT_SHREXT ".so" #define LD_LIBRARY_PATH "LD_LIBRARY_PATH" #endif /** Check if the magic number in the module matches the one in the library * * This is used to detect potential ABI issues caused by running with modules which * were built for a different version of the server. * * @param cs being parsed. * @param module being loaded. * @returns 0 on success, -1 if prefix mismatch, -2 if version mismatch, -3 if commit mismatch. */ static int check_module_magic(CONF_SECTION *cs, module_t const *module) { if (MAGIC_PREFIX(module->magic) != MAGIC_PREFIX(RADIUSD_MAGIC_NUMBER)) { cf_log_err_cs(cs, "Application and rlm_%s magic number (prefix) mismatch." " application: %x module: %x", module->name, MAGIC_PREFIX(RADIUSD_MAGIC_NUMBER), MAGIC_PREFIX(module->magic)); return -1; } if (MAGIC_VERSION(module->magic) != MAGIC_VERSION(RADIUSD_MAGIC_NUMBER)) { cf_log_err_cs(cs, "Application and rlm_%s magic number (version) mismatch." " application: %lx module: %lx", module->name, (unsigned long) MAGIC_VERSION(RADIUSD_MAGIC_NUMBER), (unsigned long) MAGIC_VERSION(module->magic)); return -2; } if (MAGIC_COMMIT(module->magic) != MAGIC_COMMIT(RADIUSD_MAGIC_NUMBER)) { cf_log_err_cs(cs, "Application and rlm_%s magic number (commit) mismatch." " application: %lx module: %lx", module->name, (unsigned long) MAGIC_COMMIT(RADIUSD_MAGIC_NUMBER), (unsigned long) MAGIC_COMMIT(module->magic)); return -3; } return 0; } lt_dlhandle lt_dlopenext(char const *name) { int flags = RTLD_NOW; void *handle; char buffer[2048]; char *env; #ifdef RTLD_GLOBAL if (strcmp(name, "rlm_perl") == 0) { flags |= RTLD_GLOBAL; } else #endif flags |= RTLD_LOCAL; #ifndef NDEBUG /* * Bind all the symbols *NOW* so we don't hit errors later */ flags |= RTLD_NOW; #endif /* * Prefer loading our libraries by absolute path. */ snprintf(buffer, sizeof(buffer), "%s/%s%s", radlib_dir, name, LT_SHREXT); DEBUG4("Loading library using absolute path \"%s\"", name); handle = dlopen(buffer, flags); if (handle) return handle; /* * Because dlopen produces really shitty and inaccurate error messages */ if (access(name, R_OK) < 0) switch (errno) { case EACCES: WARN("Library file found, but we don't have permission to read it"); break; case ENOENT: DEBUG4("Library file not found"); break; default: DEBUG4("Issue accessing library file: %s", fr_syserror(errno)); break; } DEBUG4("Falling back to linker search path(s)"); if (DEBUG_ENABLED4) { #ifdef __APPLE__ env = getenv("LD_LIBRARY_PATH"); if (env) { DEBUG4("LD_LIBRARY_PATH : %s", env); } env = getenv("DYLD_LIBRARY_PATH"); if (env) { DEBUG4("DYLB_LIBRARY_PATH : %s", env); } env = getenv("DYLD_FALLBACK_LIBRARY_PATH"); if (env) { DEBUG4("DYLD_FALLBACK_LIBRARY_PATH : %s", env); } env = getcwd(buffer, sizeof(buffer)); if (env) { DEBUG4("Current directory : %s", env); } #else env = getenv("LD_LIBRARY_PATH"); if (env) { DEBUG4("LD_LIBRARY_PATH : %s", env); } DEBUG4("Defaults : /lib:/usr/lib"); #endif } strlcpy(buffer, name, sizeof(buffer)); /* * FIXME: Make this configurable... */ strlcat(buffer, LT_SHREXT, sizeof(buffer)); return dlopen(buffer, flags); } void *lt_dlsym(lt_dlhandle handle, UNUSED char const *symbol) { return dlsym(handle, symbol); } int lt_dlclose(lt_dlhandle handle) { if (!handle) return 0; return dlclose(handle); } char const *lt_dlerror(void) { return dlerror(); } static int virtual_server_idx(char const *name) { uint32_t hash; if (!name) return 0; hash = fr_hash_string(name); return hash & (VIRTUAL_SERVER_HASH_SIZE - 1); } static virtual_server_t *virtual_server_find(char const *name) { rlm_rcode_t rcode; virtual_server_t *server; rcode = virtual_server_idx(name); for (server = virtual_servers[rcode]; server != NULL; server = server->next) { if (!name && !server->name) break; if ((name && server->name) && (strcmp(name, server->name) == 0)) break; } return server; } static int _virtual_server_free(virtual_server_t *server) { server = talloc_get_type_abort(server, virtual_server_t); if (server->components) rbtree_free(server->components); return 0; } void virtual_servers_free(time_t when) { int i; virtual_server_t **last; for (i = 0; i < VIRTUAL_SERVER_HASH_SIZE; i++) { virtual_server_t *server, *next; last = &virtual_servers[i]; for (server = virtual_servers[i]; server != NULL; server = next) { next = server->next; /* * If we delete it, fix the links so that * we don't orphan anything. Also, * delete it if it's old, AND a newer one * was defined. * * Otherwise, the last pointer gets set to * the one we didn't delete. */ if ((when == 0) || ((server->created < when) && server->can_free)) { *last = server->next; talloc_free(server); } else { last = &(server->next); } } } } static int indexed_modcallable_cmp(void const *one, void const *two) { indexed_modcallable const *a = one; indexed_modcallable const *b = two; if (a->comp < b->comp) return -1; if (a->comp > b->comp) return +1; return a->idx - b->idx; } /* * Compare two module entries */ static int module_instance_cmp(void const *one, void const *two) { module_instance_t const *a = one; module_instance_t const *b = two; return strcmp(a->name, b->name); } static void module_instance_free_old(UNUSED CONF_SECTION *cs, module_instance_t *node, time_t when) { fr_module_hup_t *mh, **last; /* * Walk the list, freeing up old instances. */ last = &(node->mh); while (*last) { mh = *last; /* * Free only every 60 seconds. */ if ((when - mh->when) < 60) { last = &(mh->next); continue; } talloc_free(mh->insthandle); *last = mh->next; talloc_free(mh); } } /* * Free a module instance. */ static void module_instance_free(void *data) { module_instance_t *this = data; module_instance_free_old(this->cs, this, time(NULL) + 100); #ifdef HAVE_PTHREAD_H if (this->mutex) { /* * FIXME * The mutex MIGHT be locked... * we'll check for that later, I guess. */ pthread_mutex_destroy(this->mutex); talloc_free(this->mutex); } #endif /* * Remove any registered paircompares. */ paircompare_unregister_instance(this->insthandle); xlat_unregister(this->name, NULL, this->insthandle); #ifndef NDEBUG memset(this, 0, sizeof(*this)); #endif talloc_free(this); } /* * Compare two module entries */ static int module_entry_cmp(void const *one, void const *two) { module_entry_t const *a = one; module_entry_t const *b = two; return strcmp(a->name, b->name); } /* * Free a module entry. */ static int _module_entry_free(module_entry_t *this) { this = talloc_get_type_abort(this, module_entry_t); #ifndef NDEBUG /* * Don't dlclose() modules if we're doing memory * debugging. This removes the symbols needed by * valgrind. */ if (!main_config.debug_memory) #endif dlclose(this->handle); /* ignore any errors */ return 0; } /* * Remove the module lists. */ int modules_free(void) { rbtree_free(instance_tree); rbtree_free(module_tree); return 0; } /* * Find a module on disk or in memory, and link to it. */ static module_entry_t *linkto_module(char const *module_name, CONF_SECTION *cs) { module_entry_t myentry; module_entry_t *node; void *handle = NULL; module_t const *module; strlcpy(myentry.name, module_name, sizeof(myentry.name)); node = rbtree_finddata(module_tree, &myentry); if (node) return node; /* * Link to the module's rlm_FOO{} structure, the same as * the module name. */ #if !defined(WITH_LIBLTDL) && defined(HAVE_DLFCN_H) && defined(RTLD_SELF) module = dlsym(RTLD_SELF, module_name); if (module) goto open_self; #endif /* * Keep the handle around so we can dlclose() it. */ handle = lt_dlopenext(module_name); if (!handle) { cf_log_err_cs(cs, "Failed to link to module '%s': %s\n", module_name, dlerror()); return NULL; } DEBUG3(" (Loaded %s, checking if it's valid)", module_name); /* * libltld MAY core here, if the handle it gives us contains * garbage data. */ module = dlsym(handle, module_name); if (!module) { cf_log_err_cs(cs, "Failed linking to %s structure: %s\n", module_name, dlerror()); dlclose(handle); return NULL; } #if !defined(WITH_LIBLTDL) && defined (HAVE_DLFCN_H) && defined(RTLD_SELF) open_self: #endif /* * Before doing anything else, check if it's sane. */ if (check_module_magic(cs, module) < 0) { dlclose(handle); return NULL; } /* make room for the module type */ node = talloc_zero(cs, module_entry_t); talloc_set_destructor(node, _module_entry_free); strlcpy(node->name, module_name, sizeof(node->name)); node->module = module; node->handle = handle; cf_log_module(cs, "Loaded module %s", module_name); /* * Add the module as "rlm_foo-version" to the configuration * section. */ if (!rbtree_insert(module_tree, node)) { ERROR("Failed to cache module %s", module_name); dlclose(handle); talloc_free(node); return NULL; } return node; } /** Parse module's configuration section and setup destructors * */ static int module_conf_parse(module_instance_t *node, void **handle) { *handle = NULL; /* * If there is supposed to be instance data, allocate it now. * Also parse the configuration data, if required. */ if (node->entry->module->inst_size) { /* FIXME: make this rlm_config_t ?? */ *handle = talloc_zero_array(node, uint8_t, node->entry->module->inst_size); rad_assert(handle); /* * So we can see where this configuration is from * FIXME: set it to rlm_NAME_t, or some such thing */ talloc_set_name(*handle, "rlm_config_t"); if (node->entry->module->config && (cf_section_parse(node->cs, *handle, node->entry->module->config) < 0)) { cf_log_err_cs(node->cs,"Invalid configuration for module \"%s\"", node->name); talloc_free(*handle); return -1; } /* * Set the destructor. */ if (node->entry->module->detach) { talloc_set_destructor((void *) *handle, node->entry->module->detach); } } return 0; } /* * Find a module instance. */ module_instance_t *find_module_instance(CONF_SECTION *modules, char const *askedname, bool do_link) { bool check_config_safe = false; CONF_SECTION *cs; char const *name1, *instname; module_instance_t *node, myNode; char module_name[256]; if (!modules) return NULL; /* * Look for the real name. Ignore the first character, * which tells the server "it's OK for this module to not * exist." */ instname = askedname; if (instname[0] == '-') { instname++; } /* * Module instances are declared in the modules{} block * and referenced later by their name, which is the * name2 from the config section, or name1 if there was * no name2. */ cs = cf_section_sub_find_name2(modules, NULL, instname); if (!cs) { ERROR("Cannot find a configuration entry for module \"%s\"", instname); return NULL; } /* * If there's already a module instance, return it. */ strlcpy(myNode.name, instname, sizeof(myNode.name)); node = rbtree_finddata(instance_tree, &myNode); if (node) { return node; } if (!do_link) { return NULL; } name1 = cf_section_name1(cs); /* * Found the configuration entry, hang the node struct off of the * configuration section. If the CS is free'd the instance will * be too. */ node = talloc_zero(cs, module_instance_t); node->cs = cs; /* * Names in the "modules" section aren't prefixed * with "rlm_", so we add it here. */ snprintf(module_name, sizeof(module_name), "rlm_%s", name1); /* * Pull in the module object */ node->entry = linkto_module(module_name, cs); if (!node->entry) { talloc_free(node); /* linkto_module logs any errors */ return NULL; } if (check_config && (node->entry->module->instantiate) && (node->entry->module->type & RLM_TYPE_CHECK_CONFIG_UNSAFE) != 0) { char const *value = NULL; CONF_PAIR *cp; cp = cf_pair_find(cs, "force_check_config"); if (cp) { value = cf_pair_value(cp); } if (value && (strcmp(value, "yes") == 0)) goto print_inst; cf_log_module(cs, "Skipping instantiation of %s", instname); } else { print_inst: check_config_safe = true; cf_log_module(cs, "Instantiating module \"%s\" from file %s", instname, cf_section_filename(cs)); } strlcpy(node->name, instname, sizeof(node->name)); /* * Parse the module configuration, and setup destructors so the * module's detach method is called when it's instance data is * about to be freed. */ if (module_conf_parse(node, &node->insthandle) < 0) { talloc_free(node); return NULL; } /* * Call the module's instantiation routine. */ if ((node->entry->module->instantiate) && (!check_config || check_config_safe) && ((node->entry->module->instantiate)(cs, node->insthandle) < 0)) { cf_log_err_cs(cs, "Instantiation failed for module \"%s\"", node->name); talloc_free(node); return NULL; } #ifdef HAVE_PTHREAD_H /* * If we're threaded, check if the module is thread-safe. * * If it isn't, we create a mutex. */ if ((node->entry->module->type & RLM_TYPE_THREAD_UNSAFE) != 0) { node->mutex = talloc_zero(node, pthread_mutex_t); /* * Initialize the mutex. */ pthread_mutex_init(node->mutex, NULL); } else { /* * The module is thread-safe. Don't give it a mutex. */ node->mutex = NULL; } #endif rbtree_insert(instance_tree, node); return node; } /** Resolve polymorphic item's from a module's CONF_SECTION to a subsection in another module * * This allows certain module sections to reference module sections in other instances * of the same module and share CONF_DATA associated with them. * * @verbatim example { data { ... } } example inst { data = example } * @endverbatim * * @param out where to write the pointer to a module's config section. May be NULL on success, indicating the config * item was not found within the module CONF_SECTION, or the chain of module references was followed and the * module at the end of the chain did not a subsection. * @param module CONF_SECTION. * @param name of the polymorphic sub-section. * @return 0 on success with referenced section, 1 on success with local section, or -1 on failure. */ int find_module_sibling_section(CONF_SECTION **out, CONF_SECTION *module, char const *name) { static bool loop = true; /* not used, we just need a valid pointer to quiet static analysis */ CONF_PAIR *cp; CONF_SECTION *cs; module_instance_t *inst; char const *inst_name; #define FIND_SIBLING_CF_KEY "find_sibling" *out = NULL; /* * Is a real section (not referencing sibling module). */ cs = cf_section_sub_find(module, name); if (cs) { *out = cs; return 0; } /* * Item omitted completely from module config. */ cp = cf_pair_find(module, name); if (!cp) return 0; if (cf_data_find(module, FIND_SIBLING_CF_KEY)) { cf_log_err_cp(cp, "Module reference loop found"); return -1; } cf_data_add(module, FIND_SIBLING_CF_KEY, &loop, NULL); /* * Item found, resolve it to a module instance. * This triggers module loading, so we don't have * instantiation order issues. */ inst_name = cf_pair_value(cp); inst = find_module_instance(cf_item_parent(cf_sectiontoitem(module)), inst_name, true); /* * Remove the config data we added for loop * detection. */ cf_data_remove(module, FIND_SIBLING_CF_KEY); if (!inst) { cf_log_err_cp(cp, "Unknown module instance \"%s\"", inst_name); return -1; } /* * Check the module instances are of the same type. */ if (strcmp(cf_section_name1(inst->cs), cf_section_name1(module)) != 0) { cf_log_err_cp(cp, "Referenced module is a rlm_%s instance, must be a rlm_%s instance", cf_section_name1(inst->cs), cf_section_name1(module)); return -1; } *out = cf_section_sub_find(inst->cs, name); return 1; } static indexed_modcallable *lookup_by_index(rbtree_t *components, rlm_components_t comp, int idx) { indexed_modcallable myc; myc.comp = comp; myc.idx = idx; return rbtree_finddata(components, &myc); } /* * Create a new sublist. */ static indexed_modcallable *new_sublist(CONF_SECTION *cs, rbtree_t *components, rlm_components_t comp, int idx) { indexed_modcallable *c; c = lookup_by_index(components, comp, idx); /* It is an error to try to create a sublist that already * exists. It would almost certainly be caused by accidental * duplication in the config file. * * index 0 is the exception, because it is used when we want * to collect _all_ listed modules under a single index by * default, which is currently the case in all components * except authenticate. */ if (c) { if (idx == 0) { return c; } return NULL; } c = talloc_zero(cs, indexed_modcallable); c->modulelist = NULL; c->comp = comp; c->idx = idx; if (!rbtree_insert(components, c)) { talloc_free(c); return NULL; } return c; } rlm_rcode_t indexed_modcall(rlm_components_t comp, int idx, REQUEST *request) { rlm_rcode_t rcode; modcallable *list = NULL; virtual_server_t *server; /* * Hack to find the correct virtual server. */ server = virtual_server_find(request->server); if (!server) { RDEBUG("No such virtual server \"%s\"", request->server); return RLM_MODULE_FAIL; } if (idx == 0) { list = server->mc[comp]; if (!list) RDEBUG3("Empty %s section. Using default return values.", section_type_value[comp].section); } else { indexed_modcallable *this; this = lookup_by_index(server->components, comp, idx); if (this) { list = this->modulelist; } else { RDEBUG3("%s sub-section not found. Ignoring.", section_type_value[comp].typename); } } if (server->subcs[comp]) { if (idx == 0) { RDEBUG("# Executing section %s from file %s", section_type_value[comp].section, cf_section_filename(server->subcs[comp])); } else { RDEBUG("# Executing group from file %s", cf_section_filename(server->subcs[comp])); } } request->component = section_type_value[comp].section; rcode = modcall(comp, list, request); request->module = ""; request->component = "<core>"; return rcode; } /* * Load a sub-module list, as found inside an Auth-Type foo {} * block */ static int load_subcomponent_section(modcallable *parent, CONF_SECTION *cs, rbtree_t *components, DICT_ATTR const *da, rlm_components_t comp) { indexed_modcallable *subcomp; modcallable *ml; DICT_VALUE *dval; char const *name2 = cf_section_name2(cs); /* * Sanity check. */ if (!name2) { return 1; } /* * Compile the group. */ ml = compile_modgroup(parent, comp, cs); if (!ml) { return 0; } /* * We must assign a numeric index to this subcomponent. * It is generated and placed in the dictionary * automatically. If it isn't found, it's a serious * error. */ dval = dict_valbyname(da->attr, da->vendor, name2); if (!dval) { cf_log_err_cs(cs, "%s %s Not previously configured", section_type_value[comp].typename, name2); talloc_free(ml); return 0; } subcomp = new_sublist(cs, components, comp, dval->value); if (!subcomp) { talloc_free(ml); return 1; } subcomp->modulelist = talloc_steal(subcomp, ml); return 1; /* OK */ } static int define_type(CONF_SECTION *cs, DICT_ATTR const *da, char const *name) { uint32_t value; DICT_VALUE *dval; /* * If the value already exists, don't * create it again. */ dval = dict_valbyname(da->attr, da->vendor, name); if (dval) return 1; /* * Create a new unique value with a * meaningless number. You can't look at * it from outside of this code, so it * doesn't matter. The only requirement * is that it's unique. */ do { value = fr_rand() & 0x00ffffff; } while (dict_valbyattr(da->attr, da->vendor, value)); cf_log_module(cs, "Creating %s = %s", da->name, name); if (dict_addvalue(name, da->name, value) < 0) { ERROR("%s", fr_strerror()); return 0; } return 1; } /* * Don't complain too often. */ #define MAX_IGNORED (32) static int last_ignored = -1; static char const *ignored[MAX_IGNORED]; static int load_component_section(CONF_SECTION *cs, rbtree_t *components, rlm_components_t comp) { modcallable *this; CONF_ITEM *modref; int idx; indexed_modcallable *subcomp; char const *modname; DICT_ATTR const *da; /* * Find the attribute used to store VALUEs for this section. */ da = dict_attrbyvalue(section_type_value[comp].attr, 0); if (!da) { cf_log_err_cs(cs, "No such attribute %s", section_type_value[comp].typename); return -1; } /* * Loop over the entries in the named section, loading * the sections this time. */ for (modref = cf_item_find_next(cs, NULL); modref != NULL; modref = cf_item_find_next(cs, modref)) { char const *name1; CONF_PAIR *cp = NULL; CONF_SECTION *scs = NULL; if (cf_item_is_section(modref)) { scs = cf_itemtosection(modref); name1 = cf_section_name1(scs); if (strcmp(name1, section_type_value[comp].typename) == 0) { if (!load_subcomponent_section(NULL, scs, components, da, comp)) { return -1; /* FIXME: memleak? */ } continue; } cp = NULL; } else if (cf_item_is_pair(modref)) { cp = cf_itemtopair(modref); } else { continue; /* ignore it */ } /* * Look for Auth-Type foo {}, which are special * cases of named sections, and allowable ONLY * at the top-level. * * i.e. They're not allowed in a "group" or "redundant" * subsection. */ if (comp == RLM_COMPONENT_AUTH) { DICT_VALUE *dval; char const *modrefname = NULL; if (cp) { modrefname = cf_pair_attr(cp); } else { modrefname = cf_section_name2(scs); if (!modrefname) { cf_log_err_cs(cs, "Errors parsing %s sub-section.\n", cf_section_name1(scs)); return -1; } } dval = dict_valbyname(PW_AUTH_TYPE, 0, modrefname); if (!dval) { /* * It's a section, but nothing we * recognize. Die! */ cf_log_err_cs(cs, "Unknown Auth-Type \"%s\" in %s sub-section.", modrefname, section_type_value[comp].section); return -1; } idx = dval->value; } else { /* See the comment in new_sublist() for explanation * of the special index 0 */ idx = 0; } subcomp = new_sublist(cs, components, comp, idx); if (!subcomp) continue; /* * Try to compile one entry. */ this = compile_modsingle(subcomp, &subcomp->modulelist, comp, modref, &modname); /* * It's OK for the module to not exist. */ if (!this && modname && (modname[0] == '-')) { int i; if (last_ignored < 0) { save_complain: last_ignored++; ignored[last_ignored] = modname; complain: WARN("Ignoring \"%s\" (see raddb/mods-available/README.rst)", modname + 1); continue; } if (last_ignored >= MAX_IGNORED) goto complain; for (i = 0; i <= last_ignored; i++) { if (strcmp(ignored[i], modname) == 0) { break; } } if (i > last_ignored) goto save_complain; continue; } if (!this) { cf_log_err_cs(cs, "Errors parsing %s section.\n", cf_section_name1(cs)); return -1; } if (debug_flag > 2) modcall_debug(this, 2); add_to_modcallable(subcomp->modulelist, this); } return 0; } static int load_byserver(CONF_SECTION *cs) { rlm_components_t comp, found; char const *name = cf_section_name2(cs); rbtree_t *components; virtual_server_t *server = NULL; indexed_modcallable *c; if (name) { cf_log_info(cs, "server %s { # from file %s", name, cf_section_filename(cs)); } else { cf_log_info(cs, "server { # from file %s", cf_section_filename(cs)); } server = talloc_zero(cs, virtual_server_t); server->name = name; server->created = time(NULL); server->cs = cs; server->components = components = rbtree_create(server, indexed_modcallable_cmp, NULL, 0); if (!components) { ERROR("Failed to initialize components"); goto error; } talloc_set_destructor(server, _virtual_server_free); /* * Define types first. */ for (comp = 0; comp < RLM_COMPONENT_COUNT; ++comp) { CONF_SECTION *subcs; CONF_ITEM *modref; DICT_ATTR const *da; subcs = cf_section_sub_find(cs, section_type_value[comp].section); if (!subcs) continue; if (cf_item_find_next(subcs, NULL) == NULL) continue; /* * Find the attribute used to store VALUEs for this section. */ da = dict_attrbyvalue(section_type_value[comp].attr, 0); if (!da) { cf_log_err_cs(subcs, "No such attribute %s", section_type_value[comp].typename); error: if (debug_flag == 0) { ERROR("Failed to load virtual server %s", (name != NULL) ? name : "<default>"); } talloc_free(server); return -1; } /* * Define dynamic types, so that others can reference * them. */ for (modref = cf_item_find_next(subcs, NULL); modref != NULL; modref = cf_item_find_next(subcs, modref)) { char const *name1; CONF_SECTION *subsubcs; /* * Create types for simple references * only when parsing the authenticate * section. */ if ((section_type_value[comp].attr == PW_AUTH_TYPE) && cf_item_is_pair(modref)) { CONF_PAIR *cp = cf_itemtopair(modref); if (!define_type(cs, da, cf_pair_attr(cp))) { goto error; } continue; } if (!cf_item_is_section(modref)) continue; subsubcs = cf_itemtosection(modref); name1 = cf_section_name1(subsubcs); if (strcmp(name1, section_type_value[comp].typename) == 0) { if (!define_type(cs, da, cf_section_name2(subsubcs))) { goto error; } } } } /* loop over components */ /* * Loop over all of the known components, finding their * configuration section, and loading it. */ found = 0; for (comp = 0; comp < RLM_COMPONENT_COUNT; ++comp) { CONF_SECTION *subcs; subcs = cf_section_sub_find(cs, section_type_value[comp].section); if (!subcs) continue; if (cf_item_find_next(subcs, NULL) == NULL) continue; /* * Skip pre/post-proxy sections if we're not * proxying. */ if ( #ifdef WITH_PROXY !main_config.proxy_requests && #endif ((comp == RLM_COMPONENT_PRE_PROXY) || (comp == RLM_COMPONENT_POST_PROXY))) { continue; } #ifndef WITH_ACCOUNTING if (comp == RLM_COMPONENT_ACCT) continue; #endif #ifndef WITH_SESSION_MGMT if (comp == RLM_COMPONENT_SESS) continue; #endif if (debug_flag <= 3) { cf_log_module(cs, "Loading %s {...}", section_type_value[comp].section); } else { DEBUG(" %s {", section_type_value[comp].section); } if (load_component_section(subcs, components, comp) < 0) { goto error; } if (debug_flag > 3) { DEBUG(" } # %s", section_type_value[comp].section); } /* * Cache a default, if it exists. Some people * put empty sections for some reason... */ c = lookup_by_index(components, comp, 0); if (c) server->mc[comp] = c->modulelist; server->subcs[comp] = subcs; found = 1; } /* loop over components */ /* * We haven't loaded any of the normal sections. Maybe we're * supposed to load the vmps section. * * This is a bit of a hack... */ if (!found) do { #if defined(WITH_VMPS) || defined(WITH_DHCP) CONF_SECTION *subcs; #endif #ifdef WITH_DHCP DICT_ATTR const *da; #endif #ifdef WITH_VMPS subcs = cf_section_sub_find(cs, "vmps"); if (subcs) { cf_log_module(cs, "Loading vmps {...}"); if (load_component_section(subcs, components, RLM_COMPONENT_POST_AUTH) < 0) { goto error; } c = lookup_by_index(components, RLM_COMPONENT_POST_AUTH, 0); if (c) server->mc[RLM_COMPONENT_POST_AUTH] = c->modulelist; break; } #endif #ifdef WITH_DHCP /* * It's OK to not have DHCP. */ subcs = cf_subsection_find_next(cs, NULL, "dhcp"); if (!subcs) break; da = dict_attrbyname("DHCP-Message-Type"); /* * Handle each DHCP Message type separately. */ while (subcs) { char const *name2 = cf_section_name2(subcs); if (name2) { cf_log_module(cs, "Loading dhcp %s {...}", name2); } else { cf_log_module(cs, "Loading dhcp {...}"); } if (!load_subcomponent_section(NULL, subcs, components, da, RLM_COMPONENT_POST_AUTH)) { goto error; /* FIXME: memleak? */ } c = lookup_by_index(components, RLM_COMPONENT_POST_AUTH, 0); if (c) server->mc[RLM_COMPONENT_POST_AUTH] = c->modulelist; subcs = cf_subsection_find_next(cs, subcs, "dhcp"); } #endif } while (0); if (name) { cf_log_info(cs, "} # server %s", name); } else { cf_log_info(cs, "} # server"); } if (debug_flag == 0) { INFO("Loaded virtual server %s", (name != NULL) ? name : "<default>"); } /* * Now that it is OK, insert it into the list. * * This is thread-safe... */ comp = virtual_server_idx(name); server->next = virtual_servers[comp]; virtual_servers[comp] = server; /* * Mark OLDER ones of the same name as being unused. */ server = server->next; while (server) { if ((!name && !server->name) || (name && server->name && (strcmp(server->name, name) == 0))) { server->can_free = true; break; } server = server->next; } return 0; } static int pass2_cb(UNUSED void *ctx, void *data) { indexed_modcallable *this = data; if (!modcall_pass2(this->modulelist)) return -1; return 0; } static int pass2_instance_cb(UNUSED void *ctx, void *data) { module_instance_t *node = data; if (!node->entry->module->config || !node->cs) return 0; if (cf_section_parse_pass2(node->cs, node->insthandle, node->entry->module->config) < 0) { return -1; } return 0; } /* * Load all of the virtual servers. */ int virtual_servers_load(CONF_SECTION *config) { CONF_SECTION *cs; virtual_server_t *server; static bool first_time = true; DEBUG2("%s: #### Loading Virtual Servers ####", main_config.name); /* * If we have "server { ...}", then there SHOULD NOT be * bare "authorize", etc. sections. if there is no such * server, then try to load the old-style sections first. * * In either case, load the "default" virtual server first. * this matches better with users expectations. */ cs = cf_section_find_name2(cf_subsection_find_next(config, NULL, "server"), "server", NULL); if (cs) { if (load_byserver(cs) < 0) { return -1; } } else { if (load_byserver(config) < 0) { return -1; } } /* * Load all of the virtual servers. */ for (cs = cf_subsection_find_next(config, NULL, "server"); cs != NULL; cs = cf_subsection_find_next(config, cs, "server")) { char const *name2; name2 = cf_section_name2(cs); if (!name2) continue; /* handled above */ server = virtual_server_find(name2); if (server && (cf_top_section(server->cs) == config)) { ERROR("Duplicate virtual server \"%s\" in file %s:%d and file %s:%d", server->name, cf_section_filename(server->cs), cf_section_lineno(server->cs), cf_section_filename(cs), cf_section_lineno(cs)); return -1; } if (load_byserver(cs) < 0) { /* * Once we successfully started once, * continue loading the OTHER servers, * even if one fails. */ if (!first_time) continue; return -1; } } /* * Check all of the module config items which are xlat expanded. */ if (rbtree_walk(instance_tree, RBTREE_IN_ORDER, pass2_instance_cb, NULL) != 0) { return -1; } /* * Now that we've loaded everything, run pass 2 over the * conditions and xlats. */ for (cs = cf_subsection_find_next(config, NULL, "server"); cs != NULL; cs = cf_subsection_find_next(config, cs, "server")) { int i; char const *name2; name2 = cf_section_name2(cs); server = virtual_server_find(name2); if (!server) continue; for (i = RLM_COMPONENT_AUTH; i < RLM_COMPONENT_COUNT; i++) { if (!modcall_pass2(server->mc[i])) return -1; } if (server->components && (rbtree_walk(server->components, RBTREE_IN_ORDER, pass2_cb, NULL) != 0)) { return -1; } } /* * If we succeed the first time around, remember that. */ first_time = false; return 0; } int module_hup_module(CONF_SECTION *cs, module_instance_t *node, time_t when) { void *insthandle; fr_module_hup_t *mh; if (!node || !node->entry->module->instantiate || ((node->entry->module->type & RLM_TYPE_HUP_SAFE) == 0)) { return 1; } cf_log_module(cs, "Trying to reload module \"%s\"", node->name); /* * Parse the module configuration, and setup destructors so the * module's detach method is called when it's instance data is * about to be freed. */ if (module_conf_parse(node, &insthandle) < 0) { cf_log_err_cs(cs, "HUP failed for module \"%s\" (parsing config failed). " "Using old configuration", node->name); return 0; } if ((node->entry->module->instantiate)(cs, insthandle) < 0) { cf_log_err_cs(cs, "HUP failed for module \"%s\". Using old configuration.", node->name); talloc_free(insthandle); return 0; } INFO(" Module: Reloaded module \"%s\"", node->name); module_instance_free_old(cs, node, when); /* * Save the old instance handle for later deletion. */ mh = talloc_zero(cs, fr_module_hup_t); mh->mi = node; mh->when = when; mh->insthandle = node->insthandle; mh->next = node->mh; node->mh = mh; node->insthandle = insthandle; /* * FIXME: Set a timeout to come back in 60s, so that * we can pro-actively clean up the old instances. */ return 1; } int modules_hup(CONF_SECTION *modules) { time_t when; CONF_ITEM *ci; CONF_SECTION *cs; module_instance_t *node; if (!modules) return 0; when = time(NULL); /* * Loop over the modules */ for (ci=cf_item_find_next(modules, NULL); ci != NULL; ci=cf_item_find_next(modules, ci)) { char const *instname; module_instance_t myNode; /* * If it's not a section, ignore it. */ if (!cf_item_is_section(ci)) continue; cs = cf_itemtosection(ci); instname = cf_section_name2(cs); if (!instname) instname = cf_section_name1(cs); strlcpy(myNode.name, instname, sizeof(myNode.name)); node = rbtree_finddata(instance_tree, &myNode); module_hup_module(cs, node, when); } return 1; } /* * Parse the module config sections, and load * and call each module's init() function. */ int modules_init(CONF_SECTION *config) { CONF_ITEM *ci, *next; CONF_SECTION *cs, *modules; /* * Set up the internal module struct. */ module_tree = rbtree_create(NULL, module_entry_cmp, NULL, 0); if (!module_tree) { ERROR("Failed to initialize modules\n"); return -1; } instance_tree = rbtree_create(NULL, module_instance_cmp, module_instance_free, 0); if (!instance_tree) { ERROR("Failed to initialize modules\n"); return -1; } memset(virtual_servers, 0, sizeof(virtual_servers)); /* * Remember where the modules were stored. */ modules = cf_section_sub_find(config, "modules"); if (!modules) { WARN("Cannot find a \"modules\" section in the configuration file!"); } #if defined(WITH_VMPS) || defined(WITH_DHCP) /* * Load dictionaries. */ for (cs = cf_subsection_find_next(config, NULL, "server"); cs != NULL; cs = cf_subsection_find_next(config, cs, "server")) { CONF_SECTION *subcs; DICT_ATTR const *da; #ifdef WITH_VMPS /* * Auto-load the VMPS/VQP dictionary. */ subcs = cf_section_sub_find(cs, "vmps"); if (subcs) { da = dict_attrbyname("VQP-Packet-Type"); if (!da) { if (dict_read(main_config.dictionary_dir, "dictionary.vqp") < 0) { ERROR("Failed reading dictionary.vqp: %s", fr_strerror()); return -1; } cf_log_module(cs, "Loading dictionary.vqp"); da = dict_attrbyname("VQP-Packet-Type"); if (!da) { ERROR("No VQP-Packet-Type in dictionary.vqp"); return -1; } } } #endif #ifdef WITH_DHCP /* * Auto-load the DHCP dictionary. */ subcs = cf_subsection_find_next(cs, NULL, "dhcp"); if (subcs) { da = dict_attrbyname("DHCP-Message-Type"); if (!da) { cf_log_module(cs, "Loading dictionary.dhcp"); if (dict_read(main_config.dictionary_dir, "dictionary.dhcp") < 0) { ERROR("Failed reading dictionary.dhcp: %s", fr_strerror()); return -1; } da = dict_attrbyname("DHCP-Message-Type"); if (!da) { ERROR("No DHCP-Message-Type in dictionary.dhcp"); return -1; } } } #endif /* * Else it's a RADIUS virtual server, and the * dictionaries are already loaded. */ } #endif DEBUG2("%s: #### Instantiating modules ####", main_config.name); /* * Loop over module definitions, looking for duplicates. * * This is O(N^2) in the number of modules, but most * systems should have less than 100 modules. */ for (ci=cf_item_find_next(modules, NULL); ci != NULL; ci=next) { char const *name1, *name2; CONF_SECTION *subcs, *duplicate; next = cf_item_find_next(modules, ci); if (!cf_item_is_section(ci)) continue; if (!next || !cf_item_is_section(next)) continue; subcs = cf_itemtosection(ci); name1 = cf_section_name1(subcs); name2 = cf_section_name2(subcs); duplicate = cf_section_find_name2(cf_itemtosection(next), name1, name2); if (!duplicate) continue; if (!name2) name2 = ""; ERROR("Duplicate module \"%s %s\", in file %s:%d and file %s:%d", name1, name2, cf_section_filename(subcs), cf_section_lineno(subcs), cf_section_filename(duplicate), cf_section_lineno(duplicate)); return -1; } /* * Look for the 'instantiate' section, which tells us * the instantiation order of the modules, and also allows * us to load modules with no authorize/authenticate/etc. * sections. */ cs = cf_section_sub_find(config, "instantiate"); if (cs != NULL) { CONF_PAIR *cp; module_instance_t *module; char const *name; cf_log_info(cs, " instantiate {"); /* * Loop over the items in the 'instantiate' section. */ for (ci=cf_item_find_next(cs, NULL); ci != NULL; ci=cf_item_find_next(cs, ci)) { /* * Skip sections and "other" stuff. * Sections will be handled later, if * they're referenced at all... */ if (!cf_item_is_pair(ci)) { continue; } cp = cf_itemtopair(ci); name = cf_pair_attr(cp); module = find_module_instance(modules, name, true); if (!module && (name[0] != '-')) { return -1; } } /* loop over items in the subsection */ cf_log_info(cs, " }"); } /* if there's an 'instantiate' section. */ /* * Now that we've loaded the explicitly ordered modules, * load everything in the "modules" section. This is * because we've now split up the modules into * mods-enabled. */ cf_log_info(cs, " modules {"); for (ci=cf_item_find_next(modules, NULL); ci != NULL; ci=next) { char const *name; module_instance_t *module; CONF_SECTION *subcs; next = cf_item_find_next(modules, ci); if (!cf_item_is_section(ci)) continue; subcs = cf_itemtosection(ci); name = cf_section_name2(subcs); if (!name) name = cf_section_name1(subcs); module = find_module_instance(modules, name, true); if (!module) return -1; } cf_log_info(cs, " } # modules"); if (virtual_servers_load(config) < 0) return -1; return 0; } /* * Call all authorization modules until one returns * somethings else than RLM_MODULE_OK */ rlm_rcode_t process_authorize(int autz_type, REQUEST *request) { return indexed_modcall(RLM_COMPONENT_AUTZ, autz_type, request); } /* * Authenticate a user/password with various methods. */ rlm_rcode_t process_authenticate(int auth_type, REQUEST *request) { return indexed_modcall(RLM_COMPONENT_AUTH, auth_type, request); } #ifdef WITH_ACCOUNTING /* * Do pre-accounting for ALL configured sessions */ rlm_rcode_t module_preacct(REQUEST *request) { return indexed_modcall(RLM_COMPONENT_PREACCT, 0, request); } /* * Do accounting for ALL configured sessions */ rlm_rcode_t process_accounting(int acct_type, REQUEST *request) { return indexed_modcall(RLM_COMPONENT_ACCT, acct_type, request); } #endif #ifdef WITH_SESSION_MGMT /* * See if a user is already logged in. * * Returns: 0 == OK, 1 == double logins, 2 == multilink attempt */ int process_checksimul(int sess_type, REQUEST *request, int maxsimul) { rlm_rcode_t rcode; if(!request->username) return 0; request->simul_count = 0; request->simul_max = maxsimul; request->simul_mpp = 1; rcode = indexed_modcall(RLM_COMPONENT_SESS, sess_type, request); if (rcode != RLM_MODULE_OK) { /* FIXME: Good spot for a *rate-limited* warning to the log */ return 0; } return (request->simul_count < maxsimul) ? 0 : request->simul_mpp; } #endif #ifdef WITH_PROXY /* * Do pre-proxying for ALL configured sessions */ rlm_rcode_t process_pre_proxy(int type, REQUEST *request) { return indexed_modcall(RLM_COMPONENT_PRE_PROXY, type, request); } /* * Do post-proxying for ALL configured sessions */ rlm_rcode_t process_post_proxy(int type, REQUEST *request) { return indexed_modcall(RLM_COMPONENT_POST_PROXY, type, request); } #endif /* * Do post-authentication for ALL configured sessions */ rlm_rcode_t process_post_auth(int postauth_type, REQUEST *request) { return indexed_modcall(RLM_COMPONENT_POST_AUTH, postauth_type, request); } #ifdef WITH_COA rlm_rcode_t process_recv_coa(int recv_coa_type, REQUEST *request) { return indexed_modcall(RLM_COMPONENT_RECV_COA, recv_coa_type, request); } rlm_rcode_t process_send_coa(int send_coa_type, REQUEST *request) { return indexed_modcall(RLM_COMPONENT_SEND_COA, send_coa_type, request); } #endif
gpl-2.0
cmc13/CHeaderGenerator
CHeaderGenerator/CSourceFileOptions.cs
4992
using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing.Design; using Microsoft.VisualStudio.Shell; using NLog; using System; using System.Linq.Expressions; namespace CHeaderGenerator { public class CSourceFileOptions : DialogPage, INotifyPropertyChanged { private bool showIncludeGuard = true; private string headerComment = @"/* Header file generated by C Header Generator. Executed by {Name} on {Date}. */"; private bool includeStaticFunctions = false; private bool includeExternFunctions = false; private string logLayout = "[${longdate}] ${level}: ${logger} - ${message}"; private LogLevel logLevel = LogLevel.Info; private bool autoSaveFiles = true; public event PropertyChangedEventHandler PropertyChanged; [Description("Generate an include guard to surround the file")] [DisplayName("Show Include Guard")] [Category("General")] public bool ShowIncludeGuard { get { return this.showIncludeGuard; } set { if (this.showIncludeGuard != value) { this.showIncludeGuard = value; this.OnPropertyChanged(() => this.ShowIncludeGuard); } } } [Description("The format of the header comment to display at the beginning of the header file")] [DisplayName("Header Comment")] [Category("General")] [Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))] public string HeaderComment { get { return this.headerComment; } set { if (this.headerComment != value) { this.headerComment = value; this.OnPropertyChanged(() => this.HeaderComment); } } } [Description("Include static declarations in header file")] [DisplayName("Include Static Declarations")] [Category("General")] public bool IncludeStaticFunctions { get { return this.includeStaticFunctions; } set { if (this.includeStaticFunctions != value) { this.includeStaticFunctions = value; this.OnPropertyChanged(() => this.IncludeStaticFunctions); } } } [Description("Include extern declarations in header file")] [DisplayName("Include Extern Declarations")] [Category("General")] public bool IncludeExternFunctions { get { return this.includeExternFunctions; } set { if (this.includeExternFunctions != value) { this.includeExternFunctions = value; this.OnPropertyChanged(() => this.IncludeExternFunctions); } } } [Description("Layout for log messages to the output window")] [DisplayName("Log Message Layout")] [Category("Logging")] public string LogLayout { get { return this.logLayout; } set { if (this.logLayout != value) { this.logLayout = value; this.OnPropertyChanged(() => this.LogLayout); } } } [Description("Minimum level for log messages")] [DisplayName("Log Level")] [Category("Logging")] public LogLevel LogLevel { get { return this.logLevel; } set { if (this.logLevel != value) { this.logLevel = value; this.OnPropertyChanged(() => this.LogLevel); } } } [Description("Automatically save files that have been modified when generating header files")] [DisplayName("Automatically Save Files")] [Category("General")] public bool AutoSaveFiles { get { return this.autoSaveFiles; } set { if (this.autoSaveFiles != value) { this.autoSaveFiles = value; this.OnPropertyChanged(() => this.AutoSaveFiles); } } } protected virtual void OnPropertyChanged<T>(Expression<Func<T>> propFunc) { var body = propFunc.Body as MemberExpression; if (body != null) this.OnPropertyChanged(body.Member.Name); } protected virtual void OnPropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
gpl-2.0
dagnarf/sgh-i717-dagkernel
drivers/usb/gadget/android.c
30277
/* * Gadget Driver for Android * * Copyright (C) 2008 Google, Inc. * Copyright (c) 2009-2010, Code Aurora Forum. All rights reserved. * Author: Mike Lockwood <[email protected]> * * 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. * */ /* #define DEBUG */ /* #define VERBOSE_DEBUG */ #include <linux/init.h> #include <linux/module.h> #include <linux/fs.h> #include <linux/delay.h> #include <linux/kernel.h> #include <linux/utsname.h> #include <linux/platform_device.h> #include <linux/pm_runtime.h> #include <linux/debugfs.h> #include <linux/usb/android_composite.h> #include <linux/usb/ch9.h> #include <linux/usb/composite.h> #include <linux/usb/gadget.h> #include "gadget_chips.h" /* * Kbuild is not very cooperative with respect to linking separately * compiled library objects into one module. So for now we won't use * separate compilation ... ensuring init/exit sections work to shrink * the runtime footprint, and giving us at least some parts of what * a "gcc --combine ... part1.c part2.c part3.c ... " build would. */ #include "usbstring.c" #include "config.c" #include "epautoconf.c" #include "composite.c" #ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE #include <mach/devices-lte.h> #endif MODULE_AUTHOR("Mike Lockwood"); MODULE_DESCRIPTION("Android Composite USB Driver"); MODULE_LICENSE("GPL"); MODULE_VERSION("1.0"); static const char longname[] = "Gadget Android"; /* Default vendor and product IDs, overridden by platform data */ #ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE # define VENDOR_ID 0x04e8 /* SAMSUNG */ # define PRODUCT_ID SAMSUNG_DEBUG_PRODUCT_ID #else /* Original VID & PID */ # define VENDOR_ID 0x18D1 # define PRODUCT_ID 0x0001 #endif /* CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE */ struct android_dev { struct usb_composite_dev *cdev; struct usb_configuration *config; int num_products; struct android_usb_product *products; int num_functions; char **functions; int product_id; int version; #ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE int current_usb_mode; /* soonyong.cho : save usb mode except tethering and askon mode. */ int requested_usb_mode; /* requested usb mode from app included tethering and askon */ int debugging_usb_mode; /* debugging usb mode */ #endif }; static struct android_dev *_android_dev; #define MAX_STR_LEN 16 /* string IDs are assigned dynamically */ #define STRING_MANUFACTURER_IDX 0 #define STRING_PRODUCT_IDX 1 #define STRING_SERIAL_IDX 2 char serial_number[MAX_STR_LEN]; /* String Table */ static struct usb_string strings_dev[] = { /* These dummy values should be overridden by platform data */ #ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE [STRING_MANUFACTURER_IDX].s = "SAMSUNG", [STRING_PRODUCT_IDX].s = "SAMSUNG_Android", [STRING_SERIAL_IDX].s = "0123456789ABCDEF", #else /* Original */ [STRING_MANUFACTURER_IDX].s = "Android", [STRING_PRODUCT_IDX].s = "Android", [STRING_SERIAL_IDX].s = "0123456789ABCDEF", #endif /* CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE */ { } /* end of list */ }; static struct usb_gadget_strings stringtab_dev = { .language = 0x0409, /* en-us */ .strings = strings_dev, }; static struct usb_gadget_strings *dev_strings[] = { &stringtab_dev, NULL, }; static struct usb_device_descriptor device_desc = { .bLength = sizeof(device_desc), .bDescriptorType = USB_DT_DEVICE, .bcdUSB = __constant_cpu_to_le16(0x0200), .bDeviceClass = USB_CLASS_PER_INTERFACE, .idVendor = __constant_cpu_to_le16(VENDOR_ID), .idProduct = __constant_cpu_to_le16(PRODUCT_ID), .bcdDevice = __constant_cpu_to_le16(0xffff), .bNumConfigurations = 1, }; static struct usb_otg_descriptor otg_descriptor = { .bLength = sizeof otg_descriptor, .bDescriptorType = USB_DT_OTG, .bmAttributes = USB_OTG_SRP | USB_OTG_HNP, .bcdOTG = __constant_cpu_to_le16(0x0200), }; static const struct usb_descriptor_header *otg_desc[] = { (struct usb_descriptor_header *) &otg_descriptor, NULL, }; static struct list_head _functions = LIST_HEAD_INIT(_functions); static int _registered_function_count = 0; #ifndef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE static void android_set_default_product(int product_id); #endif void android_usb_set_connected(int connected) { if (_android_dev && _android_dev->cdev && _android_dev->cdev->gadget) { if (connected) usb_gadget_connect(_android_dev->cdev->gadget); else usb_gadget_disconnect(_android_dev->cdev->gadget); } } #ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE static void samsung_enable_function(int mode); #endif static struct android_usb_function *get_function(const char *name) { struct android_usb_function *f; list_for_each_entry(f, &_functions, list) { if (!strcmp(name, f->name)) return f; } return 0; } static void bind_functions(struct android_dev *dev) { struct android_usb_function *f; char **functions = dev->functions; int i; for (i = 0; i < dev->num_functions; i++) { char *name = *functions++; f = get_function(name); if (f) f->bind_config(dev->config); else pr_err("%s: function %s not found\n", __func__, name); } /* * set_alt(), or next config->bind(), sets up * ep->driver_data as needed. */ usb_ep_autoconfig_reset(dev->cdev->gadget); } static int __ref android_bind_config(struct usb_configuration *c) { struct android_dev *dev = _android_dev; pr_debug("android_bind_config\n"); dev->config = c; /* bind our functions if they have all registered */ if (_registered_function_count == dev->num_functions) bind_functions(dev); return 0; } #ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE /* soonyong.cho : It is default config string. It'll be changed to real config string when last function driver is registered. */ # define ANDROID_DEFAULT_CONFIG_STRING "Samsung Android Shared Config" /* android default config string */ #else /* original */ # define ANDROID_DEBUG_CONFIG_STRING "UMS + ADB (Debugging mode)" # define ANDROID_NO_DEBUG_CONFIG_STRING "UMS Only (Not debugging mode)" #endif /* CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE */ static int android_setup_config(struct usb_configuration *c, const struct usb_ctrlrequest *ctrl); static struct usb_configuration android_config_driver = { #ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE .label = ANDROID_DEFAULT_CONFIG_STRING, #else /* original */ .label = ANDROID_NO_DEBUG_CONFIG_STRING, #endif /* CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE */ .bind = android_bind_config, .setup = android_setup_config, .bConfigurationValue = 1, #ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE .bMaxPower = 0x30, /* 96ma */ #else /* original */ .bMaxPower = 0xFA, /* 500ma */ #endif /* CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE */ }; static int android_setup_config(struct usb_configuration *c, const struct usb_ctrlrequest *ctrl) { int i; int ret = -EOPNOTSUPP; #ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE /* Do not call same function config when function has many interface. * If another function driver has different config function, It needs calling. */ char temp_name[128]={0,}; #endif for (i = 0; i < android_config_driver.next_interface_id; i++) { #ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE /*find same interface for to skip calling*/ if (!android_config_driver.interface[i]->disabled && android_config_driver.interface[i]->setup) { if (!strcmp(temp_name, android_config_driver.interface[i]->name)) { continue; } else strcpy(temp_name,android_config_driver.interface[i]->name); #else if (android_config_driver.interface[i]->setup) { #endif ret = android_config_driver.interface[i]->setup( android_config_driver.interface[i], ctrl); if (ret >= 0) return ret; } } return ret; } static int product_has_function(struct android_usb_product *p, struct usb_function *f) { char **functions = p->functions; int count = p->num_functions; const char *name = f->name; int i; for (i = 0; i < count; i++) { if (!strcmp(name, *functions++)) return 1; } return 0; } static int product_matches_functions(struct android_usb_product *p) { struct usb_function *f; list_for_each_entry(f, &android_config_driver.functions, list) { if (product_has_function(p, f) == !!f->disabled) return 0; } return 1; } static int get_product_id(struct android_dev *dev) { struct android_usb_product *p = dev->products; int count = dev->num_products; int i; if (p) { for (i = 0; i < count; i++, p++) { if (product_matches_functions(p)) return p->product_id; } } /* use default product ID */ return dev->product_id; } static int __devinit android_bind(struct usb_composite_dev *cdev) { struct android_dev *dev = _android_dev; struct usb_gadget *gadget = cdev->gadget; int gcnum, id, product_id, ret; pr_debug("android_bind\n"); /* Allocate string descriptor numbers ... note that string * contents can be overridden by the composite_dev glue. */ id = usb_string_id(cdev); if (id < 0) return id; strings_dev[STRING_MANUFACTURER_IDX].id = id; device_desc.iManufacturer = id; id = usb_string_id(cdev); if (id < 0) return id; strings_dev[STRING_PRODUCT_IDX].id = id; device_desc.iProduct = id; id = usb_string_id(cdev); if (id < 0) return id; strings_dev[STRING_SERIAL_IDX].id = id; device_desc.iSerialNumber = id; if (gadget_is_otg(cdev->gadget)) android_config_driver.descriptors = otg_desc; if (!usb_gadget_set_selfpowered(gadget)) android_config_driver.bmAttributes |= USB_CONFIG_ATT_SELFPOWER; #ifndef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE if (gadget->ops->wakeup) android_config_driver.bmAttributes |= USB_CONFIG_ATT_WAKEUP; #endif /* register our configuration */ ret = usb_add_config(cdev, &android_config_driver); if (ret) { pr_err("%s: usb_add_config failed\n", __func__); return ret; } gcnum = usb_gadget_controller_number(gadget); if (gcnum >= 0) #ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE /* Samsung KIES needs fixed bcdDevice number */ device_desc.bcdDevice = cpu_to_le16(0x0400); #else device_desc.bcdDevice = cpu_to_le16(0x0200 + gcnum); #endif else { /* gadget zero is so simple (for now, no altsettings) that * it SHOULD NOT have problems with bulk-capable hardware. * so just warn about unrcognized controllers -- don't panic. * * things like configuration and altsetting numbering * can need hardware-specific attention though. */ pr_warning("%s: controller '%s' not recognized\n", longname, gadget->name); device_desc.bcdDevice = __constant_cpu_to_le16(0x9999); } usb_gadget_set_selfpowered(gadget); dev->cdev = cdev; product_id = get_product_id(dev); device_desc.idProduct = __constant_cpu_to_le16(product_id); cdev->desc.idProduct = device_desc.idProduct; return 0; } static struct usb_composite_driver android_usb_driver = { .name = "android_usb", .dev = &device_desc, .strings = dev_strings, .bind = android_bind, .enable_function = android_enable_function, }; static bool is_func_supported(struct android_usb_function *f) { char **functions = _android_dev->functions; int count = _android_dev->num_functions; const char *name = f->name; int i; for (i = 0; i < count; i++) { if (!strcmp(*functions++, name)) return true; } return false; } void android_register_function(struct android_usb_function *f) { struct android_dev *dev = _android_dev; pr_debug("%s: %s\n", __func__, f->name); pr_info("%s: %s %d, %d\n", __func__, f->name,_registered_function_count,dev->num_functions); if (!is_func_supported(f)) return; list_add_tail(&f->list, &_functions); _registered_function_count++; /* bind our functions if they have all registered * and the main driver has bound. */ if (dev->config && _registered_function_count == dev->num_functions) { bind_functions(dev); #ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE /*Change usb mode and enable usb ip when device register last function driver */ samsung_enable_function(USBSTATUS_SAMSUNG_KIES); #else android_set_default_product(dev->product_id); #endif } } #ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE /* * Description : Set enable functions * Parameters : char** functions (product function list), int num_f (number of product functions) * Return value : Count of enable functions */ static int set_enable_functions(char **functions, int num_f) { int i; struct usb_function *func; int find = false; int count = 0; char **head_functions = functions; list_for_each_entry(func, &android_config_driver.functions, list) { pr_info("func->name=%s\n", func->name); functions = head_functions; for(i = 0; i < num_f; i++) { /* enable */ pr_info("%s: %s - %s %d, %d\n", __func__, func->name,*functions,i,num_f); if (!strcmp(func->name, *functions++)) { usb_function_set_enabled(func, 1); find = true; ++count; pr_info("enable %s\n", func->name); break; } } /* disable */ if(find == false) { usb_function_set_enabled(func, 0); } else /* finded */ find = false; } return count; } /* * Description : Set product using function as set_enable_function * Parameters : struct android_dev *dev (Refer dev->products), __u16 mode (usb mode) * Return Value : -1 (fail to find product), positive value (number of functions) */ static int set_product(struct android_dev *dev, __u16 mode) { struct android_usb_product *p = dev->products; int count = dev->num_products; int i, ret; dev->requested_usb_mode = mode; /* Save usb mode always even though it will be failed */ if (p) { for (i = 0; i < count; i++, p++) { if(p->mode == mode) { /* It is for setting dynamic interface in composite.c */ dev->cdev->product_num = p->num_functions; dev->cdev->products = p; dev->cdev->desc.bDeviceClass = p->bDeviceClass; dev->cdev->desc.bDeviceSubClass = p->bDeviceSubClass; dev->cdev->desc.bDeviceProtocol = p->bDeviceProtocol; android_config_driver.label = p->s; pr_info("%s: %d, %d\n", __func__, p->num_functions, mode); ret = set_enable_functions(p->functions, p->num_functions); pr_info("Change Device Descriptor : DeviceClass(0x%x),SubClass(0x%x),Protocol(0x%x)\n", p->bDeviceClass, p->bDeviceSubClass, p->bDeviceProtocol); pr_info("Change Label : [%d]%s\n", i, p->s); if(ret == 0) pr_info("Can't find functions(mode=0x%x)\n", mode); else pr_info("set function num=%d\n", ret); return ret; } } } return -1; } /* * Description : Enable functions for samsung composite driver * Parameters : struct usb_function *f (It depends on function's sysfs), int enable (1:enable, 0:disable) * Return value : void * */ int android_enable_function(struct usb_function *f, int enable) { struct android_dev *dev = _android_dev; int product_id = 0; int ret = -1; if (dev->requested_usb_mode == USBSTATUS_RMNET) return; if(enable) { if (!strcmp(f->name, "acm")) { ret = set_product(dev, USBSTATUS_SAMSUNG_KIES); if (ret != -1) dev->current_usb_mode = USBSTATUS_SAMSUNG_KIES; } if (!strcmp(f->name, "adb")) { ret = set_product(dev, USBSTATUS_ADB); if (ret != -1) dev->debugging_usb_mode = 1; /* save debugging status */ } if (!strcmp(f->name, "mtp")) { ret = set_product(dev, USBSTATUS_MTPONLY); if (ret != -1) dev->current_usb_mode = USBSTATUS_MTPONLY; } if (!strcmp(f->name, "rndis")) { ret = set_product(dev, USBSTATUS_VTP); } if (!strcmp(f->name, "usb_mass_storage")) { ret = set_product(dev, USBSTATUS_UMS); if (ret != -1) dev->current_usb_mode = USBSTATUS_UMS; } if (!strcmp(f->name, "rmnet_sdio")) { ret = set_product(dev, USBSTATUS_RMNET); if (ret != -1) dev->current_usb_mode = USBSTATUS_RMNET; } } else { /* for disable : Return old mode. If Non-GED model changes policy, below code has to be modified. */ if (!strcmp(f->name, "rndis") && dev->debugging_usb_mode) ret = set_product(dev, USBSTATUS_ADB); else ret = set_product(dev, dev->current_usb_mode); if(!strcmp(f->name, "adb")) dev->debugging_usb_mode = 0; } /* if(enable) */ if(ret == -1) { //return ; return -EINVAL; } product_id = get_product_id(dev); device_desc.idProduct = __constant_cpu_to_le16(product_id); if (dev->cdev){ dev->cdev->desc.idProduct = device_desc.idProduct; /* force reenumeration */ usb_composite_force_reset(dev->cdev); } return 0; } #else /* original code */ /** * android_set_function_mask() - enables functions based on selected pid. * @up: selected product id pointer * * This function enables functions related with selected product id. */ static void android_set_function_mask(struct android_usb_product *up) { int index, found = 0; struct usb_function *func; list_for_each_entry(func, &android_config_driver.functions, list) { /* adb function enable/disable handled separetely */ if (!strcmp(func->name, "adb") && !func->disabled) continue; for (index = 0; index < up->num_functions; index++) { if (!strcmp(up->functions[index], func->name)) { found = 1; break; } } if (found) { /* func is part of product. */ /* if func is disabled, enable the same. */ if (func->disabled) usb_function_set_enabled(func, 1); found = 0; } else { /* func is not part if product. */ /* if func is enabled, disable the same. */ if (!func->disabled) usb_function_set_enabled(func, 0); } } } /** * android_set_defaut_product() - selects default product id and enables * required functions * @product_id: default product id * * This function selects default product id using pdata information and * enables functions for same. */ static void android_set_default_product(int pid) { struct android_dev *dev = _android_dev; struct android_usb_product *up = dev->products; int index; for (index = 0; index < dev->num_products; index++, up++) { if (pid == up->product_id) break; } android_set_function_mask(up); } /** * android_config_functions() - selects product id based on function need * to be enabled / disabled. * @f: usb function * @enable : function needs to be enable or disable * * This function selects first product id having required function. * RNDIS/MTP function enable/disable uses this. */ #ifdef CONFIG_USB_ANDROID_RNDIS static void android_config_functions(struct usb_function *f, int enable) { struct android_dev *dev = _android_dev; struct android_usb_product *up = dev->products; int index; /* Searches for product id having function */ if (enable) { for (index = 0; index < dev->num_products; index++, up++) { if (product_has_function(up, f)) break; } android_set_function_mask(up); } else android_set_default_product(dev->product_id); } #endif void update_dev_desc(struct android_dev *dev) { struct usb_function *f; struct usb_function *last_enabled_f = NULL; int num_enabled = 0; int has_iad = 0; dev->cdev->desc.bDeviceClass = USB_CLASS_PER_INTERFACE; dev->cdev->desc.bDeviceSubClass = 0x00; dev->cdev->desc.bDeviceProtocol = 0x00; list_for_each_entry(f, &android_config_driver.functions, list) { if (!f->disabled) { num_enabled++; last_enabled_f = f; if (f->descriptors[0]->bDescriptorType == USB_DT_INTERFACE_ASSOCIATION) has_iad = 1; } if (num_enabled > 1 && has_iad) { dev->cdev->desc.bDeviceClass = USB_CLASS_MISC; dev->cdev->desc.bDeviceSubClass = 0x02; dev->cdev->desc.bDeviceProtocol = 0x01; break; } } if (num_enabled == 1) { #ifdef CONFIG_USB_ANDROID_RNDIS if (!strcmp(last_enabled_f->name, "rndis")) { #ifdef CONFIG_USB_ANDROID_RNDIS_WCEIS dev->cdev->desc.bDeviceClass = USB_CLASS_WIRELESS_CONTROLLER; #else dev->cdev->desc.bDeviceClass = USB_CLASS_COMM; #endif } #endif } } static char *sysfs_allowed[] = { "rndis", "mtp", "adb", }; static int is_sysfschange_allowed(struct usb_function *f) { char **functions = sysfs_allowed; int count = ARRAY_SIZE(sysfs_allowed); int i; for (i = 0; i < count; i++) { if (!strncmp(f->name, functions[i], 32)) return 1; } return 0; } int android_enable_function(struct usb_function *f, int enable) { struct android_dev *dev = _android_dev; int disable = !enable; int product_id; if (!is_sysfschange_allowed(f)) return -EINVAL; if (!!f->disabled != disable) { usb_function_set_enabled(f, !disable); #ifdef CONFIG_USB_ANDROID_RNDIS if (!strcmp(f->name, "rndis")) { /* We need to specify the COMM class in the device descriptor * if we are using RNDIS. */ if (enable) { #ifdef CONFIG_USB_ANDROID_RNDIS_WCEIS dev->cdev->desc.bDeviceClass = USB_CLASS_MISC; dev->cdev->desc.bDeviceSubClass = 0x02; dev->cdev->desc.bDeviceProtocol = 0x01; #else dev->cdev->desc.bDeviceClass = USB_CLASS_COMM; #endif } else { dev->cdev->desc.bDeviceClass = USB_CLASS_PER_INTERFACE; dev->cdev->desc.bDeviceSubClass = 0; dev->cdev->desc.bDeviceProtocol = 0; } android_config_functions(f, enable); } #endif #ifdef CONFIG_USB_ANDROID_MTP if (!strcmp(f->name, "mtp")) android_config_functions(f, enable); #endif product_id = get_product_id(dev); device_desc.idProduct = __constant_cpu_to_le16(product_id); if (dev->cdev) dev->cdev->desc.idProduct = device_desc.idProduct; usb_composite_force_reset(dev->cdev); } return 0; } #endif /* CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE */ #ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE static void samsung_enable_function(int mode) { struct android_dev *dev = _android_dev; int product_id = 0; int ret = -1; switch(mode) { case USBSTATUS_UMS: ret = set_product(dev, USBSTATUS_UMS); break; case USBSTATUS_SAMSUNG_KIES: ret = set_product(dev, USBSTATUS_SAMSUNG_KIES); break; case USBSTATUS_MTPONLY: ret = set_product(dev, USBSTATUS_MTPONLY); break; case USBSTATUS_ADB: ret = set_product(dev, USBSTATUS_ADB); break; #ifdef CONFIG_USB_ANDROID_RNDIS case USBSTATUS_VTP: /* do not save usb mode */ ret = set_product(dev, USBSTATUS_VTP); break; #endif case USBSTATUS_RMNET: /* do not save usb mode */ ret = set_product(dev, USBSTATUS_RMNET); break; case USBSTATUS_ASKON: /* do not save usb mode */ return; } if(ret == -1) { return ; } else if((mode != USBSTATUS_VTP) && (mode != USBSTATUS_ASKON)) { dev->current_usb_mode = mode; } product_id = get_product_id(dev); device_desc.idProduct = __constant_cpu_to_le16(product_id); if (dev->cdev){ dev->cdev->desc.idProduct = device_desc.idProduct; /* force reenumeration */ usb_composite_force_reset(dev->cdev); } } #endif /* CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE */ #ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE //Path (/sys/devices/platform/android_usb/tethering) static ssize_t tethering_switch_show(struct device *dev, struct device_attribute *attr, char *buf) { struct android_dev *a_dev = _android_dev; int value = -1; if(a_dev->cdev) { if (a_dev->requested_usb_mode == USBSTATUS_VTP ) value = 1; else value = 0; } return sprintf(buf, "%d\n", value); } //Path (/sys/devices/platform/android_usb/tethering) static ssize_t tethering_switch_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { int value; struct android_dev *a_dev = _android_dev; sscanf(buf, "%d", &value); if (value) { if(a_dev->cdev) { if(a_dev->cdev->gadget->speed == USB_SPEED_UNKNOWN) a_dev->cdev->mute_switch = 1; } samsung_enable_function(USBSTATUS_VTP); if(a_dev->cdev) if(a_dev->cdev->gadget) usb_gadget_vbus_connect(a_dev->cdev->gadget); } else { if(a_dev->debugging_usb_mode) samsung_enable_function(USBSTATUS_ADB); else samsung_enable_function(a_dev->current_usb_mode); } return size; } static DEVICE_ATTR(tethering, 0664, tethering_switch_show, tethering_switch_store); //Path (/sys/devices/platform/android_usb/UsbMenuSel) static ssize_t UsbMenuSel_switch_show(struct device *dev, struct device_attribute *attr, char *buf) { struct android_dev *a_dev = _android_dev; int value = -1; if(a_dev->cdev) { switch(a_dev->requested_usb_mode) { case USBSTATUS_UMS: return sprintf(buf, "[UsbMenuSel] UMS\n"); case USBSTATUS_SAMSUNG_KIES: return sprintf(buf, "[UsbMenuSel] ACM_MTP\n"); case USBSTATUS_MTPONLY: return sprintf(buf, "[UsbMenuSel] MTP\n"); case USBSTATUS_ASKON: return sprintf(buf, "[UsbMenuSel] ASK\n"); case USBSTATUS_VTP: return sprintf(buf, "[UsbMenuSel] TETHERING\n"); case USBSTATUS_ADB: return sprintf(buf, "[UsbMenuSel] ACM_ADB_UMS\n"); case USBSTATUS_RMNET: return sprintf(buf, "[UsbMenuSel] RMNET\n"); } } return sprintf(buf, "%d\n", value); } //Path (/sys/devices/platform/android_usb/UsbMenuSel) ssize_t UsbMenuSel_switch_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { int value; struct android_dev *andev = _android_dev; sscanf(buf, "%d", &value); printk("%s value %d %c",__func__,value, buf); switch(value) { case 0: samsung_enable_function(USBSTATUS_SAMSUNG_KIES); break; case 1: samsung_enable_function(USBSTATUS_MTPONLY); break; case 2: samsung_enable_function(USBSTATUS_UMS); break; case 3: samsung_enable_function(USBSTATUS_ASKON); break; case 4: samsung_enable_function(USBSTATUS_RMNET); break; case 5: samsung_enable_function(USBSTATUS_ADB); break; default: break; } return size; } static DEVICE_ATTR(UsbMenuSel, 0664, UsbMenuSel_switch_show, UsbMenuSel_switch_store); #endif /* CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE */ #ifdef CONFIG_DEBUG_FS static int android_debugfs_open(struct inode *inode, struct file *file) { file->private_data = inode->i_private; return 0; } static ssize_t android_debugfs_serialno_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { char str_buf[MAX_STR_LEN]; if (count > MAX_STR_LEN) return -EFAULT; if (copy_from_user(str_buf, buf, count)) return -EFAULT; memcpy(serial_number, str_buf, count); if (serial_number[count - 1] == '\n') serial_number[count - 1] = '\0'; strings_dev[STRING_SERIAL_IDX].s = serial_number; return count; } const struct file_operations android_fops = { .open = android_debugfs_open, .write = android_debugfs_serialno_write, }; struct dentry *android_debug_root; struct dentry *android_debug_serialno; static int android_debugfs_init(struct android_dev *dev) { android_debug_root = debugfs_create_dir("android", NULL); if (!android_debug_root) return -ENOENT; android_debug_serialno = debugfs_create_file("serial_number", S_IWUSR |S_IWGRP, android_debug_root, dev, &android_fops); if (!android_debug_serialno) { debugfs_remove(android_debug_root); android_debug_root = NULL; return -ENOENT; } return 0; } static void android_debugfs_cleanup(void) { debugfs_remove(android_debug_serialno); debugfs_remove(android_debug_root); } #endif static int __init android_probe(struct platform_device *pdev) { struct android_usb_platform_data *pdata = pdev->dev.platform_data; struct android_dev *dev = _android_dev; int result; dev_dbg(&pdev->dev, "%s: pdata: %p\n", __func__, pdata); pm_runtime_set_active(&pdev->dev); pm_runtime_enable(&pdev->dev); result = pm_runtime_get(&pdev->dev); if (result < 0) { dev_err(&pdev->dev, "Runtime PM: Unable to wake up the device, rc = %d\n", result); return result; } if (pdata) { dev->products = pdata->products; dev->num_products = pdata->num_products; dev->functions = pdata->functions; dev->num_functions = pdata->num_functions; if (pdata->vendor_id) device_desc.idVendor = __constant_cpu_to_le16(pdata->vendor_id); if (pdata->product_id) { dev->product_id = pdata->product_id; device_desc.idProduct = __constant_cpu_to_le16(pdata->product_id); } if (pdata->version) dev->version = pdata->version; if (pdata->product_name) strings_dev[STRING_PRODUCT_IDX].s = pdata->product_name; if (pdata->manufacturer_name) strings_dev[STRING_MANUFACTURER_IDX].s = pdata->manufacturer_name; if (pdata->serial_number) strings_dev[STRING_SERIAL_IDX].s = pdata->serial_number; } #ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE /* Create attribute of sysfs as '/sys/devices/platform/android_usb/UsbMenuSel' * It is for USB menu selection. * Application for USB Setting made by SAMSUNG uses property that uses below sysfs. */ if (device_create_file(&pdev->dev, &dev_attr_UsbMenuSel) < 0) { } if (device_create_file(&pdev->dev, &dev_attr_tethering) < 0) { } #endif #ifdef CONFIG_DEBUG_FS result = android_debugfs_init(dev); if (result) pr_debug("%s: android_debugfs_init failed\n", __func__); #endif return usb_composite_register(&android_usb_driver); } static int andr_runtime_suspend(struct device *dev) { dev_dbg(dev, "pm_runtime: suspending...\n"); return 0; } static int andr_runtime_resume(struct device *dev) { dev_dbg(dev, "pm_runtime: resuming...\n"); return 0; } static struct dev_pm_ops andr_dev_pm_ops = { .runtime_suspend = andr_runtime_suspend, .runtime_resume = andr_runtime_resume, }; static struct platform_driver android_platform_driver = { .driver = { .name = "android_usb", .pm = &andr_dev_pm_ops}, }; static int __init init(void) { struct android_dev *dev; pr_debug("android init\n"); dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM; /* set default values, which should be overridden by platform data */ dev->product_id = PRODUCT_ID; _android_dev = dev; return platform_driver_probe(&android_platform_driver, android_probe); } module_init(init); static void __exit cleanup(void) { #ifdef CONFIG_DEBUG_FS android_debugfs_cleanup(); #endif usb_composite_unregister(&android_usb_driver); platform_driver_unregister(&android_platform_driver); kfree(_android_dev); _android_dev = NULL; } module_exit(cleanup);
gpl-2.0
javilonas/Ptah-GT-I9300
arch/arm/mach-exynos/include/mach/busfreq_exynos4.h
3508
/* linux/arch/arm/mach-exynos/include/mach/busfreq_exynos4.h * * Copyright (c) 2010 Samsung Electronics Co., Ltd. * http://www.samsung.com * * EXYNOS4 - BUSFreq support * * 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 __ASM_ARCH_BUSFREQ_H #define __ASM_ARCH_BUSFREQ_H __FILE__ #include <linux/notifier.h> #include <linux/earlysuspend.h> #include <mach/ppmu.h> #define MAX_LOAD 100 #define LOAD_HISTORY_SIZE 5 #define DIVIDING_FACTOR 10000 #define TIMINGROW_OFFSET 0x34 #define PRIME_DMC_MAX_THRESHOLD 30 #define EXYNOS4412_DMC_MAX_THRESHOLD 30 #define EXYNOS4212_DMC_MAX_THRESHOLD 30 #if defined(CONFIG_MACH_P4NOTE) || defined(CONFIG_MACH_SP7160LTE) || defined(CONFIG_MACH_M0) || defined(CONFIG_MACH_C1) || defined(CONFIG_MACH_T0) #define DECODING_LOAD 5 #else #define DECODING_LOAD 10 #endif extern unsigned int up_threshold; extern unsigned int ppmu_threshold; extern unsigned int idle_threshold; extern unsigned int up_cpu_threshold; extern unsigned int max_cpu_threshold; extern unsigned int cpu_slope_size; extern unsigned int dmc_max_threshold; extern unsigned int load_history_size; struct opp; struct device; struct busfreq_table; struct busfreq_data { bool use; struct device *dev; struct delayed_work worker; struct opp *curr_opp; struct opp *max_opp; struct opp *min_opp; struct regulator *vdd_int; struct regulator *vdd_mif; unsigned int sampling_rate; struct kobject *busfreq_kobject; int table_size; struct busfreq_table *table; unsigned int *int_table; unsigned long long *time_in_state; unsigned long long last_time; unsigned int load_history[PPMU_END][LOAD_HISTORY_SIZE]; int index; int rate_mult; #ifdef CONFIG_BUSFREQ_INTERLOCK_CPUFREQ int is_lcd_on; #endif struct notifier_block exynos_buspm_notifier; struct notifier_block exynos_reboot_notifier; struct notifier_block exynos_request_notifier; struct notifier_block exynos_cpufreq_notifier; struct notifier_block exynos_busqos_notifier; struct early_suspend busfreq_early_suspend_handler; struct attribute_group busfreq_attr_group; int (*init) (struct device *dev, struct busfreq_data *data); struct opp *(*monitor)(struct busfreq_data *data); void (*target) (int index); unsigned int (*get_int_volt) (unsigned long index); unsigned int (*get_table_index) (struct opp *opp); void (*busfreq_prepare) (unsigned int index); void (*busfreq_post) (unsigned int index); void (*set_qos) (unsigned int index); void (*busfreq_suspend) (void); void (*busfreq_resume) (void); }; struct busfreq_table { unsigned int idx; unsigned int mem_clk; unsigned int volt; unsigned int clk_topdiv; unsigned int clk_dmc0div; unsigned int clk_dmc1div; }; void exynos_request_apply(unsigned long freq); struct opp *step_down(struct busfreq_data *data, int step); int exynos4x12_init(struct device *dev, struct busfreq_data *data); void exynos4x12_target(int index); unsigned int exynos4x12_get_int_volt(unsigned long freq); unsigned int exynos4x12_get_table_index(struct opp *opp); struct opp *exynos4x12_monitor(struct busfreq_data *data); void exynos4x12_prepare(unsigned int index); void exynos4x12_post(unsigned int index); void exynos4x12_set_qos(unsigned int index); void exynos4x12_suspend(void); void exynos4x12_resume(void); int exynos4x12_find_busfreq_by_volt(unsigned int req_volt, unsigned int *freq); #endif /* __ASM_ARCH_BUSFREQ_H */
gpl-2.0
kuym/openocd
tools/automake-1.15/t/configure.sh
1785
#! /bin/sh # Copyright (C) 2010-2014 Free Software Foundation, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Diagnose if the autoconf input is named configure.in. # Diagnose if both configure.in and configure.ac are present, prefer # configure.ac. . test-init.sh cat >configure.ac <<EOF AC_INIT([$me], [1.0]) AM_INIT_AUTOMAKE AC_CONFIG_FILES([Makefile]) EOF cat >configure.in <<EOF AC_INIT([$me], [1.0]) AM_INIT_AUTOMAKE([an-invalid-automake-option]) AC_CONFIG_FILES([Makefile]) EOF : >Makefile.am $ACLOCAL 2>stderr && { cat stderr >&2; exit 1; } cat stderr >&2 grep 'configure\.ac.*configure\.in.*both present' stderr $ACLOCAL -Wno-error 2>stderr || { cat stderr >&2; exit 1; } cat stderr >&2 grep 'configure\.ac.*configure\.in.*both present' stderr grep 'proceeding.*configure\.ac' stderr # Ensure we really proceed with configure.ac. AUTOMAKE_fails -Werror grep 'configure\.ac.*configure\.in.*both present' stderr grep 'proceeding.*configure\.ac' stderr AUTOMAKE_run -Wno-error grep 'configure\.ac.*configure\.in.*both present' stderr grep 'proceeding.*configure\.ac' stderr mv -f configure.ac configure.in AUTOMAKE_fails grep "autoconf input.*'configure.ac', not 'configure.in'" stderr :
gpl-2.0
uq-eresearch/oztrack
src/main/resources/org/oztrack/data/migration/V25__data_licence_identifier.sql
838
alter table data_licence add column identifier text; update data_licence set identifier = 'CC-BY' where title = 'Attribution'; update data_licence set identifier = 'CC-BY-SA' where title = 'Attribution-ShareAlike'; update data_licence set identifier = 'CC-BY-ND' where title = 'Attribution-NoDerivatives'; update data_licence set identifier = 'CC-BY-NC' where title = 'Attribution-NonCommercial'; update data_licence set identifier = 'CC-BY-NC-SA' where title = 'Attribution-NonCommercial-ShareAlike'; update data_licence set identifier = 'CC-BY-NC-ND' where title = 'Attribution-NonCommercial-NoDerivatives'; update data_licence set identifier = 'CC0' where title = 'CC0 (No Rights Reserved)'; update data_licence set identifier = 'PDM' where title = 'Public Domain Mark'; alter table data_licence alter column identifier set not null;
gpl-2.0
eugmes/rtems
cpukit/score/src/threadqextractwithproxy.c
1880
/** * @brief _Thread_queue_Extract_with_proxy * * This routine extracts the_thread from the_thread_queue * and ensures that if there is a proxy for this task on * another node, it is also dealt with. A proxy is a data * data that is on the thread queue on the remote node and * acts as a proxy for the local thread. If the local thread * was waiting on a remote operation, then the remote side * of the operation must be cleaned up. */ /* * COPYRIGHT (c) 1989-2012. * On-Line Applications Research Corporation (OAR). * * The license and distribution terms for this file may be * found in the file LICENSE in this distribution or at * http://www.rtems.com/license/LICENSE. */ #if HAVE_CONFIG_H #include "config.h" #endif #include <rtems/system.h> #include <rtems/score/chain.h> #include <rtems/score/isr.h> #include <rtems/score/object.h> #include <rtems/score/states.h> #include <rtems/score/thread.h> #include <rtems/score/threadq.h> #include <rtems/score/tqdata.h> bool _Thread_queue_Extract_with_proxy( Thread_Control *the_thread ) { States_Control state; state = the_thread->current_state; if ( _States_Is_waiting_on_thread_queue( state ) ) { #if defined(RTEMS_MULTIPROCESSING) if ( _States_Is_waiting_for_rpc_reply( state ) && _States_Is_locally_blocked( state ) ) { Objects_Information *the_information; Objects_Thread_queue_Extract_callout proxy_extract_callout; the_information = _Objects_Get_information_id( the_thread->Wait.id ); proxy_extract_callout = (Objects_Thread_queue_Extract_callout) the_information->extract; if ( proxy_extract_callout ) (*proxy_extract_callout)( the_thread ); } #endif _Thread_queue_Extract( the_thread->Wait.queue, the_thread ); return true; } return false; }
gpl-2.0
dhx/tao-comp
vendor/qtism/qtism/qtism/data/expressions/NullValue.php
1260
<?php /** * 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; under version 2 * of the License (non-upgradable). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Copyright (c) 2013 (original work) Open Assessment Technologies SA (under the project TAO-PRODUCT); * * @author Jérôme Bogaerts, <[email protected]> * @license GPLv2 * @package */ namespace qtism\data\expressions; /** * From IMS QTI: * * null is a simple expression that returns the NULL value - the null value is * treated as if it is of any desired baseType. * * @author Jérôme Bogaerts <[email protected]> * */ class NullValue extends Expression { public function getQtiClassName() { return 'null'; } }
gpl-2.0
bentley/netsurf
atari/redrawslots.h
1703
/* * Copyright 2012 Ole Loots <[email protected]> * * This file is part of NetSurf, http://www.netsurf-browser.org/ * * NetSurf is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. * * NetSurf 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/>. */ #ifndef ATARI_REDRAW_SLOTS_H #define ATARI_REDRAW_SLOTS_H #include <mt_gem.h> #include "utils/utils.h" /* MAX_REDRW_SLOTS This is the number of redraw requests that the slotlist can store. If a redraw is scheduled and all slots are used, the rectangle will be merged to one of the existing slots. */ #define MAX_REDRW_SLOTS 32 /* This struct holds scheduled redraw requests. */ struct rect; struct s_redrw_slots { struct rect areas[MAX_REDRW_SLOTS]; short size; short volatile areas_used; }; void redraw_slots_init(struct s_redrw_slots * slots, short size); void redraw_slot_schedule(struct s_redrw_slots * slots, short x0, short y0, short x1, short y1, bool force); void redraw_slot_schedule_grect(struct s_redrw_slots * slots, GRECT *area, bool force); void redraw_slots_remove_area(struct s_redrw_slots * slots, int i); void redraw_slots_free(struct s_redrw_slots * slots); #endif
gpl-2.0
SkyFireArchives/SkyFireEMU_433
src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_epoch.cpp
5315
/* * Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2011 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* Script Data Start SFName: Boss epoch SFAuthor: Tartalo SF%Complete: 80 SFComment: TODO: Intro, consecutive attacks to a random target durin time wrap, adjust timers SFCategory: Script Data End */ #include "ScriptPCH.h" #include "culling_of_stratholme.h" enum Spells { SPELL_CURSE_OF_EXERTION = 52772, SPELL_TIME_WARP = 52766, //Time slows down, reducing attack, casting and movement speed by 70% for 6 sec. SPELL_TIME_STOP = 58848, //Stops time in a 50 yard sphere for 2 sec. SPELL_WOUNDING_STRIKE = 52771, //Used only on the tank H_SPELL_WOUNDING_STRIKE = 58830 }; enum Yells { SAY_INTRO = -1595000, //"Prince Arthas Menethil, on this day, a powerful darkness has taken hold of your soul. The death you are destined to visit upon others will this day be your own." SAY_AGGRO = -1595001, //"We'll see about that, young prince." SAY_TIME_WARP_1 = -1595002, //"Tick tock, tick tock..." SAY_TIME_WARP_2 = -1595003, //"Not quick enough!" SAY_TIME_WARP_3 = -1595004, //"Let's get this over with. " SAY_SLAY_1 = -1595005, //"There is no future for you." SAY_SLAY_2 = -1595006, //"This is the hour of our greatest triumph!" SAY_SLAY_3 = -1595007, //"You were destined to fail. " SAY_DEATH = -1595008 //"*gurgles*" }; class boss_epoch : public CreatureScript { public: boss_epoch() : CreatureScript("boss_epoch") { } CreatureAI* GetAI(Creature* creature) const { return new boss_epochAI (creature); } struct boss_epochAI : public ScriptedAI { boss_epochAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); } uint8 Step; uint32 StepTimer; uint32 WoundingStrikeTimer; uint32 TimeWarpTimer; uint32 TimeStopTimer; uint32 CurseOfExertionTimer; InstanceScript* instance; void Reset() { Step = 1; StepTimer = 26000; CurseOfExertionTimer = 9300; TimeWarpTimer = 25300; TimeStopTimer = 21300; WoundingStrikeTimer = 5300; if (instance) instance->SetData(DATA_EPOCH_EVENT, NOT_STARTED); } void EnterCombat(Unit* /*who*/) { DoScriptText(SAY_AGGRO, me); if (instance) instance->SetData(DATA_EPOCH_EVENT, IN_PROGRESS); } void UpdateAI(const uint32 diff) { //Return since we have no target if (!UpdateVictim()) return; if (CurseOfExertionTimer < diff) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true)) DoCast(target, SPELL_CURSE_OF_EXERTION); CurseOfExertionTimer = 9300; } else CurseOfExertionTimer -= diff; if (WoundingStrikeTimer < diff) { DoCastVictim(SPELL_WOUNDING_STRIKE); WoundingStrikeTimer = 5300; } else WoundingStrikeTimer -= diff; if (TimeStopTimer < diff) { DoCastAOE(SPELL_TIME_STOP); TimeStopTimer = 21300; } else TimeStopTimer -= diff; if (TimeWarpTimer < diff) { DoScriptText(RAND(SAY_TIME_WARP_1, SAY_TIME_WARP_2, SAY_TIME_WARP_3), me); DoCastAOE(SPELL_TIME_WARP); TimeWarpTimer = 25300; } else TimeWarpTimer -= diff; DoMeleeAttackIfReady(); } void JustDied(Unit* /*killer*/) { DoScriptText(SAY_DEATH, me); if (instance) instance->SetData(DATA_EPOCH_EVENT, DONE); } void KilledUnit(Unit* victim) { if (victim == me) return; DoScriptText(RAND(SAY_SLAY_1, SAY_SLAY_2, SAY_SLAY_3), me); } }; }; void AddSC_boss_epoch() { new boss_epoch(); }
gpl-2.0
entdark/q3mme
trunk/code/client/snd_dma.c
5134
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code 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. Quake III Arena source code 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 Foobar; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ /***************************************************************************** * name: snd_dma.c * * desc: main control for any streaming sound output device * * $Archive: /MissionPack/code/client/snd_dma.c $ * *****************************************************************************/ #include "client.h" #include "snd_local.h" #include "snd_mix.h" #define DMA_SNDCHANNELS 128 #define DMA_LOOPCHANNELS 128 dma_t dma; static mixBackground_t dmaBackground; static mixLoop_t dmaLoops[DMA_LOOPCHANNELS]; static mixChannel_t dmaChannels[DMA_SNDCHANNELS]; static mixEffect_t dmaEffect; static qboolean dmaInit; static int dmaWrite; cvar_t *s_khz; cvar_t *s_show; cvar_t *s_mixahead; cvar_t *s_mixPreStep; /* ================== S_ClearSoundBuffer Lock the dma buffer and clear ================== */ void S_DMAClearBuffer( void ) { int clear; if (!dmaInit) return; /* Clear the active channels and loops */ Com_Memset( dmaLoops, 0, sizeof( dmaLoops )); Com_Memset( dmaChannels, 0, sizeof( dmaChannels )); Com_Memset( &dmaEffect, 0, sizeof( &dmaEffect )); s_rawend = 0; if (dma.samplebits == 8) clear = 0x80; else clear = 0; /* Fill the dma buffer */ SNDDMA_BeginPainting (); if (dma.buffer) Snd_Memset(dma.buffer, clear, dma.samples * dma.samplebits/8); SNDDMA_Submit (); } void S_DMAInit(void) { dmaInit = SNDDMA_Init(); dmaWrite = 0; s_khz = Cvar_Get ("s_khz", "22", CVAR_ARCHIVE); s_mixahead = Cvar_Get ("s_mixahead", "0.2", CVAR_ARCHIVE); s_mixPreStep = Cvar_Get ("s_mixPreStep", "0.05", CVAR_ARCHIVE); s_show = Cvar_Get ("s_show", "0", CVAR_CHEAT); } void S_DMAShowInfo(void) { if (!dmaInit) { Com_Printf( "DMA disabled\n" ); return; } Com_Printf("%5d stereo\n", dma.channels - 1); Com_Printf("%5d samples\n", dma.samples); Com_Printf("%5d samplebits\n", dma.samplebits); Com_Printf("%5d submission_chunk\n", dma.submission_chunk); Com_Printf("%5d speed\n", dma.speed); Com_Printf("0x%x dma buffer\n", dma.buffer); } //============================================================================= void S_DMA_Update( float scale ) { int ma, count; static int lastPos; int thisPos; int lastWrite, lastRead; int bufSize, bufDone; int speed; int buf[2048]; if (!dmaInit) return; bufSize = dma.samples >> (dma.channels-1); // Check for possible buffer underruns thisPos = SNDDMA_GetDMAPos() >> (dma.channels - 1); lastWrite = (lastPos <= dmaWrite) ? (dmaWrite - lastPos) : (bufSize - lastPos + dmaWrite); lastRead = ( lastPos <= thisPos ) ? (thisPos - lastPos) : (bufSize - lastPos + thisPos); if (lastRead > lastWrite) { bufDone = 0; dmaWrite = thisPos; // Com_Printf("OMG Buffer underrun\n"); } else { bufDone = lastWrite - lastRead; } // Com_Printf( "lastRead %d lastWrite %d done %d\n", lastRead, lastWrite, bufDone ); lastPos = thisPos; ma = s_mixahead->value * dma.speed; count = lastRead; if (bufDone + count < ma) { count = ma - bufDone + 1; } else if (bufDone + count > bufSize) { count = bufSize - bufDone; } if (count > sizeof(buf) / (2 * sizeof(int))) { count = sizeof(buf) / (2 * sizeof(int)); } // mix to an even submission block size count = (count + dma.submission_chunk-1) & ~(dma.submission_chunk-1); // never mix more than the complete buffer speed = (scale * (MIX_SPEED << MIX_SHIFT)) / dma.speed; /* Make sure that the speed will always go forward for very small scales */ if ( speed == 0 && scale ) speed = 1; /* Mix sound or fill with silence depending on speed */ if ( speed > 0 ) { /* mix the background track or init the buffer with silence */ S_MixBackground( &dmaBackground, speed, count, buf ); S_MixChannels( dmaChannels, DMA_SNDCHANNELS, speed, count, buf ); S_MixLoops( dmaLoops, DMA_LOOPCHANNELS, speed, count, buf ); S_MixEffects(&dmaEffect, speed, count, buf); } else { Com_Memset( buf, 0, sizeof( buf[0] ) * count * 2); } /* Lock dma buffer and copy/clip the final data */ SNDDMA_BeginPainting (); S_MixClipOutput( count, buf, (short *)dma.buffer, dmaWrite, bufSize-1 ); SNDDMA_Submit (); dmaWrite += count; if (dmaWrite >= bufSize) dmaWrite -= bufSize; }
gpl-2.0
sancome/linux-3.x
lib/div64.c
3410
/* * Copyright (C) 2003 Bernardo Innocenti <[email protected]> * * Based on former do_div() implementation from asm-parisc/div64.h: * Copyright (C) 1999 Hewlett-Packard Co * Copyright (C) 1999 David Mosberger-Tang <[email protected]> * * * Generic C version of 64bit/32bit division and modulo, with * 64bit result and 32bit remainder. * * The fast case for (n>>32 == 0) is handled inline by do_div(). * * Code generated for this function might be very inefficient * for some CPUs. __div64_32() can be overridden by linking arch-specific * assembly versions such as arch/ppc/lib/div64.S and arch/sh/lib/div64.S. */ #include <linux/module.h> #include <linux/math64.h> /* Not needed on 64bit architectures */ #if BITS_PER_LONG == 32 uint32_t __attribute__((weak)) __div64_32(uint64_t *n, uint32_t base) { uint64_t rem = *n; uint64_t b = base; uint64_t res, d = 1; uint32_t high = rem >> 32; /* Reduce the thing a bit first */ res = 0; if (high >= base) { high /= base; res = (uint64_t) high << 32; rem -= (uint64_t) (high*base) << 32; } while ((int64_t)b > 0 && b < rem) { b = b+b; d = d+d; } do { if (rem >= b) { rem -= b; res += d; } b >>= 1; d >>= 1; } while (d); *n = res; return rem; } EXPORT_SYMBOL(__div64_32); #ifndef div_s64_rem s64 div_s64_rem(s64 dividend, s32 divisor, s32 *remainder) { u64 quotient; if (dividend < 0) { quotient = div_u64_rem(-dividend, abs(divisor), (u32 *)remainder); *remainder = -*remainder; if (divisor > 0) quotient = -quotient; } else { quotient = div_u64_rem(dividend, abs(divisor), (u32 *)remainder); if (divisor < 0) quotient = -quotient; } return quotient; } EXPORT_SYMBOL(div_s64_rem); #endif /** * div64_u64 - unsigned 64bit divide with 64bit divisor * @dividend: 64bit dividend * @divisor: 64bit divisor * * This implementation is a modified version of the algorithm proposed * by the book 'Hacker's Delight'. The original source and full proof * can be found here and is available for use without restriction. * * 'http://www.hackersdelight.org/HDcode/newCode/divDouble.c' */ #ifndef div64_u64 u64 div64_u64(u64 dividend, u64 divisor) { u32 high = divisor >> 32; u64 quot; if (high == 0) { quot = div_u64(dividend, divisor); } else { int n = 1 + fls(high); quot = div_u64(dividend >> n, divisor >> n); if (quot != 0) quot--; if ((dividend - quot * divisor) >= divisor) quot++; } return quot; } EXPORT_SYMBOL(div64_u64); #endif #if defined(CONFIG_SYNO_ARMADA) u64 mod_u64_rem64(u64 dividend, u64 divisor) { if (dividend < divisor) { return dividend; } else if (dividend == divisor) { return (u64)0; } return dividend - (div64_u64(dividend, divisor) * divisor); } EXPORT_SYMBOL(mod_u64_rem64); #endif /** * div64_s64 - signed 64bit divide with 64bit divisor * @dividend: 64bit dividend * @divisor: 64bit divisor */ #ifndef div64_s64 s64 div64_s64(s64 dividend, s64 divisor) { s64 quot, t; quot = div64_u64(abs64(dividend), abs64(divisor)); t = (dividend ^ divisor) >> 63; return (quot ^ t) - t; } EXPORT_SYMBOL(div64_s64); #endif #endif /* BITS_PER_LONG == 32 */ /* * Iterative div/mod for use when dividend is not expected to be much * bigger than divisor. */ u32 iter_div_u64_rem(u64 dividend, u32 divisor, u64 *remainder) { return __iter_div_u64_rem(dividend, divisor, remainder); } EXPORT_SYMBOL(iter_div_u64_rem);
gpl-2.0
jstotero/optimus_chic_kernel
drivers/input/sensor/gp2ap002.c
27707
/* * drivers/input/sensor/gp2ap002.c - Proximity Sensor driver * * Copyright (C) 2009 - 2010 LGE, Inc. * Author: Lee, Kenobi [sungyoung.lee] * Cho, EunYoung [ey.cho] * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <asm/uaccess.h> #include <linux/module.h> #include <linux/input.h> #include <linux/i2c.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/platform_device.h> #include <asm/io.h> #include <linux/delay.h> #include <asm/gpio.h> #include <mach/vreg.h> #include <linux/wakelock.h> #include <mach/msm_i2ckbd.h> #include <linux/spinlock.h> #include <mach/board_lge.h> #define PROXIMITY_DEBUG_PRINT (1) #define PROXIMITY_ERROR_PRINT (1) /* GP2AP002 Debug mask value * usage: echo [mask_value] > /sys/module/gp2ap002/parameters/debug_mask * All : 127 * No msg : 0 * default : 24 */ enum { GP2AP_DEBUG_ERR_CHECK = 1U << 0, GP2AP_DEBUG_USER_ERROR = 1U << 1, GP2AP_DEBUG_FUNC_TRACE = 1U << 2, GP2AP_DEBUG_DEV_STATUS = 1U << 3, GP2AP_DEBUG_DEV_DEBOUNCE = 1U << 4, GP2AP_DEBUG_GEN_INFO = 1U << 5, GP2AP_DEBUG_INTR_INFO = 1U << 6, GP2AP_DEBUG_INTR_DELAY = 1U << 7, }; static unsigned int gp2ap_debug_mask = GP2AP_DEBUG_DEV_STATUS | \ GP2AP_DEBUG_DEV_DEBOUNCE; module_param_named(debug_mask, gp2ap_debug_mask, int, S_IRUGO | S_IWUSR | S_IWGRP); #if defined(PROXIMITY_DEBUG_PRINT) #define PROXD(fmt, args...) \ printk(KERN_INFO "D[%-18s:%5d]" \ fmt, __FUNCTION__, __LINE__, ##args); #else #define PROXD(fmt, args...) {}; #endif #if defined(PROXIMITY_ERROR_PRINT) #define PROXE(fmt, args...) \ printk(KERN_ERR "E[%-18s:%5d]" \ fmt, __FUNCTION__, __LINE__, ##args); #else #define PROXE(fmt, args...) {}; #endif #define GP2AP_NO_INTCLEAR (0) #define GP2AP_INTCLEAR (1 << 7) /* Define GP2AP00200F Internal Registers */ /* ------------------------------------------------------------------------ */ /* ADDRESS SYMBOL DATA Init R/W */ /* D7 D6 D5 D4 D3 D2 D1 D0 */ /* ------------------------------------------------------------------------ */ /* 0 PROX X X X X X X X VO H'00 R */ /* 1 GAIN X X X X LED0 X X X H'00 W */ /* 2 HYS HYSD HYSC1 HYSC0 X HYSF3 HYSF2 HYSF1 HYSF0 H'00 W */ /* 3 CYCLE X X CYCL2 CYCL1 CYCL0 OSC2 X X H'00 W */ /* 4 OPMOD X X X ASD X X VCON SSD H'00 W */ /* 6 CON X X X OCON1 OCON0 X X X H'00 W */ /* ------------------------------------------------------------------------ */ /* VO :Proximity sensing result(0: no detection, 1: detection) */ /* LED0 :Select switch for LED driver's On-registence(0:2x higher, 1:normal)*/ /* HYSD/HYSF :Adjusts the receiver sensitivity */ /* OSC :Select switch internal clocl frequency hoppling(0:effective) */ /* CYCL :Determine the detection cycle(typically 8ms, up to 128x) */ /* SSD :Software Shutdown function(0:shutdown, 1:operating) */ /* VCON :VOUT output method control(0:normal, 1:interrupt) */ /* ASD :Select switch for analog sleep function(0:ineffective, 1:effective)*/ /* OCON :Select switch for enabling/disabling VOUT (00:enable, 11:disable) */ #define GP2AP_REG_PROX (0x00) #define GP2AP_REG_GAIN (0x01) #define GP2AP_REG_HYS (0x02) #define GP2AP_REG_CYCLE (0x03) #define GP2AP_REG_OPMOD (0x04) #define GP2AP_REG_CON (0x06) #define GP2AP_ASD_SHIFT(x) (x << 4) #define PROX_SENSOR_DETECT_N (0) #define PROX_OPMODE_A 0x0 #define PROX_OPMODE_B1 0x1 #define PROX_OPMODE_B2 0x2 /* Declare proximity device structure for GP2AP00200F */ struct proximity_gp2ap_device { struct i2c_client *client; /* i2c client for adapter */ struct input_dev *input_dev; /* input device for android */ struct delayed_work dwork; /* delayed work for bh */ int irq; /* Terminal out irq number */ int vout_gpio; /* Terminal out GPIO pin number */ int vout_level; /* Terminal out GPIO pin level */ int sw_mode; /* Software shutdown function */ int methods; /* Terminal output Methods */ int last_vout; /* Last VO bit value */ int debounce; /* Delayed work schedule time */ u8 cycle; /* Detection Cycle */ u8 asd; /* Analog sleep function */ spinlock_t lock; /* protect resources */ int op_mode; /* operation mode - 0:A, 1:B1, 2:B2 */ u8 reg_backup[7]; /* for on/off */ }; struct detection_cycle { u8 val; unsigned char *resp_time; }; static struct detection_cycle gp2ap_cycle_table[] = { {0x04, "8ms"}, {0x0C, "16ms"}, {0x14, "32ms"}, {0x1C, "64ms"}, {0x24, "128ms"}, {0x2C, "256ms"}, {0x34, "512ms"}, {0x3C, "1024ms"}, }; static struct proximity_gp2ap_device *gp2ap_pdev = NULL; static struct workqueue_struct *proximity_wq; enum gp2ap_dev_mode { PROX_TMODE_NORMAL = 0, PROX_TMODE_INTR, }; enum gp2ap_dev_status { PROX_STAT_SHUTDOWN = 0, PROX_STAT_OPERATING, }; enum gp2ap_input_event { PROX_INPUT_NEAR = 0, PROX_INPUT_FAR, }; struct proxi_timestamp { u64 start; u64 end; u64 result_t; unsigned long rem; char ready; }; static struct proxi_timestamp time_result; /* ---------------------------------------------------------------------------------------- */ /* ---------------------------- PROXIMIY FUNCTION ----------------------------------- */ /* ---------------------------------------------------------------------------------------- */ static s32 prox_i2c_write(u8 addr, u8 value, u8 intclr) { int ret; if (GP2AP_DEBUG_ERR_CHECK & gp2ap_debug_mask) { if (gp2ap_pdev == NULL) { PROXE("gp2ap device is null\n"); return -1; } } ret = i2c_smbus_write_byte_data(gp2ap_pdev->client, addr | intclr, value); if (GP2AP_DEBUG_ERR_CHECK & gp2ap_debug_mask) { if (ret != 0) { PROXE("caddr(0x%x),addr(%u),ret(%d)\n", gp2ap_pdev->client->addr, addr, ret); return ret; } } gp2ap_pdev->reg_backup[addr] = value; if (GP2AP_DEBUG_GEN_INFO & gp2ap_debug_mask) PROXD("addr(%u),val(%u),intclr(%u)\n", addr, value, intclr); return ret; } static s32 prox_i2c_read(u8 addr, u8 intclr) { int ret = 0; if (GP2AP_DEBUG_ERR_CHECK & gp2ap_debug_mask) { if (gp2ap_pdev == NULL) { PROXE("gp2ap device is null\n"); return -1; } } if(addr == 0) { ret = i2c_smbus_read_word_data(gp2ap_pdev->client, addr | intclr); if (GP2AP_DEBUG_ERR_CHECK & gp2ap_debug_mask) { if (ret < 0) { PROXE("caddr(0x%x), intclr(%d)\n", gp2ap_pdev->client->addr, intclr); return -1; } } } else { ret = gp2ap_pdev->reg_backup[addr]; } if (GP2AP_DEBUG_GEN_INFO & gp2ap_debug_mask) PROXD("addr(%u),val(0x%08x),intclr(%u)\n", addr, ret, intclr); return ret; } static int gp2ap_device_initialise(void) { s32 ret = 0; u8 opmod = 0; u8 hys = 0; if (GP2AP_DEBUG_FUNC_TRACE & gp2ap_debug_mask) PROXD("entry\n"); if (GP2AP_DEBUG_ERR_CHECK & gp2ap_debug_mask) { if (gp2ap_pdev == NULL) { PROXE("gp2ap device is null\n"); return -1; } } ret = prox_i2c_write(GP2AP_REG_CON, 0x18, GP2AP_NO_INTCLEAR); if (ret < 0) goto end_device_init; ret = prox_i2c_write(GP2AP_REG_GAIN, 0x08, GP2AP_NO_INTCLEAR); if (ret < 0) goto end_device_init; if(gp2ap_pdev->op_mode == PROX_OPMODE_A) hys = 0xC2; else if(gp2ap_pdev->op_mode == PROX_OPMODE_B1) hys = 0x40; else /* PROX_OPMODE_B2 */ hys = 0x20; ret = prox_i2c_write(GP2AP_REG_HYS, hys, GP2AP_NO_INTCLEAR); if (ret < 0) goto end_device_init; ret = prox_i2c_write(GP2AP_REG_CYCLE, gp2ap_cycle_table[gp2ap_pdev->cycle].val, GP2AP_NO_INTCLEAR); if (ret < 0) goto end_device_init; if (gp2ap_pdev->methods) /* Interrupt mode */ opmod = (u8)(GP2AP_ASD_SHIFT(gp2ap_pdev->asd) | 0x03); else /* Normal mode */ opmod = (u8)(GP2AP_ASD_SHIFT(gp2ap_pdev->asd) | 0x01); ret = prox_i2c_write(GP2AP_REG_OPMOD, opmod, GP2AP_NO_INTCLEAR); if (ret < 0) goto end_device_init; ret = prox_i2c_write(GP2AP_REG_CON, 0x00, GP2AP_NO_INTCLEAR); if (ret < 0) goto end_device_init; if (GP2AP_DEBUG_FUNC_TRACE & gp2ap_debug_mask) PROXD("exit\n"); return ret; end_device_init: PROXE("failed to initailise\n"); return ret; } /* * interrupt service routine */ static irqreturn_t gp2ap_irq_handler(int irq, void *dev_id) { struct proximity_gp2ap_device *pdev = dev_id; unsigned long delay; if (GP2AP_DEBUG_INTR_DELAY & gp2ap_debug_mask) { time_result.ready = 1; time_result.start= 0; time_result.end = 0; time_result.result_t = 0; time_result.rem = 0; time_result.start = cpu_clock(smp_processor_id()); } spin_lock(&pdev->lock); if (GP2AP_DEBUG_INTR_INFO & gp2ap_debug_mask) PROXD("\n"); if (pdev->methods) /* Interrupt mode */ pdev->vout_level = gpio_get_value(pdev->vout_gpio); delay = msecs_to_jiffies(pdev->debounce); queue_delayed_work(proximity_wq, &pdev->dwork, delay); spin_unlock(&pdev->lock); return IRQ_HANDLED; } static void gp2ap_report_event(int state) { int input_state; if (GP2AP_DEBUG_FUNC_TRACE & gp2ap_debug_mask) PROXD("entry\n"); input_state = (state == PROX_SENSOR_DETECT_N) ? PROX_INPUT_FAR : PROX_INPUT_NEAR; input_report_abs(gp2ap_pdev->input_dev, ABS_DISTANCE, input_state); input_sync(gp2ap_pdev->input_dev); if (GP2AP_DEBUG_INTR_DELAY & gp2ap_debug_mask) { if(time_result.ready == 1) { time_result.end = cpu_clock(smp_processor_id()); time_result.result_t = time_result.end -time_result.start; time_result.rem = do_div(time_result.result_t , 1000000000); PROXD("Proximity interrupt BSP delay time = %2lu.%06lu\n", (unsigned long)time_result.result_t, time_result.rem/1000); time_result.ready = 0; } } gp2ap_pdev->last_vout = !input_state; if (GP2AP_DEBUG_DEV_STATUS & gp2ap_debug_mask) (gp2ap_pdev->last_vout) ? printk(KERN_INFO "\nPROX:Near\n") : printk(KERN_INFO "\nPROX:Far\n"); if (GP2AP_DEBUG_FUNC_TRACE & gp2ap_debug_mask) PROXD("exit\n"); } static void gp2ap_work_func(struct work_struct *work) { struct proximity_gp2ap_device *dev = container_of(work, struct proximity_gp2ap_device, dwork.work); struct proximity_platform_data* proxi_pdata = dev->client->dev.platform_data; int vo_data; if (GP2AP_DEBUG_FUNC_TRACE & gp2ap_debug_mask) PROXD("entry\n"); if (dev->methods) { /* Interrupt mode */ /* get VO bit to i2c read */ disable_irq(dev->irq); vo_data = prox_i2c_read(GP2AP_REG_PROX, GP2AP_NO_INTCLEAR); vo_data = (vo_data >> 8) & 0x1; } else { /* Nomal mode*/ if(gpio_get_value(proxi_pdata->irq_num) == 1) /* FAR */ vo_data = PROX_SENSOR_DETECT_N; else vo_data = !PROX_SENSOR_DETECT_N; } /* compare last state and current state */ if (dev->last_vout == vo_data) { if (GP2AP_DEBUG_DEV_DEBOUNCE & gp2ap_debug_mask) PROXD("not change state by debounce\n"); if (dev->methods) { /* Interrupt mode */ goto clear_interrupt; } goto work_func_end; } gp2ap_report_event(vo_data); clear_interrupt: if (dev->methods) { /* Interrupt mode */ if (dev->vout_level == 0) { if(PROX_OPMODE_B1) { (vo_data) ? prox_i2c_write(GP2AP_REG_HYS, 0x20, GP2AP_NO_INTCLEAR) : \ prox_i2c_write(GP2AP_REG_HYS, 0x40, GP2AP_NO_INTCLEAR); } else /* PROX_OPMODE_B2 */ { (vo_data) ? prox_i2c_write(GP2AP_REG_HYS, 0x00, GP2AP_NO_INTCLEAR) : \ prox_i2c_write(GP2AP_REG_HYS, 0x20, GP2AP_NO_INTCLEAR); } prox_i2c_write(GP2AP_REG_CON, 0x18, GP2AP_NO_INTCLEAR); } enable_irq(dev->irq); prox_i2c_write(GP2AP_REG_CON, 0x00, GP2AP_INTCLEAR); } work_func_end: if (GP2AP_DEBUG_FUNC_TRACE & gp2ap_debug_mask) PROXD("exit\n"); return; } static int gp2ap_suspend(struct i2c_client *i2c_dev, pm_message_t state); static int gp2ap_resume(struct i2c_client *i2c_dev); /* ------------------------------------------------------------------------ */ /* -------------------- SYSFS DEVICE FIEL --------------------------- */ /* ------------------------------------------------------------------------ */ static ssize_t gp2ap_status_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct proximity_gp2ap_device *pdev = i2c_get_clientdata(client); return snprintf(buf, PAGE_SIZE, "%d\n", !(pdev->last_vout)); } static ssize_t gp2ap_method_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct proximity_gp2ap_device *pdev = i2c_get_clientdata(client); unsigned char *string; string = (pdev->methods) ? "interrupt" : "normal"; return snprintf(buf, PAGE_SIZE, "%s\n", string); } static ssize_t gp2ap_method_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct i2c_client *client = to_i2c_client(dev); struct proximity_gp2ap_device *pdev = i2c_get_clientdata(client); pm_message_t dummy_state; unsigned char string[10]; int method; dummy_state.event = 0; sscanf(buf, "%s", string); if (!strncmp(string, "normal", 6)) method = 0; else if (!strncmp(string, "interrupt", 6)) method = 1; else { printk(KERN_INFO "Usage: echo [normal | interrupt] > method\n"); printk(KERN_INFO " normal : normal mode\n"); printk(KERN_INFO " interrupt: interrupt mode\n"); return count; } if (pdev->methods != method) { gp2ap_suspend(client, dummy_state); pdev->methods = method; gp2ap_resume(client); (pdev->methods) ? printk(KERN_INFO "interrupt\n") : printk(KERN_INFO "normal\n"); } else { printk(KERN_INFO "sw mode is already %s\n", string); return count; } return count; } static ssize_t gp2ap_cycle_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct proximity_gp2ap_device *pdev = i2c_get_clientdata(client); return snprintf(buf, PAGE_SIZE, "%s\n", gp2ap_cycle_table[pdev->cycle].resp_time); } static ssize_t gp2ap_cycle_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct i2c_client *client = to_i2c_client(dev); struct proximity_gp2ap_device *pdev = i2c_get_clientdata(client); int cycle; sscanf(buf, "%d", &cycle); if ((cycle < 0) || (cycle > ARRAY_SIZE(gp2ap_cycle_table))) { printk(KERN_INFO "Usage: echo [0 ~ %d] > cycle\n", ARRAY_SIZE(gp2ap_cycle_table)); printk(KERN_INFO " 0(8ms),1(16ms),2(32ms),3(64ms),4(128ms)\n"); printk(KERN_INFO " 5(256ms),6(512ms),7(1024ms)\n"); return count; } if (pdev->cycle != cycle) pdev->cycle = cycle; else { printk(KERN_INFO "cycle is already %d\n", pdev->cycle); return count; } disable_irq(pdev->irq); prox_i2c_write(GP2AP_REG_CON, 0x18, GP2AP_NO_INTCLEAR); prox_i2c_write(GP2AP_REG_CYCLE, gp2ap_cycle_table[pdev->cycle].val, GP2AP_NO_INTCLEAR); prox_i2c_write(GP2AP_REG_CON, 0x00, GP2AP_NO_INTCLEAR); enable_irq(pdev->irq); return count; } static ssize_t gp2ap_enable_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct proximity_gp2ap_device *pdev = i2c_get_clientdata(client); return snprintf(buf, PAGE_SIZE, "%d\n", pdev->sw_mode); } static ssize_t gp2ap_enable_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct i2c_client *client = to_i2c_client(dev); struct proximity_gp2ap_device *pdev = i2c_get_clientdata(client); pm_message_t dummy_state; int mode; dummy_state.event = 0; sscanf(buf, "%d", &mode); if ((mode != PROX_STAT_SHUTDOWN) && (mode != PROX_STAT_OPERATING)) { printk(KERN_INFO "Usage: echo [0 | 1] > enable"); printk(KERN_INFO " 0: disable\n"); printk(KERN_INFO " 1: enable\n"); return count; } if (mode == pdev->sw_mode) { printk(KERN_INFO "mode is already %d\n", pdev->sw_mode); return count; } else { if (mode) { gp2ap_resume(client); printk(KERN_INFO "Power On Enable\n"); } else { gp2ap_suspend(client, dummy_state); printk(KERN_INFO "Power Off Disable\n"); } } return count; } static ssize_t gp2ap_debounce_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct proximity_gp2ap_device *pdev = i2c_get_clientdata(client); return snprintf(buf, PAGE_SIZE, "%d ms\n", pdev->debounce); } static ssize_t gp2ap_debounce_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct i2c_client *client = to_i2c_client(dev); struct proximity_gp2ap_device *pdev = i2c_get_clientdata(client); int debounce; sscanf(buf, "%d", &debounce); if (pdev->debounce != debounce) pdev->debounce = debounce; return count; } static ssize_t gp2ap_asd_show(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); struct proximity_gp2ap_device *pdev = i2c_get_clientdata(client); return snprintf(buf, PAGE_SIZE, "%d(0:disable, 1:enable)\n", pdev->asd); } static ssize_t gp2ap_asd_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct i2c_client *client = to_i2c_client(dev); struct proximity_gp2ap_device *pdev = i2c_get_clientdata(client); int asd; u8 opmod; sscanf(buf, "%d", &asd); if ((asd < 0) || (asd > 1)) { printk(KERN_INFO "Usaage: echo [0 | 1] > asd\n"); printk(KERN_INFO " 0: disable\n"); printk(KERN_INFO " 1: enable\n"); return count; } if (pdev->asd != asd) { opmod = (u8)(GP2AP_ASD_SHIFT(asd) | (pdev->methods << 1) | pdev->sw_mode); disable_irq(pdev->irq); prox_i2c_write(GP2AP_REG_CON, 0x18, GP2AP_NO_INTCLEAR); prox_i2c_write(GP2AP_REG_OPMOD, opmod, GP2AP_NO_INTCLEAR); prox_i2c_write(GP2AP_REG_CON, 0x00, GP2AP_NO_INTCLEAR); enable_irq(pdev->irq); pdev->asd = asd; } else printk(KERN_INFO "ASD is already %d\n", pdev->asd); return count; } static struct device_attribute gp2ap_device_attrs[] = { __ATTR(show, S_IRUGO | S_IWUSR, gp2ap_status_show, NULL), __ATTR(method, S_IRUGO | S_IWUSR, gp2ap_method_show, gp2ap_method_store), __ATTR(cycle, S_IRUGO | S_IWUSR, gp2ap_cycle_show, gp2ap_cycle_store), __ATTR(enable, S_IRUGO | S_IWUSR, gp2ap_enable_show, gp2ap_enable_store), __ATTR(debounce, S_IRUGO | S_IWUSR, gp2ap_debounce_show, gp2ap_debounce_store), __ATTR(asd, S_IRUGO | S_IWUSR, gp2ap_asd_show, gp2ap_asd_store), }; /* ------------------------------------------------------------------------ */ /* -------------------- I2C DRIVER --------------------------- */ /* ------------------------------------------------------------------------ */ static int gp2ap_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id) { int ret = 0; int i; struct proximity_platform_data *pdata; pm_message_t dummy_state; if (GP2AP_DEBUG_FUNC_TRACE & gp2ap_debug_mask) PROXD("entry\n"); if (GP2AP_DEBUG_ERR_CHECK & gp2ap_debug_mask) { if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)){ PROXE("it is not support I2C_FUNC_I2C.\n"); return -ENODEV; } } gp2ap_pdev = kzalloc(sizeof(struct proximity_gp2ap_device), GFP_KERNEL); if (GP2AP_DEBUG_ERR_CHECK & gp2ap_debug_mask) { if (gp2ap_pdev == NULL) { PROXE("failed to allocation\n"); return -ENOMEM; } } INIT_DELAYED_WORK(&gp2ap_pdev->dwork, gp2ap_work_func); gp2ap_pdev->client = client; i2c_set_clientdata(gp2ap_pdev->client, gp2ap_pdev); /* allocate input device for transfer proximity event */ gp2ap_pdev->input_dev = input_allocate_device(); if (GP2AP_DEBUG_ERR_CHECK & gp2ap_debug_mask) { if (NULL == gp2ap_pdev->input_dev) { dev_err(&client->dev, "failed to allocation\n"); goto err_input_allocate_device; } } /* initialise input device for GP2AP00200F */ gp2ap_pdev->input_dev->name = "proximity"; gp2ap_pdev->input_dev->phys = "proximity/input2"; set_bit(EV_SYN, gp2ap_pdev->input_dev->evbit); //for sync set_bit(EV_ABS, gp2ap_pdev->input_dev->evbit); input_set_abs_params(gp2ap_pdev->input_dev, ABS_DISTANCE, 0, 1, 0, 0); /* register input device for GP2AP00200F */ ret = input_register_device(gp2ap_pdev->input_dev); if (GP2AP_DEBUG_ERR_CHECK & gp2ap_debug_mask) { if (ret < 0) { PROXE("failed to register input\n"); goto err_input_register_device; } } pdata = gp2ap_pdev->client->dev.platform_data; if (GP2AP_DEBUG_ERR_CHECK & gp2ap_debug_mask) { if (pdata == NULL) { PROXE("failed to get platform data\n"); goto err_gp2ap_initialise; } } /* client->irq is gpio number for interrupt */ gp2ap_pdev->vout_gpio = pdata->irq_num; gp2ap_pdev->irq = gpio_to_irq(pdata->irq_num); gp2ap_pdev->op_mode = pdata->operation_mode; gp2ap_pdev->methods = pdata->methods; gp2ap_pdev->last_vout = -1; gp2ap_pdev->debounce = pdata->debounce; gp2ap_pdev->asd = 0; /* disable */ gp2ap_pdev->cycle = pdata->cycle; /* 32ms */ spin_lock_init(&gp2ap_pdev->lock); /* turn on power supply for GP2AP00200F */ pdata->power(1); udelay(60); /* set up registers according to VOUT output mode */ ret = gp2ap_device_initialise(); if (GP2AP_DEBUG_ERR_CHECK & gp2ap_debug_mask) { if (ret < 0) { PROXE("failed to init\n"); goto err_gp2ap_initialise; } } if (GP2AP_DEBUG_GEN_INFO & gp2ap_debug_mask) PROXD("vout gpio(%d), irq(%d)\n", gp2ap_pdev->vout_gpio, gp2ap_pdev->irq); /* register interrupt handler */ ret = request_irq(gp2ap_pdev->irq, gp2ap_irq_handler, IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING, "proximity_irq", gp2ap_pdev); if (GP2AP_DEBUG_ERR_CHECK & gp2ap_debug_mask) { if (ret < 0) { PROXE("failed to register irq\n"); goto err_irq_request; } } gp2ap_pdev->sw_mode = PROX_STAT_OPERATING; if (GP2AP_DEBUG_GEN_INFO & gp2ap_debug_mask) PROXD("i2c client addr(0x%x)\n", gp2ap_pdev->client->addr); ret = set_irq_wake(gp2ap_pdev->irq, 1); if (ret) set_irq_wake(gp2ap_pdev->irq, 0); /* create sysfs attribute files */ for (i = 0; i < ARRAY_SIZE(gp2ap_device_attrs); i++) { ret = device_create_file(&client->dev, &gp2ap_device_attrs[i]); if (ret) { goto err_device_create_file; } } dummy_state.event = 0; gp2ap_suspend(gp2ap_pdev->client, dummy_state); if (GP2AP_DEBUG_FUNC_TRACE & gp2ap_debug_mask) PROXD("exit\n"); return 0; err_device_create_file: while(--i >= 0) device_remove_file(&client->dev, &gp2ap_device_attrs[i]); err_irq_request: input_unregister_device(gp2ap_pdev->input_dev); err_gp2ap_initialise: err_input_register_device: input_free_device(gp2ap_pdev->input_dev); err_input_allocate_device: kfree(gp2ap_pdev); return ret; } static int gp2ap_i2c_remove(struct i2c_client *client) { struct proximity_gp2ap_device *pdev = i2c_get_clientdata(client); int i; if (GP2AP_DEBUG_FUNC_TRACE & gp2ap_debug_mask) PROXD("entry\n"); set_irq_wake(gp2ap_pdev->irq, 0); free_irq(pdev->irq, NULL); input_unregister_device(pdev->input_dev); input_free_device(pdev->input_dev); kfree(gp2ap_pdev); for (i = 0; i < ARRAY_SIZE(gp2ap_device_attrs); i++) device_remove_file(&client->dev, &gp2ap_device_attrs[i]); if (GP2AP_DEBUG_FUNC_TRACE & gp2ap_debug_mask) PROXD("exit\n"); return 0; } static int gp2ap_suspend(struct i2c_client *i2c_dev, pm_message_t state) { struct proximity_gp2ap_device *pdev = i2c_get_clientdata(i2c_dev); struct proximity_platform_data *pdata = pdev->client->dev.platform_data; int ret; if (GP2AP_DEBUG_FUNC_TRACE & gp2ap_debug_mask) PROXD("entry\n"); /* if device is not operating, return */ if (!pdev->sw_mode) return 0; disable_irq(pdev->irq); /* shutdown & analog shutdown */ if (pdev->methods) /* Interrnupt mode */ ret = prox_i2c_write(GP2AP_REG_OPMOD, (GP2AP_ASD_SHIFT(1) | 0x02), GP2AP_NO_INTCLEAR); else /* Normal mode */ ret = prox_i2c_write(GP2AP_REG_OPMOD, (GP2AP_ASD_SHIFT(1) | 0x00), GP2AP_NO_INTCLEAR); if (GP2AP_DEBUG_ERR_CHECK & gp2ap_debug_mask) { if (ret < 0) { PROXE("failed to write\n"); } } pdev->sw_mode = PROX_STAT_SHUTDOWN; cancel_delayed_work_sync(&pdev->dwork); flush_workqueue(proximity_wq); /* turn off power supply */ pdata->power(0); set_irq_wake(pdev->irq, 0); if (GP2AP_DEBUG_FUNC_TRACE & gp2ap_debug_mask) PROXD("exit\n"); return 0; } static void gp2ap_report_init_staus(struct proximity_gp2ap_device *pdev) { int vo_data; msleep(100); vo_data = prox_i2c_read(GP2AP_REG_PROX, GP2AP_NO_INTCLEAR); vo_data = (vo_data >> 8) & 0x1; gp2ap_report_event(vo_data); } static int gp2ap_resume(struct i2c_client *i2c_dev) { struct proximity_gp2ap_device *pdev = i2c_get_clientdata(i2c_dev); struct proximity_platform_data *pdata = pdev->client->dev.platform_data; int ret; int addr; if (GP2AP_DEBUG_FUNC_TRACE & gp2ap_debug_mask) PROXD("entry\n"); if (pdev->sw_mode) return 0; /* turn on power supply */ pdata->power(1); pdev->last_vout = -1; udelay(60); /* disable shutdown value */ if (pdev->methods) /* Interrnupt mode */ pdev->reg_backup[GP2AP_REG_OPMOD] = 0x03; else /* Normal mode */ pdev->reg_backup[GP2AP_REG_OPMOD] = 0x01; for(addr = 0; addr < 6; addr++) { if(pdev->reg_backup[addr] != 0) { ret = prox_i2c_write(addr, pdev->reg_backup[addr], GP2AP_NO_INTCLEAR); if (ret < 0) { PROXE("%s failed to write - addr:%d\n", __func__, addr); pdata->power(0); return -1; } } else continue; } /* garbage data for first call */ gp2ap_report_event(PROX_SENSOR_DETECT_N); pdev->last_vout = -1; enable_irq(pdev->irq); /* safity code for H/W timming */ if (pdev->methods) prox_i2c_write(GP2AP_REG_CON, 0x00, GP2AP_INTCLEAR); /* report proxi state because v_out is high after turn on */ gp2ap_report_init_staus(pdev); pdev->sw_mode = PROX_STAT_OPERATING; ret = set_irq_wake(pdev->irq, 1); if (ret) set_irq_wake(pdev->irq, 0); if (GP2AP_DEBUG_FUNC_TRACE & gp2ap_debug_mask) PROXD("exit\n"); return 0; } static const struct i2c_device_id gp2ap_i2c_ids[] = { {"proximity_gp2ap", 0 }, { }, }; MODULE_DEVICE_TABLE(i2c, prox_ids); static struct i2c_driver gp2ap_i2c_driver = { .probe = gp2ap_i2c_probe, .remove = gp2ap_i2c_remove, .id_table = gp2ap_i2c_ids, .driver = { .name = "proximity_gp2ap", .owner = THIS_MODULE, }, }; static void __exit gp2ap_i2c_exit(void) { i2c_del_driver(&gp2ap_i2c_driver); if (proximity_wq) destroy_workqueue(proximity_wq); } static int __init gp2ap_i2c_init(void) { int ret; if (GP2AP_DEBUG_FUNC_TRACE & gp2ap_debug_mask) PROXD("entry\n"); proximity_wq = create_singlethread_workqueue("proximity_wq"); if (GP2AP_DEBUG_ERR_CHECK & gp2ap_debug_mask) { if (!proximity_wq) { PROXE("failed to create singlethread workqueue\n"); return -ENOMEM; } } ret = i2c_add_driver(&gp2ap_i2c_driver); if (GP2AP_DEBUG_ERR_CHECK & gp2ap_debug_mask) { if (ret < 0) { PROXE("failed to i2c_add_driver \n"); destroy_workqueue(proximity_wq); return ret; } } if (GP2AP_DEBUG_FUNC_TRACE & gp2ap_debug_mask) PROXD("entry\n"); return 0; } late_initcall(gp2ap_i2c_init); module_exit(gp2ap_i2c_exit); MODULE_DESCRIPTION("gp2ap00200f driver"); MODULE_LICENSE("GPL");
gpl-2.0
home4j/arsenal4j
script/js/webpack/demo05/run-server.ps1
38
webpack-dev-server --progress --colors
gpl-2.0
renshuki/dfp-manager
vendor/googleads/googleads-php-lib/src/Google/AdsApi/AdWords/v201702/mcm/CurrencyCodeErrorReason.php
216
<?php namespace Google\AdsApi\AdWords\v201702\mcm; /** * This file was generated from WSDL. DO NOT EDIT. */ class CurrencyCodeErrorReason { const UNSUPPORTED_CURRENCY_CODE = 'UNSUPPORTED_CURRENCY_CODE'; }
gpl-2.0
uQr/FrameworkWithDesingPatterns
DAI.Rule.Validation.Definition/Default.aspx.designer.cs
2704
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace DAI.Rule.Validation.Definition { public partial class Default { /// <summary> /// form1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; /// <summary> /// dominObjList control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList dominObjList; /// <summary> /// fieldList control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList fieldList; /// <summary> /// validationRule control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList validationRule; /// <summary> /// errTxt control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox errTxt; /// <summary> /// Save control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button Save; /// <summary> /// errorMsg control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Literal errorMsg; } }
gpl-2.0
photom/simon
plugins/Commands/Template/dialogcommandmanager.cpp
3878
/* * Copyright (C) 2009 Peter Grasch <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * or (at your option) any later version, as published by the Free * Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "dialogcommandmanager.h" #include "dialogconfiguration.h" #include "dialogcommand.h" #include "createdialogcommandwidget.h" #include <eventsimulation/eventhandler.h> #include <simonactions/actionmanager.h> #include <KLocalizedString> #include <KAction> K_PLUGIN_FACTORY( DialogCommandPluginFactory, registerPlugin< DialogCommandManager >(); ) K_EXPORT_PLUGIN( DialogCommandPluginFactory("simondialogcommand") ) DialogCommandManager::DialogCommandManager(QObject* parent, const QVariantList& args) : CommandManager((Scenario*) parent, args), GreedyReceiver(this), dialogWidget(new QWidget(0, Qt::Dialog|Qt::WindowStaysOnTopHint)), activateAction(new KAction(this)) { setFont(ActionManager::getInstance()->pluginBaseFont()); dialogWidget->setWindowIcon(KIcon("im-user")); ui.setupUi(dialogWidget); dialogWidget->hide(); activateAction->setText(i18n("Activate Dialog")); activateAction->setIcon(KIcon("input-dialog")); connect(activateAction, SIGNAL(triggered(bool)), this, SLOT(activate())); guiActions<<activateAction; } bool DialogCommandManager::shouldAcceptCommand(Command *command) { return (dynamic_cast<DialogCommand*>(command) != 0); } void DialogCommandManager::setFont(const QFont& font) { dialogWidget->setFont(font); } void DialogCommandManager::activate() { dialogWidget->show(); startGreedy(); } void DialogCommandManager::deregister() { stopGreedy(); } const QString DialogCommandManager::iconSrc() const { return "im-user"; } const QString DialogCommandManager::name() const { return i18n("Dialog"); } bool DialogCommandManager::greedyTrigger(const QString& inputText) { return trigger(inputText); } DialogConfiguration* DialogCommandManager::getDialogConfiguration() { return static_cast<DialogConfiguration*>(getConfigurationPage()); } bool DialogCommandManager::deSerializeConfig(const QDomElement& elem) { //Connect to Slots connect(ui.pbOk, SIGNAL(clicked()), dialogWidget, SLOT(hide())); connect(ui.pbOk, SIGNAL(clicked()), this, SLOT(deregister())); if (!config) config->deleteLater(); config = new DialogConfiguration(this, parentScenario); config->deSerialize(elem); bool succ = true; succ &= installInterfaceCommand(this, "activate", i18n("Dialog"), iconSrc(), i18n("Starts dialog"), true /* announce */, true /* show icon */, SimonCommand::DefaultState /* consider this command when in this state */, SimonCommand::GreedyState, /* if executed switch to this state */ QString() /* take default visible id from action name */, "startDialog" /* id */); succ &= installInterfaceCommand(ui.pbOk, "click", i18nc("Close the dialog", "OK"), "dialog-ok", i18n("Hides the dialog"), false, true, SimonCommand::GreedyState, SimonCommand::DefaultState); return succ; } CreateCommandWidget* DialogCommandManager::getCreateCommandWidget(QWidget *parent) { return new CreateDialogCommandWidget(this, parent); } DialogCommandManager::~DialogCommandManager() { dialogWidget->deleteLater(); activateAction->deleteLater(); }
gpl-2.0
Fabrice-li/e-venement
apps/statistics/modules/statistics/templates/controlSuccess.php
785
<?php include_partial('stats_header', array('form' => $form, 'title' => $title)); ?> <?php if ( $sf_user->hasCredential('stats-control') ): ?> <?php include_partial('global/chart_jqplot', array( 'id' => 'control', 'data' => url_for('statistics/controlJson?type=' . $type), 'width' => '1000', 'label' => __('Ticket controls') )) ?> <?php endif ?> </div> <?php use_javascript('/js/jqplot/plugins/jqplot.barRenderer.js') ?> <?php use_javascript('/js/jqplot/plugins/jqplot.cursor.js') ?> <?php use_javascript('/js/jqplot/plugins/jqplot.canvasAxisTickRenderer.js') ?> <?php use_javascript('/js/jqplot/plugins/jqplot.canvasTextRenderer.js') ?> <?php use_javascript('statistics-jqplot') ?> <?php use_javascript('statistics-control') ?>
gpl-2.0
enslyon/ensl
modules/jsonapi/src/Normalizer/Value/ConfigFieldItemNormalizerValue.php
632
<?php namespace Drupal\jsonapi\Normalizer\Value; /** * Helps normalize config entity "fields" in compliance with the JSON API spec. * * @internal */ class ConfigFieldItemNormalizerValue extends FieldItemNormalizerValue { /** * {@inheritdoc} * * @var mixed */ protected $raw; /** * Instantiate a ConfigFieldItemNormalizerValue object. * * @param mixed $values * The normalized result. */ public function __construct($values) { $this->raw = $values; } /** * {@inheritdoc} */ public function rasterizeValue() { return $this->rasterizeValueRecursive($this->raw); } }
gpl-2.0
01org/Igvtg-kernel
drivers/gpu/drm/exynos/exynos_drm_drv.c
18672
/* * Copyright (c) 2011 Samsung Electronics Co., Ltd. * Authors: * Inki Dae <[email protected]> * Joonyoung Shim <[email protected]> * Seung-Woo Kim <[email protected]> * * 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/pm_runtime.h> #include <drm/drmP.h> #include <drm/drm_crtc_helper.h> #include <linux/component.h> #include <drm/exynos_drm.h> #include "exynos_drm_drv.h" #include "exynos_drm_crtc.h" #include "exynos_drm_encoder.h" #include "exynos_drm_fbdev.h" #include "exynos_drm_fb.h" #include "exynos_drm_gem.h" #include "exynos_drm_plane.h" #include "exynos_drm_vidi.h" #include "exynos_drm_dmabuf.h" #include "exynos_drm_g2d.h" #include "exynos_drm_ipp.h" #include "exynos_drm_iommu.h" #define DRIVER_NAME "exynos" #define DRIVER_DESC "Samsung SoC DRM" #define DRIVER_DATE "20110530" #define DRIVER_MAJOR 1 #define DRIVER_MINOR 0 static struct platform_device *exynos_drm_pdev; static DEFINE_MUTEX(drm_component_lock); static LIST_HEAD(drm_component_list); struct component_dev { struct list_head list; struct device *crtc_dev; struct device *conn_dev; enum exynos_drm_output_type out_type; unsigned int dev_type_flag; }; static int exynos_drm_load(struct drm_device *dev, unsigned long flags) { struct exynos_drm_private *private; int ret; int nr; private = kzalloc(sizeof(struct exynos_drm_private), GFP_KERNEL); if (!private) return -ENOMEM; INIT_LIST_HEAD(&private->pageflip_event_list); dev_set_drvdata(dev->dev, dev); dev->dev_private = (void *)private; /* * create mapping to manage iommu table and set a pointer to iommu * mapping structure to iommu_mapping of private data. * also this iommu_mapping can be used to check if iommu is supported * or not. */ ret = drm_create_iommu_mapping(dev); if (ret < 0) { DRM_ERROR("failed to create iommu mapping.\n"); goto err_free_private; } drm_mode_config_init(dev); exynos_drm_mode_config_init(dev); for (nr = 0; nr < MAX_PLANE; nr++) { struct drm_plane *plane; unsigned long possible_crtcs = (1 << MAX_CRTC) - 1; plane = exynos_plane_init(dev, possible_crtcs, DRM_PLANE_TYPE_OVERLAY); if (!IS_ERR(plane)) continue; ret = PTR_ERR(plane); goto err_mode_config_cleanup; } /* setup possible_clones. */ exynos_drm_encoder_setup(dev); platform_set_drvdata(dev->platformdev, dev); /* Try to bind all sub drivers. */ ret = component_bind_all(dev->dev, dev); if (ret) goto err_mode_config_cleanup; ret = drm_vblank_init(dev, dev->mode_config.num_crtc); if (ret) goto err_unbind_all; /* Probe non kms sub drivers and virtual display driver. */ ret = exynos_drm_device_subdrv_probe(dev); if (ret) goto err_cleanup_vblank; /* * enable drm irq mode. * - with irq_enabled = true, we can use the vblank feature. * * P.S. note that we wouldn't use drm irq handler but * just specific driver own one instead because * drm framework supports only one irq handler. */ dev->irq_enabled = true; /* * with vblank_disable_allowed = true, vblank interrupt will be disabled * by drm timer once a current process gives up ownership of * vblank event.(after drm_vblank_put function is called) */ dev->vblank_disable_allowed = true; /* init kms poll for handling hpd */ drm_kms_helper_poll_init(dev); /* force connectors detection */ drm_helper_hpd_irq_event(dev); return 0; err_cleanup_vblank: drm_vblank_cleanup(dev); err_unbind_all: component_unbind_all(dev->dev, dev); err_mode_config_cleanup: drm_mode_config_cleanup(dev); drm_release_iommu_mapping(dev); err_free_private: kfree(private); return ret; } static int exynos_drm_unload(struct drm_device *dev) { exynos_drm_device_subdrv_remove(dev); exynos_drm_fbdev_fini(dev); drm_kms_helper_poll_fini(dev); drm_vblank_cleanup(dev); component_unbind_all(dev->dev, dev); drm_mode_config_cleanup(dev); drm_release_iommu_mapping(dev); kfree(dev->dev_private); dev->dev_private = NULL; return 0; } static int exynos_drm_suspend(struct drm_device *dev, pm_message_t state) { struct drm_connector *connector; drm_modeset_lock_all(dev); list_for_each_entry(connector, &dev->mode_config.connector_list, head) { int old_dpms = connector->dpms; if (connector->funcs->dpms) connector->funcs->dpms(connector, DRM_MODE_DPMS_OFF); /* Set the old mode back to the connector for resume */ connector->dpms = old_dpms; } drm_modeset_unlock_all(dev); return 0; } static int exynos_drm_resume(struct drm_device *dev) { struct drm_connector *connector; drm_modeset_lock_all(dev); list_for_each_entry(connector, &dev->mode_config.connector_list, head) { if (connector->funcs->dpms) { int dpms = connector->dpms; connector->dpms = DRM_MODE_DPMS_OFF; connector->funcs->dpms(connector, dpms); } } drm_modeset_unlock_all(dev); return 0; } static int exynos_drm_open(struct drm_device *dev, struct drm_file *file) { struct drm_exynos_file_private *file_priv; int ret; file_priv = kzalloc(sizeof(*file_priv), GFP_KERNEL); if (!file_priv) return -ENOMEM; file->driver_priv = file_priv; ret = exynos_drm_subdrv_open(dev, file); if (ret) goto err_file_priv_free; return ret; err_file_priv_free: kfree(file_priv); file->driver_priv = NULL; return ret; } static void exynos_drm_preclose(struct drm_device *dev, struct drm_file *file) { exynos_drm_subdrv_close(dev, file); } static void exynos_drm_postclose(struct drm_device *dev, struct drm_file *file) { struct exynos_drm_private *private = dev->dev_private; struct drm_pending_vblank_event *v, *vt; struct drm_pending_event *e, *et; unsigned long flags; if (!file->driver_priv) return; /* Release all events not unhandled by page flip handler. */ spin_lock_irqsave(&dev->event_lock, flags); list_for_each_entry_safe(v, vt, &private->pageflip_event_list, base.link) { if (v->base.file_priv == file) { list_del(&v->base.link); drm_vblank_put(dev, v->pipe); v->base.destroy(&v->base); } } /* Release all events handled by page flip handler but not freed. */ list_for_each_entry_safe(e, et, &file->event_list, link) { list_del(&e->link); e->destroy(e); } spin_unlock_irqrestore(&dev->event_lock, flags); kfree(file->driver_priv); file->driver_priv = NULL; } static void exynos_drm_lastclose(struct drm_device *dev) { exynos_drm_fbdev_restore_mode(dev); } static const struct vm_operations_struct exynos_drm_gem_vm_ops = { .fault = exynos_drm_gem_fault, .open = drm_gem_vm_open, .close = drm_gem_vm_close, }; static const struct drm_ioctl_desc exynos_ioctls[] = { DRM_IOCTL_DEF_DRV(EXYNOS_GEM_CREATE, exynos_drm_gem_create_ioctl, DRM_UNLOCKED | DRM_AUTH), DRM_IOCTL_DEF_DRV(EXYNOS_GEM_GET, exynos_drm_gem_get_ioctl, DRM_UNLOCKED), DRM_IOCTL_DEF_DRV(EXYNOS_VIDI_CONNECTION, vidi_connection_ioctl, DRM_UNLOCKED | DRM_AUTH), DRM_IOCTL_DEF_DRV(EXYNOS_G2D_GET_VER, exynos_g2d_get_ver_ioctl, DRM_UNLOCKED | DRM_AUTH), DRM_IOCTL_DEF_DRV(EXYNOS_G2D_SET_CMDLIST, exynos_g2d_set_cmdlist_ioctl, DRM_UNLOCKED | DRM_AUTH), DRM_IOCTL_DEF_DRV(EXYNOS_G2D_EXEC, exynos_g2d_exec_ioctl, DRM_UNLOCKED | DRM_AUTH), DRM_IOCTL_DEF_DRV(EXYNOS_IPP_GET_PROPERTY, exynos_drm_ipp_get_property, DRM_UNLOCKED | DRM_AUTH), DRM_IOCTL_DEF_DRV(EXYNOS_IPP_SET_PROPERTY, exynos_drm_ipp_set_property, DRM_UNLOCKED | DRM_AUTH), DRM_IOCTL_DEF_DRV(EXYNOS_IPP_QUEUE_BUF, exynos_drm_ipp_queue_buf, DRM_UNLOCKED | DRM_AUTH), DRM_IOCTL_DEF_DRV(EXYNOS_IPP_CMD_CTRL, exynos_drm_ipp_cmd_ctrl, DRM_UNLOCKED | DRM_AUTH), }; static const struct file_operations exynos_drm_driver_fops = { .owner = THIS_MODULE, .open = drm_open, .mmap = exynos_drm_gem_mmap, .poll = drm_poll, .read = drm_read, .unlocked_ioctl = drm_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = drm_compat_ioctl, #endif .release = drm_release, }; static struct drm_driver exynos_drm_driver = { .driver_features = DRIVER_MODESET | DRIVER_GEM | DRIVER_PRIME, .load = exynos_drm_load, .unload = exynos_drm_unload, .suspend = exynos_drm_suspend, .resume = exynos_drm_resume, .open = exynos_drm_open, .preclose = exynos_drm_preclose, .lastclose = exynos_drm_lastclose, .postclose = exynos_drm_postclose, .set_busid = drm_platform_set_busid, .get_vblank_counter = drm_vblank_count, .enable_vblank = exynos_drm_crtc_enable_vblank, .disable_vblank = exynos_drm_crtc_disable_vblank, .gem_free_object = exynos_drm_gem_free_object, .gem_vm_ops = &exynos_drm_gem_vm_ops, .dumb_create = exynos_drm_gem_dumb_create, .dumb_map_offset = exynos_drm_gem_dumb_map_offset, .dumb_destroy = drm_gem_dumb_destroy, .prime_handle_to_fd = drm_gem_prime_handle_to_fd, .prime_fd_to_handle = drm_gem_prime_fd_to_handle, .gem_prime_export = exynos_dmabuf_prime_export, .gem_prime_import = exynos_dmabuf_prime_import, .ioctls = exynos_ioctls, .num_ioctls = ARRAY_SIZE(exynos_ioctls), .fops = &exynos_drm_driver_fops, .name = DRIVER_NAME, .desc = DRIVER_DESC, .date = DRIVER_DATE, .major = DRIVER_MAJOR, .minor = DRIVER_MINOR, }; #ifdef CONFIG_PM_SLEEP static int exynos_drm_sys_suspend(struct device *dev) { struct drm_device *drm_dev = dev_get_drvdata(dev); pm_message_t message; if (pm_runtime_suspended(dev) || !drm_dev) return 0; message.event = PM_EVENT_SUSPEND; return exynos_drm_suspend(drm_dev, message); } static int exynos_drm_sys_resume(struct device *dev) { struct drm_device *drm_dev = dev_get_drvdata(dev); if (pm_runtime_suspended(dev) || !drm_dev) return 0; return exynos_drm_resume(drm_dev); } #endif static const struct dev_pm_ops exynos_drm_pm_ops = { SET_SYSTEM_SLEEP_PM_OPS(exynos_drm_sys_suspend, exynos_drm_sys_resume) }; int exynos_drm_component_add(struct device *dev, enum exynos_drm_device_type dev_type, enum exynos_drm_output_type out_type) { struct component_dev *cdev; if (dev_type != EXYNOS_DEVICE_TYPE_CRTC && dev_type != EXYNOS_DEVICE_TYPE_CONNECTOR) { DRM_ERROR("invalid device type.\n"); return -EINVAL; } mutex_lock(&drm_component_lock); /* * Make sure to check if there is a component which has two device * objects, for connector and for encoder/connector. * It should make sure that crtc and encoder/connector drivers are * ready before exynos drm core binds them. */ list_for_each_entry(cdev, &drm_component_list, list) { if (cdev->out_type == out_type) { /* * If crtc and encoder/connector device objects are * added already just return. */ if (cdev->dev_type_flag == (EXYNOS_DEVICE_TYPE_CRTC | EXYNOS_DEVICE_TYPE_CONNECTOR)) { mutex_unlock(&drm_component_lock); return 0; } if (dev_type == EXYNOS_DEVICE_TYPE_CRTC) { cdev->crtc_dev = dev; cdev->dev_type_flag |= dev_type; } if (dev_type == EXYNOS_DEVICE_TYPE_CONNECTOR) { cdev->conn_dev = dev; cdev->dev_type_flag |= dev_type; } mutex_unlock(&drm_component_lock); return 0; } } mutex_unlock(&drm_component_lock); cdev = kzalloc(sizeof(*cdev), GFP_KERNEL); if (!cdev) return -ENOMEM; if (dev_type == EXYNOS_DEVICE_TYPE_CRTC) cdev->crtc_dev = dev; if (dev_type == EXYNOS_DEVICE_TYPE_CONNECTOR) cdev->conn_dev = dev; cdev->out_type = out_type; cdev->dev_type_flag = dev_type; mutex_lock(&drm_component_lock); list_add_tail(&cdev->list, &drm_component_list); mutex_unlock(&drm_component_lock); return 0; } void exynos_drm_component_del(struct device *dev, enum exynos_drm_device_type dev_type) { struct component_dev *cdev, *next; mutex_lock(&drm_component_lock); list_for_each_entry_safe(cdev, next, &drm_component_list, list) { if (dev_type == EXYNOS_DEVICE_TYPE_CRTC) { if (cdev->crtc_dev == dev) { cdev->crtc_dev = NULL; cdev->dev_type_flag &= ~dev_type; } } if (dev_type == EXYNOS_DEVICE_TYPE_CONNECTOR) { if (cdev->conn_dev == dev) { cdev->conn_dev = NULL; cdev->dev_type_flag &= ~dev_type; } } /* * Release cdev object only in case that both of crtc and * encoder/connector device objects are NULL. */ if (!cdev->crtc_dev && !cdev->conn_dev) { list_del(&cdev->list); kfree(cdev); } } mutex_unlock(&drm_component_lock); } static int compare_dev(struct device *dev, void *data) { return dev == (struct device *)data; } static struct component_match *exynos_drm_match_add(struct device *dev) { struct component_match *match = NULL; struct component_dev *cdev; unsigned int attach_cnt = 0; mutex_lock(&drm_component_lock); /* Do not retry to probe if there is no any kms driver regitered. */ if (list_empty(&drm_component_list)) { mutex_unlock(&drm_component_lock); return ERR_PTR(-ENODEV); } list_for_each_entry(cdev, &drm_component_list, list) { /* * Add components to master only in case that crtc and * encoder/connector device objects exist. */ if (!cdev->crtc_dev || !cdev->conn_dev) continue; attach_cnt++; mutex_unlock(&drm_component_lock); /* * fimd and dpi modules have same device object so add * only crtc device object in this case. */ if (cdev->crtc_dev == cdev->conn_dev) { component_match_add(dev, &match, compare_dev, cdev->crtc_dev); goto out_lock; } /* * Do not chage below call order. * crtc device first should be added to master because * connector/encoder need pipe number of crtc when they * are created. */ component_match_add(dev, &match, compare_dev, cdev->crtc_dev); component_match_add(dev, &match, compare_dev, cdev->conn_dev); out_lock: mutex_lock(&drm_component_lock); } mutex_unlock(&drm_component_lock); return attach_cnt ? match : ERR_PTR(-EPROBE_DEFER); } static int exynos_drm_bind(struct device *dev) { return drm_platform_init(&exynos_drm_driver, to_platform_device(dev)); } static void exynos_drm_unbind(struct device *dev) { drm_put_dev(dev_get_drvdata(dev)); } static const struct component_master_ops exynos_drm_ops = { .bind = exynos_drm_bind, .unbind = exynos_drm_unbind, }; static struct platform_driver *const exynos_drm_kms_drivers[] = { #ifdef CONFIG_DRM_EXYNOS_FIMD &fimd_driver, #endif #ifdef CONFIG_DRM_EXYNOS_DP &dp_driver, #endif #ifdef CONFIG_DRM_EXYNOS_DSI &dsi_driver, #endif #ifdef CONFIG_DRM_EXYNOS_HDMI &mixer_driver, &hdmi_driver, #endif }; static struct platform_driver *const exynos_drm_non_kms_drivers[] = { #ifdef CONFIG_DRM_EXYNOS_G2D &g2d_driver, #endif #ifdef CONFIG_DRM_EXYNOS_FIMC &fimc_driver, #endif #ifdef CONFIG_DRM_EXYNOS_ROTATOR &rotator_driver, #endif #ifdef CONFIG_DRM_EXYNOS_GSC &gsc_driver, #endif #ifdef CONFIG_DRM_EXYNOS_IPP &ipp_driver, #endif }; static int exynos_drm_platform_probe(struct platform_device *pdev) { struct component_match *match; pdev->dev.coherent_dma_mask = DMA_BIT_MASK(32); exynos_drm_driver.num_ioctls = ARRAY_SIZE(exynos_ioctls); match = exynos_drm_match_add(&pdev->dev); if (IS_ERR(match)) { return PTR_ERR(match); } return component_master_add_with_match(&pdev->dev, &exynos_drm_ops, match); } static int exynos_drm_platform_remove(struct platform_device *pdev) { component_master_del(&pdev->dev, &exynos_drm_ops); return 0; } static const char * const strings[] = { "samsung,exynos3", "samsung,exynos4", "samsung,exynos5", }; static struct platform_driver exynos_drm_platform_driver = { .probe = exynos_drm_platform_probe, .remove = exynos_drm_platform_remove, .driver = { .owner = THIS_MODULE, .name = "exynos-drm", .pm = &exynos_drm_pm_ops, }, }; static int exynos_drm_init(void) { bool is_exynos = false; int ret, i, j; /* * Register device object only in case of Exynos SoC. * * Below codes resolves temporarily infinite loop issue incurred * by Exynos drm driver when using multi-platform kernel. * So these codes will be replaced with more generic way later. */ for (i = 0; i < ARRAY_SIZE(strings); i++) { if (of_machine_is_compatible(strings[i])) { is_exynos = true; break; } } if (!is_exynos) return -ENODEV; /* * Register device object only in case of Exynos SoC. * * Below codes resolves temporarily infinite loop issue incurred * by Exynos drm driver when using multi-platform kernel. * So these codes will be replaced with more generic way later. */ if (!of_machine_is_compatible("samsung,exynos3") && !of_machine_is_compatible("samsung,exynos4") && !of_machine_is_compatible("samsung,exynos5")) return -ENODEV; exynos_drm_pdev = platform_device_register_simple("exynos-drm", -1, NULL, 0); if (IS_ERR(exynos_drm_pdev)) return PTR_ERR(exynos_drm_pdev); ret = exynos_drm_probe_vidi(); if (ret < 0) goto err_unregister_pd; for (i = 0; i < ARRAY_SIZE(exynos_drm_kms_drivers); ++i) { ret = platform_driver_register(exynos_drm_kms_drivers[i]); if (ret < 0) goto err_unregister_kms_drivers; } for (j = 0; j < ARRAY_SIZE(exynos_drm_non_kms_drivers); ++j) { ret = platform_driver_register(exynos_drm_non_kms_drivers[j]); if (ret < 0) goto err_unregister_non_kms_drivers; } #ifdef CONFIG_DRM_EXYNOS_IPP ret = exynos_platform_device_ipp_register(); if (ret < 0) goto err_unregister_non_kms_drivers; #endif ret = platform_driver_register(&exynos_drm_platform_driver); if (ret) goto err_unregister_resources; return 0; err_unregister_resources: #ifdef CONFIG_DRM_EXYNOS_IPP exynos_platform_device_ipp_unregister(); #endif err_unregister_non_kms_drivers: while (--j >= 0) platform_driver_unregister(exynos_drm_non_kms_drivers[j]); err_unregister_kms_drivers: while (--i >= 0) platform_driver_unregister(exynos_drm_kms_drivers[i]); exynos_drm_remove_vidi(); err_unregister_pd: platform_device_unregister(exynos_drm_pdev); return ret; } static void exynos_drm_exit(void) { int i; #ifdef CONFIG_DRM_EXYNOS_IPP exynos_platform_device_ipp_unregister(); #endif for (i = ARRAY_SIZE(exynos_drm_non_kms_drivers) - 1; i >= 0; --i) platform_driver_unregister(exynos_drm_non_kms_drivers[i]); for (i = ARRAY_SIZE(exynos_drm_kms_drivers) - 1; i >= 0; --i) platform_driver_unregister(exynos_drm_kms_drivers[i]); platform_driver_unregister(&exynos_drm_platform_driver); exynos_drm_remove_vidi(); platform_device_unregister(exynos_drm_pdev); } module_init(exynos_drm_init); module_exit(exynos_drm_exit); MODULE_AUTHOR("Inki Dae <[email protected]>"); MODULE_AUTHOR("Joonyoung Shim <[email protected]>"); MODULE_AUTHOR("Seung-Woo Kim <[email protected]>"); MODULE_DESCRIPTION("Samsung SoC DRM Driver"); MODULE_LICENSE("GPL");
gpl-2.0
Telegram-FOSS-Team/Telegram-FOSS
TMessagesProj/src/main/java/org/telegram/messenger/ForwardingMessagesParams.java
8580
package org.telegram.messenger; import android.text.TextUtils; import android.util.LongSparseArray; import android.util.SparseBooleanArray; import org.telegram.tgnet.TLRPC; import java.util.ArrayList; public class ForwardingMessagesParams { public LongSparseArray<MessageObject.GroupedMessages> groupedMessagesMap = new LongSparseArray<>(); public ArrayList<MessageObject> messages; public ArrayList<MessageObject> previewMessages = new ArrayList<>(); public SparseBooleanArray selectedIds = new SparseBooleanArray(); public boolean hideForwardSendersName; public boolean hideCaption; public boolean hasCaption; public boolean hasSenders; public boolean isSecret; public boolean willSeeSenders; public boolean multiplyUsers; public boolean hasSpoilers; public ArrayList<TLRPC.TL_pollAnswerVoters> pollChoosenAnswers = new ArrayList<>(); public ForwardingMessagesParams(ArrayList<MessageObject> messages, long newDialogId) { this.messages = messages; hasCaption = false; hasSenders = false; isSecret = DialogObject.isEncryptedDialog(newDialogId); hasSpoilers = false; ArrayList<String> hiddenSendersName = new ArrayList<>(); for (int i = 0; i < messages.size(); i++) { MessageObject messageObject = messages.get(i); if (!TextUtils.isEmpty(messageObject.caption)) { hasCaption = true; } selectedIds.put(messageObject.getId(), true); TLRPC.Message message = new TLRPC.TL_message(); message.id = messageObject.messageOwner.id; message.grouped_id = messageObject.messageOwner.grouped_id; message.peer_id = messageObject.messageOwner.peer_id; message.from_id = messageObject.messageOwner.from_id; message.message = messageObject.messageOwner.message; message.media = messageObject.messageOwner.media; message.action = messageObject.messageOwner.action; message.edit_date = 0; if (messageObject.messageOwner.entities != null) { message.entities.addAll(messageObject.messageOwner.entities); if (!hasSpoilers) { for (TLRPC.MessageEntity e : message.entities) { if (e instanceof TLRPC.TL_messageEntitySpoiler) { hasSpoilers = true; break; } } } } message.out = true; message.unread = false; message.via_bot_id = messageObject.messageOwner.via_bot_id; message.reply_markup = messageObject.messageOwner.reply_markup; message.post = messageObject.messageOwner.post; message.legacy = messageObject.messageOwner.legacy; message.restriction_reason = messageObject.messageOwner.restriction_reason; TLRPC.MessageFwdHeader header = null; long clientUserId = UserConfig.getInstance(messageObject.currentAccount).clientUserId; if (!isSecret) { if (messageObject.messageOwner.fwd_from != null) { header = messageObject.messageOwner.fwd_from; if (!messageObject.isDice()) { hasSenders = true; } else { willSeeSenders = true; } if (header.from_id == null && !hiddenSendersName.contains(header.from_name)) { hiddenSendersName.add(header.from_name); } } else if (messageObject.messageOwner.from_id.user_id == 0 || messageObject.messageOwner.dialog_id != clientUserId || messageObject.messageOwner.from_id.user_id != clientUserId) { header = new TLRPC.TL_messageFwdHeader(); header.from_id = messageObject.messageOwner.from_id; if (!messageObject.isDice()) { hasSenders = true; } else { willSeeSenders = true; } } } if (header != null) { message.fwd_from = header; message.flags |= TLRPC.MESSAGE_FLAG_FWD; } message.dialog_id = newDialogId; MessageObject previewMessage = new MessageObject(messageObject.currentAccount, message, true, false) { @Override public boolean needDrawForwarded() { if (hideForwardSendersName) { return false; } return super.needDrawForwarded(); } }; previewMessage.preview = true; if (previewMessage.getGroupId() != 0) { MessageObject.GroupedMessages groupedMessages = groupedMessagesMap.get(previewMessage.getGroupId(), null); if (groupedMessages == null) { groupedMessages = new MessageObject.GroupedMessages(); groupedMessagesMap.put(previewMessage.getGroupId(), groupedMessages); } groupedMessages.messages.add(previewMessage); } previewMessages.add(0, previewMessage); if (messageObject.isPoll()) { TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) messageObject.messageOwner.media; PreviewMediaPoll newMediaPoll = new PreviewMediaPoll(); newMediaPoll.poll = mediaPoll.poll; newMediaPoll.provider = mediaPoll.provider; newMediaPoll.results = new TLRPC.TL_pollResults(); newMediaPoll.totalVotersCached = newMediaPoll.results.total_voters = mediaPoll.results.total_voters; previewMessage.messageOwner.media = newMediaPoll; if (messageObject.canUnvote()) { for (int a = 0, N = mediaPoll.results.results.size(); a < N; a++) { TLRPC.TL_pollAnswerVoters answer = mediaPoll.results.results.get(a); if (answer.chosen) { TLRPC.TL_pollAnswerVoters newAnswer = new TLRPC.TL_pollAnswerVoters(); newAnswer.chosen = answer.chosen; newAnswer.correct = answer.correct; newAnswer.flags = answer.flags; newAnswer.option = answer.option; newAnswer.voters = answer.voters; pollChoosenAnswers.add(newAnswer); newMediaPoll.results.results.add(newAnswer); } else { newMediaPoll.results.results.add(answer); } } } } } ArrayList<Long> uids = new ArrayList<>(); for (int a = 0; a < messages.size(); a++) { MessageObject object = messages.get(a); long uid; if (object.isFromUser()) { uid = object.messageOwner.from_id.user_id; } else { TLRPC.Chat chat = MessagesController.getInstance(object.currentAccount).getChat(object.messageOwner.peer_id.channel_id); if (ChatObject.isChannel(chat) && chat.megagroup && object.isForwardedChannelPost()) { uid = -object.messageOwner.fwd_from.from_id.channel_id; } else { uid = -object.messageOwner.peer_id.channel_id; } } if (!uids.contains(uid)) { uids.add(uid); } } if (uids.size() + hiddenSendersName.size() > 1) { multiplyUsers = true; } for (int i = 0; i < groupedMessagesMap.size(); i++) { groupedMessagesMap.valueAt(i).calculate(); } } public void getSelectedMessages(ArrayList<MessageObject> messagesToForward) { messagesToForward.clear(); for (int i = 0; i < messages.size(); i++) { MessageObject messageObject = messages.get(i); int id = messageObject.getId(); if (selectedIds.get(id, false)) { messagesToForward.add(messageObject); } } } public class PreviewMediaPoll extends TLRPC.TL_messageMediaPoll { public int totalVotersCached; } }
gpl-2.0
project-magpie/tdt-driver
player2_179/player/collator/collator_pes_video_divx.cpp
15639
/************************************************************************ COPYRIGHT (C) STMicroelectronics 2007 Source file name : collator_pes_video_divx_.cpp Author : Chris Implementation of the pes collator class for player 2. Date Modification Name ---- ------------ -------- 11-Jul-07 Created Chris ************************************************************************/ //////////////////////////////////////////////////////////////////////////// /// \class Collator_PesVideoDivx_c /// /// Implements initialisation of collator video class for Divx /// // ///////////////////////////////////////////////////////////////////// // // Include any component headers // #include "collator_pes_video_divx.h" // ///////////////////////////////////////////////////////////////////////// // // Locally defined constants // // #define ZERO_START_CODE_HEADER_SIZE 7 // Allow us to see 00 00 01 00 00 01 <other code> // ///////////////////////////////////////////////////////////////////////// // // Locally defined structures // //////////////////////////////////////////////////////////////////////////// /// /// Initialize the class by resetting it. /// /// During a constructor calls to virtual methods resolve to the current class (because /// the vtable is still for the class being constructed). This means we need to call /// ::Reset again because the calls made by the sub-constructors will not have called /// our reset method. /// Collator_PesVideoDivx_c::Collator_PesVideoDivx_c( void ) { if( InitializationStatus != CollatorNoError ) return; Collator_PesVideoDivx_c::Reset(); } //////////////////////////////////////////////////////////////////////////// /// /// Resets and configures according to the requirements of this stream content /// /// \return void /// CollatorStatus_t Collator_PesVideoDivx_c::Reset( void ) { CollatorStatus_t Status; // COLLATOR_DEBUG(">><<\n"); Status = Collator_PesVideo_c::Reset(); if( Status != CollatorNoError ) return Status; Configuration.GenerateStartCodeList = true; Configuration.MaxStartCodes = 16; Configuration.StreamIdentifierMask = 0xff; // Video Configuration.StreamIdentifierCode = PES_START_CODE_VIDEO; Configuration.BlockTerminateMask = 0xff; // Picture Configuration.BlockTerminateCode = 0xb6; Configuration.IgnoreCodesRangeStart = 0x01; Configuration.IgnoreCodesRangeEnd = 0x1F; Configuration.InsertFrameTerminateCode = false; Configuration.TerminalCode = 0x00; Configuration.ExtendedHeaderLength = 0; IgnoreCodes = false; Version = 5; Configuration.DeferredTerminateFlag = true; Configuration.StreamTerminateFlushesFrame = false; return CollatorNoError; } CollatorStatus_t Collator_PesVideoDivx_c::Input( PlayerInputDescriptor_t *Input, unsigned int DataLength, void *Data ) { unsigned int i; CollatorStatus_t Status; unsigned int HeaderSize; unsigned int Transfer; unsigned int Skip; unsigned int SpanningWord; unsigned int StartingWord; unsigned int SpanningCount; unsigned int CodeOffset; unsigned char Code; // AssertComponentState( "Collator_PesVideoDivx_c::Input", ComponentRunning ); ActOnInputDescriptor( Input ); // // Initialize scan state // StartCodeCount = 0; RemainingData = (unsigned char *)Data; RemainingLength = DataLength; while( RemainingLength != 0 ) { // // Are we building a pes header // if( GotPartialPesHeader ) { HeaderSize = PES_INITIAL_HEADER_SIZE; if( RemainingLength >= (PES_INITIAL_HEADER_SIZE - GotPartialPesHeaderBytes) ) HeaderSize = GotPartialPesHeaderBytes >= PES_INITIAL_HEADER_SIZE ? PES_HEADER_SIZE(StoredPesHeader) : PES_HEADER_SIZE(RemainingData-GotPartialPesHeaderBytes); Transfer = min( RemainingLength, (HeaderSize - GotPartialPesHeaderBytes) ); memcpy( StoredPesHeader+GotPartialPesHeaderBytes, RemainingData, Transfer ); GotPartialPesHeaderBytes += Transfer; RemainingData += Transfer; RemainingLength -= Transfer; if( GotPartialPesHeaderBytes == PES_HEADER_SIZE(StoredPesHeader) ) { // // Since we are going to process the partial header, we will not have it in future // GotPartialPesHeader = false; // Status = ReadPesHeader(); if( Status != CollatorNoError ) return Status; if( SeekingPesHeader ) { AccumulatedDataSize = 0; // Dump any collected data SeekingPesHeader = false; } } if( RemainingLength == 0 ) return CollatorNoError; } // // Are we building a padding header // if( GotPartialPaddingHeader ) { report(severity_error,"Partial Packing\n"); HeaderSize = PES_PADDING_INITIAL_HEADER_SIZE; Transfer = min( RemainingLength, (HeaderSize - GotPartialPaddingHeaderBytes) ); memcpy( StoredPaddingHeader+GotPartialPaddingHeaderBytes, RemainingData, Transfer ); GotPartialPaddingHeaderBytes += Transfer; RemainingData += Transfer; RemainingLength -= Transfer; if( GotPartialPaddingHeaderBytes == PES_PADDING_INITIAL_HEADER_SIZE ) { Skipping = PES_PADDING_SKIP(StoredPaddingHeader); report(severity_error,"Skipping\n"); GotPartialPaddingHeader = false; } if( RemainingLength == 0 ) return CollatorNoError; } // // Are we skipping padding // if( Skipping != 0 ) { Skip = min( Skipping, RemainingLength ); RemainingData += Skip; RemainingLength -= Skip; Skipping -= Skip; if( RemainingLength == 0 ) return CollatorNoError; } // // Check for spanning header // SpanningWord = 0xffffffff << (8 * min(AccumulatedDataSize,3)); SpanningWord |= BufferBase[AccumulatedDataSize-3] << 16; SpanningWord |= BufferBase[AccumulatedDataSize-2] << 8; SpanningWord |= BufferBase[AccumulatedDataSize-1]; StartingWord = 0x00ffffff >> (8 * min((RemainingLength-1),3)); StartingWord |= RemainingData[0] << 24; StartingWord |= RemainingData[1] << 16; StartingWord |= RemainingData[2] << 8; // // Check for a start code spanning, or in the first word // record the nature of the span in a counter indicating how many // bytes of the code are in the remaining data. // NOTE the 00 at the bottom indicates we have a byte for the code, // not what it is. // SpanningCount = 0; if( (SpanningWord << 8) == 0x00000100 ) { SpanningCount = 1; } else if( ((SpanningWord << 16) | ((StartingWord >> 16) & 0xff00)) == 0x00000100 ) { SpanningCount = 2; } else if( ((SpanningWord << 24) | ((StartingWord >> 8) & 0xffff00)) == 0x00000100 ) { SpanningCount = 3; } else if( StartingWord == 0x00000100 ) { SpanningCount = 4; UseSpanningTime = false; } // // Check that if we have a spanning code, that the code is not to be ignored // if( (SpanningCount != 0) && inrange(RemainingData[SpanningCount-1], Configuration.IgnoreCodesRangeStart, Configuration.IgnoreCodesRangeEnd) ) { SpanningCount = 0; } // // Handle a spanning start code // if( SpanningCount != 0 ) { // // Copy over the spanning bytes // for( i=0; i<SpanningCount; i++ ) BufferBase[AccumulatedDataSize + i] = RemainingData[i]; AccumulatedDataSize += SpanningCount; RemainingData += SpanningCount; RemainingLength -= SpanningCount; Code = BufferBase[AccumulatedDataSize-1]; // report(severity_info,"Start Code %x\n",Code); if( Code == 0x31 ) { Version = *RemainingData; //report(severity_error,"Version Number %d\n",Version); IgnoreCodes = false; } if( Code == 0x00 ) { GotPartialZeroHeader = true; AccumulatedDataSize -= 4; // Wind to before it GotPartialZeroHeaderBytes = 4; StoredZeroHeader = BufferBase + AccumulatedDataSize; continue; } // // Is it a pes header, and is it a pes stream we are interested in // else if( IS_PES_START_CODE_VIDEO(Code) ) { AccumulatedDataSize -= 4; // Wind to before it if( (Code & Configuration.StreamIdentifierMask) == Configuration.StreamIdentifierCode ) { GotPartialPesHeader = true; GotPartialPesHeaderBytes = 4; StoredPesHeader = BufferBase + AccumulatedDataSize; } else { SeekingPesHeader = true; } continue; } // // Or is it a padding block // else if( Code == PES_PADDING_START_CODE ) { GotPartialPaddingHeader = true; AccumulatedDataSize -= 4; // Wind to before it GotPartialPaddingHeaderBytes = 4; StoredPaddingHeader = BufferBase + AccumulatedDataSize; continue; } // // Or if we are seeking a pes header, dump what we have and try again // else if( SeekingPesHeader ) { AccumulatedDataSize = 0; // Wind to before it continue; } // // Or is it a block terminate code // else if( TerminationFlagIsSet) { AccumulatedDataSize -=4; Status = FrameFlush(); if( Status != CollatorNoError ) return Status; BufferBase[0] = 0x00; BufferBase[1] = 0x00; BufferBase[2] = 0x01; BufferBase[3] = Code; AccumulatedDataSize = 4; SeekingPesHeader = false; TerminationFlagIsSet = false; if ( Configuration.DeferredTerminateFlag && ((Code & Configuration.BlockTerminateMask) == Configuration.BlockTerminateCode)) { TerminationFlagIsSet = true; } } else if ( Configuration.DeferredTerminateFlag && ((Code & Configuration.BlockTerminateMask) == Configuration.BlockTerminateCode)) { IgnoreCodes = true; TerminationFlagIsSet = true; } // // Otherwise (and if its a block terminate) accumulate the start code // Status = AccumulateStartCode( PackStartCode(AccumulatedDataSize-4,Code) ); if( Status != CollatorNoError ) { DiscardAccumulatedData(); return Status; } } // // If we had no spanning code, but we had a spanning PTS, and we // had no normal PTS for this frame, the copy the spanning time // to the normal time. // else if( !PlaybackTimeValid ) { PlaybackTimeValid = SpanningPlaybackTimeValid; PlaybackTime = SpanningPlaybackTime; DecodeTimeValid = SpanningDecodeTimeValid; DecodeTime = SpanningDecodeTime; UseSpanningTime = false; SpanningPlaybackTimeValid = false; SpanningDecodeTimeValid = false; } // // Now enter the loop processing start codes // while( true ) { Status = FindNextStartCode( &CodeOffset ); if( Status != CollatorNoError) { // // Terminal code after start code processing copy remaining data into buffer // Status = AccumulateData( RemainingLength, RemainingData ); if( Status != CollatorNoError ) DiscardAccumulatedData(); RemainingLength = 0; return Status; } // // Got one accumulate upto and including it // Status = AccumulateData( CodeOffset+4, RemainingData ); if( Status != CollatorNoError ) { DiscardAccumulatedData(); return Status; } Code = RemainingData[CodeOffset+3]; RemainingLength -= CodeOffset+4; RemainingData += CodeOffset+4; // report(severity_info,"Start Code %x (ignore %d)\n",Code,IgnoreCodes); // second case is for when we have 2 B6's in a group which can cause issues. Test with BatmanBegins if ((IgnoreCodes == false) || ((Code & Configuration.BlockTerminateMask) == Configuration.BlockTerminateCode) ) { // // Is it a pes header, and is it a pes stream we are interested in // if( Code == 0x00 ) { GotPartialZeroHeader = true; AccumulatedDataSize -= 4; // Wind to before it GotPartialZeroHeaderBytes = 4; StoredZeroHeader = BufferBase + AccumulatedDataSize; continue; } else if( IS_PES_START_CODE_VIDEO(Code) ) { AccumulatedDataSize -= 4; // Wind to before it if( (Code & Configuration.StreamIdentifierMask) == Configuration.StreamIdentifierCode ) { GotPartialPesHeader = true; GotPartialPesHeaderBytes = 4; StoredPesHeader = BufferBase + AccumulatedDataSize; } else { SeekingPesHeader = true; } break; } // // Or is it a padding block // else if( Code == PES_PADDING_START_CODE ) { GotPartialPaddingHeader = true; AccumulatedDataSize -= 4; // Wind to before it GotPartialPaddingHeaderBytes = 4; StoredPaddingHeader = BufferBase + AccumulatedDataSize; break; } // // Or if we are seeking a pes header, dump what we have and try again // else if( SeekingPesHeader ) { AccumulatedDataSize = 0; // Wind to before it break; } // // Or is it a block terminate code // else if( TerminationFlagIsSet) { AccumulatedDataSize -=4; Status = FrameFlush(); if( Status != CollatorNoError ) return Status; BufferBase[0] = 0x00; BufferBase[1] = 0x00; BufferBase[2] = 0x01; BufferBase[3] = Code; AccumulatedDataSize = 4; SeekingPesHeader = false; if ( Configuration.DeferredTerminateFlag && ((Code & Configuration.BlockTerminateMask) == Configuration.BlockTerminateCode)) { TerminationFlagIsSet = true; } else TerminationFlagIsSet = false; } else if ( (Code & Configuration.BlockTerminateMask) == Configuration.BlockTerminateCode) { TerminationFlagIsSet = true; IgnoreCodes = true; } // // Otherwise (and if its a block terminate) accumulate the start code // Status = AccumulateStartCode( PackStartCode(AccumulatedDataSize-4,Code) ); if( Status != CollatorNoError ) { DiscardAccumulatedData(); return Status; } else if (Version != 3) // work around for issues with fake start codes in 311 streams { IgnoreCodes = false; } } else { // report (severity_error,"Ignoring Code %x\n",Code); continue; } } } return CollatorNoError; }
gpl-2.0
bmajoros/UnVeil
tigr++/TigrStringMap.H
10179
/************************************************************** TigrStringMap.H [email protected] 1/1/2003 TIGR++ : C++ class template library for bioinformatics Copyright (c) 2003, The Institute for Genomic Research (TIGR), Rockville, Maryland, U.S.A. All rights reserved. ***************************************************************/ #ifndef INCL_TigrStringMap_H #define INCL_TigrStringMap_H #include <list> #include "TigrString.H" using namespace std; /***************************************************************** Some primes to use for table sizes: tens: 13 19 23 31 41 53 61 71 83 89 hundreds: 101 199 293 401 499 601 701 797 887 thousands: 997 1097 1201 1301 1399 1499 1601 1699 1801 1901 1999 2099 2179 2297 2399 2477 2593 2699 2801 2897 3001 3089 3191 3301 3391 3499 3593 3701 3797 3889 4001 4099 4201 4297 4397 4493 4597 4691 4801 4889 4999 5101 5197 5297 5399 5501 5591 5701 5801 5897 5987 6101 6199 6301 6397 6491 6599 6701 6793 6899 7001 7079 7193 7297 7393 7499 7591 7699 7793 7901 7993 8101 8191 8297 8389 8501 8599 8699 8783 8893 9001 9091 9199 9293 9397 9497 9601 9697 9791 9901 ten-thousands: 9973 10993 11987 12983 13999 14983 15991 16993 17989 18979 19997 20983 21997 22993 23993 24989 25999 26993 27997 28979 29989 30983 31991 32999 33997 34981 35999 36997 37997 38993 39989 40993 41999 42989 43997 44987 45989 46997 47981 48991 49999 50993 51991 52999 53993 54983 55997 56999 57991 58997 59999 60961 61991 62989 63997 64997 65993 66977 67993 68993 69997 70999 71999 72997 73999 74959 75997 76991 77999 78989 79999 80989 81973 82997 83987 84991 85999 86993 87991 88997 89989 90997 91997 92993 93997 94999 95989 96997 97987 98999 hundred-thousands: 99961 199999 299993 399989 499979 599999 700001 799999 900001 millions: 999959 1999957 *****************************************************************/ /***************************************************************** */ template<class T> struct StringMapElem { int len; char *first; T second; StringMapElem(const char *,int len,const T &); StringMapElem(const char *,int len); StringMapElem(const StringMapElem<T> &); virtual ~StringMapElem(); }; /***************************************************************** */ template<class T> class StringMapIterator { public: typedef list<StringMapElem<T>*> Bucket; typedef StringMapElem<T> ElemType; StringMapIterator(int index,int tableSize,Bucket *array); inline bool operator!=(const StringMapIterator<T> &); bool operator==(const StringMapIterator<T> &); StringMapIterator<T> &operator++(int); StringMapIterator<T> &operator++(); StringMapElem<T> &operator*(); private: int index, tableSize; typename Bucket::iterator cur, end; Bucket *array; void findNonemptyBucket(); }; /***************************************************************** */ template<class T> class TigrStringMap { public: typedef StringMapElem<T> ElemType; typedef StringMapIterator<T> iterator; typedef StringMapIterator<T> const_iterator; TigrStringMap(int tableSize); TigrStringMap(const TigrStringMap<T> &); virtual ~TigrStringMap(); T &lookup(const char *,int index,int len); T &lookup(const char *,int len); bool isDefined(const char *,int index,int len); bool isDefined(const char *,int len); int size(); iterator begin(); iterator end(); iterator begin() const; iterator end() const; void clear(); void remove(const char *,int index,int len); void remove(const char *,int len); TigrStringMap<T> &operator=(const TigrStringMap &); private: typedef list<StringMapElem<T>*> Bucket; int tableSize, numElements; Bucket *array; unsigned hash(const char *,int len,int tableSize); }; /***************************************************************** */ template<class T> StringMapElem<T>::StringMapElem(const StringMapElem<T> &other) : len(other.len), second(other.second) { first=new char[len+1]; memcpy(first,other.first,len+1); } template<class T> StringMapElem<T>::StringMapElem(const char *p,int len) : len(len) { first=new char[len+1]; first[len]='\0'; strncpy(first,p,len); } template<class T> StringMapElem<T>::StringMapElem(const char *p,int len,const T &t) : second(t), len(len) { first=new char[len+1]; first[len]='\0'; strncpy(first,p,len); } template<class T> StringMapElem<T>::~StringMapElem() { delete [] first; } template<class T> StringMapElem<T> &StringMapIterator<T>::operator*() { return **cur; } template<class T> StringMapIterator<T> &StringMapIterator<T>::operator++() { if(index<tableSize) { ++cur; if(cur==end) { ++index; findNonemptyBucket(); } } return *this; } template<class T> StringMapIterator<T> &StringMapIterator<T>::operator++(int) { if(index<tableSize) { ++cur; if(cur==end) { ++index; findNonemptyBucket(); } } return *this; } template<class T> StringMapIterator<T>::StringMapIterator(int index,int tableSize,Bucket *array) : array(array), tableSize(tableSize), index(index) { findNonemptyBucket(); } template<class T> bool StringMapIterator<T>::operator!=(const StringMapIterator<T> &i) { return !(*this==i); } template<class T> bool StringMapIterator<T>::operator==(const StringMapIterator<T> &other) { if(other.index!=index) return false; if(index>=tableSize) return true; return cur==other.cur; } template<class T> void StringMapIterator<T>::findNonemptyBucket() { for(; index<tableSize ; ++index) { Bucket &bucket=array[index]; if(!bucket.empty()) { cur=bucket.begin(); end=bucket.end(); return; } } } template<class T> T &TigrStringMap<T>::lookup(const char *p,int len) { return lookup(p,0,len); } template<class T> T &TigrStringMap<T>::lookup(const char *pOrigin,int index,int len) { const char *p=pOrigin+index; unsigned hashValue=hash(p,len,tableSize); Bucket &bucket=array[hashValue]; typename Bucket::iterator end=bucket.end(); typename Bucket::iterator cur=bucket.begin(); for(; cur!=end ; ++cur) { StringMapElem<T> *elem=*cur; if(len!=elem->len) continue; if(!strncmp(p,elem->first,len)) return elem->second; } StringMapElem<T> *newElem=new StringMapElem<T>(p,len); bucket.push_back(newElem); ++numElements; return newElem->second; } template<class T> TigrStringMap<T>::TigrStringMap(const TigrStringMap<T> &other) : tableSize(other.tableSize), numElements(other.numElements), array(new Bucket[other.tableSize]) { for(int i=0 ; i<tableSize ; ++i) { Bucket &thisBucket=array[i], &thatBucket=other.array[i]; typename Bucket::iterator cur=thatBucket.begin(), end=thatBucket.end(); for(; cur!=end ; ++cur) thisBucket.push_back(new StringMapElem<T>(**cur)); } } template<class T> TigrStringMap<T> &TigrStringMap<T>::operator=(const TigrStringMap &other) { tableSize=other.tableSize; numElements=other.numElements; array=new Bucket[other.tableSize]; for(int i=0 ; i<tableSize ; ++i) { Bucket &thisBucket=array[i]; const Bucket &thatBucket=other.array[i]; typename Bucket::const_iterator cur=thatBucket.begin(), end=thatBucket.end(); for(; cur!=end ; ++cur) thisBucket.push_back(new StringMapElem<T>(**cur)); } return *this; } template<class T> TigrStringMap<T>::TigrStringMap(int tableSize) : tableSize(tableSize), numElements(0) { array=new Bucket[tableSize]; } template<class T> typename TigrStringMap<T>::iterator TigrStringMap<T>::begin() { return iterator(0,tableSize,array); } template<class T> typename TigrStringMap<T>::iterator TigrStringMap<T>::end() { return iterator(tableSize,tableSize,array); } template<class T> typename TigrStringMap<T>::iterator TigrStringMap<T>::begin() const { return iterator(0,tableSize,const_cast<Bucket*>(array)); } template<class T> typename TigrStringMap<T>::iterator TigrStringMap<T>::end() const { return iterator(tableSize,tableSize,const_cast<Bucket*>(array)); } template<class T> TigrStringMap<T>::~TigrStringMap() { //cout<<"~TigrStringMap"<<endl; for(int i=0 ; i<tableSize ; ++i) { Bucket &bucket=array[i]; typename Bucket::iterator cur=bucket.begin(), end=bucket.end(); for(; cur!=end ; ++cur) delete *cur; } delete [] array; } template<class T> bool TigrStringMap<T>::isDefined(const char *p,int len) { return isDefined(p,0,len); } template<class T> bool TigrStringMap<T>::isDefined(const char *pOrigin,int index,int len) { const char *p=pOrigin+index; unsigned hashValue=hash(p,len,tableSize); Bucket &bucket=array[hashValue]; typename Bucket::iterator cur=bucket.begin(), end=bucket.end(); for(; cur!=end ; ++cur) { StringMapElem<T> *elem=*cur; if(len!=elem->len) continue; if(!strncmp(p,elem->first,len)) return true; } return false; } template<class T> int TigrStringMap<T>::size() { return numElements; } template<class T> unsigned TigrStringMap<T>::hash(const char *s,int length,int tableSize) { int h=0; const char *p=s, *end=s+length; for(; p!=end ; ++p) { h=(h<<4)+*p; int g=h & 0xf000; if(g) h=h^(g>>8); } return labs(h) % tableSize; } template<class T> void TigrStringMap<T>::clear() { for(int i=0 ; i<tableSize ; ++i) { Bucket &bucket=array[i]; typename Bucket::iterator cur=bucket.begin(), end=bucket.end(); for(; cur!=end ; ++cur) delete *cur; bucket.clear(); } numElements=0; } template<class T> void TigrStringMap<T>::remove(const char *p,int len) { remove(p,0,len); } template<class T> void TigrStringMap<T>::remove(const char *pOrigin,int index,int len) { const char *p=pOrigin+index; unsigned hashValue=hash(p,len,tableSize); Bucket &bucket=array[hashValue]; typename Bucket::iterator cur=bucket.begin(), end=bucket.end(); for(; cur!=end ; ++cur) { StringMapElem<T> *elem=*cur; if(len!=elem->len) continue; if(!strncmp(p,elem->first,len)) { bucket.erase(cur); break; } } --numElements; } #endif
gpl-2.0
abbradar/kernel_I9001_samsung
drivers/mmc/host/msm_sdcc.c
57679
/* * linux/drivers/mmc/host/msm_sdcc.c - Qualcomm MSM 7X00A SDCC Driver * * Copyright (C) 2007 Google Inc, * Copyright (C) 2003 Deep Blue Solutions, Ltd, All Rights Reserved. * Copyright (c) 2009-2011, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * Based on mmci.c * * Author: San Mehat ([email protected]) * */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/init.h> #include <linux/ioport.h> #include <linux/device.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/delay.h> #include <linux/err.h> #include <linux/highmem.h> #include <linux/log2.h> #include <linux/mmc/host.h> #include <linux/mmc/card.h> #include <linux/mmc/mmc.h> #include <linux/mmc/sdio.h> #include <linux/clk.h> #include <linux/scatterlist.h> #include <linux/platform_device.h> #include <linux/dma-mapping.h> #include <linux/debugfs.h> #include <linux/io.h> #include <linux/memory.h> #include <linux/pm_runtime.h> #include <linux/wakelock.h> #include <asm/cacheflush.h> #include <asm/div64.h> #include <asm/sizes.h> #include <asm/mach/mmc.h> #include <mach/msm_iomap.h> #include <mach/clk.h> #include <mach/dma.h> #include <mach/htc_pwrsink.h> #include <mach/gpio.h> #include <linux/mfd/pmic8058.h> #include "msm_sdcc.h" #define DRIVER_NAME "msm-sdcc" #define DBG(host, fmt, args...) \ pr_debug("%s: %s: " fmt "\n", mmc_hostname(host->mmc), __func__ , args) #define IRQ_DEBUG 0 #define PM8058_GPIO_PM_TO_SYS(pm_gpio) (pm_gpio + NR_GPIO_IRQS) #define PM8058_GPIO_SYS_TO_PM(sys_gpio) (sys_gpio - NR_GPIO_IRQS) #if defined(CONFIG_DEBUG_FS) static void msmsdcc_dbg_createhost(struct msmsdcc_host *); static struct dentry *debugfs_dir; static struct dentry *debugfs_file; static int msmsdcc_dbg_init(void); #endif static unsigned int msmsdcc_pwrsave = 1; unsigned int external_sd_status = 1; #define DUMMY_52_STATE_NONE 0 #define DUMMY_52_STATE_SENT 1 static struct mmc_command dummy52cmd; static struct mmc_request dummy52mrq = { .cmd = &dummy52cmd, .data = NULL, .stop = NULL, }; static struct mmc_command dummy52cmd = { .opcode = SD_IO_RW_DIRECT, .flags = MMC_RSP_PRESENT, .data = NULL, .mrq = &dummy52mrq, }; struct pm8058_gpio sd_pwr_en_n_1 = { .direction = PM_GPIO_DIR_OUT, .pull = PM_GPIO_PULL_NO, .vin_sel = PM_GPIO_VIN_L5, .function = PM_GPIO_FUNC_NORMAL, .inv_int_pol = 0, .out_strength = PM_GPIO_STRENGTH_LOW, .output_value = 0, }; #define VERBOSE_COMMAND_TIMEOUTS 0 #define nT_FLASH_DET 116 #if IRQ_DEBUG == 1 static char *irq_status_bits[] = { "cmdcrcfail", "datcrcfail", "cmdtimeout", "dattimeout", "txunderrun", "rxoverrun", "cmdrespend", "cmdsent", "dataend", NULL, "datablkend", "cmdactive", "txactive", "rxactive", "txhalfempty", "rxhalffull", "txfifofull", "rxfifofull", "txfifoempty", "rxfifoempty", "txdataavlbl", "rxdataavlbl", "sdiointr", "progdone", "atacmdcompl", "sdiointrope", "ccstimeout", NULL, NULL, NULL, NULL, NULL }; static void msmsdcc_print_status(struct msmsdcc_host *host, char *hdr, uint32_t status) { int i; pr_debug("%s-%s ", mmc_hostname(host->mmc), hdr); for (i = 0; i < 32; i++) { if (status & (1 << i)) pr_debug("%s ", irq_status_bits[i]); } pr_debug("\n"); } #endif static void msmsdcc_start_command(struct msmsdcc_host *host, struct mmc_command *cmd, u32 c); static void msmsdcc_reset_and_restore(struct msmsdcc_host *host) { u32 mci_clk = 0; u32 mci_mask0 = 0; int ret; /* Save the controller state */ mci_clk = readl(host->base + MMCICLOCK); mci_mask0 = readl(host->base + MMCIMASK0); /* Reset the controller */ ret = clk_reset(host->clk, CLK_RESET_ASSERT); if (ret) pr_err("%s: Clock assert failed at %u Hz with err %d\n", mmc_hostname(host->mmc), host->clk_rate, ret); ret = clk_reset(host->clk, CLK_RESET_DEASSERT); if (ret) pr_err("%s: Clock deassert failed at %u Hz with err %d\n", mmc_hostname(host->mmc), host->clk_rate, ret); pr_debug("%s: Controller has been reinitialized\n", mmc_hostname(host->mmc)); /* Restore the contoller state */ writel(host->pwr, host->base + MMCIPOWER); writel(mci_clk, host->base + MMCICLOCK); writel(mci_mask0, host->base + MMCIMASK0); ret = clk_set_rate(host->clk, host->clk_rate); if (ret) pr_err("%s: Failed to set clk rate %u Hz. err %d\n", mmc_hostname(host->mmc), host->clk_rate, ret); } static int msmsdcc_request_end(struct msmsdcc_host *host, struct mmc_request *mrq) { int retval = 0; BUG_ON(host->curr.data); host->curr.mrq = NULL; host->curr.cmd = NULL; if (mrq->data) mrq->data->bytes_xfered = host->curr.data_xfered; if (mrq->cmd->error == -ETIMEDOUT) mdelay(5); #ifdef CONFIG_MMC_MSM_PROG_DONE_SCAN if ((mrq->cmd->opcode == SD_IO_RW_EXTENDED) && (mrq->cmd->arg & 0x80000000)) { /* If its a write and a cmd53 set the prog_scan flag. */ host->prog_scan = 1; /* Send STOP to let the SDCC know to stop. */ writel(MCI_CSPM_MCIABORT, host->base + MMCICOMMAND); retval = 1; } if (mrq->cmd->opcode == SD_IO_RW_DIRECT) { /* Ok the cmd52 following a cmd53 is received */ /* clear all the flags. */ host->prog_scan = 0; host->prog_enable = 0; } #endif /* * Need to drop the host lock here; mmc_request_done may call * back into the driver... */ spin_unlock(&host->lock); mmc_request_done(host->mmc, mrq); spin_lock(&host->lock); return retval; } static void msmsdcc_stop_data(struct msmsdcc_host *host) { host->curr.data = NULL; host->curr.got_dataend = 0; } static inline uint32_t msmsdcc_fifo_addr(struct msmsdcc_host *host) { return host->memres->start + MMCIFIFO; } static inline void msmsdcc_delay(struct msmsdcc_host *host) { udelay(1 + ((3 * USEC_PER_SEC) / (host->clk_rate ? host->clk_rate : host->plat->msmsdcc_fmin))); } static inline void msmsdcc_start_command_exec(struct msmsdcc_host *host, u32 arg, u32 c) { writel(arg, host->base + MMCIARGUMENT); msmsdcc_delay(host); writel(c, host->base + MMCICOMMAND); } static void msmsdcc_dma_exec_func(struct msm_dmov_cmd *cmd) { struct msmsdcc_host *host = (struct msmsdcc_host *)cmd->user; writel(host->cmd_timeout, host->base + MMCIDATATIMER); writel((unsigned int)host->curr.xfer_size, host->base + MMCIDATALENGTH); writel((readl(host->base + MMCIMASK0) & (~(MCI_IRQ_PIO))) | host->cmd_pio_irqmask, host->base + MMCIMASK0); msmsdcc_delay(host); /* Allow data parms to be applied */ writel(host->cmd_datactrl, host->base + MMCIDATACTRL); msmsdcc_delay(host); /* Force delay prior to ADM or command */ if (host->cmd_cmd) { msmsdcc_start_command_exec(host, (u32)host->cmd_cmd->arg, (u32)host->cmd_c); } } static void msmsdcc_dma_complete_tlet(unsigned long data) { struct msmsdcc_host *host = (struct msmsdcc_host *)data; unsigned long flags; struct mmc_request *mrq; spin_lock_irqsave(&host->lock, flags); mrq = host->curr.mrq; BUG_ON(!mrq); if (!(host->dma.result & DMOV_RSLT_VALID)) { pr_err("msmsdcc: Invalid DataMover result\n"); goto out; } if (host->dma.result & DMOV_RSLT_DONE) { host->curr.data_xfered = host->curr.xfer_size; } else { /* Error or flush */ if (host->dma.result & DMOV_RSLT_ERROR) pr_err("%s: DMA error (0x%.8x)\n", mmc_hostname(host->mmc), host->dma.result); if (host->dma.result & DMOV_RSLT_FLUSH) pr_err("%s: DMA channel flushed (0x%.8x)\n", mmc_hostname(host->mmc), host->dma.result); pr_err("Flush data: %.8x %.8x %.8x %.8x %.8x %.8x\n", host->dma.err.flush[0], host->dma.err.flush[1], host->dma.err.flush[2], host->dma.err.flush[3], host->dma.err.flush[4], host->dma.err.flush[5]); msmsdcc_reset_and_restore(host); if (!mrq->data->error) mrq->data->error = -EIO; } dma_unmap_sg(mmc_dev(host->mmc), host->dma.sg, host->dma.num_ents, host->dma.dir); if (host->curr.user_pages) { struct scatterlist *sg = host->dma.sg; int i; for (i = 0; i < host->dma.num_ents; i++, sg++) flush_dcache_page(sg_page(sg)); } host->dma.sg = NULL; host->dma.busy = 0; if (host->curr.got_dataend || mrq->data->error) { /* * If we've already gotten our DATAEND / DATABLKEND * for this request, then complete it through here. */ msmsdcc_stop_data(host); if (!mrq->data->error) host->curr.data_xfered = host->curr.xfer_size; if (!mrq->data->stop || mrq->cmd->error) { host->curr.mrq = NULL; host->curr.cmd = NULL; mrq->data->bytes_xfered = host->curr.data_xfered; spin_unlock_irqrestore(&host->lock, flags); #ifdef CONFIG_MMC_MSM_PROG_DONE_SCAN if ((mrq->cmd->opcode == SD_IO_RW_EXTENDED) && (mrq->cmd->arg & 0x80000000)) { /* set the prog_scan in a cmd53.*/ host->prog_scan = 1; /* Send STOP to let the SDCC know to stop. */ writel(MCI_CSPM_MCIABORT, host->base + MMCICOMMAND); } #endif mmc_request_done(host->mmc, mrq); return; } else msmsdcc_start_command(host, mrq->data->stop, 0); } out: spin_unlock_irqrestore(&host->lock, flags); return; } static void msmsdcc_dma_complete_func(struct msm_dmov_cmd *cmd, unsigned int result, struct msm_dmov_errdata *err) { struct msmsdcc_dma_data *dma_data = container_of(cmd, struct msmsdcc_dma_data, hdr); struct msmsdcc_host *host = dma_data->host; dma_data->result = result; if (err) memcpy(&dma_data->err, err, sizeof(struct msm_dmov_errdata)); tasklet_schedule(&host->dma_tlet); } static int validate_dma(struct msmsdcc_host *host, struct mmc_data *data) { if (host->dma.channel == -1) return -ENOENT; if ((data->blksz * data->blocks) < MCI_FIFOSIZE) return -EINVAL; if ((data->blksz * data->blocks) % MCI_FIFOSIZE) return -EINVAL; return 0; } static int msmsdcc_config_dma(struct msmsdcc_host *host, struct mmc_data *data) { struct msmsdcc_nc_dmadata *nc; dmov_box *box; uint32_t rows; uint32_t crci; unsigned int n; int i, rc; struct scatterlist *sg = data->sg; rc = validate_dma(host, data); if (rc) return rc; host->dma.sg = data->sg; host->dma.num_ents = data->sg_len; BUG_ON(host->dma.num_ents > NR_SG); /* Prevent memory corruption */ nc = host->dma.nc; if (host->pdev_id == 1) crci = DMOV_SDC1_CRCI; else if (host->pdev_id == 2) crci = DMOV_SDC2_CRCI; else if (host->pdev_id == 3) crci = DMOV_SDC3_CRCI; else if (host->pdev_id == 4) crci = DMOV_SDC4_CRCI; #ifdef DMOV_SDC5_CRCI else if (host->pdev_id == 5) crci = DMOV_SDC5_CRCI; #endif else { host->dma.sg = NULL; host->dma.num_ents = 0; return -ENOENT; } if (data->flags & MMC_DATA_READ) host->dma.dir = DMA_FROM_DEVICE; else host->dma.dir = DMA_TO_DEVICE; /* host->curr.user_pages = (data->flags & MMC_DATA_USERPAGE); */ host->curr.user_pages = 0; box = &nc->cmd[0]; for (i = 0; i < host->dma.num_ents; i++) { box->cmd = CMD_MODE_BOX; /* Initialize sg dma address */ sg->dma_address = page_to_dma(mmc_dev(host->mmc), sg_page(sg)) + sg->offset; if (i == (host->dma.num_ents - 1)) box->cmd |= CMD_LC; rows = (sg_dma_len(sg) % MCI_FIFOSIZE) ? (sg_dma_len(sg) / MCI_FIFOSIZE) + 1 : (sg_dma_len(sg) / MCI_FIFOSIZE) ; if (data->flags & MMC_DATA_READ) { box->src_row_addr = msmsdcc_fifo_addr(host); box->dst_row_addr = sg_dma_address(sg); box->src_dst_len = (MCI_FIFOSIZE << 16) | (MCI_FIFOSIZE); box->row_offset = MCI_FIFOSIZE; box->num_rows = rows * ((1 << 16) + 1); box->cmd |= CMD_SRC_CRCI(crci); } else { box->src_row_addr = sg_dma_address(sg); box->dst_row_addr = msmsdcc_fifo_addr(host); box->src_dst_len = (MCI_FIFOSIZE << 16) | (MCI_FIFOSIZE); box->row_offset = (MCI_FIFOSIZE << 16); box->num_rows = rows * ((1 << 16) + 1); box->cmd |= CMD_DST_CRCI(crci); } box++; sg++; } /* location of command block must be 64 bit aligned */ BUG_ON(host->dma.cmd_busaddr & 0x07); nc->cmdptr = (host->dma.cmd_busaddr >> 3) | CMD_PTR_LP; host->dma.hdr.cmdptr = DMOV_CMD_PTR_LIST | DMOV_CMD_ADDR(host->dma.cmdptr_busaddr); host->dma.hdr.complete_func = msmsdcc_dma_complete_func; host->dma.hdr.crci_mask = msm_dmov_build_crci_mask(1, crci); n = dma_map_sg(mmc_dev(host->mmc), host->dma.sg, host->dma.num_ents, host->dma.dir); /* dsb inside dma_map_sg will write nc out to mem as well */ if (n != host->dma.num_ents) { pr_err("%s: Unable to map in all sg elements\n", mmc_hostname(host->mmc)); host->dma.sg = NULL; host->dma.num_ents = 0; return -ENOMEM; } return 0; } static void msmsdcc_start_command_deferred(struct msmsdcc_host *host, struct mmc_command *cmd, u32 *c) { DBG(host, "op %02x arg %08x flags %08x\n", cmd->opcode, cmd->arg, cmd->flags); *c |= (cmd->opcode | MCI_CPSM_ENABLE); if (cmd->flags & MMC_RSP_PRESENT) { if (cmd->flags & MMC_RSP_136) *c |= MCI_CPSM_LONGRSP; *c |= MCI_CPSM_RESPONSE; } if (/*interrupt*/0) *c |= MCI_CPSM_INTERRUPT; if ((((cmd->opcode == 17) || (cmd->opcode == 18)) || ((cmd->opcode == 24) || (cmd->opcode == 25))) || (cmd->opcode == 53)) *c |= MCI_CSPM_DATCMD; if (host->prog_scan && (cmd->opcode == 12)) { *c |= MCI_CPSM_PROGENA; host->prog_enable = 1; } #ifdef CONFIG_MMC_MSM_PROG_DONE_SCAN if ((cmd->opcode == SD_IO_RW_DIRECT) && (host->prog_scan == 1)) { *c |= MCI_CPSM_PROGENA; host->prog_enable = 1; } #endif if (cmd == cmd->mrq->stop) *c |= MCI_CSPM_MCIABORT; if (host->curr.cmd != NULL) { pr_err("%s: Overlapping command requests\n", mmc_hostname(host->mmc)); } host->curr.cmd = cmd; } static void msmsdcc_start_data(struct msmsdcc_host *host, struct mmc_data *data, struct mmc_command *cmd, u32 c) { unsigned int datactrl, timeout; unsigned long long clks; void __iomem *base = host->base; unsigned int pio_irqmask = 0; host->curr.data = data; host->curr.xfer_size = data->blksz * data->blocks; host->curr.xfer_remain = host->curr.xfer_size; host->curr.data_xfered = 0; host->curr.got_dataend = 0; memset(&host->pio, 0, sizeof(host->pio)); datactrl = MCI_DPSM_ENABLE | (data->blksz << 4); if (!msmsdcc_config_dma(host, data)) datactrl |= MCI_DPSM_DMAENABLE; else { host->pio.sg = data->sg; host->pio.sg_len = data->sg_len; host->pio.sg_off = 0; if (data->flags & MMC_DATA_READ) { pio_irqmask = MCI_RXFIFOHALFFULLMASK; if (host->curr.xfer_remain < MCI_FIFOSIZE) pio_irqmask |= MCI_RXDATAAVLBLMASK; } else pio_irqmask = MCI_TXFIFOHALFEMPTYMASK; } if (data->flags & MMC_DATA_READ) datactrl |= MCI_DPSM_DIRECTION; clks = (unsigned long long)data->timeout_ns * host->clk_rate; do_div(clks, 1000000000UL); timeout = data->timeout_clks + (unsigned int)clks*2 ; if (datactrl & MCI_DPSM_DMAENABLE) { /* Save parameters for the exec function */ host->cmd_timeout = timeout; host->cmd_pio_irqmask = pio_irqmask; host->cmd_datactrl = datactrl; host->cmd_cmd = cmd; host->dma.hdr.exec_func = msmsdcc_dma_exec_func; host->dma.hdr.user = (void *)host; host->dma.busy = 1; if (cmd) { msmsdcc_start_command_deferred(host, cmd, &c); host->cmd_c = c; } dsb(); msm_dmov_enqueue_cmd_ext(host->dma.channel, &host->dma.hdr); if (data->flags & MMC_DATA_WRITE) host->prog_scan = 1; } else { writel(timeout, base + MMCIDATATIMER); writel(host->curr.xfer_size, base + MMCIDATALENGTH); writel((readl(host->base + MMCIMASK0) & (~(MCI_IRQ_PIO))) | pio_irqmask, host->base + MMCIMASK0); msmsdcc_delay(host); /* Allow parms to be applied */ writel(datactrl, base + MMCIDATACTRL); if (cmd) { msmsdcc_delay(host); /* Delay between data/command */ /* Daisy-chain the command if requested */ msmsdcc_start_command(host, cmd, c); } } } static void msmsdcc_start_command(struct msmsdcc_host *host, struct mmc_command *cmd, u32 c) { msmsdcc_start_command_deferred(host, cmd, &c); msmsdcc_start_command_exec(host, cmd->arg, c); } static void msmsdcc_data_err(struct msmsdcc_host *host, struct mmc_data *data, unsigned int status) { if (status & MCI_DATACRCFAIL) { if (!(data->mrq->cmd->opcode == MMC_BUSTEST_W || data->mrq->cmd->opcode == MMC_BUSTEST_R)) { pr_err("%s: Data CRC error\n", mmc_hostname(host->mmc)); pr_err("%s: opcode 0x%.8x\n", __func__, data->mrq->cmd->opcode); pr_err("%s: blksz %d, blocks %d\n", __func__, data->blksz, data->blocks); data->error = -EILSEQ; } } else if (status & MCI_DATATIMEOUT) { /* CRC is optional for the bus test commands, not all * cards respond back with CRC. However controller * waits for the CRC and times out. Hence ignore the * data timeouts during the Bustest. */ if (!(data->mrq->cmd->opcode == MMC_BUSTEST_W || data->mrq->cmd->opcode == MMC_BUSTEST_R)) { pr_err("%s: Data timeout\n", mmc_hostname(host->mmc)); data->error = -ETIMEDOUT; } } else if (status & MCI_RXOVERRUN) { pr_err("%s: RX overrun\n", mmc_hostname(host->mmc)); data->error = -EIO; } else if (status & MCI_TXUNDERRUN) { pr_err("%s: TX underrun\n", mmc_hostname(host->mmc)); data->error = -EIO; } else { pr_err("%s: Unknown error (0x%.8x)\n", mmc_hostname(host->mmc), status); data->error = -EIO; } } static int msmsdcc_pio_read(struct msmsdcc_host *host, char *buffer, unsigned int remain) { void __iomem *base = host->base; uint32_t *ptr = (uint32_t *) buffer; int count = 0; if (remain % 4) remain = ((remain >> 2) + 1) << 2; while (readl(base + MMCISTATUS) & MCI_RXDATAAVLBL) { *ptr = readl(base + MMCIFIFO + (count % MCI_FIFOSIZE)); ptr++; count += sizeof(uint32_t); remain -= sizeof(uint32_t); if (remain == 0) break; } return count; } static int msmsdcc_pio_write(struct msmsdcc_host *host, char *buffer, unsigned int remain, u32 status) { void __iomem *base = host->base; char *ptr = buffer; do { unsigned int count, maxcnt, sz; maxcnt = status & MCI_TXFIFOEMPTY ? MCI_FIFOSIZE : MCI_FIFOHALFSIZE; count = min(remain, maxcnt); sz = count % 4 ? (count >> 2) + 1 : (count >> 2); writesl(base + MMCIFIFO, ptr, sz); ptr += count; remain -= count; if (remain == 0) break; status = readl(base + MMCISTATUS); } while (status & MCI_TXFIFOHALFEMPTY); return ptr - buffer; } static irqreturn_t msmsdcc_pio_irq(int irq, void *dev_id) { struct msmsdcc_host *host = dev_id; void __iomem *base = host->base; uint32_t status; status = readl(base + MMCISTATUS); if (((readl(host->base + MMCIMASK0) & status) & (MCI_IRQ_PIO)) == 0) return IRQ_NONE; #if IRQ_DEBUG msmsdcc_print_status(host, "irq1-r", status); #endif spin_lock(&host->lock); do { unsigned long flags; unsigned int remain, len; char *buffer; if (!(status & (MCI_TXFIFOHALFEMPTY | MCI_RXDATAAVLBL))) break; /* Map the current scatter buffer */ local_irq_save(flags); buffer = kmap_atomic(sg_page(host->pio.sg), KM_BIO_SRC_IRQ) + host->pio.sg->offset; buffer += host->pio.sg_off; remain = host->pio.sg->length - host->pio.sg_off; len = 0; if (status & MCI_RXACTIVE) len = msmsdcc_pio_read(host, buffer, remain); if (status & MCI_TXACTIVE) len = msmsdcc_pio_write(host, buffer, remain, status); /* Unmap the buffer */ kunmap_atomic(buffer, KM_BIO_SRC_IRQ); local_irq_restore(flags); host->pio.sg_off += len; host->curr.xfer_remain -= len; host->curr.data_xfered += len; remain -= len; if (remain) /* Done with this page? */ break; /* Nope */ if (status & MCI_RXACTIVE && host->curr.user_pages) flush_dcache_page(sg_page(host->pio.sg)); if (!--host->pio.sg_len) { memset(&host->pio, 0, sizeof(host->pio)); break; } /* Advance to next sg */ host->pio.sg++; host->pio.sg_off = 0; status = readl(base + MMCISTATUS); } while (1); if (status & MCI_RXACTIVE && host->curr.xfer_remain < MCI_FIFOSIZE) { writel((readl(host->base + MMCIMASK0) & (~(MCI_IRQ_PIO))) | MCI_RXDATAAVLBLMASK, host->base + MMCIMASK0); if (!host->curr.xfer_remain) { /* Delay needed (same port was just written) */ msmsdcc_delay(host); writel((readl(host->base + MMCIMASK0) & (~(MCI_IRQ_PIO))) | 0, host->base + MMCIMASK0); } } else if (!host->curr.xfer_remain) writel((readl(host->base + MMCIMASK0) & (~(MCI_IRQ_PIO))) | 0, host->base + MMCIMASK0); spin_unlock(&host->lock); return IRQ_HANDLED; } static void msmsdcc_request_start(struct msmsdcc_host *host, struct mmc_request *mrq); static irqreturn_t msmsdcc_irq(int irq, void *dev_id) { struct msmsdcc_host *host = dev_id; void __iomem *base = host->base; u32 status; int ret = 0; int timer = 0; spin_lock(&host->lock); do { struct mmc_command *cmd; struct mmc_data *data; if (timer) { timer = 0; msmsdcc_delay(host); } if (!host->clks_on) { pr_info("%s: %s: SDIO async irq received\n", mmc_hostname(host->mmc), __func__); host->mmc->ios.clock = host->clk_rate; spin_unlock(&host->lock); host->mmc->ops->set_ios(host->mmc, &host->mmc->ios); spin_lock(&host->lock); if (host->plat->cfg_mpm_sdiowakeup && (host->mmc->pm_flags & MMC_PM_WAKE_SDIO_IRQ) && !host->sdio_irq_disabled) { host->sdio_irq_disabled = 1; wake_lock(&host->sdio_wlock); } /* only ansyc interrupt can come when clocks are off */ writel(MCI_SDIOINTMASK, host->base + MMCICLEAR); } status = readl(host->base + MMCISTATUS); if (((readl(host->base + MMCIMASK0) & status) & (~(MCI_IRQ_PIO))) == 0) break; #if IRQ_DEBUG msmsdcc_print_status(host, "irq0-r", status); #endif status &= readl(host->base + MMCIMASK0); writel(status, host->base + MMCICLEAR); #if IRQ_DEBUG msmsdcc_print_status(host, "irq0-p", status); #endif if ((host->plat->dummy52_required) && (host->dummy_52_state == DUMMY_52_STATE_SENT)) { if (status & MCI_PROGDONE) { host->dummy_52_state = DUMMY_52_STATE_NONE; host->curr.cmd = NULL; spin_unlock(&host->lock); msmsdcc_request_start(host, host->curr.mrq); return IRQ_HANDLED; } break; } data = host->curr.data; #ifdef CONFIG_MMC_MSM_SDIO_SUPPORT if (status & MCI_SDIOINTROPE) { if (host->sdcc_suspending) wake_lock(&host->sdio_suspend_wlock); mmc_signal_sdio_irq(host->mmc); } #endif /* * Check for proper command response */ cmd = host->curr.cmd; if ((status & (MCI_CMDSENT | MCI_CMDRESPEND | MCI_CMDCRCFAIL | MCI_CMDTIMEOUT | MCI_PROGDONE)) && cmd) { host->curr.cmd = NULL; cmd->resp[0] = readl(base + MMCIRESPONSE0); cmd->resp[1] = readl(base + MMCIRESPONSE1); cmd->resp[2] = readl(base + MMCIRESPONSE2); cmd->resp[3] = readl(base + MMCIRESPONSE3); if (status & MCI_CMDTIMEOUT) { #if VERBOSE_COMMAND_TIMEOUTS pr_err("%s: Command timeout\n", mmc_hostname(host->mmc)); #endif cmd->error = -ETIMEDOUT; } else if (status & MCI_CMDCRCFAIL && cmd->flags & MMC_RSP_CRC) { pr_err("%s: Command CRC error\n", mmc_hostname(host->mmc)); cmd->error = -EILSEQ; } if (!cmd->data || cmd->error) { if (host->curr.data && host->dma.sg) msm_dmov_stop_cmd(host->dma.channel, &host->dma.hdr, 0); else if (host->curr.data) { /* Non DMA */ msmsdcc_reset_and_restore(host); msmsdcc_stop_data(host); timer |= msmsdcc_request_end(host, cmd->mrq); } else { /* host->data == NULL */ if (!cmd->error && host->prog_enable) { if (status & MCI_PROGDONE) { host->prog_scan = 0; host->prog_enable = 0; timer |= msmsdcc_request_end( host, cmd->mrq); } else host->curr.cmd = cmd; } else { if (host->prog_enable) { host->prog_scan = 0; host->prog_enable = 0; } timer |= msmsdcc_request_end( host, cmd->mrq); } } } else if (cmd->data) { if (!(cmd->data->flags & MMC_DATA_READ)) msmsdcc_start_data(host, cmd->data, NULL, 0); } } if (data) { /* Check for data errors */ if (status & (MCI_DATACRCFAIL|MCI_DATATIMEOUT| MCI_TXUNDERRUN|MCI_RXOVERRUN)) { msmsdcc_data_err(host, data, status); host->curr.data_xfered = 0; if (host->dma.sg) msm_dmov_stop_cmd(host->dma.channel, &host->dma.hdr, 0); else { msmsdcc_reset_and_restore(host); if (host->curr.data) msmsdcc_stop_data(host); if (!data->stop) timer |= msmsdcc_request_end(host, data->mrq); else { msmsdcc_start_command(host, data->stop, 0); timer = 1; } } } /* Check for data done */ if (!host->curr.got_dataend && (status & MCI_DATAEND)) host->curr.got_dataend = 1; if (host->curr.got_dataend) { /* * If DMA is still in progress, we complete * via the completion handler */ if (!host->dma.busy) { /* * There appears to be an issue in the * controller where if you request a * small block transfer (< fifo size), * you may get your DATAEND/DATABLKEND * irq without the PIO data irq. * * Check to see if theres still data * to be read, and simulate a PIO irq. */ if (readl(host->base + MMCISTATUS) & MCI_RXDATAAVLBL) { spin_unlock(&host->lock); msmsdcc_pio_irq(1, host); spin_lock(&host->lock); } msmsdcc_stop_data(host); if (!data->error) host->curr.data_xfered = host->curr.xfer_size; if (!data->stop) timer |= msmsdcc_request_end( host, data->mrq); else { msmsdcc_start_command(host, data->stop, 0); timer = 1; } } } } ret = 1; } while (status); spin_unlock(&host->lock); return IRQ_RETVAL(ret); } static void msmsdcc_request_start(struct msmsdcc_host *host, struct mmc_request *mrq) { if (mrq->data && mrq->data->flags & MMC_DATA_READ) { /* Queue/read data, daisy-chain command when data starts */ msmsdcc_start_data(host, mrq->data, mrq->cmd, 0); } else { msmsdcc_start_command(host, mrq->cmd, 0); } } static void msmsdcc_request(struct mmc_host *mmc, struct mmc_request *mrq) { struct msmsdcc_host *host = mmc_priv(mmc); unsigned long flags; WARN_ON(host->curr.mrq != NULL); WARN_ON(host->pwr == 0); spin_lock_irqsave(&host->lock, flags); if (host->eject) { if (mrq->data && !(mrq->data->flags & MMC_DATA_READ)) { mrq->cmd->error = 0; mrq->data->bytes_xfered = mrq->data->blksz * mrq->data->blocks; } else mrq->cmd->error = -ENOMEDIUM; spin_unlock_irqrestore(&host->lock, flags); mmc_request_done(mmc, mrq); return; } host->curr.mrq = mrq; if (host->plat->dummy52_required) { if (host->dummy_52_needed) { if (mrq->data) { host->dummy_52_state = DUMMY_52_STATE_SENT; msmsdcc_start_command(host, &dummy52cmd, MCI_CPSM_PROGENA); spin_unlock_irqrestore(&host->lock, flags); return; } host->dummy_52_needed = 0; } if ((mrq->cmd->opcode == SD_IO_RW_EXTENDED) && (mrq->data)) host->dummy_52_needed = 1; } msmsdcc_request_start(host, mrq); spin_unlock_irqrestore(&host->lock, flags); } static inline int msmsdcc_is_pwrsave(struct msmsdcc_host *host) { if (host->clk_rate > 400000 && msmsdcc_pwrsave) return 1; return 0; } static void msmsdcc_set_ios(struct mmc_host *mmc, struct mmc_ios *ios) { struct msmsdcc_host *host = mmc_priv(mmc); u32 clk = 0, pwr = 0; int rc; unsigned long flags; DBG(host, "ios->clock = %u\n", ios->clock); if (ios->clock) { spin_lock_irqsave(&host->lock, flags); if (!host->clks_on) { if (!IS_ERR_OR_NULL(host->dfab_pclk)) clk_enable(host->dfab_pclk); if (!IS_ERR(host->pclk)) clk_enable(host->pclk); clk_enable(host->clk); host->clks_on = 1; if (mmc->card && mmc->card->type == MMC_TYPE_SDIO && !host->plat->sdiowakeup_irq) { writel(host->mci_irqenable, host->base + MMCIMASK0); if (host->plat->cfg_mpm_sdiowakeup && (mmc->pm_flags & MMC_PM_WAKE_SDIO_IRQ)) host->plat->cfg_mpm_sdiowakeup( mmc_dev(mmc), 0); disable_irq_wake(host->irqres->start); } } spin_unlock_irqrestore(&host->lock, flags); if ((ios->clock < host->plat->msmsdcc_fmax) && (ios->clock > host->plat->msmsdcc_fmid)) ios->clock = host->plat->msmsdcc_fmid; if (ios->clock != host->clk_rate) { rc = clk_set_rate(host->clk, ios->clock); WARN_ON(rc < 0); host->clk_rate = ios->clock; } /* * give atleast 2 MCLK cycles delay for clocks * and SDCC core to stabilize */ msmsdcc_delay(host); clk |= MCI_CLK_ENABLE; } if (ios->bus_width == MMC_BUS_WIDTH_8) clk |= MCI_CLK_WIDEBUS_8; else if (ios->bus_width == MMC_BUS_WIDTH_4) clk |= MCI_CLK_WIDEBUS_4; else clk |= MCI_CLK_WIDEBUS_1; if (msmsdcc_is_pwrsave(host)) clk |= MCI_CLK_PWRSAVE; clk |= MCI_CLK_FLOWENA; clk |= MCI_CLK_SELECTIN; /* feedback clock */ if (host->plat->translate_vdd) pwr |= host->plat->translate_vdd(mmc_dev(mmc), ios->vdd); switch (ios->power_mode) { case MMC_POWER_OFF: htc_pwrsink_set(PWRSINK_SDCARD, 0); if (!host->sdcc_irq_disabled) { disable_irq(host->irqres->start); host->sdcc_irq_disabled = 1; } break; case MMC_POWER_UP: pwr |= MCI_PWR_UP; if (host->sdcc_irq_disabled) { enable_irq(host->irqres->start); host->sdcc_irq_disabled = 0; } break; case MMC_POWER_ON: htc_pwrsink_set(PWRSINK_SDCARD, 100); pwr |= MCI_PWR_ON; break; } writel(clk, host->base + MMCICLOCK); udelay(50); if (host->pwr != pwr) { host->pwr = pwr; writel(pwr, host->base + MMCIPOWER); } spin_lock_irqsave(&host->lock, flags); if (!(clk & MCI_CLK_ENABLE) && host->clks_on) { if (mmc->card && mmc->card->type == MMC_TYPE_SDIO && !host->plat->sdiowakeup_irq) { writel(MCI_SDIOINTMASK, host->base + MMCIMASK0); WARN_ON(host->sdcc_irq_disabled); if (host->plat->cfg_mpm_sdiowakeup && (mmc->pm_flags & MMC_PM_WAKE_SDIO_IRQ)) host->plat->cfg_mpm_sdiowakeup( mmc_dev(mmc), 1); enable_irq_wake(host->irqres->start); } clk_disable(host->clk); if (!IS_ERR(host->pclk)) clk_disable(host->pclk); if (!IS_ERR_OR_NULL(host->dfab_pclk)) clk_disable(host->dfab_pclk); host->clks_on = 0; } spin_unlock_irqrestore(&host->lock, flags); } int msmsdcc_set_pwrsave(struct mmc_host *mmc, int pwrsave) { struct msmsdcc_host *host = mmc_priv(mmc); u32 clk; clk = readl(host->base + MMCICLOCK); pr_debug("Changing to pwr_save=%d", pwrsave); if (pwrsave && msmsdcc_is_pwrsave(host)) clk |= MCI_CLK_PWRSAVE; else clk &= ~MCI_CLK_PWRSAVE; writel(clk, host->base + MMCICLOCK); return 0; } static int msmsdcc_get_ro(struct mmc_host *mmc) { int wpswitch_status = -ENOSYS; struct msmsdcc_host *host = mmc_priv(mmc); if (host->plat->wpswitch) { wpswitch_status = host->plat->wpswitch(mmc_dev(mmc)); if (wpswitch_status < 0) wpswitch_status = -ENOSYS; } pr_debug("%s: Card read-only status %d\n", __func__, wpswitch_status); return wpswitch_status; } #ifdef CONFIG_MMC_MSM_SDIO_SUPPORT static void msmsdcc_enable_sdio_irq(struct mmc_host *mmc, int enable) { struct msmsdcc_host *host = mmc_priv(mmc); if (enable) { host->mci_irqenable |= MCI_SDIOINTOPERMASK; writel(readl(host->base + MMCIMASK0) | MCI_SDIOINTOPERMASK, host->base + MMCIMASK0); } else { host->mci_irqenable &= ~MCI_SDIOINTOPERMASK; writel(readl(host->base + MMCIMASK0) & ~MCI_SDIOINTOPERMASK, host->base + MMCIMASK0); } } #endif /* CONFIG_MMC_MSM_SDIO_SUPPORT */ #ifdef CONFIG_PM_RUNTIME static int msmsdcc_enable(struct mmc_host *mmc) { int rc; struct device *dev = mmc->parent; if (atomic_read(&dev->power.usage_count) > 0) { pm_runtime_get_noresume(dev); goto out; } rc = pm_runtime_get_sync(dev); if (rc < 0) { pr_info("%s: %s: failed with error %d", mmc_hostname(mmc), __func__, rc); return rc; } out: return 0; } static int msmsdcc_disable(struct mmc_host *mmc, int lazy) { int rc; if (mmc->card && mmc->card->type == MMC_TYPE_SDIO) return -ENOTSUPP; rc = pm_runtime_put_sync(mmc->parent); if (rc < 0) pr_info("%s: %s: failed with error %d", mmc_hostname(mmc), __func__, rc); return rc; } #else #define msmsdcc_enable NULL #define msmsdcc_disable NULL #endif static const struct mmc_host_ops msmsdcc_ops = { .enable = msmsdcc_enable, .disable = msmsdcc_disable, .request = msmsdcc_request, .set_ios = msmsdcc_set_ios, .get_ro = msmsdcc_get_ro, #ifdef CONFIG_MMC_MSM_SDIO_SUPPORT .enable_sdio_irq = msmsdcc_enable_sdio_irq, #endif }; static void msmsdcc_check_status(unsigned long data) { struct msmsdcc_host *host = (struct msmsdcc_host *)data; unsigned int status; if (!host->plat->status) { mmc_detect_change(host->mmc, 0); goto out; } status = host->plat->status(mmc_dev(host->mmc)); host->eject = !status; if (status ^ host->oldstat) { pr_info("%s: Slot status change detected (%d -> %d)\n", mmc_hostname(host->mmc), host->oldstat, status); if (status) mmc_detect_change(host->mmc, (5 * HZ) / 2); else mmc_detect_change(host->mmc, 0); } host->oldstat = status; out: if (host->timer.function) mod_timer(&host->timer, jiffies + HZ); } static irqreturn_t msmsdcc_platform_status_irq(int irq, void *dev_id) { struct msmsdcc_host *host = dev_id; pr_debug("%s: %d\n", __func__, irq); msmsdcc_check_status((unsigned long) host); return IRQ_HANDLED; } static irqreturn_t msmsdcc_platform_sdiowakeup_irq(int irq, void *dev_id) { struct msmsdcc_host *host = dev_id; pr_info("%s: SDIO Wake up IRQ : %d\n", __func__, irq); spin_lock(&host->lock); if (!host->sdio_irq_disabled) { wake_lock(&host->sdio_wlock); disable_irq_nosync(irq); disable_irq_wake(irq); host->sdio_irq_disabled = 1; } spin_unlock(&host->lock); return IRQ_HANDLED; } static void msmsdcc_status_notify_cb(int card_present, void *dev_id) { struct msmsdcc_host *host = dev_id; pr_debug("%s: card_present %d\n", mmc_hostname(host->mmc), card_present); msmsdcc_check_status((unsigned long) host); } static int msmsdcc_init_dma(struct msmsdcc_host *host) { memset(&host->dma, 0, sizeof(struct msmsdcc_dma_data)); host->dma.host = host; host->dma.channel = -1; if (!host->dmares) return -ENODEV; host->dma.nc = dma_alloc_coherent(NULL, sizeof(struct msmsdcc_nc_dmadata), &host->dma.nc_busaddr, GFP_KERNEL); if (host->dma.nc == NULL) { pr_err("Unable to allocate DMA buffer\n"); return -ENOMEM; } memset(host->dma.nc, 0x00, sizeof(struct msmsdcc_nc_dmadata)); host->dma.cmd_busaddr = host->dma.nc_busaddr; host->dma.cmdptr_busaddr = host->dma.nc_busaddr + offsetof(struct msmsdcc_nc_dmadata, cmdptr); host->dma.channel = host->dmares->start; return 0; } static ssize_t show_polling(struct device *dev, struct device_attribute *attr, char *buf) { struct mmc_host *mmc = dev_get_drvdata(dev); struct msmsdcc_host *host = mmc_priv(mmc); int poll; unsigned long flags; spin_lock_irqsave(&host->lock, flags); poll = !!(mmc->caps & MMC_CAP_NEEDS_POLL); spin_unlock_irqrestore(&host->lock, flags); return snprintf(buf, PAGE_SIZE, "%d\n", poll); } static ssize_t set_polling(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct mmc_host *mmc = dev_get_drvdata(dev); struct msmsdcc_host *host = mmc_priv(mmc); int value; unsigned long flags; sscanf(buf, "%d", &value); spin_lock_irqsave(&host->lock, flags); if (value) { mmc->caps |= MMC_CAP_NEEDS_POLL; mmc_detect_change(host->mmc, 0); } else { mmc->caps &= ~MMC_CAP_NEEDS_POLL; } #ifdef CONFIG_HAS_EARLYSUSPEND host->polling_enabled = mmc->caps & MMC_CAP_NEEDS_POLL; #endif spin_unlock_irqrestore(&host->lock, flags); return count; } static DEVICE_ATTR(polling, 0664, show_polling, set_polling); static struct attribute *dev_attrs[] = { &dev_attr_polling.attr, NULL, }; static struct attribute_group dev_attr_grp = { .attrs = dev_attrs, }; #ifdef CONFIG_HAS_EARLYSUSPEND static void msmsdcc_early_suspend(struct early_suspend *h) { struct msmsdcc_host *host = container_of(h, struct msmsdcc_host, early_suspend); unsigned long flags; spin_lock_irqsave(&host->lock, flags); host->polling_enabled = host->mmc->caps & MMC_CAP_NEEDS_POLL; host->mmc->caps &= ~MMC_CAP_NEEDS_POLL; spin_unlock_irqrestore(&host->lock, flags); }; static void msmsdcc_late_resume(struct early_suspend *h) { struct msmsdcc_host *host = container_of(h, struct msmsdcc_host, early_suspend); unsigned long flags; if (host->polling_enabled) { spin_lock_irqsave(&host->lock, flags); host->mmc->caps |= MMC_CAP_NEEDS_POLL; mmc_detect_change(host->mmc, 0); spin_unlock_irqrestore(&host->lock, flags); } }; #endif static int msmsdcc_probe(struct platform_device *pdev) { struct mmc_platform_data *plat = pdev->dev.platform_data; struct msmsdcc_host *host; struct mmc_host *mmc; struct resource *irqres = NULL; struct resource *memres = NULL; struct resource *dmares = NULL; int ret; int i; int rc = 0; /* must have platform data */ if (!plat) { pr_err("%s: Platform data not available\n", __func__); ret = -EINVAL; goto out; } if (pdev->id < 1 || pdev->id > 5) return -EINVAL; if (pdev->resource == NULL || pdev->num_resources < 3) { pr_err("%s: Invalid resource\n", __func__); return -ENXIO; } for (i = 0; i < pdev->num_resources; i++) { if (pdev->resource[i].flags & IORESOURCE_MEM) memres = &pdev->resource[i]; if (pdev->resource[i].flags & IORESOURCE_IRQ) irqres = &pdev->resource[i]; if (pdev->resource[i].flags & IORESOURCE_DMA) dmares = &pdev->resource[i]; } if (!irqres || !memres) { pr_err("%s: Invalid resource\n", __func__); return -ENXIO; } /* * Setup our host structure */ mmc = mmc_alloc_host(sizeof(struct msmsdcc_host), &pdev->dev); if (!mmc) { ret = -ENOMEM; goto out; } host = mmc_priv(mmc); host->pdev_id = pdev->id; host->plat = plat; host->mmc = mmc; host->curr.cmd = NULL; host->base = ioremap(memres->start, PAGE_SIZE); if (!host->base) { ret = -ENOMEM; goto host_free; } host->irqres = irqres; host->memres = memres; host->dmares = dmares; spin_lock_init(&host->lock); #ifdef CONFIG_MMC_EMBEDDED_SDIO if (plat->embedded_sdio) mmc_set_embedded_sdio_data(mmc, &plat->embedded_sdio->cis, &plat->embedded_sdio->cccr, plat->embedded_sdio->funcs, plat->embedded_sdio->num_funcs); #endif tasklet_init(&host->dma_tlet, msmsdcc_dma_complete_tlet, (unsigned long)host); /* * Setup DMA */ ret = msmsdcc_init_dma(host); if (ret) goto ioremap_free; /* * Setup SDCC clock if derived from Dayatona * fabric core clock. */ if (plat->pclk_src_dfab) { host->dfab_pclk = clk_get(&pdev->dev, "dfab_sdc_clk"); if (!IS_ERR(host->dfab_pclk)) { /* Set the clock rate to 64MHz for max. performance */ ret = clk_set_rate(host->dfab_pclk, 64000000); if (ret) goto dfab_pclk_put; ret = clk_enable(host->dfab_pclk); if (ret) goto dfab_pclk_put; } else goto dma_free; } /* * Setup main peripheral bus clock */ host->pclk = clk_get(&pdev->dev, "sdc_pclk"); if (!IS_ERR(host->pclk)) { ret = clk_enable(host->pclk); if (ret) goto pclk_put; host->pclk_rate = clk_get_rate(host->pclk); } /* * Setup SDC MMC clock */ host->clk = clk_get(&pdev->dev, "sdc_clk"); if (IS_ERR(host->clk)) { ret = PTR_ERR(host->clk); goto pclk_disable; } ret = clk_set_rate(host->clk, plat->msmsdcc_fmin); if (ret) { pr_err("%s: Clock rate set failed (%d)\n", __func__, ret); goto clk_put; } ret = clk_enable(host->clk); if (ret) goto clk_put; host->clk_rate = clk_get_rate(host->clk); host->clks_on = 1; /* * Setup MMC host structure */ mmc->ops = &msmsdcc_ops; mmc->f_min = plat->msmsdcc_fmin; mmc->f_max = plat->msmsdcc_fmax; mmc->ocr_avail = plat->ocr_mask; mmc->pm_caps |= MMC_PM_KEEP_POWER; mmc->caps |= plat->mmc_bus_width; mmc->caps |= MMC_CAP_MMC_HIGHSPEED | MMC_CAP_SD_HIGHSPEED; if (plat->nonremovable) mmc->caps |= MMC_CAP_NONREMOVABLE; #ifdef CONFIG_MMC_MSM_SDIO_SUPPORT mmc->caps |= MMC_CAP_SDIO_IRQ; #endif mmc->max_phys_segs = NR_SG; mmc->max_hw_segs = NR_SG; mmc->max_blk_size = 4096; /* MCI_DATA_CTL BLOCKSIZE up to 4096 */ mmc->max_blk_count = 65536; mmc->max_req_size = 33554432; /* MCI_DATA_LENGTH is 25 bits */ mmc->max_seg_size = mmc->max_req_size; writel(0, host->base + MMCIMASK0); writel(MCI_CLEAR_STATIC_MASK, host->base + MMCICLEAR); /* Delay needed (MMCIMASK0 was just written above) */ msmsdcc_delay(host); writel(MCI_IRQENABLE, host->base + MMCIMASK0); host->mci_irqenable = MCI_IRQENABLE; ret = request_irq(irqres->start, msmsdcc_irq, IRQF_SHARED, DRIVER_NAME " (cmd)", host); if (ret) goto clk_disable; ret = request_irq(irqres->start, msmsdcc_pio_irq, IRQF_SHARED, DRIVER_NAME " (pio)", host); if (ret) goto irq_free; /* * Enable SDCC IRQ only when host is powered on. Otherwise, this * IRQ is un-necessarily being monitored by MPM (Modem power * management block) during idle-power collapse. The MPM will be * configured to monitor the DATA1 GPIO line with level-low trigger * and thus depending on the GPIO status, it prevents TCXO shutdown * during idle-power collapse. */ disable_irq(irqres->start); host->sdcc_irq_disabled = 1; memset(&host->timer, 0, sizeof(host->timer)); if (plat->sdiowakeup_irq) { ret = request_irq(plat->sdiowakeup_irq, msmsdcc_platform_sdiowakeup_irq, IRQF_SHARED | IRQF_TRIGGER_LOW, DRIVER_NAME "sdiowakeup", host); if (ret) { pr_err("Unable to get sdio wakeup IRQ %d (%d)\n", plat->sdiowakeup_irq, ret); goto pio_irq_free; } else { mmc->pm_caps |= MMC_PM_WAKE_SDIO_IRQ; disable_irq(plat->sdiowakeup_irq); wake_lock_init(&host->sdio_wlock, WAKE_LOCK_SUSPEND, mmc_hostname(mmc)); } } if (plat->cfg_mpm_sdiowakeup) { wake_lock_init(&host->sdio_wlock, WAKE_LOCK_SUSPEND, mmc_hostname(mmc)); mmc->pm_caps |= MMC_PM_WAKE_SDIO_IRQ; } wake_lock_init(&host->sdio_suspend_wlock, WAKE_LOCK_SUSPEND, mmc_hostname(mmc)); /* * Setup card detect change */ if (plat->status) { host->oldstat = plat->status(mmc_dev(host->mmc)); host->eject = !host->oldstat; } if (plat->status_irq) { ret = request_threaded_irq(plat->status_irq, NULL, msmsdcc_platform_status_irq, plat->irq_flags, DRIVER_NAME " (slot)", host); if (ret) { pr_err("Unable to get slot IRQ %d (%d)\n", plat->status_irq, ret); goto sdiowakeup_irq_free; } } else if (plat->register_status_notify) { plat->register_status_notify(msmsdcc_status_notify_cb, host); } else if (!plat->status) pr_err("%s: No card detect facilities available\n", mmc_hostname(mmc)); else { init_timer(&host->timer); host->timer.data = (unsigned long)host; host->timer.function = msmsdcc_check_status; host->timer.expires = jiffies + HZ; add_timer(&host->timer); } mmc_set_drvdata(pdev, mmc); ret = pm_runtime_set_active(&(pdev)->dev); if (ret < 0) pr_info("%s: %s: failed with error %d", mmc_hostname(mmc), __func__, ret); /* * There is no notion of suspend/resume for SD/MMC/SDIO * cards. So host can be suspended/resumed with out * worrying about its children. */ pm_suspend_ignore_children(&(pdev)->dev, true); /* * MMC/SD/SDIO bus suspend/resume operations are defined * only for the slots that will be used for non-removable * media or for all slots when CONFIG_MMC_UNSAFE_RESUME is * defined. Otherwise, they simply become card removal and * insertion events during suspend and resume respectively. * Hence, enable run-time PM only for slots for which bus * suspend/resume operations are defined. */ #ifdef CONFIG_MMC_UNSAFE_RESUME /* * If this capability is set, MMC core will enable/disable host * for every claim/release operation on a host. We use this * notification to increment/decrement runtime pm usage count. */ mmc->caps |= MMC_CAP_DISABLE; pm_runtime_enable(&(pdev)->dev); #else if (mmc->caps & MMC_CAP_NONREMOVABLE) { mmc->caps |= MMC_CAP_DISABLE; pm_runtime_enable(&(pdev)->dev); } #endif mmc_add_host(mmc); #ifdef CONFIG_HAS_EARLYSUSPEND host->early_suspend.suspend = msmsdcc_early_suspend; host->early_suspend.resume = msmsdcc_late_resume; host->early_suspend.level = EARLY_SUSPEND_LEVEL_DISABLE_FB; register_early_suspend(&host->early_suspend); #endif if(pdev->id == 4) { if(gpio_get_value(nT_FLASH_DET)) { rc = pm8058_gpio_config(24, &sd_pwr_en_n_1); //SD_PWR_EN if (rc) { pr_err("%s PMIC_GPIO_SD_PWR_EN_N config failed\n", __func__); return rc; } gpio_set_value_cansleep(PM8058_GPIO_PM_TO_SYS(24), 1); //Low Active } else { rc = pm8058_gpio_config(24, &sd_pwr_en_n_1); //SD_PWR_EN if (rc) { pr_err("%s PMIC_GPIO_SD_PWR_EN_N config failed\n", __func__); return rc; } gpio_set_value_cansleep(PM8058_GPIO_PM_TO_SYS(24), 0); //Low Active } } pr_info("%s: Qualcomm MSM SDCC at 0x%016llx irq %d,%d dma %d\n", mmc_hostname(mmc), (unsigned long long)memres->start, (unsigned int) irqres->start, (unsigned int) plat->status_irq, host->dma.channel); pr_info("%s: 8 bit data mode %s\n", mmc_hostname(mmc), (mmc->caps & MMC_CAP_8_BIT_DATA ? "enabled" : "disabled")); pr_info("%s: 4 bit data mode %s\n", mmc_hostname(mmc), (mmc->caps & MMC_CAP_4_BIT_DATA ? "enabled" : "disabled")); pr_info("%s: polling status mode %s\n", mmc_hostname(mmc), (mmc->caps & MMC_CAP_NEEDS_POLL ? "enabled" : "disabled")); pr_info("%s: MMC clock %u -> %u Hz, PCLK %u Hz\n", mmc_hostname(mmc), plat->msmsdcc_fmin, plat->msmsdcc_fmax, host->pclk_rate); pr_info("%s: Slot eject status = %d\n", mmc_hostname(mmc), host->eject); if (strcmp(mmc_hostname(mmc), "mmc2")==0){ external_sd_status = host->eject; pr_info("%s: external_sd_status = %d\n", mmc_hostname(mmc), host->eject); } pr_info("%s: Power save feature enable = %d\n", mmc_hostname(mmc), msmsdcc_pwrsave); if (host->dma.channel != -1) { pr_info("%s: DM non-cached buffer at %p, dma_addr 0x%.8x\n", mmc_hostname(mmc), host->dma.nc, host->dma.nc_busaddr); pr_info("%s: DM cmd busaddr 0x%.8x, cmdptr busaddr 0x%.8x\n", mmc_hostname(mmc), host->dma.cmd_busaddr, host->dma.cmdptr_busaddr); } else pr_info("%s: PIO transfer enabled\n", mmc_hostname(mmc)); if (host->timer.function) pr_info("%s: Polling status mode enabled\n", mmc_hostname(mmc)); #if defined(CONFIG_DEBUG_FS) msmsdcc_dbg_createhost(host); #endif if (!plat->status_irq) { ret = sysfs_create_group(&pdev->dev.kobj, &dev_attr_grp); if (ret) goto platform_irq_free; } return 0; platform_irq_free: pm_runtime_disable(&(pdev)->dev); pm_runtime_set_suspended(&(pdev)->dev); if (plat->status_irq) free_irq(plat->status_irq, host); sdiowakeup_irq_free: wake_lock_destroy(&host->sdio_suspend_wlock); if (plat->sdiowakeup_irq) { wake_lock_destroy(&host->sdio_wlock); free_irq(plat->sdiowakeup_irq, host); } pio_irq_free: free_irq(irqres->start, host); irq_free: free_irq(irqres->start, host); clk_disable: clk_disable(host->clk); clk_put: clk_put(host->clk); pclk_disable: if (!IS_ERR(host->pclk)) clk_disable(host->pclk); pclk_put: if (!IS_ERR(host->pclk)) clk_put(host->pclk); if (!IS_ERR_OR_NULL(host->dfab_pclk)) clk_disable(host->dfab_pclk); dfab_pclk_put: if (!IS_ERR_OR_NULL(host->dfab_pclk)) clk_put(host->dfab_pclk); dma_free: dma_free_coherent(NULL, sizeof(struct msmsdcc_nc_dmadata), host->dma.nc, host->dma.nc_busaddr); ioremap_free: iounmap(host->base); host_free: mmc_free_host(mmc); out: return ret; } static int msmsdcc_remove(struct platform_device *pdev) { struct mmc_host *mmc = mmc_get_drvdata(pdev); struct mmc_platform_data *plat; struct msmsdcc_host *host; if (!mmc) return -ENXIO; if (pm_runtime_suspended(&(pdev)->dev)) pm_runtime_resume(&(pdev)->dev); host = mmc_priv(mmc); DBG(host, "Removing SDCC2 device = %d\n", pdev->id); plat = host->plat; if (!plat->status_irq) sysfs_remove_group(&pdev->dev.kobj, &dev_attr_grp); tasklet_kill(&host->dma_tlet); mmc_remove_host(mmc); if (plat->status_irq) free_irq(plat->status_irq, host); wake_lock_destroy(&host->sdio_suspend_wlock); if (plat->sdiowakeup_irq) { wake_lock_destroy(&host->sdio_wlock); set_irq_wake(plat->sdiowakeup_irq, 0); free_irq(plat->sdiowakeup_irq, host); } free_irq(host->irqres->start, host); free_irq(host->irqres->start, host); clk_put(host->clk); if (!IS_ERR(host->pclk)) clk_put(host->pclk); if (!IS_ERR_OR_NULL(host->dfab_pclk)) clk_put(host->dfab_pclk); dma_free_coherent(NULL, sizeof(struct msmsdcc_nc_dmadata), host->dma.nc, host->dma.nc_busaddr); iounmap(host->base); mmc_free_host(mmc); #ifdef CONFIG_HAS_EARLYSUSPEND unregister_early_suspend(&host->early_suspend); #endif pm_runtime_disable(&(pdev)->dev); pm_runtime_set_suspended(&(pdev)->dev); return 0; } #ifdef CONFIG_PM #define WLAN_nRST 127 static int msmsdcc_runtime_suspend(struct device *dev) { struct mmc_host *mmc = dev_get_drvdata(dev); struct msmsdcc_host *host = mmc_priv(mmc); unsigned long flags; int rc = 0; #if 1 if((host->pdev_id == 1) && (gpio_get_value(WLAN_nRST))) { printk("SDCC CH 0 : msmsdcc_runtime_suspend WLAN SKIP Suspend \n"); spin_lock_irqsave(&host->lock, flags); writel(0, host->base + MMCIMASK0); if (host->clks_on) { clk_disable(host->clk); if (!IS_ERR(host->pclk)) clk_disable(host->pclk); host->clks_on = 0; } spin_unlock_irqrestore(&host->lock, flags); return 0; } if(host->pdev_id == 4) { rc = pm8058_gpio_config(24, &sd_pwr_en_n_1); //SD_PWR_EN if (rc) { pr_err("%s PMIC_GPIO_SD_PWR_EN_N config failed\n", __func__); return rc; } gpio_set_value_cansleep(PM8058_GPIO_PM_TO_SYS(24), 1); //HIGH } #endif if (mmc) { host->sdcc_suspending = 1; mmc->suspend_task = current; /* * MMC core thinks that host is disabled by now since * runtime suspend is scheduled after msmsdcc_disable() * is called. Thus, MMC core will try to enable the host * while suspending it. This results in a synchronous * runtime resume request while in runtime suspending * context and hence inorder to complete this resume * requet, it will wait for suspend to be complete, * but runtime suspend also can not proceed further * until the host is resumed. Thus, it leads to a hang. * Hence, increase the pm usage count before suspending * the host so that any resume requests after this will * simple become pm usage counter increment operations. */ pm_runtime_get_noresume(dev); rc = mmc_suspend_host(mmc); pm_runtime_put_noidle(dev); if (!rc) { /* * If MMC core level suspend is not supported, turn * off clocks to allow deep sleep (TCXO shutdown). */ mmc->ios.clock = 0; mmc->ops->set_ios(host->mmc, &host->mmc->ios); } if (mmc->card && (mmc->card->type == MMC_TYPE_SDIO) && (mmc->pm_flags & MMC_PM_WAKE_SDIO_IRQ)) { host->sdio_irq_disabled = 0; if (host->plat->sdiowakeup_irq) { enable_irq_wake(host->plat->sdiowakeup_irq); enable_irq(host->plat->sdiowakeup_irq); } } host->sdcc_suspending = 0; mmc->suspend_task = NULL; } return rc; } static int msmsdcc_runtime_resume(struct device *dev) { struct mmc_host *mmc = dev_get_drvdata(dev); struct msmsdcc_host *host = mmc_priv(mmc); unsigned long flags; int release_lock = 0; int rc =0; if((host->pdev_id == 1) && (gpio_get_value(WLAN_nRST))) { printk("SDCC CH 0 : msmsdcc_runtime_resume WLAN SKIP Resume \n"); spin_lock_irqsave(&host->lock, flags); if (!host->clks_on) { if (!IS_ERR_OR_NULL(host->dfab_pclk)) clk_enable(host->dfab_pclk); if (!IS_ERR(host->pclk)) clk_enable(host->pclk); clk_enable(host->clk); host->clks_on = 1; } writel(host->mci_irqenable, host->base + MMCIMASK0); spin_unlock_irqrestore(&host->lock, flags); return 0; } if(host->pdev_id == 4) { if(gpio_get_value(nT_FLASH_DET)) { rc = pm8058_gpio_config(24, &sd_pwr_en_n_1); //SD_PWR_EN if (rc) { pr_err("%s PMIC_GPIO_SD_PWR_EN_N config failed\n", __func__); return rc; } gpio_set_value_cansleep(PM8058_GPIO_PM_TO_SYS(24), 1); //Low Active } else { rc = pm8058_gpio_config(24, &sd_pwr_en_n_1); //SD_PWR_EN if (rc) { pr_err("%s PMIC_GPIO_SD_PWR_EN_N config failed\n", __func__); return rc; } gpio_set_value_cansleep(PM8058_GPIO_PM_TO_SYS(24), 0); //Low Active } } if (mmc) { mmc->ios.clock = host->clk_rate; mmc->ops->set_ios(host->mmc, &host->mmc->ios); spin_lock_irqsave(&host->lock, flags); writel(host->mci_irqenable, host->base + MMCIMASK0); if (mmc->card && (mmc->card->type == MMC_TYPE_SDIO) && (mmc->pm_flags & MMC_PM_WAKE_SDIO_IRQ) && !host->sdio_irq_disabled) { if (host->plat->sdiowakeup_irq) { disable_irq_nosync( host->plat->sdiowakeup_irq); disable_irq_wake( host->plat->sdiowakeup_irq); } host->sdio_irq_disabled = 1; } else { release_lock = 1; } spin_unlock_irqrestore(&host->lock, flags); mmc_resume_host(mmc); /* * After resuming the host wait for sometime so that * the SDIO work will be processed. */ if ((mmc->pm_flags & MMC_PM_WAKE_SDIO_IRQ) && release_lock) wake_lock_timeout(&host->sdio_wlock, 1); wake_unlock(&host->sdio_suspend_wlock); } return 0; } static int msmsdcc_runtime_idle(struct device *dev) { /* Idle timeout is not configurable for now */ pm_schedule_suspend(dev, MSM_MMC_IDLE_TIMEOUT); return -EAGAIN; } static int msmsdcc_pm_suspend(struct device *dev) { struct mmc_host *mmc = dev_get_drvdata(dev); struct msmsdcc_host *host = mmc_priv(mmc); int rc = 0; if (host->plat->status_irq) disable_irq(host->plat->status_irq); if (!pm_runtime_suspended(dev)) rc = msmsdcc_runtime_suspend(dev); return rc; } static int msmsdcc_pm_resume(struct device *dev) { struct mmc_host *mmc = dev_get_drvdata(dev); struct msmsdcc_host *host = mmc_priv(mmc); int rc = 0; rc = msmsdcc_runtime_resume(dev); if (host->plat->status_irq) enable_irq(host->plat->status_irq); /* Update the run-time PM status */ pm_runtime_disable(dev); rc = pm_runtime_set_active(dev); if (rc < 0) pr_info("%s: %s: failed with error %d", mmc_hostname(mmc), __func__, rc); pm_runtime_enable(dev); return rc; } #else #define msmsdcc_runtime_suspend NULL #define msmsdcc_runtime_resume NULL #define msmsdcc_runtime_idle NULL #define msmsdcc_pm_suspend NULL #define msmsdcc_pm_resume NULL #endif static const struct dev_pm_ops msmsdcc_dev_pm_ops = { .runtime_suspend = msmsdcc_runtime_suspend, .runtime_resume = msmsdcc_runtime_resume, .runtime_idle = msmsdcc_runtime_idle, .suspend = msmsdcc_pm_suspend, .resume = msmsdcc_pm_resume, }; static struct platform_driver msmsdcc_driver = { .probe = msmsdcc_probe, .remove = msmsdcc_remove, .driver = { .name = "msm_sdcc", .pm = &msmsdcc_dev_pm_ops, }, }; static int __init msmsdcc_init(void) { #if defined(CONFIG_DEBUG_FS) int ret = 0; ret = msmsdcc_dbg_init(); if (ret) { pr_err("Failed to create debug fs dir \n"); return ret; } #endif return platform_driver_register(&msmsdcc_driver); } static void __exit msmsdcc_exit(void) { platform_driver_unregister(&msmsdcc_driver); #if defined(CONFIG_DEBUG_FS) debugfs_remove(debugfs_file); debugfs_remove(debugfs_dir); #endif } module_init(msmsdcc_init); module_exit(msmsdcc_exit); MODULE_DESCRIPTION("Qualcomm Multimedia Card Interface driver"); MODULE_LICENSE("GPL"); #if defined(CONFIG_DEBUG_FS) static int msmsdcc_dbg_state_open(struct inode *inode, struct file *file) { file->private_data = inode->i_private; return 0; } static ssize_t msmsdcc_dbg_state_read(struct file *file, char __user *ubuf, size_t count, loff_t *ppos) { struct msmsdcc_host *host = (struct msmsdcc_host *) file->private_data; char buf[1024]; int max, i; i = 0; max = sizeof(buf) - 1; i += scnprintf(buf + i, max - i, "STAT: %p %p %p\n", host->curr.mrq, host->curr.cmd, host->curr.data); if (host->curr.cmd) { struct mmc_command *cmd = host->curr.cmd; i += scnprintf(buf + i, max - i, "CMD : %.8x %.8x %.8x\n", cmd->opcode, cmd->arg, cmd->flags); } if (host->curr.data) { struct mmc_data *data = host->curr.data; i += scnprintf(buf + i, max - i, "DAT0: %.8x %.8x %.8x %.8x %.8x %.8x\n", data->timeout_ns, data->timeout_clks, data->blksz, data->blocks, data->error, data->flags); i += scnprintf(buf + i, max - i, "DAT1: %.8x %.8x %.8x %p\n", host->curr.xfer_size, host->curr.xfer_remain, host->curr.data_xfered, host->dma.sg); } return simple_read_from_buffer(ubuf, count, ppos, buf, i); } static const struct file_operations msmsdcc_dbg_state_ops = { .read = msmsdcc_dbg_state_read, .open = msmsdcc_dbg_state_open, }; static void msmsdcc_dbg_createhost(struct msmsdcc_host *host) { if (debugfs_dir) { debugfs_file = debugfs_create_file(mmc_hostname(host->mmc), 0644, debugfs_dir, host, &msmsdcc_dbg_state_ops); } } static int __init msmsdcc_dbg_init(void) { int err; debugfs_dir = debugfs_create_dir("msmsdcc", 0); if (IS_ERR(debugfs_dir)) { err = PTR_ERR(debugfs_dir); debugfs_dir = NULL; return err; } return 0; } #endif
gpl-2.0
palasthotel/grid-wordpress-box-social
vendor/google/apiclient-services/src/Google/Service/Safebrowsing/GoogleSecuritySafebrowsingV4FindFullHashesRequest.php
2567
<?php /* * Copyright 2014 Google Inc. * * 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. */ class Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4FindFullHashesRequest extends Google_Collection { protected $collection_key = 'clientStates'; protected $apiClientType = 'Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ClientInfo'; protected $apiClientDataType = ''; protected $clientType = 'Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ClientInfo'; protected $clientDataType = ''; public $clientStates; protected $threatInfoType = 'Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ThreatInfo'; protected $threatInfoDataType = ''; /** * @param Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ClientInfo */ public function setApiClient(Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ClientInfo $apiClient) { $this->apiClient = $apiClient; } /** * @return Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ClientInfo */ public function getApiClient() { return $this->apiClient; } /** * @param Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ClientInfo */ public function setClient(Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ClientInfo $client) { $this->client = $client; } /** * @return Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ClientInfo */ public function getClient() { return $this->client; } public function setClientStates($clientStates) { $this->clientStates = $clientStates; } public function getClientStates() { return $this->clientStates; } /** * @param Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ThreatInfo */ public function setThreatInfo(Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ThreatInfo $threatInfo) { $this->threatInfo = $threatInfo; } /** * @return Google_Service_Safebrowsing_GoogleSecuritySafebrowsingV4ThreatInfo */ public function getThreatInfo() { return $this->threatInfo; } }
gpl-2.0
slint/zenodo
tests/unit/records/test_schemas_marcxml.py
13950
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2016 CERN. # # Zenodo 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. # # Zenodo 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 Zenodo; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. """Zenodo Marcxml mapping test.""" from __future__ import absolute_import, print_function from datetime import datetime from invenio_pidstore.models import PersistentIdentifier from invenio_records import Record from zenodo.modules.records.serializers import marcxml_v1 def test_full_record(app, db, full_record): """Test MARC21 serialization of full record.""" # Add embargo date and OAI-PMH set information. full_record['embargo_date'] = '0900-12-31' full_record['_oai'] = { "id": "oai:zenodo.org:1", "sets": ["user-zenodo", "user-ecfunded"] } # Create record and PID. record = Record.create(full_record) pid = PersistentIdentifier.create( pid_type='recid', pid_value='12345', object_type='rec', object_uuid=record.id, ) assert record.validate() is None expected = { u'control_number': u'12345', u'date_and_time_of_latest_transaction': ( record.model.updated.strftime("%Y%m%d%H%M%S.0")), u'resource_type': { u'subtype': u'book', u'type': u'publication' }, u'title_statement': { u'title': u'Test title' }, u'publication_distribution_imprint': [ {u'date_of_publication_distribution': u'2014-02-27'}, ], u'main_entry_personal_name': { u'affiliation': u'CERN', u'personal_name': u'Doe, John', u'authority_record_control_number_or_standard_number': [ u'(gnd)170118215', u'(orcid)0000-0002-1694-233X' ] }, u'added_entry_personal_name': [ { u'affiliation': u'CERN', u'personal_name': u'Doe, Jane', u'authority_record_control_number_or_standard_number': [ u'(orcid)0000-0002-1825-0097' ] }, { u'affiliation': u'CERN', u'personal_name': u'Smith, John', }, { u'affiliation': u'CERN', u'personal_name': u'Nowak, Jack', u'authority_record_control_number_or_standard_number': [ u'(gnd)170118215' ] }, { u'affiliation': u'CERN', u'relator_code': [u'oth'], u'personal_name': u'Smith, Other', u'authority_record_control_number_or_standard_number': [ u'(orcid)0000-0002-1825-0097' ] }, { u'personal_name': u'Hansen, Viggo', u'relator_code': [u'oth'], }, { u'affiliation': u'CERN', u'relator_code': [u'dtm'], u'personal_name': u'Kowalski, Manager' }, { u'relator_code': [u'ths'], u'personal_name': u'Smith, Professor' }, ], u'summary': { u'summary': u'Test Description' }, u'index_term_uncontrolled': [ {u'uncontrolled_term': u'kw1'}, {u'uncontrolled_term': u'kw2'}, {u'uncontrolled_term': u'kw3'}, ], u'subject_added_entry_topical_term': [ { u'topical_term_or_geographic_name_entry_element': u'cc-by', u'source_of_heading_or_term': u'opendefinition.org', u'level_of_subject': u'Primary', u'thesaurus': u'Source specified in subfield $2', }, { u'topical_term_or_geographic_name_entry_element': u'Astronomy', u'authority_record_control_number_or_standard_number': ( u'(url)http://id.loc.gov/authorities/subjects/sh85009003'), u'level_of_subject': u'Primary', }, ], u'general_note': { u'general_note': u'notes' }, u'information_relating_to_copyright_status': { u'copyright_status': u'open' }, u'terms_governing_use_and_reproduction_note': { u'uniform_resource_identifier': u'https://creativecommons.org/licenses/by/4.0/', u'terms_governing_use_and_reproduction': u'Creative Commons Attribution 4.0' }, u'communities': [ u'zenodo', ], u'funding_information_note': [ {u'grant_number': u'1234', u'text_of_note': u'Grant Title'}, {u'grant_number': u'4321', u'text_of_note': u'Title Grant'} ], u'host_item_entry': [ { u'main_entry_heading': u'10.1234/foo.bar', u'note': u'doi', u'relationship_information': u'cites', }, { 'main_entry_heading': u'1234.4325', 'note': u'arxiv', 'relationship_information': u'isIdenticalTo' }, { u'main_entry_heading': u'1234.4321', u'note': u'arxiv', u'relationship_information': u'cites', }, { 'main_entry_heading': u'1234.4328', 'note': u'arxiv', 'relationship_information': u'references' }, { 'main_entry_heading': u'10.1234/zenodo.4321', 'note': u'doi', 'relationship_information': u'isPartOf' }, { 'main_entry_heading': u'10.1234/zenodo.1234', 'note': u'doi', 'relationship_information': u'hasPart' }, { u'main_entry_heading': u'Staszkowka', u'edition': u'Jol', u'title': u'Bum', u'related_parts': u'1-2', u'international_standard_book_number': u'978-0201633610', }, ], u'other_standard_identifier': [ { u'standard_number_or_code': u'10.1234/foo.bar', u'source_of_number_or_code': u'doi', }, { u'standard_number_or_code': ( u'urn:lsid:ubio.org:namebank:11815'), u'source_of_number_or_code': u'lsid', u'qualifying_information': u'alternateidentifier', }, { u'standard_number_or_code': u'2011ApJS..192...18K', u'source_of_number_or_code': u'ads', u'qualifying_information': u'alternateidentifier', }, { u'standard_number_or_code': u'0317-8471', u'source_of_number_or_code': u'issn', u'qualifying_information': u'alternateidentifier', }, { u'standard_number_or_code': u'10.1234/alternate.doi', u'source_of_number_or_code': u'doi', u'qualifying_information': u'alternateidentifier', } ], u'references': [ { u'raw_reference': u'Doe, John et al (2012). Some title. ' 'Zenodo. 10.5281/zenodo.12' }, { u'raw_reference': u'Smith, Jane et al (2012). Some title. ' 'Zenodo. 10.5281/zenodo.34' } ], u'added_entry_meeting_name': [{ u'date_of_meeting': u'23-25 June, 2014', u'meeting_name_or_jurisdiction_name_as_entry_element': u'The 13th Biennial HITRAN Conference', u'number_of_part_section_meeting': u'VI', u'miscellaneous_information': u'HITRAN13', u'name_of_part_section_of_a_work': u'1', u'location_of_meeting': u'Harvard-Smithsonian Center for Astrophysics' }], u'conference_url': 'http://hitran.org/conferences/hitran-13-2014/', u'dissertation_note': { u'name_of_granting_institution': u'I guess important', }, u'journal': { 'issue': '2', 'pages': '20', 'volume': '20', 'title': 'Bam', 'year': '2014', }, u'embargo_date': '0900-12-31', u'language_code': { 'language_code_of_text_sound_track_or_separate_title': 'eng', }, u'_oai': { u'sets': [u'user-zenodo', u'user-ecfunded'], u'id': u'oai:zenodo.org:1' }, u'_files': [ { 'uri': 'https://zenodo.org/record/12345/files/test', 'checksum': 'md5:11111111111111111111111111111111', 'type': 'txt', 'size': 4, }, ], 'leader': { 'base_address_of_data': '00000', 'bibliographic_level': 'monograph_item', 'character_coding_scheme': 'marc-8', 'descriptive_cataloging_form': 'unknown', 'encoding_level': 'unknown', 'indicator_count': 2, 'length_of_the_implementation_defined_portion': 0, 'length_of_the_length_of_field_portion': 4, 'length_of_the_starting_character_position_portion': 5, 'multipart_resource_record_level': 'not_specified_or_not_applicable', 'record_length': '00000', 'record_status': 'new', 'subfield_code_count': 2, 'type_of_control': 'no_specified_type', 'type_of_record': 'language_material', 'undefined': 0, }, } # Dump MARC21 JSON structure and compare against expected JSON. preprocessed_record = marcxml_v1.preprocess_record(record=record, pid=pid) data = marcxml_v1.schema_class().dump(preprocessed_record).data assert expected == data # Assert that we can output MARCXML. assert marcxml_v1.serialize(record=record, pid=pid) def test_minimal_record(app, db, minimal_record): """Test minimal record.""" # Create record and pid. record = Record.create(minimal_record) record.model.updated = datetime.utcnow() pid = PersistentIdentifier.create( pid_type='recid', pid_value='123', object_type='rec', object_uuid=record.id) assert record.validate() is None expected = { u'date_and_time_of_latest_transaction': ( record.model.updated.strftime("%Y%m%d%H%M%S.0")), u'publication_distribution_imprint': [{ 'date_of_publication_distribution': record['publication_date'] }], u'control_number': '123', u'other_standard_identifier': [ { 'source_of_number_or_code': u'doi', 'standard_number_or_code': u'10.5072/zenodo.123' } ], u'information_relating_to_copyright_status': { 'copyright_status': 'open' }, u'summary': { 'summary': 'My description' }, u'main_entry_personal_name': { 'personal_name': 'Test' }, u'resource_type': { 'type': 'software' }, u'title_statement': { 'title': 'Test' }, u'leader': { 'base_address_of_data': '00000', 'bibliographic_level': 'monograph_item', 'character_coding_scheme': 'marc-8', 'descriptive_cataloging_form': 'unknown', 'encoding_level': 'unknown', 'indicator_count': 2, 'length_of_the_implementation_defined_portion': 0, 'length_of_the_length_of_field_portion': 4, 'length_of_the_starting_character_position_portion': 5, 'multipart_resource_record_level': 'not_specified_or_not_applicable', 'record_length': '00000', 'record_status': 'new', 'subfield_code_count': 2, 'type_of_control': 'no_specified_type', 'type_of_record': 'computer_file', 'undefined': 0, }, } data = marcxml_v1.schema_class().dump(marcxml_v1.preprocess_record( pid=pid, record=record)).data assert expected == data marcxml_v1.serialize(pid=pid, record=record) def assert_array(a1, a2): """Check array.""" for i in range(0, len(a1)): if isinstance(a1[i], dict): assert_dict(a1[i], a2[i]) elif isinstance(a1[i], list) or isinstance(a1[i], tuple): assert_array(a1[i], a2[i]) else: assert a1[i] in a2 assert len(a1) == len(a2) def assert_dict(a1, a2): """Check dict.""" for (k, v) in a1.items(): assert k in a2 if isinstance(v, dict): assert_dict(v, a2[k]) elif isinstance(v, list) or isinstance(v, tuple): assert_array(v, a2[k]) else: assert a2[k] == v assert len(a2) == len(a1)
gpl-2.0
MSM8916-Samsung/android_kernel_samsung_e53g
drivers/soc/qcom/bam_dmux.c
77670
/* Copyright (c) 2011-2014, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only 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. * */ /* * BAM DMUX module. */ #define DEBUG #include <linux/delay.h> #include <linux/module.h> #include <linux/netdevice.h> #include <linux/platform_device.h> #include <linux/sched.h> #include <linux/skbuff.h> #include <linux/debugfs.h> #include <linux/clk.h> #include <linux/wakelock.h> #include <linux/of.h> #include <linux/ipc_logging.h> #include <linux/srcu.h> #include <linux/msm-sps.h> #include <linux/sizes.h> #include <soc/qcom/bam_dmux.h> #include <soc/qcom/smsm.h> #include <soc/qcom/subsystem_restart.h> #include <soc/qcom/subsystem_notif.h> #include "bam_dmux_private.h" #define BAM_CH_LOCAL_OPEN 0x1 #define BAM_CH_REMOTE_OPEN 0x2 #define BAM_CH_IN_RESET 0x4 #define LOW_WATERMARK 2 #define HIGH_WATERMARK 4 #define DEFAULT_POLLING_MIN_SLEEP (950) #define MAX_POLLING_SLEEP (6050) #define MIN_POLLING_SLEEP (950) #ifdef BAM_DMUX_FD static unsigned int wakelock_timeout; #endif static int msm_bam_dmux_debug_enable; module_param_named(debug_enable, msm_bam_dmux_debug_enable, int, S_IRUGO | S_IWUSR | S_IWGRP); static int POLLING_MIN_SLEEP = 2950; module_param_named(min_sleep, POLLING_MIN_SLEEP, int, S_IRUGO | S_IWUSR | S_IWGRP); static int POLLING_MAX_SLEEP = 3050; module_param_named(max_sleep, POLLING_MAX_SLEEP, int, S_IRUGO | S_IWUSR | S_IWGRP); static int POLLING_INACTIVITY = 1; module_param_named(inactivity, POLLING_INACTIVITY, int, S_IRUGO | S_IWUSR | S_IWGRP); static int bam_adaptive_timer_enabled; module_param_named(adaptive_timer_enabled, bam_adaptive_timer_enabled, int, S_IRUGO | S_IWUSR | S_IWGRP); static struct bam_ops_if bam_default_ops = { /* smsm */ .smsm_change_state_ptr = &smsm_change_state, .smsm_get_state_ptr = &smsm_get_state, .smsm_state_cb_register_ptr = &smsm_state_cb_register, .smsm_state_cb_deregister_ptr = &smsm_state_cb_deregister, /* sps */ .sps_connect_ptr = &sps_connect, .sps_disconnect_ptr = &sps_disconnect, .sps_register_bam_device_ptr = &sps_register_bam_device, .sps_deregister_bam_device_ptr = &sps_deregister_bam_device, .sps_alloc_endpoint_ptr = &sps_alloc_endpoint, .sps_free_endpoint_ptr = &sps_free_endpoint, .sps_set_config_ptr = &sps_set_config, .sps_get_config_ptr = &sps_get_config, .sps_device_reset_ptr = &sps_device_reset, .sps_register_event_ptr = &sps_register_event, .sps_transfer_one_ptr = &sps_transfer_one, .sps_get_iovec_ptr = &sps_get_iovec, .sps_get_unused_desc_num_ptr = &sps_get_unused_desc_num, .dma_to = DMA_TO_DEVICE, .dma_from = DMA_FROM_DEVICE, }; static struct bam_ops_if *bam_ops = &bam_default_ops; #if defined(DEBUG) static uint32_t bam_dmux_read_cnt; static uint32_t bam_dmux_write_cnt; static uint32_t bam_dmux_write_cpy_cnt; static uint32_t bam_dmux_write_cpy_bytes; static uint32_t bam_dmux_tx_sps_failure_cnt; static uint32_t bam_dmux_tx_stall_cnt; static atomic_t bam_dmux_ack_out_cnt = ATOMIC_INIT(0); static atomic_t bam_dmux_ack_in_cnt = ATOMIC_INIT(0); static atomic_t bam_dmux_a2_pwr_cntl_in_cnt = ATOMIC_INIT(0); #define DBG(x...) do { \ if (msm_bam_dmux_debug_enable) \ pr_debug(x); \ } while (0) #define DBG_INC_READ_CNT(x) do { \ bam_dmux_read_cnt += (x); \ if (msm_bam_dmux_debug_enable) \ pr_debug("%s: total read bytes %u\n", \ __func__, bam_dmux_read_cnt); \ } while (0) #define DBG_INC_WRITE_CNT(x) do { \ bam_dmux_write_cnt += (x); \ if (msm_bam_dmux_debug_enable) \ pr_debug("%s: total written bytes %u\n", \ __func__, bam_dmux_write_cnt); \ } while (0) #define DBG_INC_WRITE_CPY(x) do { \ bam_dmux_write_cpy_bytes += (x); \ bam_dmux_write_cpy_cnt++; \ if (msm_bam_dmux_debug_enable) \ pr_debug("%s: total write copy cnt %u, bytes %u\n", \ __func__, bam_dmux_write_cpy_cnt, \ bam_dmux_write_cpy_bytes); \ } while (0) #define DBG_INC_TX_SPS_FAILURE_CNT() do { \ bam_dmux_tx_sps_failure_cnt++; \ } while (0) #define DBG_INC_TX_STALL_CNT() do { \ bam_dmux_tx_stall_cnt++; \ } while (0) #define DBG_INC_ACK_OUT_CNT() \ atomic_inc(&bam_dmux_ack_out_cnt) #define DBG_INC_A2_POWER_CONTROL_IN_CNT() \ atomic_inc(&bam_dmux_a2_pwr_cntl_in_cnt) #define DBG_INC_ACK_IN_CNT() \ atomic_inc(&bam_dmux_ack_in_cnt) #else #define DBG(x...) do { } while (0) #define DBG_INC_READ_CNT(x...) do { } while (0) #define DBG_INC_WRITE_CNT(x...) do { } while (0) #define DBG_INC_WRITE_CPY(x...) do { } while (0) #define DBG_INC_TX_SPS_FAILURE_CNT() do { } while (0) #define DBG_INC_TX_STALL_CNT() do { } while (0) #define DBG_INC_ACK_OUT_CNT() do { } while (0) #define DBG_INC_A2_POWER_CONTROL_IN_CNT() \ do { } while (0) #define DBG_INC_ACK_IN_CNT() do { } while (0) #endif struct bam_ch_info { uint32_t status; void (*notify)(void *, int, unsigned long); void *priv; spinlock_t lock; struct platform_device *pdev; char name[BAM_DMUX_CH_NAME_MAX_LEN]; int num_tx_pkts; int use_wm; }; #define A2_NUM_PIPES 6 #define A2_SUMMING_THRESHOLD 4096 #define A2_PHYS_BASE 0x124C2000 #define A2_PHYS_SIZE 0x2000 #define DEFAULT_NUM_BUFFERS 32 #ifndef A2_BAM_IRQ #define A2_BAM_IRQ -1 #endif static phys_addr_t a2_phys_base; static uint32_t a2_phys_size; static int a2_bam_irq; static struct sps_bam_props a2_props; static unsigned long a2_device_handle; static struct sps_pipe *bam_tx_pipe; static struct sps_pipe *bam_rx_pipe; static struct sps_connect tx_connection; static struct sps_connect rx_connection; static struct sps_mem_buffer tx_desc_mem_buf; static struct sps_mem_buffer rx_desc_mem_buf; static struct sps_register_event tx_register_event; static struct sps_register_event rx_register_event; static bool satellite_mode; static uint32_t num_buffers; static unsigned long long last_rx_pkt_timestamp; static struct device *dma_dev; static bool dynamic_mtu_enabled; static uint16_t ul_mtu = DEFAULT_BUFFER_SIZE; static uint16_t dl_mtu = DEFAULT_BUFFER_SIZE; static uint16_t buffer_size = DEFAULT_BUFFER_SIZE; static bool no_cpu_affinity; static struct bam_ch_info bam_ch[BAM_DMUX_NUM_CHANNELS]; static int bam_mux_initialized; static int polling_mode; static unsigned long rx_timer_interval; static LIST_HEAD(bam_rx_pool); static DEFINE_MUTEX(bam_rx_pool_mutexlock); static int bam_rx_pool_len; static LIST_HEAD(bam_tx_pool); static DEFINE_SPINLOCK(bam_tx_pool_spinlock); static DEFINE_MUTEX(bam_pdev_mutexlock); static void notify_all(int event, unsigned long data); static void bam_mux_write_done(struct work_struct *work); static void handle_bam_mux_cmd(struct work_struct *work); static void rx_timer_work_func(struct work_struct *work); static void queue_rx_work_func(struct work_struct *work); static int ssrestart_check(void); static DECLARE_WORK(rx_timer_work, rx_timer_work_func); static DECLARE_WORK(queue_rx_work, queue_rx_work_func); static struct workqueue_struct *bam_mux_rx_workqueue; static struct workqueue_struct *bam_mux_tx_workqueue; static struct srcu_struct bam_dmux_srcu; /* A2 power collaspe */ #define UL_TIMEOUT_DELAY 1000 /* in ms */ #define SHUTDOWN_TIMEOUT_MS 500 #define UL_WAKEUP_TIMEOUT_MS 2000 static void toggle_apps_ack(void); static void reconnect_to_bam(void); static void disconnect_to_bam(void); static void ul_wakeup(void); static void ul_timeout(struct work_struct *work); static void vote_dfab(void); static void unvote_dfab(void); static void kickoff_ul_wakeup_func(struct work_struct *work); static void grab_wakelock(void); static void release_wakelock(void); static int bam_is_connected; static DEFINE_MUTEX(wakeup_lock); static struct completion ul_wakeup_ack_completion; static struct completion bam_connection_completion; static struct delayed_work ul_timeout_work; static int ul_packet_written; static atomic_t ul_ondemand_vote = ATOMIC_INIT(0); static struct clk *dfab_clk, *xo_clk; static DEFINE_RWLOCK(ul_wakeup_lock); static DECLARE_WORK(kickoff_ul_wakeup, kickoff_ul_wakeup_func); static int bam_connection_is_active; static int wait_for_ack; static struct wake_lock bam_wakelock; static int a2_pc_disabled; static DEFINE_MUTEX(dfab_status_lock); static int dfab_is_on; static int wait_for_dfab; static struct completion dfab_unvote_completion; static DEFINE_SPINLOCK(wakelock_reference_lock); static int wakelock_reference_count; static int a2_pc_disabled_wakelock_skipped; static LIST_HEAD(bam_other_notify_funcs); static DEFINE_MUTEX(smsm_cb_lock); static DEFINE_MUTEX(delayed_ul_vote_lock); static int need_delayed_ul_vote; static int in_ssr; static int ssr_skipped_disconnect; static struct completion shutdown_completion; struct outside_notify_func { void (*notify)(void *, int, unsigned long); void *priv; struct list_head list_node; }; /* End A2 power collaspe */ /* subsystem restart */ static int restart_notifier_cb(struct notifier_block *this, unsigned long code, void *data); static struct notifier_block restart_notifier = { .notifier_call = restart_notifier_cb, }; static int in_global_reset; /* end subsystem restart */ #define bam_ch_is_open(x) \ (bam_ch[(x)].status == (BAM_CH_LOCAL_OPEN | BAM_CH_REMOTE_OPEN)) #define bam_ch_is_local_open(x) \ (bam_ch[(x)].status & BAM_CH_LOCAL_OPEN) #define bam_ch_is_remote_open(x) \ (bam_ch[(x)].status & BAM_CH_REMOTE_OPEN) #define bam_ch_is_in_reset(x) \ (bam_ch[(x)].status & BAM_CH_IN_RESET) static int bam_dmux_uplink_vote; static int bam_dmux_power_state; static void *bam_ipc_log_txt; #define BAM_IPC_LOG_PAGES 5 /** * Log a state change along with a small message. * Complete size of messsage is limited to @todo. * Logging is done using IPC Logging infrastructure. * * States * D: 1 = Power collapse disabled * R: 1 = in global reset * P: 1 = BAM is powered up * A: 1 = BAM initialized and ready for data * V: 1 = Uplink vote for power * U: 1 = Uplink active * W: 1 = Uplink Wait-for-ack * A: 1 = Uplink ACK received * #: >=1 On-demand uplink vote * D: 1 = Disconnect ACK active */ #define BAM_DMUX_LOG(fmt, args...) \ do { \ if (bam_ipc_log_txt) { \ ipc_log_string(bam_ipc_log_txt, \ "<DMUX> %c%c%c%c %c%c%c%c%d " fmt, \ a2_pc_disabled ? 'D' : 'd', \ in_global_reset ? 'R' : 'r', \ bam_dmux_power_state ? 'P' : 'p', \ bam_connection_is_active ? 'A' : 'a', \ bam_dmux_uplink_vote ? 'V' : 'v', \ bam_is_connected ? 'U' : 'u', \ wait_for_ack ? 'W' : 'w', \ ul_wakeup_ack_completion.done ? 'A' : 'a', \ atomic_read(&ul_ondemand_vote), \ args); \ } \ } while (0) #define DMUX_LOG_KERR(fmt, args...) \ do { \ BAM_DMUX_LOG(fmt, args); \ pr_err(fmt, args); \ } while (0) static inline void set_tx_timestamp(struct tx_pkt_info *pkt) { unsigned long long t_now; t_now = sched_clock(); pkt->ts_nsec = do_div(t_now, 1000000000U); pkt->ts_sec = (unsigned)t_now; } static inline void verify_tx_queue_is_empty(const char *func) { unsigned long flags; struct tx_pkt_info *info; int reported = 0; spin_lock_irqsave(&bam_tx_pool_spinlock, flags); list_for_each_entry(info, &bam_tx_pool, list_node) { if (!reported) { BAM_DMUX_LOG("%s: tx pool not empty\n", func); if (!in_global_reset) pr_err("%s: tx pool not empty\n", func); reported = 1; } BAM_DMUX_LOG("%s: node=%p ts=%u.%09lu\n", __func__, &info->list_node, info->ts_sec, info->ts_nsec); if (!in_global_reset) pr_err("%s: node=%p ts=%u.%09lu\n", __func__, &info->list_node, info->ts_sec, info->ts_nsec); } spin_unlock_irqrestore(&bam_tx_pool_spinlock, flags); } static void __queue_rx(gfp_t alloc_flags) { void *ptr; struct rx_pkt_info *info; int ret; int rx_len_cached; uint16_t current_buffer_size; mutex_lock(&bam_rx_pool_mutexlock); rx_len_cached = bam_rx_pool_len; current_buffer_size = buffer_size; mutex_unlock(&bam_rx_pool_mutexlock); while (bam_connection_is_active && rx_len_cached < num_buffers) { if (in_global_reset) goto fail; info = kmalloc(sizeof(struct rx_pkt_info), alloc_flags); if (!info) { DMUX_LOG_KERR( "%s: unable to alloc rx_pkt_info w/ flags %x, will retry later\n", __func__, alloc_flags); goto fail; } info->len = current_buffer_size; INIT_WORK(&info->work, handle_bam_mux_cmd); info->skb = __dev_alloc_skb(info->len, alloc_flags); if (info->skb == NULL) { DMUX_LOG_KERR( "%s: unable to alloc skb w/ flags %x, will retry later\n", __func__, alloc_flags); goto fail_info; } ptr = skb_put(info->skb, info->len); info->dma_address = dma_map_single(dma_dev, ptr, info->len, bam_ops->dma_from); if (info->dma_address == 0 || info->dma_address == ~0) { DMUX_LOG_KERR("%s: dma_map_single failure %p for %p\n", __func__, (void *)info->dma_address, ptr); goto fail_skb; } mutex_lock(&bam_rx_pool_mutexlock); list_add_tail(&info->list_node, &bam_rx_pool); rx_len_cached = ++bam_rx_pool_len; current_buffer_size = buffer_size; ret = bam_ops->sps_transfer_one_ptr(bam_rx_pipe, info->dma_address, info->len, info, 0); if (ret) { list_del(&info->list_node); rx_len_cached = --bam_rx_pool_len; mutex_unlock(&bam_rx_pool_mutexlock); DMUX_LOG_KERR("%s: sps_transfer_one failed %d\n", __func__, ret); dma_unmap_single(dma_dev, info->dma_address, info->len, bam_ops->dma_from); goto fail_skb; } mutex_unlock(&bam_rx_pool_mutexlock); } return; fail_skb: dev_kfree_skb_any(info->skb); fail_info: kfree(info); fail: if (!in_global_reset) { DMUX_LOG_KERR("%s: rescheduling\n", __func__); schedule_work(&queue_rx_work); } } static void queue_rx(void) { /* * Hot path. Delays waiting for the allocation to find memory if its * not immediately available, and delays from logging allocation * failures which cannot be tolerated at this time. */ __queue_rx(GFP_NOWAIT | __GFP_NOWARN); } static void queue_rx_work_func(struct work_struct *work) { /* * Cold path. Delays can be tolerated. Use of GFP_KERNEL should * guarentee the requested memory will be found, after some ammount of * delay. */ __queue_rx(GFP_KERNEL); } /** * process_dynamic_mtu() - Process the dynamic MTU signal bit from data cmds * @current_state: State of the dynamic MTU signal bit for the current * data command packet. */ static void process_dynamic_mtu(bool current_state) { static bool old_state; if (!dynamic_mtu_enabled) return; if (old_state == current_state) return; mutex_lock(&bam_rx_pool_mutexlock); if (current_state) { buffer_size = dl_mtu; BAM_DMUX_LOG("%s: switching to large mtu %x\n", __func__, dl_mtu); } else { buffer_size = DEFAULT_BUFFER_SIZE; BAM_DMUX_LOG("%s: switching to reg mtu %x\n", __func__, DEFAULT_BUFFER_SIZE); } mutex_unlock(&bam_rx_pool_mutexlock); old_state = current_state; } static void bam_mux_process_data(struct sk_buff *rx_skb) { unsigned long flags; struct bam_mux_hdr *rx_hdr; unsigned long event_data; uint8_t ch_id; void (*notify)(void *, int, unsigned long); void *priv; rx_hdr = (struct bam_mux_hdr *)rx_skb->data; ch_id = rx_hdr->ch_id; process_dynamic_mtu(rx_hdr->signal & DYNAMIC_MTU_MASK); rx_skb->data = (unsigned char *)(rx_hdr + 1); skb_set_tail_pointer(rx_skb, rx_hdr->pkt_len); rx_skb->len = rx_hdr->pkt_len; rx_skb->truesize = rx_hdr->pkt_len + sizeof(struct sk_buff); event_data = (unsigned long)(rx_skb); notify = NULL; priv = NULL; spin_lock_irqsave(&bam_ch[ch_id].lock, flags); if (bam_ch[ch_id].notify) { notify = bam_ch[ch_id].notify; priv = bam_ch[ch_id].priv; } spin_unlock_irqrestore(&bam_ch[ch_id].lock, flags); if (notify) notify(priv, BAM_DMUX_RECEIVE, event_data); else dev_kfree_skb_any(rx_skb); queue_rx(); } /** * set_ul_mtu() - Converts the MTU code received from the remote side in the * open cmd into a byte value. * @mtu_code: MTU size code to translate. * @reset: Reset the MTU. */ static void set_ul_mtu(int mtu_code, bool reset) { static bool first = true; if (reset) { first = true; ul_mtu = DEFAULT_BUFFER_SIZE; return; } switch (mtu_code) { case 0: if (ul_mtu != SZ_2K && !first) { BAM_DMUX_LOG("%s: bad request for 2k, ul_mtu is %d\n", __func__, ul_mtu); ssrestart_check(); } ul_mtu = SZ_2K; break; case 1: if (ul_mtu != SZ_4K && !first) { BAM_DMUX_LOG("%s: bad request for 4k, ul_mtu is %d\n", __func__, ul_mtu); ssrestart_check(); } ul_mtu = SZ_4K; break; case 2: if (ul_mtu != SZ_8K && !first) { BAM_DMUX_LOG("%s: bad request for 8k, ul_mtu is %d\n", __func__, ul_mtu); ssrestart_check(); } ul_mtu = SZ_8K; break; case 3: if (ul_mtu != SZ_16K && !first) { BAM_DMUX_LOG("%s: bad request for 16k, ul_mtu is %d\n", __func__, ul_mtu); ssrestart_check(); } ul_mtu = SZ_16K; break; default: BAM_DMUX_LOG("%s: bad request %d\n", __func__, mtu_code); ssrestart_check(); break; } first = false; } static inline void handle_bam_mux_cmd_open(struct bam_mux_hdr *rx_hdr) { unsigned long flags; int ret; mutex_lock(&bam_pdev_mutexlock); if (in_global_reset) { BAM_DMUX_LOG("%s: open cid %d aborted due to ssr\n", __func__, rx_hdr->ch_id); mutex_unlock(&bam_pdev_mutexlock); queue_rx(); return; } if (rx_hdr->signal & DYNAMIC_MTU_MASK) { dynamic_mtu_enabled = true; set_ul_mtu((rx_hdr->signal & MTU_SIZE_MASK) >> MTU_SIZE_SHIFT, false); } else { set_ul_mtu(0, false); } spin_lock_irqsave(&bam_ch[rx_hdr->ch_id].lock, flags); if (bam_ch_is_remote_open(rx_hdr->ch_id)) { /* * Receiving an open command for a channel that is already open * is an invalid operation and likely signifies a significant * issue within the A2 which should be caught immediately * before it snowballs and the root cause is lost. */ panic("A2 sent invalid duplicate open for channel %d\n", rx_hdr->ch_id); } bam_ch[rx_hdr->ch_id].status |= BAM_CH_REMOTE_OPEN; bam_ch[rx_hdr->ch_id].num_tx_pkts = 0; spin_unlock_irqrestore(&bam_ch[rx_hdr->ch_id].lock, flags); ret = platform_device_add(bam_ch[rx_hdr->ch_id].pdev); if (ret) pr_err("%s: platform_device_add() error: %d\n", __func__, ret); mutex_unlock(&bam_pdev_mutexlock); queue_rx(); } static void handle_bam_mux_cmd(struct work_struct *work) { unsigned long flags; struct bam_mux_hdr *rx_hdr; struct rx_pkt_info *info; struct sk_buff *rx_skb; uint16_t sps_size; info = container_of(work, struct rx_pkt_info, work); rx_skb = info->skb; dma_unmap_single(dma_dev, info->dma_address, info->len, bam_ops->dma_from); sps_size = info->sps_size; kfree(info); rx_hdr = (struct bam_mux_hdr *)rx_skb->data; DBG_INC_READ_CNT(sizeof(struct bam_mux_hdr)); DBG("%s: magic %x signal %x cmd %d pad %d ch %d len %d\n", __func__, rx_hdr->magic_num, rx_hdr->signal, rx_hdr->cmd, rx_hdr->pad_len, rx_hdr->ch_id, rx_hdr->pkt_len); if (rx_hdr->magic_num != BAM_MUX_HDR_MAGIC_NO) { DMUX_LOG_KERR( "%s: dropping invalid hdr. magic %x signal %x cmd %d pad %d ch %d len %d\n", __func__, rx_hdr->magic_num, rx_hdr->signal, rx_hdr->cmd, rx_hdr->pad_len, rx_hdr->ch_id, rx_hdr->pkt_len); dev_kfree_skb_any(rx_skb); queue_rx(); return; } if (rx_hdr->ch_id >= BAM_DMUX_NUM_CHANNELS) { DMUX_LOG_KERR( "%s: dropping invalid LCID %d signal %x cmd %d pad %d ch %d len %d\n", __func__, rx_hdr->ch_id, rx_hdr->signal, rx_hdr->cmd, rx_hdr->pad_len, rx_hdr->ch_id, rx_hdr->pkt_len); dev_kfree_skb_any(rx_skb); queue_rx(); return; } switch (rx_hdr->cmd) { case BAM_MUX_HDR_CMD_DATA: if (rx_hdr->pkt_len == 0xffff) rx_hdr->pkt_len = sps_size; DBG_INC_READ_CNT(rx_hdr->pkt_len); bam_mux_process_data(rx_skb); break; case BAM_MUX_HDR_CMD_OPEN: BAM_DMUX_LOG("%s: opening cid %d PC enabled\n", __func__, rx_hdr->ch_id); handle_bam_mux_cmd_open(rx_hdr); dev_kfree_skb_any(rx_skb); break; case BAM_MUX_HDR_CMD_OPEN_NO_A2_PC: BAM_DMUX_LOG("%s: opening cid %d PC disabled\n", __func__, rx_hdr->ch_id); if (!a2_pc_disabled) { a2_pc_disabled = 1; ul_wakeup(); } handle_bam_mux_cmd_open(rx_hdr); dev_kfree_skb_any(rx_skb); break; case BAM_MUX_HDR_CMD_CLOSE: /* probably should drop pending write */ BAM_DMUX_LOG("%s: closing cid %d\n", __func__, rx_hdr->ch_id); mutex_lock(&bam_pdev_mutexlock); if (in_global_reset) { BAM_DMUX_LOG("%s: close cid %d aborted due to ssr\n", __func__, rx_hdr->ch_id); mutex_unlock(&bam_pdev_mutexlock); break; } spin_lock_irqsave(&bam_ch[rx_hdr->ch_id].lock, flags); bam_ch[rx_hdr->ch_id].status &= ~BAM_CH_REMOTE_OPEN; spin_unlock_irqrestore(&bam_ch[rx_hdr->ch_id].lock, flags); platform_device_unregister(bam_ch[rx_hdr->ch_id].pdev); bam_ch[rx_hdr->ch_id].pdev = platform_device_alloc(bam_ch[rx_hdr->ch_id].name, 2); if (!bam_ch[rx_hdr->ch_id].pdev) pr_err("%s: platform_device_alloc failed\n", __func__); mutex_unlock(&bam_pdev_mutexlock); dev_kfree_skb_any(rx_skb); queue_rx(); break; default: DMUX_LOG_KERR( "%s: dropping invalid hdr. magic %x signal %x cmd %d pad %d ch %d len %d\n", __func__, rx_hdr->magic_num, rx_hdr->signal, rx_hdr->cmd, rx_hdr->pad_len, rx_hdr->ch_id, rx_hdr->pkt_len); dev_kfree_skb_any(rx_skb); queue_rx(); return; } } static int bam_mux_write_cmd(void *data, uint32_t len) { int rc; struct tx_pkt_info *pkt; dma_addr_t dma_address; unsigned long flags; pkt = kmalloc(sizeof(struct tx_pkt_info), GFP_ATOMIC); if (pkt == NULL) { pr_err("%s: mem alloc for tx_pkt_info failed\n", __func__); rc = -ENOMEM; return rc; } dma_address = dma_map_single(dma_dev, data, len, bam_ops->dma_to); if (!dma_address) { pr_err("%s: dma_map_single() failed\n", __func__); kfree(pkt); rc = -ENOMEM; return rc; } pkt->skb = (struct sk_buff *)(data); pkt->len = len; pkt->dma_address = dma_address; pkt->is_cmd = 1; set_tx_timestamp(pkt); INIT_WORK(&pkt->work, bam_mux_write_done); spin_lock_irqsave(&bam_tx_pool_spinlock, flags); list_add_tail(&pkt->list_node, &bam_tx_pool); rc = bam_ops->sps_transfer_one_ptr(bam_tx_pipe, dma_address, len, pkt, SPS_IOVEC_FLAG_EOT); if (rc) { DMUX_LOG_KERR("%s sps_transfer_one failed rc=%d\n", __func__, rc); list_del(&pkt->list_node); DBG_INC_TX_SPS_FAILURE_CNT(); spin_unlock_irqrestore(&bam_tx_pool_spinlock, flags); dma_unmap_single(dma_dev, pkt->dma_address, pkt->len, bam_ops->dma_to); kfree(pkt); } else { spin_unlock_irqrestore(&bam_tx_pool_spinlock, flags); } ul_packet_written = 1; return rc; } static void bam_mux_write_done(struct work_struct *work) { struct sk_buff *skb; struct bam_mux_hdr *hdr; struct tx_pkt_info *info; struct tx_pkt_info *info_expected; unsigned long event_data; unsigned long flags; if (in_global_reset) return; info = container_of(work, struct tx_pkt_info, work); spin_lock_irqsave(&bam_tx_pool_spinlock, flags); info_expected = list_first_entry(&bam_tx_pool, struct tx_pkt_info, list_node); if (unlikely(info != info_expected)) { struct tx_pkt_info *errant_pkt; DMUX_LOG_KERR("%s: bam_tx_pool mismatch .next=%p," " list_node=%p, ts=%u.%09lu\n", __func__, bam_tx_pool.next, &info->list_node, info->ts_sec, info->ts_nsec ); list_for_each_entry(errant_pkt, &bam_tx_pool, list_node) { DMUX_LOG_KERR("%s: node=%p ts=%u.%09lu\n", __func__, &errant_pkt->list_node, errant_pkt->ts_sec, errant_pkt->ts_nsec); } spin_unlock_irqrestore(&bam_tx_pool_spinlock, flags); BUG(); } list_del(&info->list_node); spin_unlock_irqrestore(&bam_tx_pool_spinlock, flags); if (info->is_cmd) { kfree(info->skb); kfree(info); return; } skb = info->skb; kfree(info); hdr = (struct bam_mux_hdr *)skb->data; DBG_INC_WRITE_CNT(skb->len); /* Restore skb for client */ skb_pull(skb, sizeof(*hdr)); if (hdr->pad_len) skb_trim(skb, skb->len - hdr->pad_len); event_data = (unsigned long)(skb); spin_lock_irqsave(&bam_ch[hdr->ch_id].lock, flags); bam_ch[hdr->ch_id].num_tx_pkts--; spin_unlock_irqrestore(&bam_ch[hdr->ch_id].lock, flags); if (bam_ch[hdr->ch_id].notify) bam_ch[hdr->ch_id].notify( bam_ch[hdr->ch_id].priv, BAM_DMUX_WRITE_DONE, event_data); else dev_kfree_skb_any(skb); } int msm_bam_dmux_write(uint32_t id, struct sk_buff *skb) { int rc = 0; struct bam_mux_hdr *hdr; unsigned long flags; struct sk_buff *new_skb = NULL; dma_addr_t dma_address; struct tx_pkt_info *pkt; int rcu_id; if (id >= BAM_DMUX_NUM_CHANNELS) return -EINVAL; if (!skb) return -EINVAL; if (!bam_mux_initialized) return -ENODEV; rcu_id = srcu_read_lock(&bam_dmux_srcu); if (in_global_reset) { BAM_DMUX_LOG("%s: In SSR... ch_id[%d]\n", __func__, id); srcu_read_unlock(&bam_dmux_srcu, rcu_id); return -EFAULT; } DBG("%s: writing to ch %d len %d\n", __func__, id, skb->len); spin_lock_irqsave(&bam_ch[id].lock, flags); if (!bam_ch_is_open(id)) { spin_unlock_irqrestore(&bam_ch[id].lock, flags); pr_err("%s: port not open: %d\n", __func__, bam_ch[id].status); srcu_read_unlock(&bam_dmux_srcu, rcu_id); return -ENODEV; } if (bam_ch[id].use_wm && (bam_ch[id].num_tx_pkts >= HIGH_WATERMARK)) { spin_unlock_irqrestore(&bam_ch[id].lock, flags); pr_err("%s: watermark exceeded: %d\n", __func__, id); srcu_read_unlock(&bam_dmux_srcu, rcu_id); return -EAGAIN; } spin_unlock_irqrestore(&bam_ch[id].lock, flags); read_lock(&ul_wakeup_lock); if (!bam_is_connected) { read_unlock(&ul_wakeup_lock); ul_wakeup(); if (unlikely(in_global_reset == 1)) { srcu_read_unlock(&bam_dmux_srcu, rcu_id); return -EFAULT; } read_lock(&ul_wakeup_lock); notify_all(BAM_DMUX_UL_CONNECTED, (unsigned long)(NULL)); } /* if skb do not have any tailroom for padding, copy the skb into a new expanded skb */ if ((skb->len & 0x3) && (skb_tailroom(skb) < (4 - (skb->len & 0x3)))) { /* revisit, probably dev_alloc_skb and memcpy is effecient */ new_skb = skb_copy_expand(skb, skb_headroom(skb), 4 - (skb->len & 0x3), GFP_ATOMIC); if (new_skb == NULL) { pr_err("%s: cannot allocate skb\n", __func__); goto write_fail; } dev_kfree_skb_any(skb); skb = new_skb; DBG_INC_WRITE_CPY(skb->len); } hdr = (struct bam_mux_hdr *)skb_push(skb, sizeof(struct bam_mux_hdr)); /* caller should allocate for hdr and padding hdr is fine, padding is tricky */ hdr->magic_num = BAM_MUX_HDR_MAGIC_NO; hdr->cmd = BAM_MUX_HDR_CMD_DATA; hdr->signal = 0; hdr->ch_id = id; hdr->pkt_len = skb->len - sizeof(struct bam_mux_hdr); if (skb->len & 0x3) skb_put(skb, 4 - (skb->len & 0x3)); hdr->pad_len = skb->len - (sizeof(struct bam_mux_hdr) + hdr->pkt_len); DBG("%s: data %p, tail %p skb len %d pkt len %d pad len %d\n", __func__, skb->data, skb_tail_pointer(skb), skb->len, hdr->pkt_len, hdr->pad_len); pkt = kmalloc(sizeof(struct tx_pkt_info), GFP_ATOMIC); if (pkt == NULL) { pr_err("%s: mem alloc for tx_pkt_info failed\n", __func__); goto write_fail2; } dma_address = dma_map_single(dma_dev, skb->data, skb->len, bam_ops->dma_to); if (!dma_address) { pr_err("%s: dma_map_single() failed\n", __func__); goto write_fail3; } pkt->skb = skb; pkt->dma_address = dma_address; pkt->is_cmd = 0; set_tx_timestamp(pkt); INIT_WORK(&pkt->work, bam_mux_write_done); spin_lock_irqsave(&bam_tx_pool_spinlock, flags); list_add_tail(&pkt->list_node, &bam_tx_pool); rc = bam_ops->sps_transfer_one_ptr(bam_tx_pipe, dma_address, skb->len, pkt, SPS_IOVEC_FLAG_EOT); if (rc) { DMUX_LOG_KERR("%s sps_transfer_one failed rc=%d\n", __func__, rc); list_del(&pkt->list_node); DBG_INC_TX_SPS_FAILURE_CNT(); spin_unlock_irqrestore(&bam_tx_pool_spinlock, flags); dma_unmap_single(dma_dev, pkt->dma_address, pkt->skb->len, bam_ops->dma_to); kfree(pkt); if (new_skb) dev_kfree_skb_any(new_skb); } else { spin_unlock_irqrestore(&bam_tx_pool_spinlock, flags); spin_lock_irqsave(&bam_ch[id].lock, flags); bam_ch[id].num_tx_pkts++; spin_unlock_irqrestore(&bam_ch[id].lock, flags); } ul_packet_written = 1; read_unlock(&ul_wakeup_lock); srcu_read_unlock(&bam_dmux_srcu, rcu_id); return rc; write_fail3: kfree(pkt); write_fail2: skb_pull(skb, sizeof(struct bam_mux_hdr)); if (new_skb) dev_kfree_skb_any(new_skb); write_fail: read_unlock(&ul_wakeup_lock); srcu_read_unlock(&bam_dmux_srcu, rcu_id); return -ENOMEM; } /** * create_open_signal() - Generate a proper signal field for outgoing open cmds * * A properly constructed signal field of the mux header for opem commands semt * to the remote side depend on what has been locally configured, and what has * been received from the remote side. The byte value to code translations * must match the valid values in set_rx_buffer_ring_pool() and set_dl_mtu(). * * Return: A properly constructed signal field for an outgoing mux open command. */ static uint8_t create_open_signal(void) { uint8_t signal = 0; uint8_t buff_count = 0; uint8_t dl_size = 0; if (!dynamic_mtu_enabled) return signal; signal = DYNAMIC_MTU_MASK; switch (num_buffers) { case SZ_256: buff_count = 3; break; case SZ_128: buff_count = 2; break; case SZ_64: buff_count = 1; break; case SZ_32: buff_count = 0; break; } signal |= buff_count << DL_POOL_SIZE_SHIFT; switch (dl_mtu) { case SZ_16K: dl_size = 3; break; case SZ_8K: dl_size = 2; break; case SZ_4K: dl_size = 1; break; case SZ_2K: dl_size = 0; break; } signal |= dl_size << MTU_SIZE_SHIFT; return signal; } int msm_bam_dmux_open(uint32_t id, void *priv, void (*notify)(void *, int, unsigned long)) { struct bam_mux_hdr *hdr; unsigned long flags; int rc = 0; DBG("%s: opening ch %d\n", __func__, id); if (!bam_mux_initialized) { DBG("%s: not inititialized\n", __func__); return -ENODEV; } if (id >= BAM_DMUX_NUM_CHANNELS) { pr_err("%s: invalid channel id %d\n", __func__, id); return -EINVAL; } if (notify == NULL) { pr_err("%s: notify function is NULL\n", __func__); return -EINVAL; } hdr = kmalloc(sizeof(struct bam_mux_hdr), GFP_KERNEL); if (hdr == NULL) { pr_err("%s: hdr kmalloc failed. ch: %d\n", __func__, id); return -ENOMEM; } spin_lock_irqsave(&bam_ch[id].lock, flags); if (bam_ch_is_open(id)) { DBG("%s: Already opened %d\n", __func__, id); spin_unlock_irqrestore(&bam_ch[id].lock, flags); kfree(hdr); goto open_done; } if (!bam_ch_is_remote_open(id)) { DBG("%s: Remote not open; ch: %d\n", __func__, id); spin_unlock_irqrestore(&bam_ch[id].lock, flags); kfree(hdr); return -ENODEV; } bam_ch[id].notify = notify; bam_ch[id].priv = priv; bam_ch[id].status |= BAM_CH_LOCAL_OPEN; bam_ch[id].num_tx_pkts = 0; bam_ch[id].use_wm = 0; spin_unlock_irqrestore(&bam_ch[id].lock, flags); notify(priv, BAM_DMUX_TRANSMIT_SIZE, ul_mtu); read_lock(&ul_wakeup_lock); if (!bam_is_connected) { read_unlock(&ul_wakeup_lock); ul_wakeup(); if (unlikely(in_global_reset == 1)) { kfree(hdr); return -EFAULT; } read_lock(&ul_wakeup_lock); notify_all(BAM_DMUX_UL_CONNECTED, (unsigned long)(NULL)); } hdr->magic_num = BAM_MUX_HDR_MAGIC_NO; hdr->cmd = BAM_MUX_HDR_CMD_OPEN; hdr->signal = create_open_signal(); hdr->ch_id = id; hdr->pkt_len = 0; hdr->pad_len = 0; rc = bam_mux_write_cmd((void *)hdr, sizeof(struct bam_mux_hdr)); read_unlock(&ul_wakeup_lock); open_done: DBG("%s: opened ch %d\n", __func__, id); return rc; } int msm_bam_dmux_close(uint32_t id) { struct bam_mux_hdr *hdr; unsigned long flags; int rc; if (id >= BAM_DMUX_NUM_CHANNELS) return -EINVAL; DBG("%s: closing ch %d\n", __func__, id); if (!bam_mux_initialized || !bam_ch_is_local_open(id)) return -ENODEV; read_lock(&ul_wakeup_lock); if (!bam_is_connected && !bam_ch_is_in_reset(id)) { read_unlock(&ul_wakeup_lock); ul_wakeup(); if (unlikely(in_global_reset == 1)) return -EFAULT; read_lock(&ul_wakeup_lock); notify_all(BAM_DMUX_UL_CONNECTED, (unsigned long)(NULL)); } spin_lock_irqsave(&bam_ch[id].lock, flags); bam_ch[id].notify = NULL; bam_ch[id].priv = NULL; bam_ch[id].status &= ~BAM_CH_LOCAL_OPEN; spin_unlock_irqrestore(&bam_ch[id].lock, flags); if (bam_ch_is_in_reset(id)) { read_unlock(&ul_wakeup_lock); bam_ch[id].status &= ~BAM_CH_IN_RESET; return 0; } hdr = kmalloc(sizeof(struct bam_mux_hdr), GFP_ATOMIC); if (hdr == NULL) { pr_err("%s: hdr kmalloc failed. ch: %d\n", __func__, id); read_unlock(&ul_wakeup_lock); return -ENOMEM; } hdr->magic_num = BAM_MUX_HDR_MAGIC_NO; hdr->cmd = BAM_MUX_HDR_CMD_CLOSE; hdr->signal = 0; hdr->ch_id = id; hdr->pkt_len = 0; hdr->pad_len = 0; rc = bam_mux_write_cmd((void *)hdr, sizeof(struct bam_mux_hdr)); read_unlock(&ul_wakeup_lock); DBG("%s: closed ch %d\n", __func__, id); return rc; } int msm_bam_dmux_is_ch_full(uint32_t id) { unsigned long flags; int ret; if (id >= BAM_DMUX_NUM_CHANNELS) return -EINVAL; spin_lock_irqsave(&bam_ch[id].lock, flags); bam_ch[id].use_wm = 1; ret = bam_ch[id].num_tx_pkts >= HIGH_WATERMARK; DBG("%s: ch %d num tx pkts=%d, HWM=%d\n", __func__, id, bam_ch[id].num_tx_pkts, ret); if (!bam_ch_is_local_open(id)) { ret = -ENODEV; pr_err("%s: port not open: %d\n", __func__, bam_ch[id].status); } spin_unlock_irqrestore(&bam_ch[id].lock, flags); return ret; } int msm_bam_dmux_is_ch_low(uint32_t id) { unsigned long flags; int ret; if (id >= BAM_DMUX_NUM_CHANNELS) return -EINVAL; spin_lock_irqsave(&bam_ch[id].lock, flags); bam_ch[id].use_wm = 1; ret = bam_ch[id].num_tx_pkts <= LOW_WATERMARK; DBG("%s: ch %d num tx pkts=%d, LWM=%d\n", __func__, id, bam_ch[id].num_tx_pkts, ret); if (!bam_ch_is_local_open(id)) { ret = -ENODEV; pr_err("%s: port not open: %d\n", __func__, bam_ch[id].status); } spin_unlock_irqrestore(&bam_ch[id].lock, flags); return ret; } static void rx_switch_to_interrupt_mode(void) { struct sps_connect cur_rx_conn; struct sps_iovec iov; struct rx_pkt_info *info; int ret; /* * Attempt to enable interrupts - if this fails, * continue polling and we will retry later. */ ret = bam_ops->sps_get_config_ptr(bam_rx_pipe, &cur_rx_conn); if (ret) { pr_err("%s: sps_get_config() failed %d\n", __func__, ret); goto fail; } rx_register_event.options = SPS_O_EOT; ret = bam_ops->sps_register_event_ptr(bam_rx_pipe, &rx_register_event); if (ret) { pr_err("%s: sps_register_event() failed %d\n", __func__, ret); goto fail; } cur_rx_conn.options = SPS_O_AUTO_ENABLE | SPS_O_EOT | SPS_O_ACK_TRANSFERS; ret = bam_ops->sps_set_config_ptr(bam_rx_pipe, &cur_rx_conn); if (ret) { pr_err("%s: sps_set_config() failed %d\n", __func__, ret); goto fail; } polling_mode = 0; complete_all(&shutdown_completion); release_wakelock(); /* handle any rx packets before interrupt was enabled */ while (bam_connection_is_active && !polling_mode) { ret = bam_ops->sps_get_iovec_ptr(bam_rx_pipe, &iov); if (ret) { pr_err("%s: sps_get_iovec failed %d\n", __func__, ret); break; } if (iov.addr == 0) break; mutex_lock(&bam_rx_pool_mutexlock); if (unlikely(list_empty(&bam_rx_pool))) { DMUX_LOG_KERR("%s: have iovec %p but rx pool empty\n", __func__, (void *)(uintptr_t)iov.addr); mutex_unlock(&bam_rx_pool_mutexlock); continue; } info = list_first_entry(&bam_rx_pool, struct rx_pkt_info, list_node); if (info->dma_address != iov.addr) { DMUX_LOG_KERR("%s: iovec %p != dma %p\n", __func__, (void *)(uintptr_t)iov.addr, (void *)(uintptr_t)info->dma_address); list_for_each_entry(info, &bam_rx_pool, list_node) { DMUX_LOG_KERR("%s: dma %p\n", __func__, (void *)(uintptr_t)info->dma_address); if (iov.addr == info->dma_address) break; } } BUG_ON(info->dma_address != iov.addr); list_del(&info->list_node); --bam_rx_pool_len; mutex_unlock(&bam_rx_pool_mutexlock); info->sps_size = iov.size; handle_bam_mux_cmd(&info->work); } return; fail: pr_err("%s: reverting to polling\n", __func__); if (no_cpu_affinity) queue_work(bam_mux_rx_workqueue, &rx_timer_work); else queue_work_on(0, bam_mux_rx_workqueue, &rx_timer_work); } /** * store_rx_timestamp() - store the current raw time as as a timestamp for when * the last rx packet was processed */ static void store_rx_timestamp(void) { last_rx_pkt_timestamp = sched_clock(); } /** * log_rx_timestamp() - Log the stored rx pkt timestamp in a human readable * format */ static void log_rx_timestamp(void) { unsigned long long t = last_rx_pkt_timestamp; unsigned long nanosec_rem; nanosec_rem = do_div(t, 1000000000U); BAM_DMUX_LOG("Last rx pkt processed at [%6u.%09lu]\n", (unsigned)t, nanosec_rem); } static void rx_timer_work_func(struct work_struct *work) { struct sps_iovec iov; struct rx_pkt_info *info; int inactive_cycles = 0; int ret; u32 buffs_unused, buffs_used; BAM_DMUX_LOG("%s: polling start\n", __func__); while (bam_connection_is_active) { /* timer loop */ ++inactive_cycles; while (bam_connection_is_active) { /* deplete queue loop */ if (in_global_reset) { BAM_DMUX_LOG( "%s: polling exit, global reset detected\n", __func__); return; } ret = bam_ops->sps_get_iovec_ptr(bam_rx_pipe, &iov); if (ret) { DMUX_LOG_KERR("%s: sps_get_iovec failed %d\n", __func__, ret); break; } if (iov.addr == 0) break; store_rx_timestamp(); inactive_cycles = 0; mutex_lock(&bam_rx_pool_mutexlock); if (unlikely(list_empty(&bam_rx_pool))) { DMUX_LOG_KERR( "%s: have iovec %p but rx pool empty\n", __func__, (void *)(uintptr_t)iov.addr); mutex_unlock(&bam_rx_pool_mutexlock); continue; } info = list_first_entry(&bam_rx_pool, struct rx_pkt_info, list_node); if (info->dma_address != iov.addr) { DMUX_LOG_KERR("%s: iovec %p != dma %p\n", __func__, (void *)(uintptr_t)iov.addr, (void *)(uintptr_t)info->dma_address); list_for_each_entry(info, &bam_rx_pool, list_node) { DMUX_LOG_KERR("%s: dma %p\n", __func__, (void *)(uintptr_t) info->dma_address); if (iov.addr == info->dma_address) break; } } BUG_ON(info->dma_address != iov.addr); list_del(&info->list_node); --bam_rx_pool_len; mutex_unlock(&bam_rx_pool_mutexlock); info->sps_size = iov.size; handle_bam_mux_cmd(&info->work); } if (inactive_cycles >= POLLING_INACTIVITY) { BAM_DMUX_LOG("%s: polling exit, no data\n", __func__); rx_switch_to_interrupt_mode(); break; } if (bam_adaptive_timer_enabled) { usleep_range(rx_timer_interval, rx_timer_interval + 50); ret = bam_ops->sps_get_unused_desc_num_ptr(bam_rx_pipe, &buffs_unused); if (ret) { DMUX_LOG_KERR( "%s: error getting num buffers unused after sleep\n", __func__); break; } buffs_used = num_buffers - buffs_unused; if (buffs_unused == 0) { rx_timer_interval = MIN_POLLING_SLEEP; } else { if (buffs_used > 0) { rx_timer_interval = (2 * num_buffers * rx_timer_interval)/ (3 * buffs_used); } else { rx_timer_interval = MAX_POLLING_SLEEP; } } if (rx_timer_interval > MAX_POLLING_SLEEP) rx_timer_interval = MAX_POLLING_SLEEP; else if (rx_timer_interval < MIN_POLLING_SLEEP) rx_timer_interval = MIN_POLLING_SLEEP; } else { usleep_range(POLLING_MIN_SLEEP, POLLING_MAX_SLEEP); } } } static void bam_mux_tx_notify(struct sps_event_notify *notify) { struct tx_pkt_info *pkt; DBG("%s: event %d notified\n", __func__, notify->event_id); if (in_global_reset) return; switch (notify->event_id) { case SPS_EVENT_EOT: pkt = notify->data.transfer.user; if (!pkt->is_cmd) dma_unmap_single(dma_dev, pkt->dma_address, pkt->skb->len, bam_ops->dma_to); else dma_unmap_single(dma_dev, pkt->dma_address, pkt->len, bam_ops->dma_to); queue_work(bam_mux_tx_workqueue, &pkt->work); break; default: pr_err("%s: recieved unexpected event id %d\n", __func__, notify->event_id); } } static void bam_mux_rx_notify(struct sps_event_notify *notify) { int ret; struct sps_connect cur_rx_conn; DBG("%s: event %d notified\n", __func__, notify->event_id); if (in_global_reset) return; switch (notify->event_id) { case SPS_EVENT_EOT: /* attempt to disable interrupts in this pipe */ if (!polling_mode) { ret = bam_ops->sps_get_config_ptr(bam_rx_pipe, &cur_rx_conn); if (ret) { pr_err("%s: sps_get_config() failed %d, interrupts" " not disabled\n", __func__, ret); break; } cur_rx_conn.options = SPS_O_AUTO_ENABLE | SPS_O_ACK_TRANSFERS | SPS_O_POLL; ret = bam_ops->sps_set_config_ptr(bam_rx_pipe, &cur_rx_conn); if (ret) { pr_err("%s: sps_set_config() failed %d, interrupts" " not disabled\n", __func__, ret); break; } INIT_COMPLETION(shutdown_completion); grab_wakelock(); polling_mode = 1; /* * run on core 0 so that netif_rx() in rmnet uses only * one queue if RPS enable use no_cpu_affinity */ if (no_cpu_affinity) queue_work(bam_mux_rx_workqueue, &rx_timer_work); else queue_work_on(0, bam_mux_rx_workqueue, &rx_timer_work); } break; default: pr_err("%s: recieved unexpected event id %d\n", __func__, notify->event_id); } } #ifdef CONFIG_DEBUG_FS static int debug_tbl(char *buf, int max) { int i = 0; int j; for (j = 0; j < BAM_DMUX_NUM_CHANNELS; ++j) { i += scnprintf(buf + i, max - i, "ch%02d local open=%s remote open=%s\n", j, bam_ch_is_local_open(j) ? "Y" : "N", bam_ch_is_remote_open(j) ? "Y" : "N"); } return i; } static int debug_ul_pkt_cnt(char *buf, int max) { struct list_head *p; unsigned long flags; int n = 0; spin_lock_irqsave(&bam_tx_pool_spinlock, flags); __list_for_each(p, &bam_tx_pool) { ++n; } spin_unlock_irqrestore(&bam_tx_pool_spinlock, flags); return scnprintf(buf, max, "Number of UL packets in flight: %d\n", n); } static int debug_stats(char *buf, int max) { int i = 0; i += scnprintf(buf + i, max - i, "skb read cnt: %u\n" "skb write cnt: %u\n" "skb copy cnt: %u\n" "skb copy bytes: %u\n" "sps tx failures: %u\n" "sps tx stalls: %u\n" "rx queue len: %d\n" "a2 ack out cnt: %d\n" "a2 ack in cnt: %d\n" "a2 pwr cntl in: %d\n", bam_dmux_read_cnt, bam_dmux_write_cnt, bam_dmux_write_cpy_cnt, bam_dmux_write_cpy_bytes, bam_dmux_tx_sps_failure_cnt, bam_dmux_tx_stall_cnt, bam_rx_pool_len, atomic_read(&bam_dmux_ack_out_cnt), atomic_read(&bam_dmux_ack_in_cnt), atomic_read(&bam_dmux_a2_pwr_cntl_in_cnt) ); return i; } #define DEBUG_BUFMAX 4096 static char debug_buffer[DEBUG_BUFMAX]; static ssize_t debug_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { int (*fill)(char *buf, int max) = file->private_data; int bsize = fill(debug_buffer, DEBUG_BUFMAX); return simple_read_from_buffer(buf, count, ppos, debug_buffer, bsize); } static int debug_open(struct inode *inode, struct file *file) { file->private_data = inode->i_private; return 0; } static const struct file_operations debug_ops = { .read = debug_read, .open = debug_open, }; static void debug_create(const char *name, mode_t mode, struct dentry *dent, int (*fill)(char *buf, int max)) { struct dentry *file; file = debugfs_create_file(name, mode, dent, fill, &debug_ops); if (IS_ERR(file)) pr_err("%s: debugfs create failed %d\n", __func__, (int)PTR_ERR(file)); } #endif static void notify_all(int event, unsigned long data) { int i; unsigned long flags; struct list_head *temp; struct outside_notify_func *func; void (*notify)(void *, int, unsigned long); void *priv; BAM_DMUX_LOG("%s: event=%d, data=%lu\n", __func__, event, data); for (i = 0; i < BAM_DMUX_NUM_CHANNELS; ++i) { notify = NULL; priv = NULL; spin_lock_irqsave(&bam_ch[i].lock, flags); if (bam_ch_is_open(i)) { notify = bam_ch[i].notify; priv = bam_ch[i].priv; } spin_unlock_irqrestore(&bam_ch[i].lock, flags); if (notify) notify(priv, event, data); } __list_for_each(temp, &bam_other_notify_funcs) { func = container_of(temp, struct outside_notify_func, list_node); func->notify(func->priv, event, data); } } static void kickoff_ul_wakeup_func(struct work_struct *work) { read_lock(&ul_wakeup_lock); if (!bam_is_connected) { read_unlock(&ul_wakeup_lock); ul_wakeup(); if (unlikely(in_global_reset == 1)) return; read_lock(&ul_wakeup_lock); ul_packet_written = 1; notify_all(BAM_DMUX_UL_CONNECTED, (unsigned long)(NULL)); } read_unlock(&ul_wakeup_lock); } int msm_bam_dmux_kickoff_ul_wakeup(void) { int is_connected; read_lock(&ul_wakeup_lock); ul_packet_written = 1; is_connected = bam_is_connected; if (!is_connected) queue_work(bam_mux_tx_workqueue, &kickoff_ul_wakeup); read_unlock(&ul_wakeup_lock); return is_connected; } static void power_vote(int vote) { BAM_DMUX_LOG("%s: curr=%d, vote=%d\n", __func__, bam_dmux_uplink_vote, vote); if (bam_dmux_uplink_vote == vote) BAM_DMUX_LOG("%s: warning - duplicate power vote\n", __func__); bam_dmux_uplink_vote = vote; if (vote) bam_ops->smsm_change_state_ptr(SMSM_APPS_STATE, 0, SMSM_A2_POWER_CONTROL); else bam_ops->smsm_change_state_ptr(SMSM_APPS_STATE, SMSM_A2_POWER_CONTROL, 0); } /* * @note: Must be called with ul_wakeup_lock locked. */ static inline void ul_powerdown(void) { BAM_DMUX_LOG("%s: powerdown\n", __func__); verify_tx_queue_is_empty(__func__); if (a2_pc_disabled) { wait_for_dfab = 1; INIT_COMPLETION(dfab_unvote_completion); release_wakelock(); } else { wait_for_ack = 1; INIT_COMPLETION(ul_wakeup_ack_completion); power_vote(0); } bam_is_connected = 0; notify_all(BAM_DMUX_UL_DISCONNECTED, (unsigned long)(NULL)); } static inline void ul_powerdown_finish(void) { if (a2_pc_disabled && wait_for_dfab) { unvote_dfab(); complete_all(&dfab_unvote_completion); wait_for_dfab = 0; } } /* * Votes for UL power and returns current power state. * * @returns true if currently connected */ int msm_bam_dmux_ul_power_vote(void) { int is_connected; read_lock(&ul_wakeup_lock); atomic_inc(&ul_ondemand_vote); is_connected = bam_is_connected; if (!is_connected) queue_work(bam_mux_tx_workqueue, &kickoff_ul_wakeup); read_unlock(&ul_wakeup_lock); return is_connected; } /* * Unvotes for UL power. * * @returns true if vote count is 0 (UL shutdown possible) */ int msm_bam_dmux_ul_power_unvote(void) { int vote; read_lock(&ul_wakeup_lock); vote = atomic_dec_return(&ul_ondemand_vote); if (unlikely(vote) < 0) DMUX_LOG_KERR("%s: invalid power vote %d\n", __func__, vote); read_unlock(&ul_wakeup_lock); return vote == 0; } int msm_bam_dmux_reg_notify(void *priv, void (*notify)(void *priv, int event_type, unsigned long data)) { struct outside_notify_func *func; if (!notify) return -EINVAL; func = kmalloc(sizeof(struct outside_notify_func), GFP_KERNEL); if (!func) return -ENOMEM; func->notify = notify; func->priv = priv; list_add(&func->list_node, &bam_other_notify_funcs); return 0; } static void ul_timeout(struct work_struct *work) { unsigned long flags; int ret; if (in_global_reset) return; ret = write_trylock_irqsave(&ul_wakeup_lock, flags); if (!ret) { /* failed to grab lock, reschedule and bail */ schedule_delayed_work(&ul_timeout_work, msecs_to_jiffies(UL_TIMEOUT_DELAY)); return; } if (bam_is_connected) { if (!ul_packet_written) { spin_lock(&bam_tx_pool_spinlock); if (!list_empty(&bam_tx_pool)) { struct tx_pkt_info *info; info = list_first_entry(&bam_tx_pool, struct tx_pkt_info, list_node); DMUX_LOG_KERR("%s: UL delayed ts=%u.%09lu\n", __func__, info->ts_sec, info->ts_nsec); DBG_INC_TX_STALL_CNT(); ul_packet_written = 1; } spin_unlock(&bam_tx_pool_spinlock); } if (ul_packet_written || atomic_read(&ul_ondemand_vote)) { BAM_DMUX_LOG("%s: pkt written %d\n", __func__, ul_packet_written); ul_packet_written = 0; schedule_delayed_work(&ul_timeout_work, msecs_to_jiffies(UL_TIMEOUT_DELAY)); } else { ul_powerdown(); } } write_unlock_irqrestore(&ul_wakeup_lock, flags); ul_powerdown_finish(); } static int ssrestart_check(void) { int ret = 0; if (in_global_reset) { DMUX_LOG_KERR("%s: already in SSR\n", __func__); return 1; } DMUX_LOG_KERR( "%s: fatal modem interaction: BAM DMUX disabled for SSR\n", __func__); in_global_reset = 1; ret = subsystem_restart("modem"); if (ret == -ENODEV) panic("modem subsystem restart failed\n"); return 1; } static void ul_wakeup(void) { int ret; int do_vote_dfab = 0; mutex_lock(&wakeup_lock); if (bam_is_connected) { /* bam got connected before lock grabbed */ BAM_DMUX_LOG("%s Already awake\n", __func__); mutex_unlock(&wakeup_lock); return; } /* * if this gets hit, that means restart_notifier_cb() has started * but probably not finished, thus we know SSR has happened, but * haven't been able to send that info to our clients yet. * in that case, abort the ul_wakeup() so that we don't undo any * work restart_notifier_cb() has done. The clients will be notified * shortly. No cleanup necessary (reschedule the wakeup) as our and * their SSR handling will cover it */ if (unlikely(in_global_reset == 1)) { mutex_unlock(&wakeup_lock); return; } /* * if someone is voting for UL before bam is inited (modem up first * time), set flag for init to kickoff ul wakeup once bam is inited */ mutex_lock(&delayed_ul_vote_lock); if (unlikely(!bam_mux_initialized)) { need_delayed_ul_vote = 1; mutex_unlock(&delayed_ul_vote_lock); mutex_unlock(&wakeup_lock); return; } mutex_unlock(&delayed_ul_vote_lock); if (a2_pc_disabled) { /* * don't grab the wakelock the first time because it is * already grabbed when a2 powers on */ if (likely(a2_pc_disabled_wakelock_skipped)) { grab_wakelock(); do_vote_dfab = 1; /* vote must occur after wait */ } else { a2_pc_disabled_wakelock_skipped = 1; } if (wait_for_dfab) { ret = wait_for_completion_timeout( &dfab_unvote_completion, HZ); BUG_ON(ret == 0); } if (likely(do_vote_dfab)) vote_dfab(); schedule_delayed_work(&ul_timeout_work, msecs_to_jiffies(UL_TIMEOUT_DELAY)); bam_is_connected = 1; mutex_unlock(&wakeup_lock); return; } /* * must wait for the previous power down request to have been acked * chances are it already came in and this will just fall through * instead of waiting */ if (wait_for_ack) { BAM_DMUX_LOG("%s waiting for previous ack\n", __func__); ret = wait_for_completion_timeout( &ul_wakeup_ack_completion, msecs_to_jiffies(UL_WAKEUP_TIMEOUT_MS)); wait_for_ack = 0; if (unlikely(ret == 0) && ssrestart_check()) { mutex_unlock(&wakeup_lock); BAM_DMUX_LOG("%s timeout previous ack\n", __func__); return; } } INIT_COMPLETION(ul_wakeup_ack_completion); power_vote(1); BAM_DMUX_LOG("%s waiting for wakeup ack\n", __func__); ret = wait_for_completion_timeout(&ul_wakeup_ack_completion, msecs_to_jiffies(UL_WAKEUP_TIMEOUT_MS)); if (unlikely(ret == 0) && ssrestart_check()) { mutex_unlock(&wakeup_lock); BAM_DMUX_LOG("%s timeout wakeup ack\n", __func__); return; } BAM_DMUX_LOG("%s waiting completion\n", __func__); ret = wait_for_completion_timeout(&bam_connection_completion, msecs_to_jiffies(UL_WAKEUP_TIMEOUT_MS)); if (unlikely(ret == 0) && ssrestart_check()) { mutex_unlock(&wakeup_lock); BAM_DMUX_LOG("%s timeout power on\n", __func__); return; } bam_is_connected = 1; BAM_DMUX_LOG("%s complete\n", __func__); schedule_delayed_work(&ul_timeout_work, msecs_to_jiffies(UL_TIMEOUT_DELAY)); mutex_unlock(&wakeup_lock); } static void reconnect_to_bam(void) { int i; in_global_reset = 0; in_ssr = 0; vote_dfab(); if (ssr_skipped_disconnect) { /* delayed to here to prevent bus stall */ bam_ops->sps_disconnect_ptr(bam_tx_pipe); bam_ops->sps_disconnect_ptr(bam_rx_pipe); memset(rx_desc_mem_buf.base, 0, rx_desc_mem_buf.size); memset(tx_desc_mem_buf.base, 0, tx_desc_mem_buf.size); } ssr_skipped_disconnect = 0; i = bam_ops->sps_device_reset_ptr(a2_device_handle); if (i) pr_err("%s: device reset failed rc = %d\n", __func__, i); i = bam_ops->sps_connect_ptr(bam_tx_pipe, &tx_connection); if (i) pr_err("%s: tx connection failed rc = %d\n", __func__, i); i = bam_ops->sps_connect_ptr(bam_rx_pipe, &rx_connection); if (i) pr_err("%s: rx connection failed rc = %d\n", __func__, i); i = bam_ops->sps_register_event_ptr(bam_tx_pipe, &tx_register_event); if (i) pr_err("%s: tx event reg failed rc = %d\n", __func__, i); i = bam_ops->sps_register_event_ptr(bam_rx_pipe, &rx_register_event); if (i) pr_err("%s: rx event reg failed rc = %d\n", __func__, i); bam_connection_is_active = 1; if (polling_mode) rx_switch_to_interrupt_mode(); toggle_apps_ack(); complete_all(&bam_connection_completion); queue_rx(); } static void disconnect_to_bam(void) { struct list_head *node; struct rx_pkt_info *info; unsigned long flags; unsigned long time_remaining; if (!in_global_reset) { time_remaining = wait_for_completion_timeout( &shutdown_completion, msecs_to_jiffies(SHUTDOWN_TIMEOUT_MS)); if (time_remaining == 0) { DMUX_LOG_KERR("%s: shutdown completion timed out\n", __func__); log_rx_timestamp(); ssrestart_check(); } } bam_connection_is_active = 0; /* handle disconnect during active UL */ write_lock_irqsave(&ul_wakeup_lock, flags); if (bam_is_connected) { BAM_DMUX_LOG("%s: UL active - forcing powerdown\n", __func__); ul_powerdown(); } write_unlock_irqrestore(&ul_wakeup_lock, flags); ul_powerdown_finish(); /* tear down BAM connection */ INIT_COMPLETION(bam_connection_completion); /* in_ssr documentation/assumptions found in restart_notifier_cb */ if (likely(!in_ssr)) { BAM_DMUX_LOG("%s: disconnect tx\n", __func__); bam_ops->sps_disconnect_ptr(bam_tx_pipe); BAM_DMUX_LOG("%s: disconnect rx\n", __func__); bam_ops->sps_disconnect_ptr(bam_rx_pipe); memset(rx_desc_mem_buf.base, 0, rx_desc_mem_buf.size); memset(tx_desc_mem_buf.base, 0, tx_desc_mem_buf.size); BAM_DMUX_LOG("%s: device reset\n", __func__); bam_ops->sps_device_reset_ptr(a2_device_handle); } else { ssr_skipped_disconnect = 1; } unvote_dfab(); mutex_lock(&bam_rx_pool_mutexlock); while (!list_empty(&bam_rx_pool)) { node = bam_rx_pool.next; list_del(node); info = container_of(node, struct rx_pkt_info, list_node); dma_unmap_single(dma_dev, info->dma_address, info->len, bam_ops->dma_from); dev_kfree_skb_any(info->skb); kfree(info); } bam_rx_pool_len = 0; mutex_unlock(&bam_rx_pool_mutexlock); toggle_apps_ack(); verify_tx_queue_is_empty(__func__); } static void vote_dfab(void) { int rc; BAM_DMUX_LOG("%s\n", __func__); mutex_lock(&dfab_status_lock); if (dfab_is_on) { BAM_DMUX_LOG("%s: dfab is already on\n", __func__); mutex_unlock(&dfab_status_lock); return; } if (dfab_clk) { rc = clk_prepare_enable(dfab_clk); if (rc) DMUX_LOG_KERR("bam_dmux vote for dfab failed rc = %d\n", rc); } if (xo_clk) { rc = clk_prepare_enable(xo_clk); if (rc) DMUX_LOG_KERR("bam_dmux vote for xo failed rc = %d\n", rc); } dfab_is_on = 1; mutex_unlock(&dfab_status_lock); } static void unvote_dfab(void) { BAM_DMUX_LOG("%s\n", __func__); mutex_lock(&dfab_status_lock); if (!dfab_is_on) { DMUX_LOG_KERR("%s: dfab is already off\n", __func__); dump_stack(); mutex_unlock(&dfab_status_lock); return; } if (dfab_clk) clk_disable_unprepare(dfab_clk); if (xo_clk) clk_disable_unprepare(xo_clk); dfab_is_on = 0; mutex_unlock(&dfab_status_lock); } /* reference counting wrapper around wakelock */ static void grab_wakelock(void) { unsigned long flags; spin_lock_irqsave(&wakelock_reference_lock, flags); BAM_DMUX_LOG("%s: ref count = %d\n", __func__, wakelock_reference_count); if (wakelock_reference_count == 0) wake_lock(&bam_wakelock); ++wakelock_reference_count; spin_unlock_irqrestore(&wakelock_reference_lock, flags); } static void release_wakelock(void) { unsigned long flags; spin_lock_irqsave(&wakelock_reference_lock, flags); if (wakelock_reference_count == 0) { DMUX_LOG_KERR("%s: bam_dmux wakelock not locked\n", __func__); dump_stack(); spin_unlock_irqrestore(&wakelock_reference_lock, flags); return; } BAM_DMUX_LOG("%s: ref count = %d\n", __func__, wakelock_reference_count); --wakelock_reference_count; if (wakelock_reference_count == 0) { wake_unlock(&bam_wakelock); #ifdef BAM_DMUX_FD wake_lock_timeout(&bam_wakelock, wakelock_timeout * HZ); #endif } spin_unlock_irqrestore(&wakelock_reference_lock, flags); } static int restart_notifier_cb(struct notifier_block *this, unsigned long code, void *data) { int i; struct list_head *node; struct tx_pkt_info *info; int temp_remote_status; unsigned long flags; /* * Bam_dmux counts on the fact that the BEFORE_SHUTDOWN level of * notifications are guarenteed to execute before the AFTER_SHUTDOWN * level of notifications, and that BEFORE_SHUTDOWN always occurs in * all SSR events, no matter what triggered the SSR. Also, bam_dmux * assumes that SMD does its SSR processing in the AFTER_SHUTDOWN level * thus bam_dmux is guarenteed to detect SSR before SMD, since the * callbacks for all the drivers within the AFTER_SHUTDOWN level could * occur in any order. Bam_dmux uses this knowledge to skip accessing * the bam hardware when disconnect_to_bam() is triggered by SMD's SSR * processing. We do not wat to access the bam hardware during SSR * because a watchdog crash from a bus stall would likely occur. */ if (code == SUBSYS_BEFORE_SHUTDOWN) { BAM_DMUX_LOG("%s: begin\n", __func__); in_global_reset = 1; in_ssr = 1; /* wait till all bam_dmux writes completes */ synchronize_srcu(&bam_dmux_srcu); BAM_DMUX_LOG("%s: ssr signaling complete\n", __func__); flush_workqueue(bam_mux_rx_workqueue); } if (code != SUBSYS_AFTER_SHUTDOWN) return NOTIFY_DONE; /* Handle uplink Powerdown */ write_lock_irqsave(&ul_wakeup_lock, flags); if (bam_is_connected) { ul_powerdown(); wait_for_ack = 0; } /* * if modem crash during ul_wakeup(), power_vote is 1, needs to be * reset to 0. harmless if bam_is_connected check above passes */ power_vote(0); write_unlock_irqrestore(&ul_wakeup_lock, flags); ul_powerdown_finish(); a2_pc_disabled = 0; a2_pc_disabled_wakelock_skipped = 0; process_dynamic_mtu(false); set_ul_mtu(0, true); dynamic_mtu_enabled = false; /* Cleanup Channel States */ mutex_lock(&bam_pdev_mutexlock); for (i = 0; i < BAM_DMUX_NUM_CHANNELS; ++i) { temp_remote_status = bam_ch_is_remote_open(i); bam_ch[i].status &= ~BAM_CH_REMOTE_OPEN; bam_ch[i].num_tx_pkts = 0; if (bam_ch_is_local_open(i)) bam_ch[i].status |= BAM_CH_IN_RESET; if (temp_remote_status) { platform_device_unregister(bam_ch[i].pdev); bam_ch[i].pdev = platform_device_alloc( bam_ch[i].name, 2); } } mutex_unlock(&bam_pdev_mutexlock); /* Cleanup pending UL data */ spin_lock_irqsave(&bam_tx_pool_spinlock, flags); while (!list_empty(&bam_tx_pool)) { node = bam_tx_pool.next; list_del(node); info = container_of(node, struct tx_pkt_info, list_node); if (!info->is_cmd) { dma_unmap_single(dma_dev, info->dma_address, info->skb->len, bam_ops->dma_to); dev_kfree_skb_any(info->skb); } else { dma_unmap_single(dma_dev, info->dma_address, info->len, bam_ops->dma_to); kfree(info->skb); } kfree(info); } spin_unlock_irqrestore(&bam_tx_pool_spinlock, flags); BAM_DMUX_LOG("%s: complete\n", __func__); return NOTIFY_DONE; } static int bam_init(void) { unsigned long h; dma_addr_t dma_addr; int ret; void *a2_virt_addr; int skip_iounmap = 0; in_global_reset = 0; in_ssr = 0; vote_dfab(); /* init BAM */ a2_virt_addr = ioremap_nocache(a2_phys_base, a2_phys_size); if (!a2_virt_addr) { pr_err("%s: ioremap failed\n", __func__); ret = -ENOMEM; goto ioremap_failed; } a2_props.phys_addr = a2_phys_base; a2_props.virt_addr = a2_virt_addr; a2_props.virt_size = a2_phys_size; a2_props.irq = a2_bam_irq; a2_props.options = SPS_BAM_OPT_IRQ_WAKEUP | SPS_BAM_ATMC_MEM; a2_props.num_pipes = A2_NUM_PIPES; a2_props.summing_threshold = A2_SUMMING_THRESHOLD; a2_props.constrained_logging = true; a2_props.logging_number = 1; if (satellite_mode) a2_props.manage = SPS_BAM_MGR_DEVICE_REMOTE; /* need to free on tear down */ ret = bam_ops->sps_register_bam_device_ptr(&a2_props, &h); if (ret < 0) { pr_err("%s: register bam error %d\n", __func__, ret); goto register_bam_failed; } a2_device_handle = h; bam_tx_pipe = bam_ops->sps_alloc_endpoint_ptr(); if (bam_tx_pipe == NULL) { pr_err("%s: tx alloc endpoint failed\n", __func__); ret = -ENOMEM; goto tx_alloc_endpoint_failed; } ret = bam_ops->sps_get_config_ptr(bam_tx_pipe, &tx_connection); if (ret) { pr_err("%s: tx get config failed %d\n", __func__, ret); goto tx_get_config_failed; } tx_connection.source = SPS_DEV_HANDLE_MEM; tx_connection.src_pipe_index = 0; tx_connection.destination = h; tx_connection.dest_pipe_index = 4; tx_connection.mode = SPS_MODE_DEST; tx_connection.options = SPS_O_AUTO_ENABLE | SPS_O_EOT; tx_desc_mem_buf.size = 0x800; /* 2k */ tx_desc_mem_buf.base = dma_alloc_coherent(dma_dev, tx_desc_mem_buf.size, &dma_addr, 0); if (tx_desc_mem_buf.base == NULL) { pr_err("%s: tx memory alloc failed\n", __func__); ret = -ENOMEM; goto tx_get_config_failed; } tx_desc_mem_buf.phys_base = dma_addr; memset(tx_desc_mem_buf.base, 0x0, tx_desc_mem_buf.size); tx_connection.desc = tx_desc_mem_buf; tx_connection.event_thresh = 0x10; ret = bam_ops->sps_connect_ptr(bam_tx_pipe, &tx_connection); if (ret < 0) { pr_err("%s: tx connect error %d\n", __func__, ret); goto tx_connect_failed; } bam_rx_pipe = bam_ops->sps_alloc_endpoint_ptr(); if (bam_rx_pipe == NULL) { pr_err("%s: rx alloc endpoint failed\n", __func__); ret = -ENOMEM; goto rx_alloc_endpoint_failed; } ret = bam_ops->sps_get_config_ptr(bam_rx_pipe, &rx_connection); if (ret) { pr_err("%s: rx get config failed %d\n", __func__, ret); goto rx_get_config_failed; } rx_connection.source = h; rx_connection.src_pipe_index = 5; rx_connection.destination = SPS_DEV_HANDLE_MEM; rx_connection.dest_pipe_index = 1; rx_connection.mode = SPS_MODE_SRC; rx_connection.options = SPS_O_AUTO_ENABLE | SPS_O_EOT | SPS_O_ACK_TRANSFERS; rx_desc_mem_buf.size = 0x800; /* 2k */ rx_desc_mem_buf.base = dma_alloc_coherent(dma_dev, rx_desc_mem_buf.size, &dma_addr, 0); if (rx_desc_mem_buf.base == NULL) { pr_err("%s: rx memory alloc failed\n", __func__); ret = -ENOMEM; goto rx_mem_failed; } rx_desc_mem_buf.phys_base = dma_addr; memset(rx_desc_mem_buf.base, 0x0, rx_desc_mem_buf.size); rx_connection.desc = rx_desc_mem_buf; rx_connection.event_thresh = 0x10; ret = bam_ops->sps_connect_ptr(bam_rx_pipe, &rx_connection); if (ret < 0) { pr_err("%s: rx connect error %d\n", __func__, ret); goto rx_connect_failed; } tx_register_event.options = SPS_O_EOT; tx_register_event.mode = SPS_TRIGGER_CALLBACK; tx_register_event.xfer_done = NULL; tx_register_event.callback = bam_mux_tx_notify; tx_register_event.user = NULL; ret = bam_ops->sps_register_event_ptr(bam_tx_pipe, &tx_register_event); if (ret < 0) { pr_err("%s: tx register event error %d\n", __func__, ret); goto rx_event_reg_failed; } rx_register_event.options = SPS_O_EOT; rx_register_event.mode = SPS_TRIGGER_CALLBACK; rx_register_event.xfer_done = NULL; rx_register_event.callback = bam_mux_rx_notify; rx_register_event.user = NULL; ret = bam_ops->sps_register_event_ptr(bam_rx_pipe, &rx_register_event); if (ret < 0) { pr_err("%s: tx register event error %d\n", __func__, ret); goto rx_event_reg_failed; } mutex_lock(&delayed_ul_vote_lock); bam_mux_initialized = 1; if (need_delayed_ul_vote) { need_delayed_ul_vote = 0; msm_bam_dmux_kickoff_ul_wakeup(); } mutex_unlock(&delayed_ul_vote_lock); toggle_apps_ack(); bam_connection_is_active = 1; complete_all(&bam_connection_completion); queue_rx(); return 0; rx_event_reg_failed: bam_ops->sps_disconnect_ptr(bam_rx_pipe); rx_connect_failed: dma_free_coherent(dma_dev, rx_desc_mem_buf.size, rx_desc_mem_buf.base, rx_desc_mem_buf.phys_base); rx_mem_failed: rx_get_config_failed: bam_ops->sps_free_endpoint_ptr(bam_rx_pipe); rx_alloc_endpoint_failed: bam_ops->sps_disconnect_ptr(bam_tx_pipe); tx_connect_failed: dma_free_coherent(dma_dev, tx_desc_mem_buf.size, tx_desc_mem_buf.base, tx_desc_mem_buf.phys_base); tx_get_config_failed: bam_ops->sps_free_endpoint_ptr(bam_tx_pipe); tx_alloc_endpoint_failed: bam_ops->sps_deregister_bam_device_ptr(h); /* * sps_deregister_bam_device() calls iounmap. calling iounmap on the * same handle below will cause a crash, so skip it if we've freed * the handle here. */ skip_iounmap = 1; register_bam_failed: if (!skip_iounmap) iounmap(a2_virt_addr); ioremap_failed: /*destroy_workqueue(bam_mux_workqueue);*/ return ret; } static void toggle_apps_ack(void) { static unsigned int clear_bit; /* 0 = set the bit, else clear bit */ if (in_global_reset) { BAM_DMUX_LOG("%s: skipped due to SSR\n", __func__); return; } BAM_DMUX_LOG("%s: apps ack %d->%d\n", __func__, clear_bit & 0x1, ~clear_bit & 0x1); bam_ops->smsm_change_state_ptr(SMSM_APPS_STATE, clear_bit & SMSM_A2_POWER_CONTROL_ACK, ~clear_bit & SMSM_A2_POWER_CONTROL_ACK); clear_bit = ~clear_bit; DBG_INC_ACK_OUT_CNT(); } static void bam_dmux_smsm_cb(void *priv, uint32_t old_state, uint32_t new_state) { static int last_processed_state; mutex_lock(&smsm_cb_lock); bam_dmux_power_state = new_state & SMSM_A2_POWER_CONTROL ? 1 : 0; DBG_INC_A2_POWER_CONTROL_IN_CNT(); BAM_DMUX_LOG("%s: 0x%08x -> 0x%08x\n", __func__, old_state, new_state); if (last_processed_state == (new_state & SMSM_A2_POWER_CONTROL)) { BAM_DMUX_LOG("%s: already processed this state\n", __func__); mutex_unlock(&smsm_cb_lock); return; } last_processed_state = new_state & SMSM_A2_POWER_CONTROL; if (bam_mux_initialized && new_state & SMSM_A2_POWER_CONTROL) { BAM_DMUX_LOG("%s: reconnect\n", __func__); grab_wakelock(); reconnect_to_bam(); } else if (bam_mux_initialized && !(new_state & SMSM_A2_POWER_CONTROL)) { BAM_DMUX_LOG("%s: disconnect\n", __func__); disconnect_to_bam(); release_wakelock(); } else if (new_state & SMSM_A2_POWER_CONTROL) { BAM_DMUX_LOG("%s: init\n", __func__); grab_wakelock(); bam_init(); } else { BAM_DMUX_LOG("%s: bad state change\n", __func__); pr_err("%s: unsupported state change\n", __func__); } mutex_unlock(&smsm_cb_lock); } static void bam_dmux_smsm_ack_cb(void *priv, uint32_t old_state, uint32_t new_state) { DBG_INC_ACK_IN_CNT(); BAM_DMUX_LOG("%s: 0x%08x -> 0x%08x\n", __func__, old_state, new_state); complete_all(&ul_wakeup_ack_completion); } /** * msm_bam_dmux_set_bam_ops() - sets the bam_ops * @ops: bam_ops_if to set * * Sets bam_ops to allow switching of runtime behavior. Preconditon, bam dmux * must be in an idle state. If input ops is NULL, then bam_ops will be * restored to their default state. */ void msm_bam_dmux_set_bam_ops(struct bam_ops_if *ops) { if (ops != NULL) bam_ops = ops; else bam_ops = &bam_default_ops; } EXPORT_SYMBOL(msm_bam_dmux_set_bam_ops); /** * msm_bam_dmux_deinit() - puts bam dmux into a deinited state * * Puts bam dmux into a deinitialized state by simulating an ssr. */ void msm_bam_dmux_deinit(void) { restart_notifier_cb(NULL, SUBSYS_BEFORE_SHUTDOWN, NULL); restart_notifier_cb(NULL, SUBSYS_AFTER_SHUTDOWN, NULL); in_global_reset = 0; in_ssr = 0; } EXPORT_SYMBOL(msm_bam_dmux_deinit); /** * msm_bam_dmux_reinit() - reinitializes bam dmux */ void msm_bam_dmux_reinit(void) { bam_mux_initialized = 0; bam_ops->smsm_state_cb_register_ptr(SMSM_MODEM_STATE, SMSM_A2_POWER_CONTROL, bam_dmux_smsm_cb, NULL); bam_ops->smsm_state_cb_register_ptr(SMSM_MODEM_STATE, SMSM_A2_POWER_CONTROL_ACK, bam_dmux_smsm_ack_cb, NULL); } EXPORT_SYMBOL(msm_bam_dmux_reinit); /** * set_rx_buffer_ring_pool() - Configure the size of the rx ring pool to a * supported value. * @requested_buffs: Desired pool size. * * The requested size will be reduced to the largest supported size. The * supported sizes must match the values in create_open_signal() for proper * signal field construction in that function. */ static void set_rx_buffer_ring_pool(int requested_buffs) { if (requested_buffs >= SZ_256) { num_buffers = SZ_256; return; } if (requested_buffs >= SZ_128) { num_buffers = SZ_128; return; } if (requested_buffs >= SZ_64) { num_buffers = SZ_64; return; } num_buffers = SZ_32; } /** * set_dl_mtu() - Configure the non-default MTU to a supported value. * @requested_mtu: Desired MTU size. * * Sets the dynamic receive MTU which can be enabled via negotiation with the * remote side. Until the dynamic MTU is enabled, the default MTU will be used. * The requested size will be reduced to the largest supported size. The * supported sizes must match the values in create_open_signal() for proper * signal field construction in that function. */ static void set_dl_mtu(int requested_mtu) { if (requested_mtu >= SZ_16K) { dl_mtu = SZ_16K; return; } if (requested_mtu >= SZ_8K) { dl_mtu = SZ_8K; return; } if (requested_mtu >= SZ_4K) { dl_mtu = SZ_4K; return; } dl_mtu = SZ_2K; } static int bam_dmux_probe(struct platform_device *pdev) { int rc; struct resource *r; void *subsys_h; uint32_t requested_dl_mtu; DBG("%s probe called\n", __func__); if (bam_mux_initialized) return 0; if (pdev->dev.of_node) { r = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!r) { pr_err("%s: reg field missing\n", __func__); return -ENODEV; } a2_phys_base = r->start; a2_phys_size = (uint32_t)(resource_size(r)); a2_bam_irq = platform_get_irq(pdev, 0); if (a2_bam_irq == -ENXIO) { pr_err("%s: irq field missing\n", __func__); return -ENODEV; } satellite_mode = of_property_read_bool(pdev->dev.of_node, "qcom,satellite-mode"); rc = of_property_read_u32(pdev->dev.of_node, "qcom,rx-ring-size", &num_buffers); if (rc) { DBG("%s: falling back to num_buffs default, rc:%d\n", __func__, rc); num_buffers = DEFAULT_NUM_BUFFERS; } set_rx_buffer_ring_pool(num_buffers); rc = of_property_read_u32(pdev->dev.of_node, "qcom,max-rx-mtu", &requested_dl_mtu); if (rc) { DBG("%s: falling back to dl_mtu default, rc:%d\n", __func__, rc); requested_dl_mtu = 0; } set_dl_mtu(requested_dl_mtu); no_cpu_affinity = of_property_read_bool(pdev->dev.of_node, "qcom,no-cpu-affinity"); BAM_DMUX_LOG( "%s: base:%p size:%x irq:%d satellite:%d num_buffs:%d dl_mtu:%x cpu-affinity:%d\n", __func__, (void *)(uintptr_t)a2_phys_base, a2_phys_size, a2_bam_irq, satellite_mode, num_buffers, dl_mtu, no_cpu_affinity); } else { /* fallback to default init data */ a2_phys_base = A2_PHYS_BASE; a2_phys_size = A2_PHYS_SIZE; a2_bam_irq = A2_BAM_IRQ; num_buffers = DEFAULT_NUM_BUFFERS; set_rx_buffer_ring_pool(num_buffers); } dma_dev = &pdev->dev; /* The BAM only suports 32 bits of address */ dma_dev->dma_mask = kmalloc(sizeof(*dma_dev->dma_mask), GFP_KERNEL); if (!dma_dev->dma_mask) { DMUX_LOG_KERR("%s: cannot allocate dma_mask\n", __func__); return -ENOMEM; } *dma_dev->dma_mask = DMA_BIT_MASK(32); dma_dev->coherent_dma_mask = DMA_BIT_MASK(32); xo_clk = clk_get(&pdev->dev, "xo"); if (IS_ERR(xo_clk)) { BAM_DMUX_LOG("%s: did not get xo clock\n", __func__); xo_clk = NULL; } dfab_clk = clk_get(&pdev->dev, "bus_clk"); if (IS_ERR(dfab_clk)) { BAM_DMUX_LOG("%s: did not get dfab clock\n", __func__); dfab_clk = NULL; } else { rc = clk_set_rate(dfab_clk, 64000000); if (rc) pr_err("%s: unable to set dfab clock rate\n", __func__); } /* * setup the workqueue so that it can be pinned to core 0 and not * block the watchdog pet function, so that netif_rx() in rmnet * only uses one queue. */ bam_mux_rx_workqueue = alloc_workqueue("bam_dmux_rx", WQ_MEM_RECLAIM | WQ_CPU_INTENSIVE, 1); if (!bam_mux_rx_workqueue) return -ENOMEM; bam_mux_tx_workqueue = create_singlethread_workqueue("bam_dmux_tx"); if (!bam_mux_tx_workqueue) { destroy_workqueue(bam_mux_rx_workqueue); return -ENOMEM; } for (rc = 0; rc < BAM_DMUX_NUM_CHANNELS; ++rc) { spin_lock_init(&bam_ch[rc].lock); scnprintf(bam_ch[rc].name, BAM_DMUX_CH_NAME_MAX_LEN, "bam_dmux_ch_%d", rc); /* bus 2, ie a2 stream 2 */ bam_ch[rc].pdev = platform_device_alloc(bam_ch[rc].name, 2); if (!bam_ch[rc].pdev) { pr_err("%s: platform device alloc failed\n", __func__); destroy_workqueue(bam_mux_rx_workqueue); destroy_workqueue(bam_mux_tx_workqueue); return -ENOMEM; } } init_completion(&ul_wakeup_ack_completion); init_completion(&bam_connection_completion); init_completion(&dfab_unvote_completion); init_completion(&shutdown_completion); complete_all(&shutdown_completion); INIT_DELAYED_WORK(&ul_timeout_work, ul_timeout); wake_lock_init(&bam_wakelock, WAKE_LOCK_SUSPEND, "bam_dmux_wakelock"); init_srcu_struct(&bam_dmux_srcu); subsys_h = subsys_notif_register_notifier("modem", &restart_notifier); if (IS_ERR(subsys_h)) { destroy_workqueue(bam_mux_rx_workqueue); destroy_workqueue(bam_mux_tx_workqueue); rc = (int)PTR_ERR(subsys_h); pr_err("%s: failed to register for ssr rc: %d\n", __func__, rc); return rc; } rc = bam_ops->smsm_state_cb_register_ptr(SMSM_MODEM_STATE, SMSM_A2_POWER_CONTROL, bam_dmux_smsm_cb, NULL); if (rc) { subsys_notif_unregister_notifier(subsys_h, &restart_notifier); destroy_workqueue(bam_mux_rx_workqueue); destroy_workqueue(bam_mux_tx_workqueue); pr_err("%s: smsm cb register failed, rc: %d\n", __func__, rc); return -ENOMEM; } rc = bam_ops->smsm_state_cb_register_ptr(SMSM_MODEM_STATE, SMSM_A2_POWER_CONTROL_ACK, bam_dmux_smsm_ack_cb, NULL); if (rc) { subsys_notif_unregister_notifier(subsys_h, &restart_notifier); destroy_workqueue(bam_mux_rx_workqueue); destroy_workqueue(bam_mux_tx_workqueue); bam_ops->smsm_state_cb_deregister_ptr(SMSM_MODEM_STATE, SMSM_A2_POWER_CONTROL, bam_dmux_smsm_cb, NULL); pr_err("%s: smsm ack cb register failed, rc: %d\n", __func__, rc); for (rc = 0; rc < BAM_DMUX_NUM_CHANNELS; ++rc) platform_device_put(bam_ch[rc].pdev); return -ENOMEM; } if (bam_ops->smsm_get_state_ptr(SMSM_MODEM_STATE) & SMSM_A2_POWER_CONTROL) bam_dmux_smsm_cb(NULL, 0, bam_ops->smsm_get_state_ptr(SMSM_MODEM_STATE)); return 0; } static struct of_device_id msm_match_table[] = { {.compatible = "qcom,bam_dmux"}, {}, }; static struct platform_driver bam_dmux_driver = { .probe = bam_dmux_probe, .driver = { .name = "BAM_RMNT", .owner = THIS_MODULE, .of_match_table = msm_match_table, }, }; #ifdef BAM_DMUX_FD struct device *bamDmux_pkt_dev; static ssize_t show_waketime(struct device *dev, struct device_attribute *attr, char *buf) { if (!bamDmux_pkt_dev) return 0; return snprintf(buf, PAGE_SIZE, "%u\n", wakelock_timeout); } static ssize_t store_waketime(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int r; unsigned long msec; if (!bamDmux_pkt_dev) return count; r = kstrtoul(buf, 10, &msec); if (r) return count; wakelock_timeout = (msec/1000); return count; } static DEVICE_ATTR(waketime, 0664, show_waketime, store_waketime); #endif static int __init bam_dmux_init(void) { #ifdef CONFIG_DEBUG_FS struct dentry *dent; dent = debugfs_create_dir("bam_dmux", 0); if (!IS_ERR(dent)) { debug_create("tbl", 0444, dent, debug_tbl); debug_create("ul_pkt_cnt", 0444, dent, debug_ul_pkt_cnt); debug_create("stats", 0444, dent, debug_stats); } #endif #ifdef BAM_DMUX_FD wakelock_timeout = 0; bamDmux_pkt_dev = device_create(sec_class, NULL, 0, NULL, "bamdmux"); if (IS_ERR(bamDmux_pkt_dev)) pr_err("%s: Failed to create device(bamDmux_pkt_dev)!\n", __func__); if (device_create_file(bamDmux_pkt_dev, &dev_attr_waketime) < 0) pr_err("%s: Failed to create device file(%s)!\n", __func__, dev_attr_waketime.attr.name); #endif bam_ipc_log_txt = ipc_log_context_create(BAM_IPC_LOG_PAGES, "bam_dmux", 0); if (!bam_ipc_log_txt) { pr_err("%s : unable to create IPC Logging Context", __func__); } rx_timer_interval = DEFAULT_POLLING_MIN_SLEEP; return platform_driver_register(&bam_dmux_driver); } late_initcall(bam_dmux_init); /* needs to init after SMD */ MODULE_DESCRIPTION("MSM BAM DMUX"); MODULE_LICENSE("GPL v2");
gpl-2.0
rbrito/pkg-chrony
hash_intmd5.c
1699
/* chronyd/chronyc - Programs for keeping computer clocks accurate. ********************************************************************** * Copyright (C) Miroslav Lichvar 2012 * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ********************************************************************** ======================================================================= Routines implementing crypto hashing using internal MD5 implementation. */ #include "config.h" #include "sysincl.h" #include "hash.h" #include "memory.h" #include "md5.c" static MD5_CTX ctx; int HSH_GetHashId(const char *name) { /* only MD5 is supported */ if (strcmp(name, "MD5")) return -1; return 0; } unsigned int HSH_Hash(int id, const unsigned char *in1, unsigned int in1_len, const unsigned char *in2, unsigned int in2_len, unsigned char *out, unsigned int out_len) { if (out_len < 16) return 0; MD5Init(&ctx); MD5Update(&ctx, in1, in1_len); if (in2) MD5Update(&ctx, in2, in2_len); MD5Final(&ctx); memcpy(out, ctx.digest, 16); return 16; }
gpl-2.0
crowdcreative/cidade.vc
wp-content/plugins/mycred/plugins/mycred-hook-contact-form7.php
4148
<?php /** * Contact Form 7 Plugin * @since 0.1 * @version 1.0 */ if ( defined( 'myCRED_VERSION' ) ) { /** * Register Hook * @since 0.1 * @version 1.0 */ add_filter( 'mycred_setup_hooks', 'contact_form_seven_myCRED_Hook' ); function contact_form_seven_myCRED_Hook( $installed ) { $installed['contact_form7'] = array( 'title' => __( 'Contact Form 7 Form Submissions', 'mycred' ), 'description' => __( 'Awards %_plural% for successful form submissions (by logged in users).', 'mycred' ), 'callback' => array( 'myCRED_Contact_Form7' ) ); return $installed; } /** * Contact Form 7 Hook * @since 0.1 * @version 1.0 */ if ( !class_exists( 'myCRED_Contact_Form7' ) && class_exists( 'myCRED_Hook' ) ) { class myCRED_Contact_Form7 extends myCRED_Hook { /** * Construct */ function __construct( $hook_prefs ) { parent::__construct( array( 'id' => 'contact_form7', 'defaults' => '' ), $hook_prefs ); } /** * Run * @since 0.1 * @version 1.0 */ public function run() { add_action( 'wpcf7_mail_sent', array( $this, 'form_submission' ) ); } /** * Get Forms * Queries all Contact Form 7 forms. * @uses WP_Query() * @since 0.1 * @version 1.1 */ public function get_forms() { $forms = new WP_Query( array( 'post_type' => 'wpcf7_contact_form', 'post_status' => 'any', 'posts_per_page' => '-1', 'orderby' => 'ID', 'order' => 'ASC' ) ); $result = array(); if ( $forms->have_posts() ) { while ( $forms->have_posts() ) : $forms->the_post(); $result[get_the_ID()] = get_the_title(); endwhile; } wp_reset_postdata(); return $result; } /** * Successful Form Submission * @since 0.1 * @version 1.0 */ public function form_submission( $cf7_form ) { // Login is required if ( !is_user_logged_in() ) return; $form_id = $cf7_form->id; if ( isset( $this->prefs[$form_id] ) && $this->prefs[$form_id]['creds'] != 0 ) { $this->core->add_creds( 'contact_form_submission', get_current_user_id(), $this->prefs[$form_id]['creds'], $this->prefs[$form_id]['log'], $form_id, array( 'ref_type' => 'post' ) ); } } /** * Preferences for Commenting Hook * @since 0.1 * @version 1.0.1 */ public function preferences() { $prefs = $this->prefs; $forms = $this->get_forms(); // No forms found if ( empty( $forms ) ) { echo '<p>' . __( 'No forms found.', 'mycred' ) . '</p>'; return; } // Loop though prefs to make sure we always have a default settings (happens when a new form has been created) foreach ( $forms as $form_id => $form_title ) { if ( !isset( $prefs[$form_id] ) ) { $prefs[$form_id] = array( 'creds' => 1, 'log' => '' ); } } // Set pref if empty if ( empty( $prefs ) ) $this->prefs = $prefs; // Loop for settings foreach ( $forms as $form_id => $form_title ) { ?> <!-- Creds for --> <label for="<?php echo $this->field_id( array( $form_id, 'creds' ) ); ?>" class="subheader"><?php echo $form_title; ?></label> <ol> <li> <div class="h2"><input type="text" name="<?php echo $this->field_name( array( $form_id, 'creds' ) ); ?>" id="<?php echo $this->field_id( array( $form_id, 'creds' ) ); ?>" value="<?php echo $this->core->number( $prefs[$form_id]['creds'] ); ?>" size="8" /></div> </li> <li class="empty">&nbsp;</li> <li> <label for="<?php echo $this->field_id( array( $form_id, 'log' ) ); ?>"><?php _e( 'Log template', 'mycred' ); ?></label> <div class="h2"><input type="text" name="<?php echo $this->field_name( array( $form_id, 'log' ) ); ?>" id="<?php echo $this->field_id( array( $form_id, 'log' ) ); ?>" value="<?php echo $prefs[$form_id]['log']; ?>" class="long" /></div> <span class="description"><?php _e( 'Available template tags: General, Post', 'mycred' ); ?></span> </li> </ol> <?php } unset( $this ); } } } } ?>
gpl-2.0
dauclem/Online-Bug-Tracker
private/bt/mantisbt/mantisbt-1.2.15/core/projax_api.php
3293
<?php # MantisBT - a php based bugtracking system # MantisBT 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. # # MantisBT 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 MantisBT. If not, see <http://www.gnu.org/licenses/>. /** * @package CoreAPI * @subpackage ProjaxAPI * @copyright Copyright (C) 2000 - 2002 Kenzaburo Ito - [email protected] * @copyright Copyright (C) 2002 - 2013 MantisBT Team - [email protected] * @link http://www.mantisbt.org */ /** * requires projax.php */ require_once( 'projax' . DIRECTORY_SEPARATOR . 'projax.php' ); # enables the projax library for this page. $g_enable_projax = true; $g_projax = new Projax(); # Outputs an auto-complete field to the HTML form. The supported attribute keys in the attributes array are: # class, size, maxlength, value, and tabindex. function projax_autocomplete( $p_entrypoint, $p_field_name, $p_attributes_array = null ) { global $g_projax; static $s_projax_style_done = false; if ( ON == config_get( 'use_javascript' ) ) { echo $g_projax->text_field_with_auto_complete( $p_field_name, $p_attributes_array, $s_projax_style_done ? array( 'url' => 'xmlhttprequest.php?entrypoint=' . $p_entrypoint, 'skip_style' => '1' ) : array( 'url' => 'xmlhttprequest.php?entrypoint=' . $p_entrypoint ) ); $s_projax_style_done = true; } else { $t_tabindex = isset( $p_attributes_array['tabindex'] ) ? ( ' tabindex="' . $p_attributes_array['tabindex'] . '"' ) : ''; $t_maxlength = isset( $p_attributes_array['maxlength'] ) ?( ' maxlength="' . $p_attributes_array['maxlength'] . '"' ) : ''; echo '<input id="'.$p_field_name.'" name="'.$p_field_name.'"'. $t_tabindex . $t_maxlength . ' size="'.(isset($p_attributes_array['size'])?$p_attributes_array['size']:30).'" type="text" value="'.(isset($p_attributes_array['value'])?$p_attributes_array['value']:'').'" '.(isset($p_attributes_array['class'])?'class = "'.$p_attributes_array['class'].'" ':'').'/>'; } } # Filters the provided array of strings and only returns the ones that start with $p_prefix. # The comparison is not case sensitive. # Returns the array of the filtered strings, or an empty array. If the input array has non-unique # entries, then the output one may contain duplicates. function projax_array_filter_by_prefix( $p_array, $p_prefix ) { $t_matches = array(); foreach( $p_array as $t_entry ) { if( utf8_strtolower( utf8_substr( $t_entry, 0, utf8_strlen( $p_prefix ) ) ) == utf8_strtolower( $p_prefix ) ) { $t_matches[] = $t_entry; } } return $t_matches; } # Serializes the provided array of strings into the format expected by the auto-complete library. function projax_array_serialize_for_autocomplete( $p_array ) { $t_matches = '<ul>'; foreach( $p_array as $t_entry ) { $t_matches .= "<li>$t_entry</li>"; } $t_matches .= '</ul>'; return $t_matches; }
gpl-2.0
krozett/gcstar
lib/gcstar/GCLang/DE/GCModels/GCTVseries.pm
1511
{ package GCLang::DE::GCModels::GCTVseries; use utf8; ################################################### # # Copyright 2005-2010 Christian Jodar # # This file is part of GCstar. # # GCstar 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. # # GCstar 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 GCstar; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA # ################################################### use strict; use GCLang::GCLangUtils; use base 'Exporter'; our @EXPORT = qw(%lang); our %lang = ( CollectionDescription => 'Fernsehseriensammlung', Items => { 0 => 'Serie', 1 => 'Serie', X => 'Serien'}, NewItem => 'Neue Serie', Name => 'Name', Season => 'Staffel', Part => 'Teil', Episodes => 'Folge', FirstAired => 'Erstausstrahlung', Time => 'Länge', Producer => 'Produzent', Music => 'Musik', ); importTranslation('Films'); } 1;
gpl-2.0
cartiago92/Practicas-FDI
Segundo Curso/Tecnologia de la Programación/Pr2/testProfesor/tp/pr2/testprofesor/PlayerTest.java
3992
package tp.pr2.testprofesor; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import tp.pr2.Player; public class PlayerTest { private MockItem itemTest; private String itemId; private String itemDescription; private Player playerTest; @Before public void setUp() throws Exception { itemId ="testId"; itemDescription = "no description"; itemTest = new MockItem(itemId, itemDescription); playerTest = new Player(); } @Test public void testDefaultValues() { assertTrue("ERROR: Player starts with 100 health points", 100==playerTest.getHealth()); assertTrue("ERROR: Player starts with a score of 0 points", 0==playerTest.getPoints()); } @Test public void testGetItem() { assertNull("ERROR: When the inventory does not contain an item, getItem returns null",playerTest.getItem(itemId)); } @Test public void testAddItem() { assertTrue("ERROR: addItem adds a new an valid item but it returns false", playerTest.addItem(itemTest)); assertFalse("ERROR: addItem tries to add the same item again but it returns true", playerTest.addItem(itemTest)); assertFalse("ERROR: addItem tries to add the same item again (the id is non case-sensitive) but it returns true", playerTest.addItem(new MockItem(itemId.toUpperCase(),itemDescription))); } @Test public void testRemoveItem() { assertFalse("ERROR: removeItem tries to remove an item from an empty inventory but it returns true", playerTest.removeItem(itemId)); if(playerTest.addItem(itemTest)) { assertTrue("ERROR: removeItem tries to remove an item previously added but it returns false", playerTest.removeItem(itemId)); assertTrue("ERROR: removeItem does not work properly. Test tries to add an item" + "previously removed but it returns false", playerTest.addItem(itemTest)); } else fail("ERROR: addItem is not working properly. Check addItem method before executing this test again"); } @Test public void testAddPoints() { int points = playerTest.getPoints(); int inc = 5; playerTest.addPoints(inc); assertEquals("ERROR: addPoints is not adding correctly positive points", points+inc, playerTest.getPoints()); points = playerTest.getPoints(); inc = -5; playerTest.addPoints(inc); assertEquals("ERROR: addPoints is not adding correctly negative points", points+inc, playerTest.getPoints()); } @Test public void testAddHealth() { int health = playerTest.getHealth(); int inc = 5; playerTest.addHealth(inc); assertEquals("ERROR: addHealth is not adding correctly positive health", health+inc, playerTest.getHealth()); health = playerTest.getHealth(); inc = -5; playerTest.addHealth(inc); assertEquals("ERROR: addHealth is not adding correctly negative health", health+inc, playerTest.getHealth()); } @Test public void testDead() { assertFalse("ERROR: Player health is "+playerTest.getHealth()+" but dead method returns true", playerTest.dead()); int health = playerTest.getHealth(); playerTest.addHealth(-health); assertTrue("ERROR: Player should be dead after removing exactly her health but dead method returns false", playerTest.dead()); playerTest = new Player(); health = playerTest.getHealth(); health+=10; playerTest.addHealth(-health); assertTrue("ERROR: Player should be dead after removing more than her health but dead method returns false", playerTest.dead()); } @Test public void testShowItems() { assertTrue("ERROR: Player inventory is empty but showItems does not show the correct message", playerTest.showItems().contains("You are poor")); playerTest.addItem(itemTest); assertTrue("ERROR: Player inventory contains an items but showItems does not show the item description", playerTest.showItems().contains(itemTest.toString())); } // @Test // public void testLooseLive() { // int health = playerTest.getHealth(); // playerTest.looseLive(); // assertEquals("ERROR: looseLive must remove 5 health points", health-5, playerTest.getHealth()); // } }
gpl-2.0
joelbrock/HARVEST_CORE
documentation/doxy/output/fannie/html/class_edit_items_from_search-members.html
10097
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.4"/> <title>CORE POS - Fannie: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { if ($('.searchresults').length > 0) { searchBox.DOMSearchField().focus(); } }); </script> <link rel="search" href="search-opensearch.php?v=opensearch.xml" type="application/opensearchdescription+xml" title="CORE POS - Fannie"/> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">CORE POS - Fannie </div> <div id="projectbrief">The CORE POS back end</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.4 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <div class="left"> <form id="FSearchBox" action="search.php" method="get"> <img id="MSearchSelect" src="search/mag.png" alt=""/> <input type="text" id="MSearchField" name="query" value="Search" size="20" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)"/> </form> </div><div class="right"></div> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">EditItemsFromSearch Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="class_edit_items_from_search.html">EditItemsFromSearch</a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>$__method</b> (defined in <a class="el" href="class_fannie_r_e_s_tful_page.html">FannieRESTfulPage</a>)</td><td class="entry"><a class="el" href="class_fannie_r_e_s_tful_page.html">FannieRESTfulPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>$__models</b> (defined in <a class="el" href="class_fannie_r_e_s_tful_page.html">FannieRESTfulPage</a>)</td><td class="entry"><a class="el" href="class_fannie_r_e_s_tful_page.html">FannieRESTfulPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>$__route_stem</b> (defined in <a class="el" href="class_fannie_r_e_s_tful_page.html">FannieRESTfulPage</a>)</td><td class="entry"><a class="el" href="class_fannie_r_e_s_tful_page.html">FannieRESTfulPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr><td class="entry"><a class="el" href="class_fannie_r_e_s_tful_page.html#a2ba99eea842d834507df28b700554d1a">$__routes</a></td><td class="entry"><a class="el" href="class_fannie_r_e_s_tful_page.html">FannieRESTfulPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>$description</b> (defined in <a class="el" href="class_edit_items_from_search.html">EditItemsFromSearch</a>)</td><td class="entry"><a class="el" href="class_edit_items_from_search.html">EditItemsFromSearch</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>$header</b> (defined in <a class="el" href="class_edit_items_from_search.html">EditItemsFromSearch</a>)</td><td class="entry"><a class="el" href="class_edit_items_from_search.html">EditItemsFromSearch</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>$themed</b> (defined in <a class="el" href="class_edit_items_from_search.html">EditItemsFromSearch</a>)</td><td class="entry"><a class="el" href="class_edit_items_from_search.html">EditItemsFromSearch</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>$title</b> (defined in <a class="el" href="class_edit_items_from_search.html">EditItemsFromSearch</a>)</td><td class="entry"><a class="el" href="class_edit_items_from_search.html">EditItemsFromSearch</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>bodyContent</b>() (defined in <a class="el" href="class_fannie_r_e_s_tful_page.html">FannieRESTfulPage</a>)</td><td class="entry"><a class="el" href="class_fannie_r_e_s_tful_page.html">FannieRESTfulPage</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>get_model</b>($database_connection, $class, $params, $find=False) (defined in <a class="el" href="class_fannie_r_e_s_tful_page.html">FannieRESTfulPage</a>)</td><td class="entry"><a class="el" href="class_fannie_r_e_s_tful_page.html">FannieRESTfulPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="class_fannie_r_e_s_tful_page.html#aa89bdea912b8fc2e6c2e47503e95ee2d">getModel</a>($database_connection, $class, $params, $find=False)</td><td class="entry"><a class="el" href="class_fannie_r_e_s_tful_page.html">FannieRESTfulPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>javascript_content</b>() (defined in <a class="el" href="class_edit_items_from_search.html">EditItemsFromSearch</a>)</td><td class="entry"><a class="el" href="class_edit_items_from_search.html">EditItemsFromSearch</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>post_save_handler</b>() (defined in <a class="el" href="class_edit_items_from_search.html">EditItemsFromSearch</a>)</td><td class="entry"><a class="el" href="class_edit_items_from_search.html">EditItemsFromSearch</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>post_save_view</b>() (defined in <a class="el" href="class_edit_items_from_search.html">EditItemsFromSearch</a>)</td><td class="entry"><a class="el" href="class_edit_items_from_search.html">EditItemsFromSearch</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>post_u_handler</b>() (defined in <a class="el" href="class_edit_items_from_search.html">EditItemsFromSearch</a>)</td><td class="entry"><a class="el" href="class_edit_items_from_search.html">EditItemsFromSearch</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="class_edit_items_from_search.html#ae16ffabde5b2b808b813a50ee61db734">post_u_view</a>()</td><td class="entry"><a class="el" href="class_edit_items_from_search.html">EditItemsFromSearch</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>preprocess</b>() (defined in <a class="el" href="class_edit_items_from_search.html">EditItemsFromSearch</a>)</td><td class="entry"><a class="el" href="class_edit_items_from_search.html">EditItemsFromSearch</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="class_fannie_r_e_s_tful_page.html#ab248b5009c98297c3346aa2915a38198">readRoutes</a>()</td><td class="entry"><a class="el" href="class_fannie_r_e_s_tful_page.html">FannieRESTfulPage</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>unitTest</b>($phpunit) (defined in <a class="el" href="class_fannie_r_e_s_tful_page.html">FannieRESTfulPage</a>)</td><td class="entry"><a class="el" href="class_fannie_r_e_s_tful_page.html">FannieRESTfulPage</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="class_fannie_r_e_s_tful_page.html#afdc093f79eff94c8c011947897931ae8">unknownRequestHandler</a>()</td><td class="entry"><a class="el" href="class_fannie_r_e_s_tful_page.html">FannieRESTfulPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="class_fannie_r_e_s_tful_page.html#ad9d19fea0f22d6b25d3d7b9c94fafe58">unknownRequestView</a>()</td><td class="entry"><a class="el" href="class_fannie_r_e_s_tful_page.html">FannieRESTfulPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Thu Apr 2 2015 12:27:27 for CORE POS - Fannie by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.4 </small></address> </body> </html>
gpl-2.0
TEAMMATES/teammates
src/web/app/pages-student/student-page.component.ts
1999
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { environment } from '../../environments/environment'; import { AuthService } from '../../services/auth.service'; import { AuthInfo } from '../../types/api-output'; /** * Base skeleton for student pages. */ @Component({ selector: 'tm-student-page', templateUrl: './student-page.component.html', }) export class StudentPageComponent implements OnInit { user: string = ''; institute?: string = ''; isInstructor: boolean = false; isStudent: boolean = false; isAdmin: boolean = false; isMaintainer: boolean = false; navItems: any[] = [ { url: '/web/student', display: 'Home', }, { url: '/web/student/profile', display: 'Profile', }, { url: '/web/student/help', display: 'Help', }, ]; isFetchingAuthDetails: boolean = false; private backendUrl: string = environment.backendUrl; constructor(private route: ActivatedRoute, private authService: AuthService) {} ngOnInit(): void { this.isFetchingAuthDetails = true; this.route.queryParams.subscribe((queryParams: any) => { this.authService.getAuthUser(queryParams.user).subscribe((res: AuthInfo) => { if (res.user) { this.user = res.user.id; if (res.masquerade) { this.user += ' (M)'; } this.institute = res.institute; this.isInstructor = res.user.isInstructor; this.isStudent = res.user.isStudent; this.isAdmin = res.user.isAdmin; this.isMaintainer = res.user.isMaintainer; } else { window.location.href = `${this.backendUrl}${res.studentLoginUrl}`; } this.isFetchingAuthDetails = false; }, () => { this.isInstructor = false; this.isStudent = false; this.isAdmin = false; this.isMaintainer = false; this.isFetchingAuthDetails = false; }); }); } }
gpl-2.0
alexbevi/scummvm
engines/asylum/system/speech.cpp
8226
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "asylum/system/speech.h" #include "asylum/resources/actor.h" #include "asylum/resources/worldstats.h" #include "asylum/system/text.h" #include "asylum/views/scene.h" #include "asylum/asylum.h" #include "asylum/staticres.h" namespace Asylum { Speech::Speech(AsylumEngine *engine): _vm(engine), _textData(0), _textDataPos(0) { _tick = _vm->getTick(); _soundResourceId = kResourceNone; _textResourceId = kResourceNone; } Speech::~Speech() { // Text resource data is disposed as part of the resource manager _textData = 0; _textDataPos = 0; // Zero-out passed pointers _vm = NULL; } ResourceId Speech::play(ResourceId soundResourceId, ResourceId textResourceId) { if (soundResourceId) if (getSound()->isPlaying(soundResourceId)) getSound()->stopAll(soundResourceId); _soundResourceId = soundResourceId; _textResourceId = textResourceId; prepareSpeech(); return soundResourceId; } ResourceId Speech::playIndexed(int32 index) { int processedIndex; if (getWorld()->actorType || index != -1) { processedIndex = (int)speechIndex[index + 5 * getWorld()->actorType] + (int)rnd(speechIndexRandom[index + 5 * getWorld()->actorType]); } else { switch(_vm->getRandom(3)) { default: case 0: processedIndex = 23; break; case 1: processedIndex = 400; break; case 2: processedIndex = 401; break; case 3: processedIndex = index; break; } if (processedIndex >= 259) processedIndex -=9; } switch (getWorld()->actorType) { default: break; case kActorMax: return play(MAKE_RESOURCE(kResourcePackSpeech, processedIndex), MAKE_RESOURCE(kResourcePackText, processedIndex + 83)); case kActorSarah: return play(MAKE_RESOURCE(kResourcePackSharedSound, processedIndex + 1927), MAKE_RESOURCE(kResourcePackText, processedIndex + 586)); case kActorCyclops: return play(MAKE_RESOURCE(kResourcePackSharedSound, processedIndex + 2084), MAKE_RESOURCE(kResourcePackText, processedIndex + 743)); case kActorAztec: return play(MAKE_RESOURCE(kResourcePackSharedSound, processedIndex + 2234), MAKE_RESOURCE(kResourcePackText, processedIndex + 893)); } return kResourceNone; } ResourceId Speech::playScene(int32 type, int32 index) { switch (type) { default: play(kResourceNone, kResourceNone); break; case 0: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2363), MAKE_RESOURCE(kResourcePackText, index + 1022)); case 1: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2366), MAKE_RESOURCE(kResourcePackText, index + 1025)); case 2: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2371), MAKE_RESOURCE(kResourcePackText, index + 1030)); case 3: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2398), MAKE_RESOURCE(kResourcePackText, index + 1057)); case 4: return play(MAKE_RESOURCE(kResourcePackSpeech, index + 503), MAKE_RESOURCE(kResourcePackText, index + 1060)); case 5: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2401), MAKE_RESOURCE(kResourcePackText, index + 1068)); case 6: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2409), MAKE_RESOURCE(kResourcePackText, index + 1076)); case 7: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2415), MAKE_RESOURCE(kResourcePackText, index + 1082)); case 8: return play(MAKE_RESOURCE(kResourcePackSpeech, index + 511), MAKE_RESOURCE(kResourcePackText, index + 1084)); case 9: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2417), MAKE_RESOURCE(kResourcePackText, index + 1088)); case 10: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2417), MAKE_RESOURCE(kResourcePackText, index + 1093)); case 11: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2424), MAKE_RESOURCE(kResourcePackText, index + 1100)); case 12: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2424), MAKE_RESOURCE(kResourcePackText, index + 1102)); case 13: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2430), MAKE_RESOURCE(kResourcePackText, index + 1108)); case 14: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2432), MAKE_RESOURCE(kResourcePackText, index + 1110)); case 15: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2434), MAKE_RESOURCE(kResourcePackText, index + 1112)); case 16: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2435), MAKE_RESOURCE(kResourcePackText, index + 1113)); case 17: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2436), MAKE_RESOURCE(kResourcePackText, index + 1114)); case 18: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2438), MAKE_RESOURCE(kResourcePackText, index + 1116)); case 19: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2439), MAKE_RESOURCE(kResourcePackText, index + 1117)); } return kResourceNone; } ResourceId Speech::playPlayer(int32 index) { switch (getWorld()->actorType) { default: break; case kActorMax: { int32 soundResourceIndex = index; int32 textResourceIndex = index; if (index >= 259) { soundResourceIndex -= 9; textResourceIndex -= 9; } ResourceId soundResourceId = MAKE_RESOURCE(kResourcePackSpeech, soundResourceIndex); return play(soundResourceId, MAKE_RESOURCE(kResourcePackText, textResourceIndex + 83)); } case kActorSarah: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 1927), MAKE_RESOURCE(kResourcePackText, index + 586)); case kActorCyclops: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2084), MAKE_RESOURCE(kResourcePackText, index + 743)); case kActorAztec: return play(MAKE_RESOURCE(kResourcePackSharedSound, index + 2234), MAKE_RESOURCE(kResourcePackText, index + 893)); } return kResourceNone; } void Speech::resetResourceIds() { _soundResourceId = kResourceNone; _textResourceId = kResourceNone; } void Speech::resetTextData() { _textData = NULL; _textDataPos = NULL; } ////////////////////////////////////////////////////////////////////////// // Private methods ////////////////////////////////////////////////////////////////////////// void Speech::prepareSpeech() { int32 startTick = _vm->getTick(); if (_soundResourceId) { if (!getSound()->isPlaying(_soundResourceId) || (_tick && startTick >= _tick)) process(); if (Config.showEncounterSubtitles) { Common::Point point; Actor *actor = getScene()->getActor(); actor->adjustCoordinates(&point); int16 posY = (point.y >= 240) ? 40 : 320; getText()->draw(_textDataPos, getWorld()->font3, posY); getText()->draw(_textData, getWorld()->font1, posY); } } } void Speech::process() { _tick = 0; char *txt = getText()->get(_textResourceId); if (*(txt + strlen((const char *)txt) - 2) == 1) { _textResourceId = kResourceNone; _textData = 0; _textDataPos = 0; } else if (*txt == '{') { _textData = txt + 3; _textDataPos = 0; getText()->loadFont(getWorld()->font1); getSound()->playSound(_soundResourceId, false, Config.voiceVolume, 0); } else { _textData = 0; _textDataPos = txt; if (*txt == '/') { _textDataPos = txt + 2; } getText()->loadFont(getWorld()->font3); getSound()->playSound(_soundResourceId, false, Config.voiceVolume, 0); } } } // end of namespace Asylum
gpl-2.0
linkmauve/dolphin
Source/Core/Core/IOS/USB/Bluetooth/BTBase.cpp
1428
// Copyright 2016 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #include "Core/IOS/USB/Bluetooth/BTBase.h" #include <memory> #include <string> #include <vector> #include "Common/CommonPaths.h" #include "Common/CommonTypes.h" #include "Common/File.h" #include "Common/FileUtil.h" #include "Common/Logging/Log.h" #include "Common/SysConf.h" namespace IOS { namespace HLE { void BackUpBTInfoSection(const SysConf* sysconf) { const std::string filename = File::GetUserPath(D_CONFIG_IDX) + DIR_SEP WII_BTDINF_BACKUP; if (File::Exists(filename)) return; File::IOFile backup(filename, "wb"); const SysConf::Entry* btdinf = sysconf->GetEntry("BT.DINF"); if (!btdinf) return; const std::vector<u8>& section = btdinf->bytes; if (!backup.WriteBytes(section.data(), section.size())) ERROR_LOG(IOS_WIIMOTE, "Failed to back up BT.DINF section"); } void RestoreBTInfoSection(SysConf* sysconf) { const std::string filename = File::GetUserPath(D_CONFIG_IDX) + DIR_SEP WII_BTDINF_BACKUP; File::IOFile backup(filename, "rb"); if (!backup) return; auto& section = sysconf->GetOrAddEntry("BT.DINF", SysConf::Entry::Type::BigArray)->bytes; if (!backup.ReadBytes(section.data(), section.size())) { ERROR_LOG(IOS_WIIMOTE, "Failed to read backed up BT.DINF section"); return; } File::Delete(filename); } } // namespace HLE } // namespace IOS
gpl-2.0
kirkokada/hackathon
db/migrate/20150524135324_add_more_columns_to_users.rb
158
class AddMoreColumnsToUsers < ActiveRecord::Migration def change add_column :users, :username, :string add_column :users, :image, :string end end
gpl-2.0
ajsedgewick/tetrad
tetrad-lib/src/main/java/edu/cmu/tetrad/search/Kpc.java
14785
/////////////////////////////////////////////////////////////////////////////// // For information as to what this class does, see the Javadoc, below. // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, // // 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph // // Ramsey, and Clark Glymour. // // // // 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 // /////////////////////////////////////////////////////////////////////////////// package edu.cmu.tetrad.search; import edu.cmu.tetrad.data.DataSet; import edu.cmu.tetrad.data.IKnowledge; import edu.cmu.tetrad.data.Knowledge2; import edu.cmu.tetrad.graph.*; import edu.cmu.tetrad.util.ChoiceGenerator; import edu.cmu.tetrad.util.TetradLogger; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Kernelized PC algorithm. This is the same as the PC class, the nonparametric kernel-based HSIC test is used for * independence testing and the parameters for this test can be set directly when Kpc is initialized. * * @author Robert Tillman. */ public class Kpc implements GraphSearch { /** * The independence test used for the PC search. */ private IndTestHsic independenceTest; /** * Forbidden and required edges for the search. */ private IKnowledge knowledge = new Knowledge2(); /** * Sepset information accumulated in the search. */ private SepsetMap sepset; /** * The maximum number of nodes conditioned on in the search. The default it 1000. */ private int depth = 1000; /** * The graph that's constructed during the search. */ private Graph graph; /** * Elapsed time of the most recent search. */ private long elapsedTime; /** * True if cycles are to be aggressively prevented. May be expensive for large graphs (but also useful for large * graphs). */ private boolean aggressivelyPreventCycles = false; /** * The logger to use. */ private TetradLogger logger = TetradLogger.getInstance(); /** * In an enumeration of triple types, these are the collider triples. */ private Set<Triple> unshieldedColliders; /** * In an enumeration of triple types, these are the noncollider triples. */ private Set<Triple> unshieldedNoncolliders; /** * The number of indepdendence tests in the last search. */ private int numIndependenceTests; /** * The true graph, for purposes of comparison. Temporary. */ private Graph trueGraph; /** * The number of false dependence judgements from FAS, judging from the true graph, if set. Temporary. */ private int numFalseDependenceJudgements; /** * The number of dependence judgements from FAS. Temporary. */ private int numDependenceJudgements; /** * The threshold for rejecting the null */ private double alpha; /** * Use incomplete Choleksy factorization for Gram matrices */ private double useIncompleteCholesky = 1e-18; /** * The regularizer for singular matrices */ private double regularizer = .0001; /** * The number of bootstrap samples to generate during independence testing */ private int perms = 100; private boolean verbose = false; //=============================CONSTRUCTORS==========================// /** * Constructs a new PC search using for the given dataset. * * @param dataset The oracle for conditional independence facts. This does not make a copy of the independence test, * for fear of duplicating the data set! */ public Kpc(DataSet dataset, double alpha) { if (dataset == null) { throw new NullPointerException(); } this.alpha = alpha; this.independenceTest = new IndTestHsic(dataset, alpha); } //==============================PUBLIC METHODS========================// /** * @return true iff edges will not be added if they would create cycles. */ public boolean isAggressivelyPreventCycles() { return this.aggressivelyPreventCycles; } /** * @param aggressivelyPreventCycles Set to true just in case edges will not be addeds if they would create cycles. */ public void setAggressivelyPreventCycles(boolean aggressivelyPreventCycles) { this.aggressivelyPreventCycles = aggressivelyPreventCycles; } /** * @return the independence test being used in the search. */ public IndependenceTest getIndependenceTest() { return independenceTest; } /** * @return the knowledge specification used in the search. Non-null. */ public IKnowledge getKnowledge() { return knowledge; } /** * Sets the knowledge specification to be used in the search. May not be null. */ public void setKnowledge(IKnowledge knowledge) { if (knowledge == null) { throw new NullPointerException(); } this.knowledge = knowledge; } /** * @return the sepset map from the most recent search. Non-null after the first call to <code>search()</code>. */ public SepsetMap getSepset() { return sepset; } /** * @return the getModel depth of search--that is, the maximum number of conditioning nodes for any conditional * independence checked. */ public int getDepth() { return depth; } /** * Sets the depth of the search--that is, the maximum number of conditioning nodes for any conditional independence * checked. * * @param depth The depth of the search. The default is 1000. A value of -1 may be used to indicate that the depth * should be high (1000). A value of Integer.MAX_VALUE may not be used, due to a bug on multi-core * machines. */ public void setDepth(int depth) { if (depth < -1) { throw new IllegalArgumentException("Depth must be -1 or >= 0."); } if (depth > 1000) { throw new IllegalArgumentException("Depth must be <= 1000."); } this.depth = depth; } /** * Runs PC starting with a complete graph over all nodes of the given conditional independence test, using the given * independence test and knowledge and returns the resultant graph. The returned graph will be a pattern if the * independence information is consistent with the hypothesis that there are no latent common causes. It may, * however, contain cycles or bidirected edges if this assumption is not born out, either due to the actual presence * of latent common causes, or due to statistical errors in conditional independence judgments. */ public Graph search() { return search(independenceTest.getVariables()); } /** * Runs PC starting with a commplete graph over the given list of nodes, using the given independence test and * knowledge and returns the resultant graph. The returned graph will be a pattern if the independence information * is consistent with the hypothesis that there are no latent common causes. It may, however, contain cycles or * bidirected edges if this assumption is not born out, either due to the actual presence of latent common causes, * or due to statistical errors in conditional independence judgments. * <p> * All of the given nodes must be in the domain of the given conditional independence test. */ public Graph search(List<Node> nodes) { this.logger.log("info", "Starting kPC algorithm"); this.logger.log("info", "Independence test = " + getIndependenceTest() + "."); // this.logger.log("info", "Variables " + independenceTest.getVariables()); long startTime = System.currentTimeMillis(); if (getIndependenceTest() == null) { throw new NullPointerException(); } List allNodes = getIndependenceTest().getVariables(); if (!allNodes.containsAll(nodes)) { throw new IllegalArgumentException("All of the given nodes must " + "be in the domain of the independence test provided."); } graph = new EdgeListGraph(nodes); graph.fullyConnect(Endpoint.TAIL); Fas fas = new Fas(graph, getIndependenceTest()); fas.setKnowledge(getKnowledge()); fas.setDepth(getDepth()); fas.setTrueGraph(trueGraph); graph = fas.search(); this.sepset = fas.getSepsets(); this.numIndependenceTests = fas.getNumIndependenceTests(); this.numFalseDependenceJudgements = fas.getNumFalseDependenceJudgments(); this.numDependenceJudgements = fas.getNumDependenceJudgments(); enumerateTriples(); SearchGraphUtils.pcOrientbk(knowledge, graph, nodes); SearchGraphUtils.orientCollidersUsingSepsets(sepset, knowledge, graph, verbose); MeekRules rules = new MeekRules(); rules.setAggressivelyPreventCycles(this.aggressivelyPreventCycles); rules.setKnowledge(knowledge); rules.orientImplied(graph); this.logger.log("graph", "\nReturning this graph: " + graph); this.elapsedTime = System.currentTimeMillis() - startTime; this.logger.log("info", "Elapsed time = " + (elapsedTime) / 1000. + " s"); this.logger.log("info", "Finishing PC Algorithm."); this.logger.flush(); return graph; } /** * @return the elapsed time of the search, in milliseconds. */ public long getElapsedTime() { return elapsedTime; } /** * @return the set of unshielded colliders in the graph returned by <code>search()</code>. Non-null after * <code>search</code> is called. */ public Set<Triple> getUnshieldedColliders() { return unshieldedColliders; } /** * @return the set of unshielded noncolliders in the graph returned by <code>search()</code>. Non-null after * <code>search</code> is called. */ public Set<Triple> getUnshieldedNoncolliders() { return unshieldedNoncolliders; } //===============================ADDED FOR KPC=========================// /** * Sets the significance level at which independence judgments should be made. */ public void setAlpha(double alpha) { if (alpha < 0.0 || alpha > 1.0) { throw new IllegalArgumentException("Significance out of range."); } this.alpha = alpha; independenceTest.setAlpha(alpha); } /** * Sets the precision for the Incomplete Choleksy factorization method for approximating Gram matrices. A value <= 0 * indicates that the Incomplete Cholesky method should not be used and instead use the exact matrices. */ public void setIncompleteCholesky(double precision) { this.useIncompleteCholesky = precision; independenceTest.setIncompleteCholesky(precision); } /** * Set the number of bootstrap samples to use */ public void setPerms(int perms) { this.perms = perms; independenceTest.setPerms(perms); } /** * Sets the regularizer */ public void setRegularizer(double regularizer) { this.regularizer = regularizer; independenceTest.setRegularizer(regularizer); } /** * Gets the getModel significance level. */ public double getAlpha() { return this.alpha; } /** * Gets the getModel precision for the Incomplete Cholesky */ public double getPrecision() { return this.useIncompleteCholesky; } /** * Gets the getModel number of bootstrap samples used */ public int getPerms() { return this.perms; } /** * Gets the getModel regularizer */ public double getRegularizer() { return this.regularizer; } //===============================PRIVATE METHODS=======================// private void enumerateTriples() { this.unshieldedColliders = new HashSet<Triple>(); this.unshieldedNoncolliders = new HashSet<Triple>(); for (Node y : graph.getNodes()) { List<Node> adj = graph.getAdjacentNodes(y); if (adj.size() < 2) { continue; } ChoiceGenerator gen = new ChoiceGenerator(adj.size(), 2); int[] choice; while ((choice = gen.next()) != null) { Node x = adj.get(choice[0]); Node z = adj.get(choice[1]); List<Node> nodes = sepset.get(x, z); // Note that checking adj(x, z) does not suffice when knowledge // has been specified. if (nodes == null) { continue; } if (nodes.contains(y)) { getUnshieldedNoncolliders().add(new Triple(x, y, z)); } else { getUnshieldedColliders().add(new Triple(x, y, z)); } } } } public int getNumIndependenceTests() { return numIndependenceTests; } public void setTrueGraph(Graph trueGraph) { this.trueGraph = trueGraph; } public int getNumFalseDependenceJudgements() { return numFalseDependenceJudgements; } public int getNumDependenceJudgements() { return numDependenceJudgements; } public void setVerbose(boolean verbose) { this.verbose = verbose; } }
gpl-2.0
moses1984/aafmt
book_chapters_LaTeX_original/pgf_3.0.1.tds/doc/generic/pgf/text-en/pgfmanual-en-library-through.tex
1171
% Copyright 2006 by Till Tantau % % This file may be distributed and/or modified % % 1. under the LaTeX Project Public License and/or % 2. under the GNU Free Documentation License. % % See the file doc/generic/pgf/licenses/LICENSE for more details. \section{Through Library} \label{section-through-library} \begin{tikzlibrary}{through} This library defines keys for creating shapes that go through given points. \end{tikzlibrary} \begin{key}{/tikz/circle through=\meta{coordinate}} When this key is given as an option to a node, the following happens: \begin{enumerate} \item The |inner sep| and the |outer sep| are set to zero. \item The shape is set to |circle|. \item The |minimum size| is set such that the circle around the center of the node (which is specified using |at|), goes through \meta{coordinate}. \end{enumerate} \begin{codeexample}[] \begin{tikzpicture} \draw[help lines] (0,0) grid (3,2); \node (a) at (2,1.5) {$a$}; \node [draw] at (1,1) [circle through={(a)}] {$c$}; \end{tikzpicture} \end{codeexample} \end{key} %%% Local Variables: %%% mode: latex %%% TeX-master: "pgfmanual-pdftex-version" %%% End:
gpl-2.0
zrafa/linuxkernel
linux-2.6.17.new/drivers/mtd/maps/uclinux.c
3158
/****************************************************************************/ /* * uclinux.c -- generic memory mapped MTD driver for uclinux * * (C) Copyright 2002, Greg Ungerer ([email protected]) * * $Id: uclinux.c,v 1.12 2005/11/07 11:14:29 gleixner Exp $ */ /****************************************************************************/ #include <linux/config.h> #include <linux/module.h> #include <linux/types.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/major.h> #include <linux/root_dev.h> #include <linux/mtd/mtd.h> #include <linux/mtd/map.h> #include <linux/mtd/partitions.h> #include <asm/io.h> /****************************************************************************/ struct map_info uclinux_ram_map = { .name = "RAM", }; struct mtd_info *uclinux_ram_mtdinfo; /****************************************************************************/ struct mtd_partition uclinux_romfs[] = { { .name = "ROMfs" } }; #define NUM_PARTITIONS ARRAY_SIZE(uclinux_romfs) /****************************************************************************/ int uclinux_point(struct mtd_info *mtd, loff_t from, size_t len, size_t *retlen, u_char **mtdbuf) { struct map_info *map = mtd->priv; *mtdbuf = (u_char *) (map->virt + ((int) from)); *retlen = len; return(0); } /****************************************************************************/ int __init uclinux_mtd_init(void) { struct mtd_info *mtd; struct map_info *mapp; extern char _ebss; unsigned long addr = (unsigned long) &_ebss; mapp = &uclinux_ram_map; mapp->phys = addr; mapp->size = PAGE_ALIGN(ntohl(*((unsigned long *)(addr + 8)))); mapp->bankwidth = 4; printk("uclinux[mtd]: RAM probe address=0x%x size=0x%x\n", (int) mapp->phys, (int) mapp->size); mapp->virt = ioremap_nocache(mapp->phys, mapp->size); if (mapp->virt == 0) { printk("uclinux[mtd]: ioremap_nocache() failed\n"); return(-EIO); } simple_map_init(mapp); mtd = do_map_probe("map_ram", mapp); if (!mtd) { printk("uclinux[mtd]: failed to find a mapping?\n"); iounmap(mapp->virt); return(-ENXIO); } mtd->owner = THIS_MODULE; mtd->point = uclinux_point; mtd->priv = mapp; uclinux_ram_mtdinfo = mtd; add_mtd_partitions(mtd, uclinux_romfs, NUM_PARTITIONS); printk("uclinux[mtd]: set %s to be root filesystem\n", uclinux_romfs[0].name); ROOT_DEV = MKDEV(MTD_BLOCK_MAJOR, 0); return(0); } /****************************************************************************/ void __exit uclinux_mtd_cleanup(void) { if (uclinux_ram_mtdinfo) { del_mtd_partitions(uclinux_ram_mtdinfo); map_destroy(uclinux_ram_mtdinfo); uclinux_ram_mtdinfo = NULL; } if (uclinux_ram_map.virt) { iounmap((void *) uclinux_ram_map.virt); uclinux_ram_map.virt = 0; } } /****************************************************************************/ module_init(uclinux_mtd_init); module_exit(uclinux_mtd_cleanup); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Greg Ungerer <[email protected]>"); MODULE_DESCRIPTION("Generic RAM based MTD for uClinux"); /****************************************************************************/
gpl-2.0
SubhrajyotiSen/HelioxKernelHarpia
gcc-linaro/share/doc/gcc/Local-Reg-Vars.html
2828
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <!-- Copyright (C) 1988-2016 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 "Funding Free Software", the Front-Cover Texts being (a) (see below), and with the Back-Cover Texts being (b) (see below). A copy of the license is included in the section entitled "GNU Free Documentation License". (a) The FSF's Front-Cover Text is: A GNU Manual (b) The FSF's Back-Cover Text is: You have freedom to copy and modify this GNU Manual, like GNU software. Copies published by the Free Software Foundation raise funds for GNU development. --> <!-- Created by GNU Texinfo 5.2, http://www.gnu.org/software/texinfo/ --> <!-- This file redirects to the location of a node or anchor --> <head> <title>Using the GNU Compiler Collection (GCC): Local Reg Vars</title> <meta name="description" content="Using the GNU Compiler Collection (GCC): Local Reg Vars"> <meta name="keywords" content="Using the GNU Compiler Collection (GCC): Local Reg Vars"> <meta name="resource-type" content="document"> <meta name="distribution" content="global"> <meta name="Generator" content="makeinfo"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style type="text/css"> <!-- a.summary-letter {text-decoration: none} blockquote.smallquotation {font-size: smaller} div.display {margin-left: 3.2em} div.example {margin-left: 3.2em} div.indentedblock {margin-left: 3.2em} div.lisp {margin-left: 3.2em} div.smalldisplay {margin-left: 3.2em} div.smallexample {margin-left: 3.2em} div.smallindentedblock {margin-left: 3.2em; font-size: smaller} div.smalllisp {margin-left: 3.2em} kbd {font-style:oblique} pre.display {font-family: inherit} pre.format {font-family: inherit} pre.menu-comment {font-family: serif} pre.menu-preformatted {font-family: serif} pre.smalldisplay {font-family: inherit; font-size: smaller} pre.smallexample {font-size: smaller} pre.smallformat {font-family: inherit; font-size: smaller} pre.smalllisp {font-size: smaller} span.nocodebreak {white-space:nowrap} span.nolinebreak {white-space:nowrap} span.roman {font-family:serif; font-weight:normal} span.sansserif {font-family:sans-serif; font-weight:normal} ul.no-bullet {list-style: none} --> </style> <meta http-equiv="Refresh" content="0; url=Local-Register-Variables.html#Local-Reg-Vars"> </head> <body lang="en" bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000"> <p>The node you are looking for is at <a href="Local-Register-Variables.html#Local-Reg-Vars">Local Reg Vars</a>.</p> </body>
gpl-2.0
Fir3element/downgrade86
src/weapons.h
6161
/** * The Forgotten Server - a free and open-source MMORPG server emulator * Copyright (C) 2016 Mark Samman <[email protected]> * * 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., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef FS_WEAPONS_H_69D1993478AA42948E24C0B90B8F5BF5 #define FS_WEAPONS_H_69D1993478AA42948E24C0B90B8F5BF5 #include "luascript.h" #include "player.h" #include "baseevents.h" #include "combat.h" #include "const.h" class Weapon; class WeaponMelee; class WeaponDistance; class WeaponWand; class Weapons final : public BaseEvents { public: Weapons(); ~Weapons(); // non-copyable Weapons(const Weapons&) = delete; Weapons& operator=(const Weapons&) = delete; void loadDefaults(); const Weapon* getWeapon(const Item* item) const; static int32_t getMaxMeleeDamage(int32_t attackSkill, int32_t attackValue); static int32_t getMaxWeaponDamage(uint32_t level, int32_t attackSkill, int32_t attackValue, float attackFactor); protected: void clear() final; LuaScriptInterface& getScriptInterface() final; std::string getScriptBaseName() const final; Event* getEvent(const std::string& nodeName) final; bool registerEvent(Event* event, const pugi::xml_node& node) final; std::map<uint32_t, Weapon*> weapons; LuaScriptInterface m_scriptInterface; }; class Weapon : public Event { public: explicit Weapon(LuaScriptInterface* _interface); bool configureEvent(const pugi::xml_node& node) override; bool loadFunction(const pugi::xml_attribute&) final { return true; } virtual void configureWeapon(const ItemType& it); virtual bool interruptSwing() const { return false; } int32_t playerWeaponCheck(Player* player, Creature* target, uint8_t shootRange) const; static bool useFist(Player* player, Creature* target); virtual bool useWeapon(Player* player, Item* item, Creature* target) const; virtual int32_t getWeaponDamage(const Player* player, const Creature* target, const Item* item, bool maxDamage = false) const = 0; virtual int32_t getElementDamage(const Player* player, const Creature* target, const Item* item) const = 0; virtual CombatType_t getElementType() const = 0; uint16_t getID() const { return id; } uint32_t getReqLevel() const { return level; } uint32_t getReqMagLv() const { return magLevel; } bool isPremium() const { return premium; } bool isWieldedUnproperly() const { return wieldUnproperly; } protected: std::string getScriptEventName() const final; bool executeUseWeapon(Player* player, const LuaVariant& var) const; void internalUseWeapon(Player* player, Item* item, Creature* target, int32_t damageModifier) const; void internalUseWeapon(Player* player, Item* item, Tile* tile) const; void onUsedWeapon(Player* player, Item* item, Tile* destTile) const; virtual bool getSkillType(const Player*, const Item*, skills_t&, uint32_t&) const { return false; } uint32_t getManaCost(const Player* player) const; CombatParams params; uint32_t level; uint32_t magLevel; uint32_t mana; uint32_t manaPercent; uint32_t soul; uint16_t id; WeaponAction_t action; uint8_t breakChance; bool enabled; bool premium; bool wieldUnproperly; private: void decrementItemCount(Item* item) const; std::map<uint16_t, bool> vocWeaponMap; friend class Combat; }; class WeaponMelee final : public Weapon { public: explicit WeaponMelee(LuaScriptInterface* _interface); void configureWeapon(const ItemType& it) final; bool useWeapon(Player* player, Item* item, Creature* target) const final; int32_t getWeaponDamage(const Player* player, const Creature* target, const Item* item, bool maxDamage = false) const final; int32_t getElementDamage(const Player* player, const Creature* target, const Item* item) const final; CombatType_t getElementType() const final { return elementType; } protected: bool getSkillType(const Player* player, const Item* item, skills_t& skill, uint32_t& skillpoint) const final; CombatType_t elementType; uint16_t elementDamage; }; class WeaponDistance final : public Weapon { public: explicit WeaponDistance(LuaScriptInterface* _interface); void configureWeapon(const ItemType& it) final; bool interruptSwing() const final { return true; } bool useWeapon(Player* player, Item* item, Creature* target) const final; int32_t getWeaponDamage(const Player* player, const Creature* target, const Item* item, bool maxDamage = false) const final; int32_t getElementDamage(const Player* player, const Creature* target, const Item* item) const final; CombatType_t getElementType() const final { return elementType; } protected: bool getSkillType(const Player* player, const Item* item, skills_t& skill, uint32_t& skillpoint) const final; CombatType_t elementType; uint16_t elementDamage; }; class WeaponWand final : public Weapon { public: explicit WeaponWand(LuaScriptInterface* _interface); bool configureEvent(const pugi::xml_node& node) final; void configureWeapon(const ItemType& it) final; int32_t getWeaponDamage(const Player* player, const Creature* target, const Item* item, bool maxDamage = false) const final; int32_t getElementDamage(const Player*, const Creature*, const Item*) const final { return 0; } CombatType_t getElementType() const final { return COMBAT_NONE; } protected: bool getSkillType(const Player*, const Item*, skills_t&, uint32_t&) const final { return false; } int32_t minChange; int32_t maxChange; }; #endif
gpl-2.0
joyxu/autotest
client/tools/JUnit_api.py
65100
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated Thu Dec 1 09:58:36 2011 by generateDS.py version 2.7a. # import sys import getopt import re as re_ etree_ = None Verbose_import_ = False (XMLParser_import_none, XMLParser_import_lxml, XMLParser_import_elementtree ) = range(3) XMLParser_import_library = None try: # lxml from lxml import etree as etree_ XMLParser_import_library = XMLParser_import_lxml if Verbose_import_: print("running with lxml.etree") except ImportError: try: # cElementTree from Python 2.5+ # pylint: disable=E0602, E0611 import xml.etree.cElementTree as etree_ XMLParser_import_library = XMLParser_import_elementtree if Verbose_import_: print("running with cElementTree on Python 2.5+") except ImportError: try: # ElementTree from Python 2.5+ # pylint: disable=E0602,E0611 import xml.etree.ElementTree as etree_ XMLParser_import_library = XMLParser_import_elementtree if Verbose_import_: print("running with ElementTree on Python 2.5+") except ImportError: try: # normal cElementTree install import cElementTree as etree_ XMLParser_import_library = XMLParser_import_elementtree if Verbose_import_: print("running with cElementTree") except ImportError: try: # normal ElementTree install import elementtree.ElementTree as etree_ XMLParser_import_library = XMLParser_import_elementtree if Verbose_import_: print("running with ElementTree") except ImportError: raise ImportError("Failed to import ElementTree from any known place") def parsexml_(*args, **kwargs): if (XMLParser_import_library == XMLParser_import_lxml and 'parser' not in kwargs): # Use the lxml ElementTree compatible parser so that, e.g., # we ignore comments. kwargs['parser'] = etree_.ETCompatXMLParser() doc = etree_.parse(*args, **kwargs) return doc # # User methods # # Calls to the methods in these classes are generated by generateDS.py. # You can replace these methods by re-implementing the following class # in a module named generatedssuper.py. try: from generatedssuper import GeneratedsSuper except ImportError, exp: class GeneratedsSuper(object): def gds_format_string(self, input_data, input_name=''): return input_data def gds_validate_string(self, input_data, node, input_name=''): return input_data def gds_format_integer(self, input_data, input_name=''): return '%d' % input_data def gds_validate_integer(self, input_data, node, input_name=''): return input_data def gds_format_integer_list(self, input_data, input_name=''): return '%s' % input_data def gds_validate_integer_list(self, input_data, node, input_name=''): values = input_data.split() for value in values: try: fvalue = float(value) except (TypeError, ValueError), exp: raise_parse_error(node, 'Requires sequence of integers') return input_data def gds_format_float(self, input_data, input_name=''): return '%f' % input_data def gds_validate_float(self, input_data, node, input_name=''): return input_data def gds_format_float_list(self, input_data, input_name=''): return '%s' % input_data def gds_validate_float_list(self, input_data, node, input_name=''): values = input_data.split() for value in values: try: fvalue = float(value) except (TypeError, ValueError), exp: raise_parse_error(node, 'Requires sequence of floats') return input_data def gds_format_double(self, input_data, input_name=''): return '%e' % input_data def gds_validate_double(self, input_data, node, input_name=''): return input_data def gds_format_double_list(self, input_data, input_name=''): return '%s' % input_data def gds_validate_double_list(self, input_data, node, input_name=''): values = input_data.split() for value in values: try: fvalue = float(value) except (TypeError, ValueError), exp: raise_parse_error(node, 'Requires sequence of doubles') return input_data def gds_format_boolean(self, input_data, input_name=''): return '%s' % input_data def gds_validate_boolean(self, input_data, node, input_name=''): return input_data def gds_format_boolean_list(self, input_data, input_name=''): return '%s' % input_data def gds_validate_boolean_list(self, input_data, node, input_name=''): values = input_data.split() for value in values: if value not in ('true', '1', 'false', '0', ): raise_parse_error(node, 'Requires sequence of booleans ("true", "1", "false", "0")') return input_data def gds_str_lower(self, instring): return instring.lower() def get_path_(self, node): path_list = [] self.get_path_list_(node, path_list) path_list.reverse() path = '/'.join(path_list) return path Tag_strip_pattern_ = re_.compile(r'\{.*\}') def get_path_list_(self, node, path_list): if node is None: return tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) if tag: path_list.append(tag) self.get_path_list_(node.getparent(), path_list) def get_class_obj_(self, node, default_class=None): class_obj1 = default_class if 'xsi' in node.nsmap: classname = node.get('{%s}type' % node.nsmap['xsi']) if classname is not None: names = classname.split(':') if len(names) == 2: classname = names[1] class_obj2 = globals().get(classname) if class_obj2 is not None: class_obj1 = class_obj2 return class_obj1 def gds_build_any(self, node, type_name=None): return None # # If you have installed IPython you can uncomment and use the following. # IPython is available from http://ipython.scipy.org/. # ## from IPython.Shell import IPShellEmbed ## args = '' # ipshell = IPShellEmbed(args, ## banner = 'Dropping into IPython', # exit_msg = 'Leaving Interpreter, back to program.') # Then use the following line where and when you want to drop into the # IPython shell: # ipshell('<some message> -- Entering ipshell.\nHit Ctrl-D to exit') # # Globals # ExternalEncoding = 'ascii' Tag_pattern_ = re_.compile(r'({.*})?(.*)') String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') # # Support/utility functions. # def showIndent(outfile, level): for idx in range(level): outfile.write(' ') def quote_xml(inStr): if not inStr: return '' s1 = (isinstance(inStr, basestring) and inStr or '%s' % inStr) s1 = s1.replace('&', '&amp;') s1 = s1.replace('<', '&lt;') s1 = s1.replace('>', '&gt;') return s1 def quote_attrib(inStr): s1 = (isinstance(inStr, basestring) and inStr or '%s' % inStr) s1 = s1.replace('&', '&amp;') s1 = s1.replace('<', '&lt;') s1 = s1.replace('>', '&gt;') if '"' in s1: if "'" in s1: s1 = '"%s"' % s1.replace('"', "&quot;") else: s1 = "'%s'" % s1 else: s1 = '"%s"' % s1 return s1 def quote_python(inStr): s1 = inStr if s1.find("'") == -1: if s1.find('\n') == -1: return "'%s'" % s1 else: return "'''%s'''" % s1 else: if s1.find('"') != -1: s1 = s1.replace('"', '\\"') if s1.find('\n') == -1: return '"%s"' % s1 else: return '"""%s"""' % s1 def get_all_text_(node): if node.text is not None: text = node.text else: text = '' for child in node: if child.tail is not None: text += child.tail return text def find_attr_value_(attr_name, node): attrs = node.attrib attr_parts = attr_name.split(':') value = None if len(attr_parts) == 1: value = attrs.get(attr_name) elif len(attr_parts) == 2: prefix, name = attr_parts namespace = node.nsmap.get(prefix) if namespace is not None: value = attrs.get('{%s}%s' % (namespace, name, )) return value class GDSParseError(Exception): pass def raise_parse_error(node, msg): if XMLParser_import_library == XMLParser_import_lxml: msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) else: msg = '%s (element %s)' % (msg, node.tag, ) raise GDSParseError(msg) class MixedContainer: # Constants for category: CategoryNone = 0 CategoryText = 1 CategorySimple = 2 CategoryComplex = 3 # Constants for content_type: TypeNone = 0 TypeText = 1 TypeString = 2 TypeInteger = 3 TypeFloat = 4 TypeDecimal = 5 TypeDouble = 6 TypeBoolean = 7 def __init__(self, category, content_type, name, value): self.category = category self.content_type = content_type self.name = name self.value = value def getCategory(self): return self.category def getContenttype(self, content_type): return self.content_type def getValue(self): return self.value def getName(self): return self.name def export(self, outfile, level, name, namespace): if self.category == MixedContainer.CategoryText: # Prevent exporting empty content as empty lines. if self.value.strip(): outfile.write(self.value) elif self.category == MixedContainer.CategorySimple: self.exportSimple(outfile, level, name) else: # category == MixedContainer.CategoryComplex self.value.export(outfile, level, namespace, name) def exportSimple(self, outfile, level, name): if self.content_type == MixedContainer.TypeString: outfile.write('<%s>%s</%s>' % (self.name, self.value, self.name)) elif self.content_type == MixedContainer.TypeInteger or \ self.content_type == MixedContainer.TypeBoolean: outfile.write('<%s>%d</%s>' % (self.name, self.value, self.name)) elif self.content_type == MixedContainer.TypeFloat or \ self.content_type == MixedContainer.TypeDecimal: outfile.write('<%s>%f</%s>' % (self.name, self.value, self.name)) elif self.content_type == MixedContainer.TypeDouble: outfile.write('<%s>%g</%s>' % (self.name, self.value, self.name)) def exportLiteral(self, outfile, level, name): if self.category == MixedContainer.CategoryText: showIndent(outfile, level) outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n' % (self.category, self.content_type, self.name, self.value)) elif self.category == MixedContainer.CategorySimple: showIndent(outfile, level) outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n' % (self.category, self.content_type, self.name, self.value)) else: # category == MixedContainer.CategoryComplex showIndent(outfile, level) outfile.write('model_.MixedContainer(%d, %d, "%s",\n' % (self.category, self.content_type, self.name,)) self.value.exportLiteral(outfile, level + 1) showIndent(outfile, level) outfile.write(')\n') class MemberSpec_(object): def __init__(self, name='', data_type='', container=0): self.name = name self.data_type = data_type self.container = container def set_name(self, name): self.name = name def get_name(self): return self.name def set_data_type(self, data_type): self.data_type = data_type def get_data_type_chain(self): return self.data_type def get_data_type(self): if isinstance(self.data_type, list): if len(self.data_type) > 0: return self.data_type[-1] else: return 'xs:string' else: return self.data_type def set_container(self, container): self.container = container def get_container(self): return self.container def _cast(typ, value): if typ is None or value is None: return value return typ(value) # # Data representation classes. # class testsuites(GeneratedsSuper): """Contains an aggregation of testsuite results""" subclass = None superclass = None def __init__(self, testsuite=None): if testsuite is None: self.testsuite = [] else: self.testsuite = testsuite def factory(*args_, **kwargs_): if testsuites.subclass: # pylint: disable=E1102 return testsuites.subclass(*args_, **kwargs_) else: return testsuites(*args_, **kwargs_) factory = staticmethod(factory) def get_testsuite(self): return self.testsuite def set_testsuite(self, testsuite): self.testsuite = testsuite def add_testsuite(self, value): self.testsuite.append(value) def insert_testsuite(self, index, value): self.testsuite[index] = value def export(self, outfile, level, namespace_='', name_='testsuites', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = [] self.exportAttributes(outfile, level, already_processed, namespace_, name_='testsuites') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write('/>\n') def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='testsuites'): pass def exportChildren(self, outfile, level, namespace_='', name_='testsuites', fromsubclass_=False): for testsuite_ in self.testsuite: testsuite_.export(outfile, level, namespace_, name_='testsuite') def hasContent_(self): if ( self.testsuite ): return True else: return False def exportLiteral(self, outfile, level, name_='testsuites'): level += 1 self.exportLiteralAttributes(outfile, level, [], name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, already_processed, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('testsuite=[\n') level += 1 for testsuite_ in self.testsuite: showIndent(outfile, level) outfile.write('model_.testsuiteType(\n') testsuite_.exportLiteral(outfile, level, name_='testsuiteType') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node): self.buildAttributes(node, node.attrib, []) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_) def buildAttributes(self, node, attrs, already_processed): pass def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): if nodeName_ == 'testsuite': obj_ = testsuiteType.factory() obj_.build(child_) self.testsuite.append(obj_) # end class testsuites class testsuite(GeneratedsSuper): """Contains the results of exexuting a testsuiteFull class name of the test for non-aggregated testsuite documents. Class name without the package for aggregated testsuites documentswhen the test was executed. Timezone may not be specified.Host on which the tests were executed. 'localhost' should be used if the hostname cannot be determined.The total number of tests in the suiteThe total number of tests in the suite that failed. A failure is a test which the code has explicitly failed by using the mechanisms for that purpose. e.g., via an assertEqualsThe total number of tests in the suite that errorrd. An errored test is one that had an unanticipated problem. e.g., an unchecked throwable; or a problem with the implementation of the test.Time taken (in seconds) to execute the tests in the suite""" subclass = None superclass = None def __init__(self, tests=None, errors=None, name=None, timestamp=None, hostname=None, time=None, failures=None, properties=None, testcase=None, system_out=None, system_err=None, extensiontype_=None): self.tests = _cast(int, tests) self.errors = _cast(int, errors) self.name = _cast(None, name) self.timestamp = _cast(None, timestamp) self.hostname = _cast(None, hostname) self.time = _cast(float, time) self.failures = _cast(int, failures) self.properties = properties if testcase is None: self.testcase = [] else: self.testcase = testcase self.system_out = system_out self.system_err = system_err self.extensiontype_ = extensiontype_ def factory(*args_, **kwargs_): if testsuite.subclass: # pylint: disable=E1102 return testsuite.subclass(*args_, **kwargs_) else: return testsuite(*args_, **kwargs_) factory = staticmethod(factory) def get_properties(self): return self.properties def set_properties(self, properties): self.properties = properties def get_testcase(self): return self.testcase def set_testcase(self, testcase): self.testcase = testcase def add_testcase(self, value): self.testcase.append(value) def insert_testcase(self, index, value): self.testcase[index] = value def get_system_out(self): return self.system_out def set_system_out(self, system_out): self.system_out = system_out def get_system_err(self): return self.system_err def set_system_err(self, system_err): self.system_err = system_err def get_tests(self): return self.tests def set_tests(self, tests): self.tests = tests def get_errors(self): return self.errors def set_errors(self, errors): self.errors = errors def get_name(self): return self.name def set_name(self, name): self.name = name def get_timestamp(self): return self.timestamp def set_timestamp(self, timestamp): self.timestamp = timestamp def validate_ISO8601_DATETIME_PATTERN(self, value): # Validate type ISO8601_DATETIME_PATTERN, a restriction on xs:dateTime. pass def get_hostname(self): return self.hostname def set_hostname(self, hostname): self.hostname = hostname def get_time(self): return self.time def set_time(self, time): self.time = time def get_failures(self): return self.failures def set_failures(self, failures): self.failures = failures def get_extensiontype_(self): return self.extensiontype_ def set_extensiontype_(self, extensiontype_): self.extensiontype_ = extensiontype_ def export(self, outfile, level, namespace_='', name_='testsuite', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = [] self.exportAttributes(outfile, level, already_processed, namespace_, name_='testsuite') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write('/>\n') def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='testsuite'): if self.tests is not None and 'tests' not in already_processed: already_processed.append('tests') outfile.write(' tests="%s"' % self.gds_format_integer(self.tests, input_name='tests')) if self.errors is not None and 'errors' not in already_processed: already_processed.append('errors') outfile.write(' errors="%s"' % self.gds_format_integer(self.errors, input_name='errors')) if self.name is not None and 'name' not in already_processed: already_processed.append('name') outfile.write(' name=%s' % (self.gds_format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), )) if self.timestamp is not None and 'timestamp' not in already_processed: already_processed.append('timestamp') outfile.write(' timestamp=%s' % (quote_attrib(self.timestamp), )) if self.hostname is not None and 'hostname' not in already_processed: already_processed.append('hostname') outfile.write(' hostname=%s' % (self.gds_format_string(quote_attrib(self.hostname).encode(ExternalEncoding), input_name='hostname'), )) if self.time is not None and 'time' not in already_processed: already_processed.append('time') outfile.write(' time="%s"' % self.gds_format_float(self.time, input_name='time')) if self.failures is not None and 'failures' not in already_processed: already_processed.append('failures') outfile.write(' failures="%s"' % self.gds_format_integer(self.failures, input_name='failures')) if self.extensiontype_ is not None and 'xsi:type' not in already_processed: already_processed.append('xsi:type') outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') outfile.write(' xsi:type="%s"' % self.extensiontype_) def exportChildren(self, outfile, level, namespace_='', name_='testsuite', fromsubclass_=False): if self.properties is not None: self.properties.export(outfile, level, namespace_, name_='properties', ) for testcase_ in self.testcase: testcase_.export(outfile, level, namespace_, name_='testcase') if self.system_out is not None: showIndent(outfile, level) outfile.write('<%ssystem-out>%s</%ssystem-out>\n' % (namespace_, self.gds_format_string(quote_xml(self.system_out).encode(ExternalEncoding), input_name='system-out'), namespace_)) if self.system_err is not None: showIndent(outfile, level) outfile.write('<%ssystem-err>%s</%ssystem-err>\n' % (namespace_, self.gds_format_string(quote_xml(self.system_err).encode(ExternalEncoding), input_name='system-err'), namespace_)) def hasContent_(self): if ( self.properties is not None or self.testcase or self.system_out is not None or self.system_err is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='testsuite'): level += 1 self.exportLiteralAttributes(outfile, level, [], name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, already_processed, name_): if self.tests is not None and 'tests' not in already_processed: already_processed.append('tests') showIndent(outfile, level) outfile.write('tests = %d,\n' % (self.tests,)) if self.errors is not None and 'errors' not in already_processed: already_processed.append('errors') showIndent(outfile, level) outfile.write('errors = %d,\n' % (self.errors,)) if self.name is not None and 'name' not in already_processed: already_processed.append('name') showIndent(outfile, level) outfile.write('name = "%s",\n' % (self.name,)) if self.timestamp is not None and 'timestamp' not in already_processed: already_processed.append('timestamp') showIndent(outfile, level) outfile.write('timestamp = "%s",\n' % (self.timestamp,)) if self.hostname is not None and 'hostname' not in already_processed: already_processed.append('hostname') showIndent(outfile, level) outfile.write('hostname = "%s",\n' % (self.hostname,)) if self.time is not None and 'time' not in already_processed: already_processed.append('time') showIndent(outfile, level) outfile.write('time = %f,\n' % (self.time,)) if self.failures is not None and 'failures' not in already_processed: already_processed.append('failures') showIndent(outfile, level) outfile.write('failures = %d,\n' % (self.failures,)) def exportLiteralChildren(self, outfile, level, name_): if self.properties is not None: showIndent(outfile, level) outfile.write('properties=model_.propertiesType(\n') self.properties.exportLiteral(outfile, level, name_='properties') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('testcase=[\n') level += 1 for testcase_ in self.testcase: showIndent(outfile, level) outfile.write('model_.testcaseType(\n') testcase_.exportLiteral(outfile, level, name_='testcaseType') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') if self.system_out is not None: showIndent(outfile, level) outfile.write('system_out=%s,\n' % quote_python(self.system_out).encode(ExternalEncoding)) if self.system_err is not None: showIndent(outfile, level) outfile.write('system_err=%s,\n' % quote_python(self.system_err).encode(ExternalEncoding)) def build(self, node): self.buildAttributes(node, node.attrib, []) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_) def buildAttributes(self, node, attrs, already_processed): value = find_attr_value_('tests', node) if value is not None and 'tests' not in already_processed: already_processed.append('tests') try: self.tests = int(value) except ValueError, exp: raise_parse_error(node, 'Bad integer attribute: %s' % exp) value = find_attr_value_('errors', node) if value is not None and 'errors' not in already_processed: already_processed.append('errors') try: self.errors = int(value) except ValueError, exp: raise_parse_error(node, 'Bad integer attribute: %s' % exp) value = find_attr_value_('name', node) if value is not None and 'name' not in already_processed: already_processed.append('name') self.name = value self.name = ' '.join(self.name.split()) value = find_attr_value_('timestamp', node) if value is not None and 'timestamp' not in already_processed: already_processed.append('timestamp') self.timestamp = value self.validate_ISO8601_DATETIME_PATTERN(self.timestamp) # validate type ISO8601_DATETIME_PATTERN value = find_attr_value_('hostname', node) if value is not None and 'hostname' not in already_processed: already_processed.append('hostname') self.hostname = value self.hostname = ' '.join(self.hostname.split()) value = find_attr_value_('time', node) if value is not None and 'time' not in already_processed: already_processed.append('time') try: self.time = float(value) except ValueError, exp: raise ValueError('Bad float/double attribute (time): %s' % exp) value = find_attr_value_('failures', node) if value is not None and 'failures' not in already_processed: already_processed.append('failures') try: self.failures = int(value) except ValueError, exp: raise_parse_error(node, 'Bad integer attribute: %s' % exp) value = find_attr_value_('xsi:type', node) if value is not None and 'xsi:type' not in already_processed: already_processed.append('xsi:type') self.extensiontype_ = value def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): if nodeName_ == 'properties': obj_ = propertiesType.factory() obj_.build(child_) self.set_properties(obj_) elif nodeName_ == 'testcase': obj_ = testcaseType.factory() obj_.build(child_) self.testcase.append(obj_) elif nodeName_ == 'system-out': system_out_ = child_.text system_out_ = self.gds_validate_string(system_out_, node, 'system_out') self.system_out = system_out_ elif nodeName_ == 'system-err': system_err_ = child_.text system_err_ = self.gds_validate_string(system_err_, node, 'system_err') self.system_err = system_err_ # end class testsuite class system_out(GeneratedsSuper): """Data that was written to standard out while the test was executed""" subclass = None superclass = None def __init__(self): pass def factory(*args_, **kwargs_): if system_out.subclass: # pylint: disable=E1102 return system_out.subclass(*args_, **kwargs_) else: return system_out(*args_, **kwargs_) factory = staticmethod(factory) def export(self, outfile, level, namespace_='', name_='system-out', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = [] self.exportAttributes(outfile, level, already_processed, namespace_, name_='system-out') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write('/>\n') def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='system-out'): pass def exportChildren(self, outfile, level, namespace_='', name_='system-out', fromsubclass_=False): pass def hasContent_(self): if ( ): return True else: return False def exportLiteral(self, outfile, level, name_='system-out'): level += 1 self.exportLiteralAttributes(outfile, level, [], name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, already_processed, name_): pass def exportLiteralChildren(self, outfile, level, name_): pass def build(self, node): self.buildAttributes(node, node.attrib, []) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_) def buildAttributes(self, node, attrs, already_processed): pass def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): pass # end class system_out class system_err(GeneratedsSuper): """Data that was written to standard error while the test was executed""" subclass = None superclass = None def __init__(self): pass def factory(*args_, **kwargs_): if system_err.subclass: # pylint: disable=E1102 return system_err.subclass(*args_, **kwargs_) else: return system_err(*args_, **kwargs_) factory = staticmethod(factory) def export(self, outfile, level, namespace_='', name_='system-err', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = [] self.exportAttributes(outfile, level, already_processed, namespace_, name_='system-err') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write('/>\n') def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='system-err'): pass def exportChildren(self, outfile, level, namespace_='', name_='system-err', fromsubclass_=False): pass def hasContent_(self): if ( ): return True else: return False def exportLiteral(self, outfile, level, name_='system-err'): level += 1 self.exportLiteralAttributes(outfile, level, [], name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, already_processed, name_): pass def exportLiteralChildren(self, outfile, level, name_): pass def build(self, node): self.buildAttributes(node, node.attrib, []) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_) def buildAttributes(self, node, attrs, already_processed): pass def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): pass # end class system_err class testsuiteType(testsuite): """Derived from testsuite/@name in the non-aggregated documentsStarts at '0' for the first testsuite and is incremented by 1 for each following testsuite""" subclass = None superclass = testsuite def __init__(self, tests=None, errors=None, name=None, timestamp=None, hostname=None, time=None, failures=None, properties=None, testcase=None, system_out=None, system_err=None, id=None, package=None): super(testsuiteType, self).__init__(tests, errors, name, timestamp, hostname, time, failures, properties, testcase, system_out, system_err, ) self.id = _cast(int, id) self.package = _cast(None, package) pass def factory(*args_, **kwargs_): if testsuiteType.subclass: return testsuiteType.subclass(*args_, **kwargs_) else: return testsuiteType(*args_, **kwargs_) factory = staticmethod(factory) def get_id(self): return self.id def set_id(self, id): self.id = id def get_package(self): return self.package def set_package(self, package): self.package = package def export(self, outfile, level, namespace_='', name_='testsuiteType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = [] self.exportAttributes(outfile, level, already_processed, namespace_, name_='testsuiteType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write('/>\n') def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='testsuiteType'): super(testsuiteType, self).exportAttributes(outfile, level, already_processed, namespace_, name_='testsuiteType') if self.id is not None and 'id' not in already_processed: already_processed.append('id') outfile.write(' id="%s"' % self.gds_format_integer(self.id, input_name='id')) if self.package is not None and 'package' not in already_processed: already_processed.append('package') outfile.write(' package=%s' % (self.gds_format_string(quote_attrib(self.package).encode(ExternalEncoding), input_name='package'), )) def exportChildren(self, outfile, level, namespace_='', name_='testsuiteType', fromsubclass_=False): super(testsuiteType, self).exportChildren(outfile, level, namespace_, name_, True) def hasContent_(self): if ( super(testsuiteType, self).hasContent_() ): return True else: return False def exportLiteral(self, outfile, level, name_='testsuiteType'): level += 1 self.exportLiteralAttributes(outfile, level, [], name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, already_processed, name_): if self.id is not None and 'id' not in already_processed: already_processed.append('id') showIndent(outfile, level) outfile.write('id = %d,\n' % (self.id,)) if self.package is not None and 'package' not in already_processed: already_processed.append('package') showIndent(outfile, level) outfile.write('package = "%s",\n' % (self.package,)) super(testsuiteType, self).exportLiteralAttributes(outfile, level, already_processed, name_) def exportLiteralChildren(self, outfile, level, name_): super(testsuiteType, self).exportLiteralChildren(outfile, level, name_) def build(self, node): self.buildAttributes(node, node.attrib, []) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_) def buildAttributes(self, node, attrs, already_processed): value = find_attr_value_('id', node) if value is not None and 'id' not in already_processed: already_processed.append('id') try: self.id = int(value) except ValueError, exp: raise_parse_error(node, 'Bad integer attribute: %s' % exp) value = find_attr_value_('package', node) if value is not None and 'package' not in already_processed: already_processed.append('package') self.package = value self.package = ' '.join(self.package.split()) super(testsuiteType, self).buildAttributes(node, attrs, already_processed) def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): super(testsuiteType, self).buildChildren(child_, node, nodeName_, True) pass # end class testsuiteType class propertiesType(GeneratedsSuper): subclass = None superclass = None def __init__(self, property=None): if property is None: self.property = [] else: self.property = property def factory(*args_, **kwargs_): if propertiesType.subclass: # pylint: disable=E1102 return propertiesType.subclass(*args_, **kwargs_) else: return propertiesType(*args_, **kwargs_) factory = staticmethod(factory) def get_property(self): return self.property def set_property(self, property): self.property = property def add_property(self, value): self.property.append(value) def insert_property(self, index, value): self.property[index] = value def export(self, outfile, level, namespace_='', name_='propertiesType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = [] self.exportAttributes(outfile, level, already_processed, namespace_, name_='propertiesType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write('/>\n') def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='propertiesType'): pass def exportChildren(self, outfile, level, namespace_='', name_='propertiesType', fromsubclass_=False): for property_ in self.property: property_.export(outfile, level, namespace_, name_='property') def hasContent_(self): if ( self.property ): return True else: return False def exportLiteral(self, outfile, level, name_='propertiesType'): level += 1 self.exportLiteralAttributes(outfile, level, [], name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, already_processed, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('property=[\n') level += 1 for property_ in self.property: showIndent(outfile, level) outfile.write('model_.propertyType(\n') property_.exportLiteral(outfile, level, name_='propertyType') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node): self.buildAttributes(node, node.attrib, []) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_) def buildAttributes(self, node, attrs, already_processed): pass def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): if nodeName_ == 'property': obj_ = propertyType.factory() obj_.build(child_) self.property.append(obj_) # end class propertiesType class propertyType(GeneratedsSuper): subclass = None superclass = None def __init__(self, name=None, value=None): self.name = _cast(None, name) self.value = _cast(None, value) pass def factory(*args_, **kwargs_): if propertyType.subclass: # pylint: disable=E1102 return propertyType.subclass(*args_, **kwargs_) else: return propertyType(*args_, **kwargs_) factory = staticmethod(factory) def get_name(self): return self.name def set_name(self, name): self.name = name def get_value(self): return self.value def set_value(self, value): self.value = value def export(self, outfile, level, namespace_='', name_='propertyType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = [] self.exportAttributes(outfile, level, already_processed, namespace_, name_='propertyType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write('/>\n') def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='propertyType'): if self.name is not None and 'name' not in already_processed: already_processed.append('name') outfile.write(' name=%s' % (self.gds_format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), )) if self.value is not None and 'value' not in already_processed: already_processed.append('value') outfile.write(' value=%s' % (self.gds_format_string(quote_attrib(self.value).encode(ExternalEncoding), input_name='value'), )) def exportChildren(self, outfile, level, namespace_='', name_='propertyType', fromsubclass_=False): pass def hasContent_(self): if ( ): return True else: return False def exportLiteral(self, outfile, level, name_='propertyType'): level += 1 self.exportLiteralAttributes(outfile, level, [], name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, already_processed, name_): if self.name is not None and 'name' not in already_processed: already_processed.append('name') showIndent(outfile, level) outfile.write('name = "%s",\n' % (self.name,)) if self.value is not None and 'value' not in already_processed: already_processed.append('value') showIndent(outfile, level) outfile.write('value = "%s",\n' % (self.value,)) def exportLiteralChildren(self, outfile, level, name_): pass def build(self, node): self.buildAttributes(node, node.attrib, []) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_) def buildAttributes(self, node, attrs, already_processed): value = find_attr_value_('name', node) if value is not None and 'name' not in already_processed: already_processed.append('name') self.name = value self.name = ' '.join(self.name.split()) value = find_attr_value_('value', node) if value is not None and 'value' not in already_processed: already_processed.append('value') self.value = value def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): pass # end class propertyType class testcaseType(GeneratedsSuper): """Name of the test methodFull class name for the class the test method is in.Time taken (in seconds) to execute the test""" subclass = None superclass = None def __init__(self, classname=None, name=None, time=None, error=None, failure=None): self.classname = _cast(None, classname) self.name = _cast(None, name) self.time = _cast(float, time) self.error = error self.failure = failure def factory(*args_, **kwargs_): if testcaseType.subclass: # pylint: disable=E1102 return testcaseType.subclass(*args_, **kwargs_) else: return testcaseType(*args_, **kwargs_) factory = staticmethod(factory) def get_error(self): return self.error def set_error(self, error): self.error = error def get_failure(self): return self.failure def set_failure(self, failure): self.failure = failure def get_classname(self): return self.classname def set_classname(self, classname): self.classname = classname def get_name(self): return self.name def set_name(self, name): self.name = name def get_time(self): return self.time def set_time(self, time): self.time = time def export(self, outfile, level, namespace_='', name_='testcaseType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = [] self.exportAttributes(outfile, level, already_processed, namespace_, name_='testcaseType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write('/>\n') def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='testcaseType'): if self.classname is not None and 'classname' not in already_processed: already_processed.append('classname') outfile.write(' classname=%s' % (self.gds_format_string(quote_attrib(self.classname).encode(ExternalEncoding), input_name='classname'), )) if self.name is not None and 'name' not in already_processed: already_processed.append('name') outfile.write(' name=%s' % (self.gds_format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), )) if self.time is not None and 'time' not in already_processed: already_processed.append('time') outfile.write(' time="%s"' % self.gds_format_float(self.time, input_name='time')) def exportChildren(self, outfile, level, namespace_='', name_='testcaseType', fromsubclass_=False): if self.error is not None: self.error.export(outfile, level, namespace_, name_='error') if self.failure is not None: self.failure.export(outfile, level, namespace_, name_='failure') def hasContent_(self): if ( self.error is not None or self.failure is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='testcaseType'): level += 1 self.exportLiteralAttributes(outfile, level, [], name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, already_processed, name_): if self.classname is not None and 'classname' not in already_processed: already_processed.append('classname') showIndent(outfile, level) outfile.write('classname = "%s",\n' % (self.classname,)) if self.name is not None and 'name' not in already_processed: already_processed.append('name') showIndent(outfile, level) outfile.write('name = "%s",\n' % (self.name,)) if self.time is not None and 'time' not in already_processed: already_processed.append('time') showIndent(outfile, level) outfile.write('time = %f,\n' % (self.time,)) def exportLiteralChildren(self, outfile, level, name_): if self.error is not None: showIndent(outfile, level) outfile.write('error=model_.errorType(\n') self.error.exportLiteral(outfile, level, name_='error') showIndent(outfile, level) outfile.write('),\n') if self.failure is not None: showIndent(outfile, level) outfile.write('failure=model_.failureType(\n') self.failure.exportLiteral(outfile, level, name_='failure') showIndent(outfile, level) outfile.write('),\n') def build(self, node): self.buildAttributes(node, node.attrib, []) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_) def buildAttributes(self, node, attrs, already_processed): value = find_attr_value_('classname', node) if value is not None and 'classname' not in already_processed: already_processed.append('classname') self.classname = value self.classname = ' '.join(self.classname.split()) value = find_attr_value_('name', node) if value is not None and 'name' not in already_processed: already_processed.append('name') self.name = value self.name = ' '.join(self.name.split()) value = find_attr_value_('time', node) if value is not None and 'time' not in already_processed: already_processed.append('time') try: self.time = float(value) except ValueError, exp: raise ValueError('Bad float/double attribute (time): %s' % exp) def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): if nodeName_ == 'error': obj_ = errorType.factory() obj_.build(child_) self.set_error(obj_) elif nodeName_ == 'failure': obj_ = failureType.factory() obj_.build(child_) self.set_failure(obj_) # end class testcaseType class errorType(GeneratedsSuper): """The error message. e.g., if a java exception is thrown, the return value of getMessage()The type of error that occurred. e.g., if a java execption is thrown the full class name of the exception.""" subclass = None superclass = None def __init__(self, message=None, type_=None, valueOf_=None): self.message = _cast(None, message) self.type_ = _cast(None, type_) self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if errorType.subclass: # pylint: disable=E1102 return errorType.subclass(*args_, **kwargs_) else: return errorType(*args_, **kwargs_) factory = staticmethod(factory) def get_message(self): return self.message def set_message(self, message): self.message = message def get_type(self): return self.type_ def set_type(self, type_): self.type_ = type_ def get_valueOf_(self): return self.valueOf_ def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='errorType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = [] self.exportAttributes(outfile, level, already_processed, namespace_, name_='errorType') if self.hasContent_(): outfile.write('>') outfile.write(str(self.valueOf_).encode(ExternalEncoding)) self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write('/>\n') def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='errorType'): if self.message is not None and 'message' not in already_processed: already_processed.append('message') outfile.write(' message=%s' % (self.gds_format_string(quote_attrib(self.message).encode(ExternalEncoding), input_name='message'), )) if self.type_ is not None and 'type_' not in already_processed: already_processed.append('type_') outfile.write(' type=%s' % (self.gds_format_string(quote_attrib(self.type_).encode(ExternalEncoding), input_name='type'), )) def exportChildren(self, outfile, level, namespace_='', name_='errorType', fromsubclass_=False): pass def hasContent_(self): if ( self.valueOf_ ): return True else: return False def exportLiteral(self, outfile, level, name_='errorType'): level += 1 self.exportLiteralAttributes(outfile, level, [], name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) showIndent(outfile, level) outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,)) def exportLiteralAttributes(self, outfile, level, already_processed, name_): if self.message is not None and 'message' not in already_processed: already_processed.append('message') showIndent(outfile, level) outfile.write('message = "%s",\n' % (self.message,)) if self.type_ is not None and 'type_' not in already_processed: already_processed.append('type_') showIndent(outfile, level) outfile.write('type_ = "%s",\n' % (self.type_,)) def exportLiteralChildren(self, outfile, level, name_): pass def build(self, node): self.buildAttributes(node, node.attrib, []) self.valueOf_ = get_all_text_(node) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_) def buildAttributes(self, node, attrs, already_processed): value = find_attr_value_('message', node) if value is not None and 'message' not in already_processed: already_processed.append('message') self.message = value value = find_attr_value_('type', node) if value is not None and 'type' not in already_processed: already_processed.append('type') self.type_ = value def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): pass # end class errorType class failureType(GeneratedsSuper): """The message specified in the assertThe type of the assert.""" subclass = None superclass = None def __init__(self, message=None, type_=None, valueOf_=None): self.message = _cast(None, message) self.type_ = _cast(None, type_) self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if failureType.subclass: # pylint: disable=E1102 return failureType.subclass(*args_, **kwargs_) else: return failureType(*args_, **kwargs_) factory = staticmethod(factory) def get_message(self): return self.message def set_message(self, message): self.message = message def get_type(self): return self.type_ def set_type(self, type_): self.type_ = type_ def get_valueOf_(self): return self.valueOf_ def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='failureType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = [] self.exportAttributes(outfile, level, already_processed, namespace_, name_='failureType') if self.hasContent_(): outfile.write('>') outfile.write(str(self.valueOf_).encode(ExternalEncoding)) self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write('/>\n') def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='failureType'): if self.message is not None and 'message' not in already_processed: already_processed.append('message') outfile.write(' message=%s' % (self.gds_format_string(quote_attrib(self.message).encode(ExternalEncoding), input_name='message'), )) if self.type_ is not None and 'type_' not in already_processed: already_processed.append('type_') outfile.write(' type=%s' % (self.gds_format_string(quote_attrib(self.type_).encode(ExternalEncoding), input_name='type'), )) def exportChildren(self, outfile, level, namespace_='', name_='failureType', fromsubclass_=False): pass def hasContent_(self): if ( self.valueOf_ ): return True else: return False def exportLiteral(self, outfile, level, name_='failureType'): level += 1 self.exportLiteralAttributes(outfile, level, [], name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) showIndent(outfile, level) outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,)) def exportLiteralAttributes(self, outfile, level, already_processed, name_): if self.message is not None and 'message' not in already_processed: already_processed.append('message') showIndent(outfile, level) outfile.write('message = "%s",\n' % (self.message,)) if self.type_ is not None and 'type_' not in already_processed: already_processed.append('type_') showIndent(outfile, level) outfile.write('type_ = "%s",\n' % (self.type_,)) def exportLiteralChildren(self, outfile, level, name_): pass def build(self, node): self.buildAttributes(node, node.attrib, []) self.valueOf_ = get_all_text_(node) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_) def buildAttributes(self, node, attrs, already_processed): value = find_attr_value_('message', node) if value is not None and 'message' not in already_processed: already_processed.append('message') self.message = value value = find_attr_value_('type', node) if value is not None and 'type' not in already_processed: already_processed.append('type') self.type_ = value def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): pass # end class failureType USAGE_TEXT = """ Usage: python <Parser>.py [ -s ] <in_xml_file> """ def usage(): print USAGE_TEXT sys.exit(1) def get_root_tag(node): tag = Tag_pattern_.match(node.tag).groups()[-1] rootClass = globals().get(tag) return tag, rootClass def parse(inFileName): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'testsuite' rootClass = testsuite rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None sys.stdout.write('<?xml version="1.0" ?>\n') rootObj.export(sys.stdout, 0, name_=rootTag, namespacedef_='') return rootObj def parseString(inString): from StringIO import StringIO doc = parsexml_(StringIO(inString)) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'testsuite' rootClass = testsuite rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None sys.stdout.write('<?xml version="1.0" ?>\n') rootObj.export(sys.stdout, 0, name_="testsuite", namespacedef_='') return rootObj def parseLiteral(inFileName): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'testsuite' rootClass = testsuite rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None sys.stdout.write('#from JUnit_api import *\n\n') sys.stdout.write('import JUnit_api as model_\n\n') sys.stdout.write('rootObj = model_.rootTag(\n') rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) sys.stdout.write(')\n') return rootObj def main(): args = sys.argv[1:] if len(args) == 1: parse(args[0]) else: usage() if __name__ == '__main__': #import pdb; pdb.set_trace() main() __all__ = [ "errorType", "failureType", "propertiesType", "propertyType", "system_err", "system_out", "testcaseType", "testsuite", "testsuiteType", "testsuites" ]
gpl-2.0
luisivan/QtOctave
qtoctave/src/pkg_bind.cpp
1792
#include <QFile> #include <QMessageBox> #include "pkg_bind.h" #include "config.h" PkgBind *PkgBind::instance = NULL; /* Constructor */ PkgBind::PkgBind() { loadCommandList(); }; /* Get the unique instance * or create it if there isn't any */ PkgBind *PkgBind::getInstance() { if(instance==NULL) instance = new PkgBind(); return instance; } /* Load the command list from a file */ void PkgBind::loadCommandList() { QString path = PKG_CMD_PATH; QFile file(path); if(file.open(QIODevice::ReadOnly)) { char buffer[1024]; int len; while((len = file.readLine(buffer, sizeof(buffer))) > -1) { if(buffer[len - 1] == '\n') buffer[len - 1] = '\0'; commands << QString(buffer); } printf("[PkgBind::loadCommandList] '%s' loaded\n", path.toLocal8Bit().constData()); }else{ printf("[PkgBind::loadCommandList] '%s' can not be loaded\n", path.toLocal8Bit().constData()); } } /* Check if a symbol is defined * as a funciont included in some package */ bool PkgBind::checkSymbol(const QString &s) { return commands.contains(s); } /* Invoke the package manager * for install the package with the command * "cmd" */ void PkgBind::invokePackageManager(const QString &s) { QMessageBox *msgBox = new QMessageBox(QMessageBox::Question, "Package Manager", "There is a package that provides the command '" + s + "'\n" "Do you want to try to install it now?", QMessageBox::Yes | QMessageBox::No); invokeCmd = QString("qtoctave_pkg -s ") + s + "&"; connect(msgBox, SIGNAL(finished(int)), this, SLOT(invokeResponse(int))); msgBox->show(); } /* The dialog response */ void PkgBind::invokeResponse(int result) { if(result == QMessageBox::Yes) system(invokeCmd.toLocal8Bit().constData()); }
gpl-2.0
felipebetancur/sc3-plugins
source/StkUGens/stk-4.4.2/doc/html/classstk_1_1InetWvOut-members.html
10479
<HTML> <HEAD> <TITLE>The Synthesis ToolKit in C++ (STK)</TITLE> <LINK HREF="doxygen.css" REL="stylesheet" TYPE="text/css"> </HEAD> <BODY BGCOLOR="#FFFFFF"> <CENTER> <img src="princeton.gif"> &nbsp; <img src="ccrma.gif"> &nbsp; <img src="mcgill.gif"><P> <a class="qindex" href="index.html">Home</a> &nbsp; <a class="qindex" href="information.html">Information</a> &nbsp; <a class="qindex" href="classes.html">Classes</a> &nbsp; <a class="qindex" href="download.html">Download</a> &nbsp; <a class="qindex" href="usage.html">Usage</a> &nbsp; <a class="qindex" href="maillist.html">Mail List</a> &nbsp; <a class="qindex" href="system.html">Requirements</a> &nbsp; <a class="qindex" href="links.html">Links</a> &nbsp; <a class="qindex" href="faq.html">FAQ</a> &nbsp; <a class="qindex" href="tutorial.html">Tutorial</a></CENTER> <HR> <!-- Generated by Doxygen 1.6.2 --> <div class="contents"> <h1>stk::InetWvOut Member List</h1>This is the complete list of members for <a class="el" href="classstk_1_1InetWvOut.html">stk::InetWvOut</a>, including all inherited members.<table> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#a5ab0e88856708f65887295ad4ad90340">addSampleRateAlert</a>(Stk *ptr)</td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1WvOut.html#aed503fe979c33eb8240901f005cb48d5">clipStatus</a>(void)</td><td><a class="el" href="classstk_1_1WvOut.html">stk::WvOut</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1InetWvOut.html#a4c8b6fb25c6d751b7929bec9a2d04a53">connect</a>(int port, Socket::ProtocolType protocol=Socket::PROTO_TCP, std::string hostname=&quot;localhost&quot;, unsigned int nChannels=1, Stk::StkFormat format=STK_SINT16)</td><td><a class="el" href="classstk_1_1InetWvOut.html">stk::InetWvOut</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1InetWvOut.html#a2314d2e2d005c5b08aa24d21075af638">disconnect</a>(void)</td><td><a class="el" href="classstk_1_1InetWvOut.html">stk::InetWvOut</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1WvOut.html#aa0ef107e58e0b470cbb47de292251a5e">getFrameCount</a>(void) const </td><td><a class="el" href="classstk_1_1WvOut.html">stk::WvOut</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1WvOut.html#aca11b8991f281beb2b1c4d562c7ff43b">getTime</a>(void) const </td><td><a class="el" href="classstk_1_1WvOut.html">stk::WvOut</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#a48ac73a0d8ca28445ba1a054e1f061ff">handleError</a>(const char *message, StkError::Type type)</td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [static]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#abc18b8fc8ed5b992bd2efef162a40777">handleError</a>(std::string message, StkError::Type type)</td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [static]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#a577656590baea0d65057b221f050f83d">handleError</a>(StkError::Type type)</td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#ab8a52e4897bea5c0f5e66adf37a8e39b">ignoreSampleRateChange</a>(bool ignore=true)</td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1InetWvOut.html#acc7c0b00c68cb76d1b15e7187d67a966">InetWvOut</a>(unsigned long packetFrames=1024)</td><td><a class="el" href="classstk_1_1InetWvOut.html">stk::InetWvOut</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1InetWvOut.html#af486ade34547956d4ad7c27cf304a085">InetWvOut</a>(int port, Socket::ProtocolType protocol=Socket::PROTO_TCP, std::string hostname=&quot;localhost&quot;, unsigned int nChannels=1, Stk::StkFormat format=STK_SINT16, unsigned long packetFrames=1024)</td><td><a class="el" href="classstk_1_1InetWvOut.html">stk::InetWvOut</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#affb98f8f1f65ddc9e4af8440056b1504">printErrors</a>(bool status)</td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [inline, static]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#a5f3fd05b709788213549fe2cbaf4a52a">rawwavePath</a>(void)</td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [inline, static]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#a349865986f712f58087cb72603a6ced8">removeSampleRateAlert</a>(Stk *ptr)</td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1WvOut.html#a73f7143c2a574afd0a6c7934a92e7bf3">resetClipStatus</a>(void)</td><td><a class="el" href="classstk_1_1WvOut.html">stk::WvOut</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#a5fbe37000a611ce56075ee7d8936472d">sampleRate</a>(void)</td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [inline, static]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#a740e872daa4b2ad1c918163e7c5ab56b">sampleRateChanged</a>(StkFloat newRate, StkFloat oldRate)</td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [protected, virtual]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#a4f641ad194f9d8ce1f9d1ae56af5686b">setRawwavePath</a>(std::string path)</td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [static]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#a46e2f55e5a92c717c3893fe23dde88a5">setSampleRate</a>(StkFloat rate)</td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [static]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#a2d8b38b9f808fb7c5e65c228b4b7dbbb">showWarnings</a>(bool status)</td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [inline, static]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#ad75619ab92a0c19b5a52cb68884511e3">sleep</a>(unsigned long milliseconds)</td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [static]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#a9bff83b5a318ff171f94a218ad52226b">Stk</a>(void)</td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#a079e62be7093d593498e9d2ba4ac20fa">STK_FLOAT32</a></td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [static]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#a57b00150ae559b6f099be117b2e53af4">STK_FLOAT64</a></td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [static]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#a5a807971b7fc3c8985d97823be079a7b">STK_SINT16</a></td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [static]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#afbe8049756ea88bdd8cebad65305dd52">STK_SINT24</a></td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [static]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#a605c96894e1b0f1f08a80214a08012ad">STK_SINT32</a></td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [static]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#adec863631653693af8f1ed5c0cfc5c4c">STK_SINT8</a></td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [static]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#ab2dc4c9e67317eb0753868a89c8095f6">swap16</a>(unsigned char *ptr)</td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [static]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#a820631139e6f7e23d328d387c0f530fd">swap32</a>(unsigned char *ptr)</td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [static]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#a5f744eadf29ecbfbeddfdf7ceb5853c9">swap64</a>(unsigned char *ptr)</td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [static]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1InetWvOut.html#a800f77228d851a2d276fae6a24bcdc9a">tick</a>(const StkFloat sample)</td><td><a class="el" href="classstk_1_1InetWvOut.html">stk::InetWvOut</a></td><td><code> [virtual]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1InetWvOut.html#a0305b3498e0277443a9309799e4ad8b7">tick</a>(const StkFrames &amp;frames)</td><td><a class="el" href="classstk_1_1InetWvOut.html">stk::InetWvOut</a></td><td><code> [virtual]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1WvOut.html#a4337bc4efb010ce57af3543dc5ed6f66">WvOut</a>(void)</td><td><a class="el" href="classstk_1_1WvOut.html">stk::WvOut</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1InetWvOut.html#ae58f286de491788df700479f88b3c625">~InetWvOut</a>()</td><td><a class="el" href="classstk_1_1InetWvOut.html">stk::InetWvOut</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classstk_1_1Stk.html#ad0d5c6ab745ad2841a59032addae3905">~Stk</a>(void)</td><td><a class="el" href="classstk_1_1Stk.html">stk::Stk</a></td><td><code> [protected, virtual]</code></td></tr> </table></div> <HR> <table> <tr><td><A HREF="http://ccrma.stanford.edu/software/stk/"><I>The Synthesis ToolKit in C++ (STK)</I></A></td></tr> <tr><td>&copy;1995-2010 Perry R. Cook and Gary P. Scavone. All Rights Reserved.</td></tr> </table> </BODY> </HTML>
gpl-2.0
jolay/pesatec
cache/mod_vvisit_counter/860aea6b5aac75573e8d7d8ebc839c97-cache-mod_vvisit_counter-12c8414db0decbe26a3df6aa66213421.php
83
<?php die("Access Denied"); ?>#x#a:2:{s:6:"output";s:0:"";s:6:"result";s:4:"9243";}
gpl-2.0
knil-sama/YADDW
lib/apache-jena-2.12.1/javadoc-arq/com/hp/hpl/jena/sparql/function/library/class-use/FN_DayFromDateTime.html
4690
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_45) on Thu Oct 02 16:39:53 BST 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class com.hp.hpl.jena.sparql.function.library.FN_DayFromDateTime (Apache Jena ARQ)</title> <meta name="date" content="2014-10-02"> <link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.hp.hpl.jena.sparql.function.library.FN_DayFromDateTime (Apache Jena ARQ)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../com/hp/hpl/jena/sparql/function/library/FN_DayFromDateTime.html" title="class in com.hp.hpl.jena.sparql.function.library">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?com/hp/hpl/jena/sparql/function/library/class-use/FN_DayFromDateTime.html" target="_top">Frames</a></li> <li><a href="FN_DayFromDateTime.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class com.hp.hpl.jena.sparql.function.library.FN_DayFromDateTime" class="title">Uses of Class<br>com.hp.hpl.jena.sparql.function.library.FN_DayFromDateTime</h2> </div> <div class="classUseContainer">No usage of com.hp.hpl.jena.sparql.function.library.FN_DayFromDateTime</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../com/hp/hpl/jena/sparql/function/library/FN_DayFromDateTime.html" title="class in com.hp.hpl.jena.sparql.function.library">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?com/hp/hpl/jena/sparql/function/library/class-use/FN_DayFromDateTime.html" target="_top">Frames</a></li> <li><a href="FN_DayFromDateTime.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Licenced under the Apache License, Version 2.0</small></p> </body> </html>
gpl-2.0
highfellow/inkscape-remove-duplicates
app/main.cpp
2030
#include "SampleCode.h" #include "SkView.h" #include "SkBlurMaskFilter.h" #include "SkCanvas.h" #include "SkGradientShader.h" #include "SkGraphics.h" #include "SkImageDecoder.h" #include "SkPath.h" #include "SkRandom.h" #include "SkRegion.h" #include "SkShader.h" #include "SkUtils.h" #include "SkXfermode.h" #include "SkColorPriv.h" #include "SkColorFilter.h" #include "SkTime.h" #include "SkTypeface.h" #include "SkTextBox.h" #include "SkOSFile.h" #include "SkStream.h" #include "SkSVGParser.h" class SVGView : public SkView { public: SVGView() { SkXMLParserError err; SkFILEStream stream("/testsvg2.svg"); SkSVGParser parser(&err); if (parser.parse(stream)) { const char* text = parser.getFinal(); SkFILEWStream output("/testanim.txt"); output.write(text, strlen(text)); } } protected: // overrides from SkEventSink virtual bool onQuery(SkEvent* evt) { if (SampleCode::TitleQ(*evt)) { SkString str("SVG"); SampleCode::TitleR(evt, str.c_str()); return true; } return this->INHERITED::onQuery(evt); } void drawBG(SkCanvas* canvas) { canvas->drawColor(SK_ColorWHITE); } virtual void onDraw(SkCanvas* canvas) { this->drawBG(canvas); } virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) { return new Click(this); } virtual bool onClick(Click* click) { int y = click->fICurr.fY; if (y < 0) { y = 0; } else if (y > 255) { y = 255; } fByte = y; this->inval(NULL); return true; } private: int fByte; typedef SkView INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static SkView* MyFactory() { return new SVGView; } static SkViewRegister reg(MyFactory);
gpl-2.0
ifolder/simias
dependencies/external/libflaim/win64/flaimtk.h
207969
//------------------------------------------------------------------------------ // Desc: FLAIM's cross-platform toolkit public definitions and interfaces // Tabs: 3 // // Copyright (c) 2003-2007 Novell, Inc. All Rights Reserved. // // This library 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; version 2.1 // of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, contact Novell, Inc. // // To contact Novell about this file by physical or electronic mail, // you may find current contact information at www.novell.com. // // $Id$ //------------------------------------------------------------------------------ /// \file #ifndef FTK_H #define FTK_H /// \defgroup retcodes Return Codes #ifndef FLM_PLATFORM_CONFIGURED #define FLM_PLATFORM_CONFIGURED // Determine the build platform #undef FLM_WIN #undef FLM_NLM #undef FLM_UNIX #undef FLM_AIX #undef FLM_LINUX #undef FLM_SOLARIS #undef FLM_HPUX #undef FLM_OSX #undef FLM_S390 #undef FLM_IA64 #undef FLM_PPC #undef FLM_SPARC #undef FLM_SPARC_PLUS #undef FLM_X86 #undef FLM_BIG_ENDIAN #undef FLM_STRICT_ALIGNMENT #undef FLM_GNUC #undef FLM_HAS_ASYNC_IO #undef FLM_HAS_DIRECT_IO #if defined( __GNUC__) #define FLM_GNUC #if defined( __arch64__) #if !defined( FLM_64BIT) #define FLM_64BIT #endif #endif #endif #if defined( __NETWARE__) || defined( NLM) || defined( N_PLAT_NLM) #if defined( __WATCOMC__) && defined( __386__) #define FLM_X86 #else #error Platform architecture not supported #endif #define FLM_NLM #if !defined( FLM_RING_ZERO_NLM) && !defined( FLM_LIBC_NLM) #define FLM_RING_ZERO_NLM #endif #define FLM_OSTYPE_STR "NetWare" #if defined( __WATCOMC__) #define FLM_WATCOM_NLM #elif defined( __MWERKS__) #define FLM_MWERKS_NLM #endif #if defined( FLM_RING_ZERO_NLM) #define FLM_HAS_ASYNC_IO #define FLM_HAS_DIRECT_IO #endif #elif defined( _WIN64) #if defined( _M_IX6) || defined( _M_X64) #define FLM_X86 #endif #define FLM_WIN #define FLM_OSTYPE_STR "Windows" #ifndef FLM_64BIT #define FLM_64BIT #endif #define FLM_STRICT_ALIGNMENT #define FLM_HAS_ASYNC_IO #define FLM_HAS_DIRECT_IO #elif defined( _WIN32) #if defined( _M_IX86) || defined( _M_X64) #define FLM_X86 #else #error Platform architecture not supported #endif #define FLM_WIN #define FLM_OSTYPE_STR "Windows" #define FLM_HAS_ASYNC_IO #define FLM_HAS_DIRECT_IO #elif defined( _AIX) #define FLM_AIX #define FLM_OSTYPE_STR "AIX" #define FLM_UNIX #define FLM_BIG_ENDIAN #define FLM_STRICT_ALIGNMENT #elif defined( linux) #define FLM_LINUX #define FLM_OSTYPE_STR "Linux" #define FLM_UNIX #if defined( __PPC__) || defined( __ppc__) #define FLM_PPC #define FLM_BIG_ENDIAN #define FLM_STRICT_ALIGNMENT #elif defined( __s390__) #define FLM_S390 #define FLM_BIG_ENDIAN #define FLM_STRICT_ALIGNMENT #elif defined( __s390x__) #define FLM_S390 #ifndef FLM_64BIT #define FLM_64BIT #endif #define FLM_BIG_ENDIAN #define FLM_STRICT_ALIGNMENT #elif defined( __ia64__) #define FLM_IA64 #ifndef FLM_64BIT #define FLM_64BIT #endif #define FLM_STRICT_ALIGNMENT #elif defined( sparc) || defined( __sparc) || defined( __sparc__) #define FLM_SPARC #define FLM_BIG_ENDIAN #define FLM_STRICT_ALIGNMENT #if !defined ( FLM_SPARC_GENERIC) #if defined( __sparcv8plus) || defined( __sparcv9) || defined( __sparcv9__) || \ defined( __sparc_v8__) || defined( __sparc_v9__) || defined( __arch64__) #define FLM_SPARC_PLUS #endif #endif #elif defined( __x86__) || defined( __i386__) || defined( __x86_64__) #define FLM_X86 #else #error Platform architecture not supported #endif #define FLM_HAS_ASYNC_IO #define FLM_HAS_DIRECT_IO #elif defined( sun) #define FLM_SOLARIS #define FLM_OSTYPE_STR "Solaris" #define FLM_UNIX #define FLM_STRICT_ALIGNMENT #if defined( sparc) || defined( __sparc) || defined( __sparc__) #define FLM_SPARC #define FLM_BIG_ENDIAN #if !defined ( FLM_SPARC_GENERIC) #if defined( __sparcv8plus) || defined( __sparcv9) #define FLM_SPARC_PLUS #endif #endif #elif defined( i386) || defined( _i386) #define FLM_X86 #else #error Platform architecture not supported #endif #define FLM_HAS_ASYNC_IO #define FLM_HAS_DIRECT_IO #elif defined( __hpux) || defined( hpux) #define FLM_HPUX #define FLM_OSTYPE_STR "HPUX" #define FLM_UNIX #define FLM_BIG_ENDIAN #define FLM_STRICT_ALIGNMENT #define FLM_HAS_ASYNC_IO #define FLM_HAS_DIRECT_IO #elif defined( __APPLE__) #define FLM_OSX #define FLM_OSTYPE_STR "OSX" #define FLM_UNIX #if (defined( __ppc__) || defined( __ppc64__)) #define FLM_PPC #define FLM_BIG_ENDIAN #define FLM_STRICT_ALIGNMENT #elif defined( __x86__) || defined( __x86_64__) #define FLM_X86 #else #error Platform architecture not supported #endif #define FLM_HAS_ASYNC_IO #define FLM_HAS_DIRECT_IO #else #error Platform architecture is undefined. #endif #if !defined( FLM_64BIT) && !defined( FLM_32BIT) #if defined( FLM_UNIX) #if defined( __x86_64__) || defined( _M_X64) || \ defined( _LP64) || defined( __LP64__) || \ defined ( __64BIT__) || defined( __arch64__) || \ defined( __sparcv9) || defined( __sparcv9__) #define FLM_64BIT #endif #endif #endif #if !defined( FLM_64BIT) #define FLM_32BIT #elif defined( FLM_32BIT) #error Cannot define both FLM_32BIT and FLM_64BIT #endif #if defined( __x86_64__) || defined( _M_X64) || \ defined( _LP64) || defined( __LP64__) || \ defined ( __64BIT__) || defined( __arch64__) || \ defined( __sparcv9) || defined( __sparcv9__) #if !defined( FLM_64BIT) #error Platform word size is incorrect #endif #else #if !defined( FLM_32BIT) #error Platform word size is incorrect #endif #endif #ifdef FLM_NLM #define FSTATIC #else #define FSTATIC static #endif // Debug or release build? #ifndef FLM_DEBUG #if defined( DEBUG) || (defined( PRECHECKIN) && PRECHECKIN != 0) #define FLM_DEBUG #endif #endif // Alignment #if defined( FLM_UNIX) || defined( FLM_64BIT) #define FLM_ALLOC_ALIGN 0x0007 #define FLM_ALIGN_SIZE 8 #elif defined( FLM_WIN) || defined( FLM_NLM) #define FLM_ALLOC_ALIGN 0x0003 #define FLM_ALIGN_SIZE 4 #else #error Platform not supported #endif // Basic type definitions #if defined( FLM_UNIX) typedef unsigned long FLMUINT; typedef long FLMINT; typedef unsigned char FLMBYTE; typedef unsigned short FLMUNICODE; typedef unsigned long long FLMUINT64; typedef unsigned int FLMUINT32; typedef unsigned short FLMUINT16; typedef unsigned char FLMUINT8; typedef long long FLMINT64; typedef int FLMINT32; typedef short FLMINT16; typedef signed char FLMINT8; #if defined( FLM_64BIT) || defined( FLM_OSX) || \ defined( FLM_S390) || defined( FLM_HPUX) || defined( FLM_AIX) typedef unsigned long FLMSIZET; #else typedef unsigned FLMSIZET; #endif #else #if defined( FLM_WIN) #if defined( FLM_64BIT) typedef unsigned __int64 FLMUINT; typedef __int64 FLMINT; typedef unsigned __int64 FLMSIZET; typedef unsigned int FLMUINT32; #elif _MSC_VER >= 1300 typedef unsigned long __w64 FLMUINT; typedef long __w64 FLMINT; typedef __w64 unsigned int FLMUINT32; typedef __w64 unsigned int FLMSIZET; #else typedef unsigned long FLMUINT; typedef long FLMINT; typedef unsigned int FLMUINT32; typedef unsigned int FLMSIZET; #endif #elif defined( FLM_NLM) typedef unsigned long int FLMUINT; typedef long int FLMINT; typedef unsigned long int FLMUINT32; typedef unsigned FLMSIZET; #else #error Platform not supported #endif typedef unsigned char FLMBYTE; typedef unsigned short int FLMUNICODE; typedef unsigned short int FLMUINT16; typedef unsigned char FLMUINT8; typedef signed int FLMINT32; typedef signed short int FLMINT16; typedef signed char FLMINT8; #if defined( __MWERKS__) typedef unsigned long long FLMUINT64; typedef long long FLMINT64; #else typedef unsigned __int64 FLMUINT64; typedef __int64 FLMINT64; #endif #endif #if defined( FLM_WIN) || defined( FLM_NLM) #define FLMATOMIC volatile long #else #define FLMATOMIC volatile int #endif /// \addtogroup retcodes /// @{ typedef FLMINT32 RCODE; ///< Return code /// @} typedef FLMINT32 FLMBOOL; #define F_FILENAME_SIZE 256 #define F_PATH_MAX_SIZE 256 #define F_WAITFOREVER (0xFFFFFFFF) #define FLM_MAX_UINT ((FLMUINT)(-1L)) #define FLM_MAX_INT ((FLMINT)(((FLMUINT)(-1L)) >> 1)) #define FLM_MIN_INT ((FLMINT)((((FLMUINT)(-1L)) >> 1) + 1)) #define FLM_MAX_UINT32 ((FLMUINT32)(0xFFFFFFFFL)) #define FLM_MAX_INT32 ((FLMINT32)(0x7FFFFFFFL)) #define FLM_MIN_INT32 ((FLMINT32)(0x80000000L)) #define FLM_MAX_UINT16 ((FLMUINT16)(0xFFFF)) #define FLM_MAX_INT16 ((FLMINT16)(0x7FFF)) #define FLM_MIN_INT16 ((FLMINT16)(0x8000)) #define FLM_MAX_UINT8 ((FLMUINT8)0xFF) #if ((_MSC_VER >= 1200) && (_MSC_VER < 1300)) || defined( FLM_NLM) #define FLM_MAX_UINT64 ((FLMUINT64)(0xFFFFFFFFFFFFFFFFL)) #define FLM_MAX_INT64 ((FLMINT64)(0x7FFFFFFFFFFFFFFFL)) #define FLM_MIN_INT64 ((FLMINT64)(0x8000000000000000L)) #else #define FLM_MAX_UINT64 ((FLMUINT64)(0xFFFFFFFFFFFFFFFFLL)) #define FLM_MAX_INT64 ((FLMINT64)(0x7FFFFFFFFFFFFFFFLL)) #define FLM_MIN_INT64 ((FLMINT64)(0x8000000000000000LL)) #endif #endif // xpcselany keeps MS compilers from complaining about multiple definitions #if defined(_MSC_VER) #define xpcselany __declspec(selectany) #else #define xpcselany #endif #if !defined( FLM_UNIX) && !defined( FLM_64BIT) #define FLM_PACK_STRUCTS #ifdef FLM_WIN // For some reason, Windows emits a warning when the packing // is changed. #pragma warning( disable : 4103) #endif #endif #ifdef FLM_PACK_STRUCTS #pragma pack(push, 1) #endif typedef struct { FLMUINT32 l; FLMUINT16 w1; FLMUINT16 w2; FLMUINT8 b[ 8]; } FLM_GUID; #ifdef FLM_PACK_STRUCTS #pragma pack(pop) #endif #define RFLMIID const FLM_GUID & #define RFLMCLSID const FLM_GUID & #define FLMGUID FLM_GUID #define FLMCLSID FLM_GUID // FLM_DEFINE_GUID may be used to define or declare a GUID // #define FLM_INIT_GUID before including this header file when // you want to define the guid, all other inclusions will only declare // the guid, not define it. #if !defined( PCOM_INIT_GUID) #define FLM_DEFINE_GUID( name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ extern const FLMGUID name #else #define FLM_DEFINE_GUID( name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ extern const xpcselany FLMGUID name \ = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } #endif // platform-specific definitions for FINLINE #if defined( FLM_WIN) #ifdef FLM_DEBUG #define FINLINE inline #else #define FINLINE __forceinline #endif #elif defined( FLM_NLM) #define FINLINE inline #elif defined( FLM_UNIX) #define FINLINE inline #else #error Platform not supported #endif // platform-specific API definitions for FTK* macros #if defined( FLM_WIN) #if defined( FTK_STATIC_LINK) #define FTKEXP #else #if defined( FTK_SOURCE) #define FTKEXP __declspec(dllexport) #else #define FTKEXP __declspec(dllimport) #endif #endif #define FTKAPI __stdcall #elif defined( FLM_NLM) #define FTKEXP #define FTKAPI __stdcall #elif defined( FLM_UNIX) #define FTKEXP #define FTKAPI #else #error Platform not supported #endif #define FTKXPC extern "C" FTKEXP /**************************************************************************** Desc: Argument lists ****************************************************************************/ #define f_alignedsize(n) \ ((sizeof(n) + FLM_ALIGN_SIZE - 1) & ~(FLM_ALIGN_SIZE - 1) ) #if defined( FLM_RING_ZERO_NLM) #define f_argsize(x) \ ((sizeof(x)+sizeof(int)-1) & ~(sizeof(int)-1)) typedef unsigned long f_va_list; #define f_va_start(ap, parmN) \ ((void)((ap) = (unsigned long)&(parmN) + f_argsize(parmN))) #define f_va_arg(ap, type) \ (*(type *)(((ap) += f_argsize(type)) - (f_argsize(type)))) #define f_va_end(ap) ((void)0) #else #include <stdarg.h> #define f_va_list va_list #define f_va_start va_start #define f_va_arg va_arg #define f_va_end va_end #endif // flmnovtbl keeps MS compilers from generating vtables for interfaces #ifdef _MSC_VER #define flmnovtbl __declspec( novtable) #else #define flmnovtbl #endif #define flminterface struct flmnovtbl /**************************************************************************** Desc: General errors ****************************************************************************/ /// \addtogroup retcodes /// @{ #define NE_FLM_OK 0 ///< 0 - Operation was successful. // Error codes that need to be the same as they were for FLAIM #define NE_FLM_BOF_HIT 0xC001 ///< 0xC001 - Beginning of results encountered. #define NE_FLM_EOF_HIT 0xC002 ///< 0xC002 - End of results encountered. #define NE_FLM_EXISTS 0xC004 ///< 0xC004 - Object already exists. #define NE_FLM_FAILURE 0xC005 ///< 0xC005 - Internal failure. #define NE_FLM_NOT_FOUND 0xC006 ///< 0xC006 - An object was not found. #define NE_FLM_BTREE_ERROR 0xC012 ///< 0xC012 - Corruption found in b-tree. #define NE_FLM_BTREE_FULL 0xC013 ///< 0xC013 - B-tree cannot grow beyond current size. #define NE_FLM_CONV_DEST_OVERFLOW 0xC01C ///< 0xC01C - Destination buffer not large enough to hold data. #define NE_FLM_CONV_ILLEGAL 0xC01D ///< 0xC01D - Attempt to convert between data types is an unsupported conversion. #define NE_FLM_CONV_NUM_OVERFLOW 0xC020 ///< 0xC020 - Numeric overflow (> upper bound) converting to numeric type. #define NE_FLM_DATA_ERROR 0xC022 ///< 0xC022 - Corruption found in b-tree. #define NE_FLM_ILLEGAL_OP 0xC026 ///< 0xC026 - Illegal operation #define NE_FLM_MEM 0xC037 ///< 0xC037 - Attempt to allocate memory failed. #define NE_FLM_NOT_UNIQUE 0xC03E ///< 0xC03E - Non-unique key. #define NE_FLM_SYNTAX 0xC045 ///< 0xC045 - Syntax error while parsing. #define NE_FLM_NOT_IMPLEMENTED 0xC05F ///< 0xC05F - Attempt was made to use a feature that is not implemented. #define NE_FLM_INVALID_PARM 0xC08B ///< 0xC08B - Invalid parameter passed into a function. // I/O Errors - Must be the same as they were for FLAIM. #define NE_FLM_IO_ACCESS_DENIED 0xC201 ///< 0xC201 - Access to file is denied.\ Caller is not allowed access to a file. #define NE_FLM_IO_BAD_FILE_HANDLE 0xC202 ///< 0xC202 - Bad file handle or file descriptor. #define NE_FLM_IO_COPY_ERR 0xC203 ///< 0xC203 - Error occurred while copying a file. #define NE_FLM_IO_DISK_FULL 0xC204 ///< 0xC204 - Disk full. #define NE_FLM_IO_END_OF_FILE 0xC205 ///< 0xC205 - End of file reached while reading from the file. #define NE_FLM_IO_OPEN_ERR 0xC206 ///< 0xC206 - Error while opening the file. #define NE_FLM_IO_SEEK_ERR 0xC207 ///< 0xC207 - Error occurred while positioning (seeking) within a file. #define NE_FLM_IO_DIRECTORY_ERR 0xC208 ///< 0xC208 - Error occurred while accessing or deleting a directory. #define NE_FLM_IO_PATH_NOT_FOUND 0xC209 ///< 0xC209 - File not found. #define NE_FLM_IO_TOO_MANY_OPEN_FILES 0xC20A ///< 0xC20A - Too many files open. #define NE_FLM_IO_PATH_TOO_LONG 0xC20B ///< 0xC20B - File name too long. #define NE_FLM_IO_NO_MORE_FILES 0xC20C ///< 0xC20C - No more files in directory. #define NE_FLM_IO_DELETING_FILE 0xC20D ///< 0xC20D - Error occurred while deleting a file. #define NE_FLM_IO_FILE_LOCK_ERR 0xC20E ///< 0xC20E - Error attempting to acquire a byte-range lock on a file. #define NE_FLM_IO_FILE_UNLOCK_ERR 0xC20F ///< 0xC20F - Error attempting to release a byte-range lock on a file. #define NE_FLM_IO_PATH_CREATE_FAILURE 0xC210 ///< 0xC210 - Error occurred while attempting to create a directory or sub-directory. #define NE_FLM_IO_RENAME_FAILURE 0xC211 ///< 0xC211 - Error occurred while renaming a file. #define NE_FLM_IO_INVALID_PASSWORD 0xC212 ///< 0xC212 - Invalid file password. #define NE_FLM_SETTING_UP_FOR_READ 0xC213 ///< 0xC213 - Error occurred while setting up to perform a file read operation. #define NE_FLM_SETTING_UP_FOR_WRITE 0xC214 ///< 0xC214 - Error occurred while setting up to perform a file write operation. #define NE_FLM_IO_CANNOT_REDUCE_PATH 0xC215 ///< 0xC215 - Cannot reduce file name into more components. #define NE_FLM_INITIALIZING_IO_SYSTEM 0xC216 ///< 0xC216 - Error occurred while setting up to access the file system. #define NE_FLM_FLUSHING_FILE 0xC217 ///< 0xC217 - Error occurred while flushing file data buffers to disk. #define NE_FLM_IO_INVALID_FILENAME 0xC218 ///< 0xC218 - Invalid file name. #define NE_FLM_IO_CONNECT_ERROR 0xC219 ///< 0xC219 - Error connecting to a remote network resource. #define NE_FLM_OPENING_FILE 0xC21A ///< 0xC21A - Unexpected error occurred while opening a file. #define NE_FLM_DIRECT_OPENING_FILE 0xC21B ///< 0xC21B - Unexpected error occurred while opening a file in direct access mode. #define NE_FLM_CREATING_FILE 0xC21C ///< 0xC21C - Unexpected error occurred while creating a file. #define NE_FLM_DIRECT_CREATING_FILE 0xC21D ///< 0xC21D - Unexpected error occurred while creating a file in direct access mode. #define NE_FLM_READING_FILE 0xC21E ///< 0xC21E - Unexpected error occurred while reading a file. #define NE_FLM_DIRECT_READING_FILE 0xC21F ///< 0xC21F - Unexpected error occurred while reading a file in direct access mode. #define NE_FLM_WRITING_FILE 0xC220 ///< 0xC220 - Unexpected error occurred while writing to a file. #define NE_FLM_DIRECT_WRITING_FILE 0xC221 ///< 0xC221 - Unexpected error occurred while writing a file in direct access mode. #define NE_FLM_POSITIONING_IN_FILE 0xC222 ///< 0xC222 - Unexpected error occurred while positioning within a file. #define NE_FLM_GETTING_FILE_SIZE 0xC223 ///< 0xC223 - Unexpected error occurred while getting a file's size. #define NE_FLM_TRUNCATING_FILE 0xC224 ///< 0xC224 - Unexpected error occurred while truncating a file. #define NE_FLM_PARSING_FILE_NAME 0xC225 ///< 0xC225 - Unexpected error occurred while parsing a file's name. #define NE_FLM_CLOSING_FILE 0xC226 ///< 0xC226 - Unexpected error occurred while closing a file. #define NE_FLM_GETTING_FILE_INFO 0xC227 ///< 0xC227 - Unexpected error occurred while getting information about a file. #define NE_FLM_EXPANDING_FILE 0xC228 ///< 0xC228 - Unexpected error occurred while expanding a file. #define NE_FLM_GETTING_FREE_BLOCKS 0xC229 ///< 0xC229 - Unexpected error getting free blocks from file system. #define NE_FLM_CHECKING_FILE_EXISTENCE 0xC22A ///< 0xC22A - Unexpected error occurred while checking to see if a file exists. #define NE_FLM_RENAMING_FILE 0xC22B ///< 0xC22B - Unexpected error occurred while renaming a file. #define NE_FLM_SETTING_FILE_INFO 0xC22C ///< 0xC22C - Unexpected error occurred while setting a file's information. #define NE_FLM_IO_PENDING 0xC22D ///< 0xC22D - I/O has not yet completed #define NE_FLM_ASYNC_FAILED 0xC22E ///< 0xC22E - An async I/O operation failed #define NE_FLM_MISALIGNED_IO 0xC22F ///< 0xC22F - Misaligned buffer or offset encountered during I/O request // Stream Errors - These are new #define NE_FLM_STREAM_DECOMPRESS_ERROR 0xC400 ///< 0xC400 - Error decompressing data stream. #define NE_FLM_STREAM_NOT_COMPRESSED 0xC401 ///< 0xC401 - Attempting to decompress a data stream that is not compressed. #define NE_FLM_STREAM_TOO_MANY_FILES 0xC402 ///< 0xC402 - Too many files in input stream. // Miscellaneous new toolkit errors #define NE_FLM_COULD_NOT_CREATE_SEMAPHORE 0xC500 ///< 0xC500 - Could not create a semaphore. #define NE_FLM_BAD_UTF8 0xC501 ///< 0xC501 - An invalid byte sequence was found in a UTF-8 string #define NE_FLM_ERROR_WAITING_ON_SEMAPHORE 0xC502 ///< 0xC502 - Error occurred while waiting on a sempahore. #define NE_FLM_BAD_SEN 0xC503 ///< 0xC503 - Invalid simple encoded number. #define NE_FLM_COULD_NOT_START_THREAD 0xC504 ///< 0xC504 - Problem starting a new thread. #define NE_FLM_BAD_BASE64_ENCODING 0xC505 ///< 0xC505 - Invalid base64 sequence encountered. #define NE_FLM_STREAM_EXISTS 0xC506 ///< 0xC506 - Stream file already exists. #define NE_FLM_MULTIPLE_MATCHES 0xC507 ///< 0xC507 - Multiple items matched but only one match was expected. #define NE_FLM_BTREE_KEY_SIZE 0xC508 ///< 0xC508 - Invalid b-tree key size. #define NE_FLM_BTREE_BAD_STATE 0xC509 ///< 0xC509 - B-tree operation cannot be completed. #define NE_FLM_COULD_NOT_CREATE_MUTEX 0xC50A ///< 0xC50A - Error occurred while creating or initializing a mutex. #define NE_FLM_BAD_PLATFORM_FORMAT 0xC50B ///< 0xC50B - In-memory alignment of disk structures is incorrect #define NE_FLM_LOCK_REQ_TIMEOUT 0xC50C ///< 0xC50C - Timeout while waiting for a lock object #define NE_FLM_WAIT_TIMEOUT 0xC50D ///< 0xC50D - Timeout while waiting on a semaphore, condition variable, or reader/writer lock #define NE_FLM_BAD_HTTP_HEADER 0xC50E ///< 0xC50E - Invalid HTTP header format // Reserved range for application error codes #define NE_FLM_FIRST_APP_ERR 0xC600 ///< 0xC600 - First application-defined error code #define NE_FLM_LAST_APP_ERR 0xC6FF ///< 0xC6FF - Last application-defined error code // Network Errors - Must be the same as they were for FLAIM #define NE_FLM_NOIP_ADDR 0xC900 ///< 0xC900 - IP address not found #define NE_FLM_SOCKET_FAIL 0xC901 ///< 0xC901 - IP socket failure #define NE_FLM_CONNECT_FAIL 0xC902 ///< 0xC902 - TCP/IP connection failure #define NE_FLM_BIND_FAIL 0xC903 ///< 0xC903 - The TCP/IP services on your system may not be configured or installed. #define NE_FLM_LISTEN_FAIL 0xC904 ///< 0xC904 - TCP/IP listen failed #define NE_FLM_ACCEPT_FAIL 0xC905 ///< 0xC905 - TCP/IP accept failed #define NE_FLM_SELECT_ERR 0xC906 ///< 0xC906 - TCP/IP select failed #define NE_FLM_SOCKET_SET_OPT_FAIL 0xC907 ///< 0xC907 - TCP/IP socket operation failed #define NE_FLM_SOCKET_DISCONNECT 0xC908 ///< 0xC908 - TCP/IP disconnected #define NE_FLM_SOCKET_READ_FAIL 0xC909 ///< 0xC909 - TCP/IP read failed #define NE_FLM_SOCKET_WRITE_FAIL 0xC90A ///< 0xC90A - TCP/IP write failed #define NE_FLM_SOCKET_READ_TIMEOUT 0xC90B ///< 0xC90B - TCP/IP read timeout #define NE_FLM_SOCKET_WRITE_TIMEOUT 0xC90C ///< 0xC90C - TCP/IP write timeout #define NE_FLM_SOCKET_ALREADY_CLOSED 0xC90D ///< 0xC90D - Connection already closed /// @} /**************************************************************************** Desc: HTTP status codes ****************************************************************************/ #define FLM_HTTP_STATUS_CONTINUE 100 #define FLM_HTTP_STATUS_SWITCHING_PROTOCOLS 101 #define FLM_HTTP_STATUS_PROCESSING 102 #define FLM_HTTP_STATUS_OK 200 #define FLM_HTTP_STATUS_CREATED 201 #define FLM_HTTP_STATUS_ACCEPTED 202 #define FLM_HTTP_STATUS_NON_AUTH_INFO 203 #define FLM_HTTP_STATUS_NO_CONTENT 204 #define FLM_HTTP_STATUS_RESET_CONTENT 205 #define FLM_HTTP_STATUS_PARTIAL_CONTENT 206 #define FLM_HTTP_STATUS_MULTI_STATUS 207 #define FLM_HTTP_STATUS_MULTIPLE_CHOICES 300 #define FLM_HTTP_STATUS_MOVED_PERMANENTLY 301 #define FLM_HTTP_STATUS_FOUND 302 #define FLM_HTTP_STATUS_SEE_OTHER 303 #define FLM_HTTP_STATUS_NOT_MODIFIED 304 #define FLM_HTTP_STATUS_USE_PROXY 305 #define FLM_HTTP_STATUS_TEMPORARY_REDIRECT 307 #define FLM_HTTP_STATUS_BAD_REQUEST 400 #define FLM_HTTP_STATUS_UNAUTHORIZED 401 #define FLM_HTTP_STATUS_PAYMENT_REQUIRED 402 #define FLM_HTTP_STATUS_FORBIDDEN 403 #define FLM_HTTP_STATUS_NOT_FOUND 404 #define FLM_HTTP_STATUS_METHOD_NOT_ALLOWED 405 #define FLM_HTTP_STATUS_NOT_ACCEPTABLE 406 #define FLM_HTTP_STATUS_PROXY_AUTH_REQUIRED 407 #define FLM_HTTP_STATUS_REQUEST_TIMEOUT 408 #define FLM_HTTP_STATUS_CONFLICT 409 #define FLM_HTTP_STATUS_GONE 410 #define FLM_HTTP_STATUS_LENGTH_REQUIRED 411 #define FLM_HTTP_STATUS_PRECONDITION_FAILED 412 #define FLM_HTTP_STATUS_ENTITY_TOO_LARGE 413 #define FLM_HTTP_STATUS_URI_TOO_LONG 414 #define FLM_HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE 415 #define FLM_HTTP_STATUS_RANGE_NOT_SATISFIABLE 416 #define FLM_HTTP_STATUS_EXPECTATION_FAILED 417 #define FLM_HTTP_STATUS_INTERNAL_SERVER_ERROR 500 #define FLM_HTTP_STATUS_NOT_IMPLEMENTED 501 #define FLM_HTTP_STATUS_BAD_GATEWAY 502 #define FLM_HTTP_STATUS_SERVICE_UNAVAILABLE 503 #define FLM_HTTP_STATUS_GATEWAY_TIMEOUT 504 #define FLM_HTTP_STATUS_VERSION_NOT_SUPPORTED 505 FTKXPC const char * FTKAPI FlmGetHTTPStatusString( FLMUINT uiStatusCode); /**************************************************************************** Desc: Return code functions and macros ****************************************************************************/ #ifndef RC_OK #define RC_OK( rc) ((rc) == NE_FLM_OK) #endif #ifndef RC_BAD #define RC_BAD( rc) ((rc) != NE_FLM_OK) #endif FTKXPC RCODE FTKAPI f_mapPlatformError( FLMINT iError, RCODE defaultRc); /**************************************************************************** Desc: Forward References ****************************************************************************/ flminterface IF_DirHdl; flminterface IF_FileHdl; flminterface IF_FileSystem; flminterface IF_FileHdlCache; flminterface IF_PrintfClient; flminterface IF_IStream; flminterface IF_PosIStream; flminterface IF_ResultSet; flminterface IF_ThreadInfo; flminterface IF_OStream; flminterface IF_IOStream; flminterface IF_TCPListener; flminterface IF_SSLIOStream; flminterface IF_TCPIOStream; flminterface IF_LogMessageClient; flminterface IF_Thread; flminterface IF_IOBuffer; flminterface IF_AsyncClient; flminterface IF_Block; class F_Pool; class F_DynaBuf; class F_ListItem; class F_ListManager; class F_Arg; class F_TCPIOStream; /**************************************************************************** Desc: Cross-platform definitions ****************************************************************************/ #ifndef NULL #define NULL 0 #endif #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif #define f_offsetof(s,m) \ (((FLMSIZET)&((s *)1)->m) - 1) /**************************************************************************** Desc: Language constants IMPORTANT NOTE: If languages are added or changed, the corresponding definitions in java and C# must also be updated. ****************************************************************************/ /// \addtogroup flm_languages /// @{ #define FLM_US_LANG 0 ///< English, United States #define FLM_AF_LANG 1 ///< Afrikaans #define FLM_AR_LANG 2 ///< Arabic #define FLM_CA_LANG 3 ///< Catalan #define FLM_HR_LANG 4 ///< Croatian #define FLM_CZ_LANG 5 ///< Czech #define FLM_DK_LANG 6 ///< Danish #define FLM_NL_LANG 7 ///< Dutch #define FLM_OZ_LANG 8 ///< English, Australia #define FLM_CE_LANG 9 ///< English, Canada #define FLM_UK_LANG 10 ///< English, United Kingdom #define FLM_FA_LANG 11 ///< Farsi #define FLM_SU_LANG 12 ///< Finnish #define FLM_CF_LANG 13 ///< French, Canada #define FLM_FR_LANG 14 ///< French, France #define FLM_GA_LANG 15 ///< Galician #define FLM_DE_LANG 16 ///< German, Germany #define FLM_SD_LANG 17 ///< German, Switzerland #define FLM_GR_LANG 18 ///< Greek #define FLM_HE_LANG 19 ///< Hebrew #define FLM_HU_LANG 20 ///< Hungarian #define FLM_IS_LANG 21 ///< Icelandic #define FLM_IT_LANG 22 ///< Italian #define FLM_NO_LANG 23 ///< Norwegian #define FLM_PL_LANG 24 ///< Polish #define FLM_BR_LANG 25 ///< Portuguese, Brazil #define FLM_PO_LANG 26 ///< Portuguese, Portugal #define FLM_RU_LANG 27 ///< Russian #define FLM_SL_LANG 28 ///< Slovak #define FLM_ES_LANG 29 ///< Spanish #define FLM_SV_LANG 30 ///< Swedish #define FLM_YK_LANG 31 ///< Ukrainian #define FLM_UR_LANG 32 ///< Urdu #define FLM_TK_LANG 33 ///< Turkey #define FLM_JP_LANG 34 ///< Japanese #define FLM_KO_LANG 35 ///< Korean #define FLM_CT_LANG 36 ///< Chinese-Traditional #define FLM_CS_LANG 37 ///< Chinese-Simplified #define FLM_LA_LANG 38 ///< another Asian language /// @} #define FLM_LAST_LANG (FLM_LA_LANG + 1) #define FLM_FIRST_DBCS_LANG (FLM_JP_LANG) #define FLM_LAST_DBCS_LANG (FLM_LA_LANG) /**************************************************************************** Desc: Collation flags and constants ****************************************************************************/ #define F_HAD_SUB_COLLATION 0x01 // Set if had sub-collating values-diacritics #define F_HAD_LOWER_CASE 0x02 // Set if you hit a lowercase character #define F_COLL_FIRST_SUBSTRING 0x03 // First substring marker #define F_COLL_MARKER 0x04 // Marks place of sub-collation #define F_SC_LOWER 0x00 // Only lowercase characters exist #define F_SC_MIXED 0x01 // Lower/uppercase flags follow in next byte #define F_SC_UPPER 0x02 // Only upper characters exist #define F_SC_SUB_COL 0x03 // Sub-collation follows (diacritics|extCh) #define F_COLL_TRUNCATED 0x0C // This key piece has been truncated from original #define F_MAX_COL_OPCODE F_COLL_TRUNCATED #define F_CHSASCI 0 // ASCII #define F_CHSMUL1 1 // Multinational 1 #define F_CHSMUL2 2 // Multinational 2 #define F_CHSBOXD 3 // Box drawing #define F_CHSSYM1 4 // Typographic Symbols #define F_CHSSYM2 5 // Iconic Symbols #define F_CHSMATH 6 // Math #define F_CHMATHX 7 // Math Extension #define F_CHSGREK 8 // Greek #define F_CHSHEB 9 // Hebrew #define F_CHSCYR 10 // Cyrillic #define F_CHSKANA 11 // Japanese Kana #define F_CHSUSER 12 // User-defined #define F_CHSARB1 13 // Arabic #define F_CHSARB2 14 // Arabic script #define F_NCHSETS 15 // # of character sets (excluding asian) #define F_ACHSETS 0x0E0 // maximum character set value - asian #define F_ACHSMIN 0x024 // minimum character set value - asian #define F_ACHCMAX 0x0FE // maxmimum character value in asian sets /**************************************************************************** Desc: Diacritics ****************************************************************************/ #define F_GRAVE 0 #define F_CENTERD 1 #define F_TILDE 2 #define F_CIRCUM 3 #define F_CROSSB 4 #define F_SLASH 5 #define F_ACUTE 6 #define F_UMLAUT 7 #define F_MACRON 8 #define F_APOSAB 9 #define F_APOSBES 10 #define F_APOSBA 11 #define F_RING 14 #define F_DOTA 15 #define F_DACUTE 16 #define F_CEDILLA 17 #define F_OGONEK 18 #define F_CARON 19 #define F_STROKE 20 #define F_BREVE 22 #define F_DOTLESI 239 #define F_DOTLESJ 25 #define F_GACUTE 83 // greek acute #define F_GDIA 84 // greek diaeresis #define F_GACTDIA 85 // acute diaeresis #define F_GGRVDIA 86 // grave diaeresis #define F_GGRAVE 87 // greek grave #define F_GCIRCM 88 // greek circumflex #define F_GSMOOTH 89 // smooth breathing #define F_GROUGH 90 // rough breathing #define F_GIOTA 91 // iota subscript #define F_GSMACT 92 // smooth breathing acute #define F_GRGACT 93 // rough breathing acute #define F_GSMGRV 94 // smooth breathing grave #define F_GRGGRV 95 // rough breathing grave #define F_GSMCIR 96 // smooth breathing circumflex #define F_GRGCIR 97 // rough breathing circumflex #define F_GACTIO 98 // acute iota #define F_GGRVIO 99 // grave iota #define F_GCIRIO 100 // circumflex iota #define F_GSMIO 101 // smooth iota #define F_GRGIO 102 // rough iota #define F_GSMAIO 103 // smooth acute iota #define F_GRGAIO 104 // rough acute iota #define F_GSMGVIO 105 // smooth grave iota #define F_GRGGVIO 106 // rough grave iota #define F_GSMCIO 107 // smooth circumflex iota #define F_GRGCIO 108 // rough circumflex iota #define F_GHPRIME 81 // high prime #define F_GLPRIME 82 // low prime #define F_RACUTE 200 // russian acute #define F_RGRAVE 201 // russian grave #define F_RRTDESC 204 // russian right descender #define F_ROGONEK 205 // russian ogonek #define F_RMACRON 206 // russian macron /**************************************************************************** Desc: I/O Flags ****************************************************************************/ #define FLM_IO_CURRENT_POS FLM_MAX_UINT64 #define FLM_IO_RDONLY 0x0001 #define FLM_IO_RDWR 0x0002 #define FLM_IO_EXCL 0x0004 #define FLM_IO_CREATE_DIR 0x0008 #define FLM_IO_SH_DENYRW 0x0010 #define FLM_IO_SH_DENYWR 0x0020 #define FLM_IO_SH_DENYNONE 0x0040 #define FLM_IO_DIRECT 0x0080 #define FLM_IO_DELETE_ON_RELEASE 0x0100 #define FLM_IO_NO_MISALIGNED 0x0200 // File Positioning Definitions #define FLM_IO_SEEK_SET 0 // Beginning of File #define FLM_IO_SEEK_CUR 1 // Current File Pointer Position #define FLM_IO_SEEK_END 2 // End of File // Maximum file size #define FLM_MAXIMUM_FILE_SIZE 0xFFFC0000 // Maximum SEN (compressed number) length #define FLM_MAX_SEN_LEN 9 // Retrieval flags #define FLM_INCL 0x0010 #define FLM_EXCL 0x0020 #define FLM_EXACT 0x0040 #define FLM_KEY_EXACT 0x0080 #define FLM_FIRST 0x0100 #define FLM_LAST 0x0200 /**************************************************************************** Desc: Comparison flags for strings IMPORTANT NOTE: If changes are made to these, corresponding changes need to be made in the java and C# code where they are defined. ****************************************************************************/ /// \addtogroup compare_rules /// @{ #define FLM_COMP_CASE_INSENSITIVE 0x0001 ///< 0x0001 = Do case sensitive comparison. #define FLM_COMP_COMPRESS_WHITESPACE 0x0002 ///< 0x0002 = Compare multiple whitespace characters as a single space. #define FLM_COMP_NO_WHITESPACE 0x0004 ///< 0x0004 = Ignore all whitespace during comparison. #define FLM_COMP_NO_UNDERSCORES 0x0008 ///< 0x0008 = Ignore all underscore characters during comparison. #define FLM_COMP_NO_DASHES 0x0010 ///< 0x0010 = Ignore all dash characters during comparison. #define FLM_COMP_WHITESPACE_AS_SPACE 0x0020 ///< 0x0020 = Treat newlines and tabs as spaces during comparison. #define FLM_COMP_IGNORE_LEADING_SPACE 0x0040 ///< 0x0040 = Ignore leading space characters during comparison. #define FLM_COMP_IGNORE_TRAILING_SPACE 0x0080 ///< 0x0080 = Ignore trailing space characters during comparison. #define FLM_COMP_WILD 0x0100 /// @} /**************************************************************************** Desc: Colors ****************************************************************************/ /// Colors used for logging messages typedef enum { FLM_BLACK = 0, ///< 0 = Black FLM_BLUE, ///< 1 = Blue FLM_GREEN, ///< 2 = Green FLM_CYAN, ///< 3 = Cyan FLM_RED, ///< 4 = Red FLM_MAGENTA, ///< 5 = Magenta FLM_BROWN, ///< 6 = Brown FLM_LIGHTGRAY, ///< 7 = Light Gray FLM_DARKGRAY, ///< 8 = Dark Gray FLM_LIGHTBLUE, ///< 9 = Light Blue FLM_LIGHTGREEN, ///< 10 = Light Green FLM_LIGHTCYAN, ///< 11 = Light Cyan FLM_LIGHTRED, ///< 12 = Light Red FLM_LIGHTMAGENTA, ///< 13 = Light Magenta FLM_YELLOW, ///< 14 = Light Yellow FLM_WHITE, ///< 15 = White FLM_NUM_COLORS, FLM_CURRENT_COLOR } eColorType; #define F_FOREBLACK "%0F" #define F_FOREBLUE "%1F" #define F_FOREGREEN "%2F" #define F_FORECYAN "%3F" #define F_FORERED "%4F" #define F_FOREMAGENTA "%5F" #define F_FOREBROWN "%6F" #define F_FORELIGHTGRAY "%7F" #define F_FOREDARKGRAY "%8F" #define F_FORELIGHTBLUE "%9F" #define F_FORELIGHTGREEN "%10F" #define F_FORELIGHTCYAN "%11F" #define F_FORELIGHTRED "%12F" #define F_FORELIGHTMAGENTA "%13F" #define F_FOREYELLOW "%14F" #define F_FOREWHITE "%15F" #define F_BACKBLACK "%0B" #define F_BACKBLUE "%1B" #define F_BACKGREEN "%2B" #define F_BACKCYAN "%3B" #define F_BACKRED "%4B" #define F_BACKMAGENTA "%5B" #define F_BACKBROWN "%6B" #define F_BACKLIGHTGRAY "%7B" #define F_BACKDARKGRAY "%8B" #define F_BACKLIGHTBLUE "%9B" #define F_BACKLIGHTGREEN "%10B" #define F_BACKLIGHTCYAN "%11B" #define F_BACKLIGHTRED "%12B" #define F_BACKLIGHTMAGENTA "%13B" #define F_BACKYELLOW "%14B" #define F_BACKWHITE "%15B" #define F_PUSH_FORECOLOR "%+F" #define F_POP_FORECOLOR "%-F" #define F_PUSH_BACKCOLOR "%+B" #define F_POP_BACKCOLOR "%-B" #define F_PUSHCOLOR F_PUSH_FORECOLOR F_PUSH_BACKCOLOR #define F_POPCOLOR F_POP_FORECOLOR F_POP_BACKCOLOR #ifdef FLM_PACK_STRUCTS #pragma pack(push, 1) #endif // IMPORTANT NOTE: This structure needs to be kept in sync with corresponding // structures and classes in java and C#. /**************************************************************************** /// Structure for reporting slab usage information in cache. ****************************************************************************/ typedef struct { FLMUINT64 ui64Slabs; ///< Total slabs currently allocated. FLMUINT64 ui64SlabBytes; ///< Total bytes currently allocated in slabs. FLMUINT64 ui64AllocatedCells; ///< Total cells allocated within slabs. FLMUINT64 ui64FreeCells; ///< Total cells that are free within slabs. } FLM_SLAB_USAGE; /**************************************************************************** /// Structure returned from FlmGetThreadInfo() - contains information about a thread. ****************************************************************************/ typedef struct { FLMUINT uiThreadId; ///< Operating system thread ID. FLMUINT uiThreadGroup; ///< Thread group this thread belongs to. FLMUINT uiAppId; ///< Application ID that was assigned to the thread when it was started. FLMUINT uiStartTime; ///< Time the thread was started. char * pszThreadName; ///< Name of the thread. char * pszThreadStatus; ///< String indicating the last action the thread reported it was performing. } F_THREAD_INFO; typedef enum { FLM_THREAD_STATUS_UNKNOWN = 0, FLM_THREAD_STATUS_INITIALIZING, FLM_THREAD_STATUS_RUNNING, FLM_THREAD_STATUS_SLEEPING, FLM_THREAD_STATUS_TERMINATING } eThreadStatus; #define F_THREAD_MIN_STACK_SIZE (16 * 1024) #define F_THREAD_DEFAULT_STACK_SIZE (16 * 1024) #define F_DEFAULT_THREAD_GROUP 0 #define F_INVALID_THREAD_GROUP 0xFFFFFFFF typedef RCODE (FTKAPI * F_THREAD_FUNC)(IF_Thread *); /**************************************************************************** Desc: Startup and shutdown ****************************************************************************/ FTKXPC RCODE FTKAPI ftkStartup( void); FTKXPC void FTKAPI ftkShutdown( void); /**************************************************************************** Desc: Global data ****************************************************************************/ FTKXPC FLMUINT16 * gv_pui16USCollationTable; /**************************************************************************** /// This is a pure virtual base class that other classes inherit from.\ It /// provides methods for reference counting (AddRef, Release). ****************************************************************************/ flminterface FTKEXP IF_Object { virtual ~IF_Object() { } virtual FLMINT FTKAPI AddRef( void) = 0; virtual FLMINT FTKAPI Release( void) = 0; virtual FLMINT FTKAPI getRefCount( void) = 0; }; /**************************************************************************** /// This is the base class that all other classes inherit from.\ It /// provides methods for reference counting (AddRef, Release) as well as /// methods for overloading new and delete operators. ****************************************************************************/ class FTKEXP F_Object : public IF_Object { public: F_Object() { m_refCnt = 1; } virtual ~F_Object() { } /// Increment the reference count for this object. /// The reference count is the number of pointers that are referencing this object. /// Return value is the incremented reference count. virtual FLMINT FTKAPI AddRef( void); /// Decrement the reference count for this object. /// The reference count is the number of pointers that are referencing this object. /// Return value is the decremented reference count. If the reference count goes to /// zero, the object will be deleted. virtual FLMINT FTKAPI Release( void); /// Return the current reference count on the object. virtual FLMINT FTKAPI getRefCount( void); /// Overloaded new operator for objects of this class. void * FTKAPI operator new( FLMSIZET uiSize, ///< Number of bytes to allocate - should be sizeof( ThisClass). const char * pszFile, ///< Name of source file where this allocation is made. int iLine) ///< Line number in source file where this allocation request is made. #ifndef FLM_WATCOM_NLM throw() #endif ; /// Overloaded new operator for objects of this class. void * FTKAPI operator new( FLMSIZET uiSize) ///< Number of bytes to allocate - should be sizeof( ThisClass). #ifndef FLM_WATCOM_NLM throw() #endif ; /// Overloaded new operator (array) for objects of this class (with source file and line number). /// This new operator is called when an array of objects of this class are allocated. /// This new operator passes in the current file and line number. This information is /// useful in tracking memory allocations to determine where memory leaks are coming from. void * FTKAPI operator new[]( FLMSIZET uiSize, ///< Number of bytes to allocate - should be sizeof( ThisClass). const char * pszFile, ///< Name of source file where this allocation is made. int iLine) ///< Line number in source file where this allocation request is made. #ifndef FLM_WATCOM_NLM throw() #endif ; /// Overloaded new operator (array) for objects of this class. /// This new operator is called when an array of objects of this class are allocated. void * FTKAPI operator new[]( FLMSIZET uiSize) ///< Number of bytes to allocate - should be sizeof( ThisClass). #ifndef FLM_WATCOM_NLM throw() #endif ; /// Overloaded delete operator for objects of this class. void FTKAPI operator delete( void * ptr); ///< Pointer to object being freed. /// Overloaded delete operator (array) for objects of this class. void FTKAPI operator delete[]( void * ptr); ///< Pointer to array of objects being freed. #ifndef FLM_WATCOM_NLM /// Overloaded delete operator for objects of this class (with source file and line number). /// This delete operator passes in the current file and line number. This information is /// useful in tracking memory allocations to determine where memory leaks are coming from. void FTKAPI operator delete( void * ptr, ///< Pointer to object being freed. const char * file, ///< Name of source file where this delete occurs. int line); ///< Line number in source file where this delete occurs. #endif #ifndef FLM_WATCOM_NLM /// Overloaded delete operator (array) for objects of this class (with source file and line number). /// This delete operator is called when an array of objects of this class is freed. /// This delete operator passes in the current file and line number. This information is /// useful in tracking memory allocations to determine where memory leaks are coming from. void FTKAPI operator delete[]( void * ptr, ///< Pointer to object being freed. const char * file, ///< Name of source file where this delete occurs. int line); ///< Line number in source file where this delete occurs. #endif protected: FLMATOMIC m_refCnt; }; /**************************************************************************** Desc: Internal base class ****************************************************************************/ class FTKEXP F_OSBase { public: F_OSBase() { m_refCnt = 1; } virtual ~F_OSBase() { } void * operator new( FLMSIZET uiSize, const char * pszFile, int iLine) #ifndef FLM_WATCOM_NLM throw() #endif ; void * operator new[]( FLMSIZET uiSize, const char * pszFile, int iLine) #ifndef FLM_WATCOM_NLM throw() #endif ; void operator delete( void * ptr); void operator delete[]( void * ptr); #ifndef FLM_WATCOM_NLM void operator delete( void * ptr, const char * file, int line); #endif #ifndef FLM_WATCOM_NLM void operator delete[]( void * ptr, const char * file, int line); #endif virtual FINLINE FLMINT FTKAPI AddRef( void) { return( ++m_refCnt); } virtual FINLINE FLMINT FTKAPI Release( void) { FLMINT iRefCnt = --m_refCnt; if( !iRefCnt) { delete this; } return( iRefCnt); } virtual FINLINE FLMINT FTKAPI getRefCount( void) { return( m_refCnt); } protected: FLMATOMIC m_refCnt; }; /**************************************************************************** Desc: Errors ****************************************************************************/ #ifdef FLM_DEBUG FTKXPC RCODE FTKAPI f_makeErr( RCODE rc, const char * pszFile, int iLine, FLMBOOL bAssert); FTKXPC FLMINT FTKAPI f_enterDebugger( const char * pszFile, int iLine); #define RC_SET( rc) \ f_makeErr( rc, __FILE__, __LINE__, FALSE) #define RC_SET_AND_ASSERT( rc) \ f_makeErr( rc, __FILE__, __LINE__, TRUE) #define RC_UNEXPECTED_ASSERT( rc) \ f_makeErr( rc, __FILE__, __LINE__, TRUE) #define f_assert( c) \ (void)((c) ? 0 : f_enterDebugger( __FILE__, __LINE__)) #define flmAssert( c) \ f_assert( c) #else #define RC_SET( rc) (rc) #define RC_SET_AND_ASSERT( rc) (rc) #define RC_UNEXPECTED_ASSERT( rc) #define f_assert(c) #define flmAssert(c) #endif /**************************************************************************** Desc: Memory ****************************************************************************/ FTKXPC RCODE FTKAPI f_allocImp( FLMUINT uiSize, void ** ppvPtr, FLMBOOL bFromNewOp, const char * pszFile, int iLine); #define f_alloc(s,p) \ f_allocImp( (s), (void **)(p), FALSE, __FILE__, __LINE__) FTKXPC RCODE FTKAPI f_callocImp( FLMUINT uiSize, void ** ppvPtr, const char * pszFile, int iLine); #define f_calloc(s,p) \ f_callocImp( (s), (void **)(p), __FILE__, __LINE__) FTKXPC RCODE FTKAPI f_reallocImp( FLMUINT uiSize, void ** ppvPtr, const char * pszFile, int iLine); #define f_realloc(s,p) \ f_reallocImp( (s), (void **)(p), __FILE__, __LINE__) FTKXPC RCODE FTKAPI f_recallocImp( FLMUINT uiSize, void ** ppvPtr, const char * pszFile, int iLine); #define f_recalloc(s,p) \ f_recallocImp( (s), (void **)(p), __FILE__, __LINE__) #define f_new \ new( __FILE__, __LINE__) FTKXPC void FTKAPI f_freeImp( void ** ppvPtr, FLMBOOL bFromDelOp); #define f_free(p) \ f_freeImp( (void **)(p), FALSE) FTKXPC void f_resetStackInfoImp( void * pvPtr, const char * pszFileName, int iLineNumber); #define f_resetStackInfo(p) \ f_resetStackInfoImp( (p), __FILE__, __LINE__) FTKXPC FLMUINT f_msize( void * pvPtr); FTKXPC RCODE FTKAPI f_allocAlignedBufferImp( FLMUINT uiMinSize, void ** ppvAlloc); #define f_allocAlignedBuffer(s,p) \ f_allocAlignedBufferImp( (s), (void **)(p)) FTKXPC void FTKAPI f_freeAlignedBufferImp( void ** ppvAlloc); #define f_freeAlignedBuffer(p) \ f_freeAlignedBufferImp( (void **)(p)) FTKXPC RCODE FTKAPI f_getMemoryInfo( FLMUINT64 * pui64TotalPhysMem, FLMUINT64 * pui64AvailPhysMem); FTKXPC FLMBOOL FTKAPI f_canGetMemoryInfo( void); /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_ThreadInfo : public F_Object { virtual FLMUINT FTKAPI getNumThreads( void) = 0; virtual void FTKAPI getThreadInfo( FLMUINT uiThreadNum, FLMUINT * puiThreadId, FLMUINT * puiThreadGroup, FLMUINT * puiAppId, FLMUINT * puiStartTime, const char ** ppszThreadName, const char ** ppszThreadStatus) = 0; }; FTKXPC RCODE FTKAPI FlmGetThreadInfo( IF_ThreadInfo ** ppThreadInfo); /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_IStream : virtual public F_Object { virtual RCODE FTKAPI read( void * pvBuffer, FLMUINT uiBytesToRead, FLMUINT * puiBytesRead = NULL) = 0; virtual RCODE FTKAPI closeStream( void) = 0; }; /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_PosIStream : public IF_IStream { virtual FLMUINT64 FTKAPI totalSize( void) = 0; virtual FLMUINT64 FTKAPI remainingSize( void) = 0; virtual RCODE FTKAPI positionTo( FLMUINT64 ui64Position) = 0; virtual FLMUINT64 FTKAPI getCurrPosition( void) = 0; }; /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_BufferIStream : public IF_PosIStream { virtual RCODE FTKAPI openStream( const char * pucBuffer, FLMUINT uiLength, char ** ppucAllocatedBuffer = NULL) = 0; virtual FLMUINT64 FTKAPI totalSize( void) = 0; virtual FLMUINT64 FTKAPI remainingSize( void) = 0; virtual RCODE FTKAPI closeStream( void) = 0; virtual RCODE FTKAPI positionTo( FLMUINT64 ui64Position) = 0; virtual FLMUINT64 FTKAPI getCurrPosition( void) = 0; virtual void FTKAPI truncateStream( FLMUINT64 ui64Offset = 0) = 0; virtual RCODE FTKAPI read( void * pvBuffer, FLMUINT uiBytesToRead, FLMUINT * puiBytesRead) = 0; virtual const FLMBYTE * FTKAPI getBufferAtCurrentOffset( void) = 0; }; FTKXPC RCODE FTKAPI FlmAllocBufferIStream( IF_BufferIStream ** ppIStream); FTKXPC RCODE FTKAPI FlmOpenBufferIStream( const char * pucBuffer, FLMUINT uiLength, IF_PosIStream ** ppIStream); FTKXPC RCODE FTKAPI FlmOpenBase64EncoderIStream( IF_IStream * pSourceIStream, FLMBOOL bLineBreaks, IF_IStream ** ppIStream); FTKXPC RCODE FTKAPI FlmOpenBase64DecoderIStream( IF_IStream * pSourceIStream, IF_IStream ** ppIStream); FTKXPC RCODE FTKAPI FlmOpenFileIStream( const char * pszPath, IF_PosIStream ** ppIStream); FTKXPC RCODE FTKAPI FlmOpenMultiFileIStream( const char * pszDirectory, const char * pszBaseName, IF_IStream ** ppIStream); FTKXPC RCODE FTKAPI FlmOpenBufferedIStream( IF_IStream * pSourceIStream, FLMUINT uiBufferSize, IF_IStream ** ppIStream); FTKXPC RCODE FTKAPI FlmOpenUncompressingIStream( IF_IStream * pIStream, IF_IStream ** ppIStream); FTKXPC RCODE FTKAPI FlmOpenFileOStream( const char * pszFileName, FLMBOOL bTruncateIfExists, IF_OStream ** ppOStream); FTKXPC RCODE FTKAPI FlmOpenMultiFileOStream( const char * pszDirectory, const char * pszBaseName, FLMUINT uiMaxFileSize, FLMBOOL bOkToOverwrite, IF_OStream ** ppStream); FTKXPC RCODE FTKAPI FlmOpenBufferedOStream( IF_OStream * pOStream, FLMUINT uiBufferSize, IF_OStream ** ppOStream); FTKXPC RCODE FTKAPI FlmOpenCompressingOStream( IF_OStream * pOStream, IF_OStream ** ppOStream); FTKXPC RCODE FTKAPI FlmAllocSSLIOStream( IF_IOStream ** ppIOStream); FTKXPC RCODE FTKAPI FlmOpenSSLIOStream( const char * pszHost, FLMUINT uiPort, FLMUINT uiFlags, IF_IOStream ** ppIOStream); FTKXPC RCODE FTKAPI FlmOpenTCPIOStream( const char * pszHost, FLMUINT uiPort, FLMUINT uiFlags, FLMUINT uiConnectTimeout, IF_IOStream ** ppIOStream); FTKXPC RCODE FTKAPI FlmOpenTCPListener( FLMBYTE * pucBindAddr, FLMUINT uiBindPort, IF_TCPListener ** ppListener); FTKXPC RCODE FTKAPI FlmRemoveMultiFileStream( const char * pszDirectory, const char * pszBaseName); FTKXPC RCODE FTKAPI FlmWriteToOStream( IF_IStream * pIStream, IF_OStream * pOStream); FTKXPC RCODE FTKAPI FlmReadFully( IF_IStream * pIStream, F_DynaBuf * pDynaBuf); FTKXPC RCODE FTKAPI FlmReadLine( IF_IStream * pIStream, F_DynaBuf * pBuffer); FTKXPC void FTKAPI f_streamPrintf( IF_OStream * pStream, const char * pszFormatStr, ...); /**************************************************************************** Desc: ****************************************************************************/ typedef struct { FLMUINT64 ui64Position; FLMUNICODE uNextChar; } F_CollStreamPos; flminterface FTKEXP IF_CollIStream : public IF_PosIStream { virtual RCODE FTKAPI openStream( IF_PosIStream * pIStream, FLMBOOL bUnicodeStream, FLMUINT uiLanguage, FLMUINT uiCompareRules, FLMBOOL bMayHaveWildCards) = 0; virtual RCODE FTKAPI closeStream( void) = 0; virtual RCODE FTKAPI read( void * pvBuffer, FLMUINT uiBytesToRead, FLMUINT * puiBytesRead) = 0; virtual RCODE FTKAPI read( FLMBOOL bAllowTwoIntoOne, FLMUNICODE * puChar, FLMBOOL * pbCharIsWild, FLMUINT16 * pui16Col, FLMUINT16 * pui16SubCol, FLMBYTE * pucCase) = 0; virtual FLMUINT64 FTKAPI totalSize( void) = 0; virtual FLMUINT64 FTKAPI remainingSize( void) = 0; virtual RCODE FTKAPI positionTo( FLMUINT64 ui64Position) = 0; virtual FLMUINT64 FTKAPI getCurrPosition( void) = 0; virtual RCODE FTKAPI positionTo( F_CollStreamPos * pPos) = 0; virtual void FTKAPI getCurrPosition( F_CollStreamPos * pPos) = 0; }; /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_OStream : virtual public F_Object { virtual RCODE FTKAPI write( const void * pvBuffer, FLMUINT uiBytesToWrite, FLMUINT * puiBytesWritten = NULL) = 0; virtual RCODE FTKAPI closeStream( void) = 0; }; /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_IOStream : public IF_IStream, public IF_OStream { #if defined( FLM_WIN) && _MSC_VER < 1300 using IF_IStream::operator delete; #endif }; /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_TCPListener : public F_Object { virtual RCODE FTKAPI connectClient( IF_TCPIOStream ** ppClientStream, FLMUINT uiTimeout = 0) = 0; }; /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_TCPIOStream : public IF_IOStream { virtual RCODE FTKAPI read( void * pvBuffer, FLMUINT uiBytesToRead, FLMUINT * puiBytesRead) = 0; virtual RCODE FTKAPI write( const void * pvBuffer, FLMUINT uiBytesToWrite, FLMUINT * puiBytesWritten) = 0; virtual const char * FTKAPI getLocalHostName( void) = 0; virtual const char * FTKAPI getLocalHostAddress( void) = 0; virtual const char * FTKAPI getPeerHostName( void) = 0; virtual const char * FTKAPI getPeerHostAddress( void) = 0; virtual RCODE FTKAPI readNoWait( void * pvBuffer, FLMUINT uiCount, FLMUINT * puiReadRead) = 0; virtual RCODE FTKAPI readAll( void * pvBuffer, FLMUINT uiCount, FLMUINT * puiBytesRead) = 0; virtual void FTKAPI setIOTimeout( FLMUINT uiSeconds) = 0; }; /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_SSLIOStream : public IF_IOStream { virtual RCODE FTKAPI openStream( const char * pszHost, FLMUINT uiPort = 443, FLMUINT uiFlags = 0) = 0; virtual RCODE FTKAPI read( void * pvBuffer, FLMUINT uiBytesToRead, FLMUINT * puiBytesRead = NULL) = 0; virtual RCODE FTKAPI write( const void * pvBuffer, FLMUINT uiBytesToWrite, FLMUINT * puiBytesWritten = NULL) = 0; virtual const char * FTKAPI getPeerCertificateText( void) = 0; }; /**************************************************************************** Desc: ****************************************************************************/ typedef enum { METHOD_GET = 0, METHOD_POST, METHOD_PUT } eHttpMethod; flminterface IF_HTTPHeader : public F_Object { virtual RCODE FTKAPI readRequestHeader( IF_IStream * pIStream) = 0; virtual RCODE FTKAPI readResponseHeader( IF_IStream * pIStream) = 0; virtual RCODE FTKAPI writeRequestHeader( IF_OStream * pOStream) = 0; virtual RCODE FTKAPI writeResponseHeader( IF_OStream * pOStream) = 0; virtual RCODE FTKAPI getHeaderValue( const char * pszTag, F_DynaBuf * pBuffer) = 0; virtual RCODE FTKAPI setHeaderValue( const char * pszTag, const char * pszValue) = 0; virtual RCODE FTKAPI getHeaderValue( const char * pszTag, FLMUINT * puiValue) = 0; virtual RCODE FTKAPI setHeaderValue( const char * pszTag, FLMUINT uiValue) = 0; virtual FLMUINT FTKAPI getStatusCode( void) = 0; virtual RCODE FTKAPI setStatusCode( FLMUINT uiStatusCode) = 0; virtual RCODE FTKAPI setRequestURI( const char * pszRequestURI) = 0; const char * FTKAPI getRequestURI( void); virtual RCODE FTKAPI setMethod( eHttpMethod httpMethod) = 0; virtual eHttpMethod getMethod( void) = 0; virtual void FTKAPI resetHeader( void) = 0; }; FTKXPC RCODE FTKAPI FlmAllocHTTPHeader( IF_HTTPHeader ** ppHTTPHeader); /**************************************************************************** /// Message severity. ****************************************************************************/ typedef enum { F_FATAL_MESSAGE = 0, ///< Indicates that a fatal error occurred - the kind that would normally ///< require a shutdown or other corrective action by an administrator. F_WARN_MESSAGE, ///< Warning message. F_ERR_MESSAGE, ///< Non-fatal error message. F_INFO_MESSAGE, ///< Information-only message. F_DEBUG_MESSAGE ///< Debug message. } eLogMessageSeverity; /**************************************************************************** Desc: Logging ****************************************************************************/ FTKXPC IF_LogMessageClient * FTKAPI f_beginLogMessage( FLMUINT uiMsgType, eLogMessageSeverity eMsgSeverity); FTKEXP void FTKAPI f_logPrintf( IF_LogMessageClient * pLogMessage, const char * pszFormatStr, ...); FTKXPC void FTKAPI f_logVPrintf( IF_LogMessageClient * pLogMessage, const char * szFormatStr, f_va_list * args); FTKXPC void FTKAPI f_endLogMessage( IF_LogMessageClient ** ppLogMessage); FTKXPC void FTKAPI f_logError( RCODE rc, const char * pszDoing, const char * pszFileName, FLMINT iLineNumber); FTKEXP void FTKAPI f_logPrintf( eLogMessageSeverity msgSeverity, const char * pszFormatStr, ...); /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_LoggerClient : public F_Object { virtual IF_LogMessageClient * FTKAPI beginMessage( FLMUINT uiMsgType, eLogMessageSeverity eMsgSeverity = F_DEBUG_MESSAGE) = 0; }; FTKXPC void FTKAPI f_setLoggerClient( IF_LoggerClient * pLogger); /**************************************************************************** /// This is an abstract base class that allows an application to catch /// messages. The application must create an implementation for this class /// and then return an object of that class when the /// IF_LoggerClient::beginMessage() method is called. ****************************************************************************/ flminterface FTKEXP IF_LogMessageClient : public F_Object { /// Set the current foreground and background colors for the message. virtual void FTKAPI changeColor( eColorType eForeColor, eColorType eBackColor) = 0; /// Append a string to the message. This method may be called /// multiple times by to format a complete message. The message is not /// complete until the ::endMessage() method is called. virtual void FTKAPI appendString( const char * pszStr) = 0; /// Append a newline to the message. This method is called when a /// multi-line message is being created. Rather than embedding a /// newline character, this method is used. This allows an application /// to recognize the fact that there are multiple lines in the message /// and to log, display, store, etc. (whatever) them accordingly. virtual void FTKAPI newline( void) = 0; /// End the current message. The application should finish logging, /// displaying, storing, etc. (whatever) the message. The object /// should be reset in case a new message is subsequently started. virtual void FTKAPI endMessage( void) = 0; virtual void FTKAPI pushForegroundColor( void) = 0; virtual void FTKAPI popForegroundColor( void) = 0; virtual void FTKAPI pushBackgroundColor( void) = 0; virtual void FTKAPI popBackgroundColor( void) = 0; }; /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_FileSystem : public F_Object { virtual RCODE FTKAPI createFile( const char * pszFileName, FLMUINT uiIoFlags, IF_FileHdl ** ppFile) = 0; virtual RCODE FTKAPI createUniqueFile( char * pszPath, const char * pszFileExtension, FLMUINT uiIoFlags, IF_FileHdl ** ppFile) = 0; virtual RCODE FTKAPI createLockFile( const char * pszPath, IF_FileHdl ** ppLockFileHdl) = 0; virtual RCODE FTKAPI openFile( const char * pszFileName, FLMUINT uiIoFlags, IF_FileHdl ** ppFile) = 0; virtual RCODE FTKAPI openDir( const char * pszDirName, const char * pszPattern, IF_DirHdl ** ppDir) = 0; virtual RCODE FTKAPI createDir( const char * pszDirName) = 0; virtual RCODE FTKAPI removeDir( const char * pszDirName, FLMBOOL bClear = FALSE) = 0; virtual RCODE FTKAPI doesFileExist( const char * pszFileName) = 0; virtual FLMBOOL FTKAPI isDir( const char * pszFileName) = 0; virtual RCODE FTKAPI getFileTimeStamp( const char * pszFileName, FLMUINT * puiTimeStamp) = 0; virtual RCODE FTKAPI getFileSize( const char * pszFileName, FLMUINT64 * pui64FileSize) = 0; virtual RCODE FTKAPI deleteFile( const char * pszFileName) = 0; virtual RCODE FTKAPI deleteMultiFileStream( const char * pszDirectory, const char * pszBaseName) = 0; virtual RCODE FTKAPI copyFile( const char * pszSrcFileName, const char * pszDestFileName, FLMBOOL bOverwrite, FLMUINT64 * pui64BytesCopied) = 0; virtual RCODE FTKAPI copyPartialFile( IF_FileHdl * pSrcFileHdl, FLMUINT64 ui64SrcOffset, FLMUINT64 ui64SrcSize, IF_FileHdl * pDestFileHdl, FLMUINT64 ui64DestOffset, FLMUINT64 * pui64BytesCopiedRV) = 0; virtual RCODE FTKAPI renameFile( const char * pszFileName, const char * pszNewFileName) = 0; virtual RCODE FTKAPI setReadOnly( const char * pszFileName, FLMBOOL bReadOnly) = 0; virtual RCODE FTKAPI getSectorSize( const char * pszFileName, FLMUINT * puiSectorSize) = 0; virtual void FTKAPI pathCreateUniqueName( FLMUINT * puiTime, char * pFileName, const char * pFileExt, FLMBYTE * pHighChars, FLMBOOL bModext) = 0; virtual void FTKAPI pathParse( const char * pszPath, char * pszServer, char * pszVolume, char * pszDirPath, char * pszFileName) = 0; virtual RCODE FTKAPI pathReduce( const char * pszSourcePath, char * pszDestPath, char * pszString) = 0; virtual RCODE FTKAPI pathAppend( char * pszPath, const char * pszPathComponent) = 0; virtual RCODE FTKAPI pathToStorageString( const char * pPath, char * pszString) = 0; virtual FLMBOOL FTKAPI doesFileMatch( const char * pszFileName, const char * pszTemplate) = 0; virtual FLMBOOL FTKAPI canDoAsync( void) = 0; virtual RCODE FTKAPI allocIOBuffer( FLMUINT uiMinSize, IF_IOBuffer ** ppIOBuffer) = 0; virtual RCODE FTKAPI allocFileHandleCache( FLMUINT uiMaxCachedFiles, FLMUINT uiIdleTimeoutSecs, IF_FileHdlCache ** ppFileHdlCache) = 0; }; FTKXPC RCODE FTKAPI FlmGetFileSystem( IF_FileSystem ** ppFileSystem); FTKXPC IF_FileSystem * FTKAPI f_getFileSysPtr( void); FTKXPC FLMUINT FTKAPI f_getOpenFileCount( void); FTKXPC RCODE FTKAPI f_chdir( const char * pszDir); FTKXPC RCODE FTKAPI f_getcwd( char * pszDir); FTKXPC RCODE FTKAPI f_pathReduce( const char * pszSourcePath, char * pszDestPath, char * pszString); FTKXPC RCODE FTKAPI f_pathAppend( char * pszPath, const char * pszPathComponent); /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_FileHdl : virtual public F_Object { virtual RCODE FTKAPI flush( void) = 0; virtual RCODE FTKAPI read( FLMUINT64 ui64Offset, FLMUINT uiLength, void * pvBuffer, FLMUINT * puiBytesRead = NULL) = 0; virtual RCODE FTKAPI read( FLMUINT64 ui64ReadOffset, FLMUINT uiBytesToRead, IF_IOBuffer * pIOBuffer) = 0; virtual RCODE FTKAPI write( FLMUINT64 ui64Offset, FLMUINT uiLength, const void * pvBuffer, FLMUINT * puiBytesWritten = NULL) = 0; virtual RCODE FTKAPI write( FLMUINT64 ui64WriteOffset, FLMUINT uiBytesToWrite, IF_IOBuffer * pIOBuffer) = 0; virtual RCODE FTKAPI seek( FLMUINT64 ui64Offset, FLMINT iWhence, FLMUINT64 * pui64NewOffset = NULL) = 0; virtual RCODE FTKAPI size( FLMUINT64 * pui64Size) = 0; virtual RCODE FTKAPI tell( FLMUINT64 * pui64Offset) = 0; virtual RCODE FTKAPI extendFile( FLMUINT64 ui64FileSize) = 0; virtual RCODE FTKAPI truncateFile( FLMUINT64 ui64FileSize = 0) = 0; virtual RCODE FTKAPI closeFile( void) = 0; virtual FLMBOOL FTKAPI canDoAsync( void) = 0; virtual FLMBOOL FTKAPI canDoDirectIO( void) = 0; virtual void FTKAPI setExtendSize( FLMUINT uiExtendSize) = 0; virtual void FTKAPI setMaxAutoExtendSize( FLMUINT uiMaxAutoExtendSize) = 0; virtual FLMUINT FTKAPI getSectorSize( void) = 0; virtual FLMBOOL FTKAPI isReadOnly( void) = 0; virtual FLMBOOL FTKAPI isOpen( void) = 0; virtual RCODE FTKAPI lock( void) = 0; virtual RCODE FTKAPI unlock( void) = 0; }; /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_FileHdlCache : public F_Object { virtual RCODE FTKAPI openFile( const char * pszFileName, FLMUINT uiIoFlags, IF_FileHdl ** ppFile) = 0; virtual RCODE FTKAPI createFile( const char * pszFileName, FLMUINT uiIoFlags, IF_FileHdl ** ppFile) = 0; virtual void FTKAPI closeUnusedFiles( FLMUINT uiUnusedTime = 0) = 0; virtual FLMUINT FTKAPI getOpenThreshold( void) = 0; virtual RCODE FTKAPI setOpenThreshold( FLMUINT uiMaxOpenFiles) = 0; }; /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_MultiFileHdl : public F_Object { virtual RCODE FTKAPI createFile( const char * pszPath) = 0; virtual RCODE FTKAPI createUniqueFile( const char * pszPath, const char * pszFileExtension) = 0; virtual RCODE FTKAPI openFile( const char * pszPath) = 0; virtual RCODE FTKAPI deleteMultiFile( const char * pszPath) = 0; virtual RCODE FTKAPI flush( void) = 0; virtual RCODE FTKAPI read( FLMUINT64 ui64Offset, FLMUINT uiLength, void * pvBuffer, FLMUINT * puiBytesRead = NULL) = 0; virtual RCODE FTKAPI write( FLMUINT64 ui64Offset, FLMUINT uiLength, void * pvBuffer, FLMUINT * puiBytesWritten = NULL) = 0; virtual RCODE FTKAPI getPath( char * pszFilePath) = 0; virtual RCODE FTKAPI size( FLMUINT64 * pui64FileSize) = 0; virtual RCODE FTKAPI truncateFile( FLMUINT64 ui64Offset = 0) = 0; virtual void FTKAPI closeFile( FLMBOOL bDelete = FALSE) = 0; }; FTKXPC RCODE FTKAPI FlmAllocMultiFileHdl( IF_MultiFileHdl ** ppFileHdl); /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_SuperFileClient : public F_Object { virtual FLMUINT FTKAPI getFileNumber( FLMUINT uiBlockAddr) = 0; virtual FLMUINT FTKAPI getFileOffset( FLMUINT uiBlockAddr) = 0; virtual FLMUINT FTKAPI getBlockAddress( FLMUINT uiFileNumber, FLMUINT uiFileOffset) = 0; virtual RCODE FTKAPI getFilePath( FLMUINT uiFileNumber, char * pszPath) = 0; virtual FLMUINT64 FTKAPI getMaxFileSize( void) = 0; }; /**************************************************************************** Desc: ****************************************************************************/ class FTKEXP F_SuperFileHdl : public F_Object { public: F_SuperFileHdl(); virtual ~F_SuperFileHdl(); RCODE FTKAPI setup( IF_SuperFileClient * pSuperFileClient, IF_FileHdlCache * pFileHdlCache, FLMUINT uiFileOpenFlags, FLMUINT uiFileCreateFlags); RCODE FTKAPI createFile( FLMUINT uiFileNumber, IF_FileHdl ** ppFileHdl = NULL); RCODE FTKAPI getFileHdl( FLMUINT uiFileNumber, FLMBOOL bGetForUpdate, IF_FileHdl ** ppFileHdlRV); RCODE FTKAPI readOffset( FLMUINT uiFileNumber, FLMUINT uiOffset, FLMUINT uiBytesToRead, void * pvBuffer, FLMUINT * puiBytesRead); RCODE FTKAPI readBlock( FLMUINT uiBlkAddress, FLMUINT uiBytesToRead, void * pvBuffer, FLMUINT * puiBytesRead); RCODE FTKAPI writeBlock( FLMUINT uiBlkAddress, FLMUINT uiBytesToWrite, const void * pvBuffer, FLMUINT * puiBytesWritten); RCODE FTKAPI writeBlock( FLMUINT uiBlkAddress, FLMUINT uiBytesToWrite, IF_IOBuffer * pIOBuffer); RCODE FTKAPI getFilePath( FLMUINT uiFileNumber, char * pszPath); RCODE FTKAPI getFileSize( FLMUINT uiFileNumber, FLMUINT64 * pui64FileSize); RCODE FTKAPI releaseFiles( void); RCODE FTKAPI allocateBlocks( FLMUINT uiStartAddress, FLMUINT uiEndAddress); RCODE FTKAPI truncateFile( FLMUINT uiEOFBlkAddress); RCODE FTKAPI truncateFile( FLMUINT uiFileNumber, FLMUINT uiOffset); void FTKAPI truncateFiles( FLMUINT uiStartFileNum, FLMUINT uiEndFileNum); RCODE FTKAPI flush( void); FINLINE void FTKAPI setExtendSize( FLMUINT uiExtendSize) { m_uiExtendSize = uiExtendSize; } FINLINE void FTKAPI setMaxAutoExtendSize( FLMUINT uiMaxAutoExtendSize) { m_uiMaxAutoExtendSize = uiMaxAutoExtendSize; } FLMBOOL FTKAPI canDoAsync( void); FLMBOOL FTKAPI canDoDirectIO( void); private: IF_SuperFileClient * m_pSuperFileClient; IF_FileHdlCache * m_pFileHdlCache; IF_FileHdl * m_pCFileHdl; IF_FileHdl * m_pBlockFileHdl; FLMBOOL m_bCFileDirty; FLMBOOL m_bBlockFileDirty; FLMUINT m_uiBlockFileNum; FLMUINT m_uiMaxFileSize; FLMUINT m_uiExtendSize; FLMUINT m_uiMaxAutoExtendSize; FLMUINT m_uiFileOpenFlags; FLMUINT m_uiFileCreateFlags; }; /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_AsyncClient : virtual public F_Object { virtual RCODE FTKAPI waitToComplete( void) = 0; virtual RCODE FTKAPI getCompletionCode( void) = 0; virtual FLMUINT FTKAPI getElapsedTime( void) = 0; }; /**************************************************************************** Desc: ****************************************************************************/ typedef void (FTKAPI * F_BUFFER_COMPLETION_FUNC)(IF_IOBuffer *, void *); /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_IOBuffer : virtual public F_Object { virtual FLMBYTE * FTKAPI getBufferPtr( void) = 0; virtual FLMUINT FTKAPI getBufferSize( void) = 0; virtual void FTKAPI setCompletionCallback( F_BUFFER_COMPLETION_FUNC fnCompletion, void * pvData) = 0; virtual RCODE FTKAPI addCallbackData( void * pvData) = 0; virtual void * FTKAPI getCallbackData( FLMUINT uiSlot) = 0; virtual FLMUINT FTKAPI getCallbackDataCount( void) = 0; virtual void FTKAPI setAsyncClient( IF_AsyncClient * pAsyncClient) = 0; virtual void FTKAPI notifyComplete( RCODE completionRc) = 0; virtual void FTKAPI setPending( void) = 0; virtual void FTKAPI clearPending( void) = 0; virtual FLMBOOL FTKAPI isPending( void) = 0; virtual FLMBOOL FTKAPI isComplete( void) = 0; virtual RCODE FTKAPI waitToComplete( void) = 0; virtual RCODE FTKAPI getCompletionCode( void) = 0; virtual FLMUINT FTKAPI getElapsedTime( void) = 0; }; /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_IOBufferMgr : public F_Object { virtual RCODE FTKAPI getBuffer( FLMUINT uiBufferSize, IF_IOBuffer ** ppIOBuffer) = 0; virtual FLMBOOL FTKAPI isIOPending( void) = 0; virtual RCODE FTKAPI waitForAllPendingIO( void) = 0; }; FTKXPC RCODE FTKAPI FlmAllocIOBufferMgr( FLMUINT uiMaxBuffers, FLMUINT uiMaxBytes, FLMBOOL bReuseBuffers, IF_IOBufferMgr ** ppIOBufferMgr); /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_DirHdl : public F_Object { virtual RCODE FTKAPI next( void) = 0; virtual const char * FTKAPI currentItemName( void) = 0; virtual void FTKAPI currentItemPath( char * pszPath) = 0; virtual FLMUINT64 FTKAPI currentItemSize( void) = 0; virtual FLMBOOL FTKAPI currentItemIsDir( void) = 0; }; /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_ResultSetCompare : public F_Object { virtual RCODE FTKAPI compare( const void * pvData1, FLMUINT uiLength1, const void * pvData2, FLMUINT uiLength2, FLMINT * piCompare) = 0; }; /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_ResultSetSortStatus : public F_Object { virtual RCODE FTKAPI reportSortStatus( FLMUINT64 ui64EstTotalUnits, FLMUINT64 ui64UnitsDone) = 0; }; #define RS_POSITION_NOT_SET FLM_MAX_UINT64 /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_ResultSet : public F_Object { virtual RCODE FTKAPI setupResultSet( const char * pszPath, IF_ResultSetCompare * pCompare, FLMUINT uiEntrySize, FLMBOOL bDropDuplicates = TRUE, FLMBOOL bEntriesInOrder = FALSE, const char * pszFileName = NULL) = 0; virtual FLMUINT64 FTKAPI getTotalEntries( void) = 0; virtual RCODE FTKAPI addEntry( const void * pvEntry, FLMUINT uiEntryLength = 0) = 0; virtual RCODE FTKAPI finalizeResultSet( IF_ResultSetSortStatus * pSortStatus = NULL, FLMUINT64 * pui64TotalEntries = NULL) = 0; virtual RCODE FTKAPI getFirst( void * pvEntryBuffer, FLMUINT uiBufferLength = 0, FLMUINT * puiEntryLength = NULL) = 0; virtual RCODE FTKAPI getNext( void * pvEntryBuffer, FLMUINT uiBufferLength = 0, FLMUINT * puiEntryLength = NULL) = 0; virtual RCODE FTKAPI getLast( void * pvEntryBuffer, FLMUINT uiBufferLength = 0, FLMUINT * puiEntryLength = NULL) = 0; virtual RCODE FTKAPI getPrev( void * pvEntryBuffer, FLMUINT uiBufferLength = 0, FLMUINT * puiEntryLength = NULL) = 0; virtual RCODE FTKAPI getCurrent( void * pvEntryBuffer, FLMUINT uiBufferLength = 0, FLMUINT * puiEntryLength = NULL) = 0; virtual RCODE FTKAPI findMatch( const void * pvMatchEntry, void * pvFoundEntry) = 0; virtual RCODE FTKAPI findMatch( const void * pvMatchEntry, FLMUINT uiMatchEntryLength, void * pvFoundEntry, FLMUINT * puiFoundEntryLength) = 0; virtual RCODE FTKAPI modifyCurrent( const void * pvEntry, FLMUINT uiEntryLength = 0) = 0; virtual FLMUINT64 FTKAPI getPosition( void) = 0; virtual RCODE FTKAPI setPosition( FLMUINT64 ui64Position) = 0; virtual RCODE FTKAPI resetResultSet( FLMBOOL bDelete = TRUE) = 0; virtual RCODE FTKAPI flushToFile( void) = 0; }; FTKXPC RCODE FTKAPI FlmAllocResultSet( IF_ResultSet ** ppResultSet); /***************************************************************************** Desc: *****************************************************************************/ flminterface FTKEXP IF_BTreeResultSet : public F_Object { virtual RCODE FTKAPI addEntry( FLMBYTE * pucKey, FLMUINT uiKeyLength, FLMBYTE * pucEntry, FLMUINT uiEntryLength) = 0; virtual RCODE FTKAPI modifyEntry( FLMBYTE * pucKey, FLMUINT uiKeyLength, FLMBYTE * pucEntry, FLMUINT uiEntryLength) = 0; virtual RCODE FTKAPI getCurrent( FLMBYTE * pucKey, FLMUINT uiKeyLength, FLMBYTE * pucEntry, FLMUINT uiEntryLength, FLMUINT * puiReturnLength) = 0; virtual RCODE FTKAPI getNext( FLMBYTE * pucKey, FLMUINT uiKeyBufLen, FLMUINT * puiKeylen, FLMBYTE * pucBuffer, FLMUINT uiBufferLength, FLMUINT * puiReturnLength) = 0; virtual RCODE FTKAPI getPrev( FLMBYTE * pucKey, FLMUINT uiKeyBufLen, FLMUINT * puiKeylen, FLMBYTE * pucBuffer, FLMUINT uiBufferLength, FLMUINT * puiReturnLength) = 0; virtual RCODE FTKAPI getFirst( FLMBYTE * pucKey, FLMUINT uiKeyBufLen, FLMUINT * puiKeylen, FLMBYTE * pucBuffer, FLMUINT uiBufferLength, FLMUINT * puiReturnLength) = 0; virtual RCODE FTKAPI getLast( FLMBYTE * pucKey, FLMUINT uiKeyBufLen, FLMUINT * puiKeylen, FLMBYTE * pucBuffer, FLMUINT uiBufferLength, FLMUINT * puiReturnLength) = 0; virtual RCODE FTKAPI findEntry( FLMBYTE * pucKey, FLMUINT uiKeyLen, FLMBYTE * pucBuffer, FLMUINT uiBufferLength, FLMUINT * puiReturnLength) = 0; virtual RCODE FTKAPI deleteEntry( FLMBYTE * pucKey, FLMUINT uiKeyLength) = 0; }; FTKXPC RCODE FTKAPI FlmAllocBTreeResultSet( IF_ResultSetCompare * pCompare, IF_BTreeResultSet ** ppBTreeResultSet); /**************************************************************************** Desc: Random numbers ****************************************************************************/ #define FLM_MAX_RANDOM ((FLMUINT32)2147483646) flminterface FTKEXP IF_RandomGenerator : public F_Object { virtual void FTKAPI randomize( void) = 0; virtual void FTKAPI setSeed( FLMUINT32 ui32seed) = 0; virtual FLMUINT32 FTKAPI getSeed( void) = 0; virtual FLMUINT32 FTKAPI getUINT32( FLMUINT32 ui32Low = 0, FLMUINT32 ui32High = FLM_MAX_RANDOM) = 0; virtual FLMBOOL FTKAPI getBoolean( void) = 0; }; FTKXPC RCODE FTKAPI FlmAllocRandomGenerator( IF_RandomGenerator ** ppRandomGenerator); FTKXPC FLMUINT32 FTKAPI f_getRandomUINT32( FLMUINT32 ui32Low = 0, FLMUINT32 ui32High = FLM_MAX_RANDOM); FTKXPC FLMBYTE FTKAPI f_getRandomByte( void); /********************************************************************** Desc: Atomic operations **********************************************************************/ FTKXPC FLMINT32 FTKAPI f_atomicInc( FLMATOMIC * piTarget); FTKXPC FLMINT32 FTKAPI f_atomicDec( FLMATOMIC * piTarget); FTKXPC FLMINT32 FTKAPI f_atomicExchange( FLMATOMIC * piTarget, FLMINT32 i32NewVal); /**************************************************************************** Desc: Mutexes ****************************************************************************/ typedef void * F_MUTEX; #define F_MUTEX_NULL NULL FTKXPC RCODE FTKAPI f_mutexCreate( F_MUTEX * phMutex); FTKXPC void FTKAPI f_mutexDestroy( F_MUTEX * phMutex); FTKXPC void FTKAPI f_mutexLock( F_MUTEX hMutex); FTKXPC void FTKAPI f_mutexUnlock( F_MUTEX hMutex); #ifdef FLM_DEBUG FTKXPC void FTKAPI f_assertMutexLocked( F_MUTEX hMutex); #else #define f_assertMutexLocked( h) (void)(h) #endif #ifdef FLM_DEBUG FTKXPC void FTKAPI f_assertMutexNotLocked( F_MUTEX hMutex); #else #define f_assertMutexNotLocked( h) (void)(h) #endif /**************************************************************************** Desc: Semaphores ****************************************************************************/ typedef void * F_SEM; #define F_SEM_NULL NULL FTKXPC RCODE FTKAPI f_semCreate( F_SEM * phSem); FTKXPC void FTKAPI f_semDestroy( F_SEM * phSem); FTKXPC RCODE FTKAPI f_semWait( F_SEM hSem, FLMUINT uiTimeout); FTKXPC void FTKAPI f_semSignal( F_SEM hSem); FTKXPC FLMUINT FTKAPI f_semGetSignalCount( F_SEM hSem); /**************************************************************************** Desc: Notify Lists ****************************************************************************/ typedef struct F_NOTIFY_LIST_ITEM { F_NOTIFY_LIST_ITEM * pNext; ///< Pointer to next F_NOTIFY_LIST_ITEM structure in list. FLMUINT uiThreadId; ///< ID of thread requesting the notify RCODE * pRc; ///< Pointer to a return code variable that is to ///< be filled in when the operation is completed. ///< The thread requesting notification supplies ///< the return code variable to be filled in. void * pvData; ///< Data that is passed through to a custom ///< notify routine F_SEM hSem; ///< Semaphore that will be signaled when the ///< operation is complete. } F_NOTIFY_LIST_ITEM; FTKXPC RCODE FTKAPI f_notifyWait( F_MUTEX hMutex, F_SEM hSem, void * pvData, F_NOTIFY_LIST_ITEM ** ppNotifyList); FTKXPC void FTKAPI f_notifySignal( F_NOTIFY_LIST_ITEM * pNotifyList, RCODE notifyRc); /**************************************************************************** Desc: Reader / Writer Locks ****************************************************************************/ typedef void * F_RWLOCK; #define F_RWLOCK_NULL NULL FTKXPC RCODE FTKAPI f_rwlockCreate( F_RWLOCK * phReadWriteLock); FTKXPC void FTKAPI f_rwlockDestroy( F_RWLOCK * phReadWriteLock); FTKXPC RCODE FTKAPI f_rwlockAcquire( F_RWLOCK hReadWriteLock, F_SEM hSem, FLMBOOL bWriter); FTKXPC RCODE FTKAPI f_rwlockPromote( F_RWLOCK hReadWriteLock, F_SEM hSem); FTKXPC RCODE FTKAPI f_rwlockRelease( F_RWLOCK hReadWriteLock); /**************************************************************************** Desc: Thread manager ****************************************************************************/ flminterface FTKEXP IF_ThreadMgr : public F_Object { virtual RCODE FTKAPI setupThreadMgr( void) = 0; virtual RCODE FTKAPI createThread( IF_Thread ** ppThread, F_THREAD_FUNC fnThread, const char * pszThreadName = NULL, FLMUINT uiThreadGroup = 0, FLMUINT uiAppId = 0, void * pvParm1 = NULL, void * pvParm2 = NULL, FLMUINT uiStackSize = F_THREAD_DEFAULT_STACK_SIZE) = 0; virtual void FTKAPI shutdownThreadGroup( FLMUINT uiThreadGroup) = 0; virtual void FTKAPI setThreadShutdownFlag( FLMUINT uiThreadId) = 0; virtual RCODE FTKAPI findThread( IF_Thread ** ppThread, FLMUINT uiThreadGroup, FLMUINT uiAppId = 0, FLMBOOL bOkToFindMe = TRUE) = 0; virtual RCODE FTKAPI getNextGroupThread( IF_Thread ** ppThread, FLMUINT uiThreadGroup, FLMUINT * puiThreadId) = 0; virtual RCODE FTKAPI getThreadInfo( F_Pool * pPool, F_THREAD_INFO ** ppThreadInfo, FLMUINT * puiNumThreads) = 0; virtual RCODE FTKAPI getThreadName( FLMUINT uiThreadId, char * pszThreadName, FLMUINT * puiLength) = 0; virtual FLMUINT FTKAPI getThreadGroupCount( FLMUINT uiThreadGroup) = 0; virtual FLMUINT FTKAPI allocGroupId( void) = 0; }; FTKXPC RCODE FTKAPI FlmGetThreadMgr( IF_ThreadMgr ** ppThreadMgr); /**************************************************************************** Desc: Thread ****************************************************************************/ flminterface FTKEXP IF_Thread : public F_Object { virtual RCODE FTKAPI startThread( F_THREAD_FUNC fnThread, const char * pszThreadName = NULL, FLMUINT uiThreadGroup = F_DEFAULT_THREAD_GROUP, FLMUINT uiAppId = 0, void * pvParm1 = NULL, void * pvParm2 = NULL, FLMUINT uiStackSize = F_THREAD_DEFAULT_STACK_SIZE) = 0; virtual void FTKAPI stopThread( void) = 0; virtual FLMUINT FTKAPI getThreadId( void) = 0; virtual FLMBOOL FTKAPI getShutdownFlag( void) = 0; virtual RCODE FTKAPI getExitCode( void) = 0; virtual void * FTKAPI getParm1( void) = 0; virtual void FTKAPI setParm1( void * pvParm) = 0; virtual void * FTKAPI getParm2( void) = 0; virtual void FTKAPI setParm2( void * pvParm) = 0; virtual void FTKAPI setShutdownFlag( void) = 0; virtual FLMBOOL FTKAPI isThreadRunning( void) = 0; virtual void FTKAPI setThreadStatusStr( const char * pszStatus) = 0; virtual void FTKAPI setThreadStatus( const char * pszBuffer, ...) = 0; virtual void FTKAPI setThreadStatus( eThreadStatus genericStatus) = 0; virtual void FTKAPI setThreadAppId( FLMUINT uiAppId) = 0; virtual FLMUINT FTKAPI getThreadAppId( void) = 0; virtual FLMUINT FTKAPI getThreadGroup( void) = 0; virtual void FTKAPI cleanupThread( void) = 0; virtual void FTKAPI sleep( FLMUINT uiMilliseconds) = 0; virtual void FTKAPI waitToComplete( void) = 0; }; FTKXPC RCODE FTKAPI f_threadCreate( IF_Thread ** ppThread, F_THREAD_FUNC fnThread, const char * pszThreadName = NULL, FLMUINT uiThreadGroup = F_DEFAULT_THREAD_GROUP, FLMUINT uiAppId = 0, void * pvParm1 = NULL, void * pvParm2 = NULL, FLMUINT uiStackSize = F_THREAD_DEFAULT_STACK_SIZE); FTKXPC void FTKAPI f_threadDestroy( IF_Thread ** ppThread); FTKXPC FLMUINT FTKAPI f_threadId( void); /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_IniFile : public F_Object { virtual RCODE FTKAPI read( const char * pszFileName) = 0; virtual RCODE FTKAPI write( void) = 0; virtual FLMBOOL FTKAPI getParam( const char * pszParamName, FLMUINT * puiParamVal) = 0; virtual FLMBOOL FTKAPI getParam( const char * pszParamName, FLMBOOL * pbParamVal) = 0; virtual FLMBOOL FTKAPI getParam( const char * pszParamName, char ** ppszParamVal) = 0; virtual RCODE FTKAPI setParam( const char * pszParamName, FLMUINT uiParamVal) = 0; virtual RCODE FTKAPI setParam( const char * pszParamName, FLMBOOL bParamVal) = 0; virtual RCODE FTKAPI setParam( const char * pszParamName, const char * pszParamVal) = 0; virtual FLMBOOL FTKAPI testParam( const char * pszParamName) = 0; }; FTKXPC RCODE FTKAPI FlmAllocIniFile( IF_IniFile ** ppIniFile); /**************************************************************************** Desc: Serial numbers ****************************************************************************/ FTKXPC RCODE FTKAPI f_createSerialNumber( FLMBYTE * pszSerialNumber); #define F_SERIAL_NUM_SIZE 16 /**************************************************************************** Desc: Checksum ****************************************************************************/ FTKXPC void FTKAPI f_updateCRC( const void * pvBuffer, FLMUINT uiLength, FLMUINT32 * pui32CRC); FTKXPC FLMUINT32 FTKAPI f_calcFastChecksum( const void * pvBuffer, FLMUINT uiLength, FLMUINT * puiSum = NULL, FLMUINT * puiXOR = NULL); FTKXPC FLMBYTE FTKAPI f_calcPacketChecksum( const void * pvPacket, FLMUINT uiBytesToChecksum); /**************************************************************************** Desc: ****************************************************************************/ FTKXPC char * FTKAPI f_uwtoa( FLMUINT16 value, char * ptr); FTKXPC char * FTKAPI f_udtoa( FLMUINT value, char * ptr); FTKXPC char * FTKAPI f_wtoa( FLMINT16 value, char * ptr); FTKXPC char * FTKAPI f_dtoa( FLMINT value, char * ptr); FTKXPC char * FTKAPI f_ui64toa( FLMUINT64 value, char * ptr); FTKXPC char * FTKAPI f_i64toa( FLMINT64 value, char * ptr); FTKXPC FLMINT FTKAPI f_atoi( const char * ptr); FTKXPC FLMINT FTKAPI f_atol( const char * ptr); FTKXPC FLMINT FTKAPI f_atod( const char * ptr); FTKXPC FLMUINT FTKAPI f_atoud( const char * ptr, FLMBOOL bAllowUnprefixedHex = FALSE); FTKXPC FLMUINT64 FTKAPI f_atou64( const char * pszBuf); FTKXPC FLMBOOL FTKAPI f_atobool( const char * pszStr, FLMBOOL * pbValidFormat = NULL); FTKXPC FLMUINT FTKAPI f_unilen( const FLMUNICODE * puzStr); FTKXPC FLMUNICODE * FTKAPI f_unicpy( FLMUNICODE * puzDestStr, const FLMUNICODE * puzSrcStr); FTKXPC FLMBOOL FTKAPI f_uniIsUpper( FLMUNICODE uChar); FTKXPC FLMBOOL FTKAPI f_uniIsLower( FLMUNICODE uChar); FTKXPC FLMBOOL FTKAPI f_uniIsAlpha( FLMUNICODE uChar); FTKXPC FLMBOOL FTKAPI f_uniIsDecimalDigit( FLMUNICODE uChar); FTKXPC FLMUNICODE FTKAPI f_uniToLower( FLMUNICODE uChar); FTKXPC FLMINT FTKAPI f_unicmp( const FLMUNICODE * puzStr1, const FLMUNICODE * puzStr2); FTKXPC FLMINT FTKAPI f_uniicmp( const FLMUNICODE * puzStr1, const FLMUNICODE * puzStr2); FTKXPC FLMINT FTKAPI f_uninativecmp( const FLMUNICODE * puzStr1, const char * pszStr2); FTKXPC FLMINT FTKAPI f_uninativencmp( const FLMUNICODE * puzStr1, const char * pszStr2, FLMUINT uiCount); FTKXPC RCODE FTKAPI f_nextUCS2Char( const FLMBYTE ** ppszUTF8, const FLMBYTE * pszEndOfUTF8String, FLMUNICODE * puzChar); FTKXPC RCODE FTKAPI f_numUCS2Chars( const FLMBYTE * pszUTF8, FLMUINT * puiNumChars); FTKXPC FLMBOOL FTKAPI f_isWhitespace( FLMUNICODE ucChar); FTKXPC FLMUNICODE FTKAPI f_convertChar( FLMUNICODE uzChar, FLMUINT uiCompareRules); FTKXPC RCODE FTKAPI f_wpToUnicode( FLMUINT16 ui16WPChar, FLMUNICODE * puUniChar); FTKXPC FLMBOOL FTKAPI f_unicodeToWP( FLMUNICODE uUniChar, FLMUINT16 * pui16WPChar); FTKXPC FLMBOOL FTKAPI f_depricatedUnicodeToWP( FLMUNICODE uUniChar, FLMUINT16 * pui16WPChar); FTKXPC FLMUINT16 FTKAPI f_wpUpper( FLMUINT16 ui16WpChar); FTKXPC FLMBOOL FTKAPI f_wpIsUpper( FLMUINT16 ui16WpChar); FTKXPC FLMUINT16 FTKAPI f_wpLower( FLMUINT16 ui16WpChar); FTKXPC FLMBOOL FTKAPI f_breakWPChar( FLMUINT16 ui16WpChar, FLMUINT16 * pui16BaseChar, FLMUINT16 * pui16DiacriticChar); FTKXPC FLMBOOL FTKAPI f_combineWPChar( FLMUINT16 * pui16WpChar, FLMUINT16 ui16BaseChar, FLMINT16 ui16DiacriticChar); FTKXPC FLMUINT16 FTKAPI f_wpGetCollationImp( FLMUINT16 ui16WpChar, FLMUINT uiLanguage); FINLINE FLMUINT16 FTKAPI f_wpGetCollation( FLMUINT16 ui16WpChar, FLMUINT uiLanguage) { if( uiLanguage == FLM_US_LANG) { return( gv_pui16USCollationTable[ ui16WpChar]); } return( f_wpGetCollationImp( ui16WpChar, uiLanguage)); } FTKEXP RCODE FTKAPI f_wpCheckDoubleCollation( IF_PosIStream * pIStream, FLMBOOL bUnicodeStream, FLMBOOL bAllowTwoIntoOne, FLMUNICODE * puzChar, FLMUNICODE * puzChar2, FLMBOOL * pbTwoIntoOne, FLMUINT uiLanguage); FTKEXP FLMUINT16 FTKAPI f_wpCheckDoubleCollation( FLMUINT16 * pui16WpChar, FLMBOOL * pbTwoIntoOne, const FLMBYTE ** ppucInputStr, FLMUINT uiLanguage); FTKXPC FLMUINT16 FTKAPI f_wpHanToZenkaku( FLMUINT16 ui16WpChar, FLMUINT16 ui16NextWpChar, FLMUINT16 * pui16Zenkaku); FTKXPC FLMUINT16 FTKAPI f_wpZenToHankaku( FLMUINT16 ui16WpChar, FLMUINT16 * pui16DakutenOrHandakuten); FTKXPC FLMUINT FTKAPI f_wpToMixed( FLMBYTE * pucWPStr, FLMUINT uiWPStrLen, const FLMBYTE * pucLowUpBitStr, FLMUINT uiLang); FTKXPC RCODE FTKAPI f_asiaParseSubCol( FLMBYTE * pucWPStr, FLMUINT * puiWPStrLen, FLMUINT uiMaxWPBytes, const FLMBYTE * pucSubColBuf, FLMUINT * puiSubColBitPos); FTKXPC RCODE FTKAPI f_asiaColStr2WPStr( const FLMBYTE * pucColStr, FLMUINT uiColStrLen, FLMBYTE * pucWPStr, FLMUINT * puiWPStrLen, FLMUINT * puiUnconvChars, FLMBOOL * pbDataTruncated, FLMBOOL * pbFirstSubstring); FTKXPC RCODE FTKAPI f_colStr2WPStr( const FLMBYTE * pucColStr, FLMUINT uiColStrLen, FLMBYTE * pucWPStr, FLMUINT * puiWPStrLen, FLMUINT uiLang, FLMUINT * puiUnconvChars, FLMBOOL * pbDataTruncated, FLMBOOL * pbFirstSubstring); FTKXPC RCODE FTKAPI f_asiaUTF8ToColText( IF_PosIStream * pIStream, FLMBYTE * pucColStr, FLMUINT * puiColStrLen, FLMBOOL bCaseInsensitive, FLMUINT * puiCollationLen, FLMUINT * puiCaseLen, FLMUINT uiCharLimit, FLMBOOL bFirstSubstring, FLMBOOL bDataTruncated, FLMBOOL * pbDataTruncated); FTKXPC RCODE FTKAPI f_compareUTF8Strings( const FLMBYTE * pucLString, FLMUINT uiLStrBytes, FLMBOOL bLeftWild, const FLMBYTE * pucRString, FLMUINT uiRStrBytes, FLMBOOL bRightWild, FLMUINT uiCompareRules, FLMUINT uiLanguage, FLMINT * piResult); FTKXPC RCODE FTKAPI f_compareUTF8Streams( IF_PosIStream * pLStream, FLMBOOL bLeftWild, IF_PosIStream * pRStream, FLMBOOL bRightWild, FLMUINT uiCompareRules, FLMUINT uiLanguage, FLMINT * piResult); FTKXPC RCODE FTKAPI f_compareUnicodeStrings( const FLMUNICODE * puzLString, FLMUINT uiLStrBytes, FLMBOOL bLeftWild, const FLMUNICODE * puzRString, FLMUINT uiRStrBytes, FLMBOOL bRightWild, FLMUINT uiCompareRules, FLMUINT uiLanguage, FLMINT * piResult); FTKXPC RCODE FTKAPI f_compareUnicodeStreams( IF_PosIStream * pLStream, FLMBOOL bLeftWild, IF_PosIStream * pRStream, FLMBOOL bRightWild, FLMUINT uiCompareRules, FLMUINT uiLanguage, FLMINT * piResult); FTKXPC RCODE FTKAPI f_compareCollStreams( IF_CollIStream * pLStream, IF_CollIStream * pRStream, FLMBOOL bOpIsMatch, FLMUINT uiLanguage, FLMINT * piResult); FTKXPC RCODE FTKAPI f_utf8IsSubStr( const FLMBYTE * pszString, const FLMBYTE * pszSubString, FLMUINT uiCompareRules, FLMUINT uiLanguage, FLMBOOL * pbExists); FTKXPC RCODE FTKAPI f_readUTF8CharAsUnicode( IF_IStream * pStream, FLMUNICODE * puChar); FTKXPC RCODE FTKAPI f_readUTF8CharAsUTF8( IF_IStream * pIStream, FLMBYTE * pucBuf, FLMUINT * puiLen); FTKXPC RCODE FTKAPI f_formatUTF8Text( IF_PosIStream * pIStream, FLMBOOL bAllowEscapes, FLMUINT uiCompareRules, F_DynaBuf * pDynaBuf); FTKXPC RCODE FTKAPI f_getNextMetaphone( IF_IStream * pIStream, FLMUINT * puiMetaphone, FLMUINT * puiAltMetaphone = NULL); FTKXPC FLMUINT FTKAPI f_getSENLength( FLMBYTE ucByte); FTKXPC FLMUINT FTKAPI f_getSENByteCount( FLMUINT64 ui64Num); FTKEXP FLMUINT FTKAPI f_encodeSEN( FLMUINT64 ui64Value, FLMBYTE ** ppucBuffer, FLMUINT uiBytesWanted = 0); FTKEXP RCODE FTKAPI f_encodeSEN( FLMUINT64 ui64Value, FLMBYTE ** ppucBuffer, FLMBYTE * pucEnd); FTKXPC FLMUINT FTKAPI f_encodeSENKnownLength( FLMUINT64 ui64Value, FLMUINT uiSenLen, FLMBYTE ** ppucBuffer); FTKXPC RCODE FTKAPI f_decodeSEN( const FLMBYTE ** ppucBuffer, const FLMBYTE * pucEnd, FLMUINT * puiValue); FTKXPC RCODE FTKAPI f_decodeSEN64( const FLMBYTE ** ppucBuffer, const FLMBYTE * pucEnd, FLMUINT64 * pui64Value); FTKXPC RCODE FTKAPI f_readSEN( IF_IStream * pIStream, FLMUINT * puiValue, FLMUINT * puiLength = NULL); FTKXPC RCODE FTKAPI f_readSEN64( IF_IStream * pIStream, FLMUINT64 * pui64Value, FLMUINT * puiLength = NULL); /// Get the language string from a language code /// \ingroup language FTKXPC FLMUINT FTKAPI f_languageToNum( const char * pszLanguage); /// Convert a language string to the appropriate language code. /// \ingroup language FTKXPC void FTKAPI f_languageToStr( FLMINT iLangNum, char * pszLanguage ///< Language string that is to be converted to a code. ); FTKXPC RCODE FTKAPI flmUTF8ToColText( IF_PosIStream * pIStream, FLMBYTE * pucCollatedStr, FLMUINT * puiCollatedStrLen, FLMBOOL bCaseInsensitive, FLMUINT * puiCollationLen, FLMUINT * puiCaseLen, FLMUINT uiLanguage, FLMUINT uiCharLimit, FLMBOOL bFirstSubstring, FLMBOOL bDataTruncated, FLMBOOL * pbOriginalCharsLost, FLMBOOL * pbDataTruncated); /**************************************************************************** Desc: ASCII character constants and macros ****************************************************************************/ #define ASCII_TAB 0x09 #define ASCII_NEWLINE 0x0A #define ASCII_LF 0x0A #define ASCII_CR 0x0D #define ASCII_CTRLZ 0x1A #define ASCII_SPACE 0x20 #define ASCII_DQUOTE 0x22 #define ASCII_POUND 0x23 #define ASCII_DOLLAR 0x24 #define ASCII_SQUOTE 0x27 #define ASCII_WILDCARD 0x2A #define ASCII_PLUS 0x2B #define ASCII_COMMA 0x2C #define ASCII_DASH 0x2D #define ASCII_MINUS 0x2D #define ASCII_DOT 0x2E #define ASCII_SLASH 0x2F #define ASCII_COLON 0x3A #define ASCII_SEMICOLON 0x3B #define ASCII_EQUAL 0x3D #define ASCII_QUESTIONMARK 0x3F #define ASCII_AT 0x40 #define ASCII_BACKSLASH 0x5C #define ASCII_CARAT 0x5E #define ASCII_UNDERSCORE 0x5F #define ASCII_TILDE 0x7E #define ASCII_AMP 0x26 #define ASCII_UPPER_A 0x41 #define ASCII_UPPER_B 0x42 #define ASCII_UPPER_C 0x43 #define ASCII_UPPER_D 0x44 #define ASCII_UPPER_E 0x45 #define ASCII_UPPER_F 0x46 #define ASCII_UPPER_G 0x47 #define ASCII_UPPER_H 0x48 #define ASCII_UPPER_I 0x49 #define ASCII_UPPER_J 0x4A #define ASCII_UPPER_K 0x4B #define ASCII_UPPER_L 0x4C #define ASCII_UPPER_M 0x4D #define ASCII_UPPER_N 0x4E #define ASCII_UPPER_O 0x4F #define ASCII_UPPER_P 0x50 #define ASCII_UPPER_Q 0x51 #define ASCII_UPPER_R 0x52 #define ASCII_UPPER_S 0x53 #define ASCII_UPPER_T 0x54 #define ASCII_UPPER_U 0x55 #define ASCII_UPPER_V 0x56 #define ASCII_UPPER_W 0x57 #define ASCII_UPPER_X 0x58 #define ASCII_UPPER_Y 0x59 #define ASCII_UPPER_Z 0x5A #define ASCII_LOWER_A 0x61 #define ASCII_LOWER_B 0x62 #define ASCII_LOWER_C 0x63 #define ASCII_LOWER_D 0x64 #define ASCII_LOWER_E 0x65 #define ASCII_LOWER_F 0x66 #define ASCII_LOWER_G 0x67 #define ASCII_LOWER_H 0x68 #define ASCII_LOWER_I 0x69 #define ASCII_LOWER_J 0x6A #define ASCII_LOWER_K 0x6B #define ASCII_LOWER_L 0x6C #define ASCII_LOWER_M 0x6D #define ASCII_LOWER_N 0x6E #define ASCII_LOWER_O 0x6F #define ASCII_LOWER_P 0x70 #define ASCII_LOWER_Q 0x71 #define ASCII_LOWER_R 0x72 #define ASCII_LOWER_S 0x73 #define ASCII_LOWER_T 0x74 #define ASCII_LOWER_U 0x75 #define ASCII_LOWER_V 0x76 #define ASCII_LOWER_W 0x77 #define ASCII_LOWER_X 0x78 #define ASCII_LOWER_Y 0x79 #define ASCII_LOWER_Z 0x7A #define ASCII_ZERO 0x30 #define ASCII_ONE 0x31 #define ASCII_TWO 0x32 #define ASCII_THREE 0x33 #define ASCII_FOUR 0x34 #define ASCII_FIVE 0x35 #define ASCII_SIX 0x36 #define ASCII_SEVEN 0x37 #define ASCII_EIGHT 0x38 #define ASCII_NINE 0x39 /**************************************************************************** Desc: Native character constants and macros ****************************************************************************/ #define NATIVE_SPACE ' ' #define NATIVE_DOT '.' #define NATIVE_PLUS '+' #define NATIVE_MINUS '-' #define NATIVE_WILDCARD '*' #define NATIVE_QUESTIONMARK '?' #define NATIVE_UPPER_A 'A' #define NATIVE_UPPER_F 'F' #define NATIVE_UPPER_X 'X' #define NATIVE_UPPER_Z 'Z' #define NATIVE_LOWER_A 'a' #define NATIVE_LOWER_F 'f' #define NATIVE_LOWER_X 'x' #define NATIVE_LOWER_Z 'z' #define NATIVE_ZERO '0' #define NATIVE_NINE '9' #define f_stringToAscii( str) #define f_toascii( native) \ (native) #define f_tonative( ascii) \ (ascii) #define f_toupper( native) \ (((native) >= 'a' && (native) <= 'z') \ ? (native) - 'a' + 'A' \ : (native)) #define f_tolower( native) \ (((native) >= 'A' && (native) <= 'Z') \ ? (native) - 'A' + 'a' \ : (native)) #define f_islower( native) \ ((native) >= 'a' && (native) <= 'z') #ifndef FLM_ASCII_PLATFORM #define FLM_ASCII_PLATFORM #endif /**************************************************************************** Desc: Unicode character constants and macros ****************************************************************************/ #define FLM_UNICODE_LINEFEED ((FLMUNICODE)10) #define FLM_UNICODE_SPACE ((FLMUNICODE)32) #define FLM_UNICODE_BANG ((FLMUNICODE)33) #define FLM_UNICODE_QUOTE ((FLMUNICODE)34) #define FLM_UNICODE_POUND ((FLMUNICODE)35) #define FLM_UNICODE_DOLLAR ((FLMUNICODE)36) #define FLM_UNICODE_PERCENT ((FLMUNICODE)37) #define FLM_UNICODE_AMP ((FLMUNICODE)38) #define FLM_UNICODE_APOS ((FLMUNICODE)39) #define FLM_UNICODE_LPAREN ((FLMUNICODE)40) #define FLM_UNICODE_RPAREN ((FLMUNICODE)41) #define FLM_UNICODE_ASTERISK ((FLMUNICODE)42) #define FLM_UNICODE_PLUS ((FLMUNICODE)43) #define FLM_UNICODE_COMMA ((FLMUNICODE)44) #define FLM_UNICODE_HYPHEN ((FLMUNICODE)45) #define FLM_UNICODE_PERIOD ((FLMUNICODE)46) #define FLM_UNICODE_FSLASH ((FLMUNICODE)47) #define FLM_UNICODE_0 ((FLMUNICODE)48) #define FLM_UNICODE_1 ((FLMUNICODE)49) #define FLM_UNICODE_2 ((FLMUNICODE)50) #define FLM_UNICODE_3 ((FLMUNICODE)51) #define FLM_UNICODE_4 ((FLMUNICODE)52) #define FLM_UNICODE_5 ((FLMUNICODE)53) #define FLM_UNICODE_6 ((FLMUNICODE)54) #define FLM_UNICODE_7 ((FLMUNICODE)55) #define FLM_UNICODE_8 ((FLMUNICODE)56) #define FLM_UNICODE_9 ((FLMUNICODE)57) #define FLM_UNICODE_COLON ((FLMUNICODE)58) #define FLM_UNICODE_SEMI ((FLMUNICODE)59) #define FLM_UNICODE_LT ((FLMUNICODE)60) #define FLM_UNICODE_EQ ((FLMUNICODE)61) #define FLM_UNICODE_GT ((FLMUNICODE)62) #define FLM_UNICODE_QUEST ((FLMUNICODE)63) #define FLM_UNICODE_ATSIGN ((FLMUNICODE)64) #define FLM_UNICODE_A ((FLMUNICODE)65) #define FLM_UNICODE_B ((FLMUNICODE)66) #define FLM_UNICODE_C ((FLMUNICODE)67) #define FLM_UNICODE_D ((FLMUNICODE)68) #define FLM_UNICODE_E ((FLMUNICODE)69) #define FLM_UNICODE_F ((FLMUNICODE)70) #define FLM_UNICODE_G ((FLMUNICODE)71) #define FLM_UNICODE_H ((FLMUNICODE)72) #define FLM_UNICODE_I ((FLMUNICODE)73) #define FLM_UNICODE_J ((FLMUNICODE)74) #define FLM_UNICODE_K ((FLMUNICODE)75) #define FLM_UNICODE_L ((FLMUNICODE)76) #define FLM_UNICODE_M ((FLMUNICODE)77) #define FLM_UNICODE_N ((FLMUNICODE)78) #define FLM_UNICODE_O ((FLMUNICODE)79) #define FLM_UNICODE_P ((FLMUNICODE)80) #define FLM_UNICODE_Q ((FLMUNICODE)81) #define FLM_UNICODE_R ((FLMUNICODE)82) #define FLM_UNICODE_S ((FLMUNICODE)83) #define FLM_UNICODE_T ((FLMUNICODE)84) #define FLM_UNICODE_U ((FLMUNICODE)85) #define FLM_UNICODE_V ((FLMUNICODE)86) #define FLM_UNICODE_W ((FLMUNICODE)87) #define FLM_UNICODE_X ((FLMUNICODE)88) #define FLM_UNICODE_Y ((FLMUNICODE)89) #define FLM_UNICODE_Z ((FLMUNICODE)90) #define FLM_UNICODE_LBRACKET ((FLMUNICODE)91) #define FLM_UNICODE_BACKSLASH ((FLMUNICODE)92) #define FLM_UNICODE_RBRACKET ((FLMUNICODE)93) #define FLM_UNICODE_UNDERSCORE ((FLMUNICODE)95) #define FLM_UNICODE_a ((FLMUNICODE)97) #define FLM_UNICODE_b ((FLMUNICODE)98) #define FLM_UNICODE_c ((FLMUNICODE)99) #define FLM_UNICODE_d ((FLMUNICODE)100) #define FLM_UNICODE_e ((FLMUNICODE)101) #define FLM_UNICODE_f ((FLMUNICODE)102) #define FLM_UNICODE_g ((FLMUNICODE)103) #define FLM_UNICODE_h ((FLMUNICODE)104) #define FLM_UNICODE_i ((FLMUNICODE)105) #define FLM_UNICODE_j ((FLMUNICODE)106) #define FLM_UNICODE_k ((FLMUNICODE)107) #define FLM_UNICODE_l ((FLMUNICODE)108) #define FLM_UNICODE_m ((FLMUNICODE)109) #define FLM_UNICODE_n ((FLMUNICODE)110) #define FLM_UNICODE_o ((FLMUNICODE)111) #define FLM_UNICODE_p ((FLMUNICODE)112) #define FLM_UNICODE_q ((FLMUNICODE)113) #define FLM_UNICODE_r ((FLMUNICODE)114) #define FLM_UNICODE_s ((FLMUNICODE)115) #define FLM_UNICODE_t ((FLMUNICODE)116) #define FLM_UNICODE_u ((FLMUNICODE)117) #define FLM_UNICODE_v ((FLMUNICODE)118) #define FLM_UNICODE_w ((FLMUNICODE)119) #define FLM_UNICODE_x ((FLMUNICODE)120) #define FLM_UNICODE_y ((FLMUNICODE)121) #define FLM_UNICODE_z ((FLMUNICODE)122) #define FLM_UNICODE_LBRACE ((FLMUNICODE)123) #define FLM_UNICODE_PIPE ((FLMUNICODE)124) #define FLM_UNICODE_RBRACE ((FLMUNICODE)125) #define FLM_UNICODE_TILDE ((FLMUNICODE)126) #define FLM_UNICODE_C_CEDILLA ((FLMUNICODE)199) #define FLM_UNICODE_N_TILDE ((FLMUNICODE)209) #define FLM_UNICODE_c_CEDILLA ((FLMUNICODE)231) #define FLM_UNICODE_n_TILDE ((FLMUNICODE)241) FINLINE FLMBOOL f_isvowel( FLMUNICODE uChar) { uChar = f_uniToLower( uChar); if( uChar == FLM_UNICODE_a || uChar == FLM_UNICODE_e || uChar == FLM_UNICODE_i || uChar == FLM_UNICODE_o || uChar == FLM_UNICODE_u || uChar == FLM_UNICODE_y) { return( TRUE); } return( FALSE); } /**************************************************************************** Desc: String constants ****************************************************************************/ #define FLM_HTTP_CONTENT_LENGTH_TAG ((const char *) "Content-Length") #define FLM_HTTP_CONTENT_TYPE_TAG ((const char *) "Content-Type") #define FLM_HTTP_USER_AGENT_STR ((const char *) "User-Agent") #define FLM_MIME_TYPE_TEXT_XML_STR ((const char *) "text/xml") /**************************************************************************** Desc: Endian macros ****************************************************************************/ FINLINE FLMUINT16 f_littleEndianToUINT16( const FLMBYTE * pucBuf) { FLMUINT16 ui16Val = 0; ui16Val |= ((FLMUINT16)pucBuf[ 1]) << 8; ui16Val |= ((FLMUINT16)pucBuf[ 0]); return( ui16Val); } FINLINE FLMUINT32 f_littleEndianToUINT32( const FLMBYTE * pucBuf) { FLMUINT32 ui32Val = 0; ui32Val |= ((FLMUINT32)pucBuf[ 3]) << 24; ui32Val |= ((FLMUINT32)pucBuf[ 2]) << 16; ui32Val |= ((FLMUINT32)pucBuf[ 1]) << 8; ui32Val |= ((FLMUINT32)pucBuf[ 0]); return( ui32Val); } FINLINE FLMUINT64 f_littleEndianToUINT64( const FLMBYTE * pucBuf) { FLMUINT64 ui64Val = 0; ui64Val |= ((FLMUINT64)pucBuf[ 7]) << 56; ui64Val |= ((FLMUINT64)pucBuf[ 6]) << 48; ui64Val |= ((FLMUINT64)pucBuf[ 5]) << 40; ui64Val |= ((FLMUINT64)pucBuf[ 4]) << 32; ui64Val |= ((FLMUINT64)pucBuf[ 3]) << 24; ui64Val |= ((FLMUINT64)pucBuf[ 2]) << 16; ui64Val |= ((FLMUINT64)pucBuf[ 1]) << 8; ui64Val |= ((FLMUINT64)pucBuf[ 0]); return( ui64Val); } FINLINE void f_UINT16ToLittleEndian( FLMUINT16 ui16Num, FLMBYTE * pucBuf) { pucBuf[ 1] = (FLMBYTE) (ui16Num >> 8); pucBuf[ 0] = (FLMBYTE) (ui16Num); } FINLINE void f_UINT32ToLittleEndian( FLMUINT32 ui32Num, FLMBYTE * pucBuf) { pucBuf[ 3] = (FLMBYTE) (ui32Num >> 24); pucBuf[ 2] = (FLMBYTE) (ui32Num >> 16); pucBuf[ 1] = (FLMBYTE) (ui32Num >> 8); pucBuf[ 0] = (FLMBYTE) (ui32Num); } FINLINE void f_UINT64ToLittleEndian( FLMUINT64 ui64Num, FLMBYTE * pucBuf) { pucBuf[ 7] = (FLMBYTE) (ui64Num >> 56); pucBuf[ 6] = (FLMBYTE) (ui64Num >> 48); pucBuf[ 5] = (FLMBYTE) (ui64Num >> 40); pucBuf[ 4] = (FLMBYTE) (ui64Num >> 32); pucBuf[ 3] = (FLMBYTE) (ui64Num >> 24); pucBuf[ 2] = (FLMBYTE) (ui64Num >> 16); pucBuf[ 1] = (FLMBYTE) (ui64Num >> 8); pucBuf[ 0] = (FLMBYTE) (ui64Num); } FINLINE FLMUINT16 f_bigEndianToUINT16( const FLMBYTE * pucBuf) { FLMUINT16 ui16Val = 0; ui16Val |= ((FLMUINT16)pucBuf[ 0]) << 8; ui16Val |= ((FLMUINT16)pucBuf[ 1]); return( ui16Val); } FINLINE FLMUINT32 f_bigEndianToUINT32( const FLMBYTE * pucBuf) { FLMUINT32 ui32Val = 0; ui32Val |= ((FLMUINT32)pucBuf[ 0]) << 24; ui32Val |= ((FLMUINT32)pucBuf[ 1]) << 16; ui32Val |= ((FLMUINT32)pucBuf[ 2]) << 8; ui32Val |= ((FLMUINT32)pucBuf[ 3]); return( ui32Val); } FINLINE FLMUINT64 f_bigEndianToUINT64( const FLMBYTE * pucBuf) { FLMUINT64 ui64Val = 0; ui64Val |= ((FLMUINT64)pucBuf[ 0]) << 56; ui64Val |= ((FLMUINT64)pucBuf[ 1]) << 48; ui64Val |= ((FLMUINT64)pucBuf[ 2]) << 40; ui64Val |= ((FLMUINT64)pucBuf[ 3]) << 32; ui64Val |= ((FLMUINT64)pucBuf[ 4]) << 24; ui64Val |= ((FLMUINT64)pucBuf[ 5]) << 16; ui64Val |= ((FLMUINT64)pucBuf[ 6]) << 8; ui64Val |= ((FLMUINT64)pucBuf[ 7]); return( ui64Val); } FINLINE FLMINT16 f_bigEndianToINT16( const FLMBYTE * pucBuf) { FLMINT16 i16Val = 0; i16Val |= ((FLMINT16)pucBuf[ 0]) << 8; i16Val |= ((FLMINT16)pucBuf[ 1]); return( i16Val); } FINLINE FLMINT32 f_bigEndianToINT32( const FLMBYTE * pucBuf) { FLMINT32 i32Val = 0; i32Val |= ((FLMINT32)pucBuf[ 0]) << 24; i32Val |= ((FLMINT32)pucBuf[ 1]) << 16; i32Val |= ((FLMINT32)pucBuf[ 2]) << 8; i32Val |= ((FLMINT32)pucBuf[ 3]); return( i32Val); } FINLINE FLMINT64 f_bigEndianToINT64( const FLMBYTE * pucBuf) { FLMINT64 i64Val = 0; i64Val |= ((FLMINT64)pucBuf[ 0]) << 56; i64Val |= ((FLMINT64)pucBuf[ 1]) << 48; i64Val |= ((FLMINT64)pucBuf[ 2]) << 40; i64Val |= ((FLMINT64)pucBuf[ 3]) << 32; i64Val |= ((FLMINT64)pucBuf[ 4]) << 24; i64Val |= ((FLMINT64)pucBuf[ 5]) << 16; i64Val |= ((FLMINT64)pucBuf[ 6]) << 8; i64Val |= ((FLMINT64)pucBuf[ 7]); return( i64Val); } FINLINE void f_UINT32ToBigEndian( FLMUINT32 ui32Num, FLMBYTE * pucBuf) { pucBuf[ 0] = (FLMBYTE) (ui32Num >> 24); pucBuf[ 1] = (FLMBYTE) (ui32Num >> 16); pucBuf[ 2] = (FLMBYTE) (ui32Num >> 8); pucBuf[ 3] = (FLMBYTE) (ui32Num); } FINLINE void f_INT32ToBigEndian( FLMINT32 i32Num, FLMBYTE * pucBuf) { pucBuf[ 0] = (FLMBYTE) (i32Num >> 24); pucBuf[ 1] = (FLMBYTE) (i32Num >> 16); pucBuf[ 2] = (FLMBYTE) (i32Num >> 8); pucBuf[ 3] = (FLMBYTE) (i32Num); } FINLINE void f_INT64ToBigEndian( FLMINT64 i64Num, FLMBYTE * pucBuf) { pucBuf[ 0] = (FLMBYTE) (i64Num >> 56); pucBuf[ 1] = (FLMBYTE) (i64Num >> 48); pucBuf[ 2] = (FLMBYTE) (i64Num >> 40); pucBuf[ 3] = (FLMBYTE) (i64Num >> 32); pucBuf[ 4] = (FLMBYTE) (i64Num >> 24); pucBuf[ 5] = (FLMBYTE) (i64Num >> 16); pucBuf[ 6] = (FLMBYTE) (i64Num >> 8); pucBuf[ 7] = (FLMBYTE) (i64Num); } FINLINE void f_UINT64ToBigEndian( FLMUINT64 ui64Num, FLMBYTE * pucBuf) { pucBuf[ 0] = (FLMBYTE) (ui64Num >> 56); pucBuf[ 1] = (FLMBYTE) (ui64Num >> 48); pucBuf[ 2] = (FLMBYTE) (ui64Num >> 40); pucBuf[ 3] = (FLMBYTE) (ui64Num >> 32); pucBuf[ 4] = (FLMBYTE) (ui64Num >> 24); pucBuf[ 5] = (FLMBYTE) (ui64Num >> 16); pucBuf[ 6] = (FLMBYTE) (ui64Num >> 8); pucBuf[ 7] = (FLMBYTE) (ui64Num); } FINLINE void f_INT16ToBigEndian( FLMINT16 i16Num, FLMBYTE * pucBuf) { pucBuf[ 0] = (FLMBYTE) (i16Num >> 8); pucBuf[ 1] = (FLMBYTE) (i16Num); } FINLINE void f_UINT16ToBigEndian( FLMUINT16 ui16Num, FLMBYTE * pucBuf) { pucBuf[ 0] = (FLMBYTE) (ui16Num >> 8); pucBuf[ 1] = (FLMBYTE) (ui16Num); } #if defined( FLM_STRICT_ALIGNMENT) || defined( FLM_BIG_ENDIAN) FINLINE FLMUINT16 FB2UW( const FLMBYTE * pucBuf) { FLMUINT16 ui16Val = 0; ui16Val |= ((FLMUINT16)pucBuf[ 1]) << 8; ui16Val |= ((FLMUINT16)pucBuf[ 0]); return( ui16Val); } FINLINE FLMUINT32 FB2UD( const FLMBYTE * pucBuf) { FLMUINT32 ui32Val = 0; ui32Val |= ((FLMUINT32)pucBuf[ 3]) << 24; ui32Val |= ((FLMUINT32)pucBuf[ 2]) << 16; ui32Val |= ((FLMUINT32)pucBuf[ 1]) << 8; ui32Val |= ((FLMUINT32)pucBuf[ 0]); return( ui32Val); } FINLINE FLMUINT64 FB2U64( const FLMBYTE * pucBuf) { FLMUINT64 ui64Val = 0; ui64Val |= ((FLMUINT64)pucBuf[ 7]) << 56; ui64Val |= ((FLMUINT64)pucBuf[ 6]) << 48; ui64Val |= ((FLMUINT64)pucBuf[ 5]) << 40; ui64Val |= ((FLMUINT64)pucBuf[ 4]) << 32; ui64Val |= ((FLMUINT64)pucBuf[ 3]) << 24; ui64Val |= ((FLMUINT64)pucBuf[ 2]) << 16; ui64Val |= ((FLMUINT64)pucBuf[ 1]) << 8; ui64Val |= ((FLMUINT64)pucBuf[ 0]); return( ui64Val); } FINLINE void UW2FBA( FLMUINT uiNum, FLMBYTE * pucBuf) { f_assert( uiNum <= FLM_MAX_UINT16); pucBuf[ 1] = (FLMBYTE) (uiNum >> 8); pucBuf[ 0] = (FLMBYTE) (uiNum); } FINLINE void UD2FBA( FLMUINT uiNum, FLMBYTE * pucBuf) { f_assert( uiNum <= FLM_MAX_UINT32); pucBuf[ 3] = (FLMBYTE) (uiNum >> 24); pucBuf[ 2] = (FLMBYTE) (uiNum >> 16); pucBuf[ 1] = (FLMBYTE) (uiNum >> 8); pucBuf[ 0] = (FLMBYTE) (uiNum); } FINLINE void U642FBA( FLMUINT64 ui64Num, FLMBYTE * pucBuf) { pucBuf[ 7] = (FLMBYTE) (ui64Num >> 56); pucBuf[ 6] = (FLMBYTE) (ui64Num >> 48); pucBuf[ 5] = (FLMBYTE) (ui64Num >> 40); pucBuf[ 4] = (FLMBYTE) (ui64Num >> 32); pucBuf[ 3] = (FLMBYTE) (ui64Num >> 24); pucBuf[ 2] = (FLMBYTE) (ui64Num >> 16); pucBuf[ 1] = (FLMBYTE) (ui64Num >> 8); pucBuf[ 0] = (FLMBYTE) (ui64Num); } #else #define FB2UW( fbp) \ (*((FLMUINT16 *)(fbp))) #define FB2UD( fbp) \ (*((FLMUINT32 *)(fbp))) #define FB2U64( fbp) \ (*((FLMUINT64 *)(fbp))) #define UW2FBA( uw, fbp) \ (*((FLMUINT16 *)(fbp)) = ((FLMUINT16) (uw))) #define UD2FBA( uw, fbp) \ (*((FLMUINT32 *)(fbp)) = ((FLMUINT32) (uw))) #define U642FBA( uw, fbp) \ (*((FLMUINT64 *)(fbp)) = ((FLMUINT64) (uw))) #endif #ifdef FLM_BIG_ENDIAN #define LO( wrd) \ (*((FLMUINT8 *)&wrd + 1)) #define HI( wrd) \ (*(FLMUINT8 *)&wrd) #else #define LO(wrd) \ (*(FLMUINT8 *)&wrd) #define HI(wrd) \ (*((FLMUINT8 *)&wrd + 1)) #endif /**************************************************************************** Desc: File path functions and macros ****************************************************************************/ #if defined( FLM_WIN) || defined( FLM_NLM) #define FWSLASH '/' #define SLASH '\\' #define SSLASH "\\" #define COLON ':' #define PERIOD '.' #define PARENT_DIR ".." #define CURRENT_DIR "." #else #ifndef FWSLASH #define FWSLASH '/' #endif #ifndef SLASH #define SLASH '/' #endif #ifndef SSLASH #define SSLASH "/" #endif #ifndef COLON #define COLON ':' #endif #ifndef PERIOD #define PERIOD '.' #endif #ifndef PARENT_DIR #define PARENT_DIR ".." #endif #ifndef CURRENT_DIR #define CURRENT_DIR "." #endif #endif FTKXPC FLMUINT FTKAPI f_getMaxFileSize( void); /**************************************************************************** Desc: CPU release and sleep functions ****************************************************************************/ FTKXPC void FTKAPI f_yieldCPU( void); FTKXPC void FTKAPI f_sleep( FLMUINT uiMilliseconds); /**************************************************************************** Desc: Time, date, timestamp functions ****************************************************************************/ typedef struct { FLMUINT16 year; FLMBYTE month; FLMBYTE day; } F_DATE; typedef struct { FLMBYTE hour; FLMBYTE minute; FLMBYTE second; FLMBYTE hundredth; } F_TIME; typedef struct { FLMUINT16 year; FLMBYTE month; FLMBYTE day; FLMBYTE hour; FLMBYTE minute; FLMBYTE second; FLMBYTE hundredth; } F_TMSTAMP; #define f_timeIsLeapYear(year) \ (((((year) & 0x03) == 0) && (((year) % 100) != 0)) || (((year) % 400) == 0)) FTKXPC void FTKAPI f_timeGetSeconds( FLMUINT * puiSeconds); FTKXPC void FTKAPI f_timeGetTimeStamp( F_TMSTAMP * pTimeStamp); FTKXPC FLMINT FTKAPI f_timeGetLocalOffset( void); FTKXPC void FTKAPI f_timeSecondsToDate( FLMUINT uiSeconds, F_TMSTAMP * pTimeStamp); FTKXPC void FTKAPI f_timeDateToSeconds( F_TMSTAMP * pTimeStamp, FLMUINT * puiSeconds); FTKXPC FLMINT FTKAPI f_timeCompareTimeStamps( F_TMSTAMP * pTimeStamp1, F_TMSTAMP * pTimeStamp2, FLMUINT flag); FINLINE FLMUINT FTKAPI f_localTimeToUTC( FLMUINT uiSeconds) { return( uiSeconds + f_timeGetLocalOffset()); } FTKXPC FLMUINT FTKAPI FLM_GET_TIMER( void); FTKXPC FLMUINT FTKAPI FLM_ELAPSED_TIME( FLMUINT uiLaterTime, FLMUINT uiEarlierTime); FTKXPC FLMUINT FTKAPI FLM_SECS_TO_TIMER_UNITS( FLMUINT uiSeconds); FTKXPC FLMUINT FTKAPI FLM_TIMER_UNITS_TO_SECS( FLMUINT uiTU); FTKXPC FLMUINT FTKAPI FLM_TIMER_UNITS_TO_MILLI( FLMUINT uiTU); FTKXPC FLMUINT FTKAPI FLM_MILLI_TO_TIMER_UNITS( FLMUINT uiMilliSeconds); FTKXPC void FTKAPI f_addElapsedTime( F_TMSTAMP * pStartTime, FLMUINT64 * pui64ElapMilli); /**************************************************************************** Desc: Quick sort ****************************************************************************/ typedef FLMINT (FTKAPI * F_SORT_COMPARE_FUNC)( void * pvBuffer, FLMUINT uiPos1, FLMUINT uiPos2); typedef void (FTKAPI * F_SORT_SWAP_FUNC)( void * pvBuffer, FLMUINT uiPos1, FLMUINT uiPos2); FTKXPC FLMINT FTKAPI f_qsortUINTCompare( void * pvBuffer, FLMUINT uiPos1, FLMUINT uiPos2); FTKXPC void FTKAPI f_qsortUINTSwap( void * pvBuffer, FLMUINT uiPos1, FLMUINT uiPos2); FTKXPC void FTKAPI f_qsort( void * pvBuffer, FLMUINT uiLowerBounds, FLMUINT uiUpperBounds, F_SORT_COMPARE_FUNC fnCompare, F_SORT_SWAP_FUNC fnSwap); /**************************************************************************** Desc: Environment ****************************************************************************/ FTKXPC void FTKAPI f_getenv( const char * pszKey, FLMBYTE * pszBuffer, FLMUINT uiBufferSize, FLMUINT * puiValueLen = NULL); /**************************************************************************** Desc: f_sprintf ****************************************************************************/ FTKXPC FLMINT FTKAPI f_vsprintf( char * pszDestStr, const char * pszFormat, f_va_list * args); FTKXPC FLMINT FTKAPI f_sprintf( char * pszDestStr, const char * pszFormat, ...); FTKEXP FLMINT FTKAPI f_printf( const char * pszFormat, ...); FTKXPC FLMINT FTKAPI f_errprintf( const char * pszFormat, ...); FTKEXP FLMINT FTKAPI f_printf( IF_PrintfClient * pClient, const char * pszFormat, ...); FTKEXP FLMINT FTKAPI f_vprintf( IF_PrintfClient * pClient, const char * pszFormat, f_va_list * args); FTKEXP RCODE FTKAPI f_printf( IF_OStream * pOStream, const char * pszFormatStr, ...); FTKEXP RCODE FTKAPI f_vprintf( IF_OStream * pOStream, const char * pszFormatStr, ...); /**************************************************************************** Desc: Memory copying, moving, setting ****************************************************************************/ FTKXPC void * FTKAPI f_memcpy( void * pvDest, const void * pvSrc, FLMSIZET uiLength); FTKXPC void * FTKAPI f_memmove( void * pvDest, const void * pvSrc, FLMSIZET uiLength); FTKXPC void * FTKAPI f_memset( void * pvDest, unsigned char ucByte, FLMSIZET uiLength); FTKXPC FLMINT FTKAPI f_memcmp( const void * pvStr1, const void * pvStr2, FLMSIZET uiLength); FTKXPC char * FTKAPI f_strcat( char * pszDest, const char * pszSrc); FTKXPC char * FTKAPI f_strncat( char * pszDest, const char * pszSrc, FLMSIZET uiLength); FTKXPC char * FTKAPI f_strchr( const char * pszStr, unsigned char ucByte); FTKXPC char * FTKAPI f_strrchr( const char * pszStr, unsigned char ucByte); FTKXPC char * FTKAPI f_strstr( const char * pszStr, const char * pszSearch); FTKXPC char * FTKAPI f_strupr( char * pszStr); FTKXPC FLMINT FTKAPI f_strcmp( const char * pszStr1, const char * pszStr2); FTKXPC FLMINT FTKAPI f_strncmp( const char * pszStr1, const char * pszStr2, FLMSIZET uiLength); FTKXPC FLMINT FTKAPI f_stricmp( const char * pszStr1, const char * pszStr2); FTKXPC FLMINT FTKAPI f_strnicmp( const char * pszStr1, const char * pszStr2, FLMSIZET uiLength); FTKXPC char * FTKAPI f_strcpy( char * pszDest, const char * pszSrc); FTKXPC char * FTKAPI f_strncpy( char * pszDest, const char * pszSrc, FLMSIZET uiLength); FTKXPC FLMUINT FTKAPI f_strlen( const char * pszStr); FTKXPC RCODE FTKAPI f_strdup( const char * pszSrc, char ** ppszDup); FTKXPC RCODE FTKAPI f_getCharFromUTF8Buf( const FLMBYTE ** ppucBuf, const FLMBYTE * pucEnd, FLMUNICODE * puChar); FTKXPC RCODE FTKAPI f_uni2UTF8( FLMUNICODE uChar, FLMBYTE * pucBuf, FLMUINT * puiBufSize); FTKXPC RCODE FTKAPI f_getUTF8Length( const FLMBYTE * pucBuf, FLMUINT uiBufLen, FLMUINT * puiBytes, FLMUINT * puiChars); FTKXPC RCODE FTKAPI f_getUTF8CharFromUTF8Buf( FLMBYTE ** ppucBuf, FLMBYTE * pucEnd, FLMBYTE * pucDestBuf, FLMUINT * puiLen); FTKXPC RCODE FTKAPI f_unicode2UTF8( FLMUNICODE * puzStr, FLMUINT uiStrLen, FLMBYTE * pucBuf, FLMUINT * puiBufLength); FTKXPC FLMBYTE FTKAPI f_getBase24DigitChar( FLMBYTE ucValue); FTKXPC RCODE FTKAPI f_stripCRLF( const FLMBYTE * pucSourceBuf, FLMUINT uiSourceLength, F_DynaBuf * pDestBuf); #define shiftN(data,size,distance) \ f_memmove((FLMBYTE *)(data) + (FLMINT)(distance), \ (FLMBYTE *)(data), (unsigned)(size)) /*************************************************************************** Desc: ***************************************************************************/ flminterface FTKEXP IF_PrintfClient : public F_Object { virtual FLMINT FTKAPI outputChar( char cChar) = 0; virtual FLMINT FTKAPI outputChar( char cChar, FLMUINT uiCount) = 0; virtual FLMINT FTKAPI outputStr( const char * pszStr, FLMUINT uiLen) = 0; virtual FLMINT FTKAPI colorFormatter( char cFormatChar, eColorType eColor, FLMUINT uiFlags) = 0; }; FTKXPC RCODE FTKAPI FlmAllocStdoutPrintfClient( IF_PrintfClient ** ppClient); FTKXPC RCODE FTKAPI FlmAllocStderrPrintfClient( IF_PrintfClient ** ppClient); /**************************************************************************** Desc: XML ****************************************************************************/ flminterface FTKEXP IF_XML : public F_Object { public: virtual FLMBOOL FTKAPI isPubidChar( FLMUNICODE uChar) = 0; virtual FLMBOOL FTKAPI isQuoteChar( FLMUNICODE uChar) = 0; virtual FLMBOOL FTKAPI isWhitespace( FLMUNICODE uChar) = 0; virtual FLMBOOL FTKAPI isExtender( FLMUNICODE uChar) = 0; virtual FLMBOOL FTKAPI isCombiningChar( FLMUNICODE uChar) = 0; virtual FLMBOOL FTKAPI isNameChar( FLMUNICODE uChar) = 0; virtual FLMBOOL FTKAPI isNCNameChar( FLMUNICODE uChar) = 0; virtual FLMBOOL FTKAPI isIdeographic( FLMUNICODE uChar) = 0; virtual FLMBOOL FTKAPI isBaseChar( FLMUNICODE uChar) = 0; virtual FLMBOOL FTKAPI isDigit( FLMUNICODE uChar) = 0; virtual FLMBOOL FTKAPI isLetter( FLMUNICODE uChar) = 0; virtual FLMBOOL FTKAPI isNameValid( FLMUNICODE * puzName, FLMBYTE * pszName) = 0; }; FTKXPC RCODE FTKAPI FlmGetXMLObject( IF_XML ** ppXmlObject); /**************************************************************************** Desc: Name table ****************************************************************************/ flminterface FTKEXP IF_NameTable : public F_Object { virtual void FTKAPI clearTable( FLMUINT uiPoolBlockSize) = 0; virtual RCODE FTKAPI getNextTagTypeAndNumOrder( FLMUINT uiType, FLMUINT * puiNextPos, FLMUNICODE * puzTagName = NULL, char * pszTagName = NULL, FLMUINT uiNameBufSize = 0, FLMUINT * puiTagNum = NULL, FLMUINT * puiDataType = NULL, FLMUNICODE * puzNamespace = NULL, FLMUINT uiNamespaceBufSize = 0, FLMBOOL bTruncatedNamesOk = TRUE) = 0; virtual RCODE FTKAPI getNextTagTypeAndNameOrder( FLMUINT uiType, FLMUINT * puiNextPos, FLMUNICODE * puzTagName = NULL, char * pszTagName = NULL, FLMUINT uiNameBufSize = 0, FLMUINT * puiTagNum = NULL, FLMUINT * puiDataType = NULL, FLMUNICODE * puzNamespace = NULL, FLMUINT uiNamespaceBufSize = 0, FLMBOOL bTruncatedNamesOk = TRUE) = 0; virtual RCODE FTKAPI getFromTagTypeAndName( FLMUINT uiType, const FLMUNICODE * puzTagName, const char * pszTagName, FLMBOOL bMatchNamespace, const FLMUNICODE * puzNamespace = NULL, FLMUINT * puiTagNum = NULL, FLMUINT * puiDataType = NULL) = 0; virtual RCODE FTKAPI getFromTagTypeAndNum( FLMUINT uiType, FLMUINT uiTagNum, FLMUNICODE * puzTagName = NULL, char * pszTagName = NULL, FLMUINT * puiNameBufSize = NULL, FLMUINT * puiDataType = NULL, FLMUNICODE * puzNamespace = NULL, char * pszNamespace = NULL, FLMUINT * puiNamespaceBufSize = NULL, FLMBOOL bTruncatedNamesOk = TRUE) = 0; virtual RCODE FTKAPI addTag( FLMUINT uiType, FLMUNICODE * puzTagName, const char * pszTagName, FLMUINT uiTagNum, FLMUINT uiDataType = 0, FLMUNICODE * puzNamespace = NULL, FLMBOOL bCheckDuplicates = TRUE) = 0; virtual void FTKAPI removeTag( FLMUINT uiType, FLMUINT uiTagNum) = 0; virtual RCODE FTKAPI cloneNameTable( IF_NameTable ** ppNewNameTable) = 0; }; /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_DeleteStatus : public F_Object { virtual RCODE FTKAPI reportDelete( FLMUINT uiBlocksDeleted, FLMUINT uiBlockSize) = 0; }; /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_Relocator : public F_Object { virtual void FTKAPI relocate( void * pvOldAlloc, void * pvNewAlloc) = 0; virtual FLMBOOL FTKAPI canRelocate( void * pvOldAlloc) = 0; }; /**************************************************************************** Desc: ****************************************************************************/ typedef void (FTKAPI * F_ALLOC_INIT_FUNC)( void * pvAlloc, FLMUINT uiSize); /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_SlabManager : public F_Object { virtual RCODE FTKAPI setup( FLMUINT uiPreallocSize) = 0; virtual RCODE FTKAPI allocSlab( void ** ppSlab) = 0; virtual void FTKAPI freeSlab( void ** ppSlab) = 0; virtual RCODE FTKAPI resize( FLMUINT uiNumBytes, FLMBOOL bPreallocate, FLMUINT * puiActualSize = NULL) = 0; virtual void FTKAPI incrementTotalBytesAllocated( FLMUINT uiCount) = 0; virtual void FTKAPI decrementTotalBytesAllocated( FLMUINT uiCount) = 0; virtual FLMUINT FTKAPI getSlabSize( void) = 0; virtual FLMUINT FTKAPI getTotalSlabs( void) = 0; virtual FLMUINT FTKAPI totalBytesAllocated( void) = 0; virtual FLMUINT FTKAPI getTotalSlabBytesAllocated( void) = 0; virtual FLMUINT FTKAPI availSlabs( void) = 0; }; FTKXPC RCODE FTKAPI FlmAllocSlabManager( IF_SlabManager ** ppSlabManager); /**************************************************************************** Desc: Class to provide an efficient means of providing many allocations of a fixed size. ****************************************************************************/ flminterface FTKEXP IF_FixedAlloc : public F_Object { virtual RCODE FTKAPI setup( FLMBOOL bMultiThreaded, IF_SlabManager * pSlabManager, IF_Relocator * pDefaultRelocator, FLMUINT uiCellSize, FLM_SLAB_USAGE * pUsageStats, FLMUINT * puiTotalBytesAllocated) = 0; virtual void * FTKAPI allocCell( IF_Relocator * pRelocator, void * pvInitialData, FLMUINT uiDataSize) = 0; virtual void * FTKAPI allocCell( IF_Relocator * pRelocator, F_ALLOC_INIT_FUNC fnAllocInit) = 0; virtual void FTKAPI freeCell( void * ptr) = 0; virtual void FTKAPI freeUnused( void) = 0; virtual void FTKAPI freeAll( void) = 0; virtual FLMUINT FTKAPI getCellSize( void) = 0; virtual void FTKAPI defragmentMemory( void) = 0; }; FTKXPC RCODE FTKAPI FlmAllocFixedAllocator( IF_FixedAlloc ** ppFixedAllocator); /**************************************************************************** Desc: ****************************************************************************/ flminterface IF_BlockAlloc : public F_Object { virtual RCODE FTKAPI setup( FLMBOOL bMultiThreaded, IF_SlabManager * pSlabManager, IF_Relocator * pRelocator, FLMUINT uiBlockSize, FLM_SLAB_USAGE * pUsageStats, FLMUINT * puiTotalBytesAllocated) = 0; virtual RCODE FTKAPI allocBlock( void ** ppvBlock) = 0; virtual void FTKAPI freeBlock( void ** ppvBlock) = 0; virtual void FTKAPI freeUnused( void) = 0; virtual void FTKAPI freeAll( void) = 0; virtual void FTKAPI defragmentMemory( void) = 0; }; FTKXPC RCODE FTKAPI FlmAllocBlockAllocator( IF_BlockAlloc ** ppBlockAllocator); /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_BufferAlloc : public F_Object { virtual RCODE FTKAPI setup( FLMBOOL bMultiThreaded, IF_SlabManager * pSlabManager, IF_Relocator * pDefaultRelocator, FLM_SLAB_USAGE * pUsageStats, FLMUINT * puiTotalBytesAllocated) = 0; virtual RCODE FTKAPI allocBuf( IF_Relocator * pRelocator, FLMUINT uiSize, void * pvInitialData, FLMUINT uiDataSize, FLMBYTE ** ppucBuffer, FLMBOOL * pbAllocatedOnHeap = NULL) = 0; virtual RCODE FTKAPI allocBuf( IF_Relocator * pRelocator, FLMUINT uiSize, F_ALLOC_INIT_FUNC fnAllocInit, FLMBYTE ** ppucBuffer, FLMBOOL * pbAllocatedOnHeap = NULL) = 0; virtual RCODE FTKAPI reallocBuf( IF_Relocator * pRelocator, FLMUINT uiOldSize, FLMUINT uiNewSize, void * pvInitialData, FLMUINT uiDataSize, FLMBYTE ** ppucBuffer, FLMBOOL * pbAllocatedOnHeap = NULL) = 0; virtual void FTKAPI freeBuf( FLMUINT uiSize, FLMBYTE ** ppucBuffer) = 0; virtual FLMUINT FTKAPI getTrueSize( FLMUINT uiSize, FLMBYTE * pucBuffer) = 0; virtual FLMUINT FTKAPI getMaxCellSize( void) = 0; virtual void FTKAPI defragmentMemory( void) = 0; }; FTKXPC RCODE FTKAPI FlmAllocBufferAllocator( IF_BufferAlloc ** ppBufferAllocator); /**************************************************************************** Desc: ****************************************************************************/ flminterface FTKEXP IF_MultiAlloc : public F_Object { virtual RCODE FTKAPI setup( FLMBOOL bMultiThreaded, IF_SlabManager * pSlabManager, IF_Relocator * pDefaultRelocator, FLMUINT * puiCellSizes, FLM_SLAB_USAGE * pUsageStats, FLMUINT * puiTotalBytesAllocated) = 0; virtual RCODE FTKAPI allocBuf( IF_Relocator * pRelocator, FLMUINT uiSize, FLMBYTE ** ppucBuffer) = 0; virtual RCODE FTKAPI allocBuf( IF_Relocator * pRelocator, FLMUINT uiSize, F_ALLOC_INIT_FUNC fnAllocInit, FLMBYTE ** ppucBuffer) = 0; virtual RCODE FTKAPI reallocBuf( IF_Relocator * pRelocator, FLMUINT uiNewSize, FLMBYTE ** ppucBuffer) = 0; virtual void FTKAPI freeBuf( FLMBYTE ** ppucBuffer) = 0; virtual void FTKAPI defragmentMemory( void) = 0; virtual FLMUINT FTKAPI getTrueSize( FLMBYTE * pucBuffer) = 0; }; FTKXPC RCODE FTKAPI FlmAllocMultiAllocator( IF_MultiAlloc ** ppMultiAllocator); /**************************************************************************** Desc: Block ****************************************************************************/ flminterface FTKEXP IF_Block : public F_Object { }; /**************************************************************************** Desc: Block manager ****************************************************************************/ flminterface FTKEXP IF_BlockMgr : public F_Object { virtual FLMUINT FTKAPI getBlockSize( void) = 0; virtual RCODE FTKAPI getBlock( FLMUINT32 ui32BlockAddr, IF_Block ** ppBlock, FLMBYTE ** ppucBlock = NULL) = 0; virtual RCODE FTKAPI createBlock( IF_Block ** ppBlock, FLMBYTE ** ppucBlock = NULL, FLMUINT32 * pui32BlockAddr = NULL) = 0; virtual RCODE FTKAPI freeBlock( IF_Block ** ppBlock, FLMBYTE ** ppucBlock = NULL) = 0; virtual RCODE FTKAPI prepareForUpdate( IF_Block ** ppBlock, FLMBYTE ** ppucBlock = NULL) = 0; }; FTKXPC RCODE FTKAPI FlmAllocBlockMgr( FLMUINT uiBlockSize, IF_BlockMgr ** ppBlockMgr); /**************************************************************************** Desc: ****************************************************************************/ enum BTREE_ERR_TYPE { NO_ERR = 0, BT_HEADER, KEY_ORDER, DUPLICATE_KEYS, INFINITY_MARKER, CHILD_BLOCK_ADDRESS, GET_BLOCK_FAILED, MISSING_OVERALL_DATA_LENGTH, NOT_DATA_ONLY_BLOCK, BAD_DO_BLOCK_LENGTHS, BAD_COUNTS, CATASTROPHIC_FAILURE = 999 }; /**************************************************************************** Desc: ****************************************************************************/ typedef struct { FLMUINT uiKeyCnt; FLMUINT uiFirstKeyCnt; FLMUINT uiBlockCnt; FLMUINT uiBytesUsed; FLMUINT uiDOBlockCnt; FLMUINT uiDOBytesUsed; } BTREE_LEVEL_STATS; /**************************************************************************** Desc: ****************************************************************************/ typedef struct { FLMUINT uiBlockAddr; FLMUINT uiBlockSize; FLMUINT uiBlocksChecked; FLMUINT uiAvgFreeSpace; FLMUINT uiLevels; FLMUINT uiNumKeys; FLMUINT64 ui64FreeSpace; #define F_BTREE_MAX_LEVELS 8 BTREE_LEVEL_STATS LevelStats[ F_BTREE_MAX_LEVELS]; char szMsg[ 64]; BTREE_ERR_TYPE type; } BTREE_ERR_INFO; /**************************************************************************** Desc: B-Tree ****************************************************************************/ flminterface FTKEXP IF_BTree : public F_Object { virtual RCODE FTKAPI btCreate( FLMUINT16 ui16BtreeId, FLMBOOL bCounts, FLMBOOL bData, FLMUINT32 * pui32RootBlockAddr, IF_ResultSetCompare * pCompare = NULL) = 0; virtual RCODE FTKAPI btOpen( FLMUINT32 ui32RootBlockAddr, FLMBOOL bCounts, FLMBOOL bData, IF_ResultSetCompare * pCompare = NULL) = 0; virtual void FTKAPI btClose( void) = 0; virtual RCODE FTKAPI btDeleteTree( IF_DeleteStatus * ifpDeleteStatus = NULL) = 0; virtual RCODE FTKAPI btGetBlockChains( FLMUINT * puiBlockChains, FLMUINT * puiNumLevels) = 0; virtual RCODE FTKAPI btRemoveEntry( const FLMBYTE * pucKey, FLMUINT uiKeyBufSize, FLMUINT uiKeyLen) = 0; virtual RCODE FTKAPI btInsertEntry( const FLMBYTE * pucKey, FLMUINT uiKeyBufSize, FLMUINT uiKeyLen, const FLMBYTE * pucData, FLMUINT uiDataLen, FLMBOOL bFirst, FLMBOOL bLast, FLMUINT32 * pui32BlockAddr = NULL, FLMUINT * puiOffsetIndex = NULL) = 0; virtual RCODE FTKAPI btReplaceEntry( const FLMBYTE * pucKey, FLMUINT uiKeyBufSize, FLMUINT uiKeyLen, const FLMBYTE * pucData, FLMUINT uiDataLen, FLMBOOL bFirst, FLMBOOL bLast, FLMBOOL bTruncate = TRUE, FLMUINT32 * pui32BlockAddr = NULL, FLMUINT * puiOffsetIndex = NULL) = 0; virtual RCODE FTKAPI btLocateEntry( FLMBYTE * pucKey, FLMUINT uiKeyBufSize, FLMUINT * puiKeyLen, FLMUINT uiMatch, FLMUINT * puiPosition = NULL, FLMUINT * puiDataLength = NULL, FLMUINT32 * pui32BlockAddr = NULL, FLMUINT * puiOffsetIndex = NULL) = 0; virtual RCODE FTKAPI btGetEntry( FLMBYTE * pucKey, FLMUINT uiKeyLen, FLMBYTE * pucData, FLMUINT uiDataBufSize, FLMUINT * puiDataLen) = 0; virtual RCODE FTKAPI btNextEntry( FLMBYTE * pucKey, FLMUINT uiKeyBufSize, FLMUINT * puiKeyLen, FLMUINT * puiDataLength = NULL, FLMUINT32 * pui32BlockAddr = NULL, FLMUINT * puiOffsetIndex = NULL) = 0; virtual RCODE FTKAPI btPrevEntry( FLMBYTE * pucKey, FLMUINT uiKeyBufSize, FLMUINT * puiKeyLen, FLMUINT * puiDataLength = NULL, FLMUINT32 * pui32BlockAddr = NULL, FLMUINT * puiOffsetIndex = NULL) = 0; virtual RCODE FTKAPI btFirstEntry( FLMBYTE * pucKey, FLMUINT uiKeyBufSize, FLMUINT * puiKeyLen, FLMUINT * puiDataLength = NULL, FLMUINT32 * pui32BlockAddr = NULL, FLMUINT * puiOffsetIndex = NULL) = 0; virtual RCODE FTKAPI btLastEntry( FLMBYTE * pucKey, FLMUINT uiKeyBufSize, FLMUINT * puiKeyLen, FLMUINT * puiDataLength = NULL, FLMUINT32 * pui32BlockAddr = NULL, FLMUINT * puiOffsetIndex = NULL) = 0; virtual RCODE FTKAPI btSetReadPosition( FLMBYTE * pucKey, FLMUINT uiKeyLen, FLMUINT uiPosition) = 0; virtual RCODE FTKAPI btGetReadPosition( FLMUINT * puiPosition) = 0; virtual RCODE FTKAPI btPositionTo( FLMUINT uiPosition, FLMBYTE * pucKey, FLMUINT uiKeyBufSize, FLMUINT * puiKeyLen) = 0; virtual RCODE FTKAPI btGetPosition( FLMUINT * puiPosition) = 0; virtual RCODE FTKAPI btRewind( void) = 0; // virtual RCODE FTKAPI btComputeCounts( // IF_BTree * pUntilBtree, // FLMUINT * puiBlockCount, // FLMUINT * puiKeyCount, // FLMBOOL * pbTotalsEstimated, // FLMUINT uiAvgBlockFullness) = 0; virtual FLMBOOL FTKAPI btHasCounts( void) = 0; virtual FLMBOOL FTKAPI btHasData( void) = 0; virtual void FTKAPI btResetBtree( void) = 0; virtual FLMUINT32 FTKAPI getRootBlockAddr( void) = 0; virtual RCODE btCheck( BTREE_ERR_INFO * pErrInfo) = 0; }; FTKXPC RCODE FTKAPI FlmAllocBTree( IF_BlockMgr * pBlockMgr, IF_BTree ** ppBtree); /**************************************************************************** Desc: This class is used to do pool memory allocations. ****************************************************************************/ /// Header for blocks in a memory pool. This structure is at the head of each block that belongs to a pool of /// memory. typedef struct PoolMemoryBlock { PoolMemoryBlock * pPrevBlock; ///< Points to the previous memory block in the memory pool. FLMUINT uiBlockSize; ///< Total size of the memory block. FLMUINT uiFreeOffset; ///< Offset in block where next allocation should be made. FLMUINT uiFreeSize; ///< Amount of free memory left in block - from uiFreeOfs. } PoolMemoryBlock; /// Pool memory manager. This structure is used to keep track of a pool /// of memory blocks that are used for pool memory allocation. typedef struct { FLMUINT uiAllocBytes; ///< Total number of bytes requested from ///< GedPoolAlloc and GedPoolCalloc calls FLMUINT uiCount; ///< Number of frees and resets performed on ///< the pool } POOL_STATS; class FTKEXP F_Pool : public F_Object { public: F_Pool() { m_uiBytesAllocated = 0; m_pLastBlock = NULL; m_pPoolStats = NULL; m_uiBlockSize = 0; } virtual ~F_Pool(); /// Initialize memory pool. /// \ingroup pool FINLINE void FTKAPI poolInit( FLMUINT uiBlockSize ///< Default block size for the memory pool. ) { m_uiBlockSize = uiBlockSize; } void smartPoolInit( POOL_STATS * pPoolStats); /// Allocate memory from a memory pool. /// \ingroup pool RCODE FTKAPI poolAlloc( FLMUINT uiSize, ///< Requested allocation size (in bytes). void ** ppvPtr ///< Pointer to the allocation ); /// Allocate memory from a memory pool and initialize memory to zeroes. /// \ingroup pool RCODE FTKAPI poolCalloc( FLMUINT uiSize, ///< Requested allocation size (in bytes). void ** ppvPtr); ///< Pointer to the allocation /// Free all memory blocks in a memory pool. /// \ingroup pool void FTKAPI poolFree( void); /// Reset a memory pool back to a mark.\ Free all memory blocks allocated after the mark. /// \ingroup pool void FTKAPI poolReset( void * pvMark = NULL, ///< Mark that was obtained from GedPoolMark(). FLMBOOL bReduceFirstBlock = FALSE); /// Obtain a mark in a memory pool.\ Returned mark remembers a location in the /// pool which can later be passed to poolReset() to free all memory that was /// allocated after the mark. /// \ingroup pool FINLINE void * FTKAPI poolMark( void) { return (void *)(m_pLastBlock ? (FLMBYTE *)m_pLastBlock + m_pLastBlock->uiFreeOffset : NULL); } FINLINE FLMUINT FTKAPI getBlockSize( void) { return( m_uiBlockSize); } FINLINE FLMUINT FTKAPI getBytesAllocated( void) { return( m_uiBytesAllocated); } private: FINLINE void updateSmartPoolStats( void) { if (m_uiBytesAllocated) { if( (m_pPoolStats->uiAllocBytes + m_uiBytesAllocated) >= 0xFFFF0000) { m_pPoolStats->uiAllocBytes = (m_pPoolStats->uiAllocBytes / m_pPoolStats->uiCount) * 100; m_pPoolStats->uiCount = 100; } else { m_pPoolStats->uiAllocBytes += m_uiBytesAllocated; m_pPoolStats->uiCount++; } m_uiBytesAllocated = 0; } } FINLINE void setInitialSmartPoolBlockSize( void) { // Determine starting block size: // 1) average of bytes allocated / # of frees/resets (average size needed) // 2) add 10% - to minimize extra allocs m_uiBlockSize = (m_pPoolStats->uiAllocBytes / m_pPoolStats->uiCount); m_uiBlockSize += (m_uiBlockSize / 10); if (m_uiBlockSize < 512) { m_uiBlockSize = 512; } } void freeToMark( void * pvMark); PoolMemoryBlock * m_pLastBlock; FLMUINT m_uiBlockSize; FLMUINT m_uiBytesAllocated; POOL_STATS * m_pPoolStats; }; /**************************************************************************** Desc: *****************************************************************************/ class FTKEXP F_DynaBuf : public F_Object { public: F_DynaBuf( FLMBYTE * pucBuffer = NULL, FLMUINT uiBufferSize = 0) { m_pucBuffer = pucBuffer; m_uiBufferSize = uiBufferSize; m_uiOffset = 0; m_bAllocatedBuffer = FALSE; } virtual ~F_DynaBuf() { if( m_bAllocatedBuffer) { f_free( &m_pucBuffer); } } FINLINE void FTKAPI truncateData( FLMUINT uiSize) { if( uiSize < m_uiOffset) { m_uiOffset = uiSize; } } FINLINE RCODE FTKAPI allocSpace( FLMUINT uiSize, void ** ppvPtr) { RCODE rc = NE_FLM_OK; if( m_uiOffset + uiSize >= m_uiBufferSize) { if( RC_BAD( rc = resizeBuffer( m_uiOffset + uiSize + 512))) { goto Exit; } } *ppvPtr = &m_pucBuffer[ m_uiOffset]; m_uiOffset += uiSize; Exit: return( rc); } FINLINE RCODE FTKAPI appendByte( FLMBYTE ucChar) { RCODE rc = NE_FLM_OK; FLMBYTE * pucTmp = NULL; if( RC_BAD( rc = allocSpace( 1, (void **)&pucTmp))) { goto Exit; } *pucTmp = ucChar; Exit: return( rc); } FINLINE RCODE FTKAPI appendUniChar( FLMUNICODE uChar) { RCODE rc = NE_FLM_OK; FLMUNICODE * puTmp = NULL; if( RC_BAD( rc = allocSpace( sizeof( FLMUNICODE), (void **)&puTmp))) { goto Exit; } *puTmp = uChar; Exit: return( rc); } FINLINE RCODE FTKAPI appendData( const void * pvData, FLMUINT uiSize) { RCODE rc = NE_FLM_OK; void * pvTmp = NULL; if( RC_BAD( rc = allocSpace( uiSize, &pvTmp))) { goto Exit; } if( uiSize == 1) { *((FLMBYTE *)pvTmp) = *((FLMBYTE *)pvData); } else { f_memcpy( pvTmp, pvData, uiSize); } Exit: return( rc); } FINLINE RCODE FTKAPI appendString( const char * pszString) { RCODE rc = NE_FLM_OK; void * pvTmp = NULL; FLMUINT uiSize = f_strlen( pszString); if( RC_BAD( rc = allocSpace( uiSize, &pvTmp))) { goto Exit; } f_memcpy( pvTmp, pszString, uiSize); Exit: return( rc); } FINLINE FLMBYTE * FTKAPI getBufferPtr( void) { return( m_pucBuffer); } FINLINE FLMUNICODE * FTKAPI getUnicodePtr( void) { if( m_uiOffset >= sizeof( FLMUNICODE)) { return( (FLMUNICODE *)m_pucBuffer); } return( NULL); } FINLINE FLMUINT FTKAPI getUnicodeLength( void) { if( m_uiOffset <= sizeof( FLMUNICODE)) { return( 0); } return( (m_uiOffset >> 1) - 1); } FINLINE FLMUINT FTKAPI getDataLength( void) { return( m_uiOffset); } FINLINE RCODE FTKAPI copyFromBuffer( F_DynaBuf * pSource) { RCODE rc = NE_FLM_OK; if( RC_BAD( rc = resizeBuffer( pSource->m_uiBufferSize))) { goto Exit; } if( (m_uiOffset = pSource->m_uiOffset) != 0) { f_memcpy( m_pucBuffer, pSource->m_pucBuffer, pSource->m_uiOffset); } Exit: return( rc); } private: FINLINE RCODE resizeBuffer( FLMUINT uiNewSize) { RCODE rc = NE_FLM_OK; if( !m_bAllocatedBuffer) { if( uiNewSize > m_uiBufferSize) { FLMBYTE * pucOriginalBuf = m_pucBuffer; if( RC_BAD( rc = f_alloc( uiNewSize, &m_pucBuffer))) { m_pucBuffer = pucOriginalBuf; goto Exit; } m_bAllocatedBuffer = TRUE; if( m_uiOffset) { f_memcpy( m_pucBuffer, pucOriginalBuf, m_uiOffset); } } } else { if( RC_BAD( rc = f_realloc( uiNewSize, &m_pucBuffer))) { goto Exit; } if( uiNewSize < m_uiOffset) { m_uiOffset = uiNewSize; } } m_uiBufferSize = uiNewSize; Exit: return( rc); } FLMBOOL m_bAllocatedBuffer; FLMBYTE * m_pucBuffer; FLMUINT m_uiBufferSize; FLMUINT m_uiOffset; }; /**************************************************************************** Desc: ****************************************************************************/ class FTKEXP F_Vector : public F_Object { public: F_Vector() { m_pElementArray = NULL; m_uiArraySize = 0; } virtual ~F_Vector() { if( m_pElementArray) { f_free( &m_pElementArray); } } RCODE FTKAPI setElementAt( void * pData, FLMUINT uiIndex); void * FTKAPI getElementAt( FLMUINT uiIndex); private: void ** m_pElementArray; FLMUINT m_uiArraySize; }; /**************************************************************************** Desc: A class to safely build up a string accumulation, without worrying about buffer overflows. ****************************************************************************/ class FTKEXP F_StringAcc : public F_Object { public: F_StringAcc() { commonInit(); } F_StringAcc( char * pszStr) { commonInit(); appendTEXT( pszStr); } F_StringAcc( FLMBYTE * pszStr) { commonInit(); appendTEXT( pszStr); } virtual ~F_StringAcc() { if( m_pszVal) { f_free( &m_pszVal); } } FINLINE void FTKAPI clear( void) { if( m_pszVal) { m_pszVal[ 0] = 0; } m_szQuickBuf[ 0] = 0; m_uiValStrLen = 0; } FINLINE FLMUINT FTKAPI getLength( void) { return( m_uiValStrLen); } RCODE FTKAPI printf( const char * pszFormatString, ...); RCODE FTKAPI appendCHAR( char ucChar, FLMUINT uiHowMany = 1); RCODE FTKAPI appendTEXT( const FLMBYTE * pszVal); RCODE FTKAPI appendTEXT( const char * pszVal) { return( appendTEXT( (FLMBYTE*)pszVal)); } RCODE FTKAPI appendf( const char * pszFormatString, ...); FINLINE const char * FTKAPI getTEXT( void) { if( m_bQuickBufActive) { return( m_szQuickBuf); } else if( m_pszVal) { return( m_pszVal); } else { return( ""); } } private: void commonInit( void) { m_pszVal = NULL; m_uiValStrLen = 0; m_szQuickBuf[ 0] = 0; m_bQuickBufActive = FALSE; } RCODE formatNumber( FLMUINT uiNum, FLMUINT uiBase); char m_szQuickBuf[ 128]; FLMBOOL m_bQuickBufActive; char * m_pszVal; FLMUINT m_uiBytesAllocatedForPszVal; FLMUINT m_uiValStrLen; }; /**************************************************************************** Desc: ****************************************************************************/ typedef struct { F_ListItem * pPrevItem; F_ListItem * pNextItem; FLMUINT uiListCount; } F_ListNode; #define FLM_ALL_LISTS 0xFFFF /**************************************************************************** Desc: ****************************************************************************/ class FTKEXP F_ListItem : public F_Object { public: F_ListItem() { m_pListManager = NULL; m_pListNodes = NULL; m_uiListNodeCnt = 0; m_bInList = FALSE; } virtual ~F_ListItem(); void setup( F_ListManager * pListMgr, F_ListNode * pListNodes, FLMUINT uiListNodeCnt); void removeFromList( FLMUINT uiList = 0); FINLINE F_ListItem * getNextListItem( FLMUINT uiList = 0) { return( m_pListNodes[ uiList].pNextItem); } FINLINE F_ListItem * getPrevListItem( FLMUINT uiList = 0) { return( m_pListNodes[ uiList].pPrevItem); } FINLINE F_ListItem * setNextListItem( FLMUINT uiList, F_ListItem * pNewNext) { F_ListNode * pListNode; pListNode = &m_pListNodes[ uiList]; pListNode->pNextItem = pNewNext; return( pNewNext); } FINLINE F_ListItem * setPrevListItem( FLMUINT uiList, F_ListItem * pNewPrev) { F_ListNode * pListNode; pListNode = &m_pListNodes[ uiList]; pListNode->pPrevItem = pNewPrev; return( pNewPrev); } private: F_ListManager * m_pListManager; FLMUINT m_uiListNodeCnt; F_ListNode * m_pListNodes; FLMBOOL m_bInList; friend class F_ListManager; }; /**************************************************************************** Desc: ****************************************************************************/ class FTKEXP F_ListManager : public F_Object { public: F_ListManager( F_ListNode * pListNodes, FLMUINT uiListNodeCnt) { flmAssert( pListNodes && uiListNodeCnt ); m_uiListNodeCnt = uiListNodeCnt; m_pListNodes = pListNodes; f_memset( pListNodes, 0, sizeof( F_ListNode) * uiListNodeCnt ); } virtual ~F_ListManager() { clearList( FLM_ALL_LISTS); } void insertFirst( FLMUINT uiList, F_ListItem * pNewFirstItem); void insertLast( FLMUINT uiList, F_ListItem * pNewLastItem); F_ListItem * getItem( FLMUINT uiList, FLMUINT nth); void removeItem( FLMUINT uiList, F_ListItem * pItem); FINLINE FLMUINT getListCount( void) { return( m_uiListNodeCnt); } FLMUINT getItemCount( FLMUINT uiList); void clearList( FLMUINT uiList = 0); private: FLMUINT m_uiListNodeCnt; F_ListNode * m_pListNodes; }; // IMPORTANT NOTE: If these are changed, corresonding changes // should be made in java and C# code as well. /// Types of locks that may be requested. typedef enum { FLM_LOCK_NONE = 0, FLM_LOCK_EXCLUSIVE, ///< 1 = Exclusive lock. FLM_LOCK_SHARED ///< 2 = Shared lock. } eLockType; /**************************************************************************** /// Abstract base class to get lock information. The application must /// implement this class. A pointer to an object of this class is passed /// into IF_LockObject::getLockInfo(). ****************************************************************************/ flminterface IF_LockInfoClient : public F_Object { /// Return the lock count. This method is called by to tell the /// application how many lock holders plus lock waiters there are. This /// gives the application an opportunity to allocate memory to hold the /// information that will be returned via the /// IF_LockInfoClient::addLockInfo() method. The application should /// return TRUE from this method in order to continue, FALSE if it wants /// to stop and return from the IF_LockObject::getLockInfo() function. virtual FLMBOOL FTKAPI setLockCount( FLMUINT uiTotalLocks ///< Total number of lock holders plus lock waiters. ) = 0; /// Return lock information for a lock holder or waiter. This method /// is called for each thread that is either holding the lock or waiting /// to obtain the lock. The application should return TRUE from this /// method in order to continue, FALSE if it wants to stop and return /// from the IF_LockObject::getLockInfo() function. virtual FLMBOOL FTKAPI addLockInfo( FLMUINT uiLockNum, ///< Position in queue (0 = lock holder, 1..n = lock waiter). FLMUINT uiThreadID, ///< Thread ID of the lock holder/waiter. FLMUINT uiTime ///< For the lock holder, this is the amount of time the lock has been ///< held.\ For a lock waiter, this is the amount of time the thread ///< has been waiting to obtain the lock.\ Both times are milliseconds. ) = 0; }; // IMPORTANT NOTE: This structure needs to stay in sync with // corresponding structures in java and C# code. /************************************************************************** /// Structure used in gathering statistics to hold an operation count and an elapsed time. **************************************************************************/ typedef struct { FLMUINT64 ui64Count; ///< Number of times operation was performed FLMUINT64 ui64ElapMilli; ///< Total elapsed time (milliseconds) for the operations. } F_COUNT_TIME_STAT; // IMPORTANT NOTE: This structure needs to stay in sync with // corresponding structures in java and C# code. /************************************************************************** /// Structure for returning lock statistics. **************************************************************************/ typedef struct { F_COUNT_TIME_STAT NoLocks; ///< Statistics on times when nobody was holding a lock on the database. F_COUNT_TIME_STAT WaitingForLock; ///< Statistics on times threads were waiting to obtain a database lock. F_COUNT_TIME_STAT HeldLock; ///< Statistics on times when a thread was holding a lock on the database. } F_LOCK_STATS; /**************************************************************************** /// Structure that gives information on threads that are either waiting to /// obtain a lock or have obtained a lock. ****************************************************************************/ typedef struct { FLMUINT uiThreadId; ///< Thread id of thread that is waiting to obtain a lock or holds a lock. FLMUINT uiTime; ///< For lock holder, this is the time the lock was obtained. ///< For the lock waiter, this is the time he started waiting for the lock. } F_LOCK_USER; /**************************************************************************** Desc: ****************************************************************************/ flminterface IF_LockObject : public F_Object { virtual RCODE FTKAPI lock( F_SEM hWaitSem, FLMBOOL bExclLock, FLMUINT uiMaxWaitSecs, FLMINT iPriority, F_LOCK_STATS * pLockStats = NULL) = 0; virtual RCODE FTKAPI unlock( F_LOCK_STATS * pLockStats = NULL) = 0; virtual FLMUINT FTKAPI getLockCount( void) = 0; virtual FLMUINT FTKAPI getWaiterCount( void) = 0; virtual RCODE FTKAPI getLockInfo( FLMINT iPriority, eLockType * peCurrLockType, FLMUINT * puiThreadId, FLMUINT * puiLockHeldTime = NULL, FLMUINT * puiNumExclQueued = NULL, FLMUINT * puiNumSharedQueued = NULL, FLMUINT * puiPriorityCount = NULL) = 0; virtual RCODE FTKAPI getLockInfo( IF_LockInfoClient * pLockInfo) = 0; virtual RCODE FTKAPI getLockQueue( F_LOCK_USER ** ppLockUsers) = 0; virtual FLMBOOL FTKAPI haveHigherPriorityWaiter( FLMINT iPriority) = 0; virtual void FTKAPI timeoutLockWaiter( FLMUINT uiThreadId) = 0; virtual void FTKAPI timeoutAllWaiters( void) = 0; }; FTKXPC RCODE FTKAPI FlmAllocLockObject( IF_LockObject ** ppLockObject); /**************************************************************************** Desc: Misc. ****************************************************************************/ #define F_UNREFERENCED_PARM( parm) \ (void)parm #define f_min(a, b) \ ((a) < (b) ? (a) : (b)) #define f_max(a, b) \ ((a) < (b) ? (b) : (a)) #define f_swap( a, b, tmp) \ ((tmp) = (a), (a) = (b), (b) = (tmp)) FINLINE FLMBOOL f_isHexChar( FLMBYTE ucChar) { if( (ucChar >= '0' && ucChar <= '9') || (ucChar >= 'A' && ucChar <= 'F') || (ucChar >= 'a' && ucChar <= 'f')) { return( TRUE); } return( FALSE); } FINLINE FLMBOOL f_isHexChar( FLMUNICODE uChar) { if( uChar > 127) { return( FALSE); } return( f_isHexChar( f_tonative( (FLMBYTE)uChar))); } FINLINE FLMBYTE f_getHexVal( FLMBYTE ucChar) { if( ucChar >= '0' && ucChar <= '9') { return( (FLMBYTE)(ucChar - '0')); } else if( ucChar >= 'A' && ucChar <= 'F') { return( (FLMBYTE)((ucChar - 'A') + 10)); } else if( ucChar >= 'a' && ucChar <= 'f') { return( (FLMBYTE)((ucChar - 'a') + 10)); } return( 0); } FINLINE FLMBYTE f_getHexVal( FLMUNICODE uChar) { return( f_getHexVal( f_tonative( (FLMBYTE)uChar))); } FINLINE FLMBOOL f_isValidHexNum( const FLMBYTE * pszString) { if( *pszString == 0) { return( FALSE); } while( *pszString) { if( !f_isHexChar( *pszString)) { return( FALSE); } pszString++; } return( TRUE); } FINLINE FLMUINT64 f_roundUp( FLMUINT64 ui64ValueToRound, FLMUINT64 ui64Boundary) { FLMUINT64 ui64RetVal; ui64RetVal = ((ui64ValueToRound / ui64Boundary) * ui64Boundary); if( ui64RetVal < ui64ValueToRound) { ui64RetVal += ui64Boundary; } return( ui64RetVal); } FINLINE void f_setBit( FLMBYTE * pucBuffer, FLMUINT uiBit) { pucBuffer[ uiBit >> 3] |= (FLMBYTE)(0x01 << (uiBit & 0x07)); } FINLINE void f_clearBit( FLMBYTE * pucBuffer, FLMUINT uiBit) { pucBuffer[ uiBit >> 3] &= ~((FLMBYTE)(0x01 << (uiBit & 0x07))); } FINLINE FLMBOOL f_isBitSet( FLMBYTE * pucBuffer, FLMUINT uiBit) { return( (pucBuffer[ uiBit >> 3] & (FLMBYTE)(0x01 << (uiBit & 0x07))) ? TRUE : FALSE); } FTKXPC FLMBOOL FTKAPI f_isNumber( const char * pszStr, FLMBOOL * pbNegative = NULL, FLMBOOL * pbHex = NULL); FTKXPC RCODE FTKAPI f_filecpy( const char * pszSourceFile, const char * pszData); FTKXPC RCODE FTKAPI f_filecat( const char * pszSourceFile, const char * pszData); FTKXPC RCODE FTKAPI f_filetobuf( const char * pszSourceFile, char ** ppszBuffer); /**************************************************************************** Desc: FTX ****************************************************************************/ #define FKB_ESCAPE 0xE01B #define FKB_ESC FKB_ESCAPE #define FKB_SPACE 0x20 #define FKB_HOME 0xE008 #define FKB_UP 0xE017 #define FKB_PGUP 0xE059 #define FKB_LEFT 0xE019 #define FKB_RIGHT 0xE018 #define FKB_END 0xE055 #define FKB_DOWN 0xE01A #define FKB_PGDN 0xE05A #define FKB_PLUS 0x002B #define FKB_MINUS 0x002D #define FKB_INSERT 0xE05D #define FKB_DELETE 0xE051 #define FKB_BACKSPACE 0xE050 #define FKB_TAB 0xE009 #define FKB_ENTER 0xE00A #define FKB_F1 0xE020 #define FKB_F2 0xE021 #define FKB_F3 0xE022 #define FKB_F4 0xE023 #define FKB_F5 0xE024 #define FKB_F6 0xE025 #define FKB_F7 0xE026 #define FKB_F8 0xE027 #define FKB_F9 0xE028 #define FKB_F10 0xE029 #define FKB_F11 0xE03A #define FKB_F12 0xE03B #define FKB_STAB 0xE05E #define FKB_SF1 0xE02C #define FKB_SF2 0xE02D #define FKB_SF3 0xE02E #define FKB_SF4 0xE02F #define FKB_SF5 0xE030 #define FKB_SF6 0xE031 #define FKB_SF7 0xE032 #define FKB_SF8 0xE033 #define FKB_SF9 0xE034 #define FKB_SF10 0xE035 #define FKB_SF11 0xE036 #define FKB_SF12 0xE037 #define FKB_ALT_A 0xFDDC #define FKB_ALT_B 0xFDDD #define FKB_ALT_C 0xFDDE #define FKB_ALT_D 0xFDDF #define FKB_ALT_E 0xFDE0 #define FKB_ALT_F 0xFDE1 #define FKB_ALT_G 0xFDE2 #define FKB_ALT_H 0xFDE3 #define FKB_ALT_I 0xFDE4 #define FKB_ALT_J 0xFDE5 #define FKB_ALT_K 0xFDE6 #define FKB_ALT_L 0xFDE7 #define FKB_ALT_M 0xFDE8 #define FKB_ALT_N 0xFDE9 #define FKB_ALT_O 0xFDEA #define FKB_ALT_P 0xFDEB #define FKB_ALT_Q 0xFDEC #define FKB_ALT_R 0xFDED #define FKB_ALT_S 0xFDEE #define FKB_ALT_T 0xFDEF #define FKB_ALT_U 0xFDF0 #define FKB_ALT_V 0xFDF1 #define FKB_ALT_W 0xFDF2 #define FKB_ALT_X 0xFDF3 #define FKB_ALT_Y 0xFDF4 #define FKB_ALT_Z 0xFDF5 #define FKB_ALT_1 0xFDF7 #define FKB_ALT_2 0xFDF8 #define FKB_ALT_3 0xFDF9 #define FKB_ALT_4 0xFDFA #define FKB_ALT_5 0xFDFB #define FKB_ALT_6 0xFDFC #define FKB_ALT_7 0xFDFD #define FKB_ALT_8 0xFDFE #define FKB_ALT_9 0xFDFF #define FKB_ALT_0 0xFDF6 #define FKB_ALT_MINUS 0xE061 #define FKB_ALT_EQUAL 0xE06B #define FKB_ALT_F1 0xE038 #define FKB_ALT_F2 0xE039 #define FKB_ALT_F3 0xE03A #define FKB_ALT_F4 0xE03B #define FKB_ALT_F5 0xE03C #define FKB_ALT_F6 0xE03D #define FKB_ALT_F7 0xE03E #define FKB_ALT_F8 0xE03F #define FKB_ALT_F9 0xE040 #define FKB_ALT_F10 0xE041 #define FKB_GOTO 0xE058 #define FKB_CTRL_HOME 0xE058 #define FKB_CTRL_UP 0xE063 #define FKB_CTRL_PGUP 0xE057 #define FKB_CTRL_LEFT 0xE054 #define FKB_CTRL_RIGHT 0xE053 #define FKB_CTRL_END 0xE00B #define FKB_CTRL_DOWN 0xE064 #define FKB_CTRL_PGDN 0xE00C #define FKB_CTRL_INSERT 0xE06E #define FKB_CTRL_DELETE 0xE06D #define FKB_CTRL_ENTER 0xE05F #define FKB_CTRL_A 0xE07C #define FKB_CTRL_B 0xE07D #define FKB_CTRL_C 0xE07E #define FKB_CTRL_D 0xE07F #define FKB_CTRL_E 0xE080 #define FKB_CTRL_F 0xE081 #define FKB_CTRL_G 0xE082 #define FKB_CTRL_H 0xE083 #define FKB_CTRL_I 0xE084 #define FKB_CTRL_J 0xE085 #define FKB_CTRL_K 0xE086 #define FKB_CTRL_L 0xE087 #define FKB_CTRL_M 0xE088 #define FKB_CTRL_N 0xE089 #define FKB_CTRL_O 0xE08A #define FKB_CTRL_P 0xE08B #define FKB_CTRL_Q 0xE08C #define FKB_CTRL_R 0xE08D #define FKB_CTRL_S 0xE08E #define FKB_CTRL_T 0xE08F #define FKB_CTRL_U 0xE090 #define FKB_CTRL_V 0xE091 #define FKB_CTRL_W 0xE092 #define FKB_CTRL_X 0xE093 #define FKB_CTRL_Y 0xE094 #define FKB_CTRL_Z 0xE095 #define FKB_CTRL_1 0xE06B #define FKB_CTRL_2 0xE06C #define FKB_CTRL_3 0xE06D #define FKB_CTRL_4 0xE06E #define FKB_CTRL_5 0xE06F #define FKB_CTRL_6 0xE070 #define FKB_CTRL_7 0xE071 #define FKB_CTRL_8 0xE072 #define FKB_CTRL_9 0xE073 #define FKB_CTRL_0 0xE074 #define FKB_CTRL_MINUS 0xE060 #define FKB_CTRL_EQUAL 0xE061 #define FKB_CTRL_F1 0xE038 #define FKB_CTRL_F2 0xE039 #define FKB_CTRL_F3 0xE03A #define FKB_CTRL_F4 0xE03B #define FKB_CTRL_F5 0xE03C #define FKB_CTRL_F6 0xE03D #define FKB_CTRL_F7 0xE03E #define FKB_CTRL_F8 0xE03F #define FKB_CTRL_F9 0xE040 #define FKB_CTRL_F10 0xE041 #define FLM_CURSOR_BLOCK 0x01 #define FLM_CURSOR_UNDERLINE 0x02 #define FLM_CURSOR_INVISIBLE 0x04 #define FLM_CURSOR_VISIBLE 0x08 typedef struct FTX_SCREEN FTX_SCREEN; typedef struct FTX_WINDOW FTX_WINDOW; typedef FLMBOOL (FTKAPI * KEY_HANDLER)( FLMUINT uiKeyIn, FLMUINT * puiKeyOut, void * pvAppData); FTKXPC RCODE FTKAPI FTXInit( const char * pszAppName = NULL, FLMUINT uiCols = 0, FLMUINT uiRows = 0, eColorType backgroundColor = FLM_BLUE, eColorType foregroundColor = FLM_WHITE, KEY_HANDLER pKeyHandler = NULL, void * pvKeyHandlerData = NULL); FTKXPC void FTKAPI FTXExit( void); FTKXPC void FTKAPI FTXCycleScreensNext( void); FTKXPC void FTKAPI FTXCycleScreensPrev( void); FTKXPC void FTKAPI FTXRefreshCursor( void); FTKXPC void FTKAPI FTXInvalidate( void); FTKXPC void FTKAPI FTXSetShutdownFlag( FLMBOOL * pbShutdownFlag); FTKXPC RCODE FTKAPI FTXScreenInit( const char * pszName, FTX_SCREEN ** ppScreen); FTKXPC RCODE FTKAPI FTXCaptureScreen( FLMBYTE * pText, FLMBYTE * pForeAttrib, FLMBYTE * pBackAttrib); FTKXPC void FTKAPI FTXRefresh( void); FTKXPC void FTKAPI FTXSetRefreshState( FLMBOOL bDisable); FTKXPC FLMBOOL FTKAPI FTXRefreshDisabled( void); FTKXPC RCODE FTKAPI FTXAddKey( FLMUINT uiKey); FTKXPC RCODE FTKAPI FTXWinInit( FTX_SCREEN * pScreen, FLMUINT uiCols, FLMUINT uiRows, FTX_WINDOW ** ppWindow); FTKXPC void FTKAPI FTXWinFree( FTX_WINDOW ** ppWindow); FTKXPC RCODE FTKAPI FTXWinOpen( FTX_WINDOW * pWindow); FTKXPC RCODE FTKAPI FTXWinSetName( FTX_WINDOW * pWindow, char * pszName); FTKXPC void FTKAPI FTXWinClose( FTX_WINDOW * pWindow); FTKXPC void FTKAPI FTXWinSetFocus( FTX_WINDOW * pWindow); FTKXPC void FTKAPI FTXWinPrintChar( FTX_WINDOW * pWindow, FLMUINT uiChar); FTKXPC void FTKAPI FTXWinPrintStr( FTX_WINDOW * pWindow, const char * pszString); FTKXPC void FTKAPI FTXWinPrintf( FTX_WINDOW * pWindow, const char * pszFormat, ...); FTKXPC void FTKAPI FTXWinCPrintf( FTX_WINDOW * pWindow, eColorType backgroundColor, eColorType foregroundColor, const char * pszFormat, ...); FTKXPC void FTKAPI FTXWinPrintStrXY( FTX_WINDOW * pWindow, const char * pszString, FLMUINT uiCol, FLMUINT uiRow); FTKXPC void FTKAPI FTXWinMove( FTX_WINDOW * pWindow, FLMUINT uiCol, FLMUINT uiRow); FTKXPC void FTKAPI FTXWinPaintBackground( FTX_WINDOW * pWindow, eColorType backgroundColor); FTKXPC void FTKAPI FTXWinPaintForeground( FTX_WINDOW * pWindow, eColorType foregroundColor); FTKXPC void FTKAPI FTXWinPaintRow( FTX_WINDOW * pWindow, eColorType * pBackgroundColor, eColorType * pForegroundColor, FLMUINT uiRow); FTKXPC void FTKAPI FTXWinSetChar( FTX_WINDOW * pWindow, FLMUINT uiChar); FTKXPC void FTKAPI FTXWinPaintRowForeground( FTX_WINDOW * pWindow, eColorType foregroundColor, FLMUINT uiRow); FTKXPC void FTKAPI FTXWinPaintRowBackground( FTX_WINDOW * pWindow, eColorType backgroundColor, FLMUINT uiRow); FTKXPC void FTKAPI FTXWinSetBackFore( FTX_WINDOW * pWindow, eColorType backgroundColor, eColorType foregroundColor); FTKXPC void FTKAPI FTXWinGetCanvasSize( FTX_WINDOW * pWindow, FLMUINT * puiNumCols, FLMUINT * puiNumRows); FTKXPC void FTKAPI FTXWinGetSize( FTX_WINDOW * pWindow, FLMUINT * puiNumCols, FLMUINT * puiNumRows); FTKXPC FLMUINT FTKAPI FTXWinGetCurrRow( FTX_WINDOW * pWindow); FTKXPC FLMUINT FTKAPI FTXWinGetCurrCol( FTX_WINDOW * pWindow); FTKXPC void FTKAPI FTXWinGetBackFore( FTX_WINDOW * pWindow, eColorType * pBackgroundColor, eColorType * pForegroundColor); FTKXPC void FTKAPI FTXWinDrawBorder( FTX_WINDOW * pWindow); FTKXPC void FTKAPI FTXWinSetTitle( FTX_WINDOW * pWindow, const char * pszTitle, eColorType backgroundColor, eColorType foregroundColor); FTKXPC void FTKAPI FTXWinSetHelp( FTX_WINDOW * pWindow, const char * pszHelp, eColorType backgroundColor, eColorType foregroundColor); FTKXPC RCODE FTKAPI FTXLineEdit( FTX_WINDOW * pWindow, char * pszBuffer, FLMUINT uiBufSize, FLMUINT uiMaxWidth, FLMUINT * puiCharCount, FLMUINT * puiTermChar); FTKXPC FLMUINT FTKAPI FTXLineEd( FTX_WINDOW * pWindow, char * pszBuffer, FLMUINT uiBufSize); FTKXPC void FTKAPI FTXWinSetCursorPos( FTX_WINDOW * pWindow, FLMUINT uiCol, FLMUINT uiRow); FTKXPC void FTKAPI FTXWinGetCursorPos( FTX_WINDOW * pWindow, FLMUINT * puiCol, FLMUINT * puiRow); FTKXPC void FTKAPI FTXWinClear( FTX_WINDOW * pWindow); FTKXPC void FTKAPI FTXWinClearXY( FTX_WINDOW * pWindow, FLMUINT uiCol, FLMUINT uiRow); FTKXPC void FTKAPI FTXWinClearLine( FTX_WINDOW * pWindow, FLMUINT uiCol, FLMUINT uiRow); FTKXPC void FTKAPI FTXWinClearToEOL( FTX_WINDOW * pWindow); FTKXPC void FTKAPI FTXWinSetCursorType( FTX_WINDOW * pWindow, FLMUINT uiType); FTKXPC FLMUINT FTKAPI FTXWinGetCursorType( FTX_WINDOW * pWindow); FTKXPC RCODE FTKAPI FTXWinInputChar( FTX_WINDOW * pWindow, FLMUINT * puiChar); FTKXPC RCODE FTKAPI FTXWinTestKB( FTX_WINDOW * pWindow); FTKXPC void FTKAPI FTXWinSetScroll( FTX_WINDOW * pWindow, FLMBOOL bScroll); FTKXPC void FTKAPI FTXWinSetLineWrap( FTX_WINDOW * pWindow, FLMBOOL bLineWrap); FTKXPC void FTKAPI FTXWinGetScroll( FTX_WINDOW * pWindow, FLMBOOL * pbScroll); FTKXPC RCODE FTKAPI FTXWinGetScreen( FTX_WINDOW * pWindow, FTX_SCREEN ** ppScreen); FTKXPC RCODE FTKAPI FTXWinGetPosition( FTX_WINDOW * pWindow, FLMUINT * puiCol, FLMUINT * puiRow); FTKXPC void FTKAPI FTXScreenFree( FTX_SCREEN ** ppScreen); FTKXPC RCODE FTKAPI FTXScreenInitStandardWindows( FTX_SCREEN * pScreen, eColorType titleBackColor, eColorType titleForeColor, eColorType mainBackColor, eColorType mainForeColor, FLMBOOL bBorder, FLMBOOL bBackFill, const char * pszTitle, FTX_WINDOW ** ppTitleWin, FTX_WINDOW ** ppMainWin); FTKXPC void FTKAPI FTXScreenSetShutdownFlag( FTX_SCREEN * pScreen, FLMBOOL * pbShutdownFlag); FTKXPC RCODE FTKAPI FTXScreenDisplay( FTX_SCREEN * pScreen); FTKXPC RCODE FTKAPI FTXScreenGetSize( FTX_SCREEN * pScreen, FLMUINT * puiNumCols, FLMUINT * puiNumRows); FTKXPC RCODE FTKAPI FTXMessageWindow( FTX_SCREEN * pScreen, eColorType backgroundColor, eColorType foregroundColor, const char * pszMessage1, const char * pszMessage2, FTX_WINDOW ** ppWindow); FTKXPC RCODE FTKAPI FTXDisplayMessage( FTX_SCREEN * pScreen, eColorType backgroundColor, eColorType foregroundColor, const char * pszMessage1, const char * pszMessage2, FLMUINT * puiTermChar); FTKXPC RCODE FTKAPI FTXDisplayScrollWindow( FTX_SCREEN * pScreen, const char * pszTitle, const char * pszMessage, FLMUINT uiCols, FLMUINT uiRows); FTKXPC RCODE FTKAPI FTXGetInput( FTX_SCREEN * pScreen, const char * pszMessage, char * pszResponse, FLMUINT uiMaxRespLen, FLMUINT * puiTermChar); FTKXPC void FTKAPI FTXBeep( void); FTKXPC RCODE FTKAPI f_conInit( FLMUINT uiRows, FLMUINT uiCols, const char * pszTitle); FTKXPC void FTKAPI f_conExit( void); FTKXPC void FTKAPI f_conGetScreenSize( FLMUINT * puiNumColsRV, FLMUINT * puiNumRowsRV); FTKXPC void FTKAPI f_conDrawBorder( void); FTKXPC void FTKAPI f_conStrOut( const char * pszString); FTKXPC void FTKAPI f_conStrOutXY( const char * pszString, FLMUINT uiCol, FLMUINT uiRow); FTKXPC void FTKAPI f_conPrintf( const char * pszFormat, ...); FTKXPC void FTKAPI f_conCPrintf( eColorType back, eColorType fore, const char * pszFormat, ...); FTKXPC void FTKAPI f_conClearScreen( FLMUINT uiCol, FLMUINT uiRow); FTKXPC void FTKAPI f_conClearLine( FLMUINT uiCol, FLMUINT uiRow); FTKXPC void FTKAPI f_conSetBackFore( eColorType backColor, eColorType foreColor); FTKXPC FLMUINT FTKAPI f_conGetCursorColumn( void); FTKXPC FLMUINT FTKAPI f_conGetCursorRow( void); FTKXPC void FTKAPI f_conSetCursorType( FLMUINT uiType); FTKXPC void FTKAPI f_conSetCursorPos( FLMUINT uiCol, FLMUINT uiRow); FTKXPC FLMUINT FTKAPI f_conGetKey( void); FTKXPC FLMBOOL FTKAPI f_conHaveKey( void); FTKXPC FLMUINT FTKAPI f_conLineEdit( char * pszString, FLMUINT uiMaxLen); /**************************************************************************** Desc: ****************************************************************************/ class FTKEXP F_BufferIStream : public IF_BufferIStream { public: F_BufferIStream() { m_pucBuffer = NULL; m_uiBufferLen = 0; m_uiOffset = 0; m_bAllocatedBuffer = FALSE; m_bIsOpen = FALSE; } virtual ~F_BufferIStream(); RCODE FTKAPI openStream( const char * pucBuffer, FLMUINT uiLength, char ** ppucAllocatedBuffer = NULL); FINLINE FLMUINT64 FTKAPI totalSize( void) { f_assert( m_bIsOpen); return( m_uiBufferLen); } FINLINE FLMUINT64 FTKAPI remainingSize( void) { f_assert( m_bIsOpen); return( m_uiBufferLen - m_uiOffset); } RCODE FTKAPI closeStream( void); FINLINE RCODE FTKAPI positionTo( FLMUINT64 ui64Position) { f_assert( m_bIsOpen); if( ui64Position < m_uiBufferLen) { m_uiOffset = (FLMUINT)ui64Position; } else { m_uiOffset = m_uiBufferLen; } return( NE_FLM_OK); } FINLINE FLMUINT64 FTKAPI getCurrPosition( void) { f_assert( m_bIsOpen); return( m_uiOffset); } FINLINE void FTKAPI truncateStream( FLMUINT64 ui64Offset = 0) { f_assert( m_bIsOpen); f_assert( ui64Offset >= m_uiOffset); f_assert( ui64Offset <= m_uiBufferLen); m_uiBufferLen = (FLMUINT)ui64Offset; } RCODE FTKAPI read( void * pvBuffer, FLMUINT uiBytesToRead, FLMUINT * puiBytesRead); FINLINE const FLMBYTE * getBuffer( void) { f_assert( m_bIsOpen); return( m_pucBuffer); } FINLINE const FLMBYTE * FTKAPI getBufferAtCurrentOffset( void) { f_assert( m_bIsOpen); return( m_pucBuffer ? &m_pucBuffer[ m_uiOffset] : NULL); } FINLINE FLMBOOL isOpen( void) { return( m_bIsOpen); } private: const FLMBYTE * m_pucBuffer; FLMUINT m_uiBufferLen; FLMUINT m_uiOffset; FLMBOOL m_bAllocatedBuffer; FLMBOOL m_bIsOpen; }; /**************************************************************************** Desc: ****************************************************************************/ class FTKEXP F_FileIStream : public IF_PosIStream { public: F_FileIStream() { m_pFileHdl = NULL; m_ui64FileOffset = 0; } virtual ~F_FileIStream() { if( m_pFileHdl) { m_pFileHdl->Release(); } } RCODE FTKAPI openStream( const char * pszPath); RCODE FTKAPI closeStream( void); RCODE FTKAPI positionTo( FLMUINT64 ui64Position); FLMUINT64 FTKAPI totalSize( void); FLMUINT64 FTKAPI remainingSize( void); FLMUINT64 FTKAPI getCurrPosition( void); RCODE FTKAPI read( void * pvBuffer, FLMUINT uiBytesToRead, FLMUINT * puiBytesRead); private: IF_FileHdl * m_pFileHdl; FLMUINT64 m_ui64FileOffset; }; /**************************************************************************** Desc: ****************************************************************************/ class FTKEXP F_BufferedIStream : public IF_PosIStream { public: F_BufferedIStream() { m_pIStream = NULL; m_pucBuffer = NULL; } virtual ~F_BufferedIStream() { closeStream(); } RCODE FTKAPI openStream( IF_IStream * pIStream, FLMUINT uiBufferSize); RCODE FTKAPI read( void * pvBuffer, FLMUINT uiBytesToRead, FLMUINT * puiBytesRead); RCODE FTKAPI closeStream( void); FINLINE FLMUINT64 FTKAPI totalSize( void) { if (!m_pIStream) { f_assert( 0); return( 0); } return( m_uiBytesAvail); } FINLINE FLMUINT64 FTKAPI remainingSize( void) { if( !m_pIStream) { f_assert( 0); return( 0); } return( m_uiBytesAvail - m_uiBufferOffset); } FINLINE RCODE FTKAPI positionTo( FLMUINT64 ui64Position) { if( !m_pIStream) { f_assert( 0); return( RC_SET( NE_FLM_ILLEGAL_OP)); } if( ui64Position < m_uiBytesAvail) { m_uiBufferOffset = (FLMUINT)ui64Position; } else { m_uiBufferOffset = m_uiBytesAvail; } return( NE_FLM_OK); } FINLINE FLMUINT64 FTKAPI getCurrPosition( void) { if( !m_pIStream) { f_assert( 0); return( 0); } return( m_uiBufferOffset); } private: IF_IStream * m_pIStream; FLMBYTE * m_pucBuffer; FLMUINT m_uiBufferSize; FLMUINT m_uiBufferOffset; FLMUINT m_uiBytesAvail; }; /**************************************************************************** Desc: ****************************************************************************/ class FTKEXP F_BufferedOStream : public IF_OStream { public: F_BufferedOStream() { m_pOStream = NULL; m_pucBuffer = NULL; } virtual ~F_BufferedOStream() { closeStream(); } RCODE FTKAPI openStream( IF_OStream * pOStream, FLMUINT uiBufferSize); RCODE FTKAPI write( const void * pvBuffer, FLMUINT uiBytesToWrite, FLMUINT * puiBytesWritten); RCODE FTKAPI closeStream( void); RCODE FTKAPI flush( void); private: IF_OStream * m_pOStream; FLMBYTE * m_pucBuffer; FLMUINT m_uiBufferSize; FLMUINT m_uiBufferOffset; }; /**************************************************************************** Desc: ****************************************************************************/ class FTKEXP F_FileOStream : public IF_OStream { public: F_FileOStream() { m_pFileHdl = NULL; } virtual ~F_FileOStream() { closeStream(); } RCODE FTKAPI openStream( const char * pszFilePath, FLMBOOL bTruncateIfExists); RCODE FTKAPI write( const void * pvBuffer, FLMUINT uiBytesToWrite, FLMUINT * puiBytesWritten); RCODE FTKAPI closeStream( void); private: IF_FileHdl * m_pFileHdl; FLMUINT64 m_ui64FileOffset; }; /**************************************************************************** Desc: ****************************************************************************/ class FTKEXP F_MultiFileIStream : public IF_IStream { public: F_MultiFileIStream() { m_pIStream = NULL; m_bOpen = FALSE; } virtual ~F_MultiFileIStream() { closeStream(); } RCODE FTKAPI openStream( const char * pszDirectory, const char * pszBaseName); RCODE FTKAPI read( void * pvBuffer, FLMUINT uiBytesToRead, FLMUINT * puiBytesRead); RCODE FTKAPI closeStream( void); private: RCODE rollToNextFile( void); IF_IStream * m_pIStream; FLMBOOL m_bOpen; FLMBOOL m_bEndOfStream; FLMUINT m_uiFileNum; FLMUINT64 m_ui64FileOffset; char m_szDirectory[ F_PATH_MAX_SIZE + 1]; char m_szBaseName[ F_PATH_MAX_SIZE + 1]; }; /**************************************************************************** Desc: ****************************************************************************/ class FTKEXP F_MultiFileOStream : public IF_OStream { public: F_MultiFileOStream() { m_pOStream = NULL; m_bOpen = FALSE; } virtual ~F_MultiFileOStream() { closeStream(); } RCODE createStream( const char * pszDirectory, const char * pszBaseName, FLMUINT uiMaxFileSize, FLMBOOL bOkToOverwrite); RCODE FTKAPI write( const void * pvBuffer, FLMUINT uiBytesToWrite, FLMUINT * puiBytesWritten); RCODE FTKAPI closeStream( void); RCODE processDirectory( const char * pszDirectory, const char * pszBaseName, FLMBOOL bOkToDelete); private: RCODE rollToNextFile( void); IF_OStream * m_pOStream; FLMBOOL m_bOpen; FLMUINT m_uiFileNum; FLMUINT64 m_ui64MaxFileSize; FLMUINT64 m_ui64FileOffset; char m_szDirectory[ F_PATH_MAX_SIZE + 1]; char m_szBaseName[ F_PATH_MAX_SIZE + 1]; }; /**************************************************************************** Desc: ****************************************************************************/ class FTKEXP F_CollIStream : public IF_CollIStream { public: F_CollIStream() { m_pIStream = NULL; m_uiLanguage = 0; m_bMayHaveWildCards = FALSE; m_bUnicodeStream = FALSE; m_uNextChar = 0; } virtual ~F_CollIStream() { if( m_pIStream) { m_pIStream->Release(); } } RCODE FTKAPI openStream( IF_PosIStream * pIStream, FLMBOOL bUnicodeStream, FLMUINT uiLanguage, FLMUINT uiCompareRules, FLMBOOL bMayHaveWildCards) { if( m_pIStream) { m_pIStream->Release(); } m_pIStream = pIStream; m_pIStream->AddRef(); m_uiLanguage = uiLanguage; m_uiCompareRules = uiCompareRules; m_bCaseSensitive = (uiCompareRules & FLM_COMP_CASE_INSENSITIVE) ? FALSE : TRUE; m_bMayHaveWildCards = bMayHaveWildCards; m_bUnicodeStream = bUnicodeStream; m_ui64EndOfLeadingSpacesPos = 0; return( NE_FLM_OK); } RCODE FTKAPI closeStream( void) { if( m_pIStream) { m_pIStream->Release(); m_pIStream = NULL; } return( NE_FLM_OK); } RCODE FTKAPI read( void * pvBuffer, FLMUINT uiBytesToRead, FLMUINT * puiBytesRead) { RCODE rc = NE_FLM_OK; if( RC_BAD( rc = m_pIStream->read( pvBuffer, uiBytesToRead, puiBytesRead))) { goto Exit; } Exit: return( rc); } RCODE FTKAPI read( FLMBOOL bAllowTwoIntoOne, FLMUNICODE * puChar, FLMBOOL * pbCharIsWild, FLMUINT16 * pui16Col, FLMUINT16 * pui16SubCol, FLMBYTE * pucCase); FINLINE FLMUINT64 FTKAPI totalSize( void) { if( m_pIStream) { return( m_pIStream->totalSize()); } return( 0); } FINLINE FLMUINT64 FTKAPI remainingSize( void) { if( m_pIStream) { return( m_pIStream->remainingSize()); } return( 0); } FINLINE RCODE FTKAPI positionTo( FLMUINT64) { return( RC_SET_AND_ASSERT( NE_FLM_NOT_IMPLEMENTED)); } FINLINE RCODE FTKAPI positionTo( F_CollStreamPos * pPos) { // Should never be able to position back to before the // leading spaces. m_uNextChar = pPos->uNextChar; flmAssert( pPos->ui64Position >= m_ui64EndOfLeadingSpacesPos); return( m_pIStream->positionTo( pPos->ui64Position)); } FINLINE FLMUINT64 FTKAPI getCurrPosition( void) { flmAssert( 0); return( 0); } void FTKAPI getCurrPosition( F_CollStreamPos * pPos); private: FINLINE RCODE readCharFromStream( FLMUNICODE * puChar) { RCODE rc = NE_FLM_OK; if( m_bUnicodeStream) { if( RC_BAD( rc = m_pIStream->read( puChar, sizeof( FLMUNICODE), NULL))) { goto Exit; } } else { if( RC_BAD( rc = f_readUTF8CharAsUnicode( m_pIStream, puChar))) { goto Exit; } } Exit: return( rc); } IF_PosIStream * m_pIStream; FLMUINT m_uiLanguage; FLMBOOL m_bCaseSensitive; FLMUINT m_uiCompareRules; FLMUINT64 m_ui64EndOfLeadingSpacesPos; FLMBOOL m_bMayHaveWildCards; FLMBOOL m_bUnicodeStream; FLMUNICODE m_uNextChar; }; /**************************************************************************** Desc: Decodes an ASCII base64 stream to binary ****************************************************************************/ class FTKEXP F_Base64DecoderIStream : public IF_IStream { public: F_Base64DecoderIStream() { m_pIStream = NULL; m_uiBufOffset = 0; m_uiAvailBytes = 0; } virtual ~F_Base64DecoderIStream() { closeStream(); } RCODE FTKAPI openStream( IF_IStream * pIStream); RCODE FTKAPI read( void * pvBuffer, FLMUINT uiBytesToRead, FLMUINT * puiBytesRead); FINLINE RCODE FTKAPI closeStream( void) { RCODE rc = NE_FLM_OK; if( m_pIStream) { if( m_pIStream->getRefCount() == 1) { rc = m_pIStream->closeStream(); } m_pIStream->Release(); m_pIStream = NULL; } m_uiAvailBytes = 0; m_uiBufOffset = 0; return( rc); } private: IF_IStream * m_pIStream; FLMUINT m_uiBufOffset; FLMUINT m_uiAvailBytes; FLMBYTE m_ucBuffer[ 8]; }; FTKXPC RCODE FTKAPI f_base64Encode( const char * pData, FLMUINT uiDataLength, F_DynaBuf * pBuffer); /**************************************************************************** Desc: Encodes a binary input stream into ASCII base64. ****************************************************************************/ class FTKEXP F_Base64EncoderIStream : public IF_IStream { public: F_Base64EncoderIStream() { m_pIStream = NULL; } virtual ~F_Base64EncoderIStream() { closeStream(); } RCODE FTKAPI openStream( IF_IStream * pIStream, FLMBOOL bLineBreaks); RCODE FTKAPI read( void * pvBuffer, FLMUINT uiBytesToRead, FLMUINT * puiBytesRead); FINLINE RCODE FTKAPI closeStream( void) { RCODE rc = NE_FLM_OK; if( m_pIStream) { if( m_pIStream->getRefCount() == 1) { rc = m_pIStream->closeStream(); } m_pIStream->Release(); m_pIStream = NULL; } return( rc); } private: IF_IStream * m_pIStream; FLMBOOL m_bInputExhausted; FLMBOOL m_bLineBreaks; FLMBOOL m_bPriorLineEnd; FLMUINT m_uiBase64Count; FLMUINT m_uiBufOffset; FLMUINT m_uiAvailBytes; FLMBYTE m_ucBuffer[ 8]; }; /**************************************************************************** Desc: ****************************************************************************/ typedef struct LZWODictItem { LZWODictItem * pNext; FLMUINT16 ui16Code; FLMUINT16 ui16ParentCode; FLMBYTE ucChar; } LZWODictItem; /**************************************************************************** Desc: ****************************************************************************/ class FTKEXP F_CompressingOStream : public IF_OStream { public: F_CompressingOStream() { m_pool.poolInit( 64 * 1024); m_pOStream = NULL; m_ppHashTbl = NULL; } virtual ~F_CompressingOStream() { closeStream(); } RCODE FTKAPI openStream( IF_OStream * pOStream); RCODE FTKAPI write( const void * pvBuffer, FLMUINT uiBytesToWrite, FLMUINT * puiBytesWritten); RCODE FTKAPI closeStream( void); private: FINLINE FLMUINT getHashBucket( FLMUINT16 ui16CurrentCode, FLMBYTE ucChar) { return( ((((FLMUINT)ui16CurrentCode) << 8) | ((FLMUINT)ucChar)) % m_uiHashTblSize); } LZWODictItem * findDictEntry( FLMUINT16 ui16CurrentCode, FLMBYTE ucChar); F_Pool m_pool; IF_OStream * m_pOStream; LZWODictItem ** m_ppHashTbl; FLMUINT m_uiHashTblSize; FLMUINT m_uiLastRatio; FLMUINT m_uiBestRatio; FLMUINT m_uiCurrentBytesIn; FLMUINT m_uiTotalBytesIn; FLMUINT m_uiCurrentBytesOut; FLMUINT m_uiTotalBytesOut; FLMBOOL m_bStopCompression; FLMUINT16 m_ui16CurrentCode; FLMUINT16 m_ui16FreeCode; }; typedef struct LZWIDictItem { LZWODictItem * pNext; FLMUINT16 ui16ParentCode; FLMBYTE ucChar; } LZWIDictItem; /**************************************************************************** Desc: ****************************************************************************/ class FTKEXP F_UncompressingIStream : public IF_IStream { public: F_UncompressingIStream() { m_pIStream = NULL; m_pDict = NULL; m_pucDecodeBuffer = NULL; } virtual ~F_UncompressingIStream() { closeStream(); } RCODE FTKAPI openStream( IF_IStream * pIStream); RCODE FTKAPI read( void * pvBuffer, FLMUINT uiBytesToRead, FLMUINT * puiBytesRead); RCODE FTKAPI closeStream( void); private: RCODE readCode( FLMUINT16 * pui16Code); RCODE decodeToBuffer( FLMUINT16 ui16Code); IF_IStream * m_pIStream; LZWIDictItem * m_pDict; FLMBYTE * m_pucDecodeBuffer; FLMUINT m_uiDecodeBufferSize; FLMUINT m_uiDecodeBufferOffset; FLMUINT16 m_ui16FreeCode; FLMUINT16 m_ui16LastCode; FLMBOOL m_bStopCompression; FLMBOOL m_bEndOfStream; }; /*************************************************************************** Desc: Dynamic result sets ***************************************************************************/ typedef int (* F_DYNSET_COMPARE_FUNC)( void * pvData1, void * pvData2, void * pvUserData); typedef enum { ACCESS_HASH, ACCESS_BTREE_LEAF, ACCESS_BTREE_ROOT, ACCESS_BTREE_NON_LEAF } eDynRSetBlkTypes; class F_FixedBlk : public F_Object { public: F_FixedBlk(); virtual ~F_FixedBlk() { } eDynRSetBlkTypes blkType() { return m_eBlkType; } virtual RCODE getCurrent( void * pvEntryBuffer) = 0; virtual RCODE getFirst( void * pvEntryBuffer) = 0; virtual RCODE getLast( void * pvEntryBuffer) = 0; virtual RCODE getNext( void * pvEntryBuffer) = 0; virtual FLMUINT getTotalEntries() = 0; virtual RCODE insert( void * pvEntry) = 0; FINLINE FLMBOOL isDirty( void) { return( m_bDirty); } virtual RCODE search( void * pvEntry, void * pvFoundEntry = NULL) = 0; void setCompareFunc( F_DYNSET_COMPARE_FUNC fnCompare, void * pvUserData) { m_fnCompare = fnCompare; m_pvUserData = pvUserData; } protected: F_DYNSET_COMPARE_FUNC m_fnCompare; void * m_pvUserData; eDynRSetBlkTypes m_eBlkType; FLMUINT m_uiEntrySize; FLMUINT m_uiNumSlots; FLMUINT m_uiPosition; FLMBOOL m_bDirty; FLMBYTE * m_pucBlkBuf; }; class FTKEXP F_DynSearchSet : public F_Object { public: F_DynSearchSet() { m_fnCompare = NULL; m_pvUserData = NULL; m_uiEntrySize = 0; m_pAccess = NULL; } virtual ~F_DynSearchSet() { if( m_pAccess) { m_pAccess->Release(); } } RCODE FTKAPI setup( char * pszTmpDir, FLMUINT uiEntrySize); FINLINE void FTKAPI setCompareFunc( F_DYNSET_COMPARE_FUNC fnCompare, void * pvUserData) { m_fnCompare = fnCompare; m_pvUserData = pvUserData; m_pAccess->setCompareFunc( fnCompare, pvUserData); } RCODE FTKAPI addEntry( void * pvEntry); FINLINE RCODE FTKAPI findMatch( void * pvMatchEntry, void * pvFoundEntry) { return m_pAccess->search( pvMatchEntry, pvFoundEntry); } FINLINE FLMUINT FTKAPI getEntrySize( void) { return m_uiEntrySize; } FINLINE FLMUINT FTKAPI getTotalEntries( void) { return( m_pAccess->getTotalEntries()); } private: F_DYNSET_COMPARE_FUNC m_fnCompare; void * m_pvUserData; FLMUINT m_uiEntrySize; F_FixedBlk * m_pAccess; char m_szFileName[ F_PATH_MAX_SIZE]; }; /*************************************************************************** Desc: Hash tables ***************************************************************************/ typedef struct { void * pFirstInBucket; FLMUINT uiHashValue; } F_BUCKET; FTKXPC RCODE FTKAPI f_allocHashTable( FLMUINT uiHashTblSize, F_BUCKET ** ppHashTblRV); FTKXPC FLMUINT FTKAPI f_strHashBucket( char * pszStr, F_BUCKET * pHashTbl, FLMUINT uiNumBuckets); FTKXPC FLMUINT FTKAPI f_binHashBucket( void * pBuf, FLMUINT uiBufLen, F_BUCKET * pHashTbl, FLMUINT uiNumBuckets); /*************************************************************************** Desc: ***************************************************************************/ class FTKEXP F_HashObject : virtual public F_Object { public: #define F_INVALID_HASH_BUCKET (~((FLMUINT)0)) F_HashObject() { m_pNextInBucket = NULL; m_pPrevInBucket = NULL; m_pNextInGlobal = NULL; m_pPrevInGlobal = NULL; m_uiHashBucket = F_INVALID_HASH_BUCKET; m_ui32KeyCRC = 0; m_uiTimeAdded = 0; } virtual ~F_HashObject() { flmAssert( !m_pNextInBucket); flmAssert( !m_pPrevInBucket); flmAssert( !m_pNextInGlobal); flmAssert( !m_pPrevInGlobal); flmAssert( !getRefCount()); } virtual const void * FTKAPI getKey( void) = 0; virtual FLMUINT FTKAPI getKeyLength( void) = 0; FINLINE FLMUINT FTKAPI getKeyCRC( void) { return( m_ui32KeyCRC); } FINLINE FLMUINT FTKAPI getHashBucket( void) { return( m_uiHashBucket); } FINLINE F_HashObject * FTKAPI getNextInGlobal( void) { return( m_pNextInGlobal); } FINLINE F_HashObject * FTKAPI getNextInBucket( void) { return( m_pNextInBucket); } virtual FLMUINT FTKAPI getObjectType( void) = 0; protected: void setHashBucket( FLMUINT uiHashBucket) { m_uiHashBucket = uiHashBucket; } F_HashObject * m_pNextInBucket; F_HashObject * m_pPrevInBucket; F_HashObject * m_pNextInGlobal; F_HashObject * m_pPrevInGlobal; FLMUINT m_uiHashBucket; FLMUINT m_uiTimeAdded; FLMUINT32 m_ui32KeyCRC; friend class F_HashTable; }; /*************************************************************************** Desc: Hash tables ***************************************************************************/ class FTKEXP F_HashTable : public F_Object { public: F_HashTable(); virtual ~F_HashTable(); RCODE FTKAPI setupHashTable( FLMBOOL bMultithreaded, FLMUINT uiNumBuckets, FLMUINT uiMaxObjects); RCODE FTKAPI addObject( F_HashObject * pObject, FLMBOOL bAllowDuplicates = FALSE); RCODE FTKAPI getNextObjectInGlobal( F_HashObject ** ppObject); RCODE FTKAPI getNextObjectInBucket( F_HashObject ** ppObject); RCODE FTKAPI getObject( const void * pvKey, FLMUINT uiKeyLen, F_HashObject ** ppObject, FLMBOOL bRemove = FALSE); RCODE FTKAPI removeObject( void * pvKey, FLMUINT uiKeyLen); RCODE FTKAPI removeObject( F_HashObject * pObject); void FTKAPI removeAllObjects( void); void FTKAPI removeAgedObjects( FLMUINT uiMaxAge); FLMUINT FTKAPI getMaxObjects( void); RCODE FTKAPI setMaxObjects( FLMUINT uiMaxObjects); private: FLMUINT getHashBucket( const void * pvKey, FLMUINT uiLen, FLMUINT32 * pui32KeyCRC = NULL); void linkObject( F_HashObject * pObject, FLMUINT uiBucket); void unlinkObject( F_HashObject * pObject); RCODE findObject( const void * pvKey, FLMUINT uiKeyLen, F_HashObject ** ppObject); F_MUTEX m_hMutex; F_HashObject * m_pMRUObject; F_HashObject * m_pLRUObject; F_HashObject ** m_ppHashTable; FLMUINT m_uiBuckets; FLMUINT m_uiObjects; FLMUINT m_uiMaxObjects; }; /**************************************************************************** Desc: ****************************************************************************/ typedef FLMBOOL (* F_ARG_VALIDATOR) ( const char * pszGivenArg, const char * pszIdentifier, IF_PrintfClient * pPrintfClient, void * pvAppData); typedef enum { F_ARG_OPTION = 0, F_ARG_REQUIRED_ARG, F_ARG_OPTIONAL_ARG, F_ARG_REPEATING_ARG } F_ARG_TYPE; typedef enum { F_ARG_CONTENT_NONE = 0, F_ARG_CONTENT_BOOL, F_ARG_CONTENT_VALIDATOR, F_ARG_CONTENT_SIGNED_INT, F_ARG_CONTENT_UNSIGNED_INT, F_ARG_CONTENT_ALLOWED_STRING_SET, F_ARG_CONTENT_EXISTING_FILE, F_ARG_CONTENT_STRING } F_ARG_CONTENT_TYPE; class FTKEXP F_ArgSet : public F_Object { public: F_ArgSet(); virtual ~F_ArgSet(); RCODE FTKAPI setup( IF_PrintfClient * pPrintfClient); RCODE FTKAPI addArg( const char * pszIdentifier, const char * pszShortHelp, FLMBOOL bCaseSensitive, F_ARG_TYPE argType, F_ARG_CONTENT_TYPE contentType, ...); RCODE FTKAPI parseCommandLine( FLMUINT uiArgc, const char ** ppszArgv); FLMBOOL FTKAPI argIsPresent( const char * pszIdentifier); FLMUINT FTKAPI getValueCount( const char * pszIdentifier); FLMUINT FTKAPI getUINT( const char * pszIdentifier, FLMUINT uiIndex = 0); FLMINT FTKAPI getINT( const char * pszIdentifier, FLMUINT uiIndex = 0); // Boolean values are recognize in following formats: // // TRUE FALSE NOTES // ---- ----- ----- // true false case-insensitive // 1 0 // on off case-insensitive // yes no case-insensitive // NULL case-insensitive // * anything else is a user error FLMBOOL FTKAPI getBOOL( const char * pszIdentifier, FLMUINT uiIndex = 0); const char * FTKAPI getString( const char * pszIdentifier, FLMUINT uiIndex = 0); void FTKAPI getString( const char * pszIdentifier, char * pszDestination, FLMUINT uiDestinationBufferSize, FLMUINT uiIndex = 0); private: F_Arg * getArg( const char * pszIdentifier); void printUsage( void); void dump( F_Vector * pVec, FLMUINT uiVecLen); FLMBOOL needsPreprocessing( void); RCODE preProcessParams( void); RCODE processAtParams( FLMUINT uiInsertionPoint, char * pszBuffer); RCODE displayShortHelpLines( const char * pszShortHelp, FLMUINT uiCharsPerLine); FLMBOOL needMoreArgs( F_Vector * pVec, FLMUINT uiVecLen); RCODE parseOption( const char * pszArg); char m_szExecBaseName[ F_PATH_MAX_SIZE]; F_Vector m_argVec; FLMUINT m_uiArgVecIndex; F_Vector m_optionsVec; FLMUINT m_uiOptionsVecLen; F_Vector m_requiredArgsVec; FLMUINT m_uiRequiredArgsVecLen; F_Vector m_optionalArgsVec; FLMUINT m_uiOptionalArgsVecLen; F_Arg * m_pRepeatingArg; FLMUINT m_uiArgc; F_Vector * m_pArgv; IF_PrintfClient * m_pPrintfClient; }; /**************************************************************************** Desc: Process ID Functions ****************************************************************************/ FLMUINT f_getpid( void); #ifdef FLM_PACK_STRUCTS #pragma pack(pop) #endif #endif // FTK_H
gpl-2.0
lau-ibarra/ETISIGChacoJoomla
tmp/install_515c4270221dc/plg_system_jquery/site/jquery/no_conflict.js
218
// We do this in this rather complicated manner since Joomla groups // external javascript includes and script declarations seperately // and this call has to be made right after loading jQuery. jQuery.noConflict();
gpl-2.0
tonio-44/tikflak
shop/app/code/core/Mage/Catalog/Model/Resource/Eav/Mysql4/Abstract.php
14799
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage * @package Mage_Catalog * @copyright Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Catalog entity abstract model * * @category Mage * @package Mage_Catalog * @author Magento Core Team <[email protected]> */ abstract class Mage_Catalog_Model_Resource_Eav_Mysql4_Abstract extends Mage_Eav_Model_Entity_Abstract { /** * Redeclare attribute model * * @return string */ protected function _getDefaultAttributeModel() { return 'catalog/resource_eav_attribute'; } public function getDefaultStoreId() { return Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID; } /** * Check whether the attribute is Applicable to the object * * @param Varien_Object $object * @param Mage_Catalog_Model_Resource_Eav_Attribute $attribute * @return boolean */ protected function _isApplicableAttribute ($object, $attribute) { $applyTo = $attribute->getApplyTo(); return count($applyTo) == 0 || in_array($object->getTypeId(), $applyTo); } /** * Retrieve select object for loading entity attributes values * * Join attribute store value * * @param Varien_Object $object * @param mixed $rowId * @return Zend_Db_Select */ protected function _getLoadAttributesSelect($object, $table) { /** * This condition is applicable for all cases when we was work in not single * store mode, customize some value per specific store view and than back * to single store mode. We should load correct values */ if (Mage::app()->isSingleStoreMode()) { $storeId = Mage::app()->getStore(true)->getId(); } else { $storeId = $object->getStoreId(); } $select = $this->_read->select() ->from(array('default' => $table)); if ($setId = $object->getAttributeSetId()) { $select->join( array('set_table' => $this->getTable('eav/entity_attribute')), 'default.attribute_id=set_table.attribute_id AND ' . 'set_table.attribute_set_id=' . intval($setId), array() ); } $joinCondition = 'main.attribute_id=default.attribute_id AND ' . $this->_read->quoteInto('main.store_id=? AND ', intval($storeId)) . $this->_read->quoteInto('main.'.$this->getEntityIdField() . '=?', $object->getId()); $select->joinLeft( array('main' => $table), $joinCondition, array( 'store_value_id' => 'value_id', 'store_value' => 'value' )) ->where('default.'.$this->getEntityIdField() . '=?', $object->getId()) ->where('default.store_id=?', $this->getDefaultStoreId()); return $select; } /** * Initialize attribute value for object * * @param Varien_Object $object * @param array $valueRow * @return Mage_Eav_Model_Entity_Abstract */ protected function _setAttribteValue($object, $valueRow) { parent::_setAttribteValue($object, $valueRow); if ($attribute = $this->getAttribute($valueRow['attribute_id'])) { $attributeCode = $attribute->getAttributeCode(); if (isset($valueRow['store_value'])) { $object->setAttributeDefaultValue($attributeCode, $valueRow['value']); $object->setData($attributeCode, $valueRow['store_value']); $attribute->getBackend()->setValueId($valueRow['store_value_id']); } } return $this; } /** * Insert entity attribute value * * Insert attribute value we do only for default store * * @param Varien_Object $object * @param Mage_Eav_Model_Entity_Attribute_Abstract $attribute * @param mixed $value * @return Mage_Eav_Model_Entity_Abstract */ protected function _insertAttribute($object, $attribute, $value) { $entityIdField = $attribute->getBackend()->getEntityIdField(); $row = array( $entityIdField => $object->getId(), 'entity_type_id'=> $object->getEntityTypeId(), 'attribute_id' => $attribute->getId(), 'value' => $this->_prepareValueForSave($value, $attribute), 'store_id' => $this->getDefaultStoreId() ); $fields = array(); $values = array(); foreach ($row as $k => $v) { $fields[] = $this->_getWriteAdapter()->quoteIdentifier('?', $k); $values[] = $this->_getWriteAdapter()->quoteInto('?', $v); } $sql = sprintf('INSERT IGNORE INTO %s (%s) VALUES(%s)', $this->_getWriteAdapter()->quoteIdentifier($attribute->getBackend()->getTable()), join(',', array_keys($row)), join(',', $values)); $this->_getWriteAdapter()->query($sql); if (!$lastId = $this->_getWriteAdapter()->lastInsertId()) { $select = $this->_getReadAdapter()->select() ->from($attribute->getBackend()->getTable(), 'value_id') ->where($entityIdField . '=?', $row[$entityIdField]) ->where('entity_type_id=?', $row['entity_type_id']) ->where('attribute_id=?', $row['attribute_id']) ->where('store_id=?', $row['store_id']); $lastId = $select->query()->fetchColumn(); } if ($object->getStoreId() != $this->getDefaultStoreId()) { $this->_updateAttribute($object, $attribute, $lastId, $value); } return $this; } /** * Update entity attribute value * * @param Varien_Object $object * @param Mage_Eav_Model_Entity_Attribute_Abstract $attribute * @param mixed $valueId * @param mixed $value * @return Mage_Eav_Model_Entity_Abstract */ protected function _updateAttribute($object, $attribute, $valueId, $value) { /** * If we work in single store mode all values should be saved just * for default store id * In this case we clear all not default values */ if (Mage::app()->isSingleStoreMode()) { $this->_getWriteAdapter()->delete( $attribute->getBackend()->getTable(), $this->_getWriteAdapter()->quoteInto('attribute_id=?', $attribute->getId()) . $this->_getWriteAdapter()->quoteInto(' AND entity_id=?', $object->getId()) . $this->_getWriteAdapter()->quoteInto(' AND store_id!=?', Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID) ); } /** * Update attribute value for store */ if ($attribute->isScopeStore()) { $this->_updateAttributeForStore($object, $attribute, $value, $object->getStoreId()); } /** * Update attribute value for website */ elseif ($attribute->isScopeWebsite()) { if ($object->getStoreId() == 0) { $this->_updateAttributeForStore($object, $attribute, $value, $object->getStoreId()); } else { if (is_array($object->getWebsiteStoreIds())) { foreach ($object->getWebsiteStoreIds() as $storeId) { $this->_updateAttributeForStore($object, $attribute, $value, $storeId); } } } } else { $this->_getWriteAdapter()->update($attribute->getBackend()->getTable(), array('value' => $this->_prepareValueForSave($value, $attribute)), 'value_id='.(int)$valueId ); } return $this; } /** * Update attribute value for specific store * * @param Mage_Catalog_Model_Abstract $object * @param object $attribute * @param mixed $value * @param int $storeId * @return Mage_Catalog_Model_Resource_Eav_Mysql4_Abstract */ protected function _updateAttributeForStore($object, $attribute, $value, $storeId) { $entityIdField = $attribute->getBackend()->getEntityIdField(); $select = $this->_getWriteAdapter()->select() ->from($attribute->getBackend()->getTable(), 'value_id') ->where('entity_type_id=?', $object->getEntityTypeId()) ->where("$entityIdField=?",$object->getId()) ->where('store_id=?', $storeId) ->where('attribute_id=?', $attribute->getId()); /** * When value for store exist */ if ($valueId = $this->_getWriteAdapter()->fetchOne($select)) { $this->_getWriteAdapter()->update($attribute->getBackend()->getTable(), array('value' => $this->_prepareValueForSave($value, $attribute)), 'value_id='.$valueId ); } else { $this->_getWriteAdapter()->insert($attribute->getBackend()->getTable(), array( $entityIdField => $object->getId(), 'entity_type_id'=> $object->getEntityTypeId(), 'attribute_id' => $attribute->getId(), 'value' => $this->_prepareValueForSave($value, $attribute), 'store_id' => $storeId )); } return $this; } /** * Delete entity attribute values * * @param Varien_Object $object * @param string $table * @param array $info * @return Varien_Object */ protected function _deleteAttributes($object, $table, $info) { $entityIdField = $this->getEntityIdField(); $globalValues = array(); $websiteAttributes = array(); $storeAttributes = array(); /** * Separate attributes by scope */ foreach ($info as $itemData) { $attribute = $this->getAttribute($itemData['attribute_id']); if ($attribute->isScopeStore()) { $storeAttributes[] = $itemData['attribute_id']; } elseif ($attribute->isScopeWebsite()) { $websiteAttributes[] = $itemData['attribute_id']; } else { $globalValues[] = $itemData['value_id']; } } /** * Delete global scope attributes */ if (!empty($globalValues)) { $condition = $this->_getWriteAdapter()->quoteInto('value_id IN (?)', $globalValues); $this->_getWriteAdapter()->delete($table, $condition); } $condition = $this->_getWriteAdapter()->quoteInto("$entityIdField=?", $object->getId()) . $this->_getWriteAdapter()->quoteInto(' AND entity_type_id=?', $object->getEntityTypeId()); /** * Delete website scope attributes */ if (!empty($websiteAttributes)) { $storeIds = $object->getWebsiteStoreIds(); if (!empty($storeIds)) { $delCondition = $condition . $this->_getWriteAdapter()->quoteInto(' AND attribute_id IN(?)', $websiteAttributes) . $this->_getWriteAdapter()->quoteInto(' AND store_id IN(?)', $storeIds); $this->_getWriteAdapter()->delete($table, $delCondition); } } /** * Delete store scope attributes */ if (!empty($storeAttributes)) { $delCondition = $condition . $this->_getWriteAdapter()->quoteInto(' AND attribute_id IN(?)', $storeAttributes) . $this->_getWriteAdapter()->quoteInto(' AND store_id =?', $object->getStoreId()); $this->_getWriteAdapter()->delete($table, $delCondition);; } return $this; } protected function _getOrigObject($object) { $className = get_class($object); $origObject = new $className(); $origObject->setData(array()); $origObject->setStoreId($object->getStoreId()); $this->load($origObject, $object->getData($this->getEntityIdField())); return $origObject; } protected function _collectOrigData($object) { $this->loadAllAttributes($object); if ($this->getUseDataSharing()) { $storeId = $object->getStoreId(); } else { $storeId = $this->getStoreId(); } $allStores = Mage::getConfig()->getStoresConfigByPath('system/store/id', array(), 'code'); //echo "<pre>".print_r($allStores ,1)."</pre>"; exit; $data = array(); foreach ($this->getAttributesByTable() as $table=>$attributes) { $entityIdField = current($attributes)->getBackend()->getEntityIdField(); $select = $this->_read->select() ->from($table) ->where($this->getEntityIdField()."=?", $object->getId()); $where = $this->_read->quoteInto("store_id=?", $storeId); $globalAttributeIds = array(); foreach ($attributes as $attrCode=>$attr) { if ($attr->getIsGlobal()) { $globalAttributeIds[] = $attr->getId(); } } if (!empty($globalAttributeIds)) { $where .= ' or '.$this->_read->quoteInto('attribute_id in (?)', $globalAttributeIds); } $select->where($where); $values = $this->_read->fetchAll($select); if (empty($values)) { continue; } foreach ($values as $row) { $data[$this->getAttribute($row['attribute_id'])->getName()][$row['store_id']] = $row; } foreach ($attributes as $attrCode=>$attr) { } } return $data; } }
gpl-2.0
sancome/linux-3.x
drivers/scsi/sd.c
101176
/* * sd.c Copyright (C) 1992 Drew Eckhardt * Copyright (C) 1993, 1994, 1995, 1999 Eric Youngdale * * Linux scsi disk driver * Initial versions: Drew Eckhardt * Subsequent revisions: Eric Youngdale * Modification history: * - Drew Eckhardt <[email protected]> original * - Eric Youngdale <[email protected]> add scatter-gather, multiple * outstanding request, and other enhancements. * Support loadable low-level scsi drivers. * - Jirka Hanika <[email protected]> support more scsi disks using * eight major numbers. * - Richard Gooch <[email protected]> support devfs. * - Torben Mathiasen <[email protected]> Resource allocation fixes in * sd_init and cleanups. * - Alex Davis <[email protected]> Fix problem where partition info * not being read in sd_open. Fix problem where removable media * could be ejected after sd_open. * - Douglas Gilbert <[email protected]> cleanup for lk 2.5.x * - Badari Pulavarty <[email protected]>, Matthew Wilcox * <[email protected]>, Kurt Garloff <[email protected]>: * Support 32k/1M disks. * * Logging policy (needs CONFIG_SCSI_LOGGING defined): * - setting up transfer: SCSI_LOG_HLQUEUE levels 1 and 2 * - end of transfer (bh + scsi_lib): SCSI_LOG_HLCOMPLETE level 1 * - entering sd_ioctl: SCSI_LOG_IOCTL level 1 * - entering other commands: SCSI_LOG_HLQUEUE level 3 * Note: when the logging level is set by the user, it must be greater * than the level indicated above to trigger output. */ #include <linux/module.h> #include <linux/fs.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/bio.h> #include <linux/genhd.h> #include <linux/hdreg.h> #include <linux/errno.h> #include <linux/idr.h> #include <linux/interrupt.h> #include <linux/init.h> #include <linux/blkdev.h> #include <linux/blkpg.h> #include <linux/delay.h> #include <linux/mutex.h> #include <linux/string_helpers.h> #include <linux/async.h> #include <linux/slab.h> #include <linux/ata.h> #include <asm/uaccess.h> #include <asm/unaligned.h> #include <scsi/scsi.h> #include <scsi/scsi_cmnd.h> #include <scsi/scsi_dbg.h> #include <scsi/scsi_device.h> #include <scsi/scsi_driver.h> #include <scsi/scsi_eh.h> #include <scsi/scsi_host.h> #include <scsi/scsi_ioctl.h> #include <scsi/scsicam.h> #ifdef SYNO_SAS_DISK_NAME #include <scsi/scsi_transport_sas.h> #endif #include "sd.h" #include "scsi_logging.h" MODULE_AUTHOR("Eric Youngdale"); MODULE_DESCRIPTION("SCSI disk (sd) driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK0_MAJOR); MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK1_MAJOR); MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK2_MAJOR); MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK3_MAJOR); MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK4_MAJOR); MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK5_MAJOR); MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK6_MAJOR); MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK7_MAJOR); MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK8_MAJOR); MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK9_MAJOR); MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK10_MAJOR); MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK11_MAJOR); MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK12_MAJOR); MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK13_MAJOR); MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK14_MAJOR); MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK15_MAJOR); MODULE_ALIAS_SCSI_DEVICE(TYPE_DISK); MODULE_ALIAS_SCSI_DEVICE(TYPE_MOD); MODULE_ALIAS_SCSI_DEVICE(TYPE_RBC); #if !defined(CONFIG_DEBUG_BLOCK_EXT_DEVT) #define SD_MINORS 16 #else #define SD_MINORS 0 #endif #ifdef MY_ABC_HERE extern int syno_hibernation_log_sec; #endif #ifdef MY_ABC_HERE extern int gSynoHasDynModule; #endif #ifdef CONFIG_SYNO_ARMADA extern int gSynoUSBStation; #endif #ifdef MY_ABC_HERE struct SpinupQueue { spinlock_t q_lock; unsigned int q_id; atomic_t q_spinup_quota; struct list_head q_disk_list; struct list_head q_head; }; LIST_HEAD(SpinupListHead); DEFINE_SPINLOCK(SpinupListLock); #endif /* MY_ABC_HERE */ static void sd_config_discard(struct scsi_disk *, unsigned int); static int sd_revalidate_disk(struct gendisk *); static void sd_unlock_native_capacity(struct gendisk *disk); static int sd_probe(struct device *); static int sd_remove(struct device *); static void sd_shutdown(struct device *); static int sd_suspend(struct device *, pm_message_t state); static int sd_resume(struct device *); static void sd_rescan(struct device *); static int sd_done(struct scsi_cmnd *); static void sd_read_capacity(struct scsi_disk *sdkp, unsigned char *buffer); static void scsi_disk_release(struct device *cdev); static void sd_print_sense_hdr(struct scsi_disk *, struct scsi_sense_hdr *); static void sd_print_result(struct scsi_disk *, int); static DEFINE_SPINLOCK(sd_index_lock); static DEFINE_IDA(sd_index_ida); #ifdef MY_ABC_HERE #include <linux/libata.h> #include <linux/usb.h> #include "../usb/storage/usb.h" #ifdef SYNO_SAS_DISK_NAME static DEFINE_IDA(usb_index_ida); static DEFINE_IDA(iscsi_index_ida); static DEFINE_IDA(sas_index_ida); extern int g_is_sas_model; #endif #ifdef SYNO_SATA_PM_DEVICE_GPIO extern u8 syno_is_synology_pm(const struct ata_port *ap); #endif #endif /* This semaphore is used to mediate the 0->1 reference get in the * face of object destruction (i.e. we can't allow a get on an * object after last put) */ static DEFINE_MUTEX(sd_ref_mutex); static struct kmem_cache *sd_cdb_cache; static mempool_t *sd_cdb_pool; static const char *sd_cache_types[] = { "write through", "none", "write back", "write back, no read (daft)" }; static ssize_t sd_store_cache_type(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int i, ct = -1, rcd, wce, sp; struct scsi_disk *sdkp = to_scsi_disk(dev); struct scsi_device *sdp = sdkp->device; char buffer[64]; char *buffer_data; struct scsi_mode_data data; struct scsi_sense_hdr sshdr; int len; if (sdp->type != TYPE_DISK) /* no cache control on RBC devices; theoretically they * can do it, but there's probably so many exceptions * it's not worth the risk */ return -EINVAL; for (i = 0; i < ARRAY_SIZE(sd_cache_types); i++) { len = strlen(sd_cache_types[i]); if (strncmp(sd_cache_types[i], buf, len) == 0 && buf[len] == '\n') { ct = i; break; } } if (ct < 0) return -EINVAL; rcd = ct & 0x01 ? 1 : 0; wce = ct & 0x02 ? 1 : 0; if (scsi_mode_sense(sdp, 0x08, 8, buffer, sizeof(buffer), SD_TIMEOUT, SD_MAX_RETRIES, &data, NULL)) return -EINVAL; len = min_t(size_t, sizeof(buffer), data.length - data.header_length - data.block_descriptor_length); buffer_data = buffer + data.header_length + data.block_descriptor_length; buffer_data[2] &= ~0x05; buffer_data[2] |= wce << 2 | rcd; sp = buffer_data[0] & 0x80 ? 1 : 0; if (scsi_mode_select(sdp, 1, sp, 8, buffer_data, len, SD_TIMEOUT, SD_MAX_RETRIES, &data, &sshdr)) { if (scsi_sense_valid(&sshdr)) sd_print_sense_hdr(sdkp, &sshdr); return -EINVAL; } revalidate_disk(sdkp->disk); return count; } static ssize_t sd_store_manage_start_stop(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct scsi_disk *sdkp = to_scsi_disk(dev); struct scsi_device *sdp = sdkp->device; if (!capable(CAP_SYS_ADMIN)) return -EACCES; sdp->manage_start_stop = simple_strtoul(buf, NULL, 10); return count; } #ifdef MY_ABC_HERE #ifdef SYNO_SAS_SPINUP_DELAY_DEBUG static void SpinupQueueDump(struct SpinupQueue *q) { struct scsi_device *d; printk(" QUEUE %d:\n", q->q_id); list_for_each_entry(d, &(q->q_disk_list), spinup_list) { printk(" disk [%d]\n", d->id); } } static void SpinupQueueDumpAll(void) { struct SpinupQueue *q; printk(" -------- queue dump\n"); list_for_each_entry(q, &SpinupListHead, q_head) { SpinupQueueDump(q); } printk(" ======== queue dump\n"); } #endif /* SYNO_SAS_SPINUP_DELAY_DEBUG */ /** * * Must be called with lock held. */ static struct SpinupQueue * SpinupQueueFindById(unsigned int id) { struct SpinupQueue *q; list_for_each_entry(q, &SpinupListHead, q_head) { if (q->q_id == id) { return q; } } return NULL; } /** * * Must be called with lock held. */ static struct SpinupQueue * SpinupQueueAlloc(unsigned int id) { struct SpinupQueue *qNew; /* TODO check parameter */ qNew = kmalloc(sizeof(struct SpinupQueue), GFP_KERNEL); INIT_LIST_HEAD(&(qNew->q_disk_list)); INIT_LIST_HEAD(&(qNew->q_head)); qNew->q_id = id; spin_lock_init(&(qNew->q_lock)); atomic_set(&(qNew->q_spinup_quota), 4); /* TODO set to some changable default value */ #ifdef SYNO_SAS_SPINUP_DELAY_DEBUG printk(" == add queue %p for id %d\n", qNew, id); #endif /* SYNO_SAS_SPINUP_DELAY_DEBUG */ return qNew; } static int SpinupQueueDiskAdd(struct SpinupQueue *sq, struct scsi_device *sd) { unsigned long flags; spin_lock_irqsave(&(sq->q_lock), flags); list_add_tail(&(sd->spinup_list), &(sq->q_disk_list)); sd->spinup_queue = sq; spin_unlock_irqrestore(&(sq->q_lock), flags); return 0; } static int SpinupQueueDiskRemove(struct SpinupQueue *pSQ, struct scsi_device *pSD) { unsigned long flags; if (NULL == pSD->spinup_queue) { return 0; } spin_lock_irqsave(&(pSQ->q_lock), flags); BUG_ON(pSQ != pSD->spinup_queue); list_del(&(pSD->spinup_list)); pSD->spinup_queue = NULL; spin_unlock_irqrestore(&(pSQ->q_lock), flags); return 0; } static void SpinupQueueSet(struct scsi_device *sdp, unsigned int new_id) { unsigned int old_id; struct SpinupQueue *qOld; struct SpinupQueue *qNew; unsigned long flags; /* lock */ spin_lock_irqsave(&SpinupListLock, flags); old_id = sdp->spinup_queue_id; if (old_id == new_id) { /* No change. Do nothing. */ spin_unlock_irqrestore(&SpinupListLock, flags); return; } /* If it was in another queue, remove first. */ if (NULL != sdp->spinup_queue) { unsigned long flags_sd; #ifdef SYNO_SAS_SPINUP_DELAY_DEBUG sdev_printk(KERN_ERR, sdp, " = remove disk from queue %d\n", sdp->spinup_queue->q_id); #endif /* SYNO_SAS_SPINUP_DELAY_DEBUG */ /* delete disk from old list */ qOld = sdp->spinup_queue; BUG_ON(NULL == qOld); SpinupQueueDiskRemove(qOld, sdp); /* Delete the queue if it is empty */ spin_lock_irqsave(&(qOld->q_lock), flags_sd); if (list_empty(&(qOld->q_disk_list))) { list_del(&(qOld->q_head)); } spin_unlock_irqrestore(&(qOld->q_lock), flags_sd); } if (new_id) { /* Want to be added to a new queue */ #ifdef SYNO_SAS_SPINUP_DELAY_DEBUG sdev_printk(KERN_ERR, sdp, " = add disk from queue %d\n", new_id); #endif /* SYNO_SAS_SPINUP_DELAY_DEBUG */ /* Find list of the given id */ qNew = SpinupQueueFindById(new_id); /* if not found, create a new list for this id. */ if (NULL == qNew) { /* alloc & init */ qNew = SpinupQueueAlloc(new_id); /* Insert into queue list */ list_add_tail( &(qNew->q_head), &SpinupListHead); } /* then add self into disk list of queue. */ SpinupQueueDiskAdd(qNew, sdp); } sdp->spinup_queue_id = new_id; #ifdef SYNO_SAS_SPINUP_DELAY_DEBUG SpinupQueueDumpAll(); #endif /* SYNO_SAS_SPINUP_DELAY_DEBUG */ /* TODO create queue, add to existing queue, or remove queue */ spin_unlock_irqrestore(&SpinupListLock, flags); } static ssize_t sd_store_spinup_queue_id(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct scsi_disk *sdkp = to_scsi_disk(dev); struct scsi_device *sdp = sdkp->device; unsigned int new_id; if (!capable(CAP_SYS_ADMIN)) return -EACCES; new_id = simple_strtoul(buf, NULL, 10); SpinupQueueSet(sdp, new_id); return count; } /** * * Check if disk can spin up, and log spinup status. * * To be called from scsi midlayer to reflect spinup status. * * Return: * - 1 if caller can spinup disk * - 0 if caller must not spin up disk. */ int SynoSpinupBegin(struct scsi_device *device) { int ret = 0; struct SpinupQueue *q; /* Only handle disks that has been added to queue. */ q = device->spinup_queue; if (NULL == q) { goto Return; } /* Check if this disk is spinning up */ if (device->spinup_in_process) { /* Already spinning up. */ goto Return; } /* Atomic dec */ if (atomic_read(&(device->spinup_queue->q_spinup_quota))) { atomic_dec(&(device->spinup_queue->q_spinup_quota)); } else { /* No quota to spin up more disks. Just let it retry. */ goto Return; } #ifdef SYNO_SAS_SPINUP_DELAY_DEBUG sdev_printk(KERN_ERR, device, "Spinup disk...\n"); #endif /* SYNO_SAS_SPINUP_DELAY_DEBUG */ device->spinup_in_process = 1; /* caller can spin up disk now. */ ret = 1; Return: return ret; } /** * Clean up spinup status. * * Called from SCSI midlayer when spinup is done. */ void SynoSpinupEnd(struct scsi_device *sdev) { struct SpinupQueue *q; q = sdev->spinup_queue; atomic_inc(&(sdev->spinup_queue->q_spinup_quota)); sdev->spinup_in_process = 0; #ifdef SYNO_SAS_SPINUP_DELAY_DEBUG sdev_printk(KERN_ERR, sdev, "Spinup done. Q %d remaining %d \n", sdev->spinup_queue_id, atomic_read(&(sdev->spinup_queue->q_spinup_quota))); #endif /* SYNO_SAS_SPINUP_DELAY_DEBUG */ } int SynoSpinupRemove(struct scsi_device *sdev) { unsigned long flags; int ret; spin_lock_irqsave(&SpinupListLock, flags); ret = SpinupQueueDiskRemove(sdev->spinup_queue, sdev); spin_unlock_irqrestore(&SpinupListLock, flags); return ret; } #endif /* MY_ABC_HERE */ static ssize_t sd_store_allow_restart(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct scsi_disk *sdkp = to_scsi_disk(dev); struct scsi_device *sdp = sdkp->device; if (!capable(CAP_SYS_ADMIN)) return -EACCES; if (sdp->type != TYPE_DISK) return -EINVAL; sdp->allow_restart = simple_strtoul(buf, NULL, 10); return count; } static ssize_t sd_show_cache_type(struct device *dev, struct device_attribute *attr, char *buf) { struct scsi_disk *sdkp = to_scsi_disk(dev); int ct = sdkp->RCD + 2*sdkp->WCE; return snprintf(buf, 40, "%s\n", sd_cache_types[ct]); } static ssize_t sd_show_fua(struct device *dev, struct device_attribute *attr, char *buf) { struct scsi_disk *sdkp = to_scsi_disk(dev); return snprintf(buf, 20, "%u\n", sdkp->DPOFUA); } static ssize_t sd_show_manage_start_stop(struct device *dev, struct device_attribute *attr, char *buf) { struct scsi_disk *sdkp = to_scsi_disk(dev); struct scsi_device *sdp = sdkp->device; return snprintf(buf, 20, "%u\n", sdp->manage_start_stop); } #ifdef MY_ABC_HERE static ssize_t sd_show_spinup_queue_id(struct device *dev, struct device_attribute *attr, char *buf) { struct scsi_disk *sdkp = to_scsi_disk(dev); struct scsi_device *sdp = sdkp->device; return snprintf(buf, 20, "%u\n", sdp->spinup_queue_id); } #endif /* MY_ABC_HERE */ static ssize_t sd_show_allow_restart(struct device *dev, struct device_attribute *attr, char *buf) { struct scsi_disk *sdkp = to_scsi_disk(dev); return snprintf(buf, 40, "%d\n", sdkp->device->allow_restart); } static ssize_t sd_show_protection_type(struct device *dev, struct device_attribute *attr, char *buf) { struct scsi_disk *sdkp = to_scsi_disk(dev); return snprintf(buf, 20, "%u\n", sdkp->protection_type); } static ssize_t sd_show_protection_mode(struct device *dev, struct device_attribute *attr, char *buf) { struct scsi_disk *sdkp = to_scsi_disk(dev); struct scsi_device *sdp = sdkp->device; unsigned int dif, dix; dif = scsi_host_dif_capable(sdp->host, sdkp->protection_type); dix = scsi_host_dix_capable(sdp->host, sdkp->protection_type); if (!dix && scsi_host_dix_capable(sdp->host, SD_DIF_TYPE0_PROTECTION)) { dif = 0; dix = 1; } if (!dif && !dix) return snprintf(buf, 20, "none\n"); return snprintf(buf, 20, "%s%u\n", dix ? "dix" : "dif", dif); } static ssize_t sd_show_app_tag_own(struct device *dev, struct device_attribute *attr, char *buf) { struct scsi_disk *sdkp = to_scsi_disk(dev); return snprintf(buf, 20, "%u\n", sdkp->ATO); } static ssize_t sd_show_thin_provisioning(struct device *dev, struct device_attribute *attr, char *buf) { struct scsi_disk *sdkp = to_scsi_disk(dev); return snprintf(buf, 20, "%u\n", sdkp->lbpme); } static const char *lbp_mode[] = { [SD_LBP_FULL] = "full", [SD_LBP_UNMAP] = "unmap", [SD_LBP_WS16] = "writesame_16", [SD_LBP_WS10] = "writesame_10", [SD_LBP_ZERO] = "writesame_zero", [SD_LBP_DISABLE] = "disabled", }; static ssize_t sd_show_provisioning_mode(struct device *dev, struct device_attribute *attr, char *buf) { struct scsi_disk *sdkp = to_scsi_disk(dev); return snprintf(buf, 20, "%s\n", lbp_mode[sdkp->provisioning_mode]); } static ssize_t sd_store_provisioning_mode(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct scsi_disk *sdkp = to_scsi_disk(dev); struct scsi_device *sdp = sdkp->device; if (!capable(CAP_SYS_ADMIN)) return -EACCES; if (sdp->type != TYPE_DISK) return -EINVAL; if (!strncmp(buf, lbp_mode[SD_LBP_UNMAP], 20)) sd_config_discard(sdkp, SD_LBP_UNMAP); else if (!strncmp(buf, lbp_mode[SD_LBP_WS16], 20)) sd_config_discard(sdkp, SD_LBP_WS16); else if (!strncmp(buf, lbp_mode[SD_LBP_WS10], 20)) sd_config_discard(sdkp, SD_LBP_WS10); else if (!strncmp(buf, lbp_mode[SD_LBP_ZERO], 20)) sd_config_discard(sdkp, SD_LBP_ZERO); else if (!strncmp(buf, lbp_mode[SD_LBP_DISABLE], 20)) sd_config_discard(sdkp, SD_LBP_DISABLE); else return -EINVAL; return count; } static struct device_attribute sd_disk_attrs[] = { __ATTR(cache_type, S_IRUGO|S_IWUSR, sd_show_cache_type, sd_store_cache_type), __ATTR(FUA, S_IRUGO, sd_show_fua, NULL), __ATTR(allow_restart, S_IRUGO|S_IWUSR, sd_show_allow_restart, sd_store_allow_restart), __ATTR(manage_start_stop, S_IRUGO|S_IWUSR, sd_show_manage_start_stop, sd_store_manage_start_stop), #ifdef MY_ABC_HERE __ATTR(spinup_queue_id, S_IRUGO|S_IWUSR, sd_show_spinup_queue_id, sd_store_spinup_queue_id), #endif /* MY_ABC_HERE */ __ATTR(protection_type, S_IRUGO, sd_show_protection_type, NULL), __ATTR(protection_mode, S_IRUGO, sd_show_protection_mode, NULL), __ATTR(app_tag_own, S_IRUGO, sd_show_app_tag_own, NULL), __ATTR(thin_provisioning, S_IRUGO, sd_show_thin_provisioning, NULL), __ATTR(provisioning_mode, S_IRUGO|S_IWUSR, sd_show_provisioning_mode, sd_store_provisioning_mode), __ATTR_NULL, }; static struct class sd_disk_class = { .name = "scsi_disk", .owner = THIS_MODULE, .dev_release = scsi_disk_release, .dev_attrs = sd_disk_attrs, }; static struct scsi_driver sd_template = { .owner = THIS_MODULE, .gendrv = { .name = "sd", .probe = sd_probe, .remove = sd_remove, .suspend = sd_suspend, .resume = sd_resume, .shutdown = sd_shutdown, }, .rescan = sd_rescan, .done = sd_done, }; /* * Device no to disk mapping: * * major disc2 disc p1 * |............|.............|....|....| <- dev_t * 31 20 19 8 7 4 3 0 * * Inside a major, we have 16k disks, however mapped non- * contiguously. The first 16 disks are for major0, the next * ones with major1, ... Disk 256 is for major0 again, disk 272 * for major1, ... * As we stay compatible with our numbering scheme, we can reuse * the well-know SCSI majors 8, 65--71, 136--143. */ static int sd_major(int major_idx) { switch (major_idx) { case 0: return SCSI_DISK0_MAJOR; case 1 ... 7: return SCSI_DISK1_MAJOR + major_idx - 1; case 8 ... 15: return SCSI_DISK8_MAJOR + major_idx - 8; default: BUG(); return 0; /* shut up gcc */ } } static struct scsi_disk *__scsi_disk_get(struct gendisk *disk) { struct scsi_disk *sdkp = NULL; if (disk->private_data) { sdkp = scsi_disk(disk); if (scsi_device_get(sdkp->device) == 0) get_device(&sdkp->dev); else sdkp = NULL; } return sdkp; } static struct scsi_disk *scsi_disk_get(struct gendisk *disk) { struct scsi_disk *sdkp; mutex_lock(&sd_ref_mutex); sdkp = __scsi_disk_get(disk); mutex_unlock(&sd_ref_mutex); return sdkp; } static struct scsi_disk *scsi_disk_get_from_dev(struct device *dev) { struct scsi_disk *sdkp; mutex_lock(&sd_ref_mutex); sdkp = dev_get_drvdata(dev); if (sdkp) sdkp = __scsi_disk_get(sdkp->disk); mutex_unlock(&sd_ref_mutex); return sdkp; } static void scsi_disk_put(struct scsi_disk *sdkp) { struct scsi_device *sdev = sdkp->device; mutex_lock(&sd_ref_mutex); put_device(&sdkp->dev); scsi_device_put(sdev); mutex_unlock(&sd_ref_mutex); } static void sd_prot_op(struct scsi_cmnd *scmd, unsigned int dif) { unsigned int prot_op = SCSI_PROT_NORMAL; unsigned int dix = scsi_prot_sg_count(scmd); if (scmd->sc_data_direction == DMA_FROM_DEVICE) { if (dif && dix) prot_op = SCSI_PROT_READ_PASS; else if (dif && !dix) prot_op = SCSI_PROT_READ_STRIP; else if (!dif && dix) prot_op = SCSI_PROT_READ_INSERT; } else { if (dif && dix) prot_op = SCSI_PROT_WRITE_PASS; else if (dif && !dix) prot_op = SCSI_PROT_WRITE_INSERT; else if (!dif && dix) prot_op = SCSI_PROT_WRITE_STRIP; } scsi_set_prot_op(scmd, prot_op); scsi_set_prot_type(scmd, dif); } static void sd_config_discard(struct scsi_disk *sdkp, unsigned int mode) { struct request_queue *q = sdkp->disk->queue; unsigned int logical_block_size = sdkp->device->sector_size; unsigned int max_blocks = 0; q->limits.discard_zeroes_data = sdkp->lbprz; q->limits.discard_alignment = sdkp->unmap_alignment * logical_block_size; q->limits.discard_granularity = max(sdkp->physical_block_size, sdkp->unmap_granularity * logical_block_size); switch (mode) { case SD_LBP_DISABLE: q->limits.max_discard_sectors = 0; queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD, q); return; case SD_LBP_UNMAP: max_blocks = min_not_zero(sdkp->max_unmap_blocks, 0xffffffff); break; case SD_LBP_WS16: max_blocks = min_not_zero(sdkp->max_ws_blocks, 0xffffffff); break; case SD_LBP_WS10: max_blocks = min_not_zero(sdkp->max_ws_blocks, (u32)0xffff); break; case SD_LBP_ZERO: max_blocks = min_not_zero(sdkp->max_ws_blocks, (u32)0xffff); q->limits.discard_zeroes_data = 1; break; } q->limits.max_discard_sectors = max_blocks * (logical_block_size >> 9); queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, q); sdkp->provisioning_mode = mode; } /** * scsi_setup_discard_cmnd - unmap blocks on thinly provisioned device * @sdp: scsi device to operate one * @rq: Request to prepare * * Will issue either UNMAP or WRITE SAME(16) depending on preference * indicated by target device. **/ static int scsi_setup_discard_cmnd(struct scsi_device *sdp, struct request *rq) { struct scsi_disk *sdkp = scsi_disk(rq->rq_disk); struct bio *bio = rq->bio; sector_t sector = bio->bi_sector; unsigned int nr_sectors = bio_sectors(bio); unsigned int len; int ret; char *buf; struct page *page; if (sdkp->device->sector_size == 4096) { sector >>= 3; nr_sectors >>= 3; } rq->timeout = SD_TIMEOUT; memset(rq->cmd, 0, rq->cmd_len); page = alloc_page(GFP_ATOMIC | __GFP_ZERO); if (!page) return BLKPREP_DEFER; switch (sdkp->provisioning_mode) { case SD_LBP_UNMAP: buf = page_address(page); rq->cmd_len = 10; rq->cmd[0] = UNMAP; rq->cmd[8] = 24; put_unaligned_be16(6 + 16, &buf[0]); put_unaligned_be16(16, &buf[2]); put_unaligned_be64(sector, &buf[8]); put_unaligned_be32(nr_sectors, &buf[16]); len = 24; break; case SD_LBP_WS16: rq->cmd_len = 16; rq->cmd[0] = WRITE_SAME_16; rq->cmd[1] = 0x8; /* UNMAP */ put_unaligned_be64(sector, &rq->cmd[2]); put_unaligned_be32(nr_sectors, &rq->cmd[10]); len = sdkp->device->sector_size; break; case SD_LBP_WS10: case SD_LBP_ZERO: rq->cmd_len = 10; rq->cmd[0] = WRITE_SAME; if (sdkp->provisioning_mode == SD_LBP_WS10) rq->cmd[1] = 0x8; /* UNMAP */ put_unaligned_be32(sector, &rq->cmd[2]); put_unaligned_be16(nr_sectors, &rq->cmd[7]); len = sdkp->device->sector_size; break; default: ret = BLKPREP_KILL; goto out; } blk_add_request_payload(rq, page, len); ret = scsi_setup_blk_pc_cmnd(sdp, rq); rq->buffer = page_address(page); out: if (ret != BLKPREP_OK) { __free_page(page); rq->buffer = NULL; } return ret; } static int scsi_setup_flush_cmnd(struct scsi_device *sdp, struct request *rq) { rq->timeout = SD_FLUSH_TIMEOUT; rq->retries = SD_MAX_RETRIES; rq->cmd[0] = SYNCHRONIZE_CACHE; rq->cmd_len = 10; return scsi_setup_blk_pc_cmnd(sdp, rq); } static void sd_unprep_fn(struct request_queue *q, struct request *rq) { if (rq->cmd_flags & REQ_DISCARD) { free_page((unsigned long)rq->buffer); rq->buffer = NULL; } } /** * sd_init_command - build a scsi (read or write) command from * information in the request structure. * @SCpnt: pointer to mid-level's per scsi command structure that * contains request and into which the scsi command is written * * Returns 1 if successful and 0 if error (or cannot be done now). **/ static int sd_prep_fn(struct request_queue *q, struct request *rq) { struct scsi_cmnd *SCpnt; struct scsi_device *sdp = q->queuedata; struct gendisk *disk = rq->rq_disk; struct scsi_disk *sdkp; sector_t block = blk_rq_pos(rq); sector_t threshold; unsigned int this_count = blk_rq_sectors(rq); int ret, host_dif; unsigned char protect; /* * Discard request come in as REQ_TYPE_FS but we turn them into * block PC requests to make life easier. */ if (rq->cmd_flags & REQ_DISCARD) { ret = scsi_setup_discard_cmnd(sdp, rq); goto out; } else if (rq->cmd_flags & REQ_FLUSH) { ret = scsi_setup_flush_cmnd(sdp, rq); goto out; } else if (rq->cmd_type == REQ_TYPE_BLOCK_PC) { ret = scsi_setup_blk_pc_cmnd(sdp, rq); goto out; } else if (rq->cmd_type != REQ_TYPE_FS) { ret = BLKPREP_KILL; goto out; } ret = scsi_setup_fs_cmnd(sdp, rq); if (ret != BLKPREP_OK) goto out; SCpnt = rq->special; sdkp = scsi_disk(disk); /* from here on until we're complete, any goto out * is used for a killable error condition */ ret = BLKPREP_KILL; SCSI_LOG_HLQUEUE(1, scmd_printk(KERN_INFO, SCpnt, "sd_init_command: block=%llu, " "count=%d\n", (unsigned long long)block, this_count)); if (!sdp || !scsi_device_online(sdp) || block + blk_rq_sectors(rq) > get_capacity(disk)) { SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt, "Finishing %u sectors\n", blk_rq_sectors(rq))); SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt, "Retry with 0x%p\n", SCpnt)); goto out; } if (sdp->changed) { /* * quietly refuse to do anything to a changed disc until * the changed bit has been reset */ /* printk("SCSI disk has been changed or is not present. Prohibiting further I/O.\n"); */ goto out; } /* * Some SD card readers can't handle multi-sector accesses which touch * the last one or two hardware sectors. Split accesses as needed. */ threshold = get_capacity(disk) - SD_LAST_BUGGY_SECTORS * (sdp->sector_size / 512); if (unlikely(sdp->last_sector_bug && block + this_count > threshold)) { if (block < threshold) { /* Access up to the threshold but not beyond */ this_count = threshold - block; } else { /* Access only a single hardware sector */ this_count = sdp->sector_size / 512; } } SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt, "block=%llu\n", (unsigned long long)block)); /* * If we have a 1K hardware sectorsize, prevent access to single * 512 byte sectors. In theory we could handle this - in fact * the scsi cdrom driver must be able to handle this because * we typically use 1K blocksizes, and cdroms typically have * 2K hardware sectorsizes. Of course, things are simpler * with the cdrom, since it is read-only. For performance * reasons, the filesystems should be able to handle this * and not force the scsi disk driver to use bounce buffers * for this. */ if (sdp->sector_size == 1024) { if ((block & 1) || (blk_rq_sectors(rq) & 1)) { scmd_printk(KERN_ERR, SCpnt, "Bad block number requested\n"); goto out; } else { block = block >> 1; this_count = this_count >> 1; } } if (sdp->sector_size == 2048) { if ((block & 3) || (blk_rq_sectors(rq) & 3)) { scmd_printk(KERN_ERR, SCpnt, "Bad block number requested\n"); goto out; } else { block = block >> 2; this_count = this_count >> 2; } } if (sdp->sector_size == 4096) { if ((block & 7) || (blk_rq_sectors(rq) & 7)) { scmd_printk(KERN_ERR, SCpnt, "Bad block number requested\n"); goto out; } else { block = block >> 3; this_count = this_count >> 3; } } if (rq_data_dir(rq) == WRITE) { if (!sdp->writeable) { goto out; } SCpnt->cmnd[0] = WRITE_6; SCpnt->sc_data_direction = DMA_TO_DEVICE; if (blk_integrity_rq(rq) && sd_dif_prepare(rq, block, sdp->sector_size) == -EIO) goto out; } else if (rq_data_dir(rq) == READ) { SCpnt->cmnd[0] = READ_6; SCpnt->sc_data_direction = DMA_FROM_DEVICE; } else { scmd_printk(KERN_ERR, SCpnt, "Unknown command %x\n", rq->cmd_flags); goto out; } SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt, "%s %d/%u 512 byte blocks.\n", (rq_data_dir(rq) == WRITE) ? "writing" : "reading", this_count, blk_rq_sectors(rq))); /* Set RDPROTECT/WRPROTECT if disk is formatted with DIF */ host_dif = scsi_host_dif_capable(sdp->host, sdkp->protection_type); if (host_dif) protect = 1 << 5; else protect = 0; if (host_dif == SD_DIF_TYPE2_PROTECTION) { SCpnt->cmnd = mempool_alloc(sd_cdb_pool, GFP_ATOMIC); if (unlikely(SCpnt->cmnd == NULL)) { ret = BLKPREP_DEFER; goto out; } SCpnt->cmd_len = SD_EXT_CDB_SIZE; memset(SCpnt->cmnd, 0, SCpnt->cmd_len); SCpnt->cmnd[0] = VARIABLE_LENGTH_CMD; SCpnt->cmnd[7] = 0x18; SCpnt->cmnd[9] = (rq_data_dir(rq) == READ) ? READ_32 : WRITE_32; SCpnt->cmnd[10] = protect | ((rq->cmd_flags & REQ_FUA) ? 0x8 : 0); /* LBA */ SCpnt->cmnd[12] = sizeof(block) > 4 ? (unsigned char) (block >> 56) & 0xff : 0; SCpnt->cmnd[13] = sizeof(block) > 4 ? (unsigned char) (block >> 48) & 0xff : 0; SCpnt->cmnd[14] = sizeof(block) > 4 ? (unsigned char) (block >> 40) & 0xff : 0; SCpnt->cmnd[15] = sizeof(block) > 4 ? (unsigned char) (block >> 32) & 0xff : 0; SCpnt->cmnd[16] = (unsigned char) (block >> 24) & 0xff; SCpnt->cmnd[17] = (unsigned char) (block >> 16) & 0xff; SCpnt->cmnd[18] = (unsigned char) (block >> 8) & 0xff; SCpnt->cmnd[19] = (unsigned char) block & 0xff; /* Expected Indirect LBA */ SCpnt->cmnd[20] = (unsigned char) (block >> 24) & 0xff; SCpnt->cmnd[21] = (unsigned char) (block >> 16) & 0xff; SCpnt->cmnd[22] = (unsigned char) (block >> 8) & 0xff; SCpnt->cmnd[23] = (unsigned char) block & 0xff; /* Transfer length */ SCpnt->cmnd[28] = (unsigned char) (this_count >> 24) & 0xff; SCpnt->cmnd[29] = (unsigned char) (this_count >> 16) & 0xff; SCpnt->cmnd[30] = (unsigned char) (this_count >> 8) & 0xff; SCpnt->cmnd[31] = (unsigned char) this_count & 0xff; } else if (block > 0xffffffff) { SCpnt->cmnd[0] += READ_16 - READ_6; SCpnt->cmnd[1] = protect | ((rq->cmd_flags & REQ_FUA) ? 0x8 : 0); SCpnt->cmnd[2] = sizeof(block) > 4 ? (unsigned char) (block >> 56) & 0xff : 0; SCpnt->cmnd[3] = sizeof(block) > 4 ? (unsigned char) (block >> 48) & 0xff : 0; SCpnt->cmnd[4] = sizeof(block) > 4 ? (unsigned char) (block >> 40) & 0xff : 0; SCpnt->cmnd[5] = sizeof(block) > 4 ? (unsigned char) (block >> 32) & 0xff : 0; SCpnt->cmnd[6] = (unsigned char) (block >> 24) & 0xff; SCpnt->cmnd[7] = (unsigned char) (block >> 16) & 0xff; SCpnt->cmnd[8] = (unsigned char) (block >> 8) & 0xff; SCpnt->cmnd[9] = (unsigned char) block & 0xff; SCpnt->cmnd[10] = (unsigned char) (this_count >> 24) & 0xff; SCpnt->cmnd[11] = (unsigned char) (this_count >> 16) & 0xff; SCpnt->cmnd[12] = (unsigned char) (this_count >> 8) & 0xff; SCpnt->cmnd[13] = (unsigned char) this_count & 0xff; SCpnt->cmnd[14] = SCpnt->cmnd[15] = 0; } else if ((this_count > 0xff) || (block > 0x1fffff) || scsi_device_protection(SCpnt->device) || SCpnt->device->use_10_for_rw) { if (this_count > 0xffff) this_count = 0xffff; SCpnt->cmnd[0] += READ_10 - READ_6; SCpnt->cmnd[1] = protect | ((rq->cmd_flags & REQ_FUA) ? 0x8 : 0); SCpnt->cmnd[2] = (unsigned char) (block >> 24) & 0xff; SCpnt->cmnd[3] = (unsigned char) (block >> 16) & 0xff; SCpnt->cmnd[4] = (unsigned char) (block >> 8) & 0xff; SCpnt->cmnd[5] = (unsigned char) block & 0xff; SCpnt->cmnd[6] = SCpnt->cmnd[9] = 0; SCpnt->cmnd[7] = (unsigned char) (this_count >> 8) & 0xff; SCpnt->cmnd[8] = (unsigned char) this_count & 0xff; } else { if (unlikely(rq->cmd_flags & REQ_FUA)) { /* * This happens only if this drive failed * 10byte rw command with ILLEGAL_REQUEST * during operation and thus turned off * use_10_for_rw. */ scmd_printk(KERN_ERR, SCpnt, "FUA write on READ/WRITE(6) drive\n"); goto out; } SCpnt->cmnd[1] |= (unsigned char) ((block >> 16) & 0x1f); SCpnt->cmnd[2] = (unsigned char) ((block >> 8) & 0xff); SCpnt->cmnd[3] = (unsigned char) block & 0xff; SCpnt->cmnd[4] = (unsigned char) this_count; SCpnt->cmnd[5] = 0; } SCpnt->sdb.length = this_count * sdp->sector_size; /* If DIF or DIX is enabled, tell HBA how to handle request */ if (host_dif || scsi_prot_sg_count(SCpnt)) sd_prot_op(SCpnt, host_dif); /* * We shouldn't disconnect in the middle of a sector, so with a dumb * host adapter, it's safe to assume that we can at least transfer * this many bytes between each connect / disconnect. */ SCpnt->transfersize = sdp->sector_size; SCpnt->underflow = this_count << 9; SCpnt->allowed = SD_MAX_RETRIES; /* * This indicates that the command is ready from our end to be * queued. */ ret = BLKPREP_OK; out: return scsi_prep_return(q, rq, ret); } /** * sd_open - open a scsi disk device * @inode: only i_rdev member may be used * @filp: only f_mode and f_flags may be used * * Returns 0 if successful. Returns a negated errno value in case * of error. * * Note: This can be called from a user context (e.g. fsck(1) ) * or from within the kernel (e.g. as a result of a mount(1) ). * In the latter case @inode and @filp carry an abridged amount * of information as noted above. * * Locking: called with bdev->bd_mutex held. **/ static int sd_open(struct block_device *bdev, fmode_t mode) { struct scsi_disk *sdkp = scsi_disk_get(bdev->bd_disk); struct scsi_device *sdev; int retval; if (!sdkp) return -ENXIO; SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_open\n")); sdev = sdkp->device; retval = scsi_autopm_get_device(sdev); if (retval) goto error_autopm; /* * If the device is in error recovery, wait until it is done. * If the device is offline, then disallow any access to it. */ retval = -ENXIO; if (!scsi_block_when_processing_errors(sdev)) goto error_out; if (sdev->removable || sdkp->write_prot) check_disk_change(bdev); /* * If the drive is empty, just let the open fail. */ retval = -ENOMEDIUM; if (sdev->removable && !sdkp->media_present && !(mode & FMODE_NDELAY)) goto error_out; /* * If the device has the write protect tab set, have the open fail * if the user expects to be able to write to the thing. */ retval = -EROFS; if (sdkp->write_prot && (mode & FMODE_WRITE)) goto error_out; /* * It is possible that the disk changing stuff resulted in * the device being taken offline. If this is the case, * report this to the user, and don't pretend that the * open actually succeeded. */ retval = -ENXIO; if (!scsi_device_online(sdev)) goto error_out; if ((atomic_inc_return(&sdkp->openers) == 1) && sdev->removable) { if (scsi_block_when_processing_errors(sdev)) scsi_set_medium_removal(sdev, SCSI_REMOVAL_PREVENT); } return 0; error_out: scsi_autopm_put_device(sdev); error_autopm: scsi_disk_put(sdkp); return retval; } /** * sd_release - invoked when the (last) close(2) is called on this * scsi disk. * @inode: only i_rdev member may be used * @filp: only f_mode and f_flags may be used * * Returns 0. * * Note: may block (uninterruptible) if error recovery is underway * on this disk. * * Locking: called with bdev->bd_mutex held. **/ static int sd_release(struct gendisk *disk, fmode_t mode) { struct scsi_disk *sdkp = scsi_disk(disk); struct scsi_device *sdev = sdkp->device; SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_release\n")); if (atomic_dec_return(&sdkp->openers) == 0 && sdev->removable) { if (scsi_block_when_processing_errors(sdev)) scsi_set_medium_removal(sdev, SCSI_REMOVAL_ALLOW); } /* * XXX and what if there are packets in flight and this close() * XXX is followed by a "rmmod sd_mod"? */ scsi_autopm_put_device(sdev); scsi_disk_put(sdkp); return 0; } static int sd_getgeo(struct block_device *bdev, struct hd_geometry *geo) { struct scsi_disk *sdkp = scsi_disk(bdev->bd_disk); struct scsi_device *sdp = sdkp->device; struct Scsi_Host *host = sdp->host; int diskinfo[4]; /* default to most commonly used values */ diskinfo[0] = 0x40; /* 1 << 6 */ diskinfo[1] = 0x20; /* 1 << 5 */ diskinfo[2] = sdkp->capacity >> 11; /* override with calculated, extended default, or driver values */ if (host->hostt->bios_param) host->hostt->bios_param(sdp, bdev, sdkp->capacity, diskinfo); else scsicam_bios_param(bdev, sdkp->capacity, diskinfo); geo->heads = diskinfo[0]; geo->sectors = diskinfo[1]; geo->cylinders = diskinfo[2]; return 0; } #ifdef SYNO_BADSECTOR_TEST static int ScsiSetBadSector(struct gendisk *pDisk, SDBADSECTORS *pSectors) { int iDrive = SynoGetInternalDiskSeq(pDisk->disk_name); int max_support_disk = sizeof(grgSdBadSectors)/sizeof(SDBADSECTORS); if (pSectors == NULL) { return -EINVAL; } gBadSectorTest = 1; if (iDrive >= 0 && iDrive < max_support_disk) { if (copy_from_user(&grgSdBadSectors[iDrive], pSectors, sizeof(SDBADSECTORS))) { return -EINVAL; } if (grgSdBadSectors[iDrive].uiEnable) { int i; for (i = 0; i < 100; i++) { printk("%s[%d]:%s set bad sector: %u, max support disk: %d\n", __FILE__, __LINE__, pDisk->disk_name, grgSdBadSectors[iDrive].rgSectors[i], max_support_disk); if (grgSdBadSectors[iDrive].rgSectors[i] == 0xFFFFFFFF) { break; } } } return 0; } else { return -EINVAL; } } #endif /** * sd_ioctl - process an ioctl * @inode: only i_rdev/i_bdev members may be used * @filp: only f_mode and f_flags may be used * @cmd: ioctl command number * @arg: this is third argument given to ioctl(2) system call. * Often contains a pointer. * * Returns 0 if successful (some ioctls return positive numbers on * success as well). Returns a negated errno value in case of error. * * Note: most ioctls are forward onto the block subsystem or further * down in the scsi subsystem. **/ static int sd_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long arg) { struct gendisk *disk = bdev->bd_disk; struct scsi_disk *sdkp = scsi_disk(disk); struct scsi_device *sdp = sdkp->device; void __user *p = (void __user *)arg; int error; SCSI_LOG_IOCTL(1, sd_printk(KERN_INFO, sdkp, "sd_ioctl: disk=%s, " "cmd=0x%x\n", disk->disk_name, cmd)); error = scsi_verify_blk_ioctl(bdev, cmd); if (error < 0) return error; /* * If we are in the middle of error recovery, don't let anyone * else try and use this device. Also, if error recovery fails, it * may try and take the device offline, in which case all further * access to the device is prohibited. */ error = scsi_nonblockable_ioctl(sdp, cmd, p, (mode & FMODE_NDELAY) != 0); if (!scsi_block_when_processing_errors(sdp) || !error) goto out; /* * Send SCSI addressing ioctls directly to mid level, send other * ioctls to block level and then onto mid level if they can't be * resolved. */ switch (cmd) { case SCSI_IOCTL_GET_IDLUN: case SCSI_IOCTL_GET_BUS_NUMBER: error = scsi_ioctl(sdp, cmd, p); break; #ifdef SYNO_BADSECTOR_TEST case SCSI_IOCTL_SET_BADSECTORS: return ScsiSetBadSector(disk, p); #endif #ifdef MY_ABC_HERE case SD_IOCTL_IDLE: { return (jiffies - sdp->idle) / HZ + 1; } case SD_IOCTL_SUPPORT_SLEEP: { int *pCanSleep = (int *)arg; *pCanSleep = sdp->nospindown ? 0 : 1; return 0; } #endif /* MY_ABC_HERE */ default: error = scsi_cmd_blk_ioctl(bdev, mode, cmd, p); if (error != -ENOTTY) break; error = scsi_ioctl(sdp, cmd, p); break; } out: return error; } static void set_media_not_present(struct scsi_disk *sdkp) { if (sdkp->media_present) sdkp->device->changed = 1; if (sdkp->device->removable) { sdkp->media_present = 0; sdkp->capacity = 0; } } static int media_not_present(struct scsi_disk *sdkp, struct scsi_sense_hdr *sshdr) { if (!scsi_sense_valid(sshdr)) return 0; /* not invoked for commands that could return deferred errors */ switch (sshdr->sense_key) { case UNIT_ATTENTION: case NOT_READY: /* medium not present */ if (sshdr->asc == 0x3A) { set_media_not_present(sdkp); return 1; } } return 0; } /** * sd_check_events - check media events * @disk: kernel device descriptor * @clearing: disk events currently being cleared * * Returns mask of DISK_EVENT_*. * * Note: this function is invoked from the block subsystem. **/ static unsigned int sd_check_events(struct gendisk *disk, unsigned int clearing) { struct scsi_disk *sdkp = scsi_disk(disk); struct scsi_device *sdp = sdkp->device; struct scsi_sense_hdr *sshdr = NULL; int retval; SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_check_events\n")); /* * If the device is offline, don't send any commands - just pretend as * if the command failed. If the device ever comes back online, we * can deal with it then. It is only because of unrecoverable errors * that we would ever take a device offline in the first place. */ if (!scsi_device_online(sdp)) { set_media_not_present(sdkp); goto out; } /* * Using TEST_UNIT_READY enables differentiation between drive with * no cartridge loaded - NOT READY, drive with changed cartridge - * UNIT ATTENTION, or with same cartridge - GOOD STATUS. * * Drives that auto spin down. eg iomega jaz 1G, will be started * by sd_spinup_disk() from sd_revalidate_disk(), which happens whenever * sd_revalidate() is called. */ retval = -ENODEV; if (scsi_block_when_processing_errors(sdp)) { sshdr = kzalloc(sizeof(*sshdr), GFP_KERNEL); retval = scsi_test_unit_ready(sdp, SD_TIMEOUT, SD_MAX_RETRIES, sshdr); } /* failed to execute TUR, assume media not present */ if (host_byte(retval)) { set_media_not_present(sdkp); goto out; } if (media_not_present(sdkp, sshdr)) goto out; /* * For removable scsi disk we have to recognise the presence * of a disk in the drive. */ if (!sdkp->media_present) sdp->changed = 1; sdkp->media_present = 1; out: /* * sdp->changed is set under the following conditions: * * Medium present state has changed in either direction. * Device has indicated UNIT_ATTENTION. */ kfree(sshdr); retval = sdp->changed ? DISK_EVENT_MEDIA_CHANGE : 0; sdp->changed = 0; return retval; } static int sd_sync_cache(struct scsi_disk *sdkp) { int retries, res; struct scsi_device *sdp = sdkp->device; struct scsi_sense_hdr sshdr; if (!scsi_device_online(sdp)) return -ENODEV; for (retries = 3; retries > 0; --retries) { unsigned char cmd[10] = { 0 }; cmd[0] = SYNCHRONIZE_CACHE; /* * Leave the rest of the command zero to indicate * flush everything. */ res = scsi_execute_req(sdp, cmd, DMA_NONE, NULL, 0, &sshdr, SD_FLUSH_TIMEOUT, SD_MAX_RETRIES, NULL); if (res == 0) break; } if (res) { sd_print_result(sdkp, res); if (driver_byte(res) & DRIVER_SENSE) sd_print_sense_hdr(sdkp, &sshdr); } if (res) return -EIO; return 0; } static void sd_rescan(struct device *dev) { struct scsi_disk *sdkp = scsi_disk_get_from_dev(dev); if (sdkp) { revalidate_disk(sdkp->disk); scsi_disk_put(sdkp); } } #ifdef CONFIG_COMPAT /* * This gets directly called from VFS. When the ioctl * is not recognized we go back to the other translation paths. */ static int sd_compat_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long arg) { struct scsi_device *sdev = scsi_disk(bdev->bd_disk)->device; int ret; ret = scsi_verify_blk_ioctl(bdev, cmd); if (ret < 0) return -ENOIOCTLCMD; /* * If we are in the middle of error recovery, don't let anyone * else try and use this device. Also, if error recovery fails, it * may try and take the device offline, in which case all further * access to the device is prohibited. */ if (!scsi_block_when_processing_errors(sdev)) return -ENODEV; if (sdev->host->hostt->compat_ioctl) { ret = sdev->host->hostt->compat_ioctl(sdev, cmd, (void __user *)arg); return ret; } /* * Let the static ioctl translation table take care of it. */ return -ENOIOCTLCMD; } #endif static const struct block_device_operations sd_fops = { .owner = THIS_MODULE, .open = sd_open, .release = sd_release, .ioctl = sd_ioctl, .getgeo = sd_getgeo, #ifdef CONFIG_COMPAT .compat_ioctl = sd_compat_ioctl, #endif .check_events = sd_check_events, .revalidate_disk = sd_revalidate_disk, .unlock_native_capacity = sd_unlock_native_capacity, }; static unsigned int sd_completed_bytes(struct scsi_cmnd *scmd) { u64 start_lba = blk_rq_pos(scmd->request); u64 end_lba = blk_rq_pos(scmd->request) + (scsi_bufflen(scmd) / 512); u64 bad_lba; int info_valid; /* * resid is optional but mostly filled in. When it's unused, * its value is zero, so we assume the whole buffer transferred */ unsigned int transferred = scsi_bufflen(scmd) - scsi_get_resid(scmd); unsigned int good_bytes; if (scmd->request->cmd_type != REQ_TYPE_FS) return 0; info_valid = scsi_get_sense_info_fld(scmd->sense_buffer, SCSI_SENSE_BUFFERSIZE, &bad_lba); if (!info_valid) return 0; if (scsi_bufflen(scmd) <= scmd->device->sector_size) return 0; if (scmd->device->sector_size < 512) { /* only legitimate sector_size here is 256 */ start_lba <<= 1; end_lba <<= 1; } else { /* be careful ... don't want any overflows */ u64 factor = scmd->device->sector_size / 512; do_div(start_lba, factor); do_div(end_lba, factor); } /* The bad lba was reported incorrectly, we have no idea where * the error is. */ if (bad_lba < start_lba || bad_lba >= end_lba) return 0; /* This computation should always be done in terms of * the resolution of the device's medium. */ good_bytes = (bad_lba - start_lba) * scmd->device->sector_size; return min(good_bytes, transferred); } /** * sd_done - bottom half handler: called when the lower level * driver has completed (successfully or otherwise) a scsi command. * @SCpnt: mid-level's per command structure. * * Note: potentially run from within an ISR. Must not block. **/ static int sd_done(struct scsi_cmnd *SCpnt) { int result = SCpnt->result; unsigned int good_bytes = result ? 0 : scsi_bufflen(SCpnt); struct scsi_sense_hdr sshdr; struct scsi_disk *sdkp = scsi_disk(SCpnt->request->rq_disk); int sense_valid = 0; int sense_deferred = 0; unsigned char op = SCpnt->cmnd[0]; if ((SCpnt->request->cmd_flags & REQ_DISCARD) && !result) scsi_set_resid(SCpnt, 0); if (result) { sense_valid = scsi_command_normalize_sense(SCpnt, &sshdr); if (sense_valid) sense_deferred = scsi_sense_is_deferred(&sshdr); } #ifdef CONFIG_SCSI_LOGGING SCSI_LOG_HLCOMPLETE(1, scsi_print_result(SCpnt)); if (sense_valid) { SCSI_LOG_HLCOMPLETE(1, scmd_printk(KERN_INFO, SCpnt, "sd_done: sb[respc,sk,asc," "ascq]=%x,%x,%x,%x\n", sshdr.response_code, sshdr.sense_key, sshdr.asc, sshdr.ascq)); } #endif if (driver_byte(result) != DRIVER_SENSE && (!sense_valid || sense_deferred)) goto out; switch (sshdr.sense_key) { case HARDWARE_ERROR: case MEDIUM_ERROR: good_bytes = sd_completed_bytes(SCpnt); break; case RECOVERED_ERROR: good_bytes = scsi_bufflen(SCpnt); break; case NO_SENSE: /* This indicates a false check condition, so ignore it. An * unknown amount of data was transferred so treat it as an * error. */ scsi_print_sense("sd", SCpnt); SCpnt->result = 0; memset(SCpnt->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE); break; case ABORTED_COMMAND: if (sshdr.asc == 0x10) /* DIF: Target detected corruption */ good_bytes = sd_completed_bytes(SCpnt); break; case ILLEGAL_REQUEST: if (sshdr.asc == 0x10) /* DIX: Host detected corruption */ good_bytes = sd_completed_bytes(SCpnt); /* INVALID COMMAND OPCODE or INVALID FIELD IN CDB */ if ((sshdr.asc == 0x20 || sshdr.asc == 0x24) && (op == UNMAP || op == WRITE_SAME_16 || op == WRITE_SAME)) sd_config_discard(sdkp, SD_LBP_DISABLE); break; default: break; } out: if (rq_data_dir(SCpnt->request) == READ && scsi_prot_sg_count(SCpnt)) sd_dif_complete(SCpnt, good_bytes); if (scsi_host_dif_capable(sdkp->device->host, sdkp->protection_type) == SD_DIF_TYPE2_PROTECTION && SCpnt->cmnd != SCpnt->request->cmd) { /* We have to print a failed command here as the * extended CDB gets freed before scsi_io_completion() * is called. */ if (result) scsi_print_command(SCpnt); mempool_free(SCpnt->cmnd, sd_cdb_pool); SCpnt->cmnd = NULL; SCpnt->cmd_len = 0; } return good_bytes; } /* * spinup disk - called only in sd_revalidate_disk() */ static void sd_spinup_disk(struct scsi_disk *sdkp) { unsigned char cmd[10]; unsigned long spintime_expire = 0; int retries, spintime; unsigned int the_result; struct scsi_sense_hdr sshdr; int sense_valid = 0; spintime = 0; /* Spin up drives, as required. Only do this at boot time */ /* Spinup needs to be done for module loads too. */ do { retries = 0; do { cmd[0] = TEST_UNIT_READY; memset((void *) &cmd[1], 0, 9); the_result = scsi_execute_req(sdkp->device, cmd, DMA_NONE, NULL, 0, &sshdr, SD_TIMEOUT, SD_MAX_RETRIES, NULL); /* * If the drive has indicated to us that it * doesn't have any media in it, don't bother * with any more polling. */ if (media_not_present(sdkp, &sshdr)) return; if (the_result) sense_valid = scsi_sense_valid(&sshdr); retries++; } while (retries < 3 && (!scsi_status_is_good(the_result) || ((driver_byte(the_result) & DRIVER_SENSE) && sense_valid && sshdr.sense_key == UNIT_ATTENTION))); if ((driver_byte(the_result) & DRIVER_SENSE) == 0) { /* no sense, TUR either succeeded or failed * with a status error */ if(!spintime && !scsi_status_is_good(the_result)) { sd_printk(KERN_NOTICE, sdkp, "Unit Not Ready\n"); sd_print_result(sdkp, the_result); } break; } /* * The device does not want the automatic start to be issued. */ if (sdkp->device->no_start_on_add) break; if (sense_valid && sshdr.sense_key == NOT_READY) { if (sshdr.asc == 4 && sshdr.ascq == 3) break; /* manual intervention required */ if (sshdr.asc == 4 && sshdr.ascq == 0xb) break; /* standby */ if (sshdr.asc == 4 && sshdr.ascq == 0xc) break; /* unavailable */ /* * Issue command to spin up drive when not ready */ if (!spintime) { sd_printk(KERN_NOTICE, sdkp, "Spinning up disk..."); cmd[0] = START_STOP; cmd[1] = 1; /* Return immediately */ memset((void *) &cmd[2], 0, 8); cmd[4] = 1; /* Start spin cycle */ if (sdkp->device->start_stop_pwr_cond) cmd[4] |= 1 << 4; scsi_execute_req(sdkp->device, cmd, DMA_NONE, NULL, 0, &sshdr, SD_TIMEOUT, SD_MAX_RETRIES, NULL); spintime_expire = jiffies + 100 * HZ; spintime = 1; } /* Wait 1 second for next try */ msleep(1000); printk("."); /* * Wait for USB flash devices with slow firmware. * Yes, this sense key/ASC combination shouldn't * occur here. It's characteristic of these devices. */ } else if (sense_valid && sshdr.sense_key == UNIT_ATTENTION && sshdr.asc == 0x28) { if (!spintime) { spintime_expire = jiffies + 5 * HZ; spintime = 1; } /* Wait 1 second for next try */ msleep(1000); } else { /* we don't understand the sense code, so it's * probably pointless to loop */ if(!spintime) { sd_printk(KERN_NOTICE, sdkp, "Unit Not Ready\n"); sd_print_sense_hdr(sdkp, &sshdr); } break; } } while (spintime && time_before_eq(jiffies, spintime_expire)); if (spintime) { if (scsi_status_is_good(the_result)) printk("ready\n"); else printk("not responding...\n"); } } /* * Determine whether disk supports Data Integrity Field. */ static void sd_read_protection_type(struct scsi_disk *sdkp, unsigned char *buffer) { struct scsi_device *sdp = sdkp->device; u8 type; if (scsi_device_protection(sdp) == 0 || (buffer[12] & 1) == 0) return; type = ((buffer[12] >> 1) & 7) + 1; /* P_TYPE 0 = Type 1 */ if (type == sdkp->protection_type || !sdkp->first_scan) return; sdkp->protection_type = type; if (type > SD_DIF_TYPE3_PROTECTION) { sd_printk(KERN_ERR, sdkp, "formatted with unsupported " \ "protection type %u. Disabling disk!\n", type); sdkp->capacity = 0; return; } if (scsi_host_dif_capable(sdp->host, type)) sd_printk(KERN_NOTICE, sdkp, "Enabling DIF Type %u protection\n", type); else sd_printk(KERN_NOTICE, sdkp, "Disabling DIF Type %u protection\n", type); } static void read_capacity_error(struct scsi_disk *sdkp, struct scsi_device *sdp, struct scsi_sense_hdr *sshdr, int sense_valid, int the_result) { sd_print_result(sdkp, the_result); if (driver_byte(the_result) & DRIVER_SENSE) sd_print_sense_hdr(sdkp, sshdr); else sd_printk(KERN_NOTICE, sdkp, "Sense not available.\n"); /* * Set dirty bit for removable devices if not ready - * sometimes drives will not report this properly. */ if (sdp->removable && sense_valid && sshdr->sense_key == NOT_READY) set_media_not_present(sdkp); /* * We used to set media_present to 0 here to indicate no media * in the drive, but some drives fail read capacity even with * media present, so we can't do that. */ sdkp->capacity = 0; /* unknown mapped to zero - as usual */ } #define RC16_LEN 32 #if RC16_LEN > SD_BUF_SIZE #error RC16_LEN must not be more than SD_BUF_SIZE #endif #define READ_CAPACITY_RETRIES_ON_RESET 10 static int read_capacity_16(struct scsi_disk *sdkp, struct scsi_device *sdp, unsigned char *buffer) { unsigned char cmd[16]; struct scsi_sense_hdr sshdr; int sense_valid = 0; int the_result; int retries = 3, reset_retries = READ_CAPACITY_RETRIES_ON_RESET; unsigned int alignment; unsigned long long lba; unsigned sector_size; if (sdp->no_read_capacity_16) return -EINVAL; do { memset(cmd, 0, 16); cmd[0] = SERVICE_ACTION_IN; cmd[1] = SAI_READ_CAPACITY_16; cmd[13] = RC16_LEN; memset(buffer, 0, RC16_LEN); the_result = scsi_execute_req(sdp, cmd, DMA_FROM_DEVICE, buffer, RC16_LEN, &sshdr, SD_TIMEOUT, SD_MAX_RETRIES, NULL); if (media_not_present(sdkp, &sshdr)) return -ENODEV; if (the_result) { sense_valid = scsi_sense_valid(&sshdr); if (sense_valid && sshdr.sense_key == ILLEGAL_REQUEST && (sshdr.asc == 0x20 || sshdr.asc == 0x24) && sshdr.ascq == 0x00) /* Invalid Command Operation Code or * Invalid Field in CDB, just retry * silently with RC10 */ return -EINVAL; if (sense_valid && sshdr.sense_key == UNIT_ATTENTION && sshdr.asc == 0x29 && sshdr.ascq == 0x00) /* Device reset might occur several times, * give it one more chance */ if (--reset_retries > 0) continue; } retries--; } while (the_result && retries); if (the_result) { sd_printk(KERN_NOTICE, sdkp, "READ CAPACITY(16) failed\n"); read_capacity_error(sdkp, sdp, &sshdr, sense_valid, the_result); return -EINVAL; } sector_size = get_unaligned_be32(&buffer[8]); lba = get_unaligned_be64(&buffer[0]); sd_read_protection_type(sdkp, buffer); if ((sizeof(sdkp->capacity) == 4) && (lba >= 0xffffffffULL)) { sd_printk(KERN_ERR, sdkp, "Too big for this kernel. Use a " "kernel compiled with support for large block " "devices.\n"); sdkp->capacity = 0; return -EOVERFLOW; } /* Logical blocks per physical block exponent */ sdkp->physical_block_size = (1 << (buffer[13] & 0xf)) * sector_size; /* Lowest aligned logical block */ alignment = ((buffer[14] & 0x3f) << 8 | buffer[15]) * sector_size; blk_queue_alignment_offset(sdp->request_queue, alignment); if (alignment && sdkp->first_scan) sd_printk(KERN_NOTICE, sdkp, "physical block alignment offset: %u\n", alignment); if (buffer[14] & 0x80) { /* LBPME */ sdkp->lbpme = 1; if (buffer[14] & 0x40) /* LBPRZ */ sdkp->lbprz = 1; sd_config_discard(sdkp, SD_LBP_WS16); } sdkp->capacity = lba + 1; return sector_size; } static int read_capacity_10(struct scsi_disk *sdkp, struct scsi_device *sdp, unsigned char *buffer) { unsigned char cmd[16]; struct scsi_sense_hdr sshdr; int sense_valid = 0; int the_result; int retries = 3, reset_retries = READ_CAPACITY_RETRIES_ON_RESET; sector_t lba; unsigned sector_size; do { cmd[0] = READ_CAPACITY; memset(&cmd[1], 0, 9); memset(buffer, 0, 8); the_result = scsi_execute_req(sdp, cmd, DMA_FROM_DEVICE, buffer, 8, &sshdr, SD_TIMEOUT, SD_MAX_RETRIES, NULL); if (media_not_present(sdkp, &sshdr)) return -ENODEV; if (the_result) { sense_valid = scsi_sense_valid(&sshdr); if (sense_valid && sshdr.sense_key == UNIT_ATTENTION && sshdr.asc == 0x29 && sshdr.ascq == 0x00) /* Device reset might occur several times, * give it one more chance */ if (--reset_retries > 0) continue; } retries--; } while (the_result && retries); if (the_result) { sd_printk(KERN_NOTICE, sdkp, "READ CAPACITY failed\n"); read_capacity_error(sdkp, sdp, &sshdr, sense_valid, the_result); return -EINVAL; } sector_size = get_unaligned_be32(&buffer[4]); lba = get_unaligned_be32(&buffer[0]); if (sdp->no_read_capacity_16 && (lba == 0xffffffff)) { /* Some buggy (usb cardreader) devices return an lba of 0xffffffff when the want to report a size of 0 (with which they really mean no media is present) */ sdkp->capacity = 0; sdkp->physical_block_size = sector_size; return sector_size; } if ((sizeof(sdkp->capacity) == 4) && (lba == 0xffffffff)) { sd_printk(KERN_ERR, sdkp, "Too big for this kernel. Use a " "kernel compiled with support for large block " "devices.\n"); sdkp->capacity = 0; return -EOVERFLOW; } sdkp->capacity = lba + 1; sdkp->physical_block_size = sector_size; return sector_size; } static int sd_try_rc16_first(struct scsi_device *sdp) { if (sdp->host->max_cmd_len < 16) return 0; if (sdp->scsi_level > SCSI_SPC_2) return 1; if (scsi_device_protection(sdp)) return 1; return 0; } /* * read disk capacity */ static void sd_read_capacity(struct scsi_disk *sdkp, unsigned char *buffer) { int sector_size; struct scsi_device *sdp = sdkp->device; sector_t old_capacity = sdkp->capacity; if (sd_try_rc16_first(sdp)) { sector_size = read_capacity_16(sdkp, sdp, buffer); if (sector_size == -EOVERFLOW) goto got_data; if (sector_size == -ENODEV) return; if (sector_size < 0) sector_size = read_capacity_10(sdkp, sdp, buffer); if (sector_size < 0) return; } else { sector_size = read_capacity_10(sdkp, sdp, buffer); if (sector_size == -EOVERFLOW) goto got_data; if (sector_size < 0) return; if ((sizeof(sdkp->capacity) > 4) && (sdkp->capacity > 0xffffffffULL)) { int old_sector_size = sector_size; sd_printk(KERN_NOTICE, sdkp, "Very big device. " "Trying to use READ CAPACITY(16).\n"); sector_size = read_capacity_16(sdkp, sdp, buffer); if (sector_size < 0) { sd_printk(KERN_NOTICE, sdkp, "Using 0xffffffff as device size\n"); sdkp->capacity = 1 + (sector_t) 0xffffffff; sector_size = old_sector_size; goto got_data; } } } /* Some devices are known to return the total number of blocks, * not the highest block number. Some devices have versions * which do this and others which do not. Some devices we might * suspect of doing this but we don't know for certain. * * If we know the reported capacity is wrong, decrement it. If * we can only guess, then assume the number of blocks is even * (usually true but not always) and err on the side of lowering * the capacity. */ if (sdp->fix_capacity || (sdp->guess_capacity && (sdkp->capacity & 0x01))) { sd_printk(KERN_INFO, sdkp, "Adjusting the sector count " "from its reported value: %llu\n", (unsigned long long) sdkp->capacity); --sdkp->capacity; } got_data: if (sector_size == 0) { sector_size = 512; sd_printk(KERN_NOTICE, sdkp, "Sector size 0 reported, " "assuming 512.\n"); } if (sector_size != 512 && sector_size != 1024 && sector_size != 2048 && sector_size != 4096 && sector_size != 256) { sd_printk(KERN_NOTICE, sdkp, "Unsupported sector size %d.\n", sector_size); /* * The user might want to re-format the drive with * a supported sectorsize. Once this happens, it * would be relatively trivial to set the thing up. * For this reason, we leave the thing in the table. */ sdkp->capacity = 0; /* * set a bogus sector size so the normal read/write * logic in the block layer will eventually refuse any * request on this device without tripping over power * of two sector size assumptions */ sector_size = 512; } blk_queue_logical_block_size(sdp->request_queue, sector_size); { char cap_str_2[10], cap_str_10[10]; u64 sz = (u64)sdkp->capacity << ilog2(sector_size); string_get_size(sz, STRING_UNITS_2, cap_str_2, sizeof(cap_str_2)); string_get_size(sz, STRING_UNITS_10, cap_str_10, sizeof(cap_str_10)); if (sdkp->first_scan || old_capacity != sdkp->capacity) { sd_printk(KERN_NOTICE, sdkp, "%llu %d-byte logical blocks: (%s/%s)\n", (unsigned long long)sdkp->capacity, sector_size, cap_str_10, cap_str_2); if (sdkp->physical_block_size != sector_size) sd_printk(KERN_NOTICE, sdkp, "%u-byte physical blocks\n", sdkp->physical_block_size); } } /* Rescale capacity to 512-byte units */ if (sector_size == 4096) sdkp->capacity <<= 3; else if (sector_size == 2048) sdkp->capacity <<= 2; else if (sector_size == 1024) sdkp->capacity <<= 1; else if (sector_size == 256) sdkp->capacity >>= 1; blk_queue_physical_block_size(sdp->request_queue, sdkp->physical_block_size); sdkp->device->sector_size = sector_size; } /* called with buffer of length 512 */ static inline int sd_do_mode_sense(struct scsi_device *sdp, int dbd, int modepage, unsigned char *buffer, int len, struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr) { return scsi_mode_sense(sdp, dbd, modepage, buffer, len, SD_TIMEOUT, SD_MAX_RETRIES, data, sshdr); } /* * read write protect setting, if possible - called only in sd_revalidate_disk() * called with buffer of length SD_BUF_SIZE */ static void sd_read_write_protect_flag(struct scsi_disk *sdkp, unsigned char *buffer) { int res; struct scsi_device *sdp = sdkp->device; struct scsi_mode_data data; int old_wp = sdkp->write_prot; set_disk_ro(sdkp->disk, 0); if (sdp->skip_ms_page_3f) { sd_printk(KERN_NOTICE, sdkp, "Assuming Write Enabled\n"); return; } if (sdp->use_192_bytes_for_3f) { res = sd_do_mode_sense(sdp, 0, 0x3F, buffer, 192, &data, NULL); } else { /* * First attempt: ask for all pages (0x3F), but only 4 bytes. * We have to start carefully: some devices hang if we ask * for more than is available. */ res = sd_do_mode_sense(sdp, 0, 0x3F, buffer, 4, &data, NULL); /* * Second attempt: ask for page 0 When only page 0 is * implemented, a request for page 3F may return Sense Key * 5: Illegal Request, Sense Code 24: Invalid field in * CDB. */ if (!scsi_status_is_good(res)) res = sd_do_mode_sense(sdp, 0, 0, buffer, 4, &data, NULL); /* * Third attempt: ask 255 bytes, as we did earlier. */ if (!scsi_status_is_good(res)) res = sd_do_mode_sense(sdp, 0, 0x3F, buffer, 255, &data, NULL); } if (!scsi_status_is_good(res)) { sd_printk(KERN_WARNING, sdkp, "Test WP failed, assume Write Enabled\n"); } else { sdkp->write_prot = ((data.device_specific & 0x80) != 0); set_disk_ro(sdkp->disk, sdkp->write_prot); if (sdkp->first_scan || old_wp != sdkp->write_prot) { sd_printk(KERN_NOTICE, sdkp, "Write Protect is %s\n", sdkp->write_prot ? "on" : "off"); sd_printk(KERN_DEBUG, sdkp, "Mode Sense: %02x %02x %02x %02x\n", buffer[0], buffer[1], buffer[2], buffer[3]); } } } /* * sd_read_cache_type - called only from sd_revalidate_disk() * called with buffer of length SD_BUF_SIZE */ static void sd_read_cache_type(struct scsi_disk *sdkp, unsigned char *buffer) { int len = 0, res; struct scsi_device *sdp = sdkp->device; int dbd; int modepage; int first_len; struct scsi_mode_data data; struct scsi_sense_hdr sshdr; int old_wce = sdkp->WCE; int old_rcd = sdkp->RCD; int old_dpofua = sdkp->DPOFUA; first_len = 4; if (sdp->skip_ms_page_8) { if (sdp->type == TYPE_RBC) goto defaults; else { if (sdp->skip_ms_page_3f) goto defaults; modepage = 0x3F; if (sdp->use_192_bytes_for_3f) first_len = 192; dbd = 0; } } else if (sdp->type == TYPE_RBC) { modepage = 6; dbd = 8; } else { modepage = 8; dbd = 0; } /* cautiously ask */ res = sd_do_mode_sense(sdp, dbd, modepage, buffer, first_len, &data, &sshdr); if (!scsi_status_is_good(res)) goto bad_sense; if (!data.header_length) { modepage = 6; first_len = 0; sd_printk(KERN_ERR, sdkp, "Missing header in MODE_SENSE response\n"); } /* that went OK, now ask for the proper length */ len = data.length; /* * We're only interested in the first three bytes, actually. * But the data cache page is defined for the first 20. */ if (len < 3) goto bad_sense; else if (len > SD_BUF_SIZE) { sd_printk(KERN_NOTICE, sdkp, "Truncating mode parameter " "data from %d to %d bytes\n", len, SD_BUF_SIZE); len = SD_BUF_SIZE; } if (modepage == 0x3F && sdp->use_192_bytes_for_3f) len = 192; /* Get the data */ if (len > first_len) res = sd_do_mode_sense(sdp, dbd, modepage, buffer, len, &data, &sshdr); if (scsi_status_is_good(res)) { int offset = data.header_length + data.block_descriptor_length; while (offset < len) { u8 page_code = buffer[offset] & 0x3F; u8 spf = buffer[offset] & 0x40; if (page_code == 8 || page_code == 6) { /* We're interested only in the first 3 bytes. */ if (len - offset <= 2) { sd_printk(KERN_ERR, sdkp, "Incomplete " "mode parameter data\n"); goto defaults; } else { modepage = page_code; goto Page_found; } } else { /* Go to the next page */ if (spf && len - offset > 3) offset += 4 + (buffer[offset+2] << 8) + buffer[offset+3]; else if (!spf && len - offset > 1) offset += 2 + buffer[offset+1]; else { sd_printk(KERN_ERR, sdkp, "Incomplete " "mode parameter data\n"); goto defaults; } } } if (modepage == 0x3F) { sd_printk(KERN_ERR, sdkp, "No Caching mode page " "present\n"); goto defaults; } else if ((buffer[offset] & 0x3f) != modepage) { sd_printk(KERN_ERR, sdkp, "Got wrong page\n"); goto defaults; } Page_found: if (modepage == 8) { sdkp->WCE = ((buffer[offset + 2] & 0x04) != 0); sdkp->RCD = ((buffer[offset + 2] & 0x01) != 0); } else { sdkp->WCE = ((buffer[offset + 2] & 0x01) == 0); sdkp->RCD = 0; } sdkp->DPOFUA = (data.device_specific & 0x10) != 0; if (sdkp->DPOFUA && !sdkp->device->use_10_for_rw) { sd_printk(KERN_NOTICE, sdkp, "Uses READ/WRITE(6), disabling FUA\n"); sdkp->DPOFUA = 0; } if (sdkp->first_scan || old_wce != sdkp->WCE || old_rcd != sdkp->RCD || old_dpofua != sdkp->DPOFUA) sd_printk(KERN_NOTICE, sdkp, "Write cache: %s, read cache: %s, %s\n", sdkp->WCE ? "enabled" : "disabled", sdkp->RCD ? "disabled" : "enabled", sdkp->DPOFUA ? "supports DPO and FUA" : "doesn't support DPO or FUA"); return; } bad_sense: if (scsi_sense_valid(&sshdr) && sshdr.sense_key == ILLEGAL_REQUEST && sshdr.asc == 0x24 && sshdr.ascq == 0x0) /* Invalid field in CDB */ sd_printk(KERN_NOTICE, sdkp, "Cache data unavailable\n"); else sd_printk(KERN_ERR, sdkp, "Asking for cache data failed\n"); defaults: sd_printk(KERN_ERR, sdkp, "Assuming drive cache: write through\n"); sdkp->WCE = 0; sdkp->RCD = 0; sdkp->DPOFUA = 0; } /* * The ATO bit indicates whether the DIF application tag is available * for use by the operating system. */ static void sd_read_app_tag_own(struct scsi_disk *sdkp, unsigned char *buffer) { int res, offset; struct scsi_device *sdp = sdkp->device; struct scsi_mode_data data; struct scsi_sense_hdr sshdr; if (sdp->type != TYPE_DISK) return; if (sdkp->protection_type == 0) return; res = scsi_mode_sense(sdp, 1, 0x0a, buffer, 36, SD_TIMEOUT, SD_MAX_RETRIES, &data, &sshdr); if (!scsi_status_is_good(res) || !data.header_length || data.length < 6) { sd_printk(KERN_WARNING, sdkp, "getting Control mode page failed, assume no ATO\n"); if (scsi_sense_valid(&sshdr)) sd_print_sense_hdr(sdkp, &sshdr); return; } offset = data.header_length + data.block_descriptor_length; if ((buffer[offset] & 0x3f) != 0x0a) { sd_printk(KERN_ERR, sdkp, "ATO Got wrong page\n"); return; } if ((buffer[offset + 5] & 0x80) == 0) return; sdkp->ATO = 1; return; } /** * sd_read_block_limits - Query disk device for preferred I/O sizes. * @disk: disk to query */ static void sd_read_block_limits(struct scsi_disk *sdkp) { unsigned int sector_sz = sdkp->device->sector_size; const int vpd_len = 64; unsigned char *buffer = kmalloc(vpd_len, GFP_KERNEL); if (!buffer || /* Block Limits VPD */ scsi_get_vpd_page(sdkp->device, 0xb0, buffer, vpd_len)) goto out; blk_queue_io_min(sdkp->disk->queue, get_unaligned_be16(&buffer[6]) * sector_sz); blk_queue_io_opt(sdkp->disk->queue, get_unaligned_be32(&buffer[12]) * sector_sz); if (buffer[3] == 0x3c) { unsigned int lba_count, desc_count; sdkp->max_ws_blocks = (u32) min_not_zero(get_unaligned_be64(&buffer[36]), (u64)0xffffffff); if (!sdkp->lbpme) goto out; lba_count = get_unaligned_be32(&buffer[20]); desc_count = get_unaligned_be32(&buffer[24]); if (lba_count && desc_count) sdkp->max_unmap_blocks = lba_count; sdkp->unmap_granularity = get_unaligned_be32(&buffer[28]); if (buffer[32] & 0x80) sdkp->unmap_alignment = get_unaligned_be32(&buffer[32]) & ~(1 << 31); if (!sdkp->lbpvpd) { /* LBP VPD page not provided */ if (sdkp->max_unmap_blocks) sd_config_discard(sdkp, SD_LBP_UNMAP); else sd_config_discard(sdkp, SD_LBP_WS16); } else { /* LBP VPD page tells us what to use */ if (sdkp->lbpu && sdkp->max_unmap_blocks) sd_config_discard(sdkp, SD_LBP_UNMAP); else if (sdkp->lbpws) sd_config_discard(sdkp, SD_LBP_WS16); else if (sdkp->lbpws10) sd_config_discard(sdkp, SD_LBP_WS10); else sd_config_discard(sdkp, SD_LBP_DISABLE); } } out: kfree(buffer); } /** * sd_read_block_characteristics - Query block dev. characteristics * @disk: disk to query */ static void sd_read_block_characteristics(struct scsi_disk *sdkp) { unsigned char *buffer; u16 rot; const int vpd_len = 64; buffer = kmalloc(vpd_len, GFP_KERNEL); if (!buffer || /* Block Device Characteristics VPD */ scsi_get_vpd_page(sdkp->device, 0xb1, buffer, vpd_len)) goto out; rot = get_unaligned_be16(&buffer[4]); if (rot == 1) queue_flag_set_unlocked(QUEUE_FLAG_NONROT, sdkp->disk->queue); out: kfree(buffer); } /** * sd_read_block_provisioning - Query provisioning VPD page * @disk: disk to query */ static void sd_read_block_provisioning(struct scsi_disk *sdkp) { unsigned char *buffer; const int vpd_len = 8; if (sdkp->lbpme == 0) return; buffer = kmalloc(vpd_len, GFP_KERNEL); if (!buffer || scsi_get_vpd_page(sdkp->device, 0xb2, buffer, vpd_len)) goto out; sdkp->lbpvpd = 1; sdkp->lbpu = (buffer[5] >> 7) & 1; /* UNMAP */ sdkp->lbpws = (buffer[5] >> 6) & 1; /* WRITE SAME(16) with UNMAP */ sdkp->lbpws10 = (buffer[5] >> 5) & 1; /* WRITE SAME(10) with UNMAP */ out: kfree(buffer); } static int sd_try_extended_inquiry(struct scsi_device *sdp) { /* * Although VPD inquiries can go to SCSI-2 type devices, * some USB ones crash on receiving them, and the pages * we currently ask for are for SPC-3 and beyond */ if (sdp->scsi_level > SCSI_SPC_2) return 1; return 0; } /** * sd_revalidate_disk - called the first time a new disk is seen, * performs disk spin up, read_capacity, etc. * @disk: struct gendisk we care about **/ static int sd_revalidate_disk(struct gendisk *disk) { struct scsi_disk *sdkp = scsi_disk(disk); struct scsi_device *sdp = sdkp->device; unsigned char *buffer; unsigned flush = 0; SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_revalidate_disk\n")); /* * If the device is offline, don't try and read capacity or any * of the other niceties. */ if (!scsi_device_online(sdp)) goto out; buffer = kmalloc(SD_BUF_SIZE, GFP_KERNEL); if (!buffer) { sd_printk(KERN_WARNING, sdkp, "sd_revalidate_disk: Memory " "allocation failure.\n"); goto out; } sd_spinup_disk(sdkp); /* * Without media there is no reason to ask; moreover, some devices * react badly if we do. */ if (sdkp->media_present) { sd_read_capacity(sdkp, buffer); if (sd_try_extended_inquiry(sdp)) { sd_read_block_provisioning(sdkp); sd_read_block_limits(sdkp); sd_read_block_characteristics(sdkp); } sd_read_write_protect_flag(sdkp, buffer); sd_read_cache_type(sdkp, buffer); sd_read_app_tag_own(sdkp, buffer); } sdkp->first_scan = 0; /* * We now have all cache related info, determine how we deal * with flush requests. */ if (sdkp->WCE) { flush |= REQ_FLUSH; if (sdkp->DPOFUA) flush |= REQ_FUA; } blk_queue_flush(sdkp->disk->queue, flush); set_capacity(disk, sdkp->capacity); kfree(buffer); out: return 0; } #ifdef MY_ABC_HERE extern int syno_ida_get_new(struct ida *idp, int starting_id, int *id); #endif #ifdef MY_ABC_HERE int (*SynoUSBDeviceIsSATA)(void *) = NULL; EXPORT_SYMBOL(SynoUSBDeviceIsSATA); #endif #ifdef SYNO_SAS_DISK_NAME /** * sd_format_disk_name - format disk name * @prefix: name prefix - ie. "sd" for SCSI disks * @synoindex: index of the disk to format name for * @buf: output buffer * @buflen: length of the output buffer * * SCSI disk names starts at sd1. The 26th device is sd26 and the * 27th is sd27. * * CONTEXT: * Don't care. * * RETURNS: * 0 on success, -errno on failure. */ static int sd_format_sas_disk_name(char *prefix, int synoindex, char *buf, int buflen) { /* disk format is sata1, so synoindex 1 position in this string * So we at least need to prepare 1 position for this string */ if (buflen <= (strlen(prefix) + (synoindex + 1)/10 + 1)) { return -EINVAL; } if (snprintf(buf, buflen, "%s%d", prefix, synoindex + 1) <= 0) { return -EINVAL; } return 0; } #endif /** * sd_unlock_native_capacity - unlock native capacity * @disk: struct gendisk to set capacity for * * Block layer calls this function if it detects that partitions * on @disk reach beyond the end of the device. If the SCSI host * implements ->unlock_native_capacity() method, it's invoked to * give it a chance to adjust the device capacity. * * CONTEXT: * Defined by block layer. Might sleep. */ static void sd_unlock_native_capacity(struct gendisk *disk) { struct scsi_device *sdev = scsi_disk(disk)->device; if (sdev->host->hostt->unlock_native_capacity) sdev->host->hostt->unlock_native_capacity(sdev); } /** * sd_format_disk_name - format disk name * @prefix: name prefix - ie. "sd" for SCSI disks * @index: index of the disk to format name for * @buf: output buffer * @buflen: length of the output buffer * * SCSI disk names starts at sda. The 26th device is sdz and the * 27th is sdaa. The last one for two lettered suffix is sdzz * which is followed by sdaaa. * * This is basically 26 base counting with one extra 'nil' entry * at the beginning from the second digit on and can be * determined using similar method as 26 base conversion with the * index shifted -1 after each digit is computed. * * CONTEXT: * Don't care. * * RETURNS: * 0 on success, -errno on failure. */ static int sd_format_disk_name(char *prefix, int index, char *buf, int buflen) { const int base = 'z' - 'a' + 1; char *begin = buf + strlen(prefix); char *end = buf + buflen; char *p; int unit; p = end - 1; *p = '\0'; unit = base; do { if (p == begin) return -EINVAL; *--p = 'a' + (index % unit); index = (index / unit) - 1; } while (index >= 0); memmove(begin, p, end - p); memcpy(buf, prefix, strlen(prefix)); return 0; } /* * The asynchronous part of sd_probe */ static void sd_probe_async(void *data, async_cookie_t cookie) { struct scsi_disk *sdkp = data; struct scsi_device *sdp; struct gendisk *gd; u32 index; struct device *dev; sdp = sdkp->device; gd = sdkp->disk; index = sdkp->index; dev = &sdp->sdev_gendev; gd->major = sd_major((index & 0xf0) >> 4); gd->first_minor = ((index & 0xf) << 4) | (index & 0xfff00); gd->minors = SD_MINORS; gd->fops = &sd_fops; gd->private_data = &sdkp->driver; gd->queue = sdkp->device->request_queue; /* defaults, until the device tells us otherwise */ sdp->sector_size = 512; sdkp->capacity = 0; sdkp->media_present = 1; sdkp->write_prot = 0; sdkp->WCE = 0; sdkp->RCD = 0; sdkp->ATO = 0; sdkp->first_scan = 1; sd_revalidate_disk(gd); blk_queue_prep_rq(sdp->request_queue, sd_prep_fn); blk_queue_unprep_rq(sdp->request_queue, sd_unprep_fn); gd->driverfs_dev = &sdp->sdev_gendev; gd->flags = GENHD_FL_EXT_DEVT; if (sdp->removable) { gd->flags |= GENHD_FL_REMOVABLE; gd->events |= DISK_EVENT_MEDIA_CHANGE; } add_disk(gd); sd_dif_config_host(sdkp); sd_revalidate_disk(gd); sd_printk(KERN_NOTICE, sdkp, "Attached SCSI %sdisk\n", sdp->removable ? "removable " : ""); scsi_autopm_put_device(sdp); put_device(&sdkp->dev); } #ifdef MY_ABC_HERE #ifdef MY_ABC_HERE static bool syno_find_synoboot(void) { bool find = false; struct scsi_disk *sdisk = NULL; struct class_dev_iter iter; struct device *dev; class_dev_iter_init(&iter, &sd_disk_class, NULL, NULL); dev = class_dev_iter_next(&iter); while (dev) { if (!dev->parent) { dev = class_dev_iter_next(&iter); continue; } sdisk = dev_get_drvdata(dev->parent); if (sdisk && sdisk->disk) { if (0 == strcmp(SYNO_USB_FLASH_DEVICE_NAME, sdisk->disk->disk_name)) { find = true; goto OUT; } } dev = class_dev_iter_next(&iter); } OUT: class_dev_iter_exit(&iter); return find; } #endif static SYNO_DISK_TYPE syno_disk_type_get(struct device *dev) { struct scsi_device *sdp = to_scsi_device(dev); // iscsi #ifdef MY_ABC_HERE if(strcmp(sdp->host->hostt->name, "iSCSI Initiator over TCP/IP") == 0){ return SYNO_DISK_ISCSI; } #endif if (SYNO_PORT_TYPE_USB == sdp->host->hostt->syno_port_type) { #ifdef MY_ABC_HERE struct us_data *us = host_to_us(sdp->host); struct usb_device *usbdev = us->pusb_dev; if (IS_SYNO_USBBOOT_ID_VENDOR(le16_to_cpu(usbdev->descriptor.idVendor)) && IS_SYNO_USBBOOT_ID_PRODUCT(le16_to_cpu(usbdev->descriptor.idProduct)) && gSynoHasDynModule) { if (!syno_find_synoboot()) { return SYNO_DISK_SYNOBOOT; } } #endif return SYNO_DISK_USB; } if (SYNO_PORT_TYPE_SATA == sdp->host->hostt->syno_port_type) { // else treat as internal disks return SYNO_DISK_SATA; } // sas disks if (SYNO_PORT_TYPE_SAS == sdp->host->hostt->syno_port_type) { return SYNO_DISK_SAS; } return SYNO_DISK_UNKNOWN; } #endif /** * sd_probe - called during driver initialization and whenever a * new scsi device is attached to the system. It is called once * for each scsi device (not just disks) present. * @dev: pointer to device object * * Returns 0 if successful (or not interested in this scsi device * (e.g. scanner)); 1 when there is an error. * * Note: this function is invoked from the scsi mid-level. * This function sets up the mapping between a given * <host,channel,id,lun> (found in sdp) and new device name * (e.g. /dev/sda). More precisely it is the block device major * and minor number that is chosen here. * * Assume sd_attach is not re-entrant (for time being) * Also think about sd_attach() and sd_remove() running coincidentally. **/ static int sd_probe(struct device *dev) { struct scsi_device *sdp = to_scsi_device(dev); struct scsi_disk *sdkp; struct gendisk *gd; int index; int error; #ifdef MY_ABC_HERE struct ata_port *ap; int start_index; int iRetry = 0; u32 want_idx = 0; #endif #ifdef SYNO_SAS_DISK_NAME u32 synoidx; #endif error = -ENODEV; if (sdp->type != TYPE_DISK && sdp->type != TYPE_MOD && sdp->type != TYPE_RBC) goto out; SCSI_LOG_HLQUEUE(3, sdev_printk(KERN_INFO, sdp, "sd_attach\n")); error = -ENOMEM; sdkp = kzalloc(sizeof(*sdkp), GFP_KERNEL); if (!sdkp) goto out; gd = alloc_disk(SD_MINORS); if (!gd) goto out_free; #ifdef MY_ABC_HERE sdkp->synodisktype = syno_disk_type_get(dev); #endif do { if (!ida_pre_get(&sd_index_ida, GFP_KERNEL)) goto out_put; #ifdef SYNO_SAS_DISK_NAME if (1 == g_is_sas_model) { switch(sdkp->synodisktype) { #ifdef MY_ABC_HERE case SYNO_DISK_ISCSI: if (!ida_pre_get(&iscsi_index_ida, GFP_KERNEL)) goto out_put; break; #endif case SYNO_DISK_USB: if (!ida_pre_get(&usb_index_ida, GFP_KERNEL)) goto out_put; break; case SYNO_DISK_SAS: if (!ida_pre_get(&sas_index_ida, GFP_KERNEL)) goto out_put; break; default: break; } } #endif #ifdef MY_ABC_HERE sdp->idle = jiffies; sdp->nospindown = 0; sdp->spindown = 0; #endif spin_lock(&sd_index_lock); #ifdef MY_ABC_HERE switch(sdkp->synodisktype) { #ifdef MY_ABC_HERE case SYNO_DISK_ISCSI: #ifdef SYNO_SAS_DISK_NAME if (1 == g_is_sas_model) { error = syno_ida_get_new(&iscsi_index_ida, 0, &synoidx); want_idx = 0; break; } #endif want_idx = SYNO_ISCSI_DEVICE_INDEX; break; #endif #ifdef MY_ABC_HERE case SYNO_DISK_SYNOBOOT: want_idx = SYNO_USB_FLASH_DEVICE_INDEX; break; #endif case SYNO_DISK_USB: #ifdef SYNO_SAS_DISK_NAME if (1 == g_is_sas_model) { error = syno_ida_get_new(&usb_index_ida, 0, &synoidx); want_idx = 0; break; } #endif #ifdef CONFIG_SYNO_ARMADA /* The device node of internal micro SD card of USB station 3 should be fixed to sda. */ if (1 == gSynoHasDynModule && 1 == gSynoUSBStation) { struct us_data *us = host_to_us(sdp->host); struct usb_device *usbdev = us->pusb_dev; if (0 == strcmp((&(&usbdev->dev)->kobj)->name, SYNO_INTERNAL_MICROSD_NAME)) { want_idx = 0; } else { want_idx = SYNO_MAX_INTERNAL_DISK + 1; } } else { want_idx = SYNO_MAX_INTERNAL_DISK + 1; } #else /* CONFIG_SYNO_ARMADA */ want_idx = SYNO_MAX_INTERNAL_DISK + 1; #endif /* CONFIG_SYNO_ARMADA */ break; case SYNO_DISK_SAS: case SYNO_DISK_SATA: default: // SAS model use different naming scheme #ifdef SYNO_SAS_DISK_NAME if (1 == g_is_sas_model) { error = syno_ida_get_new(&sas_index_ida, 0, &synoidx); want_idx = 0; break; } #endif if (sdp->host->hostt->syno_index_get) { want_idx = sdp->host->hostt->syno_index_get(sdp->host, sdp->channel, sdp->id, sdp->lun); }else{ want_idx = sdp->host->host_no; } break; } error = syno_ida_get_new(&sd_index_ida, want_idx, &index); #ifdef SYNO_SAS_DISK_NAME if (1 == g_is_sas_model) { sdkp->synoindex = synoidx; } #endif // try at most 5 times while (want_idx != index && (SYNO_DISK_SATA == sdkp->synodisktype) && iRetry < 15) { /* Sometimes raid is not release all scsi disk yet. Try to delay and reget */ printk("want_idx %d index %d. delay and reget\n", want_idx, index); ida_remove(&sd_index_ida, index); spin_unlock(&sd_index_lock); schedule_timeout_uninterruptible(HZ); spin_lock(&sd_index_lock); error = syno_ida_get_new(&sd_index_ida, want_idx, &index); printk("want_idx %d index %d\n", want_idx, index); iRetry++; } #else /* MY_ABC_HERE */ error = ida_get_new(&sd_index_ida, &index); #endif /* MY_ABC_HERE */ spin_unlock(&sd_index_lock); } while (error == -EAGAIN); if (error) { sdev_printk(KERN_WARNING, sdp, "sd_probe: memory exhausted.\n"); goto out_put; } #ifdef MY_ABC_HERE gd->systemDisk = 0; switch(sdkp->synodisktype) { #ifdef MY_ABC_HERE case SYNO_DISK_ISCSI: #ifdef SYNO_SAS_DISK_NAME if (1 == g_is_sas_model) { error = sd_format_sas_disk_name(SYNO_SAS_ISCSI_DEVICE_PREFIX, synoidx, gd->disk_name, DISK_NAME_LEN); printk("got iSCSI disk[%d]\n", synoidx); break; } #endif start_index = index - SYNO_ISCSI_DEVICE_INDEX; error = sd_format_disk_name(SYNO_ISCSI_DEVICE_PREFIX, start_index, gd->disk_name, DISK_NAME_LEN); printk("got iSCSI disk[%d]\n", start_index); break; #endif #ifdef MY_ABC_HERE case SYNO_DISK_SYNOBOOT: // we assume synoboot will be plugged only once sprintf(gd->disk_name, SYNO_USB_FLASH_DEVICE_NAME); error = 0; break; #endif case SYNO_DISK_SAS: #ifdef SYNO_SAS_DISK_NAME error = sd_format_sas_disk_name(SYNO_SAS_DEVICE_PREFIX, synoidx, gd->disk_name, DISK_NAME_LEN); // block device if (NULL != dev && // sas target NULL != dev->parent && // sas end device NULL != dev->parent->parent && // sas port NULL != dev->parent->parent->parent && // internal/external expander NULL != dev->parent->parent->parent->parent && // expander - host/expander port NULL != dev->parent->parent->parent->parent->parent && // host/expander NULL != dev->parent->parent->parent->parent->parent->parent) { // if this level parent of this device is scsi host, then it is one of our internal SAS disks if (scsi_is_host_device(dev->parent->parent->parent->parent->parent->parent)) { gd->systemDisk = 1; } } #endif break; case SYNO_DISK_SATA: ap = ata_shost_to_port(sdp->host); // enuit is not system disk if (NULL != ap && !syno_is_synology_pm(ap)) { gd->systemDisk = 1; } error = sd_format_disk_name(SYNO_SATA_DEVICE_PREFIX, index, gd->disk_name, DISK_NAME_LEN); break; case SYNO_DISK_USB: default: #ifdef SYNO_SAS_DISK_NAME if (1 == g_is_sas_model) { error = sd_format_sas_disk_name(SYNO_SAS_USB_DEVICE_PREFIX, synoidx, gd->disk_name, DISK_NAME_LEN); break; } #endif error = sd_format_disk_name(SYNO_SATA_DEVICE_PREFIX, index, gd->disk_name, DISK_NAME_LEN); break; } #else error = sd_format_disk_name("sd", index, gd->disk_name, DISK_NAME_LEN); #endif if (error) { sdev_printk(KERN_WARNING, sdp, "SCSI disk (sd) name length exceeded.\n"); goto out_free_index; } sdkp->device = sdp; sdkp->driver = &sd_template; sdkp->disk = gd; sdkp->index = index; atomic_set(&sdkp->openers, 0); if (!sdp->request_queue->rq_timeout) { if (sdp->type != TYPE_MOD) blk_queue_rq_timeout(sdp->request_queue, SD_TIMEOUT); else blk_queue_rq_timeout(sdp->request_queue, SD_MOD_TIMEOUT); } device_initialize(&sdkp->dev); sdkp->dev.parent = dev; sdkp->dev.class = &sd_disk_class; dev_set_name(&sdkp->dev, dev_name(dev)); if (device_add(&sdkp->dev)) goto out_free_index; get_device(dev); dev_set_drvdata(dev, sdkp); get_device(&sdkp->dev); /* prevent release before async_schedule */ async_schedule(sd_probe_async, sdkp); #if defined(MY_ABC_HERE) && defined(CONFIG_SYNO_MV88F6281_USBSTATION) if (SYNO_DISK_SYNOBOOT != sdkp->synodisktype || !gSynoHasDynModule) { extern int SYNO_CTRL_USB_HDD_LED_SET(int status); /* we set green blink for usb disk ready. */ SYNO_CTRL_USB_HDD_LED_SET(0x4); } #endif /*MY_ABC_HERE*/ #ifdef MY_ABC_HERE strlcpy(sdp->syno_disk_name, gd->disk_name, BDEVNAME_SIZE); #endif return 0; out_free_index: spin_lock(&sd_index_lock); ida_remove(&sd_index_ida, index); #ifdef SYNO_SAS_DISK_NAME if (1 == g_is_sas_model) { switch(sdkp->synodisktype) { #ifdef MY_ABC_HERE case SYNO_DISK_ISCSI: ida_remove(&iscsi_index_ida, synoidx); break; #endif case SYNO_DISK_USB: ida_remove(&usb_index_ida, synoidx); break; case SYNO_DISK_SAS: ida_remove(&sas_index_ida, synoidx); break; default: break; } } #endif spin_unlock(&sd_index_lock); out_put: put_disk(gd); out_free: kfree(sdkp); out: return error; } /** * sd_remove - called whenever a scsi disk (previously recognized by * sd_probe) is detached from the system. It is called (potentially * multiple times) during sd module unload. * @sdp: pointer to mid level scsi device object * * Note: this function is invoked from the scsi mid-level. * This function potentially frees up a device name (e.g. /dev/sdc) * that could be re-used by a subsequent sd_probe(). * This function is not called when the built-in sd driver is "exit-ed". **/ static int sd_remove(struct device *dev) { struct scsi_disk *sdkp; sdkp = dev_get_drvdata(dev); scsi_autopm_get_device(sdkp->device); async_synchronize_full(); blk_queue_prep_rq(sdkp->device->request_queue, scsi_prep_fn); blk_queue_unprep_rq(sdkp->device->request_queue, NULL); device_del(&sdkp->dev); del_gendisk(sdkp->disk); sd_shutdown(dev); mutex_lock(&sd_ref_mutex); dev_set_drvdata(dev, NULL); put_device(&sdkp->dev); mutex_unlock(&sd_ref_mutex); return 0; } /** * scsi_disk_release - Called to free the scsi_disk structure * @dev: pointer to embedded class device * * sd_ref_mutex must be held entering this routine. Because it is * called on last put, you should always use the scsi_disk_get() * scsi_disk_put() helpers which manipulate the semaphore directly * and never do a direct put_device. **/ static void scsi_disk_release(struct device *dev) { struct scsi_disk *sdkp = to_scsi_disk(dev); struct gendisk *disk = sdkp->disk; spin_lock(&sd_index_lock); ida_remove(&sd_index_ida, sdkp->index); #ifdef SYNO_SAS_DISK_NAME if (1 == g_is_sas_model) { switch(sdkp->synodisktype) { #ifdef MY_ABC_HERE case SYNO_DISK_ISCSI: ida_remove(&iscsi_index_ida, sdkp->synoindex); break; #endif case SYNO_DISK_USB: ida_remove(&usb_index_ida, sdkp->synoindex); break; case SYNO_DISK_SAS: ida_remove(&sas_index_ida, sdkp->synoindex); break; default: break; } } #endif spin_unlock(&sd_index_lock); disk->private_data = NULL; put_disk(disk); put_device(&sdkp->device->sdev_gendev); kfree(sdkp); } static int sd_start_stop_device(struct scsi_disk *sdkp, int start) { unsigned char cmd[6] = { START_STOP }; /* START_VALID */ struct scsi_sense_hdr sshdr; struct scsi_device *sdp = sdkp->device; int res; if (start) cmd[4] |= 1; /* START */ if (sdp->start_stop_pwr_cond) cmd[4] |= start ? 1 << 4 : 3 << 4; /* Active or Standby */ if (!scsi_device_online(sdp)) return -ENODEV; res = scsi_execute_req(sdp, cmd, DMA_NONE, NULL, 0, &sshdr, SD_TIMEOUT, SD_MAX_RETRIES, NULL); if (res) { sd_printk(KERN_WARNING, sdkp, "START_STOP FAILED\n"); sd_print_result(sdkp, res); if (driver_byte(res) & DRIVER_SENSE) sd_print_sense_hdr(sdkp, &sshdr); } return res; } /* * Send a SYNCHRONIZE CACHE instruction down to the device through * the normal SCSI command structure. Wait for the command to * complete. */ static void sd_shutdown(struct device *dev) { struct scsi_disk *sdkp = scsi_disk_get_from_dev(dev); if (!sdkp) return; /* this can happen */ if (sdkp->WCE) { sd_printk(KERN_NOTICE, sdkp, "Synchronizing SCSI cache\n"); sd_sync_cache(sdkp); } if (system_state != SYSTEM_RESTART && sdkp->device->manage_start_stop) { sd_printk(KERN_NOTICE, sdkp, "Stopping disk\n"); sd_start_stop_device(sdkp, 0); } scsi_disk_put(sdkp); } static int sd_suspend(struct device *dev, pm_message_t mesg) { struct scsi_disk *sdkp = scsi_disk_get_from_dev(dev); int ret = 0; if (!sdkp) return 0; /* this can happen */ if (sdkp->WCE) { sd_printk(KERN_NOTICE, sdkp, "Synchronizing SCSI cache\n"); ret = sd_sync_cache(sdkp); if (ret) goto done; } if ((mesg.event & PM_EVENT_SLEEP) && sdkp->device->manage_start_stop) { sd_printk(KERN_NOTICE, sdkp, "Stopping disk\n"); ret = sd_start_stop_device(sdkp, 0); } done: scsi_disk_put(sdkp); return ret; } static int sd_resume(struct device *dev) { struct scsi_disk *sdkp = scsi_disk_get_from_dev(dev); int ret = 0; if (!sdkp->device->manage_start_stop) goto done; sd_printk(KERN_NOTICE, sdkp, "Starting disk\n"); ret = sd_start_stop_device(sdkp, 1); done: scsi_disk_put(sdkp); return ret; } /** * init_sd - entry point for this driver (both when built in or when * a module). * * Note: this function registers this driver with the scsi mid-level. **/ static int __init init_sd(void) { int majors = 0, i, err; SCSI_LOG_HLQUEUE(3, printk("init_sd: sd driver entry point\n")); for (i = 0; i < SD_MAJORS; i++) if (register_blkdev(sd_major(i), "sd") == 0) majors++; #ifdef SYNO_BADSECTOR_TEST gBadSectorTest = 0; #endif if (!majors) return -ENODEV; err = class_register(&sd_disk_class); if (err) goto err_out; err = scsi_register_driver(&sd_template.gendrv); if (err) goto err_out_class; sd_cdb_cache = kmem_cache_create("sd_ext_cdb", SD_EXT_CDB_SIZE, 0, 0, NULL); if (!sd_cdb_cache) { printk(KERN_ERR "sd: can't init extended cdb cache\n"); goto err_out_class; } sd_cdb_pool = mempool_create_slab_pool(SD_MEMPOOL_SIZE, sd_cdb_cache); if (!sd_cdb_pool) { printk(KERN_ERR "sd: can't init extended cdb pool\n"); goto err_out_cache; } return 0; err_out_cache: kmem_cache_destroy(sd_cdb_cache); err_out_class: class_unregister(&sd_disk_class); err_out: for (i = 0; i < SD_MAJORS; i++) unregister_blkdev(sd_major(i), "sd"); return err; } /** * exit_sd - exit point for this driver (when it is a module). * * Note: this function unregisters this driver from the scsi mid-level. **/ static void __exit exit_sd(void) { int i; SCSI_LOG_HLQUEUE(3, printk("exit_sd: exiting sd driver\n")); mempool_destroy(sd_cdb_pool); kmem_cache_destroy(sd_cdb_cache); scsi_unregister_driver(&sd_template.gendrv); class_unregister(&sd_disk_class); for (i = 0; i < SD_MAJORS; i++) unregister_blkdev(sd_major(i), "sd"); } module_init(init_sd); module_exit(exit_sd); static void sd_print_sense_hdr(struct scsi_disk *sdkp, struct scsi_sense_hdr *sshdr) { sd_printk(KERN_INFO, sdkp, " "); scsi_show_sense_hdr(sshdr); sd_printk(KERN_INFO, sdkp, " "); scsi_show_extd_sense(sshdr->asc, sshdr->ascq); } static void sd_print_result(struct scsi_disk *sdkp, int result) { sd_printk(KERN_INFO, sdkp, " "); scsi_show_result(result); } #ifdef MY_ABC_HERE int SynoSCSIGetDeviceIndex(struct block_device *bdev) { struct gendisk *disk = NULL; BUG_ON(bdev == NULL); disk = bdev->bd_disk; #ifdef SYNO_SAS_DISK_NAME if (g_is_sas_model) { return container_of(disk->private_data, struct scsi_disk, driver)->synoindex; } #endif return container_of(disk->private_data, struct scsi_disk, driver)->index; } EXPORT_SYMBOL(SynoSCSIGetDeviceIndex); #endif /* MY_ABC_HERE */ #if defined(MY_ABC_HERE) || defined(MY_ABC_HERE) /** * Please modify this when SCSI_DISK* is bigger than 15 when * porting kernel * * @param major_idx * * @return unsigned char */ static unsigned char blIsScsiDevice(int major) { unsigned char ret = 0; switch (major) { case SCSI_DISK0_MAJOR: case SCSI_DISK1_MAJOR ... SCSI_DISK7_MAJOR: case SCSI_DISK8_MAJOR ... SCSI_DISK15_MAJOR: ret = 1; break; default: break; } return ret; } #endif /* defined(MY_ABC_HERE) || defined(MY_ABC_HERE) */ #ifdef MY_ABC_HERE int IsDeviceDisappear(struct block_device *bdev) { struct gendisk *disk = NULL; struct scsi_disk *sdkp; int ret = 0; if (!bdev) { WARN_ON(bdev == NULL); goto END; } disk = bdev->bd_disk; if (!disk) { WARN_ON(disk == NULL); goto END; } if (!blIsScsiDevice(disk->major)) { /* Only work for scsi disk */ printk("This is not a kind of scsi disk %d\n", disk->major); goto END; } /* is whole disk */ sdkp = container_of(disk->private_data, struct scsi_disk, driver); if (!sdkp) { WARN_ON(!sdkp); goto END; } switch (sdkp->device->sdev_state) { case SDEV_OFFLINE: case SDEV_DEL: case SDEV_CANCEL: ret = 1; break; default: break; } END: return ret; } EXPORT_SYMBOL(IsDeviceDisappear); #endif /* MY_ABC_HERE */ #ifdef MY_ABC_HERE /** * Set the partition to specify remap mode * * @param gd [IN] general disk. Should not be NULL * @param phd [IN] partition. Should not be NULL * @param blAutoRemap * [IN] remap mode */ void PartitionRemapModeSet(struct gendisk *gd, struct hd_struct *phd, unsigned char blAutoRemap) { struct scsi_disk *sdkp; struct scsi_device *sdev; if (!gd || !phd) { goto END; } phd->auto_remap = blAutoRemap; if (!blAutoRemap) { if (!blIsScsiDevice(gd->major)) { /* Only work for scsi disk */ printk("This is not a kind of scsi disk %d\n", gd->major); goto END; } sdkp = container_of(gd->private_data, struct scsi_disk, driver); if (!sdkp) { printk(" sdkp is NULL\n"); goto END; } sdev = sdkp->device; if(!sdev) { printk(" sdev is NULL\n"); goto END; } sdev->auto_remap = 0; } END: return; } /** * Set the scsi device to specift remap mode. * * And also set the relative partition to that mode. * * @param sdev [IN] scsi devide. Should not be NULL. * @param blAutoRemap * [IN] auto remap mode. */ void ScsiRemapModeSet(struct scsi_device *sdev, unsigned char blAutoRemap) { struct scsi_disk *sdkp; struct gendisk *gd; struct hd_struct *phd; int i = 0; if (!sdev) { goto END; } if (TYPE_DISK != sdev->type) { printk("Only support scsi disk\n"); goto END; } sdev->auto_remap = blAutoRemap; sdkp = dev_get_drvdata(&sdev->sdev_gendev); if (!sdkp) { goto END; } gd = sdkp->disk; if (!gd) { goto END; } /* disk part */ for (i = 0; i < gd->minors; i++) { phd = disk_get_part(gd, i+1); if (!phd || !phd->nr_sects) continue; phd->auto_remap = blAutoRemap; } END: return; } /** * Set the block device to specify remap mode * * @param bdev [IN] block device. Should not be NULL. * @param blAutoRemap * [IN] remap mode */ void RaidRemapModeSet(struct block_device *bdev, unsigned char blAutoRemap) { struct gendisk *disk = NULL; struct scsi_disk *sdkp; if (!bdev) { WARN_ON(bdev == NULL); return; } disk = bdev->bd_disk; if (!disk) { WARN_ON(disk == NULL); return; } if (!blIsScsiDevice(disk->major)) { /* Only work for scsi disk */ printk("This is not a kind of scsi disk %d\n", disk->major); return; } if (bdev->bd_part) { /* is a partition of some disks */ bdev->bd_part->auto_remap = blAutoRemap; } else { /* is whole disk */ sdkp = container_of(disk->private_data, struct scsi_disk, driver); if (!sdkp) { WARN_ON(!sdkp); return; } ScsiRemapModeSet(sdkp->device, blAutoRemap); } } unsigned char blSectorNeedAutoRemap(struct scsi_cmnd *scsi_cmd, sector_t lba) { struct scsi_device *sdev; struct scsi_disk *sdkp; struct gendisk *gd; struct hd_struct *phd; char szName[BDEVNAME_SIZE]; sector_t start, end; u8 ret = 0; int i = 0; if (!scsi_cmd) { WARN_ON(1); goto END; } sdev = scsi_cmd->device; if (!sdev) { WARN_ON(1); goto END; } if (TYPE_DISK != sdev->type) { printk("Only support scsi disk\n"); goto END; } /* global disk auto remap */ if (sdev->auto_remap) { ret = 1; printk("%s auto remap is on\n", dev_name(&sdev->sdev_gendev)); goto END; } sdkp = dev_get_drvdata(&sdev->sdev_gendev); if (!sdkp) { goto END; } gd = sdkp->disk; if (!gd) { goto END; } /* disk part */ for (i = 0; i < gd->minors; i++) { phd = disk_get_part(gd, i+1); if (!phd || !phd->nr_sects) continue; start = phd->start_sect; end = phd->nr_sects + start - 1; if (lba >= start && lba <= end) { printk("lba %llu start %llu end %llu\n", (unsigned long long)lba, (unsigned long long)start, (unsigned long long)end); ret = phd->auto_remap; printk("%s auto_remap %u\n", disk_name(gd, i+1, szName), phd->auto_remap); } } END: return ret; } EXPORT_SYMBOL(blSectorNeedAutoRemap); EXPORT_SYMBOL(RaidRemapModeSet); EXPORT_SYMBOL(ScsiRemapModeSet); EXPORT_SYMBOL(PartitionRemapModeSet); #endif /* MY_ABC_HERE */
gpl-2.0
heiher/gst-ffmpeg
gst-libs/ext/libav/libavcodec/pcm-mpeg.c
11771
/* * LPCM codecs for PCM formats found in MPEG streams * Copyright (c) 2009 Christian Schmidt * * This file is part of Libav. * * Libav is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * Libav 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 Libav; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * PCM codecs for encodings found in MPEG streams (DVD/Blu-ray) */ #include "libavutil/audioconvert.h" #include "avcodec.h" #include "bytestream.h" /* * Channel Mapping according to * Blu-ray Disc Read-Only Format Version 1 * Part 3: Audio Visual Basic Specifications * mono M1 X * stereo L R * 3/0 L R C X * 2/1 L R S X * 3/1 L R C S * 2/2 L R LS RS * 3/2 L R C LS RS X * 3/2+lfe L R C LS RS lfe * 3/4 L R C LS Rls Rrs RS X * 3/4+lfe L R C LS Rls Rrs RS lfe */ /** * Parse the header of a LPCM frame read from a MPEG-TS stream * @param avctx the codec context * @param header pointer to the first four bytes of the data packet */ static int pcm_bluray_parse_header(AVCodecContext *avctx, const uint8_t *header) { static const uint8_t bits_per_samples[4] = { 0, 16, 20, 24 }; static const uint32_t channel_layouts[16] = { 0, AV_CH_LAYOUT_MONO, 0, AV_CH_LAYOUT_STEREO, AV_CH_LAYOUT_SURROUND, AV_CH_LAYOUT_2_1, AV_CH_LAYOUT_4POINT0, AV_CH_LAYOUT_2_2, AV_CH_LAYOUT_5POINT0, AV_CH_LAYOUT_5POINT1, AV_CH_LAYOUT_7POINT0, AV_CH_LAYOUT_7POINT1, 0, 0, 0, 0 }; static const uint8_t channels[16] = { 0, 1, 0, 2, 3, 3, 4, 4, 5, 6, 7, 8, 0, 0, 0, 0 }; uint8_t channel_layout = header[2] >> 4; if (avctx->debug & FF_DEBUG_PICT_INFO) av_dlog(avctx, "pcm_bluray_parse_header: header = %02x%02x%02x%02x\n", header[0], header[1], header[2], header[3]); /* get the sample depth and derive the sample format from it */ avctx->bits_per_coded_sample = bits_per_samples[header[3] >> 6]; if (!avctx->bits_per_coded_sample) { av_log(avctx, AV_LOG_ERROR, "unsupported sample depth (0)\n"); return -1; } avctx->sample_fmt = avctx->bits_per_coded_sample == 16 ? AV_SAMPLE_FMT_S16 : AV_SAMPLE_FMT_S32; /* get the sample rate. Not all values are known or exist. */ switch (header[2] & 0x0f) { case 1: avctx->sample_rate = 48000; break; case 4: avctx->sample_rate = 96000; break; case 5: avctx->sample_rate = 192000; break; default: avctx->sample_rate = 0; av_log(avctx, AV_LOG_ERROR, "unsupported sample rate (%d)\n", header[2] & 0x0f); return -1; } /* * get the channel number (and mapping). Not all values are known or exist. * It must be noted that the number of channels in the MPEG stream can * differ from the actual meaningful number, e.g. mono audio still has two * channels, one being empty. */ avctx->channel_layout = channel_layouts[channel_layout]; avctx->channels = channels[channel_layout]; if (!avctx->channels) { av_log(avctx, AV_LOG_ERROR, "unsupported channel configuration (%d)\n", channel_layout); return -1; } avctx->bit_rate = avctx->channels * avctx->sample_rate * avctx->bits_per_coded_sample; if (avctx->debug & FF_DEBUG_PICT_INFO) av_dlog(avctx, "pcm_bluray_parse_header: %d channels, %d bits per sample, %d kHz, %d kbit\n", avctx->channels, avctx->bits_per_coded_sample, avctx->sample_rate, avctx->bit_rate); return 0; } static int pcm_bluray_decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt) { const uint8_t *src = avpkt->data; int buf_size = avpkt->size; int num_source_channels, channel, retval; int sample_size, samples, output_size; int16_t *dst16 = data; int32_t *dst32 = data; if (buf_size < 4) { av_log(avctx, AV_LOG_ERROR, "PCM packet too small\n"); return -1; } if (pcm_bluray_parse_header(avctx, src)) return -1; src += 4; buf_size -= 4; /* There's always an even number of channels in the source */ num_source_channels = FFALIGN(avctx->channels, 2); sample_size = (num_source_channels * avctx->bits_per_coded_sample) >> 3; samples = buf_size / sample_size; output_size = samples * avctx->channels * (avctx->sample_fmt == AV_SAMPLE_FMT_S32 ? 4 : 2); if (output_size > *data_size) { av_log(avctx, AV_LOG_ERROR, "Insufficient output buffer space (%d bytes, needed %d bytes)\n", *data_size, output_size); return -1; } *data_size = output_size; if (samples) { switch (avctx->channel_layout) { /* cases with same number of source and coded channels */ case AV_CH_LAYOUT_STEREO: case AV_CH_LAYOUT_4POINT0: case AV_CH_LAYOUT_2_2: samples *= num_source_channels; if (AV_SAMPLE_FMT_S16 == avctx->sample_fmt) { #if HAVE_BIGENDIAN memcpy(dst16, src, output_size); #else do { *dst16++ = bytestream_get_be16(&src); } while (--samples); #endif } else { do { *dst32++ = bytestream_get_be24(&src) << 8; } while (--samples); } break; /* cases where number of source channels = coded channels + 1 */ case AV_CH_LAYOUT_MONO: case AV_CH_LAYOUT_SURROUND: case AV_CH_LAYOUT_2_1: case AV_CH_LAYOUT_5POINT0: if (AV_SAMPLE_FMT_S16 == avctx->sample_fmt) { do { #if HAVE_BIGENDIAN memcpy(dst16, src, avctx->channels * 2); dst16 += avctx->channels; src += sample_size; #else channel = avctx->channels; do { *dst16++ = bytestream_get_be16(&src); } while (--channel); src += 2; #endif } while (--samples); } else { do { channel = avctx->channels; do { *dst32++ = bytestream_get_be24(&src) << 8; } while (--channel); src += 3; } while (--samples); } break; /* remapping: L, R, C, LBack, RBack, LF */ case AV_CH_LAYOUT_5POINT1: if (AV_SAMPLE_FMT_S16 == avctx->sample_fmt) { do { dst16[0] = bytestream_get_be16(&src); dst16[1] = bytestream_get_be16(&src); dst16[2] = bytestream_get_be16(&src); dst16[4] = bytestream_get_be16(&src); dst16[5] = bytestream_get_be16(&src); dst16[3] = bytestream_get_be16(&src); dst16 += 6; } while (--samples); } else { do { dst32[0] = bytestream_get_be24(&src) << 8; dst32[1] = bytestream_get_be24(&src) << 8; dst32[2] = bytestream_get_be24(&src) << 8; dst32[4] = bytestream_get_be24(&src) << 8; dst32[5] = bytestream_get_be24(&src) << 8; dst32[3] = bytestream_get_be24(&src) << 8; dst32 += 6; } while (--samples); } break; /* remapping: L, R, C, LSide, LBack, RBack, RSide, <unused> */ case AV_CH_LAYOUT_7POINT0: if (AV_SAMPLE_FMT_S16 == avctx->sample_fmt) { do { dst16[0] = bytestream_get_be16(&src); dst16[1] = bytestream_get_be16(&src); dst16[2] = bytestream_get_be16(&src); dst16[5] = bytestream_get_be16(&src); dst16[3] = bytestream_get_be16(&src); dst16[4] = bytestream_get_be16(&src); dst16[6] = bytestream_get_be16(&src); dst16 += 7; src += 2; } while (--samples); } else { do { dst32[0] = bytestream_get_be24(&src) << 8; dst32[1] = bytestream_get_be24(&src) << 8; dst32[2] = bytestream_get_be24(&src) << 8; dst32[5] = bytestream_get_be24(&src) << 8; dst32[3] = bytestream_get_be24(&src) << 8; dst32[4] = bytestream_get_be24(&src) << 8; dst32[6] = bytestream_get_be24(&src) << 8; dst32 += 7; src += 3; } while (--samples); } break; /* remapping: L, R, C, LSide, LBack, RBack, RSide, LF */ case AV_CH_LAYOUT_7POINT1: if (AV_SAMPLE_FMT_S16 == avctx->sample_fmt) { do { dst16[0] = bytestream_get_be16(&src); dst16[1] = bytestream_get_be16(&src); dst16[2] = bytestream_get_be16(&src); dst16[6] = bytestream_get_be16(&src); dst16[4] = bytestream_get_be16(&src); dst16[5] = bytestream_get_be16(&src); dst16[7] = bytestream_get_be16(&src); dst16[3] = bytestream_get_be16(&src); dst16 += 8; } while (--samples); } else { do { dst32[0] = bytestream_get_be24(&src) << 8; dst32[1] = bytestream_get_be24(&src) << 8; dst32[2] = bytestream_get_be24(&src) << 8; dst32[6] = bytestream_get_be24(&src) << 8; dst32[4] = bytestream_get_be24(&src) << 8; dst32[5] = bytestream_get_be24(&src) << 8; dst32[7] = bytestream_get_be24(&src) << 8; dst32[3] = bytestream_get_be24(&src) << 8; dst32 += 8; } while (--samples); } break; } } retval = src - avpkt->data; if (avctx->debug & FF_DEBUG_BITSTREAM) av_dlog(avctx, "pcm_bluray_decode_frame: decoded %d -> %d bytes\n", retval, *data_size); return retval; } AVCodec ff_pcm_bluray_decoder = { "pcm_bluray", AVMEDIA_TYPE_AUDIO, CODEC_ID_PCM_BLURAY, 0, NULL, NULL, NULL, pcm_bluray_decode_frame, .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_NONE}, .long_name = NULL_IF_CONFIG_SMALL("PCM signed 16|20|24-bit big-endian for Blu-ray media"), };
gpl-2.0
hwellmann/greenpepper-core
src/main/java/com/greenpepper/interpreter/flow/scenario/ExpectationTypeConverter.java
1216
/** * Copyright (c) 2009 Pyxis Technologies inc. * * This 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 software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, * or see the FSF site: http://www.fsf.org. */ package com.greenpepper.interpreter.flow.scenario; import com.greenpepper.converter.*; public class ExpectationTypeConverter extends AbstractTypeConverter { @SuppressWarnings("unchecked") public boolean canConvertTo(Class type) { return Expectation.class.isAssignableFrom( type ); } protected Object doConvert(String value) { return new Expectation( value ); } }
gpl-2.0
lathen/voreen
modules/itk_generated/processors/itk_ImageIntensity/shiftscaleimagefilter.cpp
6242
/*********************************************************************************** * * * Voreen - The Volume Rendering Engine * * * * Copyright (C) 2005-2013 University of Muenster, Germany. * * Visualization and Computer Graphics Group <http://viscg.uni-muenster.de> * * For a list of authors please refer to the file "CREDITS.txt". * * * * This file is part of the Voreen software package. Voreen 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. * * * * Voreen 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 in the file * * "LICENSE.txt" along with this file. If not, see <http://www.gnu.org/licenses/>. * * * * For non-commercial academic use see the license exception specified in the file * * "LICENSE-academic.txt". To get information about commercial licensing please * * contact the authors. * * * ***********************************************************************************/ #include "shiftscaleimagefilter.h" #include "voreen/core/datastructures/volume/volumeram.h" #include "voreen/core/datastructures/volume/volume.h" #include "voreen/core/datastructures/volume/volumeatomic.h" #include "voreen/core/ports/conditions/portconditionvolumetype.h" #include "modules/itk/utils/itkwrapper.h" #include "voreen/core/datastructures/volume/operators/volumeoperatorconvert.h" #include "itkImage.h" #include "itkShiftScaleImageFilter.h" #include <iostream> namespace voreen { const std::string ShiftScaleImageFilterITK::loggerCat_("voreen.ShiftScaleImageFilterITK"); ShiftScaleImageFilterITK::ShiftScaleImageFilterITK() : ITKProcessor(), inport1_(Port::INPORT, "InputImage"), outport1_(Port::OUTPORT, "OutputImage"), enableProcessing_("enabled", "Enable", false), scale_("scale", "Scale", 1.0f, 0.0f, 5000.0f), shift_("shift", "Shift", 1.0f, 0.0f, 5000.0f) { addPort(inport1_); PortConditionLogicalOr* orCondition1 = new PortConditionLogicalOr(); orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt8()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt8()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt16()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt16()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt32()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt32()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeFloat()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeDouble()); inport1_.addCondition(orCondition1); addPort(outport1_); addProperty(enableProcessing_); addProperty(scale_); addProperty(shift_); } Processor* ShiftScaleImageFilterITK::create() const { return new ShiftScaleImageFilterITK(); } template<class T> void ShiftScaleImageFilterITK::shiftScaleImageFilterITK() { if (!enableProcessing_.get()) { outport1_.setData(inport1_.getData(), false); return; } typedef itk::Image<T, 3> InputImageType1; typedef itk::Image<T, 3> OutputImageType1; typename InputImageType1::Pointer p1 = voreenToITK<T>(inport1_.getData()); //Filter define typedef itk::ShiftScaleImageFilter<InputImageType1, OutputImageType1> FilterType; typename FilterType::Pointer filter = FilterType::New(); filter->SetInput(p1); filter->SetScale(scale_.get()); filter->SetShift(shift_.get()); observe(filter.GetPointer()); try { filter->Update(); } catch (itk::ExceptionObject &e) { LERROR(e); } Volume* outputVolume1 = 0; outputVolume1 = ITKToVoreenCopy<T>(filter->GetOutput()); if (outputVolume1) { transferRWM(inport1_.getData(), outputVolume1); transferTransformation(inport1_.getData(), outputVolume1); outport1_.setData(outputVolume1); } else outport1_.setData(0); } void ShiftScaleImageFilterITK::process() { const VolumeBase* inputHandle1 = inport1_.getData(); const VolumeRAM* inputVolume1 = inputHandle1->getRepresentation<VolumeRAM>(); if (dynamic_cast<const VolumeRAM_UInt8*>(inputVolume1)) { shiftScaleImageFilterITK<uint8_t>(); } else if (dynamic_cast<const VolumeRAM_Int8*>(inputVolume1)) { shiftScaleImageFilterITK<int8_t>(); } else if (dynamic_cast<const VolumeRAM_UInt16*>(inputVolume1)) { shiftScaleImageFilterITK<uint16_t>(); } else if (dynamic_cast<const VolumeRAM_Int16*>(inputVolume1)) { shiftScaleImageFilterITK<int16_t>(); } else if (dynamic_cast<const VolumeRAM_UInt32*>(inputVolume1)) { shiftScaleImageFilterITK<uint32_t>(); } else if (dynamic_cast<const VolumeRAM_Int32*>(inputVolume1)) { shiftScaleImageFilterITK<int32_t>(); } else if (dynamic_cast<const VolumeRAM_Float*>(inputVolume1)) { shiftScaleImageFilterITK<float>(); } else if (dynamic_cast<const VolumeRAM_Double*>(inputVolume1)) { shiftScaleImageFilterITK<double>(); } else { LERROR("Inputformat of Volume 1 is not supported!"); } } } // namespace
gpl-2.0
igraph/igraph
src/paths/histogram.c
5132
/* -*- mode: C -*- */ /* vim:set ts=4 sw=4 sts=4 et: */ /* IGraph library. Copyright (C) 2005-2021 The igraph development team 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_paths.h" #include "igraph_adjlist.h" #include "igraph_dqueue.h" #include "igraph_interface.h" #include "igraph_progress.h" #include "core/interruption.h" /** * \function igraph_path_length_hist * Create a histogram of all shortest path lengths. * * This function calculates a histogram, by calculating the * shortest path length between each pair of vertices. For directed * graphs both directions might be considered and then every pair of vertices * appears twice in the histogram. * \param graph The input graph. * \param res Pointer to an initialized vector, the result is stored * here. The first (i.e. zeroth) element contains the number of * shortest paths of length 1, etc. The supplied vector is resized * as needed. * \param unconnected Pointer to a real number, the number of * pairs for which the second vertex is not reachable from the * first is stored here. * \param directed Whether to consider directed paths in a directed * graph (if not zero). This argument is ignored for undirected * graphs. * \return Error code. * * Time complexity: O(|V||E|), the number of vertices times the number * of edges. * * \sa \ref igraph_average_path_length() and \ref igraph_shortest_paths() */ int igraph_path_length_hist(const igraph_t *graph, igraph_vector_t *res, igraph_real_t *unconnected, igraph_bool_t directed) { long int no_of_nodes = igraph_vcount(graph); long int i, j, n; igraph_vector_long_t already_added; long int nodes_reached; igraph_dqueue_t q = IGRAPH_DQUEUE_NULL; igraph_vector_int_t *neis; igraph_neimode_t dirmode; igraph_adjlist_t allneis; igraph_real_t unconn = 0; long int ressize; if (directed) { dirmode = IGRAPH_OUT; } else { dirmode = IGRAPH_ALL; } IGRAPH_CHECK(igraph_vector_long_init(&already_added, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_long_destroy, &already_added); IGRAPH_DQUEUE_INIT_FINALLY(&q, 100); IGRAPH_CHECK(igraph_adjlist_init(graph, &allneis, dirmode, IGRAPH_LOOPS, IGRAPH_MULTIPLE)); IGRAPH_FINALLY(igraph_adjlist_destroy, &allneis); IGRAPH_CHECK(igraph_vector_resize(res, 0)); ressize = 0; for (i = 0; i < no_of_nodes; i++) { nodes_reached = 1; /* itself */ IGRAPH_CHECK(igraph_dqueue_push(&q, i)); IGRAPH_CHECK(igraph_dqueue_push(&q, 0)); VECTOR(already_added)[i] = i + 1; IGRAPH_PROGRESS("Path length histogram: ", 100.0 * i / no_of_nodes, NULL); IGRAPH_ALLOW_INTERRUPTION(); while (!igraph_dqueue_empty(&q)) { long int actnode = (long int) igraph_dqueue_pop(&q); long int actdist = (long int) igraph_dqueue_pop(&q); neis = igraph_adjlist_get(&allneis, actnode); n = igraph_vector_int_size(neis); for (j = 0; j < n; j++) { long int neighbor = (long int) VECTOR(*neis)[j]; if (VECTOR(already_added)[neighbor] == i + 1) { continue; } VECTOR(already_added)[neighbor] = i + 1; nodes_reached++; if (actdist + 1 > ressize) { IGRAPH_CHECK(igraph_vector_resize(res, actdist + 1)); for (; ressize < actdist + 1; ressize++) { VECTOR(*res)[ressize] = 0; } } VECTOR(*res)[actdist] += 1; IGRAPH_CHECK(igraph_dqueue_push(&q, neighbor)); IGRAPH_CHECK(igraph_dqueue_push(&q, actdist + 1)); } } /* while !igraph_dqueue_empty */ unconn += (no_of_nodes - nodes_reached); } /* for i<no_of_nodes */ IGRAPH_PROGRESS("Path length histogram: ", 100.0, NULL); /* count every pair only once for an undirected graph */ if (!directed || !igraph_is_directed(graph)) { for (i = 0; i < ressize; i++) { VECTOR(*res)[i] /= 2; } unconn /= 2; } igraph_vector_long_destroy(&already_added); igraph_dqueue_destroy(&q); igraph_adjlist_destroy(&allneis); IGRAPH_FINALLY_CLEAN(3); if (unconnected) { *unconnected = unconn; } return 0; }
gpl-2.0
lianglee/opensource-socialnetwork
components/OssnSearch/ossn_com.php
1627
<?php /** * OpenSocialWebsite * * @package OpenSocialWebsite * @author Open Social Website Core Team <[email protected]> * @copyright 2014 iNFORMATIKON TECHNOLOGIES * @license General Public Licence http://www.opensocialwebsite.com/licence * @link http://www.opensocialwebsite.com/licence */ define('__OSSN_SEARCH__', ossn_route()->com.'OssnSearch/'); require_once(__OSSN_SEARCH__.'classes/OssnSearch.php'); function ossn_search(){ ossn_register_page('search', 'ossn_search_page'); ossn_add_hook('search', "left", 'search_menu_handler'); ossn_extend_view('css/ossn.default', 'components/OssnSearch/css/search'); } function search_menu_handler($hook, $type, $return){ $return[] = ossn_view_menu('search'); return $return; } function ossn_search_page($pages){ $page = $pages[0]; if(empty($page)){ $page = 'search'; } ossn_trigger_callback('page', 'load:search'); switch($page){ case 'search': $query = input('q'); $type = input('type'); if(empty($type)){ $params['type'] = 'users'; } else { $params['type'] = $type; } $type = $params['type']; if(ossn_is_hook('search', "type:{$type}")){ $contents['contents'] = ossn_call_hook('search', "type:{$type}", array('q' => input('q'))); } $contents = array( 'content' => ossn_view('components/OssnSearch/pages/search', $contents), ); $content = ossn_set_page_layout('search', $contents); echo ossn_view_page($title, $content); break; default: ossn_error_page(); break; } } ossn_register_callback('ossn', 'init', 'ossn_search');
gpl-2.0
rebirth-core/Rebirth---old
src/server/scripts/Commands/cs_gm.cpp
9929
/* * Copyright (C) 2008-2012 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/>. */ /* ScriptData Name: gm_commandscript %Complete: 100 Comment: All gm related commands Category: commandscripts EndScriptData */ #include "ScriptMgr.h" #include "ObjectMgr.h" #include "Chat.h" #include "AccountMgr.h" class gm_commandscript : public CommandScript { public: gm_commandscript() : CommandScript("gm_commandscript") { } ChatCommand* GetCommands() const { static ChatCommand gmCommandTable[] = { { "chat", SEC_MODERATOR, false, &HandleGMChatCommand, "", NULL }, { "fly", SEC_ADMINISTRATOR, false, &HandleGMFlyCommand, "", NULL }, { "ingame", SEC_PLAYER, true, &HandleGMListIngameCommand, "", NULL }, { "list", SEC_ADMINISTRATOR, true, &HandleGMListFullCommand, "", NULL }, { "visible", SEC_MODERATOR, false, &HandleGMVisibleCommand, "", NULL }, { "", SEC_MODERATOR, false, &HandleGMCommand, "", NULL }, { NULL, 0, false, NULL, "", NULL } }; static ChatCommand commandTable[] = { { "gm", SEC_MODERATOR, false, NULL, "", gmCommandTable }, { NULL, 0, false, NULL, "", NULL } }; return commandTable; } // Enables or disables hiding of the staff badge static bool HandleGMChatCommand(ChatHandler* handler, char const* args) { if (!*args) { WorldSession* session = handler->GetSession(); if (!AccountMgr::IsPlayerAccount(session->GetSecurity()) && session->GetPlayer()->isGMChat()) session->SendNotification(LANG_GM_CHAT_ON); else session->SendNotification(LANG_GM_CHAT_OFF); return true; } std::string param = (char*)args; if (param == "on") { handler->GetSession()->GetPlayer()->SetGMChat(true); handler->GetSession()->SendNotification(LANG_GM_CHAT_ON); return true; } if (param == "off") { handler->GetSession()->GetPlayer()->SetGMChat(false); handler->GetSession()->SendNotification(LANG_GM_CHAT_OFF); return true; } handler->SendSysMessage(LANG_USE_BOL); handler->SetSentErrorMessage(true); return false; } static bool HandleGMFlyCommand(ChatHandler* handler, char const* args) { if (!*args) return false; Player* target = handler->getSelectedPlayer(); if (!target) target = handler->GetSession()->GetPlayer(); WorldPacket data(12); if (strncmp(args, "on", 3) == 0) data.SetOpcode(SMSG_MOVE_SET_CAN_FLY); else if (strncmp(args, "off", 4) == 0) data.SetOpcode(SMSG_MOVE_UNSET_CAN_FLY); else { handler->SendSysMessage(LANG_USE_BOL); return false; } data.append(target->GetPackGUID()); data << uint32(0); // unknown target->SendMessageToSet(&data, true); handler->PSendSysMessage(LANG_COMMAND_FLYMODE_STATUS, handler->GetNameLink(target).c_str(), args); return true; } static bool HandleGMListIngameCommand(ChatHandler* handler, char const* /*args*/) { bool first = true; bool footer = false; TRINITY_READ_GUARD(HashMapHolder<Player>::LockType, *HashMapHolder<Player>::GetLock()); HashMapHolder<Player>::MapType const& m = sObjectAccessor->GetPlayers(); for (HashMapHolder<Player>::MapType::const_iterator itr = m.begin(); itr != m.end(); ++itr) { AccountTypes itrSec = itr->second->GetSession()->GetSecurity(); if ((itr->second->isGameMaster() || (!AccountMgr::IsPlayerAccount(itrSec) && itrSec <= AccountTypes(sWorld->getIntConfig(CONFIG_GM_LEVEL_IN_GM_LIST)))) && (!handler->GetSession() || itr->second->IsVisibleGloballyFor(handler->GetSession()->GetPlayer()))) { if (first) { first = false; footer = true; handler->SendSysMessage(LANG_GMS_ON_SRV); handler->SendSysMessage("========================"); } char const* name = itr->second->GetName(); uint8 security = itrSec; uint8 max = ((16 - strlen(name)) / 2); uint8 max2 = max; if ((max + max2 + strlen(name)) == 16) max2 = max - 1; if (handler->GetSession()) handler->PSendSysMessage("| %s GMLevel %u", name, security); else handler->PSendSysMessage("|%*s%s%*s| %u |", max, " ", name, max2, " ", security); } } if (footer) handler->SendSysMessage("========================"); if (first) handler->SendSysMessage(LANG_GMS_NOT_LOGGED); return true; } /// Display the list of GMs static bool HandleGMListFullCommand(ChatHandler* handler, char const* /*args*/) { ///- Get the accounts with GM Level >0 QueryResult result = LoginDatabase.PQuery("SELECT a.username, aa.gmlevel FROM account a, account_access aa WHERE a.id=aa.id AND aa.gmlevel >= %u", SEC_MODERATOR); if (result) { handler->SendSysMessage(LANG_GMLIST); handler->SendSysMessage("========================"); ///- Cycle through them. Display username and GM level do { Field* fields = result->Fetch(); char const* name = fields[0].GetCString(); uint8 security = fields[1].GetUInt8(); uint8 max = (16 - strlen(name)) / 2; uint8 max2 = max; if ((max + max2 + strlen(name)) == 16) max2 = max - 1; if (handler->GetSession()) handler->PSendSysMessage("| %s GMLevel %u", name, security); else handler->PSendSysMessage("|%*s%s%*s| %u |", max, " ", name, max2, " ", security); } while (result->NextRow()); handler->SendSysMessage("========================"); } else handler->PSendSysMessage(LANG_GMLIST_EMPTY); return true; } //Enable\Disable Invisible mode static bool HandleGMVisibleCommand(ChatHandler* handler, char const* args) { if (!*args) { handler->PSendSysMessage(LANG_YOU_ARE, handler->GetSession()->GetPlayer()->isGMVisible() ? handler->GetTrinityString(LANG_VISIBLE) : handler->GetTrinityString(LANG_INVISIBLE)); return true; } std::string param = (char*)args; if (param == "on") { handler->GetSession()->GetPlayer()->SetGMVisible(true); handler->GetSession()->SendNotification(LANG_INVISIBLE_VISIBLE); return true; } if (param == "off") { handler->GetSession()->SendNotification(LANG_INVISIBLE_INVISIBLE); handler->GetSession()->GetPlayer()->SetGMVisible(false); return true; } handler->SendSysMessage(LANG_USE_BOL); handler->SetSentErrorMessage(true); return false; } //Enable\Disable GM Mode static bool HandleGMCommand(ChatHandler* handler, char const* args) { if (!*args) { if (handler->GetSession()->GetPlayer()->isGameMaster()) handler->GetSession()->SendNotification(LANG_GM_ON); else handler->GetSession()->SendNotification(LANG_GM_OFF); return true; } std::string param = (char*)args; if (param == "on") { handler->GetSession()->GetPlayer()->SetGameMaster(true); handler->GetSession()->SendNotification(LANG_GM_ON); handler->GetSession()->GetPlayer()->UpdateTriggerVisibility(); #ifdef _DEBUG_VMAPS VMAP::IVMapManager* vMapManager = VMAP::VMapFactory::createOrGetVMapManager(); vMapManager->processCommand("stoplog"); #endif return true; } if (param == "off") { handler->GetSession()->GetPlayer()->SetGameMaster(false); handler->GetSession()->SendNotification(LANG_GM_OFF); handler->GetSession()->GetPlayer()->UpdateTriggerVisibility(); #ifdef _DEBUG_VMAPS VMAP::IVMapManager* vMapManager = VMAP::VMapFactory::createOrGetVMapManager(); vMapManager->processCommand("startlog"); #endif return true; } handler->SendSysMessage(LANG_USE_BOL); handler->SetSentErrorMessage(true); return false; } }; void AddSC_gm_commandscript() { new gm_commandscript(); }
gpl-2.0
infinidb/infinidb
writeengine/server/we_getfilesizes.cpp
11001
/* Copyright (C) 2014 InfiniDB, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /***************************************************************************** * $Id: we_getfilesizes.cpp 4450 2013-01-21 14:13:24Z rdempsey $ * ****************************************************************************/ #include "we_getfilesizes.h" #include <iostream> #include <stdexcept> using namespace std; #include "calpontsystemcatalog.h" using namespace execplan; #include "threadpool.h" using namespace threadpool; #include "bytestream.h" using namespace messageqcpp; #include "we_fileop.h" #include "idbcompress.h" using namespace compress; #include "IDBFileSystem.h" #include "IDBPolicy.h" using namespace idbdatafile; namespace WriteEngine { struct FileInfo { uint32_t partition; /** @brief Partition for a file*/ uint16_t segment; /** @brief Segment for a file */ uint16_t dbRoot; /** @brief DbRoot for a file */ std::string segFileName; /** @brief seg file path */ double fileSize; /** @brief seg file size in giga bytes */ void serialize(messageqcpp::ByteStream& bs) { bs << partition; bs << segment; bs << dbRoot; bs << segFileName; bs << (*(uint64_t*)(&fileSize)); } }; typedef std::vector<FileInfo> Files; typedef std::map<uint32_t, Files> columnMap; typedef std::map<int, columnMap*> allColumnMap; allColumnMap wholeMap; boost::mutex columnMapLock; ActiveThreadCounter *activeThreadCounter; size_t readFillBuffer( idbdatafile::IDBDataFile* pFile, char* buffer, size_t bytesReq) { char* pBuf = buffer; ssize_t nBytes; size_t bytesToRead = bytesReq; size_t totalBytesRead = 0; while (1) { nBytes = pFile->read(pBuf, bytesToRead); if (nBytes > 0) totalBytesRead += nBytes; else break; if ((size_t)nBytes == bytesToRead) break; pBuf += nBytes; bytesToRead = bytesToRead - (size_t)nBytes; } return totalBytesRead; } off64_t getCompressedDataSize(string& fileName) { off64_t dataSize = 0; IDBDataFile* pFile = 0; size_t nBytes; // Some IDBPolicy functions can throw exceptions, caller will catch it IDBPolicy::configIDBPolicy(); bool bHdfsFile = IDBPolicy::useHdfs(); if (bHdfsFile) pFile = IDBDataFile::open(IDBDataFile::HDFS, fileName.c_str(), "r", 0); else pFile = IDBDataFile::open(IDBDataFile::BUFFERED, fileName.c_str(), "r", 0); if (!pFile) { std::ostringstream oss; oss << "Cannot open file " << fileName << " for read."; throw std::runtime_error(oss.str()); } IDBCompressInterface decompressor; //-------------------------------------------------------------------------- // Read headers and extract compression pointers //-------------------------------------------------------------------------- char hdr1[IDBCompressInterface::HDR_BUF_LEN]; nBytes = readFillBuffer( pFile,hdr1,IDBCompressInterface::HDR_BUF_LEN); if ( nBytes != IDBCompressInterface::HDR_BUF_LEN ) { std::ostringstream oss; oss << "Error reading first header from file " << fileName; throw std::runtime_error(oss.str()); } int64_t ptrSecSize = decompressor.getHdrSize(hdr1) - IDBCompressInterface::HDR_BUF_LEN; char* hdr2 = new char[ptrSecSize]; nBytes = readFillBuffer( pFile,hdr2,ptrSecSize); if ( (int64_t)nBytes != ptrSecSize ) { std::ostringstream oss; oss << "Error reading second header from file " << fileName; throw std::runtime_error(oss.str()); } CompChunkPtrList chunkPtrs; int rc = decompressor.getPtrList(hdr2, ptrSecSize, chunkPtrs); delete[] hdr2; if (rc != 0) { std::ostringstream oss; oss << "Error decompressing second header from file " << fileName; throw std::runtime_error(oss.str()); } unsigned k = chunkPtrs.size(); // last header's offset + length will be the data bytes dataSize = chunkPtrs[k-1].first + chunkPtrs[k-1].second; delete pFile; return dataSize; } struct ColumnThread { ColumnThread(uint32_t oid, int32_t compressionType, bool reportRealUse, int key) : fOid(oid), fCompressionType(compressionType), fReportRealUse(reportRealUse), fKey(key) {} void operator()() { Config config; config.initConfigCache(); std::vector<uint16_t> rootList; config.getRootIdList( rootList ); FileOp fileOp; Files aFiles; // This function relies on IDBPolicy being initialized by // IDBPolicy::init(). This is done when WriteEngineServer main() calls // IDBPolicy::configIDBPolicy(); IDBDataFile::Types fileType; bool bUsingHdfs = IDBPolicy::useHdfs(); if (bUsingHdfs) fileType = IDBDataFile::HDFS; else fileType = IDBDataFile::UNBUFFERED; IDBFileSystem& fs = IDBFileSystem::getFs( fileType ); for (uint32_t i=0; i < rootList.size(); i++) { std::vector<struct BRM::EMEntry> entries; (void)BRMWrapper::getInstance()->getExtents_dbroot(fOid, entries, rootList[i]); std::vector<struct BRM::EMEntry>::const_iterator iter = entries.begin(); while ( iter != entries.end() ) //organize extents into files { //Find the size of this file //string fileName; char fileName[200]; (void)fileOp.getFileName( fOid, fileName, rootList[i], entries[0].partitionNum, entries[0].segmentNum); string aFile(fileName); //convert between char* and string off64_t fileSize = 0; if (fReportRealUse && (fCompressionType > 0)) { try { fileSize = getCompressedDataSize(aFile); } catch (std::exception& ex) { cerr << ex.what(); } } else fileSize = fs.size( fileName ); if (fileSize > 0) // File exists, add to list { FileInfo aFileInfo; aFileInfo.partition = entries[0].partitionNum; aFileInfo.segment = entries[0].segmentNum; aFileInfo.dbRoot = rootList[i]; aFileInfo.segFileName = aFile; aFileInfo.fileSize = (double)fileSize / (1024 * 1024 * 1024); aFiles.push_back(aFileInfo); //cout.precision(15); //cout << "The file " << aFileInfo.segFileName << " has size " << fixed << aFileInfo.fileSize << "GB" << endl; } //erase the entries from this dbroot. std::vector<struct BRM::EMEntry> entriesTrimed; for (uint32_t m=0; m<entries.size(); m++) { if ((entries[0].partitionNum != entries[m].partitionNum) || (entries[0].segmentNum != entries[m].segmentNum)) entriesTrimed.push_back(entries[m]); } entriesTrimed.swap(entries); iter = entries.begin(); } } boost::mutex::scoped_lock lk(columnMapLock); //cout << "Current size of columnsMap is " << columnsMap.size() << endl; allColumnMap::iterator colMapiter = wholeMap.find(fKey); if (colMapiter != wholeMap.end()) { (colMapiter->second)->insert(make_pair(fOid,aFiles)); activeThreadCounter->decr(); //cout << "Added to columnsMap aFiles with size " << aFiles.size() << " for oid " << fOid << endl; } } uint32_t fOid; int32_t fCompressionType; bool fReportRealUse; int fKey; }; //------------------------------------------------------------------------------ // Process a table size based on input from the // bytestream object. //------------------------------------------------------------------------------ int WE_GetFileSizes::processTable( messageqcpp::ByteStream& bs, std::string& errMsg, int key) { uint8_t rc = 0; errMsg.clear(); try { std::string aTableName; std::string schemaName; bool reportRealUse = false; ByteStream::byte tmp8; bs >> schemaName; //cout << "schema: "<< schemaName << endl; bs >> aTableName; //cout << "tableName: " << aTableName << endl; bs >> tmp8; reportRealUse = (tmp8 != 0); //get column oids boost::shared_ptr<CalpontSystemCatalog> systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(0); CalpontSystemCatalog::TableName tableName; tableName.schema = schemaName; tableName.table = aTableName; CalpontSystemCatalog::RIDList columnList = systemCatalogPtr->columnRIDs(tableName); CalpontSystemCatalog::ColType colType; CalpontSystemCatalog::DictOIDList dictOidList = systemCatalogPtr->dictOIDs(tableName); int serverThreads = 20; int serverQueueSize = serverThreads * 100; threadpool::ThreadPool tp(serverThreads,serverQueueSize); int totalSize = columnList.size() + dictOidList.size(); activeThreadCounter = new ActiveThreadCounter(totalSize); columnMap *columnsMap = new columnMap(); { boost::mutex::scoped_lock lk(columnMapLock); wholeMap[key] = columnsMap; } for (uint32_t i=0; i < columnList.size(); i++) { colType = systemCatalogPtr->colType(columnList[i].objnum); tp.invoke(ColumnThread(columnList[i].objnum, colType.compressionType, reportRealUse, key)); if (colType.ddn.dictOID > 0) tp.invoke(ColumnThread(colType.ddn.dictOID, colType.compressionType, reportRealUse, key)); } /* for (uint32_t i=0; i < dictOidList.size(); i++) { tp.invoke(ColumnThread(dictOidList[i].dictOID)); } */ //check whether all threads finish int sleepTime = 100; // sleep 100 milliseconds between checks struct timespec rm_ts; rm_ts.tv_sec = sleepTime/1000; rm_ts.tv_nsec = sleepTime%1000 *1000000; uint32_t currentActiveThreads = 10; while (currentActiveThreads > 0) { #ifdef _MSC_VER Sleep(sleepTime); #else struct timespec abs_ts; do { abs_ts.tv_sec = rm_ts.tv_sec; abs_ts.tv_nsec = rm_ts.tv_nsec; } while(nanosleep(&abs_ts,&rm_ts) < 0); #endif currentActiveThreads = activeThreadCounter->cur(); } } catch(std::exception& ex) { //cout << "WE_GetFileSizes got exception-" << ex.what() << // std::endl; errMsg = ex.what(); rc = 1; } //Build the message to send to the caller bs.reset(); boost::mutex::scoped_lock lk(columnMapLock); allColumnMap::iterator colMapiter = wholeMap.find(key); if (colMapiter != wholeMap.end()) { columnMap::iterator iter = colMapiter->second->begin(); uint64_t size; Files::iterator it; while ( iter != colMapiter->second->end()) { bs << iter->first; //cout << "processTable::coloid = " << iter->first << endl; size = iter->second.size(); bs << size; for (it = iter->second.begin(); it != iter->second.end(); it++) it->serialize(bs); //cout << "length now is " << bs.length() << endl; iter++; } wholeMap.erase(colMapiter); } return rc; } }
gpl-2.0
vexorian/kawigi-edit
kawigi/util/StringsUtil.java
8044
package kawigi.util; import java.util.Comparator; /** */ public final class StringsUtil { /** * Line separator in current Operating System. */ public static final String CRLF = System.getProperty("line.separator"); /** * Regular expression for line separator matching. */ public static final String sCRLFregex = "\r?\n"; private static StringsComparator compar = new StringsComparator(); private StringsUtil() {} public static int getFirstNonSpaceInd(CharSequence val, int startInd) { int res = startInd; while (val.length() > res) { char c = val.charAt(res); if (!Character.isSpaceChar(c) && !Character.isWhitespace(c)) break; ++res; } return res; } public static int getFirstNonSpaceInd(CharSequence val) { return getFirstNonSpaceInd(val, 0); } public static int getLastNonSpaceInd(CharSequence val, int startInd) { int res = startInd; while (0 <= res) { char c = val.charAt(res); if (!Character.isSpaceChar(c) && !Character.isWhitespace(c)) break; --res; } return res; } public static int getLastNonSpaceInd(CharSequence val) { return getLastNonSpaceInd(val, val.length() - 1); } public static void removeAllNextSpace(StringBuilder val, int startInd) { int endInd = getFirstNonSpaceInd(val, startInd); val.delete(startInd, endInd); } public static void removeAllPrevSpace(StringBuilder val, int endInd) { int startInd = getLastNonSpaceInd(val, endInd); val.delete(startInd + 1, endInd + 1); } public static void trim(StringBuilder val) { removeAllNextSpace(val, 0); removeAllPrevSpace(val, val.length() - 1); } public static void addArrayMarks(StringBuilder val) { val.insert(0, '{').append('}'); } public static void removeArrayMarks(StringBuilder val) { trim(val); if (0 < val.length()) { if ('{' == val.charAt(0)) { val.deleteCharAt(0); if ('}' == val.charAt(val.length() - 1)) val.setLength(val.length() - 1); } } } public static void addStringMarks(StringBuilder val) { val.insert(0, '"').append('"'); } public static void removeStringMarks(StringBuilder val) { trim(val); if (0 < val.length()) { if ('"' == val.charAt(0)) { val.deleteCharAt(0); if ('"' == val.charAt(val.length() - 1)) val.setLength(val.length() - 1); } } } public static Comparator<CharSequence> getComparator() { return compar; } /** * Compares two strings in CharSequences on equality. CharSequences can't * do this check themselves, so I was bound to write this method. * * @param val1 First value to compare * @param val2 Second value to compare * @return <code>true</code> if two values given are equal, * <code>false</code> otherwise */ public static boolean isEqual(CharSequence val1, CharSequence val2) { return 0 == compar.compare(val1, val2); } /** * Converts string value to lowercase. Converting made inplace. * * @param val Value to be converted and place to make result */ public static void toLower(StringBuilder val) { for (int i = 0; val.length() > i; ++i) { val.setCharAt(i, Character.toLowerCase(val.charAt(i))); } } /** * Replaces the value in StringBuilder with another CharSeqence. * * @param val StringBuilder for the result to be placed * @param seq Value that must be placed into <code>val</code> */ public static void reset(StringBuilder val, CharSequence seq) { val.setLength(0); val.append(seq); } /** * Replaces the part of string with another string without unnecessary * deletions and insertions. Value is changed inplace. * * @param val Value to be changed * @param start Start index of replacement object * @param end End index (one char behind end) of replacement object * @param seq Sequence to be inserted instead */ public static void replace(StringBuilder val, int start, int end, CharSequence seq) { int valPos = start, seqPos = 0; // First we char-by-char replace what we can for (; valPos != end && seqPos != seq.length(); ++valPos, ++seqPos) val.setCharAt(valPos, seq.charAt(seqPos)); // Then we do deletion and insertion of the rest if (valPos < end) val.delete(valPos, end); else if (seqPos < seq.length()) val.insert(end, seq, seqPos, seq.length()); } /** * Finds first occurence of character in CharSequence starting from index start. * * @param val Sequence to search for character * @param c Character to search for * @param start Starting index in sequence to search * @return Index in sequence where character is found or -1 * if it wasn't found */ public static int indexOf(CharSequence val, char c, int start) { int res = -1; for (int i = start; val.length() > i; ++i) { if (val.charAt(i) == c) { res = i; break; } } return res; } /** * Finds first occurence of character in CharSequence starting from the beginning. * * @param val Sequence to search for character * @param c Character to search for * @return Index in sequence where character is found or -1 * if it wasn't found */ public static int indexOf(CharSequence val, char c) { return indexOf(val, c, 0); } /** * Finds last occurence of character in CharSequence starting from index start. * * @param val Sequence to search for character * @param c Character to search for * @param start Starting index in sequence to search * @return Index in sequence where character is found or -1 * if it wasn't found */ public static int lastIndexOf(CharSequence val, char c, int start) { int res = -1; int i = start; if (val.length() <= i) i = val.length() - 1; for (; 0 <= i; --i) { if (val.charAt(i) == c) { res = i; break; } } return res; } /** * Finds last occurence of character in CharSequence starting from the beginning. * * @param val Sequence to search for character * @param c Character to search for * @return Index in sequence where character is found or -1 * if it wasn't found */ public static int lastIndexOf(CharSequence val, char c) { return lastIndexOf(val, c, val.length() - 1); } /** * Checks if some string ('needle') stands at particular point ('startInd') in * another string ('hay'). * * @param hay String to look for 'needle' in * @param needle String to check for appearance in 'hay' * @param startInd Index in 'hay' at which 'needle' should stand * @return <code>true</code> if 'needle' stands in 'hay' at position * 'startInd'. <code>false</code> otherwise. */ public static boolean isStringAt(CharSequence hay, CharSequence needle, int startInd) { boolean res = false; if (hay.length() >= startInd + needle.length()) { res = true; for (int i = 0, j = startInd; needle.length() > i; ++i, ++j) { if (hay.charAt(j) != needle.charAt(i)) { res = false; break; } } } return res; } /** * Appends some excerpt from character sequence to StringBuilder trimming all * white space from excerpt beforehand. * * @param val Value to be modified * @param fromVal Sequence to make excerpt from * @param start Starting index of excerpt from sequence * @param end Ending index of excerpt from sequence (one character after end) */ public static void appendTrimmed(StringBuilder val, CharSequence fromVal, int start, int end) { val.append(fromVal, getFirstNonSpaceInd(fromVal, start), getLastNonSpaceInd(fromVal, end - 1) + 1); } }
gpl-2.0
nam2long/WMACS---DP-PHP
config/WMACS.Config.php
1879
<?PHP $server = $_SERVER['SERVER_NAME']; //Required for MYSQL query unless you remove it from here and line 39 /*-----------------INFORMATION & LICENSING----------------- * AUTHOR: Christopher Sparrowgrove * WEBSITE: https://github.com/nam2long/WMACS * DATE: January 13, 2014 * NAME: WMACS (Website Maintenance/Availability Check System)(Ver 3.0.0.008) * DESCRIPTION: This script check the health status of a webapp via a database or script. * LICENSE: GNU GENERAL PUBLIC LICENSE (Ver 2.0) */ //DEFAULT CONFIGURATIONS //PAGES $hpage = "home.php"; //Default Page/Script $dpage = "down.php"; //Down Page/Script //OVERRIDE $wmacs = false; //WMACS Database Support Override: Set below switch if disabled $override = "1"; // Check ERROR PAGE CONFIG for status numbers //MYSQL CONFIG $mysql_host = "localhost"; //Database Host $mysql_user = "root"; //Database Username $mysql_pass = ""; //Database Password $mysql_database = "cms"; //Database $mysql_table = "wmacs"; //Database Table // DO NOT MODIFY BEYOND THIS POINT \\ // UNLESS YOU KNOW WHAT YOU ARE DOIN \\ if ($wmacs == true) //if override is true { $switch = $override; //set switch from below override option } else { $dbconnect = mysqli_connect($mysql_host, $mysql_user, $mysql_pass, $mysql_database) or die ("Sorry, There was an issue connecting to database"); if ($result = $dbconnect->query('SELECT srv,switch FROM wmacs WHERE srv = "'.$server.'"') or die ("Sorry, There was an issue when querying the database")) //Grab only current accessed site data { $count = $result->num_rows; $row = $result->fetch_object(); $srv = $row->srv; //Grab & Assign Srv URI $switch = $row->switch; //Grab & Assign SRV Switch } } ?>
gpl-2.0
uq-eresearch/oztrack
src/main/java/org/oztrack/validator/UserFormValidator.java
2724
package org.oztrack.validator; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import org.apache.commons.lang3.StringUtils; import org.oztrack.app.OzTrackApplication; import org.oztrack.data.access.UserDao; import org.oztrack.data.model.User; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; public class UserFormValidator implements Validator { private UserDao userDao; public UserFormValidator(UserDao userDao) { this.userDao = userDao; } @Override public boolean supports(@SuppressWarnings("rawtypes") Class clazz) { return User.class.isAssignableFrom(clazz); } @Override public void validate(Object obj, Errors errors) { User loginUser = (User) obj; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "error.empty.field", "Please enter username"); User existingUserByUsername = userDao.getByUsername(loginUser.getUsername()); if ((existingUserByUsername != null) && (existingUserByUsername != loginUser)) { errors.rejectValue("username", "unavailable.user", "This username is unavailable. Please try another."); } User existingUserByEmail = userDao.getByEmail(loginUser.getEmail()); if ((existingUserByEmail != null) && (existingUserByEmail != loginUser)) { errors.rejectValue("email", "unavailable.email", "This email address is already associated with another account."); } if (OzTrackApplication.getApplicationContext().isAafEnabled() && StringUtils.isNotBlank(loginUser.getAafId())) { User existingUserByAafId = userDao.getByAafId(loginUser.getAafId()); if ((existingUserByAafId != null) && (existingUserByAafId != loginUser)) { errors.rejectValue("aafId", "aafId.user", "This AAF ID is already associated with another account."); } } ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "error.empty.field", "Please enter first name"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "error.empty.field", "Please enter last name"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "error.empty.field", "Please enter email"); if (!errors.hasFieldErrors("email")) { try { InternetAddress emailAddr = new InternetAddress(loginUser.getEmail()); emailAddr.validate(); } catch (AddressException ex) { errors.rejectValue("email", "invalid.email", "Email error: " + ex.getMessage()); } } } }
gpl-2.0
ksjogo/TYPO3.CMS
typo3/sysext/extbase/Classes/Utility/LocalizationUtility.php
12059
<?php namespace TYPO3\CMS\Extbase\Utility; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use TYPO3\CMS\Core\Localization\Locales; use TYPO3\CMS\Core\Localization\LocalizationFactory; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface; use TYPO3\CMS\Extbase\Object\ObjectManager; /** * Localization helper which should be used to fetch localized labels. * * @api */ class LocalizationUtility { /** * @var string */ protected static $locallangPath = 'Resources/Private/Language/'; /** * Local Language content * * @var array */ protected static $LOCAL_LANG = []; /** * Contains those LL keys, which have been set to (empty) in TypoScript. * This is necessary, as we cannot distinguish between a nonexisting * translation and a label that has been cleared by TS. * In both cases ['key'][0]['target'] is "". * * @var array */ protected static $LOCAL_LANG_UNSET = []; /** * Key of the language to use * * @var string */ protected static $languageKey = 'default'; /** * Pointer to alternative fall-back language to use * * @var array */ protected static $alternativeLanguageKeys = []; /** * @var \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface */ protected static $configurationManager = null; /** * Returns the localized label of the LOCAL_LANG key, $key. * * @param string $key The key from the LOCAL_LANG array for which to return the value. * @param string $extensionName The name of the extension * @param array $arguments the arguments of the extension, being passed over to vsprintf * @return string|NULL The value from LOCAL_LANG or NULL if no translation was found. * @api * @todo : If vsprintf gets a malformed string, it returns FALSE! Should we throw an exception there? */ public static function translate($key, $extensionName, $arguments = null) { $value = null; if (GeneralUtility::isFirstPartOfStr($key, 'LLL:')) { $value = self::translateFileReference($key); } else { self::initializeLocalization($extensionName); // The "from" charset of csConv() is only set for strings from TypoScript via _LOCAL_LANG if (!empty(self::$LOCAL_LANG[$extensionName][self::$languageKey][$key][0]['target']) || isset(self::$LOCAL_LANG_UNSET[$extensionName][self::$languageKey][$key]) ) { // Local language translation for key exists $value = self::$LOCAL_LANG[$extensionName][self::$languageKey][$key][0]['target']; } elseif (!empty(self::$alternativeLanguageKeys)) { $languages = array_reverse(self::$alternativeLanguageKeys); foreach ($languages as $language) { if (!empty(self::$LOCAL_LANG[$extensionName][$language][$key][0]['target']) || isset(self::$LOCAL_LANG_UNSET[$extensionName][$language][$key]) ) { // Alternative language translation for key exists $value = self::$LOCAL_LANG[$extensionName][$language][$key][0]['target']; break; } } } if ($value === null && (!empty(self::$LOCAL_LANG[$extensionName]['default'][$key][0]['target']) || isset(self::$LOCAL_LANG_UNSET[$extensionName]['default'][$key])) ) { // Default language translation for key exists // No charset conversion because default is English and thereby ASCII $value = self::$LOCAL_LANG[$extensionName]['default'][$key][0]['target']; } } if (is_array($arguments) && $value !== null) { return vsprintf($value, $arguments); } else { return $value; } } /** * Returns the localized label of the LOCAL_LANG key, $key. * * @param string $key The language key including the path to a custom locallang file ("LLL:path:key"). * @return string The value from LOCAL_LANG or NULL if no translation was found. * @see language::sL() * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::sL() */ protected static function translateFileReference($key) { if (TYPO3_MODE === 'FE') { $value = self::getTypoScriptFrontendController()->sL($key); return $value !== false ? $value : null; } elseif (is_object($GLOBALS['LANG'])) { $value = self::getLanguageService()->sL($key); return $value !== '' ? $value : null; } else { return $key; } } /** * Loads local-language values by looking for a "locallang.xlf" (or "locallang.xml") file in the plugin resources directory and if found includes it. * Also locallang values set in the TypoScript property "_LOCAL_LANG" are merged onto the values found in the "locallang.xlf" file. * * @param string $extensionName */ protected static function initializeLocalization($extensionName) { if (isset(self::$LOCAL_LANG[$extensionName])) { return; } $locallangPathAndFilename = 'EXT:' . GeneralUtility::camelCaseToLowerCaseUnderscored($extensionName) . '/' . self::$locallangPath . 'locallang.xlf'; self::setLanguageKeys(); /** @var $languageFactory LocalizationFactory */ $languageFactory = GeneralUtility::makeInstance(LocalizationFactory::class); self::$LOCAL_LANG[$extensionName] = $languageFactory->getParsedData($locallangPathAndFilename, self::$languageKey, 'utf-8'); foreach (self::$alternativeLanguageKeys as $language) { $tempLL = $languageFactory->getParsedData($locallangPathAndFilename, $language, 'utf-8'); if (self::$languageKey !== 'default' && isset($tempLL[$language])) { self::$LOCAL_LANG[$extensionName][$language] = $tempLL[$language]; } } self::loadTypoScriptLabels($extensionName); } /** * Sets the currently active language/language_alt keys. * Default values are "default" for language key and "" for language_alt key. */ protected static function setLanguageKeys() { self::$languageKey = 'default'; self::$alternativeLanguageKeys = []; if (TYPO3_MODE === 'FE') { if (isset(self::getTypoScriptFrontendController()->config['config']['language'])) { self::$languageKey = self::getTypoScriptFrontendController()->config['config']['language']; if (isset(self::getTypoScriptFrontendController()->config['config']['language_alt'])) { self::$alternativeLanguageKeys[] = self::getTypoScriptFrontendController()->config['config']['language_alt']; } else { /** @var $locales \TYPO3\CMS\Core\Localization\Locales */ $locales = GeneralUtility::makeInstance(Locales::class); if (in_array(self::$languageKey, $locales->getLocales())) { foreach ($locales->getLocaleDependencies(self::$languageKey) as $language) { self::$alternativeLanguageKeys[] = $language; } } } } } elseif (!empty($GLOBALS['BE_USER']->uc['lang'])) { self::$languageKey = $GLOBALS['BE_USER']->uc['lang']; } elseif (!empty(self::getLanguageService()->lang)) { self::$languageKey = self::getLanguageService()->lang; } } /** * Overwrites labels that are set via TypoScript. * TS locallang labels have to be configured like: * plugin.tx_myextension._LOCAL_LANG.languageKey.key = value * * @param string $extensionName */ protected static function loadTypoScriptLabels($extensionName) { $configurationManager = static::getConfigurationManager(); $frameworkConfiguration = $configurationManager->getConfiguration(ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK, $extensionName); if (!is_array($frameworkConfiguration['_LOCAL_LANG'])) { return; } self::$LOCAL_LANG_UNSET[$extensionName] = []; foreach ($frameworkConfiguration['_LOCAL_LANG'] as $languageKey => $labels) { if (!(is_array($labels) && isset(self::$LOCAL_LANG[$extensionName][$languageKey]))) { continue; } foreach ($labels as $labelKey => $labelValue) { if (is_string($labelValue)) { self::$LOCAL_LANG[$extensionName][$languageKey][$labelKey][0]['target'] = $labelValue; if ($labelValue === '') { self::$LOCAL_LANG_UNSET[$extensionName][$languageKey][$labelKey] = ''; } } elseif (is_array($labelValue)) { $labelValue = self::flattenTypoScriptLabelArray($labelValue, $labelKey); foreach ($labelValue as $key => $value) { self::$LOCAL_LANG[$extensionName][$languageKey][$key][0]['target'] = $value; if ($value === '') { self::$LOCAL_LANG_UNSET[$extensionName][$languageKey][$key] = ''; } } } } } } /** * Flatten TypoScript label array; converting a hierarchical array into a flat * array with the keys separated by dots. * * Example Input: array('k1' => array('subkey1' => 'val1')) * Example Output: array('k1.subkey1' => 'val1') * * @param array $labelValues Hierarchical array of labels * @param string $parentKey the name of the parent key in the recursion; is only needed for recursion. * @return array flattened array of labels. */ protected static function flattenTypoScriptLabelArray(array $labelValues, $parentKey = '') { $result = []; foreach ($labelValues as $key => $labelValue) { if (!empty($parentKey)) { $key = $parentKey . '.' . $key; } if (is_array($labelValue)) { $labelValue = self::flattenTypoScriptLabelArray($labelValue, $key); $result = array_merge($result, $labelValue); } else { $result[$key] = $labelValue; } } return $result; } /** * Returns instance of the configuration manager * * @return \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface */ protected static function getConfigurationManager() { if (!is_null(static::$configurationManager)) { return static::$configurationManager; } $objectManager = GeneralUtility::makeInstance(ObjectManager::class); $configurationManager = $objectManager->get(ConfigurationManagerInterface::class); static::$configurationManager = $configurationManager; return $configurationManager; } /** * @return \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController */ protected static function getTypoScriptFrontendController() { return $GLOBALS['TSFE']; } /** * @return \TYPO3\CMS\Lang\LanguageService */ protected static function getLanguageService() { return $GLOBALS['LANG']; } }
gpl-2.0
adri360/DarkNoteIII-Kernel
mm/memory.c
116921
/* * linux/mm/memory.c * * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds */ /* * demand-loading started 01.12.91 - seems it is high on the list of * things wanted, and it should be easy to implement. - Linus */ /* * Ok, demand-loading was easy, shared pages a little bit tricker. Shared * pages started 02.12.91, seems to work. - Linus. * * Tested sharing by executing about 30 /bin/sh: under the old kernel it * would have taken more than the 6M I have free, but it worked well as * far as I could see. * * Also corrected some "invalidate()"s - I wasn't doing enough of them. */ /* * Real VM (paging to/from disk) started 18.12.91. Much more work and * thought has to go into this. Oh, well.. * 19.12.91 - works, somewhat. Sometimes I get faults, don't know why. * Found it. Everything seems to work now. * 20.12.91 - Ok, making the swap-device changeable like the root. */ /* * 05.04.94 - Multi-page memory management added for v1.1. * Idea by Alex Bligh ([email protected]) * * 16.07.99 - Support of BIGMEM added by Gerhard Wichert, Siemens AG * ([email protected]) * * Aug/Sep 2004 Changed to four level page tables (Andi Kleen) */ #include <linux/kernel_stat.h> #include <linux/mm.h> #include <linux/hugetlb.h> #include <linux/mman.h> #include <linux/swap.h> #include <linux/highmem.h> #include <linux/pagemap.h> #include <linux/ksm.h> #include <linux/rmap.h> #include <linux/export.h> #include <linux/delayacct.h> #include <linux/delay.h> #include <linux/init.h> #include <linux/writeback.h> #include <linux/memcontrol.h> #include <linux/mmu_notifier.h> #include <linux/kallsyms.h> #include <linux/swapops.h> #include <linux/elf.h> #include <linux/gfp.h> #include <asm/io.h> #include <asm/pgalloc.h> #include <asm/uaccess.h> #include <asm/tlb.h> #include <asm/tlbflush.h> #include <asm/pgtable.h> #include "internal.h" #ifndef CONFIG_NEED_MULTIPLE_NODES /* use the per-pgdat data instead for discontigmem - mbligh */ unsigned long max_mapnr; struct page *mem_map; EXPORT_SYMBOL(max_mapnr); EXPORT_SYMBOL(mem_map); #endif unsigned long num_physpages; /* * A number of key systems in x86 including ioremap() rely on the assumption * that high_memory defines the upper bound on direct map memory, then end * of ZONE_NORMAL. Under CONFIG_DISCONTIG this means that max_low_pfn and * highstart_pfn must be the same; there must be no gap between ZONE_NORMAL * and ZONE_HIGHMEM. */ void * high_memory; EXPORT_SYMBOL(num_physpages); EXPORT_SYMBOL(high_memory); /* * Randomize the address space (stacks, mmaps, brk, etc.). * * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization, * as ancient (libc5 based) binaries can segfault. ) */ int randomize_va_space __read_mostly = #ifdef CONFIG_COMPAT_BRK 1; #else 2; #endif static int __init disable_randmaps(char *s) { randomize_va_space = 0; return 1; } __setup("norandmaps", disable_randmaps); unsigned long zero_pfn __read_mostly; unsigned long highest_memmap_pfn __read_mostly; /* * CONFIG_MMU architectures set up ZERO_PAGE in their paging_init() */ static int __init init_zero_pfn(void) { zero_pfn = page_to_pfn(ZERO_PAGE(0)); return 0; } core_initcall(init_zero_pfn); #if defined(SPLIT_RSS_COUNTING) void sync_mm_rss(struct mm_struct *mm) { int i; for (i = 0; i < NR_MM_COUNTERS; i++) { if (current->rss_stat.count[i]) { add_mm_counter(mm, i, current->rss_stat.count[i]); current->rss_stat.count[i] = 0; } } current->rss_stat.events = 0; } static void add_mm_counter_fast(struct mm_struct *mm, int member, int val) { struct task_struct *task = current; if (likely(task->mm == mm)) task->rss_stat.count[member] += val; else add_mm_counter(mm, member, val); } #define inc_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, 1) #define dec_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, -1) /* sync counter once per 64 page faults */ #define TASK_RSS_EVENTS_THRESH (64) #if defined(CONFIG_VMWARE_MVP) EXPORT_SYMBOL_GPL(get_mm_counter); #endif static void check_sync_rss_stat(struct task_struct *task) { if (unlikely(task != current)) return; if (unlikely(task->rss_stat.events++ > TASK_RSS_EVENTS_THRESH)) sync_mm_rss(task->mm); } #else /* SPLIT_RSS_COUNTING */ #define inc_mm_counter_fast(mm, member) inc_mm_counter(mm, member) #define dec_mm_counter_fast(mm, member) dec_mm_counter(mm, member) static void check_sync_rss_stat(struct task_struct *task) { } #endif /* SPLIT_RSS_COUNTING */ #ifdef HAVE_GENERIC_MMU_GATHER static int tlb_next_batch(struct mmu_gather *tlb) { struct mmu_gather_batch *batch; batch = tlb->active; if (batch->next) { tlb->active = batch->next; return 1; } batch = (void *)__get_free_pages(GFP_NOWAIT | __GFP_NOWARN, 0); if (!batch) return 0; batch->next = NULL; batch->nr = 0; batch->max = MAX_GATHER_BATCH; tlb->active->next = batch; tlb->active = batch; return 1; } /* tlb_gather_mmu * Called to initialize an (on-stack) mmu_gather structure for page-table * tear-down from @mm. The @fullmm argument is used when @mm is without * users and we're going to destroy the full address space (exit/execve). */ void tlb_gather_mmu(struct mmu_gather *tlb, struct mm_struct *mm, bool fullmm) { tlb->mm = mm; tlb->fullmm = fullmm; tlb->need_flush = 0; tlb->fast_mode = (num_possible_cpus() == 1); tlb->local.next = NULL; tlb->local.nr = 0; tlb->local.max = ARRAY_SIZE(tlb->__pages); tlb->active = &tlb->local; #ifdef CONFIG_HAVE_RCU_TABLE_FREE tlb->batch = NULL; #endif } void tlb_flush_mmu(struct mmu_gather *tlb) { struct mmu_gather_batch *batch; if (!tlb->need_flush) return; tlb->need_flush = 0; tlb_flush(tlb); #ifdef CONFIG_HAVE_RCU_TABLE_FREE tlb_table_flush(tlb); #endif if (tlb_fast_mode(tlb)) return; for (batch = &tlb->local; batch; batch = batch->next) { free_pages_and_swap_cache(batch->pages, batch->nr); batch->nr = 0; } tlb->active = &tlb->local; } /* tlb_finish_mmu * Called at the end of the shootdown operation to free up any resources * that were required. */ void tlb_finish_mmu(struct mmu_gather *tlb, unsigned long start, unsigned long end) { struct mmu_gather_batch *batch, *next; tlb_flush_mmu(tlb); /* keep the page table cache within bounds */ check_pgt_cache(); for (batch = tlb->local.next; batch; batch = next) { next = batch->next; free_pages((unsigned long)batch, 0); } tlb->local.next = NULL; } /* __tlb_remove_page * Must perform the equivalent to __free_pte(pte_get_and_clear(ptep)), while * handling the additional races in SMP caused by other CPUs caching valid * mappings in their TLBs. Returns the number of free page slots left. * When out of page slots we must call tlb_flush_mmu(). */ int __tlb_remove_page(struct mmu_gather *tlb, struct page *page) { struct mmu_gather_batch *batch; VM_BUG_ON(!tlb->need_flush); if (tlb_fast_mode(tlb)) { free_page_and_swap_cache(page); return 1; /* avoid calling tlb_flush_mmu() */ } batch = tlb->active; batch->pages[batch->nr++] = page; if (batch->nr == batch->max) { if (!tlb_next_batch(tlb)) return 0; batch = tlb->active; } VM_BUG_ON(batch->nr > batch->max); return batch->max - batch->nr; } #endif /* HAVE_GENERIC_MMU_GATHER */ #ifdef CONFIG_HAVE_RCU_TABLE_FREE /* * See the comment near struct mmu_table_batch. */ static void tlb_remove_table_smp_sync(void *arg) { /* Simply deliver the interrupt */ } static void tlb_remove_table_one(void *table) { /* * This isn't an RCU grace period and hence the page-tables cannot be * assumed to be actually RCU-freed. * * It is however sufficient for software page-table walkers that rely on * IRQ disabling. See the comment near struct mmu_table_batch. */ smp_call_function(tlb_remove_table_smp_sync, NULL, 1); __tlb_remove_table(table); } static void tlb_remove_table_rcu(struct rcu_head *head) { struct mmu_table_batch *batch; int i; batch = container_of(head, struct mmu_table_batch, rcu); for (i = 0; i < batch->nr; i++) __tlb_remove_table(batch->tables[i]); free_page((unsigned long)batch); } void tlb_table_flush(struct mmu_gather *tlb) { struct mmu_table_batch **batch = &tlb->batch; if (*batch) { call_rcu_sched(&(*batch)->rcu, tlb_remove_table_rcu); *batch = NULL; } } void tlb_remove_table(struct mmu_gather *tlb, void *table) { struct mmu_table_batch **batch = &tlb->batch; tlb->need_flush = 1; /* * When there's less then two users of this mm there cannot be a * concurrent page-table walk. */ if (atomic_read(&tlb->mm->mm_users) < 2) { __tlb_remove_table(table); return; } if (*batch == NULL) { *batch = (struct mmu_table_batch *)__get_free_page(GFP_NOWAIT | __GFP_NOWARN); if (*batch == NULL) { tlb_remove_table_one(table); return; } (*batch)->nr = 0; } (*batch)->tables[(*batch)->nr++] = table; if ((*batch)->nr == MAX_TABLE_BATCH) tlb_table_flush(tlb); } #endif /* CONFIG_HAVE_RCU_TABLE_FREE */ /* * If a p?d_bad entry is found while walking page tables, report * the error, before resetting entry to p?d_none. Usually (but * very seldom) called out from the p?d_none_or_clear_bad macros. */ void pgd_clear_bad(pgd_t *pgd) { pgd_ERROR(*pgd); pgd_clear(pgd); } void pud_clear_bad(pud_t *pud) { pud_ERROR(*pud); pud_clear(pud); } void pmd_clear_bad(pmd_t *pmd) { pmd_ERROR(*pmd); pmd_clear(pmd); } /* * Note: this doesn't free the actual pages themselves. That * has been handled earlier when unmapping all the memory regions. */ static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd, unsigned long addr) { pgtable_t token = pmd_pgtable(*pmd); pmd_clear(pmd); pte_free_tlb(tlb, token, addr); tlb->mm->nr_ptes--; } static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud, unsigned long addr, unsigned long end, unsigned long floor, unsigned long ceiling) { pmd_t *pmd; unsigned long next; unsigned long start; start = addr; pmd = pmd_offset(pud, addr); do { next = pmd_addr_end(addr, end); if (pmd_none_or_clear_bad(pmd)) continue; free_pte_range(tlb, pmd, addr); } while (pmd++, addr = next, addr != end); start &= PUD_MASK; if (start < floor) return; if (ceiling) { ceiling &= PUD_MASK; if (!ceiling) return; } if (end - 1 > ceiling - 1) return; pmd = pmd_offset(pud, start); pud_clear(pud); pmd_free_tlb(tlb, pmd, start); } static inline void free_pud_range(struct mmu_gather *tlb, pgd_t *pgd, unsigned long addr, unsigned long end, unsigned long floor, unsigned long ceiling) { pud_t *pud; unsigned long next; unsigned long start; start = addr; pud = pud_offset(pgd, addr); do { next = pud_addr_end(addr, end); if (pud_none_or_clear_bad(pud)) continue; free_pmd_range(tlb, pud, addr, next, floor, ceiling); } while (pud++, addr = next, addr != end); start &= PGDIR_MASK; if (start < floor) return; if (ceiling) { ceiling &= PGDIR_MASK; if (!ceiling) return; } if (end - 1 > ceiling - 1) return; pud = pud_offset(pgd, start); pgd_clear(pgd); pud_free_tlb(tlb, pud, start); } /* * This function frees user-level page tables of a process. * * Must be called with pagetable lock held. */ void free_pgd_range(struct mmu_gather *tlb, unsigned long addr, unsigned long end, unsigned long floor, unsigned long ceiling) { pgd_t *pgd; unsigned long next; /* * The next few lines have given us lots of grief... * * Why are we testing PMD* at this top level? Because often * there will be no work to do at all, and we'd prefer not to * go all the way down to the bottom just to discover that. * * Why all these "- 1"s? Because 0 represents both the bottom * of the address space and the top of it (using -1 for the * top wouldn't help much: the masks would do the wrong thing). * The rule is that addr 0 and floor 0 refer to the bottom of * the address space, but end 0 and ceiling 0 refer to the top * Comparisons need to use "end - 1" and "ceiling - 1" (though * that end 0 case should be mythical). * * Wherever addr is brought up or ceiling brought down, we must * be careful to reject "the opposite 0" before it confuses the * subsequent tests. But what about where end is brought down * by PMD_SIZE below? no, end can't go down to 0 there. * * Whereas we round start (addr) and ceiling down, by different * masks at different levels, in order to test whether a table * now has no other vmas using it, so can be freed, we don't * bother to round floor or end up - the tests don't need that. */ addr &= PMD_MASK; if (addr < floor) { addr += PMD_SIZE; if (!addr) return; } if (ceiling) { ceiling &= PMD_MASK; if (!ceiling) return; } if (end - 1 > ceiling - 1) end -= PMD_SIZE; if (addr > end - 1) return; pgd = pgd_offset(tlb->mm, addr); do { next = pgd_addr_end(addr, end); if (pgd_none_or_clear_bad(pgd)) continue; free_pud_range(tlb, pgd, addr, next, floor, ceiling); } while (pgd++, addr = next, addr != end); } void free_pgtables(struct mmu_gather *tlb, struct vm_area_struct *vma, unsigned long floor, unsigned long ceiling) { while (vma) { struct vm_area_struct *next = vma->vm_next; unsigned long addr = vma->vm_start; /* * Hide vma from rmap and truncate_pagecache before freeing * pgtables */ unlink_anon_vmas(vma); unlink_file_vma(vma); if (is_vm_hugetlb_page(vma)) { hugetlb_free_pgd_range(tlb, addr, vma->vm_end, floor, next? next->vm_start: ceiling); } else { /* * Optimization: gather nearby vmas into one call down */ while (next && next->vm_start <= vma->vm_end + PMD_SIZE && !is_vm_hugetlb_page(next)) { vma = next; next = vma->vm_next; unlink_anon_vmas(vma); unlink_file_vma(vma); } free_pgd_range(tlb, addr, vma->vm_end, floor, next? next->vm_start: ceiling); } vma = next; } } int __pte_alloc(struct mm_struct *mm, struct vm_area_struct *vma, pmd_t *pmd, unsigned long address) { pgtable_t new = pte_alloc_one(mm, address); int wait_split_huge_page; if (!new) return -ENOMEM; /* * Ensure all pte setup (eg. pte page lock and page clearing) are * visible before the pte is made visible to other CPUs by being * put into page tables. * * The other side of the story is the pointer chasing in the page * table walking code (when walking the page table without locking; * ie. most of the time). Fortunately, these data accesses consist * of a chain of data-dependent loads, meaning most CPUs (alpha * being the notable exception) will already guarantee loads are * seen in-order. See the alpha page table accessors for the * smp_read_barrier_depends() barriers in page table walking code. */ smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */ spin_lock(&mm->page_table_lock); wait_split_huge_page = 0; if (likely(pmd_none(*pmd))) { /* Has another populated it ? */ mm->nr_ptes++; pmd_populate(mm, pmd, new); new = NULL; } else if (unlikely(pmd_trans_splitting(*pmd))) wait_split_huge_page = 1; spin_unlock(&mm->page_table_lock); if (new) pte_free(mm, new); if (wait_split_huge_page) wait_split_huge_page(vma->anon_vma, pmd); return 0; } int __pte_alloc_kernel(pmd_t *pmd, unsigned long address) { pte_t *new = pte_alloc_one_kernel(&init_mm, address); if (!new) return -ENOMEM; smp_wmb(); /* See comment in __pte_alloc */ spin_lock(&init_mm.page_table_lock); if (likely(pmd_none(*pmd))) { /* Has another populated it ? */ pmd_populate_kernel(&init_mm, pmd, new); new = NULL; } else VM_BUG_ON(pmd_trans_splitting(*pmd)); spin_unlock(&init_mm.page_table_lock); if (new) pte_free_kernel(&init_mm, new); return 0; } static inline void init_rss_vec(int *rss) { memset(rss, 0, sizeof(int) * NR_MM_COUNTERS); } static inline void add_mm_rss_vec(struct mm_struct *mm, int *rss) { int i; if (current->mm == mm) sync_mm_rss(mm); for (i = 0; i < NR_MM_COUNTERS; i++) if (rss[i]) add_mm_counter(mm, i, rss[i]); } /* * This function is called to print an error when a bad pte * is found. For example, we might have a PFN-mapped pte in * a region that doesn't allow it. * * The calling function must still handle the error. */ static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr, pte_t pte, struct page *page) { pgd_t *pgd = pgd_offset(vma->vm_mm, addr); pud_t *pud = pud_offset(pgd, addr); pmd_t *pmd = pmd_offset(pud, addr); struct address_space *mapping; pgoff_t index; static unsigned long resume; static unsigned long nr_shown; static unsigned long nr_unshown; /* * Allow a burst of 60 reports, then keep quiet for that minute; * or allow a steady drip of one report per second. */ if (nr_shown == 60) { if (time_before(jiffies, resume)) { nr_unshown++; return; } if (nr_unshown) { printk(KERN_ALERT "BUG: Bad page map: %lu messages suppressed\n", nr_unshown); nr_unshown = 0; } nr_shown = 0; } if (nr_shown++ == 0) resume = jiffies + 60 * HZ; mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL; index = linear_page_index(vma, addr); printk(KERN_ALERT "BUG: Bad page map in process %s pte:%08llx pmd:%08llx\n", current->comm, (long long)pte_val(pte), (long long)pmd_val(*pmd)); if (page) dump_page(page); printk(KERN_ALERT "addr:%p vm_flags:%08lx anon_vma:%p mapping:%p index:%lx\n", (void *)addr, vma->vm_flags, vma->anon_vma, mapping, index); /* * Choose text because data symbols depend on CONFIG_KALLSYMS_ALL=y */ if (vma->vm_ops) print_symbol(KERN_ALERT "vma->vm_ops->fault: %s\n", (unsigned long)vma->vm_ops->fault); if (vma->vm_file && vma->vm_file->f_op) print_symbol(KERN_ALERT "vma->vm_file->f_op->mmap: %s\n", (unsigned long)vma->vm_file->f_op->mmap); dump_stack(); add_taint(TAINT_BAD_PAGE); } static inline int is_cow_mapping(vm_flags_t flags) { return (flags & (VM_SHARED | VM_MAYWRITE)) == VM_MAYWRITE; } #ifndef is_zero_pfn static inline int is_zero_pfn(unsigned long pfn) { return pfn == zero_pfn; } #endif #ifndef my_zero_pfn static inline unsigned long my_zero_pfn(unsigned long addr) { return zero_pfn; } #endif /* * vm_normal_page -- This function gets the "struct page" associated with a pte. * * "Special" mappings do not wish to be associated with a "struct page" (either * it doesn't exist, or it exists but they don't want to touch it). In this * case, NULL is returned here. "Normal" mappings do have a struct page. * * There are 2 broad cases. Firstly, an architecture may define a pte_special() * pte bit, in which case this function is trivial. Secondly, an architecture * may not have a spare pte bit, which requires a more complicated scheme, * described below. * * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a * special mapping (even if there are underlying and valid "struct pages"). * COWed pages of a VM_PFNMAP are always normal. * * The way we recognize COWed pages within VM_PFNMAP mappings is through the * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit * set, and the vm_pgoff will point to the first PFN mapped: thus every special * mapping will always honor the rule * * pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT) * * And for normal mappings this is false. * * This restricts such mappings to be a linear translation from virtual address * to pfn. To get around this restriction, we allow arbitrary mappings so long * as the vma is not a COW mapping; in that case, we know that all ptes are * special (because none can have been COWed). * * * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP. * * VM_MIXEDMAP mappings can likewise contain memory with or without "struct * page" backing, however the difference is that _all_ pages with a struct * page (that is, those where pfn_valid is true) are refcounted and considered * normal pages by the VM. The disadvantage is that pages are refcounted * (which can be slower and simply not an option for some PFNMAP users). The * advantage is that we don't have to follow the strict linearity rule of * PFNMAP mappings in order to support COWable mappings. * */ #ifdef __HAVE_ARCH_PTE_SPECIAL # define HAVE_PTE_SPECIAL 1 #else # define HAVE_PTE_SPECIAL 0 #endif struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr, pte_t pte) { unsigned long pfn = pte_pfn(pte); if (HAVE_PTE_SPECIAL) { if (likely(!pte_special(pte))) goto check_pfn; if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP)) return NULL; if (!is_zero_pfn(pfn)) print_bad_pte(vma, addr, pte, NULL); return NULL; } /* !HAVE_PTE_SPECIAL case follows: */ if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) { if (vma->vm_flags & VM_MIXEDMAP) { if (!pfn_valid(pfn)) return NULL; goto out; } else { unsigned long off; off = (addr - vma->vm_start) >> PAGE_SHIFT; if (pfn == vma->vm_pgoff + off) return NULL; if (!is_cow_mapping(vma->vm_flags)) return NULL; } } if (is_zero_pfn(pfn)) return NULL; check_pfn: if (unlikely(pfn > highest_memmap_pfn)) { print_bad_pte(vma, addr, pte, NULL); return NULL; } /* * NOTE! We still have PageReserved() pages in the page tables. * eg. VDSO mappings can cause them to exist. */ out: return pfn_to_page(pfn); } #ifdef CONFIG_TIMA_RKP_L2_GROUP /* redefining the original function for L2 group * Original function is is asm-generic. */ static inline void tima_l2group_ptep_set_wrprotect(struct mm_struct *mm, unsigned long address, pte_t *ptep, tima_l2group_entry_t *tima_l2group_buffer, unsigned long *tima_l2group_buffer_index) { pte_t old_pte = *ptep; timal2group_set_pte_at(ptep, pte_wrprotect(old_pte), (((unsigned long) tima_l2group_buffer) + (sizeof(tima_l2group_entry_t)*(*tima_l2group_buffer_index))), address, tima_l2group_buffer_index); //set_pte_at(mm, address, ptep, pte_wrprotect(old_pte)); /* Removed as grouping works */ } #endif /* CONFIG_TIMA_RKP_L2_GROUP */ /* * copy one vm_area from one task to the other. Assumes the page tables * already present in the new task to be cleared in the whole range * covered by this vma. */ #ifdef CONFIG_TIMA_RKP_L2_GROUP static inline unsigned long tima_l2group_copy_one_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm, pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *vma, unsigned long addr, int *rss, tima_l2group_entry_t *tima_l2group_buffer, unsigned long *tima_l2group_buffer_index, unsigned long tima_l2group_flag) #else static inline unsigned long copy_one_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm, pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *vma, unsigned long addr, int *rss) #endif /* CONFIG_TIMA_RKP_L2_GROUP */ { unsigned long vm_flags = vma->vm_flags; pte_t pte = *src_pte; struct page *page; /* pte contains position in swap or file, so copy. */ if (unlikely(!pte_present(pte))) { if (!pte_file(pte)) { swp_entry_t entry = pte_to_swp_entry(pte); if (swap_duplicate(entry) < 0) return entry.val; /* make sure dst_mm is on swapoff's mmlist. */ if (unlikely(list_empty(&dst_mm->mmlist))) { spin_lock(&mmlist_lock); if (list_empty(&dst_mm->mmlist)) list_add(&dst_mm->mmlist, &src_mm->mmlist); spin_unlock(&mmlist_lock); } if (likely(!non_swap_entry(entry))) rss[MM_SWAPENTS]++; else if (is_migration_entry(entry)) { page = migration_entry_to_page(entry); if (PageAnon(page)) rss[MM_ANONPAGES]++; else rss[MM_FILEPAGES]++; if (is_write_migration_entry(entry) && is_cow_mapping(vm_flags)) { /* * COW mappings require pages in both * parent and child to be set to read. */ make_migration_entry_read(&entry); pte = swp_entry_to_pte(entry); set_pte_at(src_mm, addr, src_pte, pte); } } } goto out_set_pte; } /* * If it's a COW mapping, write protect it both * in the parent and the child */ if (is_cow_mapping(vm_flags)) { #ifdef CONFIG_TIMA_RKP_L2_GROUP if (tima_l2group_flag) { tima_l2group_ptep_set_wrprotect(src_mm, addr, src_pte, tima_l2group_buffer, tima_l2group_buffer_index); //(*tima_l2group_buffer_index)++; } else ptep_set_wrprotect(src_mm, addr, src_pte); #else ptep_set_wrprotect(src_mm, addr, src_pte); #endif /* CONFIG_TIMA_RKP_L2_GROUP */ pte = pte_wrprotect(pte); } /* * If it's a shared mapping, mark it clean in * the child */ if (vm_flags & VM_SHARED) pte = pte_mkclean(pte); pte = pte_mkold(pte); page = vm_normal_page(vma, addr, pte); if (page) { get_page(page); page_dup_rmap(page); if (PageAnon(page)) rss[MM_ANONPAGES]++; else rss[MM_FILEPAGES]++; } out_set_pte: set_pte_at(dst_mm, addr, dst_pte, pte); return 0; } int copy_pte_range(struct mm_struct *dst_mm, struct mm_struct *src_mm, pmd_t *dst_pmd, pmd_t *src_pmd, struct vm_area_struct *vma, unsigned long addr, unsigned long end) { pte_t *orig_src_pte, *orig_dst_pte; pte_t *src_pte, *dst_pte; spinlock_t *src_ptl, *dst_ptl; int progress = 0; int rss[NR_MM_COUNTERS]; swp_entry_t entry = (swp_entry_t){0}; #ifdef CONFIG_TIMA_RKP_L2_GROUP unsigned long tima_l2group_flag = 0; tima_l2group_entry_t *tima_l2group_buffer = NULL; unsigned long tima_l2group_numb_entries; unsigned long tima_l2group_buffer_index = 0; #endif again: init_rss_vec(rss); dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl); if (!dst_pte) return -ENOMEM; src_pte = pte_offset_map(src_pmd, addr); src_ptl = pte_lockptr(src_mm, src_pmd); spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING); orig_src_pte = src_pte; orig_dst_pte = dst_pte; arch_enter_lazy_mmu_mode(); #ifdef CONFIG_TIMA_RKP_L2_GROUP /* Initialize all L2_GROUP variables */ tima_l2group_flag= 0; tima_l2group_buffer = NULL; tima_l2group_numb_entries = ((end-addr) >> PAGE_SHIFT); tima_l2group_buffer_index = 0; /* * Lazy mmu mode for tima: * 1-Define a memory area to hold the PTEs to be changed * 2-Commit the changes right away to TIMA * 0x200 = 512 bytes which is 2 L2 pages. If grouped * entries are <= 2, there is not much point in * grouping it, in which case follow the normal path. */ if (tima_l2group_numb_entries > 2 && tima_l2group_numb_entries <= 0x200 && tima_is_pg_protected((unsigned long)src_pte) == 1) { /* * Kmalloc does not work in this function (causes crashes) so * we use get_free_pages instead which mostly wastes some space */ /*tima_l2group_buffer = kmalloc(sizeof(*tima_l2group_buffer) * tima_l2group_numb_entries, GFP_KERNEL | GFP_ATOMIC);*/ tima_l2group_buffer = (tima_l2group_entry_t *) __get_free_pages(GFP_ATOMIC, 1); if (tima_l2group_buffer == NULL) { printk(KERN_ERR"TIMA -> L2GRP FAILED %lx %lx %lx\n", addr, end, tima_l2group_numb_entries); } else { tima_l2group_flag = 1; /* make sure index is reset here, or all * hell breaks loose! */ tima_l2group_buffer_index = 0; } } #endif /* CONFIG_TIMA_RKP_L2_GROUP */ do { /* * We are holding two locks at this point - either of them * could generate latencies in another task on another CPU. */ if (progress >= 32) { progress = 0; if (need_resched() || spin_needbreak(src_ptl) || spin_needbreak(dst_ptl)) break; } if (pte_none(*src_pte)) { progress++; continue; } #ifdef CONFIG_TIMA_RKP_L2_GROUP /* function tima_l2group_copy_one_pte() increments * tima_l2group_buffer_index. Do not increment * it outside else we end up with buffer sizes * which are invalid. */ entry.val = tima_l2group_copy_one_pte(dst_mm, src_mm, dst_pte, src_pte, vma, addr, rss, tima_l2group_buffer, &tima_l2group_buffer_index, tima_l2group_flag); #else entry.val = copy_one_pte(dst_mm, src_mm, dst_pte, src_pte, vma, addr, rss); #endif /* CONFIG_TIMA_RKP_L2_GROUP */ if (entry.val) break; progress += 8; } while (dst_pte++, src_pte++, addr += PAGE_SIZE, addr != end); #ifdef CONFIG_TIMA_RKP_L2_GROUP if (tima_l2group_flag) { unsigned long buffer_va = (unsigned long) tima_l2group_buffer; /*First: Flush the cache of the buffer to be read by the TZ side */ flush_dcache_page(virt_to_page(buffer_va)); flush_dcache_page(virt_to_page(buffer_va + PAGE_SIZE)); /*Second: Pass the buffer pointer and length to TIMA to commit the changes */ if (tima_l2group_buffer_index) { timal2group_set_pte_commit(tima_l2group_buffer, tima_l2group_buffer_index, (void*)src_pte); } free_pages((unsigned long) tima_l2group_buffer, 1); } #endif /* CONFIG_TIMA_RKP_L2_GROUP */ arch_leave_lazy_mmu_mode(); spin_unlock(src_ptl); pte_unmap(orig_src_pte); add_mm_rss_vec(dst_mm, rss); pte_unmap_unlock(orig_dst_pte, dst_ptl); cond_resched(); if (entry.val) { if (add_swap_count_continuation(entry, GFP_KERNEL) < 0) return -ENOMEM; progress = 0; } if (addr != end) goto again; return 0; } static inline int copy_pmd_range(struct mm_struct *dst_mm, struct mm_struct *src_mm, pud_t *dst_pud, pud_t *src_pud, struct vm_area_struct *vma, unsigned long addr, unsigned long end) { pmd_t *src_pmd, *dst_pmd; unsigned long next; dst_pmd = pmd_alloc(dst_mm, dst_pud, addr); if (!dst_pmd) return -ENOMEM; src_pmd = pmd_offset(src_pud, addr); do { next = pmd_addr_end(addr, end); if (pmd_trans_huge(*src_pmd)) { int err; VM_BUG_ON(next-addr != HPAGE_PMD_SIZE); err = copy_huge_pmd(dst_mm, src_mm, dst_pmd, src_pmd, addr, vma); if (err == -ENOMEM) return -ENOMEM; if (!err) continue; /* fall through */ } if (pmd_none_or_clear_bad(src_pmd)) continue; if (copy_pte_range(dst_mm, src_mm, dst_pmd, src_pmd, vma, addr, next)) return -ENOMEM; } while (dst_pmd++, src_pmd++, addr = next, addr != end); return 0; } static inline int copy_pud_range(struct mm_struct *dst_mm, struct mm_struct *src_mm, pgd_t *dst_pgd, pgd_t *src_pgd, struct vm_area_struct *vma, unsigned long addr, unsigned long end) { pud_t *src_pud, *dst_pud; unsigned long next; dst_pud = pud_alloc(dst_mm, dst_pgd, addr); if (!dst_pud) return -ENOMEM; src_pud = pud_offset(src_pgd, addr); do { next = pud_addr_end(addr, end); if (pud_none_or_clear_bad(src_pud)) continue; if (copy_pmd_range(dst_mm, src_mm, dst_pud, src_pud, vma, addr, next)) return -ENOMEM; } while (dst_pud++, src_pud++, addr = next, addr != end); return 0; } int copy_page_range(struct mm_struct *dst_mm, struct mm_struct *src_mm, struct vm_area_struct *vma) { pgd_t *src_pgd, *dst_pgd; unsigned long next; unsigned long addr = vma->vm_start; unsigned long end = vma->vm_end; int ret; /* * Don't copy ptes where a page fault will fill them correctly. * Fork becomes much lighter when there are big shared or private * readonly mappings. The tradeoff is that copy_page_range is more * efficient than faulting. */ if (!(vma->vm_flags & (VM_HUGETLB|VM_NONLINEAR|VM_PFNMAP|VM_INSERTPAGE))) { if (!vma->anon_vma) return 0; } if (is_vm_hugetlb_page(vma)) return copy_hugetlb_page_range(dst_mm, src_mm, vma); if (unlikely(is_pfn_mapping(vma))) { /* * We do not free on error cases below as remove_vma * gets called on error from higher level routine */ ret = track_pfn_vma_copy(vma); if (ret) return ret; } /* * We need to invalidate the secondary MMU mappings only when * there could be a permission downgrade on the ptes of the * parent mm. And a permission downgrade will only happen if * is_cow_mapping() returns true. */ if (is_cow_mapping(vma->vm_flags)) mmu_notifier_invalidate_range_start(src_mm, addr, end); ret = 0; dst_pgd = pgd_offset(dst_mm, addr); src_pgd = pgd_offset(src_mm, addr); do { next = pgd_addr_end(addr, end); if (pgd_none_or_clear_bad(src_pgd)) continue; if (unlikely(copy_pud_range(dst_mm, src_mm, dst_pgd, src_pgd, vma, addr, next))) { ret = -ENOMEM; break; } } while (dst_pgd++, src_pgd++, addr = next, addr != end); if (is_cow_mapping(vma->vm_flags)) mmu_notifier_invalidate_range_end(src_mm, vma->vm_start, end); return ret; } static unsigned long zap_pte_range(struct mmu_gather *tlb, struct vm_area_struct *vma, pmd_t *pmd, unsigned long addr, unsigned long end, struct zap_details *details) { struct mm_struct *mm = tlb->mm; int force_flush = 0; int rss[NR_MM_COUNTERS]; spinlock_t *ptl; pte_t *start_pte; pte_t *pte; again: init_rss_vec(rss); start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl); pte = start_pte; arch_enter_lazy_mmu_mode(); do { pte_t ptent = *pte; if (pte_none(ptent)) { continue; } if (pte_present(ptent)) { struct page *page; page = vm_normal_page(vma, addr, ptent); if (unlikely(details) && page) { /* * unmap_shared_mapping_pages() wants to * invalidate cache without truncating: * unmap shared but keep private pages. */ if (details->check_mapping && details->check_mapping != page->mapping) continue; /* * Each page->index must be checked when * invalidating or truncating nonlinear. */ if (details->nonlinear_vma && (page->index < details->first_index || page->index > details->last_index)) continue; } ptent = ptep_get_and_clear_full(mm, addr, pte, tlb->fullmm); tlb_remove_tlb_entry(tlb, pte, addr); if (unlikely(!page)) continue; if (unlikely(details) && details->nonlinear_vma && linear_page_index(details->nonlinear_vma, addr) != page->index) set_pte_at(mm, addr, pte, pgoff_to_pte(page->index)); if (PageAnon(page)) rss[MM_ANONPAGES]--; else { if (pte_dirty(ptent)) set_page_dirty(page); if (pte_young(ptent) && likely(!VM_SequentialReadHint(vma))) mark_page_accessed(page); rss[MM_FILEPAGES]--; } page_remove_rmap(page); if (unlikely(page_mapcount(page) < 0)) print_bad_pte(vma, addr, ptent, page); force_flush = !__tlb_remove_page(tlb, page); if (force_flush) break; continue; } /* * If details->check_mapping, we leave swap entries; * if details->nonlinear_vma, we leave file entries. */ if (unlikely(details)) continue; if (pte_file(ptent)) { if (unlikely(!(vma->vm_flags & VM_NONLINEAR))) print_bad_pte(vma, addr, ptent, NULL); } else { swp_entry_t entry = pte_to_swp_entry(ptent); if (!non_swap_entry(entry)) rss[MM_SWAPENTS]--; else if (is_migration_entry(entry)) { struct page *page; page = migration_entry_to_page(entry); if (PageAnon(page)) rss[MM_ANONPAGES]--; else rss[MM_FILEPAGES]--; } if (unlikely(!free_swap_and_cache(entry))) print_bad_pte(vma, addr, ptent, NULL); } pte_clear_not_present_full(mm, addr, pte, tlb->fullmm); } while (pte++, addr += PAGE_SIZE, addr != end); add_mm_rss_vec(mm, rss); arch_leave_lazy_mmu_mode(); pte_unmap_unlock(start_pte, ptl); /* * mmu_gather ran out of room to batch pages, we break out of * the PTE lock to avoid doing the potential expensive TLB invalidate * and page-free while holding it. */ if (force_flush) { force_flush = 0; tlb_flush_mmu(tlb); if (addr != end) goto again; } return addr; } static inline unsigned long zap_pmd_range(struct mmu_gather *tlb, struct vm_area_struct *vma, pud_t *pud, unsigned long addr, unsigned long end, struct zap_details *details) { pmd_t *pmd; unsigned long next; pmd = pmd_offset(pud, addr); do { next = pmd_addr_end(addr, end); if (pmd_trans_huge(*pmd)) { if (next - addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) goto next; /* fall through */ } /* * Here there can be other concurrent MADV_DONTNEED or * trans huge page faults running, and if the pmd is * none or trans huge it can change under us. This is * because MADV_DONTNEED holds the mmap_sem in read * mode. */ if (pmd_none_or_trans_huge_or_clear_bad(pmd)) goto next; next = zap_pte_range(tlb, vma, pmd, addr, next, details); next: cond_resched(); } while (pmd++, addr = next, addr != end); return addr; } static inline unsigned long zap_pud_range(struct mmu_gather *tlb, struct vm_area_struct *vma, pgd_t *pgd, unsigned long addr, unsigned long end, struct zap_details *details) { pud_t *pud; unsigned long next; pud = pud_offset(pgd, addr); do { next = pud_addr_end(addr, end); if (pud_none_or_clear_bad(pud)) continue; next = zap_pmd_range(tlb, vma, pud, addr, next, details); } while (pud++, addr = next, addr != end); return addr; } static void unmap_page_range(struct mmu_gather *tlb, struct vm_area_struct *vma, unsigned long addr, unsigned long end, struct zap_details *details) { pgd_t *pgd; unsigned long next; if (details && !details->check_mapping && !details->nonlinear_vma) details = NULL; BUG_ON(addr >= end); mem_cgroup_uncharge_start(); tlb_start_vma(tlb, vma); pgd = pgd_offset(vma->vm_mm, addr); do { next = pgd_addr_end(addr, end); if (pgd_none_or_clear_bad(pgd)) continue; next = zap_pud_range(tlb, vma, pgd, addr, next, details); } while (pgd++, addr = next, addr != end); tlb_end_vma(tlb, vma); mem_cgroup_uncharge_end(); } static void unmap_single_vma(struct mmu_gather *tlb, struct vm_area_struct *vma, unsigned long start_addr, unsigned long end_addr, unsigned long *nr_accounted, struct zap_details *details) { unsigned long start = max(vma->vm_start, start_addr); unsigned long end; if (start >= vma->vm_end) return; end = min(vma->vm_end, end_addr); if (end <= vma->vm_start) return; if (vma->vm_flags & VM_ACCOUNT) *nr_accounted += (end - start) >> PAGE_SHIFT; if (unlikely(is_pfn_mapping(vma))) untrack_pfn_vma(vma, 0, 0); if (start != end) { if (unlikely(is_vm_hugetlb_page(vma))) { /* * It is undesirable to test vma->vm_file as it * should be non-null for valid hugetlb area. * However, vm_file will be NULL in the error * cleanup path of do_mmap_pgoff. When * hugetlbfs ->mmap method fails, * do_mmap_pgoff() nullifies vma->vm_file * before calling this function to clean up. * Since no pte has actually been setup, it is * safe to do nothing in this case. */ if (vma->vm_file) unmap_hugepage_range(vma, start, end, NULL); } else unmap_page_range(tlb, vma, start, end, details); } } /** * unmap_vmas - unmap a range of memory covered by a list of vma's * @tlb: address of the caller's struct mmu_gather * @vma: the starting vma * @start_addr: virtual address at which to start unmapping * @end_addr: virtual address at which to end unmapping * @nr_accounted: Place number of unmapped pages in vm-accountable vma's here * @details: details of nonlinear truncation or shared cache invalidation * * Unmap all pages in the vma list. * * Only addresses between `start' and `end' will be unmapped. * * The VMA list must be sorted in ascending virtual address order. * * unmap_vmas() assumes that the caller will flush the whole unmapped address * range after unmap_vmas() returns. So the only responsibility here is to * ensure that any thus-far unmapped pages are flushed before unmap_vmas() * drops the lock and schedules. */ void unmap_vmas(struct mmu_gather *tlb, struct vm_area_struct *vma, unsigned long start_addr, unsigned long end_addr, unsigned long *nr_accounted, struct zap_details *details) { struct mm_struct *mm = vma->vm_mm; mmu_notifier_invalidate_range_start(mm, start_addr, end_addr); for ( ; vma && vma->vm_start < end_addr; vma = vma->vm_next) unmap_single_vma(tlb, vma, start_addr, end_addr, nr_accounted, details); mmu_notifier_invalidate_range_end(mm, start_addr, end_addr); } /** * zap_page_range - remove user pages in a given range * @vma: vm_area_struct holding the applicable pages * @address: starting address of pages to zap * @size: number of bytes to zap * @details: details of nonlinear truncation or shared cache invalidation * * Caller must protect the VMA list */ void zap_page_range(struct vm_area_struct *vma, unsigned long address, unsigned long size, struct zap_details *details) { struct mm_struct *mm = vma->vm_mm; struct mmu_gather tlb; unsigned long end = address + size; unsigned long nr_accounted = 0; lru_add_drain(); tlb_gather_mmu(&tlb, mm, 0); update_hiwater_rss(mm); unmap_vmas(&tlb, vma, address, end, &nr_accounted, details); tlb_finish_mmu(&tlb, address, end); } /** * zap_page_range_single - remove user pages in a given range * @vma: vm_area_struct holding the applicable pages * @address: starting address of pages to zap * @size: number of bytes to zap * @details: details of nonlinear truncation or shared cache invalidation * * The range must fit into one VMA. */ static void zap_page_range_single(struct vm_area_struct *vma, unsigned long address, unsigned long size, struct zap_details *details) { struct mm_struct *mm = vma->vm_mm; struct mmu_gather tlb; unsigned long end = address + size; unsigned long nr_accounted = 0; lru_add_drain(); tlb_gather_mmu(&tlb, mm, 0); update_hiwater_rss(mm); mmu_notifier_invalidate_range_start(mm, address, end); unmap_single_vma(&tlb, vma, address, end, &nr_accounted, details); mmu_notifier_invalidate_range_end(mm, address, end); tlb_finish_mmu(&tlb, address, end); } /** * zap_vma_ptes - remove ptes mapping the vma * @vma: vm_area_struct holding ptes to be zapped * @address: starting address of pages to zap * @size: number of bytes to zap * * This function only unmaps ptes assigned to VM_PFNMAP vmas. * * The entire address range must be fully contained within the vma. * * Returns 0 if successful. */ int zap_vma_ptes(struct vm_area_struct *vma, unsigned long address, unsigned long size) { if (address < vma->vm_start || address + size > vma->vm_end || !(vma->vm_flags & VM_PFNMAP)) return -1; zap_page_range_single(vma, address, size, NULL); return 0; } EXPORT_SYMBOL_GPL(zap_vma_ptes); /** * follow_page - look up a page descriptor from a user-virtual address * @vma: vm_area_struct mapping @address * @address: virtual address to look up * @flags: flags modifying lookup behaviour * * @flags can have FOLL_ flags set, defined in <linux/mm.h> * * Returns the mapped (struct page *), %NULL if no mapping exists, or * an error pointer if there is a mapping to something not represented * by a page descriptor (see also vm_normal_page()). */ struct page *follow_page(struct vm_area_struct *vma, unsigned long address, unsigned int flags) { pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t *ptep, pte; spinlock_t *ptl; struct page *page; struct mm_struct *mm = vma->vm_mm; page = follow_huge_addr(mm, address, flags & FOLL_WRITE); if (!IS_ERR(page)) { BUG_ON(flags & FOLL_GET); goto out; } page = NULL; pgd = pgd_offset(mm, address); if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd))) goto no_page_table; pud = pud_offset(pgd, address); if (pud_none(*pud)) goto no_page_table; if (pud_huge(*pud) && vma->vm_flags & VM_HUGETLB) { BUG_ON(flags & FOLL_GET); page = follow_huge_pud(mm, address, pud, flags & FOLL_WRITE); goto out; } if (unlikely(pud_bad(*pud))) goto no_page_table; pmd = pmd_offset(pud, address); if (pmd_none(*pmd)) goto no_page_table; if (pmd_huge(*pmd) && vma->vm_flags & VM_HUGETLB) { BUG_ON(flags & FOLL_GET); page = follow_huge_pmd(mm, address, pmd, flags & FOLL_WRITE); goto out; } if (pmd_trans_huge(*pmd)) { if (flags & FOLL_SPLIT) { split_huge_page_pmd(mm, pmd); goto split_fallthrough; } spin_lock(&mm->page_table_lock); if (likely(pmd_trans_huge(*pmd))) { if (unlikely(pmd_trans_splitting(*pmd))) { spin_unlock(&mm->page_table_lock); wait_split_huge_page(vma->anon_vma, pmd); } else { page = follow_trans_huge_pmd(mm, address, pmd, flags); spin_unlock(&mm->page_table_lock); goto out; } } else spin_unlock(&mm->page_table_lock); /* fall through */ } split_fallthrough: if (unlikely(pmd_bad(*pmd))) goto no_page_table; ptep = pte_offset_map_lock(mm, pmd, address, &ptl); pte = *ptep; if (!pte_present(pte)) goto no_page; if ((flags & FOLL_WRITE) && !pte_write(pte)) goto unlock; page = vm_normal_page(vma, address, pte); if (unlikely(!page)) { if ((flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(pte))) goto bad_page; page = pte_page(pte); } if (flags & FOLL_GET) get_page_foll(page); if (flags & FOLL_TOUCH) { if ((flags & FOLL_WRITE) && !pte_dirty(pte) && !PageDirty(page)) set_page_dirty(page); /* * pte_mkyoung() would be more correct here, but atomic care * is needed to avoid losing the dirty bit: it is easier to use * mark_page_accessed(). */ mark_page_accessed(page); } if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) { /* * The preliminary mapping check is mainly to avoid the * pointless overhead of lock_page on the ZERO_PAGE * which might bounce very badly if there is contention. * * If the page is already locked, we don't need to * handle it now - vmscan will handle it later if and * when it attempts to reclaim the page. */ if (page->mapping && trylock_page(page)) { lru_add_drain(); /* push cached pages to LRU */ /* * Because we lock page here and migration is * blocked by the pte's page reference, we need * only check for file-cache page truncation. */ if (page->mapping) mlock_vma_page(page); unlock_page(page); } } unlock: pte_unmap_unlock(ptep, ptl); out: return page; bad_page: pte_unmap_unlock(ptep, ptl); return ERR_PTR(-EFAULT); no_page: pte_unmap_unlock(ptep, ptl); if (!pte_none(pte)) return page; no_page_table: /* * When core dumping an enormous anonymous area that nobody * has touched so far, we don't want to allocate unnecessary pages or * page tables. Return error instead of NULL to skip handle_mm_fault, * then get_dump_page() will return NULL to leave a hole in the dump. * But we can only make this optimization where a hole would surely * be zero-filled if handle_mm_fault() actually did handle it. */ if ((flags & FOLL_DUMP) && (!vma->vm_ops || !vma->vm_ops->fault)) return ERR_PTR(-EFAULT); return page; } static inline int stack_guard_page(struct vm_area_struct *vma, unsigned long addr) { return stack_guard_page_start(vma, addr) || stack_guard_page_end(vma, addr+PAGE_SIZE); } /** * __get_user_pages() - pin user pages in memory * @tsk: task_struct of target task * @mm: mm_struct of target mm * @start: starting user address * @nr_pages: number of pages from start to pin * @gup_flags: flags modifying pin behaviour * @pages: array that receives pointers to the pages pinned. * Should be at least nr_pages long. Or NULL, if caller * only intends to ensure the pages are faulted in. * @vmas: array of pointers to vmas corresponding to each page. * Or NULL if the caller does not require them. * @nonblocking: whether waiting for disk IO or mmap_sem contention * * Returns number of pages pinned. This may be fewer than the number * requested. If nr_pages is 0 or negative, returns 0. If no pages * were pinned, returns -errno. Each page returned must be released * with a put_page() call when it is finished with. vmas will only * remain valid while mmap_sem is held. * * Must be called with mmap_sem held for read or write. * * __get_user_pages walks a process's page tables and takes a reference to * each struct page that each user address corresponds to at a given * instant. That is, it takes the page that would be accessed if a user * thread accesses the given user virtual address at that instant. * * This does not guarantee that the page exists in the user mappings when * __get_user_pages returns, and there may even be a completely different * page there in some cases (eg. if mmapped pagecache has been invalidated * and subsequently re faulted). However it does guarantee that the page * won't be freed completely. And mostly callers simply care that the page * contains data that was valid *at some point in time*. Typically, an IO * or similar operation cannot guarantee anything stronger anyway because * locks can't be held over the syscall boundary. * * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If * the page is written to, set_page_dirty (or set_page_dirty_lock, as * appropriate) must be called after the page is finished with, and * before put_page is called. * * If @nonblocking != NULL, __get_user_pages will not wait for disk IO * or mmap_sem contention, and if waiting is needed to pin all pages, * *@nonblocking will be set to 0. * * In most cases, get_user_pages or get_user_pages_fast should be used * instead of __get_user_pages. __get_user_pages should be used only if * you need some special @gup_flags. */ int __get_user_pages(struct task_struct *tsk, struct mm_struct *mm, unsigned long start, int nr_pages, unsigned int gup_flags, struct page **pages, struct vm_area_struct **vmas, int *nonblocking) { int i; unsigned long vm_flags; if (nr_pages <= 0) return 0; VM_BUG_ON(!!pages != !!(gup_flags & FOLL_GET)); /* * Require read or write permissions. * If FOLL_FORCE is set, we only require the "MAY" flags. */ vm_flags = (gup_flags & FOLL_WRITE) ? (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD); vm_flags &= (gup_flags & FOLL_FORCE) ? (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE); i = 0; do { struct vm_area_struct *vma; vma = find_extend_vma(mm, start); if (!vma && in_gate_area(mm, start)) { unsigned long pg = start & PAGE_MASK; pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t *pte; /* user gate pages are read-only */ if (gup_flags & FOLL_WRITE) return i ? : -EFAULT; if (pg > TASK_SIZE) pgd = pgd_offset_k(pg); else pgd = pgd_offset_gate(mm, pg); BUG_ON(pgd_none(*pgd)); pud = pud_offset(pgd, pg); BUG_ON(pud_none(*pud)); pmd = pmd_offset(pud, pg); if (pmd_none(*pmd)) return i ? : -EFAULT; VM_BUG_ON(pmd_trans_huge(*pmd)); pte = pte_offset_map(pmd, pg); if (pte_none(*pte)) { pte_unmap(pte); return i ? : -EFAULT; } vma = get_gate_vma(mm); if (pages) { struct page *page; page = vm_normal_page(vma, start, *pte); if (!page) { if (!(gup_flags & FOLL_DUMP) && is_zero_pfn(pte_pfn(*pte))) page = pte_page(*pte); else { pte_unmap(pte); return i ? : -EFAULT; } } pages[i] = page; get_page(page); } pte_unmap(pte); goto next_page; } if (use_user_accessible_timers()) { if (!vma && in_user_timers_area(mm, start)) { int goto_next_page = 0; int user_timer_ret = get_user_timer_page(vma, mm, start, gup_flags, pages, i, &goto_next_page); if (goto_next_page) goto next_page; else return user_timer_ret; } } if (!vma || (vma->vm_flags & (VM_IO | VM_PFNMAP)) || !(vm_flags & vma->vm_flags)) return i ? : -EFAULT; if (is_vm_hugetlb_page(vma)) { i = follow_hugetlb_page(mm, vma, pages, vmas, &start, &nr_pages, i, gup_flags); continue; } do { struct page *page; unsigned int foll_flags = gup_flags; /* * If we have a pending SIGKILL, don't keep faulting * pages and potentially allocating memory. */ if (unlikely(fatal_signal_pending(current))) return i ? i : -ERESTARTSYS; cond_resched(); while (!(page = follow_page(vma, start, foll_flags))) { int ret; unsigned int fault_flags = 0; /* For mlock, just skip the stack guard page. */ if (foll_flags & FOLL_MLOCK) { if (stack_guard_page(vma, start)) goto next_page; } if (foll_flags & FOLL_WRITE) fault_flags |= FAULT_FLAG_WRITE; if (nonblocking) fault_flags |= FAULT_FLAG_ALLOW_RETRY; if (foll_flags & FOLL_NOWAIT) fault_flags |= (FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT); ret = handle_mm_fault(mm, vma, start, fault_flags); if (ret & VM_FAULT_ERROR) { if (ret & VM_FAULT_OOM) return i ? i : -ENOMEM; if (ret & (VM_FAULT_HWPOISON | VM_FAULT_HWPOISON_LARGE)) { if (i) return i; else if (gup_flags & FOLL_HWPOISON) return -EHWPOISON; else return -EFAULT; } if (ret & VM_FAULT_SIGBUS) return i ? i : -EFAULT; BUG(); } if (tsk) { if (ret & VM_FAULT_MAJOR) tsk->maj_flt++; else tsk->min_flt++; } if (ret & VM_FAULT_RETRY) { if (nonblocking) *nonblocking = 0; return i; } /* * The VM_FAULT_WRITE bit tells us that * do_wp_page has broken COW when necessary, * even if maybe_mkwrite decided not to set * pte_write. We can thus safely do subsequent * page lookups as if they were reads. But only * do so when looping for pte_write is futile: * in some cases userspace may also be wanting * to write to the gotten user page, which a * read fault here might prevent (a readonly * page might get reCOWed by userspace write). */ if ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE)) foll_flags &= ~FOLL_WRITE; cond_resched(); } if (IS_ERR(page)) return i ? i : PTR_ERR(page); if (pages) { pages[i] = page; flush_anon_page(vma, page, start); flush_dcache_page(page); } next_page: if (vmas) vmas[i] = vma; i++; start += PAGE_SIZE; nr_pages--; } while (nr_pages && start < vma->vm_end); } while (nr_pages); return i; } EXPORT_SYMBOL(__get_user_pages); /* * fixup_user_fault() - manually resolve a user page fault * @tsk: the task_struct to use for page fault accounting, or * NULL if faults are not to be recorded. * @mm: mm_struct of target mm * @address: user address * @fault_flags:flags to pass down to handle_mm_fault() * * This is meant to be called in the specific scenario where for locking reasons * we try to access user memory in atomic context (within a pagefault_disable() * section), this returns -EFAULT, and we want to resolve the user fault before * trying again. * * Typically this is meant to be used by the futex code. * * The main difference with get_user_pages() is that this function will * unconditionally call handle_mm_fault() which will in turn perform all the * necessary SW fixup of the dirty and young bits in the PTE, while * handle_mm_fault() only guarantees to update these in the struct page. * * This is important for some architectures where those bits also gate the * access permission to the page because they are maintained in software. On * such architectures, gup() will not be enough to make a subsequent access * succeed. * * This should be called with the mm_sem held for read. */ int fixup_user_fault(struct task_struct *tsk, struct mm_struct *mm, unsigned long address, unsigned int fault_flags) { struct vm_area_struct *vma; int ret; vma = find_extend_vma(mm, address); if (!vma || address < vma->vm_start) return -EFAULT; ret = handle_mm_fault(mm, vma, address, fault_flags); if (ret & VM_FAULT_ERROR) { if (ret & VM_FAULT_OOM) return -ENOMEM; if (ret & (VM_FAULT_HWPOISON | VM_FAULT_HWPOISON_LARGE)) return -EHWPOISON; if (ret & VM_FAULT_SIGBUS) return -EFAULT; BUG(); } if (tsk) { if (ret & VM_FAULT_MAJOR) tsk->maj_flt++; else tsk->min_flt++; } return 0; } /* * get_user_pages() - pin user pages in memory * @tsk: the task_struct to use for page fault accounting, or * NULL if faults are not to be recorded. * @mm: mm_struct of target mm * @start: starting user address * @nr_pages: number of pages from start to pin * @write: whether pages will be written to by the caller * @force: whether to force write access even if user mapping is * readonly. This will result in the page being COWed even * in MAP_SHARED mappings. You do not want this. * @pages: array that receives pointers to the pages pinned. * Should be at least nr_pages long. Or NULL, if caller * only intends to ensure the pages are faulted in. * @vmas: array of pointers to vmas corresponding to each page. * Or NULL if the caller does not require them. * * Returns number of pages pinned. This may be fewer than the number * requested. If nr_pages is 0 or negative, returns 0. If no pages * were pinned, returns -errno. Each page returned must be released * with a put_page() call when it is finished with. vmas will only * remain valid while mmap_sem is held. * * Must be called with mmap_sem held for read or write. * * get_user_pages walks a process's page tables and takes a reference to * each struct page that each user address corresponds to at a given * instant. That is, it takes the page that would be accessed if a user * thread accesses the given user virtual address at that instant. * * This does not guarantee that the page exists in the user mappings when * get_user_pages returns, and there may even be a completely different * page there in some cases (eg. if mmapped pagecache has been invalidated * and subsequently re faulted). However it does guarantee that the page * won't be freed completely. And mostly callers simply care that the page * contains data that was valid *at some point in time*. Typically, an IO * or similar operation cannot guarantee anything stronger anyway because * locks can't be held over the syscall boundary. * * If write=0, the page must not be written to. If the page is written to, * set_page_dirty (or set_page_dirty_lock, as appropriate) must be called * after the page is finished with, and before put_page is called. * * get_user_pages is typically used for fewer-copy IO operations, to get a * handle on the memory by some means other than accesses via the user virtual * addresses. The pages may be submitted for DMA to devices or accessed via * their kernel linear mapping (via the kmap APIs). Care should be taken to * use the correct cache flushing APIs. * * See also get_user_pages_fast, for performance critical applications. */ int get_user_pages(struct task_struct *tsk, struct mm_struct *mm, unsigned long start, int nr_pages, int write, int force, struct page **pages, struct vm_area_struct **vmas) { int flags = FOLL_TOUCH; if (pages) flags |= FOLL_GET; if (write) flags |= FOLL_WRITE; if (force) flags |= FOLL_FORCE; return __get_user_pages(tsk, mm, start, nr_pages, flags, pages, vmas, NULL); } EXPORT_SYMBOL(get_user_pages); /** * get_dump_page() - pin user page in memory while writing it to core dump * @addr: user address * * Returns struct page pointer of user page pinned for dump, * to be freed afterwards by page_cache_release() or put_page(). * * Returns NULL on any kind of failure - a hole must then be inserted into * the corefile, to preserve alignment with its headers; and also returns * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found - * allowing a hole to be left in the corefile to save diskspace. * * Called without mmap_sem, but after all other threads have been killed. */ #ifdef CONFIG_ELF_CORE struct page *get_dump_page(unsigned long addr) { struct vm_area_struct *vma; struct page *page; if (__get_user_pages(current, current->mm, addr, 1, FOLL_FORCE | FOLL_DUMP | FOLL_GET, &page, &vma, NULL) < 1) return NULL; flush_cache_page(vma, addr, page_to_pfn(page)); return page; } #endif /* CONFIG_ELF_CORE */ pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr, spinlock_t **ptl) { pgd_t * pgd = pgd_offset(mm, addr); pud_t * pud = pud_alloc(mm, pgd, addr); if (pud) { pmd_t * pmd = pmd_alloc(mm, pud, addr); if (pmd) { VM_BUG_ON(pmd_trans_huge(*pmd)); return pte_alloc_map_lock(mm, pmd, addr, ptl); } } return NULL; } /* * This is the old fallback for page remapping. * * For historical reasons, it only allows reserved pages. Only * old drivers should use this, and they needed to mark their * pages reserved for the old functions anyway. */ static int insert_page(struct vm_area_struct *vma, unsigned long addr, struct page *page, pgprot_t prot) { struct mm_struct *mm = vma->vm_mm; int retval; pte_t *pte; spinlock_t *ptl; retval = -EINVAL; if (PageAnon(page)) goto out; retval = -ENOMEM; flush_dcache_page(page); pte = get_locked_pte(mm, addr, &ptl); if (!pte) goto out; retval = -EBUSY; if (!pte_none(*pte)) goto out_unlock; /* Ok, finally just insert the thing.. */ get_page(page); inc_mm_counter_fast(mm, MM_FILEPAGES); page_add_file_rmap(page); set_pte_at(mm, addr, pte, mk_pte(page, prot)); retval = 0; pte_unmap_unlock(pte, ptl); return retval; out_unlock: pte_unmap_unlock(pte, ptl); out: return retval; } /** * vm_insert_page - insert single page into user vma * @vma: user vma to map to * @addr: target user address of this page * @page: source kernel page * * This allows drivers to insert individual pages they've allocated * into a user vma. * * The page has to be a nice clean _individual_ kernel allocation. * If you allocate a compound page, you need to have marked it as * such (__GFP_COMP), or manually just split the page up yourself * (see split_page()). * * NOTE! Traditionally this was done with "remap_pfn_range()" which * took an arbitrary page protection parameter. This doesn't allow * that. Your vma protection will have to be set up correctly, which * means that if you want a shared writable mapping, you'd better * ask for a shared writable mapping! * * The page does not need to be reserved. */ int vm_insert_page(struct vm_area_struct *vma, unsigned long addr, struct page *page) { if (addr < vma->vm_start || addr >= vma->vm_end) return -EFAULT; if (!page_count(page)) return -EINVAL; vma->vm_flags |= VM_INSERTPAGE; return insert_page(vma, addr, page, vma->vm_page_prot); } EXPORT_SYMBOL(vm_insert_page); static int insert_pfn(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn, pgprot_t prot) { struct mm_struct *mm = vma->vm_mm; int retval; pte_t *pte, entry; spinlock_t *ptl; retval = -ENOMEM; pte = get_locked_pte(mm, addr, &ptl); if (!pte) goto out; retval = -EBUSY; if (!pte_none(*pte)) goto out_unlock; /* Ok, finally just insert the thing.. */ entry = pte_mkspecial(pfn_pte(pfn, prot)); set_pte_at(mm, addr, pte, entry); update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */ retval = 0; out_unlock: pte_unmap_unlock(pte, ptl); out: return retval; } /** * vm_insert_pfn - insert single pfn into user vma * @vma: user vma to map to * @addr: target user address of this page * @pfn: source kernel pfn * * Similar to vm_inert_page, this allows drivers to insert individual pages * they've allocated into a user vma. Same comments apply. * * This function should only be called from a vm_ops->fault handler, and * in that case the handler should return NULL. * * vma cannot be a COW mapping. * * As this is called only for pages that do not currently exist, we * do not need to flush old virtual caches or the TLB. */ int vm_insert_pfn(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn) { int ret; pgprot_t pgprot = vma->vm_page_prot; /* * Technically, architectures with pte_special can avoid all these * restrictions (same for remap_pfn_range). However we would like * consistency in testing and feature parity among all, so we should * try to keep these invariants in place for everybody. */ BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))); BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) == (VM_PFNMAP|VM_MIXEDMAP)); BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags)); BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn)); if (addr < vma->vm_start || addr >= vma->vm_end) return -EFAULT; if (track_pfn_vma_new(vma, &pgprot, pfn, PAGE_SIZE)) return -EINVAL; ret = insert_pfn(vma, addr, pfn, pgprot); if (ret) untrack_pfn_vma(vma, pfn, PAGE_SIZE); return ret; } EXPORT_SYMBOL(vm_insert_pfn); int vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn) { BUG_ON(!(vma->vm_flags & VM_MIXEDMAP)); if (addr < vma->vm_start || addr >= vma->vm_end) return -EFAULT; /* * If we don't have pte special, then we have to use the pfn_valid() * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must* * refcount the page if pfn_valid is true (hence insert_page rather * than insert_pfn). If a zero_pfn were inserted into a VM_MIXEDMAP * without pte special, it would there be refcounted as a normal page. */ if (!HAVE_PTE_SPECIAL && pfn_valid(pfn)) { struct page *page; page = pfn_to_page(pfn); return insert_page(vma, addr, page, vma->vm_page_prot); } return insert_pfn(vma, addr, pfn, vma->vm_page_prot); } EXPORT_SYMBOL(vm_insert_mixed); /* * maps a range of physical memory into the requested pages. the old * mappings are removed. any references to nonexistent pages results * in null mappings (currently treated as "copy-on-access") */ static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd, unsigned long addr, unsigned long end, unsigned long pfn, pgprot_t prot) { pte_t *pte; spinlock_t *ptl; pte = pte_alloc_map_lock(mm, pmd, addr, &ptl); if (!pte) return -ENOMEM; arch_enter_lazy_mmu_mode(); do { BUG_ON(!pte_none(*pte)); set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot))); pfn++; } while (pte++, addr += PAGE_SIZE, addr != end); arch_leave_lazy_mmu_mode(); pte_unmap_unlock(pte - 1, ptl); return 0; } static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud, unsigned long addr, unsigned long end, unsigned long pfn, pgprot_t prot) { pmd_t *pmd; unsigned long next; pfn -= addr >> PAGE_SHIFT; pmd = pmd_alloc(mm, pud, addr); if (!pmd) return -ENOMEM; VM_BUG_ON(pmd_trans_huge(*pmd)); do { next = pmd_addr_end(addr, end); if (remap_pte_range(mm, pmd, addr, next, pfn + (addr >> PAGE_SHIFT), prot)) return -ENOMEM; } while (pmd++, addr = next, addr != end); return 0; } static inline int remap_pud_range(struct mm_struct *mm, pgd_t *pgd, unsigned long addr, unsigned long end, unsigned long pfn, pgprot_t prot) { pud_t *pud; unsigned long next; pfn -= addr >> PAGE_SHIFT; pud = pud_alloc(mm, pgd, addr); if (!pud) return -ENOMEM; do { next = pud_addr_end(addr, end); if (remap_pmd_range(mm, pud, addr, next, pfn + (addr >> PAGE_SHIFT), prot)) return -ENOMEM; } while (pud++, addr = next, addr != end); return 0; } /** * remap_pfn_range - remap kernel memory to userspace * @vma: user vma to map to * @addr: target user address to start at * @pfn: physical address of kernel memory * @size: size of map area * @prot: page protection flags for this mapping * * Note: this is only safe if the mm semaphore is held when called. */ int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn, unsigned long size, pgprot_t prot) { pgd_t *pgd; unsigned long next; unsigned long end = addr + PAGE_ALIGN(size); struct mm_struct *mm = vma->vm_mm; int err; /* * Physically remapped pages are special. Tell the * rest of the world about it: * VM_IO tells people not to look at these pages * (accesses can have side effects). * VM_RESERVED is specified all over the place, because * in 2.4 it kept swapout's vma scan off this vma; but * in 2.6 the LRU scan won't even find its pages, so this * flag means no more than count its pages in reserved_vm, * and omit it from core dump, even when VM_IO turned off. * VM_PFNMAP tells the core MM that the base pages are just * raw PFN mappings, and do not have a "struct page" associated * with them. * * There's a horrible special case to handle copy-on-write * behaviour that some programs depend on. We mark the "original" * un-COW'ed pages by matching them up with "vma->vm_pgoff". */ if (addr == vma->vm_start && end == vma->vm_end) { vma->vm_pgoff = pfn; vma->vm_flags |= VM_PFN_AT_MMAP; } else if (is_cow_mapping(vma->vm_flags)) return -EINVAL; vma->vm_flags |= VM_IO | VM_RESERVED | VM_PFNMAP; err = track_pfn_vma_new(vma, &prot, pfn, PAGE_ALIGN(size)); if (err) { /* * To indicate that track_pfn related cleanup is not * needed from higher level routine calling unmap_vmas */ vma->vm_flags &= ~(VM_IO | VM_RESERVED | VM_PFNMAP); vma->vm_flags &= ~VM_PFN_AT_MMAP; return -EINVAL; } BUG_ON(addr >= end); pfn -= addr >> PAGE_SHIFT; pgd = pgd_offset(mm, addr); flush_cache_range(vma, addr, end); do { next = pgd_addr_end(addr, end); err = remap_pud_range(mm, pgd, addr, next, pfn + (addr >> PAGE_SHIFT), prot); if (err) break; } while (pgd++, addr = next, addr != end); if (err) untrack_pfn_vma(vma, pfn, PAGE_ALIGN(size)); return err; } EXPORT_SYMBOL(remap_pfn_range); /** * vm_iomap_memory - remap memory to userspace * @vma: user vma to map to * @start: start of area * @len: size of area * * This is a simplified io_remap_pfn_range() for common driver use. The * driver just needs to give us the physical memory range to be mapped, * we'll figure out the rest from the vma information. * * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get * whatever write-combining details or similar. */ int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len) { unsigned long vm_len, pfn, pages; /* Check that the physical memory area passed in looks valid */ if (start + len < start) return -EINVAL; /* * You *really* shouldn't map things that aren't page-aligned, * but we've historically allowed it because IO memory might * just have smaller alignment. */ len += start & ~PAGE_MASK; pfn = start >> PAGE_SHIFT; pages = (len + ~PAGE_MASK) >> PAGE_SHIFT; if (pfn + pages < pfn) return -EINVAL; /* We start the mapping 'vm_pgoff' pages into the area */ if (vma->vm_pgoff > pages) return -EINVAL; pfn += vma->vm_pgoff; pages -= vma->vm_pgoff; /* Can we fit all of the mapping? */ vm_len = vma->vm_end - vma->vm_start; if (vm_len >> PAGE_SHIFT > pages) return -EINVAL; /* Ok, let it rip */ return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot); } EXPORT_SYMBOL(vm_iomap_memory); static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd, unsigned long addr, unsigned long end, pte_fn_t fn, void *data) { pte_t *pte; int err; pgtable_t token; spinlock_t *uninitialized_var(ptl); pte = (mm == &init_mm) ? pte_alloc_kernel(pmd, addr) : pte_alloc_map_lock(mm, pmd, addr, &ptl); if (!pte) return -ENOMEM; BUG_ON(pmd_huge(*pmd)); arch_enter_lazy_mmu_mode(); token = pmd_pgtable(*pmd); do { err = fn(pte++, token, addr, data); if (err) break; } while (addr += PAGE_SIZE, addr != end); arch_leave_lazy_mmu_mode(); if (mm != &init_mm) pte_unmap_unlock(pte-1, ptl); return err; } static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud, unsigned long addr, unsigned long end, pte_fn_t fn, void *data) { pmd_t *pmd; unsigned long next; int err; BUG_ON(pud_huge(*pud)); pmd = pmd_alloc(mm, pud, addr); if (!pmd) return -ENOMEM; do { next = pmd_addr_end(addr, end); err = apply_to_pte_range(mm, pmd, addr, next, fn, data); if (err) break; } while (pmd++, addr = next, addr != end); return err; } static int apply_to_pud_range(struct mm_struct *mm, pgd_t *pgd, unsigned long addr, unsigned long end, pte_fn_t fn, void *data) { pud_t *pud; unsigned long next; int err; pud = pud_alloc(mm, pgd, addr); if (!pud) return -ENOMEM; do { next = pud_addr_end(addr, end); err = apply_to_pmd_range(mm, pud, addr, next, fn, data); if (err) break; } while (pud++, addr = next, addr != end); return err; } /* * Scan a region of virtual memory, filling in page tables as necessary * and calling a provided function on each leaf page table. */ int apply_to_page_range(struct mm_struct *mm, unsigned long addr, unsigned long size, pte_fn_t fn, void *data) { pgd_t *pgd; unsigned long next; unsigned long end = addr + size; int err; BUG_ON(addr >= end); pgd = pgd_offset(mm, addr); do { next = pgd_addr_end(addr, end); err = apply_to_pud_range(mm, pgd, addr, next, fn, data); if (err) break; } while (pgd++, addr = next, addr != end); return err; } EXPORT_SYMBOL_GPL(apply_to_page_range); /* * handle_pte_fault chooses page fault handler according to an entry * which was read non-atomically. Before making any commitment, on * those architectures or configurations (e.g. i386 with PAE) which * might give a mix of unmatched parts, do_swap_page and do_nonlinear_fault * must check under lock before unmapping the pte and proceeding * (but do_wp_page is only called after already making such a check; * and do_anonymous_page can safely check later on). */ static inline int pte_unmap_same(struct mm_struct *mm, pmd_t *pmd, pte_t *page_table, pte_t orig_pte) { int same = 1; #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT) if (sizeof(pte_t) > sizeof(unsigned long)) { spinlock_t *ptl = pte_lockptr(mm, pmd); spin_lock(ptl); same = pte_same(*page_table, orig_pte); spin_unlock(ptl); } #endif pte_unmap(page_table); return same; } static inline void cow_user_page(struct page *dst, struct page *src, unsigned long va, struct vm_area_struct *vma) { /* * If the source page was a PFN mapping, we don't have * a "struct page" for it. We do a best-effort copy by * just copying from the original user address. If that * fails, we just zero-fill it. Live with it. */ if (unlikely(!src)) { void *kaddr = kmap_atomic(dst); void __user *uaddr = (void __user *)(va & PAGE_MASK); /* * This really shouldn't fail, because the page is there * in the page tables. But it might just be unreadable, * in which case we just give up and fill the result with * zeroes. */ if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) clear_page(kaddr); kunmap_atomic(kaddr); flush_dcache_page(dst); } else copy_user_highpage(dst, src, va, vma); } /* * This routine handles present pages, when users try to write * to a shared page. It is done by copying the page to a new address * and decrementing the shared-page counter for the old page. * * Note that this routine assumes that the protection checks have been * done by the caller (the low-level page fault routine in most cases). * Thus we can safely just mark it writable once we've done any necessary * COW. * * We also mark the page dirty at this point even though the page will * change only once the write actually happens. This avoids a few races, * and potentially makes it more efficient. * * We enter with non-exclusive mmap_sem (to exclude vma changes, * but allow concurrent faults), with pte both mapped and locked. * We return with mmap_sem still held, but pte unmapped and unlocked. */ static int do_wp_page(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, spinlock_t *ptl, pte_t orig_pte) __releases(ptl) { struct page *old_page, *new_page; pte_t entry; int ret = 0; int page_mkwrite = 0; struct page *dirty_page = NULL; old_page = vm_normal_page(vma, address, orig_pte); if (!old_page) { /* * VM_MIXEDMAP !pfn_valid() case * * We should not cow pages in a shared writeable mapping. * Just mark the pages writable as we can't do any dirty * accounting on raw pfn maps. */ if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) == (VM_WRITE|VM_SHARED)) goto reuse; goto gotten; } /* * Take out anonymous pages first, anonymous shared vmas are * not dirty accountable. */ if (PageAnon(old_page) && !PageKsm(old_page)) { if (!trylock_page(old_page)) { page_cache_get(old_page); pte_unmap_unlock(page_table, ptl); lock_page(old_page); page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (!pte_same(*page_table, orig_pte)) { unlock_page(old_page); goto unlock; } page_cache_release(old_page); } if (reuse_swap_page(old_page)) { /* * The page is all ours. Move it to our anon_vma so * the rmap code will not search our parent or siblings. * Protected against the rmap code by the page lock. */ page_move_anon_rmap(old_page, vma, address); unlock_page(old_page); goto reuse; } unlock_page(old_page); } else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) == (VM_WRITE|VM_SHARED))) { /* * Only catch write-faults on shared writable pages, * read-only shared pages can get COWed by * get_user_pages(.write=1, .force=1). */ if (vma->vm_ops && vma->vm_ops->page_mkwrite) { struct vm_fault vmf; int tmp; vmf.virtual_address = (void __user *)(address & PAGE_MASK); vmf.pgoff = old_page->index; vmf.flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE; vmf.page = old_page; /* * Notify the address space that the page is about to * become writable so that it can prohibit this or wait * for the page to get into an appropriate state. * * We do this without the lock held, so that it can * sleep if it needs to. */ page_cache_get(old_page); pte_unmap_unlock(page_table, ptl); tmp = vma->vm_ops->page_mkwrite(vma, &vmf); if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) { ret = tmp; goto unwritable_page; } if (unlikely(!(tmp & VM_FAULT_LOCKED))) { lock_page(old_page); if (!old_page->mapping) { ret = 0; /* retry the fault */ unlock_page(old_page); goto unwritable_page; } } else VM_BUG_ON(!PageLocked(old_page)); /* * Since we dropped the lock we need to revalidate * the PTE as someone else may have changed it. If * they did, we just return, as we can count on the * MMU to tell us if they didn't also make it writable. */ page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (!pte_same(*page_table, orig_pte)) { unlock_page(old_page); goto unlock; } page_mkwrite = 1; } dirty_page = old_page; get_page(dirty_page); reuse: flush_cache_page(vma, address, pte_pfn(orig_pte)); entry = pte_mkyoung(orig_pte); entry = maybe_mkwrite(pte_mkdirty(entry), vma); if (ptep_set_access_flags(vma, address, page_table, entry,1)) update_mmu_cache(vma, address, page_table); pte_unmap_unlock(page_table, ptl); ret |= VM_FAULT_WRITE; if (!dirty_page) return ret; /* * Yes, Virginia, this is actually required to prevent a race * with clear_page_dirty_for_io() from clearing the page dirty * bit after it clear all dirty ptes, but before a racing * do_wp_page installs a dirty pte. * * __do_fault is protected similarly. */ if (!page_mkwrite) { wait_on_page_locked(dirty_page); set_page_dirty_balance(dirty_page, page_mkwrite); } put_page(dirty_page); if (page_mkwrite) { struct address_space *mapping = dirty_page->mapping; set_page_dirty(dirty_page); unlock_page(dirty_page); page_cache_release(dirty_page); if (mapping) { /* * Some device drivers do not set page.mapping * but still dirty their pages */ balance_dirty_pages_ratelimited(mapping); } } /* file_update_time outside page_lock */ if (vma->vm_file) file_update_time(vma->vm_file); return ret; } /* * Ok, we need to copy. Oh, well.. */ page_cache_get(old_page); gotten: pte_unmap_unlock(page_table, ptl); if (unlikely(anon_vma_prepare(vma))) goto oom; if (is_zero_pfn(pte_pfn(orig_pte))) { new_page = alloc_zeroed_user_highpage_movable(vma, address); if (!new_page) goto oom; } else { new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address); if (!new_page) goto oom; cow_user_page(new_page, old_page, address, vma); } __SetPageUptodate(new_page); if (mem_cgroup_newpage_charge(new_page, mm, GFP_KERNEL)) goto oom_free_new; /* * Re-check the pte - we dropped the lock */ page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (likely(pte_same(*page_table, orig_pte))) { if (old_page) { if (!PageAnon(old_page)) { dec_mm_counter_fast(mm, MM_FILEPAGES); inc_mm_counter_fast(mm, MM_ANONPAGES); } } else inc_mm_counter_fast(mm, MM_ANONPAGES); flush_cache_page(vma, address, pte_pfn(orig_pte)); entry = mk_pte(new_page, vma->vm_page_prot); entry = maybe_mkwrite(pte_mkdirty(entry), vma); /* * Clear the pte entry and flush it first, before updating the * pte with the new entry. This will avoid a race condition * seen in the presence of one thread doing SMC and another * thread doing COW. */ ptep_clear_flush(vma, address, page_table); page_add_new_anon_rmap(new_page, vma, address); /* * We call the notify macro here because, when using secondary * mmu page tables (such as kvm shadow page tables), we want the * new page to be mapped directly into the secondary page table. */ set_pte_at_notify(mm, address, page_table, entry); update_mmu_cache(vma, address, page_table); if (old_page) { /* * Only after switching the pte to the new page may * we remove the mapcount here. Otherwise another * process may come and find the rmap count decremented * before the pte is switched to the new page, and * "reuse" the old page writing into it while our pte * here still points into it and can be read by other * threads. * * The critical issue is to order this * page_remove_rmap with the ptp_clear_flush above. * Those stores are ordered by (if nothing else,) * the barrier present in the atomic_add_negative * in page_remove_rmap. * * Then the TLB flush in ptep_clear_flush ensures that * no process can access the old page before the * decremented mapcount is visible. And the old page * cannot be reused until after the decremented * mapcount is visible. So transitively, TLBs to * old page will be flushed before it can be reused. */ page_remove_rmap(old_page); } /* Free the old page.. */ new_page = old_page; ret |= VM_FAULT_WRITE; } else mem_cgroup_uncharge_page(new_page); if (new_page) page_cache_release(new_page); unlock: pte_unmap_unlock(page_table, ptl); if (old_page) { /* * Don't let another task, with possibly unlocked vma, * keep the mlocked page. */ if ((ret & VM_FAULT_WRITE) && (vma->vm_flags & VM_LOCKED)) { lock_page(old_page); /* LRU manipulation */ munlock_vma_page(old_page); unlock_page(old_page); } page_cache_release(old_page); } return ret; oom_free_new: page_cache_release(new_page); oom: if (old_page) { if (page_mkwrite) { unlock_page(old_page); page_cache_release(old_page); } page_cache_release(old_page); } return VM_FAULT_OOM; unwritable_page: page_cache_release(old_page); return ret; } static void unmap_mapping_range_vma(struct vm_area_struct *vma, unsigned long start_addr, unsigned long end_addr, struct zap_details *details) { zap_page_range_single(vma, start_addr, end_addr - start_addr, details); } static inline void unmap_mapping_range_tree(struct prio_tree_root *root, struct zap_details *details) { struct vm_area_struct *vma; struct prio_tree_iter iter; pgoff_t vba, vea, zba, zea; vma_prio_tree_foreach(vma, &iter, root, details->first_index, details->last_index) { vba = vma->vm_pgoff; vea = vba + ((vma->vm_end - vma->vm_start) >> PAGE_SHIFT) - 1; /* Assume for now that PAGE_CACHE_SHIFT == PAGE_SHIFT */ zba = details->first_index; if (zba < vba) zba = vba; zea = details->last_index; if (zea > vea) zea = vea; unmap_mapping_range_vma(vma, ((zba - vba) << PAGE_SHIFT) + vma->vm_start, ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start, details); } } static inline void unmap_mapping_range_list(struct list_head *head, struct zap_details *details) { struct vm_area_struct *vma; /* * In nonlinear VMAs there is no correspondence between virtual address * offset and file offset. So we must perform an exhaustive search * across *all* the pages in each nonlinear VMA, not just the pages * whose virtual address lies outside the file truncation point. */ list_for_each_entry(vma, head, shared.vm_set.list) { details->nonlinear_vma = vma; unmap_mapping_range_vma(vma, vma->vm_start, vma->vm_end, details); } } /** * unmap_mapping_range - unmap the portion of all mmaps in the specified address_space corresponding to the specified page range in the underlying file. * @mapping: the address space containing mmaps to be unmapped. * @holebegin: byte in first page to unmap, relative to the start of * the underlying file. This will be rounded down to a PAGE_SIZE * boundary. Note that this is different from truncate_pagecache(), which * must keep the partial page. In contrast, we must get rid of * partial pages. * @holelen: size of prospective hole in bytes. This will be rounded * up to a PAGE_SIZE boundary. A holelen of zero truncates to the * end of the file. * @even_cows: 1 when truncating a file, unmap even private COWed pages; * but 0 when invalidating pagecache, don't throw away private data. */ void unmap_mapping_range(struct address_space *mapping, loff_t const holebegin, loff_t const holelen, int even_cows) { struct zap_details details; pgoff_t hba = holebegin >> PAGE_SHIFT; pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT; /* Check for overflow. */ if (sizeof(holelen) > sizeof(hlen)) { long long holeend = (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT; if (holeend & ~(long long)ULONG_MAX) hlen = ULONG_MAX - hba + 1; } details.check_mapping = even_cows? NULL: mapping; details.nonlinear_vma = NULL; details.first_index = hba; details.last_index = hba + hlen - 1; if (details.last_index < details.first_index) details.last_index = ULONG_MAX; mutex_lock(&mapping->i_mmap_mutex); if (unlikely(!prio_tree_empty(&mapping->i_mmap))) unmap_mapping_range_tree(&mapping->i_mmap, &details); if (unlikely(!list_empty(&mapping->i_mmap_nonlinear))) unmap_mapping_range_list(&mapping->i_mmap_nonlinear, &details); mutex_unlock(&mapping->i_mmap_mutex); } EXPORT_SYMBOL(unmap_mapping_range); /* * We enter with non-exclusive mmap_sem (to exclude vma changes, * but allow concurrent faults), and pte mapped but not yet locked. * We return with mmap_sem still held, but pte unmapped and unlocked. */ static int do_swap_page(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, unsigned int flags, pte_t orig_pte) { spinlock_t *ptl; struct page *page, *swapcache = NULL; swp_entry_t entry; pte_t pte; int locked; struct mem_cgroup *ptr; int exclusive = 0; int ret = 0; if (!pte_unmap_same(mm, pmd, page_table, orig_pte)) goto out; entry = pte_to_swp_entry(orig_pte); if (unlikely(non_swap_entry(entry))) { if (is_migration_entry(entry)) { #ifdef CONFIG_CMA /* * FIXME: mszyprow: cruel, brute-force method for * letting cma/migration to finish it's job without * stealing the lock migration_entry_wait() and creating * a live-lock on the faulted page * (page->_count == 2 migration failure issue) */ mdelay(10); #endif migration_entry_wait(mm, pmd, address); } else if (is_hwpoison_entry(entry)) { ret = VM_FAULT_HWPOISON; } else { print_bad_pte(vma, address, orig_pte, NULL); ret = VM_FAULT_SIGBUS; } goto out; } delayacct_set_flag(DELAYACCT_PF_SWAPIN); page = lookup_swap_cache(entry); if (!page) { grab_swap_token(mm); /* Contend for token _before_ read-in */ page = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE, vma, address); if (!page) { /* * Back out if somebody else faulted in this pte * while we released the pte lock. */ page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (likely(pte_same(*page_table, orig_pte))) ret = VM_FAULT_OOM; delayacct_clear_flag(DELAYACCT_PF_SWAPIN); goto unlock; } /* Had to read the page from swap area: Major fault */ ret = VM_FAULT_MAJOR; count_vm_event(PGMAJFAULT); mem_cgroup_count_vm_event(mm, PGMAJFAULT); } else if (PageHWPoison(page)) { /* * hwpoisoned dirty swapcache pages are kept for killing * owner processes (which may be unknown at hwpoison time) */ ret = VM_FAULT_HWPOISON; delayacct_clear_flag(DELAYACCT_PF_SWAPIN); goto out_release; } #ifdef CONFIG_ZSWAP else if (!(flags & FAULT_FLAG_TRIED)) swap_cache_hit(vma); #endif locked = lock_page_or_retry(page, mm, flags); delayacct_clear_flag(DELAYACCT_PF_SWAPIN); if (!locked) { ret |= VM_FAULT_RETRY; goto out_release; } /* * Make sure try_to_free_swap or reuse_swap_page or swapoff did not * release the swapcache from under us. The page pin, and pte_same * test below, are not enough to exclude that. Even if it is still * swapcache, we need to check that the page's swap has not changed. */ if (unlikely(!PageSwapCache(page) || page_private(page) != entry.val)) goto out_page; if (ksm_might_need_to_copy(page, vma, address)) { swapcache = page; page = ksm_does_need_to_copy(page, vma, address); if (unlikely(!page)) { ret = VM_FAULT_OOM; page = swapcache; swapcache = NULL; goto out_page; } } if (mem_cgroup_try_charge_swapin(mm, page, GFP_KERNEL, &ptr)) { ret = VM_FAULT_OOM; goto out_page; } /* * Back out if somebody else already faulted in this pte. */ page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (unlikely(!pte_same(*page_table, orig_pte))) goto out_nomap; if (unlikely(!PageUptodate(page))) { ret = VM_FAULT_SIGBUS; goto out_nomap; } /* * The page isn't present yet, go ahead with the fault. * * Be careful about the sequence of operations here. * To get its accounting right, reuse_swap_page() must be called * while the page is counted on swap but not yet in mapcount i.e. * before page_add_anon_rmap() and swap_free(); try_to_free_swap() * must be called after the swap_free(), or it will never succeed. * Because delete_from_swap_page() may be called by reuse_swap_page(), * mem_cgroup_commit_charge_swapin() may not be able to find swp_entry * in page->private. In this case, a record in swap_cgroup is silently * discarded at swap_free(). */ inc_mm_counter_fast(mm, MM_ANONPAGES); dec_mm_counter_fast(mm, MM_SWAPENTS); pte = mk_pte(page, vma->vm_page_prot); if ((flags & FAULT_FLAG_WRITE) && reuse_swap_page(page)) { pte = maybe_mkwrite(pte_mkdirty(pte), vma); flags &= ~FAULT_FLAG_WRITE; ret |= VM_FAULT_WRITE; exclusive = 1; } flush_icache_page(vma, page); set_pte_at(mm, address, page_table, pte); do_page_add_anon_rmap(page, vma, address, exclusive); /* It's better to call commit-charge after rmap is established */ mem_cgroup_commit_charge_swapin(page, ptr); swap_free(entry); if (vm_swap_full() || (vma->vm_flags & VM_LOCKED) || PageMlocked(page)) try_to_free_swap(page); unlock_page(page); if (swapcache) { /* * Hold the lock to avoid the swap entry to be reused * until we take the PT lock for the pte_same() check * (to avoid false positives from pte_same). For * further safety release the lock after the swap_free * so that the swap count won't change under a * parallel locked swapcache. */ unlock_page(swapcache); page_cache_release(swapcache); } if (flags & FAULT_FLAG_WRITE) { ret |= do_wp_page(mm, vma, address, page_table, pmd, ptl, pte); if (ret & VM_FAULT_ERROR) ret &= VM_FAULT_ERROR; goto out; } /* No need to invalidate - it was non-present before */ update_mmu_cache(vma, address, page_table); unlock: pte_unmap_unlock(page_table, ptl); out: return ret; out_nomap: mem_cgroup_cancel_charge_swapin(ptr); pte_unmap_unlock(page_table, ptl); out_page: unlock_page(page); out_release: page_cache_release(page); if (swapcache) { unlock_page(swapcache); page_cache_release(swapcache); } return ret; } /* * This is like a special single-page "expand_{down|up}wards()", * except we must first make sure that 'address{-|+}PAGE_SIZE' * doesn't hit another vma. */ static inline int check_stack_guard_page(struct vm_area_struct *vma, unsigned long address) { address &= PAGE_MASK; if ((vma->vm_flags & VM_GROWSDOWN) && address == vma->vm_start) { struct vm_area_struct *prev = vma->vm_prev; /* * Is there a mapping abutting this one below? * * That's only ok if it's the same stack mapping * that has gotten split.. */ if (prev && prev->vm_end == address) return prev->vm_flags & VM_GROWSDOWN ? 0 : -ENOMEM; expand_downwards(vma, address - PAGE_SIZE); } if ((vma->vm_flags & VM_GROWSUP) && address + PAGE_SIZE == vma->vm_end) { struct vm_area_struct *next = vma->vm_next; /* As VM_GROWSDOWN but s/below/above/ */ if (next && next->vm_start == address + PAGE_SIZE) return next->vm_flags & VM_GROWSUP ? 0 : -ENOMEM; expand_upwards(vma, address + PAGE_SIZE); } return 0; } /* * We enter with non-exclusive mmap_sem (to exclude vma changes, * but allow concurrent faults), and pte mapped but not yet locked. * We return with mmap_sem still held, but pte unmapped and unlocked. */ static int do_anonymous_page(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, unsigned int flags) { struct page *page; spinlock_t *ptl; pte_t entry; pte_unmap(page_table); /* Check if we need to add a guard page to the stack */ if (check_stack_guard_page(vma, address) < 0) return VM_FAULT_SIGBUS; /* Use the zero-page for reads */ if (!(flags & FAULT_FLAG_WRITE)) { entry = pte_mkspecial(pfn_pte(my_zero_pfn(address), vma->vm_page_prot)); page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (!pte_none(*page_table)) goto unlock; goto setpte; } /* Allocate our own private page. */ if (unlikely(anon_vma_prepare(vma))) goto oom; page = alloc_zeroed_user_highpage_movable(vma, address); if (!page) goto oom; __SetPageUptodate(page); if (mem_cgroup_newpage_charge(page, mm, GFP_KERNEL)) goto oom_free_page; entry = mk_pte(page, vma->vm_page_prot); if (vma->vm_flags & VM_WRITE) entry = pte_mkwrite(pte_mkdirty(entry)); page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (!pte_none(*page_table)) goto release; inc_mm_counter_fast(mm, MM_ANONPAGES); page_add_new_anon_rmap(page, vma, address); setpte: set_pte_at(mm, address, page_table, entry); /* No need to invalidate - it was non-present before */ update_mmu_cache(vma, address, page_table); unlock: pte_unmap_unlock(page_table, ptl); return 0; release: mem_cgroup_uncharge_page(page); page_cache_release(page); goto unlock; oom_free_page: page_cache_release(page); oom: return VM_FAULT_OOM; } /* * __do_fault() tries to create a new page mapping. It aggressively * tries to share with existing pages, but makes a separate copy if * the FAULT_FLAG_WRITE is set in the flags parameter in order to avoid * the next page fault. * * As this is called only for pages that do not currently exist, we * do not need to flush old virtual caches or the TLB. * * We enter with non-exclusive mmap_sem (to exclude vma changes, * but allow concurrent faults), and pte neither mapped nor locked. * We return with mmap_sem still held, but pte unmapped and unlocked. */ static int __do_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pmd_t *pmd, pgoff_t pgoff, unsigned int flags, pte_t orig_pte) { pte_t *page_table; spinlock_t *ptl; struct page *page; struct page *cow_page; pte_t entry; int anon = 0; struct page *dirty_page = NULL; struct vm_fault vmf; int ret; int page_mkwrite = 0; /* * If we do COW later, allocate page befor taking lock_page() * on the file cache page. This will reduce lock holding time. */ if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) { if (unlikely(anon_vma_prepare(vma))) return VM_FAULT_OOM; cow_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address); if (!cow_page) return VM_FAULT_OOM; if (mem_cgroup_newpage_charge(cow_page, mm, GFP_KERNEL)) { page_cache_release(cow_page); return VM_FAULT_OOM; } } else cow_page = NULL; vmf.virtual_address = (void __user *)(address & PAGE_MASK); vmf.pgoff = pgoff; vmf.flags = flags; vmf.page = NULL; ret = vma->vm_ops->fault(vma, &vmf); if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) goto uncharge_out; if (unlikely(PageHWPoison(vmf.page))) { if (ret & VM_FAULT_LOCKED) unlock_page(vmf.page); ret = VM_FAULT_HWPOISON; goto uncharge_out; } /* * For consistency in subsequent calls, make the faulted page always * locked. */ if (unlikely(!(ret & VM_FAULT_LOCKED))) lock_page(vmf.page); else VM_BUG_ON(!PageLocked(vmf.page)); /* * Should we do an early C-O-W break? */ page = vmf.page; if (flags & FAULT_FLAG_WRITE) { if (!(vma->vm_flags & VM_SHARED)) { page = cow_page; anon = 1; copy_user_highpage(page, vmf.page, address, vma); __SetPageUptodate(page); } else { /* * If the page will be shareable, see if the backing * address space wants to know that the page is about * to become writable */ if (vma->vm_ops->page_mkwrite) { int tmp; unlock_page(page); vmf.flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE; tmp = vma->vm_ops->page_mkwrite(vma, &vmf); if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) { ret = tmp; goto unwritable_page; } if (unlikely(!(tmp & VM_FAULT_LOCKED))) { lock_page(page); if (!page->mapping) { ret = 0; /* retry the fault */ unlock_page(page); goto unwritable_page; } } else VM_BUG_ON(!PageLocked(page)); page_mkwrite = 1; } } } page_table = pte_offset_map_lock(mm, pmd, address, &ptl); /* * This silly early PAGE_DIRTY setting removes a race * due to the bad i386 page protection. But it's valid * for other architectures too. * * Note that if FAULT_FLAG_WRITE is set, we either now have * an exclusive copy of the page, or this is a shared mapping, * so we can make it writable and dirty to avoid having to * handle that later. */ /* Only go through if we didn't race with anybody else... */ if (likely(pte_same(*page_table, orig_pte))) { flush_icache_page(vma, page); entry = mk_pte(page, vma->vm_page_prot); if (flags & FAULT_FLAG_WRITE) entry = maybe_mkwrite(pte_mkdirty(entry), vma); if (anon) { inc_mm_counter_fast(mm, MM_ANONPAGES); page_add_new_anon_rmap(page, vma, address); } else { inc_mm_counter_fast(mm, MM_FILEPAGES); page_add_file_rmap(page); if (flags & FAULT_FLAG_WRITE) { dirty_page = page; get_page(dirty_page); } } set_pte_at(mm, address, page_table, entry); /* no need to invalidate: a not-present page won't be cached */ update_mmu_cache(vma, address, page_table); } else { if (cow_page) mem_cgroup_uncharge_page(cow_page); if (anon) page_cache_release(page); else anon = 1; /* no anon but release faulted_page */ } pte_unmap_unlock(page_table, ptl); if (dirty_page) { struct address_space *mapping = page->mapping; if (set_page_dirty(dirty_page)) page_mkwrite = 1; unlock_page(dirty_page); put_page(dirty_page); if (page_mkwrite && mapping) { /* * Some device drivers do not set page.mapping but still * dirty their pages */ balance_dirty_pages_ratelimited(mapping); } /* file_update_time outside page_lock */ if (vma->vm_file) file_update_time(vma->vm_file); } else { unlock_page(vmf.page); if (anon) page_cache_release(vmf.page); } return ret; unwritable_page: page_cache_release(page); return ret; uncharge_out: /* fs's fault handler get error */ if (cow_page) { mem_cgroup_uncharge_page(cow_page); page_cache_release(cow_page); } return ret; } static int do_linear_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, unsigned int flags, pte_t orig_pte) { pgoff_t pgoff = (((address & PAGE_MASK) - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff; pte_unmap(page_table); return __do_fault(mm, vma, address, pmd, pgoff, flags, orig_pte); } /* * Fault of a previously existing named mapping. Repopulate the pte * from the encoded file_pte if possible. This enables swappable * nonlinear vmas. * * We enter with non-exclusive mmap_sem (to exclude vma changes, * but allow concurrent faults), and pte mapped but not yet locked. * We return with mmap_sem still held, but pte unmapped and unlocked. */ static int do_nonlinear_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, unsigned int flags, pte_t orig_pte) { pgoff_t pgoff; flags |= FAULT_FLAG_NONLINEAR; if (!pte_unmap_same(mm, pmd, page_table, orig_pte)) return 0; if (unlikely(!(vma->vm_flags & VM_NONLINEAR))) { /* * Page table corrupted: show pte and kill process. */ print_bad_pte(vma, address, orig_pte, NULL); return VM_FAULT_SIGBUS; } pgoff = pte_to_pgoff(orig_pte); return __do_fault(mm, vma, address, pmd, pgoff, flags, orig_pte); } /* * These routines also need to handle stuff like marking pages dirty * and/or accessed for architectures that don't do it in hardware (most * RISC architectures). The early dirtying is also good on the i386. * * There is also a hook called "update_mmu_cache()" that architectures * with external mmu caches can use to update those (ie the Sparc or * PowerPC hashed page tables that act as extended TLBs). * * We enter with non-exclusive mmap_sem (to exclude vma changes, * but allow concurrent faults), and pte mapped but not yet locked. * We return with mmap_sem still held, but pte unmapped and unlocked. */ int handle_pte_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *pte, pmd_t *pmd, unsigned int flags) { pte_t entry; spinlock_t *ptl; entry = *pte; if (!pte_present(entry)) { if (pte_none(entry)) { if (vma->vm_ops) { if (likely(vma->vm_ops->fault)) return do_linear_fault(mm, vma, address, pte, pmd, flags, entry); } return do_anonymous_page(mm, vma, address, pte, pmd, flags); } if (pte_file(entry)) return do_nonlinear_fault(mm, vma, address, pte, pmd, flags, entry); return do_swap_page(mm, vma, address, pte, pmd, flags, entry); } ptl = pte_lockptr(mm, pmd); spin_lock(ptl); if (unlikely(!pte_same(*pte, entry))) goto unlock; if (flags & FAULT_FLAG_WRITE) { if (!pte_write(entry)) return do_wp_page(mm, vma, address, pte, pmd, ptl, entry); entry = pte_mkdirty(entry); } entry = pte_mkyoung(entry); if (ptep_set_access_flags(vma, address, pte, entry, flags & FAULT_FLAG_WRITE)) { update_mmu_cache(vma, address, pte); } else { /* * This is needed only for protection faults but the arch code * is not yet telling us if this is a protection fault or not. * This still avoids useless tlb flushes for .text page faults * with threads. */ if (flags & FAULT_FLAG_WRITE) flush_tlb_fix_spurious_fault(vma, address); } unlock: pte_unmap_unlock(pte, ptl); return 0; } /* * By the time we get here, we already hold the mm semaphore */ int handle_mm_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, unsigned int flags) { pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t *pte; __set_current_state(TASK_RUNNING); count_vm_event(PGFAULT); mem_cgroup_count_vm_event(mm, PGFAULT); /* do counter updates before entering really critical section. */ check_sync_rss_stat(current); if (unlikely(is_vm_hugetlb_page(vma))) return hugetlb_fault(mm, vma, address, flags); pgd = pgd_offset(mm, address); pud = pud_alloc(mm, pgd, address); if (!pud) return VM_FAULT_OOM; pmd = pmd_alloc(mm, pud, address); if (!pmd) return VM_FAULT_OOM; if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) { if (!vma->vm_ops) return do_huge_pmd_anonymous_page(mm, vma, address, pmd, flags); } else { pmd_t orig_pmd = *pmd; barrier(); if (pmd_trans_huge(orig_pmd)) { if (flags & FAULT_FLAG_WRITE && !pmd_write(orig_pmd) && !pmd_trans_splitting(orig_pmd)) return do_huge_pmd_wp_page(mm, vma, address, pmd, orig_pmd); return 0; } } /* * Use __pte_alloc instead of pte_alloc_map, because we can't * run pte_offset_map on the pmd, if an huge pmd could * materialize from under us from a different thread. */ if (unlikely(pmd_none(*pmd)) && __pte_alloc(mm, vma, pmd, address)) return VM_FAULT_OOM; /* if an huge pmd materialized from under us just retry later */ if (unlikely(pmd_trans_huge(*pmd))) return 0; /* * A regular pmd is established and it can't morph into a huge pmd * from under us anymore at this point because we hold the mmap_sem * read mode and khugepaged takes it in write mode. So now it's * safe to run pte_offset_map(). */ pte = pte_offset_map(pmd, address); return handle_pte_fault(mm, vma, address, pte, pmd, flags); } #ifndef __PAGETABLE_PUD_FOLDED /* * Allocate page upper directory. * We've already handled the fast-path in-line. */ int __pud_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address) { pud_t *new = pud_alloc_one(mm, address); if (!new) return -ENOMEM; smp_wmb(); /* See comment in __pte_alloc */ spin_lock(&mm->page_table_lock); if (pgd_present(*pgd)) /* Another has populated it */ pud_free(mm, new); else pgd_populate(mm, pgd, new); spin_unlock(&mm->page_table_lock); return 0; } #endif /* __PAGETABLE_PUD_FOLDED */ #ifndef __PAGETABLE_PMD_FOLDED /* * Allocate page middle directory. * We've already handled the fast-path in-line. */ int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address) { pmd_t *new = pmd_alloc_one(mm, address); if (!new) return -ENOMEM; smp_wmb(); /* See comment in __pte_alloc */ spin_lock(&mm->page_table_lock); #ifndef __ARCH_HAS_4LEVEL_HACK if (pud_present(*pud)) /* Another has populated it */ pmd_free(mm, new); else pud_populate(mm, pud, new); #else if (pgd_present(*pud)) /* Another has populated it */ pmd_free(mm, new); else pgd_populate(mm, pud, new); #endif /* __ARCH_HAS_4LEVEL_HACK */ spin_unlock(&mm->page_table_lock); return 0; } #endif /* __PAGETABLE_PMD_FOLDED */ int make_pages_present(unsigned long addr, unsigned long end) { int ret, len, write; struct vm_area_struct * vma; vma = find_vma(current->mm, addr); if (!vma) return -ENOMEM; /* * We want to touch writable mappings with a write fault in order * to break COW, except for shared mappings because these don't COW * and we would not want to dirty them for nothing. */ write = (vma->vm_flags & (VM_WRITE | VM_SHARED)) == VM_WRITE; BUG_ON(addr >= end); BUG_ON(end > vma->vm_end); len = DIV_ROUND_UP(end, PAGE_SIZE) - addr/PAGE_SIZE; ret = get_user_pages(current, current->mm, addr, len, write, 0, NULL, NULL); if (ret < 0) return ret; return ret == len ? 0 : -EFAULT; } #if !defined(__HAVE_ARCH_GATE_AREA) #if defined(AT_SYSINFO_EHDR) static struct vm_area_struct gate_vma; static int __init gate_vma_init(void) { gate_vma.vm_mm = NULL; gate_vma.vm_start = FIXADDR_USER_START; gate_vma.vm_end = FIXADDR_USER_END; gate_vma.vm_flags = VM_READ | VM_MAYREAD | VM_EXEC | VM_MAYEXEC; gate_vma.vm_page_prot = __P101; return 0; } __initcall(gate_vma_init); #endif struct vm_area_struct *get_gate_vma(struct mm_struct *mm) { #ifdef AT_SYSINFO_EHDR return &gate_vma; #else return NULL; #endif } int in_gate_area_no_mm(unsigned long addr) { #ifdef AT_SYSINFO_EHDR if ((addr >= FIXADDR_USER_START) && (addr < FIXADDR_USER_END)) return 1; #endif return 0; } #endif /* __HAVE_ARCH_GATE_AREA */ static int __follow_pte(struct mm_struct *mm, unsigned long address, pte_t **ptepp, spinlock_t **ptlp) { pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t *ptep; pgd = pgd_offset(mm, address); if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd))) goto out; pud = pud_offset(pgd, address); if (pud_none(*pud) || unlikely(pud_bad(*pud))) goto out; pmd = pmd_offset(pud, address); VM_BUG_ON(pmd_trans_huge(*pmd)); if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd))) goto out; /* We cannot handle huge page PFN maps. Luckily they don't exist. */ if (pmd_huge(*pmd)) goto out; ptep = pte_offset_map_lock(mm, pmd, address, ptlp); if (!ptep) goto out; if (!pte_present(*ptep)) goto unlock; *ptepp = ptep; return 0; unlock: pte_unmap_unlock(ptep, *ptlp); out: return -EINVAL; } static inline int follow_pte(struct mm_struct *mm, unsigned long address, pte_t **ptepp, spinlock_t **ptlp) { int res; /* (void) is needed to make gcc happy */ (void) __cond_lock(*ptlp, !(res = __follow_pte(mm, address, ptepp, ptlp))); return res; } /** * follow_pfn - look up PFN at a user virtual address * @vma: memory mapping * @address: user virtual address * @pfn: location to store found PFN * * Only IO mappings and raw PFN mappings are allowed. * * Returns zero and the pfn at @pfn on success, -ve otherwise. */ int follow_pfn(struct vm_area_struct *vma, unsigned long address, unsigned long *pfn) { int ret = -EINVAL; spinlock_t *ptl; pte_t *ptep; if (!(vma->vm_flags & (VM_IO | VM_PFNMAP))) return ret; ret = follow_pte(vma->vm_mm, address, &ptep, &ptl); if (ret) return ret; *pfn = pte_pfn(*ptep); pte_unmap_unlock(ptep, ptl); return 0; } EXPORT_SYMBOL(follow_pfn); #ifdef CONFIG_HAVE_IOREMAP_PROT int follow_phys(struct vm_area_struct *vma, unsigned long address, unsigned int flags, unsigned long *prot, resource_size_t *phys) { int ret = -EINVAL; pte_t *ptep, pte; spinlock_t *ptl; if (!(vma->vm_flags & (VM_IO | VM_PFNMAP))) goto out; if (follow_pte(vma->vm_mm, address, &ptep, &ptl)) goto out; pte = *ptep; if ((flags & FOLL_WRITE) && !pte_write(pte)) goto unlock; *prot = pgprot_val(pte_pgprot(pte)); *phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT; ret = 0; unlock: pte_unmap_unlock(ptep, ptl); out: return ret; } int generic_access_phys(struct vm_area_struct *vma, unsigned long addr, void *buf, int len, int write) { resource_size_t phys_addr; unsigned long prot = 0; void __iomem *maddr; int offset = addr & (PAGE_SIZE-1); if (follow_phys(vma, addr, write, &prot, &phys_addr)) return -EINVAL; maddr = ioremap_prot(phys_addr, PAGE_SIZE, prot); if (write) memcpy_toio(maddr + offset, buf, len); else memcpy_fromio(buf, maddr + offset, len); iounmap(maddr); return len; } #endif /* * Access another process' address space as given in mm. If non-NULL, use the * given task for page fault accounting. */ static int __access_remote_vm(struct task_struct *tsk, struct mm_struct *mm, unsigned long addr, void *buf, int len, int write) { struct vm_area_struct *vma; void *old_buf = buf; down_read(&mm->mmap_sem); /* ignore errors, just check how much was successfully transferred */ while (len) { int bytes, ret, offset; void *maddr; struct page *page = NULL; ret = get_user_pages(tsk, mm, addr, 1, write, 1, &page, &vma); if (ret <= 0) { /* * Check if this is a VM_IO | VM_PFNMAP VMA, which * we can access using slightly different code. */ #ifdef CONFIG_HAVE_IOREMAP_PROT vma = find_vma(mm, addr); if (!vma || vma->vm_start > addr) break; if (vma->vm_ops && vma->vm_ops->access) ret = vma->vm_ops->access(vma, addr, buf, len, write); if (ret <= 0) #endif break; bytes = ret; } else { bytes = len; offset = addr & (PAGE_SIZE-1); if (bytes > PAGE_SIZE-offset) bytes = PAGE_SIZE-offset; maddr = kmap(page); if (write) { copy_to_user_page(vma, page, addr, maddr + offset, buf, bytes); set_page_dirty_lock(page); } else { copy_from_user_page(vma, page, addr, buf, maddr + offset, bytes); } kunmap(page); page_cache_release(page); } len -= bytes; buf += bytes; addr += bytes; } up_read(&mm->mmap_sem); return buf - old_buf; } /** * access_remote_vm - access another process' address space * @mm: the mm_struct of the target address space * @addr: start address to access * @buf: source or destination buffer * @len: number of bytes to transfer * @write: whether the access is a write * * The caller must hold a reference on @mm. */ int access_remote_vm(struct mm_struct *mm, unsigned long addr, void *buf, int len, int write) { return __access_remote_vm(NULL, mm, addr, buf, len, write); } /* * Access another process' address space. * Source/target buffer must be kernel space, * Do not walk the page table directly, use get_user_pages */ int access_process_vm(struct task_struct *tsk, unsigned long addr, void *buf, int len, int write) { struct mm_struct *mm; int ret; mm = get_task_mm(tsk); if (!mm) return 0; ret = __access_remote_vm(tsk, mm, addr, buf, len, write); mmput(mm); return ret; } /* * Print the name of a VMA. */ void print_vma_addr(char *prefix, unsigned long ip) { struct mm_struct *mm = current->mm; struct vm_area_struct *vma; /* * Do not print if we are in atomic * contexts (in exception stacks, etc.): */ if (preempt_count()) return; down_read(&mm->mmap_sem); vma = find_vma(mm, ip); if (vma && vma->vm_file) { struct file *f = vma->vm_file; char *buf = (char *)__get_free_page(GFP_KERNEL); if (buf) { char *p, *s; p = d_path(&f->f_path, buf, PAGE_SIZE); if (IS_ERR(p)) p = "?"; s = strrchr(p, '/'); if (s) p = s+1; printk("%s%s[%lx+%lx]", prefix, p, vma->vm_start, vma->vm_end - vma->vm_start); free_page((unsigned long)buf); } } up_read(&current->mm->mmap_sem); } #ifdef CONFIG_PROVE_LOCKING void might_fault(void) { /* * Some code (nfs/sunrpc) uses socket ops on kernel memory while * holding the mmap_sem, this is safe because kernel memory doesn't * get paged out, therefore we'll never actually fault, and the * below annotations will generate false positives. */ if (segment_eq(get_fs(), KERNEL_DS)) return; might_sleep(); /* * it would be nicer only to annotate paths which are not under * pagefault_disable, however that requires a larger audit and * providing helpers like get_user_atomic. */ if (!in_atomic() && current->mm) might_lock_read(&current->mm->mmap_sem); } EXPORT_SYMBOL(might_fault); #endif #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS) static void clear_gigantic_page(struct page *page, unsigned long addr, unsigned int pages_per_huge_page) { int i; struct page *p = page; might_sleep(); for (i = 0; i < pages_per_huge_page; i++, p = mem_map_next(p, page, i)) { cond_resched(); clear_user_highpage(p, addr + i * PAGE_SIZE); } } void clear_huge_page(struct page *page, unsigned long addr, unsigned int pages_per_huge_page) { int i; if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) { clear_gigantic_page(page, addr, pages_per_huge_page); return; } might_sleep(); for (i = 0; i < pages_per_huge_page; i++) { cond_resched(); clear_user_highpage(page + i, addr + i * PAGE_SIZE); } } static void copy_user_gigantic_page(struct page *dst, struct page *src, unsigned long addr, struct vm_area_struct *vma, unsigned int pages_per_huge_page) { int i; struct page *dst_base = dst; struct page *src_base = src; for (i = 0; i < pages_per_huge_page; ) { cond_resched(); copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma); i++; dst = mem_map_next(dst, dst_base, i); src = mem_map_next(src, src_base, i); } } void copy_user_huge_page(struct page *dst, struct page *src, unsigned long addr, struct vm_area_struct *vma, unsigned int pages_per_huge_page) { int i; if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) { copy_user_gigantic_page(dst, src, addr, vma, pages_per_huge_page); return; } might_sleep(); for (i = 0; i < pages_per_huge_page; i++) { cond_resched(); copy_user_highpage(dst + i, src + i, addr + i*PAGE_SIZE, vma); } } #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
gpl-2.0
empeg/empeg-hijack
fs/reiserfs/utils/include/reiserfs.h
914
/* * Copyright 2000 Hans Reiser */ // // ./fs/reiserfs/utils/lib/reiserfs.c // int not_formatted_node (char * buf, int blocksize); int not_data_block (struct super_block * s, b_blocknr_t block); int uread_super_block (struct super_block * s); int uread_bitmaps (struct super_block * s); #define bh_desc(bh) ((struct reiserfs_journal_desc *)((bh)->b_data)) #define bh_commit(bh) ((struct reiserfs_journal_commit *)((bh)->b_data)) int get_journal_start (struct super_block * s); int get_journal_size (struct super_block * s); int is_desc_block (struct buffer_head * bh); int does_desc_match_commit (struct reiserfs_journal_desc * desc, struct reiserfs_journal_commit * commit); void make_dir_stat_data (struct key * dir_key, struct item_head * ih, struct stat_data * sd); void make_empty_dir_item (char * body, objectid_t dirid, objectid_t objid, objectid_t par_dirid, objectid_t par_objid);
gpl-2.0
napoleon789/qlkh
osv/protected/modules/employees/controllers/EmployeesSubjectsController.php
6334
<?php class EmployeesSubjectsController extends RController { /** * @var string the default layout for the views. Defaults to '//layouts/column2', meaning * using two-column layout. See 'protected/views/layouts/column2.php'. */ public $layout='//layouts/column2'; /** * @return array action filters */ public function filters() { return array( 'rights', // perform access control for CRUD operations ); } /** * Specifies the access control rules. * This method is used by the 'accessControl' filter. * @return array access control rules */ public function accessRules() { return array( array('allow', // allow all users to perform 'index' and 'view' actions 'actions'=>array('index','view','Assign','Deleterow'), 'users'=>array('*'), ), array('allow', // allow authenticated user to perform 'create' and 'update' actions 'actions'=>array('create','update','subject','current','remove','employee'), 'users'=>array('@'), ), array('allow', // allow admin user to perform 'admin' and 'delete' actions 'actions'=>array('admin','delete'), 'users'=>array('admin'), ), array('deny', // deny all users 'users'=>array('*'), ), ); } /** * Displays a particular model. * @param integer $id the ID of the model to be displayed */ public function actionView($id) { $this->render('view',array( 'model'=>$this->loadModel($id), )); } /** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model=new EmployeesSubjects; // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if(isset($_POST['EmployeesSubjects'])) { $model->attributes=$_POST['EmployeesSubjects']; if($model->save()) $this->redirect(array('view','id'=>$model->id)); } $this->render('create',array( 'model'=>$model, )); } /** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model=$this->loadModel($id); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if(isset($_POST['EmployeesSubjects'])) { $model->attributes=$_POST['EmployeesSubjects']; if($model->save()) $this->redirect(array('view','id'=>$model->id)); } $this->render('update',array( 'model'=>$model, )); } public function actionDeleterow() { $postRecord = EmployeesSubjects::model()->findByPk($_REQUEST['id']); $postRecord->delete(); $this->redirect(array('create','cou'=>$_REQUEST['cou'],'sub'=>$_REQUEST['sub'],'dept'=>$_REQUEST['dept'])); } /** * Deletes a particular model. * If deletion is successful, the browser will be redirected to the 'admin' page. * @param integer $id the ID of the model to be deleted */ public function actionDelete($id) { if(Yii::app()->request->isPostRequest) { // we only allow deletion via POST request $this->loadModel($id)->delete(); // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser if(!isset($_GET['ajax'])) $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin')); } else throw new CHttpException(400,'Invalid request. Please do not repeat this request again.'); } /** * Lists all models. */ public function actionIndex() { $dataProvider=new CActiveDataProvider('EmployeesSubjects'); $this->render('index',array( 'dataProvider'=>$dataProvider, )); } public function actionAssign() { $model = new EmployeesSubjects; $model->employee_id = $_REQUEST['emp_id']; $model->subject_id = $_REQUEST['sub']; $model->save(); $this->redirect(array('create','cou'=>$_REQUEST['cou'],'sub'=>$_REQUEST['sub'],'dept'=>$_REQUEST['dept'])); } /** * Manages all models. */ public function actionAdmin() { $model=new EmployeesSubjects('search'); $model->unsetAttributes(); // clear any default values if(isset($_GET['EmployeesSubjects'])) $model->attributes=$_GET['EmployeesSubjects']; $this->render('admin',array( 'model'=>$model, )); } /** * Returns the data model based on the primary key given in the GET variable. * If the data model is not found, an HTTP exception will be raised. * @param integer the ID of the model to be loaded */ public function loadModel($id) { $model=EmployeesSubjects::model()->findByPk($id); if($model===null) throw new CHttpException(404,'The requested page does not exist.'); return $model; } /** * Performs the AJAX validation. * @param CModel the model to be validated */ protected function performAjaxValidation($model) { if(isset($_POST['ajax']) && $_POST['ajax']==='employees-subjects-form') { echo CActiveForm::validate($model); Yii::app()->end(); } } public function actionSubject() { $data=Subjects::model()->findAll(array('join' => 'JOIN batches ON batch_id = batches.id','condition'=>'batches.course_id=:id', 'params'=>array(':id'=>(int) $_POST['id']))); $data=CHtml::listData($data,'id','name'); foreach($data as $value=>$name) { echo CHtml::tag('option', array('value'=>$value),CHtml::encode($name),true); } } public function actionEmployee() { $data=Employees::model()->findAll(array('order'=>'first_name DESC','condition'=>'employee_department_id=:id', 'params'=>array(':id'=>(int) $_POST['did']))); $data=CHtml::listData($data,'id','first_name'); foreach($data as $value=>$name) { echo CHtml::tag('option', array('value'=>$value),CHtml::encode($name),true); } } public function actionCurrent() { if(isset($_POST['EmployeesSubjects']['subject_id'])) { $this->renderPartial('assign',array('subject_id' =>$_POST['EmployeesSubjects']['subject_id'])); } else { echo 'remove'; } } public function actionRemove() { EmployeesSubjects::model()->findByAttributes(array('subject_id'=>$_REQUEST['subject_id'],'employee_id'=>$_REQUEST['employee_id']))->delete(); $this->redirect(Yii::app()->createUrl('EmployeesSubjects/create')); } }
gpl-2.0
mlloewen/chinhama
wp-content/themes/rakiya/content/content.php
1824
<article <?php hybrid_attr( 'post' ); ?>> <?php if ( is_singular( get_post_type() ) ) : // If viewing a single post. ?> <header class="entry-header"> <h1 <?php hybrid_attr( 'entry-title' ); ?>><?php single_post_title(); ?></h1> <?php hybrid_post_terms( array( 'taxonomy' => 'category' ) ); ?> <div class="entry-byline"> </div><!-- .entry-byline --> </header><!-- .entry-header --> <div <?php hybrid_attr( 'entry-content' ); ?>> <?php the_content(); ?> <?php wp_link_pages(); ?> </div><!-- .entry-content --> <footer class="entry-footer"> <time <?php hybrid_attr( 'entry-published' ); ?>><?php echo get_the_date(); ?></time> <?php esc_html_e('by', 'rakiya' ); ?> <span <?php hybrid_attr( 'entry-author' ); ?>><?php the_author_posts_link(); ?></span> <?php edit_post_link(); ?> <?php hybrid_post_terms( array( 'taxonomy' => 'post_tag', 'text' => esc_html__( 'Tagged: %s', 'rakiya' ), 'before' => '<br />' ) ); ?> </footer><!-- .entry-footer --> <?php else : // If not viewing a single post. ?> <?php get_the_image(); ?> <header class="entry-header"> <?php the_title( '<h2 ' . hybrid_get_attr( 'entry-title' ) . '><a href="' . get_permalink() . '" rel="bookmark" itemprop="url">', '</a></h2>' ); ?> <?php hybrid_post_terms( array( 'taxonomy' => 'category' ) ); ?> </header><!-- .entry-header --> <div <?php hybrid_attr( 'entry-summary' ); ?>> <?php the_excerpt(); ?> </div><!-- .entry-summary --> <footer class="entry-footer"> <time <?php hybrid_attr( 'entry-published' ); ?>><?php echo get_the_date(); ?></time> <?php esc_html_e( 'by', 'rakiya' ); ?> <span <?php hybrid_attr( 'entry-author' ); ?>><?php the_author_posts_link(); ?></span> </footer> <?php endif; // End single post check. ?> </article><!-- .entry -->
gpl-2.0
Beau-M/document-management-system
src/main/java/com/openkm/api/OKMRepository.java
8219
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2017 Paco Avila & Josep Llort * <p> * No bytes were intentionally harmed during the development of this application. * <p> * 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. * <p> * 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. * <p> * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.api; import com.openkm.bean.AppVersion; import com.openkm.bean.ExtendedAttributes; import com.openkm.bean.Folder; import com.openkm.core.*; import com.openkm.module.ModuleManager; import com.openkm.module.RepositoryModule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class OKMRepository implements RepositoryModule { private static Logger log = LoggerFactory.getLogger(OKMRepository.class); private static OKMRepository instance = new OKMRepository(); private OKMRepository() { } public static OKMRepository getInstance() { return instance; } @Override public Folder getRootFolder(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getRootFolder({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); Folder rootFolder = rm.getRootFolder(token); log.debug("getRootFolder: {}", rootFolder); return rootFolder; } @Override public Folder getTrashFolder(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getTrashFolder({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); Folder trashFolder = rm.getTrashFolder(token); log.debug("getTrashFolder: {}", trashFolder); return trashFolder; } @Override public Folder getTrashFolderBase(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getTrashFolderBase({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); Folder trashFolder = rm.getTrashFolderBase(token); log.debug("getTrashFolderBase: {}", trashFolder); return trashFolder; } @Override public Folder getTemplatesFolder(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getTemplatesFolder({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); Folder templatesFolder = rm.getTemplatesFolder(token); log.debug("getTemplatesFolder: {}", templatesFolder); return templatesFolder; } @Override public Folder getPersonalFolder(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getPersonalFolder({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); Folder personalFolder = rm.getPersonalFolder(token); log.debug("getPersonalFolder: {}", personalFolder); return personalFolder; } @Override public Folder getPersonalFolderBase(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getPersonalFolderBase({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); Folder personalFolder = rm.getPersonalFolderBase(token); log.debug("getPersonalFolderBase: {}", personalFolder); return personalFolder; } @Override public Folder getMailFolder(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getMailFolder({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); Folder mailFolder = rm.getMailFolder(token); log.debug("getMailFolder: {}", mailFolder); return mailFolder; } @Override public Folder getMailFolderBase(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getMailFolderBase({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); Folder mailFolder = rm.getMailFolderBase(token); log.debug("getMailFolderBase: {}", mailFolder); return mailFolder; } @Override public Folder getThesaurusFolder(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getThesaurusFolder({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); Folder thesaurusFolder = rm.getThesaurusFolder(token); log.debug("getThesaurusFolder: {}", thesaurusFolder); return thesaurusFolder; } @Override public Folder getCategoriesFolder(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getCategoriesFolder({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); Folder categoriesFolder = rm.getCategoriesFolder(token); log.debug("getCategoriesFolder: {}", categoriesFolder); return categoriesFolder; } @Override public void purgeTrash(String token) throws PathNotFoundException, AccessDeniedException, LockException, RepositoryException, DatabaseException { log.debug("purgeTrash({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); rm.purgeTrash(token); log.debug("purgeTrash: void"); } @Override public String getUpdateMessage(String token) throws RepositoryException { log.debug("getUpdateMessage({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); String updateMessage = rm.getUpdateMessage(token); log.debug("getUpdateMessage: {}", updateMessage); return updateMessage; } @Override public String getRepositoryUuid(String token) throws RepositoryException { log.debug("getRepositoryUuid({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); String uuid = rm.getRepositoryUuid(token); log.debug("getRepositoryUuid: {}", uuid); return uuid; } @Override public boolean hasNode(String token, String path) throws AccessDeniedException, RepositoryException, DatabaseException { log.debug("hasNode({})", token, path); RepositoryModule rm = ModuleManager.getRepositoryModule(); boolean ret = rm.hasNode(token, path); log.debug("hasNode: {}", ret); return ret; } @Override public String getNodePath(String token, String uuid) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getNodePath({}, {})", token, uuid); RepositoryModule rm = ModuleManager.getRepositoryModule(); String ret = rm.getNodePath(token, uuid); log.debug("getNodePath: {}", ret); return ret; } @Override public String getNodeUuid(String token, String path) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getNodeUuid({}, {})", token, path); RepositoryModule rm = ModuleManager.getRepositoryModule(); String ret = rm.getNodeUuid(token, path); log.debug("getNodeUuid: {}", ret); return ret; } public AppVersion getAppVersion(String token) throws AccessDeniedException, RepositoryException, DatabaseException { log.debug("getAppVersion({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); AppVersion ret = rm.getAppVersion(token); log.debug("getAppVersion: {}", ret); return ret; } @Override public void copyAttributes(String token, String srcId, String dstId, ExtendedAttributes extAttr) throws AccessDeniedException, PathNotFoundException, DatabaseException { log.debug("copyAttributes({}, {}, {}, {})", new Object[]{token, srcId, dstId, extAttr}); RepositoryModule rm = ModuleManager.getRepositoryModule(); rm.copyAttributes(token, srcId, dstId, extAttr); log.debug("copyAttributes: void"); } }
gpl-2.0
scottrcarlson/opendoom
src/hu_stuff.c
46050
/* Emacs style mode select -*- C++ -*- *----------------------------------------------------------------------------- * * * PrBoom: a Doom port merged with LxDoom and LSDLDoom * based on BOOM, a modified and improved DOOM engine * Copyright (C) 1999 by * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman * Copyright (C) 1999-2000 by * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze * Copyright 2005, 2006 by * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko * * 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. * * DESCRIPTION: Heads-up displays * *----------------------------------------------------------------------------- */ // killough 5/3/98: remove unnecessary headers #include "doomstat.h" #include "hu_stuff.h" #include "hu_lib.h" #include "st_stuff.h" /* jff 2/16/98 need loc of status bar */ #include "w_wad.h" #include "s_sound.h" #include "dstrings.h" #include "sounds.h" #include "d_deh.h" /* Ty 03/27/98 - externalization of mapnamesx arrays */ #include "g_game.h" #include "r_main.h" // global heads up display controls int hud_active; //jff 2/17/98 controls heads-up display mode int hud_displayed; //jff 2/23/98 turns heads-up display on/off int hud_nosecrets; //jff 2/18/98 allows secrets line to be disabled in HUD int hud_distributed; //jff 3/4/98 display HUD in different places on screen int hud_graph_keys=1; //jff 3/7/98 display HUD keys as graphics // // Locally used constants, shortcuts. // // Ty 03/28/98 - // These four shortcuts modifed to reflect char ** of mapnamesx[] #define HU_TITLE (*mapnames[(gameepisode-1)*9+gamemap-1]) #define HU_TITLE2 (*mapnames2[gamemap-1]) #define HU_TITLEP (*mapnamesp[gamemap-1]) #define HU_TITLET (*mapnamest[gamemap-1]) #define HU_TITLEHEIGHT 1 #define HU_TITLEX 0 //jff 2/16/98 change 167 to ST_Y-1 // CPhipps - changed to ST_TY // proff - changed to 200-ST_HEIGHT for stretching #define HU_TITLEY ((200-ST_HEIGHT) - 1 - hu_font[0].height) //jff 2/16/98 add coord text widget coordinates // proff - changed to SCREENWIDTH to 320 for stretching #define HU_COORDX (320 - 13*hu_font2['A'-HU_FONTSTART].width) //jff 3/3/98 split coord widget into three lines in upper right of screen #define HU_COORDX_Y (1 + 0*hu_font['A'-HU_FONTSTART].height) #define HU_COORDY_Y (2 + 1*hu_font['A'-HU_FONTSTART].height) #define HU_COORDZ_Y (3 + 2*hu_font['A'-HU_FONTSTART].height) //jff 2/16/98 add ammo, health, armor widgets, 2/22/98 less gap #define HU_GAPY 8 #define HU_HUDHEIGHT (6*HU_GAPY) #define HU_HUDX 2 #define HU_HUDY (200-HU_HUDHEIGHT-1) #define HU_MONSECX (HU_HUDX) #define HU_MONSECY (HU_HUDY+0*HU_GAPY) #define HU_KEYSX (HU_HUDX) //jff 3/7/98 add offset for graphic key widget #define HU_KEYSGX (HU_HUDX+4*hu_font2['A'-HU_FONTSTART].width) #define HU_KEYSY (HU_HUDY+1*HU_GAPY) #define HU_WEAPX (HU_HUDX) #define HU_WEAPY (HU_HUDY+2*HU_GAPY) #define HU_AMMOX (HU_HUDX) #define HU_AMMOY (HU_HUDY+3*HU_GAPY) #define HU_HEALTHX (HU_HUDX) #define HU_HEALTHY (HU_HUDY+4*HU_GAPY) #define HU_ARMORX (HU_HUDX) #define HU_ARMORY (HU_HUDY+5*HU_GAPY) //jff 3/4/98 distributed HUD positions #define HU_HUDX_LL 2 #define HU_HUDY_LL (200-2*HU_GAPY-1) // proff/nicolas 09/20/98: Changed for high-res #define HU_HUDX_LR (320-120) #define HU_HUDY_LR (200-2*HU_GAPY-1) // proff/nicolas 09/20/98: Changed for high-res #define HU_HUDX_UR (320-96) #define HU_HUDY_UR 2 #define HU_MONSECX_D (HU_HUDX_LL) #define HU_MONSECY_D (HU_HUDY_LL+0*HU_GAPY) #define HU_KEYSX_D (HU_HUDX_LL) #define HU_KEYSGX_D (HU_HUDX_LL+4*hu_font2['A'-HU_FONTSTART].width) #define HU_KEYSY_D (HU_HUDY_LL+1*HU_GAPY) #define HU_WEAPX_D (HU_HUDX_LR) #define HU_WEAPY_D (HU_HUDY_LR+0*HU_GAPY) #define HU_AMMOX_D (HU_HUDX_LR) #define HU_AMMOY_D (HU_HUDY_LR+1*HU_GAPY) #define HU_HEALTHX_D (HU_HUDX_UR) #define HU_HEALTHY_D (HU_HUDY_UR+0*HU_GAPY) #define HU_ARMORX_D (HU_HUDX_UR) #define HU_ARMORY_D (HU_HUDY_UR+1*HU_GAPY) //#define HU_INPUTTOGGLE 't' // not used // phares #define HU_INPUTX HU_MSGX #define HU_INPUTY (HU_MSGY + HU_MSGHEIGHT*(hu_font[0].height) +1) #define HU_INPUTWIDTH 64 #define HU_INPUTHEIGHT 1 #define key_alt KEYD_RALT #define key_shift KEYD_RSHIFT const char* chat_macros[] = // Ty 03/27/98 - *not* externalized // CPhipps - const char* { HUSTR_CHATMACRO0, HUSTR_CHATMACRO1, HUSTR_CHATMACRO2, HUSTR_CHATMACRO3, HUSTR_CHATMACRO4, HUSTR_CHATMACRO5, HUSTR_CHATMACRO6, HUSTR_CHATMACRO7, HUSTR_CHATMACRO8, HUSTR_CHATMACRO9 }; const char* player_names[] = // Ty 03/27/98 - *not* externalized // CPhipps - const char* { HUSTR_PLRGREEN, HUSTR_PLRINDIGO, HUSTR_PLRBROWN, HUSTR_PLRRED }; //jff 3/17/98 translate player colmap to text color ranges int plyrcoltran[MAXPLAYERS]={CR_GREEN,CR_GRAY,CR_BROWN,CR_RED}; char chat_char; // remove later. static player_t* plr; // font sets patchnum_t hu_font[HU_FONTSIZE]; patchnum_t hu_font2[HU_FONTSIZE]; patchnum_t hu_fontk[HU_FONTSIZE];//jff 3/7/98 added for graphic key indicators patchnum_t hu_msgbg[9]; //jff 2/26/98 add patches for message background // widgets static hu_textline_t w_title; static hu_stext_t w_message; static hu_itext_t w_chat; static hu_itext_t w_inputbuffer[MAXPLAYERS]; static hu_textline_t w_coordx; //jff 2/16/98 new coord widget for automap static hu_textline_t w_coordy; //jff 3/3/98 split coord widgets automap static hu_textline_t w_coordz; //jff 3/3/98 split coord widgets automap static hu_textline_t w_ammo; //jff 2/16/98 new ammo widget for hud static hu_textline_t w_health; //jff 2/16/98 new health widget for hud static hu_textline_t w_armor; //jff 2/16/98 new armor widget for hud static hu_textline_t w_weapon; //jff 2/16/98 new weapon widget for hud static hu_textline_t w_keys; //jff 2/16/98 new keys widget for hud static hu_textline_t w_gkeys; //jff 3/7/98 graphic keys widget for hud static hu_textline_t w_monsec; //jff 2/16/98 new kill/secret widget for hud static hu_mtext_t w_rtext; //jff 2/26/98 text message refresh widget static boolean always_off = false; static char chat_dest[MAXPLAYERS]; boolean chat_on; static boolean message_on; static boolean message_list; //2/26/98 enable showing list of messages boolean message_dontfuckwithme; static boolean message_nottobefuckedwith; static int message_counter; extern int showMessages; extern boolean automapactive; static boolean headsupactive = false; //jff 2/16/98 hud supported automap colors added int hudcolor_titl; // color range of automap level title int hudcolor_xyco; // color range of new coords on automap //jff 2/16/98 hud text colors, controls added int hudcolor_mesg; // color range of scrolling messages int hudcolor_chat; // color range of chat lines int hud_msg_lines; // number of message lines in window //jff 2/26/98 hud text colors, controls added int hudcolor_list; // list of messages color int hud_list_bgon; // enable for solid window background for message list //jff 2/16/98 initialization strings for ammo, health, armor widgets static char hud_coordstrx[32]; static char hud_coordstry[32]; static char hud_coordstrz[32]; static char hud_ammostr[80]; static char hud_healthstr[80]; static char hud_armorstr[80]; static char hud_weapstr[80]; static char hud_keysstr[80]; static char hud_gkeysstr[80]; //jff 3/7/98 add support for graphic key display static char hud_monsecstr[80]; // // Builtin map names. // The actual names can be found in DStrings.h. // // Ty 03/27/98 - externalized map name arrays - now in d_deh.c // and converted to arrays of pointers to char * // See modified HUTITLEx macros extern char **mapnames[]; extern char **mapnames2[]; extern char **mapnamesp[]; extern char **mapnamest[]; extern int map_point_coordinates; // key tables // jff 5/10/98 french support removed, // as it was not being used and couldn't be easily tested // const char* shiftxform; const char english_shiftxform[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, ' ', '!', '"', '#', '$', '%', '&', '"', // shift-' '(', ')', '*', '+', '<', // shift-, '_', // shift-- '>', // shift-. '?', // shift-/ ')', // shift-0 '!', // shift-1 '@', // shift-2 '#', // shift-3 '$', // shift-4 '%', // shift-5 '^', // shift-6 '&', // shift-7 '*', // shift-8 '(', // shift-9 ':', ':', // shift-; '<', '+', // shift-= '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', // shift-[ '!', // shift-backslash - OH MY GOD DOES WATCOM SUCK ']', // shift-] '"', '_', '\'', // shift-` 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '{', '|', '}', '~', 127 }; // // HU_Init() // // Initialize the heads-up display, text that overwrites the primary display // // Passed nothing, returns nothing // void HU_Init(void) { int i; int j; char buffer[9]; shiftxform = english_shiftxform; // load the heads-up font j = HU_FONTSTART; for (i=0;i<HU_FONTSIZE;i++,j++) { if ('0'<=j && j<='9') { sprintf(buffer, "DIG%.1d",j-48); R_SetPatchNum(&hu_font2[i], buffer); sprintf(buffer, "STCFN%.3d",j); R_SetPatchNum(&hu_font[i], buffer); } else if ('A'<=j && j<='Z') { sprintf(buffer, "DIG%c",j); R_SetPatchNum(&hu_font2[i], buffer); sprintf(buffer, "STCFN%.3d",j); R_SetPatchNum(&hu_font[i], buffer); } else if (j=='-') { R_SetPatchNum(&hu_font2[i], "DIG45"); R_SetPatchNum(&hu_font[i], "STCFN045"); } else if (j=='/') { R_SetPatchNum(&hu_font2[i], "DIG47"); R_SetPatchNum(&hu_font[i], "STCFN047"); } else if (j==':') { R_SetPatchNum(&hu_font2[i], "DIG58"); R_SetPatchNum(&hu_font[i], "STCFN058"); } else if (j=='[') { R_SetPatchNum(&hu_font2[i], "DIG91"); R_SetPatchNum(&hu_font[i], "STCFN091"); } else if (j==']') { R_SetPatchNum(&hu_font2[i], "DIG93"); R_SetPatchNum(&hu_font[i], "STCFN093"); } else if (j<97) { sprintf(buffer, "STCFN%.3d",j); R_SetPatchNum(&hu_font2[i], buffer); R_SetPatchNum(&hu_font[i], buffer); //jff 2/23/98 make all font chars defined, useful or not } else if (j>122) { sprintf(buffer, "STBR%.3d",j); R_SetPatchNum(&hu_font2[i], buffer); R_SetPatchNum(&hu_font[i], buffer); } else hu_font[i] = hu_font[0]; //jff 2/16/98 account for gap } // CPhipps - load patches for message background for (i=0; i<9; i++) { sprintf(buffer, "BOX%c%c", "UCL"[i/3], "LCR"[i%3]); R_SetPatchNum(&hu_msgbg[i], buffer); } // CPhipps - load patches for keys and double keys for (i=0; i<6; i++) { sprintf(buffer, "STKEYS%d", i); R_SetPatchNum(&hu_fontk[i], buffer); } } // // HU_Stop() // // Make the heads-up displays inactive // // Passed nothing, returns nothing // static void HU_Stop(void) { headsupactive = false; } // // HU_Start(void) // // Create and initialize the heads-up widgets, software machines to // maintain, update, and display information over the primary display // // This routine must be called after any change to the heads up configuration // in order for the changes to take effect in the actual displays // // Passed nothing, returns nothing // void HU_Start(void) { int i; const char* s; /* cph - const */ if (headsupactive) // stop before starting HU_Stop(); plr = &players[displayplayer]; // killough 3/7/98 message_on = false; message_dontfuckwithme = false; message_nottobefuckedwith = false; chat_on = false; // create the message widget // messages to player in upper-left of screen HUlib_initSText ( &w_message, HU_MSGX, HU_MSGY, HU_MSGHEIGHT, hu_font, HU_FONTSTART, hudcolor_mesg, &message_on ); //jff 2/16/98 added some HUD widgets // create the map title widget - map title display in lower left of automap HUlib_initTextLine ( &w_title, HU_TITLEX, HU_TITLEY, hu_font, HU_FONTSTART, hudcolor_titl ); // create the hud health widget // bargraph and number for amount of health, // lower left or upper right of screen HUlib_initTextLine ( &w_health, hud_distributed? HU_HEALTHX_D : HU_HEALTHX, //3/4/98 distribute hud_distributed? HU_HEALTHY_D : HU_HEALTHY, hu_font2, HU_FONTSTART, CR_GREEN ); // create the hud armor widget // bargraph and number for amount of armor, // lower left or upper right of screen HUlib_initTextLine ( &w_armor, hud_distributed? HU_ARMORX_D : HU_ARMORX, //3/4/98 distribute hud_distributed? HU_ARMORY_D : HU_ARMORY, hu_font2, HU_FONTSTART, CR_GREEN ); // create the hud ammo widget // bargraph and number for amount of ammo for current weapon, // lower left or lower right of screen HUlib_initTextLine ( &w_ammo, hud_distributed? HU_AMMOX_D : HU_AMMOX, //3/4/98 distribute hud_distributed? HU_AMMOY_D : HU_AMMOY, hu_font2, HU_FONTSTART, CR_GOLD ); // create the hud weapons widget // list of numbers of weapons possessed // lower left or lower right of screen HUlib_initTextLine ( &w_weapon, hud_distributed? HU_WEAPX_D : HU_WEAPX, //3/4/98 distribute hud_distributed? HU_WEAPY_D : HU_WEAPY, hu_font2, HU_FONTSTART, CR_GRAY ); // create the hud keys widget // display of key letters possessed // lower left of screen HUlib_initTextLine ( &w_keys, hud_distributed? HU_KEYSX_D : HU_KEYSX, //3/4/98 distribute hud_distributed? HU_KEYSY_D : HU_KEYSY, hu_font2, HU_FONTSTART, CR_GRAY ); // create the hud graphic keys widget // display of key graphics possessed // lower left of screen HUlib_initTextLine ( &w_gkeys, hud_distributed? HU_KEYSGX_D : HU_KEYSGX, //3/4/98 distribute hud_distributed? HU_KEYSY_D : HU_KEYSY, hu_fontk, HU_FONTSTART, CR_RED ); // create the hud monster/secret widget // totals and current values for kills, items, secrets // lower left of screen HUlib_initTextLine ( &w_monsec, hud_distributed? HU_MONSECX_D : HU_MONSECX, //3/4/98 distribute hud_distributed? HU_MONSECY_D : HU_MONSECY, hu_font2, HU_FONTSTART, CR_GRAY ); // create the hud text refresh widget // scrolling display of last hud_msg_lines messages received if (hud_msg_lines>HU_MAXMESSAGES) hud_msg_lines=HU_MAXMESSAGES; //jff 4/21/98 if setup has disabled message list while active, turn it off message_list = hud_msg_lines > 1; //jff 8/8/98 initialize both ways //jff 2/26/98 add the text refresh widget initialization HUlib_initMText ( &w_rtext, 0, 0, 320, // SCREENWIDTH, (hud_msg_lines+2)*HU_REFRESHSPACING, hu_font, HU_FONTSTART, hudcolor_list, hu_msgbg, &message_list ); // initialize the automap's level title widget if (gamestate == GS_LEVEL) /* cph - stop SEGV here when not in level */ switch (gamemode) { case shareware: case registered: case retail: s = HU_TITLE; break; case commercial: default: // Ty 08/27/98 - modified to check mission for TNT/Plutonia s = (gamemission==pack_tnt) ? HU_TITLET : (gamemission==pack_plut) ? HU_TITLEP : HU_TITLE2; break; } else s = ""; while (*s) HUlib_addCharToTextLine(&w_title, *(s++)); // create the automaps coordinate widget // jff 3/3/98 split coord widget into three lines: x,y,z // jff 2/16/98 added HUlib_initTextLine ( &w_coordx, HU_COORDX, HU_COORDX_Y, hu_font, HU_FONTSTART, hudcolor_xyco ); HUlib_initTextLine ( &w_coordy, HU_COORDX, HU_COORDY_Y, hu_font, HU_FONTSTART, hudcolor_xyco ); HUlib_initTextLine ( &w_coordz, HU_COORDX, HU_COORDZ_Y, hu_font, HU_FONTSTART, hudcolor_xyco ); // initialize the automaps coordinate widget //jff 3/3/98 split coordstr widget into 3 parts if (map_point_coordinates) { sprintf(hud_coordstrx,"X: %-5d",0); //jff 2/22/98 added z s = hud_coordstrx; while (*s) HUlib_addCharToTextLine(&w_coordx, *(s++)); sprintf(hud_coordstry,"Y: %-5d",0); //jff 3/3/98 split x,y,z s = hud_coordstry; while (*s) HUlib_addCharToTextLine(&w_coordy, *(s++)); sprintf(hud_coordstrz,"Z: %-5d",0); //jff 3/3/98 split x,y,z s = hud_coordstrz; while (*s) HUlib_addCharToTextLine(&w_coordz, *(s++)); } //jff 2/16/98 initialize ammo widget strcpy(hud_ammostr,"AMM "); s = hud_ammostr; while (*s) HUlib_addCharToTextLine(&w_ammo, *(s++)); //jff 2/16/98 initialize health widget strcpy(hud_healthstr,"HEL "); s = hud_healthstr; while (*s) HUlib_addCharToTextLine(&w_health, *(s++)); //jff 2/16/98 initialize armor widget strcpy(hud_armorstr,"ARM "); s = hud_armorstr; while (*s) HUlib_addCharToTextLine(&w_armor, *(s++)); //jff 2/17/98 initialize weapons widget strcpy(hud_weapstr,"WEA "); s = hud_weapstr; while (*s) HUlib_addCharToTextLine(&w_weapon, *(s++)); //jff 2/17/98 initialize keys widget if (!deathmatch) //jff 3/17/98 show frags in deathmatch mode strcpy(hud_keysstr,"KEY "); else strcpy(hud_keysstr,"FRG "); s = hud_keysstr; while (*s) HUlib_addCharToTextLine(&w_keys, *(s++)); //jff 2/17/98 initialize graphic keys widget strcpy(hud_gkeysstr," "); s = hud_gkeysstr; while (*s) HUlib_addCharToTextLine(&w_gkeys, *(s++)); //jff 2/17/98 initialize kills/items/secret widget strcpy(hud_monsecstr,"STS "); s = hud_monsecstr; while (*s) HUlib_addCharToTextLine(&w_monsec, *(s++)); // create the chat widget HUlib_initIText ( &w_chat, HU_INPUTX, HU_INPUTY, hu_font, HU_FONTSTART, hudcolor_chat, &chat_on ); // create the inputbuffer widgets, one per player for (i=0 ; i<MAXPLAYERS ; i++) HUlib_initIText ( &w_inputbuffer[i], 0, 0, 0, 0, hudcolor_chat, &always_off ); // now allow the heads-up display to run headsupactive = true; } // // HU_MoveHud() // // Move the HUD display from distributed to compact mode or vice-versa // // Passed nothing, returns nothing // //jff 3/9/98 create this externally callable to avoid glitch // when menu scatter's HUD due to delay in change of position // void HU_MoveHud(void) { static int ohud_distributed=-1; //jff 3/4/98 move displays around on F5 changing hud_distributed if (hud_distributed!=ohud_distributed) { w_ammo.x = hud_distributed? HU_AMMOX_D : HU_AMMOX; w_ammo.y = hud_distributed? HU_AMMOY_D : HU_AMMOY; w_weapon.x = hud_distributed? HU_WEAPX_D : HU_WEAPX; w_weapon.y = hud_distributed? HU_WEAPY_D : HU_WEAPY; w_keys.x = hud_distributed? HU_KEYSX_D : HU_KEYSX; w_keys.y = hud_distributed? HU_KEYSY_D : HU_KEYSY; w_gkeys.x = hud_distributed? HU_KEYSGX_D : HU_KEYSGX; w_gkeys.y = hud_distributed? HU_KEYSY_D : HU_KEYSY; w_monsec.x = hud_distributed? HU_MONSECX_D : HU_MONSECX; w_monsec.y = hud_distributed? HU_MONSECY_D : HU_MONSECY; w_health.x = hud_distributed? HU_HEALTHX_D : HU_HEALTHX; w_health.y = hud_distributed? HU_HEALTHY_D : HU_HEALTHY; w_armor.x = hud_distributed? HU_ARMORX_D : HU_ARMORX; w_armor.y = hud_distributed? HU_ARMORY_D : HU_ARMORY; } ohud_distributed = hud_distributed; } // // HU_Drawer() // // Draw all the pieces of the heads-up display // // Passed nothing, returns nothing // void HU_Drawer(void) { char *s; player_t *plr; char ammostr[80]; //jff 3/8/98 allow plenty room for dehacked mods char healthstr[80];//jff char armorstr[80]; //jff int i,doit; plr = &players[displayplayer]; // killough 3/7/98 // draw the automap widgets if automap is displayed if (automapmode & am_active) { // map title HUlib_drawTextLine(&w_title, false); //jff 2/16/98 output new coord display // x-coord if (map_point_coordinates) { sprintf(hud_coordstrx,"X: %-5d", (plr->mo->x)>>FRACBITS); HUlib_clearTextLine(&w_coordx); s = hud_coordstrx; while (*s) HUlib_addCharToTextLine(&w_coordx, *(s++)); HUlib_drawTextLine(&w_coordx, false); //jff 3/3/98 split coord display into x,y,z lines // y-coord sprintf(hud_coordstry,"Y: %-5d", (plr->mo->y)>>FRACBITS); HUlib_clearTextLine(&w_coordy); s = hud_coordstry; while (*s) HUlib_addCharToTextLine(&w_coordy, *(s++)); HUlib_drawTextLine(&w_coordy, false); //jff 3/3/98 split coord display into x,y,z lines //jff 2/22/98 added z // z-coord sprintf(hud_coordstrz,"Z: %-5d", (plr->mo->z)>>FRACBITS); HUlib_clearTextLine(&w_coordz); s = hud_coordstrz; while (*s) HUlib_addCharToTextLine(&w_coordz, *(s++)); HUlib_drawTextLine(&w_coordz, false); } } // draw the weapon/health/ammo/armor/kills/keys displays if optioned //jff 2/17/98 allow new hud stuff to be turned off // killough 2/21/98: really allow new hud stuff to be turned off COMPLETELY if ( hud_active>0 && // hud optioned on hud_displayed && // hud on from fullscreen key viewheight==SCREENHEIGHT && // fullscreen mode is active !(automapmode & am_active) // automap is not active ) { doit = !(gametic&1); //jff 3/4/98 speed update up for slow systems if (doit) //jff 8/7/98 update every time, avoid lag in update { HU_MoveHud(); // insure HUD display coords are correct // do the hud ammo display // clear the widgets internal line HUlib_clearTextLine(&w_ammo); strcpy(hud_ammostr,"AMM "); if (weaponinfo[plr->readyweapon].ammo == am_noammo) { // special case for weapon with no ammo selected - blank bargraph + N/A strcat(hud_ammostr,"\x7f\x7f\x7f\x7f\x7f\x7f\x7f N/A"); w_ammo.cm = CR_GRAY; } else { int ammo = plr->ammo[weaponinfo[plr->readyweapon].ammo]; int fullammo = plr->maxammo[weaponinfo[plr->readyweapon].ammo]; int ammopct = (100*ammo)/fullammo; int ammobars = ammopct/4; // build the numeric amount init string sprintf(ammostr,"%d/%d",ammo,fullammo); // build the bargraph string // full bargraph chars for (i=4;i<4+ammobars/4;) hud_ammostr[i++] = 123; // plus one last character with 0,1,2,3 bars switch(ammobars%4) { case 0: break; case 1: hud_ammostr[i++] = 126; break; case 2: hud_ammostr[i++] = 125; break; case 3: hud_ammostr[i++] = 124; break; } // pad string with blank bar characters while(i<4+7) hud_ammostr[i++] = 127; hud_ammostr[i] = '\0'; strcat(hud_ammostr,ammostr); // set the display color from the percentage of total ammo held if (ammopct<ammo_red) w_ammo.cm = CR_RED; else if (ammopct<ammo_yellow) w_ammo.cm = CR_GOLD; else w_ammo.cm = CR_GREEN; } // transfer the init string to the widget s = hud_ammostr; while (*s) HUlib_addCharToTextLine(&w_ammo, *(s++)); } // display the ammo widget every frame HUlib_drawTextLine(&w_ammo, false); // do the hud health display if (doit) { int health = plr->health; int healthbars = health>100? 25 : health/4; // clear the widgets internal line HUlib_clearTextLine(&w_health); // build the numeric amount init string sprintf(healthstr,"%3d",health); // build the bargraph string // full bargraph chars for (i=4;i<4+healthbars/4;) hud_healthstr[i++] = 123; // plus one last character with 0,1,2,3 bars switch(healthbars%4) { case 0: break; case 1: hud_healthstr[i++] = 126; break; case 2: hud_healthstr[i++] = 125; break; case 3: hud_healthstr[i++] = 124; break; } // pad string with blank bar characters while(i<4+7) hud_healthstr[i++] = 127; hud_healthstr[i] = '\0'; strcat(hud_healthstr,healthstr); // set the display color from the amount of health posessed if (health<health_red) w_health.cm = CR_RED; else if (health<health_yellow) w_health.cm = CR_GOLD; else if (health<=health_green) w_health.cm = CR_GREEN; else w_health.cm = CR_BLUE; // transfer the init string to the widget s = hud_healthstr; while (*s) HUlib_addCharToTextLine(&w_health, *(s++)); } // display the health widget every frame HUlib_drawTextLine(&w_health, false); // do the hud armor display if (doit) { int armor = plr->armorpoints; int armorbars = armor>100? 25 : armor/4; // clear the widgets internal line HUlib_clearTextLine(&w_armor); // build the numeric amount init string sprintf(armorstr,"%3d",armor); // build the bargraph string // full bargraph chars for (i=4;i<4+armorbars/4;) hud_armorstr[i++] = 123; // plus one last character with 0,1,2,3 bars switch(armorbars%4) { case 0: break; case 1: hud_armorstr[i++] = 126; break; case 2: hud_armorstr[i++] = 125; break; case 3: hud_armorstr[i++] = 124; break; } // pad string with blank bar characters while(i<4+7) hud_armorstr[i++] = 127; hud_armorstr[i] = '\0'; strcat(hud_armorstr,armorstr); // set the display color from the amount of armor posessed if (armor<armor_red) w_armor.cm = CR_RED; else if (armor<armor_yellow) w_armor.cm = CR_GOLD; else if (armor<=armor_green) w_armor.cm = CR_GREEN; else w_armor.cm = CR_BLUE; // transfer the init string to the widget s = hud_armorstr; while (*s) HUlib_addCharToTextLine(&w_armor, *(s++)); } // display the armor widget every frame HUlib_drawTextLine(&w_armor, false); // do the hud weapon display if (doit) { int w; int ammo,fullammo,ammopct; // clear the widgets internal line HUlib_clearTextLine(&w_weapon); i=4; hud_weapstr[i] = '\0'; //jff 3/7/98 make sure ammo goes away // do each weapon that exists in current gamemode for (w=0;w<=wp_supershotgun;w++) //jff 3/4/98 show fists too, why not? { int ok=1; //jff avoid executing for weapons that do not exist switch (gamemode) { case shareware: if (w>=wp_plasma && w!=wp_chainsaw) ok=0; break; case retail: case registered: if (w>=wp_supershotgun) ok=0; break; default: case commercial: break; } if (!ok) continue; ammo = plr->ammo[weaponinfo[w].ammo]; fullammo = plr->maxammo[weaponinfo[w].ammo]; ammopct=0; // skip weapons not currently posessed if (!plr->weaponowned[w]) continue; ammopct = fullammo? (100*ammo)/fullammo : 100; // display each weapon number in a color related to the ammo for it hud_weapstr[i++] = '\x1b'; //jff 3/26/98 use ESC not '\' for paths if (weaponinfo[w].ammo==am_noammo) //jff 3/14/98 show berserk on HUD hud_weapstr[i++] = plr->powers[pw_strength]? '0'+CR_GREEN : '0'+CR_GRAY; else if (ammopct<ammo_red) hud_weapstr[i++] = '0'+CR_RED; else if (ammopct<ammo_yellow) hud_weapstr[i++] = '0'+CR_GOLD; else hud_weapstr[i++] = '0'+CR_GREEN; hud_weapstr[i++] = '0'+w+1; hud_weapstr[i++] = ' '; hud_weapstr[i] = '\0'; } // transfer the init string to the widget s = hud_weapstr; while (*s) HUlib_addCharToTextLine(&w_weapon, *(s++)); } // display the weapon widget every frame HUlib_drawTextLine(&w_weapon, false); if (doit && hud_active>1) { int k; hud_keysstr[4] = '\0'; //jff 3/7/98 make sure deleted keys go away //jff add case for graphic key display if (!deathmatch && hud_graph_keys) { i=0; hud_gkeysstr[i] = '\0'; //jff 3/7/98 init graphic keys widget string // build text string whose characters call out graphic keys from fontk for (k=0;k<6;k++) { // skip keys not possessed if (!plr->cards[k]) continue; hud_gkeysstr[i++] = '!'+k; // key number plus '!' is char for key hud_gkeysstr[i++] = ' '; // spacing hud_gkeysstr[i++] = ' '; } hud_gkeysstr[i]='\0'; } else // not possible in current code, unless deathmatching, { i=4; hud_keysstr[i] = '\0'; //jff 3/7/98 make sure deleted keys go away // if deathmatch, build string showing top four frag counts if (deathmatch) //jff 3/17/98 show frags, not keys, in deathmatch { int top1=-999,top2=-999,top3=-999,top4=-999; int idx1=-1,idx2=-1,idx3=-1,idx4=-1; int fragcount,m; char numbuf[32]; // scan thru players for (k=0;k<MAXPLAYERS;k++) { // skip players not in game if (!playeringame[k]) continue; fragcount = 0; // compute number of times they've fragged each player // minus number of times they've been fragged by them for (m=0;m<MAXPLAYERS;m++) { if (!playeringame[m]) continue; fragcount += (m!=k)? players[k].frags[m] : -players[k].frags[m]; } // very primitive sort of frags to find top four if (fragcount>top1) { top4=top3; top3=top2; top2 = top1; top1=fragcount; idx4=idx3; idx3=idx2; idx2 = idx1; idx1=k; } else if (fragcount>top2) { top4=top3; top3=top2; top2=fragcount; idx4=idx3; idx3=idx2; idx2=k; } else if (fragcount>top3) { top4=top3; top3=fragcount; idx4=idx3; idx3=k; } else if (fragcount>top4) { top4=fragcount; idx4=k; } } // if the biggest number exists, put it in the init string if (idx1>-1) { sprintf(numbuf,"%5d",top1); // make frag count in player's color via escape code hud_keysstr[i++] = '\x1b'; //jff 3/26/98 use ESC not '\' for paths hud_keysstr[i++] = '0'+plyrcoltran[idx1&3]; s = numbuf; while (*s) hud_keysstr[i++] = *(s++); } // if the second biggest number exists, put it in the init string if (idx2>-1) { sprintf(numbuf,"%5d",top2); // make frag count in player's color via escape code hud_keysstr[i++] = '\x1b'; //jff 3/26/98 use ESC not '\' for paths hud_keysstr[i++] = '0'+plyrcoltran[idx2&3]; s = numbuf; while (*s) hud_keysstr[i++] = *(s++); } // if the third biggest number exists, put it in the init string if (idx3>-1) { sprintf(numbuf,"%5d",top3); // make frag count in player's color via escape code hud_keysstr[i++] = '\x1b'; //jff 3/26/98 use ESC not '\' for paths hud_keysstr[i++] = '0'+plyrcoltran[idx3&3]; s = numbuf; while (*s) hud_keysstr[i++] = *(s++); } // if the fourth biggest number exists, put it in the init string if (idx4>-1) { sprintf(numbuf,"%5d",top4); // make frag count in player's color via escape code hud_keysstr[i++] = '\x1b'; //jff 3/26/98 use ESC not '\' for paths hud_keysstr[i++] = '0'+plyrcoltran[idx4&3]; s = numbuf; while (*s) hud_keysstr[i++] = *(s++); } hud_keysstr[i] = '\0'; } //jff 3/17/98 end of deathmatch clause else // build alphabetical key display (not used currently) { // scan the keys for (k=0;k<6;k++) { // skip any not possessed by the displayed player's stats if (!plr->cards[k]) continue; // use color escapes to make text in key's color hud_keysstr[i++] = '\x1b'; //jff 3/26/98 use ESC not '\' for paths switch(k) { case 0: hud_keysstr[i++] = '0'+CR_BLUE; hud_keysstr[i++] = 'B'; hud_keysstr[i++] = 'C'; hud_keysstr[i++] = ' '; break; case 1: hud_keysstr[i++] = '0'+CR_GOLD; hud_keysstr[i++] = 'Y'; hud_keysstr[i++] = 'C'; hud_keysstr[i++] = ' '; break; case 2: hud_keysstr[i++] = '0'+CR_RED; hud_keysstr[i++] = 'R'; hud_keysstr[i++] = 'C'; hud_keysstr[i++] = ' '; break; case 3: hud_keysstr[i++] = '0'+CR_BLUE; hud_keysstr[i++] = 'B'; hud_keysstr[i++] = 'S'; hud_keysstr[i++] = ' '; break; case 4: hud_keysstr[i++] = '0'+CR_GOLD; hud_keysstr[i++] = 'Y'; hud_keysstr[i++] = 'S'; hud_keysstr[i++] = ' '; break; case 5: hud_keysstr[i++] = '0'+CR_RED; hud_keysstr[i++] = 'R'; hud_keysstr[i++] = 'S'; hud_keysstr[i++] = ' '; break; } hud_keysstr[i]='\0'; } } } } // display the keys/frags line each frame if (hud_active>1) { HUlib_clearTextLine(&w_keys); // clear the widget strings HUlib_clearTextLine(&w_gkeys); // transfer the built string (frags or key title) to the widget s = hud_keysstr; //jff 3/7/98 display key titles/key text or frags while (*s) HUlib_addCharToTextLine(&w_keys, *(s++)); HUlib_drawTextLine(&w_keys, false); //jff 3/17/98 show graphic keys in non-DM only if (!deathmatch) //jff 3/7/98 display graphic keys { // transfer the graphic key text to the widget s = hud_gkeysstr; while (*s) HUlib_addCharToTextLine(&w_gkeys, *(s++)); // display the widget HUlib_drawTextLine(&w_gkeys, false); } } // display the hud kills/items/secret display if optioned if (!hud_nosecrets) { if (hud_active>1 && doit) { // clear the internal widget text buffer HUlib_clearTextLine(&w_monsec); //jff 3/26/98 use ESC not '\' for paths // build the init string with fixed colors sprintf ( hud_monsecstr, "STS \x1b\x36K \x1b\x33%d \x1b\x36M \x1b\x33%d \x1b\x37I \x1b\x33%d/%d \x1b\x35S \x1b\x33%d/%d", plr->killcount,totallive, plr->itemcount,totalitems, plr->secretcount,totalsecret ); // transfer the init string to the widget s = hud_monsecstr; while (*s) HUlib_addCharToTextLine(&w_monsec, *(s++)); } // display the kills/items/secrets each frame, if optioned if (hud_active>1) HUlib_drawTextLine(&w_monsec, false); } } //jff 3/4/98 display last to give priority HU_Erase(); // jff 4/24/98 Erase current lines before drawing current // needed when screen not fullsize //jff 4/21/98 if setup has disabled message list while active, turn it off if (hud_msg_lines<=1) message_list = false; // if the message review not enabled, show the standard message widget if (!message_list) HUlib_drawSText(&w_message); // if the message review is enabled show the scrolling message review if (hud_msg_lines>1 && message_list) HUlib_drawMText(&w_rtext); // display the interactive buffer for chat entry HUlib_drawIText(&w_chat); } // // HU_Erase() // // Erase hud display lines that can be trashed by small screen display // // Passed nothing, returns nothing // void HU_Erase(void) { // erase the message display or the message review display if (!message_list) HUlib_eraseSText(&w_message); else HUlib_eraseMText(&w_rtext); // erase the interactive text buffer for chat entry HUlib_eraseIText(&w_chat); // erase the automap title HUlib_eraseTextLine(&w_title); } // // HU_Ticker() // // Update the hud displays once per frame // // Passed nothing, returns nothing // static boolean bsdown; // Is backspace down? static int bscounter; void HU_Ticker(void) { int i, rc; char c; // tick down message counter if message is up if (message_counter && !--message_counter) { message_on = false; message_nottobefuckedwith = false; } if (bsdown && bscounter++ > 9) { HUlib_keyInIText(&w_chat, (unsigned char)key_backspace); bscounter = 8; } // if messages on, or "Messages Off" is being displayed // this allows the notification of turning messages off to be seen if (showMessages || message_dontfuckwithme) { // display message if necessary if ((plr->message && !message_nottobefuckedwith) || (plr->message && message_dontfuckwithme)) { //post the message to the message widget HUlib_addMessageToSText(&w_message, 0, plr->message); //jff 2/26/98 add message to refresh text widget too HUlib_addMessageToMText(&w_rtext, 0, plr->message); // clear the message to avoid posting multiple times plr->message = 0; // note a message is displayed message_on = true; // start the message persistence counter message_counter = HU_MSGTIMEOUT; // transfer "Messages Off" exception to the "being displayed" variable message_nottobefuckedwith = message_dontfuckwithme; // clear the flag that "Messages Off" is being posted message_dontfuckwithme = 0; } } // check for incoming chat characters if (netgame) { for (i=0; i<MAXPLAYERS; i++) { if (!playeringame[i]) continue; if (i != consoleplayer && (c = players[i].cmd.chatchar)) { if (c <= HU_BROADCAST) chat_dest[i] = c; else { if (c >= 'a' && c <= 'z') c = (char) shiftxform[(unsigned char) c]; rc = HUlib_keyInIText(&w_inputbuffer[i], c); if (rc && c == KEYD_ENTER) { if (w_inputbuffer[i].l.len && (chat_dest[i] == consoleplayer+1 || chat_dest[i] == HU_BROADCAST)) { HUlib_addMessageToSText(&w_message, player_names[i], w_inputbuffer[i].l.l); message_nottobefuckedwith = true; message_on = true; message_counter = HU_MSGTIMEOUT; if ( gamemode == commercial ) S_StartSound(0, sfx_radio); else S_StartSound(0, sfx_tink); } HUlib_resetIText(&w_inputbuffer[i]); } } players[i].cmd.chatchar = 0; } } } } #define QUEUESIZE 128 static char chatchars[QUEUESIZE]; static int head = 0; static int tail = 0; // // HU_queueChatChar() // // Add an incoming character to the circular chat queue // // Passed the character to queue, returns nothing // static void HU_queueChatChar(char c) { if (((head + 1) & (QUEUESIZE-1)) == tail) { plr->message = HUSTR_MSGU; } else { chatchars[head] = c; head = (head + 1) & (QUEUESIZE-1); } } // // HU_dequeueChatChar() // // Remove the earliest added character from the circular chat queue // // Passed nothing, returns the character dequeued // char HU_dequeueChatChar(void) { char c; if (head != tail) { c = chatchars[tail]; tail = (tail + 1) & (QUEUESIZE-1); } else { c = 0; } return c; } // // HU_Responder() // // Responds to input events that affect the heads up displays // // Passed the event to respond to, returns true if the event was handled // boolean HU_Responder(event_t *ev) { static char lastmessage[HU_MAXLINELENGTH+1]; const char* macromessage; // CPhipps - const char* boolean eatkey = false; static boolean shiftdown = false; static boolean altdown = false; unsigned char c; int i; int numplayers; static int num_nobrainers = 0; numplayers = 0; for (i=0 ; i<MAXPLAYERS ; i++) numplayers += playeringame[i]; if (ev->data1 == key_shift) { shiftdown = ev->type == ev_keydown; return false; } else if (ev->data1 == key_alt) { altdown = ev->type == ev_keydown; return false; } else if (ev->data1 == key_backspace) { bsdown = ev->type == ev_keydown; bscounter = 0; } if (ev->type != ev_keydown) return false; if (!chat_on) { if (ev->data1 == key_enter) // phares { #ifndef INSTRUMENTED // never turn on message review if INSTRUMENTED defined if (hud_msg_lines>1) // it posts multi-line messages that will trash { if (message_list) HU_Erase(); //jff 4/28/98 erase behind messages message_list = !message_list; //jff 2/26/98 toggle list of messages } #endif if (!message_list) // if not message list, refresh message { message_on = true; message_counter = HU_MSGTIMEOUT; } eatkey = true; }//jff 2/26/98 no chat if message review is displayed else if (!message_list && netgame && ev->data1 == key_chat) { eatkey = chat_on = true; HUlib_resetIText(&w_chat); HU_queueChatChar(HU_BROADCAST); }//jff 2/26/98 no chat if message review is displayed // killough 10/02/98: no chat if demo playback else if (!demoplayback && !message_list && netgame && numplayers > 2) { for (i=0; i<MAXPLAYERS ; i++) { if (ev->data1 == destination_keys[i]) { if (playeringame[i] && i!=consoleplayer) { eatkey = chat_on = true; HUlib_resetIText(&w_chat); HU_queueChatChar((char)(i+1)); break; } else if (i == consoleplayer) { num_nobrainers++; if (num_nobrainers < 3) plr->message = HUSTR_TALKTOSELF1; else if (num_nobrainers < 6) plr->message = HUSTR_TALKTOSELF2; else if (num_nobrainers < 9) plr->message = HUSTR_TALKTOSELF3; else if (num_nobrainers < 32) plr->message = HUSTR_TALKTOSELF4; else plr->message = HUSTR_TALKTOSELF5; } } } } }//jff 2/26/98 no chat functions if message review is displayed else if (!message_list) { c = ev->data1; // send a macro if (altdown) { c = c - '0'; if (c > 9) return false; macromessage = chat_macros[c]; // kill last message with a '\n' HU_queueChatChar((char)key_enter); // DEBUG!!! // phares // send the macro message while (*macromessage) HU_queueChatChar(*macromessage++); HU_queueChatChar((char)key_enter); // phares // leave chat mode and notify that it was sent chat_on = false; strcpy(lastmessage, chat_macros[c]); plr->message = lastmessage; eatkey = true; } else { if (shiftdown || (c >= 'a' && c <= 'z')) c = shiftxform[c]; eatkey = HUlib_keyInIText(&w_chat, c); if (eatkey) HU_queueChatChar(c); if (c == key_enter) // phares { chat_on = false; if (w_chat.l.len) { strcpy(lastmessage, w_chat.l.l); plr->message = lastmessage; } } else if (c == key_escape) // phares chat_on = false; } } return eatkey; }
gpl-2.0
SirPiter/folk
www/media/com_ats/js/adm_buckets_choose.js
382
akeeba.jQuery(document).ready(function($){ akeeba.jQuery('#addTickets').click(function(){ if(document.adminForm.boxchecked.value == 0) { alert(akeeba.jQuery('#chooseone').val()); return false; } if(document.adminForm.boxchecked.value > 1) { alert(akeeba.jQuery('#chooseonlyone').val()); return false; } Joomla.submitbutton('addtickets'); }); });
gpl-2.0
stuffekarl/KingFunk2
CRT_timer/CRT_timer.cydsn/codegentemp/D5.c
4613
/******************************************************************************* * File Name: D5.c * Version 2.10 * * Description: * This file contains API to enable firmware control of a Pins component. * * Note: * ******************************************************************************** * Copyright 2008-2014, Cypress Semiconductor Corporation. All rights reserved. * You may use this file only in accordance with the license, terms, conditions, * disclaimers, and limitations in the end user license agreement accompanying * the software package with which this file was provided. *******************************************************************************/ #include "cytypes.h" #include "D5.h" #define SetP4PinDriveMode(shift, mode) \ do { \ D5_PC = (D5_PC & \ (uint32)(~(uint32)(D5_DRIVE_MODE_IND_MASK << (D5_DRIVE_MODE_BITS * (shift))))) | \ (uint32)((uint32)(mode) << (D5_DRIVE_MODE_BITS * (shift))); \ } while (0) /******************************************************************************* * Function Name: D5_Write ******************************************************************************** * * Summary: * Assign a new value to the digital port's data output register. * * Parameters: * prtValue: The value to be assigned to the Digital Port. * * Return: * None * *******************************************************************************/ void D5_Write(uint8 value) { uint8 drVal = (uint8)(D5_DR & (uint8)(~D5_MASK)); drVal = (drVal | ((uint8)(value << D5_SHIFT) & D5_MASK)); D5_DR = (uint32)drVal; } /******************************************************************************* * Function Name: D5_SetDriveMode ******************************************************************************** * * Summary: * Change the drive mode on the pins of the port. * * Parameters: * mode: Change the pins to one of the following drive modes. * * D5_DM_STRONG Strong Drive * D5_DM_OD_HI Open Drain, Drives High * D5_DM_OD_LO Open Drain, Drives Low * D5_DM_RES_UP Resistive Pull Up * D5_DM_RES_DWN Resistive Pull Down * D5_DM_RES_UPDWN Resistive Pull Up/Down * D5_DM_DIG_HIZ High Impedance Digital * D5_DM_ALG_HIZ High Impedance Analog * * Return: * None * *******************************************************************************/ void D5_SetDriveMode(uint8 mode) { SetP4PinDriveMode(D5__0__SHIFT, mode); } /******************************************************************************* * Function Name: D5_Read ******************************************************************************** * * Summary: * Read the current value on the pins of the Digital Port in right justified * form. * * Parameters: * None * * Return: * Returns the current value of the Digital Port as a right justified number * * Note: * Macro D5_ReadPS calls this function. * *******************************************************************************/ uint8 D5_Read(void) { return (uint8)((D5_PS & D5_MASK) >> D5_SHIFT); } /******************************************************************************* * Function Name: D5_ReadDataReg ******************************************************************************** * * Summary: * Read the current value assigned to a Digital Port's data output register * * Parameters: * None * * Return: * Returns the current value assigned to the Digital Port's data output register * *******************************************************************************/ uint8 D5_ReadDataReg(void) { return (uint8)((D5_DR & D5_MASK) >> D5_SHIFT); } /* If Interrupts Are Enabled for this Pins component */ #if defined(D5_INTSTAT) /******************************************************************************* * Function Name: D5_ClearInterrupt ******************************************************************************** * * Summary: * Clears any active interrupts attached to port and returns the value of the * interrupt status register. * * Parameters: * None * * Return: * Returns the value of the interrupt status register * *******************************************************************************/ uint8 D5_ClearInterrupt(void) { uint8 maskedStatus = (uint8)(D5_INTSTAT & D5_MASK); D5_INTSTAT = maskedStatus; return maskedStatus >> D5_SHIFT; } #endif /* If Interrupts Are Enabled for this Pins component */ /* [] END OF FILE */
gpl-2.0
bstroebl/QGIS
python/plugins/sextante/admintools/PostGISExecuteSQL.py
3170
# -*- coding: utf-8 -*- """ *************************************************************************** PostGISExecuteSQL.py --------------------- Date : October 2012 Copyright : (C) 2012 by Victor Olaya and Carterix Geomatics Email : volayaf at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ from sextante.core.GeoAlgorithm import GeoAlgorithm __author__ = 'Victor Olaya, Carterix Geomatics' __date__ = 'October 2012' __copyright__ = '(C) 2012, Victor Olaya, Carterix Geomatics' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import os from qgis.core import * from PyQt4.QtCore import * from PyQt4.QtGui import * from sextante.parameters.ParameterString import ParameterString from sextante.admintools import postgis_utils from sextante.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException class PostGISExecuteSQL(GeoAlgorithm): DATABASE = "DATABASE" SQL = "SQL" def getIcon(self): return QIcon(os.path.dirname(__file__) + "/../images/postgis.png") def processAlgorithm(self, progress): connection = self.getParameterValue(self.DATABASE) settings = QSettings() mySettings = "/PostgreSQL/connections/"+ connection try: database = settings.value(mySettings+"/database").toString() username = settings.value(mySettings+"/username").toString() host = settings.value(mySettings+"/host").toString() port = int(settings.value(mySettings+"/port").toString()) password = settings.value(mySettings+"/password").toString() except Exception, e: raise GeoAlgorithmExecutionException("Wrong database connection name: " + connection) try: self.db = postgis_utils.GeoDB(host=host, port=port, dbname=database, user=username, passwd=password) except postgis_utils.DbError, e: raise GeoAlgorithmExecutionException("Couldn't connect to database:\n"+e.message) sql = self.getParameterValue(self.SQL).replace("\n", " ") try: self.db._exec_sql_and_commit(str(sql)) except postgis_utils.DbError, e: raise GeoAlgorithmExecutionException("Error executing SQL:\n"+e.message) def defineCharacteristics(self): self.name = "PostGIS execute SQL" self.group = "PostGIS management tools" self.addParameter(ParameterString(self.DATABASE, "Database")) self.addParameter(ParameterString(self.SQL, "SQL query", "", True))
gpl-2.0
gitprj/samantha-ohlsen-photography
wp-content/themes/fineliner/woocommerce/cart/cart.php
6140
<?php /* * Theme Note * ------------------- * - Changed the location of cross-sells section (woocommerce_cart_collaterals action) and adjusted the layout a bit * - Added if-else for "wc_print_notices()", "wp_nonce_field( 'woocommerce-cart' );" * - Note: This file is based on WooC 2.1.9 * */ /** * Cart Page * * @author WooThemes * @package WooCommerce/Templates * @version 2.1.0 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly global $woocommerce; if ( version_compare( WOOCOMMERCE_VERSION, '2.1' ) >= 0 ) { wc_print_notices(); } else { $woocommerce->show_messages(); } do_action( 'woocommerce_before_cart' ); ?> <form action="<?php echo esc_url( WC()->cart->get_cart_url() ); ?>" method="post"> <?php do_action( 'woocommerce_before_cart_table' ); ?> <table class="shop_table cart" cellspacing="0"> <thead> <tr> <th class="product-remove">&nbsp;</th> <th class="product-thumbnail">&nbsp;</th> <th class="product-name"><?php _e( 'Product', 'woocommerce' ); ?></th> <th class="product-price"><?php _e( 'Price', 'woocommerce' ); ?></th> <th class="product-quantity"><?php _e( 'Quantity', 'woocommerce' ); ?></th> <th class="product-subtotal"><?php _e( 'Total', 'woocommerce' ); ?></th> </tr> </thead> <tbody> <?php do_action( 'woocommerce_before_cart_contents' ); ?> <?php foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { $_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key ); $product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key ); if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_cart_item_visible', true, $cart_item, $cart_item_key ) ) { ?> <tr class="<?php echo esc_attr( apply_filters( 'woocommerce_cart_item_class', 'cart_item', $cart_item, $cart_item_key ) ); ?>"> <td class="product-remove"> <?php echo apply_filters( 'woocommerce_cart_item_remove_link', sprintf( '<a href="%s" class="remove" title="%s">&times;</a>', esc_url( WC()->cart->get_remove_url( $cart_item_key ) ), __( 'Remove this item', 'woocommerce' ) ), $cart_item_key ); ?> </td> <td class="product-thumbnail"> <?php $thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key ); if ( ! $_product->is_visible() ) echo $thumbnail; else printf( '<a href="%s">%s</a>', $_product->get_permalink(), $thumbnail ); ?> </td> <td class="product-name"> <?php if ( ! $_product->is_visible() ) echo apply_filters( 'woocommerce_cart_item_name', $_product->get_title(), $cart_item, $cart_item_key ); else echo apply_filters( 'woocommerce_cart_item_name', sprintf( '<a href="%s">%s</a>', $_product->get_permalink(), $_product->get_title() ), $cart_item, $cart_item_key ); // Meta data echo WC()->cart->get_item_data( $cart_item ); // Backorder notification if ( $_product->backorders_require_notification() && $_product->is_on_backorder( $cart_item['quantity'] ) ) echo '<p class="backorder_notification">' . __( 'Available on backorder', 'woocommerce' ) . '</p>'; ?> </td> <td class="product-price"> <?php echo apply_filters( 'woocommerce_cart_item_price', WC()->cart->get_product_price( $_product ), $cart_item, $cart_item_key ); ?> </td> <td class="product-quantity"> <?php if ( $_product->is_sold_individually() ) { $product_quantity = sprintf( '1 <input type="hidden" name="cart[%s][qty]" value="1" />', $cart_item_key ); } else { $product_quantity = woocommerce_quantity_input( array( 'input_name' => "cart[{$cart_item_key}][qty]", 'input_value' => $cart_item['quantity'], 'max_value' => $_product->backorders_allowed() ? '' : $_product->get_stock_quantity(), 'min_value' => '0' ), $_product, false ); } echo apply_filters( 'woocommerce_cart_item_quantity', $product_quantity, $cart_item_key ); ?> </td> <td class="product-subtotal"> <?php echo apply_filters( 'woocommerce_cart_item_subtotal', WC()->cart->get_product_subtotal( $_product, $cart_item['quantity'] ), $cart_item, $cart_item_key ); ?> </td> </tr> <?php } } do_action( 'woocommerce_cart_contents' ); ?> <tr> <td colspan="6" class="actions"> <?php if ( WC()->cart->coupons_enabled() ) { ?> <div class="coupon"> <label for="coupon_code"><?php _e( 'Coupon', 'woocommerce' ); ?>:</label> <input type="text" name="coupon_code" class="input-text" id="coupon_code" value="" placeholder="<?php _e( 'Coupon code', 'woocommerce' ); ?>" /> <input type="submit" class="button" name="apply_coupon" value="<?php _e( 'Apply Coupon', 'woocommerce' ); ?>" /> <?php do_action('woocommerce_cart_coupon'); ?> </div> <?php } ?> <input type="submit" class="button" name="update_cart" value="<?php _e( 'Update Cart', 'woocommerce' ); ?>" /> <input type="submit" class="checkout-button button alt wc-forward" name="proceed" value="<?php _e( 'Proceed to Checkout', 'woocommerce' ); ?>" /> <?php do_action( 'woocommerce_proceed_to_checkout' ); ?> <?php if ( version_compare( WOOCOMMERCE_VERSION, '2.1' ) >= 0 ) { wp_nonce_field( 'woocommerce-cart' ); } else { $woocommerce->nonce_field('cart'); } ?> </td> </tr> <?php do_action( 'woocommerce_after_cart_contents' ); ?> </tbody> </table> <?php do_action( 'woocommerce_after_cart_table' ); ?> </form> <div class="row"> <div class="uxb-col large-6 columns"> <?php woocommerce_cart_totals(); ?> </div> <div class="uxb-col large-6 columns"> <?php woocommerce_shipping_calculator(); ?> </div> </div> <?php do_action( 'woocommerce_cart_collaterals' ); ?> <?php do_action( 'woocommerce_after_cart' ); ?>
gpl-2.0
squid-cache/squid
src/base/AsyncCbdataCalls.h
1286
/* * Copyright (C) 1996-2022 The Squid Software Foundation and contributors * * Squid software is distributed under GPLv2+ license and includes * contributions from numerous individuals and organizations. * Please see the COPYING and CONTRIBUTORS files for details. */ #ifndef SQUID_BASE_ASYNCCBDATACALLS_H #define SQUID_BASE_ASYNCCBDATACALLS_H #include "base/AsyncCall.h" #include "base/CbcPointer.h" // dialer to run cbdata callback functions as Async Calls // to ease the transition of these cbdata objects to full Jobs template<class Argument1> class UnaryCbdataDialer : public CallDialer { public: typedef void Handler(Argument1 *); UnaryCbdataDialer(Handler *aHandler, Argument1 *aArg) : arg1(aArg), handler(aHandler) {} virtual bool canDial(AsyncCall &) { return arg1.valid(); } void dial(AsyncCall &) { handler(arg1.get()); } virtual void print(std::ostream &os) const { os << '(' << arg1 << ')'; } public: CbcPointer<Argument1> arg1; Handler *handler; }; // helper function to simplify Dialer creation. template <class Argument1> UnaryCbdataDialer<Argument1> cbdataDialer(typename UnaryCbdataDialer<Argument1>::Handler *handler, Argument1 *arg1) { return UnaryCbdataDialer<Argument1>(handler, arg1); } #endif
gpl-2.0
midaboghetich/netnumero
src/com/numhero/client/model/datacargo/auth/AuthResponse.java
594
package com.numhero.client.model.datacargo.auth; import com.numhero.shared.datacargo.CommandResponse; import java.util.Date; public class AuthResponse implements CommandResponse { private String sessionID; private Date expirationDate; public String getSessionID() { return sessionID; } public void setSessionID(String sessionID) { this.sessionID = sessionID; } public Date getExpirationDate() { return expirationDate; } public void setExpirationDate(Date expirationDate) { this.expirationDate = expirationDate; } }
gpl-2.0
nike-17/sylius.ru
client/app/app.js
295
'use strict'; angular.module('syliusApp', [ 'ngCookies', 'ngResource', 'ngSanitize', 'ui.router', 'ui.bootstrap' ]) .config(function ($stateProvider, $urlRouterProvider, $locationProvider) { $urlRouterProvider .otherwise('/'); $locationProvider.html5Mode(true); });
gpl-2.0
DerKnob/scummvm-for-sally
engines/sci/engine/seg_manager.h
15564
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * $URL: https://scummvm.svn.sourceforge.net/svnroot/scummvm/scummvm/tags/release-1-1-1/engines/sci/engine/seg_manager.h $ * $Id: seg_manager.h 47836 2010-02-03 01:34:15Z fingolfin $ * */ #ifndef SCI_ENGINE_SEGMAN_H #define SCI_ENGINE_SEGMAN_H #include "common/scummsys.h" #include "common/serializer.h" #include "sci/engine/vm.h" #include "sci/engine/segment.h" namespace Sci { #define GET_SEGMENT(mgr, index, rtype) (((mgr).getSegmentType(index) == (rtype))? (mgr)._heap[index] : NULL) /** * Verify the the given condition is true, output the message if condition is false, and exit. * @param cond condition to be verified * @param msg the message to be printed if condition fails */ #define VERIFY( cond, msg ) if (!(cond)) {\ error("%s, line, %d, %s", __FILE__, __LINE__, msg); \ } /** * Parameters for getScriptSegment(). */ enum ScriptLoadType { SCRIPT_GET_DONT_LOAD = 0, /**< Fail if not loaded */ SCRIPT_GET_LOAD = 1, /**< Load, if neccessary */ SCRIPT_GET_LOCK = 3 /**< Load, if neccessary, and lock */ }; class SegManager : public Common::Serializable { friend class Console; public: /** * Initialize the segment manager. */ SegManager(ResourceManager *resMan); /** * Deallocate all memory associated with the segment manager. */ ~SegManager(); void resetSegMan(); virtual void saveLoadWithSerializer(Common::Serializer &ser); // 1. Scripts /** * Allocate a script into the segment manager. * @param script_nr The number of the script to load * @param seg_id The segment ID of the newly allocated segment, * on success * @return 0 on failure, 1 on success */ Script *allocateScript(int script_nr, SegmentId *seg_id); // The script must then be initialised; see section (1b.), below. /** * Forcefully deallocate a previously allocated script. * @param script_nr number of the script to deallocate */ void deallocateScript(int script_nr); /** * Reconstructs scripts. Used when restoring saved games */ void reconstructScripts(EngineState *s); /** * Validate whether the specified public function is exported by * the script in the specified segment. * @param pubfunct Index of the function to validate * @param seg Segment ID of the script the check is to * be performed for * @return NULL if the public function is invalid, its * offset into the script's segment otherwise */ uint16 validateExportFunc(int pubfunct, SegmentId seg); /** * Determines the segment occupied by a certain script, if any. * @param script_nr Number of the script to look up * @return The script's segment ID, or 0 on failure */ SegmentId getScriptSegment(int script_nr) const; /** * Determines the segment occupied by a certain script. Optionally * load it, or load & lock it. * @param[in] script_nr Number of the script to look up * @param[in] load flag determining whether to load/lock the script * @return The script's segment ID, or 0 on failure */ SegmentId getScriptSegment(int script_nr, ScriptLoadType load); // TODO: document this reg_t lookupScriptExport(int script_nr, int export_index) { SegmentId seg = getScriptSegment(script_nr, SCRIPT_GET_DONT_LOAD); return make_reg(seg, validateExportFunc(export_index, seg)); } // TODO: document this reg_t getClassAddress(int classnr, ScriptLoadType lock, reg_t caller); /** * Return a pointer to the specified script. * If the id is invalid, does not refer to a script or the script is * not loaded, this will invoke error(). * @param seg ID of the script segment to check for * @return A pointer to the Script object */ Script *getScript(SegmentId seg); /** * Return a pointer to the specified script. * If the id is invalid, does not refer to a script, or * the script is not loaded, this will return NULL * @param seg ID of the script segment to check for * @return A pointer to the Script object, or NULL */ Script *getScriptIfLoaded(SegmentId seg); // 1b. Script Initialisation // The set of functions below are intended // to be used during script instantiation, // i.e. loading and linking. /** * Initializes a script's local variable block * All variables are initialized to zero. * @param seg Segment containing the script to initialize * @param nr Number of local variables to allocate */ void scriptInitialiseLocalsZero(SegmentId seg, int nr); /** * Initializes a script's local variable block according to a prototype * @param location Location to initialize from */ void scriptInitialiseLocals(reg_t location); /** * Tells the segment manager whether exports are wide (32-bit) or not. * @param flag true if exports are wide, false otherwise */ void setExportAreWide(bool flag); // 2. Clones /** * Allocate a fresh clone * @param addr The offset of the freshly allocated clone * @return Reference to the memory allocated for the clone */ Clone *allocateClone(reg_t *addr); /** * Reconstructs clones. Used when restoring saved games */ void reconstructClones(); // 4. Stack /** * Allocates a data stack * @param size Number of stack entries to reserve * @param segid Segment ID of the stack * @return The physical stack */ DataStack *allocateStack(int size, SegmentId *segid); // 5. System Strings /** * Allocates a system string table * See also sys_string_acquire(); * @param[in] segid Segment ID of the stack * @returns The physical stack */ SystemStrings *allocateSysStrings(SegmentId *segid); // 5. System Strings // 6, 7. Lists and Nodes /** * Allocate a fresh list * @param[in] addr The offset of the freshly allocated list * @return Reference to the memory allocated for the list */ List *allocateList(reg_t *addr); /** * Allocate a fresh node * @param[in] addr The offset of the freshly allocated node * @return Reference to the memory allocated for the node */ Node *allocateNode(reg_t *addr); /** * Resolves a list pointer to a list. * @param addr The address to resolve * @return The list referenced, or NULL on error */ List *lookupList(reg_t addr); /** * Resolves an address into a list node. * @param addr The address to resolve * @return The list node referenced, or NULL on error */ Node *lookupNode(reg_t addr); // 8. Hunk Memory /** * Allocate a fresh chunk of the hunk * @param[in] size Number of bytes to allocate for the hunk entry * @param[in] hunk_type A descriptive string for the hunk entry, for * debugging purposes * @param[out] addr The offset of the freshly allocated hunk entry * @return Reference to the memory allocated for the hunk * piece */ Hunk *allocateHunkEntry(const char *hunk_type, int size, reg_t *addr); /** * Deallocates a hunk entry * @param[in] addr Offset of the hunk entry to delete */ void freeHunkEntry(reg_t addr); // 9. Dynamic Memory /** * Allocate some dynamic memory * @param[in] size Number of bytes to allocate * @param[in] description A descriptive string for debugging purposes * @param[out] addr The offset of the freshly allocated X * @return Raw pointer into the allocated dynamic * memory */ byte *allocDynmem(int size, const char *description, reg_t *addr); /** * Deallocates a piece of dynamic memory * @param[in] addr Offset of the dynmem chunk to free */ int freeDynmem(reg_t addr); // Generic Operations on Segments and Addresses /** * Dereferences a raw memory pointer * @param[in] reg The reference to dereference * @return The data block referenced */ SegmentRef dereference(reg_t pointer); /** * Dereferences a heap pointer pointing to raw memory. * @param pointer The pointer to dereference * @parm entries The number of values expected (for checkingO * @return A physical reference to the address pointed to, or NULL on error or * if not enough entries were available. */ byte *derefBulkPtr(reg_t pointer, int entries); /** * Dereferences a heap pointer pointing to a (list of) register(s). * Ensures alignedness of data. * @param pointer The pointer to dereference * @parm entries The number of values expected (for checking) * @return A physical reference to the address pointed to, or NULL on error or * if not enough entries were available. */ reg_t *derefRegPtr(reg_t pointer, int entries); /** * Dereferences a heap pointer pointing to raw memory. * @param pointer The pointer to dereference * @parm entries The number of values expected (for checking) * @return A physical reference to the address pointed to, or NULL on error or * if not enough entries were available. */ char *derefString(reg_t pointer, int entries = 0); /** * Return the string referenced by pointer. * pointer can point to either a raw or non-raw segment. * @param pointer The pointer to dereference * @parm entries The number of values expected (for checking) * @return The string referenced, or an empty string if not enough * entries were available. */ Common::String getString(reg_t pointer, int entries = 0); /** * Copies a string from src to dest. * src and dest can point to raw and non-raw segments. * Conversion is performed as required. */ void strcpy(reg_t dest, reg_t src); /** * Copies a string from src to dest. * dest can point to a raw or non-raw segment. * Conversion is performed as required. */ void strcpy(reg_t dest, const char *src); /** * Copies a string from src to dest. * src and dest can point to raw and non-raw segments. * Conversion is performed as required. At most n characters are copied. * TODO: determine if dest should always be null-terminated. */ void strncpy(reg_t dest, reg_t src, size_t n); /** * Copies a string from src to dest. * dest can point to a raw or non-raw segment. * Conversion is performed as required. At most n characters are copied. * TODO: determine if dest should always be null-terminated. */ void strncpy(reg_t dest, const char *src, size_t n); /** * Copies n bytes of data from src to dest. * src and dest can point to raw and non-raw segments. * Conversion is performed as required. */ void memcpy(reg_t dest, reg_t src, size_t n); /** * Copies n bytes of data from src to dest. * dest can point to a raw or non-raw segment. * Conversion is performed as required. */ void memcpy(reg_t dest, const byte* src, size_t n); /** * Copies n bytes of data from src to dest. * src can point to raw and non-raw segments. * Conversion is performed as required. */ void memcpy(byte *dest, reg_t src, size_t n); /** * Determine length of string at str. * str can point to a raw or non-raw segment. */ size_t strlen(reg_t str); /** * Finds a unique segment by type * @param type The type of the segment to find * @return The segment number, or -1 if the segment wasn't found */ SegmentId findSegmentByType(int type); // TODO: document this SegmentObj *getSegmentObj(SegmentId seg); // TODO: document this SegmentType getSegmentType(SegmentId seg); /** * Retrieves an object from the specified location * @param[in] offset Location (segment, offset) of the object * @return The object in question, or NULL if there is none */ Object *getObject(reg_t pos); /** * Checks whether a heap address contains an object * @parm obj The address to check * @return True if it is an object, false otherwise */ bool isObject(reg_t obj) { return getObject(obj) != NULL; } // TODO: document this bool isHeapObject(reg_t pos); /** * Determines the name of an object * @param[in] pos Location (segment, offset) of the object * @return A name for that object, or a string describing an error * that occured while looking it up. The string is stored * in a static buffer and need not be freed (neither may * it be modified). */ const char *getObjectName(reg_t pos); /** * Find the address of an object by its name. In case multiple objects * with the same name occur, the optional index parameter can be used * to distinguish between them. If index is -1, then if there is a * unique object with the specified name, its address is returned; * if there are multiple matches, or none, then NULL_REG is returned. * * @param name the name of the object we are looking for * @param index the index of the object in case there are multiple * @return the address of the object, or NULL_REG */ reg_t findObjectByName(const Common::String &name, int index = -1); void scriptRelocateExportsSci11(SegmentId seg); void scriptInitialiseObjectsSci11(SegmentId seg); public: // TODO: make private Common::Array<SegmentObj *> _heap; Common::Array<Class> _classtable; /**< Table of all classes */ #ifdef ENABLE_SCI32 SciArray<reg_t> *allocateArray(reg_t *addr); SciArray<reg_t> *lookupArray(reg_t addr); void freeArray(reg_t addr); SciString *allocateString(reg_t *addr); SciString *lookupString(reg_t addr); void freeString(reg_t addr); SegmentId getStringSegmentId() { return String_seg_id; } #endif private: /** Map script ids to segment ids. */ Common::HashMap<int, SegmentId> _scriptSegMap; ResourceManager *_resMan; bool _exportsAreWide; SegmentId Clones_seg_id; ///< ID of the (a) clones segment SegmentId Lists_seg_id; ///< ID of the (a) list segment SegmentId Nodes_seg_id; ///< ID of the (a) node segment SegmentId Hunks_seg_id; ///< ID of the (a) hunk segment #ifdef ENABLE_SCI32 SegmentId Arrays_seg_id; SegmentId String_seg_id; #endif private: SegmentObj *allocSegment(SegmentObj *mem, SegmentId *segid); LocalVariables *allocLocalsSegment(Script *scr, int count); int deallocate(SegmentId seg, bool recursive); void createClassTable(); SegmentId findFreeSegment() const; /** * Check segment validity * @param[in] seg The segment to validate * @return false if 'seg' is an invalid segment, true if * 'seg' is a valid segment */ bool check(SegmentId seg); }; } // End of namespace Sci #endif // SCI_ENGINE_SEGMAN_H
gpl-2.0
chregu/fluxcms
inc/bx/streams/db2xml.php
1061
<?php class bx_streams_db2xml extends bx_streams_buffer { function contentOnRead($path) { $db2xml = new XML_db2xml(NULL, NULL, 'Extended'); $xml = ''; $options = array( 'formatOptions' => array ( 'xml_seperator' => '', 'element_id' => 'id' ) ); $db2xml->Format->SetOptions($options); if(preg_match('/\/(.*)[\/]/', $path, $matches)) { $table = $matches[1]; } $where = $this->getParameter('where'); if(!empty($table)) { $query = "select * from $table"; if(!empty($where)) { $query .= " where $where"; } $res = $GLOBALS['POOL']->db->query($query); if (PEAR::isError($res) || $res->numRows() == 0) { $xml = "<nothingFound/>"; } else { $xml = $db2xml->getXML($res); } } return $xml; } function contentOnWrite($content) { } }
gpl-2.0
michael42/dmcrypt-static-android
test/shell/vgmerge-operation.sh
2299
#!/bin/sh # Copyright (C) 2007-2008 Red Hat, Inc. All rights reserved. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions # of the GNU General Public License v.2. # # 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 test_description='Test vgmerge operation' . lib/test aux prepare_pvs 4 64 # 'vgmerge succeeds with single linear LV in source VG' vgcreate -c n $vg1 $dev1 $dev2 vgcreate -c n $vg2 $dev3 $dev4 lvcreate -l 4 -n $lv1 $vg1 $dev1 vgchange -an $vg1 check pvlv_counts $vg1 2 1 0 check pvlv_counts $vg2 2 0 0 vgmerge $vg2 $vg1 check pvlv_counts $vg2 4 1 0 vgremove -f $vg2 # 'vgmerge succeeds with single linear LV in source and destination VG' vgcreate -c n $vg1 $dev1 $dev2 vgcreate -c n $vg2 $dev3 $dev4 lvcreate -l 4 -n $lv1 $vg1 lvcreate -l 4 -n $lv2 $vg2 vgchange -an $vg1 vgchange -an $vg2 check pvlv_counts $vg1 2 1 0 check pvlv_counts $vg2 2 1 0 vgmerge $vg2 $vg1 check pvlv_counts $vg2 4 2 0 vgremove -f $vg2 # 'vgmerge succeeds with linear LV + snapshots in source VG' vgcreate -c n $vg1 $dev1 $dev2 vgcreate -c n $vg2 $dev3 $dev4 lvcreate -l 16 -n $lv1 $vg1 lvcreate -l 4 -s -n $lv2 $vg1/$lv1 vgchange -an $vg1 check pvlv_counts $vg1 2 2 1 check pvlv_counts $vg2 2 0 0 vgmerge $vg2 $vg1 check pvlv_counts $vg2 4 2 1 lvremove -f $vg2/$lv2 vgremove -f $vg2 # 'vgmerge succeeds with mirrored LV in source VG' vgcreate -c n $vg1 $dev1 $dev2 $dev3 vgcreate -c n $vg2 $dev4 lvcreate -l 4 -n $lv1 -m1 $vg1 vgchange -an $vg1 check pvlv_counts $vg1 3 1 0 check pvlv_counts $vg2 1 0 0 vgmerge $vg2 $vg1 check pvlv_counts $vg2 4 1 0 lvremove -f $vg2/$lv1 vgremove -f $vg2 # 'vgmerge rejects LV name collision' vgcreate -c n $vg1 $dev1 $dev2 vgcreate -c n $vg2 $dev3 $dev4 lvcreate -l 4 -n $lv1 $vg1 lvcreate -l 4 -n $lv1 $vg2 vgchange -an $vg1 check pvlv_counts $vg1 2 1 0 check pvlv_counts $vg2 2 1 0 not vgmerge $vg2 $vg1 2>err grep "Duplicate logical volume name \"$lv1\" in \"$vg2\" and \"$vg1" err check pvlv_counts $vg1 2 1 0 check pvlv_counts $vg2 2 1 0 vgremove -f $vg1 vgremove -f $vg2
gpl-2.0
ohumbel/rtc2jira
src/main/java/to/rtc/rtc2jira/exporter/jira/entities/Version.java
1511
package to.rtc.rtc2jira.exporter.jira.entities; import java.util.Date; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.codehaus.jackson.map.annotate.JsonView; public class Version extends NamedEntity { String description; boolean archived = false; boolean released = true; Date releaseDate; String project; Integer projectId; @JsonView(IssueView.Filtered.class) @Override public String getKey() { return super.getKey(); } @Override public String getPath() { return "/version"; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isArchived() { return archived; } public void setArchived(boolean archived) { this.archived = archived; } public boolean isReleased() { return released; } public void setReleased(boolean released) { this.released = released; } @XmlJavaTypeAdapter(JiraDateStringAdapter.class) public Date getReleaseDate() { return releaseDate; } public void setReleaseDate(Date releaseDate) { this.releaseDate = releaseDate; } @JsonView(IssueView.Create.class) public String getProject() { return project; } public void setProject(String project) { this.project = project; } public Integer getProjectId() { return projectId; } public void setProjectId(Integer projectId) { this.projectId = projectId; } }
gpl-2.0
shubhamchaudhary/juk
tagguesserconfigdlg.cpp
4971
/** * Copyright (C) 2003 Frerich Raabe <[email protected]> * * 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 "tagguesserconfigdlg.h" #include "tagguesser.h" #include <kicon.h> #include <klocale.h> #include <kpushbutton.h> #include <klineedit.h> #include <kapplication.h> #include <QKeyEvent> #include <QStringListModel> TagGuesserConfigDlg::TagGuesserConfigDlg(QWidget *parent, const char *name) : KDialog(parent) { setObjectName( QLatin1String( name ) ); setModal(true); setCaption(i18n("Tag Guesser Configuration")); setButtons(Ok | Cancel); setDefaultButton(Ok); showButtonSeparator(true); m_child = new TagGuesserConfigDlgWidget(this); setMainWidget(m_child); m_child->bMoveUp->setIcon(KIcon( QLatin1String( "arrow-up" ))); m_child->bMoveDown->setIcon(KIcon( QLatin1String( "arrow-down" ))); m_tagSchemeModel = new QStringListModel(m_child->lvSchemes); m_child->lvSchemes->setModel(m_tagSchemeModel); m_child->lvSchemes->setHeaderHidden(true); m_tagSchemeModel->setStringList(TagGuesser::schemeStrings()); connect(m_child->lvSchemes, SIGNAL(clicked(QModelIndex)), this, SLOT(slotCurrentChanged(QModelIndex))); connect(m_child->bMoveUp, SIGNAL(clicked()), this, SLOT(slotMoveUpClicked())); connect(m_child->bMoveDown, SIGNAL(clicked()), this, SLOT(slotMoveDownClicked())); connect(m_child->bAdd, SIGNAL(clicked()), this, SLOT(slotAddClicked())); connect(m_child->bModify, SIGNAL(clicked()), this, SLOT(slotModifyClicked())); connect(m_child->bRemove, SIGNAL(clicked()), this, SLOT(slotRemoveClicked())); resize( 400, 300 ); } void TagGuesserConfigDlg::slotCurrentChanged(QModelIndex item) { m_child->bRemove->setEnabled(m_tagSchemeModel->rowCount() != 0); // Ensure up/down buttons are appropriately enabled. if (!m_tagSchemeModel->rowCount() || item == m_tagSchemeModel->index(0, 0, QModelIndex())) m_child->bMoveUp->setEnabled(false); else m_child->bMoveUp->setEnabled(true); if (!m_tagSchemeModel->rowCount() || item == m_tagSchemeModel->index(m_tagSchemeModel->rowCount(QModelIndex())-1, 0, QModelIndex())) m_child->bMoveDown->setEnabled(false); else m_child->bMoveDown->setEnabled(true); } void TagGuesserConfigDlg::slotMoveUpClicked() { QModelIndex currentItem = m_child->lvSchemes->currentIndex(); int row = currentItem.row(); m_tagSchemeModel->insertRow(row - 1); // Insert in front of item above row++; // Now we're one row down QModelIndex newItem = m_tagSchemeModel->index(row - 2, 0); // Copy over, then delete old item currentItem = m_tagSchemeModel->index(row, 0); m_tagSchemeModel->setData(newItem, m_tagSchemeModel->data(currentItem, Qt::DisplayRole), Qt::DisplayRole); m_tagSchemeModel->removeRow(row); m_child->lvSchemes->setCurrentIndex(newItem); slotCurrentChanged(newItem); } void TagGuesserConfigDlg::slotMoveDownClicked() { QModelIndex currentItem = m_child->lvSchemes->currentIndex(); int row = currentItem.row(); m_tagSchemeModel->insertRow(row + 2); // Insert in front of 2 items below QModelIndex newItem = m_tagSchemeModel->index(row + 2, 0); // Copy over, then delete old item currentItem = m_tagSchemeModel->index(row, 0); m_tagSchemeModel->setData(newItem, m_tagSchemeModel->data(currentItem, Qt::DisplayRole), Qt::DisplayRole); m_tagSchemeModel->removeRow(row); newItem = m_tagSchemeModel->index(row + 1, 0); m_child->lvSchemes->setCurrentIndex(newItem); slotCurrentChanged(newItem); } void TagGuesserConfigDlg::slotAddClicked() { m_tagSchemeModel->insertRow(0, QModelIndex()); m_child->lvSchemes->setCurrentIndex(m_tagSchemeModel->index(0, 0, QModelIndex())); m_child->lvSchemes->edit(m_child->lvSchemes->currentIndex()); slotCurrentChanged(m_child->lvSchemes->currentIndex()); } void TagGuesserConfigDlg::slotModifyClicked() { m_child->lvSchemes->edit(m_child->lvSchemes->currentIndex()); } void TagGuesserConfigDlg::slotRemoveClicked() { m_tagSchemeModel->removeRow(m_child->lvSchemes->currentIndex().row(), QModelIndex()); slotCurrentChanged(m_child->lvSchemes->currentIndex()); } void TagGuesserConfigDlg::accept() { TagGuesser::setSchemeStrings(m_tagSchemeModel->stringList()); KDialog::accept(); } // vim: set et sw=4 tw=0 sta:
gpl-2.0