code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
package net.minecraft.server; public class IntHashMap { private transient IntHashMapEntry[] a = new IntHashMapEntry[16]; private transient int b; private int c = 12; private final float d = 0.75F; public IntHashMap() {} private static int g(int i) { i ^= i >>> 20 ^ i >>> 12; return i ^ i >>> 7 ^ i >>> 4; } private static int a(int i, int j) { return i & j - 1; } public Object get(int i) { int j = g(i); for (IntHashMapEntry inthashmapentry = this.a[a(j, this.a.length)]; inthashmapentry != null; inthashmapentry = inthashmapentry.c) { if (inthashmapentry.a == i) { return inthashmapentry.b; } } return null; } public boolean b(int i) { return this.c(i) != null; } final IntHashMapEntry c(int i) { int j = g(i); for (IntHashMapEntry inthashmapentry = this.a[a(j, this.a.length)]; inthashmapentry != null; inthashmapentry = inthashmapentry.c) { if (inthashmapentry.a == i) { return inthashmapentry; } } return null; } public void a(int i, Object object) { int j = g(i); int k = a(j, this.a.length); for (IntHashMapEntry inthashmapentry = this.a[k]; inthashmapentry != null; inthashmapentry = inthashmapentry.c) { if (inthashmapentry.a == i) { inthashmapentry.b = object; return; } } this.a(j, i, object, k); } private void h(int i) { IntHashMapEntry[] ainthashmapentry = this.a; int j = ainthashmapentry.length; if (j == 1073741824) { this.c = Integer.MAX_VALUE; } else { IntHashMapEntry[] ainthashmapentry1 = new IntHashMapEntry[i]; this.a(ainthashmapentry1); this.a = ainthashmapentry1; this.c = (int) ((float) i * this.d); } } private void a(IntHashMapEntry[] ainthashmapentry) { IntHashMapEntry[] ainthashmapentry1 = this.a; int i = ainthashmapentry.length; for (int j = 0; j < ainthashmapentry1.length; ++j) { IntHashMapEntry inthashmapentry = ainthashmapentry1[j]; if (inthashmapentry != null) { ainthashmapentry1[j] = null; IntHashMapEntry inthashmapentry1; do { inthashmapentry1 = inthashmapentry.c; int k = a(inthashmapentry.d, i); inthashmapentry.c = ainthashmapentry[k]; ainthashmapentry[k] = inthashmapentry; inthashmapentry = inthashmapentry1; } while (inthashmapentry1 != null); } } } public Object d(int i) { IntHashMapEntry inthashmapentry = this.e(i); return inthashmapentry == null ? null : inthashmapentry.b; } final IntHashMapEntry e(int i) { int j = g(i); int k = a(j, this.a.length); IntHashMapEntry inthashmapentry = this.a[k]; IntHashMapEntry inthashmapentry1; IntHashMapEntry inthashmapentry2; for (inthashmapentry1 = inthashmapentry; inthashmapentry1 != null; inthashmapentry1 = inthashmapentry2) { inthashmapentry2 = inthashmapentry1.c; if (inthashmapentry1.a == i) { --this.b; if (inthashmapentry == inthashmapentry1) { this.a[k] = inthashmapentry2; } else { inthashmapentry.c = inthashmapentry2; } return inthashmapentry1; } inthashmapentry = inthashmapentry1; } return inthashmapentry1; } public void c() { IntHashMapEntry[] ainthashmapentry = this.a; for (int i = 0; i < ainthashmapentry.length; ++i) { ainthashmapentry[i] = null; } this.b = 0; } private void a(int i, int j, Object object, int k) { IntHashMapEntry inthashmapentry = this.a[k]; this.a[k] = new IntHashMapEntry(i, j, object, inthashmapentry); if (this.b++ >= this.c) { this.h(2 * this.a.length); } } static int f(int i) { return g(i); } }
Codecarinas/massive-octo-shame
Server/work/decompile-8eb82bde/net/minecraft/server/IntHashMap.java
Java
cc0-1.0
4,349
var clone = require('clone'); var async = require('async'); Patch.prototype.get_jot_operations = function(callback) { /* Computes an array of JOT object APPLY operations that represent the changes made by this patch. Passes the array to the callback. Each APPLY operation encodes which path it is for. */ var jot_objects = require('../ext/jot/jot/objects.js'); var jot_sequences = require('../ext/jot/jot/sequences.js'); var jot_values = require('../ext/jot/jot/values.js'); var jot_meta = require('../ext/jot/jot/meta.js'); // map each changed file to a JOT operation var patch = this; async.map( Object.keys(patch.files), function(changed_path, callback) { patch.getPathContent(changed_path, true, function(base_content, current_content) { callback( null, // no error jot_objects.APPLY( changed_path, jot_meta.COMPOSITION( // use Google Diff Match Patch to create an array of operations // that represent the changes made to this path jot_sequences.from_diff( base_content, current_content, "words" ) ) ) ); }); }, function(err, results) { callback(results); } ); }; Patch.prototype.compute_rebase = function(jot_op, callback) { // Computes the rebase of the *subtree* headed by this patch // against jot_op, which is a JOT operation object representing // the changes made in the patch we are rebasing against. // // If stop_at is a Patch, then we recurse only as deeply as // as that patch. var patch = this; this.get_jot_operations(function(this_as_jot_op) { // compute the rebase of this patch var jot_base = require('../ext/jot/jot/base.js'); var result = jot_base.rebase_array(jot_op, this_as_jot_op); var inverse_result = jot_base.rebase_array(this_as_jot_op, jot_op); if (!result || !inverse_result) { callback("The changes conflict with the changes in patch " + patch.id + "."); return; } async.map( patch.children, function(child_uuid, callback) { Patch.loadByUUID(child_uuid, function(child_patch) { child_patch.compute_rebase(inverse_result, function(err, result) { if (err) { callback(err); return; } callback(null, [child_uuid, result]) }); }) }, function(err, child_results) { if (err) { callback(err); return; } callback( null, // no error { me: result, children: child_results }); } ); }); } Patch.prototype.save_rebase = function(rebase_data, callback) { // Apply var jot_base = require('../ext/jot/jot/base.js'); var patch = this; // rebase_data.me contains an array of JOT objects APPLY operations, // each specifying the path of a modified file. async.map( rebase_data.me, function(applyop, callback) { // This JOT operation has a key named 'key' which has the // path of a modified file, and another key named 'op' which // has a COMPOSITION operation which will transform the file // contents. var changed_path = applyop.key; patch.getPathContent(changed_path, true, function(base_content) { var rebased_content = jot_base.apply(applyop.op, base_content); patch.writePathContent(changed_path, rebased_content, true); // 'true' overrides sanity checks, since usually we are not allowed to write to patches with children callback(); // no errror & nothing to return }); }, function() { // no error or results are possible // now apply to the children async.map( rebase_data.children || [], function(child_info, callback) { var child_uuid = child_info[0]; var child_rebase_data = child_info[1]; Patch.loadByUUID(child_uuid, function(child_patch) { child_patch.save_rebase(child_rebase_data, callback); }) }, function() { callback(); // done, no error & nothing to return } ); } ); } exports.merge_up = function(patch, callback) { /* Merges a patch with its parent, rebasing any other children of the parent. If the patch has children, the children are moved to be the children of the patch's base. */ if (patch.type == "root") { callback("Cannot merge up a root patch."); return; } // First turn the patch into a JOT operation. patch.get_jot_operations(function(patch_as_jot_op) { // Now attempt to rebase each sibling tree in parallel. patch.getBase(function(base_patch) { // Can't merge into the root patch either. if (base_patch.type == "root") { callback("Cannot merge into a root patch."); return; } // get the other children of base_patch var sibling_uuids = base_patch.children.filter(function(item) { return item != patch.uuid }); // compute the rebase of each sibling async.map( sibling_uuids, function(uuid, callback) { Patch.loadByUUID(uuid, function(sibling_patch) { sibling_patch.compute_rebase(patch_as_jot_op, callback) }) }, function(err, sibling_rebase_data) { if (err) { callback(err); return; } // Now that we know the rebase was successful, we can apply it. // for each modified path in the patch, save the new content // as the contents of the path in the base patch async.map( Object.keys(patch.files), function(changed_path, callback) { patch.getPathContent(changed_path, false, function(base_content, current_content) { base_patch.writePathContent(changed_path, current_content, true); // 'true' overrides sanity checks, since usually we are not allowed to write to patches with children callback(); // no errror & nothing to return }); }, function() { // no error is possible // Delete the patch, with force=true (it's the argument after the callback) // so that the method skips the check if any paths were modified. Since the // base patch has been modified in place, the patch's state is already // inconsistent anyway. Deleting also has the effect of re-setting the patch's // children's bases to be the patch's base rather than the patch itself, // which is good. But note how this creates new siblings. patch.delete(function(err) { if (err) { callback("Really bad error while deleting the patch: " + err + " Workspace is possibly corrupted."); return; } // Now that the base patch has been updated, apply the rebased operations // computed above to update the patch content of the siblings. Use the same // list of siblings from above a) because it's in the same order as // sibling_rebase_data, and b) after patch.delete() the patch may have // new siblings. async.map( Object.keys(sibling_uuids), // => array indexes function(i, callback) { Patch.loadByUUID(sibling_uuids[i], function(sibling_patch) { sibling_patch.save_rebase(sibling_rebase_data[i], callback); }) }, function(err) { if (err) err = "Really bad error while writing rebased patches: " + err + " Workspace is possibly corrupted."; callback(err, base_patch); // done, possibly with an error } ); }, true); // 'true' is the force callback to delete() } ); } ); }); }); } exports.move_to = function(patch, new_base, callback) { /* Reorders the patches. We may be in one of two situations. First check who is a descendant of who. */ if (patch.id == new_base.id) { callback("Cannot move a patch to be a child of itself.") return; } async.map( [patch, new_base], function(item, callback) { item.getAncestors(function(ancestors) { callback(null, ancestors); }); }, function(err, results) { // Who is in whose ancestor list. // Is new_base an ancestor of patch? for (var i = 0; i < results[0].length; i++) { if (results[0][i].id == new_base.id) { move_to_(-1, patch, new_base, results[0].slice(i+1), callback); return; } } // Is patch an ancestor of new_base? for (var i = 0; i < results[1].length; i++) { if (results[1][i].id == patch.id) { move_to_(1, patch, new_base, results[1].slice(i+1), callback); return; } } callback("You cannot move that patch there.") }); } function move_to_(direction, patch, new_base, route, callback) { /* Reorders patches. We may be in one of two cases. A) direction == -1. The patch is a descendant of new_base. Move around patches so that new_base C1 ... CN patch D1 becomes new_base patch C1 ... CN D1 Which means: * C1, new_base's child and an ancestor of patch, goes from being a child of new_base to being a child of patch * patch goes from being a child of CN to being a child of new_base * D1, patch's first child, becomes a child of CN (other children of patch are not affected and are carried along) B) direction == +1. The patch is an ancestor of new_base. Move around patches so that P patch C1 ... new_base D1 becomes P C1 ... new_base patch D1 But C1 may not be present. If C1 is present, this means: * C1, patch's child and an ancestor of new_base, goes from being a child of patch to being a child of P * patch goes from being a child of P to being a child of new_base * D1, new_base's first child, becomes a child of patch (other children of new_base are not affected) If C1 is not present, * new_base, which is patch's child, becomes a child of P * patch goes from being a child of P to being a child of new_base * D1, new_base's first child, becomes a child of patch (other children of new_base are not affected) We can think about this operation as iteratively reversing the order of patch and either its base or first child until we've flipped patch and C1 or new_base. TODO: If there are intermediate children they need to be rebased too? And on patch and new_base? */ if (direction == -1 && patch.base == new_base.uuid) { callback("Nothing to do."); return; } if (direction == 1 && patch.type == "root") { callback("A root patch cannot be moved.") return; } var root_copy = clone(route); if (direction == 1) { root_copy.push(new_base); root_copy.reverse(); } flip_and_iterate( patch, function() { if (root_copy.length == 0) return null; // no more else return root_copy.pop(); }, direction, function(err, rebase_data) { if (err) { callback(err); return; } // Re-jigger the connectivity. This must be done before writing // the rebased patch contents because that will have to look at // the connectivity to compute the new states of the paths. var d1_parent = (direction == -1 ? patch : new_base); if (d1_parent.children.length == 0) save_connectivity(null); else Patch.loadByUUID(d1_parent.children[0], save_connectivity); function save_connectivity(d1, patch_base) { if (direction == -1) { change_patch_parent(route[0], new_base, patch); change_patch_parent(patch, route[route.length-1], new_base); if (d1) change_patch_parent(d1, patch, route[route.length-1]); } else { if (patch_base == null) { patch.getBase(function(base_patch) { save_connectivity(d1, base_patch) }); return; } if (route.length > 0) change_patch_parent(route[0], patch, patch_base); else change_patch_parent(new_base, patch, patch_base); change_patch_parent(patch, patch_base, new_base); if (d1) change_patch_parent(d1, new_base, patch); } // and save new_base.save(); patch.save(); if (patch_base) patch_base.save() if (d1) d1.save(); if (route.length > 0) route[0].save(); if (route.length > 0) route[route.length-1].save(); // Now save the rebased content changes. The changes must be saved // in order because each patch looks at its parent's contents. if (direction == -1) rebase_data.reverse(); function save_rebased_content() { if (rebase_data.length == 0) { callback(); // done } else { var next = rebase_data.shift(); next[0].save_rebase({me: next[1]}, save_rebased_content); } } save_rebased_content(); } } ); } function flip_patches_compute_rebase(a, b) { /* Computes the rebase required to flip two patches, where a is the parent of b. The arguments a and b are arrays of JOT operations. We replace b's operations with b rebased against the inverse of a, and we replace a's operations with a rebased against *that* (= b rebased against the inverse of a). */ var jot_base = require('../ext/jot/jot/base.js'); var a_inv = jot_base.invert_array(a); var b_new = jot_base.rebase_array(a_inv, b); if (!b_new) return false; var a_new = jot_base.rebase_array(b_new, a); if (!a_new) return false; return [a_new, b_new]; } function flip_and_iterate(starting_patch, get_next_item_func, direction, callback) { function iter(item1_ops, rebase_data) { var item2 = get_next_item_func(); if (!item2) { rebase_data.push([starting_patch, item1_ops]); callback(null, rebase_data); // all done return; } item2.get_jot_operations(function(item2_ops) { var rebases; if (direction == 1) { // moving item1 to the right rebases = flip_patches_compute_rebase(item1_ops, item2_ops); } else if (direction == -1) { // moving item1 to the left rebases = flip_patches_compute_rebase(item2_ops, item1_ops); if (rebases) rebases = [rebases[1], rebases[0]]; } if (!rebases) { // fail callback("The patch cannot be moved. There is a conflict with " + item2.id + "."); } else { rebase_data.push([item2, rebases[1]]); // because item2 is now moved and finished iter(rebases[0], rebase_data); // because item1 is carried forward to the next flip } }); } starting_patch.get_jot_operations(function(item1_ops) { iter(item1_ops, []) }); } function change_patch_parent(patch, old_parent, new_parent) { patch.base = new_parent.uuid; old_parent.children.splice(old_parent.children.indexOf(patch.uuid), 1); new_parent.children.push(patch.uuid); }
JoshData/dc-code-editor
editor/management.js
JavaScript
cc0-1.0
14,423
#!/bin/bash set -eu source ../../common-functions.sh PATCHES_FOLDER="mypatches/java.base" MODS_FOLDER="mods/com.greetings" SRC_FOLDER="src" echo "" echo "${info} *** Displaying the contents of the '$SRC_FOLDER' folder *** ${normal}" runTree "$SRC_FOLDER" echo "" echo "${info} *** Compiling a new version of ConcurrentHashMap *** ${normal}" javac --patch-module java.base=src \ -d mypatches/java.base \ src/java.base/java/util/concurrent/ConcurrentHashMap.java echo "" echo "${info} *** Compiling Main class*** ${normal}" javac --module-path mods \ -d mods/com.greetings/ \ src/com.greetings/module-info.java \ src/com.greetings/com/greetings/Main.java echo "" echo "${info} *** Displaying the contents in the '$PATCHES_FOLDER' folder *** ${normal}" runTree "$PATCHES_FOLDER" echo "" echo "${info} *** Displaying the contents in the '$MODS_FOLDER' folder *** ${normal}" runTree "$MODS_FOLDER"
AdoptOpenJDK/jdk9-jigsaw
session-1-jigsaw-intro/07_patch_module_option/compile.sh
Shell
cc0-1.0
933
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta http-equiv="refresh" content="0;url=/2011/06/05/sunday-warning-signals-manuscript-mostly.html" /> </head> </html>
sunbjt/cboettig.github.com
wordpress/archives/1903/index.html
HTML
cc0-1.0
232
package worker import scala.collection.immutable.Queue import akka.actor.Actor import akka.actor.ActorLogging import akka.actor.ActorRef import akka.contrib.pattern.DistributedPubSubExtension import akka.contrib.pattern.DistributedPubSubMediator import akka.contrib.pattern.DistributedPubSubMediator.Put import scala.concurrent.duration.Deadline import scala.concurrent.duration.FiniteDuration import akka.actor.Props import akka.contrib.pattern.ClusterReceptionistExtension import akka.cluster.Cluster import akka.persistence.PersistentActor object Master { val ResultsTopic = "results" def props(workTimeout: FiniteDuration): Props = Props(classOf[Master], workTimeout) case class Ack(workId: String) private sealed trait WorkerStatus private case object Idle extends WorkerStatus private case class Busy(workId: String, deadline: Deadline) extends WorkerStatus private case class WorkerState(ref: ActorRef, status: WorkerStatus) private case object CleanupTick } class Master(workTimeout: FiniteDuration) extends PersistentActor with ActorLogging { import Master._ import WorkState._ val mediator = DistributedPubSubExtension(context.system).mediator ClusterReceptionistExtension(context.system).registerService(self) // persistenceId must include cluster role to support multiple masters override def persistenceId: String = Cluster(context.system).selfRoles.find(_.startsWith("backend-")) match { case Some(role) ⇒ role + "-master" case None ⇒ "master" } // workers state is not event sourced private var workers = Map[String, WorkerState]() // workState is event sourced private var workState = WorkState.empty import context.dispatcher val cleanupTask = context.system.scheduler.schedule(workTimeout / 2, workTimeout / 2, self, CleanupTick) override def postStop(): Unit = cleanupTask.cancel() override def receiveRecover: Receive = { case event: WorkDomainEvent => // only update current state by applying the event, no side effects workState = workState.updated(event) log.info("Replayed {}", event.getClass.getSimpleName) } override def receiveCommand: Receive = { case MasterWorkerProtocol.RegisterWorker(workerId) => if (workers.contains(workerId)) { workers += (workerId -> workers(workerId).copy(ref = sender())) } else { log.info("Worker registered: {}", workerId) workers += (workerId -> WorkerState(sender(), status = Idle)) if (workState.hasWork) sender() ! MasterWorkerProtocol.WorkIsReady } case MasterWorkerProtocol.WorkerRequestsWork(workerId) => if (workState.hasWork) { workers.get(workerId) match { case Some(s @ WorkerState(_, Idle)) => val work = workState.nextWork persist(WorkStarted(work.workId)) { event => workState = workState.updated(event) log.info("Giving worker {} some work {}", workerId, work.workId) workers += (workerId -> s.copy(status = Busy(work.workId, Deadline.now + workTimeout))) sender() ! work } case _ => } } case MasterWorkerProtocol.WorkIsDone(workerId, workId, result) => // idempotent if (workState.isDone(workId)) { // previous Ack was lost, confirm again that this is done sender() ! MasterWorkerProtocol.Ack(workId) } else if (!workState.isInProgress(workId)) { log.info("Work {} not in progress, reported as done by worker {}", workId, workerId) } else { log.info("Work {} is done by worker {}", workId, workerId) changeWorkerToIdle(workerId, workId) persist(WorkCompleted(workId, result)) { event ⇒ workState = workState.updated(event) mediator ! DistributedPubSubMediator.Publish(ResultsTopic, WorkResult(workId, result)) // Ack back to original sender sender ! MasterWorkerProtocol.Ack(workId) } } case MasterWorkerProtocol.WorkFailed(workerId, workId) => if (workState.isInProgress(workId)) { log.info("Work {} failed by worker {}", workId, workerId) changeWorkerToIdle(workerId, workId) persist(WorkerFailed(workId)) { event ⇒ workState = workState.updated(event) notifyWorkers() } } case work: Work => // idempotent if (workState.isAccepted(work.workId)) { sender() ! Master.Ack(work.workId) } else { log.info("Accepted work: {}", work.workId) persist(WorkAccepted(work)) { event ⇒ // Ack back to original sender sender() ! Master.Ack(work.workId) workState = workState.updated(event) notifyWorkers() } } case CleanupTick => for ((workerId, s @ WorkerState(_, Busy(workId, timeout))) ← workers) { if (timeout.isOverdue) { log.info("Work timed out: {}", workId) workers -= workerId persist(WorkerTimedOut(workId)) { event ⇒ workState = workState.updated(event) notifyWorkers() } } } } def notifyWorkers(): Unit = if (workState.hasWork) { // could pick a few random instead of all workers.foreach { case (_, WorkerState(ref, Idle)) => ref ! MasterWorkerProtocol.WorkIsReady case _ => // busy } } def changeWorkerToIdle(workerId: String, workId: String): Unit = workers.get(workerId) match { case Some(s @ WorkerState(_, Busy(`workId`, _))) ⇒ workers += (workerId -> s.copy(status = Idle)) case _ ⇒ // ok, might happen after standby recovery, worker state is not persisted } // TODO cleanup old workers // TODO cleanup old workIds, doneWorkIds }
kitingChris/planetsim2
src/main/scala/worker/Master.scala
Scala
cc0-1.0
5,859
package scorex.crypto.authds.avltree.batch import com.google.common.primitives.Longs import org.scalacheck.commands.Commands import org.scalacheck.{Gen, Prop} import org.scalatest.propspec.AnyPropSpec import scorex.crypto.authds._ import scorex.crypto.hash.{Blake2b256, Digest32} import scorex.utils.{Random => RandomBytes} import scala.util.{Failure, Random, Success, Try} class AVLBatchStatefulSpecification extends AnyPropSpec { property("BatchAVLProver: prove and verify") { AVLCommands.property().check } } object AVLCommands extends Commands { val KL = 32 val VL = 8 val MINIMUM_OPERATIONS_LENGTH = 10 val MAXIMUM_GENERATED_OPERATIONS = 10 val UPDATE_FRACTION = 2 val REMOVE_FRACTION = 4 type T = Digest32 type HF = Blake2b256.type case class Operations(operations: List[Operation]) { def include(ops: List[Operation]): Operations = Operations(operations ++ ops) } case class BatchResult(digest: ADDigest, proof: SerializedAdProof, postDigest: Array[Byte]) override type State = Operations override type Sut = BatchAVLProver[T, HF] val initialState = Operations(operations = List.empty[Operation]) override def canCreateNewSut(newState: State, initSuts: Traversable[State], runningSuts: Traversable[Sut]): Boolean = true override def newSut(state: State): Sut = new BatchAVLProver[T, HF](keyLength = KL, valueLengthOpt = Some(VL)) override def destroySut(sut: Sut): Unit = () override def initialPreCondition(state: State): Boolean = state.operations.isEmpty override def genInitialState: Gen[State] = Gen.const(initialState) override def genCommand(state: State): Gen[Command] = PerformAndVerify(generateOperations(state)) private def nextPositiveLong: Long = Random.nextInt(Int.MaxValue).toLong private def generateOperations(state: State): List[Operation] = { val appendsCommandsLength = Random.nextInt(MAXIMUM_GENERATED_OPERATIONS) + MINIMUM_OPERATIONS_LENGTH val keys = (0 until appendsCommandsLength).map { _ => ADKey @@ RandomBytes.randomBytes(KL) }.toList val removedKeys = state.operations.filter(_.isInstanceOf[Remove]).map(_.key).distinct val prevKeys = state.operations.map(_.key).distinct.filterNot(k1 => removedKeys.exists { k2 => k1.sameElements(k2) }) val uniqueKeys = keys.filterNot(prevKeys.contains).distinct val updateKeys = Random.shuffle(prevKeys).take(safeDivide(prevKeys.length, UPDATE_FRACTION)) val removeKeys = Random.shuffle(prevKeys).take(safeDivide(prevKeys.length, REMOVE_FRACTION)) val appendCommands: List[Operation] = uniqueKeys.map { k => Insert(k, ADValue @@ Longs.toByteArray(nextPositiveLong)) } val updateCommands: List[Operation] = updateKeys.map { k => UpdateLongBy(k, nextPositiveLong) } val removeCommands: List[Operation] = removeKeys.map { k => Remove(k) } appendCommands ++ updateCommands ++ removeCommands } private def safeDivide(base: Int, fraction: Int): Int = if (base > fraction) base / fraction else 0 case class PerformAndVerify(ops: List[Operation]) extends Command { override type Result = BatchResult override def run(sut: Sut): Result = { val digest = sut.digest ops.foreach(sut.performOneOperation) sut.checkTree(postProof = false) val proof = sut.generateProof() sut.checkTree(postProof = true) val postDigest = sut.digest BatchResult(digest, proof, postDigest) } override def nextState(state: Operations): Operations = state.include(ops) override def preCondition(state: Operations): Boolean = true override def postCondition(state: Operations, result: Try[Result]): Prop = { val check = result match { case Success(res) => val verifier = new BatchAVLVerifier[T, HF](res.digest, res.proof, KL, Some(VL)) ops.foreach(verifier.performOneOperation) verifier.digest.exists(_.sameElements(res.postDigest)) case Failure(_) => false } Prop.propBoolean(check) } } }
ScorexProject/scrypto
src/test/scala/scorex/crypto/authds/avltree/batch/AVLBatchStatefulSpecification.scala
Scala
cc0-1.0
4,070
/******************************************************************************* * Copyright (C) 2008, Marek Zawirski <marek.zawirski@gmail.com> * * 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.push; import java.util.ArrayList; import java.util.List; import org.eclipse.egit.core.op.PushOperationResult; import org.eclipse.egit.ui.UIIcons; import org.eclipse.egit.ui.UIText; import org.eclipse.egit.ui.UIUtils; import org.eclipse.egit.ui.internal.WorkbenchStyledLabelProvider; import org.eclipse.egit.ui.internal.commit.CommitEditor; import org.eclipse.egit.ui.internal.commit.RepositoryCommit; import org.eclipse.egit.ui.internal.dialogs.SpellcheckableMessageArea; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.viewers.ColumnViewerToolTipSupport; import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider; import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider; import org.eclipse.jface.viewers.IElementComparer; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.StyledString; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.jgit.lib.ObjectReader; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.RemoteRefUpdate.Status; import org.eclipse.jgit.transport.URIish; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.Tree; /** * Table displaying push operation results. */ class PushResultTable { private static final int TEXT_PREFERRED_HEIGHT = 100; private static final String EMPTY_STRING = ""; //$NON-NLS-1$ private static final String SPACE = " "; //$NON-NLS-1$ private final TreeViewer treeViewer; private final Composite root; private final Image deleteImage; private ObjectReader reader; private Repository repo; PushResultTable(final Composite parent) { root = new Composite(parent, SWT.NONE); GridLayoutFactory.swtDefaults().numColumns(2).applyTo(root); treeViewer = new TreeViewer(root); treeViewer.setAutoExpandLevel(2); addToolbar(root); ColumnViewerToolTipSupport.enableFor(treeViewer); final Tree table = treeViewer.getTree(); GridDataFactory.fillDefaults().grab(true, true).applyTo(table); table.setLinesVisible(true); deleteImage = UIIcons.ELCL16_DELETE.createImage(); UIUtils.hookDisposal(root, deleteImage); root.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { if (reader != null) reader.release(); } }); treeViewer.setComparer(new IElementComparer() { // we need this to keep refresh() working while having custom // equals() in PushOperationResult public boolean equals(Object a, Object b) { return a == b; } public int hashCode(Object element) { return element.hashCode(); } }); final IStyledLabelProvider styleProvider = new WorkbenchStyledLabelProvider() { public StyledString getStyledText(Object element) { // TODO Replace with use of IWorkbenchAdapter3 when 3.6 is no // longer supported if (element instanceof RefUpdateElement) return ((RefUpdateElement) element).getStyledText(element); if (element instanceof RepositoryCommit) return ((RepositoryCommit) element).getStyledText(element); return super.getStyledText(element); } }; treeViewer.setSorter(new ViewerSorter() { public int compare(Viewer viewer, Object e1, Object e2) { if (e1 instanceof RefUpdateElement && e2 instanceof RefUpdateElement) { RefUpdateElement r1 = (RefUpdateElement) e1; RefUpdateElement r2 = (RefUpdateElement) e2; // Put rejected refs first if (r1.isRejected() && !r2.isRejected()) return -1; if (!r1.isRejected() && r2.isRejected()) return 1; // Put new refs next if (r1.isAdd() && !r2.isAdd()) return -1; if (!r1.isAdd() && r2.isAdd()) return 1; // Put branches before tags if (!r1.isTag() && r2.isTag()) return -1; if (r1.isTag() && !r2.isTag()) return 1; Status s1 = r1.getStatus(); Status s2 = r2.getStatus(); // Put up to date refs last if (s1 != Status.UP_TO_DATE && s2 == Status.UP_TO_DATE) return -1; if (s1 == Status.UP_TO_DATE && s2 != Status.UP_TO_DATE) return 1; String ref1 = r1.getDstRefName(); String ref2 = r2.getDstRefName(); if (ref1 != null && ref2 != null) return ref1.compareToIgnoreCase(ref2); } // Don't alter commit ordering if (e1 instanceof RepositoryCommit && e2 instanceof RepositoryCommit) return 0; return super.compare(viewer, e1, e2); } }); treeViewer.setLabelProvider(new DelegatingStyledCellLabelProvider( styleProvider)); treeViewer.setContentProvider(new RefUpdateContentProvider()); // detail message Group messageGroup = new Group(root, SWT.NONE); messageGroup.setText(UIText.PushResultTable_MesasgeText); GridLayoutFactory.swtDefaults().applyTo(messageGroup); GridDataFactory.fillDefaults().grab(true, false).span(2, 1) .applyTo(messageGroup); final SpellcheckableMessageArea text = new SpellcheckableMessageArea( messageGroup, EMPTY_STRING, true, SWT.BORDER) { protected void createMarginPainter() { // Disabled intentionally } }; GridDataFactory.fillDefaults().grab(true, true) .hint(SWT.DEFAULT, TEXT_PREFERRED_HEIGHT).applyTo(text); treeViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { ISelection selection = event.getSelection(); if (!(selection instanceof IStructuredSelection)) { text.setText(EMPTY_STRING); return; } IStructuredSelection structuredSelection = (IStructuredSelection) selection; if (structuredSelection.size() != 1) { text.setText(EMPTY_STRING); return; } Object selected = structuredSelection.getFirstElement(); if (selected instanceof RefUpdateElement) text.setText(getResult((RefUpdateElement) selected)); } }); treeViewer.addOpenListener(new IOpenListener() { public void open(OpenEvent event) { ISelection selection = event.getSelection(); if (selection instanceof IStructuredSelection) for (Object element : ((IStructuredSelection) selection) .toArray()) if (element instanceof RepositoryCommit) CommitEditor.openQuiet((RepositoryCommit) element); } }); } private void addToolbar(Composite parent) { ToolBar toolbar = new ToolBar(parent, SWT.VERTICAL); GridDataFactory.fillDefaults().grab(false, true).applyTo(toolbar); UIUtils.addExpansionItems(toolbar, treeViewer); } private String getResult(RefUpdateElement element) { StringBuilder result = new StringBuilder(EMPTY_STRING); PushOperationResult pushOperationResult = element .getPushOperationResult(); final URIish uri = element.getUri(); result.append(UIText.PushResultTable_repository); result.append(SPACE); result.append(uri.toString()); result.append(Text.DELIMITER); result.append(Text.DELIMITER); String message = element.getRemoteRefUpdate().getMessage(); if (message != null) result.append(message).append(Text.DELIMITER); StringBuilder messagesBuffer = new StringBuilder(pushOperationResult .getPushResult(uri).getMessages()); trim(messagesBuffer); if (messagesBuffer.length() > 0) result.append(messagesBuffer).append(Text.DELIMITER); trim(result); return result.toString(); } private static void trim(StringBuilder s) { // remove leading line breaks while (s.length() > 0 && (s.charAt(0) == '\n' || s.charAt(0) == '\r')) s.deleteCharAt(0); // remove trailing line breaks while (s.length() > 0 && (s.charAt(s.length() - 1) == '\n' || s .charAt(s.length() - 1) == '\r')) s.deleteCharAt(s.length() - 1); } void setData(final Repository localDb, final PushOperationResult result) { reader = localDb.newObjectReader(); repo = localDb; // Set empty result for a while. treeViewer.setInput(null); if (result == null) { root.layout(); return; } final List<RefUpdateElement> results = new ArrayList<RefUpdateElement>(); for (URIish uri : result.getURIs()) if (result.isSuccessfulConnection(uri)) for (RemoteRefUpdate update : result.getPushResult(uri) .getRemoteUpdates()) results.add(new RefUpdateElement(result, update, uri, reader, repo)); treeViewer.setInput(results.toArray()); // select the first row of table to get the details of the first // push result shown in the Text control Tree table = treeViewer.getTree(); if (table.getItemCount() > 0) treeViewer.setSelection(new StructuredSelection(table.getItem(0) .getData())); root.layout(); } Control getControl() { return root; } }
mdoninger/egit
org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/push/PushResultTable.java
Java
epl-1.0
9,918
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.knx.internal.bus; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import tuwien.auto.calimero.GroupAddress; import tuwien.auto.calimero.datapoint.CommandDP; import tuwien.auto.calimero.datapoint.Datapoint; import tuwien.auto.calimero.exception.KNXFormatException; /** * @author Volker Daube * @since 1.6.0 */ public class KNXBusReaderSchedulerTest { private KNXBusReaderScheduler kNXBindingAutoRefreshScheduler; private int dpCount = 0; @Before public void setUp() throws Exception { kNXBindingAutoRefreshScheduler = new KNXBusReaderScheduler(); } @Test public void testStart() throws KNXFormatException { assertFalse(kNXBindingAutoRefreshScheduler.isRunning()); kNXBindingAutoRefreshScheduler.start(); assertTrue(kNXBindingAutoRefreshScheduler.isRunning()); kNXBindingAutoRefreshScheduler.stop(); assertFalse(kNXBindingAutoRefreshScheduler.isRunning()); } @Test public void testAdd() throws KNXFormatException { kNXBindingAutoRefreshScheduler.start(); assertTrue(kNXBindingAutoRefreshScheduler.isRunning()); Datapoint datapoint = createDP("1.001"); assertTrue(kNXBindingAutoRefreshScheduler.scheduleRead(datapoint, 0)); assertFalse(kNXBindingAutoRefreshScheduler.scheduleRead(null, 0)); assertFalse(kNXBindingAutoRefreshScheduler.scheduleRead(null, 1)); assertFalse(kNXBindingAutoRefreshScheduler.scheduleRead(datapoint, -1)); assertTrue(kNXBindingAutoRefreshScheduler.scheduleRead(datapoint, 2)); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } assertTrue(kNXBindingAutoRefreshScheduler.scheduleRead(datapoint, 3)); try { Thread.sleep(7000); } catch (InterruptedException e) { e.printStackTrace(); } kNXBindingAutoRefreshScheduler.clear(); kNXBindingAutoRefreshScheduler.stop(); assertFalse(kNXBindingAutoRefreshScheduler.isRunning()); } @Test public void testLargeNumberOfDPs() throws KNXFormatException { kNXBindingAutoRefreshScheduler.start(); assertTrue(kNXBindingAutoRefreshScheduler.isRunning()); Datapoint datapoint = createDP("1.001"); assertTrue(kNXBindingAutoRefreshScheduler.scheduleRead(datapoint, 1)); datapoint = createDP("1.001"); assertTrue(kNXBindingAutoRefreshScheduler.scheduleRead(datapoint, 1)); datapoint = createDP("1.001"); assertTrue(kNXBindingAutoRefreshScheduler.scheduleRead(datapoint, 1)); datapoint = createDP("1.001"); assertTrue(kNXBindingAutoRefreshScheduler.scheduleRead(datapoint, 1)); datapoint = createDP("2.001"); assertTrue(kNXBindingAutoRefreshScheduler.scheduleRead(datapoint, 2)); datapoint = createDP("2.001"); assertTrue(kNXBindingAutoRefreshScheduler.scheduleRead(datapoint, 2)); datapoint = createDP("2.001"); assertTrue(kNXBindingAutoRefreshScheduler.scheduleRead(datapoint, 2)); datapoint = createDP("2.001"); assertTrue(kNXBindingAutoRefreshScheduler.scheduleRead(datapoint, 2)); datapoint = createDP("2.001"); assertTrue(kNXBindingAutoRefreshScheduler.scheduleRead(datapoint, 10)); datapoint = createDP("2.001"); assertTrue(kNXBindingAutoRefreshScheduler.scheduleRead(datapoint, 11)); datapoint = createDP("2.001"); assertTrue(kNXBindingAutoRefreshScheduler.scheduleRead(datapoint, 12)); datapoint = createDP("2.001"); assertTrue(kNXBindingAutoRefreshScheduler.scheduleRead(datapoint, 13)); try { Thread.sleep(15000); } catch (InterruptedException e) { e.printStackTrace(); } kNXBindingAutoRefreshScheduler.clear(); kNXBindingAutoRefreshScheduler.stop(); assertFalse(kNXBindingAutoRefreshScheduler.isRunning()); } @Test public void testClear() { kNXBindingAutoRefreshScheduler.clear(); } /** * Convenience method creating a Datapoint * * @param dpt datapoint type * @return a new CommandDP * @throws KNXFormatException */ private Datapoint createDP(String dpt) throws KNXFormatException { dpCount++; int mainNumber = Integer.parseInt(dpt.substring(0, dpt.indexOf('.'))); return new CommandDP(new GroupAddress("1/1/" + dpCount), "test" + dpCount, mainNumber, dpt); } }
openhab/openhab
bundles/binding/org.openhab.binding.knx.test/src/test/java/org/openhab/binding/knx/internal/bus/KNXBusReaderSchedulerTest.java
Java
epl-1.0
4,982
/******************************************************************************* * Copyright (c) 2012 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.kernel.feature.provisioning; import java.util.Map; public interface HeaderElementDefinition { public String getSymbolicName(); public Map<String, String> getAttributes(); public Map<String, String> getDirectives(); }
OpenLiberty/open-liberty
dev/com.ibm.ws.kernel.feature.core/src/com/ibm/ws/kernel/feature/provisioning/HeaderElementDefinition.java
Java
epl-1.0
788
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.fmiweather; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.math.BigDecimal; import java.nio.file.Path; import java.util.Optional; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.openhab.binding.fmiweather.internal.client.Data; import org.openhab.binding.fmiweather.internal.client.FMIResponse; import org.openhab.binding.fmiweather.internal.client.Location; /** * Test cases for Client.parseMultiPointCoverageXml with a xml response having single place and multiple * parameters * and timestamps * * @author Sami Salonen - Initial contribution */ @NonNullByDefault public class FMIResponseParsingSinglePlaceTest extends AbstractFMIResponseParsingTest { private Path observations1 = getTestResource("observations_single_place.xml"); @NonNullByDefault({}) private FMIResponse observationsResponse1; @NonNullByDefault({}) private FMIResponse observationsResponse1NaN; private Location emasalo = new Location("Porvoo Emäsalo", "101023", new BigDecimal("60.20382"), new BigDecimal("25.62546")); @BeforeEach public void setUp() { try { observationsResponse1 = parseMultiPointCoverageXml(readTestResourceUtf8(observations1)); observationsResponse1NaN = parseMultiPointCoverageXml( readTestResourceUtf8(observations1).replace("276.0", "NaN")); } catch (Throwable e) { throw new RuntimeException("Test data malformed", e); } assertNotNull(observationsResponse1); } @Test public void testLocationsSinglePlace() { assertThat(observationsResponse1.getLocations().size(), is(1)); assertThat(observationsResponse1.getLocations().stream().findFirst().get(), deeplyEqualTo(emasalo)); } @Test public void testParameters() { // parameters Optional<Set<String>> parametersOptional = observationsResponse1.getParameters(emasalo); Set<String> parameters = parametersOptional.get(); assertThat(parameters.size(), is(6)); assertThat(parameters, hasItems("wd_10min", "wg_10min", "rh", "p_sea", "ws_10min", "t2m")); } @Test public void testGetDataWithInvalidArguments() { Location loc = observationsResponse1.getLocations().stream().findAny().get(); // Invalid parameter or location (fmisid) assertThat(observationsResponse1.getData(loc, "foobar"), is(Optional.empty())); assertThat(observationsResponse1.getData( new Location("Porvoo Emäsalo", "9999999", new BigDecimal("60.20382"), new BigDecimal("25.62546")), "rh"), is(Optional.empty())); } @Test public void testParseObservations1Data() { Data wd_10min = observationsResponse1.getData(emasalo, "wd_10min").get(); assertThat(wd_10min, is(deeplyEqualTo(1552215600L, 60, "312.0", "286.0", "295.0", "282.0", "271.0", "262.0", "243.0", "252.0", "262.0", "276.0"))); } @Test public void testParseObservations1NaN() { // last value is null, due to NaN measurement value Data wd_10min = observationsResponse1NaN.getData(emasalo, "wd_10min").get(); assertThat(wd_10min, is(deeplyEqualTo(1552215600L, 60, "312.0", "286.0", "295.0", "282.0", "271.0", "262.0", "243.0", "252.0", "262.0", null))); } }
MikeJMajor/openhab2-addons-dlinksmarthome
bundles/org.openhab.binding.fmiweather/src/test/java/org/openhab/binding/fmiweather/FMIResponseParsingSinglePlaceTest.java
Java
epl-1.0
3,972
package latis.ops.filter import latis.dm.Function import latis.ops.OperationFactory import latis.dm.Sample import latis.metadata.Metadata import latis.dm.WrappedFunction import latis.util.iterator.MappingIterator import latis.util.LatisServiceException /** * Keep only the first 'limit' samples of any outer Function in the Dataset. */ class LimitFilter(val limit: Int) extends Filter { override def applyToFunction(function: Function): Option[Function] = { //Assume we can hold this all in memory. //get the first 'limit' samples, or all if we had less val samples = function.iterator.take(limit).toList //change length of Function in metadata val md = Metadata(function.getMetadata.getProperties + ("length" -> samples.length.toString)) //make the new function with the updated metadata samples.length match { case 0 => Some(Function(function.getDomain, function.getRange, Iterator.empty, md)) //empty Function with type of original case _ => Some(Function(samples, md)) } } } object LimitFilter extends OperationFactory { override def apply(args: Seq[String]): LimitFilter = { if (args.length > 1) throw new LatisServiceException("The LimitFilter accepts only one argument") try { LimitFilter(args.head.toInt) } catch { case e: NumberFormatException => throw new LatisServiceException("The LimitFilter requires an integer argument") } } def apply(limit: Int): LimitFilter = new LimitFilter(limit) def unapply(lf: LimitFilter): Option[Int] = Some(lf.limit) }
dlindhol/LaTiS
src/main/scala/latis/ops/filter/LimitFilter.scala
Scala
epl-1.0
1,577
/******************************************************************************* * Copyright (c) 2020 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 *******************************************************************************/ /** * @version 1.0.0 */ @org.osgi.annotation.versioning.Version("1.0.0") package io.openliberty.security.common.config;
OpenLiberty/open-liberty
dev/com.ibm.ws.security.common/src/io/openliberty/security/common/config/package-info.java
Java
epl-1.0
657
/******************************************************************************* * Copyright (c) 2020 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 *******************************************************************************/ @org.osgi.annotation.versioning.Version("1.0") package io.openliberty.grpc.internal.client.config;
OpenLiberty/open-liberty
dev/io.openliberty.grpc.1.0.internal.client/src/io/openliberty/grpc/internal/client/config/package-info.java
Java
epl-1.0
634
/******************************************************************************* * Copyright (c) 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.jca.utils.xml.ra.v10; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * */ @XmlType(name = "securityPermissionType", propOrder = { "description", "securityPermissionSpec" }) public class Ra10SecurityPermission { @XmlElement(name = "description") private String description; @XmlElement(name = "security-permission-spec", required = true) private String securityPermissionSpec; /** * @return the description */ public String getDescription() { return description; } /** * @return the securityPermissionSpec */ public String getSecurityPermissionSpec() { return securityPermissionSpec; } }
OpenLiberty/open-liberty
dev/com.ibm.ws.jca.utils/src/com/ibm/ws/jca/utils/xml/ra/v10/Ra10SecurityPermission.java
Java
epl-1.0
1,269
/*! * Copyright 2002 - 2013 Webdetails, a Pentaho company. All rights reserved. * * This software was developed by Webdetails and is provided under the terms * of the Mozilla Public License, Version 2.0, or any later version. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails. * * Software distributed under the Mozilla Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations. */ /*! * Copyright 2002 - 2013 Webdetails, a Pentaho company. All rights reserved. * * This software was developed by Webdetails and is provided under the terms * of the Mozilla Public License, Version 2.0, or any later version. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails. * * Software distributed under the Mozilla Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations. */ /*! Copyright 2010 Stanford Visualization Group, Mike Bostock, BSD license. */ /*! 0a846e02116638f4d7f3c88a223ee1ae23f0cb3f */ /* * TERMS OF USE - EASING EQUATIONS * * Open source under the BSD License. * * Copyright 2001 Robert Penner * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of the author nor the names of contributors may be used to * endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ pen.define("cdf/lib/CCC/protovis", function() { function genNumberTicks(N, min, max, options) { var ticks, span = max - min; if (span && isFinite(span)) { var precision = pv.parseNumNonNeg(pv.get(options, "precision", 0)), precisionMin = pv.parseNumNonNeg(pv.get(options, "precisionMin", 0)), precisionMax = pv.parseNumNonNeg(pv.get(options, "precisionMax", 1/0)), roundInside = pv.get(options, "roundInside", !0); isFinite(precision) || (precision = 0); isFinite(precisionMin) || (precisionMin = 0); precisionMax || (precisionMax = 1/0); var exponentMin = pv.get(options, "numberExponentMin"), exponentMax = pv.get(options, "numberExponentMax"); null != exponentMin && isFinite(exponentMin) && (precisionMin = Math.max(precisionMin, Math.pow(10, Math.floor(exponentMin)))); null != exponentMax && isFinite(exponentMax) && (precisionMax = Math.min(precisionMax, 5 * Math.pow(10, Math.floor(exponentMax)))); if (roundInside) { precisionMin > span && (precisionMin = span); precisionMax > span && (precisionMax = span); } precisionMin > precisionMax && (precisionMax = precisionMin); precision ? precision = Math.max(Math.min(precision, precisionMax), precisionMin) : precisionMin === precisionMax && (precision = precisionMin); var result, precMin, precMax, NObtained, overflow = 0, fixed = !!precision; if (fixed) { result = { base: Math.abs(precision), mult: 1, value: 1 }; result.value = result.base; } else { var NMax = pv.parseNumNonNeg(pv.get(options, "tickCountMax", 1/0)); 1 > NMax && (NMax = 1); null == N ? N = Math.min(10, NMax) : isFinite(N) ? N > NMax && (N = NMax) : N = isFinite(NMax) ? NMax : 10; result = { base: isFinite(N) ? pv.logFloor(span / N, 10) : 0, mult: 1, value: 1 }; result.value = result.base; if (precisionMin > 0) { precMin = readNumberPrecision(precisionMin, !0); if (result.value < precMin.value) { numberCopyResult(result, precMin); overflow = -1; } } if (isFinite(precisionMax)) { precMax = readNumberPrecision(precisionMax, !1); if (precMin && precMax.value <= precMin.value) precMax = null; else if (precMax.value < result.value) { numberCopyResult(result, precMax); overflow = 1; } } if (1 !== overflow && isFinite(N) && result.mult < 10) { NObtained = span / result.base; if (NObtained > N) { var err = N / NObtained; .15 >= err ? result.mult = 10 : result.mult < 5 && (.35 >= err ? result.mult = 5 : result.mult < 2 && .75 >= err && (result.mult = 2)); if (result.mult > 1) { result.value = result.base * result.mult; if (precMin && result.value < precMin.value) { numberCopyResult(result, precMin); overflow = -1; } else if (precMax && precMax.value < result.value) { numberCopyResult(result, precMax); overflow = 1; } else if (10 === result.mult) { result.base *= 10; result.mult = 1; } } } } } for (var resultPrev; ;) { var step = result.value, start = step * Math[roundInside ? "ceil" : "floor"](min / step), end = step * Math[roundInside ? "floor" : "ceil"](max / step); if (resultPrev && (start > end || precMax && end - start > precMax.value)) { result = resultPrev; break; } var exponent = Math.floor(pv.log(step, 10) + 1e-10); result.decPlaces = Math.max(0, -exponent); result.ticks = pv.range(start, end + step, step); if (fixed || overflow > 0 || result.ticks.length <= NMax) break; if (resultPrev && resultPrev.ticks.length <= result.ticks.length) { result = resultPrev; break; } result = numberResultAbove(resultPrev = result); } ticks = result.ticks; ticks.step = result.value; ticks.base = result.base; ticks.mult = result.mult; ticks.decPlaces = result.decPlaces; ticks.format = pv.Format.number().fractionDigits(result.decPlaces); } else { ticks = [ +min ]; ticks.step = ticks.base = ticks.mult = 1; ticks.decPlaces = 0; ticks.format = pv.Format.number().fractionDigits(0); } return ticks; } function numberCopyResult(to, from) { to.base = from.base; to.mult = from.mult; to.value = from.value; return to; } function numberResultAbove(result) { var out = numberCopyResult({}, result); switch (out.mult) { case 5: out.mult = 1; out.base *= 10; break; case 2: out.mult = 5; break; case 1: out.mult = 2; } out.value = out.base * out.mult; return out; } function readNumberPrecision(precision, isMin) { 0 > precision && (precision = -precision); var base = pv.logFloor(precision, 10), mult = precision / base; isMin ? mult > 5 ? (mult = 1, base *= 10) : mult = mult > 2 ? 5 : mult > 1 ? 2 : 1 : mult = mult >= 5 ? 5 : mult >= 2 ? 2 : 1; return { base: base, mult: mult, value: base * mult, source: precision }; } function newDate(x) { return new Date(x); } function genDateTicks(N, min, max, precision, format, weekStart, options) { var ticks, span = max - min; if (span && isFinite(span)) { precision = parseDatePrecision(pv.get(options, "precision"), precision); var precisionMin = parseDatePrecision(pv.get(options, "precisionMin"), 0), precisionMax = parseDatePrecision(pv.get(options, "precisionMax"), 1/0); precisionMin > precisionMax && (precisionMax = precisionMin); precision ? precision = Math.max(Math.min(precision, precisionMax), precisionMin) : precisionMin === precisionMax && (precision = precisionMin); var NMax = pv.parseNumNonNeg(pv.get(options, "tickCountMax", 1/0)); 2 > NMax && (NMax = 2); N = Math.min(null == N ? 5 : N, NMax); for (var precResultPrev, keyArgs = { weekStart: weekStart, roundInside: pv.get(options, "roundInside", 1) }, precResult = chooseDatePrecision(N, span, precision, precisionMin, precisionMax, keyArgs), fixed = precResult.fixed, overflow = precResult.overflow; ;) { precResult.ticks = ticks = precResult.comp.ticks(min, max, precResult.mult, keyArgs); if (precResultPrev && precResult.precMax && ticks[ticks.length - 1] - ticks[0] > precResult.precMax.value) { precResult = precResultPrev; break; } if (fixed || overflow > 0 || precResult.ticks.length <= NMax) break; if (precResultPrev && precResultPrev.ticks.length <= precResult.ticks.length) { precResult = precResultPrev; break; } precResultPrev = precResult; precResult = precResult.comp.resultAbove(precResult.mult); } ticks = precResult.ticks; ticks.step = precResult.value; ticks.base = precResult.comp.value; ticks.mult = precResult.mult; ticks.format = parseTickDateFormat(format) || precResult.comp.format; } else { ticks = [ newDate(min) ]; ticks.step = ticks.base = ticks.mult = 1; ticks.format = pv.Format.date("%x"); } return ticks; } function chooseDatePrecision(N, span, precision, precisionMin, precisionMax, options) { var dateComp, castResult, precMin, precMax, overflow = 0, mult = 1, fixed = !!precision; if (precision) { castResult = readDatePrecision(precision, !1); if (castResult.value !== precision) dateComp = castResult.comp.withPrecision(precision); else { dateComp = castResult.comp; mult = castResult.mult; } } else { if (isFinite(N)) { dateComp = getGreatestLessOrEqualDateComp(span, N); mult = dateComp.multiple(span / dateComp.value, options); } else { dateComp = lowestPrecisionValueDateComp(); mult = 1; } precision = dateComp.value * mult; precisionMin > precision && (precMin = readDatePrecision(precisionMin, !0)); precision > precisionMax && (precMax = readDatePrecision(precisionMax, !1)); if (precMin && precision < precMin.value) { dateComp = precMin.comp; mult = precMin.mult; overflow = -1; } else if (precMax && precisionMin < precMax.value && precMax.value < precision) { dateComp = precMax.comp; mult = precMax.mult; overflow = 1; } } return { comp: dateComp, mult: mult, value: dateComp.value * mult, source: precision, overflow: overflow, fixed: fixed, precMin: precMin, precMax: precMax }; } function readDatePrecision(precision, ceil) { return null == precision || 0 >= precision || !isFinite(precision) ? null : (ceil ? lowestPrecisionValueDateComp : highestPrecisionValueDateComp)().castValue(precision, ceil); } function DateComponent(value, prev, keyArgs) { this.value = value; this.mult = keyArgs.mult || 1; this.base = 1 === this.mult ? this.value : Math.floor(this.value / this.mult); dateCompCopyArgs.forEach(function(p) { null != keyArgs[p] && (this[p] = keyArgs[p]); }, this); keyArgs.floor && (this.floorLocal = keyArgs.floor); this.format = parseTickDateFormat(keyArgs.format); this.first = pv.functor(keyArgs.first || 0); this.prev = prev; this.next = null; prev && (prev.next = this); } function parseTickDateFormat(format) { return null == format ? null : "function" == typeof format ? format : pv.Format.date(format); } function firstWeekStartOfMonth(date, dateTickWeekStart) { var d = new Date(date.getFullYear(), date.getMonth(), 1), wd = dateTickWeekStart - d.getDay(); if (wd) { 0 > wd && (wd += 7); d.setDate(d.getDate() + wd); } return d; } function parseDatePrecision(value, dv) { if ("string" == typeof value) { var n = +value; if (isNaN(n)) { if (value) { var m = /^(\d*)([a-zA-Z]+)$/.exec(value); if (m) { value = parseDateInterval(m[2]); value && (value *= +m[1] || 1); } } } else value = n; } ("number" != typeof value || 0 > value) && (value = null != dv ? dv : 0); return value; } function parseDateInterval(s) { switch (s) { case "y": return 31536e6; case "m": return 2592e6; case "w": return 6048e5; case "d": return 864e5; case "h": return 36e5; case "M": return 6e4; case "s": return 1e3; case "ms": return 1; } } function defDateComp(value, keyArgs) { var prev = highestPrecisionValueDateComp(); _dateComps.push(new DateComponent(value, prev, keyArgs)); } function lowestPrecisionValueDateComp() { return _dateComps[0]; } function highestPrecisionValueDateComp() { return _dateComps.length ? _dateComps[_dateComps.length - 1] : null; } function getGreatestLessOrEqualDateComp(length, N) { null == N && (N = 1); var comp, prev = highestPrecisionValueDateComp(); do comp = prev; while (length < N * comp.value && (prev = comp.prev)); return comp; } Array.prototype.map || (Array.prototype.map = function(f, o) { for (var n = this.length, result = new Array(n), i = 0; n > i; i++) i in this && (result[i] = f.call(o, this[i], i, this)); return result; }); Array.prototype.filter || (Array.prototype.filter = function(f, o) { for (var n = this.length, result = new Array(), i = 0; n > i; i++) if (i in this) { var v = this[i]; f.call(o, v, i, this) && result.push(v); } return result; }); Array.prototype.forEach || (Array.prototype.forEach = function(f, o) { for (var n = this.length >>> 0, i = 0; n > i; i++) i in this && f.call(o, this[i], i, this); }); Array.prototype.reduce || (Array.prototype.reduce = function(f, v) { var len = this.length; if (!len && 1 == arguments.length) throw new Error("reduce: empty array, no initial value"); var i = 0; if (arguments.length < 2) for (;;) { if (i in this) { v = this[i++]; break; } if (++i >= len) throw new Error("reduce: no values, no initial value"); } for (;len > i; i++) i in this && (v = f(v, this[i], i, this)); return v; }); Array.prototype.indexOf || (Array.prototype.indexOf = function(s, from) { for (var n = this.length >>> 0, i = !isFinite(from) || 0 > from ? 0 : from > this.length ? this.length : from; n > i; i++) if (this[i] === s) return i; return -1; }); Date.now || (Date.now = function() { return +new Date(); }); Object.create || (Object.create = function(proto) { function g() {} g.prototype = proto; return new g(); }); var pv = {}; pv.version = { major: 3, minor: 3 }; pv.identity = function(x) { return x; }; pv.index = function() { return this.index; }; pv.child = function() { return this.childIndex; }; pv.parent = function() { return this.parent.index; }; !function() { pv.extend = function(f) { return Object.create(f.prototype || f); }; pv.extendType = function(g, f) { var sub = g.prototype = pv.extend(f); sub.constructor = g; return g; }; pv.parse = function(js) { for (var m, d, re = new RegExp("function\\s*(\\b\\w+)?\\s*\\([^)]*\\)\\s*", "mg"), i = 0, s = ""; m = re.exec(js); ) { var j = m.index + m[0].length; if ("{" != js.charAt(j)) { s += js.substring(i, j) + "{return "; i = j; for (var p = 0; p >= 0 && j < js.length; j++) { var c = js.charAt(j); switch (c) { case '"': case "'": for (;++j < js.length && (d = js.charAt(j)) != c; ) "\\" == d && j++; break; case "[": case "(": p++; break; case "]": case ")": p--; break; case ";": case ",": 0 == p && p--; } } s += pv.parse(js.substring(i, --j)) + ";}"; i = j; } re.lastIndex = j; } s += js.substring(i); return s; }; pv.error = function(e) { "undefined" != typeof console && console.error ? console.error(e) : alert(e); }; pv.listen = function(target, type, listener) { listener = pv.listener(listener); if ("load" === type || "onload" === type) return pv.listenForPageLoad(listener); if (target.addEventListener) target.addEventListener(type, listener, !1); else { target === window && (target = document.documentElement); target.attachEvent("on" + type, listener); } return listener; }; pv.unlisten = function(target, type, listener) { listener.$listener && (listener = listener.$listener); target.removeEventListener ? target.removeEventListener(type, listener, !1) : target.detachEvent("on" + type, listener); }; pv.listenForPageLoad = function(listener) { "complete" !== document.readyState ? document.addEventListener ? window.addEventListener("load", listener, !1) : document.attachEvent && window.attachEvent("onload", listener) : listener(null); }; pv.listener = function(f) { return f.$listener || (f.$listener = function(ev) { try { pv.event = ev = ev && pv.fixEvent(ev); return f.call(this, ev); } catch (ex) { pv.error(ex); } finally { delete pv.event; } }); }; pv.fixEvent = function(ev) { if (null == ev.pageX && null != ev.clientX) { var eventDoc = ev.target && ev.target.ownerDocument || document, doc = eventDoc.documentElement, body = eventDoc.body; ev.pageX = 1 * ev.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); ev.pageY = 1 * ev.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } return ev; }; pv.ancestor = function(a, e) { for (;e; ) { if (e === a) return !0; e = e.parentNode; } return !1; }; pv.removeChildren = function(p) { for (;p.lastChild; ) p.removeChild(p.lastChild); }; pv.getWindow = function(elem) { return null != elem && elem == elem.window ? elem : 9 === elem.nodeType ? elem.defaultView || elem.parentWindow : !1; }; var _reHiphenSep = /\-([a-z])/g; pv.hiphen2camel = function(prop) { return _reHiphenSep.test(prop) ? prop.replace(_reHiphenSep, function($0, $1) { return $1.toUpperCase(); }) : prop; }; var _getCompStyle = window.getComputedStyle; pv.css = function(e, p) { return _getCompStyle ? _getCompStyle.call(window, e, null).getPropertyValue(p) : e.currentStyle["float" === p ? "styleFloat" : pv.hiphen2camel(p)]; }; pv.cssStyle = function(e) { var style; if (_getCompStyle) { style = _getCompStyle.call(window, e, null); return function(p) { return style.getPropertyValue(p); }; } style = e.currentStyle; return function(p) { return style["float" === p ? "styleFloat" : pv.hiphen2camel(p)]; }; }; pv._getElementsByClass = function(searchClass, node) { null == node && (node = document); for (var classElements = [], els = node.getElementsByTagName("*"), L = els.length, pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)"), i = 0, j = 0; L > i; i++) if (pattern.test(els[i].className)) { classElements[j] = els[i]; j++; } return classElements; }; pv.getElementsByClassName = function(node, classname) { return node.getElementsByClassName ? node.getElementsByClassName(classname) : pv._getElementsByClass(classname, node); }; pv.elementOffset = function(elem) { var doc = elem && elem.ownerDocument; if (doc) { var body = doc.body; if (body !== elem) { var box; box = "undefined" != typeof elem.getBoundingClientRect ? elem.getBoundingClientRect() : { top: 0, left: 0 }; var win = pv.getWindow(doc), docElem = doc.documentElement, clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, scrollTop = win.pageYOffset || docElem.scrollTop, scrollLeft = win.pageXOffset || docElem.scrollLeft; return { top: box.top + scrollTop - clientTop, left: box.left + scrollLeft - clientLeft }; } } }; pv.renderer = function() { var renderer = document.svgImplementation || "nativesvg"; pv.renderer = function() { return renderer; }; return renderer; }; var _id = 1; pv.id = function() { return _id++; }; pv.functor = function(v) { return "function" == typeof v ? v : function() { return v; }; }; pv.stringLowerCase = function(s) { return String(s).toLowerCase(); }; pv.get = function(o, p, dv) { var v; return o && null != (v = o[p]) ? v : dv; }; var hasOwn = Object.prototype.hasOwnProperty; pv.lazyArrayOwn = function(o, p) { var v; return o && hasOwn.call(o, p) && (v = o[p]) ? v : o[p] = []; }; pv.parseNumNonNeg = function(v, dv) { null != v && ("string" == typeof v ? v = +v : "number" != typeof v && (v = null)); return null == v || isNaN(v) || 0 > v ? null == dv ? 0 : dv : v; }; var epsilon = pv.epsilon = 1e-6; pv.floatLess = function(a, b) { return !pv.floatEqual(a, b) && b > a; }; pv.floatLessOrEqual = function(a, b) { return b > a || pv.floatEqual(a, b); }; pv.floatGreater = function(a, b) { return !pv.floatEqual(a, b) && a > b; }; pv.floatEqual = function(a, b) { return Math.abs(b - a) < epsilon; }; pv.floatZero = function(value) { return Math.abs(value) < epsilon; }; pv.floatBelongsOpen = function(min, value, max) { return pv.floatLess(min, value) && pv.floatLess(value, max); }; pv.floatBelongsClosed = function(min, value, max) { return pv.floatLessOrEqual(min, value) && pv.floatLessOrEqual(value, max); }; }(); pv.listen(window, "load", function() { pv.$ = { i: 0, x: document.getElementsByTagName("script") }; pv.$.xlen = pv.$.x.length; for (;pv.$.i < pv.$.xlen; pv.$.i++) { pv.$.s = pv.$.x[pv.$.i]; if ("text/javascript+protovis" == pv.$.s.type) try { window.eval(pv.parse(pv.$.s.text)); } catch (e) { pv.error(e); } } delete pv.$; }); pv.Format = {}; pv.Format.re = function(s) { return s.replace(/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g, "\\$&"); }; pv.Format.pad = function(c, n, s) { var m = n - String(s).length; return 1 > m ? s : new Array(m + 1).join(c) + s; }; pv.Format.date = function(pattern) { function format(d) { return pattern.replace(/%[a-zA-Z0-9]/g, function(s) { switch (s) { case "%a": return [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ][d.getDay()]; case "%A": return [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ][d.getDay()]; case "%h": case "%b": return [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ][d.getMonth()]; case "%B": return [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ][d.getMonth()]; case "%c": return d.toLocaleString(); case "%C": return pad("0", 2, Math.floor(d.getFullYear() / 100) % 100); case "%d": return pad("0", 2, d.getDate()); case "%x": case "%D": return pad("0", 2, d.getMonth() + 1) + "/" + pad("0", 2, d.getDate()) + "/" + pad("0", 2, d.getFullYear() % 100); case "%e": return pad(" ", 2, d.getDate()); case "%H": return pad("0", 2, d.getHours()); case "%I": var h = d.getHours() % 12; return h ? pad("0", 2, h) : 12; case "%m": return pad("0", 2, d.getMonth() + 1); case "%M": return pad("0", 2, d.getMinutes()); case "%n": return "\n"; case "%p": return d.getHours() < 12 ? "AM" : "PM"; case "%T": case "%X": case "%r": var h = d.getHours() % 12; return (h ? pad("0", 2, h) : 12) + ":" + pad("0", 2, d.getMinutes()) + ":" + pad("0", 2, d.getSeconds()) + " " + (d.getHours() < 12 ? "AM" : "PM"); case "%R": return pad("0", 2, d.getHours()) + ":" + pad("0", 2, d.getMinutes()); case "%S": return pad("0", 2, d.getSeconds()); case "%Q": return pad("0", 3, d.getMilliseconds()); case "%t": return " "; case "%u": var w = d.getDay(); return w ? w : 1; case "%w": return d.getDay(); case "%y": return pad("0", 2, d.getFullYear() % 100); case "%Y": return d.getFullYear(); case "%%": return "%"; } return s; }); } var pad = pv.Format.pad; format.format = format; format.parse = function(s) { var year = 1970, month = 0, date = 1, hour = 0, minute = 0, second = 0, fields = [ function() {} ], re = pv.Format.re(pattern).replace(/%[a-zA-Z0-9]/g, function(s) { switch (s) { case "%b": fields.push(function(x) { month = { Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5, Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov: 10, Dec: 11 }[x]; }); return "([A-Za-z]+)"; case "%h": case "%B": fields.push(function(x) { month = { January: 0, February: 1, March: 2, April: 3, May: 4, June: 5, July: 6, August: 7, September: 8, October: 9, November: 10, December: 11 }[x]; }); return "([A-Za-z]+)"; case "%e": case "%d": fields.push(function(x) { date = x; }); return "([0-9]+)"; case "%I": case "%H": fields.push(function(x) { hour = x; }); return "([0-9]+)"; case "%m": fields.push(function(x) { month = x - 1; }); return "([0-9]+)"; case "%M": fields.push(function(x) { minute = x; }); return "([0-9]+)"; case "%p": fields.push(function(x) { 12 == hour ? "am" == x && (hour = 0) : "pm" == x && (hour = Number(hour) + 12); }); return "(am|pm)"; case "%S": fields.push(function(x) { second = x; }); return "([0-9]+)"; case "%y": fields.push(function(x) { x = Number(x); year = x + (x >= 0 && 69 > x ? 2e3 : x >= 69 && 100 > x ? 1900 : 0); }); return "([0-9]+)"; case "%Y": fields.push(function(x) { year = x; }); return "([0-9]+)"; case "%%": fields.push(function() {}); return "%"; } return s; }), match = s.match(re); match && match.forEach(function(m, i) { fields[i](m); }); return new Date(year, month, date, hour, minute, second); }; return format; }; pv.Format.time = function(type) { function format(t) { t = Number(t); switch (type) { case "short": return t >= 31536e6 ? (t / 31536e6).toFixed(1) + " years" : t >= 6048e5 ? (t / 6048e5).toFixed(1) + " weeks" : t >= 864e5 ? (t / 864e5).toFixed(1) + " days" : t >= 36e5 ? (t / 36e5).toFixed(1) + " hours" : t >= 6e4 ? (t / 6e4).toFixed(1) + " minutes" : (t / 1e3).toFixed(1) + " seconds"; case "long": var a = [], s = t % 6e4 / 1e3 >> 0, m = t % 36e5 / 6e4 >> 0; a.push(pad("0", 2, s)); if (t >= 36e5) { var h = t % 864e5 / 36e5 >> 0; a.push(pad("0", 2, m)); if (t >= 864e5) { a.push(pad("0", 2, h)); a.push(Math.floor(t / 864e5).toFixed()); } else a.push(h.toFixed()); } else a.push(m.toFixed()); return a.reverse().join(":"); } } var pad = pv.Format.pad; format.format = format; format.parse = function(s) { switch (type) { case "short": for (var a, re = /([0-9,.]+)\s*([a-z]+)/g, t = 0; a = re.exec(s); ) { var f = parseFloat(a[0].replace(",", "")), u = 0; switch (a[2].toLowerCase()) { case "year": case "years": u = 31536e6; break; case "week": case "weeks": u = 6048e5; break; case "day": case "days": u = 864e5; break; case "hour": case "hours": u = 36e5; break; case "minute": case "minutes": u = 6e4; break; case "second": case "seconds": u = 1e3; } t += f * u; } return t; case "long": var a = s.replace(",", "").split(":").reverse(), t = 0; a.length && (t += 1e3 * parseFloat(a[0])); a.length > 1 && (t += 6e4 * parseFloat(a[1])); a.length > 2 && (t += 36e5 * parseFloat(a[2])); a.length > 3 && (t += 864e5 * parseFloat(a[3])); return t; } }; return format; }; pv.Format.number = function() { function format(x) { 1/0 > maxf && (x = Math.round(x * maxk) / maxk); var s = String(Math.abs(x)).split("."), i = s[0]; i.length > maxi && (i = i.substring(i.length - maxi)); padg && i.length < mini && (i = new Array(mini - i.length + 1).join(padi) + i); i.length > 3 && (i = i.replace(/\B(?=(?:\d{3})+(?!\d))/g, group)); !padg && i.length < mins && (i = new Array(mins - i.length + 1).join(padi) + i); s[0] = 0 > x ? np + i + ns : i; var f = s[1] || ""; f.length > maxf && (f = s[1] = f.substr(0, maxf)); f.length < minf && (s[1] = f + new Array(minf - f.length + 1).join(padf)); return s.join(decimal); } var mini = 0, maxi = 1/0, mins = 0, minf = 0, maxf = 0, maxk = 1, padi = "0", padf = "0", padg = !0, decimal = ".", group = ",", np = "−", ns = ""; format.format = format; format.parse = function(x) { var re = pv.Format.re, s = String(x).split(decimal); 1 == s.length && (s[1] = ""); s[0].replace(new RegExp("^(" + re(padi) + ")*"), ""); s[1].replace(new RegExp("(" + re(padf) + ")*$"), ""); var i = s[0].replace(new RegExp(re(group), "g"), ""); i.length > maxi && (i = i.substring(i.length - maxi)); var f = s[1] ? Number("0." + s[1]) : 0; 1/0 > maxf && (f = Math.round(f * maxk) / maxk); return Math.round(i) + f; }; format.integerDigits = function(min, max) { if (arguments.length) { mini = Number(min); maxi = arguments.length > 1 ? Number(max) : mini; mins = mini + Math.floor(mini / 3) * group.length; return this; } return [ mini, maxi ]; }; format.fractionDigits = function(min, max) { if (arguments.length) { minf = Number(min); maxf = arguments.length > 1 ? Number(max) : minf; maxk = Math.pow(10, maxf); return this; } return [ minf, maxf ]; }; format.integerPad = function(x) { if (arguments.length) { padi = String(x); padg = /\d/.test(padi); return this; } return padi; }; format.fractionPad = function(x) { if (arguments.length) { padf = String(x); return this; } return padf; }; format.decimal = function(x) { if (arguments.length) { decimal = String(x); return this; } return decimal; }; format.group = function(x) { if (arguments.length) { group = x ? String(x) : ""; mins = mini + Math.floor(mini / 3) * group.length; return this; } return group; }; format.negativeAffix = function(x, y) { if (arguments.length) { np = String(x || ""); ns = String(y || ""); return this; } return [ np, ns ]; }; return format; }; !function() { var _cache; pv.Text = {}; pv.Text.createCache = function() { return new FontSizeCache(); }; pv.Text.usingCache = function(cache, fun, ctx) { if (!(cache instanceof FontSizeCache)) throw new Error("Not a valid cache."); var prevCache = _cache; _cache = cache; try { return fun.call(ctx); } finally { _cache = prevCache; } }; pv.Text.measure = function(text, font) { text = null == text ? "" : String(text); var bbox = _cache && _cache.get(font, text); if (!bbox) { bbox = text ? this.measureCore(text, font) : { width: 0, height: 0 }; _cache && _cache.put(font, text, bbox); } return bbox; }; pv.Text.measureWidth = function(text, font) { return pv.Text.measure(text, font).width; }; pv.Text.fontHeight = function(font) { return pv.Text.measure("M", font).height; }; pv.Text.measureCore = function() { function getTextSizeElement() { return _svgText || (_svgText = createTextSizeElement()); } function createTextSizeElement() { var div = document.createElement("div"); div.id = "pvSVGText_" + new Date().getTime(); var style = div.style; style.position = "absolute"; style.visibility = "hidden"; style.width = 0; style.height = 0; style.left = 0; style.top = 0; style.lineHeight = 1; style.textTransform = "none"; style.letterSpacing = "normal"; style.whiteSpace = "nowrap"; var svgElem = pv.SvgScene.create("svg"); svgElem.setAttribute("font-size", "10px"); svgElem.setAttribute("font-family", "sans-serif"); div.appendChild(svgElem); var svgText = pv.SvgScene.create("text"); svgElem.appendChild(svgText); svgText.appendChild(document.createTextNode("")); document.body.appendChild(div); return svgText; } var _svgText, _lastFont = "10px sans-serif"; return function(text, font) { font || (font = null); var svgText = getTextSizeElement(); if (_lastFont !== font) { _lastFont = font; pv.SvgScene.setStyle(svgText, { font: font }); } svgText.firstChild.nodeValue = String(text); var box; try { box = svgText.getBBox(); } catch (ex) { "function" == typeof console.error && console.error("GetBBox failed: ", ex); throw ex; } return { width: box.width, height: box.height }; }; }(); var FontSizeCache = function() { this._fontsCache = {}; }, hasOwnProp = Object.prototype.hasOwnProperty; FontSizeCache.prototype._getFont = function(font) { font = font || ""; return hasOwnProp.call(this._fontsCache, font) ? this._fontsCache[font] : this._fontsCache[font] = {}; }; FontSizeCache.prototype.get = function(font, text) { text = text || ""; var fontCache = this._getFont(font); return hasOwnProp.call(fontCache, text) ? fontCache[text] : null; }; FontSizeCache.prototype.put = function(font, text, size) { return this._getFont(font)[text || ""] = size; }; }(); pv.map = function(array, f) { var o = {}; return f ? array.map(function(d, i) { o.index = i; return f.call(o, d); }) : array.slice(); }; pv.repeat = function(array, n) { 1 == arguments.length && (n = 2); return pv.blend(pv.range(n).map(function() { return array; })); }; pv.array = function(len, dv) { var a = len >= 0 ? new Array(len) : []; if (void 0 !== dv) for (var i = 0; len > i; i++) a[i] = dv; return a; }; pv.cross = function(a, b) { for (var array = [], i = 0, n = a.length, m = b.length; n > i; i++) for (var j = 0, x = a[i]; m > j; j++) array.push([ x, b[j] ]); return array; }; pv.blend = function(arrays) { return Array.prototype.concat.apply([], arrays); }; pv.transpose = function(arrays) { var n = arrays.length, m = pv.max(arrays, function(d) { return d.length; }); if (m > n) { arrays.length = m; for (var i = n; m > i; i++) arrays[i] = new Array(n); for (var i = 0; n > i; i++) for (var j = i + 1; m > j; j++) { var t = arrays[i][j]; arrays[i][j] = arrays[j][i]; arrays[j][i] = t; } } else { for (var i = 0; m > i; i++) arrays[i].length = n; for (var i = 0; n > i; i++) for (var j = 0; i > j; j++) { var t = arrays[i][j]; arrays[i][j] = arrays[j][i]; arrays[j][i] = t; } } arrays.length = m; for (var i = 0; m > i; i++) arrays[i].length = n; return arrays; }; pv.normalize = function(array, f) { for (var norm = pv.map(array, f), sum = pv.sum(norm), i = 0; i < norm.length; i++) norm[i] /= sum; return norm; }; pv.permute = function(array, indexes, f) { f || (f = pv.identity); var p = new Array(indexes.length), o = {}; indexes.forEach(function(j, i) { o.index = j; p[i] = f.call(o, array[j]); }); return p; }; pv.numerate = function(keys, f) { f || (f = pv.identity); var map = {}, o = {}; keys.forEach(function(x, i) { o.index = i; map[f.call(o, x)] = i; }); return map; }; pv.uniq = function(array, f) { f || (f = pv.identity); var y, map = {}, keys = [], o = {}; array.forEach(function(x, i) { o.index = i; y = f.call(o, x); y in map || (map[y] = keys.push(y)); }); return keys; }; pv.naturalOrder = function(a, b) { return b > a ? -1 : a > b ? 1 : 0; }; pv.reverseOrder = function(b, a) { return b > a ? -1 : a > b ? 1 : 0; }; pv.search = function(array, value, f) { f || (f = pv.identity); for (var low = 0, high = array.length - 1; high >= low; ) { var mid = low + high >> 1, midValue = f(array[mid]); if (value > midValue) low = mid + 1; else { if (!(midValue > value)) return mid; high = mid - 1; } } return -low - 1; }; pv.search.index = function(array, value, f) { var i = pv.search(array, value, f); return 0 > i ? -i - 1 : i; }; pv.range = function(start, stop, step) { if (1 == arguments.length) { stop = start; start = 0; } void 0 == step && (step = 1); if ((stop - start) / step == 1/0) throw new Error("range must be finite"); var j, array = [], i = 0; stop -= 1e-10 * (stop - start); if (0 > step) for (;(j = start + step * i++) > stop; ) array.push(j); else for (;(j = start + step * i++) < stop; ) array.push(j); return array; }; pv.random = function(start, stop, step) { if (1 == arguments.length) { stop = start; start = 0; } void 0 == step && (step = 1); return step ? Math.floor(Math.random() * (stop - start) / step) * step + start : Math.random() * (stop - start) + start; }; pv.sum = function(array, f) { var o = {}; return array.reduce(f ? function(p, d, i) { o.index = i; return p + f.call(o, d); } : function(p, d) { return p + d; }, 0); }; pv.max = function(array, f) { return f == pv.index ? array.length - 1 : Math.max.apply(null, f ? pv.map(array, f) : array); }; pv.max.index = function(array, f) { if (!array.length) return -1; if (f == pv.index) return array.length - 1; f || (f = pv.identity); for (var maxi = 0, maxx = -1/0, o = {}, i = 0; i < array.length; i++) { o.index = i; var x = f.call(o, array[i]); if (x > maxx) { maxx = x; maxi = i; } } return maxi; }; pv.min = function(array, f) { return f == pv.index ? 0 : Math.min.apply(null, f ? pv.map(array, f) : array); }; pv.min.index = function(array, f) { if (!array.length) return -1; if (f == pv.index) return 0; f || (f = pv.identity); for (var mini = 0, minx = 1/0, o = {}, i = 0; i < array.length; i++) { o.index = i; var x = f.call(o, array[i]); if (minx > x) { minx = x; mini = i; } } return mini; }; pv.mean = function(array, f) { return pv.sum(array, f) / array.length; }; pv.median = function(array, f) { if (f == pv.index) return (array.length - 1) / 2; array = pv.map(array, f).sort(pv.naturalOrder); if (array.length % 2) return array[Math.floor(array.length / 2)]; var i = array.length / 2; return (array[i - 1] + array[i]) / 2; }; pv.variance = function(array, f) { if (array.length < 1) return 0/0; if (1 == array.length) return 0; var mean = pv.mean(array, f), sum = 0, o = {}; f || (f = pv.identity); for (var i = 0; i < array.length; i++) { o.index = i; var d = f.call(o, array[i]) - mean; sum += d * d; } return sum; }; pv.deviation = function(array, f) { return Math.sqrt(pv.variance(array, f) / (array.length - 1)); }; pv.log = function(x, b) { return Math.log(x) / Math.log(b); }; pv.logSymmetric = function(x, b) { return 0 == x ? 0 : 0 > x ? -pv.log(-x, b) : pv.log(x, b); }; pv.logAdjusted = function(x, b) { if (!isFinite(x)) return x; var negative = 0 > x; b > x && (x += (b - x) / b); return negative ? -pv.log(x, b) : pv.log(x, b); }; pv.logFloor = function(x, b) { return x > 0 ? Math.pow(b, Math.floor(pv.log(x, b))) : -Math.pow(b, -Math.floor(-pv.log(-x, b))); }; pv.logCeil = function(x, b) { return x > 0 ? Math.pow(b, Math.ceil(pv.log(x, b))) : -Math.pow(b, -Math.ceil(-pv.log(-x, b))); }; !function() { var _radians = Math.PI / 180, _degrees = 180 / Math.PI; pv.radians = function(degrees) { return _radians * degrees; }; pv.degrees = function(radians) { return _degrees * radians; }; }(); pv.keys = function(map) { var array = []; for (var key in map) array.push(key); return array; }; pv.entries = function(map) { var array = []; for (var key in map) array.push({ key: key, value: map[key] }); return array; }; pv.values = function(map) { var array = []; for (var key in map) array.push(map[key]); return array; }; pv.dict = function(keys, f) { for (var m = {}, o = {}, i = 0; i < keys.length; i++) if (i in keys) { var k = keys[i]; o.index = i; m[k] = f.call(o, k); } return m; }; pv.hasOwnProp = Object.prototype.hasOwnProperty; pv.copyOwn = function(a, b) { if (b) { var hop = pv.hasOwnProp; for (var p in b) hop.call(b, p) && (a[p] = b[p]); } return a; }; pv.dom = function(map) { return new pv.Dom(map); }; pv.Dom = function(map) { this.$map = map; }; pv.Dom.prototype.$leaf = function(n) { return "object" != typeof n; }; pv.Dom.prototype.leaf = function(f) { if (arguments.length) { this.$leaf = f; return this; } return this.$leaf; }; pv.Dom.prototype.root = function(nodeName) { function recurse(map) { var n = new pv.Dom.Node(); for (var k in map) { var v = map[k]; n.appendChild(leaf(v) ? new pv.Dom.Node(v) : recurse(v)).nodeName = k; } return n; } var leaf = this.$leaf, root = recurse(this.$map); root.nodeName = nodeName; return root; }; pv.Dom.prototype.nodes = function() { return this.root().nodes(); }; pv.Dom.Node = function(value) { void 0 !== value && (this.nodeValue = value); }; pv.Dom.Node.prototype.nodeValue = void 0; pv.Dom.Node.prototype.childNodes = []; pv.Dom.Node.prototype.parentNode = null; pv.Dom.Node.prototype.firstChild = null; pv.Dom.Node.prototype.lastChild = null; pv.Dom.Node.prototype.previousSibling = null; pv.Dom.Node.prototype.nextSibling = null; pv.Dom.Node.prototype._firstDirtyChildIndex = 1/0; pv.Dom.Node.prototype._childIndex = -1; pv.Dom.Node.prototype.findChildIndex = function(n) { if (!n) throw new Error("Argument 'n' required"); if (n.parentNode === this) { var i = n.childIndex(!0); if (i > -1) return i; } throw new Error("child not found"); }; pv.Dom.Node.prototype._childRemoved = function() {}; pv.Dom.Node.prototype._childAdded = function() {}; pv.Dom.Node.prototype.removeChild = function(n) { var i = this.findChildIndex(n); return this.removeAt(i); }; pv.Dom.Node.prototype.appendChild = function(n) { var pn = n.parentNode; pn && pn.removeChild(n); var lc = this.lastChild; n.parentNode = this; n.previousSibling = lc; if (lc) { lc.nextSibling = n; n._childIndex = lc._childIndex + 1; } else { this.firstChild = n; n._childIndex = 0; } this.lastChild = n; var L = pv.lazyArrayOwn(this, "childNodes").push(n); this._childAdded(n, L - 1); return n; }; pv.Dom.Node.prototype.insertBefore = function(n, r) { if (!r) return this.appendChild(n); var i = this.findChildIndex(r); return this.insertAt(n, i); }; pv.Dom.Node.prototype.insertAt = function(n, i) { if (null == i) return this.appendChild(n); var ns = this.childNodes, L = ns.length; if (i === L) return this.appendChild(n); if (0 > i || i > L) throw new Error("Index out of range."); var pn = n.parentNode; pn && pn.removeChild(n); var ni = i + 1; ni < this._firstDirtyChildIndex && (this._firstDirtyChildIndex = ni); var r = ns[i]; n.parentNode = this; n.nextSibling = r; n._childIndex = i; var psib = n.previousSibling = r.previousSibling; r.previousSibling = n; if (psib) psib.nextSibling = n; else { r === this.lastChild && (this.lastChild = n); this.firstChild = n; } ns.splice(i, 0, n); this._childAdded(n, i); return n; }; pv.Dom.Node.prototype.removeAt = function(i) { var ns = this.childNodes, L = ns.length; if (!(0 > i || i >= L)) { var n = ns[i]; ns.splice(i, 1); L - 1 > i && i < this._firstDirtyChildIndex && (this._firstDirtyChildIndex = i); var psib = n.previousSibling, nsib = n.nextSibling; psib ? psib.nextSibling = nsib : this.firstChild = nsib; nsib ? nsib.previousSibling = psib : this.lastChild = psib; n.nextSibling = n.previousSibling = n.parentNode = null; this._childRemoved(n, i); return n; } }; pv.Dom.Node.prototype.replaceChild = function(n, r) { var i = this.findChildIndex(r), pn = n.parentNode; pn && pn.removeChild(n); n.parentNode = this; n.nextSibling = r.nextSibling; n._childIndex = r._childIndex; var psib = n.previousSibling = r.previousSibling; psib ? psib.nextSibling = n : this.firstChild = n; var nsib = r.nextSibling; nsib ? nsib.previousSibling = n : this.lastChild = n; this.childNodes[i] = n; this._childRemoved(r, i); this._childAdded(n, i); return r; }; pv.Dom.Node.prototype.childIndex = function(noRebuild) { var p = this.parentNode; if (p) { var di = p._firstDirtyChildIndex; if (1/0 > di) { var ns = p.childNodes; if (!noRebuild) return ns.indexOf(this); for (var L = ns.length; L > di; ) { ns[di]._childIndex = di; di++; } p._firstDirtyChildIndex = 1/0; } return this._childIndex; } return -1; }; pv.Dom.Node.prototype.visitBefore = function(f) { function visit(n, d) { f(n, d); for (var c = n.firstChild; c; c = c.nextSibling) visit(c, d + 1); } visit(this, 0); }; pv.Dom.Node.prototype.visitAfter = function(f) { function visit(n, d) { for (var c = n.firstChild; c; c = c.nextSibling) visit(c, d + 1); f(n, d); } visit(this, 0); }; pv.Dom.Node.prototype.sort = function(f) { if (this.firstChild) { this._firstDirtyChildIndex = 1/0; var cs = this.childNodes; cs.sort(f); var c, p = this.firstChild = cs[0]; delete p.previousSibling; p._childIndex = 0; for (var i = 1, L = cs.length; L > i; i++) { p.sort(f); c = cs[i]; c._childIndex = i; c.previousSibling = p; p = p.nextSibling = c; } this.lastChild = p; delete p.nextSibling; p.sort(f); } return this; }; pv.Dom.Node.prototype.reverse = function() { var childNodes = []; this.visitAfter(function(n) { this._firstDirtyChildIndex = 1/0; for (var c; c = n.lastChild; ) childNodes.push(n.removeChild(c)); if (childNodes.length) for (;c = childNodes.pop(); ) n.insertBefore(c, n.firstChild); }); return this; }; pv.Dom.Node.prototype.nodes = function() { var array = []; this.visitBefore(function(n) { array.push(n); }); return array; }; pv.Dom.Node.prototype.toggle = function(recursive) { if (recursive) return this.toggled ? this.visitBefore(function(n) { n.toggled && n.toggle(); }) : this.visitAfter(function(n) { n.toggled || n.toggle(); }); var c, n = this; if (n.toggled) { for (;c = n.toggled.pop(); ) n.appendChild(c); delete n.toggled; } else if (c = n.lastChild) { n.toggled = []; do n.toggled.push(n.removeChild(c)); while (c = n.lastChild); } }; pv.nodes = function(values) { for (var root = new pv.Dom.Node(), i = 0, V = values.length; V > i; i++) root.appendChild(new pv.Dom.Node(values[i])); return root.nodes(); }; pv.tree = function(array) { return new pv.Tree(array); }; pv.Tree = function(array) { this.array = array; }; pv.Tree.prototype.keys = function(k) { this.k = k; return this; }; pv.Tree.prototype.value = function(v) { this.v = v; return this; }; pv.Tree.prototype.map = function() { for (var map = {}, o = {}, i = 0; i < this.array.length; i++) { o.index = i; for (var value = this.array[i], keys = this.k.call(o, value), node = map, j = 0; j < keys.length - 1; j++) node = node[keys[j]] || (node[keys[j]] = {}); node[keys[j]] = this.v ? this.v.call(o, value) : value; } return map; }; pv.nest = function(array) { return new pv.Nest(array); }; pv.Nest = function(array) { this.array = array; this.keys = []; }; pv.Nest.prototype.key = function(key) { this.keys.push(key); return this; }; pv.Nest.prototype.sortKeys = function(order) { this.keys[this.keys.length - 1].order = order || pv.naturalOrder; return this; }; pv.Nest.prototype.sortValues = function(order) { this.order = order || pv.naturalOrder; return this; }; pv.Nest.prototype.map = function() { for (var i, map = {}, values = [], j = 0; j < this.array.length; j++) { var x = this.array[j], m = map; for (i = 0; i < this.keys.length - 1; i++) { var k = this.keys[i](x); m[k] || (m[k] = {}); m = m[k]; } k = this.keys[i](x); if (!m[k]) { var a = []; values.push(a); m[k] = a; } m[k].push(x); } if (this.order) for (var i = 0; i < values.length; i++) values[i].sort(this.order); return map; }; pv.Nest.prototype.entries = function() { function entries(map) { var array = []; for (var k in map) { var v = map[k]; array.push({ key: k, values: v instanceof Array ? v : entries(v) }); } return array; } function sort(array, i) { var o = this.keys[i].order; o && array.sort(function(a, b) { return o(a.key, b.key); }); if (++i < this.keys.length) for (var j = 0; j < array.length; j++) sort.call(this, array[j].values, i); return array; } return sort.call(this, entries(this.map()), 0); }; pv.Nest.prototype.rollup = function(f) { function rollup(map) { for (var key in map) { var value = map[key]; value instanceof Array ? map[key] = f(value) : rollup(value); } return map; } return rollup(this.map()); }; pv.flatten = function(map) { return new pv.Flatten(map); }; pv.Flatten = function(map) { this.map = map; this.keys = []; }; pv.Flatten.prototype.key = function(key, f) { this.keys.push({ name: key, value: f }); delete this.$leaf; return this; }; pv.Flatten.prototype.leaf = function(f) { this.keys.length = 0; this.$leaf = f; return this; }; pv.Flatten.prototype.array = function() { function recurse(value, i) { if (leaf(value)) entries.push({ keys: stack.slice(), value: value }); else for (var key in value) { stack.push(key); recurse(value[key], i + 1); stack.pop(); } } function visit(value, i) { if (i < keys.length - 1) for (var key in value) { stack.push(key); visit(value[key], i + 1); stack.pop(); } else entries.push(stack.concat(value)); } var entries = [], stack = [], keys = this.keys, leaf = this.$leaf; if (leaf) { recurse(this.map, 0); return entries; } visit(this.map, 0); return entries.map(function(stack) { for (var m = {}, i = 0; i < keys.length; i++) { var k = keys[i], v = stack[i]; m[k.name] = k.value ? k.value.call(null, v) : v; } return m; }); }; pv.Transform = function() {}; pv.Transform.prototype = { k: 1, x: 0, y: 0 }; pv.Transform.identity = new pv.Transform(); pv.Transform.prototype.translate = function(x, y) { var v = new pv.Transform(); v.k = this.k; v.x = this.k * x + this.x; v.y = this.k * y + this.y; return v; }; pv.Transform.prototype.scale = function(k) { var v = new pv.Transform(); v.k = this.k * k; v.x = this.x; v.y = this.y; return v; }; pv.Transform.prototype.invert = function() { var v = new pv.Transform(), k = 1 / this.k; v.k = k; v.x = -this.x * k; v.y = -this.y * k; return v; }; pv.Transform.prototype.times = function(m) { var v = new pv.Transform(); v.k = this.k * m.k; v.x = this.k * m.x + this.x; v.y = this.k * m.y + this.y; return v; }; pv.Scale = function() {}; pv.Scale.interpolator = function(start, end) { if ("number" == typeof start) return function(t) { return t * (end - start) + start; }; var startGradient = start.type && "solid" !== start.type, endGradient = end.type && "solid" !== end.type; if (startGradient || endGradient) { start = startGradient ? start : pv.color(start).rgb(); end = endGradient ? end : pv.color(end).rgb(); return function(t) { return .5 > t ? start : end; }; } start = pv.color(start).rgb(); end = pv.color(end).rgb(); return function(t) { var a = start.a * (1 - t) + end.a * t; 1e-5 > a && (a = 0); return 0 == start.a ? pv.rgb(end.r, end.g, end.b, a) : 0 == end.a ? pv.rgb(start.r, start.g, start.b, a) : pv.rgb(Math.round(start.r * (1 - t) + end.r * t), Math.round(start.g * (1 - t) + end.g * t), Math.round(start.b * (1 - t) + end.b * t), a); }; }; pv.Scale.common = { by: function(f) { function by() { return scale(f.apply(this, arguments)); } var scale = this; for (var method in scale) by[method] = scale[method]; return by; }, by1: function(f) { function by1(x) { return scale(f.call(this, x)); } var scale = this; for (var method in scale) by1[method] = scale[method]; return by1; }, transform: function(t) { function transfScale() { return t.call(this, scale.apply(scale, arguments)); } var scale = this; for (var method in scale) transfScale[method] = scale[method]; return transfScale; } }; pv.Scale.quantitative = function() { function scale(x) { var j = pv.search(d, x); 0 > j && (j = -j - 2); j = Math.max(0, Math.min(i.length - 1, j)); return i[j]((f(x) - l[j]) / (l[j + 1] - l[j])); } var dateTickFormat, dateTickPrecision, lastTicks, d = [ 0, 1 ], l = [ 0, 1 ], r = [ 0, 1 ], i = [ pv.identity ], type = Number, n = !1, f = pv.identity, g = pv.identity, tickFormatter = null, dateTickWeekStart = 0; scale.transform = function(forward, inverse) { f = function(x) { return n ? -forward(-x) : forward(x); }; g = function(y) { return n ? -inverse(-y) : inverse(y); }; l = d.map(f); return this; }; scale.domain = function(array, min, max) { if (arguments.length) { var o; if (array instanceof Array) { arguments.length < 2 && (min = pv.identity); arguments.length < 3 && (max = min); o = array.length && min(array[0]); d = array.length ? [ pv.min(array, min), pv.max(array, max) ] : []; } else { o = array; d = Array.prototype.slice.call(arguments).map(Number); } d.length ? 1 == d.length && (d = [ d[0], d[0] ]) : d = [ -1/0, 1/0 ]; n = (d[0] || d[d.length - 1]) < 0; l = d.map(f); type = o instanceof Date ? newDate : Number; return this; } return d.map(type); }; scale.range = function() { if (arguments.length) { r = Array.prototype.slice.call(arguments); r.length ? 1 == r.length && (r = [ r[0], r[0] ]) : r = [ -1/0, 1/0 ]; i = []; for (var j = 0; j < r.length - 1; j++) i.push(pv.Scale.interpolator(r[j], r[j + 1])); return this; } return r; }; scale.invert = function(y) { var j = pv.search(r, y); 0 > j && (j = -j - 2); j = Math.max(0, Math.min(i.length - 1, j)); return type(g(l[j] + (y - r[j]) / (r[j + 1] - r[j]) * (l[j + 1] - l[j]))); }; scale.ticks = function(N, options) { var start = d[0], end = d[d.length - 1], reverse = start > end, min = reverse ? end : start, max = reverse ? start : end; lastTicks = type === newDate ? genDateTicks(N, min, max, dateTickPrecision, dateTickFormat, dateTickWeekStart, options) : genNumberTicks(N, min, max, options); return reverse ? lastTicks.reverse() : lastTicks; }; scale.dateTickFormat = function() { if (arguments.length) { dateTickFormat = arguments[0]; return this; } return dateTickFormat; }; scale.dateTickPrecision = function() { if (arguments.length) { dateTickPrecision = parseDatePrecision(arguments[0], 0); return this; } return dateTickPrecision; }; scale.dateTickWeekStart = function(weekStart) { if (arguments.length) { switch (("" + weekStart).toLowerCase()) { case "0": case "sunday": dateTickWeekStart = 0; break; case "1": case "monday": dateTickWeekStart = 1; break; case "2": case "tuesday": dateTickWeekStart = 2; break; case "3": case "wednesday": dateTickWeekStart = 3; break; case "4": case "thursday": dateTickWeekStart = 4; break; case "5": case "friday": dateTickWeekStart = 5; break; case "6": case "saturday": dateTickWeekStart = 6; break; default: dateTickWeekStart = 0; } return this; } return dateTickWeekStart; }; scale.tickFormatter = function(f) { if (arguments.length) { tickFormatter = f; return this; } return tickFormatter; }; scale.tickFormat = function(t, index) { var text; if (tickFormatter) { if (!lastTicks) { lastTicks = []; lastTicks.step = lastTicks.base = lastTicks.mult = 1; lastTicks.decPlaces = 0; lastTicks.format = String; } var precision = type !== Number ? lastTicks.step : lastTicks.decPlaces; text = tickFormatter.call(lastTicks, t, precision, null != index ? index : -1); } else text = lastTicks ? lastTicks.format(t) : String(t); return text; }; scale.nice = function() { if (2 != d.length) return this; var start = d[0], end = d[d.length - 1], reverse = start > end, min = reverse ? end : start, max = reverse ? start : end, span = max - min; if (!span || !isFinite(span)) return this; var step = Math.pow(10, Math.round(Math.log(span) / Math.log(10)) - 1); d = [ Math.floor(min / step) * step, Math.ceil(max / step) * step ]; reverse && d.reverse(); l = d.map(f); return this; }; pv.copyOwn(scale, pv.Scale.common); scale.domain.apply(scale, arguments); return scale; }; var dateCompCopyArgs = [ "get", "set", "multiple", "multiples", "thresholds", "closeds", "castValue" ]; DateComponent.prototype.increment = function(d, n) { null == n && (n = 1); 1 !== this.mult && (n *= this.mult); this.set(d, this.get(d) + n); }; DateComponent.prototype.get = function(d) { return d.getMilliseconds(); }; DateComponent.prototype.set = function(d, v) { d.setMilliseconds(v); }; DateComponent.prototype.floorLocal = function() {}; DateComponent.prototype.floor = function(d, options) { var skip = 0; if (1 !== this.mult) { this.floorLocal(d, options); skip = this.base; } for (var comp = this.prev; comp; ) { 1 === comp.mult && comp.value !== skip && comp.clear(d, options); comp = comp.prev; } }; DateComponent.prototype.floorMultiple = function(d, n, options) { var first = this.first(d, options), delta = this.get(d) - first; if (delta) { var M = n * this.mult, offset = Math.floor(delta / M) * M; this.set(d, first + offset); } }; DateComponent.prototype.clear = function(d, options) { this.set(d, this.first(d, options)); }; DateComponent.prototype.multiple = function(N) { for (var ms = this.multiples, ts = this.thresholds, cl = this.closeds, L = ms.length, i = -1; ++i < L; ) if (cl[i] ? N <= ts[i] : N < ts[i]) return ms[i]; throw new Error("Invalid configuration."); }; DateComponent.prototype.resultAbove = function(mult) { return this.castValue(this.value * mult + .1, !0); }; DateComponent.prototype.castValue = function(value, ceil) { var ms = this.multiples; if (!ms) return this._castValueResult(1, value, 1); var i, m = value / this.value, L = ms.length; if (ceil) { i = -1; for (;++i < L; ) if (m <= ms[i]) return this._castValueResult(ms[i], value, 0); return this.next ? this.next.castValue(value, ceil) : this._castValueResult(ms[L - 1], value, 1); } i = L; for (;i--; ) if (ms[i] <= m) return this._castValueResult(ms[i], value, 0); return this.prev ? this.prev.castValue(value, ceil) : this._castValueResult(ms[0], value, -1); }; DateComponent.prototype._castValueResult = function(mult, value, overflow) { return { comp: this, mult: mult, value: this.value * mult, source: value, overflow: overflow }; }; DateComponent.prototype.withPrecision = function(value) { var comp = this; this.value !== value && (comp = new DateComponent(value, null, { mult: value, format: this.format })); return comp; }; DateComponent.prototype.ticks = function(min, max, mult, options) { var ticks = [], tick = new Date(min); this.floor(tick, options); mult > 1 && this.floorMultiple(tick, mult, options); if (pv.get(options, "roundInside", 1)) { min !== +tick && this.increment(tick, mult); do { ticks.push(new Date(tick)); this.increment(tick, mult); } while (max >= tick); } else { ticks.push(new Date(tick)); do { this.increment(tick, mult); ticks.push(new Date(tick)); } while (max > tick); } return ticks; }; var _dateComps = []; defDateComp(1, { format: "%S.%Qs", multiples: [ 1, 5, 25, 50, 100, 250 ], thresholds: [ 10, 50, 100, 200, 1e3, 1/0 ], closeds: [ 1, 1, 1, 1, 1, 1 ] }); defDateComp(1e3, { get: function(d) { return d.getSeconds(); }, set: function(d, v) { d.setSeconds(v); }, format: "%I:%M:%S", multiples: [ 1, 5, 10, 15 ], thresholds: [ 10, 60, 90, 1/0 ], closeds: [ 1, 1, 1, 1 ] }); defDateComp(6e4, { get: function(d) { return d.getMinutes(); }, set: function(d, v) { d.setMinutes(v); }, format: "%I:%M %p", multiples: [ 1, 5, 10, 15 ], thresholds: [ 10, 15, 30, 1/0 ], closeds: [ 1, 1, 1, 1 ] }); defDateComp(36e5, { get: function(d) { return d.getHours(); }, set: function(d, v) { d.setHours(v); }, format: "%I:%M %p", multiples: [ 1, 3, 6 ], thresholds: [ 10, 20, 1/0 ], closeds: [ 1, 1, 1 ] }); defDateComp(864e5, { get: function(d) { return d.getDate(); }, set: function(d, v) { d.setDate(v); }, format: "%m/%d", first: 1, multiples: [ 1, 2, 3, 5 ], thresholds: [ 10, 15, 30, 1/0 ], closeds: [ 1, 0, 0, 1 ] }); defDateComp(6048e5, { get: function(d) { return d.getDate(); }, set: function(d, v) { d.setDate(v); }, mult: 7, floor: function(d, options) { var wd = d.getDay() - pv.get(options, "weekStart", 0); if (0 !== wd) { 0 > wd && (wd += 7); this.set(d, this.get(d) - wd); } }, first: function(d, options) { return this.get(firstWeekStartOfMonth(d, pv.get(options, "weekStart", 0))); }, format: "%m/%d", multiples: [ 1, 2, 3 ], thresholds: [ 10, 15, 1/0 ], closeds: [ 1, 1, 1 ] }); defDateComp(2592e6, { get: function(d) { return d.getMonth(); }, set: function(d, v) { d.setMonth(v); }, format: "%m/%Y", multiples: [ 1, 2, 3 ], thresholds: [ 12, 24, 1/0 ], closeds: [ 1, 1, 1 ] }); defDateComp(31536e6, { get: function(d) { return d.getFullYear(); }, set: function(d, v) { d.setFullYear(v); }, format: "%Y", multiple: function(N) { if (10 >= N) return 1; var mult = pv.logCeil(N / 15, 10); 2 > N / mult ? mult /= 5 : 5 > N / mult && (mult /= 2); return mult; }, castValue: function(value, ceil) { var base, mult, M = value / this.value; if (1 > M) { if (!ceil) return this.prev ? this.prev.castValue(value, ceil) : this._castValueResult(1, value, -1); base = 1; } else base = pv.logFloor(M, 10); mult = M / base; if (ceil) if (mult > 5) { base *= 10; mult = 1; } else mult = mult > 2 ? 5 : mult > 1 ? 2 : 1; else if (mult > 5) mult = 5; else if (mult > 2) mult = 2; else if (mult > 1) mult = 1; else if (1 > mult) return this.prev ? this.prev.castValue(value, ceil) : this._castValueResult(base, value, -1); return this._castValueResult(base * mult, value, 0); } }); pv.Scale.linear = function() { var scale = pv.Scale.quantitative(); scale.domain.apply(scale, arguments); return scale; }; pv.Scale.log = function() { var b, p, scale = pv.Scale.quantitative(1, 10), log = function(x) { return Math.log(x) / p; }, pow = function(y) { return Math.pow(b, y); }; scale.ticks = function() { var d = scale.domain(), n = d[0] < 0, i = Math.floor(n ? -log(-d[0]) : log(d[0])), j = Math.ceil(n ? -log(-d[1]) : log(d[1])), ticks = []; if (n) { ticks.push(-pow(-i)); for (;i++ < j; ) for (var k = b - 1; k > 0; k--) ticks.push(-pow(-i) * k); } else { for (;j > i; i++) for (var k = 1; b > k; k++) ticks.push(pow(i) * k); ticks.push(pow(i)); } for (i = 0; ticks[i] < d[0]; i++) ; for (j = ticks.length; ticks[j - 1] > d[1]; j--) ; return ticks.slice(i, j); }; scale.tickFormat = function(t) { return t.toPrecision(1); }; scale.nice = function() { var d = scale.domain(); return scale.domain(pv.logFloor(d[0], b), pv.logCeil(d[1], b)); }; scale.base = function(v) { if (arguments.length) { b = Number(v); p = Math.log(b); scale.transform(log, pow); return this; } return b; }; scale.domain.apply(scale, arguments); return scale.base(10); }; pv.Scale.root = function() { var scale = pv.Scale.quantitative(); scale.power = function(v) { if (arguments.length) { var b = Number(v), p = 1 / b; scale.transform(function(x) { return Math.pow(x, p); }, function(y) { return Math.pow(y, b); }); return this; } return b; }; scale.domain.apply(scale, arguments); return scale.power(2); }; pv.Scale.ordinal = function() { function scale(x) { x in i || (i[x] = d.push(x) - 1); return r[i[x] % r.length]; } var d = [], i = {}, r = []; scale.domain = function(array, f) { if (arguments.length) { array = array instanceof Array ? arguments.length > 1 ? pv.map(array, f) : array : Array.prototype.slice.call(arguments); d = []; for (var seen = {}, j = 0; j < array.length; j++) { var o = array[j]; if (!(o in seen)) { seen[o] = !0; d.push(o); } } i = pv.numerate(d); return this; } return d; }; scale.range = function(array, f) { if (arguments.length) { r = array instanceof Array ? arguments.length > 1 ? pv.map(array, f) : array : Array.prototype.slice.call(arguments); "string" == typeof r[0] && (r = r.map(pv.fillStyle)); r.min = r[0]; r.max = r[r.length - 1]; return this; } return r; }; scale.split = function(min, max) { var R = max - min, N = this.domain().length, step = 0; if (0 === R) r = pv.array(N, min); else if (N) { step = (max - min) / N; r = pv.range(min + step / 2, max, step); } r.min = min; r.max = max; r.step = step; return this; }; scale.splitBandedCenter = function(min, max, bandRatio) { null == bandRatio && (bandRatio = 1); return this._splitBandedCore(min, max, function(info) { var S = info.range / info.count; info.step = S; info.band = S * bandRatio; info.offset = S / 2; }); }; scale.splitBandedCenterAbs = function(min, max, band, margin) { return this._splitBandedCore(min, max, function(info) { var step; if (null == band || null == margin) { step = info.range / info.count; if (null == band) if (null == margin) { band = step; margin = 0; } else { margin = Math.min(margin, step); band = step - margin; } else { band = Math.min(band, step); margin = step - band; } } else step = band + margin; info.step = step; info.band = band; info.offset = step / 2; }); }; scale._splitBandedCore = function(min, max, fSplit) { var margin, info = { min: min, max: max, range: max - min, count: this.domain().length, offset: 0, step: 0, band: 0 }; if (0 === info.range) { r = pv.array(info.count, min); margin = 0; } else if (info.count) { fSplit(info); margin = info.step - info.band; r = pv.range(min + info.offset, max, info.step); } r.offset = info.offset; r.step = info.step; r.band = info.band; r.margin = margin; r.min = min; r.max = max; return this; }; scale.splitBandedFlushCenter = function(min, max, bandRatio) { null == bandRatio && (bandRatio = 1); return this._splitBandedCore(min, max, function(info) { var R = info.range, N = info.count, B = R * bandRatio / N, M = N > 1 ? (R - N * B) / (N - 1) : 0; info.band = B; info.step = M + B; info.offset = B / 2; }); }; scale.splitFlush = function(min, max) { var n = this.domain().length, step = (max - min) / (n - 1); r = 1 == n ? [ (min + max) / 2 ] : pv.range(min, max + step / 2, step); r.min = min; r.max = max; return this; }; scale.splitBanded = function(min, max, band) { arguments.length < 3 && (band = 1); if (0 > band) { var n = this.domain().length, total = -band * n, remaining = max - min - total, padding = remaining / (n + 1); r = pv.range(min + padding, max, padding - band); r.band = -band; } else { var step = (max - min) / (this.domain().length + (1 - band)); r = pv.range(min + step * (1 - band), max, step); r.band = step * band; r.step = step; r.margin = step - r.band; } r.min = min; r.max = max; return this; }; scale.invertIndex = function(y, noRound) { var N = this.domain().length; if (0 === N) return -1; var r = this.range(), R = r.max - r.min; if (0 === R) return 0; var S = R / N; if (y >= r.max) return N; if (y < r.min) return 0; var i = (y - r.min) / S; return noRound ? i : Math.round(i); }; pv.copyOwn(scale, pv.Scale.common); scale.domain.apply(scale, arguments); return scale; }; pv.Scale.quantile = function() { function scale(x) { return y(Math.max(0, Math.min(j, pv.search.index(q, x) - 1)) / j); } var n = -1, j = -1, q = [], d = [], y = pv.Scale.linear(); scale.quantiles = function(x) { if (arguments.length) { n = Number(x); if (0 > n) { q = [ d[0] ].concat(d); j = d.length - 1; } else { q = []; q[0] = d[0]; for (var i = 1; n >= i; i++) q[i] = d[~~(i * (d.length - 1) / n)]; j = n - 1; } return this; } return q; }; scale.domain = function(array, f) { if (arguments.length) { d = array instanceof Array ? pv.map(array, f) : Array.prototype.slice.call(arguments); d.sort(pv.naturalOrder); scale.quantiles(n); return this; } return d; }; scale.range = function() { if (arguments.length) { y.range.apply(y, arguments); return this; } return y.range(); }; pv.copyOwn(scale, pv.Scale.common); scale.domain.apply(scale, arguments); return scale; }; pv.histogram = function(data, f) { var frequency = !0; return { bins: function(ticks) { var x = pv.map(data, f), bins = []; arguments.length || (ticks = pv.Scale.linear(x).ticks()); for (var i = 0; i < ticks.length - 1; i++) { var bin = bins[i] = []; bin.x = ticks[i]; bin.dx = ticks[i + 1] - ticks[i]; bin.y = 0; } for (var i = 0; i < x.length; i++) { var j = pv.search.index(ticks, x[i]) - 1, bin = bins[Math.max(0, Math.min(bins.length - 1, j))]; bin.y++; bin.push(data[i]); } if (!frequency) for (var i = 0; i < bins.length; i++) bins[i].y /= x.length; return bins; }, frequency: function(x) { if (arguments.length) { frequency = Boolean(x); return this; } return frequency; } }; }; !function() { pv.Shape = function() {}; var _k0 = { x: 1, y: 1 }; pv.Shape.dist2 = function(v, w, k) { k = k || _k0; var dx = v.x - w.x, dy = v.y - w.y, dx2 = dx * dx, dy2 = dy * dy; return { cost: dx2 + dy2, dist2: k.x * dx2 + k.y * dy2 }; }; var pi = Math.PI, pi2 = 2 * pi, atan2 = Math.atan2; pv.Shape.normalizeAngle = function(a) { a %= pi2; pv.floatLess(a, 0) && (a += pi2); return a; }; pv.Shape.atan2Norm = function(dy, dx) { var a = atan2(dy, dx); pv.floatLess(a, 0) && (a += pi2); return a; }; pv.Shape.prototype.hasArea = function() { return !0; }; pv.Shape.prototype.bbox = function() { return this._bbox || (this._bbox = this._calcBBox()); }; pv.Shape.prototype._calcBBox = function() { var minX, minY, maxX, maxY; this.points().forEach(function(point) { var x = point.x, y = point.y; if (null == minX) { minX = maxX = x; minY = maxY = y; } else { minX > x ? minX = x : x > maxX && (maxX = x); minY > y ? minY = y : y > maxY && (maxY = y); } }); return null != minX ? new pv.Shape.Rect(minX, minY, maxX - minX, maxY - minY) : void 0; }; pv.Shape.prototype.containsPoint = function(p, k) { if (k) { var bbox; if (!k.y) return bbox = this.bbox(), pv.floatBelongsClosed(bbox.x, p.x, bbox.x2); if (!k.x) return bbox = this.bbox(), pv.floatBelongsClosed(bbox.y, p.y, bbox.y2); } return this._containsPointCore(p); }; pv.Shape.prototype._containsPointCore = function() { return !1; }; }(); !function() { var dist2 = pv.Shape.dist2, cos = Math.cos, sin = Math.sin, sqrt = Math.sqrt; pv.vector = function(x, y) { return new Point(x, y); }; pv.Vector = function(x, y) { this.x = x; this.y = y; }; var Point = pv.Shape.Point = pv.Vector; pv.Vector.prototype = pv.extend(pv.Shape); pv.Vector.prototype.perp = function() { return new Point(-this.y, this.x); }; pv.Vector.prototype.rotate = function(angle) { var c = cos(angle), s = sin(angle); return new Point(c * this.x - s * this.y, s * this.x + c * this.y); }; pv.Vector.prototype.norm = function() { var l = this.length(); return this.times(l ? 1 / l : 1); }; pv.Vector.prototype.length = function() { return sqrt(this.x * this.x + this.y * this.y); }; pv.Vector.prototype.times = function(k) { return new Point(this.x * k, this.y * k); }; pv.Vector.prototype.plus = function(x, y) { return 1 === arguments.length ? new Point(this.x + x.x, this.y + x.y) : new Point(this.x + x, this.y + y); }; pv.Vector.prototype.minus = function(x, y) { return 1 === arguments.length ? new Point(this.x - x.x, this.y - x.y) : new Point(this.x - x, this.y - y); }; pv.Vector.prototype.dot = function(x, y) { return 1 == arguments.length ? this.x * x.x + this.y * x.y : this.x * x + this.y * y; }; pv.Vector.prototype.hasArea = function() { return !1; }; pv.Vector.prototype.clone = function() { return new Point(this.x, this.y); }; pv.Vector.prototype.apply = function(t) { return new Point(t.x + t.k * this.x, t.y + t.k * this.y); }; pv.Vector.prototype.intersectsRect = function(rect) { return pv.floatBelongsClosed(rect.x, this.x, rect.x2) && pv.floatBelongsClosed(rect.y, this.y, rect.y2); }; pv.Vector.prototype._containsPointCore = function(p) { return this.x === p.x && this.y === p.y; }; pv.Vector.prototype.points = function() { return [ this ]; }; pv.Vector.prototype.edges = function() { return []; }; pv.Vector.prototype.center = function() { return this; }; pv.Vector.prototype.distance2 = function(p, k) { return dist2(this, p, k); }; }(); !function() { var Point = pv.Shape.Point, dist2 = pv.Shape.dist2; pv.Shape.Line = function(x, y, x2, y2) { this.x = x || 0; this.y = y || 0; this.x2 = x2 || 0; this.y2 = y2 || 0; }; var Line = pv.Shape.Line; Line.prototype = pv.extend(pv.Shape); Line.prototype.hasArea = function() { return !1; }; Line.prototype.clone = function() { return new Line(this.x, this.y, this.x2, this.x2); }; Line.prototype.apply = function(t) { var x = t.x + t.k * this.x, y = t.y + t.k * this.y, x2 = t.x + t.k * this.x2, y2 = t.y + t.k * this.y2; return new Line(x, y, x2, y2); }; Line.prototype.points = function() { return [ new Point(this.x, this.y), new Point(this.x2, this.y2) ]; }; Line.prototype.edges = function() { return [ this ]; }; Line.prototype.center = function() { return new Point((this.x + this.x2) / 2, (this.y + this.y2) / 2); }; Line.prototype.normal = function(at, shapeCenter) { var points = this.points(), norm = points[1].minus(points[0]).perp().norm(); if (shapeCenter) { var outside = points[0].minus(shapeCenter); outside.dot(norm) < 0 && (norm = norm.times(-1)); } return norm; }; Line.prototype.intersectsRect = function(rect) { var i, L, points = this.points(); L = points.length; for (i = 0; L > i; i++) if (points[i].intersectsRect(rect)) return !0; var edges = rect.edges(); L = edges.length; for (i = 0; L > i; i++) if (this.intersectsLine(edges[i])) return !0; return !1; }; Line.prototype._containsPointCore = function(p) { var x = this.x, x2 = this.x2, y = this.y, y2 = this.y2; return pv.floatBelongsClosed(x, p.x, x2) && (pv.floatEqual(x, x2) ? pv.floatBelongsClosed(Math.min(y, y2), p.y, Math.max(y, y2)) : pv.floatZero((y2 - y) / (x2 - x) * (p.x - x) + y - p.y)); }; Line.prototype.intersectsLine = function(b) { var a = this, x21 = a.x2 - a.x, y21 = a.y2 - a.y, x43 = b.x2 - b.x, y43 = b.y2 - b.y, denom = y43 * x21 - x43 * y21; if (pv.floatZero(denom)) return !1; var y13 = a.y - b.y, x13 = a.x - b.x, numa = x43 * y13 - y43 * x13, numb = x21 * y13 - y21 * x13; if (pv.floatZero(denom)) return pv.floatZero(numa) && pv.floatZero(numb); var ua = numa / denom; if (!pv.floatBelongsClosed(0, ua, 1)) return !1; var ub = numb / denom; return pv.floatBelongsClosed(0, ub, 1) ? !0 : !1; }; Line.prototype.distance2 = function(p, k) { var v = this, w = { x: this.x2, y: this.y2 }, l2 = dist2(v, w).cost; if (pv.floatZero(l2)) return dist2(p, v, k); var wvx = w.x - v.x, wvy = w.y - v.y, t = ((p.x - v.x) * wvx + (p.y - v.y) * wvy) / l2; if (pv.floatLess(t, 0)) return dist2(p, v, k); if (pv.floatGreater(t, 1)) return dist2(p, w, k); var proj = { x: v.x + t * wvx, y: v.y + t * wvy }; return dist2(p, proj, k); }; }(); !function() { var Point = pv.Shape.Point, Line = pv.Shape.Line; pv.Shape.Polygon = function(points) { this._points = points || []; }; var Polygon = pv.Shape.Polygon; Polygon.prototype = pv.extend(pv.Shape); Polygon.prototype.points = function() { return this._points; }; Polygon.prototype.clone = function() { return new Polygon(this.points().slice()); }; Polygon.prototype.apply = function(t) { for (var points = this.points(), L = points.length, points2 = new Array(L), i = 0; L > i; i++) points2[i] = points[i].apply(t); return new Polygon(points2); }; Polygon.prototype.intersectsRect = function(rect) { var i, L, points = this.points(); L = points.length; for (i = 0; L > i; i++) if (points[i].intersectsRect(rect)) return !0; var edges = this.edges(); L = edges.length; for (i = 0; L > i; i++) if (edges[i].intersectsRect(rect)) return !0; return !1; }; Polygon.prototype.edges = function() { var edges = this._edges; if (!edges) { edges = this._edges = []; var points = this.points(), L = points.length; if (L) { for (var point, prevPoint = points[0], firstPoint = prevPoint, i = 1; L > i; i++) { point = points[i]; edges.push(new Line(prevPoint.x, prevPoint.y, point.x, point.y)); prevPoint = point; } L > 2 && edges.push(new Line(point.x, point.y, firstPoint.x, firstPoint.y)); } } return edges; }; Polygon.prototype.distance2 = function(p, k) { var min = { cost: 1/0, dist2: 1/0 }; this.edges().forEach(function(edge) { var d = edge.distance2(p, k); pv.floatLess(d.cost, min.cost) && (min = d); }, this); return min; }; Polygon.prototype.center = function() { for (var points = this.points(), x = 0, y = 0, i = 0, L = points.length; L > i; i++) { var p = points[i]; x += p.x; y += p.y; } return new Point(x / L, y / L); }; Polygon.prototype._containsPointCore = function(p) { var bbox = this.bbox(); if (!bbox._containsPointCore(p)) return !1; var e = .01 * bbox.dx, ray = new Line(bbox.x - e, p.y, p.x, p.y), intersectCount = 0, edges = this.edges(); edges.forEach(function(edge) { edge.intersectsLine(ray) && intersectCount++; }); return 1 === (1 & intersectCount); }; }(); !function() { var Point = pv.Shape.Point, Line = pv.Shape.Line; pv.Shape.Rect = function(x, y, dx, dy) { this.x = x || 0; this.y = y || 0; this.dx = dx || 0; this.dy = dy || 0; if (this.dx < 0) { this.dx = Math.max(0, -this.dx); this.x = this.x - this.dx; } if (this.dy < 0) { this.dy = Math.max(0, -this.dy); this.y = this.y - this.dy; } this.x2 = this.x + this.dx; this.y2 = this.y + this.dy; }; var Rect = pv.Shape.Rect; Rect.prototype = pv.extend(pv.Shape.Polygon); Rect.prototype.clone = function() { var r2 = Object.create(Rect.prototype); r2.x = this.x; r2.y = this.y; r2.dx = this.dx; r2.dy = this.dy; r2.x2 = this.x2; r2.y2 = this.y2; return r2; }; Rect.prototype.apply = function(t) { var x = t.x + t.k * this.x, y = t.y + t.k * this.y, dx = t.k * this.dx, dy = t.k * this.dy; return new Rect(x, y, dx, dy); }; Rect.prototype._containsPointCore = function(p) { return pv.floatBelongsClosed(this.x, p.x, this.x2) && pv.floatBelongsClosed(this.y, p.y, this.y2); }; Rect.prototype.intersectsRect = function(rect) { return pv.floatGreater(this.x2, rect.x) && pv.floatLess(this.x, rect.x2) && pv.floatGreater(this.y2, rect.y) && pv.floatLess(this.y, rect.y2); }; Rect.prototype.edges = function() { if (!this._edges) { var x = this.x, y = this.y, x2 = this.x2, y2 = this.y2; this._edges = [ new Line(x, y, x2, y), new Line(x2, y, x2, y2), new Line(x2, y2, x, y2), new Line(x, y2, x, y) ]; } return this._edges; }; Rect.prototype.center = function() { return new Point(this.x + this.dx / 2, this.y + this.dy / 2); }; Rect.prototype.points = function() { var points = this._points; if (!points) { var x = this.x, y = this.y, x2 = this.x2, y2 = this.y2; points = this._points = [ new Point(x, y), new Point(x2, y), new Point(x2, y2), new Point(x, y2) ]; } return points; }; Rect.prototype._calcBBox = function() { return this; }; }(); !function() { var Point = pv.Shape.Point, dist2 = pv.Shape.dist2, sqrt = Math.sqrt, abs = Math.abs, pow = Math.pow; pv.Shape.Circle = function(x, y, radius) { this.x = x || 0; this.y = y || 0; this.radius = radius || 0; }; var Circle = pv.Shape.Circle; Circle.prototype = pv.extend(pv.Shape); Circle.prototype.clone = function() { return new Circle(this.x, this.y, this.radius); }; Circle.prototype.apply = function(t) { var x = t.x + t.k * this.x, y = t.y + t.k * this.y, r = t.k * this.radius; return new Circle(x, y, r); }; Circle.prototype.intersectsRect = function(rect) { var dx2 = rect.dx / 2, dy2 = rect.dy / 2, r = this.radius, circleDistX = abs(this.x - rect.x - dx2), circleDistY = abs(this.y - rect.y - dy2); if (circleDistX > dx2 + r || circleDistY > dy2 + r) return !1; if (dx2 >= circleDistX || dy2 >= circleDistY) return !0; var sqCornerDistance = pow(circleDistX - dx2, 2) + pow(circleDistY - dy2, 2); return r * r >= sqCornerDistance; }; Circle.prototype.intersectLine = function(line, isInfiniteLine) { var baX = line.x2 - line.x, baY = line.y2 - line.y, caX = this.x - line.x, caY = this.y - line.y, ba2 = baX * baX + baY * baY, bBy2 = baX * caX + baY * caY, r = this.radius, c = caX * caX + caY * caY - r * r, pBy2 = bBy2 / ba2, disc = pBy2 * pBy2 - c / ba2; if (!(0 > disc)) { var discSqrt = sqrt(disc), t1 = pBy2 - discSqrt, t2 = pBy2 + discSqrt, ps = []; (isInfiniteLine || t1 >= 0 && 1 >= t1) && ps.push(new Point(line.x + baX * t1, line.y + baY * t1)); 0 !== disc && (isInfiniteLine || t2 >= 0 && 1 >= t2) && ps.push(new Point(line.x + baX * t2, line.y + baY * t2)); return ps; } }; Circle.prototype.points = function() { return [ this.center() ]; }; Circle.prototype.center = function() { return new Point(this.x, this.y); }; Circle.prototype.normal = function(at) { return at.minus(this.x, this.y).norm(); }; Circle.prototype._containsPointCore = function(p) { var dx = p.x - this.x, dy = p.y - this.y, r = this.radius; return r * r >= dx * dx + dy * dy; }; Circle.prototype.distance2 = function(p, k) { var r = this.radius, b = p.minus(this).norm().times(r).plus(this), dBorder = dist2(p, b, k); return dBorder; }; Circle.prototype._calcBBox = function() { var r = this.radius, r_2 = 2 * r; return new pv.Shape.Rect(this.x - r, this.y - r, r_2, r_2); }; }(); !function() { var Point = pv.Shape.Point, dist2 = pv.Shape.dist2, normalizeAngle = pv.Shape.normalizeAngle, atan2Norm = pv.Shape.atan2Norm, cos = Math.cos, sin = Math.sin, sqrt = Math.sqrt, pi = Math.PI, pi_2 = 2 * pi, pi_1_2 = pi / 2, pi_3_2 = 3 * pi / 2; pv.Shape.Arc = function(x, y, radius, startAngle, angleSpan) { this.x = x; this.y = y; this.radius = radius; pv.floatBelongsClosed(0, angleSpan, pi_2) || (angleSpan = normalizeAngle(angleSpan)); this.startAngle = normalizeAngle(startAngle); this.angleSpan = angleSpan; this.endAngle = this.startAngle + this.angleSpan; }; var Arc = pv.Shape.Arc; Arc.prototype = pv.extend(pv.Shape); Arc.prototype.hasArea = function() { return !1; }; Arc.prototype.clone = function() { var arc = Object.create(Arc.prototype), me = this; arc.x = me.x; arc.y = me.y; arc.radius = me.radius; arc.startAngle = me.startAngle; arc.angleSpan = me.angleSpan; arc.endAngle = me.endAngle; return arc; }; Arc.prototype.apply = function(t) { var x = t.x + t.k * this.x, y = t.y + t.k * this.y, r = t.k * this.radius; return new Arc(x, y, r, this.startAngle, this.angleSpan); }; Arc.prototype.containsAngle = function(a, inside) { pv.floatBelongsClosed(0, a, pi_2) || (a = normalizeAngle(a)); var ai = this.startAngle, af = this.endAngle; if (inside ? pv.floatBelongsOpen(ai, a, af) : pv.floatBelongsClosed(ai, a, af)) return !0; if (pv.floatLessOrEqual(af, pi_2)) return !1; a += pi_2; return inside ? pv.floatBelongsOpen(ai, a, af) : pv.floatBelongsClosed(ai, a, af); }; Arc.prototype._containsPointCore = function(p) { var dx = p.x - this.x, dy = p.y - this.y, r = sqrt(dx * dx + dy * dy); return pv.floatEqual(r, this.radius) && this.containsAngle(atan2Norm(dy, dx)); }; Arc.prototype.intersectsRect = function(rect) { var i, points = this.points(), L = points.length; for (i = 0; L > i; i++) if (points[i].intersectsRect(rect)) return !0; var edges = rect.edges(); L = edges.length; for (i = 0; L > i; i++) if (this.intersectLine(edges[i])) return !0; return !1; }; var circleIntersectLine = pv.Shape.Circle.prototype.intersectLine; Arc.prototype.intersectLine = function(line, isInfiniteLine) { var ps = circleIntersectLine.call(this, line, isInfiniteLine); if (ps) { ps = ps.filter(function(p) { return this._containsPointCore(p); }, this); if (ps.length) return ps; } }; Arc.prototype.points = function() { function addAngle(a) { me.containsAngle(a, !0) && points.push(new Point(x + r * cos(a), y + r * sin(a))); } var me = this, x = me.x, y = me.y, r = me.radius, ai = me.startAngle, af = me.endAngle, points = [ new Point(x + r * cos(ai), y + r * sin(ai)), new Point(x + r * cos(af), y + r * sin(af)) ]; addAngle(0); addAngle(pi_1_2); addAngle(pi); addAngle(pi_3_2); return points; }; Arc.prototype.center = function() { var x = this.x, y = this.y, r = this.radius, am = (this.startAngle + this.endAngle) / 2; return new Point(x + r * cos(am), y + r * sin(am)); }; Arc.prototype.normal = function(at, shapeCenter) { var norm = at.minus(this.x, this.y).norm(); if (shapeCenter) { var outside = this.center().minus(shapeCenter); outside.dot(norm) < 0 && (norm = norm.times(-1)); } return norm; }; Arc.prototype.distance2 = function(p, k) { var dx = p.x - this.x, dy = p.y - this.y, a = atan2Norm(dy, dx); if (this.containsAngle(a)) { var b = new Point(this.x + this.radius * cos(a), this.y + this.radius * sin(a)); return dist2(p, b, k); } var points = this.points(), d1 = dist2(p, points[0], k), d2 = dist2(p, points[1], k); return pv.floatLess(d1.cost, d2.cost) ? d1 : d2; }; }(); !function() { var Arc = pv.Shape.Arc, Line = pv.Shape.Line, Point = pv.Shape.Point, cos = Math.cos, sin = Math.sin, sqrt = Math.sqrt, pi = Math.PI, pi_2 = 2 * pi, pi_1_2 = pi / 2, pi_3_2 = 3 * pi / 2, atan2Norm = pv.Shape.atan2Norm, normalizeAngle = pv.Shape.normalizeAngle; pv.Shape.Wedge = function(x, y, innerRadius, outerRadius, startAngle, angleSpan) { this.x = x; this.y = y; this.innerRadius = innerRadius; this.outerRadius = outerRadius; pv.floatBelongsClosed(0, angleSpan, pi_2) || (angleSpan = normalizeAngle(angleSpan)); this.startAngle = normalizeAngle(startAngle); this.angleSpan = angleSpan; this.endAngle = this.startAngle + angleSpan; }; var Wedge = pv.Shape.Wedge; Wedge.prototype = pv.extend(pv.Shape); Wedge.prototype.clone = function() { return new Wedge(this.x, this.y, this.innerRadius, this.outerRadius, this.startAngle, this.angleSpan); }; Wedge.prototype.apply = function(t) { var x = t.x + t.k * this.x, y = t.y + t.k * this.y, ir = t.k * this.innerRadius, or = t.k * this.outerRadius; return new Wedge(x, y, ir, or, this.startAngle, this.angleSpan); }; Wedge.prototype.containsAngle = Arc.prototype.containsAngle; Wedge.prototype._containsPointCore = function(p) { var dx = p.x - this.x, dy = p.y - this.y, r = sqrt(dx * dx + dy * dy); return pv.floatBelongsClosed(this.innerRadius, r, this.outerRadius) && this.containsAngle(atan2Norm(dy, dx)); }; Wedge.prototype.intersectsRect = function(rect) { var i, L, points, edges; points = this.points(); L = points.length; for (i = 0; L > i; i++) if (points[i].intersectsRect(rect)) return !0; points = rect.points(); L = points.length; for (i = 0; L > i; i++) if (this._containsPointCore(points[i])) return !0; edges = this.edges(); L = edges.length; for (i = 0; L > i; i++) if (edges[i].intersectsRect(rect)) return !0; return !1; }; Wedge.prototype.points = function() { this._points || this.edges(); return this._points; }; Wedge.prototype.edges = function() { function addAngle(a) { me.containsAngle(a, !0) && points.push(new Point(x + or * cos(a), y + or * sin(a))); } var me = this, edges = me._edges; if (!edges) { var pii, pfi, x = me.x, y = me.y, ir = me.innerRadius, irPositive = pv.floatGreater(ir, 0), or = me.outerRadius, ai = me.startAngle, af = me.endAngle, aa = me.angleSpan, cai = cos(ai), sai = sin(ai), caf = cos(af), saf = sin(af); if (irPositive) { pii = new Point(x + ir * cai, y + ir * sai); pfi = new Point(x + ir * caf, y + ir * saf); } else pii = pfi = new Point(x, y); var pio = new Point(x + or * cai, y + or * sai), pfo = new Point(x + or * caf, y + or * saf); edges = me._edges = []; irPositive && edges.push(new Arc(x, y, ir, ai, aa)); edges.push(new Line(pii.x, pii.y, pio.x, pio.y), new Arc(x, y, or, ai, aa), new Line(pfi.x, pfi.y, pfo.x, pfo.y)); var points = me._points = [ pii, pio, pfo ]; irPositive && points.push(pfi); addAngle(0); addAngle(pi_1_2); addAngle(pi); addAngle(pi_3_2); } return edges; }; Wedge.prototype.distance2 = function(p, k) { var min = { cost: 1/0, dist2: 1/0 }; this.edges().forEach(function(edge) { var d = edge.distance2(p, k); pv.floatLess(d.cost, min.cost) && (min = d); }); return min; }; Wedge.prototype.center = function() { var midAngle = (this.startAngle + this.endAngle) / 2, midRadius = (this.innerRadius + this.outerRadius) / 2; return new Point(this.x + midRadius * cos(midAngle), this.y + midRadius * sin(midAngle)); }; }(); !function() { var round = Math.round, parseRgb = function(c) { var f = parseFloat(c); return "%" == c[c.length - 1] ? round(2.55 * f) : f; }, reSysColor = /([a-z]+)\((.*)\)/i, createColor = function(format) { if ("#" === format.charAt(0)) { var r, g, b; if (4 === format.length) { r = format.charAt(1); r += r; g = format.charAt(2); g += g; b = format.charAt(3); b += b; } else if (7 === format.length) { r = format.substring(1, 3); g = format.substring(3, 5); b = format.substring(5, 7); } return pv.rgb(parseInt(r, 16), parseInt(g, 16), parseInt(b, 16), 1); } var m1 = reSysColor.exec(format); if (m1) { var m2 = m1[2].split(","), a = 1; switch (m1[1]) { case "hsla": case "rgba": a = parseFloat(m2[3]); if (!a) return pv.Color.transparent; } switch (m1[1]) { case "hsla": case "hsl": var h = parseFloat(m2[0]), s = parseFloat(m2[1]) / 100, l = parseFloat(m2[2]) / 100; return new pv.Color.Hsl(h, s, l, a).rgb(); case "rgba": case "rgb": var r = parseRgb(m2[0]), g = parseRgb(m2[1]), b = parseRgb(m2[2]); return pv.rgb(r, g, b, a); } } return new pv.Color(format, 1); }, colorsByFormat = {}; pv.color = function(format) { if (format.rgb) return format.rgb(); var color = pv.Color.names[format]; color || (color = colorsByFormat[format] || (colorsByFormat[format] = createColor(format))); return color; }; }(); pv.Color = function(color, opacity) { this.color = color; this.opacity = opacity; this.key = "solid " + color + " alpha(" + opacity + ")"; }; pv.Color.prototype.hsl = function() { return this.rgb().hsl(); }; pv.Color.prototype.brighter = function(k) { return this.rgb().brighter(k); }; pv.Color.prototype.darker = function(k) { return this.rgb().darker(k); }; pv.Color.prototype.alphaBlend = function(mate) { var rgb = this.rgb(), a = rgb.a; if (1 === a) return this; mate = mate ? pv.color(mate) : pv.Color.names.white; mate = mate.rgb(); var z = 1 - a; return pv.rgb(z * rgb.r + a * mate.r, z * rgb.g + a * mate.g, z * rgb.b + a * mate.b, 1); }; pv.Color.prototype.rgbDecimal = function(mate) { var rgb = this.alphaBlend(mate); return rgb.r << 16 | rgb.g << 8 | rgb.b; }; pv.Color.prototype.isDark = function() { return this.rgbDecimal() < 8388607.5; }; pv.rgb = function(r, g, b, a) { return new pv.Color.Rgb(r, g, b, 4 == arguments.length ? a : 1); }; pv.Color.Rgb = function(r, g, b, a) { pv.Color.call(this, a ? "rgb(" + r + "," + g + "," + b + ")" : "none", a); this.r = r; this.g = g; this.b = b; this.a = a; }; pv.Color.Rgb.prototype = pv.extend(pv.Color); pv.Color.Rgb.prototype.red = function(r) { return pv.rgb(r, this.g, this.b, this.a); }; pv.Color.Rgb.prototype.green = function(g) { return pv.rgb(this.r, g, this.b, this.a); }; pv.Color.Rgb.prototype.blue = function(b) { return pv.rgb(this.r, this.g, b, this.a); }; pv.Color.Rgb.prototype.alpha = function(a) { return pv.rgb(this.r, this.g, this.b, a); }; pv.Color.Rgb.prototype.rgb = function() { return this; }; pv.Color.Rgb.prototype.brighter = function(k) { k = Math.pow(.7, null != k ? k : 1); var r = this.r, g = this.g, b = this.b, i = 30; if (!r && !g && !b) return pv.rgb(i, i, i, this.a); r && i > r && (r = i); g && i > g && (g = i); b && i > b && (b = i); return pv.rgb(Math.min(255, Math.floor(r / k)), Math.min(255, Math.floor(g / k)), Math.min(255, Math.floor(b / k)), this.a); }; pv.Color.Rgb.prototype.darker = function(k) { k = Math.pow(.7, null != k ? k : 1); return pv.rgb(Math.max(0, Math.floor(k * this.r)), Math.max(0, Math.floor(k * this.g)), Math.max(0, Math.floor(k * this.b)), this.a); }; pv.Color.Rgb.prototype.hsl = function() { var h, s, r = this.r / 255, g = this.g / 255, b = this.b / 255, max = Math.max(r, g, b), min = Math.min(r, g, b), l = (max + min) / 2; if (max === min) h = s = 0; else { var d = max - min; s = l > .5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (b > g ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; } h /= 6; } return pv.hsl(360 * h, s, l, this.a); }; pv.Color.Rgb.prototype.complementary = function() { return this.hsl().complementary().rgb(); }; pv.hsl = function(h, s, l, a) { return new pv.Color.Hsl(h, s, l, 4 == arguments.length ? a : 1); }; pv.Color.Hsl = function(h, s, l, a) { pv.Color.call(this, "hsl(" + h + "," + 100 * s + "%," + 100 * l + "%)", a); this.h = h; this.s = s; this.l = l; this.a = a; }; pv.Color.Hsl.prototype = pv.extend(pv.Color); pv.Color.Hsl.prototype.hsl = function() { return this; }; pv.Color.Hsl.prototype.hue = function(h) { return pv.hsl(h, this.s, this.l, this.a); }; pv.Color.Hsl.prototype.saturation = function(s) { return pv.hsl(this.h, s, this.l, this.a); }; pv.Color.Hsl.prototype.lightness = function(l) { return pv.hsl(this.h, this.s, l, this.a); }; pv.Color.Hsl.prototype.alpha = function(a) { return pv.hsl(this.h, this.s, this.l, a); }; pv.Color.Hsl.prototype.complementary = function() { return pv.hsl((this.h + 180) % 360, 1 - this.s, 1 - this.l, this.a); }; pv.Color.Hsl.prototype.rgb = function() { function v(h) { h > 360 ? h -= 360 : 0 > h && (h += 360); return 60 > h ? m1 + (m2 - m1) * h / 60 : 180 > h ? m2 : 240 > h ? m1 + (m2 - m1) * (240 - h) / 60 : m1; } function vv(h) { return Math.round(255 * v(h)); } var h = this.h, s = this.s, l = this.l; h %= 360; 0 > h && (h += 360); s = Math.max(0, Math.min(s, 1)); l = Math.max(0, Math.min(l, 1)); var m2 = .5 >= l ? l * (1 + s) : l + s - l * s, m1 = 2 * l - m2; return pv.rgb(vv(h + 120), vv(h), vv(h - 120), this.a); }; pv.Color.names = { aliceblue: "#f0f8ff", antiquewhite: "#faebd7", aqua: "#00ffff", aquamarine: "#7fffd4", azure: "#f0ffff", beige: "#f5f5dc", bisque: "#ffe4c4", black: "#000000", blanchedalmond: "#ffebcd", blue: "#0000ff", blueviolet: "#8a2be2", brown: "#a52a2a", burlywood: "#deb887", cadetblue: "#5f9ea0", chartreuse: "#7fff00", chocolate: "#d2691e", coral: "#ff7f50", cornflowerblue: "#6495ed", cornsilk: "#fff8dc", crimson: "#dc143c", cyan: "#00ffff", darkblue: "#00008b", darkcyan: "#008b8b", darkgoldenrod: "#b8860b", darkgray: "#a9a9a9", darkgreen: "#006400", darkgrey: "#a9a9a9", darkkhaki: "#bdb76b", darkmagenta: "#8b008b", darkolivegreen: "#556b2f", darkorange: "#ff8c00", darkorchid: "#9932cc", darkred: "#8b0000", darksalmon: "#e9967a", darkseagreen: "#8fbc8f", darkslateblue: "#483d8b", darkslategray: "#2f4f4f", darkslategrey: "#2f4f4f", darkturquoise: "#00ced1", darkviolet: "#9400d3", deeppink: "#ff1493", deepskyblue: "#00bfff", dimgray: "#696969", dimgrey: "#696969", dodgerblue: "#1e90ff", firebrick: "#b22222", floralwhite: "#fffaf0", forestgreen: "#228b22", fuchsia: "#ff00ff", gainsboro: "#dcdcdc", ghostwhite: "#f8f8ff", gold: "#ffd700", goldenrod: "#daa520", gray: "#808080", green: "#008000", greenyellow: "#adff2f", grey: "#808080", honeydew: "#f0fff0", hotpink: "#ff69b4", indianred: "#cd5c5c", indigo: "#4b0082", ivory: "#fffff0", khaki: "#f0e68c", lavender: "#e6e6fa", lavenderblush: "#fff0f5", lawngreen: "#7cfc00", lemonchiffon: "#fffacd", lightblue: "#add8e6", lightcoral: "#f08080", lightcyan: "#e0ffff", lightgoldenrodyellow: "#fafad2", lightgray: "#d3d3d3", lightgreen: "#90ee90", lightgrey: "#d3d3d3", lightpink: "#ffb6c1", lightsalmon: "#ffa07a", lightseagreen: "#20b2aa", lightskyblue: "#87cefa", lightslategray: "#778899", lightslategrey: "#778899", lightsteelblue: "#b0c4de", lightyellow: "#ffffe0", lime: "#00ff00", limegreen: "#32cd32", linen: "#faf0e6", magenta: "#ff00ff", maroon: "#800000", mediumaquamarine: "#66cdaa", mediumblue: "#0000cd", mediumorchid: "#ba55d3", mediumpurple: "#9370db", mediumseagreen: "#3cb371", mediumslateblue: "#7b68ee", mediumspringgreen: "#00fa9a", mediumturquoise: "#48d1cc", mediumvioletred: "#c71585", midnightblue: "#191970", mintcream: "#f5fffa", mistyrose: "#ffe4e1", moccasin: "#ffe4b5", navajowhite: "#ffdead", navy: "#000080", oldlace: "#fdf5e6", olive: "#808000", olivedrab: "#6b8e23", orange: "#ffa500", orangered: "#ff4500", orchid: "#da70d6", palegoldenrod: "#eee8aa", palegreen: "#98fb98", paleturquoise: "#afeeee", palevioletred: "#db7093", papayawhip: "#ffefd5", peachpuff: "#ffdab9", peru: "#cd853f", pink: "#ffc0cb", plum: "#dda0dd", powderblue: "#b0e0e6", purple: "#800080", red: "#ff0000", rosybrown: "#bc8f8f", royalblue: "#4169e1", saddlebrown: "#8b4513", salmon: "#fa8072", sandybrown: "#f4a460", seagreen: "#2e8b57", seashell: "#fff5ee", sienna: "#a0522d", silver: "#c0c0c0", skyblue: "#87ceeb", slateblue: "#6a5acd", slategray: "#708090", slategrey: "#708090", snow: "#fffafa", springgreen: "#00ff7f", steelblue: "#4682b4", tan: "#d2b48c", teal: "#008080", thistle: "#d8bfd8", tomato: "#ff6347", turquoise: "#40e0d0", violet: "#ee82ee", wheat: "#f5deb3", white: "#ffffff", whitesmoke: "#f5f5f5", yellow: "#ffff00", yellowgreen: "#9acd32", transparent: pv.Color.transparent = pv.rgb(0, 0, 0, 0) }; !function() { var names = pv.Color.names; names.none = names.transparent; for (var name in names) names[name] = pv.color(names[name]); }(); pv.colors = function() { var scale = pv.Scale.ordinal(); scale.range.apply(scale, arguments); return scale; }; pv.Colors = {}; pv.Colors.category10 = function() { var scale = pv.colors("#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"); scale.domain.apply(scale, arguments); return scale; }; pv.Colors.category20 = function() { var scale = pv.colors("#1f77b4", "#aec7e8", "#ff7f0e", "#ffbb78", "#2ca02c", "#98df8a", "#d62728", "#ff9896", "#9467bd", "#c5b0d5", "#8c564b", "#c49c94", "#e377c2", "#f7b6d2", "#7f7f7f", "#c7c7c7", "#bcbd22", "#dbdb8d", "#17becf", "#9edae5"); scale.domain.apply(scale, arguments); return scale; }; pv.Colors.category19 = function() { var scale = pv.colors("#9c9ede", "#7375b5", "#4a5584", "#cedb9c", "#b5cf6b", "#8ca252", "#637939", "#e7cb94", "#e7ba52", "#bd9e39", "#8c6d31", "#e7969c", "#d6616b", "#ad494a", "#843c39", "#de9ed6", "#ce6dbd", "#a55194", "#7b4173"); scale.domain.apply(scale, arguments); return scale; }; !function() { function parseLinearGradient(text) { var terms = parseText(text); if (!terms.length) return null; var keyAngle, m, f, angle = Math.PI, term = terms[0]; if (0 === term.indexOf("to ")) { m = /^to\s+(?:((top|bottom)(?:\s+(left|right))?)|((left|right)(?:\\s+(top|bottom))?))$/.exec(term); if (m) { if (m[1]) { keyAngle = m[2]; m[3] && (keyAngle += " " + m[3]); } else { keyAngle = m[5]; m[6] && (keyAngle = m[6] + " " + keyAngle); } angle = pv.radians(keyAnglesDeg[keyAngle]); terms.shift(); } } else { f = parseFloat(term); if (!isNaN(f)) { angle = f; /^.*?deg$/.test(term) && (angle = pv.radians(angle)); terms.shift(); } } var stops = parseStops(terms); switch (stops.length) { case 0: return null; case 1: return new pv.FillStyle.Solid(stops[0].color, 1); } return new pv.FillStyle.LinearGradient(angle, stops, text); } function parseRadialGradient(text) { var terms = parseText(text); if (!terms.length) return null; var stops = parseStops(terms); switch (stops.length) { case 0: return null; case 1: return new pv.FillStyle.Solid(stops[0].color, 1); } return new pv.FillStyle.RadialGradient(50, 50, stops, text); } function parseText(text) { var colorFuns = {}, colorFunId = 0; text = text.replace(/\b\w+?\(.*?\)/g, function($0) { var id = "__color" + colorFunId++; colorFuns[id] = $0; return id; }); var terms = text.split(/\s*,\s*/); if (!terms.length) return null; colorFunId && terms.forEach(function(id, index) { colorFuns.hasOwnProperty(id) && (terms[index] = colorFuns[id]); }); return terms; } function parseStops(terms) { function processPendingStops(lastOffset) { var count = pendingOffsetStops.length; if (count) { for (var firstOffset = maxOffsetPercent, step = (lastOffset - firstOffset) / (count + 1), i = 0; count > i; i++) { firstOffset += step; pendingOffsetStops[i].offset = firstOffset; } pendingOffsetStops.length = 0; } } for (var stops = [], minOffsetPercent = +1/0, maxOffsetPercent = -1/0, pendingOffsetStops = [], i = 0, T = terms.length; T > i; ) { var term = terms[i++], m = /^(.+?)\s*([+\-]?[e\.\d]+%)?$/i.exec(term); if (m) { var stop = { color: pv.color(m[1]) }, offsetPercent = parseFloat(m[2]); isNaN(offsetPercent) && (stops.length ? i === T && (offsetPercent = Math.max(maxOffsetPercent, 100)) : offsetPercent = 0); stops.push(stop); if (isNaN(offsetPercent)) pendingOffsetStops.push(stop); else { stop.offset = offsetPercent; processPendingStops(offsetPercent); offsetPercent > maxOffsetPercent ? maxOffsetPercent = offsetPercent : maxOffsetPercent > offsetPercent && (offsetPercent = maxOffsetPercent); minOffsetPercent > offsetPercent && (minOffsetPercent = offsetPercent); } } } if (stops.length >= 2 && (0 > minOffsetPercent || maxOffsetPercent > 100)) { var colorDomain = [], colorRange = []; stops.forEach(function(stop) { colorDomain.push(stop.offset); colorRange.push(stop.color); }); var colorScale = pv.scale.linear().domain(colorDomain).range(colorRange); if (0 > minOffsetPercent) { for (;stops.length && stops[0].offset <= 0; ) stops.shift(); stops.unshift({ offset: 0, color: colorScale(0) }); } if (maxOffsetPercent > 100) { for (;stops.length && stops[stops.length - 1].offset >= 100; ) stops.pop(); stops.push({ offset: 100, color: colorScale(100) }); } } return stops; } pv.fillStyle = function(format) { if (format.type) return format; var k = format.key || format, fillStyle = fillStylesByKey[k]; fillStyle = fillStyle ? fillStyle.clone() : fillStylesByKey[k] = createFillStyle(format); return fillStyle; }; var fillStylesByKey = {}, createFillStyle = function(format) { if (format.rgb) return new pv.FillStyle.Solid(format.color, format.opacity); var match = /^\s*([a-z\-]+)\(\s*(.*?)\s*\)\s*$/.exec(format); if (match) switch (match[1]) { case "linear-gradient": return parseLinearGradient(match[2]); case "radial-gradient": return parseRadialGradient(match[2]); } return new pv.FillStyle.Solid(pv.color(format)); }, keyAnglesDeg = { top: 0, "top right": 45, right: 90, "bottom right": 135, bottom: 180, "bottom left": 225, left: 270, "top left": 315 }, FillStyle = pv.FillStyle = function(type) { this.type = type; this.key = type; }; pv.extendType(FillStyle, new pv.Color("none", 1)); FillStyle.prototype.rgb = function() { var color = pv.color(this.color); this.opacity !== color.opacity && (color = color.alpha(this.opacity)); return color; }; FillStyle.prototype.alphaBlend = function(mate) { return this.rgb().alphaBlend(mate); }; FillStyle.prototype.rgbDecimal = function(mate) { return this.rgb().rgbDecimal(mate); }; FillStyle.prototype.isDark = function() { return this.rgb().isDark(); }; var Solid = pv.FillStyle.Solid = function(color, opacity) { FillStyle.call(this, "solid"); if (color.rgb) { this.color = color.color; this.opacity = color.opacity; } else { this.color = color; this.opacity = opacity; } this.key += " " + this.color + " alpha(" + this.opacity + ")"; }; pv.extendType(Solid, FillStyle); Solid.prototype.alpha = function(opacity) { return new Solid(this.color, opacity); }; Solid.prototype.brighter = function(k) { return new Solid(this.rgb().brighter(k)); }; Solid.prototype.darker = function(k) { return new Solid(this.rgb().darker(k)); }; Solid.prototype.complementary = function() { return new Solid(this.rgb().complementary()); }; Solid.prototype.clone = function() { var o = pv.extend(Solid); o.type = this.type; o.key = this.key; o.color = this.color; o.opacity = this.opacity; return o; }; pv.FillStyle.transparent = new Solid(pv.Color.transparent); var gradient_id = 0, Gradient = pv.FillStyle.Gradient = function(type, stops) { FillStyle.call(this, type); this.id = ++gradient_id; this.stops = stops; stops.length && (this.color = stops[0].color.color); this.key += " stops(" + stops.map(function(stop) { var color = stop.color; return color.color + " alpha(" + color.opacity + ") at(" + stop.offset + ")"; }).join(", ") + ")"; }; pv.extendType(Gradient, FillStyle); Gradient.prototype.rgb = function() { return this.stops.length ? this.stops[0].color : void 0; }; Gradient.prototype.alpha = function(opacity) { return this._cloneWithStops(this.stops.map(function(stop) { return { offset: stop.offset, color: stop.color.alpha(opacity) }; })); }; Gradient.prototype.darker = function(k) { return this._cloneWithStops(this.stops.map(function(stop) { return { offset: stop.offset, color: stop.color.darker(k) }; })); }; Gradient.prototype.brighter = function(k) { return this._cloneWithStops(this.stops.map(function(stop) { return { offset: stop.offset, color: stop.color.brighter(k) }; })); }; Gradient.prototype.complementary = function() { return this._cloneWithStops(this.stops.map(function(stop) { return { offset: stop.offset, color: stop.color.complementary() }; })); }; Gradient.prototype.alphaBlend = function(mate) { return this._cloneWithStops(this.stops.map(function(stop) { return { offset: stop.offset, color: stop.color.alphaBlend(mate) }; })); }; Gradient.prototype.clone = function() { var Type = this.constructor, o = pv.extend(Type); o.constructor = Type; o.id = ++gradient_id; o.type = this.type; o.key = this.key; var stops = this.stops; o.stops = stops; stops.length && (o.color = stops[0].color.color); this._initClone(o); return o; }; var LinearGradient = pv.FillStyle.LinearGradient = function(angle, stops) { Gradient.call(this, "lineargradient", stops); this.angle = angle; this.key += " angle(" + angle + ")"; }; pv.extendType(LinearGradient, Gradient); LinearGradient.prototype._cloneWithStops = function(stops) { return new LinearGradient(this.angle, stops); }; LinearGradient.prototype._initClone = function(o) { o.angle = this.angle; }; var RadialGradient = pv.FillStyle.RadialGradient = function(cx, cy, stops) { Gradient.call(this, "radialgradient", stops); this.cx = cx; this.cy = cy; this.key += " center(" + cx + "," + cy + ")"; }; pv.extendType(RadialGradient, Gradient); RadialGradient.prototype._cloneWithStops = function(stops) { return new RadialGradient(this.cx, this.cy, stops); }; RadialGradient.prototype._initClone = function(o) { o.cx = this.cx; o.cy = this.cy; }; }(); pv.ramp = function() { var scale = pv.Scale.linear(); scale.range.apply(scale, arguments); return scale; }; pv.Scene = pv.SvgScene = { svg: "http://www.w3.org/2000/svg", xmlns: "http://www.w3.org/2000/xmlns", xlink: "http://www.w3.org/1999/xlink", xhtml: "http://www.w3.org/1999/xhtml", scale: 1, events: [ "DOMMouseScroll", "mousewheel", "mousedown", "mouseup", "mouseover", "mouseout", "mousemove", "click", "dblclick", "contextmenu" ], mousePositionEventSet: { mousedown: 1, mouseup: 1, mouseover: 1, mouseout: 1, mousemove: 1, click: 1, dblclick: 1, contextmenu: 1 }, implicit: { svg: { "shape-rendering": "auto", "pointer-events": "painted", x: 0, y: 0, dy: 0, "text-anchor": "start", transform: "translate(0,0)", fill: "none", "fill-opacity": 1, stroke: "none", "stroke-opacity": 1, "stroke-width": 1.5, "stroke-linejoin": "miter", "stroke-linecap": "butt", "stroke-miterlimit": 8, "stroke-dasharray": "none" }, css: { font: "10px sans-serif" } } }; pv.SvgScene.updateAll = function(scenes) { if (scenes.length && scenes[0].reverse && "line" !== scenes.type && "area" !== scenes.type) { for (var reversed = Object.create(scenes), i = 0, j = scenes.length - 1; j >= 0; i++, j--) reversed[i] = scenes[j]; scenes = reversed; } this.removeSiblings(this[scenes.type](scenes)); }; pv.SvgScene.create = function(type) { return document.createElementNS(this.svg, type); }; pv.SvgScene.expect = function(e, type, scenes, i, attributes, style) { var tagName; if (e) { tagName = e.tagName; if ("defs" === tagName) { e = e.nextSibling; e && (tagName = e.tagName); } else "a" === tagName && (e = e.firstChild); } if (e) { if (tagName !== type) { var n = this.create(type); e.parentNode.replaceChild(n, e); e = n; } } else e = this.create(type); attributes && this.setAttributes(e, attributes); style && this.setStyle(e, style); return e; }; pv.SvgScene.setAttributes = function(e, attributes) { var implicitSvg = this.implicit.svg, prevAttrs = e.__attributes__; prevAttrs === attributes && (prevAttrs = null); for (var name in attributes) { var value = attributes[name]; prevAttrs && value === prevAttrs[name] || (null == value || value == implicitSvg[name] ? e.removeAttribute(name) : e.setAttribute(name, value)); } e.__attributes__ = attributes; }; pv.SvgScene.setStyle = function(e, style) { var implicitCss = this.implicit.css, prevStyle = e.__style__; prevStyle === style && (prevStyle = null); for (var name in style) { var value = style[name]; prevStyle && value === prevStyle[name] || (null == value || value == implicitCss[name] ? e.style.removeProperty(name) : e.style[name] = value); } e.__style__ = style; }; pv.SvgScene.append = function(e, scenes, index) { e.$scene = { scenes: scenes, index: index }; e = this.title(e, scenes[index]); e.parentNode || scenes.$g.appendChild(e); return e.nextSibling; }; pv.SvgScene.title = function(e, s) { var a = e.parentNode; a && "a" != a.tagName && (a = null); if (s.title) { if (!a) { a = this.create("a"); a.setAttributeNS(this.xlink, "xlink:href", ""); e.parentNode && e.parentNode.replaceChild(a, e); a.appendChild(e); } a.setAttributeNS(this.xlink, "xlink:title", s.title); for (var t = null, c = e.firstChild; null != c; c = c.nextSibling) if ("title" == c.nodeName) { t = c; break; } if (t) t.removeChild(t.firstChild); else { t = this.create("title"); e.appendChild(t); } t.appendChild(document.createTextNode(s.title)); return a; } a && a.parentNode.replaceChild(e, a); return e; }; pv.SvgScene.dispatch = pv.listener(function(e) { var t = e.target.$scene; if (t) { var type = e.type; switch (type) { case "DOMMouseScroll": type = "mousewheel"; e.wheel = -480 * e.detail; break; case "mousewheel": e.wheel = (window.opera ? 12 : 1) * e.wheelDelta; } if (pv.Mark.dispatch(type, t.scenes, t.index, e)) { e.preventDefault(); e.stopPropagation(); } } }); pv.SvgScene.removeSiblings = function(e) { for (;e; ) { var n = e.nextSibling; "defs" !== e.nodeName && e.parentNode.removeChild(e); e = n; } }; pv.SvgScene.undefined = function() {}; !function() { var dashAliasMap = { "-": "shortdash", ".": "shortdot", "-.": "shortdashdot", "-..": "shortdashdotdot", ". ": "dot", "- ": "dash", "--": "longdash", "- .": "dashdot", "--.": "longdashdot", "--..": "longdashdotdot" }, dashMap = { shortdash: [ 3, 1 ], shortdot: [ 1, 1 ], shortdashdot: [ 3, 1, 1, 1 ], shortdashdotdot: [ 3, 1, 1, 1, 1, 1 ], dot: [ 1, 3 ], dash: [ 4, 3 ], longdash: [ 8, 3 ], dashdot: [ 4, 3, 1, 3 ], longdashdot: [ 8, 3, 1, 3 ], longdashdotdot: [ 8, 3, 1, 3, 1, 3 ] }; pv.SvgScene.isStandardDashStyle = function(dashArray) { return dashMap.hasOwnProperty(dashArray); }; pv.SvgScene.translateDashStyleAlias = function(dashArray) { return dashAliasMap.hasOwnProperty(dashArray) ? dashAliasMap[dashArray] : dashArray; }; pv.SvgScene.parseDasharray = function(s) { var dashArray = s.strokeDasharray; if (dashArray && "none" !== dashArray) { dashArray = this.translateDashStyleAlias(dashArray); var standardDashArray = dashMap[dashArray]; dashArray = standardDashArray ? standardDashArray : dashArray.split(/[\s,]+/); var lineWidth = s.lineWidth, lineCap = s.lineCap || "butt", isButtCap = "butt" === lineCap; dashArray = dashArray.map(function(num, index) { num = +num; isButtCap || (index % 2 ? num++ : num -= 1); 0 >= num && (num = .001); return num * lineWidth / this.scale; }, this).join(" "); } else dashArray = null; return dashArray; }; }(); !function() { var reTestUrlColor = /^url\(#/, next_gradient_id = 1, pi2 = Math.PI / 2, pi4 = pi2 / 2, sqrt22 = Math.SQRT2 / 2, abs = Math.abs, sin = Math.sin, cos = Math.cos, zr = function(x) { return abs(x) <= 1e-12 ? 0 : x; }; pv.SvgScene.addFillStyleDefinition = function(scenes, fill) { if (fill.type && "solid" !== fill.type && !reTestUrlColor.test(fill.color)) { var rootMark = scenes.mark.root, fillStyleMap = rootMark.__fillStyleMap__ || (rootMark.__fillStyleMap__ = {}), k = fill.key, instId = fillStyleMap[k]; if (!instId) { instId = fillStyleMap[k] = "__pvGradient" + next_gradient_id++; var elem = createGradientDef.call(this, scenes, fill, instId); rootMark.scene.$defs.appendChild(elem); } fill.color = "url(#" + instId + ")"; } }; var createGradientDef = function(scenes, fill, instId) { var isLinear = "lineargradient" === fill.type, elem = this.create(isLinear ? "linearGradient" : "radialGradient"); elem.setAttribute("id", instId); if (isLinear) { var svgAngle = fill.angle - pi2, diagAngle = abs(svgAngle % pi2) - pi4, r = abs(sqrt22 * cos(diagAngle)), dirx = r * cos(svgAngle), diry = r * sin(svgAngle); elem.setAttribute("x1", zr(.5 - dirx)); elem.setAttribute("y1", zr(.5 - diry)); elem.setAttribute("x2", zr(.5 + dirx)); elem.setAttribute("y2", zr(.5 + diry)); } for (var stops = fill.stops, S = stops.length, i = 0; S > i; i++) { var stop = stops[i], stopElem = elem.appendChild(this.create("stop")), color = stop.color; stopElem.setAttribute("offset", stop.offset + "%"); stopElem.setAttribute("stop-color", color.color); stopElem.setAttribute("stop-opacity", color.opacity + ""); } return elem; }; }(); pv.SvgScene.pathBasis = function() { function weight(w, p0, p1, p2, p3) { return { x: w[0] * p0.left + w[1] * p1.left + w[2] * p2.left + w[3] * p3.left, y: w[0] * p0.top + w[1] * p1.top + w[2] * p2.top + w[3] * p3.top }; } var basis = [ [ 1 / 6, 2 / 3, 1 / 6, 0 ], [ 0, 2 / 3, 1 / 3, 0 ], [ 0, 1 / 3, 2 / 3, 0 ], [ 0, 1 / 6, 2 / 3, 1 / 6 ] ], convert = function(p0, p1, p2, p3) { var b1 = weight(basis[1], p0, p1, p2, p3), b2 = weight(basis[2], p0, p1, p2, p3), b3 = weight(basis[3], p0, p1, p2, p3); return "C" + b1.x + "," + b1.y + "," + b2.x + "," + b2.y + "," + b3.x + "," + b3.y; }; convert.segment = function(p0, p1, p2, p3) { var b0 = weight(basis[0], p0, p1, p2, p3), b1 = weight(basis[1], p0, p1, p2, p3), b2 = weight(basis[2], p0, p1, p2, p3), b3 = weight(basis[3], p0, p1, p2, p3); return [ "M" + b0.x + "," + b0.y, "C" + b1.x + "," + b1.y + "," + b2.x + "," + b2.y + "," + b3.x + "," + b3.y ]; }; return convert; }(); pv.SvgScene.curveBasis = function(points, from, to) { var L; if (null == from) { L = points.length; from = 0; to = L - 1; } else L = to - from + 1; if (2 >= L) return ""; var path = "", p0 = points[from], p1 = p0, p2 = p0, p3 = points[from + 1]; path += this.pathBasis(p0, p1, p2, p3); for (var i = from + 2; to >= i; i++) { p0 = p1; p1 = p2; p2 = p3; p3 = points[i]; path += this.pathBasis(p0, p1, p2, p3); } path += this.pathBasis(p1, p2, p3, p3); path += this.pathBasis(p2, p3, p3, p3); return path; }; pv.SvgScene.curveBasisSegments = function(points, from, to) { var L; if (null == from) { L = points.length; from = 0; to = L - 1; } else L = to - from + 1; if (2 >= L) return ""; var paths = [], p0 = points[from], p1 = p0, p2 = p0, p3 = points[from + 1], firstPath = this.pathBasis.segment(p0, p1, p2, p3); p0 = p1; p1 = p2; p2 = p3; p3 = points[from + 2]; firstPath[1] += this.pathBasis(p0, p1, p2, p3); paths.push(firstPath); for (var i = from + 3; to >= i; i++) { p0 = p1; p1 = p2; p2 = p3; p3 = points[i]; paths.push(this.pathBasis.segment(p0, p1, p2, p3)); } var lastPath = this.pathBasis.segment(p1, p2, p3, p3); lastPath[1] += this.pathBasis(p2, p3, p3, p3); paths.push(lastPath); return paths; }; pv.SvgScene.curveHermite = function(points, tangents, from, to) { var L; if (null == from) { L = points.length; from = 0; to = L - 1; } else L = to - from + 1; var T = tangents.length; if (1 > T || L !== T && L !== T + 2) return ""; var quad = L !== T, path = "", p0 = points[from], p = points[from + 1], t0 = tangents[0], t = t0, pi = from + 1; if (quad) { path += "Q" + (p.left - 2 * t0.x / 3) + "," + (p.top - 2 * t0.y / 3) + "," + p.left + "," + p.top; p0 = points[from + 1]; pi = from + 2; } if (T > 1) { t = tangents[1]; p = points[pi]; pi++; path += "C" + (p0.left + t0.x) + "," + (p0.top + t0.y) + "," + (p.left - t.x) + "," + (p.top - t.y) + "," + p.left + "," + p.top; for (var i = 2; T > i; i++, pi++) { p = points[pi]; t = tangents[i]; path += "S" + (p.left - t.x) + "," + (p.top - t.y) + "," + p.left + "," + p.top; } } if (quad) { var lp = points[pi]; path += "Q" + (p.left + 2 * t.x / 3) + "," + (p.top + 2 * t.y / 3) + "," + lp.left + "," + lp.top; } return path; }; pv.SvgScene.curveHermiteSegments = function(points, tangents, from, to) { var L; if (null == from) { L = points.length; from = 0; to = L - 1; } else L = to - from + 1; var T = tangents.length; if (1 > T || L !== T && L !== T + 2) return []; var quad = L !== T, paths = [], p0 = points[from], p = p0, t0 = tangents[0], t = t0, pi = from + 1; if (quad) { p = points[from + 1]; paths.push([ "M" + p0.left + "," + p0.top, "Q" + (p.left - 2 * t.x / 3) + "," + (p.top - 2 * t.y / 3) + "," + p.left + "," + p.top ]); pi = from + 2; } for (var i = 1; T > i; i++, pi++) { p0 = p; t0 = t; p = points[pi]; t = tangents[i]; paths.push([ "M" + p0.left + "," + p0.top, "C" + (p0.left + t0.x) + "," + (p0.top + t0.y) + "," + (p.left - t.x) + "," + (p.top - t.y) + "," + p.left + "," + p.top ]); } if (quad) { var lp = points[pi]; paths.push([ "M" + p.left + "," + p.top, "Q" + (p.left + 2 * t.x / 3) + "," + (p.top + 2 * t.y / 3) + "," + lp.left + "," + lp.top ]); } return paths; }; pv.SvgScene.cardinalTangents = function(points, tension, from, to) { var L; if (null == from) { L = points.length; from = 0; to = L - 1; } else L = to - from + 1; for (var tangents = [], a = (1 - tension) / 2, p0 = points[from], p1 = points[from + 1], p2 = points[from + 2], i = from + 3; to >= i; i++) { tangents.push({ x: a * (p2.left - p0.left), y: a * (p2.top - p0.top) }); p0 = p1; p1 = p2; p2 = points[i]; } tangents.push({ x: a * (p2.left - p0.left), y: a * (p2.top - p0.top) }); return tangents; }; pv.SvgScene.curveCardinal = function(points, tension, from, to) { var L; if (null == from) { L = points.length; from = 0; to = L - 1; } else L = to - from + 1; return 2 >= L ? "" : this.curveHermite(points, this.cardinalTangents(points, tension, from, to), from, to); }; pv.SvgScene.curveCardinalSegments = function(points, tension, from, to) { var L; if (null == from) { L = points.length; from = 0; to = L - 1; } else L = to - from + 1; return 2 >= L ? "" : this.curveHermiteSegments(points, this.cardinalTangents(points, tension, from, to), from, to); }; pv.SvgScene.monotoneTangents = function(points, from, to) { var L; if (null == from) { L = points.length; from = 0; to = L - 1; } else L = to - from + 1; var j, tangents = [], d = [], m = [], dx = [], k = 0; for (k = 0; L - 1 > k; k++) { j = from + k; var den = points[j + 1].left - points[j].left; d[k] = Math.abs(den) <= 1e-12 ? 0 : (points[j + 1].top - points[j].top) / den; } m[0] = d[0]; dx[0] = points[from + 1].left - points[from].left; for (k = 1, j = from + k; L - 1 > k; k++, j++) { m[k] = (d[k - 1] + d[k]) / 2; dx[k] = (points[j + 1].left - points[j - 1].left) / 2; } m[k] = d[k - 1]; dx[k] = points[j].left - points[j - 1].left; for (k = 0; L - 1 > k; k++) if (0 == d[k]) { m[k] = 0; m[k + 1] = 0; } for (k = 0; L - 1 > k; k++) if (!(Math.abs(m[k]) < 1e-5 || Math.abs(m[k + 1]) < 1e-5)) { var ak = m[k] / d[k], bk = m[k + 1] / d[k], s = ak * ak + bk * bk; if (s > 9) { var tk = 3 / Math.sqrt(s); m[k] = tk * ak * d[k]; m[k + 1] = tk * bk * d[k]; } } for (var len, i = 0; L > i; i++) { len = 1 + m[i] * m[i]; tangents.push({ x: dx[i] / 3 / len, y: m[i] * dx[i] / 3 / len }); } return tangents; }; pv.SvgScene.curveMonotone = function(points, from, to) { var L; if (null == from) { L = points.length; from = 0; to = L - 1; } else L = to - from + 1; return 2 >= L ? "" : this.curveHermite(points, this.monotoneTangents(points, from, to), from, to); }; pv.SvgScene.curveMonotoneSegments = function(points, from, to) { var L; if (null == from) { L = points.length; from = 0; to = L - 1; } else L = to - from + 1; return 2 >= L ? "" : this.curveHermiteSegments(points, this.monotoneTangents(points, from, to), from, to); }; pv.SvgScene.area = function(scenes) { var e = scenes.$g.firstChild, count = scenes.length; if (!count) return e; var s = scenes[0]; return "smart" === s.segmented ? this.areaSegmentedSmart(e, scenes) : s.segmented ? this.areaSegmentedFull(e, scenes) : this.areaFixed(e, scenes, 0, count - 1, !0); }; pv.SvgScene.areaFixed = function(elm, scenes, from, to, addEvents) { var count = to - from + 1; if (1 === count) return this.lineAreaDotAlone(elm, scenes, from); var s = scenes[from]; if (!s.visible) return elm; var fill = s.fillStyle, stroke = s.strokeStyle; if (!fill.opacity && !stroke.opacity) return elm; this.addFillStyleDefinition(scenes, fill); this.addFillStyleDefinition(scenes, stroke); var isInterpBasis = !1, isInterpCardinal = !1, isInterpMonotone = !1, isInterpStepAfter = !1, isInterpStepBefore = !1; switch (s.interpolate) { case "basis": isInterpBasis = !0; break; case "cardinal": isInterpCardinal = !0; break; case "monotone": isInterpMonotone = !0; break; case "step-after": isInterpStepAfter = !0; break; case "step-before": isInterpStepBefore = !0; } for (var si, sj, isInterpBasisCardinalOrMonotone = isInterpBasis || isInterpCardinal || isInterpMonotone, d = [], i = from; to >= i; i++) { si = scenes[i]; if (si.width || si.height) { for (var j = i + 1; to >= j; j++) { sj = scenes[j]; if (!sj.width && !sj.height) break; } i > from && !isInterpStepAfter && i--; to >= j && !isInterpStepBefore && j++; var fun = isInterpBasisCardinalOrMonotone && j - i > 2 ? this.areaPathCurve : this.areaPathStraight; d.push(fun.call(this, scenes, i, j - 1, s)); i = j - 1; } } if (!d.length) return elm; var sop = stroke.opacity; elm = this.expect(elm, "path", scenes, from, { "shape-rendering": s.antialias ? null : "crispEdges", "pointer-events": addEvents ? s.events : "none", cursor: s.cursor, d: "M" + d.join("ZM") + "Z", fill: fill.color, "fill-opacity": fill.opacity || null, stroke: stroke.color, "stroke-opacity": sop || null, "stroke-width": sop ? s.lineWidth / this.scale : null, "stroke-linecap": s.lineCap, "stroke-linejoin": s.lineJoin, "stroke-miterlimit": s.strokeMiterLimit, "stroke-dasharray": sop ? this.parseDasharray(s) : null }); s.svg && this.setAttributes(elm, s.svg); s.css && this.setStyle(elm, s.css); return this.append(elm, scenes, from); }; pv.SvgScene.areaSegmentedSmart = function(elm, scenes) { return this.eachLineAreaSegment(elm, scenes, function(elm, scenes, from, to) { var segment = this.areaSegmentPaths(scenes, from, to), pathsT = segment.top, pathsB = segment.bottom, fromp = from, options = { breakOnKeyChange: !0, from: from, to: to }; return this.eachLineAreaSegment(elm, scenes, options, function(elm, scenes, from, to, ka, eventsMax) { var s1 = scenes[from], fill = s1.fillStyle, stroke = s1.strokeStyle; this.addFillStyleDefinition(scenes, fill); this.addFillStyleDefinition(scenes, stroke); if (from === to) return this.lineAreaDotAlone(elm, scenes, from); var d = this.areaJoinPaths(pathsT, pathsB, from - fromp, to - fromp - 1), sop = stroke.opacity, attrs = { "shape-rendering": s1.antialias ? null : "crispEdges", "pointer-events": eventsMax, cursor: s1.cursor, d: d, fill: fill.color, "fill-opacity": fill.opacity || null, stroke: stroke.color, "stroke-opacity": sop || null, "stroke-width": sop ? s1.lineWidth / this.scale : null, "stroke-linecap": s1.lineCap, "stroke-linejoin": s1.lineJoin, "stroke-miterlimit": s1.strokeMiterLimit, "stroke-dasharray": sop ? this.parseDasharray(s1) : null }; elm = this.expect(elm, "path", scenes, from, attrs, s1.css); return this.append(elm, scenes, from); }); }); }; pv.SvgScene.areaSegmentPaths = function(scenes, from, to) { return this.areaSegmentCurvePaths(scenes, from, to) || this.areaSegmentStraightPaths(scenes, from, to); }; pv.SvgScene.areaSegmentCurvePaths = function(scenes, from, to) { var count = to - from + 1, s = scenes[from], isBasis = "basis" === s.interpolate, isCardinal = !isBasis && "cardinal" === s.interpolate; if (isBasis || isCardinal || "monotone" == s.interpolate) { for (var pointsT = [], pointsB = [], i = 0; count > i; i++) { var si = scenes[from + i], sj = scenes[to - i]; pointsT.push(si); pointsB.push({ left: sj.left + sj.width, top: sj.top + sj.height }); } var pathsT, pathsB; if (isBasis) { pathsT = this.curveBasisSegments(pointsT); pathsB = this.curveBasisSegments(pointsB); } else if (isCardinal) { pathsT = this.curveCardinalSegments(pointsT, s.tension); pathsB = this.curveCardinalSegments(pointsB, s.tension); } else { pathsT = this.curveMonotoneSegments(pointsT); pathsB = this.curveMonotoneSegments(pointsB); } if (pathsT || pathsT.length) return { from: from, top: pathsT, bottom: pathsB }; } }; pv.SvgScene.areaSegmentStraightPaths = function(scenes, i, j) { for (var pathsT = [], pathsB = [], k = j, m = i; k > i; i++, j--) { var si = scenes[i], sj = scenes[j], pi = [ "M" + si.left + "," + si.top ], pj = [ "M" + (sj.left + sj.width) + "," + (sj.top + sj.height) ], sk = scenes[i + 1], sl = scenes[j - 1]; switch (si.interpolate) { case "step-before": pi.push("V" + sk.top + "H" + sk.left); break; case "step-after": pi.push("H" + sk.left + "V" + sk.top); break; default: pi.push("L" + sk.left + "," + sk.top); } pj.push("L" + (sl.left + sl.width) + "," + (sl.top + sl.height)); pathsT.push(pi); pathsB.push(pj); } return { from: m, top: pathsT, bottom: pathsB }; }; pv.SvgScene.areaJoinPaths = function(pathsT, pathsB, i, j) { for (var fullPathT = "", fullPathB = "", N = pathsT.length, k = i, l = N - 1 - j; j >= k; k++, l++) { var dT, dB, pathT = pathsT[k], pathB = pathsB[l]; if (k === i) { dT = pathT.join(""); dB = "L" + pathB[0].substr(1) + pathB[1]; } else { dT = pathT[1]; dB = pathB[1]; } fullPathT += dT; fullPathB += dB; } return fullPathT + fullPathB + "Z"; }; pv.SvgScene.areaSegmentedFull = function(e, scenes) { var pathsT, pathsB, count = scenes.length, result = this.areaSegmentCurvePaths(scenes, 0, count - 1); if (result) { pathsT = result.top; pathsB = result.bottom; } for (var i = (scenes[0], 0); count - 1 > i; i++) { var s1 = scenes[i], s2 = scenes[i + 1]; if (s1.visible && s2.visible) { var fill = s1.fillStyle, stroke = s1.strokeStyle; if (fill.opacity || stroke.opacity) { var d; if (pathsT) { var pathT = pathsT[i].join(""), pathB = "L" + pathsB[count - i - 2].join("").substr(1); d = pathT + pathB + "Z"; } else { var si = s1, sj = s2; switch (s1.interpolate) { case "step-before": si = s2; break; case "step-after": sj = s1; } d = "M" + s1.left + "," + si.top + "L" + s2.left + "," + sj.top + "L" + (s2.left + s2.width) + "," + (sj.top + sj.height) + "L" + (s1.left + s1.width) + "," + (si.top + si.height) + "Z"; } var attrs = { "shape-rendering": s1.antialias ? null : "crispEdges", "pointer-events": s1.events, cursor: s1.cursor, d: d, fill: fill.color, "fill-opacity": fill.opacity || null, stroke: stroke.color, "stroke-opacity": stroke.opacity || null, "stroke-width": stroke.opacity ? s1.lineWidth / this.scale : null }; e = this.expect(e, "path", scenes, i, attrs); s1.svg && this.setAttributes(e, s1.svg); s1.css && this.setStyle(e, s1.css); e = this.append(e, scenes, i); } } } return e; }; pv.SvgScene.areaPathStraight = function(scenes, i, j, s) { for (var pointsT = [], pointsB = [], k = j; k >= i; i++, j--) { var si = scenes[i], sj = scenes[j], pi = si.left + "," + si.top, pj = sj.left + sj.width + "," + (sj.top + sj.height); if (k > i) { var sk = scenes[i + 1], sl = scenes[j - 1]; switch (s.interpolate) { case "step-before": pi += "V" + sk.top; pj += "H" + (sl.left + sl.width); break; case "step-after": pi += "H" + sk.left; pj += "V" + (sl.top + sl.height); } } pointsT.push(pi); pointsB.push(pj); } return pointsT.concat(pointsB).join("L"); }; pv.SvgScene.areaPathCurve = function(scenes, i, j, s) { for (var pathT, pathB, pointsT = [], pointsB = [], k = j; k >= i; i++, j--) { var sj = scenes[j]; pointsT.push(scenes[i]); pointsB.push({ left: sj.left + sj.width, top: sj.top + sj.height }); } switch (s.interpolate) { case "basis": pathT = this.curveBasis(pointsT); pathB = this.curveBasis(pointsB); break; case "cardinal": pathT = this.curveCardinal(pointsT, s.tension); pathB = this.curveCardinal(pointsB, s.tension); break; default: pathT = this.curveMonotone(pointsT); pathB = this.curveMonotone(pointsB); } return pointsT[0].left + "," + pointsT[0].top + pathT + "L" + pointsB[0].left + "," + pointsB[0].top + pathB; }; pv.SvgScene.minBarWidth = 1; pv.SvgScene.minBarHeight = 1; pv.SvgScene.minBarLineWidth = .2; pv.SvgScene.bar = function(scenes) { for (var e = scenes.$g.firstChild, i = 0; i < scenes.length; i++) { var s = scenes[i]; if (!(!s.visible || Math.abs(s.width) <= 1e-10 || Math.abs(s.height) <= 1e-10)) { s.width < this.minBarWidth && (s.width = this.minBarWidth); s.height < this.minBarHeight && (s.height = this.minBarHeight); var fill = s.fillStyle, stroke = s.strokeStyle; if (fill.opacity || stroke.opacity) { this.addFillStyleDefinition(scenes, fill); this.addFillStyleDefinition(scenes, stroke); var lineWidth; if (stroke.opacity) { lineWidth = s.lineWidth; lineWidth = 1e-10 > lineWidth ? 0 : Math.max(this.minBarLineWidth, lineWidth / this.scale); } else lineWidth = null; e = this.expect(e, "rect", scenes, i, { "shape-rendering": s.antialias ? null : "crispEdges", "pointer-events": s.events, cursor: s.cursor, x: s.left, y: s.top, width: Math.max(1e-10, s.width), height: Math.max(1e-10, s.height), fill: fill.color, "fill-opacity": fill.opacity || null, stroke: stroke.color, "stroke-opacity": stroke.opacity || null, "stroke-width": lineWidth, "stroke-linecap": s.lineCap, "stroke-dasharray": stroke.opacity ? this.parseDasharray(s) : null }); s.svg && this.setAttributes(e, s.svg); s.css && this.setStyle(e, s.css); e = this.append(e, scenes, i); } } } return e; }; pv.SvgScene.dot = function(scenes) { for (var e = scenes.$g.firstChild, i = 0, L = scenes.length; L > i; i++) { var s = scenes[i]; if (s.visible) { var fill = s.fillStyle, fillOp = fill.opacity, stroke = s.strokeStyle, strokeOp = stroke.opacity; if (fillOp || strokeOp) { this.addFillStyleDefinition(scenes, fill); this.addFillStyleDefinition(scenes, stroke); var svg = { "shape-rendering": s.antialias ? null : "crispEdges", "pointer-events": s.events, cursor: s.cursor, fill: fill.color, "fill-opacity": fillOp || null, stroke: stroke.color, "stroke-opacity": strokeOp || null, "stroke-width": strokeOp ? s.lineWidth / this.scale : null, "stroke-linecap": s.lineCap, "stroke-dasharray": strokeOp ? this.parseDasharray(s) : null }, shape = s.shape || "circle", ar = s.aspectRatio, sa = s.shapeAngle, t = null; if ("circle" !== shape && this.hasSymbol(shape)) { var r = s.shapeRadius, rx = r, ry = r; if (ar > 0 && 1 !== ar) { var sy = 1 / Math.sqrt(ar), sx = ar * sy; rx *= sx; ry *= sy; } svg.d = this.renderSymbol(shape, s, rx, ry); shape = "path"; t = "translate(" + s.left + "," + s.top + ") "; sa && (t += "rotate(" + pv.degrees(sa) + ") "); } else if (1 === ar) { shape = "circle"; svg.cx = s.left; svg.cy = s.top; svg.r = s.shapeRadius; } else { shape = "ellipse"; svg.cx = svg.cy = 0; t = "translate(" + s.left + "," + s.top + ") "; sa && (t += "rotate(" + pv.degrees(sa) + ") "); svg.rx = s._width / 2; svg.ry = s._height / 2; } t && (svg.transform = t); e = this.expect(e, shape, scenes, i, svg); s.svg && this.setAttributes(e, s.svg); s.css && this.setStyle(e, s.css); e = this.append(e, scenes, i); } } } return e; }; !function(S) { var _renderersBySymName = {}; S.registerSymbol = function(symName, funRenderer) { _renderersBySymName[symName.toLowerCase()] = funRenderer; return S; }; S.renderSymbol = function(symName, instance, rx, ry) { return _renderersBySymName[symName].call(S, instance, symName, rx, ry); }; S.hasSymbol = function(symName) { return _renderersBySymName.hasOwnProperty(symName); }; S.symbols = function() { return pv.keys(_renderersBySymName); }; var C1 = 2 / Math.sqrt(3); S.registerSymbol("circle", function() { throw new Error("Not implemented as a symbol"); }).registerSymbol("cross", function(s, name, rx, ry) { var rxn = (s.shapeRadius, -rx), ryn = -ry; return "M" + rxn + "," + ryn + "L" + rx + "," + ry + "M" + rx + "," + ryn + "L" + rxn + "," + ry; }).registerSymbol("triangle", function(s, name, rx, ry) { var hp = ry, wp = rx * C1, hn = -ry, wn = -wp; return "M0," + hp + "L" + wp + "," + hn + " " + wn + "," + hn + "Z"; }).registerSymbol("diamond", function(s, name, rx, ry) { var rxp = rx * Math.SQRT2, ryp = ry * Math.SQRT2, rxn = -rxp, ryn = -ryp; return "M0," + ryn + "L" + rxp + ",0 0," + ryp + " " + rxn + ",0Z"; }).registerSymbol("square", function(s, name, rx, ry) { var rxn = -rx, ryn = -ry; return "M" + rxn + "," + ryn + "L" + rx + "," + ryn + " " + rx + "," + ry + " " + rxn + "," + ry + "Z"; }).registerSymbol("tick", function(s, name, rx, ry) { var ry2 = -ry * ry; return "M0,0L0," + ry2; }).registerSymbol("bar", function(s, name, rx, ry) { var z2 = ry * ry / 2; return "M0," + z2 + "L0," + -z2; }); }(pv.SvgScene); pv.SvgScene.image = function(scenes) { for (var e = scenes.$g.firstChild, i = 0; i < scenes.length; i++) { var s = scenes[i]; if (s.visible) { e = this.fill(e, scenes, i); if (s.image) { e = this.expect(e, "foreignObject", scenes, i, { cursor: s.cursor, x: s.left, y: s.top, width: s.width, height: s.height }); s.svg && this.setAttributes(e, s.svg); s.css && this.setStyle(e, s.css); var c = e.firstChild || e.appendChild(document.createElementNS(this.xhtml, "canvas")); c.$scene = { scenes: scenes, index: i }; c.style.width = s.width; c.style.height = s.height; c.width = s.imageWidth; c.height = s.imageHeight; c.getContext("2d").putImageData(s.image, 0, 0); } else { e = this.expect(e, "image", scenes, i, { preserveAspectRatio: "none", cursor: s.cursor, x: s.left, y: s.top, width: s.width, height: s.height }); s.svg && this.setAttributes(e, s.svg); s.css && this.setStyle(e, s.css); e.setAttributeNS(this.xlink, "xlink:href", s.url); } e = this.append(e, scenes, i); e = this.stroke(e, scenes, i); } } return e; }; pv.SvgScene.label = function(scenes) { for (var e = scenes.$g.firstChild, i = 0; i < scenes.length; i++) { var s = scenes[i]; if (s.visible) { var fill = s.textStyle; if (fill.opacity && s.text) { var x = 0, y = 0, dy = 0, anchor = "start"; switch (s.textBaseline) { case "middle": dy = ".35em"; break; case "top": dy = ".71em"; y = s.textMargin; break; case "bottom": y = "-" + s.textMargin; } switch (s.textAlign) { case "right": anchor = "end"; x = "-" + s.textMargin; break; case "center": anchor = "middle"; break; case "left": x = s.textMargin; } e = this.expect(e, "text", scenes, i, { "pointer-events": s.events, cursor: s.cursor, x: x, y: y, dy: dy, transform: "translate(" + s.left + "," + s.top + ")" + (s.textAngle ? " rotate(" + 180 * s.textAngle / Math.PI + ")" : "") + (1 != this.scale ? " scale(" + 1 / this.scale + ")" : ""), fill: fill.color, "fill-opacity": fill.opacity || null, "text-anchor": anchor }, { font: s.font, "text-shadow": s.textShadow, "text-decoration": s.textDecoration }); s.svg && this.setAttributes(e, s.svg); s.css && this.setStyle(e, s.css); e.firstChild ? e.firstChild.nodeValue = s.text : e.appendChild(document.createTextNode(s.text)); e = this.append(e, scenes, i); } } } return e; }; pv.SvgScene.line = function(scenes) { var e = scenes.$g.firstChild, count = scenes.length; if (!count) return e; var s = scenes[0]; return "smart" === s.segmented ? this.lineSegmentedSmart(e, scenes) : 2 > count ? e : s.segmented ? this.lineSegmentedFull(e, scenes) : this.lineFixed(e, scenes); }; pv.SvgScene.lineFixed = function(elm, scenes) { var count = scenes.length; if (1 === count) return this.lineAreaDotAlone(elm, scenes, 0); var s = scenes[0]; if (!s.visible) return elm; var fill = s.fillStyle, stroke = s.strokeStyle; if (!fill.opacity && !stroke.opacity) return elm; this.addFillStyleDefinition(scenes, fill); this.addFillStyleDefinition(scenes, stroke); var d = "M" + s.left + "," + s.top, curveInterpolated = count > 2; if (curveInterpolated) switch (s.interpolate) { case "basis": d += this.curveBasis(scenes); break; case "cardinal": d += this.curveCardinal(scenes, s.tension); break; case "monotone": d += this.curveMonotone(scenes); break; default: curveInterpolated = !1; } if (!curveInterpolated) for (var i = 1; count > i; i++) d += this.lineSegmentPath(scenes[i - 1], scenes[i]); var sop = stroke.opacity, attrs = { "shape-rendering": s.antialias ? null : "crispEdges", "pointer-events": s.events, cursor: s.cursor, d: d, fill: fill.color, "fill-opacity": fill.opacity || null, stroke: stroke.color, "stroke-opacity": sop || null, "stroke-width": sop ? s.lineWidth / this.scale : null, "stroke-linecap": s.lineCap, "stroke-linejoin": s.lineJoin, "stroke-miterlimit": s.strokeMiterLimit, "stroke-dasharray": sop ? this.parseDasharray(s) : null }; elm = this.expect(elm, "path", scenes, 0, attrs, s.css); s.svg && this.setAttributes(elm, s.svg); return this.append(elm, scenes, 0); }; pv.SvgScene.lineSegmentedSmart = function(elm, scenes) { return this.eachLineAreaSegment(elm, scenes, function(elm, scenes, from, to) { var paths = this.lineSegmentPaths(scenes, from, to), fromp = from, options = { breakOnKeyChange: !0, from: from, to: to }; return this.eachLineAreaSegment(elm, scenes, options, function(elm, scenes, from, to, ka, eventsMax) { var s1 = scenes[from], fill = s1.fillStyle; this.addFillStyleDefinition(scenes, fill); var stroke = s1.strokeStyle; this.addFillStyleDefinition(scenes, stroke); if (from === to) return this.lineAreaDotAlone(elm, scenes, from); var d = this.lineJoinPaths(paths, from - fromp, to - fromp - 1), sop = stroke.opacity, attrs = { "shape-rendering": s1.antialias ? null : "crispEdges", "pointer-events": eventsMax, cursor: s1.cursor, d: d, fill: fill.color, "fill-opacity": fill.opacity || null, stroke: stroke.color, "stroke-opacity": sop || null, "stroke-width": sop ? s1.lineWidth / this.scale : null, "stroke-linecap": s1.lineCap, "stroke-linejoin": s1.lineJoin, "stroke-miterlimit": s1.strokeMiterLimit, "stroke-dasharray": sop ? this.parseDasharray(s1) : null }; elm = this.expect(elm, "path", scenes, from, attrs, s1.css); return this.append(elm, scenes, from); }); }); }; pv.SvgScene.lineSegmentedFull = function(e, scenes) { var paths, s = scenes[0]; switch (s.interpolate) { case "basis": paths = this.curveBasisSegments(scenes); break; case "cardinal": paths = this.curveCardinalSegments(scenes, s.tension); break; case "monotone": paths = this.curveMonotoneSegments(scenes); } for (var i = 0, n = scenes.length - 1; n > i; i++) { var s1 = scenes[i], s2 = scenes[i + 1]; if (s1.visible && s2.visible) { var stroke = s1.strokeStyle, fill = pv.FillStyle.transparent; if (stroke.opacity) { var d; if ("linear" == s1.interpolate && "miter" == s1.lineJoin) { fill = stroke; stroke = pv.FillStyle.transparent; d = this.pathJoin(scenes[i - 1], s1, s2, scenes[i + 2]); } else d = paths ? paths[i].join("") : "M" + s1.left + "," + s1.top + this.lineSegmentPath(s1, s2); e = this.expect(e, "path", scenes, i, { "shape-rendering": s1.antialias ? null : "crispEdges", "pointer-events": s1.events, cursor: s1.cursor, d: d, fill: fill.color, "fill-opacity": fill.opacity || null, stroke: stroke.color, "stroke-opacity": stroke.opacity || null, "stroke-width": stroke.opacity ? s1.lineWidth / this.scale : null, "stroke-linejoin": s1.lineJoin }); s1.svg && this.setAttributes(e, s1.svg); s1.css && this.setStyle(e, s1.css); e = this.append(e, scenes, i); } } } return e; }; pv.SvgScene.lineSegmentPath = function(s1, s2) { var l = 1; switch (s1.interpolate) { case "polar-reverse": l = 0; case "polar": var dx = s2.left - s1.left, dy = s2.top - s1.top, e = 1 - s1.eccentricity, r = Math.sqrt(dx * dx + dy * dy) / (2 * e); if (0 >= e || e > 1) break; return "A" + r + "," + r + " 0 0," + l + " " + s2.left + "," + s2.top; case "step-before": return "V" + s2.top + "H" + s2.left; case "step-after": return "H" + s2.left + "V" + s2.top; } return "L" + s2.left + "," + s2.top; }; pv.SvgScene.lineSegmentPaths = function(scenes, from, to) { var paths, s = scenes[from]; switch (s.interpolate) { case "basis": paths = this.curveBasisSegments(scenes, from, to); break; case "cardinal": paths = this.curveCardinalSegments(scenes, s.tension, from, to); break; case "monotone": paths = this.curveMonotoneSegments(scenes, from, to); } if (!paths || !paths.length) { paths = []; for (var i = from + 1; to >= i; i++) { var s1 = scenes[i - 1], s2 = scenes[i]; paths.push([ "M" + s1.left + "," + s1.top, this.lineSegmentPath(s1, s2) ]); } } return paths; }; pv.strokeMiterLimit = 4; pv.SvgScene.pathJoin = function(s0, s1, s2, s3) { var miterLimit, miterRatio, miterLength, pts = [], w1 = s1.lineWidth / this.scale, p1 = pv.vector(s1.left, s1.top), p2 = pv.vector(s2.left, s2.top), p21 = p2.minus(p1), v21 = p21.perp().norm(), w21 = v21.times(w1 / 2), a = p1.plus(w21), d = p1.minus(w21), b = p2.plus(w21), c = p2.minus(w21); if (s0 && s0.visible) { var p0 = pv.vector(s0.left, s0.top), p10 = p1.minus(p0), v10 = p10.perp().norm(), v1 = v10.plus(v21).norm(), am = this.lineIntersect(p1, v1, a, p21), dm = this.lineIntersect(p1, v1, d, p21); miterLength = am.minus(dm).length(); var w0 = s0.lineWidth / this.scale, w10avg = (w1 + w0) / 2; miterRatio = miterLength / w10avg; miterLimit = s1.strokeMiterLimit || pv.strokeMiterLimit; if (miterLimit >= miterRatio) pts.push(dm, am); else { var p12 = p21.times(-1), v1Outer = p10.norm().plus(p12.norm()).norm(), bevel10 = p1.plus(v1Outer.times(w10avg / 2)); v1Outer.dot(v21) >= 0 ? pts.push(dm, bevel10, a) : pts.push(d, bevel10, am); } } else pts.push(d, a); if (s3 && s3.visible) { var p3 = pv.vector(s3.left, s3.top), p32 = p3.minus(p2), v32 = p32.perp().norm(), v2 = v32.plus(v21).norm(), bm = this.lineIntersect(p2, v2, b, p21), cm = this.lineIntersect(p2, v2, c, p21); miterLength = bm.minus(cm).length(); var w3 = s3.lineWidth / this.scale, w31avg = (w3 + w1) / 2; miterRatio = miterLength / w31avg; miterLimit = s2.strokeMiterLimit || pv.strokeMiterLimit; if (miterLimit >= miterRatio) pts.push(bm, cm); else { var p23 = p32.times(-1), v2Outer = p21.norm().plus(p23.norm()).norm(), bevel31 = p2.plus(v2Outer.times(w31avg / 2)); v2Outer.dot(v21) >= 0 ? pts.push(b, bevel31, cm) : pts.push(bm, bevel31, c); } } else pts.push(b, c); var pt = pts.shift(); return "M" + pt.x + "," + pt.y + "L" + pts.map(function(pt2) { return pt2.x + "," + pt2.y; }).join(" "); }; pv.SvgScene.lineIntersect = function(o1, d1, o2, d2) { return o1.plus(d1.times(o2.minus(o1).dot(d2.perp()) / d1.dot(d2.perp()))); }; pv.SvgScene.lineJoinPaths = function(paths, from, to) { for (var d = paths[from].join(""), i = from + 1; to >= i; i++) d += paths[i][1]; return d; }; pv.SvgScene.lineAreaDotAlone = function(elm) { return elm; }; pv.Scene.eventsToNumber = { "": 0, none: 0, painted: 1, all: 2 }; pv.Scene.numberToEvents = [ "none", "painted", "all" ]; pv.SvgScene.eachLineAreaSegment = function(elm, scenes, keyArgs, lineAreaSegment) { if ("function" == typeof keyArgs) { lineAreaSegment = keyArgs; keyArgs = null; } var eventsNumber, ki, kf, breakOnKeyChange = pv.get(keyArgs, "breakOnKeyChange", !1), from = pv.get(keyArgs, "from") || 0, to = pv.get(keyArgs, "to", scenes.length - 1); if (breakOnKeyChange) { ki = []; kf = []; } for (var i = from; to >= i; ) { var si = scenes[i]; if (this.isSceneVisible(si)) { eventsNumber = this.eventsToNumber[si.events] || 0; breakOnKeyChange && this.lineAreaSceneKey(si, ki); for (var i2, f = i; ;) { var f2 = f + 1; if (f2 > to) { i2 = f2; break; } var sf = scenes[f2]; if (!this.isSceneVisible(sf)) { i2 = f2 + 1; break; } eventsNumber = Math.max(eventsNumber, this.eventsToNumber[sf.events] || 0); f = f2; if (breakOnKeyChange) { this.lineAreaSceneKey(sf, kf); if (!this.equalSceneKeys(ki, kf)) { i2 = f; break; } } } elm = lineAreaSegment.call(this, elm, scenes, i, f, keyArgs, this.numberToEvents[eventsNumber]); i = i2; } else i++; } return elm; }; pv.SvgScene.lineAreaSceneKey = function(s, k) { k[0] = s.fillStyle.key; k[1] = s.strokeStyle.key; k[2] = s.lineWidth; k[3] = s.strokeDasharray || "none"; k[4] = s.interpolate; return k; }; pv.SvgScene.isSceneVisible = function(s) { return s.visible && (s.fillStyle.opacity > 0 || s.strokeStyle.opacity > 0); }; pv.SvgScene.equalSceneKeys = function(ka, kb) { for (var i = 0, K = ka.length; K > i; i++) if (ka[i] !== kb[i]) return !1; return !0; }; pv.SvgScene.panel = function(scene) { for (var g = scene.$g, e = g && g.firstChild, i = 0, L = scene.length; L > i; i++) { var s = scene[i]; if (s.visible) { if (!scene.parent) { var canvas = s.canvas; this.applyCanvasStyle(canvas); if (g && g.parentNode !== canvas) { g = canvas.firstChild; e = g && g.firstChild; } if (g) e && "defs" === e.tagName && (e = e.nextSibling); else { g = this.createRootPanelElement(); e = null; this.initRootPanelElement(g, scene.mark); canvas.appendChild(g); scene.$defs = g.appendChild(this.create("defs")); scene.$g = g; } g.setAttribute("width", s.width + s.left + s.right); g.setAttribute("height", s.height + s.top + s.bottom); } var clip_g = null; if ("hidden" === s.overflow) { var clipResult = this.addPanelClipPath(g, e, scene, i, s); clip_g = clipResult.g; scene.$g = g = clip_g; e = clipResult.next; } e = this.fill(e, scene, i); var k = this.scale, t = s.transform, x = s.left + t.x, y = s.top + t.y; this.scale *= t.k; if (s.children.length) for (var attrs = { transform: "translate(" + x + "," + y + ")" + (1 != t.k ? " scale(" + t.k + ")" : "") }, childScenes = this.getSortedChildScenes(scene, i), j = 0, C = childScenes.length; C > j; j++) { var childScene = childScenes[j]; childScene.$g = e = this.expect(e, "g", scene, i, attrs); this.updateAll(childScene); e.parentNode || g.appendChild(e); e = e.nextSibling; } this.scale = k; e = this.stroke(e, scene, i); if (clip_g) { scene.$g = g = clip_g.parentNode; e = clip_g.nextSibling; } } } return e; }; pv.SvgScene.applyCanvasStyle = function(canvas) { canvas.style.display = "inline-block"; }; pv.SvgScene.createRootPanelElement = function() { return this.create("svg"); }; pv.SvgScene.initRootPanelElement = function(g, panel) { g.setAttribute("font-size", "10px"); g.setAttribute("font-family", "sans-serif"); g.setAttribute("fill", "none"); g.setAttribute("stroke", "none"); g.setAttribute("stroke-width", 1.5); this.disableElementSelection(g); this.listenRootPanelElement(g, panel); }; pv.SvgScene.listenRootPanelElement = function(g, panel) { for (var j = 0, evs = this.events, J = evs.length; J > j; j++) { g.addEventListener(evs[j], this.dispatch, !1); panel._registerBoundEvent(g, evs[j], this.dispatch, !1); } }; pv.SvgScene.disableElementSelection = function(g) { g.setAttribute("style", "-webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none;"); if ("undefined" != typeof g.onselectstart) { g.setAttribute("unselectable", "on"); g.onselectstart = function() { return !1; }; } }; pv.SvgScene.addPanelClipPath = function(g, e, scene, i, s) { var id = pv.id().toString(36), clip_g = this.expect(e, "g", scene, i, { "clip-path": "url(#" + id + ")" }), clip_p = this.expect(clip_g.firstChild, "clipPath", scene, i, { id: id }), r = clip_p.firstChild || clip_p.appendChild(this.create("rect")); r.setAttribute("x", s.left); r.setAttribute("y", s.top); r.setAttribute("width", s.width); r.setAttribute("height", s.height); clip_p.parentNode || clip_g.appendChild(clip_p); clip_g.parentNode || g.appendChild(clip_g); return { g: clip_g, next: clip_p.nextSibling }; }; pv.SvgScene.getSortedChildScenes = function(scene, i) { var children = scene[i].children; if (scene.mark._zOrderChildCount) { children = children.slice(0); children.sort(function(scenes1, scenes2) { var compare = scenes1.mark._zOrder - scenes2.mark._zOrder; 0 === compare && (compare = scenes1.childIndex - scenes2.childIndex); return compare; }); } return children; }; pv.SvgScene.fill = function(e, scene, i) { var s = scene[i], fill = s.fillStyle; if (fill.opacity || "all" == s.events) { this.addFillStyleDefinition(scene, fill); e = this.expect(e, "rect", scene, i, { "shape-rendering": s.antialias ? null : "crispEdges", "pointer-events": s.events, cursor: s.cursor, x: s.left, y: s.top, width: s.width, height: s.height, fill: fill.color, "fill-opacity": fill.opacity, stroke: null }); e = this.append(e, scene, i); } return e; }; pv.SvgScene.stroke = function(e, scene, i) { var s = scene[i], stroke = s.strokeStyle; if (stroke.opacity || "all" == s.events) { e = this.expect(e, "rect", scene, i, { "shape-rendering": s.antialias ? null : "crispEdges", "pointer-events": "all" == s.events ? "stroke" : s.events, cursor: s.cursor, x: s.left, y: s.top, width: Math.max(1e-10, s.width), height: Math.max(1e-10, s.height), fill: null, stroke: stroke.color, "stroke-opacity": stroke.opacity, "stroke-width": s.lineWidth / this.scale, "stroke-linecap": s.lineCap, "stroke-dasharray": stroke.opacity ? this.parseDasharray(s) : null }); e = this.append(e, scene, i); } return e; }; pv.SvgScene.minRuleLineWidth = 1; pv.SvgScene.rule = function(scenes) { for (var e = scenes.$g.firstChild, i = 0; i < scenes.length; i++) { var s = scenes[i]; if (s.visible) { var stroke = s.strokeStyle; if (stroke.opacity) { var lineWidth = s.lineWidth; lineWidth = 1e-10 > lineWidth ? 0 : Math.max(this.minRuleLineWidth, lineWidth / this.scale); e = this.expect(e, "line", scenes, i, { "shape-rendering": s.antialias ? null : "crispEdges", "pointer-events": s.events, cursor: s.cursor, x1: s.left, y1: s.top, x2: s.left + s.width, y2: s.top + s.height, stroke: stroke.color, "stroke-opacity": stroke.opacity, "stroke-width": lineWidth, "stroke-linecap": s.lineCap, "stroke-dasharray": stroke.opacity ? this.parseDasharray(s) : null }); s.svg && this.setAttributes(e, s.svg); s.css && this.setStyle(e, s.css); e = this.append(e, scenes, i); } } } return e; }; pv.SvgScene.wedge = function(scenes) { for (var e = scenes.$g.firstChild, i = 0; i < scenes.length; i++) { var s = scenes[i]; if (s.visible) { var fill = s.fillStyle, stroke = s.strokeStyle; if (fill.opacity || stroke.opacity) { var p, r1 = s.innerRadius, r2 = s.outerRadius, a = Math.abs(s.angle); if (a >= 2 * Math.PI) p = r1 ? "M0," + r2 + "A" + r2 + "," + r2 + " 0 1,1 0," + -r2 + "A" + r2 + "," + r2 + " 0 1,1 0," + r2 + "M0," + r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + -r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + r1 + "Z" : "M0," + r2 + "A" + r2 + "," + r2 + " 0 1,1 0," + -r2 + "A" + r2 + "," + r2 + " 0 1,1 0," + r2 + "Z"; else { var sa = Math.min(s.startAngle, s.endAngle), ea = Math.max(s.startAngle, s.endAngle), c1 = Math.cos(sa), c2 = Math.cos(ea), s1 = Math.sin(sa), s2 = Math.sin(ea); p = r1 ? "M" + r2 * c1 + "," + r2 * s1 + "A" + r2 + "," + r2 + " 0 " + (a < Math.PI ? "0" : "1") + ",1 " + r2 * c2 + "," + r2 * s2 + "L" + r1 * c2 + "," + r1 * s2 + "A" + r1 + "," + r1 + " 0 " + (a < Math.PI ? "0" : "1") + ",0 " + r1 * c1 + "," + r1 * s1 + "Z" : "M" + r2 * c1 + "," + r2 * s1 + "A" + r2 + "," + r2 + " 0 " + (a < Math.PI ? "0" : "1") + ",1 " + r2 * c2 + "," + r2 * s2 + "L0,0Z"; } this.addFillStyleDefinition(scenes, fill); this.addFillStyleDefinition(scenes, stroke); e = this.expect(e, "path", scenes, i, { "shape-rendering": s.antialias ? null : "crispEdges", "pointer-events": s.events, cursor: s.cursor, transform: "translate(" + s.left + "," + s.top + ")", d: p, fill: fill.color, "fill-rule": "evenodd", "fill-opacity": fill.opacity || null, stroke: stroke.color, "stroke-opacity": stroke.opacity || null, "stroke-width": stroke.opacity ? s.lineWidth / this.scale : null, "stroke-linejoin": s.lineJoin, "stroke-miterlimit": s.strokeMiterLimit, "stroke-linecap": s.lineCap, "stroke-dasharray": stroke.opacity ? this.parseDasharray(s) : null }); s.svg && this.setAttributes(e, s.svg); s.css && this.setStyle(e, s.css); e = this.append(e, scenes, i); } } } return e; }; pv.Mark = function() { this.$properties = []; this.$propertiesMap = {}; this.$handlers = {}; }; pv.Mark.prototype.properties = {}; pv.Mark.cast = {}; pv.Mark.prototype.property = function(name, cast) { this.hasOwnProperty("properties") || (this.properties = pv.extend(this.properties)); this.properties[name] = !0; pv.Mark.prototype.propertyMethod(name, !1, pv.Mark.cast[name] = cast); return this; }; pv.Mark.prototype.localProperty = function(name, cast) { this.hasOwnProperty("properties") || (this.properties = pv.extend(this.properties)); this.properties[name] = !0; var currCast = pv.Mark.cast[name]; cast && (pv.Mark.cast[name] = currCast = cast); this.propertyMethod(name, !1, currCast); return this; }; pv.Mark.prototype.def = function(name, v) { this.propertyMethod(name, !0); return this[name](arguments.length > 1 ? v : null); }; pv.Mark.prototype.propertyMethod = function(name, isDef, cast) { cast || (cast = pv.Mark.cast[name]); this[name] = function(v, tag) { if (isDef && this.scene) { var defs = this.scene.defs; if (arguments.length) { defs[name] = { id: null == v ? 0 : pv.id(), value: null != v && cast ? cast(v) : v }; return this; } var def = defs[name]; return def ? def.value : null; } if (arguments.length) { this.setPropertyValue(name, v, isDef, cast, !1, tag); return this; } var s = this.instance(); if (pv.propBuildMark === this && 1 !== pv.propBuilt[name]) { pv.propBuilt[name] = 1; return s[name] = this.evalProperty(this.binds.properties[name]); } return s[name]; }; }; pv.Mark.funPropertyCaller = function(fun, cast) { function mark_callFunProperty() { var value = fun.apply(this, stack); return null != value ? cast(value) : value; } var stack = pv.Mark.stack; return mark_callFunProperty; }; pv.Mark.prototype.setPropertyValue = function(name, v, isDef, cast, chain, tag) { var type = !isDef << 1 | "function" == typeof v; 1 & type && cast ? v = pv.Mark.funPropertyCaller(v, cast) : null != v && cast && (v = cast(v)); var propertiesMap = this.$propertiesMap, properties = this.$properties, p = { name: name, id: pv.id(), value: v, type: type, tag: tag, proto: null, root: null, _proto: null }; p.root = p; var existing = propertiesMap[name]; propertiesMap[name] = p; if (existing) for (var i = 0, P = properties.length; P > i; i++) if (properties[i] === existing) { properties.splice(i, 1); break; } properties.push(p); if (chain && existing && 3 === type) { p.proto = existing; p.root = existing.root; } return p; }; pv.Mark.prototype.intercept = function(name, v, keyArgs) { this.setPropertyValue(name, v, !1, pv.get(keyArgs, "noCast") ? null : pv.Mark.cast[name], !0, pv.get(keyArgs, "tag")); return this; }; pv.Mark.prototype.propertyValue = function(name, inherit) { var p = this.$propertiesMap[name]; if (p) return p.value; if (inherit) { if (this.proto) { var value = this.proto._propertyValueRecursive(name); if (void 0 !== value) return value; } return this.defaults._propertyValueRecursive(name); } }; pv.Mark.prototype._propertyValueRecursive = function(name) { var p = this.$propertiesMap[name]; return p ? p.value : this.proto ? this.proto._propertyValueRecursive(name) : void 0; }; pv.Mark.stack = []; pv.Mark.prototype.property("data").property("visible", Boolean).property("css", Object).property("svg", Object).property("left", Number).property("right", Number).property("top", Number).property("bottom", Number).property("cursor", String).property("title", String).property("reverse", Boolean).property("antialias", Boolean).property("events", pv.stringLowerCase).property("id", String); pv.Mark.prototype.childIndex = -1; pv.Mark.prototype.index = -1; pv.Mark.prototype.scale = 1; pv.Mark.prototype._zOrder = 0; pv.Mark.prototype.defaults = new pv.Mark().data(function(d) { return [ d ]; }).visible(!0).antialias(!0).events("painted"); pv.Mark.prototype.extend = function(proto) { this.proto = proto; this.target = proto.target; return this; }; pv.Mark.prototype.add = function(type) { return this.parent.add(type).extend(this); }; pv.Mark.prototype.zOrder = function(zOrder) { if (!arguments.length) return this._zOrder; zOrder = +zOrder || 0; if (this._zOrder !== zOrder) { var p = this.parent; p && 0 !== this._zOrder && p._zOrderChildCount--; this._zOrder = zOrder; p && 0 !== this._zOrder && p._zOrderChildCount++; } return this; }; pv.Mark.prototype.anchor = function(name) { return new pv.Anchor(this).name(name || "center").data(function() { return this.scene.target.map(function(s) { return s.data; }); }).visible(function() { return this.scene.target[this.index].visible; }).id(function() { return this.scene.target[this.index].id; }).left(function() { var s = this.scene.target[this.index], w = s.width || 0; switch (this.name()) { case "bottom": case "top": case "center": return s.left + w / 2; case "left": return null; } return s.left + w; }).top(function() { var s = this.scene.target[this.index], h = s.height || 0; switch (this.name()) { case "left": case "right": case "center": return s.top + h / 2; case "top": return null; } return s.top + h; }).right(function() { var s = this.scene.target[this.index]; return "left" == this.name() ? s.right + (s.width || 0) : null; }).bottom(function() { var s = this.scene.target[this.index]; return "top" == this.name() ? s.bottom + (s.height || 0) : null; }).textAlign(function() { switch (this.name()) { case "bottom": case "top": case "center": return "center"; case "right": return "right"; } return "left"; }).textBaseline(function() { switch (this.name()) { case "right": case "left": case "center": return "middle"; case "top": return "top"; } return "bottom"; }); }; pv.Mark.prototype.anchorTarget = function() { return this.target; }; pv.Mark.prototype.margin = function(n) { return this.left(n).right(n).top(n).bottom(n); }; pv.Mark.prototype.instance = function(defaultIndex) { var scene = this.scene || this.parent.instance(-1).children[this.childIndex], index = null == defaultIndex || this.hasOwnProperty("index") ? this.index : defaultIndex; return scene[0 > index ? scene.length - 1 : index]; }; pv.Mark.prototype.instances = function(source) { for (var scene, mark = this, index = []; !(scene = mark.scene); ) { index.push({ index: source.parentIndex, childIndex: mark.childIndex }); source = source.parent; mark = mark.parent; } for (var j = index.length; j--; ) { var info = index[j]; scene = scene[info.index].children[info.childIndex]; } if (this.hasOwnProperty("index")) { var s = pv.extend(scene[this.index]); s.right = s.top = s.left = s.bottom = 0; return [ s ]; } return scene; }; pv.Mark.prototype.first = function() { return this.scene[0]; }; pv.Mark.prototype.last = function() { return this.scene[this.scene.length - 1]; }; pv.Mark.prototype.sibling = function() { return 0 == this.index ? null : this.scene[this.index - 1]; }; pv.Mark.prototype.cousin = function() { var p = this.parent, s = p && p.sibling(); return s && s.children ? s.children[this.childIndex][this.index] : null; }; pv.Mark.prototype._renderId = 0; pv.Mark.prototype.renderId = function() { return this.root._renderId; }; pv.Mark.prototype.render = function() { var root = this.root; if (!this.parent || root.scene) { root._renderId++; this.renderCore(); } else root.render(); }; pv.Mark.prototype.renderCore = function() { function render(mark, depth, scale) { mark.scale = scale; if (L > depth) { var addStack = depth >= stack.length; addStack && stack.unshift(null); if (mark.hasOwnProperty("index")) renderCurrentInstance(mark, depth, scale, addStack); else { for (var i = 0, n = mark.scene.length; n > i; i++) { mark.index = i; renderCurrentInstance(mark, depth, scale, addStack); } delete mark.index; } addStack && stack.shift(); } else { mark.build(); pv.Scene.scale = scale; pv.Scene.updateAll(mark.scene); } delete mark.scale; } function renderCurrentInstance(mark, depth, scale, fillStack) { var i, s = mark.scene[mark.index]; if (s.visible) { var childMarks = mark.children, childScenez = s.children, childIndex = indexes[depth], childMark = childMarks[childIndex]; childMark.scene || childIndex++; for (i = 0; childIndex > i; i++) childMarks[i].scene = childScenez[i]; fillStack && (stack[0] = s.data); render(childMark, depth + 1, scale * s.transform.k); for (i = 0; childIndex > i; i++) childMarks[i].scene = void 0; } } for (var parent = this.parent, stack = pv.Mark.stack, S = stack.length, indexes = [], mark = this; mark.parent; mark = mark.parent) indexes.unshift(mark.childIndex); var L = indexes.length; this.bind(); for (;parent && !parent.hasOwnProperty("index"); ) parent = parent.parent; try { this.context(parent ? parent.scene : void 0, parent ? parent.index : -1, function() { render(this.root, 0, 1); }); } catch (e) { stack.length > S && (stack.length = S); throw e; } }; pv.Mark.prototype.bind = function() { function bind(mark) { do for (var properties = mark.$properties, i = properties.length; i--; ) { var p = properties[i], name = p.name, pLeaf = seen[name]; if (pLeaf) { var pRoot = root[name]; if (3 === pRoot.type) { pRoot._proto = p; pRoot = root[name] = p.root; pRoot._proto = null; } } else { seen[name] = p; root[name] = p.root; p.root._proto = null; switch (name) { case "data": data = p; break; case "visible": case "id": required.push(p); break; default: types[p.type].push(p); } } } while (mark = mark.proto); } var data, seen = {}, root = {}, required = [], types = [ [], [], [], [] ]; bind(this); bind(this.defaults); var types0 = types[0], types1 = types[1].reverse(), types2 = types[2]; types[3].reverse(); var mark = this; do for (var name in mark.properties) name in seen || types2.push(seen[name] = { name: name, type: 2, value: null }); while (mark = mark.proto); var defs; if (types0.length || types1.length) { defs = types0.concat(types1); for (var i = 0, D = defs.length; D > i; i++) this.propertyMethod(defs[i].name, !0); } else defs = []; this.binds = { properties: seen, data: data, defs: defs, required: required, optional: pv.blend(types) }; }; pv.Mark.prototype.build = function() { var stack = pv.Mark.stack, scene = this.scene; if (!scene) { scene = this.scene = []; scene.mark = this; scene.type = this.type; scene.childIndex = this.childIndex; var parent = this.parent; if (parent) { scene.parent = parent.scene; scene.parentIndex = parent.index; } } this.target && (scene.target = this.target.instances(scene)); var bdefs = this.binds.defs; if (bdefs.length) for (var defs = scene.defs || (scene.defs = {}), i = 0, B = bdefs.length; B > i; i++) { var p = bdefs[i], d = defs[p.name]; (!d || p.id > d.id) && (defs[p.name] = { id: 0, value: 1 & p.type ? p.value.apply(this, stack) : p.value }); } var datas = this.evalProperty(this.binds.data), L = datas.length; scene.length = L; if (L) { var markProto = pv.Mark.prototype; stack.unshift(null); var propBuildMarkBefore = pv.propBuildMark, propBuiltBefore = pv.propBuilt; pv.propBuildMark = this; try { for (var i = 0; L > i; i++) { markProto.index = this.index = i; pv.propBuilt = {}; var instance = scene[i]; instance ? instance._state && delete instance._state : instance = scene[i] = {}; instance.data = stack[0] = datas[i]; this.preBuildInstance(instance); this.buildInstance(instance); } } finally { markProto.index = -1; delete this.index; stack.shift(); pv.propBuildMark = propBuildMarkBefore; pv.propBuilt = propBuiltBefore; } } return this; }; pv.Mark.prototype.instanceState = function(s) { s || (s = this.instance()); return s ? s._state || (s._state = {}) : null; }; pv.Mark.prototype.preBuildInstance = function() {}; pv.Mark.prototype.buildInstance = function(s) { this.buildProperties(s, this.binds.required); if (s.visible) { this.buildProperties(s, this.binds.optional); this.buildImplied(s); } }; !function() { var _protoProp, _stack = pv.Mark.stack, _evalPropByType = [ function(p) { return this.scene.defs[p.name].value; }, null, function(p) { return p.value; }, function(p) { _protoProp = p.proto || p._proto; return p.value.apply(this, _stack); } ]; _evalPropByType[1] = _evalPropByType[0]; pv.Mark.prototype.buildProperties = function(s, properties) { var built = pv.propBuilt, localBuilt = !built; if (localBuilt) { pv.propBuildMark = this; pv.propBuilt = built = {}; } for (var protoPropBefore = _protoProp, i = 0, P = properties.length; P > i; i++) { var p = properties[i], pname = p.name; if (!(pname in built)) { built[pname] = 1; s[pname] = _evalPropByType[p.type].call(this, p); } } _protoProp = protoPropBefore; localBuilt && (pv.propBuildMark = pv.propBuilt = null); }; pv.Mark.prototype.evalProperty = function(p) { var protoPropBefore = _protoProp, v = _evalPropByType[p.type].call(this, p); _protoProp = protoPropBefore; return v; }; pv.Mark.prototype.evalInPropertyContext = function(f, protoProp) { var protoPropBefore = _protoProp; _protoProp = protoProp; var v = f.apply(this, _stack); _protoProp = protoPropBefore; return v; }; pv.Mark.prototype.delegate = function(dv, tag) { if (_protoProp && (!tag || _protoProp.tag === tag)) { var value = this.evalProperty(_protoProp); if (void 0 !== value) return value; } return dv; }; pv.Mark.prototype.delegateExcept = function(dv, notTag) { if (_protoProp && (!notTag || _protoProp.tag !== notTag)) { var value = this.evalProperty(_protoProp); if (void 0 !== value) return value; } return dv; }; pv.Mark.prototype.hasDelegate = function(tag) { return !(!_protoProp || tag && _protoProp.tag !== tag); }; }(); pv.Mark.prototype.buildImplied = function(s) { var parent_s, checked, l = s.left, r = s.right, t = s.top, b = s.bottom, p = this.properties, w = p.width ? s.width : 0, h = p.height ? s.height : 0; if (null == w || null == r || null == l) { parent_s = this.parent && this.parent.instance(); checked = !0; var width = parent_s ? parent_s.width : w + l + r; null == w ? w = width - (r = r || 0) - (l = l || 0) : null == r ? null == l ? l = r = (width - w) / 2 : r = width - w - l : l = width - w - r; } if (null == h || null == b || null == t) { checked || (parent_s = this.parent && this.parent.instance()); var height = parent_s ? parent_s.height : h + t + b; null == h ? h = height - (t = t || 0) - (b = b || 0) : null == b ? b = null == t ? t = (height - h) / 2 : height - h - t : t = height - h - b; } s.left = l; s.right = r; s.top = t; s.bottom = b; p.width && (s.width = w); p.height && (s.height = h); p.textStyle && !s.textStyle && (s.textStyle = pv.FillStyle.transparent); p.fillStyle && !s.fillStyle && (s.fillStyle = pv.FillStyle.transparent); p.strokeStyle && !s.strokeStyle && (s.strokeStyle = pv.FillStyle.transparent); }; pv.Mark.prototype.mouse = function() { var n = this.root.canvas(), ev = pv.event, x = ev && ev.pageX || 0, y = ev && ev.pageY || 0, offset = pv.elementOffset(n); if (offset) { var getStyle = pv.cssStyle(n); x -= offset.left + parseFloat(getStyle("paddingLeft") || 0); y -= offset.top + parseFloat(getStyle("paddingTop") || 0); } var t = pv.Transform.identity, p = this.properties.transform ? this : this.parent, pz = []; do pz.push(p); while (p = p.parent); for (;p = pz.pop(); ) { var pinst = p.instance(); t = t.translate(pinst.left, pinst.top).times(pinst.transform); } t = t.invert(); return pv.vector(x * t.k + t.x, y * t.k + t.y); }; pv.Mark.prototype.event = function(type, handler) { handler = pv.functor(handler); var hs = this.$handlers[type]; hs ? hs instanceof Array ? hs.push(handler) : hs = [ hs, handler ] : hs = handler; this.$hasHandlers = !0; this.$handlers[type] = hs; return this; }; pv.Mark.prototype.context = function(scene, index, f) { function apply(scene, index) { pv.Mark.scene = scene; proto.index = index; if (scene) { var i, that = scene.mark, mark = that, ancestors = []; do { ancestors.push(mark); stack.push(scene[index].data); mark.index = index; mark.scene = scene; if (mark = mark.parent) { index = scene.parentIndex; scene = scene.parent; } } while (mark); var k = 1; i = ancestors.length - 1; if (i > 0) do { mark = ancestors[i--]; mark.scale = k; k *= mark.scene[mark.index].transform.k; } while (i); that.scale = k; var n, children = that.children; if (children && (n = children.length) > 0) { var thatInst = that.scene[that.index]; k *= thatInst.transform.k; var childScenes = thatInst.children; i = n; for (;i--; ) { mark = children[i]; mark.scene = childScenes[i]; mark.scale = k; } } } } function clear(scene) { if (scene) { var mark, that = scene.mark, children = that.children; if (children) for (var i = children.length; i--; ) { mark = children[i]; mark.scene = void 0; mark.scale = 1; } mark = that; var parent, count = 0; do { count++; delete mark.index; if (parent = mark.parent) { mark.scene = void 0; mark.scale = 1; } } while (mark = parent); count && (stack.length -= count); } } var proto = pv.Mark.prototype, stack = pv.Mark.stack, oscene = pv.Mark.scene, oindex = proto.index; if (scene && scene === oscene && index === oindex) try { f.apply(this, stack); } catch (ex) { pv.error(ex); throw ex; } finally { pv.Mark.scene = oscene; proto.index = oindex; } else { clear(oscene, oindex); apply(scene, index); try { f.apply(this, stack); } catch (ex) { pv.error(ex); throw ex; } finally { clear(scene, index); apply(oscene, oindex); } } }; pv.Mark.prototype.getEventHandler = function(type, scenes, index, ev) { var handler = this.$handlers[type]; return handler ? [ handler, scenes, index, ev ] : this.getParentEventHandler(type, scenes, index, ev); }; pv.Mark.prototype.getParentEventHandler = function(type, scenes, index, ev) { var parentScenes = scenes.parent; return parentScenes ? parentScenes.mark.getEventHandler(type, parentScenes, scenes.parentIndex, ev) : void 0; }; pv.Mark.dispatch = function(type, scenes, index, event) { var root = scenes.mark.root; if (root.$transition) return !0; var handlerInfo, interceptors = root.$interceptors && root.$interceptors[type]; if (interceptors) for (var i = 0, L = interceptors.length; L > i; i++) { handlerInfo = interceptors[i](type, event); if (handlerInfo) break; if (handlerInfo === !1) return !0; } if (!handlerInfo) { handlerInfo = scenes.mark.getEventHandler(type, scenes, index, event); if (!handlerInfo) return !1; } return this.handle.apply(this, handlerInfo); }; pv.Mark.handle = function(handler, scenes, index, event) { var m = scenes.mark; m.context(scenes, index, function() { var i, L, mi, stack = pv.Mark.stack.concat(event); if (handler instanceof Array) { var ms; for (i = 0, L = handler.length; L > i; i++) { mi = handler[i].apply(m, stack); mi && mi.render && (ms || (ms = [])).push(mi); } if (ms) for (i = 0, L = ms.length; L > i; i++) ms[i].render(); } else { mi = handler.apply(m, stack); mi && mi.render && mi.render(); } }); return !0; }; pv.Mark.prototype.addEventInterceptor = function(type, handler, before) { var root = this.root; if (root) { var ints = root.$interceptors || (root.$interceptors = {}), list = ints[type] || (ints[type] = []); before ? list.unshift(handler) : list.push(handler); } }; pv.Mark.prototype.eachInstance = function(fun, ctx) { function mapRecursive(scene, level, toScreen) { var D = scene.length; if (D > 0) { var childIndex, isLastLevel = level === L; isLastLevel || (childIndex = indexes[level]); for (var index = 0; D > index; index++) { var instance = scene[index]; if (instance.visible) if (level === L) fun.call(ctx, scene, index, toScreen); else { var childScene = instance.children[childIndex]; if (childScene) { var childToScreen = toScreen.times(instance.transform).translate(instance.left, instance.top); mapRecursive(childScene, level + 1, childToScreen); } } } } } for (var mark = this, indexes = []; mark.parent; ) { indexes.unshift(mark.childIndex); mark = mark.parent; } var rootScene = mark.scene; if (rootScene) { var L = indexes.length; mapRecursive(rootScene, 0, pv.Transform.identity); } }; pv.Mark.prototype.toScreenTransform = function() { var t = pv.Transform.identity; this instanceof pv.Panel && (t = t.translate(this.left(), this.top()).times(this.transform())); var parent = this.parent; if (parent) do t = t.translate(parent.left(), parent.top()).times(parent.transform()); while (parent = parent.parent); return t; }; pv.Mark.prototype.transition = function() { return new pv.Transition(this); }; pv.Mark.prototype.on = function(state) { return this["$" + state] = new pv.Transient(this); }; pv.Mark.prototype.getShape = function(scenes, index, inset) { var s = scenes[index]; if (!s.visible) return null; null == inset && (inset = 0); var key = "_shape_inset_" + inset; return s[key] || (s[key] = this.getShapeCore(scenes, index, inset)); }; pv.Mark.prototype.getShapeCore = function(scenes, index, inset) { var s = scenes[index], l = s.left, t = s.top, w = s.width, h = s.height; if (inset > 0 && 1 >= inset) { var dw = inset * w, dh = inset * h; l += dw; t += dh; w -= 2 * dw; h -= 2 * dh; } return new pv.Shape.Rect(l, t, w, h); }; pv.Mark.prototype.pointingRadiusMax = function(value) { if (arguments.length) { value = +value; this._pointingRadiusMax = isNaN(value) || 0 > value ? 0 : value; return this; } return this._pointingRadiusMax; }; pv.Mark.prototype._pointingRadiusMax = 1/0; pv.Anchor = function(target) { pv.Mark.call(this); this.target = target; this.parent = target.parent; }; pv.Anchor.prototype = pv.extend(pv.Mark).property("name", String); pv.Anchor.prototype.extend = function(proto) { this.proto = proto; return this; }; pv.Area = function() { pv.Mark.call(this); }; pv.Area.castSegmented = function(v) { if (!v) return ""; v = String(v).toLowerCase(); switch (v) { case "smart": case "full": break; default: v = "full"; } return v; }; pv.Area.prototype = pv.extend(pv.Mark).property("width", Number).property("height", Number).property("lineWidth", Number).property("lineJoin", pv.stringLowerCase).property("strokeMiterLimit", Number).property("lineCap", pv.stringLowerCase).property("strokeDasharray", pv.stringLowerCase).property("strokeStyle", pv.fillStyle).property("fillStyle", pv.fillStyle).property("segmented", pv.Area.castSegmented).property("interpolate", pv.stringLowerCase).property("tension", Number); pv.Area.prototype.type = "area"; pv.Area.prototype.defaults = new pv.Area().extend(pv.Mark.prototype.defaults).lineWidth(1.5).fillStyle(pv.Colors.category20().by(pv.parent)).interpolate("linear").tension(.7).lineJoin("miter").strokeMiterLimit(8).lineCap("butt").strokeDasharray("none"); pv.Area.prototype.buildImplied = function(s) { null == s.height && (s.height = 0); null == s.width && (s.width = 0); pv.Mark.prototype.buildImplied.call(this, s); }; pv.Area.fixed = { lineWidth: 1, lineJoin: 1, strokeMiterLimit: 1, lineCap: 1, strokeStyle: 1, strokeDasharray: 1, fillStyle: 1, segmented: 1, interpolate: 1, tension: 1 }; pv.Area.prototype.bind = function() { pv.Mark.prototype.bind.call(this); for (var binds = this.binds, required = binds.required, optional = binds.optional, i = 0, n = optional.length; n > i; i++) { var p = optional[i]; p.fixed = p.name in pv.Area.fixed; if ("segmented" == p.name) { required.push(p); optional.splice(i, 1); i--; n--; } } this.binds.$required = required; this.binds.$optional = optional; }; pv.Area.prototype.buildInstance = function(s) { function f(p) { return !p.fixed || (fixed.push(p), !1); } var binds = this.binds; if (this.index) { var fixed = binds.fixed; if (!fixed) { fixed = binds.fixed = []; binds.required = binds.required.filter(f); this.scene[0].segmented || (binds.optional = binds.optional.filter(f)); } var n = fixed.length; if (n) for (var firstScene = this.scene[0], i = 0; n > i; i++) { var p = fixed[i].name; s[p] = firstScene[p]; } } else { binds.required = binds.$required; binds.optional = binds.$optional; binds.fixed = null; } pv.Mark.prototype.buildInstance.call(this, s); }; pv.Area.prototype.anchor = function(name) { return pv.Mark.prototype.anchor.call(this, name).interpolate(function() { return this.scene.target[this.index].interpolate; }).eccentricity(function() { return this.scene.target[this.index].eccentricity; }).tension(function() { return this.scene.target[this.index].tension; }); }; pv.Area.prototype.getEventHandler = function(type, scene, index, ev) { var s = scene[index], needEventSimulation = 1 === pv.Scene.mousePositionEventSet[type] && (!s.segmented || "smart" === s.segmented); if (!needEventSimulation) return pv.Mark.prototype.getEventHandler.call(this, type, scene, index, ev); var mouseIndex, handlerMouseOver = "mousemove" === type ? this.$handlers.mouseover : null, handler = this.$handlers[type], handlers = handler || handlerMouseOver; if (handlers) { mouseIndex = this.getNearestInstanceToMouse(scene, index); if (handlerMouseOver && !this.filterMouseMove(scene, mouseIndex)) { handlerMouseOver = null; handlers = handler; } } if (!handlers) return this.getParentEventHandler(type, scene, index, ev); handler && handlerMouseOver && (handlers = [].concat(handler, handlerMouseOver)); return [ handlers, scene, mouseIndex, ev ]; }; pv.Area.prototype.filterMouseMove = function(scene, mouseIndex) { var prevMouseOverScene = this._mouseOverScene; if (!prevMouseOverScene || prevMouseOverScene !== scene || this._mouseOverIndex !== mouseIndex) { this._mouseOverScene = scene; this._mouseOverIndex = mouseIndex; return !0; } }; pv.Area.prototype.getNearestInstanceToMouse = function(scene, eventIndex) { for (var p = this.mouse(), minDist2 = 1/0, minIndex = null, index = eventIndex, L = scene.length; L > index; index++) { var shape = this.getShape(scene, index); if (shape) { if (shape.containsPoint(p)) return index; var dist2 = shape.distance2(p).dist2; if (minDist2 > dist2) { minDist2 = dist2; minIndex = index; } } } return null != minIndex ? minIndex : eventIndex; }; pv.Area.prototype.getShapeCore = function(scenes, index) { var s = scenes[index], w = s.width || 0, h = s.height || 0, x = s.left, y = s.top, s2 = index + 1 < scenes.length ? scenes[index + 1] : null; if (!s2 || !s2.visible) return new pv.Shape.Line(x, y, x + w, y + h); var x2 = s2.left, y2 = s2.top, h2 = s2.height || 0, w2 = s2.width || 0; return new pv.Shape.Polygon([ new pv.Vector(x, y), new pv.Vector(x2, y2), new pv.Vector(x2 + w2, y2 + h2), new pv.Vector(x + w, y + h) ]); }; pv.Bar = function() { pv.Mark.call(this); }; pv.Bar.prototype = pv.extend(pv.Mark).property("width", Number).property("height", Number).property("lineWidth", Number).property("strokeStyle", pv.fillStyle).property("fillStyle", pv.fillStyle).property("lineCap", pv.stringLowerCase).property("strokeDasharray", pv.stringLowerCase); pv.Bar.prototype.type = "bar"; pv.Bar.prototype.defaults = new pv.Bar().extend(pv.Mark.prototype.defaults).lineWidth(1.5).fillStyle(pv.Colors.category20().by(pv.parent)).lineCap("butt").strokeDasharray("none"); pv.Dot = function() { pv.Mark.call(this); }; pv.Dot.prototype = pv.extend(pv.Mark).property("shape", pv.stringLowerCase).property("shapeAngle", Number).property("shapeRadius", Number).property("shapeSize", Number).property("aspectRatio", Number).property("lineWidth", Number).property("strokeStyle", pv.fillStyle).property("lineCap", pv.stringLowerCase).property("strokeDasharray", pv.stringLowerCase).property("fillStyle", pv.fillStyle); pv.Dot.prototype.type = "dot"; pv.Dot.prototype.defaults = new pv.Dot().extend(pv.Mark.prototype.defaults).shape("circle").aspectRatio(1).lineWidth(1.5).strokeStyle(pv.Colors.category10().by(pv.parent)).lineCap("butt").strokeDasharray("none"); pv.Dot.prototype.anchor = function(name) { return pv.Mark.prototype.anchor.call(this, name).left(function() { var s = this.scene.target[this.index]; switch (this.name()) { case "bottom": case "top": case "center": return s.left; case "left": return null; } return s.left + s._width / 2; }).right(function() { var s = this.scene.target[this.index]; return "left" == this.name() ? s.right + s._width / 2 : null; }).top(function() { var s = this.scene.target[this.index]; switch (this.name()) { case "left": case "right": case "center": return s.top; case "top": return null; } return s.top + s._height / 2; }).bottom(function() { var s = this.scene.target[this.index]; return "top" == this.name() ? s.bottom + s._height / 2 : null; }).textAlign(function() { switch (this.name()) { case "left": return "right"; case "bottom": case "top": case "center": return "center"; } return "left"; }).textBaseline(function() { switch (this.name()) { case "right": case "left": case "center": return "middle"; case "bottom": return "top"; } return "bottom"; }); }; pv.Dot.prototype.buildImplied = function(s) { var r = s.shapeRadius, z = s.shapeSize, a = s.aspectRatio || 1; if (null == r) if (null == z) { z = s.shapeSize = 20.25; r = s.shapeRadius = 4.5; } else r = s.shapeRadius = Math.sqrt(z); else null == z && (z = s.shapeSize = r * r); var h, w; if (1 === a || 0 > a) h = w = 2 * r; else { h = 2 * r / Math.sqrt(a); w = a * h; } s._height = h; s._width = w; pv.Mark.prototype.buildImplied.call(this, s); }; pv.Dot.prototype.width = function() { return this.instance()._width; }; pv.Dot.prototype.height = function() { return this.instance()._height; }; pv.Dot.prototype.getShapeCore = function(scenes, index) { var s = scenes[index], h = s._width, w = s._height, cx = s.left, cy = s.top; switch (s.shape) { case "diamond": h *= Math.SQRT2; w *= Math.SQRT2; case "square": case "cross": return new pv.Shape.Rect(cx - w / 2, cy - h / 2, w, h); } return new pv.Shape.Circle(cx, cy, s.shapeRadius); }; pv.Label = function() { pv.Mark.call(this); }; pv.Label.prototype = pv.extend(pv.Mark).property("text", String).property("font", String).property("textAngle", Number).property("textStyle", pv.color).property("textAlign", pv.stringLowerCase).property("textBaseline", pv.stringLowerCase).property("textMargin", Number).property("textDecoration", String).property("textShadow", String); pv.Label.prototype.type = "label"; pv.Label.prototype.defaults = new pv.Label().extend(pv.Mark.prototype.defaults).events("none").text(pv.identity).font("10px sans-serif").textAngle(0).textStyle("black").textAlign("left").textBaseline("bottom").textMargin(3); pv.Label.prototype.getShapeCore = function(scenes, index, inset) { var s = scenes[index], size = pv.Text.measure(s.text, s.font), l = s.left, t = s.top, w = size.width, h = size.height; if (inset > 0 && 1 >= inset) { var dw = inset * w, dh = inset * h; l += dw; t += dh; w -= 2 * dw; h -= 2 * dh; } return pv.Label.getPolygon(w, h, s.textAlign, s.textBaseline, s.textAngle, s.textMargin).apply(pv.Transform.identity.translate(l, t)); }; pv.Label.getPolygon = function(textWidth, textHeight, align, baseline, angle, margin) { var x, y; switch (baseline) { case "middle": y = textHeight / 2; break; case "top": y = margin + textHeight; break; case "bottom": y = -margin; } switch (align) { case "right": x = -margin - textWidth; break; case "center": x = -textWidth / 2; break; case "left": x = margin; } var bl = new pv.Vector(x, y), br = bl.plus(textWidth, 0), tr = br.plus(0, -textHeight), tl = bl.plus(0, -textHeight); if (0 !== angle) { bl = bl.rotate(angle); br = br.rotate(angle); tl = tl.rotate(angle); tr = tr.rotate(angle); } return new pv.Shape.Polygon([ bl, br, tr, tl ]); }; pv.Line = function() { pv.Mark.call(this); }; pv.Line.prototype = pv.extend(pv.Mark).property("lineWidth", Number).property("lineJoin", pv.stringLowerCase).property("strokeMiterLimit", Number).property("lineCap", pv.stringLowerCase).property("strokeStyle", pv.fillStyle).property("strokeDasharray", pv.stringLowerCase).property("fillStyle", pv.fillStyle).property("segmented", pv.Area.castSegmented).property("interpolate", pv.stringLowerCase).property("eccentricity", Number).property("tension", Number); pv.Line.prototype.type = "line"; pv.Line.prototype.defaults = new pv.Line().extend(pv.Mark.prototype.defaults).lineWidth(1.5).strokeStyle(pv.Colors.category10().by(pv.parent)).interpolate("linear").eccentricity(0).tension(.7).lineJoin("miter").strokeMiterLimit(8).lineCap("butt").strokeDasharray("none"); pv.Line.prototype.bind = pv.Area.prototype.bind; pv.Line.prototype.buildInstance = pv.Area.prototype.buildInstance; pv.Line.prototype.getEventHandler = pv.Area.prototype.getEventHandler; pv.Line.prototype.getNearestInstanceToMouse = pv.Area.prototype.getNearestInstanceToMouse; pv.Line.prototype.filterMouseMove = pv.Area.prototype.filterMouseMove; pv.Line.prototype.anchor = function(name) { return pv.Area.prototype.anchor.call(this, name).textAlign(function() { switch (this.name()) { case "left": return "right"; case "bottom": case "top": case "center": return "center"; case "right": return "left"; } }).textBaseline(function() { switch (this.name()) { case "right": case "left": case "center": return "middle"; case "top": return "bottom"; case "bottom": return "top"; } }); }; pv.Line.prototype.getShapeCore = function(scenes, index) { var s = scenes[index], s2 = index + 1 < scenes.length ? scenes[index + 1] : null; return null != s2 && s2.visible ? new pv.Shape.Line(s.left, s.top, s2.left, s2.top) : new pv.Shape.Point(s.left, s.top); }; pv.Rule = function() { pv.Mark.call(this); }; pv.Rule.prototype = pv.extend(pv.Mark).property("width", Number).property("height", Number).property("lineWidth", Number).property("strokeStyle", pv.fillStyle).property("lineCap", pv.stringLowerCase).property("strokeDasharray", pv.stringLowerCase); pv.Rule.prototype.type = "rule"; pv.Rule.prototype.defaults = new pv.Rule().extend(pv.Mark.prototype.defaults).lineWidth(1).strokeStyle("black").antialias(!1).lineCap("butt").strokeDasharray("none"); pv.Rule.prototype.anchor = pv.Line.prototype.anchor; pv.Rule.prototype.buildImplied = function(s) { { var l = s.left, r = s.right; s.top, s.bottom; } null != s.width || null == l && null == r || null != r && null != l ? s.height = 0 : s.width = 0; pv.Mark.prototype.buildImplied.call(this, s); }; pv.Rule.prototype.getShapeCore = function(scenes, index) { var s = scenes[index]; return new pv.Shape.Line(s.left, s.top, s.left + s.width, s.top + s.height); }; pv.Panel = function() { pv.Bar.call(this); this.children = []; this.root = this; this.$dom = pv.$ && pv.$.s; }; pv.Panel.prototype = pv.extend(pv.Bar).property("transform").property("overflow", pv.stringLowerCase).property("canvas", function(c) { return "string" == typeof c ? document.getElementById(c) : c; }); pv.Panel.prototype.type = "panel"; pv.Panel.prototype._zOrderChildCount = 0; pv.Panel.prototype.defaults = new pv.Panel().extend(pv.Bar.prototype.defaults).fillStyle(null).overflow("visible"); pv.Panel.prototype.anchor = function(name) { var anchor = pv.Bar.prototype.anchor.call(this, name); anchor.parent = this; return anchor; }; pv.Panel.prototype.add = function(Type) { var child = new Type(); child.parent = this; child.root = this.root; child.childIndex = this.children.length; this.children.push(child); var zOrder = +child._zOrder || 0; 0 !== zOrder && this._zOrderChildCount++; return child; }; pv.Panel.prototype.bind = function() { pv.Mark.prototype.bind.call(this); for (var children = this.children, i = 0, n = children.length; n > i; i++) children[i].bind(); }; pv.Panel.prototype.buildInstance = function(s) { pv.Bar.prototype.buildInstance.call(this, s); if (s.visible) { var scale = this.scale * s.transform.k; pv.Mark.prototype.index = -1; for (var child, children = this.children, childScenes = s.children || (s.children = []), i = 0, n = children.length; n > i; i++) { child = children[i]; child.scene = childScenes[i]; child.scale = scale; child.build(); } i = n; for (;i--; ) { child = children[i]; childScenes[i] = child.scene; delete child.scene; delete child.scale; } childScenes.length = n; } }; pv.Panel.prototype.buildImplied = function(s) { if (this.parent || this._buildRootInstanceImplied(s)) { s.transform || (s.transform = pv.Transform.identity); pv.Mark.prototype.buildImplied.call(this, s); } else s.visible = !1; }; pv.Panel.prototype._buildRootInstanceImplied = function(s) { var c = s.canvas; if (c) { if (!this._rootInstanceStealCanvas(s, c)) return !1; this._rootInstanceInitCanvas(s, c); } else s.canvas = this._rootInstanceGetInlineCanvas(s); return !0; }; pv.Panel.prototype._rootInstanceStealCanvas = function(s, c) { var cPanel = c.$panel; if (cPanel !== this) { if (cPanel) { if (this.$lastCreateId) return !1; cPanel._disposeRootPanel(); this._updateCreateId(c); } c.$panel = this; pv.removeChildren(c); } else this._updateCreateId(c); return !0; }; pv.Panel.prototype._registerBoundEvent = function(source, name, listener, capturePhase) { if (source.removeEventListener) { var boundEvents = this._boundEvents || (this._boundEvents = []); boundEvents.push([ source, name, listener, capturePhase ]); } }; pv.Panel.prototype._disposeRootPanel = function() { var t = this.$transition; t && t.stop(); var boundEvents = this._boundEvents; if (boundEvents) { this._boundEvents = null; for (var i = 0, L = boundEvents.length; L > i; i++) { var be = boundEvents[i]; be[0].removeEventListener(be[1], be[2], be[3]); } } }; pv.Panel.prototype._rootInstanceInitCanvas = function(s, c) { var w, h, cssStyle; if (null == s.width) { cssStyle = pv.cssStyle(c); w = parseFloat(cssStyle("width") || 0); s.width = w - s.left - s.right; } if (null == s.height) { cssStyle || (cssStyle = pv.cssStyle(c)); h = parseFloat(cssStyle("height") || 0); s.height = h - s.top - s.bottom; } cssStyle = null; }; pv.Panel.prototype._rootInstanceGetInlineCanvas = function() { var c, cache = this.$canvas || (this.$canvas = []); if (!(c = cache[this.index])) { c = cache[this.index] = document.createElement("span"); if (this.$dom) this.$dom.parentNode.insertBefore(c, this.$dom); else { for (var n = document.body; n.lastChild && n.lastChild.tagName; ) n = n.lastChild; n != document.body && (n = n.parentNode); n.appendChild(c); } } return c; }; pv.Panel.prototype._updateCreateId = function(c) { this.$lastCreateId = c.$pvCreateId = (c.$pvCreateId || 0) + 1; }; pv.Image = function() { pv.Bar.call(this); }; pv.Image.prototype = pv.extend(pv.Bar).property("url", String).property("imageWidth", Number).property("imageHeight", Number); pv.Image.prototype.type = "image"; pv.Image.prototype.defaults = new pv.Image().extend(pv.Bar.prototype.defaults).fillStyle(null); pv.Image.prototype.image = function(f) { this.$image = function() { var c = f.apply(this, arguments); return null == c ? pv.Color.transparent : "string" == typeof c ? pv.color(c) : c; }; return this; }; pv.Image.prototype.bind = function() { pv.Bar.prototype.bind.call(this); var binds = this.binds, mark = this; do binds.image = mark.$image; while (!binds.image && (mark = mark.proto)); }; pv.Image.prototype.buildImplied = function(s) { pv.Bar.prototype.buildImplied.call(this, s); if (s.visible) { null == s.imageWidth && (s.imageWidth = s.width); null == s.imageHeight && (s.imageHeight = s.height); if (null == s.url && this.binds.image) { var data, canvas = this.$canvas || (this.$canvas = document.createElement("canvas")), context = canvas.getContext("2d"), w = s.imageWidth, h = s.imageHeight, stack = pv.Mark.stack; canvas.width = w; canvas.height = h; data = (s.image = context.createImageData(w, h)).data; stack.unshift(null, null); for (var y = 0, p = 0; h > y; y++) { stack[1] = y; for (var x = 0; w > x; x++) { stack[0] = x; var color = this.binds.image.apply(this, stack); data[p++] = color.r; data[p++] = color.g; data[p++] = color.b; data[p++] = 255 * color.a; } } stack.splice(0, 2); } } }; pv.Wedge = function() { pv.Mark.call(this); }; pv.Wedge.prototype = pv.extend(pv.Mark).property("startAngle", Number).property("endAngle", Number).property("angle", Number).property("innerRadius", Number).property("outerRadius", Number).property("lineWidth", Number).property("strokeStyle", pv.fillStyle).property("lineJoin", pv.stringLowerCase).property("strokeMiterLimit", Number).property("lineCap", pv.stringLowerCase).property("strokeDasharray", pv.stringLowerCase).property("fillStyle", pv.fillStyle); pv.Wedge.prototype.type = "wedge"; pv.Wedge.prototype.defaults = new pv.Wedge().extend(pv.Mark.prototype.defaults).startAngle(function() { var s = this.sibling(); return s ? s.endAngle : -Math.PI / 2; }).innerRadius(0).lineWidth(1.5).strokeStyle(null).fillStyle(pv.Colors.category20().by(pv.index)).lineJoin("miter").strokeMiterLimit(8).lineCap("butt").strokeDasharray("none"); pv.Wedge.prototype.midRadius = function() { return (this.innerRadius() + this.outerRadius()) / 2; }; pv.Wedge.prototype.midAngle = function() { return (this.startAngle() + this.endAngle()) / 2; }; pv.Wedge.prototype.anchor = function(name) { function partial(s) { return s.innerRadius || s.angle < 2 * Math.PI; } function midRadius(s) { return (s.innerRadius + s.outerRadius) / 2; } function midAngle(s) { return (s.startAngle + s.endAngle) / 2; } return pv.Mark.prototype.anchor.call(this, name).left(function() { var s = this.scene.target[this.index]; if (partial(s)) switch (this.name()) { case "outer": return s.left + s.outerRadius * Math.cos(midAngle(s)); case "inner": return s.left + s.innerRadius * Math.cos(midAngle(s)); case "start": return s.left + midRadius(s) * Math.cos(s.startAngle); case "center": return s.left + midRadius(s) * Math.cos(midAngle(s)); case "end": return s.left + midRadius(s) * Math.cos(s.endAngle); } return s.left; }).top(function() { var s = this.scene.target[this.index]; if (partial(s)) switch (this.name()) { case "outer": return s.top + s.outerRadius * Math.sin(midAngle(s)); case "inner": return s.top + s.innerRadius * Math.sin(midAngle(s)); case "start": return s.top + midRadius(s) * Math.sin(s.startAngle); case "center": return s.top + midRadius(s) * Math.sin(midAngle(s)); case "end": return s.top + midRadius(s) * Math.sin(s.endAngle); } return s.top; }).textAlign(function() { var s = this.scene.target[this.index]; if (partial(s)) switch (this.name()) { case "outer": return pv.Wedge.upright(midAngle(s)) ? "right" : "left"; case "inner": return pv.Wedge.upright(midAngle(s)) ? "left" : "right"; } return "center"; }).textBaseline(function() { var s = this.scene.target[this.index]; if (partial(s)) switch (this.name()) { case "start": return pv.Wedge.upright(s.startAngle) ? "top" : "bottom"; case "end": return pv.Wedge.upright(s.endAngle) ? "bottom" : "top"; } return "middle"; }).textAngle(function() { var s = this.scene.target[this.index], a = 0; if (partial(s)) switch (this.name()) { case "center": case "inner": case "outer": a = midAngle(s); break; case "start": a = s.startAngle; break; case "end": a = s.endAngle; } return pv.Wedge.upright(a) ? a : a + Math.PI; }); }; pv.Wedge.upright = function(angle) { angle %= 2 * Math.PI; angle = 0 > angle ? 2 * Math.PI + angle : angle; return angle < Math.PI / 2 || angle >= 3 * Math.PI / 2; }; pv.Wedge.prototype.buildImplied = function(s) { null == s.angle ? s.angle = s.endAngle - s.startAngle : null == s.endAngle && (s.endAngle = s.startAngle + s.angle); pv.Mark.prototype.buildImplied.call(this, s); }; pv.Wedge.prototype.getShapeCore = function(scenes, index) { var s = scenes[index]; return new pv.Shape.Wedge(s.left, s.top, s.innerRadius, s.outerRadius, s.startAngle, s.angle); }; pv.Ease = function() { function reverse(f) { return function(t) { return 1 - f(1 - t); }; } function reflect(f) { return function(t) { return .5 * (.5 > t ? f(2 * t) : 2 - f(2 - 2 * t)); }; } function poly(e) { return function(t) { return 0 > t ? 0 : t > 1 ? 1 : Math.pow(t, e); }; } function sin(t) { return 1 - Math.cos(t * Math.PI / 2); } function exp(t) { return t ? Math.pow(2, 10 * (t - 1)) - .001 : 0; } function circle(t) { return -(Math.sqrt(1 - t * t) - 1); } function elastic(a, p) { var s; p || (p = .45); if (!a || 1 > a) { a = 1; s = p / 4; } else s = p / (2 * Math.PI) * Math.asin(1 / a); return function(t) { return 0 >= t || t >= 1 ? t : -(a * Math.pow(2, 10 * --t) * Math.sin(2 * (t - s) * Math.PI / p)); }; } function back(s) { s || (s = 1.70158); return function(t) { return t * t * ((s + 1) * t - s); }; } function bounce(t) { return 1 / 2.75 > t ? 7.5625 * t * t : 2 / 2.75 > t ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : 2.5 / 2.75 > t ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375; } var quad = poly(2), cubic = poly(3), elasticDefault = elastic(), backDefault = back(), eases = { linear: pv.identity, "quad-in": quad, "quad-out": reverse(quad), "quad-in-out": reflect(quad), "quad-out-in": reflect(reverse(quad)), "cubic-in": cubic, "cubic-out": reverse(cubic), "cubic-in-out": reflect(cubic), "cubic-out-in": reflect(reverse(cubic)), "sin-in": sin, "sin-out": reverse(sin), "sin-in-out": reflect(sin), "sin-out-in": reflect(reverse(sin)), "exp-in": exp, "exp-out": reverse(exp), "exp-in-out": reflect(exp), "exp-out-in": reflect(reverse(exp)), "circle-in": circle, "circle-out": reverse(circle), "circle-in-out": reflect(circle), "circle-out-in": reflect(reverse(circle)), "elastic-in": elasticDefault, "elastic-out": reverse(elasticDefault), "elastic-in-out": reflect(elasticDefault), "elastic-out-in": reflect(reverse(elasticDefault)), "back-in": backDefault, "back-out": reverse(backDefault), "back-in-out": reflect(backDefault), "back-out-in": reflect(reverse(backDefault)), "bounce-in": bounce, "bounce-out": reverse(bounce), "bounce-in-out": reflect(bounce), "bounce-out-in": reflect(reverse(bounce)) }; pv.ease = function(f) { return eases[f]; }; return { reverse: reverse, reflect: reflect, linear: function() { return pv.identity; }, sin: function() { return sin; }, exp: function() { return exp; }, circle: function() { return circle; }, elastic: elastic, back: back, bounce: bounce, poly: poly }; }(); pv.Transient = function(mark) { pv.Mark.call(this); this.fillStyle(null).strokeStyle(null).textStyle(null); this.on = function(state) { return mark.on(state); }; }; pv.Transient.prototype = pv.extend(pv.Mark); !function() { function ids(scene) { for (var map = {}, i = scene.length; i--; ) { var s = scene[i], id = s.id; id && (map[id] = s); } return map; } function interpolateProperty(list, name, before, after) { var step; if (name in _interpolated) { var interp = pv.Scale.interpolator(before[name], after[name]); step = function(t) { before[name] = interp(t); }; } else step = function(t) { t > .5 && (before[name] = after[name]); }; step.next = list.head; list.head = step; } function interpolateInstance(list, beforeInst, afterInst) { for (var name in beforeInst) "children" !== name && beforeInst[name] != afterInst[name] && interpolateProperty(list, name, beforeInst, afterInst); var beforeChildScenes = beforeInst.children; if (beforeChildScenes) for (var afterChildScenes = afterInst.children, j = 0, L = beforeChildScenes.length; L > j; j++) interpolate(list, beforeChildScenes[j], afterChildScenes[j]); } function overrideInstance(scene, index, proto, other) { var t, otherInst = Object.create(scene[index]), m = scene.mark, rs = m.root.scene; if (other.target && (t = other.target[other.length])) { scene = Object.create(scene); scene.target = Object.create(other.target); scene.target[index] = t; } proto || (proto = _defaults); var ps = proto.$properties, overriden = proto.$propertiesMap; ps = m.binds.optional.filter(function(p) { return !(p.name in overriden); }).concat(ps); m.context(scene, index, function() { this.buildProperties(otherInst, ps); this.buildImplied(otherInst); }); m.root.scene = rs; return otherInst; } function interpolate(list, before, after) { for (var beforeInst, afterInst, mark = before.mark, beforeById = ids(before), afterById = ids(after), i = 0, L = before.length; L > i; i++) { beforeInst = before[i]; afterInst = beforeInst.id ? afterById[beforeInst.id] : after[i]; beforeInst.index = i; if (beforeInst.visible) { if (!afterInst || !afterInst.visible) { var overridenAfterInst = overrideInstance(before, i, mark.$exit, after); beforeInst.transition = afterInst ? 2 : (after.push(overridenAfterInst), 1); afterInst = overridenAfterInst; } interpolateInstance(list, beforeInst, afterInst); } } i = 0; L = after.length; for (;L > i; i++) { afterInst = after[i]; beforeInst = afterInst.id ? beforeById[afterInst.id] : before[i]; if ((!beforeInst || !beforeInst.visible) && afterInst.visible) { var overridenBeforeInst = overrideInstance(after, i, mark.$enter, before); beforeInst ? before[beforeInst.index] = overridenBeforeInst : before.push(overridenBeforeInst); interpolateInstance(list, overridenBeforeInst, afterInst); } } } function cleanup(scene) { for (var i = 0, j = 0; i < scene.length; i++) { var s = scene[i]; if (1 != s.transition) { scene[j++] = s; 2 == s.transition && (s.visible = !1); s.children && s.children.forEach(cleanup); } } scene.length = j; } var _interpolated = { top: 1, left: 1, right: 1, bottom: 1, width: 1, height: 1, innerRadius: 1, outerRadius: 1, radius: 1, shapeRadius: 1, shapeSize: 1, startAngle: 1, endAngle: 1, angle: 1, fillStyle: 1, strokeStyle: 1, lineWidth: 1, eccentricity: 1, tension: 1, textAngle: 1, textStyle: 1, textMargin: 1 }, _defaults = new pv.Transient(); pv.Transition = function(mark) { function doEnd(success) { var started = mark.root.$transition === that; started && (mark.root.$transition = null); if (null != timer) { clearInterval(timer); timer = null; } started && cleanupOnce(mark.scene); if (onEndCallback) { var cb = onEndCallback; onEndCallback = null; cb(success); } return success; } var timer, onEndCallback, cleanedup, that = this, ease = pv.ease("cubic-in-out"), duration = 250, cleanupOnce = function(scene) { if (!cleanedup) { cleanedup = !0; cleanup(scene); } }; that.ease = function(x) { return arguments.length ? (ease = "function" == typeof x ? x : pv.ease(x), that) : ease; }; that.duration = function(x) { return arguments.length ? (duration = Number(x), that) : duration; }; that.start = function(onEnd) { if (mark.parent) throw new Error("Animated partial rendering is not supported."); onEndCallback = onEnd; var root = mark.root; if (root.$transition) try { root.$transition.stop(); } catch (ex) { return doEnd(!1); } var list, start; root.$transition = that; root._renderId++; var before = mark.scene; mark.scene = null; var i0 = pv.Mark.prototype.index; try { mark.bind(); mark.build(); var after = mark.scene; mark.scene = before; pv.Mark.prototype.index = i0; start = Date.now(); list = {}; interpolate(list, before, after); } catch (ex) { pv.Mark.prototype.index = i0; return doEnd(!1); } if (!list.head) return doEnd(!0); var advance = function() { var t = Math.max(0, Math.min(1, (Date.now() - start) / duration)), te = ease(t), step = list.head; do step(te); while (step = step.next); if (1 === t) { cleanupOnce(mark.scene); pv.Scene.updateAll(before); doEnd(!0); } else pv.Scene.updateAll(before); }; timer = setInterval(function() { try { advance(); } catch (ex) { doEnd(!1); } }, 24); }; that.stop = function() { doEnd(!0); }; }; }(); pv.simulation = function(particles) { return new pv.Simulation(particles); }; pv.Simulation = function(particles) { for (var i = 0; i < particles.length; i++) this.particle(particles[i]); }; pv.Simulation.prototype.particle = function(p) { p.next = this.particles; isNaN(p.px) && (p.px = p.x); isNaN(p.py) && (p.py = p.y); isNaN(p.fx) && (p.fx = 0); isNaN(p.fy) && (p.fy = 0); this.particles = p; return this; }; pv.Simulation.prototype.force = function(f) { f.next = this.forces; this.forces = f; return this; }; pv.Simulation.prototype.constraint = function(c) { c.next = this.constraints; this.constraints = c; return this; }; pv.Simulation.prototype.stabilize = function(n) { var c; arguments.length || (n = 3); for (var i = 0; n > i; i++) { var q = new pv.Quadtree(this.particles); for (c = this.constraints; c; c = c.next) c.apply(this.particles, q); } for (var p = this.particles; p; p = p.next) { p.px = p.x; p.py = p.y; } return this; }; pv.Simulation.prototype.step = function() { var p, f, c; for (p = this.particles; p; p = p.next) { var px = p.px, py = p.py; p.px = p.x; p.py = p.y; p.x += p.vx = p.x - px + p.fx; p.y += p.vy = p.y - py + p.fy; } var q = new pv.Quadtree(this.particles); for (c = this.constraints; c; c = c.next) c.apply(this.particles, q); for (p = this.particles; p; p = p.next) p.fx = p.fy = 0; for (f = this.forces; f; f = f.next) f.apply(this.particles, q); }; pv.Quadtree = function(particles) { function insert(n, p, x1, y1, x2, y2) { if (!isNaN(p.x) && !isNaN(p.y)) if (n.leaf) if (n.p) if (Math.abs(n.p.x - p.x) + Math.abs(n.p.y - p.y) < .01) insertChild(n, p, x1, y1, x2, y2); else { var v = n.p; n.p = null; insertChild(n, v, x1, y1, x2, y2); insertChild(n, p, x1, y1, x2, y2); } else n.p = p; else insertChild(n, p, x1, y1, x2, y2); } function insertChild(n, p, x1, y1, x2, y2) { var sx = .5 * (x1 + x2), sy = .5 * (y1 + y2), right = p.x >= sx, bottom = p.y >= sy; n.leaf = !1; switch ((bottom << 1) + right) { case 0: n = n.c1 || (n.c1 = new pv.Quadtree.Node()); break; case 1: n = n.c2 || (n.c2 = new pv.Quadtree.Node()); break; case 2: n = n.c3 || (n.c3 = new pv.Quadtree.Node()); break; case 3: n = n.c4 || (n.c4 = new pv.Quadtree.Node()); } right ? x1 = sx : x2 = sx; bottom ? y1 = sy : y2 = sy; insert(n, p, x1, y1, x2, y2); } var p, x1 = Number.POSITIVE_INFINITY, y1 = x1, x2 = Number.NEGATIVE_INFINITY, y2 = x2; for (p = particles; p; p = p.next) { p.x < x1 && (x1 = p.x); p.y < y1 && (y1 = p.y); p.x > x2 && (x2 = p.x); p.y > y2 && (y2 = p.y); } var dx = x2 - x1, dy = y2 - y1; dx > dy ? y2 = y1 + dx : x2 = x1 + dy; this.xMin = x1; this.yMin = y1; this.xMax = x2; this.yMax = y2; this.root = new pv.Quadtree.Node(); for (p = particles; p; p = p.next) insert(this.root, p, x1, y1, x2, y2); }; pv.Quadtree.Node = function() { this.leaf = !0; this.c1 = null; this.c2 = null; this.c3 = null; this.c4 = null; this.p = null; }; pv.Force = {}; pv.Force.charge = function(k) { function accumulate(n) { function accumulateChild(c) { accumulate(c); n.cn += c.cn; cx += c.cn * c.cx; cy += c.cn * c.cy; } var cx = 0, cy = 0; n.cn = 0; if (!n.leaf) { n.c1 && accumulateChild(n.c1); n.c2 && accumulateChild(n.c2); n.c3 && accumulateChild(n.c3); n.c4 && accumulateChild(n.c4); } if (n.p) { n.cn += k; cx += k * n.p.x; cy += k * n.p.y; } n.cx = cx / n.cn; n.cy = cy / n.cn; } function forces(n, p, x1, y1, x2, y2) { var dx = n.cx - p.x, dy = n.cy - p.y, dn = 1 / Math.sqrt(dx * dx + dy * dy); if (n.leaf && n.p != p || theta > (x2 - x1) * dn) { if (max1 > dn) return; dn > min1 && (dn = min1); var kc = n.cn * dn * dn * dn, fx = dx * kc, fy = dy * kc; p.fx += fx; p.fy += fy; } else if (!n.leaf) { var sx = .5 * (x1 + x2), sy = .5 * (y1 + y2); n.c1 && forces(n.c1, p, x1, y1, sx, sy); n.c2 && forces(n.c2, p, sx, y1, x2, sy); n.c3 && forces(n.c3, p, x1, sy, sx, y2); n.c4 && forces(n.c4, p, sx, sy, x2, y2); if (max1 > dn) return; dn > min1 && (dn = min1); if (n.p && n.p != p) { var kc = k * dn * dn * dn, fx = dx * kc, fy = dy * kc; p.fx += fx; p.fy += fy; } } } var min = 2, min1 = 1 / min, max = 500, max1 = 1 / max, theta = .9, force = {}; arguments.length || (k = -40); force.constant = function(x) { if (arguments.length) { k = Number(x); return force; } return k; }; force.domain = function(a, b) { if (arguments.length) { min = Number(a); min1 = 1 / min; max = Number(b); max1 = 1 / max; return force; } return [ min, max ]; }; force.theta = function(x) { if (arguments.length) { theta = Number(x); return force; } return theta; }; force.apply = function(particles, q) { accumulate(q.root); for (var p = particles; p; p = p.next) forces(q.root, p, q.xMin, q.yMin, q.xMax, q.yMax); }; return force; }; pv.Force.drag = function(k) { var force = {}; arguments.length || (k = .1); force.constant = function(x) { if (arguments.length) { k = x; return force; } return k; }; force.apply = function(particles) { if (k) for (var p = particles; p; p = p.next) { p.fx -= k * p.vx; p.fy -= k * p.vy; } }; return force; }; pv.Force.spring = function(k) { var links, kl, d = .1, l = 20, force = {}; arguments.length || (k = .1); force.links = function(x) { if (arguments.length) { links = x; kl = x.map(function(l) { return 1 / Math.sqrt(Math.max(l.sourceNode.linkDegree, l.targetNode.linkDegree)); }); return force; } return links; }; force.constant = function(x) { if (arguments.length) { k = Number(x); return force; } return k; }; force.damping = function(x) { if (arguments.length) { d = Number(x); return force; } return d; }; force.length = function(x) { if (arguments.length) { l = Number(x); return force; } return l; }; force.apply = function() { for (var i = 0; i < links.length; i++) { var a = links[i].sourceNode, b = links[i].targetNode, dx = a.x - b.x, dy = a.y - b.y, dn = Math.sqrt(dx * dx + dy * dy), dd = dn ? 1 / dn : 1, ks = k * kl[i], kd = d * kl[i], kk = (ks * (dn - l) + kd * (dx * (a.vx - b.vx) + dy * (a.vy - b.vy)) * dd) * dd, fx = -kk * (dn ? dx : .01 * (.5 - Math.random())), fy = -kk * (dn ? dy : .01 * (.5 - Math.random())); a.fx += fx; a.fy += fy; b.fx -= fx; b.fy -= fy; } }; return force; }; pv.Constraint = {}; pv.Constraint.collision = function(radius) { function constrain(n, p, x1, y1, x2, y2) { if (!n.leaf) { var sx = .5 * (x1 + x2), sy = .5 * (y1 + y2), top = sy > py1, bottom = py2 > sy, left = sx > px1, right = px2 > sx; if (top) { n.c1 && left && constrain(n.c1, p, x1, y1, sx, sy); n.c2 && right && constrain(n.c2, p, sx, y1, x2, sy); } if (bottom) { n.c3 && left && constrain(n.c3, p, x1, sy, sx, y2); n.c4 && right && constrain(n.c4, p, sx, sy, x2, y2); } } if (n.p && n.p != p) { var dx = p.x - n.p.x, dy = p.y - n.p.y, l = Math.sqrt(dx * dx + dy * dy), d = r1 + radius(n.p); if (d > l) { var k = (l - d) / l * .5; dx *= k; dy *= k; p.x -= dx; p.y -= dy; n.p.x += dx; n.p.y += dy; } } } var r1, px1, py1, px2, py2, n = 1, constraint = {}; arguments.length || (r1 = 10); constraint.repeat = function(x) { if (arguments.length) { n = Number(x); return constraint; } return n; }; constraint.apply = function(particles, q) { var p, r, max = -1/0; for (p = particles; p; p = p.next) { r = radius(p); r > max && (max = r); } for (var i = 0; n > i; i++) for (p = particles; p; p = p.next) { r = (r1 = radius(p)) + max; px1 = p.x - r; px2 = p.x + r; py1 = p.y - r; py2 = p.y + r; constrain(q.root, p, q.xMin, q.yMin, q.xMax, q.yMax); } }; return constraint; }; pv.Constraint.position = function(f) { var a = 1, constraint = {}; arguments.length || (f = function(p) { return p.fix; }); constraint.alpha = function(x) { if (arguments.length) { a = Number(x); return constraint; } return a; }; constraint.apply = function(particles) { for (var p = particles; p; p = p.next) { var v = f(p); if (v) { p.x += (v.x - p.x) * a; p.y += (v.y - p.y) * a; p.fx = p.fy = p.vx = p.vy = 0; } } }; return constraint; }; pv.Constraint.bound = function() { var x, y, constraint = {}; constraint.x = function(min, max) { if (arguments.length) { x = { min: Math.min(min, max), max: Math.max(min, max) }; return this; } return x; }; constraint.y = function(min, max) { if (arguments.length) { y = { min: Math.min(min, max), max: Math.max(min, max) }; return this; } return y; }; constraint.apply = function(particles) { if (x) for (var p = particles; p; p = p.next) p.x = p.x < x.min ? x.min : p.x > x.max ? x.max : p.x; if (y) for (var p = particles; p; p = p.next) p.y = p.y < y.min ? y.min : p.y > y.max ? y.max : p.y; }; return constraint; }; pv.Layout = function() { pv.Panel.call(this); }; pv.Layout.prototype = pv.extend(pv.Panel); pv.Layout.prototype.property = pv.Mark.prototype.localProperty; pv.Layout.Network = function() { pv.Layout.call(this); var that = this; this.$id = pv.id(); (this.node = new pv.Mark().data(function() { return that.nodes(); }).strokeStyle("#1f77b4").fillStyle("#fff").left(function(n) { return n.x; }).top(function(n) { return n.y; })).parent = this; this.link = new pv.Mark().extend(this.node).data(function(p) { return [ p.sourceNode, p.targetNode ]; }).fillStyle(null).lineWidth(function(d, p) { return 1.5 * p.linkValue; }).strokeStyle("rgba(0,0,0,.2)"); this.link.add = function(type) { return that.add(pv.Panel).data(function() { return that.links(); }).add(type).extend(this); }; (this.label = new pv.Mark().extend(this.node).textMargin(7).textBaseline("middle").text(function(n) { return n.nodeName || n.nodeValue; }).textAngle(function(n) { var a = n.midAngle; return pv.Wedge.upright(a) ? a : a + Math.PI; }).textAlign(function(n) { return pv.Wedge.upright(n.midAngle) ? "left" : "right"; })).parent = this; }; pv.Layout.Network.prototype = pv.extend(pv.Layout).property("nodes", function(v) { return v.map(function(d, i) { "object" != typeof d && (d = { nodeValue: d }); d.index = i; return d; }); }).property("links", function(v) { return v.map(function(d) { isNaN(d.linkValue) && (d.linkValue = isNaN(d.value) ? 1 : d.value); return d; }); }); pv.Layout.Network.prototype.reset = function() { this.$id = pv.id(); return this; }; pv.Layout.Network.prototype.buildProperties = function(s, properties) { (s.$id || 0) < this.$id && pv.Layout.prototype.buildProperties.call(this, s, properties); }; pv.Layout.Network.prototype.buildImplied = function(s) { pv.Layout.prototype.buildImplied.call(this, s); if (s.$id >= this.$id) return !0; s.$id = this.$id; s.nodes.forEach(function(d) { d.linkDegree = 0; }); s.links.forEach(function(d) { var v = d.linkValue; (d.sourceNode || (d.sourceNode = s.nodes[d.source])).linkDegree += v; (d.targetNode || (d.targetNode = s.nodes[d.target])).linkDegree += v; }); }; pv.Layout.Hierarchy = function() { pv.Layout.Network.call(this); this.link.strokeStyle("#ccc"); }; pv.Layout.Hierarchy.prototype = pv.extend(pv.Layout.Network); pv.Layout.Hierarchy.prototype.buildImplied = function(s) { s.links || (s.links = pv.Layout.Hierarchy.links.call(this)); pv.Layout.Network.prototype.buildImplied.call(this, s); }; pv.Layout.Hierarchy.links = function() { return this.nodes().filter(function(n) { return n.parentNode; }).map(function(n) { return { sourceNode: n, targetNode: n.parentNode, linkValue: 1 }; }); }; pv.Layout.Hierarchy.NodeLink = { buildImplied: function(s) { function radius(n) { return n.parentNode ? n.depth * (or - ir) + ir : 0; } function midAngle(n) { return n.parentNode ? 2 * (n.breadth - .25) * Math.PI : 0; } function x(n) { switch (orient) { case "left": return n.depth * w; case "right": return w - n.depth * w; case "top": return n.breadth * w; case "bottom": return w - n.breadth * w; case "radial": return w / 2 + radius(n) * Math.cos(n.midAngle); } } function y(n) { switch (orient) { case "left": return n.breadth * h; case "right": return h - n.breadth * h; case "top": return n.depth * h; case "bottom": return h - n.depth * h; case "radial": return h / 2 + radius(n) * Math.sin(n.midAngle); } } var nodes = s.nodes, orient = s.orient, horizontal = /^(top|bottom)$/.test(orient), w = s.width, h = s.height; if ("radial" == orient) { var ir = s.innerRadius, or = s.outerRadius; null == ir && (ir = 0); null == or && (or = Math.min(w, h) / 2); } for (var i = 0; i < nodes.length; i++) { var n = nodes[i]; n.midAngle = "radial" == orient ? midAngle(n) : horizontal ? Math.PI / 2 : 0; n.x = x(n); n.y = y(n); n.firstChild && (n.midAngle += Math.PI); } } }; pv.Layout.Hierarchy.Fill = { constructor: function() { this.node.strokeStyle("#fff").fillStyle("#ccc").width(function(n) { return n.dx; }).height(function(n) { return n.dy; }).innerRadius(function(n) { return n.innerRadius; }).outerRadius(function(n) { return n.outerRadius; }).startAngle(function(n) { return n.startAngle; }).angle(function(n) { return n.angle; }); this.label.textAlign("center").left(function(n) { return n.x + n.dx / 2; }).top(function(n) { return n.y + n.dy / 2; }); delete this.link; }, buildImplied: function(s) { function scale(d, depth) { return (d + depth) / (1 + depth); } function x(n) { switch (orient) { case "left": return scale(n.minDepth, depth) * w; case "right": return (1 - scale(n.maxDepth, depth)) * w; case "top": return n.minBreadth * w; case "bottom": return (1 - n.maxBreadth) * w; case "radial": return w / 2; } } function y(n) { switch (orient) { case "left": return n.minBreadth * h; case "right": return (1 - n.maxBreadth) * h; case "top": return scale(n.minDepth, depth) * h; case "bottom": return (1 - scale(n.maxDepth, depth)) * h; case "radial": return h / 2; } } function dx(n) { switch (orient) { case "left": case "right": return (n.maxDepth - n.minDepth) / (1 + depth) * w; case "top": case "bottom": return (n.maxBreadth - n.minBreadth) * w; case "radial": return n.parentNode ? (n.innerRadius + n.outerRadius) * Math.cos(n.midAngle) : 0; } } function dy(n) { switch (orient) { case "left": case "right": return (n.maxBreadth - n.minBreadth) * h; case "top": case "bottom": return (n.maxDepth - n.minDepth) / (1 + depth) * h; case "radial": return n.parentNode ? (n.innerRadius + n.outerRadius) * Math.sin(n.midAngle) : 0; } } function innerRadius(n) { return Math.max(0, scale(n.minDepth, depth / 2)) * (or - ir) + ir; } function outerRadius(n) { return scale(n.maxDepth, depth / 2) * (or - ir) + ir; } function startAngle(n) { return 2 * (n.parentNode ? n.minBreadth - .25 : 0) * Math.PI; } function angle(n) { return 2 * (n.parentNode ? n.maxBreadth - n.minBreadth : 1) * Math.PI; } var nodes = s.nodes, orient = s.orient, horizontal = /^(top|bottom)$/.test(orient), w = s.width, h = s.height, depth = -nodes[0].minDepth; if ("radial" == orient) { var ir = s.innerRadius, or = s.outerRadius; null == ir && (ir = 0); ir && (depth *= 2); null == or && (or = Math.min(w, h) / 2); } for (var i = 0; i < nodes.length; i++) { var n = nodes[i]; n.x = x(n); n.y = y(n); if ("radial" == orient) { n.innerRadius = innerRadius(n); n.outerRadius = outerRadius(n); n.startAngle = startAngle(n); n.angle = angle(n); n.midAngle = n.startAngle + n.angle / 2; } else n.midAngle = horizontal ? -Math.PI / 2 : 0; n.dx = dx(n); n.dy = dy(n); } } }; pv.Layout.Grid = function() { pv.Layout.call(this); var that = this; (this.cell = new pv.Mark().data(function() { return that.scene[that.index].$grid; }).width(function() { return that.width() / that.cols(); }).height(function() { return that.height() / that.rows(); }).left(function() { return this.width() * (this.index % that.cols()); }).top(function() { return this.height() * Math.floor(this.index / that.cols()); })).parent = this; }; pv.Layout.Grid.prototype = pv.extend(pv.Layout).property("rows").property("cols"); pv.Layout.Grid.prototype.defaults = new pv.Layout.Grid().extend(pv.Layout.prototype.defaults).rows(1).cols(1); pv.Layout.Grid.prototype.buildImplied = function(s) { pv.Layout.prototype.buildImplied.call(this, s); var r = s.rows, c = s.cols; "object" == typeof c && (r = pv.transpose(c)); if ("object" == typeof r) { s.$grid = pv.blend(r); s.rows = r.length; s.cols = r[0] ? r[0].length : 0; } else s.$grid = pv.repeat([ s.data ], r * c); }; pv.Layout.Stack = function() { function proxy(name) { return function() { return prop[name](this.parent.index, this.index); }; } pv.Layout.call(this); var values, that = this, none = function() { return null; }, prop = { t: none, l: none, r: none, b: none, w: none, h: none }, buildImplied = that.buildImplied; this.buildImplied = function(s) { buildImplied.call(this, s); var m, data = s.layers, n = data.length, orient = s.orient, horizontal = /^(top|bottom)\b/.test(orient), h = this.parent[horizontal ? "height" : "width"](), x = [], y = [], dy = [], stack = pv.Mark.stack, o = { parent: { parent: this } }; stack.unshift(null); values = []; for (var i = 0; n > i; i++) { dy[i] = []; y[i] = []; o.parent.index = i; stack[0] = data[i]; values[i] = this.$values.apply(o.parent, stack); i || (m = values[i].length); stack.unshift(null); for (var j = 0; m > j; j++) { stack[0] = values[i][j]; o.index = j; i || (x[j] = this.$x.apply(o, stack)); dy[i][j] = this.$y.apply(o, stack); } stack.shift(); } stack.shift(); var index; switch (s.order) { case "inside-out": for (var max = dy.map(function(v) { return pv.max.index(v); }), map = pv.range(n).sort(function(a, b) { return max[a] - max[b]; }), sums = dy.map(function(v) { return pv.sum(v); }), top = 0, bottom = 0, tops = [], bottoms = [], i = 0; n > i; i++) { var j = map[i]; if (bottom > top) { top += sums[j]; tops.push(j); } else { bottom += sums[j]; bottoms.push(j); } } index = bottoms.reverse().concat(tops); break; case "reverse": index = pv.range(n - 1, -1, -1); break; default: index = pv.range(n); } switch (s.offset) { case "silohouette": for (var j = 0; m > j; j++) { for (var o = 0, i = 0; n > i; i++) o += dy[i][j]; y[index[0]][j] = (h - o) / 2; } break; case "wiggle": for (var o = 0, i = 0; n > i; i++) o += dy[i][0]; y[index[0]][0] = o = (h - o) / 2; for (var j = 1; m > j; j++) { for (var s1 = 0, s2 = 0, dx = x[j] - x[j - 1], i = 0; n > i; i++) s1 += dy[i][j]; for (var i = 0; n > i; i++) { for (var s3 = (dy[index[i]][j] - dy[index[i]][j - 1]) / (2 * dx), k = 0; i > k; k++) s3 += (dy[index[k]][j] - dy[index[k]][j - 1]) / dx; s2 += s3 * dy[index[i]][j]; } y[index[0]][j] = o -= s1 ? s2 / s1 * dx : 0; } break; case "expand": for (var j = 0; m > j; j++) { y[index[0]][j] = 0; for (var k = 0, i = 0; n > i; i++) k += dy[i][j]; if (k) { k = h / k; for (var i = 0; n > i; i++) dy[i][j] *= k; } else { k = h / n; for (var i = 0; n > i; i++) dy[i][j] = k; } } break; default: for (var j = 0; m > j; j++) y[index[0]][j] = 0; } for (var j = 0; m > j; j++) for (var o = y[index[0]][j], i = 1; n > i; i++) { o += dy[index[i - 1]][j]; y[index[i]][j] = o; } var i = orient.indexOf("-"), pdy = horizontal ? "h" : "w", px = 0 > i ? horizontal ? "l" : "b" : orient.charAt(i + 1), py = orient.charAt(0); for (var p in prop) prop[p] = none; prop[px] = function(i, j) { return x[j]; }; prop[py] = function(i, j) { return y[i][j]; }; prop[pdy] = function(i, j) { return dy[i][j]; }; }; this.layer = new pv.Mark().data(function() { return values[this.parent.index]; }).top(proxy("t")).left(proxy("l")).right(proxy("r")).bottom(proxy("b")).width(proxy("w")).height(proxy("h")); this.layer.add = function(type) { return that.add(pv.Panel).data(function() { return that.layers(); }).add(type).extend(this); }; }; pv.Layout.Stack.prototype = pv.extend(pv.Layout).property("orient", String).property("offset", String).property("order", String).property("layers"); pv.Layout.Stack.prototype.defaults = new pv.Layout.Stack().extend(pv.Layout.prototype.defaults).orient("bottom-left").offset("zero").layers([ [] ]); pv.Layout.Stack.prototype.$x = pv.Layout.Stack.prototype.$y = function() { return 0; }; pv.Layout.Stack.prototype.x = function(f) { this.$x = pv.functor(f); return this; }; pv.Layout.Stack.prototype.y = function(f) { this.$y = pv.functor(f); return this; }; pv.Layout.Stack.prototype.$values = pv.identity; pv.Layout.Stack.prototype.values = function(f) { this.$values = pv.functor(f); return this; }; pv.Layout.Band = function() { function proxy(name) { return function() { return itemProps[name](this.index, this.parent.index); }; } pv.Layout.call(this); var itemProps, values, that = this, buildImplied = that.buildImplied, itemProto = new pv.Mark().data(function() { return values[this.parent.index]; }).top(proxy("t")).left(proxy("l")).right(proxy("r")).bottom(proxy("b")).width(proxy("w")).height(proxy("h")).antialias(proxy("antialias")); this.buildImplied = function(s) { buildImplied.call(this, s); itemProps = Object.create(pv.Layout.Band.$baseItemProps); values = []; var data = s.layers, L = data.length; if (L > 0) { var orient = s.orient, horizontal = /^(top|bottom)\b/.test(orient), bh = this.parent[horizontal ? "height" : "width"](), bands = this._readData(data, values, s), B = bands.length; "reverse" === s.bandOrder && bands.reverse(); if ("reverse" === s.order) { values.reverse(); for (var b = 0; B > b; b++) bands[b].items.reverse(); } switch (s.layout) { case "grouped": this._calcGrouped(bands, L, s); break; case "stacked": this._calcStacked(bands, L, bh, s); } for (var hZero = s.hZero || 0, isStacked = "stacked" === s.layout, i = 0; B > i; i++) for (var band = bands[i], hMargin2 = isStacked ? Math.max(0, band.vertiMargin) / 2 : 0, j = 0; L > j; j++) { var item = band.items[j]; if (item.zero) { item.h = hZero; item.y -= hMargin2 + hZero / 2; } } this._bindItemProps(bands, itemProps, orient, horizontal); } }; var itemAccessor = this.item = { end: this, add: function(type) { return that.add(pv.Panel).data(function() { return that.layers(); }).add(type).extend(itemProto); }, order: function(value) { that.order(value); return this; }, w: function(f) { that.$iw = pv.functor(f); return this; }, h: function(f) { that.$ih = pv.functor(f); return this; }, horizontalRatio: function(f) { that.$ihorizRatio = pv.functor(f); return this; }, verticalMargin: function(f) { that.$ivertiMargin = pv.functor(f); return this; } }, bandAccessor = this.band = { end: this, w: function(f) { that.$bw = pv.functor(f); return this; }, x: function(f) { that.$bx = pv.functor(f); return this; }, order: function(value) { that.bandOrder(value); return this; }, differentialControl: function(f) { that.$bDiffControl = pv.functor(f); return this; } }; this.band.item = itemAccessor; this.item.band = bandAccessor; }; pv.Layout.Band.$baseItemProps = function() { var none = function() { return null; }; return { t: none, l: none, r: none, b: none, w: none, h: none }; }(); pv.Layout.Band.prototype = pv.extend(pv.Layout).property("orient", String).property("layout", String).property("layers").property("yZero", Number).property("hZero", Number).property("verticalMode", String).property("horizontalMode", String).property("order", String).property("bandOrder", String); pv.Layout.Band.prototype.defaults = new pv.Layout.Band().extend(pv.Layout.prototype.defaults).orient("bottom-left").layout("grouped").yZero(0).hZero(1.5).layers([ [] ]); pv.Layout.Band.prototype.$bx = pv.Layout.Band.prototype.$bw = pv.Layout.Band.prototype.$bDiffControl = pv.Layout.Band.prototype.$iw = pv.Layout.Band.prototype.$ih = pv.Layout.Band.prototype.$ivertiMargin = pv.functor(0); pv.Layout.Band.prototype.$ihorizRatio = pv.functor(.9); pv.Layout.Band.prototype.$values = pv.identity; pv.Layout.Band.prototype.values = function(f) { this.$values = pv.functor(f); return this; }; pv.Layout.prototype._readData = function(data, layersValues, scene) { var B, L = data.length, bands = [], stack = pv.Mark.stack, hZero = scene.hZero, o = { parent: { parent: this } }; stack.unshift(null); for (var l = 0; L > l; l++) { o.parent.index = l; stack[0] = data[l]; var layerValues = layersValues[l] = this.$values.apply(o.parent, stack); l || (B = layerValues.length); stack.unshift(null); for (var b = 0; B > b; b++) { stack[0] = layerValues[b]; o.index = b; var band = bands[b]; band || (band = bands[b] = { horizRatio: this.$ihorizRatio.apply(o, stack), vertiMargin: this.$ivertiMargin.apply(o, stack), w: this.$bw.apply(o, stack), x: this.$bx.apply(o, stack), diffControl: this.$bDiffControl ? this.$bDiffControl.apply(o, stack) : 0, items: [] }); var ih = this.$ih.apply(o, stack), h = null != ih ? Math.abs(ih) : ih; band.items[l] = { y: scene.yZero || 0, x: 0, w: this.$iw.apply(o, stack), h: h, zero: null != h && hZero >= h, dir: 0 > ih ? -1 : 1 }; } stack.shift(); } stack.shift(); return bands; }; pv.Layout.Band.prototype._calcGrouped = function(bands, L, scene) { for (var b = 0, B = bands.length; B > b; b++) { for (var band = bands[b], items = band.items, w = band.w, horizRatio = band.horizRatio, wItems = 0, l = 0; L > l; l++) wItems += items[l].w; 1 === L ? horizRatio = 1 : horizRatio > 0 && 1 >= horizRatio || (horizRatio = 1); if (null == w) w = band.w = wItems / horizRatio; else if ("expand" === scene.horizontalMode) { var wItems2 = horizRatio * w; if (wItems) for (var wScale = wItems2 / wItems, l = 0; L > l; l++) items[l].w *= wScale; else for (var wiavg = wItems2 / L, l = 0; L > l; l++) items[l].w = wiavg; wItems = wItems2; } for (var wItemsWithMargin = wItems / horizRatio, ix = band.x - wItemsWithMargin / 2, margin = L > 1 ? (wItemsWithMargin - wItems) / (L - 1) : 0, l = 0; L > l; l++) { var item = items[l]; item.x = ix; ix += item.w + margin; item.dir < 0 && (item.y -= item.h); } } }; pv.Layout.Band.prototype._calcStacked = function(bands, L, bh, scene) { var items, B = bands.length; if ("expand" === scene.verticalMode) for (var b = 0; B > b; b++) { items = bands[b].items; for (var hSum = null, nonNullCount = 0, l = 0; L > l; l++) { var item = items[l]; item.dir = 1; var h = item.h; if (null != h) { nonNullCount++; hSum += h; } } if (nonNullCount) if (hSum) for (var hScale = bh / hSum, l = 0; L > l; l++) { var h = items[l].h; null != h && (items[l].h = h * hScale); } else if (0 == hSum) for (var l = 0; L > l; l++) items[l].h = 0; else for (var hAvg = bh / nonNullCount, l = 0; L > l; l++) { var h = items[l].h; null != h && (items[l].h = hAvg); } } for (var yZero = scene.yZero, yOffset = yZero, b = 0; B > b; b++) { var band = bands[b], bx = band.x, bDiffControl = band.diffControl, positiveGoesDown = 0 > bDiffControl, vertiMargin = Math.max(0, band.vertiMargin); items = band.items; var resultPos = this._layoutItemsOfDir(1, positiveGoesDown, items, vertiMargin, bx, yOffset), resultNeg = null; resultPos.existsOtherDir && (resultNeg = this._layoutItemsOfDir(-1, positiveGoesDown, items, vertiMargin, bx, yOffset)); if (bDiffControl) { if (1 === Math.abs(bDiffControl)) { var yOffset0 = yOffset; yOffset = resultPos.yOffset; resultNeg && (yOffset -= yOffset0 - resultNeg.yOffset); } } else yOffset = yZero; } }; pv.Layout.Band.prototype._layoutItemsOfDir = function(stackDir, positiveGoesDown, items, vertiMargin, bx, yOffset) { for (var existsOtherDir = !1, vertiMargin2 = vertiMargin / 2, efDir = positiveGoesDown ? -stackDir : stackDir, reverseLayers = positiveGoesDown, l = 0, L = items.length; L > l; l += 1) { var item = items[reverseLayers ? L - l - 1 : l]; if (item.dir === stackDir) { var h = item.h || 0; if (efDir > 0) { item.y = yOffset + vertiMargin2; yOffset += h; } else { item.y = yOffset - (h - vertiMargin2); yOffset -= h; } var h2 = h - vertiMargin; item.h = h2 > 0 ? h2 : 0; item.x = bx - item.w / 2; } else existsOtherDir = !0; } return { existsOtherDir: existsOtherDir, yOffset: yOffset }; }; pv.Layout.Band.prototype._bindItemProps = function(bands, itemProps, orient, horizontal) { var index = orient.indexOf("-"), ph = horizontal ? "h" : "w", pw = horizontal ? "w" : "h", px = 0 > index ? horizontal ? "l" : "b" : orient.charAt(index + 1), py = orient.charAt(0); itemProps[px] = function(b, l) { return bands[b].items[l].x; }; itemProps[py] = function(b, l) { return bands[b].items[l].y; }; itemProps[pw] = function(b, l) { return bands[b].items[l].w; }; itemProps[ph] = function(b, l) { return bands[b].items[l].h || 0; }; itemProps.antialias = function(b, l) { return bands[b].items[l].zero; }; }; pv.Layout.Treemap = function() { pv.Layout.Hierarchy.call(this); this.node.strokeStyle("#fff").fillStyle("rgba(31, 119, 180, .25)").width(function(n) { return n.dx; }).height(function(n) { return n.dy; }); this.label.visible(function(n) { return !n.firstChild; }).left(function(n) { return n.x + n.dx / 2; }).top(function(n) { return n.y + n.dy / 2; }).textAlign("center").textAngle(function(n) { return n.dx > n.dy ? 0 : -Math.PI / 2; }); (this.leaf = new pv.Mark().extend(this.node).fillStyle(null).strokeStyle(null).visible(function(n) { return !n.firstChild; })).parent = this; delete this.link; }; pv.Layout.Treemap.prototype = pv.extend(pv.Layout.Hierarchy).property("round", Boolean).property("mode", String).property("order", String); pv.Layout.Treemap.prototype.defaults = new pv.Layout.Treemap().extend(pv.Layout.Hierarchy.prototype.defaults).mode("squarify").order("ascending"); pv.Layout.Treemap.prototype.$size = function(d) { return Number(d.nodeValue); }; pv.Layout.Treemap.prototype.$padLeft = pv.Layout.Treemap.prototype.$padRight = pv.Layout.Treemap.prototype.$padBottom = pv.Layout.Treemap.prototype.$padTop = function() { return 0; }; pv.Layout.Treemap.prototype.size = function(f) { this.$size = pv.functor(f); return this; }; pv.Layout.Treemap.prototype.padding = function(n) { n = pv.functor(n); return this.paddingLeft(n).paddingRight(n).paddingTop(n).paddingBottom(n); }; pv.Layout.Treemap.prototype.paddingLeft = function(f) { if (arguments.length) { this.$padLeft = pv.functor(f); return this; } return this.$padLeft; }; pv.Layout.Treemap.prototype.paddingRight = function(f) { if (arguments.length) { this.$padRight = pv.functor(f); return this; } return this.$padRight; }; pv.Layout.Treemap.prototype.paddingBottom = function(f) { if (arguments.length) { this.$padBottom = pv.functor(f); return this; } return this.$padBottom; }; pv.Layout.Treemap.prototype.paddingTop = function(f) { if (arguments.length) { this.$padTop = pv.functor(f); return this; } return this.$padTop; }; pv.Layout.Treemap.prototype.buildImplied = function(s) { function slice(row, sum, horizontal, x, y, w, h) { for (var i = 0, d = 0; i < row.length; i++) { var n = row[i]; if (horizontal) { n.x = x + d; n.y = y; d += n.dx = round(w * n.size / sum); n.dy = h; } else { n.x = x; n.y = y + d; n.dx = w; d += n.dy = round(h * n.size / sum); } } n && (horizontal ? n.dx += w - d : n.dy += h - d); } function ratio(row, l) { for (var rmax = -1/0, rmin = 1/0, s = 0, i = 0; i < row.length; i++) { var r = row[i].size; rmin > r && (rmin = r); r > rmax && (rmax = r); s += r; } s *= s; l *= l; return Math.max(l * rmax / s, s / (l * rmin)); } function layout(n, i) { function position(row) { var horizontal = w == l, sum = pv.sum(row, size), r = l ? round(sum / l) : 0; slice(row, sum, horizontal, x, y, horizontal ? w : r, horizontal ? r : h); if (horizontal) { y += r; h -= r; } else { x += r; w -= r; } l = Math.min(w, h); return horizontal; } var p = n.parentNode, x = n.x, y = n.y, w = n.dx, h = n.dy; if (p) { x += p.paddingLeft; y += p.paddingTop; w += -p.paddingLeft - p.paddingRight, h += -p.paddingTop - p.paddingBottom; } if ("squarify" == mode) { var row = [], mink = 1/0, l = Math.min(w, h), k = w * h / n.size; if (!(n.size <= 0)) { n.visitBefore(function(n) { n.size *= k; }); for (var children = n.childNodes.slice(); children.length; ) { var child = children[children.length - 1]; if (child.size) { row.push(child); var k = ratio(row, l); if (mink >= k) { children.pop(); mink = k; } else { row.pop(); position(row); row.length = 0; mink = 1/0; } } else children.pop(); } if (position(row)) for (var i = 0; i < row.length; i++) row[i].dy += h; else for (var i = 0; i < row.length; i++) row[i].dx += w; } } else slice(n.childNodes, n.size, "slice" == mode ? !0 : "dice" == mode ? !1 : 1 & i, x, y, w, h); } if (!pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) { var that = this, nodes = s.nodes, root = nodes[0], stack = pv.Mark.stack, size = function(n) { return n.size; }, round = s.round ? Math.round : Number, mode = s.mode; stack.unshift(null); try { root.visitAfter(function(n, i) { n.depth = i; n.x = n.y = n.dx = n.dy = 0; stack[0] = n; if (n.firstChild) { n.size = pv.sum(n.childNodes, size); n.paddingRight = +that.$padRight.apply(that, stack) || 0; n.paddingLeft = +that.$padLeft.apply(that, stack) || 0; n.paddingBottom = +that.$padBottom.apply(that, stack) || 0; n.paddingTop = +that.$padTop.apply(that, stack) || 0; } else n.size = that.$size.apply(that, stack); }); } finally { stack.shift(); } switch (s.order) { case "ascending": root.sort(function(a, b) { return a.size - b.size; }); break; case "descending": root.sort(function(a, b) { return b.size - a.size; }); break; case "reverse": root.reverse(); } root.x = 0; root.y = 0; root.dx = s.width; root.dy = s.height; root.visitBefore(layout); } }; pv.Layout.Tree = function() { pv.Layout.Hierarchy.call(this); }; pv.Layout.Tree.prototype = pv.extend(pv.Layout.Hierarchy).property("group", Number).property("breadth", Number).property("depth", Number).property("orient", String); pv.Layout.Tree.prototype.defaults = new pv.Layout.Tree().extend(pv.Layout.Hierarchy.prototype.defaults).group(1).breadth(15).depth(60).orient("top"); pv.Layout.Tree.prototype.buildImplied = function(s) { function firstWalk(v) { var l, r, a; if (v.firstChild) { l = v.firstChild; r = v.lastChild; a = l; for (var c = l; c; c = c.nextSibling) { firstWalk(c); a = apportion(c, a); } executeShifts(v); var midpoint = .5 * (l.prelim + r.prelim); if (l = v.previousSibling) { v.prelim = l.prelim + distance(v.depth, !0); v.mod = v.prelim - midpoint; } else v.prelim = midpoint; } else (l = v.previousSibling) && (v.prelim = l.prelim + distance(v.depth, !0)); } function secondWalk(v, m, depth) { v.breadth = v.prelim + m; m += v.mod; for (var c = v.firstChild; c; c = c.nextSibling) secondWalk(c, m, depth); } function apportion(v, a) { var w = v.previousSibling; if (w) { for (var vip = v, vop = v, vim = w, vom = v.parentNode.firstChild, sip = vip.mod, sop = vop.mod, sim = vim.mod, som = vom.mod, nr = nextRight(vim), nl = nextLeft(vip); nr && nl; ) { vim = nr; vip = nl; vom = nextLeft(vom); vop = nextRight(vop); vop.ancestor = v; var shift = vim.prelim + sim - (vip.prelim + sip) + distance(vim.depth, !1); if (shift > 0) { moveSubtree(ancestor(vim, v, a), v, shift); sip += shift; sop += shift; } sim += vim.mod; sip += vip.mod; som += vom.mod; sop += vop.mod; nr = nextRight(vim); nl = nextLeft(vip); } if (nr && !nextRight(vop)) { vop.thread = nr; vop.mod += sim - sop; } if (nl && !nextLeft(vom)) { vom.thread = nl; vom.mod += sip - som; a = v; } } return a; } function nextLeft(v) { return v.firstChild || v.thread; } function nextRight(v) { return v.lastChild || v.thread; } function moveSubtree(wm, wp, shift) { var subtrees = wp.number - wm.number; wp.change -= shift / subtrees; wp.shift += shift; wm.change += shift / subtrees; wp.prelim += shift; wp.mod += shift; } function executeShifts(v) { for (var shift = 0, change = 0, c = v.lastChild; c; c = c.previousSibling) { c.prelim += shift; c.mod += shift; change += c.change; shift += c.shift + change; } } function ancestor(vim, v, a) { return vim.ancestor.parentNode == v.parentNode ? vim.ancestor : a; } function distance(depth, siblings) { return (siblings ? 1 : group + 1) / ("radial" == orient ? depth : 1); } function midAngle(n) { return "radial" == orient ? n.breadth / depth : 0; } function x(n) { switch (orient) { case "left": return n.depth; case "right": return w - n.depth; case "top": case "bottom": return n.breadth + w / 2; case "radial": return w / 2 + n.depth * Math.cos(midAngle(n)); } } function y(n) { switch (orient) { case "left": case "right": return n.breadth + h / 2; case "top": return n.depth; case "bottom": return h - n.depth; case "radial": return h / 2 + n.depth * Math.sin(midAngle(n)); } } if (!pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) { var nodes = s.nodes, orient = s.orient, depth = s.depth, breadth = s.breadth, group = s.group, w = s.width, h = s.height, root = nodes[0]; root.visitAfter(function(v, i) { v.ancestor = v; v.prelim = 0; v.mod = 0; v.change = 0; v.shift = 0; v.number = v.previousSibling ? v.previousSibling.number + 1 : 0; v.depth = i; }); firstWalk(root); secondWalk(root, -root.prelim, 0); root.visitAfter(function(v) { v.breadth *= breadth; v.depth *= depth; v.midAngle = midAngle(v); v.x = x(v); v.y = y(v); v.firstChild && (v.midAngle += Math.PI); delete v.breadth; delete v.depth; delete v.ancestor; delete v.prelim; delete v.mod; delete v.change; delete v.shift; delete v.number; delete v.thread; }); } }; pv.Layout.Indent = function() { pv.Layout.Hierarchy.call(this); this.link.interpolate("step-after"); }; pv.Layout.Indent.prototype = pv.extend(pv.Layout.Hierarchy).property("depth", Number).property("breadth", Number); pv.Layout.Indent.prototype.defaults = new pv.Layout.Indent().extend(pv.Layout.Hierarchy.prototype.defaults).depth(15).breadth(15); pv.Layout.Indent.prototype.buildImplied = function(s) { function position(n, breadth, depth) { n.x = ax + depth++ * dspace; n.y = ay + breadth++ * bspace; n.midAngle = 0; for (var c = n.firstChild; c; c = c.nextSibling) breadth = position(c, breadth, depth); return breadth; } if (!pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) { var nodes = s.nodes, bspace = s.breadth, dspace = s.depth, ax = 0, ay = 0; position(nodes[0], 1, 1); } }; pv.Layout.Pack = function() { pv.Layout.Hierarchy.call(this); this.node.shapeRadius(function(n) { return n.radius; }).strokeStyle("rgb(31, 119, 180)").fillStyle("rgba(31, 119, 180, .25)"); this.label.textAlign("center"); delete this.link; }; pv.Layout.Pack.prototype = pv.extend(pv.Layout.Hierarchy).property("spacing", Number).property("order", String); pv.Layout.Pack.prototype.defaults = new pv.Layout.Pack().extend(pv.Layout.Hierarchy.prototype.defaults).spacing(1).order("ascending"); pv.Layout.Pack.prototype.$radius = function() { return 1; }; pv.Layout.Pack.prototype.size = function(f) { this.$radius = "function" == typeof f ? function() { return Math.sqrt(f.apply(this, arguments)); } : (f = Math.sqrt(f), function() { return f; }); return this; }; pv.Layout.Pack.prototype.buildImplied = function(s) { function radii(nodes) { var stack = pv.Mark.stack; stack.unshift(null); for (var i = 0, n = nodes.length; n > i; i++) { var c = nodes[i]; c.firstChild || (c.radius = that.$radius.apply(that, (stack[0] = c, stack))); } stack.shift(); } function packTree(n) { for (var nodes = [], c = n.firstChild; c; c = c.nextSibling) { c.firstChild && (c.radius = packTree(c)); c.n = c.p = c; nodes.push(c); } switch (s.order) { case "ascending": nodes.sort(function(a, b) { return a.radius - b.radius; }); break; case "descending": nodes.sort(function(a, b) { return b.radius - a.radius; }); break; case "reverse": nodes.reverse(); } return packCircle(nodes); } function packCircle(nodes) { function bound(n) { xMin = Math.min(n.x - n.radius, xMin); xMax = Math.max(n.x + n.radius, xMax); yMin = Math.min(n.y - n.radius, yMin); yMax = Math.max(n.y + n.radius, yMax); } function insert(a, b) { var c = a.n; a.n = b; b.p = a; b.n = c; c.p = b; } function splice(a, b) { a.n = b; b.p = a; } function intersects(a, b) { var dx = b.x - a.x, dy = b.y - a.y, dr = a.radius + b.radius; return dr * dr - dx * dx - dy * dy > .001; } var a, b, c, j, k, xMin = 1/0, xMax = -1/0, yMin = 1/0, yMax = -1/0; a = nodes[0]; a.x = -a.radius; a.y = 0; bound(a); if (nodes.length > 1) { b = nodes[1]; b.x = b.radius; b.y = 0; bound(b); if (nodes.length > 2) { c = nodes[2]; place(a, b, c); bound(c); insert(a, c); a.p = c; insert(c, b); b = a.n; for (var i = 3; i < nodes.length; i++) { place(a, b, c = nodes[i]); var isect = 0, s1 = 1, s2 = 1; for (j = b.n; j != b; j = j.n, s1++) if (intersects(j, c)) { isect = 1; break; } if (1 == isect) for (k = a.p; k != j.p; k = k.p, s2++) if (intersects(k, c)) { if (s1 > s2) { isect = -1; j = k; } break; } if (0 == isect) { insert(a, c); b = c; bound(c); } else if (isect > 0) { splice(a, j); b = j; i--; } else if (0 > isect) { splice(j, b); a = j; i--; } } } } for (var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0, i = 0; i < nodes.length; i++) { var n = nodes[i]; n.x -= cx; n.y -= cy; cr = Math.max(cr, n.radius + Math.sqrt(n.x * n.x + n.y * n.y)); } return cr + s.spacing; } function place(a, b, c) { var da = b.radius + c.radius, db = a.radius + c.radius, dx = b.x - a.x, dy = b.y - a.y, dc = Math.sqrt(dx * dx + dy * dy), cos = (db * db + dc * dc - da * da) / (2 * db * dc), theta = Math.acos(cos), x = cos * db, h = Math.sin(theta) * db; dx /= dc; dy /= dc; c.x = a.x + x * dx + h * dy; c.y = a.y + x * dy - h * dx; } function transform(n, x, y, k) { for (var c = n.firstChild; c; c = c.nextSibling) { c.x += n.x; c.y += n.y; transform(c, x, y, k); } n.x = x + k * n.x; n.y = y + k * n.y; n.radius *= k; } if (!pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) { var that = this, nodes = s.nodes, root = nodes[0]; radii(nodes); root.x = 0; root.y = 0; root.radius = packTree(root); var w = this.width(), h = this.height(), k = 1 / Math.max(2 * root.radius / w, 2 * root.radius / h); transform(root, w / 2, h / 2, k); } }; pv.Layout.Force = function() { pv.Layout.Network.call(this); this.link.lineWidth(function(d, p) { return 1.5 * Math.sqrt(p.linkValue); }); this.label.textAlign("center"); }; pv.Layout.Force.prototype = pv.extend(pv.Layout.Network).property("bound", Boolean).property("iterations", Number).property("dragConstant", Number).property("chargeConstant", Number).property("chargeMinDistance", Number).property("chargeMaxDistance", Number).property("chargeTheta", Number).property("springConstant", Number).property("springDamping", Number).property("springLength", Number); pv.Layout.Force.prototype.defaults = new pv.Layout.Force().extend(pv.Layout.Network.prototype.defaults).dragConstant(.1).chargeConstant(-40).chargeMinDistance(2).chargeMaxDistance(500).chargeTheta(.9).springConstant(.1).springDamping(.3).springLength(20); pv.Layout.Force.prototype.buildImplied = function(s) { function speed(n) { return n.fix ? 1 : n.vx * n.vx + n.vy * n.vy; } if (pv.Layout.Network.prototype.buildImplied.call(this, s)) { var f = s.$force; if (f) { f.next = this.binds.$force; this.binds.$force = f; } } else { for (var n, that = this, nodes = s.nodes, links = s.links, k = s.iterations, w = s.width, h = s.height, i = 0; i < nodes.length; i++) { n = nodes[i]; isNaN(n.x) && (n.x = w / 2 + 40 * Math.random() - 20); isNaN(n.y) && (n.y = h / 2 + 40 * Math.random() - 20); } var sim = pv.simulation(nodes); sim.force(pv.Force.drag(s.dragConstant)); sim.force(pv.Force.charge(s.chargeConstant).domain(s.chargeMinDistance, s.chargeMaxDistance).theta(s.chargeTheta)); sim.force(pv.Force.spring(s.springConstant).damping(s.springDamping).length(s.springLength).links(links)); sim.constraint(pv.Constraint.position()); s.bound && sim.constraint(pv.Constraint.bound().x(6, w - 6).y(6, h - 6)); if (null == k) { sim.step(); sim.step(); { s.$force = this.binds.$force = { next: this.binds.$force, nodes: nodes, min: 1e-4 * (links.length + 1), sim: sim }; } this.$timer || (this.$timer = setInterval(function() { for (var render = !1, f = that.binds.$force; f; f = f.next) if (pv.max(f.nodes, speed) > f.min) { f.sim.step(); render = !0; } render && that.render(); }, 42)); } else for (var i = 0; k > i; i++) sim.step(); } }; pv.Layout.Cluster = function() { pv.Layout.Hierarchy.call(this); var interpolate, buildImplied = this.buildImplied; this.buildImplied = function(s) { buildImplied.call(this, s); interpolate = /^(top|bottom)$/.test(s.orient) ? "step-before" : /^(left|right)$/.test(s.orient) ? "step-after" : "linear"; }; this.link.interpolate(function() { return interpolate; }); }; pv.Layout.Cluster.prototype = pv.extend(pv.Layout.Hierarchy).property("group", Number).property("orient", String).property("innerRadius", Number).property("outerRadius", Number); pv.Layout.Cluster.prototype.defaults = new pv.Layout.Cluster().extend(pv.Layout.Hierarchy.prototype.defaults).group(0).orient("top"); pv.Layout.Cluster.prototype.buildImplied = function(s) { if (!pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) { var breadth, depth, root = s.nodes[0], group = s.group, leafCount = 0, leafIndex = .5 - group / 2, p = void 0; root.visitAfter(function(n) { if (n.firstChild) n.depth = 1 + pv.max(n.childNodes, function(n) { return n.depth; }); else { if (group && p != n.parentNode) { p = n.parentNode; leafCount += group; } leafCount++; n.depth = 0; } }); breadth = 1 / leafCount; depth = 1 / root.depth; var p = void 0; root.visitAfter(function(n) { if (n.firstChild) n.breadth = pv.mean(n.childNodes, function(n) { return n.breadth; }); else { if (group && p != n.parentNode) { p = n.parentNode; leafIndex += group; } n.breadth = breadth * leafIndex++; } n.depth = 1 - n.depth * depth; }); root.visitAfter(function(n) { n.minBreadth = n.firstChild ? n.firstChild.minBreadth : n.breadth - breadth / 2; n.maxBreadth = n.firstChild ? n.lastChild.maxBreadth : n.breadth + breadth / 2; }); root.visitBefore(function(n) { n.minDepth = n.parentNode ? n.parentNode.maxDepth : 0; n.maxDepth = n.parentNode ? n.depth + root.depth : n.minDepth + 2 * root.depth; }); root.minDepth = -depth; pv.Layout.Hierarchy.NodeLink.buildImplied.call(this, s); } }; pv.Layout.Cluster.Fill = function() { pv.Layout.Cluster.call(this); pv.Layout.Hierarchy.Fill.constructor.call(this); }; pv.Layout.Cluster.Fill.prototype = pv.extend(pv.Layout.Cluster); pv.Layout.Cluster.Fill.prototype.buildImplied = function(s) { pv.Layout.Cluster.prototype.buildImplied.call(this, s) || pv.Layout.Hierarchy.Fill.buildImplied.call(this, s); }; pv.Layout.Partition = function() { pv.Layout.Hierarchy.call(this); }; pv.Layout.Partition.prototype = pv.extend(pv.Layout.Hierarchy).property("order", String).property("orient", String).property("innerRadius", Number).property("outerRadius", Number); pv.Layout.Partition.prototype.defaults = new pv.Layout.Partition().extend(pv.Layout.Hierarchy.prototype.defaults).orient("top"); pv.Layout.Partition.prototype.$size = function() { return 1; }; pv.Layout.Partition.prototype.size = function(f) { this.$size = f; return this; }; pv.Layout.Partition.prototype.buildImplied = function(s) { if (!pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) { var that = this, root = s.nodes[0], stack = pv.Mark.stack, maxDepth = 0; stack.unshift(null); root.visitAfter(function(n, depth) { depth > maxDepth && (maxDepth = depth); n.size = n.firstChild ? pv.sum(n.childNodes, function(n) { return n.size; }) : that.$size.apply(that, (stack[0] = n, stack)); }); stack.shift(); switch (s.order) { case "ascending": root.sort(function(a, b) { return a.size - b.size; }); break; case "descending": root.sort(function(b, a) { return a.size - b.size; }); } root.minBreadth = 0; root.breadth = .5; root.maxBreadth = 1; root.visitBefore(function(n) { for (var b = n.minBreadth, s = n.maxBreadth - b, c = n.firstChild; c; c = c.nextSibling) { c.minBreadth = b; b += c.size / n.size * s; c.maxBreadth = b; c.breadth = (b + c.minBreadth) / 2; } }); root.visitAfter(function(n, depth) { n.minDepth = (depth - 1) / maxDepth; n.maxDepth = n.depth = depth / maxDepth; }); pv.Layout.Hierarchy.NodeLink.buildImplied.call(this, s); } }; pv.Layout.Partition.Fill = function() { pv.Layout.Partition.call(this); pv.Layout.Hierarchy.Fill.constructor.call(this); }; pv.Layout.Partition.Fill.prototype = pv.extend(pv.Layout.Partition); pv.Layout.Partition.Fill.prototype.buildImplied = function(s) { pv.Layout.Partition.prototype.buildImplied.call(this, s) || pv.Layout.Hierarchy.Fill.buildImplied.call(this, s); }; pv.Layout.Arc = function() { pv.Layout.Network.call(this); var interpolate, directed, reverse, buildImplied = this.buildImplied; this.buildImplied = function(s) { buildImplied.call(this, s); directed = s.directed; interpolate = "radial" == s.orient ? "linear" : "polar"; reverse = "right" == s.orient || "top" == s.orient; }; this.link.data(function(p) { var s = p.sourceNode, t = p.targetNode; return reverse != (directed || s.breadth < t.breadth) ? [ s, t ] : [ t, s ]; }).interpolate(function() { return interpolate; }); }; pv.Layout.Arc.prototype = pv.extend(pv.Layout.Network).property("orient", String).property("directed", Boolean); pv.Layout.Arc.prototype.defaults = new pv.Layout.Arc().extend(pv.Layout.Network.prototype.defaults).orient("bottom"); pv.Layout.Arc.prototype.sort = function(f) { this.$sort = f; return this; }; pv.Layout.Arc.prototype.buildImplied = function(s) { function midAngle(b) { switch (orient) { case "top": return -Math.PI / 2; case "bottom": return Math.PI / 2; case "left": return Math.PI; case "right": return 0; case "radial": return 2 * (b - .25) * Math.PI; } } function x(b) { switch (orient) { case "top": case "bottom": return b * w; case "left": return 0; case "right": return w; case "radial": return w / 2 + r * Math.cos(midAngle(b)); } } function y(b) { switch (orient) { case "top": return 0; case "bottom": return h; case "left": case "right": return b * h; case "radial": return h / 2 + r * Math.sin(midAngle(b)); } } if (!pv.Layout.Network.prototype.buildImplied.call(this, s)) { var nodes = s.nodes, orient = s.orient, sort = this.$sort, index = pv.range(nodes.length), w = s.width, h = s.height, r = Math.min(w, h) / 2; sort && index.sort(function(a, b) { return sort(nodes[a], nodes[b]); }); for (var i = 0; i < nodes.length; i++) { var n = nodes[index[i]], b = n.breadth = (i + .5) / nodes.length; n.x = x(b); n.y = y(b); n.midAngle = midAngle(b); } } }; pv.Layout.Horizon = function() { pv.Layout.call(this); var bands, mode, size, fill, red, blue, that = this, buildImplied = this.buildImplied; this.buildImplied = function(s) { buildImplied.call(this, s); bands = s.bands; mode = s.mode; size = Math.round(("color" == mode ? .5 : 1) * s.height); fill = s.backgroundStyle; red = pv.ramp(fill, s.negativeStyle).domain(0, bands); blue = pv.ramp(fill, s.positiveStyle).domain(0, bands); }; var bands = new pv.Panel().data(function() { return pv.range(2 * bands); }).overflow("hidden").height(function() { return size; }).top(function(i) { return "color" == mode ? (1 & i) * size : 0; }).fillStyle(function(i) { return i ? null : fill; }); this.band = new pv.Mark().top(function(d, i) { return "mirror" == mode && 1 & i ? (i + 1 >> 1) * size : null; }).bottom(function(d, i) { return "mirror" == mode ? 1 & i ? null : (i + 1 >> 1) * -size : (1 & i || -1) * (i + 1 >> 1) * size; }).fillStyle(function(d, i) { return (1 & i ? red : blue)((i >> 1) + 1); }); this.band.add = function(type) { return that.add(pv.Panel).extend(bands).add(type).extend(this); }; }; pv.Layout.Horizon.prototype = pv.extend(pv.Layout).property("bands", Number).property("mode", String).property("backgroundStyle", pv.fillStyle).property("positiveStyle", pv.fillStyle).property("negativeStyle", pv.fillStyle); pv.Layout.Horizon.prototype.defaults = new pv.Layout.Horizon().extend(pv.Layout.prototype.defaults).bands(2).mode("offset").backgroundStyle("white").positiveStyle("#1f77b4").negativeStyle("#d62728"); pv.Layout.Rollup = function() { pv.Layout.Network.call(this); var nodes, links, that = this, buildImplied = that.buildImplied; this.buildImplied = function(s) { buildImplied.call(this, s); nodes = s.$rollup.nodes; links = s.$rollup.links; }; this.node.data(function() { return nodes; }).shapeSize(function(d) { return 20 * d.nodes.length; }); this.link.interpolate("polar").eccentricity(.8); this.link.add = function(type) { return that.add(pv.Panel).data(function() { return links; }).add(type).extend(this); }; }; pv.Layout.Rollup.prototype = pv.extend(pv.Layout.Network).property("directed", Boolean); pv.Layout.Rollup.prototype.x = function(f) { this.$x = pv.functor(f); return this; }; pv.Layout.Rollup.prototype.y = function(f) { this.$y = pv.functor(f); return this; }; pv.Layout.Rollup.prototype.buildImplied = function(s) { function id(i) { return x[i] + "," + y[i]; } if (!pv.Layout.Network.prototype.buildImplied.call(this, s)) { var nodes = s.nodes, links = s.links, directed = s.directed, n = nodes.length, x = [], y = [], rnindex = 0, rnodes = {}, rlinks = {}, stack = pv.Mark.stack, o = { parent: this }; stack.unshift(null); for (var i = 0; n > i; i++) { o.index = i; stack[0] = nodes[i]; x[i] = this.$x.apply(o, stack); y[i] = this.$y.apply(o, stack); } stack.shift(); for (var i = 0; i < nodes.length; i++) { var nodeId = id(i), rn = rnodes[nodeId]; if (!rn) { rn = rnodes[nodeId] = Object.create(nodes[i]); rn.index = rnindex++; rn.x = x[i]; rn.y = y[i]; rn.nodes = []; } rn.nodes.push(nodes[i]); } for (var i = 0; i < links.length; i++) { var source = links[i].sourceNode, target = links[i].targetNode, rsource = rnodes[id(source.index)], rtarget = rnodes[id(target.index)], reverse = !directed && rsource.index > rtarget.index, linkId = reverse ? rtarget.index + "," + rsource.index : rsource.index + "," + rtarget.index, rl = rlinks[linkId]; rl || (rl = rlinks[linkId] = { sourceNode: rsource, targetNode: rtarget, linkValue: 0, links: [] }); rl.links.push(links[i]); rl.linkValue += links[i].linkValue; } s.$rollup = { nodes: pv.values(rnodes), links: pv.values(rlinks) }; } }; pv.Layout.Matrix = function() { pv.Layout.Network.call(this); var n, dx, dy, labels, pairs, that = this, buildImplied = that.buildImplied; this.buildImplied = function(s) { buildImplied.call(this, s); n = s.nodes.length; dx = s.width / n; dy = s.height / n; labels = s.$matrix.labels; pairs = s.$matrix.pairs; }; this.link.data(function() { return pairs; }).left(function() { return dx * (this.index % n); }).top(function() { return dy * Math.floor(this.index / n); }).width(function() { return dx; }).height(function() { return dy; }).lineWidth(1.5).strokeStyle("#fff").fillStyle(function(l) { return l.linkValue ? "#555" : "#eee"; }).parent = this; delete this.link.add; this.label.data(function() { return labels; }).left(function() { return 1 & this.index ? dx * ((this.index >> 1) + .5) : 0; }).top(function() { return 1 & this.index ? 0 : dy * ((this.index >> 1) + .5); }).textMargin(4).textAlign(function() { return 1 & this.index ? "left" : "right"; }).textAngle(function() { return 1 & this.index ? -Math.PI / 2 : 0; }); delete this.node; }; pv.Layout.Matrix.prototype = pv.extend(pv.Layout.Network).property("directed", Boolean); pv.Layout.Matrix.prototype.sort = function(f) { this.$sort = f; return this; }; pv.Layout.Matrix.prototype.buildImplied = function(s) { if (!pv.Layout.Network.prototype.buildImplied.call(this, s)) { var nodes = s.nodes, links = s.links, sort = this.$sort, n = nodes.length, index = pv.range(n), labels = [], pairs = [], map = {}; s.$matrix = { labels: labels, pairs: pairs }; sort && index.sort(function(a, b) { return sort(nodes[a], nodes[b]); }); for (var i = 0; n > i; i++) for (var j = 0; n > j; j++) { var a = index[i], b = index[j], p = { row: i, col: j, sourceNode: nodes[a], targetNode: nodes[b], linkValue: 0 }; pairs.push(map[a + "." + b] = p); } for (var i = 0; n > i; i++) { var a = index[i]; labels.push(nodes[a], nodes[a]); } for (var i = 0; i < links.length; i++) { var l = links[i], source = l.sourceNode.index, target = l.targetNode.index, value = l.linkValue; map[source + "." + target].linkValue += value; s.directed || (map[target + "." + source].linkValue += value); } } }; pv.Layout.Bullet = function() { pv.Layout.call(this); var orient, horizontal, rangeColor, measureColor, x, that = this, buildImplied = that.buildImplied, scale = that.x = pv.Scale.linear(); this.buildImplied = function(s) { buildImplied.call(this, x = s); orient = s.orient; horizontal = /^left|right$/.test(orient); rangeColor = pv.ramp("#bbb", "#eee").domain(0, Math.max(1, x.ranges.length - 1)); measureColor = pv.ramp("steelblue", "lightsteelblue").domain(0, Math.max(1, x.measures.length - 1)); }; (this.range = new pv.Mark()).data(function() { return x.ranges; }).reverse(!0).left(function() { return "left" == orient ? 0 : null; }).top(function() { return "top" == orient ? 0 : null; }).right(function() { return "right" == orient ? 0 : null; }).bottom(function() { return "bottom" == orient ? 0 : null; }).width(function(d) { return horizontal ? scale(d) : null; }).height(function(d) { return horizontal ? null : scale(d); }).fillStyle(function() { return rangeColor(this.index); }).antialias(!1).parent = that; (this.measure = new pv.Mark()).extend(this.range).data(function() { return x.measures; }).left(function() { return "left" == orient ? 0 : horizontal ? null : this.parent.width() / 3.25; }).top(function() { return "top" == orient ? 0 : horizontal ? this.parent.height() / 3.25 : null; }).right(function() { return "right" == orient ? 0 : horizontal ? null : this.parent.width() / 3.25; }).bottom(function() { return "bottom" == orient ? 0 : horizontal ? this.parent.height() / 3.25 : null; }).fillStyle(function() { return measureColor(this.index); }).parent = that; (this.marker = new pv.Mark()).data(function() { return x.markers; }).left(function(d) { return "left" == orient ? scale(d) : horizontal ? null : this.parent.width() / 2; }).top(function(d) { return "top" == orient ? scale(d) : horizontal ? this.parent.height() / 2 : null; }).right(function(d) { return "right" == orient ? scale(d) : null; }).bottom(function(d) { return "bottom" == orient ? scale(d) : null; }).strokeStyle("black").shape("bar").shapeAngle(function() { return horizontal ? 0 : Math.PI / 2; }).parent = that; (this.tick = new pv.Mark()).data(function() { return scale.ticks(7); }).left(function(d) { return "left" == orient ? scale(d) : null; }).top(function(d) { return "top" == orient ? scale(d) : null; }).right(function(d) { return "right" == orient ? scale(d) : horizontal ? null : -6; }).bottom(function(d) { return "bottom" == orient ? scale(d) : horizontal ? -8 : null; }).height(function() { return horizontal ? 6 : null; }).width(function() { return horizontal ? null : 6; }).parent = that; }; pv.Layout.Bullet.prototype = pv.extend(pv.Layout).property("orient", String).property("ranges").property("markers").property("measures").property("minimum").property("maximum"); pv.Layout.Bullet.prototype.defaults = new pv.Layout.Bullet().extend(pv.Layout.prototype.defaults).orient("left").ranges([]).markers([]).measures([]); pv.Layout.Bullet.prototype._originIsZero = !0; pv.Layout.Bullet.prototype.originIsZero = function(value) { return arguments.length ? this._originIsZero = !!value : this._originIsZero; }; pv.Layout.Bullet.prototype.buildImplied = function(s) { pv.Layout.prototype.buildImplied.call(this, s); var allValues, size = this.parent[/^left|right$/.test(s.orient) ? "width" : "height"](), max = s.maximum, min = s.minimum, delta = 1e-10; if (null == max) { allValues = [].concat(s.ranges, s.markers, s.measures); max = pv.max(allValues); } else max = +max; if (null == min) { allValues || (allValues = [].concat(s.ranges, s.markers, s.measures)); min = pv.min(allValues); min = .95 * min; } else min = +min; (min > max || delta > max - min) && (min = Math.abs(max) < delta ? -.1 : .99 * max); this._originIsZero && min * max > 0 && (min > 0 ? min = 0 : max = 0); s.minimum = min; s.maximum = max; this.x.domain(min, max).range(0, size); }; pv.Behavior = {}; pv.Behavior.dragBase = function(shared) { function mousedown(d) { if (!inited) { inited = !0; this.addEventInterceptor("click", eventInterceptor, !0); } if (!events) { var root = this.root.scene.$g; events = [ [ root, "mousemove", pv.listen(root, "mousemove", mousemove) ], [ root, "mouseup", pv.listen(root, "mouseup", mouseup) ], [ document, "mousemove", pv.listen(document, "mousemove", mousemove) ], [ document, "mouseup", pv.listen(document, "mouseup", mouseup) ] ]; } var ev = arguments[arguments.length - 1]; downElem = ev.target; cancelClick = !1; ev.stopPropagation(); var m1 = this.mouse(), scene = this.scene, index = this.index; drag = scene[index].drag = { phase: "start", m: m1, m1: m1, m2: null, d: d, scene: scene, index: index }; ev = wrapEvent(ev, drag); shared.dragstart.call(this, ev); var m = drag.m; if (m !== m1) { m1.x = m.x; m1.y = m.y; } } function mousemove(ev) { if (drag) { drag.phase = "move"; ev.stopPropagation(); ev = wrapEvent(ev, drag); var scene = drag.scene; scene.mark.context(scene, drag.index, function() { var mprev = drag.m2 || drag.m1, m2 = this.mouse(); if (!(mprev && m2.distance2(mprev).dist2 <= 2)) { drag.m = drag.m2 = m2; shared.drag.call(this, ev); var m = drag.m; if (m !== m2) { m2.x = m.x; m2.y = m.y; } } }); } } function mouseup(ev) { if (drag) { drag.phase = "end"; var m2 = drag.m2, isDrag = m2 && drag.m1.distance2(m2).dist2 > .1; drag.canceled = !isDrag; cancelClick = isDrag && downElem === ev.target; cancelClick || (downElem = null); ev.stopPropagation(); ev = wrapEvent(ev, drag); if (events) { events.forEach(function(registration) { pv.unlisten.apply(pv, registration); }); events = null; } var scene = drag.scene, index = drag.index; try { scene.mark.context(scene, index, function() { shared.dragend.call(this, ev); }); } finally { drag = null; delete scene[index].drag; } } } function wrapEvent(ev, drag) { try { ev.drag = drag; return ev; } catch (ex) {} var ev2 = {}; for (var p in ev) { var v = ev[p]; ev2[p] = "function" != typeof v ? v : bindEventFun(v, ev); } ev2._sourceEvent = ev; return ev2; } function bindEventFun(f, ctx) { return function() { return f.apply(ctx, arguments); }; } function eventInterceptor(type, ev) { if (cancelClick && downElem === ev.target) { cancelClick = !1; downElem = null; return !1; } } var events, downElem, cancelClick, inited, drag; shared.autoRender = !0; shared.positionConstraint = null; shared.bound = function(v, a_p) { return Math.max(drag.min[a_p], Math.min(drag.max[a_p], v)); }; mousedown.autoRender = function(_) { if (arguments.length) { shared.autoRender = !!_; return mousedown; } return shared.autoRender; }; mousedown.positionConstraint = function(_) { if (arguments.length) { shared.positionConstraint = _; return mousedown; } return shared.positionConstraint; }; return mousedown; }; pv.Behavior.drag = function() { var v1, collapse = null, kx = 1, ky = 1, shared = { dragstart: function(ev) { var drag = ev.drag; drag.type = "drag"; var p = drag.d, fix = pv.vector(p.x, p.y); p.fix = fix; p.drag = drag; v1 = fix.minus(drag.m1); var parent = this.parent; drag.max = { x: parent.width() - (p.dx || 0), y: parent.height() - (p.dy || 0) }; drag.min = { x: 0, y: 0 }; shared.autoRender && this.render(); pv.Mark.dispatch("dragstart", drag.scene, drag.index, ev); }, drag: function(ev) { var drag = ev.drag, m2 = drag.m2, p = drag.d; drag.m = v1.plus(m2); var constraint = shared.positionConstraint; constraint && constraint(drag); var m = drag.m; kx && (p.x = p.fix.x = shared.bound(m.x, "x")); ky && (p.y = p.fix.y = shared.bound(m.y, "y")); shared.autoRender && this.render(); pv.Mark.dispatch("drag", drag.scene, drag.index, ev); }, dragend: function(ev) { var drag = ev.drag, p = drag.d; p.fix = null; v1 = null; shared.autoRender && this.render(); try { pv.Mark.dispatch("dragend", drag.scene, drag.index, ev); } finally { delete p.drag; } } }, mousedown = pv.Behavior.dragBase(shared); mousedown.collapse = function(x) { if (arguments.length) { collapse = String(x); switch (collapse) { case "y": kx = 1; ky = 0; break; case "x": kx = 0; ky = 1; break; default: kx = 1; ky = 1; } return mousedown; } return collapse; }; return mousedown; }; pv.Behavior.point = function(keyArgs) { function searchSceneChildren(scene, curr) { if (scene.visible) for (var i = scene.children.length - 1; i >= 0; i--) if (searchScenes(scene.children[i], curr)) return !0; } function searchScenes(scenes, curr) { var result, mark = scenes.mark, isPanel = "panel" === mark.type; if (mark.$handlers.point) for (var visibility, mouse = (isPanel && mark.parent || mark).mouse(), markRMax = mark._pointingRadiusMax, markCostMax = markRMax * markRMax, j = scenes.length - 1; j >= 0; j--) if ((visibility = sceneVisibility(scenes, j)) && evalScene(scenes, j, mouse, curr, visibility, markCostMax)) { result = !0; break; } if (isPanel) { mark.scene = scenes; try { for (var j = scenes.length - 1; j >= 0; j--) { mark.index = j; if (searchSceneChildren(scenes[j], curr)) return !0; } } finally { delete mark.scene; delete mark.index; } } return result; } function sceneVisibility(scenes, index) { var s = scenes[index]; if (!s.visible) return 0; if (!painted) return 1; var ps = scenes.mark.properties; if (!ps.fillStyle && !ps.strokeStyle) return 1; var o1 = s.fillStyle ? s.fillStyle.opacity : 0, o2 = s.strokeStyle ? s.strokeStyle.opacity : 0, o = Math.max(o1, o2); return .02 > o ? 0 : o > .98 ? 1 : .5; } function evalScene(scenes, index, mouse, curr, visibility, markCostMax) { function makeChoice() { if (applyMarkCostMax && 0 >= markCostMax) return -1; cand = shape.distance2(mouse, k); if (applyMarkCostMax && pv.floatLess(markCostMax, cand.cost)) return -2; if (finiteDist2Max && !inside && pv.floatLess(dist2Max, cand.dist2)) return -3; if (hasArea === curr.hasArea) { if (inside < curr.inside) return -4; if (inside > curr.inside) return 1; } else { if (collapse) { if (!inside && curr.inside) return -5; if (inside && !curr.inside) return 2; } if (hasArea || 2 !== curr.inside) { if (hasArea && 2 === inside) { if (2 === curr.inside) return -7; if (0 === curr.inside && pv.floatLess(3, curr.cost)) return 4; } } else { if (2 === inside) return 3; if (0 === inside && pv.floatLess(3, cand.cost)) return -6; } } if (!collapse || !inside) { if (pv.floatLess(curr.dist2, cand.dist2)) return -8; if (pv.floatLess(cand.dist2, curr.dist2)) return 5; } return collapse && pv.floatLess(cand.cost, curr.cost) ? 6 : -9; } var cand, shape = scenes.mark.getShape(scenes, index), hasArea = shape.hasArea(), inside = shape.containsPoint(mouse, k) ? !collapse || shape.containsPoint(mouse) ? 2 : 1 : 0, applyMarkCostMax = isFinite(markCostMax) && 2 > inside, choice = makeChoice(); DEBUG && function() { if (-3 > choice || choice > 0) { var pointMark = scenes && scenes.mark; console.log("POINT " + (choice > 0 ? "choose" : "skip") + " (" + choice + ") " + (pointMark ? pointMark.type + " " + index : "none") + " in=" + inside + " d2=" + (cand && cand.dist2) + " cost=" + (cand && cand.cost) + " opaq=" + (1 === visibility)); } }(); if (choice > 0) { curr.hasArea = hasArea; curr.inside = inside; curr.dist2 = cand.dist2; curr.cost = cand.cost; curr.scenes = scenes; curr.index = index; curr.shape = shape; if (hasArea && 2 === inside && 1 === visibility) return !0; } } function mousemove() { var e = pv.event; DEBUG && console.log("POINT MOUSE MOVE BEG"); try { var point = { cost: 1/0, dist2: 1/0, inside: 0, hasArea: !1, x: e.pageX || 0, y: e.pageY || 0 }; if (unpoint && radiusHyst2 && pv.Shape.dist2(point, unpoint).cost < radiusHyst2) return; searchSceneChildren(this.scene[this.index], point); point.inside || isFinite(point.cost) || (point = null); if (unpoint) { if (point && unpoint.scenes == point.scenes && unpoint.index == point.index) return; e.isPointSwitch = !!point; pv.Mark.dispatch("unpoint", unpoint.scenes, unpoint.index, e); } unpoint = point; if (point) { pv.Mark.dispatch("point", point.scenes, point.index, e); if (pointingPanel) ; else if ("panel" === this.type) { pointingPanel = this; this.event("mouseout", function() { mouseout.call(this.scene.$g); }); stealClick && pointingPanel.addEventInterceptor("click", eventInterceptor); } else pv.listen(this.root.canvas(), "mouseout", mouseout); } } finally { DEBUG && console.log("POINT MOUSE MOVE END"); } } function mouseout() { var e = pv.event; if (unpoint && !pv.ancestor(this, e.relatedTarget)) { pv.Mark.dispatch("unpoint", unpoint.scenes, unpoint.index, e); unpoint = null; } } function eventInterceptor(type, ev) { if (unpoint) { var scenes = unpoint.scenes, handler = scenes.mark.$handlers[type]; if (handler) return [ handler, scenes, unpoint.index, ev ]; } } "object" != typeof keyArgs && (keyArgs = { radius: keyArgs }); var unpoint, DEBUG = 0, collapse = null, painted = !!pv.get(keyArgs, "painted", !1), stealClick = !!pv.get(keyArgs, "stealClick", !1), k = { x: 1, y: 1 }, pointingPanel = null, dist2Max = function() { var r = pv.parseNumNonNeg(pv.get(keyArgs, "radius"), 30); return r * r; }(), finiteDist2Max = isFinite(dist2Max), radiusHyst2 = function() { var r = pv.parseNumNonNeg(pv.get(keyArgs, "radiusHyst"), 0); isFinite(r) || (r = 4); return r * r; }(); mousemove.collapse = function(x) { if (arguments.length) { collapse = String(x); switch (collapse) { case "y": k.x = 1; k.y = 0; break; case "x": k.x = 0; k.y = 1; break; default: k.x = 1; k.y = 1; collapse = null; } return mousemove; } return collapse; }; keyArgs && null != keyArgs.collapse && mousemove.collapse(keyArgs.collapse); keyArgs = null; return mousemove; }; pv.Behavior.select = function() { var collapse = null, kx = 1, ky = 1, preserveLength = !1, shared = { dragstart: function(ev) { var drag = ev.drag; drag.type = "select"; drag.dxmin = 0; drag.dymin = 0; var r = drag.d; r.drag = drag; drag.max = { x: this.width(), y: this.height() }; drag.min = { x: 0, y: 0 }; var constraint = shared.positionConstraint; if (constraint) { drag.m = drag.m.clone(); constraint(drag); } var m = drag.m; if (kx) { r.x = shared.bound(m.x, "x"); preserveLength || (r.dx = Math.max(0, drag.dxmin)); } if (ky) { r.y = shared.bound(m.y, "y"); preserveLength || (r.dy = Math.max(0, drag.dymin)); } pv.Mark.dispatch("selectstart", drag.scene, drag.index, ev); }, drag: function(ev) { var drag = ev.drag, m1 = drag.m1, r = drag.d; drag.max.x = this.width(); drag.max.y = this.height(); var constraint = shared.positionConstraint; if (constraint) { drag.m = drag.m.clone(); constraint(drag); } var m = drag.m; if (kx) { var bx = Math.min(m1.x, m.x); bx = shared.bound(bx, "x"); r.x = bx; if (!preserveLength) { var ex = Math.max(m.x, m1.x); ex = shared.bound(ex, "x"); r.dx = Math.max(0, drag.dxmin, ex - bx); } } if (ky) { var by = Math.min(m1.y, m.y); by = shared.bound(by, "y"); r.y = by; if (!preserveLength) { var ey = Math.max(m.y, m1.y); ey = shared.bound(ey, "y"); r.dy = Math.max(0, drag.dymin, ey - by); } } shared.autoRender && this.render(); pv.Mark.dispatch("select", drag.scene, drag.index, ev); }, dragend: function(ev) { var drag = ev.drag; try { pv.Mark.dispatch("selectend", drag.scene, drag.index, ev); } finally { var r = drag.d; delete r.drag; } } }, mousedown = pv.Behavior.dragBase(shared); mousedown.collapse = function(x) { if (arguments.length) { collapse = String(x); switch (collapse) { case "y": kx = 1; ky = 0; break; case "x": kx = 0; ky = 1; break; default: kx = 1; ky = 1; } return mousedown; } return collapse; }; mousedown.preserveLength = function(_) { if (arguments.length) { preserveLength = !!_; return mousedown; } return preserveLength; }; return mousedown; }; pv.Behavior.resize = function(side) { var preserveOrtho = !1, isLeftRight = "left" === side || "right" === side, shared = { dragstart: function(ev) { var drag = ev.drag; drag.type = "resize"; var m1 = drag.m1, r = drag.d; r.drag = drag; switch (side) { case "left": m1.x = r.x + r.dx; break; case "right": m1.x = r.x; break; case "top": m1.y = r.y + r.dy; break; case "bottom": m1.y = r.y; } var parent = this.parent; drag.max = { x: parent.width(), y: parent.height() }; drag.min = { x: 0, y: 0 }; pv.Mark.dispatch("resizestart", drag.scene, drag.index, ev); }, drag: function(ev) { var drag = ev.drag, m1 = drag.m1, constraint = shared.positionConstraint; if (constraint) { drag.m = drag.m.clone(); constraint(drag); } var m = drag.m, r = drag.d; if (!preserveOrtho || isLeftRight) { var bx = Math.min(m1.x, m.x), ex = Math.max(m.x, m1.x); bx = shared.bound(bx, "x"); ex = shared.bound(ex, "x"); r.x = bx; r.dx = ex - bx; } if (!preserveOrtho || !isLeftRight) { var by = Math.min(m1.y, m.y), ey = Math.max(m.y, m1.y); by = shared.bound(by, "y"); ey = shared.bound(ey, "y"); r.y = by; r.dy = ey - by; } shared.autoRender && this.render(); pv.Mark.dispatch("resize", drag.scene, drag.index, ev); }, dragend: function(ev) { var drag = ev.drag; drag.max = null; try { pv.Mark.dispatch("resizeend", drag.scene, drag.index, ev); } finally { var r = drag.d; delete r.drag; } } }, mousedown = pv.Behavior.dragBase(shared); mousedown.preserveOrtho = function(_) { if (arguments.length) { preserveOrtho = !!_; return mousedown; } return preserveOrtho; }; return mousedown; }; pv.Behavior.pan = function() { function mousedown() { index = this.index; scene = this.scene; v1 = pv.vector(pv.event.pageX, pv.event.pageY); m1 = this.transform(); k = 1 / (m1.k * this.scale); bound && (bound = { x: (1 - m1.k) * this.width(), y: (1 - m1.k) * this.height() }); } function mousemove(e) { if (scene) { scene.mark.context(scene, index, function() { var x = (pv.event.pageX - v1.x) * k, y = (pv.event.pageY - v1.y) * k, m = m1.translate(x, y); if (bound) { m.x = Math.max(bound.x, Math.min(0, m.x)); m.y = Math.max(bound.y, Math.min(0, m.y)); } this.transform(m).render(); }); pv.Mark.dispatch("pan", scene, index, e); } } function mouseup() { scene = null; } var scene, index, m1, v1, k, bound; mousedown.bound = function(x) { if (arguments.length) { bound = Boolean(x); return this; } return Boolean(bound); }; pv.listen(window, "mousemove", mousemove); pv.listen(window, "mouseup", mouseup); return mousedown; }; pv.Behavior.zoom = function(speed) { function mousewheel(e) { var v = this.mouse(), k = pv.event.wheel * speed, m = this.transform().translate(v.x, v.y).scale(0 > k ? 1e3 / (1e3 - k) : (1e3 + k) / 1e3).translate(-v.x, -v.y); if (bound) { m.k = Math.max(1, m.k); m.x = Math.max((1 - m.k) * this.width(), Math.min(0, m.x)); m.y = Math.max((1 - m.k) * this.height(), Math.min(0, m.y)); } this.transform(m).render(); pv.Mark.dispatch("zoom", this.scene, this.index, e); } var bound; arguments.length || (speed = 1 / 48); mousewheel.bound = function(x) { if (arguments.length) { bound = Boolean(x); return this; } return Boolean(bound); }; return mousewheel; }; pv.Geo = function() {}; pv.Geo.projections = { mercator: { project: function(latlng) { return { x: latlng.lng / 180, y: latlng.lat > 85 ? 1 : latlng.lat < -85 ? -1 : Math.log(Math.tan(Math.PI / 4 + pv.radians(latlng.lat) / 2)) / Math.PI }; }, invert: function(xy) { return { lng: 180 * xy.x, lat: pv.degrees(2 * Math.atan(Math.exp(xy.y * Math.PI)) - Math.PI / 2) }; } }, "gall-peters": { project: function(latlng) { return { x: latlng.lng / 180, y: Math.sin(pv.radians(latlng.lat)) }; }, invert: function(xy) { return { lng: 180 * xy.x, lat: pv.degrees(Math.asin(xy.y)) }; } }, sinusoidal: { project: function(latlng) { return { x: pv.radians(latlng.lng) * Math.cos(pv.radians(latlng.lat)) / Math.PI, y: latlng.lat / 90 }; }, invert: function(xy) { return { lng: pv.degrees(xy.x * Math.PI / Math.cos(xy.y * Math.PI / 2)), lat: 90 * xy.y }; } }, aitoff: { project: function(latlng) { var l = pv.radians(latlng.lng), f = pv.radians(latlng.lat), a = Math.acos(Math.cos(f) * Math.cos(l / 2)); return { x: 2 * (a ? Math.cos(f) * Math.sin(l / 2) * a / Math.sin(a) : 0) / Math.PI, y: 2 * (a ? Math.sin(f) * a / Math.sin(a) : 0) / Math.PI }; }, invert: function(xy) { var x = xy.x * Math.PI / 2, y = xy.y * Math.PI / 2; return { lng: pv.degrees(x / Math.cos(y)), lat: pv.degrees(y) }; } }, hammer: { project: function(latlng) { var l = pv.radians(latlng.lng), f = pv.radians(latlng.lat), c = Math.sqrt(1 + Math.cos(f) * Math.cos(l / 2)); return { x: 2 * Math.SQRT2 * Math.cos(f) * Math.sin(l / 2) / c / 3, y: Math.SQRT2 * Math.sin(f) / c / 1.5 }; }, invert: function(xy) { var x = 3 * xy.x, y = 1.5 * xy.y, z = Math.sqrt(1 - x * x / 16 - y * y / 4); return { lng: pv.degrees(2 * Math.atan2(z * x, 2 * (2 * z * z - 1))), lat: pv.degrees(Math.asin(z * y)) }; } }, identity: { project: function(latlng) { return { x: latlng.lng / 180, y: latlng.lat / 90 }; }, invert: function(xy) { return { lng: 180 * xy.x, lat: 90 * xy.y }; } } }; pv.Geo.scale = function(p) { function scale(latlng) { if (!lastLatLng || latlng.lng != lastLatLng.lng || latlng.lat != lastLatLng.lat) { lastLatLng = latlng; var p = project(latlng); lastPoint = { x: x(p.x), y: y(p.y) }; } return lastPoint; } function project(latlng) { var offset = { lng: latlng.lng - c.lng, lat: latlng.lat }; return j.project(offset); } function invert(xy) { var latlng = j.invert(xy); latlng.lng += c.lng; return latlng; } var lastLatLng, lastPoint, rmin = { x: 0, y: 0 }, rmax = { x: 1, y: 1 }, d = [], j = pv.Geo.projections.identity, x = pv.Scale.linear(-1, 1).range(0, 1), y = pv.Scale.linear(-1, 1).range(1, 0), c = { lng: 0, lat: 0 }; scale.x = function(latlng) { return scale(latlng).x; }; scale.y = function(latlng) { return scale(latlng).y; }; scale.ticks = { lng: function(m) { var lat, lng; if (d.length > 1) { var s = pv.Scale.linear(); void 0 == m && (m = 10); lat = s.domain(d, function(d) { return d.lat; }).ticks(m); lng = s.domain(d, function(d) { return d.lng; }).ticks(m); } else { lat = pv.range(-80, 81, 10); lng = pv.range(-180, 181, 10); } return lng.map(function(lng) { return lat.map(function(lat) { return { lat: lat, lng: lng }; }); }); }, lat: function(m) { return pv.transpose(scale.ticks.lng(m)); } }; scale.invert = function(p) { return invert({ x: x.invert(p.x), y: y.invert(p.y) }); }; scale.domain = function(array, f) { if (arguments.length) { d = array instanceof Array ? arguments.length > 1 ? pv.map(array, f) : array : Array.prototype.slice.call(arguments); if (d.length > 1) { var lngs = d.map(function(c) { return c.lng; }), lats = d.map(function(c) { return c.lat; }); c = { lng: (pv.max(lngs) + pv.min(lngs)) / 2, lat: (pv.max(lats) + pv.min(lats)) / 2 }; var n = d.map(project); x.domain(n, function(p) { return p.x; }); y.domain(n, function(p) { return p.y; }); } else { c = { lng: 0, lat: 0 }; x.domain(-1, 1); y.domain(-1, 1); } lastLatLng = null; return this; } return d; }; scale.range = function(min, max) { if (arguments.length) { if ("object" == typeof min) { rmin = { x: Number(min.x), y: Number(min.y) }; rmax = { x: Number(max.x), y: Number(max.y) }; } else { rmin = { x: 0, y: 0 }; rmax = { x: Number(min), y: Number(max) }; } x.range(rmin.x, rmax.x); y.range(rmax.y, rmin.y); lastLatLng = null; return this; } return [ rmin, rmax ]; }; scale.projection = function(p) { if (arguments.length) { j = "string" == typeof p ? pv.Geo.projections[p] || pv.Geo.projections.identity : p; return this.domain(d); } return p; }; pv.copyOwn(scale, pv.Scale.common); arguments.length && scale.projection(p); return scale; }; return pv; });
SteveSchafer-Innovent/innovent-pentaho-birt-plugin
js-lib/expanded/cdf/lib/CCC/protovis.js
JavaScript
epl-1.0
391,603
/******************************************************************************* * Copyright (c) 2012-2016 Codenvy, S.A. * 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: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.ide.api.debug; import com.google.gwt.http.client.URL; import com.google.inject.Inject; import com.google.inject.Singleton; import org.eclipse.che.api.debug.shared.dto.BreakpointDto; import org.eclipse.che.api.debug.shared.dto.DebugSessionDto; import org.eclipse.che.api.debug.shared.dto.LocationDto; import org.eclipse.che.api.debug.shared.dto.SimpleValueDto; import org.eclipse.che.api.debug.shared.dto.StackFrameDumpDto; import org.eclipse.che.api.debug.shared.dto.VariableDto; import org.eclipse.che.api.debug.shared.dto.action.ActionDto; import org.eclipse.che.api.debug.shared.dto.action.ResumeActionDto; import org.eclipse.che.api.debug.shared.dto.action.StartActionDto; import org.eclipse.che.api.debug.shared.dto.action.StepIntoActionDto; import org.eclipse.che.api.debug.shared.dto.action.StepOutActionDto; import org.eclipse.che.api.debug.shared.dto.action.StepOverActionDto; import org.eclipse.che.api.promises.client.Promise; import org.eclipse.che.ide.api.app.AppContext; import org.eclipse.che.ide.json.JsonHelper; import org.eclipse.che.ide.rest.AsyncRequestFactory; import org.eclipse.che.ide.rest.DtoUnmarshallerFactory; import org.eclipse.che.ide.rest.StringUnmarshaller; import org.eclipse.che.ide.ui.loaders.request.LoaderFactory; import java.util.List; import java.util.Map; import static org.eclipse.che.ide.MimeType.APPLICATION_JSON; import static org.eclipse.che.ide.rest.HTTPHeader.CONTENT_TYPE; /** * The implementation of {@link DebuggerServiceClient}. * * @author Anatoliy Bazko */ @Singleton public class DebuggerServiceClientImpl implements DebuggerServiceClient { private final LoaderFactory loaderFactory; private final AsyncRequestFactory asyncRequestFactory; private final DtoUnmarshallerFactory dtoUnmarshallerFactory; private final AppContext appContext; @Inject protected DebuggerServiceClientImpl(AppContext appContext, LoaderFactory loaderFactory, AsyncRequestFactory asyncRequestFactory, DtoUnmarshallerFactory dtoUnmarshallerFactory) { this.loaderFactory = loaderFactory; this.asyncRequestFactory = asyncRequestFactory; this.dtoUnmarshallerFactory = dtoUnmarshallerFactory; this.appContext = appContext; } @Override public Promise<DebugSessionDto> connect(String debuggerType, Map<String, String> connectionProperties) { final String requestUrl = getBaseUrl(null) + "?type=" + debuggerType; return asyncRequestFactory.createPostRequest(requestUrl, null) .header(CONTENT_TYPE, APPLICATION_JSON) .data(JsonHelper.toJson(connectionProperties)) .send(dtoUnmarshallerFactory.newUnmarshaller(DebugSessionDto.class)); } @Override public Promise<Void> disconnect(String id) { final String requestUrl = getBaseUrl(id); return asyncRequestFactory.createDeleteRequest(requestUrl) .loader(loaderFactory.newLoader()) .send(); } @Override public Promise<DebugSessionDto> getSessionInfo(String id) { final String requestUrl = getBaseUrl(id); return asyncRequestFactory.createGetRequest(requestUrl) .send(dtoUnmarshallerFactory.newUnmarshaller(DebugSessionDto.class)); } @Override public Promise<Void> start(String id, StartActionDto action) { return performAction(id, action); } @Override public Promise<Void> addBreakpoint(String id, BreakpointDto breakpointDto) { final String requestUrl = getBaseUrl(id) + "/breakpoint"; return asyncRequestFactory.createPostRequest(requestUrl, breakpointDto) .send(); } @Override public Promise<List<BreakpointDto>> getAllBreakpoints(String id) { final String requestUrl = getBaseUrl(id) + "/breakpoint"; return asyncRequestFactory.createGetRequest(requestUrl) .send(dtoUnmarshallerFactory.newListUnmarshaller(BreakpointDto.class)); } @Override public Promise<Void> deleteBreakpoint(String id, LocationDto locationDto) { final String requestUrl = getBaseUrl(id) + "/breakpoint"; final String params = "?target=" + locationDto.getTarget() + "&line=" + locationDto.getLineNumber(); return asyncRequestFactory.createDeleteRequest(requestUrl + params).send(); } @Override public Promise<Void> deleteAllBreakpoints(String id) { final String requestUrl = getBaseUrl(id) + "/breakpoint"; return asyncRequestFactory.createDeleteRequest(requestUrl).send(); } @Override public Promise<StackFrameDumpDto> getStackFrameDump(String id) { final String requestUrl = getBaseUrl(id) + "/dump"; return asyncRequestFactory.createGetRequest(requestUrl) .send(dtoUnmarshallerFactory.newUnmarshaller(StackFrameDumpDto.class)); } @Override public Promise<Void> resume(String id, ResumeActionDto action) { return performAction(id, action); } @Override public Promise<SimpleValueDto> getValue(String id, VariableDto variableDto) { final String requestUrl = getBaseUrl(id) + "/value"; List<String> path = variableDto.getVariablePath().getPath(); StringBuilder params = new StringBuilder(); for (int i = 0; i < path.size(); i++) { params.append(i == 0 ? "?" : "&"); params.append("path"); params.append(i); params.append("="); params.append(path.get(i)); } return asyncRequestFactory.createGetRequest(requestUrl + params) .send(dtoUnmarshallerFactory.newUnmarshaller(SimpleValueDto.class)); } @Override public Promise<Void> setValue(String id, VariableDto variableDto) { final String requestUrl = getBaseUrl(id) + "/value"; return asyncRequestFactory.createPutRequest(requestUrl, variableDto) .send(); } @Override public Promise<Void> stepInto(String id, StepIntoActionDto action) { return performAction(id, action); } @Override public Promise<Void> stepOver(String id, StepOverActionDto action) { return performAction(id, action); } @Override public Promise<Void> stepOut(String id, StepOutActionDto action) { return performAction(id, action); } @Override public Promise<String> evaluate(String id, String expression) { String requestUrl = getBaseUrl(id) + "/evaluation"; String params = "?expression=" + URL.encodeQueryString(expression); return asyncRequestFactory.createGetRequest(requestUrl + params) .loader(loaderFactory.newLoader()) .send(new StringUnmarshaller()); } private String getBaseUrl(String id) { final String url = appContext.getDevMachine().getWsAgentBaseUrl() + "/debugger"; if (id != null) { return url + "/" + id; } return url; } protected Promise<Void> performAction(String id, ActionDto actionDto) { final String requestUrl = getBaseUrl(id); return asyncRequestFactory.createPostRequest(requestUrl, actionDto) .send(); } }
Mirage20/che
ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/debug/DebuggerServiceClientImpl.java
Java
epl-1.0
8,132
// Shamelessly stolen from ztellman's byte-streams package gnuplot; import java.io.IOException; public class InputStream extends java.io.InputStream { public interface Streamable { int available(); void close(); long skip(long n); int read() throws IOException; int read(byte[] bytes, int offset, int length) throws IOException; } private Streamable _s; public InputStream(Streamable s) { _s = s; } public void close() { _s.close(); } public int available() { return _s.available(); } public boolean markSupported() { return false; } public void mark(int readlimit) { throw new UnsupportedOperationException(); } public void reset() { throw new UnsupportedOperationException(); } public long skip(long n) { return _s.skip(n); } public int read() throws IOException { return _s.read(); } public int read(byte[] bytes, int offset, int length) throws IOException { return _s.read(bytes, offset, length); } }
edipofederle/gnuplot
src/gnuplot/InputStream.java
Java
epl-1.0
1,114
package anatlyzer.atl.analyser.batch.invariants; import java.util.List; import java.util.Set; import java.util.function.Function; import anatlyzer.atl.analyser.generators.CSPModel2; import anatlyzer.atl.analyser.generators.ErrorSlice; import anatlyzer.atl.analyser.generators.GraphvizBuffer; import anatlyzer.atl.util.Pair; import anatlyzer.atlext.ATL.InPatternElement; import anatlyzer.atlext.ATL.OutPatternElement; import anatlyzer.atlext.OCL.CollectionOperationCallExp; import anatlyzer.atlext.OCL.Iterator; import anatlyzer.atlext.OCL.IteratorExp; import anatlyzer.atlext.OCL.LetExp; import anatlyzer.atlext.OCL.OCLFactory; import anatlyzer.atlext.OCL.OclExpression; import anatlyzer.atlext.OCL.SequenceExp; public class SplitIteratorBodyNode extends AbstractInvariantReplacerNode { private List<IInvariantNode> paths; private IteratorExp expr; public SplitIteratorBodyNode(List<IInvariantNode> paths, IteratorExp expr) { super(null); this.paths = paths; this.expr = expr; this.paths.forEach(p -> p.setParent(this)); } @Override public void genErrorSlice(ErrorSlice slice) { paths.forEach(p -> p.genErrorSlice(slice)); } @Override public OclExpression genExpr(CSPModel2 builder) { return genAux(builder, (node) -> node.genExpr(builder)); } @Override public OclExpression genExprNormalized(CSPModel2 builder) { return genAux(builder, (node) -> node.genExprNormalized(builder)); } public OclExpression genAux(CSPModel2 builder, Function<IInvariantNode, OclExpression> gen) { // assume the paths are from collections... SequenceExp seq = OCLFactory.eINSTANCE.createSequenceExp(); for (IInvariantNode iInvariantNode : paths) { seq.getElements().add(gen.apply(iInvariantNode)); } CollectionOperationCallExp flatten = OCLFactory.eINSTANCE.createCollectionOperationCallExp(); flatten.setOperationName("flatten"); flatten.setSource(seq); return flatten; } @Override public void genGraphviz(GraphvizBuffer<IInvariantNode> gv) { gv.addNode(this, gvText("Split node. ", expr), true); paths.forEach(p -> { p.genGraphviz(gv); gv.addEdge(p, this); }); } @Override public void getTargetObjectsInBinding(Set<OutPatternElement> elems) { paths.forEach(n -> n.getTargetObjectsInBinding(elems)); } @Override public Pair<LetExp, LetExp> genIteratorBindings(CSPModel2 builder, Iterator it, Iterator targetIt) { // do nothing return null; } @Override public boolean isUsed(InPatternElement e) { throw new UnsupportedOperationException(); } }
jesusc/anatlyzer
plugins/anatlyzer.atl.typing/src/anatlyzer/atl/analyser/batch/invariants/SplitIteratorBodyNode.java
Java
epl-1.0
2,530
/* * (C) Copyright IBM Corp. 2009, 2012 * * LICENSE: Eclipse Public License v1.0 * http://www.eclipse.org/legal/epl-v10.html */ package fabric.bus.routing; import fabric.Fabric; import fabric.core.xml.XML; /** * Data structure representing the the route embedded in a Fabric message. * */ public abstract class MessageRoutingFactory { /** Copyright notice. */ public static final String copyrightNotice = "(C) Copyright IBM Corp. 2009, 2012"; /* * Class methods */ /** * No instantiation of this class. */ private MessageRoutingFactory() { } /** * Create a Fabric routing instance from an existing XML representation. * * @param element * the element containing the XML. * * @param messageXML * the Fabric message containing routing information. * * @throws Exception */ public static IRouting construct(String element, XML messageXML) throws Exception { /* To hold the new instance */ IRouting instance = null; /* Get the message type (making sure that we have the full class name for the type) */ String compactType = messageXML.get(element + "/rt@t"); String type = (compactType != null) ? Fabric.longName(compactType) : null; String className = (type != null) ? type : compactType; /* If a routing type has been specified... */ if (className != null) { /* Create a new instance */ instance = (IRouting) Fabric.instantiate(type); } /* If we have created a new instance... */ if (instance != null) { instance.init(element, messageXML); } return instance; } }
acshea/edgware
fabric.lib/src/fabric/bus/routing/MessageRoutingFactory.java
Java
epl-1.0
1,751
--- layout : new-simple title: Recover password --- <div class="vmiddle"> <div class="container"> <div class="row text-center"> <div class="col-md-12"> <a href="/"><img src="images/logo@3x.png" alt="logo" class="logo" /></a> <div class="notice"> <h2>Forgot your password? Enter your email below.</h2> </div> <div class="forgotpassword-result hide"> <hr class="short-line"> <h2>We've sent a reset password link to your email.</h2> </div><!-- forgot password result --> <div class="error-container"></div> <form class="forgotpassword-form" id="forgotForm" > <ul> <li> <span class="input-con"><input id="emailid" name="email" type="text" placeholder="Email" /></span> <span class="input-con"><input type="submit" Value="Reset password" /></span> </li> </ul> </form> <ul id='bottom-ul'> </ul> </div> </div> </div> </div>
R-Brain/codenvy
site/app/site/recover-password.html
HTML
epl-1.0
1,031
/** * Copyright (c) 2010-2018 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.smaenergymeter.internal.handler; import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Date; import org.eclipse.smarthome.core.library.types.DecimalType; /** * The {@link EnergyMeter} class is responsible for communication with the SMA device * and extracting the data fields out of the received telegrams. * * @author Osman Basha - Initial contribution */ public class EnergyMeter { private String multicastGroup; private int port; private String serialNumber; private Date lastUpdate; private final FieldDTO powerIn; private final FieldDTO energyIn; private final FieldDTO powerOut; private final FieldDTO energyOut; public static final String DEFAULT_MCAST_GRP = "239.12.255.254"; public static final int DEFAULT_MCAST_PORT = 9522; public EnergyMeter(String multicastGroup, int port) { this.multicastGroup = multicastGroup; this.port = port; powerIn = new FieldDTO(0x20, 4, 10); energyIn = new FieldDTO(0x28, 8, 3600000); powerOut = new FieldDTO(0x34, 4, 10); energyOut = new FieldDTO(0x3C, 8, 3600000); } public void update() throws IOException { byte[] bytes = new byte[600]; try (MulticastSocket socket = new MulticastSocket(port)) { socket.setSoTimeout(5000); InetAddress address = InetAddress.getByName(multicastGroup); socket.joinGroup(address); DatagramPacket msgPacket = new DatagramPacket(bytes, bytes.length); socket.receive(msgPacket); String sma = new String(Arrays.copyOfRange(bytes, 0x00, 0x03)); if (!sma.equals("SMA")) { throw new IOException("Not a SMA telegram." + sma); } ByteBuffer buffer = ByteBuffer.wrap(Arrays.copyOfRange(bytes, 0x14, 0x18)); serialNumber = String.valueOf(buffer.getInt()); powerIn.updateValue(bytes); energyIn.updateValue(bytes); powerOut.updateValue(bytes); energyOut.updateValue(bytes); lastUpdate = new Date(System.currentTimeMillis()); } catch (Exception e) { throw new IOException(e); } } public String getSerialNumber() { return serialNumber; } public Date getLastUpdate() { return lastUpdate; } public DecimalType getPowerIn() { return new DecimalType(powerIn.getValue()); } public DecimalType getPowerOut() { return new DecimalType(powerOut.getValue()); } public DecimalType getEnergyIn() { return new DecimalType(energyIn.getValue()); } public DecimalType getEnergyOut() { return new DecimalType(energyOut.getValue()); } }
tavalin/openhab2-addons
addons/binding/org.openhab.binding.smaenergymeter/src/main/java/org/openhab/binding/smaenergymeter/internal/handler/EnergyMeter.java
Java
epl-1.0
3,231
/////////////////////////////////////////////////////////////////////////////// // // JTOpenLite // // Filename: AttributePackageLibrary.java // // The source code contained herein is licensed under the IBM Public License // Version 1.0, which has been approved by the Open Source Initiative. // Copyright (C) 2011-2012 International Business Machines Corporation and // others. All rights reserved. // /////////////////////////////////////////////////////////////////////////////// package com.ibm.jtopenlite.database; interface AttributePackageLibrary { public String getPackageLibrary(); public boolean isPackageLibrarySet(); public void setPackageLibrary(String value); }
devjunix/libjt400-java
jtopenlite/com/ibm/jtopenlite/database/AttributePackageLibrary.java
Java
epl-1.0
689
package com.linkonworks.df.vo; public class LoginLog implements java.io.Serializable{ private String id; private String code; private String loginTime; private String loginIp; private String machineName; private String operation; public LoginLog() { super(); } public LoginLog(String id, String code, String loginTime, String loginIp, String machineName, String operation) { super(); this.id = id; this.code = code; this.loginTime = loginTime; this.loginIp = loginIp; this.machineName = machineName; this.operation = operation; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getLoginTime() { return loginTime; } public void setLoginTime(String loginTime) { this.loginTime = loginTime; } public String getLoginIp() { return loginIp; } public void setLoginIp(String loginIp) { this.loginIp = loginIp; } public String getMachineName() { return machineName; } public void setMachineName(String machineName) { this.machineName = machineName; } public String getOperation() { return operation; } public void setOperation(String operation) { this.operation = operation; } }
helylinhe/Test
ps/src/com/linkonworks/df/vo/LoginLog.java
Java
epl-1.0
1,319
/* * Copyright (c) [2015] - [2017] Red Hat, Inc. * 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: * Red Hat, Inc. - initial API and implementation */ 'use strict'; interface ICreditCardElement extends ng.IAugmentedJQuery { card: Function; } /** * Defines a directive for creating a credit card component. * @author Oleksii Kurinnyi */ export class AddCreditCard { $timeout: ng.ITimeoutService; restrict: string = 'E'; replace: boolean = false; templateUrl: string = 'app/billing/card-info/add-credit-card/add-credit-card.html'; bindToController: boolean = true; controller: string = 'AddCreditCardController'; controllerAs: string = 'addCreditCardController'; scope: { [propName: string]: string }; /** * Default constructor that is using resource * @ngInject for Dependency injection */ constructor ($timeout: ng.ITimeoutService) { this.$timeout = $timeout; this.scope = { creditCard: '=' }; } link($scope: ng.IScope, $element: ICreditCardElement): void { ($element.find('.addCreditCardForm') as ICreditCardElement).card({ // a selector or jQuery object for the container // where you want the card to appear container: '.card-wrapper', // *required* numberInput: 'input[name="deskcardNumber"]', // optional — default input[name="number"] expiryInput: 'input[name="deskexpires"]', // optional — default input[name="expiry"] cvcInput: 'input[name="deskcvv"]', // optional — default input[name="cvc"] nameInput: 'input[name="deskcardholder"]', // optional - defaults input[name="name"] // width: 200, // optional — default 350px formatting: true // optional - default true }); let deregistrationFn = $scope.$watch(() => { return $element.find('input[name="deskcardNumber"]').is(':visible'); }, (visible) => { if (visible) { deregistrationFn(); this.$timeout(() => { $element.find('input[name="deskcardNumber"]').focus(); }, 100); } }); } }
R-Brain/codenvy
dashboard/src/app/billing/card-info/add-credit-card/add-credit-card.directive.ts
TypeScript
epl-1.0
2,261
import xml.sax import unittest import test_utils import xmlreader import os path = os.path.dirname(os.path.abspath(__file__) ) class XmlReaderTestCase(unittest.TestCase): def test_XmlDumpAllRevs(self): pages = [r for r in xmlreader.XmlDump(path + "/data/article-pear.xml", allrevisions=True).parse()] self.assertEquals(4, len(pages)) self.assertEquals(u"Automated conversion", pages[0].comment) self.assertEquals(u"Pear", pages[0].title) self.assertEquals(u"24278", pages[0].id) self.assertTrue(pages[0].text.startswith('Pears are [[tree]]s of')) self.assertEquals(u"Quercusrobur", pages[1].username) self.assertEquals(u"Pear", pages[0].title) def test_XmlDumpFirstRev(self): pages = [r for r in xmlreader.XmlDump(path + "/data/article-pear.xml").parse()] self.assertEquals(1, len(pages)) self.assertEquals(u"Automated conversion", pages[0].comment) self.assertEquals(u"Pear", pages[0].title) self.assertEquals(u"24278", pages[0].id) self.assertTrue(pages[0].text.startswith('Pears are [[tree]]s of')) self.assertTrue(not pages[0].isredirect) def test_XmlDumpRedirect(self): pages = [r for r in xmlreader.XmlDump(path + "/data/article-pyrus.xml").parse()] self.assertTrue(pages[0].isredirect) def test_MediaWikiXmlHandler(self): handler = xmlreader.MediaWikiXmlHandler() pages = [] def pageDone(page): pages.append(page) handler.setCallback(pageDone) xml.sax.parse(path + "/data/article-pear.xml", handler) self.assertEquals(u"Pear", pages[0].title) self.assertEquals(4, len(pages)) self.assertNotEquals("", pages[0].comment) if __name__ == '__main__': unittest.main()
races1986/SafeLanguage
CEM/tests/test_xmlreader.py
Python
epl-1.0
1,809
/****************************************************************************** * Copyright (C) 2006-2012 IFS Institute for Software 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 * * Original authors: * Dennis Hunziker * Ueli Kistler * Reto Schuettel * Robin Stocker * Contributors: * Fabio Zadrozny <fabiofz@gmail.com> - initial implementation ******************************************************************************/ /* * Copyright (C) 2006, 2007 Dennis Hunziker, Ueli Kistler * Copyright (C) 2007 Reto Schuettel, Robin Stocker * * IFS Institute for Software, HSR Rapperswil, Switzerland * */ package org.python.pydev.refactoring.coderefactoring.extractmethod.edit; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.python.pydev.parser.jython.SimpleNode; import org.python.pydev.parser.jython.ast.Import; import org.python.pydev.parser.jython.ast.ImportFrom; import org.python.pydev.parser.jython.ast.Name; import org.python.pydev.parser.jython.ast.NameTok; import org.python.pydev.parser.jython.ast.NameTokType; import org.python.pydev.parser.jython.ast.aliasType; import org.python.pydev.refactoring.ast.adapters.AbstractScopeNode; import org.python.pydev.refactoring.ast.adapters.ModuleAdapter; import org.python.pydev.refactoring.ast.adapters.SimpleAdapter; import org.python.pydev.shared_core.string.ICoreTextSelection; public class ParameterReturnDeduce { private List<String> parameters; private Collection<String> returns; private AbstractScopeNode<?> scopeAdapter; private ICoreTextSelection selection; private ModuleAdapter moduleAdapter; public ParameterReturnDeduce(AbstractScopeNode<?> scope, ICoreTextSelection selection, ModuleAdapter moduleAdapter) { this.scopeAdapter = scope; this.selection = selection; this.parameters = new ArrayList<String>(); this.returns = new LinkedHashSet<String>(); //maintain order. this.moduleAdapter = moduleAdapter; deduce(); } private void deduce() { ModuleAdapter module = scopeAdapter.getModule(); List<SimpleAdapter> selected = module.getWithinSelection(selection, scopeAdapter.getUsedVariables()); List<SimpleAdapter> before = new ArrayList<SimpleAdapter>(); List<SimpleAdapter> after = new ArrayList<SimpleAdapter>(); extractBeforeAfterVariables(selected, before, after); deduceParameters(before, selected); deduceReturns(after, selected); } private void deduceParameters(List<SimpleAdapter> before, List<SimpleAdapter> selected) { Set<String> globalVariableNames = new HashSet<String>(moduleAdapter.getGlobalVariableNames()); for (SimpleAdapter adapter : before) { SimpleNode astNode = adapter.getASTNode(); String id; if (astNode instanceof Name) { Name variable = (Name) astNode; id = variable.id; } else if (astNode instanceof NameTok) { NameTok variable = (NameTok) astNode; id = variable.id; } else { continue; } if (globalVariableNames.contains(id) && !isStored(id, before)) { // It's a global variable and there's no assignment // shadowing it in the local scope, so don't add it as a // parameter. continue; } if (id.equals("True") || id.equals("False") || id.equals("None")) { // The user most likely doesn't want them to be passed. continue; } if (isUsed(id, selected)) { if (!parameters.contains(id)) { parameters.add(id); } } } } private void deduceReturns(List<SimpleAdapter> after, List<SimpleAdapter> selected) { for (SimpleAdapter adapter : after) { SimpleNode astNode = adapter.getASTNode(); String id; if (astNode instanceof Name) { Name variable = (Name) astNode; id = variable.id; } else if (astNode instanceof NameTok) { NameTok variable = (NameTok) astNode; id = variable.id; } else { continue; } if (isStored(id, selected)) { returns.add(id); } } } private void extractBeforeAfterVariables(List<SimpleAdapter> selectedVariables, List<SimpleAdapter> before, List<SimpleAdapter> after) { List<SimpleAdapter> scopeVariables = scopeAdapter.getUsedVariables(); if (selectedVariables.isEmpty()) { return; } SimpleAdapter firstSelectedVariable = selectedVariables.get(0); SimpleAdapter lastSelectedVariable = selectedVariables.get(selectedVariables.size() - 1); for (SimpleAdapter adapter : scopeVariables) { if (isBeforeSelectedLine(firstSelectedVariable, adapter) || isBeforeOnSameLine(firstSelectedVariable, adapter)) { before.add(adapter); } else if (isAfterSelectedLine(lastSelectedVariable, adapter) || isAfterOnSameLine(lastSelectedVariable, adapter)) { after.add(adapter); } } } private boolean isAfterOnSameLine(SimpleAdapter lastSelectedVariable, SimpleAdapter adapter) { return adapter.getNodeFirstLine(false) == lastSelectedVariable.getNodeFirstLine(false) && (adapter.getNodeIndent() > lastSelectedVariable.getNodeIndent()); } private boolean isAfterSelectedLine(SimpleAdapter lastSelectedVariable, SimpleAdapter adapter) { return adapter.getNodeFirstLine(false) > lastSelectedVariable.getNodeFirstLine(false); } private boolean isBeforeOnSameLine(SimpleAdapter firstSelectedVariable, SimpleAdapter adapter) { return adapter.getNodeFirstLine(false) == firstSelectedVariable.getNodeFirstLine(false) && (adapter.getNodeIndent() < firstSelectedVariable.getNodeIndent()); } private boolean isBeforeSelectedLine(SimpleAdapter firstSelectedVariable, SimpleAdapter adapter) { return adapter.getNodeFirstLine(false) < firstSelectedVariable.getNodeFirstLine(false); } /** * Fix (fabioz): to check if it is used, it must be in a load context */ private boolean isUsed(String var, List<SimpleAdapter> scopeVariables) { for (SimpleAdapter adapter : scopeVariables) { SimpleNode astNode = adapter.getASTNode(); if (astNode instanceof Name) { Name scopeVar = (Name) astNode; if ((scopeVar.ctx == Name.Load || scopeVar.ctx == Name.AugLoad) && scopeVar.id.equals(var)) { return true; } } //Note: NameTok are always only in store context. } return false; } private boolean isStored(String var, List<SimpleAdapter> scopeVariables) { boolean isStored = false; // must traverse all variables, because a // variable may be used in other context! for (SimpleAdapter adapter : scopeVariables) { SimpleNode astNode = adapter.getASTNode(); if (astNode instanceof Name) { Name scopeVar = (Name) astNode; if (scopeVar.id.equals(var)) { isStored = (scopeVar.ctx != Name.Load && scopeVar.ctx != Name.AugLoad); } } else if (astNode instanceof NameTok) { NameTok scopeVar = (NameTok) astNode; if (scopeVar.id.equals(var)) { isStored = true; //NameTok are always store contexts. } } else if (astNode instanceof Import) { Import importNode = (Import) astNode; isStored = checkNames(var, importNode.names); } else if (astNode instanceof ImportFrom) { ImportFrom importFrom = (ImportFrom) astNode; isStored = checkNames(var, importFrom.names); } if (isStored) { break; } } return isStored; } private boolean checkNames(String var, aliasType[] names) { boolean isStored = false; if (names != null) { for (aliasType alias : names) { if (alias.asname != null) { isStored = nameMatches(var, alias.asname); } else if (alias.name != null) { isStored = nameMatches(var, alias.name); } } } return isStored; } private boolean nameMatches(String var, NameTokType asname) { return ((NameTok) asname).id.equals(var); } public List<String> getParameters() { return this.parameters; } public List<String> getReturns() { return new ArrayList<String>(this.returns); } }
akurtakov/Pydev
plugins/org.python.pydev.refactoring/src/org/python/pydev/refactoring/coderefactoring/extractmethod/edit/ParameterReturnDeduce.java
Java
epl-1.0
9,397
// $Id$ # ifndef CPPAD_OP_HPP # define CPPAD_OP_HPP /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-15 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Eclipse Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ // used by the sparse operators # include <cppad/local/sparse_pattern.hpp> // operations # include <cppad/local/std_math_98.hpp> # include <cppad/local/abs_op.hpp> # include <cppad/local/add_op.hpp> # include <cppad/local/acos_op.hpp> # include <cppad/local/acosh_op.hpp> # include <cppad/local/asin_op.hpp> # include <cppad/local/asinh_op.hpp> # include <cppad/local/atan_op.hpp> # include <cppad/local/atanh_op.hpp> # include <cppad/local/comp_op.hpp> # include <cppad/local/cond_op.hpp> # include <cppad/local/cos_op.hpp> # include <cppad/local/cosh_op.hpp> # include <cppad/local/cskip_op.hpp> # include <cppad/local/csum_op.hpp> # include <cppad/local/discrete_op.hpp> # include <cppad/local/div_op.hpp> # include <cppad/local/erf_op.hpp> # include <cppad/local/exp_op.hpp> # include <cppad/local/expm1_op.hpp> # include <cppad/local/load_op.hpp> # include <cppad/local/log_op.hpp> # include <cppad/local/log1p_op.hpp> # include <cppad/local/mul_op.hpp> # include <cppad/local/parameter_op.hpp> # include <cppad/local/pow_op.hpp> # include <cppad/local/print_op.hpp> # include <cppad/local/sign_op.hpp> # include <cppad/local/sin_op.hpp> # include <cppad/local/sinh_op.hpp> # include <cppad/local/sqrt_op.hpp> # include <cppad/local/sub_op.hpp> # include <cppad/local/sparse_binary_op.hpp> # include <cppad/local/sparse_unary_op.hpp> # include <cppad/local/store_op.hpp> # include <cppad/local/tan_op.hpp> # include <cppad/local/tanh_op.hpp> # include <cppad/local/zmul_op.hpp> # endif
wegamekinglc/CppAD
cppad/local/op.hpp
C++
epl-1.0
2,085
/******************************************************************************* * Copyright (c) 2003, 2019 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.ejbcontainer.timer.persistent.core.ejb; import javax.ejb.CreateException; import javax.ejb.EJBLocalHome; /** * Home interface for a basic Stateless Session that does not * implement the TimedObject interface. It contains methods to test * TimerService access. **/ public interface StatelessHome extends EJBLocalHome { /** * @return StatelessObject The StatelessBean EJB object. * @exception javax.ejb.CreateException StatelessBean EJB object was not created. */ public StatelessObject create() throws CreateException; }
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer.timer.persistent_fat/test-applications/PersistentTimerCoreEJB.jar/src/com/ibm/ws/ejbcontainer/timer/persistent/core/ejb/StatelessHome.java
Java
epl-1.0
1,111
#include "Corridor.h" Corridor::Corridor():leftWall(-5.0),rightWall(5.0),topWall(5.0f),bottomWall(-5.0f),farWall(-32.0f){ } double Corridor::getRW() const{ return rightWall; } double Corridor::getLW() const{ return leftWall; } double Corridor::getTW() const{ return topWall; } double Corridor::getBW() const{ return bottomWall; } double Corridor::getFW() const{ return farWall; }
cis542/VR_Wall
SquashGame/Game/Corridor.cpp
C++
epl-1.0
392
/** * Copyright (c) 2015-2018 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.core.types; /** * This is a marker interface for all command types. * * @author Kai Kreuzer * @since 0.1.0 * */ public interface Command extends Type { }
lewie/openhab
bundles/api/org.openhab.core1/src/main/java/org/openhab/core/types/Command.java
Java
epl-1.0
523
/**************************************************************** * * Copyright 2013, Big Switch Networks, Inc. * * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html * * 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. * ****************************************************************/ /****************************************************************************** * * /module/src/loci_config.c * * loci Config Information * *****************************************************************************/ #include <loci/loci_config.h> #include <loci/loci.h> #include "loci_int.h" #include <stdlib.h> #include <string.h> /* <auto.start.cdefs(LOCI_CONFIG_HEADER).source> */ #define __loci_config_STRINGIFY_NAME(_x) #_x #define __loci_config_STRINGIFY_VALUE(_x) __loci_config_STRINGIFY_NAME(_x) loci_config_settings_t loci_config_settings[] = { #ifdef LOCI_CONFIG_INCLUDE_LOGGING { __loci_config_STRINGIFY_NAME(LOCI_CONFIG_INCLUDE_LOGGING), __loci_config_STRINGIFY_VALUE(LOCI_CONFIG_INCLUDE_LOGGING) }, #else { LOCI_CONFIG_INCLUDE_LOGGING(__loci_config_STRINGIFY_NAME), "__undefined__" }, #endif #ifdef LOCI_CONFIG_LOG_OPTIONS_DEFAULT { __loci_config_STRINGIFY_NAME(LOCI_CONFIG_LOG_OPTIONS_DEFAULT), __loci_config_STRINGIFY_VALUE(LOCI_CONFIG_LOG_OPTIONS_DEFAULT) }, #else { LOCI_CONFIG_LOG_OPTIONS_DEFAULT(__loci_config_STRINGIFY_NAME), "__undefined__" }, #endif #ifdef LOCI_CONFIG_LOG_BITS_DEFAULT { __loci_config_STRINGIFY_NAME(LOCI_CONFIG_LOG_BITS_DEFAULT), __loci_config_STRINGIFY_VALUE(LOCI_CONFIG_LOG_BITS_DEFAULT) }, #else { LOCI_CONFIG_LOG_BITS_DEFAULT(__loci_config_STRINGIFY_NAME), "__undefined__" }, #endif #ifdef LOCI_CONFIG_LOG_CUSTOM_BITS_DEFAULT { __loci_config_STRINGIFY_NAME(LOCI_CONFIG_LOG_CUSTOM_BITS_DEFAULT), __loci_config_STRINGIFY_VALUE(LOCI_CONFIG_LOG_CUSTOM_BITS_DEFAULT) }, #else { LOCI_CONFIG_LOG_CUSTOM_BITS_DEFAULT(__loci_config_STRINGIFY_NAME), "__undefined__" }, #endif #ifdef LOCI_CONFIG_PORTING_STDLIB { __loci_config_STRINGIFY_NAME(LOCI_CONFIG_PORTING_STDLIB), __loci_config_STRINGIFY_VALUE(LOCI_CONFIG_PORTING_STDLIB) }, #else { LOCI_CONFIG_PORTING_STDLIB(__loci_config_STRINGIFY_NAME), "__undefined__" }, #endif #ifdef LOCI_CONFIG_PORTING_INCLUDE_STDLIB_HEADERS { __loci_config_STRINGIFY_NAME(LOCI_CONFIG_PORTING_INCLUDE_STDLIB_HEADERS), __loci_config_STRINGIFY_VALUE(LOCI_CONFIG_PORTING_INCLUDE_STDLIB_HEADERS) }, #else { LOCI_CONFIG_PORTING_INCLUDE_STDLIB_HEADERS(__loci_config_STRINGIFY_NAME), "__undefined__" }, #endif #ifdef LOCI_CONFIG_INCLUDE_UCLI { __loci_config_STRINGIFY_NAME(LOCI_CONFIG_INCLUDE_UCLI), __loci_config_STRINGIFY_VALUE(LOCI_CONFIG_INCLUDE_UCLI) }, #else { LOCI_CONFIG_INCLUDE_UCLI(__loci_config_STRINGIFY_NAME), "__undefined__" }, #endif { NULL, NULL } }; #undef __loci_config_STRINGIFY_VALUE #undef __loci_config_STRINGIFY_NAME const char* loci_config_lookup(const char* setting) { int i; for(i = 0; loci_config_settings[i].name; i++) { if(strcmp(loci_config_settings[i].name, setting)) { return loci_config_settings[i].value; } } return NULL; } int loci_config_show(struct aim_pvs_s* pvs) { int i; for(i = 0; loci_config_settings[i].name; i++) { aim_printf(pvs, "%s = %s\n", loci_config_settings[i].name, loci_config_settings[i].value); } return i; } /* <auto.end.cdefs(LOCI_CONFIG_HEADER).source> */ /** * Necessary for module initialization infrastructure. * This should register with AIM. */ void __loci_module_init__(void) { }
rlane/indigo
Modules/loci/src/loci_config.c
C
epl-1.0
3,990
package org.camunda.bpm.modeler.ui.property.tabs; import org.camunda.bpm.modeler.core.property.AbstractTabSection; import org.eclipse.bpmn2.BaseElement; import org.eclipse.emf.ecore.EObject; import org.eclipse.swt.widgets.Composite; /** * Extensions tab for form data properties * * @author kristin.polenz */ public class ExtensionsTabSection extends AbstractTabSection { @Override protected Composite createCompositeForObject(Composite parent, EObject businessObject) { if (businessObject instanceof BaseElement) { new ExtensionsTabCompositeFactory(this, parent).createCompositeForBusinessObject((BaseElement) businessObject); } return parent; } }
camunda/camunda-eclipse-plugin
org.camunda.bpm.modeler/src/org/camunda/bpm/modeler/ui/property/tabs/ExtensionsTabSection.java
Java
epl-1.0
670
/* * mmx.h * Copyright (C) 1997-1999 H. Dietz and R. Fisher * * This file is part of mpeg2dec, a free MPEG-2 video stream decoder. * * mpeg2dec is free software; you can redistribute it and/or modify * 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. * * mpeg2dec is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * The type of an value that fits in an MMX register (note that long * long constant values MUST be suffixed by LL and unsigned long long * values by ULL, lest they be truncated by the compiler) */ #include <stdint.h> typedef union { int64_t q; /* Quadword (64-bit) value */ uint64_t uq; /* Unsigned Quadword */ int32_t d[2]; /* 2 Doubleword (32-bit) values */ uint32_t ud[2]; /* 2 Unsigned Doubleword */ int16_t w[4]; /* 4 Word (16-bit) values */ uint16_t uw[4]; /* 4 Unsigned Word */ int8_t b[8]; /* 8 Byte (8-bit) values */ uint8_t ub[8]; /* 8 Unsigned Byte */ float s[2]; /* Single-precision (32-bit) value */ } /*ATTR_ALIGN(8)*/ mmx_t; /* On an 8-byte (64-bit) boundary */ // sunqueen modify start #if 0 #define mmx_i2r(op,imm,reg) \ __asm__ __volatile__ (#op " %0, %%" #reg \ : /* nothing */ \ : "i" (imm) \ : #reg) #endif #define mmx_i2r(op,imm,reg) __asm op reg, imm #if 0 #define mmx_m2r(op,mem,reg) \ __asm__ __volatile__ (#op " %0, %%" #reg \ : /* nothing */ \ : "m" (mem) \ : #reg) #endif #define mmx_m2r(op,mem,reg) __asm op reg, mem #if 0 #define mmx_r2m(op,reg,mem) \ __asm__ __volatile__ (#op " %%" #reg ", %0" \ : "=m" (mem) \ : /* nothing */ \ : "memory") #endif #define mmx_r2m(op,reg,mem) __asm op mem, reg #if 0 #define mmx_r2r(op,regs,regd) \ __asm__ __volatile__ (#op " %%" #regs ", %%" #regd ::: #regd) #endif #define mmx_r2r(op,regs,regd) __asm op regd, regs //#define emms() __asm__ __volatile__ ("emms") #define emms() __asm emms // sunqueen modify end #define movd_m2r(var,reg) mmx_m2r (movd, var, reg) #define movd_r2m(reg,var) mmx_r2m (movd, reg, var) #define movd_r2r(regs,regd) mmx_r2r (movd, regs, regd) #define movq_m2r(var,reg) mmx_m2r (movq, var, reg) #define movq_r2m(reg,var) mmx_r2m (movq, reg, var) #define movq_r2r(regs,regd) mmx_r2r (movq, regs, regd) #define packssdw_m2r(var,reg) mmx_m2r (packssdw, var, reg) #define packssdw_r2r(regs,regd) mmx_r2r (packssdw, regs, regd) #define packsswb_m2r(var,reg) mmx_m2r (packsswb, var, reg) #define packsswb_r2r(regs,regd) mmx_r2r (packsswb, regs, regd) #define packuswb_m2r(var,reg) mmx_m2r (packuswb, var, reg) #define packuswb_r2r(regs,regd) mmx_r2r (packuswb, regs, regd) #define paddb_m2r(var,reg) mmx_m2r (paddb, var, reg) #define paddb_r2r(regs,regd) mmx_r2r (paddb, regs, regd) #define paddd_m2r(var,reg) mmx_m2r (paddd, var, reg) #define paddd_r2r(regs,regd) mmx_r2r (paddd, regs, regd) #define paddw_m2r(var,reg) mmx_m2r (paddw, var, reg) #define paddw_r2r(regs,regd) mmx_r2r (paddw, regs, regd) #define paddsb_m2r(var,reg) mmx_m2r (paddsb, var, reg) #define paddsb_r2r(regs,regd) mmx_r2r (paddsb, regs, regd) #define paddsw_m2r(var,reg) mmx_m2r (paddsw, var, reg) #define paddsw_r2r(regs,regd) mmx_r2r (paddsw, regs, regd) #define paddusb_m2r(var,reg) mmx_m2r (paddusb, var, reg) #define paddusb_r2r(regs,regd) mmx_r2r (paddusb, regs, regd) #define paddusw_m2r(var,reg) mmx_m2r (paddusw, var, reg) #define paddusw_r2r(regs,regd) mmx_r2r (paddusw, regs, regd) #define pand_m2r(var,reg) mmx_m2r (pand, var, reg) #define pand_r2r(regs,regd) mmx_r2r (pand, regs, regd) #define pandn_m2r(var,reg) mmx_m2r (pandn, var, reg) #define pandn_r2r(regs,regd) mmx_r2r (pandn, regs, regd) #define pcmpeqb_m2r(var,reg) mmx_m2r (pcmpeqb, var, reg) #define pcmpeqb_r2r(regs,regd) mmx_r2r (pcmpeqb, regs, regd) #define pcmpeqd_m2r(var,reg) mmx_m2r (pcmpeqd, var, reg) #define pcmpeqd_r2r(regs,regd) mmx_r2r (pcmpeqd, regs, regd) #define pcmpeqw_m2r(var,reg) mmx_m2r (pcmpeqw, var, reg) #define pcmpeqw_r2r(regs,regd) mmx_r2r (pcmpeqw, regs, regd) #define pcmpgtb_m2r(var,reg) mmx_m2r (pcmpgtb, var, reg) #define pcmpgtb_r2r(regs,regd) mmx_r2r (pcmpgtb, regs, regd) #define pcmpgtd_m2r(var,reg) mmx_m2r (pcmpgtd, var, reg) #define pcmpgtd_r2r(regs,regd) mmx_r2r (pcmpgtd, regs, regd) #define pcmpgtw_m2r(var,reg) mmx_m2r (pcmpgtw, var, reg) #define pcmpgtw_r2r(regs,regd) mmx_r2r (pcmpgtw, regs, regd) #define pmaddwd_m2r(var,reg) mmx_m2r (pmaddwd, var, reg) #define pmaddwd_r2r(regs,regd) mmx_r2r (pmaddwd, regs, regd) #define pmulhw_m2r(var,reg) mmx_m2r (pmulhw, var, reg) #define pmulhw_r2r(regs,regd) mmx_r2r (pmulhw, regs, regd) #define pmullw_m2r(var,reg) mmx_m2r (pmullw, var, reg) #define pmullw_r2r(regs,regd) mmx_r2r (pmullw, regs, regd) #define por_m2r(var,reg) mmx_m2r (por, var, reg) #define por_r2r(regs,regd) mmx_r2r (por, regs, regd) #define pslld_i2r(imm,reg) mmx_i2r (pslld, imm, reg) #define pslld_m2r(var,reg) mmx_m2r (pslld, var, reg) #define pslld_r2r(regs,regd) mmx_r2r (pslld, regs, regd) #define psllq_i2r(imm,reg) mmx_i2r (psllq, imm, reg) #define psllq_m2r(var,reg) mmx_m2r (psllq, var, reg) #define psllq_r2r(regs,regd) mmx_r2r (psllq, regs, regd) #define psllw_i2r(imm,reg) mmx_i2r (psllw, imm, reg) #define psllw_m2r(var,reg) mmx_m2r (psllw, var, reg) #define psllw_r2r(regs,regd) mmx_r2r (psllw, regs, regd) #define psrad_i2r(imm,reg) mmx_i2r (psrad, imm, reg) #define psrad_m2r(var,reg) mmx_m2r (psrad, var, reg) #define psrad_r2r(regs,regd) mmx_r2r (psrad, regs, regd) #define psraw_i2r(imm,reg) mmx_i2r (psraw, imm, reg) #define psraw_m2r(var,reg) mmx_m2r (psraw, var, reg) #define psraw_r2r(regs,regd) mmx_r2r (psraw, regs, regd) #define psrld_i2r(imm,reg) mmx_i2r (psrld, imm, reg) #define psrld_m2r(var,reg) mmx_m2r (psrld, var, reg) #define psrld_r2r(regs,regd) mmx_r2r (psrld, regs, regd) #define psrlq_i2r(imm,reg) mmx_i2r (psrlq, imm, reg) #define psrlq_m2r(var,reg) mmx_m2r (psrlq, var, reg) #define psrlq_r2r(regs,regd) mmx_r2r (psrlq, regs, regd) #define psrlw_i2r(imm,reg) mmx_i2r (psrlw, imm, reg) #define psrlw_m2r(var,reg) mmx_m2r (psrlw, var, reg) #define psrlw_r2r(regs,regd) mmx_r2r (psrlw, regs, regd) #define psubb_m2r(var,reg) mmx_m2r (psubb, var, reg) #define psubb_r2r(regs,regd) mmx_r2r (psubb, regs, regd) #define psubd_m2r(var,reg) mmx_m2r (psubd, var, reg) #define psubd_r2r(regs,regd) mmx_r2r (psubd, regs, regd) #define psubw_m2r(var,reg) mmx_m2r (psubw, var, reg) #define psubw_r2r(regs,regd) mmx_r2r (psubw, regs, regd) #define psubsb_m2r(var,reg) mmx_m2r (psubsb, var, reg) #define psubsb_r2r(regs,regd) mmx_r2r (psubsb, regs, regd) #define psubsw_m2r(var,reg) mmx_m2r (psubsw, var, reg) #define psubsw_r2r(regs,regd) mmx_r2r (psubsw, regs, regd) #define psubusb_m2r(var,reg) mmx_m2r (psubusb, var, reg) #define psubusb_r2r(regs,regd) mmx_r2r (psubusb, regs, regd) #define psubusw_m2r(var,reg) mmx_m2r (psubusw, var, reg) #define psubusw_r2r(regs,regd) mmx_r2r (psubusw, regs, regd) #define punpckhbw_m2r(var,reg) mmx_m2r (punpckhbw, var, reg) #define punpckhbw_r2r(regs,regd) mmx_r2r (punpckhbw, regs, regd) #define punpckhdq_m2r(var,reg) mmx_m2r (punpckhdq, var, reg) #define punpckhdq_r2r(regs,regd) mmx_r2r (punpckhdq, regs, regd) #define punpckhwd_m2r(var,reg) mmx_m2r (punpckhwd, var, reg) #define punpckhwd_r2r(regs,regd) mmx_r2r (punpckhwd, regs, regd) #define punpcklbw_m2r(var,reg) mmx_m2r (punpcklbw, var, reg) #define punpcklbw_r2r(regs,regd) mmx_r2r (punpcklbw, regs, regd) #define punpckldq_m2r(var,reg) mmx_m2r (punpckldq, var, reg) #define punpckldq_r2r(regs,regd) mmx_r2r (punpckldq, regs, regd) #define punpcklwd_m2r(var,reg) mmx_m2r (punpcklwd, var, reg) #define punpcklwd_r2r(regs,regd) mmx_r2r (punpcklwd, regs, regd) #define pxor_m2r(var,reg) mmx_m2r (pxor, var, reg) #define pxor_r2r(regs,regd) mmx_r2r (pxor, regs, regd) /* 3DNOW extensions */ #define pavgusb_m2r(var,reg) mmx_m2r (pavgusb, var, reg) #define pavgusb_r2r(regs,regd) mmx_r2r (pavgusb, regs, regd) /* AMD MMX extensions - also available in intel SSE */ #define mmx_m2ri(op,mem,reg,imm) \ __asm__ __volatile__ (#op " %1, %0, %%" #reg \ : /* nothing */ \ : "X" (mem), "X" (imm) \ : #reg) #define mmx_r2ri(op,regs,regd,imm) \ __asm__ __volatile__ (#op " %0, %%" #regs ", %%" #regd \ : /* nothing */ \ : "X" (imm) \ : #regd) #define mmx_fetch(mem,hint) \ __asm__ __volatile__ ("prefetch" #hint " %0" \ : /* nothing */ \ : "X" (mem)) #define maskmovq(regs,maskreg) mmx_r2ri (maskmovq, regs, maskreg) #define movntq_r2m(mmreg,var) mmx_r2m (movntq, mmreg, var) #define pavgb_m2r(var,reg) mmx_m2r (pavgb, var, reg) #define pavgb_r2r(regs,regd) mmx_r2r (pavgb, regs, regd) #define pavgw_m2r(var,reg) mmx_m2r (pavgw, var, reg) #define pavgw_r2r(regs,regd) mmx_r2r (pavgw, regs, regd) #define pextrw_r2r(mmreg,reg,imm) mmx_r2ri (pextrw, mmreg, reg, imm) #define pinsrw_r2r(reg,mmreg,imm) mmx_r2ri (pinsrw, reg, mmreg, imm) #define pmaxsw_m2r(var,reg) mmx_m2r (pmaxsw, var, reg) #define pmaxsw_r2r(regs,regd) mmx_r2r (pmaxsw, regs, regd) #define pmaxub_m2r(var,reg) mmx_m2r (pmaxub, var, reg) #define pmaxub_r2r(regs,regd) mmx_r2r (pmaxub, regs, regd) #define pminsw_m2r(var,reg) mmx_m2r (pminsw, var, reg) #define pminsw_r2r(regs,regd) mmx_r2r (pminsw, regs, regd) #define pminub_m2r(var,reg) mmx_m2r (pminub, var, reg) #define pminub_r2r(regs,regd) mmx_r2r (pminub, regs, regd) #define pmovmskb(mmreg,reg) \ __asm__ __volatile__ ("movmskps %" #mmreg ", %" #reg : : : #reg) #define pmulhuw_m2r(var,reg) mmx_m2r (pmulhuw, var, reg) #define pmulhuw_r2r(regs,regd) mmx_r2r (pmulhuw, regs, regd) #define prefetcht0(mem) mmx_fetch (mem, t0) #define prefetcht1(mem) mmx_fetch (mem, t1) #define prefetcht2(mem) mmx_fetch (mem, t2) #define prefetchnta(mem) mmx_fetch (mem, nta) #define psadbw_m2r(var,reg) mmx_m2r (psadbw, var, reg) #define psadbw_r2r(regs,regd) mmx_r2r (psadbw, regs, regd) #define pshufw_m2r(var,reg,imm) mmx_m2ri(pshufw, var, reg, imm) #define pshufw_r2r(regs,regd,imm) mmx_r2ri(pshufw, regs, regd, imm) #define sfence() __asm__ __volatile__ ("sfence\n\t")
sunqueen/vlc-2.2.1.32-2013
modules/video_filter/deinterlace/mmx.h
C
gpl-2.0
11,906
/* Copyright (C) 2008-2016 Vana 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; 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. */ #pragma once #include "common/data/type/card_map_range_info.hpp" #include "common/data/type/morph_chance_info.hpp" #include "common/types.hpp" #include <vector> namespace vana { namespace data { namespace type { struct consume_info { bool auto_consume = false; bool ignore_wdef = false; bool ignore_mdef = false; bool party = false; bool mouse_cancel = true; bool ignore_continent = false; bool ghost = false; bool barrier = false; bool override_traction = false; bool prevent_drown = false; bool prevent_freeze = false; bool meso_up = false; bool drop_up = false; bool party_drop_up = false; uint8_t effect = 0; uint8_t dec_hunger = 0; uint8_t dec_fatigue = 0; uint8_t cp = 0; game_health hp = 0; game_health mp = 0; int16_t hp_rate = 0; int16_t mp_rate = 0; game_stat watk = 0; game_stat matk = 0; game_stat avo = 0; game_stat acc = 0; game_stat wdef = 0; game_stat mdef = 0; game_stat speed = 0; game_stat jump = 0; int16_t fire_resist = 0; int16_t ice_resist = 0; int16_t lightning_resist = 0; int16_t poison_resist = 0; int16_t curse_def = 0; int16_t stun_def = 0; int16_t weakness_def = 0; int16_t darkness_def = 0; int16_t seal_def = 0; int16_t drop_up_item_range = 0; uint16_t chance = 0; game_item_id drop_up_item = 0; game_map_id move_to = 0; game_item_id item_id = 0; int32_t ailment = 0; seconds buff_time = seconds{0}; vector<morph_chance_info> morphs; vector<card_map_range_info> map_ranges; }; } } }
diamondo25/Vana
src/common/data/type/consume_info.hpp
C++
gpl-2.0
2,309
/* (c) 2014 Open Source Geospatial Foundation - all rights reserved * This code is licensed under the GPL 2.0 license, available at the root * application directory. */ package org.geoserver.geofence.services.rest; import org.geoserver.geofence.services.rest.exception.BadRequestRestEx; import org.geoserver.geofence.services.rest.exception.InternalErrorRestEx; import org.geoserver.geofence.services.rest.exception.NotFoundRestEx; import org.geoserver.geofence.services.rest.model.RESTInputRule; import org.geoserver.geofence.services.rest.model.RESTOutputRule; import org.geoserver.geofence.services.rest.model.RESTOutputRuleList; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.cxf.jaxrs.ext.multipart.Multipart; /** * * @author Emanuele Tajariol (etj at geo-solutions.it) */ @Path("/") public interface RESTRuleService { @POST @Path("/") @Produces(MediaType.APPLICATION_XML) Response insert(@Multipart("rule") RESTInputRule rule) throws BadRequestRestEx, NotFoundRestEx; @GET @Path("/id/{id}") @Produces(MediaType.APPLICATION_XML) RESTOutputRule get(@PathParam("id") Long id) throws BadRequestRestEx, NotFoundRestEx; @PUT @Path("/id/{id}") @Produces(MediaType.APPLICATION_XML) void update(@PathParam("id") Long id, @Multipart("rule") RESTInputRule rule) throws BadRequestRestEx, NotFoundRestEx; @DELETE @Path("/id/{id}") @Produces(MediaType.APPLICATION_XML) Response delete(@PathParam("id") Long id) throws BadRequestRestEx, NotFoundRestEx; @GET @Path("/") @Produces(MediaType.APPLICATION_XML) RESTOutputRuleList get( @QueryParam("page") Integer page, @QueryParam("entries") Integer entries, @QueryParam("full")@DefaultValue("false") boolean full, @QueryParam("userName") String userName, @QueryParam("userAny") Boolean userAny, @QueryParam("groupName") String groupName, @QueryParam("groupAny") Boolean groupAny, @QueryParam("instanceId") Long instanceId, @QueryParam("instanceName") String instanceName, @QueryParam("instanceAny") Boolean instanceAny, @QueryParam("service") String serviceName, @QueryParam("serviceAny") Boolean serviceAny, @QueryParam("request") String requestName, @QueryParam("requestAny") Boolean requestAny, @QueryParam("workspace") String workspace, @QueryParam("workspaceAny") Boolean workspaceAny, @QueryParam("layer") String layer, @QueryParam("layerAny") Boolean layerAny ) throws BadRequestRestEx, InternalErrorRestEx; @GET @Path("/count") long count( @QueryParam("userName") String userName, @QueryParam("userAny") Boolean userAny, @QueryParam("groupName") String groupName, @QueryParam("groupAny") Boolean groupAny, @QueryParam("instanceId") Long instanceId, @QueryParam("instanceName") String instanceName, @QueryParam("instanceAny") Boolean instanceAny, @QueryParam("service") String serviceName, @QueryParam("serviceAny") Boolean serviceAny, @QueryParam("request") String requestName, @QueryParam("requestAny") Boolean requestAny, @QueryParam("workspace") String workspace, @QueryParam("workspaceAny") Boolean workspaceAny, @QueryParam("layer") String layer, @QueryParam("layerAny") Boolean layerAny ); }
andrefilo/geofence
src/services/modules/rest/api/src/main/java/org/geoserver/geofence/services/rest/RESTRuleService.java
Java
gpl-2.0
3,780
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8; c-indent-level: 8 -*- */ /* * Copyright (C) 2017, Bastien Nocera <hadess@hadess.net> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, 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 "config.h" #include "ev-archive.h" #include <archive.h> #include <archive_entry.h> #include <unarr/unarr.h> #include <gio/gio.h> #define BUFFER_SIZE (64 * 1024) struct _EvArchive { GObject parent_instance; EvArchiveType type; /* libarchive */ struct archive *libar; struct archive_entry *libar_entry; /* unarr */ ar_stream *unarr_stream; ar_archive *unarr; }; G_DEFINE_TYPE(EvArchive, ev_archive, G_TYPE_OBJECT); static void ev_archive_finalize (GObject *object) { EvArchive *archive = EV_ARCHIVE (object); switch (archive->type) { case EV_ARCHIVE_TYPE_RAR: g_clear_pointer (&archive->unarr, ar_close_archive); g_clear_pointer (&archive->unarr_stream, ar_close); break; case EV_ARCHIVE_TYPE_ZIP: case EV_ARCHIVE_TYPE_7Z: case EV_ARCHIVE_TYPE_TAR: g_clear_pointer (&archive->libar, archive_free); break; default: break; } G_OBJECT_CLASS (ev_archive_parent_class)->finalize (object); } static void ev_archive_class_init (EvArchiveClass *klass) { GObjectClass *object_class = (GObjectClass *) klass; object_class->finalize = ev_archive_finalize; } EvArchive * ev_archive_new (void) { return g_object_new (EV_TYPE_ARCHIVE, NULL); } static void libarchive_set_archive_type (EvArchive *archive, EvArchiveType archive_type) { archive->type = archive_type; archive->libar = archive_read_new (); if (archive_type == EV_ARCHIVE_TYPE_ZIP) archive_read_support_format_zip (archive->libar); else if (archive_type == EV_ARCHIVE_TYPE_7Z) archive_read_support_format_7zip (archive->libar); else if (archive_type == EV_ARCHIVE_TYPE_TAR) archive_read_support_format_tar (archive->libar); } EvArchiveType ev_archive_get_archive_type (EvArchive *archive) { g_return_val_if_fail (EV_IS_ARCHIVE (archive), EV_ARCHIVE_TYPE_NONE); return archive->type; } gboolean ev_archive_set_archive_type (EvArchive *archive, EvArchiveType archive_type) { g_return_val_if_fail (EV_IS_ARCHIVE (archive), FALSE); g_return_val_if_fail (archive->type == EV_ARCHIVE_TYPE_NONE, FALSE); switch (archive_type) { case EV_ARCHIVE_TYPE_RAR: archive->type = archive_type; break; case EV_ARCHIVE_TYPE_ZIP: case EV_ARCHIVE_TYPE_7Z: case EV_ARCHIVE_TYPE_TAR: libarchive_set_archive_type (archive, archive_type); break; default: g_assert_not_reached (); } return TRUE; } gboolean ev_archive_open_filename (EvArchive *archive, const char *path, GError **error) { int r; g_return_val_if_fail (EV_IS_ARCHIVE (archive), FALSE); g_return_val_if_fail (archive->type != EV_ARCHIVE_TYPE_NONE, FALSE); g_return_val_if_fail (path != NULL, FALSE); switch (archive->type) { case EV_ARCHIVE_TYPE_NONE: g_assert_not_reached (); case EV_ARCHIVE_TYPE_RAR: archive->unarr_stream = ar_open_file (path); if (archive->unarr_stream == NULL) { g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED, "Error opening archive"); return FALSE; } archive->unarr = ar_open_rar_archive (archive->unarr_stream); if (archive->unarr == NULL) { g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED, "Error opening RAR archive"); return FALSE; } return TRUE; case EV_ARCHIVE_TYPE_ZIP: case EV_ARCHIVE_TYPE_7Z: case EV_ARCHIVE_TYPE_TAR: r = archive_read_open_filename (archive->libar, path, BUFFER_SIZE); if (r != ARCHIVE_OK) { g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "Error opening archive: %s", archive_error_string (archive->libar)); return FALSE; } return TRUE; } return FALSE; } static gboolean libarchive_read_next_header (EvArchive *archive, GError **error) { while (1) { int r; r = archive_read_next_header (archive->libar, &archive->libar_entry); if (r != ARCHIVE_OK) { if (r != ARCHIVE_EOF) g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "Error reading archive: %s", archive_error_string (archive->libar)); return FALSE; } if (archive_entry_filetype (archive->libar_entry) != AE_IFREG) { g_debug ("Skipping '%s' as it's not a regular file", archive_entry_pathname (archive->libar_entry)); continue; } g_debug ("At header for file '%s'", archive_entry_pathname (archive->libar_entry)); break; } return TRUE; } gboolean ev_archive_read_next_header (EvArchive *archive, GError **error) { g_return_val_if_fail (EV_IS_ARCHIVE (archive), FALSE); g_return_val_if_fail (archive->type != EV_ARCHIVE_TYPE_NONE, FALSE); switch (archive->type) { case EV_ARCHIVE_TYPE_NONE: g_assert_not_reached (); case EV_ARCHIVE_TYPE_RAR: return ar_parse_entry (archive->unarr); case EV_ARCHIVE_TYPE_ZIP: case EV_ARCHIVE_TYPE_7Z: case EV_ARCHIVE_TYPE_TAR: return libarchive_read_next_header (archive, error); } return FALSE; } const char * ev_archive_get_entry_pathname (EvArchive *archive) { g_return_val_if_fail (EV_IS_ARCHIVE (archive), NULL); g_return_val_if_fail (archive->type != EV_ARCHIVE_TYPE_NONE, NULL); switch (archive->type) { case EV_ARCHIVE_TYPE_NONE: g_assert_not_reached (); case EV_ARCHIVE_TYPE_RAR: g_return_val_if_fail (archive->unarr != NULL, NULL); return ar_entry_get_name (archive->unarr); case EV_ARCHIVE_TYPE_ZIP: case EV_ARCHIVE_TYPE_7Z: case EV_ARCHIVE_TYPE_TAR: g_return_val_if_fail (archive->libar_entry != NULL, NULL); return archive_entry_pathname (archive->libar_entry); } return NULL; } gint64 ev_archive_get_entry_size (EvArchive *archive) { g_return_val_if_fail (EV_IS_ARCHIVE (archive), -1); g_return_val_if_fail (archive->type != EV_ARCHIVE_TYPE_NONE, -1); switch (archive->type) { case EV_ARCHIVE_TYPE_RAR: g_return_val_if_fail (archive->unarr != NULL, -1); return ar_entry_get_size (archive->unarr); case EV_ARCHIVE_TYPE_NONE: g_assert_not_reached (); case EV_ARCHIVE_TYPE_ZIP: case EV_ARCHIVE_TYPE_7Z: case EV_ARCHIVE_TYPE_TAR: g_return_val_if_fail (archive->libar_entry != NULL, -1); return archive_entry_size (archive->libar_entry); } return -1; } gboolean ev_archive_get_entry_is_encrypted (EvArchive *archive) { g_return_val_if_fail (EV_IS_ARCHIVE (archive), FALSE); g_return_val_if_fail (archive->type != EV_ARCHIVE_TYPE_NONE, FALSE); switch (archive->type) { case EV_ARCHIVE_TYPE_RAR: g_return_val_if_fail (archive->unarr != NULL, FALSE); /* password-protected RAR is not even detected right now */ return FALSE; case EV_ARCHIVE_TYPE_NONE: g_assert_not_reached (); case EV_ARCHIVE_TYPE_ZIP: case EV_ARCHIVE_TYPE_7Z: case EV_ARCHIVE_TYPE_TAR: g_return_val_if_fail (archive->libar_entry != NULL, -1); return archive_entry_is_encrypted (archive->libar_entry); } return FALSE; } gssize ev_archive_read_data (EvArchive *archive, void *buf, gsize count, GError **error) { gssize r = -1; g_return_val_if_fail (EV_IS_ARCHIVE (archive), -1); g_return_val_if_fail (archive->type != EV_ARCHIVE_TYPE_NONE, -1); switch (archive->type) { case EV_ARCHIVE_TYPE_RAR: g_return_val_if_fail (archive->unarr != NULL, -1); if (!ar_entry_uncompress (archive->unarr, buf, count)) { g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED, "Failed to decompress RAR data"); return -1; } r = count; break; case EV_ARCHIVE_TYPE_NONE: g_assert_not_reached (); case EV_ARCHIVE_TYPE_ZIP: case EV_ARCHIVE_TYPE_7Z: case EV_ARCHIVE_TYPE_TAR: g_return_val_if_fail (archive->libar_entry != NULL, -1); r = archive_read_data (archive->libar, buf, count); if (r < 0) { g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "Failed to decompress data: %s", archive_error_string (archive->libar)); } break; } return r; } void ev_archive_reset (EvArchive *archive) { g_return_if_fail (EV_IS_ARCHIVE (archive)); g_return_if_fail (archive->type != EV_ARCHIVE_TYPE_NONE); switch (archive->type) { case EV_ARCHIVE_TYPE_RAR: g_clear_pointer (&archive->unarr, ar_close_archive); g_clear_pointer (&archive->unarr_stream, ar_close); break; case EV_ARCHIVE_TYPE_ZIP: case EV_ARCHIVE_TYPE_7Z: case EV_ARCHIVE_TYPE_TAR: g_clear_pointer (&archive->libar, archive_free); libarchive_set_archive_type (archive, archive->type); break; default: g_assert_not_reached (); } } static void ev_archive_init (EvArchive *archive) { }
gpoo/evince
backend/comics/ev-archive.c
C
gpl-2.0
9,120
/* * This file is part of DrFTPD, Distributed FTP Daemon. * * DrFTPD 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. * * DrFTPD 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 DrFTPD; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.drftpd.commands.find.action; import org.drftpd.commandmanager.CommandRequest; import org.drftpd.commandmanager.ImproperUsageException; import org.drftpd.vfs.InodeHandle; /** * @author scitz0 * @version $Id$ */ public class PrintAction implements ActionInterface { @Override public void initialize(String action, String[] args) throws ImproperUsageException { } @Override public String exec(CommandRequest request, InodeHandle inode) { return inode.getPath(); } @Override public boolean execInDirs() { return true; } @Override public boolean execInFiles() { return true; } @Override public boolean failed() { return false; } }
dr3plus/dr3
src/plugins/org.drftpd.commands.find/src/org/drftpd/commands/find/action/PrintAction.java
Java
gpl-2.0
1,432
/****************************************************************************** * Copyright (C) 2010 by Sebastian Doerner <sebastian@sebastian-doerner.de> * * * * 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 CHECKOUTDIALOG_H #define CHECKOUTDIALOG_H #include <kdialog.h> #include <QSet> #include <QString> class KComboBox; class KLineEdit; class QCheckBox; class QGroupBox; class QRadioButton; /** * @brief The dialog for checking out Branches or Tags in Git. */ class CheckoutDialog : public KDialog { Q_OBJECT public: CheckoutDialog(QWidget* parent = 0); /** * Returns the name of the selected tag or branch to be checkout out * @returns The name of the selected tag or branch */ QString checkoutIdentifier() const; /** * @returns True if the user selected a forced checkout, false otherwise. */ bool force() const; /** * @returns The user selected name of the new branch, if a new branch is to be * created, empty String otherwise. */ QString newBranchName() const; private slots: void branchRadioButtonToggled(bool checked); void newBranchCheckBoxStateToggled(int state); /** * Checks whether the values of all relevant widgets are valid. * Enables or disables the OK button and sets tooltips accordingly. */ void setOkButtonState(); void noteUserEditedNewBranchName(); /** * Inserts a default name for the new branch into m_newBranchName unless the user * has already edited the content. * @param baseBranchName The base name to derive the new name of. */ void setDefaultNewBranchName(const QString & baseBranchName); private: inline void setLineEditErrorModeActive(bool active); private: ///@brief true if the user has manually edited the branchName, false otherwise bool m_userEditedNewBranchName; QSet<QString> m_branchNames; QPalette m_errorColors; QGroupBox * m_branchSelectGroupBox; QRadioButton * m_branchRadioButton; KComboBox * m_branchComboBox; KComboBox * m_tagComboBox; QCheckBox * m_newBranchCheckBox; KLineEdit * m_newBranchName; QCheckBox * m_forceCheckBox; }; #endif // CHECKOUTDIALOG_H
vishesh/dolphin-plugins
git/checkoutdialog.h
C
gpl-2.0
3,446
package org.checkerframework.mavenplugin; import org.apache.maven.plugin.CompilationFailureException; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.logging.Log; import org.codehaus.plexus.compiler.CompilerError; import org.codehaus.plexus.util.cli.CommandLineException; import org.codehaus.plexus.util.cli.CommandLineUtils; import org.codehaus.plexus.util.cli.Commandline; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * A CommandLineExecutor that formats warning and error messages in a similar style to the maven-compiler-plugin. * @see org.checkerframework.mavenplugin.CommandLineExceutor */ public class MavenIOExecutor implements CommandLineExceutor { private final String pathToExecutable; public MavenIOExecutor(final String pathToExecutable) { this.pathToExecutable = pathToExecutable; } /** * {@inheritDoc} */ public void executeCommandLine(final Commandline cl, final Log log, final boolean failOnError) throws MojoExecutionException, MojoFailureException { CommandLineUtils.StringStreamConsumer out = new CommandLineUtils.StringStreamConsumer(); CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer(); log.debug("command line: " + Arrays.toString(cl.getCommandline())); // Executing the command final int exitCode; try { exitCode = CommandLineUtils.executeCommandLine(cl, out, err); } catch (CommandLineException e) { throw new MojoExecutionException("Unable to execute the Checker Framework, executable: " + pathToExecutable + ", command line: " + Arrays.toString(cl.getCommandline()), e); } // Parsing the messages from the compiler final List<CompilerError> messages; try { messages = JavacErrorMessagesParser.parseMessages(err.getOutput()); } catch (RuntimeException e) { throw new MojoExecutionException("Unable to parse messages.", e); } // Sanity check - if the exit code is non-zero, there should be some messages if (exitCode != 0 && messages.isEmpty()) { throw new MojoExecutionException("Exit code from the compiler was not zero (" + exitCode + "), but no messages reported. Error stream content: " + err.getOutput() + " command line: " + Arrays.toString(cl.getCommandline())); } if (messages.isEmpty()) { log.info("No errors found by the processor(s)."); } else { if (failOnError) { final List<CompilerError> warnings = new ArrayList<CompilerError>(); final List<CompilerError> errors = new ArrayList<CompilerError>(); for (final CompilerError message : messages) { if (message.isError()) { errors.add(message); } else { warnings.add(message); } } if (!warnings.isEmpty()) { logErrors(warnings, "warning", true, log); } logErrors(errors, "error", false, log); throw new MojoFailureException(null, "Errors found by the processor(s)", CompilationFailureException.longMessage(errors)); } else { log.info("Run with debug logging in order to view the compiler command line"); for (final CompilerError compilerError : messages) { log.warn(compilerError.toString()); } } } } /** * Print a header with the given label and print all errors similar to the style * maven itself uses * @param errors Errors to print * @param label The label (usually ERRORS or WARNINGS) to head the error list * @param log The log to which the messages are printed */ private static final void logErrors(final List<CompilerError> errors, final String label, boolean warn, final Log log) { log.info("-------------------------------------------------------------"); log.warn("CHECKER FRAMEWORK " + label.toUpperCase() + ": "); log.info("-------------------------------------------------------------"); for (final CompilerError error : errors) { final String msg = error.toString().trim(); if (warn) { log.warn(msg); } else { log.error(msg); } } final String labelLc = label.toLowerCase() + ((errors.size() == 1) ? "" : "s"); log.info(errors.size() + " " + labelLc); log.info("-------------------------------------------------------------"); } }
atomicknight/checker-framework
maven-plugin/src/main/java/org/checkerframework/mavenplugin/MavenIOExecutor.java
Java
gpl-2.0
4,931
// -*- mode: cpp; mode: fold -*- // Description /*{{{*/ // $Id: debversion.cc,v 1.8 2003/09/10 23:39:49 mdz Exp $ /* ###################################################################### Debian Version - Versioning system for Debian This implements the standard Debian versioning system. ##################################################################### */ /*}}}*/ // Include Files /*{{{*/ #define APT_COMPATIBILITY 986 #include <apt-pkg/debversion.h> #include <apt-pkg/pkgcache.h> #include <stdlib.h> #include <ctype.h> /*}}}*/ debVersioningSystem debVS; // debVS::debVersioningSystem - Constructor /*{{{*/ // --------------------------------------------------------------------- /* */ debVersioningSystem::debVersioningSystem() { Label = "Standard .deb"; } /*}}}*/ // debVS::CmpFragment - Compare versions /*{{{*/ // --------------------------------------------------------------------- /* This compares a fragment of the version. This is a slightly adapted version of what dpkg uses. */ #define order(x) ((x) == '~' ? -1 \ : isdigit((x)) ? 0 \ : !(x) ? 0 \ : isalpha((x)) ? (x) \ : (x) + 256) int debVersioningSystem::CmpFragment(const char *A,const char *AEnd, const char *B,const char *BEnd) { if (A >= AEnd && B >= BEnd) return 0; if (A >= AEnd) { if (*B == '~') return 1; return -1; } if (B >= BEnd) { if (*A == '~') return -1; return 1; } /* Iterate over the whole string What this does is to split the whole string into groups of numeric and non numeric portions. For instance: a67bhgs89 Has 4 portions 'a', '67', 'bhgs', '89'. A more normal: 2.7.2-linux-1 Has '2', '.', '7', '.' ,'-linux-','1' */ const char *lhs = A; const char *rhs = B; while (lhs != AEnd && rhs != BEnd) { int first_diff = 0; while (lhs != AEnd && rhs != BEnd && (!isdigit(*lhs) || !isdigit(*rhs))) { int vc = order(*lhs); int rc = order(*rhs); if (vc != rc) return vc - rc; lhs++; rhs++; } while (*lhs == '0') lhs++; while (*rhs == '0') rhs++; while (isdigit(*lhs) && isdigit(*rhs)) { if (!first_diff) first_diff = *lhs - *rhs; lhs++; rhs++; } if (isdigit(*lhs)) return 1; if (isdigit(*rhs)) return -1; if (first_diff) return first_diff; } // The strings must be equal if (lhs == AEnd && rhs == BEnd) return 0; // lhs is shorter if (lhs == AEnd) { if (*rhs == '~') return 1; return -1; } // rhs is shorter if (rhs == BEnd) { if (*lhs == '~') return -1; return 1; } // Shouldnt happen return 1; } /*}}}*/ // debVS::CmpVersion - Comparison for versions /*{{{*/ // --------------------------------------------------------------------- /* This fragments the version into E:V-R triples and compares each portion separately. */ int debVersioningSystem::DoCmpVersion(const char *A,const char *AEnd, const char *B,const char *BEnd) { // Strip off the epoch and compare it const char *lhs = A; const char *rhs = B; for (;lhs != AEnd && *lhs != ':'; lhs++); for (;rhs != BEnd && *rhs != ':'; rhs++); if (lhs == AEnd) lhs = A; if (rhs == BEnd) rhs = B; // Special case: a zero epoch is the same as no epoch, // so remove it. if (lhs != A) { for (; *A == '0'; ++A); if (A == lhs) { ++A; ++lhs; } } if (rhs != B) { for (; *B == '0'; ++B); if (B == rhs) { ++B; ++rhs; } } // Compare the epoch int Res = CmpFragment(A,lhs,B,rhs); if (Res != 0) return Res; // Skip the : if (lhs != A) lhs++; if (rhs != B) rhs++; // Find the last - const char *dlhs = AEnd-1; const char *drhs = BEnd-1; for (;dlhs > lhs && *dlhs != '-'; dlhs--); for (;drhs > rhs && *drhs != '-'; drhs--); if (dlhs == lhs) dlhs = AEnd; if (drhs == rhs) drhs = BEnd; // Compare the main version Res = CmpFragment(lhs,dlhs,rhs,drhs); if (Res != 0) return Res; // Skip the - if (dlhs != lhs) dlhs++; if (drhs != rhs) drhs++; return CmpFragment(dlhs,AEnd,drhs,BEnd); } /*}}}*/ // debVS::CheckDep - Check a single dependency /*{{{*/ // --------------------------------------------------------------------- /* This simply preforms the version comparison and switch based on operator. If DepVer is 0 then we are comparing against a provides with no version. */ bool debVersioningSystem::CheckDep(const char *PkgVer, int Op,const char *DepVer) { if (DepVer == 0 || DepVer[0] == 0) return true; if (PkgVer == 0 || PkgVer[0] == 0) return false; // Perform the actual comparision. int Res = CmpVersion(PkgVer,DepVer); switch (Op & 0x0F) { case pkgCache::Dep::LessEq: if (Res <= 0) return true; break; case pkgCache::Dep::GreaterEq: if (Res >= 0) return true; break; case pkgCache::Dep::Less: if (Res < 0) return true; break; case pkgCache::Dep::Greater: if (Res > 0) return true; break; case pkgCache::Dep::Equals: if (Res == 0) return true; break; case pkgCache::Dep::NotEquals: if (Res != 0) return true; break; } return false; } /*}}}*/ // debVS::UpstreamVersion - Return the upstream version string /*{{{*/ // --------------------------------------------------------------------- /* This strips all the debian specific information from the version number */ string debVersioningSystem::UpstreamVersion(const char *Ver) { // Strip off the bit before the first colon const char *I = Ver; for (; *I != 0 && *I != ':'; I++); if (*I == ':') Ver = I + 1; // Chop off the trailing - I = Ver; unsigned Last = strlen(Ver); for (; *I != 0; I++) if (*I == '-') Last = I - Ver; return string(Ver,Last); } /*}}}*/
nexgenta/apt
apt-pkg/deb/debversion.cc
C++
gpl-2.0
6,201
/********************************************************************** Android-Freeciv - Copyright (C) 2010 - C Vaughn 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. ***********************************************************************/ #define BUG_URL "fixme" #define META_URL "fixme" #define DEFAULT_SOCK_PORT 9999 #define MAJOR_VERSION 2 #define MINOR_VERSION 1 #define PATCH_VERSION 2 #define VERSION_LABEL "forandroid" #define VERSION_STRING "forandroid" #define FC_CONFIG_H 1 #define NETWORK_CAPSTRING_MANDATORY "+2.2b" #define NETWORK_CAPSTRING_OPTIONAL "trade_illness" #define WIKI_URL "fixme"
teknoa/freeciv-android
jni/freeciv/include/config.h
C
gpl-2.0
1,069
#ifndef _ASM_ARM_FUTEX_H #define _ASM_ARM_FUTEX_H #ifdef __KERNEL__ #include <linux/futex.h> #include <linux/uaccess.h> #include <asm/errno.h> #define __futex_atomic_ex_table(err_reg) \ "3:\n" \ " .pushsection __ex_table,\"a\"\n" \ " .align 3\n" \ " .long 1b, 4f, 2b, 4f\n" \ " .popsection\n" \ " .pushsection .fixup,\"ax\"\n" \ "4: mov %0, " err_reg "\n" \ " b 3b\n" \ " .popsection" #ifdef CONFIG_SMP #define __futex_atomic_op(insn, ret, oldval, tmp, uaddr, oparg) \ smp_mb(); \ __asm__ __volatile__( \ "1: ldrex %1, [%3]\n" \ " " insn "\n" \ "2: strex %2, %0, [%3]\n" \ " teq %2, #0\n" \ " bne 1b\n" \ " mov %0, #0\n" \ __futex_atomic_ex_table("%5") \ : "=&r" (ret), "=&r" (oldval), "=&r" (tmp) \ : "r" (uaddr), "r" (oparg), "Ir" (-EFAULT) \ : "cc", "memory") static inline int futex_atomic_cmpxchg_inatomic(u32 *uval, u32 __user *uaddr, u32 oldval, u32 newval) { int ret; u32 val; if (!access_ok(VERIFY_WRITE, uaddr, sizeof(u32))) return -EFAULT; smp_mb(); __asm__ __volatile__("@futex_atomic_cmpxchg_inatomic\n" "1: ldrex %1, [%4]\n" " teq %1, %2\n" " ite eq @ explicit IT needed for the 2b label\n" "2: strexeq %0, %3, [%4]\n" " movne %0, #0\n" " teq %0, #0\n" " bne 1b\n" __futex_atomic_ex_table("%5") : "=&r" (ret), "=&r" (val) : "r" (oldval), "r" (newval), "r" (uaddr), "Ir" (-EFAULT) : "cc", "memory"); smp_mb(); *uval = val; return ret; } #else /* !SMP, we can work around lack of atomic ops by disabling preemption */ #include <linux/preempt.h> #include <asm/domain.h> #define __futex_atomic_op(insn, ret, oldval, tmp, uaddr, oparg) \ __asm__ __volatile__( \ "1: " TUSER(ldr) " %1, [%3]\n" \ " " insn "\n" \ "2: " TUSER(str) " %0, [%3]\n" \ " mov %0, #0\n" \ __futex_atomic_ex_table("%5") \ : "=&r" (ret), "=&r" (oldval), "=&r" (tmp) \ : "r" (uaddr), "r" (oparg), "Ir" (-EFAULT) \ : "cc", "memory") static inline int futex_atomic_cmpxchg_inatomic(u32 *uval, u32 __user *uaddr, u32 oldval, u32 newval) { int ret = 0; u32 val; if (!access_ok(VERIFY_WRITE, uaddr, sizeof(u32))) return -EFAULT; __asm__ __volatile__("@futex_atomic_cmpxchg_inatomic\n" "1: " TUSER(ldr) " %1, [%4]\n" " teq %1, %2\n" " it eq @ explicit IT needed for the 2b label\n" "2: " TUSER(streq) " %3, [%4]\n" __futex_atomic_ex_table("%5") : "+r" (ret), "=&r" (val) : "r" (oldval), "r" (newval), "r" (uaddr), "Ir" (-EFAULT) : "cc", "memory"); *uval = val; return ret; } #endif /* !SMP */ static inline int futex_atomic_op_inuser (int encoded_op, u32 __user *uaddr) { int op = (encoded_op >> 28) & 7; int cmp = (encoded_op >> 24) & 15; int oparg = (encoded_op << 8) >> 20; int cmparg = (encoded_op << 20) >> 20; int oldval = 0, ret, tmp; if (encoded_op & (FUTEX_OP_OPARG_SHIFT << 28)) oparg = 1 << oparg; if (!access_ok(VERIFY_WRITE, uaddr, sizeof(u32))) return -EFAULT; pagefault_disable(); /* implies preempt_disable() */ switch (op) { case FUTEX_OP_SET: __futex_atomic_op("mov %0, %4", ret, oldval, tmp, uaddr, oparg); break; case FUTEX_OP_ADD: __futex_atomic_op("add %0, %1, %4", ret, oldval, tmp, uaddr, oparg); break; case FUTEX_OP_OR: __futex_atomic_op("orr %0, %1, %4", ret, oldval, tmp, uaddr, oparg); break; case FUTEX_OP_ANDN: __futex_atomic_op("and %0, %1, %4", ret, oldval, tmp, uaddr, ~oparg); break; case FUTEX_OP_XOR: __futex_atomic_op("eor %0, %1, %4", ret, oldval, tmp, uaddr, oparg); break; default: ret = -ENOSYS; } pagefault_enable(); /* subsumes preempt_enable() */ if (!ret) { switch (cmp) { case FUTEX_OP_CMP_EQ: ret = (oldval == cmparg); break; case FUTEX_OP_CMP_NE: ret = (oldval != cmparg); break; case FUTEX_OP_CMP_LT: ret = (oldval < cmparg); break; case FUTEX_OP_CMP_GE: ret = (oldval >= cmparg); break; case FUTEX_OP_CMP_LE: ret = (oldval <= cmparg); break; case FUTEX_OP_CMP_GT: ret = (oldval > cmparg); break; default: ret = -ENOSYS; } } return ret; } #endif /* __KERNEL__ */ #endif /* _ASM_ARM_FUTEX_H */
tellapart/ubuntu-precise
arch/arm/include/asm/futex.h
C
gpl-2.0
4,071
#include "gp2xsdk.h" #include "burner.h" #include "config.h" #include <bcm_host.h> #include <SDL.h> #include <assert.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <glib.h> #include <EGL/egl.h> #include <EGL/eglext.h> static SDL_Window *sdlscreen = NULL; void logoutput(const char *text, ...); unsigned short *VideoBuffer = NULL; SDL_Joystick *joys[4]; char joyCount = 0; extern CFG_OPTIONS config_options; extern bool bShowFPS; static int surface_width; static int surface_height; static GKeyFile *gkeyfile = 0; static void open_config_file(void) { GError *error = NULL; gkeyfile = g_key_file_new(); if (!(int) g_key_file_load_from_file(gkeyfile, config_options.configfile, G_KEY_FILE_NONE, &error)) { gkeyfile = 0; } } static void close_config_file(void) { if (gkeyfile) g_key_file_free(gkeyfile); } static int get_integer_conf(const char *section, const char *option, int defval) { GError *error = NULL; int tempint; if (!gkeyfile) return defval; tempint = g_key_file_get_integer(gkeyfile, section, option, &error); if (!error) return tempint; else return defval; } unsigned char joy_buttons[4][32]; int joy_axes[4][8]; int joy_hats[4]; int joy_indexes[4]; int joyaxis_LR_1, joyaxis_UD_1; int joyaxis_LR_2, joyaxis_UD_2; int joyaxis_LR_3, joyaxis_UD_3; int joyaxis_LR_4, joyaxis_UD_4; #define NUMKEYS 256 static Uint16 pi_key[NUMKEYS]; static Uint16 pi_joy[4][NUMKEYS]; static Uint16 pi_specials[NUMKEYS]; void pi_initialize_input() { memset(joy_buttons, 0, 32 * 4); memset(joy_axes, 0, 8 * 4 * sizeof(int)); memset(joy_hats, 0, 4 * sizeof(int)); memset(pi_key, 0, NUMKEYS * 2); memset(pi_joy, 0, NUMKEYS * 2 * 4); //Open config file for reading below open_config_file(); //Configure keys from config file or defaults pi_key[A_1] = get_integer_conf("Keyboard", "A_1", RPI_KEY_A); pi_key[B_1] = get_integer_conf("Keyboard", "B_1", RPI_KEY_B); pi_key[X_1] = get_integer_conf("Keyboard", "X_1", RPI_KEY_X); pi_key[Y_1] = get_integer_conf("Keyboard", "Y_1", RPI_KEY_Y); pi_key[L_1] = get_integer_conf("Keyboard", "L_1", RPI_KEY_L); pi_key[R_1] = get_integer_conf("Keyboard", "R_1", RPI_KEY_R); pi_key[START_1] = get_integer_conf("Keyboard", "START_1", RPI_KEY_START); pi_key[SELECT_1] = get_integer_conf("Keyboard", "SELECT_1", RPI_KEY_SELECT); pi_key[LEFT_1] = get_integer_conf("Keyboard", "LEFT_1", RPI_KEY_LEFT); pi_key[RIGHT_1] = get_integer_conf("Keyboard", "RIGHT_1", RPI_KEY_RIGHT); pi_key[UP_1] = get_integer_conf("Keyboard", "UP_1", RPI_KEY_UP); pi_key[DOWN_1] = get_integer_conf("Keyboard", "DOWN_1", RPI_KEY_DOWN); pi_key[A_2] = get_integer_conf("Keyboard", "A_2", RPI_KEY_A_2); pi_key[B_2] = get_integer_conf("Keyboard", "B_2", RPI_KEY_B_2); pi_key[X_2] = get_integer_conf("Keyboard", "X_2", RPI_KEY_X_2); pi_key[Y_2] = get_integer_conf("Keyboard", "Y_2", RPI_KEY_Y_2); pi_key[L_2] = get_integer_conf("Keyboard", "L_2", RPI_KEY_L_2); pi_key[R_2] = get_integer_conf("Keyboard", "R_2", RPI_KEY_R_2); pi_key[START_2] = get_integer_conf("Keyboard", "START_2", RPI_KEY_START_2); pi_key[SELECT_2] = get_integer_conf("Keyboard", "SELECT_2", RPI_KEY_SELECT_2); pi_key[LEFT_2] = get_integer_conf("Keyboard", "LEFT_2", RPI_KEY_LEFT_2); pi_key[RIGHT_2] = get_integer_conf("Keyboard", "RIGHT_2", RPI_KEY_RIGHT_2); pi_key[UP_2] = get_integer_conf("Keyboard", "UP_2", RPI_KEY_UP_2); pi_key[DOWN_2] = get_integer_conf("Keyboard", "DOWN_2", RPI_KEY_DOWN_2); pi_key[A_2] = get_integer_conf("Keyboard", "A_2", RPI_KEY_A_2); pi_key[B_2] = get_integer_conf("Keyboard", "B_2", RPI_KEY_B_2); pi_key[X_2] = get_integer_conf("Keyboard", "X_2", RPI_KEY_X_2); pi_key[Y_2] = get_integer_conf("Keyboard", "Y_2", RPI_KEY_Y_2); pi_key[L_2] = get_integer_conf("Keyboard", "L_2", RPI_KEY_L_2); pi_key[R_2] = get_integer_conf("Keyboard", "R_2", RPI_KEY_R_2); pi_key[START_2] = get_integer_conf("Keyboard", "START_2", RPI_KEY_START_2); pi_key[SELECT_2] = get_integer_conf("Keyboard", "SELECT_2", RPI_KEY_SELECT_2); pi_key[LEFT_2] = get_integer_conf("Keyboard", "LEFT_2", RPI_KEY_LEFT_2); pi_key[RIGHT_2] = get_integer_conf("Keyboard", "RIGHT_2", RPI_KEY_RIGHT_2); pi_key[UP_2] = get_integer_conf("Keyboard", "UP_2", RPI_KEY_UP_2); pi_key[DOWN_2] = get_integer_conf("Keyboard", "DOWN_2", RPI_KEY_DOWN_2); pi_key[QUIT] = get_integer_conf("Keyboard", "QUIT", RPI_KEY_QUIT); //Configure joysticks from config file or defaults joy_indexes[0] = get_integer_conf("Joystick", "SDLID_1", -1); joy_indexes[1] = get_integer_conf("Joystick", "SDLID_2", -1); joy_indexes[2] = get_integer_conf("Joystick", "SDLID_3", -1); joy_indexes[3] = get_integer_conf("Joystick", "SDLID_4", -1); char configName[10]; for (int player = 0; player < 4; player++) { logoutput("Setting player %d input\n", player + 1); sprintf(configName, "A_%d", player + 1); pi_joy[player][J_A] = get_integer_conf("Joystick", configName, 200); logoutput("Setted J_A : %d\n", pi_joy[player][J_A]); sprintf(configName, "B_%d", player + 1); pi_joy[player][J_B] = get_integer_conf("Joystick", configName, RPI_JOY_B); sprintf(configName, "X_%d", player + 1); pi_joy[player][J_X] = get_integer_conf("Joystick", configName, RPI_JOY_X); sprintf(configName, "Y_%d", player + 1); pi_joy[player][J_Y] = get_integer_conf("Joystick", configName, RPI_JOY_Y); sprintf(configName, "L_%d", player + 1); pi_joy[player][J_L] = get_integer_conf("Joystick", configName, RPI_JOY_L); sprintf(configName, "R_%d", player + 1); pi_joy[player][J_R] = get_integer_conf("Joystick", configName, RPI_JOY_R); sprintf(configName, "UP_%d", player + 1); pi_joy[player][J_UP] = get_integer_conf("Joystick", configName, RPI_JOY_UP); sprintf(configName, "DOWN_%d", player + 1); pi_joy[player][J_DOWN] = get_integer_conf("Joystick", configName, RPI_JOY_DOWN); sprintf(configName, "LEFT_%d", player + 1); pi_joy[player][J_LEFT] = get_integer_conf("Joystick", configName, RPI_JOY_LEFT); sprintf(configName, "RIGHT_%d", player + 1); pi_joy[player][J_RIGHT] = get_integer_conf("Joystick", configName, RPI_JOY_RIGHT); sprintf(configName, "START_%d", player + 1); pi_joy[player][J_START] = get_integer_conf("Joystick", configName, RPI_JOY_START); sprintf(configName, "SELECT_%d", player + 1); pi_joy[player][J_SELECT] = get_integer_conf("Joystick", configName, RPI_JOY_SELECT); sprintf(configName, "JA_LR_%d", player + 1); pi_joy[player][J_AXIS_LR] = get_integer_conf("Joystick", configName, RPI_JOY_AXIS_LR); sprintf(configName, "JA_UD_%d", player + 1); pi_joy[player][J_AXIS_UD] = get_integer_conf("Joystick", configName, RPI_JOY_AXIS_UD); } pi_specials[HOTKEY] = get_integer_conf("Joystick", "HOTKEY", RPI_JOY_HOTKEY); pi_specials[QUIT] = get_integer_conf("Joystick", "QUIT", RPI_JOY_QUIT); pi_specials[ACCEL] = get_integer_conf("Joystick", "ACCEL", RPI_JOY_ACCEL); pi_specials[QLOAD] = get_integer_conf("Joystick", "QLOAD", RPI_JOY_QLOAD); pi_specials[QSAVE] = get_integer_conf("Joystick", "QSAVE", RPI_JOY_QSAVE); // Read joystick axis to use, default to 0 & 1 (keep it for hats...) // joyaxis_LR_1 = get_integer_conf("Joystick", "JA_LR_1", 0); // joyaxis_UD_1 = get_integer_conf("Joystick", "JA_UD_1", 1); // // joyaxis_LR_2 = get_integer_conf("Joystick", "JA_LR_2", 0); // joyaxis_UD_2 = get_integer_conf("Joystick", "JA_UD_2", 1); // // joyaxis_LR_3 = get_integer_conf("Joystick", "JA_LR_3", 0); // joyaxis_UD_3 = get_integer_conf("Joystick", "JA_UD_3", 1); // // joyaxis_LR_4 = get_integer_conf("Joystick", "JA_LR_4", 0); // joyaxis_UD_4 = get_integer_conf("Joystick", "JA_UD_4", 1); close_config_file(); } void pi_parse_config_file(void) { int i = 0; open_config_file(); config_options.display_smooth_stretch = get_integer_conf("Graphics", "DisplaySmoothStretch", 1); config_options.option_display_border = get_integer_conf("Graphics", "DisplayBorder", 0); config_options.display_effect = get_integer_conf("Graphics", "DisplayEffect", 0); config_options.maintain_aspect_ratio = get_integer_conf("Graphics", "MaintainAspectRatio", 1); config_options.rotate = get_integer_conf("Graphics", "RotateScreen", 1); close_config_file(); } void pi_initialize() { pi_initialize_input(); pi_parse_config_file(); init_SDL(); //Initialise display just for the rom loading screen first. pi_setvideo_mode(320, 240); pi_video_flip(); } void pi_terminate(void) { struct stat info; pi_deinit(); deinit_SDL(); exit(0); } // create two resources for 'page flipping' static DISPMANX_RESOURCE_HANDLE_T resource0; static DISPMANX_RESOURCE_HANDLE_T resource1; static DISPMANX_RESOURCE_HANDLE_T resource_bg; // these are used for switching between the buffers //static DISPMANX_RESOURCE_HANDLE_T cur_res; //static DISPMANX_RESOURCE_HANDLE_T prev_res; //static DISPMANX_RESOURCE_HANDLE_T tmp_res; DISPMANX_ELEMENT_HANDLE_T dispman_element; DISPMANX_ELEMENT_HANDLE_T dispman_element_bg; DISPMANX_DISPLAY_HANDLE_T dispman_display; DISPMANX_UPDATE_HANDLE_T dispman_update; void gles2_create(int display_width, int display_height, int bitmap_width, int bitmap_height, int depth); void gles2_destroy(); void gles2_palette_changed(); EGLDisplay display = NULL; EGLSurface surface = NULL; static EGLContext context = NULL; static EGL_DISPMANX_WINDOW_T nativewindow; void exitfunc() { SDL_Quit(); bcm_host_deinit(); } SDL_Joystick *myjoy[4]; int init_SDL(void) { joys[0] = 0; joys[1] = 0; joys[2] = 0; joys[3] = 0; if (SDL_Init(SDL_INIT_JOYSTICK) < 0) { fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError()); return (0); } sdlscreen = SDL_CreateWindow("", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 0, 0, SDL_SWSURFACE); //We handle up to four joysticks if (SDL_NumJoysticks()) { int joystickIndex; int configuratedJoysticks[4] = {-1, -1, -1, -1}; SDL_JoystickEventState(SDL_ENABLE); // Try to configure joysticks from config indexes for (int player = 0; player < 4; player++) { joystickIndex = joy_indexes[player]; if (joystickIndex >= 0) { if (SDL_NumJoysticks() > joystickIndex) { SDL_Joystick *joystick = SDL_JoystickOpen(joystickIndex); //Check for valid joystick, some keyboards //aren't SDL compatible if (joystick) { if (SDL_JoystickNumAxes(myjoy[joystickIndex]) > 6) { SDL_JoystickClose(myjoy[joystickIndex]); joystick = 0; logoutput("Error detected invalid joystick/keyboard\n"); break; } } configuratedJoysticks[player] = joystickIndex; joys[player] = joystick; logoutput("Configured joystick %s at %d for player %d\n", SDL_JoystickNameForIndex(joystickIndex), joystickIndex, player + 1); joyCount++; } } } // Finish configuration for (joystickIndex = 0; joystickIndex < SDL_NumJoysticks(); joystickIndex++) { // If already configured skip bool alreadyConfig = false; for (int player = 0; player < 4; player++) { logoutput("Checking if joystick at %d is configured for player %d : %d\n", joystickIndex, player, configuratedJoysticks[player]); if (configuratedJoysticks[player] == joystickIndex) { alreadyConfig = true; break; } } if (alreadyConfig) continue; SDL_Joystick *joystick = SDL_JoystickOpen(joystickIndex); //Check for valid joystick, some keyboards //aren't SDL compatible if (joystick) { if (SDL_JoystickNumAxes(myjoy[joystickIndex]) > 6) { SDL_JoystickClose(myjoy[joystickIndex]); joystick = 0; logoutput("Error detected invalid joystick/keyboard\n"); break; } // Set the first free joystick for (int player = 0; player < 4; player++) { if (configuratedJoysticks[player] == -1) { joy_indexes[player] = joystickIndex; joys[player] = joystick; configuratedJoysticks[player] = joystickIndex; logoutput("Default Configured joystick at %d for player %d\n", joystickIndex, player + 1); joyCount++; break; } } } } if (joys[0]) logoutput("Found %d joysticks\n", joyCount); } else joyCount = 1; //sq frig number of players for keyboard //joyCount=2; //SDL_EventState(SDL_ACTIVEEVENT, SDL_IGNORE); SDL_EventState(SDL_SYSWMEVENT, SDL_IGNORE); SDL_EventState(SDL_WINDOWEVENT_RESIZED, SDL_IGNORE); SDL_EventState(SDL_USEREVENT, SDL_IGNORE); SDL_ShowCursor(SDL_DISABLE); //Initialise dispmanx bcm_host_init(); //Clean exits, hopefully! atexit(exitfunc); return (1); } void deinit_SDL(void) { if (sdlscreen) { SDL_DestroyWindow(sdlscreen); sdlscreen = NULL; } SDL_Quit(); bcm_host_deinit(); } static uint32_t display_adj_width, display_adj_height; //display size minus border void pi_setvideo_mode(int width, int height) { uint32_t display_width, display_height; uint32_t display_x = 0, display_y = 0; float display_ratio, game_ratio; VC_RECT_T dst_rect; VC_RECT_T src_rect; surface_width = width; surface_height = height; VideoBuffer = (unsigned short *) calloc(1, width * height * 4); // get an EGL display connection display = eglGetDisplay(EGL_DEFAULT_DISPLAY); assert(display != EGL_NO_DISPLAY); // initialize the EGL display connection EGLBoolean result = eglInitialize(display, NULL, NULL); assert(EGL_FALSE != result); // get an appropriate EGL frame buffer configuration EGLint num_config; EGLConfig config; static const EGLint attribute_list[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_NONE }; result = eglChooseConfig(display, attribute_list, &config, 1, &num_config); assert(EGL_FALSE != result); result = eglBindAPI(EGL_OPENGL_ES_API); assert(EGL_FALSE != result); // create an EGL rendering context static const EGLint context_attributes[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; context = eglCreateContext(display, config, EGL_NO_CONTEXT, context_attributes); assert(context != EGL_NO_CONTEXT); // create an EGL window surface int32_t success = graphics_get_display_size(0, &display_width, &display_height); assert(success >= 0); display_adj_width = display_width - (config_options.option_display_border * 2); display_adj_height = display_height - (config_options.option_display_border * 2); if (config_options.display_smooth_stretch) { //We use the dispmanx scaler to smooth stretch the display //so GLES2 doesn't have to handle the performance intensive postprocessing uint32_t sx, sy; // Work out the position and size on the display display_ratio = (float) display_width / (float) display_height; game_ratio = (float) width / (float) height; display_x = sx = display_adj_width; display_y = sy = display_adj_height; if (config_options.maintain_aspect_ratio || game_ratio < 1) { if (game_ratio > display_ratio) sy = (float) display_adj_width / (float) game_ratio; else sx = (float) display_adj_height * (float) game_ratio; } // Centre bitmap on screen display_x = (display_x - sx) / 2; display_y = (display_y - sy) / 2; vc_dispmanx_rect_set(&dst_rect, display_x + config_options.option_display_border, display_y + config_options.option_display_border, sx, sy); } else vc_dispmanx_rect_set(&dst_rect, config_options.option_display_border, config_options.option_display_border, display_adj_width, display_adj_height); if (config_options.display_smooth_stretch) vc_dispmanx_rect_set(&src_rect, 0, 0, width << 16, height << 16); else vc_dispmanx_rect_set(&src_rect, 0, 0, display_adj_width << 16, display_adj_height << 16); dispman_display = vc_dispmanx_display_open(0); dispman_update = vc_dispmanx_update_start(0); dispman_element = vc_dispmanx_element_add(dispman_update, dispman_display, 10, &dst_rect, 0, &src_rect, DISPMANX_PROTECTION_NONE, NULL, NULL, DISPMANX_NO_ROTATE); //Black background surface dimensions vc_dispmanx_rect_set(&dst_rect, 0, 0, display_width, display_height); vc_dispmanx_rect_set(&src_rect, 0, 0, 128 << 16, 128 << 16); //Create a blank background for the whole screen, make sure width is divisible by 32! uint32_t crap; resource_bg = vc_dispmanx_resource_create(VC_IMAGE_RGB565, 128, 128, &crap); dispman_element_bg = vc_dispmanx_element_add(dispman_update, dispman_display, 9, &dst_rect, resource_bg, &src_rect, DISPMANX_PROTECTION_NONE, 0, 0, (DISPMANX_TRANSFORM_T) 0); nativewindow.element = dispman_element; if (config_options.display_smooth_stretch) { nativewindow.width = width; nativewindow.height = height; } else { nativewindow.width = display_adj_width; nativewindow.height = display_adj_height; } vc_dispmanx_update_submit_sync(dispman_update); surface = eglCreateWindowSurface(display, config, &nativewindow, NULL); assert(surface != EGL_NO_SURFACE); // connect the context to the surface result = eglMakeCurrent(display, surface, surface, context); assert(EGL_FALSE != result); //Smooth stretch the display size for GLES2 is the size of the bitmap //otherwise let GLES2 upscale (NEAR) to the size of the display if (config_options.display_smooth_stretch) gles2_create(width, height, width, height, 16); else gles2_create(display_adj_width, display_adj_height, width, height, 16); } void pi_deinit(void) { gles2_destroy(); // Release OpenGL resources eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); eglDestroySurface(display, surface); eglDestroyContext(display, context); eglTerminate(display); dispman_update = vc_dispmanx_update_start(0); vc_dispmanx_element_remove(dispman_update, dispman_element); vc_dispmanx_element_remove(dispman_update, dispman_element_bg); vc_dispmanx_update_submit_sync(dispman_update); vc_dispmanx_resource_delete(resource0); vc_dispmanx_resource_delete(resource1); vc_dispmanx_resource_delete(resource_bg); vc_dispmanx_display_close(dispman_display); if (VideoBuffer) free(VideoBuffer); VideoBuffer = 0; } void gles2_draw(void *screen, int width, int height, int depth); extern EGLDisplay display; extern EGLSurface surface; void pi_video_flip() { // extern int throttle; static int throttle = 1; static int save_throttle = 0; if (throttle != save_throttle) { if (throttle) eglSwapInterval(display, 1); else eglSwapInterval(display, 0); save_throttle = throttle; } //Draw to the screen gles2_draw(VideoBuffer, surface_width, surface_height, 16); eglSwapBuffers(display, surface); } int StatedLoad(int nSlot); int StatedSave(int nSlot); const Uint8* sdl_keys; void pi_process_events(void) { int num = 0; SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_JOYBUTTONDOWN: joy_buttons[event.jbutton.which][event.jbutton.button] = 1; break; case SDL_JOYBUTTONUP: joy_buttons[event.jbutton.which][event.jbutton.button] = 0; break; case SDL_JOYAXISMOTION: joy_axes[event.jaxis.which][event.jaxis.axis] = event.jaxis.value; // if(event.jaxis.axis == joyaxis_LR) { // if(event.jaxis.value > -10000 && event.jaxis.value < 10000) // joy_axes[event.jbutton.which][joyaxis_LR] = CENTER; // else if(event.jaxis.value > 10000) // joy_axes[event.jbutton.which][joyaxis_LR] = RIGHT; // else // joy_axes[event.jbutton.which][joyaxis_LR] = LEFT; // } // if(event.jaxis.axis == joyaxis_UD) { // if(event.jaxis.value > -10000 && event.jaxis.value < 10000) // joy_axes[event.jbutton.which][joyaxis_UD] = CENTER; // else if(event.jaxis.value > 10000) // joy_axes[event.jbutton.which][joyaxis_UD] = DOWN; // else // joy_axes[event.jbutton.which][joyaxis_UD] = UP; // } break; case SDL_JOYHATMOTION: joy_hats[event.jhat.which] = event.jhat.value; case SDL_KEYDOWN: sdl_keys = SDL_GetKeyboardState(NULL); if (event.key.keysym.sym == SDLK_0) bShowFPS = !bShowFPS; // if (event.key.keysym.sym == SDLK_F1) num = 1; // else if (event.key.keysym.sym == SDLK_F2) num = 2; // else if (event.key.keysym.sym == SDLK_F3) num = 3; // else if (event.key.keysym.sym == SDLK_F4) num = 4; // if (num) { // if (event.key.keysym.mod & KMOD_SHIFT) // StatedSave(num); // else // StatedLoad(num); // } break; case SDL_KEYUP: sdl_keys = SDL_GetKeyboardState(NULL); break; } } //Check START+R,L for quicksave/quickload. Needs to go here outside of the internal processing // if (joy_buttons[0][pi_joy[QLOAD]] || (joy_buttons[0][pi_joy[SELECT_1]] && joy_buttons[0][pi_joy[L_1]] )) { // char fname[256]; // strcpy(fname, S9xGetFilename (".000")); // S9xLoadSnapshot (fname); // } // if (joy_buttons[0][pi_joy[QSAVE]] || (joy_buttons[0][pi_joy[SELECT_1]] && joy_buttons[0][pi_joy[R_1]] )) { // char fname[256]; // strcpy(fname, S9xGetFilename (".000")); // S9xFreezeGame (fname); // } } extern bool GameLooping; int joyvalue = 0; unsigned long pi_joystick_read(int which1) { unsigned long val = 0; //Only handle two players //if(which1 > 1) return val; //if (which1 == 0) { int playerjoyindex = joy_indexes[which1]; if (playerjoyindex != -1) { if (joy_buttons[playerjoyindex][pi_joy[which1][J_L]]) val |= GP2X_L; if (joy_buttons[playerjoyindex][pi_joy[which1][J_R]]) val |= GP2X_R; if (joy_buttons[playerjoyindex][pi_joy[which1][J_X]]) val |= GP2X_X; if (joy_buttons[playerjoyindex][pi_joy[which1][J_Y]]) val |= GP2X_Y; if (joy_buttons[playerjoyindex][pi_joy[which1][J_B]]) val |= GP2X_B; if (joy_buttons[playerjoyindex][pi_joy[which1][J_A]]) val |= GP2X_A; if (joy_buttons[playerjoyindex][pi_joy[which1][J_START]]) val |= GP2X_START; if (joy_buttons[playerjoyindex][pi_joy[which1][J_SELECT]]) val |= GP2X_SELECT; if (joy_buttons[playerjoyindex][pi_joy[which1][J_UP]]) val |= GP2X_UP; if (joy_buttons[playerjoyindex][pi_joy[which1][J_DOWN]]) val |= GP2X_DOWN; if (joy_buttons[playerjoyindex][pi_joy[which1][J_LEFT]]) val |= GP2X_LEFT; if (joy_buttons[playerjoyindex][pi_joy[which1][J_RIGHT]]) val |= GP2X_RIGHT; joyvalue = joy_axes[playerjoyindex][pi_joy[which1][J_AXIS_LR]]; if (joyvalue > 10000) val |= GP2X_RIGHT; else if (joyvalue < -10000) val |= GP2X_LEFT; joyvalue = joy_axes[playerjoyindex][pi_joy[which1][J_AXIS_UD]]; if (joyvalue > 10000) val |= GP2X_DOWN; else if (joyvalue < -10000) val |= GP2X_UP; // HATS int hatvalue = joy_hats[playerjoyindex]; switch (hatvalue) { case SDL_HAT_UP: val |= GP2X_UP; break; case SDL_HAT_DOWN: val |= GP2X_DOWN; break; case SDL_HAT_LEFT: val |= GP2X_LEFT; break; case SDL_HAT_RIGHT: val |= GP2X_RIGHT; break; case SDL_HAT_RIGHTUP: val |= GP2X_UP; val |= GP2X_RIGHT; break; case SDL_HAT_LEFTUP: val |= GP2X_UP; val |= GP2X_LEFT; break; case SDL_HAT_RIGHTDOWN: val |= GP2X_DOWN; val |= GP2X_RIGHT; break; case SDL_HAT_LEFTDOWN: val |= GP2X_DOWN; val |= GP2X_LEFT; break; } if (joy_buttons[playerjoyindex][pi_specials[QUIT]] && joy_buttons[playerjoyindex][pi_specials[HOTKEY]]) GameLooping = 0; } if (sdl_keys) { if (which1 == 0) { if (sdl_keys[pi_key[L_1]] == SDL_PRESSED) val |= GP2X_L; if (sdl_keys[pi_key[R_1]] == SDL_PRESSED) val |= GP2X_R; if (sdl_keys[pi_key[X_1]] == SDL_PRESSED) val |= GP2X_X; if (sdl_keys[pi_key[Y_1]] == SDL_PRESSED) val |= GP2X_Y; if (sdl_keys[pi_key[B_1]] == SDL_PRESSED) val |= GP2X_B; if (sdl_keys[pi_key[A_1]] == SDL_PRESSED) val |= GP2X_A; if (sdl_keys[pi_key[START_1]] == SDL_PRESSED) val |= GP2X_START; if (sdl_keys[pi_key[SELECT_1]] == SDL_PRESSED) val |= GP2X_SELECT; if (sdl_keys[pi_key[UP_1]] == SDL_PRESSED) val |= GP2X_UP; if (sdl_keys[pi_key[DOWN_1]] == SDL_PRESSED) val |= GP2X_DOWN; if (sdl_keys[pi_key[LEFT_1]] == SDL_PRESSED) val |= GP2X_LEFT; if (sdl_keys[pi_key[RIGHT_1]] == SDL_PRESSED) val |= GP2X_RIGHT; if (sdl_keys[pi_key[QUIT]] == SDL_PRESSED) GameLooping = 0; } else { if (sdl_keys[pi_key[L_2]] == SDL_PRESSED) val |= GP2X_L; if (sdl_keys[pi_key[R_2]] == SDL_PRESSED) val |= GP2X_R; if (sdl_keys[pi_key[X_2]] == SDL_PRESSED) val |= GP2X_X; if (sdl_keys[pi_key[Y_2]] == SDL_PRESSED) val |= GP2X_Y; if (sdl_keys[pi_key[B_2]] == SDL_PRESSED) val |= GP2X_B; if (sdl_keys[pi_key[A_2]] == SDL_PRESSED) val |= GP2X_A; if (sdl_keys[pi_key[START_2]] == SDL_PRESSED) val |= GP2X_START; if (sdl_keys[pi_key[SELECT_2]] == SDL_PRESSED) val |= GP2X_SELECT; if (sdl_keys[pi_key[UP_2]] == SDL_PRESSED) val |= GP2X_UP; if (sdl_keys[pi_key[DOWN_2]] == SDL_PRESSED) val |= GP2X_DOWN; if (sdl_keys[pi_key[LEFT_2]] == SDL_PRESSED) val |= GP2X_LEFT; if (sdl_keys[pi_key[RIGHT_2]] == SDL_PRESSED) val |= GP2X_RIGHT; } } return (val); } //sq Historical GP2X function to replace malloc, // saves having to rename all the function calls void *UpperMalloc(size_t size) { return (void *) calloc(1, size); } //sq Historical GP2X function to replace malloc, // saves having to rename all the function calls void UpperFree(void *mem) { free(mem); }
digitalLumberjack/pifba
rpi/gp2xsdk.cpp
C++
gpl-2.0
28,893
<?php /** * The template page 404 * * * @author KuteTheme * @package THEME/WooCommerce * @version KuteTheme 1.0 */ if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } get_header(); ?> <div id="primary" class="content-area "> <main id="main" class="site-main" role="main"> <section class="error-404 not-found"> <header class="page-header"> <h1 class="page-title"><?php esc_html_e( 'Oops! That page can&rsquo;t be found.', 'kutetheme' ); ?></h1> </header><!-- .page-header --> <div class="page-content"> <p><?php esc_html_e( 'It looks like nothing was found at this location. Maybe try a search?', 'kutetheme' ); ?></p> <?php get_search_form(); ?> </div><!-- .page-content --> </section><!-- .error-404 --> </main><!-- .site-main --> </div><!-- .content-area --> <?php get_footer(); ?>
hikaram/wee
wp-content/themes/wee/woocommerce/404.php
PHP
gpl-2.0
863
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Asterisk Project : Asterisk 10 Application_IAX2Provision</title> <link rel="stylesheet" href="styles/site.css" type="text/css" /> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <table class="pagecontent" border="0" cellpadding="0" cellspacing="0" width="100%" bgcolor="#ffffff"> <tr> <td valign="top" class="pagebody"> <div class="pageheader"> <span class="pagetitle"> Asterisk Project : Asterisk 10 Application_IAX2Provision </span> </div> <div class="pagesubheading"> This page last changed on Oct 14, 2011 by <font color="#0050B2">wikibot</font>. </div> <h1><a name="Asterisk10Application_IAX2Provision-IAX2Provision%28%29"></a>IAX2Provision()</h1> <h3><a name="Asterisk10Application_IAX2Provision-Synopsis"></a>Synopsis</h3> <p>Provision a calling IAXy with a given template.</p> <h3><a name="Asterisk10Application_IAX2Provision-Description"></a>Description</h3> <p>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the given <em>template</em>. Returns <tt>-1</tt> on error or <tt>0</tt> on success.</p> <h3><a name="Asterisk10Application_IAX2Provision-Syntax"></a>Syntax</h3> <div class="preformatted panel" style="border-width: 1px;"><div class="preformattedContent panelContent"> <pre>IAX2Provision([template])</pre> </div></div> <h5><a name="Asterisk10Application_IAX2Provision-Arguments"></a>Arguments</h5> <ul> <li><tt>template</tt> - If not specified, defaults to <tt>default</tt>.</li> </ul> <h3><a name="Asterisk10Application_IAX2Provision-SeeAlso"></a>See Also</h3> <h3><a name="Asterisk10Application_IAX2Provision-ImportVersion"></a>Import Version</h3> <p>This documentation was imported from Asterisk version SVN-branch-10-r340810.</p> </td> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td height="12" background="https://wiki.asterisk.org/wiki/images/border/border_bottom.gif"><img src="images/border/spacer.gif" width="1" height="1" border="0"/></td> </tr> <tr> <td align="center"><font color="grey">Document generated by Confluence on Oct 14, 2011 13:24</font></td> </tr> </table> </body> </html>
sameersethi/minorproject-asterisk
doc/Asterisk-Admin-Guide/Asterisk 10 Application_IAX2Provision.html
HTML
gpl-2.0
2,547
// Copyright 2017 Monax Industries Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package vm import ( "fmt" "github.com/monax/burrow/common/sanity" "github.com/monax/burrow/manager/burrow-mint/evm/sha3" ptypes "github.com/monax/burrow/permission/types" . "github.com/monax/burrow/word256" "strings" "github.com/monax/burrow/manager/burrow-mint/evm/abi" ) // // SNative (from 'secure natives') are native (go) contracts that are dispatched // based on account permissions and can access and modify an account's permissions // // Metadata for SNative contract. Acts as a call target from the EVM. Can be // used to generate bindings in a smart contract languages. type SNativeContractDescription struct { // Comment describing purpose of SNative contract and reason for assembling // the particular functions Comment string // Name of the SNative contract Name string functionsByID map[abi.FunctionSelector]*SNativeFunctionDescription functions []*SNativeFunctionDescription } // Metadata for SNative functions. Act as call targets for the EVM when // collected into an SNativeContractDescription. Can be used to generate // bindings in a smart contract languages. type SNativeFunctionDescription struct { // Comment describing function's purpose, parameters, and return value Comment string // Function name (used to form signature) Name string // Function arguments (used to form signature) Args []abi.Arg // Function return value Return abi.Return // Permissions required to call function PermFlag ptypes.PermFlag // Native function to which calls will be dispatched when a containing // contract is called with a FunctionSelector matching this NativeContract F NativeContract } func registerSNativeContracts() { for _, contract := range SNativeContracts() { registeredNativeContracts[contract.AddressWord256()] = contract.Dispatch } } // Returns a map of all SNative contracts defined indexed by name func SNativeContracts() map[string]*SNativeContractDescription { permFlagTypeName := abi.Uint64TypeName roleTypeName := abi.Bytes32TypeName contracts := []*SNativeContractDescription{ NewSNativeContract(` * Interface for managing Secure Native authorizations. * @dev This interface describes the functions exposed by the SNative permissions layer in burrow. `, "Permissions", &SNativeFunctionDescription{` * @notice Adds a role to an account * @param _account account address * @param _role role name * @return result whether role was added `, "addRole", []abi.Arg{ arg("_account", abi.AddressTypeName), arg("_role", roleTypeName), }, ret("result", abi.BoolTypeName), ptypes.AddRole, addRole}, &SNativeFunctionDescription{` * @notice Removes a role from an account * @param _account account address * @param _role role name * @return result whether role was removed `, "removeRole", []abi.Arg{ arg("_account", abi.AddressTypeName), arg("_role", roleTypeName), }, ret("result", abi.BoolTypeName), ptypes.RmRole, removeRole}, &SNativeFunctionDescription{` * @notice Indicates whether an account has a role * @param _account account address * @param _role role name * @return result whether account has role `, "hasRole", []abi.Arg{ arg("_account", abi.AddressTypeName), arg("_role", roleTypeName), }, ret("result", abi.BoolTypeName), ptypes.HasRole, hasRole}, &SNativeFunctionDescription{` * @notice Sets the permission flags for an account. Makes them explicitly set (on or off). * @param _account account address * @param _permission the base permissions flags to set for the account * @param _set whether to set or unset the permissions flags at the account level * @return result the effective permissions flags on the account after the call `, "setBase", []abi.Arg{ arg("_account", abi.AddressTypeName), arg("_permission", permFlagTypeName), arg("_set", abi.BoolTypeName), }, ret("result", permFlagTypeName), ptypes.SetBase, setBase}, &SNativeFunctionDescription{` * @notice Unsets the permissions flags for an account. Causes permissions being unset to fall through to global permissions. * @param _account account address * @param _permission the permissions flags to unset for the account * @return result the effective permissions flags on the account after the call `, "unsetBase", []abi.Arg{ arg("_account", abi.AddressTypeName), arg("_permission", permFlagTypeName)}, ret("result", permFlagTypeName), ptypes.UnsetBase, unsetBase}, &SNativeFunctionDescription{` * @notice Indicates whether an account has a subset of permissions set * @param _account account address * @param _permission the permissions flags (mask) to check whether enabled against base permissions for the account * @return result whether account has the passed permissions flags set `, "hasBase", []abi.Arg{ arg("_account", abi.AddressTypeName), arg("_permission", permFlagTypeName)}, ret("result", permFlagTypeName), ptypes.HasBase, hasBase}, &SNativeFunctionDescription{` * @notice Sets the global (default) permissions flags for the entire chain * @param _permission the permissions flags to set * @param _set whether to set (or unset) the permissions flags * @return result the global permissions flags after the call `, "setGlobal", []abi.Arg{ arg("_permission", permFlagTypeName), arg("_set", abi.BoolTypeName)}, ret("result", permFlagTypeName), ptypes.SetGlobal, setGlobal}, ), } contractMap := make(map[string]*SNativeContractDescription, len(contracts)) for _, contract := range contracts { if _, ok := contractMap[contract.Name]; ok { // If this happens we have a pseudo compile time error that will be caught // on native.go init() panic(fmt.Errorf("Duplicate contract with name %s defined. "+ "Contract names must be unique.", contract.Name)) } contractMap[contract.Name] = contract } return contractMap } // Create a new SNative contract description object by passing a comment, name // and a list of member functions descriptions func NewSNativeContract(comment, name string, functions ...*SNativeFunctionDescription) *SNativeContractDescription { functionsByID := make(map[abi.FunctionSelector]*SNativeFunctionDescription, len(functions)) for _, f := range functions { fid := f.ID() otherF, ok := functionsByID[fid] if ok { panic(fmt.Errorf("Function with ID %x already defined: %s", fid, otherF)) } functionsByID[fid] = f } return &SNativeContractDescription{ Comment: comment, Name: name, functionsByID: functionsByID, functions: functions, } } // This function is designed to be called from the EVM once a SNative contract // has been selected. It is also placed in a registry by registerSNativeContracts // So it can be looked up by SNative address func (contract *SNativeContractDescription) Dispatch(appState AppState, caller *Account, args []byte, gas *int64) (output []byte, err error) { if len(args) < abi.FunctionSelectorLength { return nil, fmt.Errorf("SNatives dispatch requires a 4-byte function "+ "identifier but arguments are only %s bytes long", len(args)) } function, err := contract.FunctionByID(firstFourBytes(args)) if err != nil { return nil, err } remainingArgs := args[abi.FunctionSelectorLength:] // check if we have permission to call this function if !HasPermission(appState, caller, function.PermFlag) { return nil, ErrInvalidPermission{caller.Address, function.Name} } // ensure there are enough arguments if len(remainingArgs) != function.NArgs()*Word256Length { return nil, fmt.Errorf("%s() takes %d arguments", function.Name, function.NArgs()) } // call the function return function.F(appState, caller, remainingArgs, gas) } // We define the address of an SNative contact as the last 20 bytes of the sha3 // hash of its name func (contract *SNativeContractDescription) Address() abi.Address { var address abi.Address hash := sha3.Sha3([]byte(contract.Name)) copy(address[:], hash[len(hash)-abi.AddressLength:]) return address } // Get address as a byte slice func (contract *SNativeContractDescription) AddressBytes() []byte { address := contract.Address() return address[:] } // Get address as a left-padded Word256 func (contract *SNativeContractDescription) AddressWord256() Word256 { return LeftPadWord256(contract.AddressBytes()) } // Get function by calling identifier FunctionSelector func (contract *SNativeContractDescription) FunctionByID(id abi.FunctionSelector) (*SNativeFunctionDescription, error) { f, ok := contract.functionsByID[id] if !ok { return nil, fmt.Errorf("Unknown SNative function with ID %x", id) } return f, nil } // Get function by name func (contract *SNativeContractDescription) FunctionByName(name string) (*SNativeFunctionDescription, error) { for _, f := range contract.functions { if f.Name == name { return f, nil } } return nil, fmt.Errorf("Unknown SNative function with name %s", name) } // Get functions in order of declaration func (contract *SNativeContractDescription) Functions() []*SNativeFunctionDescription { functions := make([]*SNativeFunctionDescription, len(contract.functions)) copy(functions, contract.functions) return functions } // // SNative functions // // Get function signature func (function *SNativeFunctionDescription) Signature() string { argTypeNames := make([]string, len(function.Args)) for i, arg := range function.Args { argTypeNames[i] = string(arg.TypeName) } return fmt.Sprintf("%s(%s)", function.Name, strings.Join(argTypeNames, ",")) } // Get function calling identifier FunctionSelector func (function *SNativeFunctionDescription) ID() abi.FunctionSelector { return firstFourBytes(sha3.Sha3([]byte(function.Signature()))) } // Get number of function arguments func (function *SNativeFunctionDescription) NArgs() int { return len(function.Args) } func arg(name string, abiTypeName abi.TypeName) abi.Arg { return abi.Arg{ Name: name, TypeName: abiTypeName, } } func ret(name string, abiTypeName abi.TypeName) abi.Return { return abi.Return{ Name: name, TypeName: abiTypeName, } } // Permission function defintions // TODO: catch errors, log em, return 0s to the vm (should some errors cause exceptions though?) func hasBase(appState AppState, caller *Account, args []byte, gas *int64) (output []byte, err error) { addr, permNum := returnTwoArgs(args) vmAcc := appState.GetAccount(addr) if vmAcc == nil { return nil, fmt.Errorf("Unknown account %X", addr) } permN := ptypes.PermFlag(Uint64FromWord256(permNum)) // already shifted if !ValidPermN(permN) { return nil, ptypes.ErrInvalidPermission(permN) } permInt := byteFromBool(HasPermission(appState, vmAcc, permN)) dbg.Printf("snative.hasBasePerm(0x%X, %b) = %v\n", addr.Postfix(20), permN, permInt) return LeftPadWord256([]byte{permInt}).Bytes(), nil } func setBase(appState AppState, caller *Account, args []byte, gas *int64) (output []byte, err error) { addr, permNum, permVal := returnThreeArgs(args) vmAcc := appState.GetAccount(addr) if vmAcc == nil { return nil, fmt.Errorf("Unknown account %X", addr) } permN := ptypes.PermFlag(Uint64FromWord256(permNum)) if !ValidPermN(permN) { return nil, ptypes.ErrInvalidPermission(permN) } permV := !permVal.IsZero() if err = vmAcc.Permissions.Base.Set(permN, permV); err != nil { return nil, err } appState.UpdateAccount(vmAcc) dbg.Printf("snative.setBasePerm(0x%X, %b, %v)\n", addr.Postfix(20), permN, permV) return effectivePermBytes(vmAcc.Permissions.Base, globalPerms(appState)), nil } func unsetBase(appState AppState, caller *Account, args []byte, gas *int64) (output []byte, err error) { addr, permNum := returnTwoArgs(args) vmAcc := appState.GetAccount(addr) if vmAcc == nil { return nil, fmt.Errorf("Unknown account %X", addr) } permN := ptypes.PermFlag(Uint64FromWord256(permNum)) if !ValidPermN(permN) { return nil, ptypes.ErrInvalidPermission(permN) } if err = vmAcc.Permissions.Base.Unset(permN); err != nil { return nil, err } appState.UpdateAccount(vmAcc) dbg.Printf("snative.unsetBasePerm(0x%X, %b)\n", addr.Postfix(20), permN) return effectivePermBytes(vmAcc.Permissions.Base, globalPerms(appState)), nil } func setGlobal(appState AppState, caller *Account, args []byte, gas *int64) (output []byte, err error) { permNum, permVal := returnTwoArgs(args) vmAcc := appState.GetAccount(ptypes.GlobalPermissionsAddress256) if vmAcc == nil { sanity.PanicSanity("cant find the global permissions account") } permN := ptypes.PermFlag(Uint64FromWord256(permNum)) if !ValidPermN(permN) { return nil, ptypes.ErrInvalidPermission(permN) } permV := !permVal.IsZero() if err = vmAcc.Permissions.Base.Set(permN, permV); err != nil { return nil, err } appState.UpdateAccount(vmAcc) dbg.Printf("snative.setGlobalPerm(%b, %v)\n", permN, permV) return permBytes(vmAcc.Permissions.Base.ResultantPerms()), nil } func hasRole(appState AppState, caller *Account, args []byte, gas *int64) (output []byte, err error) { addr, role := returnTwoArgs(args) vmAcc := appState.GetAccount(addr) if vmAcc == nil { return nil, fmt.Errorf("Unknown account %X", addr) } roleS := string(role.Bytes()) permInt := byteFromBool(vmAcc.Permissions.HasRole(roleS)) dbg.Printf("snative.hasRole(0x%X, %s) = %v\n", addr.Postfix(20), roleS, permInt > 0) return LeftPadWord256([]byte{permInt}).Bytes(), nil } func addRole(appState AppState, caller *Account, args []byte, gas *int64) (output []byte, err error) { addr, role := returnTwoArgs(args) vmAcc := appState.GetAccount(addr) if vmAcc == nil { return nil, fmt.Errorf("Unknown account %X", addr) } roleS := string(role.Bytes()) permInt := byteFromBool(vmAcc.Permissions.AddRole(roleS)) appState.UpdateAccount(vmAcc) dbg.Printf("snative.addRole(0x%X, %s) = %v\n", addr.Postfix(20), roleS, permInt > 0) return LeftPadWord256([]byte{permInt}).Bytes(), nil } func removeRole(appState AppState, caller *Account, args []byte, gas *int64) (output []byte, err error) { addr, role := returnTwoArgs(args) vmAcc := appState.GetAccount(addr) if vmAcc == nil { return nil, fmt.Errorf("Unknown account %X", addr) } roleS := string(role.Bytes()) permInt := byteFromBool(vmAcc.Permissions.RmRole(roleS)) appState.UpdateAccount(vmAcc) dbg.Printf("snative.rmRole(0x%X, %s) = %v\n", addr.Postfix(20), roleS, permInt > 0) return LeftPadWord256([]byte{permInt}).Bytes(), nil } //------------------------------------------------------------------------------------------------ // Errors and utility funcs type ErrInvalidPermission struct { Address Word256 SNative string } func (e ErrInvalidPermission) Error() string { return fmt.Sprintf("Account %X does not have permission snative.%s", e.Address.Postfix(20), e.SNative) } // Checks if a permission flag is valid (a known base chain or snative permission) func ValidPermN(n ptypes.PermFlag) bool { if n > ptypes.TopPermFlag { return false } return true } // Get the global BasePermissions func globalPerms(appState AppState) ptypes.BasePermissions { vmAcc := appState.GetAccount(ptypes.GlobalPermissionsAddress256) if vmAcc == nil { sanity.PanicSanity("cant find the global permissions account") } return vmAcc.Permissions.Base } // Compute the effective permissions from an Account's BasePermissions by // taking the bitwise or with the global BasePermissions resultant permissions func effectivePermBytes(basePerms ptypes.BasePermissions, globalPerms ptypes.BasePermissions) []byte { return permBytes(basePerms.ResultantPerms() | globalPerms.ResultantPerms()) } func permBytes(basePerms ptypes.PermFlag) []byte { return Uint64ToWord256(uint64(basePerms)).Bytes() } // CONTRACT: length has already been checked func returnTwoArgs(args []byte) (a Word256, b Word256) { copy(a[:], args[:32]) copy(b[:], args[32:64]) return } // CONTRACT: length has already been checked func returnThreeArgs(args []byte) (a Word256, b Word256, c Word256) { copy(a[:], args[:32]) copy(b[:], args[32:64]) copy(c[:], args[64:96]) return } func byteFromBool(b bool) byte { if b { return 0x1 } return 0x0 } func firstFourBytes(byteSlice []byte) [4]byte { var bs [4]byte copy(bs[:], byteSlice[:4]) return bs }
eris-ltd/eris-compilers
vendor/github.com/monax/cli/vendor/github.com/monax/burrow/manager/burrow-mint/evm/snative.go
GO
gpl-2.0
17,036
//////////////////////////////////////////////////////////////////////////////// // $RCSfile: ZipPlatform.cpp,v $ // $Revision: 1.7 $ $Name: 1.7 $ // $Date: 2005/09/20 18:13:17 $ $Author: Tadeusz Dracz $ //////////////////////////////////////////////////////////////////////////////// // This source file is part of the ZipArchive library source distribution and // is Copyrighted 2000-2005 by Tadeusz Dracz (http://www.artpol-software.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. // // For the licensing details see the file License.txt //////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ZipPlatform.h" #include "ZipFileHeader.h" #include "ZipException.h" #include "ZipAutoBuffer.h" #include <sys/stat.h> #if defined _MSC_VER && !defined __BORLANDC__ /*_MSC_VER may be defined in Borland after converting the VC project */ #include <sys/utime.h> #else #include <utime.h> #endif #include <direct.h> #include <io.h> #include <time.h> #include "ZipPathComponent.h" #include "ZipCompatibility.h" const TCHAR CZipPathComponent::m_cSeparator = _T('\\'); #ifndef _UTIMBUF_DEFINED #define _utimbuf utimbuf #endif DWORD ZipPlatform::GetDeviceFreeSpace(LPCTSTR lpszPath) { DWORD SectorsPerCluster, BytesPerSector, NumberOfFreeClusters, TotalNumberOfClusters; CZipPathComponent zpc (lpszPath); CZipString szDrive = zpc.GetFileDrive(); if (!GetDiskFreeSpace( szDrive, &SectorsPerCluster, &BytesPerSector, &NumberOfFreeClusters, &TotalNumberOfClusters)) { CZipPathComponent::AppendSeparator(szDrive); // in spite of what is written in MSDN it is sometimes needed (on fixed disks) if (!GetDiskFreeSpace( szDrive, &SectorsPerCluster, &BytesPerSector, &NumberOfFreeClusters, &TotalNumberOfClusters)) return 0; } __int64 total = SectorsPerCluster * BytesPerSector * NumberOfFreeClusters; return (DWORD)total; } bool ZipPlatform::GetFileSize(LPCTSTR lpszFileName, DWORD& dSize) { HANDLE f = CreateFile(lpszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if (!f) return false; DWORD dwSize; dwSize = ::GetFileSize(f, NULL); CloseHandle(f); if (dwSize == 0xFFFFFFFF) return false; dSize = dwSize; return true; } CZipString ZipPlatform::GetTmpFileName(LPCTSTR lpszPath, DWORD iSizeNeeded) { TCHAR empty[] = _T(""); CZipString tempPath; bool bCheckTemp = true; if (lpszPath) { tempPath = lpszPath; bCheckTemp = GetDeviceFreeSpace(tempPath) < iSizeNeeded; } if (bCheckTemp) { DWORD size = GetTempPath(0, NULL); if (size == 0) return empty; GetTempPath(size, tempPath.GetBuffer(size)); tempPath.ReleaseBuffer(); if (GetDeviceFreeSpace(tempPath) < iSizeNeeded) { if (!GetCurrentDirectory(tempPath) || GetDeviceFreeSpace(tempPath) < iSizeNeeded) return empty; } } CZipString tempName; if (!GetTempFileName(tempPath, _T("ZAR"), 0, tempName.GetBuffer(_MAX_PATH))) return empty; tempName.ReleaseBuffer(); return tempName; } bool ZipPlatform::GetCurrentDirectory(CZipString& sz) { DWORD i = ::GetCurrentDirectory(0, NULL); if (!i) return false; TCHAR* pBuf = new TCHAR[i]; bool b = true; if (!::GetCurrentDirectory(i, pBuf)) b = false; else sz = pBuf; delete[] pBuf; return b; } bool ZipPlatform::SetFileAttr(LPCTSTR lpFileName, DWORD uAttr) { return ::SetFileAttributes(lpFileName, uAttr) != 0; } bool ZipPlatform::GetFileAttr(LPCTSTR lpFileName, DWORD& uAttr) { // not using MFC due to MFC bug (attr is one byte there) DWORD temp = ::GetFileAttributes(lpFileName); if (temp == -1) return false; uAttr = temp; return true; } bool ZipPlatform::GetFileModTime(LPCTSTR lpFileName, time_t & ttime) { #if defined _MSC_VER && !defined __BORLANDC__ /*_MSC_VER may be defined in Borland after converting the VC project */ struct _stat st; if (_tstat(lpFileName, &st) != 0) #else struct stat st; if (stat(lpFileName, &st) != 0) #endif return false; ttime = st.st_mtime; return ttime != -1; } bool ZipPlatform::SetFileModTime(LPCTSTR lpFileName, time_t ttime) { struct _utimbuf ub; ub.actime = time(NULL); ub.modtime = ttime == -1 ? time(NULL) : ttime; // if wrong file time, set it to the current #ifdef __MINGW32__ return utime(lpFileName, &ub) == 0; #else return _tutime(lpFileName, &ub) == 0; #endif } bool ZipPlatform::ChangeDirectory(LPCTSTR lpDirectory) { return _tchdir(lpDirectory) == 0; // returns 0 if ok } int ZipPlatform::FileExists(LPCTSTR lpszName) { if (_taccess(lpszName, 0) == 0) { if (DirectoryExists(lpszName)) return -1; return 1; } else return 0; } ZIPINLINE bool ZipPlatform::IsDriveRemovable(LPCTSTR lpszFilePath) { CZipPathComponent zpc(lpszFilePath); return ::GetDriveType(zpc.GetFileDrive()) == DRIVE_REMOVABLE; } ZIPINLINE bool ZipPlatform::SetVolLabel(LPCTSTR lpszPath, LPCTSTR lpszLabel) { CZipPathComponent zpc(lpszPath); CZipString szDrive = zpc.GetFileDrive(); CZipPathComponent::AppendSeparator(szDrive); return ::SetVolumeLabel(szDrive, lpszLabel) != 0; } ZIPINLINE void ZipPlatform::AnsiOem(CZipAutoBuffer& buffer, bool bAnsiToOem) { if (bAnsiToOem) CharToOemBuffA(buffer, buffer, buffer.GetSize()); else OemToCharBuffA(buffer, buffer, buffer.GetSize()); } ZIPINLINE bool ZipPlatform::RemoveFile(LPCTSTR lpszFileName, bool bThrow) { if (!::DeleteFile((LPTSTR)lpszFileName)) if (bThrow) CZipException::Throw(CZipException::notRemoved, lpszFileName); else return false; return true; } ZIPINLINE bool ZipPlatform::RenameFile( LPCTSTR lpszOldName, LPCTSTR lpszNewName, bool bThrow) { if (!::MoveFile((LPTSTR)lpszOldName, (LPTSTR)lpszNewName)) if (bThrow) CZipException::Throw(CZipException::notRenamed, lpszOldName); else return false; return true; } ZIPINLINE bool ZipPlatform::IsDirectory(DWORD uAttr) { return (uAttr & FILE_ATTRIBUTE_DIRECTORY) != 0; } ZIPINLINE bool ZipPlatform::CreateDirectory(LPCTSTR lpDirectory) { return ::CreateDirectory(lpDirectory, NULL) != 0; } ZIPINLINE DWORD ZipPlatform::GetDefaultAttributes() { return 0x81a40020; // make it readable under Unix } ZIPINLINE DWORD ZipPlatform::GetDefaultDirAttributes() { return 0x41ff0010; // make it readable under Unix } ZIPINLINE int ZipPlatform::GetSystemID() { return ZipCompatibility::zcDosFat; } ZIPINLINE bool ZipPlatform::GetSystemCaseSensitivity() { return false; } #ifdef _UNICODE int ZipPlatform::WideToSingle(LPCTSTR lpWide, CZipAutoBuffer &szSingle, bool bUseAnsi) { size_t wideLen = wcslen(lpWide); if (wideLen == 0) { szSingle.Release(); return 0; } // iLen does not include terminating character UINT uCodePage = bUseAnsi ? CP_ACP : CP_UTF8; int iLen = WideCharToMultiByte(uCodePage, 0, lpWide, (int)wideLen, szSingle, 0, NULL, NULL); if (iLen > 0) { szSingle.Allocate(iLen, true); iLen = WideCharToMultiByte(uCodePage, 0, lpWide , (int)wideLen, szSingle, iLen, NULL, NULL); ASSERT(iLen != 0); } else // here it means error { szSingle.Release(); iLen --; } return iLen; } int ZipPlatform::SingleToWide(const CZipAutoBuffer &szSingle, CZipString& szWide, bool bUseAnsi) { int singleLen = szSingle.GetSize(); // iLen doesn't include terminating character UINT uCodePage; DWORD dwFlags; if (bUseAnsi) { uCodePage = CP_ACP; dwFlags = MB_PRECOMPOSED; } else { uCodePage = CP_UTF8; dwFlags = 0; } int iLen = MultiByteToWideChar(uCodePage, dwFlags, szSingle.GetBuffer(), singleLen, NULL, 0); if (iLen > 0) { iLen = MultiByteToWideChar(uCodePage, dwFlags, szSingle.GetBuffer(), singleLen, szWide.GetBuffer(iLen) , iLen); szWide.ReleaseBuffer(iLen); ASSERT(iLen != 0); } else { szWide.Empty(); iLen --; // return -1 } return iLen; } #endif #ifndef _MFC_VER #include <io.h> #include <share.h> bool ZipPlatform::TruncateFile(int iDes, DWORD iSize) { int ret = chsize(iDes, iSize); return ret != -1; } int ZipPlatform::OpenFile(LPCTSTR lpszFileName, UINT iMode, int iShareMode) { switch (iShareMode) { case (CZipFile::shareDenyWrite & CZipFile::shareDenyRead): iShareMode = SH_DENYRW; break; case (CZipFile::shareDenyRead): iShareMode = SH_DENYRD; break; case (CZipFile::shareDenyWrite): iShareMode = SH_DENYWR; break; default: iShareMode = SH_DENYNO; } return _tsopen(lpszFileName, iMode, iShareMode, S_IREAD | S_IWRITE /*required only when O_CREAT mode*/); } bool ZipPlatform::FlushFile(int iDes) { return _commit(iDes) == 0; } int ZipPlatform::GetFileSystemHandle(int iDes) { return (int)_get_osfhandle(iDes); } #endif //_MFC_VER
RandallFlagg/kgbarchiver
KGB Archiver 1/sfx/zip/ZipPlatform.cpp
C++
gpl-2.0
8,809
/* * include/linux/mfd/wm831x/otp.h -- OTP interface for WM831x * * Copyright 2009 Wolfson Microelectronics PLC. * * Author: Mark Brown <broonie@opensource.wolfsonmicro.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. * */ #ifndef __MFD_WM831X_OTP_H__ #define __MFD_WM831X_OTP_H__ int wm831x_otp_init(struct wm831x *wm831x); void wm831x_otp_exit(struct wm831x *wm831x); /* * R30720 (0x7800) - Unique ID 1 */ #define WM831X_UNIQUE_ID_MASK 0xFFFF /* UNIQUE_ID - [15:0] */ #define WM831X_UNIQUE_ID_SHIFT 0 /* UNIQUE_ID - [15:0] */ #define WM831X_UNIQUE_ID_WIDTH 16 /* UNIQUE_ID - [15:0] */ /* * R30721 (0x7801) - Unique ID 2 */ #define WM831X_UNIQUE_ID_MASK 0xFFFF /* UNIQUE_ID - [15:0] */ #define WM831X_UNIQUE_ID_SHIFT 0 /* UNIQUE_ID - [15:0] */ #define WM831X_UNIQUE_ID_WIDTH 16 /* UNIQUE_ID - [15:0] */ /* * R30722 (0x7802) - Unique ID 3 */ #define WM831X_UNIQUE_ID_MASK 0xFFFF /* UNIQUE_ID - [15:0] */ #define WM831X_UNIQUE_ID_SHIFT 0 /* UNIQUE_ID - [15:0] */ #define WM831X_UNIQUE_ID_WIDTH 16 /* UNIQUE_ID - [15:0] */ /* * R30723 (0x7803) - Unique ID 4 */ #define WM831X_UNIQUE_ID_MASK 0xFFFF /* UNIQUE_ID - [15:0] */ #define WM831X_UNIQUE_ID_SHIFT 0 /* UNIQUE_ID - [15:0] */ #define WM831X_UNIQUE_ID_WIDTH 16 /* UNIQUE_ID - [15:0] */ /* * R30724 (0x7804) - Unique ID 5 */ #define WM831X_UNIQUE_ID_MASK 0xFFFF /* UNIQUE_ID - [15:0] */ #define WM831X_UNIQUE_ID_SHIFT 0 /* UNIQUE_ID - [15:0] */ #define WM831X_UNIQUE_ID_WIDTH 16 /* UNIQUE_ID - [15:0] */ /* * R30725 (0x7805) - Unique ID 6 */ #define WM831X_UNIQUE_ID_MASK 0xFFFF /* UNIQUE_ID - [15:0] */ #define WM831X_UNIQUE_ID_SHIFT 0 /* UNIQUE_ID - [15:0] */ #define WM831X_UNIQUE_ID_WIDTH 16 /* UNIQUE_ID - [15:0] */ /* * R30726 (0x7806) - Unique ID 7 */ #define WM831X_UNIQUE_ID_MASK 0xFFFF /* UNIQUE_ID - [15:0] */ #define WM831X_UNIQUE_ID_SHIFT 0 /* UNIQUE_ID - [15:0] */ #define WM831X_UNIQUE_ID_WIDTH 16 /* UNIQUE_ID - [15:0] */ /* * R30727 (0x7807) - Unique ID 8 */ #define WM831X_UNIQUE_ID_MASK 0xFFFF /* UNIQUE_ID - [15:0] */ #define WM831X_UNIQUE_ID_SHIFT 0 /* UNIQUE_ID - [15:0] */ #define WM831X_UNIQUE_ID_WIDTH 16 /* UNIQUE_ID - [15:0] */ /* * R30728 (0x7808) - Factory OTP ID */ #define WM831X_OTP_FACT_ID_MASK 0xFFFE /* OTP_FACT_ID - [15:1] */ #define WM831X_OTP_FACT_ID_SHIFT 1 /* OTP_FACT_ID - [15:1] */ #define WM831X_OTP_FACT_ID_WIDTH 15 /* OTP_FACT_ID - [15:1] */ #define WM831X_OTP_FACT_FINAL 0x0001 /* OTP_FACT_FINAL */ #define WM831X_OTP_FACT_FINAL_MASK 0x0001 /* OTP_FACT_FINAL */ #define WM831X_OTP_FACT_FINAL_SHIFT 0 /* OTP_FACT_FINAL */ #define WM831X_OTP_FACT_FINAL_WIDTH 1 /* OTP_FACT_FINAL */ /* * R30729 (0x7809) - Factory OTP 1 */ #define WM831X_DC3_TRIM_MASK 0xF000 /* DC3_TRIM - [15:12] */ #define WM831X_DC3_TRIM_SHIFT 12 /* DC3_TRIM - [15:12] */ #define WM831X_DC3_TRIM_WIDTH 4 /* DC3_TRIM - [15:12] */ #define WM831X_DC2_TRIM_MASK 0x0FC0 /* DC2_TRIM - [11:6] */ #define WM831X_DC2_TRIM_SHIFT 6 /* DC2_TRIM - [11:6] */ #define WM831X_DC2_TRIM_WIDTH 6 /* DC2_TRIM - [11:6] */ #define WM831X_DC1_TRIM_MASK 0x003F /* DC1_TRIM - [5:0] */ #define WM831X_DC1_TRIM_SHIFT 0 /* DC1_TRIM - [5:0] */ #define WM831X_DC1_TRIM_WIDTH 6 /* DC1_TRIM - [5:0] */ /* * R30730 (0x780A) - Factory OTP 2 */ #define WM831X_CHIP_ID_MASK 0xFFFF /* CHIP_ID - [15:0] */ #define WM831X_CHIP_ID_SHIFT 0 /* CHIP_ID - [15:0] */ #define WM831X_CHIP_ID_WIDTH 16 /* CHIP_ID - [15:0] */ /* * R30731 (0x780B) - Factory OTP 3 */ #define WM831X_OSC_TRIM_MASK 0x0780 /* OSC_TRIM - [10:7] */ #define WM831X_OSC_TRIM_SHIFT 7 /* OSC_TRIM - [10:7] */ #define WM831X_OSC_TRIM_WIDTH 4 /* OSC_TRIM - [10:7] */ #define WM831X_BG_TRIM_MASK 0x0078 /* BG_TRIM - [6:3] */ #define WM831X_BG_TRIM_SHIFT 3 /* BG_TRIM - [6:3] */ #define WM831X_BG_TRIM_WIDTH 4 /* BG_TRIM - [6:3] */ #define WM831X_LPBG_TRIM_MASK 0x0007 /* LPBG_TRIM - [2:0] */ #define WM831X_LPBG_TRIM_SHIFT 0 /* LPBG_TRIM - [2:0] */ #define WM831X_LPBG_TRIM_WIDTH 3 /* LPBG_TRIM - [2:0] */ /* * R30732 (0x780C) - Factory OTP 4 */ #define WM831X_CHILD_I2C_ADDR_MASK 0x00FE /* CHILD_I2C_ADDR - [7:1] */ #define WM831X_CHILD_I2C_ADDR_SHIFT 1 /* CHILD_I2C_ADDR - [7:1] */ #define WM831X_CHILD_I2C_ADDR_WIDTH 7 /* CHILD_I2C_ADDR - [7:1] */ #define WM831X_CH_AW 0x0001 /* CH_AW */ #define WM831X_CH_AW_MASK 0x0001 /* CH_AW */ #define WM831X_CH_AW_SHIFT 0 /* CH_AW */ #define WM831X_CH_AW_WIDTH 1 /* CH_AW */ /* * R30733 (0x780D) - Factory OTP 5 */ #define WM831X_CHARGE_TRIM_MASK 0x003F /* CHARGE_TRIM - [5:0] */ #define WM831X_CHARGE_TRIM_SHIFT 0 /* CHARGE_TRIM - [5:0] */ #define WM831X_CHARGE_TRIM_WIDTH 6 /* CHARGE_TRIM - [5:0] */ /* * R30736 (0x7810) - Customer OTP ID */ #define WM831X_OTP_AUTO_PROG 0x8000 /* OTP_AUTO_PROG */ #define WM831X_OTP_AUTO_PROG_MASK 0x8000 /* OTP_AUTO_PROG */ #define WM831X_OTP_AUTO_PROG_SHIFT 15 /* OTP_AUTO_PROG */ #define WM831X_OTP_AUTO_PROG_WIDTH 1 /* OTP_AUTO_PROG */ #define WM831X_OTP_CUST_ID_MASK 0x7FFE /* OTP_CUST_ID - [14:1] */ #define WM831X_OTP_CUST_ID_SHIFT 1 /* OTP_CUST_ID - [14:1] */ #define WM831X_OTP_CUST_ID_WIDTH 14 /* OTP_CUST_ID - [14:1] */ #define WM831X_OTP_CUST_FINAL 0x0001 /* OTP_CUST_FINAL */ #define WM831X_OTP_CUST_FINAL_MASK 0x0001 /* OTP_CUST_FINAL */ #define WM831X_OTP_CUST_FINAL_SHIFT 0 /* OTP_CUST_FINAL */ #define WM831X_OTP_CUST_FINAL_WIDTH 1 /* OTP_CUST_FINAL */ /* * R30759 (0x7827) - DBE CHECK DATA */ #define WM831X_DBE_VALID_DATA_MASK 0xFFFF /* DBE_VALID_DATA - [15:0] */ #define WM831X_DBE_VALID_DATA_SHIFT 0 /* DBE_VALID_DATA - [15:0] */ #define WM831X_DBE_VALID_DATA_WIDTH 16 /* DBE_VALID_DATA - [15:0] */ #endif
evolver56k/xpenology
include/linux/mfd/wm831x/otp.h
C
gpl-2.0
7,348
#!/bin/sh # Copyright (c) 2002, Intel Corporation. All rights reserved. # Created by: julie.n.fleischer REMOVE-THIS AT intel DOT com # This file is licensed under the GPL license. For the full content # of this license, see the COPYING file at the top level of this # source tree. # # # Test various methods of removing invalid signals to sigaddset(). # ./4-core 3
rogerq/ltp-ddt
testcases/open_posix_testsuite/conformance/interfaces/sigdelset/4-3.sh
Shell
gpl-2.0
371
package com.development.buccola.myrecipes.add_recipe; import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import com.development.buccola.myrecipes.recipe.Ingredient; import com.development.buccola.myrecipes.recipe.Recipe; import com.example.megan.myapplication.R; import java.util.ArrayList; /*************************************************** * FILE: AddRecipe_General_Fragment * PROGRAMMER: Megan Buccola * CREATED: 3/22/15. * EXTENDS: Fragment * IMPLEMENTS: GetRecipeData * Purpose: control fragments for each tab. * NOTES: with code example from https://www.youtube.com/watch?v=zwqzhY5i2rc * LAYOUT: add_recipe_general_fragment ***************************************************/ public class AddRecipe_General_Fragment extends Fragment implements GetRecipeData { View rootview; static EditText title, source, cookTime, prepTime, caloriesPerServing, servingsPerMeal, servingSize; Spinner spinnerMealTypes; static String currentType; int sendCook, sendPrep, sendCalories, sendServingSize, sendServingsPerRecipe; String sendTitle, sendSource; static GetRecipeData SM; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootview = inflater.inflate(R.layout.add_recipe_general_fragment, container, false); spinnerMealTypes = (Spinner) rootview.findViewById(R.id.mealTypeSpinner); title = (EditText) rootview.findViewById(R.id.title); source = (EditText) rootview.findViewById(R.id.source); prepTime = (EditText) rootview.findViewById(R.id.etPrepTime); cookTime = (EditText) rootview.findViewById(R.id.etCookTime); caloriesPerServing = (EditText) rootview.findViewById(R.id.numOfCaloriesPer); servingsPerMeal = (EditText) rootview.findViewById(R.id.numOfServings); servingSize = (EditText) rootview.findViewById(R.id.servingsPerPerson); loadMealTypesSpinner(); /********************************* When a new meal type in the spinner is selected the currentType is changed to the selected item *********************************/ spinnerMealTypes.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { currentType = spinnerMealTypes.getSelectedItem().toString(); } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); return rootview; } /********************************* FUNCTION: void loadmealTypesSpinner() PARAMS: NONE RETUNS: returns nothing PURPOSE: laods meal types spinner. NOTES: uses ArrayAdapter to load spinner. Options are loaded from R.array.Meal_types_array *********************************/ private void loadMealTypesSpinner(){ ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( getActivity(), R.array.Meal_types_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerMealTypes.setAdapter(adapter); } @Override public void onAttach(Activity activity){ super.onAttach(activity); try{ SM = (GetRecipeData) getParentFragment(); }catch(ClassCastException e){ throw new ClassCastException("You need to implement all methods"); } } @Override public void RequestForGeneral() { } @Override public void RequestForIngredients() { } @Override public void sendData(Recipe recipe) { } @Override public void sendArrayData(ArrayList<Ingredient> data) { } /********************************* FUNCTION: void requestMade() PARAMS: NONE RETUNS: returns nothing PURPOSE: sends the General info to Steps Fragment when user saves recipe NOTES: data is added to a Recipe Object and sent as a recipe object *********************************/ public void requestMade(){ Recipe recipe = new Recipe(); sendTitle = title.getText().toString(); sendSource = source.getText().toString(); if(cookTime.getText().toString().isEmpty()) sendCook =-1; else sendCook = Integer.parseInt(cookTime.getText().toString()); if(prepTime.getText().toString().isEmpty()) sendPrep = -1; else sendPrep = Integer.parseInt(prepTime.getText().toString()); if(caloriesPerServing.getText().toString().isEmpty()) sendCalories = -1; else sendCalories = Integer.parseInt(caloriesPerServing.getText().toString()); if(servingSize.getText().toString().isEmpty()) sendServingSize = -1; else sendServingSize = Integer.parseInt(servingSize.getText().toString()); if(servingsPerMeal.getText().toString().isEmpty()) sendServingsPerRecipe = -1; else sendServingsPerRecipe = Integer.parseInt(servingsPerMeal.getText().toString()); recipe.setTitle(sendTitle); recipe.setSource(sendSource); recipe.setCook_time(sendCook); recipe.setPrep_time(sendPrep); recipe.setMeal_type(currentType); recipe.setCalories_per_serving(sendCalories); recipe.setServing_size(sendServingSize); recipe.setTotal_servings(sendServingsPerRecipe); SM.sendData(recipe); } }
m2345/my_recipes
app/add_recipe/AddRecipe_General_Fragment.java
Java
gpl-2.0
6,604
(function($){ $.map(['validatebox','textbox','filebox','searchbox', 'combo','combobox','combogrid','combotree', 'datebox','datetimebox','numberbox', 'spinner','numberspinner','timespinner','datetimespinner'], function(plugin){ if ($.fn[plugin]){ $.extend($.fn[plugin].defaults, { iconAlign: 'left', buttonAlign: 'left', tipPosition: 'left', panelAlign: 'right', deltaX: -19 }); } }); $.fn.validatebox.defaults.deltaX = 0; $.map(['linkbutton','menubutton','splitbutton'], function(plugin){ if ($.fn[plugin]){ $.extend($.fn[plugin].defaults, { iconAlign: 'right', menuAlign: 'right' }); } }); $.map(['datagrid','propertygrid','treegrid','combogrid'], function(plugin){ if ($.fn[plugin]){ $.extend($.fn[plugin].defaults, { resizeHandle: 'left' }); } }); $.fn.searchbox.defaults.buttonAlign = 'right'; $.fn.menu.defaults.align = 'right'; $.fn.tabs.defaults.toolPosition = 'left'; $.fn.pagination.defaults.nav.first.iconCls = 'pagination-last'; $.fn.pagination.defaults.nav.prev.iconCls = 'pagination-next'; $.fn.pagination.defaults.nav.next.iconCls = 'pagination-prev'; $.fn.pagination.defaults.nav.last.iconCls = 'pagination-first'; $.fn.slider.defaults.reversed = true; var datagrid_freezeRow = $.fn.datagrid.methods.freezeRow; $.fn.datagrid.methods.freezeRow = function(jq, index){ return jq.each(function(){ datagrid_freezeRow.call(this, jq, index); var state = $.data(this, 'datagrid'); if (!state.rtlscroll){ state.rtlscroll = true; var dc = state.dc; dc.body2.bind('scroll', function(){ var ftable = $(this).children('table.datagrid-btable-frozen'); ftable.css('left', $(this)._outerWidth() + $(this)._scrollLeft() - ftable._outerWidth()); }); } }); } var tabs_update = $.fn.tabs.methods.update; $.fn.tabs.methods.update = function(jq, options){ return jq.each(function(){ tabs_update.call(this, jq, options); var wrap = $(this).find('>div.tabs-header>div.tabs.wrap'); var opts = options.tab.panel('options'); var tab = opts.tab; var tool = tab.find('.tabs-p-tool'); if (tool.length){ var pos = tool.css('right'); tool.css({ left: pos, right: 'auto' }); var title = tab.find('.tabs-title'); var pos = title.css('padding-right'); title.css({ paddingLeft: pos, paddingRight: '' }); } }); } function checkScrollLeftType(){ var tmp = $('<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">test</div>').appendTo('body'); if (tmp.scrollLeft() > 0){ $._rtlScrollType = 'default'; // chrome } else { tmp.scrollLeft(1); if (tmp.scrollLeft() == 0){ $._rtlScrollType = 'negative'; // firefox } else { $._rtlScrollType = 'reverse'; // ie } } tmp.remove(); } $.fn._scrollLeft = function(left){ if ($._rtlScrollType == undefined){checkScrollLeftType();} if (left == undefined){ if ($._rtlScrollType == 'reverse'){ return this.scrollLeft(); } else if ($._rtlScrollType == 'negative'){ return -this.scrollLeft(); } else { return this[0].scrollWidth - this[0].clientWidth - this.scrollLeft(); } } return this.each(function(){ if ($._rtlScrollType == 'reverse'){ $(this).scrollLeft(left); } else if ($._rtlScrollType == 'negative'){ $(this).scrollLeft(-left); } else { $(this).scrollLeft(this.scrollWidth - this.clientWidth - left); } }); } $.fn.tabs.methods.scrollBy = function(jq, deltaX){ if ($._rtlScrollType == undefined){checkScrollLeftType();} return jq.each(function(){ var opts = $(this).tabs('options'); var wrap = $(this).find('>div.tabs-header>div.tabs-wrap'); var pos = Math.min(wrap._scrollLeft() - deltaX, getMaxScrollWidth()); // if ($.browser.msie){ // wrap.animate({scrollLeft: pos}, opts.scrollDuration); // } else if ($.browser.mozilla){ // wrap.animate({scrollLeft: -pos}, opts.scrollDuration); // } else { // wrap.animate({scrollLeft: wrap[0].scrollWidth - wrap[0].clientWidth - pos}, opts.scrollDuration); // } if ($._rtlScrollType == 'reverse'){ wrap.animate({scrollLeft: pos}, opts.scrollDuration); } else if ($._rtlScrollType == 'negative'){ wrap.animate({scrollLeft: -pos}, opts.scrollDuration); } else { wrap.animate({scrollLeft: wrap[0].scrollWidth - wrap[0].clientWidth - pos}, opts.scrollDuration); } function getMaxScrollWidth(){ var w = 0; var ul = wrap.children('ul'); ul.children('li').each(function(){ w += $(this).outerWidth(true); }); return w - wrap.width() + (ul.outerWidth() - ul.width()); } }); } $.fn.combo.methods.showPanel = function(jq){ return jq.each(function(){ var target = this; var state = $.data(target, 'combo'); var combo = state.combo; var panel = state.panel; var opts = $(target).combo('options'); var palOpts = panel.panel('options'); palOpts.comboTarget = target; // store the target combo element if (palOpts.closed){ panel.panel('panel').show().css({ zIndex: ($.fn.menu ? $.fn.menu.defaults.zIndex++ : $.fn.window.defaults.zIndex++), left: -999999 }); panel.panel('resize', { width: (opts.panelWidth ? opts.panelWidth : combo._outerWidth()), height: opts.panelHeight }); panel.panel('panel').hide(); panel.panel('open'); } (function(){ if (panel.is(':visible')){ panel.panel('move', { left:getLeft(), top:getTop() }); setTimeout(arguments.callee, 200); } })(); function getLeft(){ var left = combo.offset().left; if (opts.panelAlign == 'right'){ left += combo._outerWidth() - panel._outerWidth(); } return left; } function getTop(){ var top = combo.offset().top + combo._outerHeight(); if (top + panel._outerHeight() > $(window)._outerHeight() + $(document).scrollTop()){ top = combo.offset().top - panel._outerHeight(); } if (top < $(document).scrollTop()){ top = combo.offset().top + combo._outerHeight(); } return top; } }); } $.fn.menu.methods.show = function(jq, param){ return jq.each(function(){ var target = this; var left,top; param = param || {}; var menu = $(param.menu || target); if (menu.hasClass('menu-top')){ var opts = $.data(target, 'menu').options; $.extend(opts, param); left = opts.left - menu.outerWidth(); top = opts.top; if (opts.alignTo){ var at = $(opts.alignTo); left = at.offset().left; top = at.offset().top + at._outerHeight(); if (opts.align == 'right'){ left += at.outerWidth() - menu.outerWidth(); } } top = _fixTop(top, opts.alignTo); } else { var parent = param.parent; // the parent menu item left = parent.offset().left - menu.outerWidth() + 2; top = _fixTop(parent.offset().top - 3); } function _fixTop(top, alignTo){ if (top + menu.outerHeight() > $(window)._outerHeight() + $(document).scrollTop()){ if (alignTo){ var at = $(alignTo); top = at.offset().top - menu._outerHeight(); if (top < $(document).scrollTop()){ top = at.offset().top + at._outerHeight(); } } else { top = $(window)._outerHeight() + $(document).scrollTop() - menu.outerHeight() - 5; } } if (top < 0){top = 0;} return top; } menu.css({left:left,top:top}); menu.show(0, function(){ if (!menu[0].shadow){ menu[0].shadow = $('<div class="menu-shadow"></div>').insertAfter(menu); } menu[0].shadow.css({ display:'block', zIndex:$.fn.menu.defaults.zIndex++, left:menu.css('left'), top:menu.css('top'), width:menu.outerWidth(), height:menu.outerHeight() }); menu.css('z-index', $.fn.menu.defaults.zIndex++); if (menu.hasClass('menu-top')){ $.data(menu[0], 'menu').options.onShow.call(menu[0]); } }); }); } })(jQuery);
sansusan/yii2-easyui
assets/jquery-easyui-1.4.4/extensions/jquery-easyui-rtl/easyui-rtl.js
JavaScript
gpl-2.0
8,004
/* * drivers/usb/driver.c - most of the driver model stuff for usb * * (C) Copyright 2005 Greg Kroah-Hartman <gregkh@suse.de> * * based on drivers/usb/usb.c which had the following copyrights: * (C) Copyright Linus Torvalds 1999 * (C) Copyright Johannes Erdfelt 1999-2001 * (C) Copyright Andreas Gal 1999 * (C) Copyright Gregory P. Smith 1999 * (C) Copyright Deti Fliegl 1999 (new USB architecture) * (C) Copyright Randy Dunlap 2000 * (C) Copyright David Brownell 2000-2004 * (C) Copyright Yggdrasil Computing, Inc. 2000 * (usb_device_id matching changes by Adam J. Richter) * (C) Copyright Greg Kroah-Hartman 2002-2003 * * NOTE! This is not actually a driver at all, rather this is * just a collection of helper routines that implement the * generic USB things that the real drivers can use.. * */ #include <linux/config.h> #include <linux/device.h> #include <linux/usb.h> #include "hcd.h" #include "usb.h" static int usb_match_one_id(struct usb_interface *interface, const struct usb_device_id *id); struct usb_dynid { struct list_head node; struct usb_device_id id; }; static int generic_probe(struct device *dev) { return 0; } static int generic_remove(struct device *dev) { struct usb_device *udev = to_usb_device(dev); /* if this is only an unbind, not a physical disconnect, then * unconfigure the device */ if (udev->state == USB_STATE_CONFIGURED) usb_set_configuration(udev, 0); /* in case the call failed or the device was suspended */ if (udev->state >= USB_STATE_CONFIGURED) usb_disable_device(udev, 0); return 0; } struct device_driver usb_generic_driver = { .owner = THIS_MODULE, .name = "usb", .bus = &usb_bus_type, .probe = generic_probe, .remove = generic_remove, }; /* Fun hack to determine if the struct device is a * usb device or a usb interface. */ int usb_generic_driver_data; #ifdef CONFIG_HOTPLUG /* * Adds a new dynamic USBdevice ID to this driver, * and cause the driver to probe for all devices again. */ static ssize_t store_new_id(struct device_driver *driver, const char *buf, size_t count) { struct usb_driver *usb_drv = to_usb_driver(driver); struct usb_dynid *dynid; u32 idVendor = 0; u32 idProduct = 0; int fields = 0; fields = sscanf(buf, "%x %x", &idVendor, &idProduct); if (fields < 2) return -EINVAL; dynid = kzalloc(sizeof(*dynid), GFP_KERNEL); if (!dynid) return -ENOMEM; INIT_LIST_HEAD(&dynid->node); dynid->id.idVendor = idVendor; dynid->id.idProduct = idProduct; dynid->id.match_flags = USB_DEVICE_ID_MATCH_DEVICE; spin_lock(&usb_drv->dynids.lock); list_add_tail(&usb_drv->dynids.list, &dynid->node); spin_unlock(&usb_drv->dynids.lock); if (get_driver(driver)) { driver_attach(driver); put_driver(driver); } return count; } static DRIVER_ATTR(new_id, S_IWUSR, NULL, store_new_id); static int usb_create_newid_file(struct usb_driver *usb_drv) { int error = 0; if (usb_drv->no_dynamic_id) goto exit; if (usb_drv->probe != NULL) error = sysfs_create_file(&usb_drv->driver.kobj, &driver_attr_new_id.attr); exit: return error; } static void usb_remove_newid_file(struct usb_driver *usb_drv) { if (usb_drv->no_dynamic_id) return; if (usb_drv->probe != NULL) sysfs_remove_file(&usb_drv->driver.kobj, &driver_attr_new_id.attr); } static void usb_free_dynids(struct usb_driver *usb_drv) { struct usb_dynid *dynid, *n; spin_lock(&usb_drv->dynids.lock); list_for_each_entry_safe(dynid, n, &usb_drv->dynids.list, node) { list_del(&dynid->node); kfree(dynid); } spin_unlock(&usb_drv->dynids.lock); } #else static inline int usb_create_newid_file(struct usb_driver *usb_drv) { return 0; } static void usb_remove_newid_file(struct usb_driver *usb_drv) { } static inline void usb_free_dynids(struct usb_driver *usb_drv) { } #endif static const struct usb_device_id *usb_match_dynamic_id(struct usb_interface *intf, struct usb_driver *drv) { struct usb_dynid *dynid; spin_lock(&drv->dynids.lock); list_for_each_entry(dynid, &drv->dynids.list, node) { if (usb_match_one_id(intf, &dynid->id)) { spin_unlock(&drv->dynids.lock); return &dynid->id; } } spin_unlock(&drv->dynids.lock); return NULL; } /* called from driver core with usb_bus_type.subsys writelock */ static int usb_probe_interface(struct device *dev) { struct usb_interface * intf = to_usb_interface(dev); struct usb_driver * driver = to_usb_driver(dev->driver); const struct usb_device_id *id; int error = -ENODEV; dev_dbg(dev, "%s\n", __FUNCTION__); if (!driver->probe) return error; /* FIXME we'd much prefer to just resume it ... */ if (interface_to_usbdev(intf)->state == USB_STATE_SUSPENDED) return -EHOSTUNREACH; id = usb_match_id(intf, driver->id_table); if (!id) id = usb_match_dynamic_id(intf, driver); if (id) { dev_dbg(dev, "%s - got id\n", __FUNCTION__); /* Interface "power state" doesn't correspond to any hardware * state whatsoever. We use it to record when it's bound to * a driver that may start I/0: it's not frozen/quiesced. */ mark_active(intf); intf->condition = USB_INTERFACE_BINDING; error = driver->probe(intf, id); if (error) { mark_quiesced(intf); intf->condition = USB_INTERFACE_UNBOUND; } else intf->condition = USB_INTERFACE_BOUND; } return error; } /* called from driver core with usb_bus_type.subsys writelock */ static int usb_unbind_interface(struct device *dev) { struct usb_interface *intf = to_usb_interface(dev); struct usb_driver *driver = to_usb_driver(intf->dev.driver); intf->condition = USB_INTERFACE_UNBINDING; /* release all urbs for this interface */ usb_disable_interface(interface_to_usbdev(intf), intf); if (driver && driver->disconnect) driver->disconnect(intf); /* reset other interface state */ usb_set_interface(interface_to_usbdev(intf), intf->altsetting[0].desc.bInterfaceNumber, 0); usb_set_intfdata(intf, NULL); intf->condition = USB_INTERFACE_UNBOUND; mark_quiesced(intf); return 0; } /* returns 0 if no match, 1 if match */ static int usb_match_one_id(struct usb_interface *interface, const struct usb_device_id *id) { struct usb_host_interface *intf; struct usb_device *dev; /* proc_connectinfo in devio.c may call us with id == NULL. */ if (id == NULL) return 0; intf = interface->cur_altsetting; dev = interface_to_usbdev(interface); if ((id->match_flags & USB_DEVICE_ID_MATCH_VENDOR) && id->idVendor != le16_to_cpu(dev->descriptor.idVendor)) return 0; if ((id->match_flags & USB_DEVICE_ID_MATCH_PRODUCT) && id->idProduct != le16_to_cpu(dev->descriptor.idProduct)) return 0; /* No need to test id->bcdDevice_lo != 0, since 0 is never greater than any unsigned number. */ if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_LO) && (id->bcdDevice_lo > le16_to_cpu(dev->descriptor.bcdDevice))) return 0; if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_HI) && (id->bcdDevice_hi < le16_to_cpu(dev->descriptor.bcdDevice))) return 0; if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_CLASS) && (id->bDeviceClass != dev->descriptor.bDeviceClass)) return 0; if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_SUBCLASS) && (id->bDeviceSubClass!= dev->descriptor.bDeviceSubClass)) return 0; if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_PROTOCOL) && (id->bDeviceProtocol != dev->descriptor.bDeviceProtocol)) return 0; if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_CLASS) && (id->bInterfaceClass != intf->desc.bInterfaceClass)) return 0; if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_SUBCLASS) && (id->bInterfaceSubClass != intf->desc.bInterfaceSubClass)) return 0; if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_PROTOCOL) && (id->bInterfaceProtocol != intf->desc.bInterfaceProtocol)) return 0; return 1; } /** * usb_match_id - find first usb_device_id matching device or interface * @interface: the interface of interest * @id: array of usb_device_id structures, terminated by zero entry * * usb_match_id searches an array of usb_device_id's and returns * the first one matching the device or interface, or null. * This is used when binding (or rebinding) a driver to an interface. * Most USB device drivers will use this indirectly, through the usb core, * but some layered driver frameworks use it directly. * These device tables are exported with MODULE_DEVICE_TABLE, through * modutils, to support the driver loading functionality of USB hotplugging. * * What Matches: * * The "match_flags" element in a usb_device_id controls which * members are used. If the corresponding bit is set, the * value in the device_id must match its corresponding member * in the device or interface descriptor, or else the device_id * does not match. * * "driver_info" is normally used only by device drivers, * but you can create a wildcard "matches anything" usb_device_id * as a driver's "modules.usbmap" entry if you provide an id with * only a nonzero "driver_info" field. If you do this, the USB device * driver's probe() routine should use additional intelligence to * decide whether to bind to the specified interface. * * What Makes Good usb_device_id Tables: * * The match algorithm is very simple, so that intelligence in * driver selection must come from smart driver id records. * Unless you have good reasons to use another selection policy, * provide match elements only in related groups, and order match * specifiers from specific to general. Use the macros provided * for that purpose if you can. * * The most specific match specifiers use device descriptor * data. These are commonly used with product-specific matches; * the USB_DEVICE macro lets you provide vendor and product IDs, * and you can also match against ranges of product revisions. * These are widely used for devices with application or vendor * specific bDeviceClass values. * * Matches based on device class/subclass/protocol specifications * are slightly more general; use the USB_DEVICE_INFO macro, or * its siblings. These are used with single-function devices * where bDeviceClass doesn't specify that each interface has * its own class. * * Matches based on interface class/subclass/protocol are the * most general; they let drivers bind to any interface on a * multiple-function device. Use the USB_INTERFACE_INFO * macro, or its siblings, to match class-per-interface style * devices (as recorded in bDeviceClass). * * Within those groups, remember that not all combinations are * meaningful. For example, don't give a product version range * without vendor and product IDs; or specify a protocol without * its associated class and subclass. */ const struct usb_device_id *usb_match_id(struct usb_interface *interface, const struct usb_device_id *id) { /* proc_connectinfo in devio.c may call us with id == NULL. */ if (id == NULL) return NULL; /* It is important to check that id->driver_info is nonzero, since an entry that is all zeroes except for a nonzero id->driver_info is the way to create an entry that indicates that the driver want to examine every device and interface. */ for (; id->idVendor || id->bDeviceClass || id->bInterfaceClass || id->driver_info; id++) { if (usb_match_one_id(interface, id)) return id; } return NULL; } EXPORT_SYMBOL(usb_match_id); int usb_device_match(struct device *dev, struct device_driver *drv) { struct usb_interface *intf; struct usb_driver *usb_drv; const struct usb_device_id *id; /* check for generic driver, which we don't match any device with */ if (drv == &usb_generic_driver) return 0; intf = to_usb_interface(dev); usb_drv = to_usb_driver(drv); id = usb_match_id(intf, usb_drv->id_table); if (id) return 1; id = usb_match_dynamic_id(intf, usb_drv); if (id) return 1; return 0; } /** * usb_register_driver - register a USB driver * @new_driver: USB operations for the driver * @owner: module owner of this driver. * * Registers a USB driver with the USB core. The list of unattached * interfaces will be rescanned whenever a new driver is added, allowing * the new driver to attach to any recognized devices. * Returns a negative error code on failure and 0 on success. * * NOTE: if you want your driver to use the USB major number, you must call * usb_register_dev() to enable that functionality. This function no longer * takes care of that. */ int usb_register_driver(struct usb_driver *new_driver, struct module *owner) { int retval = 0; if (usb_disabled()) return -ENODEV; new_driver->driver.name = (char *)new_driver->name; new_driver->driver.bus = &usb_bus_type; new_driver->driver.probe = usb_probe_interface; new_driver->driver.remove = usb_unbind_interface; new_driver->driver.owner = owner; spin_lock_init(&new_driver->dynids.lock); INIT_LIST_HEAD(&new_driver->dynids.list); retval = driver_register(&new_driver->driver); if (!retval) { pr_info("%s: registered new driver %s\n", usbcore_name, new_driver->name); usbfs_update_special(); usb_create_newid_file(new_driver); } else { printk(KERN_ERR "%s: error %d registering driver %s\n", usbcore_name, retval, new_driver->name); } return retval; } EXPORT_SYMBOL(usb_register_driver); /** * usb_deregister - unregister a USB driver * @driver: USB operations of the driver to unregister * Context: must be able to sleep * * Unlinks the specified driver from the internal USB driver list. * * NOTE: If you called usb_register_dev(), you still need to call * usb_deregister_dev() to clean up your driver's allocated minor numbers, * this * call will no longer do it for you. */ void usb_deregister(struct usb_driver *driver) { pr_info("%s: deregistering driver %s\n", usbcore_name, driver->name); usb_remove_newid_file(driver); usb_free_dynids(driver); driver_unregister(&driver->driver); usbfs_update_special(); } EXPORT_SYMBOL(usb_deregister);
odit/rv042
linux/kernel_2.6/linux/drivers/usb/core/driver.c
C
gpl-2.0
13,941
#!/usr/bin/python # # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 Google 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 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. """Burnin program """ import sys import optparse import time import socket import urllib from itertools import izip, islice, cycle from cStringIO import StringIO from ganeti import opcodes from ganeti import constants from ganeti import cli from ganeti import errors from ganeti import utils from ganeti import hypervisor from ganeti import compat from ganeti import pathutils from ganeti.confd import client as confd_client USAGE = ("\tburnin -o OS_NAME [options...] instance_name ...") MAX_RETRIES = 3 LOG_HEADERS = { 0: "- ", 1: "* ", 2: "", } #: Disk templates supporting a single node _SINGLE_NODE_DISK_TEMPLATES = compat.UniqueFrozenset([ constants.DT_DISKLESS, constants.DT_PLAIN, constants.DT_FILE, constants.DT_SHARED_FILE, constants.DT_EXT, constants.DT_RBD, ]) _SUPPORTED_DISK_TEMPLATES = compat.UniqueFrozenset([ constants.DT_DISKLESS, constants.DT_DRBD8, constants.DT_EXT, constants.DT_FILE, constants.DT_PLAIN, constants.DT_RBD, constants.DT_SHARED_FILE, ]) #: Disk templates for which import/export is tested _IMPEXP_DISK_TEMPLATES = (_SUPPORTED_DISK_TEMPLATES - frozenset([ constants.DT_DISKLESS, constants.DT_FILE, constants.DT_SHARED_FILE, ])) class InstanceDown(Exception): """The checked instance was not up""" class BurninFailure(Exception): """Failure detected during burning""" def Usage(): """Shows program usage information and exits the program.""" print >> sys.stderr, "Usage:" print >> sys.stderr, USAGE sys.exit(2) def Log(msg, *args, **kwargs): """Simple function that prints out its argument. """ if args: msg = msg % args indent = kwargs.get("indent", 0) sys.stdout.write("%*s%s%s\n" % (2 * indent, "", LOG_HEADERS.get(indent, " "), msg)) sys.stdout.flush() def Err(msg, exit_code=1): """Simple error logging that prints to stderr. """ sys.stderr.write(msg + "\n") sys.stderr.flush() sys.exit(exit_code) class SimpleOpener(urllib.FancyURLopener): """A simple url opener""" # pylint: disable=W0221 def prompt_user_passwd(self, host, realm, clear_cache=0): """No-interaction version of prompt_user_passwd.""" # we follow parent class' API # pylint: disable=W0613 return None, None def http_error_default(self, url, fp, errcode, errmsg, headers): """Custom error handling""" # make sure sockets are not left in CLOSE_WAIT, this is similar # but with a different exception to the BasicURLOpener class _ = fp.read() # throw away data fp.close() raise InstanceDown("HTTP error returned: code %s, msg %s" % (errcode, errmsg)) OPTIONS = [ cli.cli_option("-o", "--os", dest="os", default=None, help="OS to use during burnin", metavar="<OS>", completion_suggest=cli.OPT_COMPL_ONE_OS), cli.HYPERVISOR_OPT, cli.OSPARAMS_OPT, cli.cli_option("--disk-size", dest="disk_size", help="Disk size (determines disk count)", default="128m", type="string", metavar="<size,size,...>", completion_suggest=("128M 512M 1G 4G 1G,256M" " 4G,1G,1G 10G").split()), cli.cli_option("--disk-growth", dest="disk_growth", help="Disk growth", default="128m", type="string", metavar="<size,size,...>"), cli.cli_option("--mem-size", dest="mem_size", help="Memory size", default=None, type="unit", metavar="<size>", completion_suggest=("128M 256M 512M 1G 4G 8G" " 12G 16G").split()), cli.cli_option("--maxmem-size", dest="maxmem_size", help="Max Memory size", default=256, type="unit", metavar="<size>", completion_suggest=("128M 256M 512M 1G 4G 8G" " 12G 16G").split()), cli.cli_option("--minmem-size", dest="minmem_size", help="Min Memory size", default=128, type="unit", metavar="<size>", completion_suggest=("128M 256M 512M 1G 4G 8G" " 12G 16G").split()), cli.cli_option("--vcpu-count", dest="vcpu_count", help="VCPU count", default=3, type="unit", metavar="<count>", completion_suggest=("1 2 3 4").split()), cli.DEBUG_OPT, cli.VERBOSE_OPT, cli.NOIPCHECK_OPT, cli.NONAMECHECK_OPT, cli.EARLY_RELEASE_OPT, cli.cli_option("--no-replace1", dest="do_replace1", help="Skip disk replacement with the same secondary", action="store_false", default=True), cli.cli_option("--no-replace2", dest="do_replace2", help="Skip disk replacement with a different secondary", action="store_false", default=True), cli.cli_option("--no-failover", dest="do_failover", help="Skip instance failovers", action="store_false", default=True), cli.cli_option("--no-migrate", dest="do_migrate", help="Skip instance live migration", action="store_false", default=True), cli.cli_option("--no-move", dest="do_move", help="Skip instance moves", action="store_false", default=True), cli.cli_option("--no-importexport", dest="do_importexport", help="Skip instance export/import", action="store_false", default=True), cli.cli_option("--no-startstop", dest="do_startstop", help="Skip instance stop/start", action="store_false", default=True), cli.cli_option("--no-reinstall", dest="do_reinstall", help="Skip instance reinstall", action="store_false", default=True), cli.cli_option("--no-reboot", dest="do_reboot", help="Skip instance reboot", action="store_false", default=True), cli.cli_option("--no-renamesame", dest="do_renamesame", help="Skip instance rename to same name", action="store_false", default=True), cli.cli_option("--reboot-types", dest="reboot_types", help="Specify the reboot types", default=None), cli.cli_option("--no-activate-disks", dest="do_activate_disks", help="Skip disk activation/deactivation", action="store_false", default=True), cli.cli_option("--no-add-disks", dest="do_addremove_disks", help="Skip disk addition/removal", action="store_false", default=True), cli.cli_option("--no-add-nics", dest="do_addremove_nics", help="Skip NIC addition/removal", action="store_false", default=True), cli.cli_option("--no-nics", dest="nics", help="No network interfaces", action="store_const", const=[], default=[{}]), cli.cli_option("--no-confd", dest="do_confd_tests", help="Skip confd queries", action="store_false", default=constants.ENABLE_CONFD), cli.cli_option("--rename", dest="rename", default=None, help=("Give one unused instance name which is taken" " to start the renaming sequence"), metavar="<instance_name>"), cli.cli_option("-t", "--disk-template", dest="disk_template", choices=list(_SUPPORTED_DISK_TEMPLATES), default=constants.DT_DRBD8, help=("Disk template (default %s, otherwise one of %s)" % (constants.DT_DRBD8, utils.CommaJoin(_SUPPORTED_DISK_TEMPLATES)))), cli.cli_option("-n", "--nodes", dest="nodes", default="", help=("Comma separated list of nodes to perform" " the burnin on (defaults to all nodes)"), completion_suggest=cli.OPT_COMPL_MANY_NODES), cli.cli_option("-I", "--iallocator", dest="iallocator", default=None, type="string", help=("Perform the allocation using an iallocator" " instead of fixed node spread (node restrictions no" " longer apply, therefore -n/--nodes must not be" " used"), completion_suggest=cli.OPT_COMPL_ONE_IALLOCATOR), cli.cli_option("-p", "--parallel", default=False, action="store_true", dest="parallel", help=("Enable parallelization of some operations in" " order to speed burnin or to test granular locking")), cli.cli_option("--net-timeout", default=15, type="int", dest="net_timeout", help=("The instance check network timeout in seconds" " (defaults to 15 seconds)"), completion_suggest="15 60 300 900".split()), cli.cli_option("-C", "--http-check", default=False, action="store_true", dest="http_check", help=("Enable checking of instance status via http," " looking for /hostname.txt that should contain the" " name of the instance")), cli.cli_option("-K", "--keep-instances", default=False, action="store_true", dest="keep_instances", help=("Leave instances on the cluster after burnin," " for investigation in case of errors or simply" " to use them")), cli.REASON_OPT, ] # Mainly used for bash completion ARGUMENTS = [cli.ArgInstance(min=1)] def _DoCheckInstances(fn): """Decorator for checking instances. """ def wrapper(self, *args, **kwargs): val = fn(self, *args, **kwargs) for instance in self.instances: self._CheckInstanceAlive(instance) # pylint: disable=W0212 return val return wrapper def _DoBatch(retry): """Decorator for possible batch operations. Must come after the _DoCheckInstances decorator (if any). @param retry: whether this is a retryable batch, will be passed to StartBatch """ def wrap(fn): def batched(self, *args, **kwargs): self.StartBatch(retry) val = fn(self, *args, **kwargs) self.CommitQueue() return val return batched return wrap class Burner(object): """Burner class.""" def __init__(self): """Constructor.""" self.url_opener = SimpleOpener() self._feed_buf = StringIO() self.nodes = [] self.instances = [] self.to_rem = [] self.queued_ops = [] self.opts = None self.queue_retry = False self.disk_count = self.disk_growth = self.disk_size = None self.hvp = self.bep = None self.ParseOptions() self.cl = cli.GetClient() self.GetState() def ClearFeedbackBuf(self): """Clear the feedback buffer.""" self._feed_buf.truncate(0) def GetFeedbackBuf(self): """Return the contents of the buffer.""" return self._feed_buf.getvalue() def Feedback(self, msg): """Acumulate feedback in our buffer.""" formatted_msg = "%s %s" % (time.ctime(utils.MergeTime(msg[0])), msg[2]) self._feed_buf.write(formatted_msg + "\n") if self.opts.verbose: Log(formatted_msg, indent=3) def MaybeRetry(self, retry_count, msg, fn, *args): """Possibly retry a given function execution. @type retry_count: int @param retry_count: retry counter: - 0: non-retryable action - 1: last retry for a retryable action - MAX_RETRIES: original try for a retryable action @type msg: str @param msg: the kind of the operation @type fn: callable @param fn: the function to be called """ try: val = fn(*args) if retry_count > 0 and retry_count < MAX_RETRIES: Log("Idempotent %s succeeded after %d retries", msg, MAX_RETRIES - retry_count) return val except Exception, err: # pylint: disable=W0703 if retry_count == 0: Log("Non-idempotent %s failed, aborting", msg) raise elif retry_count == 1: Log("Idempotent %s repeated failure, aborting", msg) raise else: Log("Idempotent %s failed, retry #%d/%d: %s", msg, MAX_RETRIES - retry_count + 1, MAX_RETRIES, err) self.MaybeRetry(retry_count - 1, msg, fn, *args) def _ExecOp(self, *ops): """Execute one or more opcodes and manage the exec buffer. @return: if only opcode has been passed, we return its result; otherwise we return the list of results """ job_id = cli.SendJob(ops, cl=self.cl) results = cli.PollJob(job_id, cl=self.cl, feedback_fn=self.Feedback) if len(ops) == 1: return results[0] else: return results def ExecOp(self, retry, *ops): """Execute one or more opcodes and manage the exec buffer. @return: if only opcode has been passed, we return its result; otherwise we return the list of results """ if retry: rval = MAX_RETRIES else: rval = 0 cli.SetGenericOpcodeOpts(ops, self.opts) return self.MaybeRetry(rval, "opcode", self._ExecOp, *ops) def ExecOrQueue(self, name, ops, post_process=None): """Execute an opcode and manage the exec buffer.""" if self.opts.parallel: cli.SetGenericOpcodeOpts(ops, self.opts) self.queued_ops.append((ops, name, post_process)) else: val = self.ExecOp(self.queue_retry, *ops) # pylint: disable=W0142 if post_process is not None: post_process() return val def StartBatch(self, retry): """Start a new batch of jobs. @param retry: whether this is a retryable batch """ self.queued_ops = [] self.queue_retry = retry def CommitQueue(self): """Execute all submitted opcodes in case of parallel burnin""" if not self.opts.parallel or not self.queued_ops: return if self.queue_retry: rval = MAX_RETRIES else: rval = 0 try: results = self.MaybeRetry(rval, "jobset", self.ExecJobSet, self.queued_ops) finally: self.queued_ops = [] return results def ExecJobSet(self, jobs): """Execute a set of jobs and return once all are done. The method will return the list of results, if all jobs are successful. Otherwise, OpExecError will be raised from within cli.py. """ self.ClearFeedbackBuf() jex = cli.JobExecutor(cl=self.cl, feedback_fn=self.Feedback) for ops, name, _ in jobs: jex.QueueJob(name, *ops) # pylint: disable=W0142 try: results = jex.GetResults() except Exception, err: # pylint: disable=W0703 Log("Jobs failed: %s", err) raise BurninFailure() fail = False val = [] for (_, name, post_process), (success, result) in zip(jobs, results): if success: if post_process: try: post_process() except Exception, err: # pylint: disable=W0703 Log("Post process call for job %s failed: %s", name, err) fail = True val.append(result) else: fail = True if fail: raise BurninFailure() return val def ParseOptions(self): """Parses the command line options. In case of command line errors, it will show the usage and exit the program. """ parser = optparse.OptionParser(usage="\n%s" % USAGE, version=("%%prog (ganeti) %s" % constants.RELEASE_VERSION), option_list=OPTIONS) options, args = parser.parse_args() if len(args) < 1 or options.os is None: Usage() if options.mem_size: options.maxmem_size = options.mem_size options.minmem_size = options.mem_size elif options.minmem_size > options.maxmem_size: Err("Maximum memory lower than minimum memory") if options.disk_template not in _SUPPORTED_DISK_TEMPLATES: Err("Unknown or unsupported disk template '%s'" % options.disk_template) if options.disk_template == constants.DT_DISKLESS: disk_size = disk_growth = [] options.do_addremove_disks = False else: disk_size = [utils.ParseUnit(v) for v in options.disk_size.split(",")] disk_growth = [utils.ParseUnit(v) for v in options.disk_growth.split(",")] if len(disk_growth) != len(disk_size): Err("Wrong disk sizes/growth combination") if ((disk_size and options.disk_template == constants.DT_DISKLESS) or (not disk_size and options.disk_template != constants.DT_DISKLESS)): Err("Wrong disk count/disk template combination") self.disk_size = disk_size self.disk_growth = disk_growth self.disk_count = len(disk_size) if options.nodes and options.iallocator: Err("Give either the nodes option or the iallocator option, not both") if options.http_check and not options.name_check: Err("Can't enable HTTP checks without name checks") self.opts = options self.instances = args self.bep = { constants.BE_MINMEM: options.minmem_size, constants.BE_MAXMEM: options.maxmem_size, constants.BE_VCPUS: options.vcpu_count, } self.hypervisor = None self.hvp = {} if options.hypervisor: self.hypervisor, self.hvp = options.hypervisor if options.reboot_types is None: options.reboot_types = constants.REBOOT_TYPES else: options.reboot_types = options.reboot_types.split(",") rt_diff = set(options.reboot_types).difference(constants.REBOOT_TYPES) if rt_diff: Err("Invalid reboot types specified: %s" % utils.CommaJoin(rt_diff)) socket.setdefaulttimeout(options.net_timeout) def GetState(self): """Read the cluster state from the master daemon.""" if self.opts.nodes: names = self.opts.nodes.split(",") else: names = [] try: op = opcodes.OpNodeQuery(output_fields=["name", "offline", "drained"], names=names, use_locking=True) result = self.ExecOp(True, op) except errors.GenericError, err: err_code, msg = cli.FormatError(err) Err(msg, exit_code=err_code) self.nodes = [data[0] for data in result if not (data[1] or data[2])] op_diagnose = opcodes.OpOsDiagnose(output_fields=["name", "variants", "hidden"], names=[]) result = self.ExecOp(True, op_diagnose) if not result: Err("Can't get the OS list") found = False for (name, variants, _) in result: if self.opts.os in cli.CalculateOSNames(name, variants): found = True break if not found: Err("OS '%s' not found" % self.opts.os) cluster_info = self.cl.QueryClusterInfo() self.cluster_info = cluster_info if not self.cluster_info: Err("Can't get cluster info") default_nic_params = self.cluster_info["nicparams"][constants.PP_DEFAULT] self.cluster_default_nicparams = default_nic_params if self.hypervisor is None: self.hypervisor = self.cluster_info["default_hypervisor"] self.hv_can_migrate = \ hypervisor.GetHypervisorClass(self.hypervisor).CAN_MIGRATE @_DoCheckInstances @_DoBatch(False) def BurnCreateInstances(self): """Create the given instances. """ self.to_rem = [] mytor = izip(cycle(self.nodes), islice(cycle(self.nodes), 1, None), self.instances) Log("Creating instances") for pnode, snode, instance in mytor: Log("instance %s", instance, indent=1) if self.opts.iallocator: pnode = snode = None msg = "with iallocator %s" % self.opts.iallocator elif self.opts.disk_template not in constants.DTS_INT_MIRROR: snode = None msg = "on %s" % pnode else: msg = "on %s, %s" % (pnode, snode) Log(msg, indent=2) op = opcodes.OpInstanceCreate(instance_name=instance, disks=[{"size": size} for size in self.disk_size], disk_template=self.opts.disk_template, nics=self.opts.nics, mode=constants.INSTANCE_CREATE, os_type=self.opts.os, pnode=pnode, snode=snode, start=True, ip_check=self.opts.ip_check, name_check=self.opts.name_check, wait_for_sync=True, file_driver="loop", file_storage_dir=None, iallocator=self.opts.iallocator, beparams=self.bep, hvparams=self.hvp, hypervisor=self.hypervisor, osparams=self.opts.osparams, ) remove_instance = lambda name: lambda: self.to_rem.append(name) self.ExecOrQueue(instance, [op], post_process=remove_instance(instance)) @_DoBatch(False) def BurnModifyRuntimeMemory(self): """Alter the runtime memory.""" Log("Setting instance runtime memory") for instance in self.instances: Log("instance %s", instance, indent=1) tgt_mem = self.bep[constants.BE_MINMEM] op = opcodes.OpInstanceSetParams(instance_name=instance, runtime_mem=tgt_mem) Log("Set memory to %s MB", tgt_mem, indent=2) self.ExecOrQueue(instance, [op]) @_DoBatch(False) def BurnGrowDisks(self): """Grow both the os and the swap disks by the requested amount, if any.""" Log("Growing disks") for instance in self.instances: Log("instance %s", instance, indent=1) for idx, growth in enumerate(self.disk_growth): if growth > 0: op = opcodes.OpInstanceGrowDisk(instance_name=instance, disk=idx, amount=growth, wait_for_sync=True) Log("increase disk/%s by %s MB", idx, growth, indent=2) self.ExecOrQueue(instance, [op]) @_DoBatch(True) def BurnReplaceDisks1D8(self): """Replace disks on primary and secondary for drbd8.""" Log("Replacing disks on the same nodes") early_release = self.opts.early_release for instance in self.instances: Log("instance %s", instance, indent=1) ops = [] for mode in constants.REPLACE_DISK_SEC, constants.REPLACE_DISK_PRI: op = opcodes.OpInstanceReplaceDisks(instance_name=instance, mode=mode, disks=list(range(self.disk_count)), early_release=early_release) Log("run %s", mode, indent=2) ops.append(op) self.ExecOrQueue(instance, ops) @_DoBatch(True) def BurnReplaceDisks2(self): """Replace secondary node.""" Log("Changing the secondary node") mode = constants.REPLACE_DISK_CHG mytor = izip(islice(cycle(self.nodes), 2, None), self.instances) for tnode, instance in mytor: Log("instance %s", instance, indent=1) if self.opts.iallocator: tnode = None msg = "with iallocator %s" % self.opts.iallocator else: msg = tnode op = opcodes.OpInstanceReplaceDisks(instance_name=instance, mode=mode, remote_node=tnode, iallocator=self.opts.iallocator, disks=[], early_release=self.opts.early_release) Log("run %s %s", mode, msg, indent=2) self.ExecOrQueue(instance, [op]) @_DoCheckInstances @_DoBatch(False) def BurnFailover(self): """Failover the instances.""" Log("Failing over instances") for instance in self.instances: Log("instance %s", instance, indent=1) op = opcodes.OpInstanceFailover(instance_name=instance, ignore_consistency=False) self.ExecOrQueue(instance, [op]) @_DoCheckInstances @_DoBatch(False) def BurnMove(self): """Move the instances.""" Log("Moving instances") mytor = izip(islice(cycle(self.nodes), 1, None), self.instances) for tnode, instance in mytor: Log("instance %s", instance, indent=1) op = opcodes.OpInstanceMove(instance_name=instance, target_node=tnode) self.ExecOrQueue(instance, [op]) @_DoBatch(False) def BurnMigrate(self): """Migrate the instances.""" Log("Migrating instances") for instance in self.instances: Log("instance %s", instance, indent=1) op1 = opcodes.OpInstanceMigrate(instance_name=instance, mode=None, cleanup=False) op2 = opcodes.OpInstanceMigrate(instance_name=instance, mode=None, cleanup=True) Log("migration and migration cleanup", indent=2) self.ExecOrQueue(instance, [op1, op2]) @_DoCheckInstances @_DoBatch(False) def BurnImportExport(self): """Export the instance, delete it, and import it back. """ Log("Exporting and re-importing instances") mytor = izip(cycle(self.nodes), islice(cycle(self.nodes), 1, None), islice(cycle(self.nodes), 2, None), self.instances) for pnode, snode, enode, instance in mytor: Log("instance %s", instance, indent=1) # read the full name of the instance nam_op = opcodes.OpInstanceQuery(output_fields=["name"], names=[instance], use_locking=True) full_name = self.ExecOp(False, nam_op)[0][0] if self.opts.iallocator: pnode = snode = None import_log_msg = ("import from %s" " with iallocator %s" % (enode, self.opts.iallocator)) elif self.opts.disk_template not in constants.DTS_INT_MIRROR: snode = None import_log_msg = ("import from %s to %s" % (enode, pnode)) else: import_log_msg = ("import from %s to %s, %s" % (enode, pnode, snode)) exp_op = opcodes.OpBackupExport(instance_name=instance, target_node=enode, mode=constants.EXPORT_MODE_LOCAL, shutdown=True) rem_op = opcodes.OpInstanceRemove(instance_name=instance, ignore_failures=True) imp_dir = utils.PathJoin(pathutils.EXPORT_DIR, full_name) imp_op = opcodes.OpInstanceCreate(instance_name=instance, disks=[{"size": size} for size in self.disk_size], disk_template=self.opts.disk_template, nics=self.opts.nics, mode=constants.INSTANCE_IMPORT, src_node=enode, src_path=imp_dir, pnode=pnode, snode=snode, start=True, ip_check=self.opts.ip_check, name_check=self.opts.name_check, wait_for_sync=True, file_storage_dir=None, file_driver="loop", iallocator=self.opts.iallocator, beparams=self.bep, hvparams=self.hvp, osparams=self.opts.osparams, ) erem_op = opcodes.OpBackupRemove(instance_name=instance) Log("export to node %s", enode, indent=2) Log("remove instance", indent=2) Log(import_log_msg, indent=2) Log("remove export", indent=2) self.ExecOrQueue(instance, [exp_op, rem_op, imp_op, erem_op]) @staticmethod def StopInstanceOp(instance): """Stop given instance.""" return opcodes.OpInstanceShutdown(instance_name=instance) @staticmethod def StartInstanceOp(instance): """Start given instance.""" return opcodes.OpInstanceStartup(instance_name=instance, force=False) @staticmethod def RenameInstanceOp(instance, instance_new): """Rename instance.""" return opcodes.OpInstanceRename(instance_name=instance, new_name=instance_new) @_DoCheckInstances @_DoBatch(True) def BurnStopStart(self): """Stop/start the instances.""" Log("Stopping and starting instances") for instance in self.instances: Log("instance %s", instance, indent=1) op1 = self.StopInstanceOp(instance) op2 = self.StartInstanceOp(instance) self.ExecOrQueue(instance, [op1, op2]) @_DoBatch(False) def BurnRemove(self): """Remove the instances.""" Log("Removing instances") for instance in self.to_rem: Log("instance %s", instance, indent=1) op = opcodes.OpInstanceRemove(instance_name=instance, ignore_failures=True) self.ExecOrQueue(instance, [op]) def BurnRename(self): """Rename the instances. Note that this function will not execute in parallel, since we only have one target for rename. """ Log("Renaming instances") rename = self.opts.rename for instance in self.instances: Log("instance %s", instance, indent=1) op_stop1 = self.StopInstanceOp(instance) op_stop2 = self.StopInstanceOp(rename) op_rename1 = self.RenameInstanceOp(instance, rename) op_rename2 = self.RenameInstanceOp(rename, instance) op_start1 = self.StartInstanceOp(rename) op_start2 = self.StartInstanceOp(instance) self.ExecOp(False, op_stop1, op_rename1, op_start1) self._CheckInstanceAlive(rename) self.ExecOp(False, op_stop2, op_rename2, op_start2) self._CheckInstanceAlive(instance) @_DoCheckInstances @_DoBatch(True) def BurnReinstall(self): """Reinstall the instances.""" Log("Reinstalling instances") for instance in self.instances: Log("instance %s", instance, indent=1) op1 = self.StopInstanceOp(instance) op2 = opcodes.OpInstanceReinstall(instance_name=instance) Log("reinstall without passing the OS", indent=2) op3 = opcodes.OpInstanceReinstall(instance_name=instance, os_type=self.opts.os) Log("reinstall specifying the OS", indent=2) op4 = self.StartInstanceOp(instance) self.ExecOrQueue(instance, [op1, op2, op3, op4]) @_DoCheckInstances @_DoBatch(True) def BurnReboot(self): """Reboot the instances.""" Log("Rebooting instances") for instance in self.instances: Log("instance %s", instance, indent=1) ops = [] for reboot_type in self.opts.reboot_types: op = opcodes.OpInstanceReboot(instance_name=instance, reboot_type=reboot_type, ignore_secondaries=False) Log("reboot with type '%s'", reboot_type, indent=2) ops.append(op) self.ExecOrQueue(instance, ops) @_DoCheckInstances @_DoBatch(True) def BurnRenameSame(self): """Rename the instances to their own name.""" Log("Renaming the instances to their own name") for instance in self.instances: Log("instance %s", instance, indent=1) op1 = self.StopInstanceOp(instance) op2 = self.RenameInstanceOp(instance, instance) Log("rename to the same name", indent=2) op4 = self.StartInstanceOp(instance) self.ExecOrQueue(instance, [op1, op2, op4]) @_DoCheckInstances @_DoBatch(True) def BurnActivateDisks(self): """Activate and deactivate disks of the instances.""" Log("Activating/deactivating disks") for instance in self.instances: Log("instance %s", instance, indent=1) op_start = self.StartInstanceOp(instance) op_act = opcodes.OpInstanceActivateDisks(instance_name=instance) op_deact = opcodes.OpInstanceDeactivateDisks(instance_name=instance) op_stop = self.StopInstanceOp(instance) Log("activate disks when online", indent=2) Log("activate disks when offline", indent=2) Log("deactivate disks (when offline)", indent=2) self.ExecOrQueue(instance, [op_act, op_stop, op_act, op_deact, op_start]) @_DoCheckInstances @_DoBatch(False) def BurnAddRemoveDisks(self): """Add and remove an extra disk for the instances.""" Log("Adding and removing disks") for instance in self.instances: Log("instance %s", instance, indent=1) op_add = opcodes.OpInstanceSetParams( instance_name=instance, disks=[(constants.DDM_ADD, {"size": self.disk_size[0]})]) op_rem = opcodes.OpInstanceSetParams( instance_name=instance, disks=[(constants.DDM_REMOVE, {})]) op_stop = self.StopInstanceOp(instance) op_start = self.StartInstanceOp(instance) Log("adding a disk", indent=2) Log("removing last disk", indent=2) self.ExecOrQueue(instance, [op_add, op_stop, op_rem, op_start]) @_DoBatch(False) def BurnAddRemoveNICs(self): """Add, change and remove an extra NIC for the instances.""" Log("Adding and removing NICs") for instance in self.instances: Log("instance %s", instance, indent=1) op_add = opcodes.OpInstanceSetParams( instance_name=instance, nics=[(constants.DDM_ADD, {})]) op_chg = opcodes.OpInstanceSetParams( instance_name=instance, nics=[(constants.DDM_MODIFY, -1, {"mac": constants.VALUE_GENERATE})]) op_rem = opcodes.OpInstanceSetParams( instance_name=instance, nics=[(constants.DDM_REMOVE, {})]) Log("adding a NIC", indent=2) Log("changing a NIC", indent=2) Log("removing last NIC", indent=2) self.ExecOrQueue(instance, [op_add, op_chg, op_rem]) def ConfdCallback(self, reply): """Callback for confd queries""" if reply.type == confd_client.UPCALL_REPLY: if reply.server_reply.status != constants.CONFD_REPL_STATUS_OK: Err("Query %s gave non-ok status %s: %s" % (reply.orig_request, reply.server_reply.status, reply.server_reply)) if reply.orig_request.type == constants.CONFD_REQ_PING: Log("Ping: OK", indent=1) elif reply.orig_request.type == constants.CONFD_REQ_CLUSTER_MASTER: if reply.server_reply.answer == self.cluster_info["master"]: Log("Master: OK", indent=1) else: Err("Master: wrong: %s" % reply.server_reply.answer) elif reply.orig_request.type == constants.CONFD_REQ_NODE_ROLE_BYNAME: if reply.server_reply.answer == constants.CONFD_NODE_ROLE_MASTER: Log("Node role for master: OK", indent=1) else: Err("Node role for master: wrong: %s" % reply.server_reply.answer) def DoConfdRequestReply(self, req): self.confd_counting_callback.RegisterQuery(req.rsalt) self.confd_client.SendRequest(req, async=False) while not self.confd_counting_callback.AllAnswered(): if not self.confd_client.ReceiveReply(): Err("Did not receive all expected confd replies") break def BurnConfd(self): """Run confd queries for our instances. The following confd queries are tested: - CONFD_REQ_PING: simple ping - CONFD_REQ_CLUSTER_MASTER: cluster master - CONFD_REQ_NODE_ROLE_BYNAME: node role, for the master """ Log("Checking confd results") filter_callback = confd_client.ConfdFilterCallback(self.ConfdCallback) counting_callback = confd_client.ConfdCountingCallback(filter_callback) self.confd_counting_callback = counting_callback self.confd_client = confd_client.GetConfdClient(counting_callback) req = confd_client.ConfdClientRequest(type=constants.CONFD_REQ_PING) self.DoConfdRequestReply(req) req = confd_client.ConfdClientRequest( type=constants.CONFD_REQ_CLUSTER_MASTER) self.DoConfdRequestReply(req) req = confd_client.ConfdClientRequest( type=constants.CONFD_REQ_NODE_ROLE_BYNAME, query=self.cluster_info["master"]) self.DoConfdRequestReply(req) def _CheckInstanceAlive(self, instance): """Check if an instance is alive by doing http checks. This will try to retrieve the url on the instance /hostname.txt and check that it contains the hostname of the instance. In case we get ECONNREFUSED, we retry up to the net timeout seconds, for any other error we abort. """ if not self.opts.http_check: return end_time = time.time() + self.opts.net_timeout url = None while time.time() < end_time and url is None: try: url = self.url_opener.open("http://%s/hostname.txt" % instance) except IOError: # here we can have connection refused, no route to host, etc. time.sleep(1) if url is None: raise InstanceDown(instance, "Cannot contact instance") hostname = url.read().strip() url.close() if hostname != instance: raise InstanceDown(instance, ("Hostname mismatch, expected %s, got %s" % (instance, hostname))) def BurninCluster(self): """Test a cluster intensively. This will create instances and then start/stop/failover them. It is safe for existing instances but could impact performance. """ Log("Testing global parameters") if (len(self.nodes) == 1 and self.opts.disk_template not in _SINGLE_NODE_DISK_TEMPLATES): Err("When one node is available/selected the disk template must" " be one of %s" % utils.CommaJoin(_SINGLE_NODE_DISK_TEMPLATES)) if self.opts.do_confd_tests and not constants.ENABLE_CONFD: Err("You selected confd tests but confd was disabled at configure time") has_err = True try: self.BurnCreateInstances() if self.bep[constants.BE_MINMEM] < self.bep[constants.BE_MAXMEM]: self.BurnModifyRuntimeMemory() if self.opts.do_replace1 and \ self.opts.disk_template in constants.DTS_INT_MIRROR: self.BurnReplaceDisks1D8() if (self.opts.do_replace2 and len(self.nodes) > 2 and self.opts.disk_template in constants.DTS_INT_MIRROR): self.BurnReplaceDisks2() if (self.opts.disk_template in constants.DTS_GROWABLE and compat.any(n > 0 for n in self.disk_growth)): self.BurnGrowDisks() if self.opts.do_failover and \ self.opts.disk_template in constants.DTS_MIRRORED: self.BurnFailover() if self.opts.do_migrate: if self.opts.disk_template not in constants.DTS_MIRRORED: Log("Skipping migration (disk template %s does not support it)", self.opts.disk_template) elif not self.hv_can_migrate: Log("Skipping migration (hypervisor %s does not support it)", self.hypervisor) else: self.BurnMigrate() if (self.opts.do_move and len(self.nodes) > 1 and self.opts.disk_template in [constants.DT_PLAIN, constants.DT_FILE]): self.BurnMove() if (self.opts.do_importexport and self.opts.disk_template in _IMPEXP_DISK_TEMPLATES): self.BurnImportExport() if self.opts.do_reinstall: self.BurnReinstall() if self.opts.do_reboot: self.BurnReboot() if self.opts.do_renamesame: self.BurnRenameSame() if self.opts.do_addremove_disks: self.BurnAddRemoveDisks() default_nic_mode = self.cluster_default_nicparams[constants.NIC_MODE] # Don't add/remove nics in routed mode, as we would need an ip to add # them with if self.opts.do_addremove_nics: if default_nic_mode == constants.NIC_MODE_BRIDGED: self.BurnAddRemoveNICs() else: Log("Skipping nic add/remove as the cluster is not in bridged mode") if self.opts.do_activate_disks: self.BurnActivateDisks() if self.opts.rename: self.BurnRename() if self.opts.do_confd_tests: self.BurnConfd() if self.opts.do_startstop: self.BurnStopStart() has_err = False finally: if has_err: Log("Error detected: opcode buffer follows:\n\n") Log(self.GetFeedbackBuf()) Log("\n\n") if not self.opts.keep_instances: try: self.BurnRemove() except Exception, err: # pylint: disable=W0703 if has_err: # already detected errors, so errors in removal # are quite expected Log("Note: error detected during instance remove: %s", err) else: # non-expected error raise return constants.EXIT_SUCCESS def Main(): """Main function. """ utils.SetupLogging(pathutils.LOG_BURNIN, sys.argv[0], debug=False, stderr_logging=True) return Burner().BurninCluster()
vladimir-ipatov/ganeti
lib/tools/burnin.py
Python
gpl-2.0
42,651
# This file is a part of pysnapshotd, a program for automated backups # Copyright (C) 2015-2016 Jonas Thiem # # 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. import threading class BufferedPipeObject(object): def __init__(self): self.closed = False self.contents = b"" self.access_mutex = threading.Lock() self.waiting_for_content_semaphore = \ threading.Semaphore() self.waiting_for_content_counter = 0 self._write_func = None def _set_write_func(self, f): self.access_mutex.acquire() self._write_func = f self.access_mutex.release() def close(self): self.access_mutex.acquire() self.closed = True self.access_mutex.release() def write(self, data): # First, check if pipe is still open at all: self.access_mutex.acquire() if self.closed: self.access_mutex.release() raise OSError("broken pipe - pipe has been closed") # Do nothing for an obvious dummy command: if len(data) == 0: self.access_mutex.release() return 0 # Try to write with the write func if given: # (which means this pipe object itself will always remain empty and # .read() on it will block forever, since things are somewhat bypassed # directly to some target write function) if self._write_func != None: try: self._write_func(data) except Exception: self.closed = True finally: self.access_mutex.release() return # Otherwise, just put contents in internal buffer for reading from # this pipe from "the other end": try: self.contents += data i = 0 while i < self.waiting_for_content_counter: self.waiting_for_content_semaphore.\ release() i += 1 finally: self.access_mutex.release() def read(self, amount): print(" >> PIPE READ: " + str(amount)) if amount <= 0: print(" >> PIPE READ DATA: <empty read>") return b"" self.access_mutex.acquire() # Try to read data as long as needed to acquire requested amount: obtained_data = b"" while True: # If pipe was closed along this process, abort: if self.closed: self.access_mutex.release() raise OSError("broken pipe - pipe has been closed") # Try to obtain as much data as requested: if len(self.contents) > 0: added_data = self.contents[:amount] obtained_data += added_data self.contents = self.contents[len(added_data):] amount -= len(added_data) # If there is not enough data available, we will need to wait for # more: if amount > 0: self.waiting_for_content_counter += 1 self.access_mutex.release() self.waiting_for_content_semaphore.acquire() self.access_mutex.acquire() else: assert(len(obtained_data) > 0) print(" >> PIPE READ DATA: " + str(obtained_data)) return obtained_data
JonasT/pyrsnapshotd
src/pysnapshotd/pipeobject.py
Python
gpl-2.0
4,032
<?php class formWidgetContentCategoriesOptions extends cmsForm { public function init() { return array( array( 'type' => 'fieldset', 'title' => LANG_CONTENT_TYPE, 'childs' => array( new fieldList('options:ctype_name', array( 'generator' => function($item) { $model = cmsCore::getModel('content'); $tree = $model->getContentTypes(); $items = array(0 => LANG_WD_CONTENT_CATS_DETECT); if ($tree) { foreach ($tree as $item) { $items[$item['name']] = $item['title']; } } return $items; } )), ) ), array( 'type' => 'fieldset', 'title' => LANG_OPTIONS, 'childs' => array( new fieldCheckbox('options:is_root', array( 'title' => LANG_WD_CONTENT_CATS_SHOW_ROOT, 'default' => false )), new fieldCheckbox('options:show_full_tree', array( 'title' => LANG_WD_CONTENT_CATS_SHOW_FULL_TREE, 'default' => false )) ) ), ); } }
Val-Git/icms2
system/controllers/content/widgets/categories/options.form.php
PHP
gpl-2.0
1,558
#region License /* Copyright (C) 1999-2015 John Källén. * * 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; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ #endregion using Reko.Core.Lib; using NUnit.Framework; using System; using System.Collections.Generic; using System.Text; namespace Reko.UnitTests.Core.Lib { [TestFixture] public class PriorityQueueTests { [Test] public void AddItem() { var pq = new PriorityQueue<string>(); pq.Enqueue(1, "foo"); Assert.AreEqual(1, pq.Count); } [Test] public void EnqDeq() { var pq = new PriorityQueue<string>(); pq.Enqueue(1, "world"); pq.Enqueue(2, "hello"); Assert.AreEqual("hello", pq.Dequeue()); Assert.AreEqual("world", pq.Dequeue()); } } }
chubbymaggie/reko
src/UnitTests/Core/Lib/PriorityQueueTests.cs
C#
gpl-2.0
1,479
<?php /** * CHRONOFORMS version 4.0 * Copyright (c) 2006 - 2011 Chrono_Man, ChronoEngine.com. All rights reserved. * Author: Chrono_Man (ChronoEngine.com) * @license GNU/GPL * Visit http://www.ChronoEngine.com for regular updates and information. **/ namespace GCore\Admin\Extensions\Chronoforms\Actions\XlsExport; /* @copyright:ChronoEngine.com @license:GPLv2 */defined('_JEXEC') or die('Restricted access'); defined("GCORE_SITE") or die; Class XlsExport extends \GCore\Admin\Extensions\Chronoforms\Action{ static $title = 'XLS Export'; static $group = array('data_management' => 'Data Management'); var $defaults = array( 'enabled' => 1, 'data_path' => '', 'list_fields' => '', 'list_headers' => '', 'before_headers' => '', 'add_bom' => 0, 'save_file' => 0, 'post_file_name' => '', 'file_name' => 'cf_export.xls', 'save_path' => '', ); function execute(&$form, $action_id){ $config = $form->actions_config[$action_id]; $config = new \GCore\Libs\Parameter($config); if(!$config->get('enabled')){ return; } $data_path = trim($config->get('data_path', '')); $data_path = !empty($data_path) ? explode('.', $data_path) : array(); $data = \GCore\Libs\Arr::getVal($form->data, $data_path); if(!empty($data) AND is_array($data)){ $data = array_values($data); $first_data_record = $data[0]; $list_fields = strlen(trim($config->get('list_fields', ''))) ? explode(',', trim($config->get('list_fields', ''))) : array_keys($first_data_record); $list_headers = strlen(trim($config->get('list_headers', ''))) ? explode(',', trim($config->get('list_headers', ''))) : array_keys($first_data_record); $table_rows = ''; if(strlen(trim($config->get('before_headers', '')))){ $table_rows .= '<tr bgcolor="#fff">'."\n"; $table_rows .= '<td>'.\GCore\Libs\Arr::getVal($form->data, explode('.', trim($config->get('before_headers', '')))).'</td>'."\n"; $table_rows .= '</tr>'."\n"; } //add headers $table_rows .= '<tr bgcolor="#999999">'."\n"; foreach($list_headers as $k => $v){ $table_rows .= '<td style="color:white">'.$v.'</td>'."\n"; } $table_rows .= '</tr>'."\n"; //add data rows foreach($data as $record){ $table_rows .= '<tr>'."\n"; foreach($record as $k => $v){ if(!in_array($k, $list_fields)){ continue; } $table_rows .= '<td valign="top" style="mso-number-format:\@">'.$v.'</td>'."\n"; } $table_rows .= '</tr>'."\n"; } //finalize table $excel_table = "<table border='1'>".$table_rows."</table>"; if($config->get('save_file', 0) == 1){ $save_path = $config->get('save_path', '') ? $config->get('save_path', '') : \GCore\C::ext_path('chronoforms', 'front').'exports'.DS.$form->form['Form']['title'].DS; if (!file_exists($save_path.'index.html')){ if(!mkdir($save_path, 0755, true)){ $form->debug[$action_id][self::$title] = "Couldn't create save folder: {$save_path}"; return; } file_put_contents($save_path.'index.html', ''); } if((bool)$config->get('add_bom', 0) === true){ $excel_table = "\xEF\xBB\xBF".$excel_table; } $file_name = $config->get('file_name', 'cf_export.xls'); $saved = file_put_contents($save_path.$file_name, $excel_table); if(empty($saved)){ $form->debug[$action_id][self::$title] = "Couldn't create XLS file"; return; } if(strlen($config->get('post_file_name', '')) > 0){ $post_file_name = $config->get('post_file_name', ''); $form->data[$post_file_name] = $file_name; $form->files[$post_file_name] = array('name' => $file_name, 'path' => $save_path.$file_name, 'size' => filesize($save_path.$file_name)); //$form->files[$post_file_name]['link'] = $save_url.$file_name; } }else{ //set headers header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download");; header("Content-Disposition: attachment;filename=".$config->get('file_name', 'cf_export.xls')); header("Content-Transfer-Encoding: binary"); header('Content-Encoding: UTF-8'); //output data @ob_end_clean(); if((bool)$config->get('add_bom', 0) === true){ echo "\xEF\xBB\xBF"; } echo $excel_table; exit; } }else{ $form->debug[$action_id][self::$title] = "No data could be loaded or found, please check your action settings."; } } public static function config(){ echo \GCore\Helpers\Html::formStart('action_config csv_export_action_config', 'csv_export_action_config_{N}'); echo \GCore\Helpers\Html::formSecStart(); echo \GCore\Helpers\Html::formLine('Form[extras][actions_config][{N}][enabled]', array('type' => 'dropdown', 'label' => l_('CF_ENABLED'), 'options' => array(0 => l_('NO'), 1 => l_('YES')))); echo \GCore\Helpers\Html::formLine('Form[extras][actions_config][{N}][data_path]', array('type' => 'text', 'class' => 'M', 'label' => l_('CF_XLS_DATA_PATH'), 'sublabel' => l_('CF_XLS_DATA_PATH_DESC'))); echo \GCore\Helpers\Html::formLine('Form[extras][actions_config][{N}][list_fields]', array('type' => 'text', 'class' => 'XL', 'label' => l_('CF_XLS_LIST_FIELDS'), 'sublabel' => l_('CF_XLS_LIST_FIELDS_DESC'))); echo \GCore\Helpers\Html::formLine('Form[extras][actions_config][{N}][list_headers]', array('type' => 'text', 'class' => 'XL', 'label' => l_('CF_XLS_LIST_HEADERS'), 'sublabel' => l_('CF_XLS_LIST_HEADERS_DESC'))); echo \GCore\Helpers\Html::formLine('Form[extras][actions_config][{N}][file_name]', array('type' => 'text', 'class' => 'XL', 'label' => l_('CF_XLS_FILE_NAME'), 'sublabel' => l_('CF_XLS_FILE_NAME_DESC'))); echo \GCore\Helpers\Html::formLine('Form[extras][actions_config][{N}][post_file_name]', array('type' => 'text', 'class' => 'XL', 'label' => l_('CF_XLS_POST_FILE_NAME'), 'sublabel' => l_('CF_XLS_POST_FILE_NAME_DESC'))); echo \GCore\Helpers\Html::formLine('Form[extras][actions_config][{N}][before_headers]', array('type' => 'text', 'class' => 'XL', 'label' => l_('CF_XLS_BEFORE_HEADERS'), 'sublabel' => l_('CF_XLS_BEFORE_HEADERS_DESC'))); echo \GCore\Helpers\Html::formLine('Form[extras][actions_config][{N}][save_file]', array('type' => 'dropdown', 'label' => l_('CF_XLS_SAVE_FILE'), 'sublabel' => l_('CF_XLS_SAVE_FILE_DESC'), 'options' => array(0 => l_('NO'), 1 => l_('YES')))); echo \GCore\Helpers\Html::formLine('Form[extras][actions_config][{N}][save_path]', array('type' => 'text', 'class' => 'XL', 'label' => l_('CF_XLS_SAVE_PATH'), 'sublabel' => l_('CF_XLS_SAVE_PATH_DESC'))); echo \GCore\Helpers\Html::formLine('Form[extras][actions_config][{N}][add_bom]', array('type' => 'dropdown', 'label' => l_('CF_XLS_ADD_BOM'), 'sublabel' => l_('CF_XLS_ADD_BOM_DESC'), 'options' => array(0 => l_('NO'), 1 => l_('YES')))); echo \GCore\Helpers\Html::formSecEnd(); echo \GCore\Helpers\Html::formEnd(); } public static function config_check($data = array()){ $diags = array(); $diags[l_('CF_DIAG_ENABLED')] = !empty($data['enabled']); $diags[l_('CF_DIAG_DATAPATH_SET')] = !empty($data['data_path']); $diags[l_('CF_DIAG_FILENAME_SET')] = !empty($data['file_name']); return $diags; } } ?>
faridv/Tourism
administrator/components/com_chronoforms5/chronoforms/actions/xls_export/xls_export.php
PHP
gpl-2.0
7,275
#!/usr/bin/ruby require "../../rules/util.rb" require "../../rules/mosync_util.rb" require "FileUtils" msbuildpath = "/Windows/Microsoft.NET/Framework/v4.0.30319/MSBuild.exe" verbose = "q" if ARGV.length != 0 ARGV.each do|a| if a == "--help" puts "For building a certain configuration pass it as a command line parameter\n" puts "e.g.:" puts "\n \"ruby buildLibraries.rb Release\" will build for release;" puts "\n \"ruby buildLibraries.rb Debug\" will build for degub;" puts "\n \"ruby buildLiraries.rb Release Debug\" will build for both release and debug;" puts "\nFor setting the verbose option pass one of the following options:" puts "\n q (quite)" puts "\n m (minimal)" puts "\n n (normal)" puts "\n d (detailed)" puts "\n diag (diagnostic)" puts "\ne.g.:" puts "\n \"ruby buildLibraries.rb q Debug\" will build for debug verbose \"quite\";" puts "\nNote: The default value is q" else if a == "q" || a == "m" || a == "n" || a == "d" || a == "diag" verbose = a else if a == "release" || a == "debug" || a == "Release" || a == "Debug" sh "#{msbuildpath} /v:#{verbose} WP8Libs.sln /p:Configuration=#{a}" puts "\n\n----------------------------------\n\n" puts "Builded with Configuration: #{a}" puts "\n----------------------------------\n\n" else puts "For help pass --help as an option.\n" end end end end else puts "\nNo option given; Building for Release with verbose \"quite\"; Pass --help for more information;\n\n" sh "#{msbuildpath} /v:q WP8Libs.sln /p:Configuration=Release" puts "\n\n----------------------------------\n\n" puts "Builded with Configuration: Release" puts "\n----------------------------------\n\n" end
MoSync/MoSync
libs/WP8Libs/buildLibraries.rb
Ruby
gpl-2.0
1,776
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * Product name: redemption, a FLOSS RDP proxy * Copyright (C) Wallix 2010-2013 * Author(s): Christophe Grosjean, Xiaopeng Zhou, Jonathan Poelen, * Meng Tan */ #ifndef REDEMPTION_MOD_INTERNAL_INTERACTIVE_TARGET_MOD_HPP #define REDEMPTION_MOD_INTERNAL_INTERACTIVE_TARGET_MOD_HPP #include "translation.hpp" #include "front_api.hpp" #include "config.hpp" #include "widget2/flat_interactive_target.hpp" #include "widget2/screen.hpp" #include "internal_mod.hpp" class InteractiveTargetMod : public InternalMod, public NotifyApi { bool ask_device; bool ask_login; bool ask_password; FlatInteractiveTarget challenge; Inifile & ini; public: InteractiveTargetMod(Inifile & ini, FrontAPI & front, uint16_t width, uint16_t height) : InternalMod(front, width, height, ini.font, &ini) , ask_device(ini.context_is_asked(AUTHID_TARGET_HOST)) , ask_login(ini.context_is_asked(AUTHID_TARGET_USER)) , ask_password((this->ask_login || ini.context_is_asked(AUTHID_TARGET_PASSWORD))) , challenge(*this, width, height, this->screen, this, 0, ini.context_is_asked(AUTHID_TARGET_HOST), ini.context_is_asked(AUTHID_TARGET_USER), ini.context_is_asked(AUTHID_TARGET_PASSWORD), ini.theme, TR("target_info_required", ini), TR("device", ini), ini.context_get_value(AUTHID_TARGET_DEVICE), TR("login", ini), ini.context_get_value(AUTHID_TARGET_USER), TR("password", ini), ini.font) , ini(ini) { this->screen.add_widget(&this->challenge); this->challenge.password_edit.set_text(""); this->screen.set_widget_focus(&this->challenge, Widget2::focus_reason_tabkey); if (this->ask_device) { this->challenge.set_widget_focus(&this->challenge.device_edit, Widget2::focus_reason_tabkey); } else if (this->ask_login) { this->challenge.set_widget_focus(&this->challenge.login_edit, Widget2::focus_reason_tabkey); } else { this->challenge.set_widget_focus(&this->challenge.password_edit, Widget2::focus_reason_tabkey); } this->screen.refresh(this->screen.rect); } virtual ~InteractiveTargetMod() { this->screen.clear(); } virtual void notify(Widget2* sender, notify_event_t event) { switch (event) { case NOTIFY_SUBMIT: this->accepted(); break; case NOTIFY_CANCEL: this->refused(); break; default: ; } } private: TODO("ugly. The value should be pulled by authentifier when module is closed instead of being pushed to it by mod") void accepted() { if (this->ask_device) { this->ini.context_set_value(AUTHID_TARGET_HOST, this->challenge.device_edit.get_text()); } if (this->ask_login) { this->ini.context_set_value(AUTHID_TARGET_USER, this->challenge.login_edit.get_text()); } if (this->ask_password) { this->ini.context_set_value(AUTHID_TARGET_PASSWORD, this->challenge.password_edit.get_text()); } this->ini.context_set_value(AUTHID_DISPLAY_MESSAGE, "True"); this->event.signal = BACK_EVENT_NEXT; this->event.set(); } TODO("ugly. The value should be pulled by authentifier when module is closed instead of being pushed to it by mod") void refused() { this->ini.context_set_value(AUTHID_TARGET_PASSWORD, ""); this->ini.context_set_value(AUTHID_DISPLAY_MESSAGE, "False"); this->event.signal = BACK_EVENT_NEXT; this->event.set(); } public: virtual void draw_event(time_t now) { this->event.reset(); } }; #endif
speidy/redemption
src/mod/internal/interactive_target_mod.hpp
C++
gpl-2.0
4,829
// { dg-do compile } // { dg-options "-pthread" } // { dg-require-effective-target c++11 } // { dg-require-effective-target pthread } // { dg-require-cstdint "" } // { dg-require-gthreads "" } // Copyright (C) 2014-2017 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // libstdc++/60497 #include <mutex> #include <memory> #include <functional> struct A; template<typename T> struct B { T t; }; using UP = std::unique_ptr<B<A>>; void f(UP&) { } void g(UP& p) { std::once_flag o; std::call_once(o, f, std::ref(p)); }
itsimbal/gcc.cet
libstdc++-v3/testsuite/30_threads/call_once/60497.cc
C++
gpl-2.0
1,215
--[[ ▄▇▇▇▇▇▇▄▇▇▇▇▇▇▄ ❉❉❉ ฿ᵧ ➣ @PXPP3 ➥ CHANNEL ◐ @INSTAOFFICIAL ▄▇▇▇▇▇▇▄▇▇▇▇▇▇▄ ]] do local function run(msg,matches) local reply_id = msg['id'] if is_momod(msg) and matches[1]== 'help' then local alnaze = [[❍____↝◐helplist◐↜____❍ ___⭐💬___🚨___⭐💭___ جميع الاوامر تعمل بالاشارات [!/] ___⭐💬___🚨___⭐💭___ 💭[!/]sphelp : اوامر الرئيسية🌐 💬[!/]spban : اوامر طرد حضر كتم _______😈😈😈😈________ 👮[!/]dvhelp : اوامر مطورين⭐ ⭐_______🃏😈😈👮______⭐ 🚨 Dev - : @PXPP3 ◐ 🌐 CHANNEL - : @INSTAOFFICIAL ◐ ____________MONSTERBOT♺ ]] reply_msg(reply_id, alnaze, ok_cb, false) end local reply_id = msg['id'] if not is_momod(msg) then local alnaz = "للمشرفين فقط 🖕🏿😎" reply_msg(reply_id, alnaze, ok_cb, false) end end return { patterns ={ "^[!#/](help)$", }, run = run } end
devmonstervip/MONSTERBOT
plugins/help.lua
Lua
gpl-2.0
1,027
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (C) 2015 Cedric Hnyda <ced.hnyda@gmail.com> * * Calls getrandom(2), checks that the buffer is filled with random bytes * and expects success. */ #include "tst_test.h" #include "lapi/getrandom.h" #include "lapi/syscalls.h" #define PROC_ENTROPY_AVAIL "/proc/sys/kernel/random/entropy_avail" static int modes[] = { 0, GRND_RANDOM, GRND_NONBLOCK, GRND_RANDOM | GRND_NONBLOCK }; static int check_content(unsigned char *buf, int nb) { int table[256]; int i, index, max; memset(table, 0, sizeof(table)); max = 6 + nb * 0.2; for (i = 0; i < nb; i++) { index = buf[i]; table[index]++; } for (i = 0; i < nb; i++) { if (max > 0 && table[i] > max) return 0; } return 1; } static void verify_getrandom(unsigned int n) { unsigned char buf[256]; int bufsize = 64, entropy_avail; if (access(PROC_ENTROPY_AVAIL, F_OK) == 0) { SAFE_FILE_SCANF(PROC_ENTROPY_AVAIL, "%d", &entropy_avail); if (entropy_avail > 256) bufsize = sizeof(buf); } memset(buf, 0, sizeof(buf)); do { TEST(tst_syscall(__NR_getrandom, buf, bufsize, modes[n])); } while ((modes[n] & GRND_NONBLOCK) && TST_RET == -1 && TST_ERR == EAGAIN); if (!check_content(buf, TST_RET)) tst_res(TFAIL | TTERRNO, "getrandom failed"); else tst_res(TPASS, "getrandom returned %ld", TST_RET); } static struct tst_test test = { .tcnt = ARRAY_SIZE(modes), .test = verify_getrandom, };
linux-test-project/ltp
testcases/kernel/syscalls/getrandom/getrandom02.c
C
gpl-2.0
1,446
<?php /** * @package WordPress * @subpackage ThemeWoot * @author ThemeWoot Team * * This source file is subject to the GNU GENERAL PUBLIC LICENSE (GPL 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://www.gnu.org/licenses/gpl-3.0.txt */ if ( !function_exists( 'shortcode_button' ) ) { function shortcode_button($atts, $content = null) { extract(shortcode_atts( array( 'style' => 'default', 'size' => 'medium', 'link' => '', 'target' => 'self' ), $atts)); if($content) { $html = '<a href="'.$link.'" target="_'.$target.'" class="shortcode-button button button-'.$style.' button-'.$size.'">'.do_shortcode($content).'</a>'."\n"; return $html; } } add_shortcode('button', 'shortcode_button'); } ?>
sniezekjp/staging-fs
wp-content/plugins/twoot-toolkit/zilla-shortcodes/shortcodes/button.php
PHP
gpl-2.0
860
#undef CONFIG_CPU_R4X00
ZigFisher/FlyRouter
toolchain/kernel-headers/include/config/cpu/r4x00.h
C
gpl-2.0
25
/* * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_VM_RUNTIME_STUBROUTINES_HPP #define SHARE_VM_RUNTIME_STUBROUTINES_HPP #include "code/codeBlob.hpp" #include "memory/allocation.hpp" #include "runtime/frame.hpp" #include "runtime/mutexLocker.hpp" #include "runtime/stubCodeGenerator.hpp" #include "utilities/top.hpp" #ifdef TARGET_ARCH_x86 # include "nativeInst_x86.hpp" #endif #ifdef TARGET_ARCH_sparc # include "nativeInst_sparc.hpp" #endif #ifdef TARGET_ARCH_zero # include "nativeInst_zero.hpp" #endif #ifdef TARGET_ARCH_arm # include "nativeInst_arm.hpp" #endif #ifdef TARGET_ARCH_ppc # include "nativeInst_ppc.hpp" #endif // StubRoutines provides entry points to assembly routines used by // compiled code and the run-time system. Platform-specific entry // points are defined in the platform-specific inner class. // // Class scheme: // // platform-independent platform-dependent // // stubRoutines.hpp <-- included -- stubRoutines_<arch>.hpp // ^ ^ // | | // implements implements // | | // | | // stubRoutines.cpp stubRoutines_<arch>.cpp // stubRoutines_<os_family>.cpp stubGenerator_<arch>.cpp // stubRoutines_<os_arch>.cpp // // Note 1: The important thing is a clean decoupling between stub // entry points (interfacing to the whole vm; i.e., 1-to-n // relationship) and stub generators (interfacing only to // the entry points implementation; i.e., 1-to-1 relationship). // This significantly simplifies changes in the generator // structure since the rest of the vm is not affected. // // Note 2: stubGenerator_<arch>.cpp contains a minimal portion of // machine-independent code; namely the generator calls of // the generator functions that are used platform-independently. // However, it comes with the advantage of having a 1-file // implementation of the generator. It should be fairly easy // to change, should it become a problem later. // // Scheme for adding a new entry point: // // 1. determine if it's a platform-dependent or independent entry point // a) if platform independent: make subsequent changes in the independent files // b) if platform dependent: make subsequent changes in the dependent files // 2. add a private instance variable holding the entry point address // 3. add a public accessor function to the instance variable // 4. implement the corresponding generator function in the platform-dependent // stubGenerator_<arch>.cpp file and call the function in generate_all() of that file class StubRoutines: AllStatic { public: enum platform_independent_constants { max_size_of_parameters = 256 // max. parameter size supported by megamorphic lookups }; // Dependencies friend class StubGenerator; #ifdef TARGET_ARCH_MODEL_x86_32 # include "stubRoutines_x86_32.hpp" #endif #ifdef TARGET_ARCH_MODEL_x86_64 # include "stubRoutines_x86_64.hpp" #endif #ifdef TARGET_ARCH_MODEL_sparc # include "stubRoutines_sparc.hpp" #endif #ifdef TARGET_ARCH_MODEL_zero # include "stubRoutines_zero.hpp" #endif #ifdef TARGET_ARCH_MODEL_arm # include "stubRoutines_arm.hpp" #endif #ifdef TARGET_ARCH_MODEL_ppc_32 # include "stubRoutines_ppc_32.hpp" #endif #ifdef TARGET_ARCH_MODEL_ppc_64 # include "stubRoutines_ppc_64.hpp" #endif static jint _verify_oop_count; static address _verify_oop_subroutine_entry; static address _call_stub_return_address; // the return PC, when returning to a call stub static address _call_stub_entry; static address _forward_exception_entry; static address _catch_exception_entry; static address _throw_AbstractMethodError_entry; static address _throw_IncompatibleClassChangeError_entry; static address _throw_NullPointerException_at_call_entry; static address _throw_StackOverflowError_entry; static address _handler_for_unsafe_access_entry; static address _atomic_xchg_entry; static address _atomic_xchg_ptr_entry; static address _atomic_store_entry; static address _atomic_store_ptr_entry; static address _atomic_cmpxchg_entry; static address _atomic_cmpxchg_ptr_entry; static address _atomic_cmpxchg_long_entry; static address _atomic_add_entry; static address _atomic_add_ptr_entry; static address _fence_entry; static address _d2i_wrapper; static address _d2l_wrapper; static jint _fpu_cntrl_wrd_std; static jint _fpu_cntrl_wrd_24; static jint _fpu_cntrl_wrd_64; static jint _fpu_cntrl_wrd_trunc; static jint _mxcsr_std; static jint _fpu_subnormal_bias1[3]; static jint _fpu_subnormal_bias2[3]; static BufferBlob* _code1; // code buffer for initial routines static BufferBlob* _code2; // code buffer for all other routines // Leaf routines which implement arraycopy and their addresses // arraycopy operands aligned on element type boundary static address _jbyte_arraycopy; static address _jshort_arraycopy; static address _jint_arraycopy; static address _jlong_arraycopy; static address _oop_arraycopy, _oop_arraycopy_uninit; static address _jbyte_disjoint_arraycopy; static address _jshort_disjoint_arraycopy; static address _jint_disjoint_arraycopy; static address _jlong_disjoint_arraycopy; static address _oop_disjoint_arraycopy, _oop_disjoint_arraycopy_uninit; // arraycopy operands aligned on zero'th element boundary // These are identical to the ones aligned aligned on an // element type boundary, except that they assume that both // source and destination are HeapWord aligned. static address _arrayof_jbyte_arraycopy; static address _arrayof_jshort_arraycopy; static address _arrayof_jint_arraycopy; static address _arrayof_jlong_arraycopy; static address _arrayof_oop_arraycopy, _arrayof_oop_arraycopy_uninit; static address _arrayof_jbyte_disjoint_arraycopy; static address _arrayof_jshort_disjoint_arraycopy; static address _arrayof_jint_disjoint_arraycopy; static address _arrayof_jlong_disjoint_arraycopy; static address _arrayof_oop_disjoint_arraycopy, _arrayof_oop_disjoint_arraycopy_uninit; // these are recommended but optional: static address _checkcast_arraycopy, _checkcast_arraycopy_uninit; static address _unsafe_arraycopy; static address _generic_arraycopy; static address _jbyte_fill; static address _jshort_fill; static address _jint_fill; static address _arrayof_jbyte_fill; static address _arrayof_jshort_fill; static address _arrayof_jint_fill; // zero heap space aligned to jlong (8 bytes) static address _zero_aligned_words; static address _aescrypt_encryptBlock; static address _aescrypt_decryptBlock; static address _cipherBlockChaining_encryptAESCrypt; static address _cipherBlockChaining_decryptAESCrypt; // These are versions of the java.lang.Math methods which perform // the same operations as the intrinsic version. They are used for // constant folding in the compiler to ensure equivalence. If the // intrinsic version returns the same result as the strict version // then they can be set to the appropriate function from // SharedRuntime. static double (*_intrinsic_log)(double); static double (*_intrinsic_log10)(double); static double (*_intrinsic_exp)(double); static double (*_intrinsic_pow)(double, double); static double (*_intrinsic_sin)(double); static double (*_intrinsic_cos)(double); static double (*_intrinsic_tan)(double); #ifdef SAFEFETCH_STUBS // On platforms where the compiler does not properly support inline // assembly safefetch can be implemented as stub routines. This also // allows to use a single implementation if an architecture is // supported on several os platforms. static address _safefetch32_entry; static address _safefetch32_fault_pc; static address _safefetch32_continuation_pc; static address _safefetchN_entry; static address _safefetchN_fault_pc; static address _safefetchN_continuation_pc; #endif public: // Initialization/Testing static void initialize1(); // must happen before universe::genesis static void initialize2(); // must happen after universe::genesis static bool is_stub_code(address addr) { return contains(addr); } static bool contains(address addr) { return (_code1 != NULL && _code1->blob_contains(addr)) || (_code2 != NULL && _code2->blob_contains(addr)) ; } static CodeBlob* code1() { return _code1; } static CodeBlob* code2() { return _code2; } // Debugging static jint verify_oop_count() { return _verify_oop_count; } static jint* verify_oop_count_addr() { return &_verify_oop_count; } // a subroutine for debugging the GC static address verify_oop_subroutine_entry_address() { return (address)&_verify_oop_subroutine_entry; } // We need this address to lazily jump to in interpreter. static address throw_StackOverflowError_entry_address() { return (address)&_throw_StackOverflowError_entry; } static address catch_exception_entry() { return _catch_exception_entry; } // Calls to Java typedef void (*CallStub)( address link, intptr_t* result, BasicType result_type, methodOopDesc* method, address entry_point, intptr_t* parameters, int size_of_parameters, TRAPS ); static CallStub call_stub() { return CAST_TO_FN_PTR(CallStub, _call_stub_entry); } // Exceptions static address forward_exception_entry() { return _forward_exception_entry; } // Implicit exceptions static address throw_AbstractMethodError_entry() { return _throw_AbstractMethodError_entry; } static address throw_IncompatibleClassChangeError_entry(){ return _throw_IncompatibleClassChangeError_entry; } static address throw_NullPointerException_at_call_entry(){ return _throw_NullPointerException_at_call_entry; } static address throw_StackOverflowError_entry() { return _throw_StackOverflowError_entry; } // Exceptions during unsafe access - should throw Java exception rather // than crash. static address handler_for_unsafe_access() { return _handler_for_unsafe_access_entry; } static address atomic_xchg_entry() { return _atomic_xchg_entry; } static address atomic_xchg_ptr_entry() { return _atomic_xchg_ptr_entry; } static address atomic_store_entry() { return _atomic_store_entry; } static address atomic_store_ptr_entry() { return _atomic_store_ptr_entry; } static address atomic_cmpxchg_entry() { return _atomic_cmpxchg_entry; } static address atomic_cmpxchg_ptr_entry() { return _atomic_cmpxchg_ptr_entry; } static address atomic_cmpxchg_long_entry() { return _atomic_cmpxchg_long_entry; } static address atomic_add_entry() { return _atomic_add_entry; } static address atomic_add_ptr_entry() { return _atomic_add_ptr_entry; } static address fence_entry() { return _fence_entry; } static address d2i_wrapper() { return _d2i_wrapper; } static address d2l_wrapper() { return _d2l_wrapper; } static jint fpu_cntrl_wrd_std() { return _fpu_cntrl_wrd_std; } static address addr_fpu_cntrl_wrd_std() { return (address)&_fpu_cntrl_wrd_std; } static address addr_fpu_cntrl_wrd_24() { return (address)&_fpu_cntrl_wrd_24; } static address addr_fpu_cntrl_wrd_64() { return (address)&_fpu_cntrl_wrd_64; } static address addr_fpu_cntrl_wrd_trunc() { return (address)&_fpu_cntrl_wrd_trunc; } static address addr_mxcsr_std() { return (address)&_mxcsr_std; } static address addr_fpu_subnormal_bias1() { return (address)&_fpu_subnormal_bias1; } static address addr_fpu_subnormal_bias2() { return (address)&_fpu_subnormal_bias2; } static address select_arraycopy_function(BasicType t, bool aligned, bool disjoint, const char* &name, bool dest_uninitialized); static address jbyte_arraycopy() { return _jbyte_arraycopy; } static address jshort_arraycopy() { return _jshort_arraycopy; } static address jint_arraycopy() { return _jint_arraycopy; } static address jlong_arraycopy() { return _jlong_arraycopy; } static address oop_arraycopy(bool dest_uninitialized = false) { return dest_uninitialized ? _oop_arraycopy_uninit : _oop_arraycopy; } static address jbyte_disjoint_arraycopy() { return _jbyte_disjoint_arraycopy; } static address jshort_disjoint_arraycopy() { return _jshort_disjoint_arraycopy; } static address jint_disjoint_arraycopy() { return _jint_disjoint_arraycopy; } static address jlong_disjoint_arraycopy() { return _jlong_disjoint_arraycopy; } static address oop_disjoint_arraycopy(bool dest_uninitialized = false) { return dest_uninitialized ? _oop_disjoint_arraycopy_uninit : _oop_disjoint_arraycopy; } static address arrayof_jbyte_arraycopy() { return _arrayof_jbyte_arraycopy; } static address arrayof_jshort_arraycopy() { return _arrayof_jshort_arraycopy; } static address arrayof_jint_arraycopy() { return _arrayof_jint_arraycopy; } static address arrayof_jlong_arraycopy() { return _arrayof_jlong_arraycopy; } static address arrayof_oop_arraycopy(bool dest_uninitialized = false) { return dest_uninitialized ? _arrayof_oop_arraycopy_uninit : _arrayof_oop_arraycopy; } static address arrayof_jbyte_disjoint_arraycopy() { return _arrayof_jbyte_disjoint_arraycopy; } static address arrayof_jshort_disjoint_arraycopy() { return _arrayof_jshort_disjoint_arraycopy; } static address arrayof_jint_disjoint_arraycopy() { return _arrayof_jint_disjoint_arraycopy; } static address arrayof_jlong_disjoint_arraycopy() { return _arrayof_jlong_disjoint_arraycopy; } static address arrayof_oop_disjoint_arraycopy(bool dest_uninitialized = false) { return dest_uninitialized ? _arrayof_oop_disjoint_arraycopy_uninit : _arrayof_oop_disjoint_arraycopy; } static address checkcast_arraycopy(bool dest_uninitialized = false) { return dest_uninitialized ? _checkcast_arraycopy_uninit : _checkcast_arraycopy; } static address unsafe_arraycopy() { return _unsafe_arraycopy; } static address generic_arraycopy() { return _generic_arraycopy; } static address jbyte_fill() { return _jbyte_fill; } static address jshort_fill() { return _jshort_fill; } static address jint_fill() { return _jint_fill; } static address arrayof_jbyte_fill() { return _arrayof_jbyte_fill; } static address arrayof_jshort_fill() { return _arrayof_jshort_fill; } static address arrayof_jint_fill() { return _arrayof_jint_fill; } static address aescrypt_encryptBlock() { return _aescrypt_encryptBlock; } static address aescrypt_decryptBlock() { return _aescrypt_decryptBlock; } static address cipherBlockChaining_encryptAESCrypt() { return _cipherBlockChaining_encryptAESCrypt; } static address cipherBlockChaining_decryptAESCrypt() { return _cipherBlockChaining_decryptAESCrypt; } static address select_fill_function(BasicType t, bool aligned, const char* &name); static address zero_aligned_words() { return _zero_aligned_words; } static double intrinsic_log(double d) { assert(_intrinsic_log != NULL, "must be defined"); return _intrinsic_log(d); } static double intrinsic_log10(double d) { assert(_intrinsic_log != NULL, "must be defined"); return _intrinsic_log10(d); } static double intrinsic_exp(double d) { assert(_intrinsic_exp != NULL, "must be defined"); return _intrinsic_exp(d); } static double intrinsic_pow(double d, double d2) { assert(_intrinsic_pow != NULL, "must be defined"); return _intrinsic_pow(d, d2); } static double intrinsic_sin(double d) { assert(_intrinsic_sin != NULL, "must be defined"); return _intrinsic_sin(d); } static double intrinsic_cos(double d) { assert(_intrinsic_cos != NULL, "must be defined"); return _intrinsic_cos(d); } static double intrinsic_tan(double d) { assert(_intrinsic_tan != NULL, "must be defined"); return _intrinsic_tan(d); } #ifdef SAFEFETCH_STUBS typedef int (*SafeFetch32Stub)(int* adr, int errValue); typedef intptr_t (*SafeFetchNStub) (intptr_t* adr, intptr_t errValue); static SafeFetch32Stub SafeFetch32_stub() { return CAST_TO_FN_PTR(SafeFetch32Stub, _safefetch32_entry); } static SafeFetchNStub SafeFetchN_stub() { return CAST_TO_FN_PTR(SafeFetchNStub, _safefetchN_entry); } static bool is_safefetch_fault(address pc) { return pc != NULL && (pc == _safefetch32_fault_pc || pc == _safefetchN_fault_pc); } static address continuation_for_safefetch_fault(address pc) { assert(_safefetch32_continuation_pc != NULL && _safefetchN_continuation_pc != NULL, "not initialized"); if (pc == _safefetch32_fault_pc) return _safefetch32_continuation_pc; if (pc == _safefetchN_fault_pc) return _safefetchN_continuation_pc; ShouldNotReachHere(); return NULL; } #endif // // Default versions of the above arraycopy functions for platforms which do // not have specialized versions // static void jbyte_copy (jbyte* src, jbyte* dest, size_t count); static void jshort_copy (jshort* src, jshort* dest, size_t count); static void jint_copy (jint* src, jint* dest, size_t count); static void jlong_copy (jlong* src, jlong* dest, size_t count); static void oop_copy (oop* src, oop* dest, size_t count); static void oop_copy_uninit(oop* src, oop* dest, size_t count); static void arrayof_jbyte_copy (HeapWord* src, HeapWord* dest, size_t count); static void arrayof_jshort_copy (HeapWord* src, HeapWord* dest, size_t count); static void arrayof_jint_copy (HeapWord* src, HeapWord* dest, size_t count); static void arrayof_jlong_copy (HeapWord* src, HeapWord* dest, size_t count); static void arrayof_oop_copy (HeapWord* src, HeapWord* dest, size_t count); static void arrayof_oop_copy_uninit(HeapWord* src, HeapWord* dest, size_t count); }; #ifdef SAFEFETCH_STUBS static int SafeFetch32(int* adr, int errValue) { return StubRoutines::SafeFetch32_stub()(adr, errValue); } static intptr_t SafeFetchN(intptr_t* adr, intptr_t errValue) { return StubRoutines::SafeFetchN_stub()(adr, errValue); } static bool CanUseSafeFetch32() { return StubRoutines::SafeFetch32_stub() ? true : false; } static bool CanUseSafeFetchN() { return StubRoutines::SafeFetchN_stub() ? true : false; } #else // Declared as extern "C" in os.hpp. static bool CanUseSafeFetch32() { return true; } static bool CanUseSafeFetchN() { return true; } #endif #endif // SHARE_VM_RUNTIME_STUBROUTINES_HPP
openjdk/jdk7u
hotspot/src/share/vm/runtime/stubRoutines.hpp
C++
gpl-2.0
20,465
/* * max17058_battery.c * fuel-gauge systems for lithium-ion (Li+) batteries * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/module.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/mutex.h> #include <linux/err.h> #include <linux/i2c.h> #include <linux/delay.h> #include <linux/power_supply.h> #include <linux/slab.h> //#include <linux/qpnp/qpnp-adc.h> #include <linux/HWVersion.h> #include <linux/switch.h> #include "asus_battery.h" #include "smb_external_include.h" #define max17058_VCELL_REG 0x02/*max17058_VCELL_MSB*/ #define max17058_SOC_REG 0x04/*max17058_SOC_MSB*/ #define max17058_MODE_REG 0x06/*max17058_MODE_MSB*/ #define max17058_VER_REG 0x08/*max17058_VER_MSB*/ #define max17058_RCOMP_REG 0x0C/*max17058_RCOMP_MSB*/ #define max17058_VRESET_REG 0x18 #define max17058_STATUS_REG 0x1A #define max17058_CMD_REG 0xFE/*max17058_CMD_MSB*/ #define max17058_MODEL_ACCESS_REG 0x3E #define max17058_OCV_REG 0x0E //add by peter #define MAX17058_TABLE 0x40 //add by peter #define max17058_MODEL_ACCESS_UNLOCK 0x4A57 #define max17058_MODEL_ACCESS_LOCK 0x0000 #define max17058_POR_CMD 0x5400 //add by peter #define max17058_DELAY 60*HZ //1000->10*HZ #define max17058_BATTERY_FULL 95 //below are from .ini file //--------------------.ini file--------------------------------- #define INI_RCOMP (165) #define INI_RCOMP_CHR (160) #define INI_RCOMP_FACTOR 1 const static int TempCoHot = -2300*INI_RCOMP_FACTOR; const static int TempCoCold = -4100*INI_RCOMP_FACTOR; #define INI_SOCCHECKA (121) #define INI_SOCCHECKB (123) #define INI_OCVTEST (58992) #define INI_BITS (18) //--------------------.ini file end------------------------------- #define VERIFY_AND_FIX 1 #define LOAD_MODEL !(VERIFY_AND_FIX) #define GAUGE_ERR(...) printk(KERN_ERR "[MAX17058_ERR] " __VA_ARGS__) #define GAUGE_INFO(...) printk(KERN_INFO "[MAX17058] " __VA_ARGS__) extern int Read_PROJ_ID(void); extern int pmic_get_battery_pack_temp(int *temp); static int max17058_check_por(struct i2c_client *client); static void prepare_to_load_model(struct i2c_client *client); static void load_model(struct i2c_client *client); static bool verify_model_is_correct(struct i2c_client *client); static void cleanup_model_load(struct i2c_client *client); static int max17058_write_reg(struct i2c_client *client, u8 reg, u16 value); static int max17058_read_reg(struct i2c_client *client, u8 reg); static u8 original_OCV_1=0, original_OCV_2=0; static u8 por_flag = 0; static struct dev_func max17058_tbl; static struct switch_dev max17058_batt_dev; static struct max17058_chip *g_max17058_chip; static int g_temp=25, g_soc=0; struct max17058_chip { struct mutex lock; struct i2c_client *client; struct delayed_work work; struct delayed_work hand_work; #ifdef MAX17058_REG_POWERSUPPLY struct power_supply fgbattery; struct power_supply *bms_psy; #endif /* State Of Connect */ int online; /* battery voltage */ int vcell; /* battery capacity */ int soc; /* State Of Charge */ int status; }; uint8_t model_data[] = { 0x96, 0x00, 0xB7, 0x50, 0xB8, 0x70, 0xBA, 0x90, 0xBC, 0x20, 0xBD, 0x40, 0xBD, 0xF0, 0xBF, 0x60, 0xC0, 0x00, 0xC3, 0x30, 0xC6, 0x10, 0xC8, 0x60, 0xCF, 0xD0, 0xD1, 0xF0, 0xD6, 0x40, 0xDC, 0x70, 0x00, 0x20, 0x1B, 0x50, 0x0F, 0xA0, 0x14, 0xD0, 0x19, 0x10, 0x17, 0x30, 0x15, 0xC0, 0x14, 0xA0, 0x0C, 0x40, 0x08, 0x30, 0x08, 0xE0, 0x07, 0xA0, 0x07, 0x30, 0x06, 0xA0, 0x07, 0x50, 0x07, 0x50 }; static int max17058_write_reg(struct i2c_client *client, u8 reg, u16 value) { int ret; ret = i2c_smbus_write_word_data(client, reg, swab16(value)); if (ret < 0) dev_err(&client->dev, "%s: err %d\n", __func__, ret); return ret; } static int max17058_read_reg(struct i2c_client *client, u8 reg) { int ret; ret = i2c_smbus_read_word_data(client, reg); if (ret < 0) dev_err(&client->dev, "%s: err %d\n", __func__, ret); return ret; } //check POR static int max17058_check_por(struct i2c_client *client) { u16 val; val = max17058_read_reg(client, max17058_STATUS_REG); //GAUGE_INFO("%s: max17058_STATUS_REG 0x1A = 0x%04x\n", __func__, val); val = swab16(val)&0x0100; return val; } //get chip version static u16 max17058_get_version(struct i2c_client *client) { u16 fg_version = 0; u16 chip_version = 0; fg_version = max17058_read_reg(client, max17058_VER_REG); chip_version = swab16(fg_version); GAUGE_INFO("%s: max17058 Fuel-Gauge Ver 0x%04x\n", __func__, chip_version); return chip_version; } static void prepare_to_load_model(struct i2c_client *client) { u16 msb; u16 check_times = 0; u8 unlock_test_OCV_1/*MSB*/, unlock_test_OCV_2/*LSB*/; u16 chip_version; u16 val; int ret = 0; do{ //Step1:unlock model access, enable access to OCV and table registers ret = max17058_write_reg(client, max17058_MODEL_ACCESS_REG, max17058_MODEL_ACCESS_UNLOCK); if (ret < 0){ GAUGE_ERR("failed to Unlock Model Access in step 1\n"); return; } //Step2:Read OCV, verify Model Access Unlocked msleep(100); msb = max17058_read_reg(client, max17058_OCV_REG);//read OCV if (msb < 0){ GAUGE_ERR("failed to read OCV in step 2\n"); return; } unlock_test_OCV_1 = (msb)&(0x00FF);//"big endian":low byte save MSB unlock_test_OCV_2 = ((msb)&(0xFF00))>>8; if(check_times++ >= 3) {//avoid of while(1) check_times = 0; GAUGE_ERR("failed to ulock the model..."); break; } }while ((unlock_test_OCV_1==0xFF)&&(unlock_test_OCV_2==0xFF));//verify Model Access Unlocked /* The OCV Register will be modified during the process of loading the custom model. Read and store this value so that it can be written back to the device after the model has been loaded. do it for only the first time after power up or chip reset */ if(por_flag ==1){ original_OCV_1 = unlock_test_OCV_1;//"big endian":low byte save to MSB original_OCV_2 = unlock_test_OCV_2; por_flag = 0; //clear POR bit val = max17058_read_reg(client, max17058_STATUS_REG); val = swab16(val)& 0xFEFF; max17058_write_reg(client,max17058_STATUS_REG,val); } /****************************************************************************** Step 2.5.1 MAX17058/59 Only To ensure good RCOMP_Seg values in MAX17058/59, a POR signal has to be sent to MAX17058. The OCV must be saved before the POR signal is sent for best Fuel Gauge performance.for chip version 0x0011 only *******************************************************************************/ chip_version = max17058_get_version(client); if(chip_version == 0x0011){ do { ret = max17058_write_reg(client, max17058_CMD_REG, max17058_POR_CMD ); if (ret < 0){ GAUGE_ERR("failed to send POR Command in step 2.5.1\n"); return; } ret = max17058_write_reg(client, max17058_MODEL_ACCESS_REG, max17058_MODEL_ACCESS_UNLOCK); if (ret < 0){ GAUGE_ERR("failed to send Unlock Command in step 2.5.1\n"); return; } msleep(100); msb = max17058_read_reg(client, max17058_OCV_REG); if (msb < 0){ GAUGE_ERR("failed to Read OCV in step 2.5.1\n"); return; } unlock_test_OCV_1 = (msb)&(0x00FF);//"big endian":low byte save MSB unlock_test_OCV_2 = ((msb)&(0xFF00))>>8; if(check_times++ >= 3){//avoid of while(1) check_times = 0; GAUGE_ERR("time out3..."); break; } }while ((unlock_test_OCV_1==0xFF)&&(unlock_test_OCV_2==0xFF)); } //Step3: Write OCV //only for max17058/1/3/4, //do nothing for MAX17058 //Step4: Write RCOMP to its Maximum Value // only for max17058/1/3/4 // max17058_write_reg(client, max17058_RCOMP_REG, 0xFF00); //do nothing for MAX17058 } static void load_model(struct i2c_client *client) { int i = 0; /****************************************************************************** Step 5. Write the Model Once the model is unlocked, the host software must write the 64 byte model to the device. The model is located between memory 0x40 and 0x7F. The model is available in the INI file provided with your performance report. See the end of this document for an explanation of the INI file. Note that the table registers are write-only and will always read 0xFF. Step 9 will confirm the values were written correctly. */ for (i = 0; i < 4; i += 1) { if (i2c_smbus_write_i2c_block_data(client, (MAX17058_TABLE+i*16), 16, &model_data[i*0x10]) < 0) { GAUGE_ERR("%s: error writing model data:\n", __func__); return; } } #if 0 int k=0; u16 value = 0; //Once the model is unlocked, the host software must write the 64 bytes model to the device for(k=0;k<0x40;k+=2) { value = (model_data[k]<<8)+model_data[k+1]; //The model is located between memory 0x40 and 0x7F max17058_write_reg(client, 0x40+k, value); } #endif //Write RCOMPSeg (for MAX17048/MAX17049 only) /*for(k=0;k<0x10;k++){ max17058_write_reg(client,0x80, 0x0080); }*/ } static bool verify_model_is_correct(struct i2c_client *client) { u8 SOC_1, SOC_2; u16 msb; int ret = 0; //msleep(200);//Delay at least 150ms(max17058/1/3/4 only) //Step 7. Write OCV:write(reg[0x0E], INI_OCVTest_High_Byte, INI_OCVTest_Low_Byte) ret = max17058_write_reg(client, 0x0E, INI_OCVTEST); if (ret < 0){ GAUGE_ERR("failed to write INI_OCVTEST in step 7\n"); return ret; } //Step 7.1 Disable Hibernate (MAX17048/49 only) //max17058_write_reg(client,0x0A,0x0); //Step 7.2. Lock Model Access (MAX17048/49/58/59 only) ret = max17058_write_reg(client, max17058_MODEL_ACCESS_REG, max17058_MODEL_ACCESS_LOCK); if (ret < 0){ GAUGE_ERR("failed to Lock Model in step 7.2\n"); return ret; } //Step 8: Delay between 150ms and 600ms, delaying beyond 600ms could cause the verification to fail msleep(500); //Step 9. Read SOC register and compare to expected result msb = max17058_read_reg(client, max17058_SOC_REG); if (msb < 0){ GAUGE_ERR("failed to Read SOC register in Step 9\n"); return ret; } SOC_1 = (msb)&(0x00FF);//"big endian":low byte save MSB SOC_2 = ((msb)&(0xFF00))>>8; if(SOC_1 >= INI_SOCCHECKA && SOC_1 <= INI_SOCCHECKB) { GAUGE_INFO("####model was loaded successfully####\n"); return true; } else { GAUGE_ERR("!!!!model was NOT loaded successfully!!!!\n"); return false; } } static void cleanup_model_load(struct i2c_client *client) { u16 original_ocv=0; int ret = 0; original_ocv = ((u16)((original_OCV_1)<<8)+(u16)original_OCV_2); //step9.1, Unlock Model Access (MAX17048/49/58/59 only): To write OCV, requires model access to be unlocked ret = max17058_write_reg(client,max17058_MODEL_ACCESS_REG, max17058_MODEL_ACCESS_UNLOCK); if (ret < 0){ GAUGE_ERR("failed to Lock Model Access in step 9.1\n"); return; } //step 10 Restore CONFIG and OCV: write(reg[0x0C], INI_RCOMP, Your_Desired_Alert_Configuration) ret = max17058_write_reg(client,max17058_RCOMP_REG, 0x8A1C);//RCOMP0=8A , battery empty Alert threshold = 4% -> 0x1C if (ret < 0){ GAUGE_ERR("failed to Restore Config in step 10\n"); return; } ret = max17058_write_reg(client,max17058_OCV_REG, original_ocv); if (ret < 0){ GAUGE_ERR("failed to Restore in step 10\n"); return; } //step 10.1 Restore Hibernate (MAX17048/49 only) //do nothing for MAX17058 //step 11 Lock Model Access ret = max17058_write_reg(client,max17058_MODEL_ACCESS_REG, max17058_MODEL_ACCESS_LOCK); if (ret < 0){ GAUGE_ERR("failed to Lock Model Access in step 11\n"); return; } //step 12,//delay at least 150ms before reading SOC register mdelay(200); } static void handle_model(struct i2c_client *client,int load_or_verify) { bool model_load_ok = false; int status; int check_times = 0; u16 rcomp_reg=0, tmp_reg=0; tmp_reg = max17058_read_reg(client, max17058_RCOMP_REG); GAUGE_INFO("max17058_RCOMP_REG = 0x%04x\n", tmp_reg); rcomp_reg = tmp_reg & 0x00FF; tmp_reg = tmp_reg >> 8; status = max17058_check_por(client); if (status) { GAUGE_INFO("POR happens,need to load model data\n"); por_flag = 1; } else if ((tmp_reg != 0x001d)&&(tmp_reg != 0x003d)) { GAUGE_INFO("reg 0x0D=0x%04x != 0x001d/0x003d, need to load model data\n", tmp_reg); por_flag = 1; } else { GAUGE_INFO("POR does not happen,don't need to load model data\n"); return; } do { if(load_or_verify == LOAD_MODEL) { // Steps 1-4 prepare_to_load_model(client); // Step 5 load_model(client); } // Steps 6-9 model_load_ok = verify_model_is_correct(client); if(!model_load_ok) { load_or_verify = LOAD_MODEL; } if(check_times++ >= 3) { check_times = 0; GAUGE_INFO("max17058 handle model :time out1..."); break; } } while(!model_load_ok); // Steps 10-12 cleanup_model_load(client); //write back rcomp & alert register tmp_reg = ( rcomp_reg << 8 ) | 0x1d; GAUGE_INFO("write back max17058_RCOMP_REG value= 0x%04x\n", tmp_reg); max17058_write_reg(client, max17058_RCOMP_REG, tmp_reg); msleep(150); } static int max17058_get_temp(struct i2c_client *client) { #ifdef MAX17058_REG_POWERSUPPLY struct max17058_chip *chip = i2c_get_clientdata(client); union power_supply_propval val; if (!chip->bms_psy) chip->bms_psy = power_supply_get_by_name("battery"); if(!chip->bms_psy) { GAUGE_ERR("%s get battery power_supply error!\n", __func__); return 25;//defult 25C } chip->bms_psy->get_property(chip->bms_psy, POWER_SUPPLY_PROP_TEMP, &val); val.intval = val.intval/10; GAUGE_INFO("%s, temp = %d\n", __func__, val.intval); return val.intval; #else return g_temp; #endif } //update static void update_rcomp(struct i2c_client *client) { int NewRCOMP; u16 cfg=0; u8 temp=0; int rcomp=0; if (smb1357_get_charging_status() == POWER_SUPPLY_STATUS_CHARGING) rcomp = INI_RCOMP_CHR; else rcomp = INI_RCOMP; temp = max17058_get_temp(client); if(temp > 20) { NewRCOMP = rcomp + ((temp - 20) * TempCoHot)/INI_RCOMP_FACTOR/1000; }else if(temp <20) { NewRCOMP = rcomp + ((temp - 20) * TempCoCold)/INI_RCOMP_FACTOR/1000; }else { NewRCOMP = rcomp; } if(NewRCOMP > 0xFF) { NewRCOMP = 0xFF; }else if(NewRCOMP <0) { NewRCOMP = 0; } cfg=(NewRCOMP<<8)|((max17058_read_reg(client, max17058_RCOMP_REG) & 0xFF00) >> 8); max17058_write_reg(client, max17058_RCOMP_REG, cfg); msleep(150); } #ifdef MAX17058_REG_POWERSUPPLY static int max17058_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct max17058_chip *chip = container_of(psy, struct max17058_chip, fgbattery); switch (psp) { case POWER_SUPPLY_PROP_STATUS: val->intval = chip->status; break; case POWER_SUPPLY_PROP_ONLINE: val->intval = chip->online; break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: val->intval = chip->vcell; break; case POWER_SUPPLY_PROP_CAPACITY: val->intval = chip->soc; break; default: return -EINVAL; } return 0; } #endif //static void max17058_reset(struct i2c_client *client) //{ // max17058_write_reg(client, max17058_CMD_REG, max17058_POR_CMD); //} static void max17058_get_vcell(struct i2c_client *client) { struct max17058_chip *chip = i2c_get_clientdata(client); u16 fg_vcell = 0; u32 vcell_mV = 0; fg_vcell = max17058_read_reg(client, max17058_VCELL_REG); vcell_mV = (u32)(((fg_vcell & 0xFF)<<8) + ((fg_vcell & 0xFF00)>>8))*5/64;//78125uV/(1000*1000) = 5/64 mV/cell chip->vcell = vcell_mV; GAUGE_INFO("%s: chip->vcell = %d mV\n", __func__, chip->vcell); } static void max17058_get_soc(struct i2c_client *client) { struct max17058_chip *chip = i2c_get_clientdata(client); u16 fg_soc = 0, temp_soc=0; mutex_lock(&chip->lock); fg_soc = max17058_read_reg(client, max17058_SOC_REG); if(fg_soc < 0){ GAUGE_ERR("%s failed to get soc\n", __func__); } temp_soc = ((u16)(fg_soc & 0xFF)<<8) + ((u16)(fg_soc & 0xFF00)>>8); GAUGE_INFO("%s: temp_soc = %d, fg_soc = %d\n", __func__, temp_soc, fg_soc); if(INI_BITS == 19) { chip->soc = temp_soc/512; }else if(INI_BITS == 18){ temp_soc += 128; chip->soc = temp_soc/256; } if (chip->soc>100) chip->soc = 100; GAUGE_INFO("%s: Get final SOC = %d\n", __func__, chip->soc); mutex_unlock(&chip->lock); } #ifdef MAX17058_REG_POWERSUPPLY static void max17058_get_online(struct i2c_client *client) { struct max17058_chip *chip = i2c_get_clientdata(client); if (chip->pdata->battery_online) chip->online = chip->pdata->battery_online(); else chip->online = 1; } static void max17058_get_status(struct i2c_client *client) { struct max17058_chip *chip = i2c_get_clientdata(client); if (!chip->pdata->charger_online || !chip->pdata->charger_enable) { chip->status = POWER_SUPPLY_STATUS_UNKNOWN; return; } if (chip->pdata->charger_online()) { if (chip->pdata->charger_enable()) chip->status = POWER_SUPPLY_STATUS_CHARGING; else chip->status = POWER_SUPPLY_STATUS_NOT_CHARGING; } else { chip->status = POWER_SUPPLY_STATUS_DISCHARGING; } if (chip->soc > max17058_BATTERY_FULL) chip->status = POWER_SUPPLY_STATUS_FULL; } #endif int max17058_read_percentage(void) { //GAUGE_INFO("%s start\n", __func__); max17058_get_soc(g_max17058_chip->client); g_soc = g_max17058_chip->soc; //GAUGE_INFO("%s ori soc=%d, final soc=%d\n", __func__, g_max17058_chip->soc, g_soc); if (g_soc>100) g_soc = 100; return g_soc; } int max17058_read_current(void) { int curr=0; curr += 0x10000; return curr; } int max17058_read_volt(void) { uint16_t volt; //GAUGE_INFO("%s start\n", __func__); max17058_get_vcell(g_max17058_chip->client); volt = g_max17058_chip->vcell; //GAUGE_INFO("%s, volt = %d\n", __func__, volt); return volt; } int max17058_read_temp(void) { int ret, temp; ret = pmic_get_battery_pack_temp(&temp); //GAUGE_INFO("%s, ret = %d, temp = %d\n", __func__, ret, temp); if(ret<0) { GAUGE_ERR("%s, error when reading temp with ret = %d, set temp to 25\n", __func__, ret); return 250; } else { g_temp = temp; return temp*10; } } int max17058_read_fcc(void) { return 3000; } int max17058_read_rm(void) { return 3000 * g_soc / 100; } static void max17058_work(struct work_struct *work) { struct max17058_chip *chip; chip = container_of(work, struct max17058_chip, work.work); max17058_get_vcell(chip->client); max17058_get_soc(chip->client); max17058_read_temp();//update temp update_rcomp(chip->client);//update rcomp periodically #ifdef MAX17058_REG_POWERSUPPLY if(0) { max17058_get_online(chip->client); max17058_get_status(chip->client); } #endif handle_model(chip->client, LOAD_MODEL); GAUGE_INFO("%s: v=%d, soc=%d, rcomp=%d, temp=%d\n", __func__, chip->vcell, chip->soc, max17058_read_reg(chip->client, max17058_RCOMP_REG), g_temp); schedule_delayed_work(&chip->work, max17058_DELAY); } //static void max17058_handle_work(struct work_struct *work) //{ // struct max17058_chip *chip; // // chip = container_of(work, struct max17058_chip, work.work); // handle_model(chip->client, LOAD_MODEL); // schedule_delayed_work(&chip->hand_work, max17058_DELAY); //} static ssize_t batt_switch_name(struct switch_dev *sdev, char *buf) { u16 version = (max17058_read_reg(g_max17058_chip->client, max17058_RCOMP_REG)>>8); if ((version==0x001d)||(version==0x003d)) return sprintf(buf, "%s\n", "Z2CP3 20151019"); else return sprintf(buf, "%s\n", "Z2CP3 00010001"); } #ifdef MAX17058_REG_POWERSUPPLY static enum power_supply_property max17058_battery_props[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_ONLINE, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_CAPACITY, }; #endif static int max17058_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent); struct max17058_chip *chip; u16 rcomp_reg=0; int ret; u32 test_major_flag=0; struct asus_bat_config bat_cfg; GAUGE_INFO("%s +++\n", __func__); if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE)) return -EIO; chip = kzalloc(sizeof(*chip), GFP_KERNEL); if (!chip) return -ENOMEM; chip->client = client; #ifdef MAX17058_REG_POWERSUPPLY chip->pdata = client->dev.platform_data; #endif i2c_set_clientdata(client, chip); #ifdef MAX17058_REG_POWERSUPPLY chip->fgbattery.name = "max17058_fgauge"; chip->fgbattery.type = POWER_SUPPLY_TYPE_BATTERY; chip->fgbattery.get_property = max17058_get_property; chip->fgbattery.properties = max17058_battery_props; chip->fgbattery.num_properties = ARRAY_SIZE(max17058_battery_props); ret = power_supply_register(&client->dev, &chip->fgbattery); if (ret) { GAUGE_INFO("failed: power supply register\n"); kfree(chip); return ret; } chip->bms_psy = power_supply_get_by_name("battery"); if (!chip->bms_psy) { GAUGE_ERR("ma17058 battery power supply not found deferring probe\n"); //return -EPROBE_DEFER; } #endif //turn to jiffeys bat_cfg.polling_time = 0; bat_cfg.critical_polling_time = 0; bat_cfg.polling_time *= HZ; bat_cfg.critical_polling_time *= HZ; ret = asus_battery_init(bat_cfg.polling_time, bat_cfg.critical_polling_time, test_major_flag); if (ret) GAUGE_ERR("asus_battery_init fail\n"); max17058_get_version(client); rcomp_reg = (0x8A<<8)|((max17058_read_reg(client, max17058_RCOMP_REG) & 0xFF00)>>8); max17058_write_reg(client, max17058_RCOMP_REG, rcomp_reg); handle_model(client, LOAD_MODEL); g_max17058_chip = chip; /* initial mutex */ mutex_init(&chip->lock); INIT_DELAYED_WORK(&chip->work, max17058_work); //INIT_DELAYED_WORK(&chip->hand_work, max17058_handle_work); schedule_delayed_work(&chip->work, 5*HZ); //schedule_delayed_work(&chip->hand_work, 0); max17058_tbl.read_percentage = max17058_read_percentage; max17058_tbl.read_current = max17058_read_current; max17058_tbl.read_volt = max17058_read_volt; max17058_tbl.read_temp = max17058_read_temp; max17058_tbl.read_fcc = max17058_read_fcc; max17058_tbl.read_rm = max17058_read_rm; ret = asus_register_power_supply(&client->dev, &max17058_tbl); if (ret) GAUGE_ERR("asus_register_power_supply fail\n"); /* register switch device for battery information versions report */ max17058_batt_dev.name = "battery"; max17058_batt_dev.print_name = batt_switch_name; if (switch_dev_register(&max17058_batt_dev) < 0) GAUGE_ERR("%s: fail to register battery switch\n", __func__); GAUGE_INFO("%s ---\n", __func__); return 0; } static int max17058_remove(struct i2c_client *client) { struct max17058_chip *chip = i2c_get_clientdata(client); #ifdef MAX17058_REG_POWERSUPPLY power_supply_unregister(&chip->fgbattery); #endif cancel_delayed_work(&chip->work); kfree(chip); return 0; } #ifdef CONFIG_PM static int max17058_suspend(struct i2c_client *client, pm_message_t state) { struct max17058_chip *chip = i2c_get_clientdata(client); GAUGE_INFO("%s +++\n", __func__); cancel_delayed_work(&chip->work); return 0; } static int max17058_resume(struct i2c_client *client) { struct max17058_chip *chip = i2c_get_clientdata(client); GAUGE_INFO("%s +++\n", __func__); schedule_delayed_work(&chip->work, max17058_DELAY); return 0; } #else #define max17058_suspend NULL #define max17058_resume NULL #endif /* CONFIG_PM */ //static struct of_device_id max17058_match_table[] = { // { .compatible = "max,max17058-fg"}, // { }, //}; static const struct i2c_device_id max17058_id[] = { { "max17058_batt", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, max17058_id); static struct i2c_driver max17058_i2c_driver = { .driver = { .name = "max17058_batt", // .of_match_table = max17058_match_table, }, .probe = max17058_probe, .remove = max17058_remove, .suspend = max17058_suspend, .resume = max17058_resume, .id_table = max17058_id, }; //module_i2c_driver(max17058_i2c_driver); //static struct i2c_board_info max17058_board_info[] = { // { // I2C_BOARD_INFO("max17058", 0x36), // }, //}; static int __init max17058_init(void) { int ret; GAUGE_INFO("%s +++\n", __func__); if (Read_PROJ_ID()!=PROJ_ID_ZX550ML) { GAUGE_INFO("Project version is NOT ZX550ML, so donot init\n"); return 0; } ret = i2c_add_driver(&max17058_i2c_driver); if (ret) GAUGE_ERR("%s: i2c_add_driver failed\n", __func__); // ret = i2c_register_board_info(2, max17058_board_info, ARRAY_SIZE(max17058_board_info)); // if (ret) // GAUGE_ERR("%s: i2c_register_board_info failed\n", __func__); GAUGE_INFO("%s ---\n", __func__); return ret; } late_initcall(max17058_init); static void max17058_exit(void) { i2c_del_driver(&max17058_i2c_driver); } module_exit(max17058_exit); MODULE_AUTHOR("maxim integrated"); MODULE_DESCRIPTION("max17058 Fuel Gauge"); MODULE_LICENSE("GPL");
shakalaca/ASUS_ZenFone_ZX551ML
linux/kernel/drivers/power/ASUS_BATTERY/max17058_battery.c
C
gpl-2.0
24,657
# Copyright (C) 2008 Canonical Ltd # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # 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 from __future__ import absolute_import """Server-side pack repository related request implmentations.""" from bzrlib.smart.request import ( FailedSmartServerResponse, SuccessfulSmartServerResponse, ) from bzrlib.smart.repository import ( SmartServerRepositoryRequest, ) class SmartServerPackRepositoryAutopack(SmartServerRepositoryRequest): def do_repository_request(self, repository): pack_collection = getattr(repository, '_pack_collection', None) if pack_collection is None: # This is a not a pack repo, so asking for an autopack is just a # no-op. return SuccessfulSmartServerResponse(('ok',)) repository.lock_write() try: repository._pack_collection.autopack() finally: repository.unlock() return SuccessfulSmartServerResponse(('ok',))
stewartsmith/bzr
bzrlib/smart/packrepository.py
Python
gpl-2.0
1,623
/*****************************************************************************\ * read_config.h - functions and declarations for reading slurmdbd.conf ***************************************************************************** * Copyright (C) 2003-2007 The Regents of the University of California. * Copyright (C) 2008-2009 Lawrence Livermore National Security. * Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER). * Written by Morris Jette <jette1@llnl.gov> * CODE-OCEC-09-009. All rights reserved. * * This file is part of SLURM, a resource management program. * For details, see <http://slurm.schedmd.com/>. * Please also read the included file: DISCLAIMER. * * SLURM 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. * * In addition, as a special exception, the copyright holders give permission * to link the code of portions of this program with the OpenSSL library under * certain conditions as described in each individual source file, and * distribute linked combinations including the two. You must obey the GNU * General Public License in all respects for all of the code used other than * OpenSSL. If you modify file(s) with this exception, you may extend this * exception to your version of the file(s), but you are not obligated to do * so. If you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files in * the program, then also delete it here. * * SLURM 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 SLURM; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. \*****************************************************************************/ #ifndef _DBD_READ_CONFIG_H #define _DBD_READ_CONFIG_H #if HAVE_CONFIG_H # include "config.h" #if HAVE_INTTYPES_H # include <inttypes.h> #else /* !HAVE_INTTYPES_H */ # if HAVE_STDINT_H # include <stdint.h> # endif #endif /* HAVE_INTTYPES_H */ #else /* !HAVE_CONFIG_H */ #include <stdint.h> #endif /* HAVE_CONFIG_H */ #include <time.h> #include <pthread.h> #include "src/common/list.h" #define DEFAULT_SLURMDBD_AUTHTYPE "auth/none" //#define DEFAULT_SLURMDBD_JOB_PURGE 12 #define DEFAULT_SLURMDBD_PIDFILE "/var/run/slurmdbd.pid" #define DEFAULT_SLURMDBD_ARCHIVE_DIR "/tmp" //#define DEFAULT_SLURMDBD_STEP_PURGE 1 /* SlurmDBD configuration parameters */ typedef struct slurm_dbd_conf { time_t last_update; /* time slurmdbd.conf read */ char * archive_dir; /* location to localy * store data if not * using a script */ char * archive_script; /* script to archive old data */ char * auth_info; /* authentication info */ char * auth_type; /* authentication mechanism */ uint16_t control_timeout;/* how long to wait before * backup takes control */ char * dbd_addr; /* network address of Slurm DBD */ char * dbd_backup; /* hostname of Slurm DBD backup */ char * dbd_host; /* hostname of Slurm DBD */ uint16_t dbd_port; /* port number for RPCs to DBD */ uint16_t debug_level; /* Debug level, default=3 */ char * default_qos; /* default qos setting when * adding clusters */ char * log_file; /* Log file */ uint16_t log_fmt; /* Log file timestamt format */ uint16_t msg_timeout; /* message timeout */ char * pid_file; /* where to store current PID */ char * plugindir; /* dir to look for plugins */ uint16_t private_data; /* restrict information */ /* purge variable format * controlled by PURGE_FLAGS */ uint32_t purge_event; /* purge events older than * this in months or days */ uint32_t purge_job; /* purge time for job info */ uint32_t purge_resv; /* purge time for reservation info */ uint32_t purge_step; /* purge time for step info */ uint32_t purge_suspend; /* purge suspend data older * than this in months or days */ uint32_t slurm_user_id; /* uid of slurm_user_name */ char * slurm_user_name;/* user that slurmcdtld runs as */ char * storage_backup_host;/* backup host where DB is * running */ char * storage_host; /* host where DB is running */ char * storage_loc; /* database name */ char * storage_pass; /* password for DB write */ uint16_t storage_port; /* port DB is listening to */ char * storage_type; /* DB to be used for storage */ char * storage_user; /* user authorized to write DB */ uint16_t track_wckey; /* Whether or not to track wckey*/ uint16_t track_ctld; /* Whether or not track when a * slurmctld goes down or not */ } slurm_dbd_conf_t; extern pthread_mutex_t conf_mutex; extern slurm_dbd_conf_t *slurmdbd_conf; /* * free_slurmdbd_conf - free storage associated with the global variable * slurmdbd_conf */ extern void free_slurmdbd_conf(void); /* Return the DbdPort value */ extern uint16_t get_dbd_port(void); /* lock and unlock the dbd_conf */ extern void slurmdbd_conf_lock(void); extern void slurmdbd_conf_unlock(void); /* Log the current configuration using verbose() */ extern void log_config(void); /* * read_slurmdbd_conf - load the SlurmDBD configuration from the slurmdbd.conf * file. This function can be called more than once if so desired. * RET SLURM_SUCCESS if no error, otherwise an error code */ extern int read_slurmdbd_conf(void); /* Dump the configuration in name,value pairs for output to * "sacctmgr show config", caller must call list_destroy() */ extern List dump_config(void); #endif /* !_DBD_READ_CONFIG_H */
surban/slurm
src/slurmdbd/read_config.h
C
gpl-2.0
6,082
import os, platform sysstr = platform.system() if sysstr == "Windows": LF = '\r\n' elif sysstr == "Linux": LF = '\n' def StripStr(str): # @Function: Remove space(' ') and indent('\t') at the begin and end of the string oldStr = '' newStr = str while oldStr != newStr: oldStr = newStr newStr = oldStr.strip('\t') newStr = newStr.strip(' ') return newStr def SplitStr(str, spliters=None): # @Function: Split string by spliter space(' ') and indent('\t') as default # spliters = [' ', '\t'] # spliters = [] # if spliter is not None: # spliters.append(spliter) if spliters is None: spliters = [' ', '\t'] destStrs = [] srcStrs = [str] while True: oldDestStrs = srcStrs[:] for s in spliters: for srcS in srcStrs: tempStrs = srcS.split(s) for tempS in tempStrs: tempS = StripStr(tempS) if tempS != '': destStrs.append(tempS) srcStrs = destStrs[:] destStrs = [] if oldDestStrs == srcStrs: destStrs = srcStrs[:] break return destStrs def isPathExists(path): if os.path.isdir(path): if os.path.exists(path): return True else: return False else: return False def WriteLog(logfile, contentlist, MODE='replace'): if os.path.exists(logfile): if MODE == 'replace': os.remove(logfile) logStatus = open(logfile, 'w') else: logStatus = open(logfile, 'a') else: logStatus = open(logfile, 'w') if isinstance(contentlist, list) or isinstance(contentlist,tuple): for content in contentlist: logStatus.write("%s%s" % (content, LF)) else: logStatus.write(contentlist) logStatus.flush() logStatus.close()
seims/SEIMS
scenario_analysis/util.py
Python
gpl-2.0
1,939
/*************************************************************************** qgsactionmenu.h -------------------------------------- Date : 11.8.2014 Copyright : (C) 2014 Matthias Kuhn Email : matthias at opengis dot ch *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef QGSACTIONMENU_H #define QGSACTIONMENU_H #include <QMenu> #include <QSignalMapper> #include "qgsactionmanager.h" #include "qgsmaplayeractionregistry.h" /** * This class is a menu that is populated automatically with the actions defined for a given layer. */ class GUI_EXPORT QgsActionMenu : public QMenu { Q_OBJECT public: enum ActionType { Invalid, //!< Invalid MapLayerAction, //!< Standard actions (defined by core or plugins) AttributeAction //!< Custom actions (manually defined in layer properties) }; struct ActionData { ActionData() : actionType( Invalid ) , actionId( 0 ) , featureId( 0 ) , mapLayer( nullptr ) {} ActionData( int actionId, QgsFeatureId featureId, QgsMapLayer* mapLayer ) : actionType( AttributeAction ) , actionId( actionId ) , featureId( featureId ) , mapLayer( mapLayer ) {} ActionData( QgsMapLayerAction* action, QgsFeatureId featureId, QgsMapLayer* mapLayer ) : actionType( MapLayerAction ) , actionId( action ) , featureId( featureId ) , mapLayer( mapLayer ) {} ActionType actionType; union aid { aid( int i ) : id( i ) {} aid( QgsMapLayerAction* a ) : action( a ) {} int id; QgsMapLayerAction* action; } actionId; QgsFeatureId featureId; QgsMapLayer* mapLayer; }; /** * Constructs a new QgsActionMenu * * @param layer The layer that this action will be run upon. * @param feature The feature that this action will be run upon. Make sure that this feature is available * for the lifetime of this object. * @param parent The usual QWidget parent. */ explicit QgsActionMenu( QgsVectorLayer *layer, const QgsFeature *feature, QWidget *parent = nullptr ); /** * Constructs a new QgsActionMenu * * @param layer The layer that this action will be run upon. * @param fid The feature id of the feature for which this action will be run. * @param parent The usual QWidget parent. */ explicit QgsActionMenu( QgsVectorLayer *layer, const QgsFeatureId fid, QWidget *parent = nullptr ); /** * Destructor */ ~QgsActionMenu(); /** * Change the feature on which actions are performed * * @param feature A feature. Will not take ownership. It's the callers responsibility to keep the feature * as long as the menu is displayed and the action is running. */ void setFeature( QgsFeature* feature ); private slots: void triggerAction(); void reloadActions(); signals: void reinit(); private: void init(); const QgsFeature* feature(); QgsVectorLayer* mLayer; QgsActionManager* mActions; const QgsFeature* mFeature; QgsFeatureId mFeatureId; bool mOwnsFeature; }; Q_DECLARE_METATYPE( QgsActionMenu::ActionData ) #endif // QGSACTIONMENU_H
AsgerPetersen/QGIS
src/gui/qgsactionmenu.h
C
gpl-2.0
3,983
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Implementation of the Transmission Control Protocol(TCP). * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Mark Evans, <evansmp@uhura.aston.ac.uk> * Corey Minyard <wf-rch!minyard@relay.EU.net> * Florian La Roche, <flla@stud.uni-sb.de> * Charles Hedrick, <hedrick@klinzhai.rutgers.edu> * Linus Torvalds, <torvalds@cs.helsinki.fi> * Alan Cox, <gw4pts@gw4pts.ampr.org> * Matthew Dillon, <dillon@apollo.west.oic.com> * Arnt Gulbrandsen, <agulbra@nvg.unit.no> * Jorge Cwik, <jorge@laser.satlink.net> */ /* * Changes: Pedro Roque : Retransmit queue handled by TCP. * : Fragmentation on mtu decrease * : Segment collapse on retransmit * : AF independence * * Linus Torvalds : send_delayed_ack * David S. Miller : Charge memory using the right skb * during syn/ack processing. * David S. Miller : Output engine completely rewritten. * Andrea Arcangeli: SYNACK carry ts_recent in tsecr. * Cacophonix Gaul : draft-minshall-nagle-01 * J Hadi Salim : ECN support * */ #include <net/tcp.h> #include <linux/compiler.h> #include <linux/gfp.h> #include <linux/module.h> /* People can turn this off for buggy TCP's found in printers etc. */ int sysctl_tcp_retrans_collapse __read_mostly = 1; /* People can turn this on to work with those rare, broken TCPs that * interpret the window field as a signed quantity. */ int sysctl_tcp_workaround_signed_windows __read_mostly = 0; /* This limits the percentage of the congestion window which we * will allow a single TSO frame to consume. Building TSO frames * which are too large can cause TCP streams to be bursty. */ int sysctl_tcp_tso_win_divisor __read_mostly = 3; int sysctl_tcp_mtu_probing __read_mostly = 0; int sysctl_tcp_base_mss __read_mostly = TCP_BASE_MSS; /* By default, RFC2861 behavior. */ int sysctl_tcp_slow_start_after_idle __read_mostly = 1; int sysctl_tcp_cookie_size __read_mostly = 0; /* TCP_COOKIE_MAX */ EXPORT_SYMBOL_GPL(sysctl_tcp_cookie_size); /* Account for new data that has been sent to the network. */ static void tcp_event_new_data_sent(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); unsigned int prior_packets = tp->packets_out; tcp_advance_send_head(sk, skb); tp->snd_nxt = TCP_SKB_CB(skb)->end_seq; /* Don't override Nagle indefinitely with F-RTO */ if (tp->frto_counter == 2) tp->frto_counter = 3; tp->packets_out += tcp_skb_pcount(skb); if (!prior_packets) inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS, inet_csk(sk)->icsk_rto, TCP_RTO_MAX); } /* SND.NXT, if window was not shrunk. * If window has been shrunk, what should we make? It is not clear at all. * Using SND.UNA we will fail to open window, SND.NXT is out of window. :-( * Anything in between SND.UNA...SND.UNA+SND.WND also can be already * invalid. OK, let's make this for now: */ static inline __u32 tcp_acceptable_seq(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); if (!before(tcp_wnd_end(tp), tp->snd_nxt)) return tp->snd_nxt; else return tcp_wnd_end(tp); } /* Calculate mss to advertise in SYN segment. * RFC1122, RFC1063, draft-ietf-tcpimpl-pmtud-01 state that: * * 1. It is independent of path mtu. * 2. Ideally, it is maximal possible segment size i.e. 65535-40. * 3. For IPv4 it is reasonable to calculate it from maximal MTU of * attached devices, because some buggy hosts are confused by * large MSS. * 4. We do not make 3, we advertise MSS, calculated from first * hop device mtu, but allow to raise it to ip_rt_min_advmss. * This may be overridden via information stored in routing table. * 5. Value 65535 for MSS is valid in IPv6 and means "as large as possible, * probably even Jumbo". */ static __u16 tcp_advertise_mss(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct dst_entry *dst = __sk_dst_get(sk); int mss = tp->advmss; if (dst) { unsigned int metric = dst_metric_advmss(dst); if (metric < mss) { mss = metric; tp->advmss = mss; } } // #if defined(LGE_ATT) || defined(LGE_TRACFONE) mss = 1370; tp->advmss = mss; #endif // return (__u16)mss; } /* RFC2861. Reset CWND after idle period longer RTO to "restart window". * This is the first part of cwnd validation mechanism. */ static void tcp_cwnd_restart(struct sock *sk, struct dst_entry *dst) { struct tcp_sock *tp = tcp_sk(sk); s32 delta = tcp_time_stamp - tp->lsndtime; u32 restart_cwnd = tcp_init_cwnd(tp, dst); u32 cwnd = tp->snd_cwnd; tcp_ca_event(sk, CA_EVENT_CWND_RESTART); tp->snd_ssthresh = tcp_current_ssthresh(sk); restart_cwnd = min(restart_cwnd, cwnd); while ((delta -= inet_csk(sk)->icsk_rto) > 0 && cwnd > restart_cwnd) cwnd >>= 1; tp->snd_cwnd = max(cwnd, restart_cwnd); tp->snd_cwnd_stamp = tcp_time_stamp; tp->snd_cwnd_used = 0; } /* Congestion state accounting after a packet has been sent. */ static void tcp_event_data_sent(struct tcp_sock *tp, struct sk_buff *skb, struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); const u32 now = tcp_time_stamp; if (sysctl_tcp_slow_start_after_idle && (!tp->packets_out && (s32)(now - tp->lsndtime) > icsk->icsk_rto)) tcp_cwnd_restart(sk, __sk_dst_get(sk)); tp->lsndtime = now; /* If it is a reply for ato after last received * packet, enter pingpong mode. */ if ((u32)(now - icsk->icsk_ack.lrcvtime) < icsk->icsk_ack.ato) icsk->icsk_ack.pingpong = 1; } /* Account for an ACK we sent. */ static inline void tcp_event_ack_sent(struct sock *sk, unsigned int pkts) { tcp_dec_quickack_mode(sk, pkts); inet_csk_clear_xmit_timer(sk, ICSK_TIME_DACK); } /* Determine a window scaling and initial window to offer. * Based on the assumption that the given amount of space * will be offered. Store the results in the tp structure. * NOTE: for smooth operation initial space offering should * be a multiple of mss if possible. We assume here that mss >= 1. * This MUST be enforced by all callers. */ void tcp_select_initial_window(int __space, __u32 mss, __u32 *rcv_wnd, __u32 *window_clamp, int wscale_ok, __u8 *rcv_wscale, __u32 init_rcv_wnd) { unsigned int space = (__space < 0 ? 0 : __space); /* If no clamp set the clamp to the max possible scaled window */ if (*window_clamp == 0) (*window_clamp) = (65535 << 14); space = min(*window_clamp, space); /* Quantize space offering to a multiple of mss if possible. */ if (space > mss) space = (space / mss) * mss; /* NOTE: offering an initial window larger than 32767 * will break some buggy TCP stacks. If the admin tells us * it is likely we could be speaking with such a buggy stack * we will truncate our initial window offering to 32K-1 * unless the remote has sent us a window scaling option, * which we interpret as a sign the remote TCP is not * misinterpreting the window field as a signed quantity. */ if (sysctl_tcp_workaround_signed_windows) (*rcv_wnd) = min(space, MAX_TCP_WINDOW); else (*rcv_wnd) = space; (*rcv_wscale) = 0; if (wscale_ok) { /* Set window scaling on max possible window * See RFC1323 for an explanation of the limit to 14 */ space = max_t(u32, sysctl_tcp_rmem[2], sysctl_rmem_max); space = min_t(u32, space, *window_clamp); while (space > 65535 && (*rcv_wscale) < 14) { space >>= 1; (*rcv_wscale)++; } } // #if defined(LGE_ATT) || defined(LGE_TRACFONE) (*rcv_wnd) = space; #else /* Set initial window to a value enough for senders starting with * initial congestion window of TCP_DEFAULT_INIT_RCVWND. Place * a limit on the initial window when mss is larger than 1460. */ if (mss > (1 << *rcv_wscale)) { int init_cwnd = TCP_DEFAULT_INIT_RCVWND; if (mss > 1460) init_cwnd = max_t(u32, (1460 * TCP_DEFAULT_INIT_RCVWND) / mss, 2); /* when initializing use the value from init_rcv_wnd * rather than the default from above */ if (init_rcv_wnd) *rcv_wnd = min(*rcv_wnd, init_rcv_wnd * mss); else *rcv_wnd = min(*rcv_wnd, init_cwnd * mss); } #endif // /* Set the clamp no higher than max representable value */ (*window_clamp) = min(65535U << (*rcv_wscale), *window_clamp); } EXPORT_SYMBOL(tcp_select_initial_window); /* Chose a new window to advertise, update state in tcp_sock for the * socket, and return result with RFC1323 scaling applied. The return * value can be stuffed directly into th->window for an outgoing * frame. */ static u16 tcp_select_window(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); u32 cur_win = tcp_receive_window(tp); u32 new_win = __tcp_select_window(sk); /* Never shrink the offered window */ if (new_win < cur_win) { /* Danger Will Robinson! * Don't update rcv_wup/rcv_wnd here or else * we will not be able to advertise a zero * window in time. --DaveM * * Relax Will Robinson. */ new_win = ALIGN(cur_win, 1 << tp->rx_opt.rcv_wscale); } tp->rcv_wnd = new_win; tp->rcv_wup = tp->rcv_nxt; /* Make sure we do not exceed the maximum possible * scaled window. */ if (!tp->rx_opt.rcv_wscale && sysctl_tcp_workaround_signed_windows) new_win = min(new_win, MAX_TCP_WINDOW); else new_win = min(new_win, (65535U << tp->rx_opt.rcv_wscale)); /* RFC1323 scaling applied */ new_win >>= tp->rx_opt.rcv_wscale; /* If we advertise zero window, disable fast path. */ if (new_win == 0) tp->pred_flags = 0; return new_win; } /* Packet ECN state for a SYN-ACK */ static inline void TCP_ECN_send_synack(struct tcp_sock *tp, struct sk_buff *skb) { TCP_SKB_CB(skb)->flags &= ~TCPHDR_CWR; if (!(tp->ecn_flags & TCP_ECN_OK)) TCP_SKB_CB(skb)->flags &= ~TCPHDR_ECE; } /* Packet ECN state for a SYN. */ static inline void TCP_ECN_send_syn(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); tp->ecn_flags = 0; if (sysctl_tcp_ecn == 1) { TCP_SKB_CB(skb)->flags |= TCPHDR_ECE | TCPHDR_CWR; tp->ecn_flags = TCP_ECN_OK; } } static __inline__ void TCP_ECN_make_synack(struct request_sock *req, struct tcphdr *th) { if (inet_rsk(req)->ecn_ok) th->ece = 1; } /* Set up ECN state for a packet on a ESTABLISHED socket that is about to * be sent. */ static inline void TCP_ECN_send(struct sock *sk, struct sk_buff *skb, int tcp_header_len) { struct tcp_sock *tp = tcp_sk(sk); if (tp->ecn_flags & TCP_ECN_OK) { /* Not-retransmitted data segment: set ECT and inject CWR. */ if (skb->len != tcp_header_len && !before(TCP_SKB_CB(skb)->seq, tp->snd_nxt)) { INET_ECN_xmit(sk); if (tp->ecn_flags & TCP_ECN_QUEUE_CWR) { tp->ecn_flags &= ~TCP_ECN_QUEUE_CWR; tcp_hdr(skb)->cwr = 1; skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN; } } else { /* ACK or retransmitted segment: clear ECT|CE */ INET_ECN_dontxmit(sk); } if (tp->ecn_flags & TCP_ECN_DEMAND_CWR) tcp_hdr(skb)->ece = 1; } } /* Constructs common control bits of non-data skb. If SYN/FIN is present, * auto increment end seqno. */ static void tcp_init_nondata_skb(struct sk_buff *skb, u32 seq, u8 flags) { skb->ip_summed = CHECKSUM_PARTIAL; skb->csum = 0; TCP_SKB_CB(skb)->flags = flags; TCP_SKB_CB(skb)->sacked = 0; skb_shinfo(skb)->gso_segs = 1; skb_shinfo(skb)->gso_size = 0; skb_shinfo(skb)->gso_type = 0; TCP_SKB_CB(skb)->seq = seq; if (flags & (TCPHDR_SYN | TCPHDR_FIN)) seq++; TCP_SKB_CB(skb)->end_seq = seq; } static inline int tcp_urg_mode(const struct tcp_sock *tp) { return tp->snd_una != tp->snd_up; } #define OPTION_SACK_ADVERTISE (1 << 0) #define OPTION_TS (1 << 1) #define OPTION_MD5 (1 << 2) #define OPTION_WSCALE (1 << 3) #define OPTION_COOKIE_EXTENSION (1 << 4) struct tcp_out_options { u8 options; /* bit field of OPTION_* */ u8 ws; /* window scale, 0 to disable */ u8 num_sack_blocks; /* number of SACK blocks to include */ u8 hash_size; /* bytes in hash_location */ u16 mss; /* 0 to disable */ __u32 tsval, tsecr; /* need to include OPTION_TS */ __u8 *hash_location; /* temporary pointer, overloaded */ }; /* The sysctl int routines are generic, so check consistency here. */ static u8 tcp_cookie_size_check(u8 desired) { int cookie_size; if (desired > 0) /* previously specified */ return desired; cookie_size = ACCESS_ONCE(sysctl_tcp_cookie_size); if (cookie_size <= 0) /* no default specified */ return 0; if (cookie_size <= TCP_COOKIE_MIN) /* value too small, specify minimum */ return TCP_COOKIE_MIN; if (cookie_size >= TCP_COOKIE_MAX) /* value too large, specify maximum */ return TCP_COOKIE_MAX; if (cookie_size & 1) /* 8-bit multiple, illegal, fix it */ cookie_size++; return (u8)cookie_size; } /* Write previously computed TCP options to the packet. * * Beware: Something in the Internet is very sensitive to the ordering of * TCP options, we learned this through the hard way, so be careful here. * Luckily we can at least blame others for their non-compliance but from * inter-operatibility perspective it seems that we're somewhat stuck with * the ordering which we have been using if we want to keep working with * those broken things (not that it currently hurts anybody as there isn't * particular reason why the ordering would need to be changed). * * At least SACK_PERM as the first option is known to lead to a disaster * (but it may well be that other scenarios fail similarly). */ static void tcp_options_write(__be32 *ptr, struct tcp_sock *tp, struct tcp_out_options *opts) { u8 options = opts->options; /* mungable copy */ /* Having both authentication and cookies for security is redundant, * and there's certainly not enough room. Instead, the cookie-less * extension variant is proposed. * * Consider the pessimal case with authentication. The options * could look like: * COOKIE|MD5(20) + MSS(4) + SACK|TS(12) + WSCALE(4) == 40 */ if (unlikely(OPTION_MD5 & options)) { if (unlikely(OPTION_COOKIE_EXTENSION & options)) { *ptr++ = htonl((TCPOPT_COOKIE << 24) | (TCPOLEN_COOKIE_BASE << 16) | (TCPOPT_MD5SIG << 8) | TCPOLEN_MD5SIG); } else { *ptr++ = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | (TCPOPT_MD5SIG << 8) | TCPOLEN_MD5SIG); } options &= ~OPTION_COOKIE_EXTENSION; /* overload cookie hash location */ opts->hash_location = (__u8 *)ptr; ptr += 4; } if (unlikely(opts->mss)) { *ptr++ = htonl((TCPOPT_MSS << 24) | (TCPOLEN_MSS << 16) | opts->mss); } if (likely(OPTION_TS & options)) { if (unlikely(OPTION_SACK_ADVERTISE & options)) { *ptr++ = htonl((TCPOPT_SACK_PERM << 24) | (TCPOLEN_SACK_PERM << 16) | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP); options &= ~OPTION_SACK_ADVERTISE; } else { *ptr++ = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP); } *ptr++ = htonl(opts->tsval); *ptr++ = htonl(opts->tsecr); } /* Specification requires after timestamp, so do it now. * * Consider the pessimal case without authentication. The options * could look like: * MSS(4) + SACK|TS(12) + COOKIE(20) + WSCALE(4) == 40 */ if (unlikely(OPTION_COOKIE_EXTENSION & options)) { __u8 *cookie_copy = opts->hash_location; u8 cookie_size = opts->hash_size; /* 8-bit multiple handled in tcp_cookie_size_check() above, * and elsewhere. */ if (0x2 & cookie_size) { __u8 *p = (__u8 *)ptr; /* 16-bit multiple */ *p++ = TCPOPT_COOKIE; *p++ = TCPOLEN_COOKIE_BASE + cookie_size; *p++ = *cookie_copy++; *p++ = *cookie_copy++; ptr++; cookie_size -= 2; } else { /* 32-bit multiple */ *ptr++ = htonl(((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | (TCPOPT_COOKIE << 8) | TCPOLEN_COOKIE_BASE) + cookie_size); } if (cookie_size > 0) { memcpy(ptr, cookie_copy, cookie_size); ptr += (cookie_size / 4); } } if (unlikely(OPTION_SACK_ADVERTISE & options)) { *ptr++ = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | (TCPOPT_SACK_PERM << 8) | TCPOLEN_SACK_PERM); } if (unlikely(OPTION_WSCALE & options)) { *ptr++ = htonl((TCPOPT_NOP << 24) | (TCPOPT_WINDOW << 16) | (TCPOLEN_WINDOW << 8) | opts->ws); } if (unlikely(opts->num_sack_blocks)) { struct tcp_sack_block *sp = tp->rx_opt.dsack ? tp->duplicate_sack : tp->selective_acks; int this_sack; *ptr++ = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | (TCPOPT_SACK << 8) | (TCPOLEN_SACK_BASE + (opts->num_sack_blocks * TCPOLEN_SACK_PERBLOCK))); for (this_sack = 0; this_sack < opts->num_sack_blocks; ++this_sack) { *ptr++ = htonl(sp[this_sack].start_seq); *ptr++ = htonl(sp[this_sack].end_seq); } tp->rx_opt.dsack = 0; } } /* Compute TCP options for SYN packets. This is not the final * network wire format yet. */ static unsigned tcp_syn_options(struct sock *sk, struct sk_buff *skb, struct tcp_out_options *opts, struct tcp_md5sig_key **md5) { struct tcp_sock *tp = tcp_sk(sk); struct tcp_cookie_values *cvp = tp->cookie_values; unsigned remaining = MAX_TCP_OPTION_SPACE; u8 cookie_size = (!tp->rx_opt.cookie_out_never && cvp != NULL) ? tcp_cookie_size_check(cvp->cookie_desired) : 0; #ifdef CONFIG_TCP_MD5SIG *md5 = tp->af_specific->md5_lookup(sk, sk); if (*md5) { opts->options |= OPTION_MD5; remaining -= TCPOLEN_MD5SIG_ALIGNED; } #else *md5 = NULL; #endif /* We always get an MSS option. The option bytes which will be seen in * normal data packets should timestamps be used, must be in the MSS * advertised. But we subtract them from tp->mss_cache so that * calculations in tcp_sendmsg are simpler etc. So account for this * fact here if necessary. If we don't do this correctly, as a * receiver we won't recognize data packets as being full sized when we * should, and thus we won't abide by the delayed ACK rules correctly. * SACKs don't matter, we never delay an ACK when we have any of those * going out. */ opts->mss = tcp_advertise_mss(sk); remaining -= TCPOLEN_MSS_ALIGNED; if (likely(sysctl_tcp_timestamps && *md5 == NULL)) { opts->options |= OPTION_TS; opts->tsval = TCP_SKB_CB(skb)->when; opts->tsecr = tp->rx_opt.ts_recent; remaining -= TCPOLEN_TSTAMP_ALIGNED; } if (likely(sysctl_tcp_window_scaling)) { opts->ws = tp->rx_opt.rcv_wscale; opts->options |= OPTION_WSCALE; remaining -= TCPOLEN_WSCALE_ALIGNED; } if (likely(sysctl_tcp_sack)) { opts->options |= OPTION_SACK_ADVERTISE; if (unlikely(!(OPTION_TS & opts->options))) remaining -= TCPOLEN_SACKPERM_ALIGNED; } /* Note that timestamps are required by the specification. * * Odd numbers of bytes are prohibited by the specification, ensuring * that the cookie is 16-bit aligned, and the resulting cookie pair is * 32-bit aligned. */ if (*md5 == NULL && (OPTION_TS & opts->options) && cookie_size > 0) { int need = TCPOLEN_COOKIE_BASE + cookie_size; if (0x2 & need) { /* 32-bit multiple */ need += 2; /* NOPs */ if (need > remaining) { /* try shrinking cookie to fit */ cookie_size -= 2; need -= 4; } } while (need > remaining && TCP_COOKIE_MIN <= cookie_size) { cookie_size -= 4; need -= 4; } if (TCP_COOKIE_MIN <= cookie_size) { opts->options |= OPTION_COOKIE_EXTENSION; opts->hash_location = (__u8 *)&cvp->cookie_pair[0]; opts->hash_size = cookie_size; /* Remember for future incarnations. */ cvp->cookie_desired = cookie_size; if (cvp->cookie_desired != cvp->cookie_pair_size) { /* Currently use random bytes as a nonce, * assuming these are completely unpredictable * by hostile users of the same system. */ get_random_bytes(&cvp->cookie_pair[0], cookie_size); cvp->cookie_pair_size = cookie_size; } remaining -= need; } } return MAX_TCP_OPTION_SPACE - remaining; } /* Set up TCP options for SYN-ACKs. */ static unsigned tcp_synack_options(struct sock *sk, struct request_sock *req, unsigned mss, struct sk_buff *skb, struct tcp_out_options *opts, struct tcp_md5sig_key **md5, struct tcp_extend_values *xvp) { struct inet_request_sock *ireq = inet_rsk(req); unsigned remaining = MAX_TCP_OPTION_SPACE; u8 cookie_plus = (xvp != NULL && !xvp->cookie_out_never) ? xvp->cookie_plus : 0; #ifdef CONFIG_TCP_MD5SIG *md5 = tcp_rsk(req)->af_specific->md5_lookup(sk, req); if (*md5) { opts->options |= OPTION_MD5; remaining -= TCPOLEN_MD5SIG_ALIGNED; /* We can't fit any SACK blocks in a packet with MD5 + TS * options. There was discussion about disabling SACK * rather than TS in order to fit in better with old, * buggy kernels, but that was deemed to be unnecessary. */ ireq->tstamp_ok &= !ireq->sack_ok; } #else *md5 = NULL; #endif /* We always send an MSS option. */ opts->mss = mss; remaining -= TCPOLEN_MSS_ALIGNED; if (likely(ireq->wscale_ok)) { opts->ws = ireq->rcv_wscale; opts->options |= OPTION_WSCALE; remaining -= TCPOLEN_WSCALE_ALIGNED; } if (likely(ireq->tstamp_ok)) { opts->options |= OPTION_TS; opts->tsval = TCP_SKB_CB(skb)->when; opts->tsecr = req->ts_recent; remaining -= TCPOLEN_TSTAMP_ALIGNED; } if (likely(ireq->sack_ok)) { opts->options |= OPTION_SACK_ADVERTISE; if (unlikely(!ireq->tstamp_ok)) remaining -= TCPOLEN_SACKPERM_ALIGNED; } /* Similar rationale to tcp_syn_options() applies here, too. * If the <SYN> options fit, the same options should fit now! */ if (*md5 == NULL && ireq->tstamp_ok && cookie_plus > TCPOLEN_COOKIE_BASE) { int need = cookie_plus; /* has TCPOLEN_COOKIE_BASE */ if (0x2 & need) { /* 32-bit multiple */ need += 2; /* NOPs */ } if (need <= remaining) { opts->options |= OPTION_COOKIE_EXTENSION; opts->hash_size = cookie_plus - TCPOLEN_COOKIE_BASE; remaining -= need; } else { /* There's no error return, so flag it. */ xvp->cookie_out_never = 1; /* true */ opts->hash_size = 0; } } return MAX_TCP_OPTION_SPACE - remaining; } /* Compute TCP options for ESTABLISHED sockets. This is not the * final wire format yet. */ static unsigned tcp_established_options(struct sock *sk, struct sk_buff *skb, struct tcp_out_options *opts, struct tcp_md5sig_key **md5) { struct tcp_skb_cb *tcb = skb ? TCP_SKB_CB(skb) : NULL; struct tcp_sock *tp = tcp_sk(sk); unsigned size = 0; unsigned int eff_sacks; #ifdef CONFIG_TCP_MD5SIG *md5 = tp->af_specific->md5_lookup(sk, sk); if (unlikely(*md5)) { opts->options |= OPTION_MD5; size += TCPOLEN_MD5SIG_ALIGNED; } #else *md5 = NULL; #endif if (likely(tp->rx_opt.tstamp_ok)) { opts->options |= OPTION_TS; opts->tsval = tcb ? tcb->when : 0; opts->tsecr = tp->rx_opt.ts_recent; size += TCPOLEN_TSTAMP_ALIGNED; } eff_sacks = tp->rx_opt.num_sacks + tp->rx_opt.dsack; if (unlikely(eff_sacks)) { const unsigned remaining = MAX_TCP_OPTION_SPACE - size; opts->num_sack_blocks = min_t(unsigned, eff_sacks, (remaining - TCPOLEN_SACK_BASE_ALIGNED) / TCPOLEN_SACK_PERBLOCK); size += TCPOLEN_SACK_BASE_ALIGNED + opts->num_sack_blocks * TCPOLEN_SACK_PERBLOCK; } return size; } /* This routine actually transmits TCP packets queued in by * tcp_do_sendmsg(). This is used by both the initial * transmission and possible later retransmissions. * All SKB's seen here are completely headerless. It is our * job to build the TCP header, and pass the packet down to * IP so it can do the same plus pass the packet off to the * device. * * We are working here with either a clone of the original * SKB, or a fresh unique copy made by the retransmit engine. */ static int tcp_transmit_skb(struct sock *sk, struct sk_buff *skb, int clone_it, gfp_t gfp_mask) { const struct inet_connection_sock *icsk = inet_csk(sk); struct inet_sock *inet; struct tcp_sock *tp; struct tcp_skb_cb *tcb; struct tcp_out_options opts; unsigned tcp_options_size, tcp_header_size; struct tcp_md5sig_key *md5; struct tcphdr *th; int err; BUG_ON(!skb || !tcp_skb_pcount(skb)); /* If congestion control is doing timestamping, we must * take such a timestamp before we potentially clone/copy. */ if (icsk->icsk_ca_ops->flags & TCP_CONG_RTT_STAMP) __net_timestamp(skb); if (likely(clone_it)) { if (unlikely(skb_cloned(skb))) skb = pskb_copy(skb, gfp_mask); else skb = skb_clone(skb, gfp_mask); if (unlikely(!skb)) return -ENOBUFS; } inet = inet_sk(sk); tp = tcp_sk(sk); tcb = TCP_SKB_CB(skb); memset(&opts, 0, sizeof(opts)); if (unlikely(tcb->flags & TCPHDR_SYN)) tcp_options_size = tcp_syn_options(sk, skb, &opts, &md5); else tcp_options_size = tcp_established_options(sk, skb, &opts, &md5); tcp_header_size = tcp_options_size + sizeof(struct tcphdr); if (tcp_packets_in_flight(tp) == 0) { tcp_ca_event(sk, CA_EVENT_TX_START); skb->ooo_okay = 1; } else skb->ooo_okay = 0; skb_push(skb, tcp_header_size); skb_reset_transport_header(skb); skb_set_owner_w(skb, sk); /* Build TCP header and checksum it. */ th = tcp_hdr(skb); th->source = inet->inet_sport; th->dest = inet->inet_dport; th->seq = htonl(tcb->seq); th->ack_seq = htonl(tp->rcv_nxt); *(((__be16 *)th) + 6) = htons(((tcp_header_size >> 2) << 12) | tcb->flags); if (unlikely(tcb->flags & TCPHDR_SYN)) { /* RFC1323: The window in SYN & SYN/ACK segments * is never scaled. */ th->window = htons(min(tp->rcv_wnd, 65535U)); } else { th->window = htons(tcp_select_window(sk)); } th->check = 0; th->urg_ptr = 0; /* The urg_mode check is necessary during a below snd_una win probe */ if (unlikely(tcp_urg_mode(tp) && before(tcb->seq, tp->snd_up))) { if (before(tp->snd_up, tcb->seq + 0x10000)) { th->urg_ptr = htons(tp->snd_up - tcb->seq); th->urg = 1; } else if (after(tcb->seq + 0xFFFF, tp->snd_nxt)) { th->urg_ptr = htons(0xFFFF); th->urg = 1; } } tcp_options_write((__be32 *)(th + 1), tp, &opts); if (likely((tcb->flags & TCPHDR_SYN) == 0)) TCP_ECN_send(sk, skb, tcp_header_size); #ifdef CONFIG_TCP_MD5SIG /* Calculate the MD5 hash, as we have all we need now */ if (md5) { sk_nocaps_add(sk, NETIF_F_GSO_MASK); tp->af_specific->calc_md5_hash(opts.hash_location, md5, sk, NULL, skb); } #endif icsk->icsk_af_ops->send_check(sk, skb); if (likely(tcb->flags & TCPHDR_ACK)) tcp_event_ack_sent(sk, tcp_skb_pcount(skb)); if (skb->len != tcp_header_size) tcp_event_data_sent(tp, skb, sk); if (after(tcb->end_seq, tp->snd_nxt) || tcb->seq == tcb->end_seq) TCP_ADD_STATS(sock_net(sk), TCP_MIB_OUTSEGS, tcp_skb_pcount(skb)); err = icsk->icsk_af_ops->queue_xmit(skb, &inet->cork.fl); if (likely(err <= 0)) return err; tcp_enter_cwr(sk, 1); return net_xmit_eval(err); } /* This routine just queues the buffer for sending. * * NOTE: probe0 timer is not checked, do not forget tcp_push_pending_frames, * otherwise socket can stall. */ static void tcp_queue_skb(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); /* Advance write_seq and place onto the write_queue. */ tp->write_seq = TCP_SKB_CB(skb)->end_seq; skb_header_release(skb); tcp_add_write_queue_tail(sk, skb); sk->sk_wmem_queued += skb->truesize; sk_mem_charge(sk, skb->truesize); } /* Initialize TSO segments for a packet. */ static void tcp_set_skb_tso_segs(struct sock *sk, struct sk_buff *skb, unsigned int mss_now) { if (skb->len <= mss_now || !sk_can_gso(sk) || skb->ip_summed == CHECKSUM_NONE) { /* Avoid the costly divide in the normal * non-TSO case. */ skb_shinfo(skb)->gso_segs = 1; skb_shinfo(skb)->gso_size = 0; skb_shinfo(skb)->gso_type = 0; } else { skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss_now); skb_shinfo(skb)->gso_size = mss_now; skb_shinfo(skb)->gso_type = sk->sk_gso_type; } } /* When a modification to fackets out becomes necessary, we need to check * skb is counted to fackets_out or not. */ static void tcp_adjust_fackets_out(struct sock *sk, struct sk_buff *skb, int decr) { struct tcp_sock *tp = tcp_sk(sk); if (!tp->sacked_out || tcp_is_reno(tp)) return; if (after(tcp_highest_sack_seq(tp), TCP_SKB_CB(skb)->seq)) tp->fackets_out -= decr; } /* Pcount in the middle of the write queue got changed, we need to do various * tweaks to fix counters */ static void tcp_adjust_pcount(struct sock *sk, struct sk_buff *skb, int decr) { struct tcp_sock *tp = tcp_sk(sk); tp->packets_out -= decr; if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED) tp->sacked_out -= decr; if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS) tp->retrans_out -= decr; if (TCP_SKB_CB(skb)->sacked & TCPCB_LOST) tp->lost_out -= decr; /* Reno case is special. Sigh... */ if (tcp_is_reno(tp) && decr > 0) tp->sacked_out -= min_t(u32, tp->sacked_out, decr); tcp_adjust_fackets_out(sk, skb, decr); if (tp->lost_skb_hint && before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(tp->lost_skb_hint)->seq) && (tcp_is_fack(tp) || (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED))) tp->lost_cnt_hint -= decr; tcp_verify_left_out(tp); } /* Function to create two new TCP segments. Shrinks the given segment * to the specified size and appends a new segment with the rest of the * packet to the list. This won't be called frequently, I hope. * Remember, these are still headerless SKBs at this point. */ int tcp_fragment(struct sock *sk, struct sk_buff *skb, u32 len, unsigned int mss_now) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *buff; int nsize, old_factor; int nlen; u8 flags; if (WARN_ON(len > skb->len)) return -EINVAL; nsize = skb_headlen(skb) - len; if (nsize < 0) nsize = 0; if (skb_cloned(skb) && skb_is_nonlinear(skb) && pskb_expand_head(skb, 0, 0, GFP_ATOMIC)) return -ENOMEM; /* Get a new skb... force flag on. */ buff = sk_stream_alloc_skb(sk, nsize, GFP_ATOMIC); if (buff == NULL) return -ENOMEM; /* We'll just try again later. */ sk->sk_wmem_queued += buff->truesize; sk_mem_charge(sk, buff->truesize); nlen = skb->len - len - nsize; buff->truesize += nlen; skb->truesize -= nlen; /* Correct the sequence numbers. */ TCP_SKB_CB(buff)->seq = TCP_SKB_CB(skb)->seq + len; TCP_SKB_CB(buff)->end_seq = TCP_SKB_CB(skb)->end_seq; TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(buff)->seq; /* PSH and FIN should only be set in the second packet. */ flags = TCP_SKB_CB(skb)->flags; TCP_SKB_CB(skb)->flags = flags & ~(TCPHDR_FIN | TCPHDR_PSH); TCP_SKB_CB(buff)->flags = flags; TCP_SKB_CB(buff)->sacked = TCP_SKB_CB(skb)->sacked; if (!skb_shinfo(skb)->nr_frags && skb->ip_summed != CHECKSUM_PARTIAL) { /* Copy and checksum data tail into the new buffer. */ buff->csum = csum_partial_copy_nocheck(skb->data + len, skb_put(buff, nsize), nsize, 0); skb_trim(skb, len); skb->csum = csum_block_sub(skb->csum, buff->csum, len); } else { skb->ip_summed = CHECKSUM_PARTIAL; skb_split(skb, buff, len); } buff->ip_summed = skb->ip_summed; /* Looks stupid, but our code really uses when of * skbs, which it never sent before. --ANK */ TCP_SKB_CB(buff)->when = TCP_SKB_CB(skb)->when; buff->tstamp = skb->tstamp; old_factor = tcp_skb_pcount(skb); /* Fix up tso_factor for both original and new SKB. */ tcp_set_skb_tso_segs(sk, skb, mss_now); tcp_set_skb_tso_segs(sk, buff, mss_now); /* If this packet has been sent out already, we must * adjust the various packet counters. */ if (!before(tp->snd_nxt, TCP_SKB_CB(buff)->end_seq)) { int diff = old_factor - tcp_skb_pcount(skb) - tcp_skb_pcount(buff); if (diff) tcp_adjust_pcount(sk, skb, diff); } /* Link BUFF into the send queue. */ skb_header_release(buff); tcp_insert_write_queue_after(skb, buff, sk); return 0; } /* This is similar to __pskb_pull_head() (it will go to core/skbuff.c * eventually). The difference is that pulled data not copied, but * immediately discarded. */ static void __pskb_trim_head(struct sk_buff *skb, int len) { int i, k, eat; eat = len; k = 0; for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { if (skb_shinfo(skb)->frags[i].size <= eat) { put_page(skb_shinfo(skb)->frags[i].page); eat -= skb_shinfo(skb)->frags[i].size; } else { skb_shinfo(skb)->frags[k] = skb_shinfo(skb)->frags[i]; if (eat) { skb_shinfo(skb)->frags[k].page_offset += eat; skb_shinfo(skb)->frags[k].size -= eat; eat = 0; } k++; } } skb_shinfo(skb)->nr_frags = k; skb_reset_tail_pointer(skb); skb->data_len -= len; skb->len = skb->data_len; } /* Remove acked data from a packet in the transmit queue. */ int tcp_trim_head(struct sock *sk, struct sk_buff *skb, u32 len) { if (skb_cloned(skb) && pskb_expand_head(skb, 0, 0, GFP_ATOMIC)) return -ENOMEM; /* If len == headlen, we avoid __skb_pull to preserve alignment. */ if (unlikely(len < skb_headlen(skb))) __skb_pull(skb, len); else __pskb_trim_head(skb, len - skb_headlen(skb)); TCP_SKB_CB(skb)->seq += len; skb->ip_summed = CHECKSUM_PARTIAL; skb->truesize -= len; sk->sk_wmem_queued -= len; sk_mem_uncharge(sk, len); sock_set_flag(sk, SOCK_QUEUE_SHRUNK); /* Any change of skb->len requires recalculation of tso factor. */ if (tcp_skb_pcount(skb) > 1) tcp_set_skb_tso_segs(sk, skb, tcp_skb_mss(skb)); return 0; } /* Calculate MSS. Not accounting for SACKs here. */ int tcp_mtu_to_mss(struct sock *sk, int pmtu) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); int mss_now; /* Calculate base mss without TCP options: It is MMS_S - sizeof(tcphdr) of rfc1122 */ mss_now = pmtu - icsk->icsk_af_ops->net_header_len - sizeof(struct tcphdr); /* Clamp it (mss_clamp does not include tcp options) */ if (mss_now > tp->rx_opt.mss_clamp) mss_now = tp->rx_opt.mss_clamp; /* Now subtract optional transport overhead */ mss_now -= icsk->icsk_ext_hdr_len; /* Then reserve room for full set of TCP options and 8 bytes of data */ if (mss_now < 48) mss_now = 48; /* Now subtract TCP options size, not including SACKs */ mss_now -= tp->tcp_header_len - sizeof(struct tcphdr); return mss_now; } /* Inverse of above */ int tcp_mss_to_mtu(struct sock *sk, int mss) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); int mtu; mtu = mss + tp->tcp_header_len + icsk->icsk_ext_hdr_len + icsk->icsk_af_ops->net_header_len; return mtu; } /* MTU probing init per socket */ void tcp_mtup_init(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); icsk->icsk_mtup.enabled = sysctl_tcp_mtu_probing > 1; icsk->icsk_mtup.search_high = tp->rx_opt.mss_clamp + sizeof(struct tcphdr) + icsk->icsk_af_ops->net_header_len; icsk->icsk_mtup.search_low = tcp_mss_to_mtu(sk, sysctl_tcp_base_mss); icsk->icsk_mtup.probe_size = 0; } EXPORT_SYMBOL(tcp_mtup_init); /* This function synchronize snd mss to current pmtu/exthdr set. tp->rx_opt.user_mss is mss set by user by TCP_MAXSEG. It does NOT counts for TCP options, but includes only bare TCP header. tp->rx_opt.mss_clamp is mss negotiated at connection setup. It is minimum of user_mss and mss received with SYN. It also does not include TCP options. inet_csk(sk)->icsk_pmtu_cookie is last pmtu, seen by this function. tp->mss_cache is current effective sending mss, including all tcp options except for SACKs. It is evaluated, taking into account current pmtu, but never exceeds tp->rx_opt.mss_clamp. NOTE1. rfc1122 clearly states that advertised MSS DOES NOT include either tcp or ip options. NOTE2. inet_csk(sk)->icsk_pmtu_cookie and tp->mss_cache are READ ONLY outside this function. --ANK (980731) */ unsigned int tcp_sync_mss(struct sock *sk, u32 pmtu) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); int mss_now; if (icsk->icsk_mtup.search_high > pmtu) icsk->icsk_mtup.search_high = pmtu; mss_now = tcp_mtu_to_mss(sk, pmtu); mss_now = tcp_bound_to_half_wnd(tp, mss_now); /* And store cached results */ icsk->icsk_pmtu_cookie = pmtu; if (icsk->icsk_mtup.enabled) mss_now = min(mss_now, tcp_mtu_to_mss(sk, icsk->icsk_mtup.search_low)); tp->mss_cache = mss_now; return mss_now; } EXPORT_SYMBOL(tcp_sync_mss); /* Compute the current effective MSS, taking SACKs and IP options, * and even PMTU discovery events into account. */ unsigned int tcp_current_mss(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct dst_entry *dst = __sk_dst_get(sk); u32 mss_now; unsigned header_len; struct tcp_out_options opts; struct tcp_md5sig_key *md5; mss_now = tp->mss_cache; if (dst) { u32 mtu = dst_mtu(dst); if (mtu != inet_csk(sk)->icsk_pmtu_cookie) mss_now = tcp_sync_mss(sk, mtu); } header_len = tcp_established_options(sk, NULL, &opts, &md5) + sizeof(struct tcphdr); /* The mss_cache is sized based on tp->tcp_header_len, which assumes * some common options. If this is an odd packet (because we have SACK * blocks etc) then our calculated header_len will be different, and * we have to adjust mss_now correspondingly */ if (header_len != tp->tcp_header_len) { int delta = (int) header_len - tp->tcp_header_len; mss_now -= delta; } return mss_now; } /* Congestion window validation. (RFC2861) */ static void tcp_cwnd_validate(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); if (tp->packets_out >= tp->snd_cwnd) { /* Network is feed fully. */ tp->snd_cwnd_used = 0; tp->snd_cwnd_stamp = tcp_time_stamp; } else { /* Network starves. */ if (tp->packets_out > tp->snd_cwnd_used) tp->snd_cwnd_used = tp->packets_out; if (sysctl_tcp_slow_start_after_idle && (s32)(tcp_time_stamp - tp->snd_cwnd_stamp) >= inet_csk(sk)->icsk_rto) tcp_cwnd_application_limited(sk); } } /* Returns the portion of skb which can be sent right away without * introducing MSS oddities to segment boundaries. In rare cases where * mss_now != mss_cache, we will request caller to create a small skb * per input skb which could be mostly avoided here (if desired). * * We explicitly want to create a request for splitting write queue tail * to a small skb for Nagle purposes while avoiding unnecessary modulos, * thus all the complexity (cwnd_len is always MSS multiple which we * return whenever allowed by the other factors). Basically we need the * modulo only when the receiver window alone is the limiting factor or * when we would be allowed to send the split-due-to-Nagle skb fully. */ static unsigned int tcp_mss_split_point(struct sock *sk, struct sk_buff *skb, unsigned int mss_now, unsigned int cwnd) { struct tcp_sock *tp = tcp_sk(sk); u32 needed, window, cwnd_len; window = tcp_wnd_end(tp) - TCP_SKB_CB(skb)->seq; cwnd_len = mss_now * cwnd; if (likely(cwnd_len <= window && skb != tcp_write_queue_tail(sk))) return cwnd_len; needed = min(skb->len, window); if (cwnd_len <= needed) return cwnd_len; return needed - needed % mss_now; } /* Can at least one segment of SKB be sent right now, according to the * congestion window rules? If so, return how many segments are allowed. */ static inline unsigned int tcp_cwnd_test(struct tcp_sock *tp, struct sk_buff *skb) { u32 in_flight, cwnd; /* Don't be strict about the congestion window for the final FIN. */ if ((TCP_SKB_CB(skb)->flags & TCPHDR_FIN) && tcp_skb_pcount(skb) == 1) return 1; in_flight = tcp_packets_in_flight(tp); cwnd = tp->snd_cwnd; if (in_flight < cwnd) return (cwnd - in_flight); return 0; } /* Initialize TSO state of a skb. * This must be invoked the first time we consider transmitting * SKB onto the wire. */ static int tcp_init_tso_segs(struct sock *sk, struct sk_buff *skb, unsigned int mss_now) { int tso_segs = tcp_skb_pcount(skb); if (!tso_segs || (tso_segs > 1 && tcp_skb_mss(skb) != mss_now)) { tcp_set_skb_tso_segs(sk, skb, mss_now); tso_segs = tcp_skb_pcount(skb); } return tso_segs; } /* Minshall's variant of the Nagle send check. */ static inline int tcp_minshall_check(const struct tcp_sock *tp) { return after(tp->snd_sml, tp->snd_una) && !after(tp->snd_sml, tp->snd_nxt); } /* Return 0, if packet can be sent now without violation Nagle's rules: * 1. It is full sized. * 2. Or it contains FIN. (already checked by caller) * 3. Or TCP_NODELAY was set. * 4. Or TCP_CORK is not set, and all sent packets are ACKed. * With Minshall's modification: all sent small packets are ACKed. */ static inline int tcp_nagle_check(const struct tcp_sock *tp, const struct sk_buff *skb, unsigned mss_now, int nonagle) { return skb->len < mss_now && ((nonagle & TCP_NAGLE_CORK) || (!nonagle && tp->packets_out && tcp_minshall_check(tp))); } /* Return non-zero if the Nagle test allows this packet to be * sent now. */ static inline int tcp_nagle_test(struct tcp_sock *tp, struct sk_buff *skb, unsigned int cur_mss, int nonagle) { /* Nagle rule does not apply to frames, which sit in the middle of the * write_queue (they have no chances to get new data). * * This is implemented in the callers, where they modify the 'nonagle' * argument based upon the location of SKB in the send queue. */ if (nonagle & TCP_NAGLE_PUSH) return 1; /* Don't use the nagle rule for urgent data (or for the final FIN). * Nagle can be ignored during F-RTO too (see RFC4138). */ if (tcp_urg_mode(tp) || (tp->frto_counter == 2) || (TCP_SKB_CB(skb)->flags & TCPHDR_FIN)) return 1; if (!tcp_nagle_check(tp, skb, cur_mss, nonagle)) return 1; return 0; } /* Does at least the first segment of SKB fit into the send window? */ static inline int tcp_snd_wnd_test(struct tcp_sock *tp, struct sk_buff *skb, unsigned int cur_mss) { u32 end_seq = TCP_SKB_CB(skb)->end_seq; if (skb->len > cur_mss) end_seq = TCP_SKB_CB(skb)->seq + cur_mss; return !after(end_seq, tcp_wnd_end(tp)); } /* This checks if the data bearing packet SKB (usually tcp_send_head(sk)) * should be put on the wire right now. If so, it returns the number of * packets allowed by the congestion window. */ static unsigned int tcp_snd_test(struct sock *sk, struct sk_buff *skb, unsigned int cur_mss, int nonagle) { struct tcp_sock *tp = tcp_sk(sk); unsigned int cwnd_quota; tcp_init_tso_segs(sk, skb, cur_mss); if (!tcp_nagle_test(tp, skb, cur_mss, nonagle)) return 0; cwnd_quota = tcp_cwnd_test(tp, skb); if (cwnd_quota && !tcp_snd_wnd_test(tp, skb, cur_mss)) cwnd_quota = 0; return cwnd_quota; } /* Test if sending is allowed right now. */ int tcp_may_send_now(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb = tcp_send_head(sk); return skb && tcp_snd_test(sk, skb, tcp_current_mss(sk), (tcp_skb_is_last(sk, skb) ? tp->nonagle : TCP_NAGLE_PUSH)); } /* Trim TSO SKB to LEN bytes, put the remaining data into a new packet * which is put after SKB on the list. It is very much like * tcp_fragment() except that it may make several kinds of assumptions * in order to speed up the splitting operation. In particular, we * know that all the data is in scatter-gather pages, and that the * packet has never been sent out before (and thus is not cloned). */ static int tso_fragment(struct sock *sk, struct sk_buff *skb, unsigned int len, unsigned int mss_now, gfp_t gfp) { struct sk_buff *buff; int nlen = skb->len - len; u8 flags; /* All of a TSO frame must be composed of paged data. */ if (skb->len != skb->data_len) return tcp_fragment(sk, skb, len, mss_now); buff = sk_stream_alloc_skb(sk, 0, gfp); if (unlikely(buff == NULL)) return -ENOMEM; sk->sk_wmem_queued += buff->truesize; sk_mem_charge(sk, buff->truesize); buff->truesize += nlen; skb->truesize -= nlen; /* Correct the sequence numbers. */ TCP_SKB_CB(buff)->seq = TCP_SKB_CB(skb)->seq + len; TCP_SKB_CB(buff)->end_seq = TCP_SKB_CB(skb)->end_seq; TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(buff)->seq; /* PSH and FIN should only be set in the second packet. */ flags = TCP_SKB_CB(skb)->flags; TCP_SKB_CB(skb)->flags = flags & ~(TCPHDR_FIN | TCPHDR_PSH); TCP_SKB_CB(buff)->flags = flags; /* This packet was never sent out yet, so no SACK bits. */ TCP_SKB_CB(buff)->sacked = 0; buff->ip_summed = skb->ip_summed = CHECKSUM_PARTIAL; skb_split(skb, buff, len); /* Fix up tso_factor for both original and new SKB. */ tcp_set_skb_tso_segs(sk, skb, mss_now); tcp_set_skb_tso_segs(sk, buff, mss_now); /* Link BUFF into the send queue. */ skb_header_release(buff); tcp_insert_write_queue_after(skb, buff, sk); return 0; } /* Try to defer sending, if possible, in order to minimize the amount * of TSO splitting we do. View it as a kind of TSO Nagle test. * * This algorithm is from John Heffner. */ static int tcp_tso_should_defer(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); const struct inet_connection_sock *icsk = inet_csk(sk); u32 send_win, cong_win, limit, in_flight; int win_divisor; if (TCP_SKB_CB(skb)->flags & TCPHDR_FIN) goto send_now; if (icsk->icsk_ca_state != TCP_CA_Open) goto send_now; /* Defer for less than two clock ticks. */ if (tp->tso_deferred && (((u32)jiffies << 1) >> 1) - (tp->tso_deferred >> 1) > 1) goto send_now; in_flight = tcp_packets_in_flight(tp); BUG_ON(tcp_skb_pcount(skb) <= 1 || (tp->snd_cwnd <= in_flight)); send_win = tcp_wnd_end(tp) - TCP_SKB_CB(skb)->seq; /* From in_flight test above, we know that cwnd > in_flight. */ cong_win = (tp->snd_cwnd - in_flight) * tp->mss_cache; limit = min(send_win, cong_win); /* If a full-sized TSO skb can be sent, do it. */ if (limit >= sk->sk_gso_max_size) goto send_now; /* Middle in queue won't get any more data, full sendable already? */ if ((skb != tcp_write_queue_tail(sk)) && (limit >= skb->len)) goto send_now; win_divisor = ACCESS_ONCE(sysctl_tcp_tso_win_divisor); if (win_divisor) { u32 chunk = min(tp->snd_wnd, tp->snd_cwnd * tp->mss_cache); /* If at least some fraction of a window is available, * just use it. */ chunk /= win_divisor; if (limit >= chunk) goto send_now; } else { /* Different approach, try not to defer past a single * ACK. Receiver should ACK every other full sized * frame, so if we have space for more than 3 frames * then send now. */ if (limit > tcp_max_burst(tp) * tp->mss_cache) goto send_now; } /* Ok, it looks like it is advisable to defer. */ tp->tso_deferred = 1 | (jiffies << 1); return 1; send_now: tp->tso_deferred = 0; return 0; } /* Create a new MTU probe if we are ready. * MTU probe is regularly attempting to increase the path MTU by * deliberately sending larger packets. This discovers routing * changes resulting in larger path MTUs. * * Returns 0 if we should wait to probe (no cwnd available), * 1 if a probe was sent, * -1 otherwise */ static int tcp_mtu_probe(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); struct sk_buff *skb, *nskb, *next; int len; int probe_size; int size_needed; int copy; int mss_now; /* Not currently probing/verifying, * not in recovery, * have enough cwnd, and * not SACKing (the variable headers throw things off) */ if (!icsk->icsk_mtup.enabled || icsk->icsk_mtup.probe_size || inet_csk(sk)->icsk_ca_state != TCP_CA_Open || tp->snd_cwnd < 11 || tp->rx_opt.num_sacks || tp->rx_opt.dsack) return -1; /* Very simple search strategy: just double the MSS. */ mss_now = tcp_current_mss(sk); probe_size = 2 * tp->mss_cache; size_needed = probe_size + (tp->reordering + 1) * tp->mss_cache; if (probe_size > tcp_mtu_to_mss(sk, icsk->icsk_mtup.search_high)) { /* TODO: set timer for probe_converge_event */ return -1; } /* Have enough data in the send queue to probe? */ if (tp->write_seq - tp->snd_nxt < size_needed) return -1; if (tp->snd_wnd < size_needed) return -1; if (after(tp->snd_nxt + size_needed, tcp_wnd_end(tp))) return 0; /* Do we need to wait to drain cwnd? With none in flight, don't stall */ if (tcp_packets_in_flight(tp) + 2 > tp->snd_cwnd) { if (!tcp_packets_in_flight(tp)) return -1; else return 0; } /* We're allowed to probe. Build it now. */ if ((nskb = sk_stream_alloc_skb(sk, probe_size, GFP_ATOMIC)) == NULL) return -1; sk->sk_wmem_queued += nskb->truesize; sk_mem_charge(sk, nskb->truesize); skb = tcp_send_head(sk); TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(skb)->seq; TCP_SKB_CB(nskb)->end_seq = TCP_SKB_CB(skb)->seq + probe_size; TCP_SKB_CB(nskb)->flags = TCPHDR_ACK; TCP_SKB_CB(nskb)->sacked = 0; nskb->csum = 0; nskb->ip_summed = skb->ip_summed; tcp_insert_write_queue_before(nskb, skb, sk); len = 0; tcp_for_write_queue_from_safe(skb, next, sk) { copy = min_t(int, skb->len, probe_size - len); if (nskb->ip_summed) skb_copy_bits(skb, 0, skb_put(nskb, copy), copy); else nskb->csum = skb_copy_and_csum_bits(skb, 0, skb_put(nskb, copy), copy, nskb->csum); if (skb->len <= copy) { /* We've eaten all the data from this skb. * Throw it away. */ TCP_SKB_CB(nskb)->flags |= TCP_SKB_CB(skb)->flags; tcp_unlink_write_queue(skb, sk); sk_wmem_free_skb(sk, skb); } else { TCP_SKB_CB(nskb)->flags |= TCP_SKB_CB(skb)->flags & ~(TCPHDR_FIN|TCPHDR_PSH); if (!skb_shinfo(skb)->nr_frags) { skb_pull(skb, copy); if (skb->ip_summed != CHECKSUM_PARTIAL) skb->csum = csum_partial(skb->data, skb->len, 0); } else { __pskb_trim_head(skb, copy); tcp_set_skb_tso_segs(sk, skb, mss_now); } TCP_SKB_CB(skb)->seq += copy; } len += copy; if (len >= probe_size) break; } tcp_init_tso_segs(sk, nskb, nskb->len); /* We're ready to send. If this fails, the probe will * be resegmented into mss-sized pieces by tcp_write_xmit(). */ TCP_SKB_CB(nskb)->when = tcp_time_stamp; if (!tcp_transmit_skb(sk, nskb, 1, GFP_ATOMIC)) { /* Decrement cwnd here because we are sending * effectively two packets. */ tp->snd_cwnd--; tcp_event_new_data_sent(sk, nskb); icsk->icsk_mtup.probe_size = tcp_mss_to_mtu(sk, nskb->len); tp->mtu_probe.probe_seq_start = TCP_SKB_CB(nskb)->seq; tp->mtu_probe.probe_seq_end = TCP_SKB_CB(nskb)->end_seq; return 1; } return -1; } /* This routine writes packets to the network. It advances the * send_head. This happens as incoming acks open up the remote * window for us. * * LARGESEND note: !tcp_urg_mode is overkill, only frames between * snd_up-64k-mss .. snd_up cannot be large. However, taking into * account rare use of URG, this is not a big flaw. * * Returns 1, if no segments are in flight and we have queued segments, but * cannot send anything now because of SWS or another problem. */ static int tcp_write_xmit(struct sock *sk, unsigned int mss_now, int nonagle, int push_one, gfp_t gfp) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; unsigned int tso_segs, sent_pkts; int cwnd_quota; int result; sent_pkts = 0; if (!push_one) { /* Do MTU probing. */ result = tcp_mtu_probe(sk); if (!result) { return 0; } else if (result > 0) { sent_pkts = 1; } } while ((skb = tcp_send_head(sk))) { unsigned int limit; tso_segs = tcp_init_tso_segs(sk, skb, mss_now); BUG_ON(!tso_segs); cwnd_quota = tcp_cwnd_test(tp, skb); if (!cwnd_quota) break; if (unlikely(!tcp_snd_wnd_test(tp, skb, mss_now))) break; if (tso_segs == 1) { if (unlikely(!tcp_nagle_test(tp, skb, mss_now, (tcp_skb_is_last(sk, skb) ? nonagle : TCP_NAGLE_PUSH)))) break; } else { if (!push_one && tcp_tso_should_defer(sk, skb)) break; } limit = mss_now; if (tso_segs > 1 && !tcp_urg_mode(tp)) limit = tcp_mss_split_point(sk, skb, mss_now, cwnd_quota); if (skb->len > limit && unlikely(tso_fragment(sk, skb, limit, mss_now, gfp))) break; TCP_SKB_CB(skb)->when = tcp_time_stamp; if (unlikely(tcp_transmit_skb(sk, skb, 1, gfp))) break; /* Advance the send_head. This one is sent out. * This call will increment packets_out. */ tcp_event_new_data_sent(sk, skb); tcp_minshall_update(tp, mss_now, skb); sent_pkts++; if (push_one) break; } if (likely(sent_pkts)) { tcp_cwnd_validate(sk); return 0; } return !tp->packets_out && tcp_send_head(sk); } /* Push out any pending frames which were held back due to * TCP_CORK or attempt at coalescing tiny packets. * The socket must be locked by the caller. */ void __tcp_push_pending_frames(struct sock *sk, unsigned int cur_mss, int nonagle) { /* If we are closed, the bytes will have to remain here. * In time closedown will finish, we empty the write queue and * all will be happy. */ if (unlikely(sk->sk_state == TCP_CLOSE)) return; if (tcp_write_xmit(sk, cur_mss, nonagle, 0, GFP_ATOMIC)) tcp_check_probe_timer(sk); } /* Send _single_ skb sitting at the send head. This function requires * true push pending frames to setup probe timer etc. */ void tcp_push_one(struct sock *sk, unsigned int mss_now) { struct sk_buff *skb = tcp_send_head(sk); BUG_ON(!skb || skb->len < mss_now); tcp_write_xmit(sk, mss_now, TCP_NAGLE_PUSH, 1, sk->sk_allocation); } /* This function returns the amount that we can raise the * usable window based on the following constraints * * 1. The window can never be shrunk once it is offered (RFC 793) * 2. We limit memory per socket * * RFC 1122: * "the suggested [SWS] avoidance algorithm for the receiver is to keep * RECV.NEXT + RCV.WIN fixed until: * RCV.BUFF - RCV.USER - RCV.WINDOW >= min(1/2 RCV.BUFF, MSS)" * * i.e. don't raise the right edge of the window until you can raise * it at least MSS bytes. * * Unfortunately, the recommended algorithm breaks header prediction, * since header prediction assumes th->window stays fixed. * * Strictly speaking, keeping th->window fixed violates the receiver * side SWS prevention criteria. The problem is that under this rule * a stream of single byte packets will cause the right side of the * window to always advance by a single byte. * * Of course, if the sender implements sender side SWS prevention * then this will not be a problem. * * BSD seems to make the following compromise: * * If the free space is less than the 1/4 of the maximum * space available and the free space is less than 1/2 mss, * then set the window to 0. * [ Actually, bsd uses MSS and 1/4 of maximal _window_ ] * Otherwise, just prevent the window from shrinking * and from being larger than the largest representable value. * * This prevents incremental opening of the window in the regime * where TCP is limited by the speed of the reader side taking * data out of the TCP receive queue. It does nothing about * those cases where the window is constrained on the sender side * because the pipeline is full. * * BSD also seems to "accidentally" limit itself to windows that are a * multiple of MSS, at least until the free space gets quite small. * This would appear to be a side effect of the mbuf implementation. * Combining these two algorithms results in the observed behavior * of having a fixed window size at almost all times. * * Below we obtain similar behavior by forcing the offered window to * a multiple of the mss when it is feasible to do so. * * Note, we don't "adjust" for TIMESTAMP or SACK option bytes. * Regular options like TIMESTAMP are taken into account. */ u32 __tcp_select_window(struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); /* MSS for the peer's data. Previous versions used mss_clamp * here. I don't know if the value based on our guesses * of peer's MSS is better for the performance. It's more correct * but may be worse for the performance because of rcv_mss * fluctuations. --SAW 1998/11/1 */ int mss = icsk->icsk_ack.rcv_mss; int free_space = tcp_space(sk); int full_space = min_t(int, tp->window_clamp, tcp_full_space(sk)); int window; if (mss > full_space) mss = full_space; if (free_space < (full_space >> 1)) { icsk->icsk_ack.quick = 0; if (tcp_memory_pressure) tp->rcv_ssthresh = min(tp->rcv_ssthresh, 4U * tp->advmss); if (free_space < mss) return 0; } if (free_space > tp->rcv_ssthresh) free_space = tp->rcv_ssthresh; /* Don't do rounding if we are using window scaling, since the * scaled window will not line up with the MSS boundary anyway. */ window = tp->rcv_wnd; if (tp->rx_opt.rcv_wscale) { window = free_space; /* Advertise enough space so that it won't get scaled away. * Import case: prevent zero window announcement if * 1<<rcv_wscale > mss. */ if (((window >> tp->rx_opt.rcv_wscale) << tp->rx_opt.rcv_wscale) != window) window = (((window >> tp->rx_opt.rcv_wscale) + 1) << tp->rx_opt.rcv_wscale); } else { /* Get the largest window that is a nice multiple of mss. * Window clamp already applied above. * If our current window offering is within 1 mss of the * free space we just keep it. This prevents the divide * and multiply from happening most of the time. * We also don't do any window rounding when the free space * is too small. */ if (window <= free_space - mss || window > free_space) window = (free_space / mss) * mss; else if (mss == full_space && free_space > window + (full_space >> 1)) window = free_space; } return window; } /* Collapses two adjacent SKB's during retransmission. */ static void tcp_collapse_retrans(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *next_skb = tcp_write_queue_next(sk, skb); int skb_size, next_skb_size; skb_size = skb->len; next_skb_size = next_skb->len; BUG_ON(tcp_skb_pcount(skb) != 1 || tcp_skb_pcount(next_skb) != 1); tcp_highest_sack_combine(sk, next_skb, skb); tcp_unlink_write_queue(next_skb, sk); skb_copy_from_linear_data(next_skb, skb_put(skb, next_skb_size), next_skb_size); if (next_skb->ip_summed == CHECKSUM_PARTIAL) skb->ip_summed = CHECKSUM_PARTIAL; if (skb->ip_summed != CHECKSUM_PARTIAL) skb->csum = csum_block_add(skb->csum, next_skb->csum, skb_size); /* Update sequence range on original skb. */ TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(next_skb)->end_seq; /* Merge over control information. This moves PSH/FIN etc. over */ TCP_SKB_CB(skb)->flags |= TCP_SKB_CB(next_skb)->flags; /* All done, get rid of second SKB and account for it so * packet counting does not break. */ TCP_SKB_CB(skb)->sacked |= TCP_SKB_CB(next_skb)->sacked & TCPCB_EVER_RETRANS; /* changed transmit queue under us so clear hints */ tcp_clear_retrans_hints_partial(tp); if (next_skb == tp->retransmit_skb_hint) tp->retransmit_skb_hint = skb; tcp_adjust_pcount(sk, next_skb, tcp_skb_pcount(next_skb)); sk_wmem_free_skb(sk, next_skb); } /* Check if coalescing SKBs is legal. */ static int tcp_can_collapse(struct sock *sk, struct sk_buff *skb) { if (tcp_skb_pcount(skb) > 1) return 0; /* TODO: SACK collapsing could be used to remove this condition */ if (skb_shinfo(skb)->nr_frags != 0) return 0; if (skb_cloned(skb)) return 0; if (skb == tcp_send_head(sk)) return 0; /* Some heurestics for collapsing over SACK'd could be invented */ if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED) return 0; return 1; } /* Collapse packets in the retransmit queue to make to create * less packets on the wire. This is only done on retransmission. */ static void tcp_retrans_try_collapse(struct sock *sk, struct sk_buff *to, int space) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb = to, *tmp; int first = 1; if (!sysctl_tcp_retrans_collapse) return; if (TCP_SKB_CB(skb)->flags & TCPHDR_SYN) return; tcp_for_write_queue_from_safe(skb, tmp, sk) { if (!tcp_can_collapse(sk, skb)) break; space -= skb->len; if (first) { first = 0; continue; } if (space < 0) break; /* Punt if not enough space exists in the first SKB for * the data in the second */ if (skb->len > skb_tailroom(to)) break; if (after(TCP_SKB_CB(skb)->end_seq, tcp_wnd_end(tp))) break; tcp_collapse_retrans(sk, to); } } /* This retransmits one SKB. Policy decisions and retransmit queue * state updates are done by the caller. Returns non-zero if an * error occurred which prevented the send. */ int tcp_retransmit_skb(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); unsigned int cur_mss; int err; /* Inconslusive MTU probe */ if (icsk->icsk_mtup.probe_size) { icsk->icsk_mtup.probe_size = 0; } /* Do not sent more than we queued. 1/4 is reserved for possible * copying overhead: fragmentation, tunneling, mangling etc. */ if (atomic_read(&sk->sk_wmem_alloc) > min(sk->sk_wmem_queued + (sk->sk_wmem_queued >> 2), sk->sk_sndbuf)) return -EAGAIN; if (before(TCP_SKB_CB(skb)->seq, tp->snd_una)) { if (before(TCP_SKB_CB(skb)->end_seq, tp->snd_una)) BUG(); if (tcp_trim_head(sk, skb, tp->snd_una - TCP_SKB_CB(skb)->seq)) return -ENOMEM; } if (inet_csk(sk)->icsk_af_ops->rebuild_header(sk)) return -EHOSTUNREACH; /* Routing failure or similar. */ cur_mss = tcp_current_mss(sk); /* If receiver has shrunk his window, and skb is out of * new window, do not retransmit it. The exception is the * case, when window is shrunk to zero. In this case * our retransmit serves as a zero window probe. */ if (!before(TCP_SKB_CB(skb)->seq, tcp_wnd_end(tp)) && TCP_SKB_CB(skb)->seq != tp->snd_una) return -EAGAIN; if (skb->len > cur_mss) { if (tcp_fragment(sk, skb, cur_mss, cur_mss)) return -ENOMEM; /* We'll try again later. */ } else { int oldpcount = tcp_skb_pcount(skb); if (unlikely(oldpcount > 1)) { tcp_init_tso_segs(sk, skb, cur_mss); tcp_adjust_pcount(sk, skb, oldpcount - tcp_skb_pcount(skb)); } } tcp_retrans_try_collapse(sk, skb, cur_mss); /* Some Solaris stacks overoptimize and ignore the FIN on a * retransmit when old data is attached. So strip it off * since it is cheap to do so and saves bytes on the network. */ if (skb->len > 0 && (TCP_SKB_CB(skb)->flags & TCPHDR_FIN) && tp->snd_una == (TCP_SKB_CB(skb)->end_seq - 1)) { if (!pskb_trim(skb, 0)) { /* Reuse, even though it does some unnecessary work */ tcp_init_nondata_skb(skb, TCP_SKB_CB(skb)->end_seq - 1, TCP_SKB_CB(skb)->flags); skb->ip_summed = CHECKSUM_NONE; } } /* Make a copy, if the first transmission SKB clone we made * is still in somebody's hands, else make a clone. */ TCP_SKB_CB(skb)->when = tcp_time_stamp; err = tcp_transmit_skb(sk, skb, 1, GFP_ATOMIC); if (err == 0) { /* Update global TCP statistics. */ TCP_INC_STATS(sock_net(sk), TCP_MIB_RETRANSSEGS); tp->total_retrans++; #if FASTRETRANS_DEBUG > 0 if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS) { if (net_ratelimit()) printk(KERN_DEBUG "retrans_out leaked.\n"); } #endif if (!tp->retrans_out) tp->lost_retrans_low = tp->snd_nxt; TCP_SKB_CB(skb)->sacked |= TCPCB_RETRANS; tp->retrans_out += tcp_skb_pcount(skb); /* Save stamp of the first retransmit. */ if (!tp->retrans_stamp) tp->retrans_stamp = TCP_SKB_CB(skb)->when; tp->undo_retrans += tcp_skb_pcount(skb); /* snd_nxt is stored to detect loss of retransmitted segment, * see tcp_input.c tcp_sacktag_write_queue(). */ TCP_SKB_CB(skb)->ack_seq = tp->snd_nxt; } return err; } /* Check if we forward retransmits are possible in the current * window/congestion state. */ static int tcp_can_forward_retransmit(struct sock *sk) { const struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); /* Forward retransmissions are possible only during Recovery. */ if (icsk->icsk_ca_state != TCP_CA_Recovery) return 0; /* No forward retransmissions in Reno are possible. */ if (tcp_is_reno(tp)) return 0; /* Yeah, we have to make difficult choice between forward transmission * and retransmission... Both ways have their merits... * * For now we do not retransmit anything, while we have some new * segments to send. In the other cases, follow rule 3 for * NextSeg() specified in RFC3517. */ if (tcp_may_send_now(sk)) return 0; return 1; } /* This gets called after a retransmit timeout, and the initially * retransmitted data is acknowledged. It tries to continue * resending the rest of the retransmit queue, until either * we've sent it all or the congestion window limit is reached. * If doing SACK, the first ACK which comes back for a timeout * based retransmit packet might feed us FACK information again. * If so, we use it to avoid unnecessarily retransmissions. */ void tcp_xmit_retransmit_queue(struct sock *sk) { const struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; struct sk_buff *hole = NULL; u32 last_lost; int mib_idx; int fwd_rexmitting = 0; if (!tp->packets_out) return; if (!tp->lost_out) tp->retransmit_high = tp->snd_una; if (tp->retransmit_skb_hint) { skb = tp->retransmit_skb_hint; last_lost = TCP_SKB_CB(skb)->end_seq; if (after(last_lost, tp->retransmit_high)) last_lost = tp->retransmit_high; } else { skb = tcp_write_queue_head(sk); last_lost = tp->snd_una; } tcp_for_write_queue_from(skb, sk) { __u8 sacked = TCP_SKB_CB(skb)->sacked; if (skb == tcp_send_head(sk)) break; /* we could do better than to assign each time */ if (hole == NULL) tp->retransmit_skb_hint = skb; /* Assume this retransmit will generate * only one packet for congestion window * calculation purposes. This works because * tcp_retransmit_skb() will chop up the * packet to be MSS sized and all the * packet counting works out. */ if (tcp_packets_in_flight(tp) >= tp->snd_cwnd) return; if (fwd_rexmitting) { begin_fwd: if (!before(TCP_SKB_CB(skb)->seq, tcp_highest_sack_seq(tp))) break; mib_idx = LINUX_MIB_TCPFORWARDRETRANS; } else if (!before(TCP_SKB_CB(skb)->seq, tp->retransmit_high)) { tp->retransmit_high = last_lost; if (!tcp_can_forward_retransmit(sk)) break; /* Backtrack if necessary to non-L'ed skb */ if (hole != NULL) { skb = hole; hole = NULL; } fwd_rexmitting = 1; goto begin_fwd; } else if (!(sacked & TCPCB_LOST)) { if (hole == NULL && !(sacked & (TCPCB_SACKED_RETRANS|TCPCB_SACKED_ACKED))) hole = skb; continue; } else { last_lost = TCP_SKB_CB(skb)->end_seq; if (icsk->icsk_ca_state != TCP_CA_Loss) mib_idx = LINUX_MIB_TCPFASTRETRANS; else mib_idx = LINUX_MIB_TCPSLOWSTARTRETRANS; } if (sacked & (TCPCB_SACKED_ACKED|TCPCB_SACKED_RETRANS)) continue; if (tcp_retransmit_skb(sk, skb)) return; NET_INC_STATS_BH(sock_net(sk), mib_idx); if (skb == tcp_write_queue_head(sk)) inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS, inet_csk(sk)->icsk_rto, TCP_RTO_MAX); } } /* Send a fin. The caller locks the socket for us. This cannot be * allowed to fail queueing a FIN frame under any circumstances. */ void tcp_send_fin(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb = tcp_write_queue_tail(sk); int mss_now; /* Optimization, tack on the FIN if we have a queue of * unsent frames. But be careful about outgoing SACKS * and IP options. */ mss_now = tcp_current_mss(sk); if (tcp_send_head(sk) != NULL) { TCP_SKB_CB(skb)->flags |= TCPHDR_FIN; TCP_SKB_CB(skb)->end_seq++; tp->write_seq++; } else { /* Socket is locked, keep trying until memory is available. */ for (;;) { skb = alloc_skb_fclone(MAX_TCP_HEADER, sk->sk_allocation); if (skb) break; yield(); } /* Reserve space for headers and prepare control bits. */ skb_reserve(skb, MAX_TCP_HEADER); /* FIN eats a sequence byte, write_seq advanced by tcp_queue_skb(). */ tcp_init_nondata_skb(skb, tp->write_seq, TCPHDR_ACK | TCPHDR_FIN); tcp_queue_skb(sk, skb); } __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_OFF); } /* We get here when a process closes a file descriptor (either due to * an explicit close() or as a byproduct of exit()'ing) and there * was unread data in the receive queue. This behavior is recommended * by RFC 2525, section 2.17. -DaveM */ void tcp_send_active_reset(struct sock *sk, gfp_t priority) { struct sk_buff *skb; /* NOTE: No TCP options attached and we never retransmit this. */ skb = alloc_skb(MAX_TCP_HEADER, priority); if (!skb) { NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTFAILED); return; } /* Reserve space for headers and prepare control bits. */ skb_reserve(skb, MAX_TCP_HEADER); tcp_init_nondata_skb(skb, tcp_acceptable_seq(sk), TCPHDR_ACK | TCPHDR_RST); /* Send it off. */ TCP_SKB_CB(skb)->when = tcp_time_stamp; if (tcp_transmit_skb(sk, skb, 0, priority)) NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTFAILED); TCP_INC_STATS(sock_net(sk), TCP_MIB_OUTRSTS); } /* Send a crossed SYN-ACK during socket establishment. * WARNING: This routine must only be called when we have already sent * a SYN packet that crossed the incoming SYN that caused this routine * to get called. If this assumption fails then the initial rcv_wnd * and rcv_wscale values will not be correct. */ int tcp_send_synack(struct sock *sk) { struct sk_buff *skb; skb = tcp_write_queue_head(sk); if (skb == NULL || !(TCP_SKB_CB(skb)->flags & TCPHDR_SYN)) { printk(KERN_DEBUG "tcp_send_synack: wrong queue state\n"); return -EFAULT; } if (!(TCP_SKB_CB(skb)->flags & TCPHDR_ACK)) { if (skb_cloned(skb)) { struct sk_buff *nskb = skb_copy(skb, GFP_ATOMIC); if (nskb == NULL) return -ENOMEM; tcp_unlink_write_queue(skb, sk); skb_header_release(nskb); __tcp_add_write_queue_head(sk, nskb); sk_wmem_free_skb(sk, skb); sk->sk_wmem_queued += nskb->truesize; sk_mem_charge(sk, nskb->truesize); skb = nskb; } TCP_SKB_CB(skb)->flags |= TCPHDR_ACK; TCP_ECN_send_synack(tcp_sk(sk), skb); } TCP_SKB_CB(skb)->when = tcp_time_stamp; return tcp_transmit_skb(sk, skb, 1, GFP_ATOMIC); } /* Prepare a SYN-ACK. */ struct sk_buff *tcp_make_synack(struct sock *sk, struct dst_entry *dst, struct request_sock *req, struct request_values *rvp) { struct tcp_out_options opts; struct tcp_extend_values *xvp = tcp_xv(rvp); struct inet_request_sock *ireq = inet_rsk(req); struct tcp_sock *tp = tcp_sk(sk); const struct tcp_cookie_values *cvp = tp->cookie_values; struct tcphdr *th; struct sk_buff *skb; struct tcp_md5sig_key *md5; int tcp_header_size; int mss; int s_data_desired = 0; if (cvp != NULL && cvp->s_data_constant && cvp->s_data_desired) s_data_desired = cvp->s_data_desired; skb = sock_wmalloc(sk, MAX_TCP_HEADER + 15 + s_data_desired, 1, GFP_ATOMIC); if (skb == NULL) return NULL; /* Reserve space for headers. */ skb_reserve(skb, MAX_TCP_HEADER); skb_dst_set(skb, dst_clone(dst)); mss = dst_metric_advmss(dst); if (tp->rx_opt.user_mss && tp->rx_opt.user_mss < mss) mss = tp->rx_opt.user_mss; if (req->rcv_wnd == 0) { /* ignored for retransmitted syns */ __u8 rcv_wscale; /* Set this up on the first call only */ req->window_clamp = tp->window_clamp ? : dst_metric(dst, RTAX_WINDOW); /* limit the window selection if the user enforce a smaller rx buffer */ if (sk->sk_userlocks & SOCK_RCVBUF_LOCK && (req->window_clamp > tcp_full_space(sk) || req->window_clamp == 0)) req->window_clamp = tcp_full_space(sk); /* tcp_full_space because it is guaranteed to be the first packet */ tcp_select_initial_window(tcp_full_space(sk), mss - (ireq->tstamp_ok ? TCPOLEN_TSTAMP_ALIGNED : 0), &req->rcv_wnd, &req->window_clamp, ireq->wscale_ok, &rcv_wscale, dst_metric(dst, RTAX_INITRWND)); ireq->rcv_wscale = rcv_wscale; } memset(&opts, 0, sizeof(opts)); #ifdef CONFIG_SYN_COOKIES if (unlikely(req->cookie_ts)) TCP_SKB_CB(skb)->when = cookie_init_timestamp(req); else #endif TCP_SKB_CB(skb)->when = tcp_time_stamp; tcp_header_size = tcp_synack_options(sk, req, mss, skb, &opts, &md5, xvp) + sizeof(*th); skb_push(skb, tcp_header_size); skb_reset_transport_header(skb); th = tcp_hdr(skb); memset(th, 0, sizeof(struct tcphdr)); th->syn = 1; th->ack = 1; TCP_ECN_make_synack(req, th); th->source = ireq->loc_port; th->dest = ireq->rmt_port; /* Setting of flags are superfluous here for callers (and ECE is * not even correctly set) */ tcp_init_nondata_skb(skb, tcp_rsk(req)->snt_isn, TCPHDR_SYN | TCPHDR_ACK); if (OPTION_COOKIE_EXTENSION & opts.options) { if (s_data_desired) { u8 *buf = skb_put(skb, s_data_desired); /* copy data directly from the listening socket. */ memcpy(buf, cvp->s_data_payload, s_data_desired); TCP_SKB_CB(skb)->end_seq += s_data_desired; } if (opts.hash_size > 0) { __u32 workspace[SHA_WORKSPACE_WORDS]; u32 *mess = &xvp->cookie_bakery[COOKIE_DIGEST_WORDS]; u32 *tail = &mess[COOKIE_MESSAGE_WORDS-1]; /* Secret recipe depends on the Timestamp, (future) * Sequence and Acknowledgment Numbers, Initiator * Cookie, and others handled by IP variant caller. */ *tail-- ^= opts.tsval; *tail-- ^= tcp_rsk(req)->rcv_isn + 1; *tail-- ^= TCP_SKB_CB(skb)->seq + 1; /* recommended */ *tail-- ^= (((__force u32)th->dest << 16) | (__force u32)th->source); *tail-- ^= (u32)(unsigned long)cvp; /* per sockopt */ sha_transform((__u32 *)&xvp->cookie_bakery[0], (char *)mess, &workspace[0]); opts.hash_location = (__u8 *)&xvp->cookie_bakery[0]; } } th->seq = htonl(TCP_SKB_CB(skb)->seq); th->ack_seq = htonl(tcp_rsk(req)->rcv_isn + 1); /* RFC1323: The window in SYN & SYN/ACK segments is never scaled. */ th->window = htons(min(req->rcv_wnd, 65535U)); tcp_options_write((__be32 *)(th + 1), tp, &opts); th->doff = (tcp_header_size >> 2); TCP_ADD_STATS(sock_net(sk), TCP_MIB_OUTSEGS, tcp_skb_pcount(skb)); #ifdef CONFIG_TCP_MD5SIG /* Okay, we have all we need - do the md5 hash if needed */ if (md5) { tcp_rsk(req)->af_specific->calc_md5_hash(opts.hash_location, md5, NULL, req, skb); } #endif return skb; } EXPORT_SYMBOL(tcp_make_synack); /* Do all connect socket setups that can be done AF independent. */ static void tcp_connect_init(struct sock *sk) { struct dst_entry *dst = __sk_dst_get(sk); struct tcp_sock *tp = tcp_sk(sk); __u8 rcv_wscale; /* We'll fix this up when we get a response from the other end. * See tcp_input.c:tcp_rcv_state_process case TCP_SYN_SENT. */ tp->tcp_header_len = sizeof(struct tcphdr) + (sysctl_tcp_timestamps ? TCPOLEN_TSTAMP_ALIGNED : 0); #ifdef CONFIG_TCP_MD5SIG if (tp->af_specific->md5_lookup(sk, sk) != NULL) tp->tcp_header_len += TCPOLEN_MD5SIG_ALIGNED; #endif /* If user gave his TCP_MAXSEG, record it to clamp */ if (tp->rx_opt.user_mss) tp->rx_opt.mss_clamp = tp->rx_opt.user_mss; tp->max_window = 0; tcp_mtup_init(sk); tcp_sync_mss(sk, dst_mtu(dst)); if (!tp->window_clamp) tp->window_clamp = dst_metric(dst, RTAX_WINDOW); tp->advmss = dst_metric_advmss(dst); if (tp->rx_opt.user_mss && tp->rx_opt.user_mss < tp->advmss) tp->advmss = tp->rx_opt.user_mss; tcp_initialize_rcv_mss(sk); /* limit the window selection if the user enforce a smaller rx buffer */ if (sk->sk_userlocks & SOCK_RCVBUF_LOCK && (tp->window_clamp > tcp_full_space(sk) || tp->window_clamp == 0)) tp->window_clamp = tcp_full_space(sk); tcp_select_initial_window(tcp_full_space(sk), tp->advmss - (tp->rx_opt.ts_recent_stamp ? tp->tcp_header_len - sizeof(struct tcphdr) : 0), &tp->rcv_wnd, &tp->window_clamp, sysctl_tcp_window_scaling, &rcv_wscale, dst_metric(dst, RTAX_INITRWND)); tp->rx_opt.rcv_wscale = rcv_wscale; tp->rcv_ssthresh = tp->rcv_wnd; sk->sk_err = 0; sock_reset_flag(sk, SOCK_DONE); tp->snd_wnd = 0; tcp_init_wl(tp, 0); tp->snd_una = tp->write_seq; tp->snd_sml = tp->write_seq; tp->snd_up = tp->write_seq; tp->rcv_nxt = 0; tp->rcv_wup = 0; tp->copied_seq = 0; inet_csk(sk)->icsk_rto = TCP_TIMEOUT_INIT; inet_csk(sk)->icsk_retransmits = 0; tcp_clear_retrans(tp); } /* Build a SYN and send it off. */ int tcp_connect(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *buff; int err; tcp_connect_init(sk); buff = alloc_skb_fclone(MAX_TCP_HEADER + 15, sk->sk_allocation); if (unlikely(buff == NULL)) return -ENOBUFS; /* Reserve space for headers. */ skb_reserve(buff, MAX_TCP_HEADER); tp->snd_nxt = tp->write_seq; tcp_init_nondata_skb(buff, tp->write_seq++, TCPHDR_SYN); TCP_ECN_send_syn(sk, buff); /* Send it off. */ TCP_SKB_CB(buff)->when = tcp_time_stamp; tp->retrans_stamp = TCP_SKB_CB(buff)->when; skb_header_release(buff); __tcp_add_write_queue_tail(sk, buff); sk->sk_wmem_queued += buff->truesize; sk_mem_charge(sk, buff->truesize); tp->packets_out += tcp_skb_pcount(buff); err = tcp_transmit_skb(sk, buff, 1, sk->sk_allocation); if (err == -ECONNREFUSED) return err; /* We change tp->snd_nxt after the tcp_transmit_skb() call * in order to make this packet get counted in tcpOutSegs. */ tp->snd_nxt = tp->write_seq; tp->pushed_seq = tp->write_seq; TCP_INC_STATS(sock_net(sk), TCP_MIB_ACTIVEOPENS); /* Timer for repeating the SYN until an answer. */ inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS, inet_csk(sk)->icsk_rto, TCP_RTO_MAX); return 0; } EXPORT_SYMBOL(tcp_connect); /* Send out a delayed ack, the caller does the policy checking * to see if we should even be here. See tcp_input.c:tcp_ack_snd_check() * for details. */ void tcp_send_delayed_ack(struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); int ato = icsk->icsk_ack.ato; unsigned long timeout; if (ato > TCP_DELACK_MIN) { const struct tcp_sock *tp = tcp_sk(sk); int max_ato = HZ / 2; if (icsk->icsk_ack.pingpong || (icsk->icsk_ack.pending & ICSK_ACK_PUSHED)) max_ato = TCP_DELACK_MAX; /* Slow path, intersegment interval is "high". */ /* If some rtt estimate is known, use it to bound delayed ack. * Do not use inet_csk(sk)->icsk_rto here, use results of rtt measurements * directly. */ if (tp->srtt) { int rtt = max(tp->srtt >> 3, TCP_DELACK_MIN); if (rtt < max_ato) max_ato = rtt; } ato = min(ato, max_ato); } /* Stay within the limit we were given */ timeout = jiffies + ato; /* Use new timeout only if there wasn't a older one earlier. */ if (icsk->icsk_ack.pending & ICSK_ACK_TIMER) { /* If delack timer was blocked or is about to expire, * send ACK now. */ if (icsk->icsk_ack.blocked || time_before_eq(icsk->icsk_ack.timeout, jiffies + (ato >> 2))) { tcp_send_ack(sk); return; } if (!time_before(timeout, icsk->icsk_ack.timeout)) timeout = icsk->icsk_ack.timeout; } icsk->icsk_ack.pending |= ICSK_ACK_SCHED | ICSK_ACK_TIMER; icsk->icsk_ack.timeout = timeout; sk_reset_timer(sk, &icsk->icsk_delack_timer, timeout); } /* This routine sends an ack and also updates the window. */ void tcp_send_ack(struct sock *sk) { struct sk_buff *buff; /* If we have been reset, we may not send again. */ if (sk->sk_state == TCP_CLOSE) return; /* We are not putting this on the write queue, so * tcp_transmit_skb() will set the ownership to this * sock. */ buff = alloc_skb(MAX_TCP_HEADER, GFP_ATOMIC); if (buff == NULL) { inet_csk_schedule_ack(sk); inet_csk(sk)->icsk_ack.ato = TCP_ATO_MIN; inet_csk_reset_xmit_timer(sk, ICSK_TIME_DACK, TCP_DELACK_MAX, TCP_RTO_MAX); return; } /* Reserve space for headers and prepare control bits. */ skb_reserve(buff, MAX_TCP_HEADER); tcp_init_nondata_skb(buff, tcp_acceptable_seq(sk), TCPHDR_ACK); /* Send it off, this clears delayed acks for us. */ TCP_SKB_CB(buff)->when = tcp_time_stamp; tcp_transmit_skb(sk, buff, 0, GFP_ATOMIC); } /* This routine sends a packet with an out of date sequence * number. It assumes the other end will try to ack it. * * Question: what should we make while urgent mode? * 4.4BSD forces sending single byte of data. We cannot send * out of window data, because we have SND.NXT==SND.MAX... * * Current solution: to send TWO zero-length segments in urgent mode: * one is with SEG.SEQ=SND.UNA to deliver urgent pointer, another is * out-of-date with SND.UNA-1 to probe window. */ static int tcp_xmit_probe_skb(struct sock *sk, int urgent) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; /* We don't queue it, tcp_transmit_skb() sets ownership. */ skb = alloc_skb(MAX_TCP_HEADER, GFP_ATOMIC); if (skb == NULL) return -1; /* Reserve space for headers and set control bits. */ skb_reserve(skb, MAX_TCP_HEADER); /* Use a previous sequence. This should cause the other * end to send an ack. Don't queue or clone SKB, just * send it. */ tcp_init_nondata_skb(skb, tp->snd_una - !urgent, TCPHDR_ACK); TCP_SKB_CB(skb)->when = tcp_time_stamp; return tcp_transmit_skb(sk, skb, 0, GFP_ATOMIC); } /* Initiate keepalive or window probe from timer. */ int tcp_write_wakeup(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; if (sk->sk_state == TCP_CLOSE) return -1; if ((skb = tcp_send_head(sk)) != NULL && before(TCP_SKB_CB(skb)->seq, tcp_wnd_end(tp))) { int err; unsigned int mss = tcp_current_mss(sk); unsigned int seg_size = tcp_wnd_end(tp) - TCP_SKB_CB(skb)->seq; if (before(tp->pushed_seq, TCP_SKB_CB(skb)->end_seq)) tp->pushed_seq = TCP_SKB_CB(skb)->end_seq; /* We are probing the opening of a window * but the window size is != 0 * must have been a result SWS avoidance ( sender ) */ if (seg_size < TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq || skb->len > mss) { seg_size = min(seg_size, mss); TCP_SKB_CB(skb)->flags |= TCPHDR_PSH; if (tcp_fragment(sk, skb, seg_size, mss)) return -1; } else if (!tcp_skb_pcount(skb)) tcp_set_skb_tso_segs(sk, skb, mss); TCP_SKB_CB(skb)->flags |= TCPHDR_PSH; TCP_SKB_CB(skb)->when = tcp_time_stamp; err = tcp_transmit_skb(sk, skb, 1, GFP_ATOMIC); if (!err) tcp_event_new_data_sent(sk, skb); return err; } else { if (between(tp->snd_up, tp->snd_una + 1, tp->snd_una + 0xFFFF)) tcp_xmit_probe_skb(sk, 1); return tcp_xmit_probe_skb(sk, 0); } } /* A window probe timeout has occurred. If window is not closed send * a partial packet else a zero probe. */ void tcp_send_probe0(struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); int err; err = tcp_write_wakeup(sk); if (tp->packets_out || !tcp_send_head(sk)) { /* Cancel probe timer, if it is not required. */ icsk->icsk_probes_out = 0; icsk->icsk_backoff = 0; return; } if (err <= 0) { if (icsk->icsk_backoff < sysctl_tcp_retries2) icsk->icsk_backoff++; icsk->icsk_probes_out++; inet_csk_reset_xmit_timer(sk, ICSK_TIME_PROBE0, min(icsk->icsk_rto << icsk->icsk_backoff, TCP_RTO_MAX), TCP_RTO_MAX); } else { /* If packet was not sent due to local congestion, * do not backoff and do not remember icsk_probes_out. * Let local senders to fight for local resources. * * Use accumulated backoff yet. */ if (!icsk->icsk_probes_out) icsk->icsk_probes_out = 1; inet_csk_reset_xmit_timer(sk, ICSK_TIME_PROBE0, min(icsk->icsk_rto << icsk->icsk_backoff, TCP_RESOURCE_PROBE_INTERVAL), TCP_RTO_MAX); } }
chaveiro/LG_P920_V30A_Kernel
net/ipv4/tcp_output.c
C
gpl-2.0
84,185
/* Cabal - Legacy Game Implementations * * Cabal 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. * */ // Based on the ScummVM (GPLv2+) file of the same name #ifdef WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #undef ARRAYSIZE // winnt.h defines ARRAYSIZE, but we want our own one... #include <shellapi.h> #include "audio/audiodev/pcspk.h" #include "common/scummsys.h" #include "common/config-manager.h" #include "common/error.h" #include "common/textconsole.h" #include "backends/audiocd/win32/win32-audiocd.h" #include "backends/audiodev/win32/win32_pcspk.h" #include "backends/platform/sdl/win32/win32.h" #include "backends/platform/sdl/win32/win32-window.h" #include "backends/saves/windows/windows-saves.h" #ifdef USE_FREETYPE2 #include "backends/fonts/win32/win32-font-provider.h" #endif #include "backends/fs/windows/windows-fs-factory.h" #include "backends/taskbar/win32/win32-taskbar.h" #include "common/memstream.h" #define DEFAULT_CONFIG_FILE "cabalexec.ini" void OSystem_Win32::init() { // Initialize File System Factory _fsFactory = new WindowsFilesystemFactory(); // Create Win32 specific window _window = new SdlWindow_Win32(); #if defined(USE_TASKBAR) // Initialize taskbar manager _taskbarManager = new Win32TaskbarManager(_window); #endif // Invoke parent implementation of this method OSystem_SDL::init(); } void OSystem_Win32::initBackend() { // Console window is enabled by default on Windows ConfMan.registerDefault("console", true); // Enable or disable the window console window if (ConfMan.getBool("console")) { if (AllocConsole()) { freopen("CONIN$","r",stdin); freopen("CONOUT$","w",stdout); freopen("CONOUT$","w",stderr); } SetConsoleTitle("Cabal Status Window"); } else { FreeConsole(); } // Create the savefile manager if (_savefileManager == 0) _savefileManager = new WindowsSaveFileManager(); // Register the PC speaker device PCSpeakerFactoryMan.registerFactory("win32", "Win32 Hardware Device", &Audio::createWin32PCSpeaker); #ifdef USE_FREETYPE2 // Create the system font provider if (!_systemFontProvider) _systemFontProvider = createWin32FontProvider(); #endif // Invoke parent implementation of this method OSystem_SDL::initBackend(); } bool OSystem_Win32::hasFeature(Feature f) { if (f == kFeatureDisplayLogFile) return true; return OSystem_SDL::hasFeature(f); } bool OSystem_Win32::displayLogFile() { if (_logFilePath.empty()) return false; // Try opening the log file with the default text editor // log files should be registered as "txtfile" by default and thus open in the default text editor HINSTANCE shellExec = ShellExecute(NULL, NULL, _logFilePath.c_str(), NULL, NULL, SW_SHOWNORMAL); if ((intptr_t)shellExec > 32) return true; // ShellExecute with the default verb failed, try the "Open with..." dialog PROCESS_INFORMATION processInformation; STARTUPINFO startupInfo; memset(&processInformation, 0, sizeof(processInformation)); memset(&startupInfo, 0, sizeof(startupInfo)); startupInfo.cb = sizeof(startupInfo); char cmdLine[MAX_PATH * 2]; // CreateProcess may change the contents of cmdLine sprintf(cmdLine, "rundll32 shell32.dll,OpenAs_RunDLL %s", _logFilePath.c_str()); BOOL result = CreateProcess(NULL, cmdLine, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &startupInfo, &processInformation); if (result) return true; return false; } Common::String OSystem_Win32::getDefaultConfigFileName() { char configFile[MAXPATHLEN]; OSVERSIONINFO win32OsVersion; ZeroMemory(&win32OsVersion, sizeof(OSVERSIONINFO)); win32OsVersion.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&win32OsVersion); // Check for non-9X version of Windows. if (win32OsVersion.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) { // Use the Application Data directory of the user profile. if (win32OsVersion.dwMajorVersion >= 5) { if (!GetEnvironmentVariable("APPDATA", configFile, sizeof(configFile))) error("Unable to access application data directory"); } else { if (!GetEnvironmentVariable("USERPROFILE", configFile, sizeof(configFile))) error("Unable to access user profile directory"); strcat(configFile, "\\Application Data"); // If the directory already exists (as it should in most cases), // we don't want to fail, but we need to stop on other errors (such as ERROR_PATH_NOT_FOUND) if (!CreateDirectory(configFile, NULL)) { if (GetLastError() != ERROR_ALREADY_EXISTS) error("Cannot create Application data folder"); } } strcat(configFile, "\\Cabal"); if (!CreateDirectory(configFile, NULL)) { if (GetLastError() != ERROR_ALREADY_EXISTS) error("Cannot create Cabal application data folder"); } strcat(configFile, "\\" DEFAULT_CONFIG_FILE); FILE *tmp = NULL; if ((tmp = fopen(configFile, "r")) == NULL) { // Check windows directory char oldConfigFile[MAXPATHLEN]; uint ret = GetWindowsDirectory(oldConfigFile, MAXPATHLEN); if (ret == 0 || ret > MAXPATHLEN) error("Cannot retrieve the path of the Windows directory"); strcat(oldConfigFile, "\\" DEFAULT_CONFIG_FILE); if ((tmp = fopen(oldConfigFile, "r"))) { strcpy(configFile, oldConfigFile); fclose(tmp); } } else { fclose(tmp); } } else { // Check windows directory uint ret = GetWindowsDirectory(configFile, MAXPATHLEN); if (ret == 0 || ret > MAXPATHLEN) error("Cannot retrieve the path of the Windows directory"); strcat(configFile, "\\" DEFAULT_CONFIG_FILE); } return configFile; } Common::WriteStream *OSystem_Win32::createLogFile() { // Start out by resetting _logFilePath, so that in case // of a failure, we know that no log file is open. _logFilePath.clear(); char logFile[MAXPATHLEN]; OSVERSIONINFO win32OsVersion; ZeroMemory(&win32OsVersion, sizeof(OSVERSIONINFO)); win32OsVersion.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&win32OsVersion); // Check for non-9X version of Windows. if (win32OsVersion.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) { // Use the Application Data directory of the user profile. if (win32OsVersion.dwMajorVersion >= 5) { if (!GetEnvironmentVariable("APPDATA", logFile, sizeof(logFile))) error("Unable to access application data directory"); } else { if (!GetEnvironmentVariable("USERPROFILE", logFile, sizeof(logFile))) error("Unable to access user profile directory"); strcat(logFile, "\\Application Data"); CreateDirectory(logFile, NULL); } strcat(logFile, "\\Cabal"); CreateDirectory(logFile, NULL); strcat(logFile, "\\Logs"); CreateDirectory(logFile, NULL); strcat(logFile, "\\cabalexec.log"); Common::FSNode file(logFile); Common::WriteStream *stream = file.createWriteStream(); if (stream) _logFilePath= logFile; return stream; } else { return 0; } } namespace { class Win32ResourceArchive : public Common::Archive { friend BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCTSTR lpszType, LPTSTR lpszName, LONG_PTR lParam); public: Win32ResourceArchive(); virtual bool hasFile(const Common::String &name) const; virtual int listMembers(Common::ArchiveMemberList &list) const; virtual const Common::ArchiveMemberPtr getMember(const Common::String &name) const; virtual Common::SeekableReadStream *createReadStreamForMember(const Common::String &name) const; private: typedef Common::List<Common::String> FilenameList; FilenameList _files; }; BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCTSTR lpszType, LPTSTR lpszName, LONG_PTR lParam) { if (IS_INTRESOURCE(lpszName)) return TRUE; Win32ResourceArchive *arch = (Win32ResourceArchive *)lParam; arch->_files.push_back(lpszName); return TRUE; } Win32ResourceArchive::Win32ResourceArchive() { EnumResourceNames(NULL, MAKEINTRESOURCE(256), &EnumResNameProc, (LONG_PTR)this); } bool Win32ResourceArchive::hasFile(const Common::String &name) const { for (FilenameList::const_iterator i = _files.begin(); i != _files.end(); ++i) { if (i->equalsIgnoreCase(name)) return true; } return false; } int Win32ResourceArchive::listMembers(Common::ArchiveMemberList &list) const { int count = 0; for (FilenameList::const_iterator i = _files.begin(); i != _files.end(); ++i, ++count) list.push_back(Common::ArchiveMemberPtr(new Common::GenericArchiveMember(*i, this))); return count; } const Common::ArchiveMemberPtr Win32ResourceArchive::getMember(const Common::String &name) const { return Common::ArchiveMemberPtr(new Common::GenericArchiveMember(name, this)); } Common::SeekableReadStream *Win32ResourceArchive::createReadStreamForMember(const Common::String &name) const { HRSRC resource = FindResource(NULL, name.c_str(), MAKEINTRESOURCE(256)); if (resource == NULL) return 0; HGLOBAL handle = LoadResource(NULL, resource); if (handle == NULL) return 0; const byte *data = (const byte *)LockResource(handle); if (data == NULL) return 0; uint32 size = SizeofResource(NULL, resource); if (size == 0) return 0; return new Common::MemoryReadStream(data, size); } } // End of anonymous namespace void OSystem_Win32::addSysArchivesToSearchSet(Common::SearchSet &s, int priority) { s.add("Win32Res", new Win32ResourceArchive(), priority); OSystem_SDL::addSysArchivesToSearchSet(s, priority); } AudioCDManager *OSystem_Win32::createAudioCDManager() { return createWin32AudioCDManager(); } #endif
clone2727/cabal
backends/platform/sdl/win32/win32.cpp
C++
gpl-2.0
10,473
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ModelAnimationLibrary { public struct float4 { private float _num1, _num2, _num3, _num4; /*public float4() { _num1 = -1; _num2 = -1; _num3 = -1; _num4 = -1; }*/ public void Init() { _num1 = -1; _num2 = -1; _num3 = -1; _num4 = -1; } public float4(float num1, float num2, float num3, float num4) { _num1 = num1; _num2 = num2; _num3 = num3; _num4 = num4; } public void AddFloat(float num) { if (_num1 == -1) _num1 = num; else if (_num2 == -1) _num2 = num; else if (_num3 == -1) _num3 = num; else if (_num4 == -1) _num4 = num; } public float[] ToFloatArray() { return new float[4] { _num1, _num2, _num3, _num4 }; } public float this[int index] { get { switch (index) { case 1: return _num1; case 2: return _num2; case 3: return _num3; case 4: return _num4; default: return -1; } } } }; }
JoshuaKlaser/ANSKLibrary
AnimationExample/ModelAnimationLibrary/ShaderVars/float4.cs
C#
gpl-2.0
1,626
/* Copyright (c) 2013-2015, 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. */ #define SENSOR_DRIVER_I2C "i2c_camera" #include "msm_sensor.h" #include "msm_sd.h" #include "camera.h" #include "msm_cci.h" #include "msm_camera_dt_util.h" #undef CDBG #define CDBG(fmt, args...) pr_debug(fmt, ##args) #define SENSOR_MAX_MOUNTANGLE (360) static struct kobject *android_imx377_htc; static const char *imx377_htcVendor = "Sony"; static const char *imx377_htcNAME = "imx377_htc"; static const char *imx377_htcSize = "12M"; static struct kobject *android_s5k4e6_htc; static const char *s5k4e6_htcVendor = "Samsung"; static const char *s5k4e6_htcNAME = "s5k4e6_htc"; static const char *s5k4e6_htcSize = "5M"; uint32_t msm_sensor_driver_get_boardinfo(struct device_node *of_node) { uint32_t boardinfo = 0; if (0 > of_property_read_u32(of_node, "qcom,camera-ver", &boardinfo)) { boardinfo = 0; } pr_info("%s: msm_sensor_get_boardinfo, read boardinfo:%d \n",__func__, boardinfo); return boardinfo; } static ssize_t sensor_vendor_show(struct device *dev, struct device_attribute *attr, char *buf) { ssize_t ret = 0; sprintf(buf, "%s %s %s\n", imx377_htcVendor, imx377_htcNAME, imx377_htcSize); ret = strlen(buf) + 1; return ret; } static ssize_t sensor_vendor_show_front(struct device *dev, struct device_attribute *attr, char *buf) { ssize_t ret = 0; sprintf(buf, "%s %s %s\n", s5k4e6_htcVendor, s5k4e6_htcNAME, s5k4e6_htcSize); ret = strlen(buf) + 1; return ret; } static int imx377_htc_sysfs_init(void) { int ret ; static DEVICE_ATTR(sensor, 0444, sensor_vendor_show, NULL); pr_info("imx377_htc:kobject creat and add\n"); android_imx377_htc = kobject_create_and_add("android_camera", NULL); if (android_imx377_htc == NULL) { pr_info("imx377_htc_sysfs_init: subsystem_register " \ "failed\n"); ret = -ENOMEM; return ret ; } pr_info("imx377_htc:sysfs_create_file\n"); ret = sysfs_create_file(android_imx377_htc, &dev_attr_sensor.attr); if (ret) { pr_info("imx377_htc_sysfs_init: sysfs_create_file " \ "failed\n"); kobject_del(android_imx377_htc); } pr_info("[CAM][Sensor main]%s %s %s\n",imx377_htcVendor, imx377_htcNAME, imx377_htcSize); return 0 ; } static int s5k4e6_htc_sysfs_init(void) { int ret ; static DEVICE_ATTR(sensor, 0444, sensor_vendor_show_front, NULL); pr_info("s5k4e6_htc:kobject creat and add\n"); android_s5k4e6_htc = kobject_create_and_add("android_camera2", NULL); if (android_s5k4e6_htc == NULL) { pr_info("s5k4e6_htc_sysfs_init: subsystem_register " \ "failed\n"); ret = -ENOMEM; return ret ; } pr_info("s5k4e6_htc:sysfs_create_file\n"); ret = sysfs_create_file(android_s5k4e6_htc, &dev_attr_sensor.attr); if (ret) { pr_info("s5k4e6_htc_sysfs_init: sysfs_create_file " \ "failed\n"); kobject_del(android_s5k4e6_htc); } pr_info("[CAM][Sensor front]%s %s %s\n",s5k4e6_htcVendor, s5k4e6_htcNAME, s5k4e6_htcSize); return 0 ; } static struct v4l2_file_operations msm_sensor_v4l2_subdev_fops; static int32_t msm_sensor_driver_platform_probe(struct platform_device *pdev); static struct msm_sensor_ctrl_t *g_sctrl[MAX_CAMERAS]; static int msm_sensor_platform_remove(struct platform_device *pdev) { struct msm_sensor_ctrl_t *s_ctrl; pr_err("%s: sensor FREE\n", __func__); s_ctrl = g_sctrl[pdev->id]; if (!s_ctrl) { pr_err("%s: sensor device is NULL\n", __func__); return 0; } msm_sensor_free_sensor_data(s_ctrl); kfree(s_ctrl->msm_sensor_mutex); kfree(s_ctrl->sensor_i2c_client); kfree(s_ctrl); g_sctrl[pdev->id] = NULL; return 0; } static const struct of_device_id msm_sensor_driver_dt_match[] = { {.compatible = "qcom,camera"}, {} }; MODULE_DEVICE_TABLE(of, msm_sensor_driver_dt_match); static struct platform_driver msm_sensor_platform_driver = { .probe = msm_sensor_driver_platform_probe, .driver = { .name = "qcom,camera", .owner = THIS_MODULE, .of_match_table = msm_sensor_driver_dt_match, }, .remove = msm_sensor_platform_remove, }; static struct v4l2_subdev_info msm_sensor_driver_subdev_info[] = { { .code = V4L2_MBUS_FMT_SBGGR10_1X10, .colorspace = V4L2_COLORSPACE_JPEG, .fmt = 1, .order = 0, }, }; static int32_t msm_sensor_driver_create_i2c_v4l_subdev (struct msm_sensor_ctrl_t *s_ctrl) { int32_t rc = 0; uint32_t session_id = 0; struct i2c_client *client = s_ctrl->sensor_i2c_client->client; CDBG("%s %s I2c probe succeeded\n", __func__, client->name); rc = camera_init_v4l2(&client->dev, &session_id); if (rc < 0) { pr_err("failed: camera_init_i2c_v4l2 rc %d", rc); return rc; } CDBG("%s rc %d session_id %d\n", __func__, rc, session_id); snprintf(s_ctrl->msm_sd.sd.name, sizeof(s_ctrl->msm_sd.sd.name), "%s", s_ctrl->sensordata->sensor_name); v4l2_i2c_subdev_init(&s_ctrl->msm_sd.sd, client, s_ctrl->sensor_v4l2_subdev_ops); v4l2_set_subdevdata(&s_ctrl->msm_sd.sd, client); s_ctrl->msm_sd.sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; media_entity_init(&s_ctrl->msm_sd.sd.entity, 0, NULL, 0); s_ctrl->msm_sd.sd.entity.type = MEDIA_ENT_T_V4L2_SUBDEV; s_ctrl->msm_sd.sd.entity.group_id = MSM_CAMERA_SUBDEV_SENSOR; s_ctrl->msm_sd.sd.entity.name = s_ctrl->msm_sd.sd.name; s_ctrl->sensordata->sensor_info->session_id = session_id; s_ctrl->msm_sd.close_seq = MSM_SD_CLOSE_2ND_CATEGORY | 0x3; msm_sd_register(&s_ctrl->msm_sd); msm_sensor_v4l2_subdev_fops = v4l2_subdev_fops; #ifdef CONFIG_COMPAT msm_sensor_v4l2_subdev_fops.compat_ioctl32 = msm_sensor_subdev_fops_ioctl; #endif s_ctrl->msm_sd.sd.devnode->fops = &msm_sensor_v4l2_subdev_fops; CDBG("%s:%d\n", __func__, __LINE__); return rc; } static int32_t msm_sensor_driver_create_v4l_subdev (struct msm_sensor_ctrl_t *s_ctrl) { int32_t rc = 0; uint32_t session_id = 0; rc = camera_init_v4l2(&s_ctrl->pdev->dev, &session_id); if (rc < 0) { pr_err("failed: camera_init_v4l2 rc %d", rc); return rc; } CDBG("rc %d session_id %d", rc, session_id); s_ctrl->sensordata->sensor_info->session_id = session_id; v4l2_subdev_init(&s_ctrl->msm_sd.sd, s_ctrl->sensor_v4l2_subdev_ops); snprintf(s_ctrl->msm_sd.sd.name, sizeof(s_ctrl->msm_sd.sd.name), "%s", s_ctrl->sensordata->sensor_name); v4l2_set_subdevdata(&s_ctrl->msm_sd.sd, s_ctrl->pdev); s_ctrl->msm_sd.sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; media_entity_init(&s_ctrl->msm_sd.sd.entity, 0, NULL, 0); s_ctrl->msm_sd.sd.entity.type = MEDIA_ENT_T_V4L2_SUBDEV; s_ctrl->msm_sd.sd.entity.group_id = MSM_CAMERA_SUBDEV_SENSOR; s_ctrl->msm_sd.sd.entity.name = s_ctrl->msm_sd.sd.name; s_ctrl->msm_sd.close_seq = MSM_SD_CLOSE_2ND_CATEGORY | 0x3; msm_sd_register(&s_ctrl->msm_sd); msm_cam_copy_v4l2_subdev_fops(&msm_sensor_v4l2_subdev_fops); #ifdef CONFIG_COMPAT msm_sensor_v4l2_subdev_fops.compat_ioctl32 = msm_sensor_subdev_fops_ioctl; #endif s_ctrl->msm_sd.sd.devnode->fops = &msm_sensor_v4l2_subdev_fops; return rc; } static int32_t msm_sensor_fill_eeprom_subdevid_by_name( struct msm_sensor_ctrl_t *s_ctrl) { int32_t rc = 0; const char *eeprom_name; struct device_node *src_node = NULL; uint32_t val = 0, eeprom_name_len; int32_t *eeprom_subdev_id, i, userspace_probe = 0; int32_t count = 0; struct msm_sensor_info_t *sensor_info; struct device_node *of_node = s_ctrl->of_node; const void *p; if (!s_ctrl->sensordata->eeprom_name || !of_node) return -EINVAL; eeprom_name_len = strlen(s_ctrl->sensordata->eeprom_name); if (eeprom_name_len >= MAX_SENSOR_NAME) return -EINVAL; sensor_info = s_ctrl->sensordata->sensor_info; eeprom_subdev_id = &sensor_info->subdev_id[SUB_MODULE_EEPROM]; *eeprom_subdev_id = -1; if (0 == eeprom_name_len) return 0; p = of_get_property(of_node, "qcom,eeprom-src", &count); if (!p || !count) return 0; count /= sizeof(uint32_t); for (i = 0; i < count; i++) { userspace_probe = 0; eeprom_name = NULL; src_node = of_parse_phandle(of_node, "qcom,eeprom-src", i); if (!src_node) { pr_err("eeprom src node NULL\n"); continue; } rc = of_property_read_string(src_node, "qcom,eeprom-name", &eeprom_name); if (rc < 0) { pr_err("%s:%d Eeprom userspace probe for %s\n", __func__, __LINE__, s_ctrl->sensordata->eeprom_name); of_node_put(src_node); userspace_probe = 1; if (count > 1) return -EINVAL; } if (!userspace_probe && strcmp(eeprom_name, s_ctrl->sensordata->eeprom_name)) continue; rc = of_property_read_u32(src_node, "cell-index", &val); if (rc < 0) { pr_err("%s qcom,eeprom cell index %d, rc %d\n", __func__, val, rc); of_node_put(src_node); if (userspace_probe) return -EINVAL; continue; } *eeprom_subdev_id = val; CDBG("%s:%d Eeprom subdevice id is %d\n", __func__, __LINE__, val); of_node_put(src_node); src_node = NULL; break; } return rc; } static int32_t msm_sensor_fill_actuator_subdevid_by_name( struct msm_sensor_ctrl_t *s_ctrl) { int32_t rc = 0; struct device_node *src_node = NULL; uint32_t val = 0, actuator_name_len; int32_t *actuator_subdev_id; struct msm_sensor_info_t *sensor_info; struct device_node *of_node = s_ctrl->of_node; if (!s_ctrl->sensordata->actuator_name || !of_node) return -EINVAL; actuator_name_len = strlen(s_ctrl->sensordata->actuator_name); if (actuator_name_len >= MAX_SENSOR_NAME) return -EINVAL; sensor_info = s_ctrl->sensordata->sensor_info; actuator_subdev_id = &sensor_info->subdev_id[SUB_MODULE_ACTUATOR]; *actuator_subdev_id = -1; if (0 == actuator_name_len) return 0; src_node = of_parse_phandle(of_node, "qcom,actuator-src", 0); if (!src_node) { CDBG("%s:%d src_node NULL\n", __func__, __LINE__); } else { rc = of_property_read_u32(src_node, "cell-index", &val); CDBG("%s qcom,actuator cell index %d, rc %d\n", __func__, val, rc); if (rc < 0) { pr_err("%s failed %d\n", __func__, __LINE__); return -EINVAL; } *actuator_subdev_id = val; of_node_put(src_node); src_node = NULL; } return rc; } static int32_t msm_sensor_fill_ois_subdevid_by_name( struct msm_sensor_ctrl_t *s_ctrl) { int32_t rc = 0; struct device_node *src_node = NULL; uint32_t val = 0, ois_name_len; int32_t *ois_subdev_id; struct msm_sensor_info_t *sensor_info; struct device_node *of_node = s_ctrl->of_node; if (!s_ctrl->sensordata->ois_name || !of_node) return -EINVAL; ois_name_len = strlen(s_ctrl->sensordata->ois_name); if (ois_name_len >= MAX_SENSOR_NAME) return -EINVAL; sensor_info = s_ctrl->sensordata->sensor_info; ois_subdev_id = &sensor_info->subdev_id[SUB_MODULE_OIS]; *ois_subdev_id = -1; if (0 == ois_name_len) return 0; src_node = of_parse_phandle(of_node, "qcom,ois-src", 0); if (!src_node) { CDBG("%s:%d src_node NULL\n", __func__, __LINE__); } else { rc = of_property_read_u32(src_node, "cell-index", &val); CDBG("%s qcom,ois cell index %d, rc %d\n", __func__, val, rc); if (rc < 0) { pr_err("%s failed %d\n", __func__, __LINE__); return -EINVAL; } *ois_subdev_id = val; of_node_put(src_node); src_node = NULL; } return rc; } static int32_t msm_sensor_fill_slave_info_init_params( struct msm_camera_sensor_slave_info *slave_info, struct msm_sensor_info_t *sensor_info) { struct msm_sensor_init_params *sensor_init_params; if (!slave_info || !sensor_info) return -EINVAL; if (!slave_info->is_init_params_valid) return 0; sensor_init_params = &slave_info->sensor_init_params; if (INVALID_CAMERA_B != sensor_init_params->position) sensor_info->position = sensor_init_params->position; if (SENSOR_MAX_MOUNTANGLE > sensor_init_params->sensor_mount_angle) { sensor_info->sensor_mount_angle = sensor_init_params->sensor_mount_angle; sensor_info->is_mount_angle_valid = 1; } if (CAMERA_MODE_INVALID != sensor_init_params->modes_supported) sensor_info->modes_supported = sensor_init_params->modes_supported; return 0; } static int32_t msm_sensor_validate_slave_info( struct msm_sensor_info_t *sensor_info) { if (INVALID_CAMERA_B == sensor_info->position) { sensor_info->position = BACK_CAMERA_B; CDBG("%s:%d Set default sensor position\n", __func__, __LINE__); } if (CAMERA_MODE_INVALID == sensor_info->modes_supported) { sensor_info->modes_supported = CAMERA_MODE_2D_B; CDBG("%s:%d Set default sensor modes_supported\n", __func__, __LINE__); } if (SENSOR_MAX_MOUNTANGLE <= sensor_info->sensor_mount_angle) { sensor_info->sensor_mount_angle = 0; CDBG("%s:%d Set default sensor mount angle\n", __func__, __LINE__); sensor_info->is_mount_angle_valid = 1; } return 0; } #ifdef CONFIG_COMPAT static int32_t msm_sensor_get_pw_settings_compat( struct msm_sensor_power_setting *ps, struct msm_sensor_power_setting *us_ps, uint32_t size) { int32_t rc = 0, i = 0; struct msm_sensor_power_setting32 *ps32 = kzalloc(sizeof(*ps32) * size, GFP_KERNEL); if (!ps32) { pr_err("failed: no memory ps32"); return -ENOMEM; } if (copy_from_user(ps32, (void *)us_ps, sizeof(*ps32) * size)) { pr_err("failed: copy_from_user"); kfree(ps32); return -EFAULT; } for (i = 0; i < size; i++) { ps[i].config_val = ps32[i].config_val; ps[i].delay = ps32[i].delay; ps[i].seq_type = ps32[i].seq_type; ps[i].seq_val = ps32[i].seq_val; } kfree(ps32); return rc; } #endif static int32_t msm_sensor_create_pd_settings(void *setting, struct msm_sensor_power_setting *pd, uint32_t size_down, struct msm_sensor_power_setting *pu) { int32_t rc = 0; int c, end; struct msm_sensor_power_setting pd_tmp; pr_err("Generating power_down_setting"); #ifdef CONFIG_COMPAT if (is_compat_task()) { int i = 0; struct msm_sensor_power_setting32 *power_setting_iter = (struct msm_sensor_power_setting32 *)compat_ptr(( (struct msm_camera_sensor_slave_info32 *)setting)-> power_setting_array.power_setting); for (i = 0; i < size_down; i++) { pd[i].config_val = power_setting_iter[i].config_val; pd[i].delay = power_setting_iter[i].delay; pd[i].seq_type = power_setting_iter[i].seq_type; pd[i].seq_val = power_setting_iter[i].seq_val; } } else #endif { if (copy_from_user(pd, (void *)pu, sizeof(*pd) * size_down)) { pr_err("failed: copy_from_user"); return -EFAULT; } } end = size_down - 1; for (c = 0; c < size_down/2; c++) { pd_tmp = pd[c]; pd[c] = pd[end]; pd[end] = pd_tmp; end--; } return rc; } static int32_t msm_sensor_get_power_down_settings(void *setting, struct msm_camera_sensor_slave_info *slave_info, struct msm_camera_power_ctrl_t *power_info) { int32_t rc = 0; uint16_t size_down = 0; uint16_t i = 0; struct msm_sensor_power_setting *pd = NULL; int hw_version = 0; struct device_node *of_node = g_sctrl[slave_info->camera_id]->of_node; struct msm_sensor_power_setting *pu_temp = NULL; int index = 0; hw_version = msm_sensor_driver_get_boardinfo(of_node); size_down = slave_info->power_setting_array.size_down; if (!size_down || size_down > MAX_POWER_CONFIG) size_down = slave_info->power_setting_array.size; if (size_down > MAX_POWER_CONFIG) { pr_err("failed: invalid size_down %d", size_down); return -EINVAL; } pd = kzalloc(sizeof(*pd) * size_down, GFP_KERNEL); if (!pd) { pr_err("failed: no memory power_setting %p", pd); return -EFAULT; } if (slave_info->power_setting_array.power_down_setting) { #ifdef CONFIG_COMPAT if (is_compat_task()) { rc = msm_sensor_get_pw_settings_compat( pd, slave_info->power_setting_array. power_down_setting, size_down); if (rc < 0) { pr_err("failed"); kfree(pd); return -EFAULT; } } else #endif if (copy_from_user(pd, (void *)slave_info->power_setting_array. power_down_setting, sizeof(*pd) * size_down)) { pr_err("failed: copy_from_user"); kfree(pd); return -EFAULT; } } else { rc = msm_sensor_create_pd_settings(setting, pd, size_down, slave_info->power_setting_array.power_setting); if (rc < 0) { pr_err("failed"); kfree(pd); return -EFAULT; } } if(hw_version > 0) { pu_temp = kzalloc(sizeof(*pu_temp) * size_down, GFP_KERNEL); if (!pu_temp) { pr_err("failed: power_down pu_temp no memory power_setting"); kfree(pd); return -EFAULT; } index = 0; if(hw_version == 1) { for (i = 0; i < size_down; i++) { pr_info("(%d)[CAM]DOWN seq_type %d seq_val %d config_val %ld delay %d \n", i, pd[i].seq_type, pd[i].seq_val, pd[i].config_val, pd[i].delay); if(SENSOR_GPIO == pd[i].seq_type && pd[i].seq_val == SENSOR_GPIO_VANA) { pr_info("[CAM] power down skip SENSOR_GPIO_VANA"); } else { memcpy(&(pu_temp[index]), &(pd[i]) , sizeof(*pu_temp)); index++; } } } else if(hw_version == 2) { for (i = 0; i < size_down; i++) { pr_info("[CAM](%d)DOWN seq_type %d seq_val %d config_val %ld delay %d", i, pd[i].seq_type, pd[i].seq_val, pd[i].config_val, pd[i].delay); if(SENSOR_VREG == pd[i].seq_type && pd[i].seq_val == CAM_VANA) { pr_info("[CAM]power down skip CAM_VANA"); } else { memcpy(&(pu_temp[index]), &(pd[i]) , sizeof(*pu_temp)); index++; } } } else { pr_err("[CAM]Error, Down wrong HW version"); kfree(pd); return -EFAULT; } power_info->power_down_setting = pu_temp; power_info->power_down_setting_size = size_down -1 ; kfree(pd); } else { power_info->power_down_setting = pd; power_info->power_down_setting_size = size_down; for (i = 0; i < size_down; i++) { CDBG("DOWN seq_type %d seq_val %d config_val %ld delay %d", pd[i].seq_type, pd[i].seq_val, pd[i].config_val, pd[i].delay); } } return rc; } static int32_t msm_sensor_get_power_up_settings(void *setting, struct msm_camera_sensor_slave_info *slave_info, struct msm_camera_power_ctrl_t *power_info) { int32_t rc = 0; uint16_t size = 0; uint16_t i = 0; struct msm_sensor_power_setting *pu = NULL; int hw_version = 0; struct device_node *of_node = g_sctrl[slave_info->camera_id]->of_node; struct msm_sensor_power_setting *pu_temp = NULL; int index = 0; hw_version = msm_sensor_driver_get_boardinfo(of_node); size = slave_info->power_setting_array.size; if ((size == 0) || (size > MAX_POWER_CONFIG)) { pr_err("failed: invalid power_setting size_up = %d\n", size); return -EINVAL; } pu = kzalloc(sizeof(*pu) * size, GFP_KERNEL); if (!pu) { pr_err("failed: no memory power_setting %p", pu); return -ENOMEM; } #ifdef CONFIG_COMPAT if (is_compat_task()) { rc = msm_sensor_get_pw_settings_compat(pu, slave_info->power_setting_array. power_setting, size); if (rc < 0) { pr_err("failed"); kfree(pu); return -EFAULT; } } else #endif { if (copy_from_user(pu, (void *)slave_info->power_setting_array.power_setting, sizeof(*pu) * size)) { pr_err("failed: copy_from_user"); kfree(pu); return -EFAULT; } } if(hw_version > 0) { pu_temp = kzalloc(sizeof(*pu_temp) * size, GFP_KERNEL); if (!pu_temp) { pr_err("failed: power_up pu_temp no memory power_setting"); kfree(pu); return -EFAULT; } index = 0; if(hw_version == 1) { for (i = 0; i < size; i++) { pr_info("(%d)[CAM]UP seq_type %d seq_val %d config_val %ld delay %d \n", i, pu[i].seq_type, pu[i].seq_val, pu[i].config_val, pu[i].delay); if(SENSOR_GPIO == pu[i].seq_type && pu[i].seq_val == SENSOR_GPIO_VANA) { pr_info("[CAM] power up skip SENSOR_GPIO_VANA"); } else { memcpy(&(pu_temp[index]), &(pu[i]) , sizeof(*pu_temp)); index++; } } } else if(hw_version == 2) { for (i = 0; i < size; i++) { pr_info("[CAM](%d)UP seq_type %d seq_val %d config_val %ld delay %d", i, pu[i].seq_type, pu[i].seq_val, pu[i].config_val, pu[i].delay); if(SENSOR_VREG == pu[i].seq_type && pu[i].seq_val == CAM_VANA) { pr_info("[CAM]power up skip CAM_VANA"); } else { memcpy(&(pu_temp[index]), &(pu[i]) , sizeof(*pu_temp)); index++; } } } else { pr_err("[CAM]Error, UP wrong HW version"); kfree(pu); return -EFAULT; } power_info->power_setting = pu_temp; power_info->power_setting_size = size - 1; kfree(pu); } else { for (i = 0; i < size; i++) { CDBG("UP seq_type %d seq_val %d config_val %ld delay %d", pu[i].seq_type, pu[i].seq_val, pu[i].config_val, pu[i].delay); } power_info->power_setting = pu; power_info->power_setting_size = size; } return rc; } static int32_t msm_sensor_get_power_settings(void *setting, struct msm_camera_sensor_slave_info *slave_info, struct msm_camera_power_ctrl_t *power_info) { int32_t rc = 0; rc = msm_sensor_get_power_up_settings(setting, slave_info, power_info); if (rc < 0) { pr_err("failed"); return -EINVAL; } rc = msm_sensor_get_power_down_settings(setting, slave_info, power_info); if (rc < 0) { pr_err("failed"); return -EINVAL; } return rc; } static void msm_sensor_fill_sensor_info(struct msm_sensor_ctrl_t *s_ctrl, struct msm_sensor_info_t *sensor_info, char *entity_name) { uint32_t i; if (!s_ctrl || !sensor_info) { pr_err("%s:failed\n", __func__); return; } strlcpy(sensor_info->sensor_name, s_ctrl->sensordata->sensor_name, MAX_SENSOR_NAME); sensor_info->session_id = s_ctrl->sensordata->sensor_info->session_id; s_ctrl->sensordata->sensor_info->subdev_id[SUB_MODULE_SENSOR] = s_ctrl->sensordata->sensor_info->session_id; for (i = 0; i < SUB_MODULE_MAX; i++) { sensor_info->subdev_id[i] = s_ctrl->sensordata->sensor_info->subdev_id[i]; sensor_info->subdev_intf[i] = s_ctrl->sensordata->sensor_info->subdev_intf[i]; } sensor_info->is_mount_angle_valid = s_ctrl->sensordata->sensor_info->is_mount_angle_valid; sensor_info->sensor_mount_angle = s_ctrl->sensordata->sensor_info->sensor_mount_angle; sensor_info->modes_supported = s_ctrl->sensordata->sensor_info->modes_supported; sensor_info->position = s_ctrl->sensordata->sensor_info->position; strlcpy(entity_name, s_ctrl->msm_sd.sd.entity.name, MAX_SENSOR_NAME); } #define EEPROM_COMPONENT_I2C_ADDR_WRITE 0xA0 void msm_sensor_read_OTP(struct msm_camera_sensor_slave_info *sensor_slave_info, struct msm_sensor_ctrl_t *s_ctrl) { int rc = 0; struct msm_camera_i2c_client *sensor_i2c_client; struct msm_camera_slave_info *slave_info; pr_err("[CAM]%s: %s +, slave_info->slave_addr:%d", __func__, sensor_slave_info->sensor_name, sensor_slave_info->slave_addr); sensor_i2c_client = s_ctrl->sensor_i2c_client; slave_info = s_ctrl->sensordata->slave_info; if (!sensor_i2c_client || !slave_info ) { pr_err("[CAM]%s: %s, return", __func__, sensor_slave_info->sensor_name); return; } if(strncmp("imx377_htc", sensor_slave_info->sensor_name, sizeof("imx377_htc")) == 0) { pr_err("[CAM]%s: %s, match sensor name, use byte address", __func__, sensor_slave_info->sensor_name); #ifdef CONFIG_COMPAT rc = s_ctrl->func_tbl->sensor_i2c_read_fuseid32(NULL, s_ctrl); #else rc = s_ctrl->func_tbl->sensor_i2c_read_fuseid(NULL, s_ctrl); #endif imx377_htc_sysfs_init(); pr_err("[CAM]%s: imx377_htc_sysfs_init done", __func__); } else if(strncmp("s5k4e6_htc", sensor_slave_info->sensor_name, sizeof("s5k4e6_htc")) == 0) { #ifdef CONFIG_COMPAT rc = s_ctrl->func_tbl->sensor_i2c_read_fuseid32(NULL, s_ctrl); #else rc = s_ctrl->func_tbl->sensor_i2c_read_fuseid(NULL, s_ctrl); #endif s5k4e6_htc_sysfs_init(); pr_err("[CAM]%s: s5k4e6_htc_sysfs_init done", __func__); } else { pr_err("[CAM]%s: %s, NOT match sensor name", __func__, sensor_slave_info->sensor_name); } pr_err("[CAM]%s: %s -", __func__, sensor_slave_info->sensor_name); } int32_t msm_sensor_driver_probe(void *setting, struct msm_sensor_info_t *probed_info, char *entity_name) { int32_t rc = 0; struct msm_sensor_ctrl_t *s_ctrl = NULL; struct msm_camera_cci_client *cci_client = NULL; struct msm_camera_sensor_slave_info *slave_info = NULL; struct msm_camera_slave_info *camera_info = NULL; unsigned long mount_pos = 0; uint32_t is_yuv; if (!setting) { pr_err("failed: slave_info %p", setting); return -EINVAL; } slave_info = kzalloc(sizeof(*slave_info), GFP_KERNEL); if (!slave_info) { pr_err("failed: no memory slave_info %p", slave_info); return -ENOMEM; } #ifdef CONFIG_COMPAT if (is_compat_task()) { struct msm_camera_sensor_slave_info32 *slave_info32 = kzalloc(sizeof(*slave_info32), GFP_KERNEL); if (!slave_info32) { pr_err("failed: no memory for slave_info32 %p\n", slave_info32); rc = -ENOMEM; goto free_slave_info; } if (copy_from_user((void *)slave_info32, setting, sizeof(*slave_info32))) { pr_err("failed: copy_from_user"); rc = -EFAULT; kfree(slave_info32); goto free_slave_info; } strlcpy(slave_info->actuator_name, slave_info32->actuator_name, sizeof(slave_info->actuator_name)); strlcpy(slave_info->eeprom_name, slave_info32->eeprom_name, sizeof(slave_info->eeprom_name)); strlcpy(slave_info->sensor_name, slave_info32->sensor_name, sizeof(slave_info->sensor_name)); strlcpy(slave_info->ois_name, slave_info32->ois_name, sizeof(slave_info->ois_name)); strlcpy(slave_info->flash_name, slave_info32->flash_name, sizeof(slave_info->flash_name)); slave_info->addr_type = slave_info32->addr_type; slave_info->camera_id = slave_info32->camera_id; slave_info->i2c_freq_mode = slave_info32->i2c_freq_mode; slave_info->sensor_id_info = slave_info32->sensor_id_info; slave_info->slave_addr = slave_info32->slave_addr; slave_info->power_setting_array.size = slave_info32->power_setting_array.size; slave_info->power_setting_array.size_down = slave_info32->power_setting_array.size_down; slave_info->power_setting_array.size_down = slave_info32->power_setting_array.size_down; slave_info->power_setting_array.power_setting = compat_ptr(slave_info32-> power_setting_array.power_setting); slave_info->power_setting_array.power_down_setting = compat_ptr(slave_info32-> power_setting_array.power_down_setting); slave_info->is_init_params_valid = slave_info32->is_init_params_valid; slave_info->sensor_init_params = slave_info32->sensor_init_params; slave_info->output_format = slave_info32->output_format; kfree(slave_info32); } else #endif { if (copy_from_user(slave_info, (void *)setting, sizeof(*slave_info))) { pr_err("failed: copy_from_user"); rc = -EFAULT; goto free_slave_info; } } CDBG("camera id %d Slave addr 0x%X addr_type %d\n", slave_info->camera_id, slave_info->slave_addr, slave_info->addr_type); CDBG("sensor_id_reg_addr 0x%X sensor_id 0x%X sensor id mask %d", slave_info->sensor_id_info.sensor_id_reg_addr, slave_info->sensor_id_info.sensor_id, slave_info->sensor_id_info.sensor_id_mask); CDBG("power up size %d power down size %d\n", slave_info->power_setting_array.size, slave_info->power_setting_array.size_down); if (slave_info->is_init_params_valid) { CDBG("position %d", slave_info->sensor_init_params.position); CDBG("mount %d", slave_info->sensor_init_params.sensor_mount_angle); } if (slave_info->camera_id >= MAX_CAMERAS) { pr_err("failed: invalid camera id %d max %d", slave_info->camera_id, MAX_CAMERAS); rc = -EINVAL; goto free_slave_info; } s_ctrl = g_sctrl[slave_info->camera_id]; if (!s_ctrl) { pr_err("failed: s_ctrl %p for camera_id %d", s_ctrl, slave_info->camera_id); rc = -EINVAL; goto free_slave_info; } CDBG("s_ctrl[%d] %p", slave_info->camera_id, s_ctrl); if (s_ctrl->is_probe_succeed == 1) { if (slave_info->sensor_id_info.sensor_id == s_ctrl->sensordata->cam_slave_info-> sensor_id_info.sensor_id) { pr_err("slot%d: sensor id%d already probed\n", slave_info->camera_id, s_ctrl->sensordata->cam_slave_info-> sensor_id_info.sensor_id); msm_sensor_fill_sensor_info(s_ctrl, probed_info, entity_name); } else pr_err("slot %d has some other sensor\n", slave_info->camera_id); rc = 0; goto free_slave_info; } if (slave_info->power_setting_array.size == 0 && slave_info->slave_addr == 0) { s_ctrl->is_csid_tg_mode = 1; goto CSID_TG; } rc = msm_sensor_get_power_settings(setting, slave_info, &s_ctrl->sensordata->power_info); if (rc < 0) { pr_err("failed"); goto free_slave_info; } camera_info = kzalloc(sizeof(struct msm_camera_slave_info), GFP_KERNEL); if (!camera_info) { pr_err("failed: no memory slave_info %p", camera_info); goto free_slave_info; } s_ctrl->sensordata->slave_info = camera_info; camera_info->sensor_slave_addr = slave_info->slave_addr; camera_info->sensor_id_reg_addr = slave_info->sensor_id_info.sensor_id_reg_addr; camera_info->sensor_id = slave_info->sensor_id_info.sensor_id; camera_info->sensor_id_mask = slave_info->sensor_id_info.sensor_id_mask; if (!s_ctrl->sensor_i2c_client) { pr_err("failed: sensor_i2c_client %p", s_ctrl->sensor_i2c_client); rc = -EINVAL; goto free_camera_info; } s_ctrl->sensor_i2c_client->addr_type = slave_info->addr_type; if (s_ctrl->sensor_i2c_client->client) s_ctrl->sensor_i2c_client->client->addr = camera_info->sensor_slave_addr; cci_client = s_ctrl->sensor_i2c_client->cci_client; if (!cci_client) { pr_err("failed: cci_client %p", cci_client); goto free_camera_info; } cci_client->cci_i2c_master = s_ctrl->cci_i2c_master; cci_client->sid = slave_info->slave_addr >> 1; cci_client->retries = 3; cci_client->id_map = 0; cci_client->i2c_freq_mode = slave_info->i2c_freq_mode; rc = msm_camera_fill_vreg_params( s_ctrl->sensordata->power_info.cam_vreg, s_ctrl->sensordata->power_info.num_vreg, s_ctrl->sensordata->power_info.power_setting, s_ctrl->sensordata->power_info.power_setting_size); if (rc < 0) { pr_err("failed: msm_camera_get_dt_power_setting_data rc %d", rc); goto free_camera_info; } rc = msm_camera_fill_vreg_params( s_ctrl->sensordata->power_info.cam_vreg, s_ctrl->sensordata->power_info.num_vreg, s_ctrl->sensordata->power_info.power_down_setting, s_ctrl->sensordata->power_info.power_down_setting_size); if (rc < 0) { pr_err("failed: msm_camera_fill_vreg_params for PDOWN rc %d", rc); goto free_camera_info; } CSID_TG: s_ctrl->sensordata->sensor_name = slave_info->sensor_name; s_ctrl->sensordata->eeprom_name = slave_info->eeprom_name; s_ctrl->sensordata->actuator_name = slave_info->actuator_name; s_ctrl->sensordata->ois_name = slave_info->ois_name; rc = msm_sensor_fill_eeprom_subdevid_by_name(s_ctrl); if (rc < 0) { pr_err("%s failed %d\n", __func__, __LINE__); goto free_camera_info; } rc = msm_sensor_fill_actuator_subdevid_by_name(s_ctrl); if (rc < 0) { pr_err("%s failed %d\n", __func__, __LINE__); goto free_camera_info; } rc = msm_sensor_fill_ois_subdevid_by_name(s_ctrl); if (rc < 0) { pr_err("%s failed %d\n", __func__, __LINE__); goto free_camera_info; } rc = s_ctrl->func_tbl->sensor_power_up(s_ctrl); if (rc < 0) { pr_err("%s power up failed", slave_info->sensor_name); goto free_camera_info; } pr_err("%s probe succeeded", slave_info->sensor_name); msm_sensor_read_OTP(slave_info, s_ctrl); s_ctrl->is_probe_succeed = 1; if (strlen(slave_info->flash_name) == 0) { s_ctrl->sensordata->sensor_info-> subdev_id[SUB_MODULE_LED_FLASH] = -1; } if (s_ctrl->sensor_device_type == MSM_CAMERA_PLATFORM_DEVICE) rc = msm_sensor_driver_create_v4l_subdev(s_ctrl); else rc = msm_sensor_driver_create_i2c_v4l_subdev(s_ctrl); if (rc < 0) { pr_err("failed: camera creat v4l2 rc %d", rc); goto camera_power_down; } s_ctrl->func_tbl->sensor_power_down(s_ctrl); rc = msm_sensor_fill_slave_info_init_params( slave_info, s_ctrl->sensordata->sensor_info); if (rc < 0) { pr_err("%s Fill slave info failed", slave_info->sensor_name); goto free_camera_info; } rc = msm_sensor_validate_slave_info(s_ctrl->sensordata->sensor_info); if (rc < 0) { pr_err("%s Validate slave info failed", slave_info->sensor_name); goto free_camera_info; } is_yuv = (slave_info->output_format == MSM_SENSOR_YCBCR) ? 1 : 0; mount_pos = is_yuv << 25 | (s_ctrl->sensordata->sensor_info->position << 16) | ((s_ctrl->sensordata-> sensor_info->sensor_mount_angle / 90) << 8); s_ctrl->msm_sd.sd.entity.flags = mount_pos | MEDIA_ENT_FL_DEFAULT; s_ctrl->sensordata->cam_slave_info = slave_info; msm_sensor_fill_sensor_info(s_ctrl, probed_info, entity_name); return rc; camera_power_down: s_ctrl->func_tbl->sensor_power_down(s_ctrl); free_camera_info: kfree(camera_info); free_slave_info: kfree(slave_info); return rc; } static int32_t msm_sensor_driver_get_gpio_data( struct msm_camera_sensor_board_info *sensordata, struct device_node *of_node) { int32_t rc = 0, i = 0; struct msm_camera_gpio_conf *gconf = NULL; uint16_t *gpio_array = NULL; uint16_t gpio_array_size = 0; if (!sensordata || !of_node) { pr_err("failed: invalid params sensordata %p of_node %p", sensordata, of_node); return -EINVAL; } sensordata->power_info.gpio_conf = kzalloc( sizeof(struct msm_camera_gpio_conf), GFP_KERNEL); if (!sensordata->power_info.gpio_conf) { pr_err("failed"); return -ENOMEM; } gconf = sensordata->power_info.gpio_conf; gpio_array_size = of_gpio_count(of_node); CDBG("gpio count %d", gpio_array_size); if (!gpio_array_size) return 0; gpio_array = kzalloc(sizeof(uint16_t) * gpio_array_size, GFP_KERNEL); if (!gpio_array) { pr_err("failed"); goto FREE_GPIO_CONF; } for (i = 0; i < gpio_array_size; i++) { gpio_array[i] = of_get_gpio(of_node, i); CDBG("gpio_array[%d] = %d", i, gpio_array[i]); } rc = msm_camera_get_dt_gpio_req_tbl(of_node, gconf, gpio_array, gpio_array_size); if (rc < 0) { pr_err("failed"); goto FREE_GPIO_CONF; } rc = msm_camera_init_gpio_pin_tbl(of_node, gconf, gpio_array, gpio_array_size); if (rc < 0) { pr_err("failed"); goto FREE_GPIO_REQ_TBL; } kfree(gpio_array); return rc; FREE_GPIO_REQ_TBL: kfree(sensordata->power_info.gpio_conf->cam_gpio_req_tbl); FREE_GPIO_CONF: kfree(sensordata->power_info.gpio_conf); kfree(gpio_array); return rc; } static int32_t msm_sensor_driver_get_dt_data(struct msm_sensor_ctrl_t *s_ctrl) { int32_t rc = 0; struct msm_camera_sensor_board_info *sensordata = NULL; struct device_node *of_node = s_ctrl->of_node; uint32_t cell_id; s_ctrl->sensordata = kzalloc(sizeof(*sensordata), GFP_KERNEL); if (!s_ctrl->sensordata) { pr_err("failed: no memory"); return -ENOMEM; } sensordata = s_ctrl->sensordata; rc = of_property_read_u32(of_node, "cell-index", &cell_id); if (rc < 0) { pr_err("failed: cell-index rc %d", rc); goto FREE_SENSOR_DATA; } s_ctrl->id = cell_id; if (cell_id >= MAX_CAMERAS) { pr_err("failed: invalid cell_id %d", cell_id); rc = -EINVAL; goto FREE_SENSOR_DATA; } if (g_sctrl[cell_id]) { pr_err("failed: sctrl already filled for cell_id %d", cell_id); rc = -EINVAL; goto FREE_SENSOR_DATA; } rc = msm_sensor_get_sub_module_index(of_node, &sensordata->sensor_info); if (rc < 0) { pr_err("failed"); goto FREE_SENSOR_DATA; } rc = msm_camera_get_dt_vreg_data(of_node, &sensordata->power_info.cam_vreg, &sensordata->power_info.num_vreg); if (rc < 0) { pr_err("failed: msm_camera_get_dt_vreg_data rc %d", rc); goto FREE_SUB_MODULE_DATA; } rc = msm_sensor_driver_get_gpio_data(sensordata, of_node); if (rc < 0) { pr_err("failed: msm_sensor_driver_get_gpio_data rc %d", rc); goto FREE_VREG_DATA; } rc = of_property_read_u32(of_node, "qcom,cci-master", &s_ctrl->cci_i2c_master); CDBG("qcom,cci-master %d, rc %d", s_ctrl->cci_i2c_master, rc); if (rc < 0) { s_ctrl->cci_i2c_master = MASTER_0; rc = 0; } if (0 > of_property_read_u32(of_node, "qcom,mount-angle", &sensordata->sensor_info->sensor_mount_angle)) { sensordata->sensor_info->is_mount_angle_valid = 0; sensordata->sensor_info->sensor_mount_angle = 0; } else { sensordata->sensor_info->is_mount_angle_valid = 1; } CDBG("%s qcom,mount-angle %d\n", __func__, sensordata->sensor_info->sensor_mount_angle); if (0 > of_property_read_u32(of_node, "qcom,sensor-position", &sensordata->sensor_info->position)) { CDBG("%s:%d Invalid sensor position\n", __func__, __LINE__); sensordata->sensor_info->position = INVALID_CAMERA_B; } if (0 > of_property_read_u32(of_node, "qcom,sensor-mode", &sensordata->sensor_info->modes_supported)) { CDBG("%s:%d Invalid sensor mode supported\n", __func__, __LINE__); sensordata->sensor_info->modes_supported = CAMERA_MODE_INVALID; } of_property_read_string(of_node, "qcom,vdd-cx-name", &sensordata->misc_regulator); CDBG("qcom,misc_regulator %s", sensordata->misc_regulator); s_ctrl->set_mclk_23880000 = of_property_read_bool(of_node, "qcom,mclk-23880000"); CDBG("%s qcom,mclk-23880000 = %d\n", __func__, s_ctrl->set_mclk_23880000); return rc; FREE_VREG_DATA: kfree(sensordata->power_info.cam_vreg); FREE_SUB_MODULE_DATA: kfree(sensordata->sensor_info); FREE_SENSOR_DATA: kfree(sensordata); return rc; } static int32_t msm_sensor_driver_parse(struct msm_sensor_ctrl_t *s_ctrl) { int32_t rc = 0; CDBG("Enter"); s_ctrl->sensor_i2c_client = kzalloc(sizeof(*s_ctrl->sensor_i2c_client), GFP_KERNEL); if (!s_ctrl->sensor_i2c_client) { pr_err("failed: no memory sensor_i2c_client %p", s_ctrl->sensor_i2c_client); return -ENOMEM; } s_ctrl->msm_sensor_mutex = kzalloc(sizeof(*s_ctrl->msm_sensor_mutex), GFP_KERNEL); if (!s_ctrl->msm_sensor_mutex) { pr_err("failed: no memory msm_sensor_mutex %p", s_ctrl->msm_sensor_mutex); goto FREE_SENSOR_I2C_CLIENT; } rc = msm_sensor_driver_get_dt_data(s_ctrl); if (rc < 0) { pr_err("failed: rc %d", rc); goto FREE_MUTEX; } mutex_init(s_ctrl->msm_sensor_mutex); s_ctrl->sensor_v4l2_subdev_info = msm_sensor_driver_subdev_info; s_ctrl->sensor_v4l2_subdev_info_size = ARRAY_SIZE(msm_sensor_driver_subdev_info); rc = msm_sensor_init_default_params(s_ctrl); if (rc < 0) { pr_err("failed: msm_sensor_init_default_params rc %d", rc); goto FREE_DT_DATA; } g_sctrl[s_ctrl->id] = s_ctrl; CDBG("g_sctrl[%d] %p", s_ctrl->id, g_sctrl[s_ctrl->id]); return rc; FREE_DT_DATA: kfree(s_ctrl->sensordata->power_info.gpio_conf->gpio_num_info); kfree(s_ctrl->sensordata->power_info.gpio_conf->cam_gpio_req_tbl); kfree(s_ctrl->sensordata->power_info.gpio_conf); kfree(s_ctrl->sensordata->power_info.cam_vreg); kfree(s_ctrl->sensordata); FREE_MUTEX: kfree(s_ctrl->msm_sensor_mutex); FREE_SENSOR_I2C_CLIENT: kfree(s_ctrl->sensor_i2c_client); return rc; } static int32_t msm_sensor_driver_platform_probe(struct platform_device *pdev) { int32_t rc = 0; struct msm_sensor_ctrl_t *s_ctrl = NULL; s_ctrl = kzalloc(sizeof(*s_ctrl), GFP_KERNEL); if (!s_ctrl) { pr_err("failed: no memory s_ctrl %p", s_ctrl); return -ENOMEM; } platform_set_drvdata(pdev, s_ctrl); s_ctrl->sensor_device_type = MSM_CAMERA_PLATFORM_DEVICE; s_ctrl->of_node = pdev->dev.of_node; rc = msm_sensor_driver_parse(s_ctrl); if (rc < 0) { pr_err("failed: msm_sensor_driver_parse rc %d", rc); goto FREE_S_CTRL; } pdev->id = s_ctrl->id; s_ctrl->pdev = pdev; s_ctrl->sensordata->power_info.dev = &pdev->dev; return rc; FREE_S_CTRL: kfree(s_ctrl); return rc; } static int32_t msm_sensor_driver_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id) { int32_t rc = 0; struct msm_sensor_ctrl_t *s_ctrl; CDBG("\n\nEnter: msm_sensor_driver_i2c_probe"); if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { pr_err("%s %s i2c_check_functionality failed\n", __func__, client->name); rc = -EFAULT; return rc; } s_ctrl = kzalloc(sizeof(*s_ctrl), GFP_KERNEL); if (!s_ctrl) { pr_err("failed: no memory s_ctrl %p", s_ctrl); return -ENOMEM; } i2c_set_clientdata(client, s_ctrl); s_ctrl->sensor_device_type = MSM_CAMERA_I2C_DEVICE; s_ctrl->of_node = client->dev.of_node; rc = msm_sensor_driver_parse(s_ctrl); if (rc < 0) { pr_err("failed: msm_sensor_driver_parse rc %d", rc); goto FREE_S_CTRL; } if (s_ctrl->sensor_i2c_client != NULL) { s_ctrl->sensor_i2c_client->client = client; s_ctrl->sensordata->power_info.dev = &client->dev; } return rc; FREE_S_CTRL: kfree(s_ctrl); return rc; } static int msm_sensor_driver_i2c_remove(struct i2c_client *client) { struct msm_sensor_ctrl_t *s_ctrl = i2c_get_clientdata(client); pr_err("%s: sensor FREE\n", __func__); if (!s_ctrl) { pr_err("%s: sensor device is NULL\n", __func__); return 0; } g_sctrl[s_ctrl->id] = NULL; msm_sensor_free_sensor_data(s_ctrl); kfree(s_ctrl->msm_sensor_mutex); kfree(s_ctrl->sensor_i2c_client); kfree(s_ctrl); return 0; } static const struct i2c_device_id i2c_id[] = { {SENSOR_DRIVER_I2C, (kernel_ulong_t)NULL}, { } }; static struct i2c_driver msm_sensor_driver_i2c = { .id_table = i2c_id, .probe = msm_sensor_driver_i2c_probe, .remove = msm_sensor_driver_i2c_remove, .driver = { .name = SENSOR_DRIVER_I2C, }, }; static int __init msm_sensor_driver_init(void) { int32_t rc = 0; CDBG("%s Enter\n", __func__); rc = platform_driver_register(&msm_sensor_platform_driver); if (rc) pr_err("%s platform_driver_register failed rc = %d", __func__, rc); rc = i2c_add_driver(&msm_sensor_driver_i2c); if (rc) pr_err("%s i2c_add_driver failed rc = %d", __func__, rc); return rc; } static void __exit msm_sensor_driver_exit(void) { CDBG("Enter"); platform_driver_unregister(&msm_sensor_platform_driver); i2c_del_driver(&msm_sensor_driver_i2c); return; } module_init(msm_sensor_driver_init); module_exit(msm_sensor_driver_exit); MODULE_DESCRIPTION("msm_sensor_driver"); MODULE_LICENSE("GPL v2");
MassStash/htc_pme_kernel_sense_6.0
drivers/media/platform/msm/camera_v2/sensor/msm_sensor_driver.c
C
gpl-2.0
42,551
# coding: utf-8 # Copyright 2014 Globo.com Player authors. All rights reserved. # Use of this source code is governed by a MIT License # license that can be found in the LICENSE file. from collections import namedtuple import os import errno import math try: import urlparse as url_parser except ImportError: import urllib.parse as url_parser import parser class M3U8(object): ''' Represents a single M3U8 playlist. Should be instantiated with the content as string. Parameters: `content` the m3u8 content as string `base_path` all urls (key and segments url) will be updated with this base_path, ex.: base_path = "http://videoserver.com/hls" /foo/bar/key.bin --> http://videoserver.com/hls/key.bin http://vid.com/segment1.ts --> http://videoserver.com/hls/segment1.ts can be passed as parameter or setted as an attribute to ``M3U8`` object. `base_uri` uri the playlist comes from. it is propagated to SegmentList and Key ex.: http://example.com/path/to Attributes: `key` it's a `Key` object, the EXT-X-KEY from m3u8. Or None `segments` a `SegmentList` object, represents the list of `Segment`s from this playlist `is_variant` Returns true if this M3U8 is a variant playlist, with links to other M3U8s with different bitrates. If true, `playlists` is a list of the playlists available, and `iframe_playlists` is a list of the i-frame playlists available. `is_endlist` Returns true if EXT-X-ENDLIST tag present in M3U8. http://tools.ietf.org/html/draft-pantos-http-live-streaming-07#section-3.3.8 `playlists` If this is a variant playlist (`is_variant` is True), returns a list of Playlist objects `iframe_playlists` If this is a variant playlist (`is_variant` is True), returns a list of IFramePlaylist objects `playlist_type` A lower-case string representing the type of the playlist, which can be one of VOD (video on demand) or EVENT. `media` If this is a variant playlist (`is_variant` is True), returns a list of Media objects `target_duration` Returns the EXT-X-TARGETDURATION as an integer http://tools.ietf.org/html/draft-pantos-http-live-streaming-07#section-3.3.2 `media_sequence` Returns the EXT-X-MEDIA-SEQUENCE as an integer http://tools.ietf.org/html/draft-pantos-http-live-streaming-07#section-3.3.3 `program_date_time` Returns the EXT-X-PROGRAM-DATE-TIME as a string http://tools.ietf.org/html/draft-pantos-http-live-streaming-07#section-3.3.5 `version` Return the EXT-X-VERSION as is `allow_cache` Return the EXT-X-ALLOW-CACHE as is `files` Returns an iterable with all files from playlist, in order. This includes segments and key uri, if present. `base_uri` It is a property (getter and setter) used by SegmentList and Key to have absolute URIs. `is_i_frames_only` Returns true if EXT-X-I-FRAMES-ONLY tag present in M3U8. http://tools.ietf.org/html/draft-pantos-http-live-streaming-07#section-3.3.12 `is_independent_segments` Returns true if EXT-X-INDEPENDENT-SEGMENTS tag present in M3U8. https://tools.ietf.org/html/draft-pantos-http-live-streaming-13#section-3.4.16 ''' simple_attributes = ( # obj attribute # parser attribute ('is_variant', 'is_variant'), ('is_endlist', 'is_endlist'), ('is_i_frames_only', 'is_i_frames_only'), ('target_duration', 'targetduration'), ('media_sequence', 'media_sequence'), ('program_date_time', 'program_date_time'), ('is_independent_segments', 'is_independent_segments'), ('version', 'version'), ('allow_cache', 'allow_cache'), ('playlist_type', 'playlist_type') ) def __init__(self, content=None, base_path=None, base_uri=None, strict=False): if content is not None: self.data = parser.parse(content, strict) else: self.data = {} self._base_uri = base_uri if self._base_uri: if not self._base_uri.endswith('/'): self._base_uri += '/' self._initialize_attributes() self.base_path = base_path def _initialize_attributes(self): self.key = Key(base_uri=self.base_uri, **self.data['key']) if 'key' in self.data else None self.segments = SegmentList([ Segment(base_uri=self.base_uri, **params) for params in self.data.get('segments', []) ]) for attr, param in self.simple_attributes: setattr(self, attr, self.data.get(param)) self.files = [] if self.key: self.files.append(self.key.uri) self.files.extend(self.segments.uri) self.media = MediaList([ Media(base_uri=self.base_uri, **media) for media in self.data.get('media', []) ]) self.playlists = PlaylistList([ Playlist(base_uri=self.base_uri, media=self.media, **playlist) for playlist in self.data.get('playlists', []) ]) self.iframe_playlists = PlaylistList() for ifr_pl in self.data.get('iframe_playlists', []): self.iframe_playlists.append( IFramePlaylist(base_uri=self.base_uri, uri=ifr_pl['uri'], iframe_stream_info=ifr_pl['iframe_stream_info']) ) def __unicode__(self): return self.dumps() @property def base_uri(self): return self._base_uri @base_uri.setter def base_uri(self, new_base_uri): self._base_uri = new_base_uri self.media.base_uri = new_base_uri self.playlists.base_uri = new_base_uri self.segments.base_uri = new_base_uri @property def base_path(self): return self._base_path @base_path.setter def base_path(self, newbase_path): self._base_path = newbase_path self._update_base_path() def _update_base_path(self): if self._base_path is None: return if self.key: self.key.base_path = self.base_path self.media.base_path = self.base_path self.segments.base_path = self.base_path self.playlists.base_path = self.base_path def add_playlist(self, playlist): self.is_variant = True self.playlists.append(playlist) def add_iframe_playlist(self, iframe_playlist): if iframe_playlist is not None: self.is_variant = True self.iframe_playlists.append(iframe_playlist) def add_media(self, media): self.media.append(media) def add_segment(self, segment): self.segments.append(segment) def dumps(self): ''' Returns the current m3u8 as a string. You could also use unicode(<this obj>) or str(<this obj>) ''' output = ['#EXTM3U'] if self.is_independent_segments: output.append('#EXT-X-INDEPENDENT-SEGMENTS') if self.media_sequence: output.append('#EXT-X-MEDIA-SEQUENCE:' + str(self.media_sequence)) if self.allow_cache: output.append('#EXT-X-ALLOW-CACHE:' + self.allow_cache.upper()) if self.version: output.append('#EXT-X-VERSION:' + self.version) if self.key: output.append(str(self.key)) if self.target_duration: output.append('#EXT-X-TARGETDURATION:' + int_or_float_to_string(self.target_duration)) if self.program_date_time is not None: output.append('#EXT-X-PROGRAM-DATE-TIME:' + parser.format_date_time(self.program_date_time)) if not (self.playlist_type is None or self.playlist_type == ''): output.append( '#EXT-X-PLAYLIST-TYPE:%s' % str(self.playlist_type).upper()) if self.is_i_frames_only: output.append('#EXT-X-I-FRAMES-ONLY') if self.is_variant: if self.media: output.append(str(self.media)) output.append(str(self.playlists)) if self.iframe_playlists: output.append(str(self.iframe_playlists)) output.append(str(self.segments)) if self.is_endlist: output.append('#EXT-X-ENDLIST') return '\n'.join(output) def dump(self, filename): ''' Saves the current m3u8 to ``filename`` ''' self._create_sub_directories(filename) with open(filename, 'w') as fileobj: fileobj.write(self.dumps()) def _create_sub_directories(self, filename): basename = os.path.dirname(filename) try: os.makedirs(basename) except OSError as error: if error.errno != errno.EEXIST: raise class BasePathMixin(object): @property def absolute_uri(self): if self.uri is None: return None if parser.is_url(self.uri): return self.uri else: if self.base_uri is None: raise ValueError('There can not be `absolute_uri` with no `base_uri` set') return _urijoin(self.base_uri, self.uri) @property def base_path(self): return os.path.dirname(self.uri) @base_path.setter def base_path(self, newbase_path): if not self.base_path: self.uri = "%s/%s" % (newbase_path, self.uri) self.uri = self.uri.replace(self.base_path, newbase_path) class GroupedBasePathMixin(object): def _set_base_uri(self, new_base_uri): for item in self: item.base_uri = new_base_uri base_uri = property(None, _set_base_uri) def _set_base_path(self, newbase_path): for item in self: item.base_path = newbase_path base_path = property(None, _set_base_path) class Segment(BasePathMixin): ''' A video segment from a M3U8 playlist `uri` a string with the segment uri `title` title attribute from EXTINF parameter `program_date_time` Returns the EXT-X-PROGRAM-DATE-TIME as a datetime http://tools.ietf.org/html/draft-pantos-http-live-streaming-07#section-3.3.5 `discontinuity` Returns a boolean indicating if a EXT-X-DISCONTINUITY tag exists http://tools.ietf.org/html/draft-pantos-http-live-streaming-13#section-3.4.11 `cue_out` Returns a boolean indicating if a EXT-X-CUE-OUT-CONT tag exists `duration` duration attribute from EXTINF parameter `base_uri` uri the key comes from in URI hierarchy. ex.: http://example.com/path/to `byterange` byterange attribute from EXT-X-BYTERANGE parameter `key` Key used to encrypt the segment (EXT-X-KEY) ''' def __init__(self, uri, base_uri, program_date_time=None, duration=None, title=None, byterange=None, cue_out=False, discontinuity=False, key=None): self.uri = uri self.duration = duration self.title = title self.base_uri = base_uri self.byterange = byterange self.program_date_time = program_date_time self.discontinuity = discontinuity self.cue_out = cue_out self.key = Key(base_uri=base_uri,**key) if key else None def dumps(self, last_segment): output = [] if last_segment and self.key != last_segment.key: output.append(str(self.key)) output.append('\n') if self.discontinuity: output.append('#EXT-X-DISCONTINUITY\n') if self.program_date_time: output.append('#EXT-X-PROGRAM-DATE-TIME:%s\n' % parser.format_date_time(self.program_date_time)) if self.cue_out: output.append('#EXT-X-CUE-OUT-CONT\n') output.append('#EXTINF:%s,' % int_or_float_to_string(self.duration)) if self.title: output.append(quoted(self.title)) output.append('\n') if self.byterange: output.append('#EXT-X-BYTERANGE:%s\n' % self.byterange) output.append(self.uri) return ''.join(output) def __str__(self): return self.dumps(None) class SegmentList(list, GroupedBasePathMixin): def __str__(self): output = [] last_segment = None for segment in self: output.append(segment.dumps(last_segment)) last_segment = segment return '\n'.join(output) @property def uri(self): return [seg.uri for seg in self] class Key(BasePathMixin): ''' Key used to encrypt the segments in a m3u8 playlist (EXT-X-KEY) `method` is a string. ex.: "AES-128" `uri` is a string. ex:: "https://priv.example.com/key.php?r=52" `base_uri` uri the key comes from in URI hierarchy. ex.: http://example.com/path/to `iv` initialization vector. a string representing a hexadecimal number. ex.: 0X12A ''' def __init__(self, method, uri, base_uri, iv=None, keyformat=None, keyformatversions=None): self.method = method self.uri = uri self.iv = iv self.keyformat = keyformat self.keyformatversions = keyformatversions self.base_uri = base_uri def __str__(self): output = [ 'METHOD=%s' % self.method, ] if self.uri: output.append('URI="%s"' % self.uri) if self.iv: output.append('IV=%s' % self.iv) if self.keyformat: output.append('KEYFORMAT="%s"' % self.keyformat) if self.keyformatversions: output.append('KEYFORMATVERSIONS="%s"' % self.keyformatversions) return '#EXT-X-KEY:' + ','.join(output) def __eq__(self, other): return self.method == other.method and \ self.uri == other.uri and \ self.iv == other.iv and \ self.base_uri == other.base_uri and \ self.keyformat == other.keyformat and \ self.keyformatversions == other.keyformatversions def __ne__(self, other): return not self.__eq__(other) class Playlist(BasePathMixin): ''' Playlist object representing a link to a variant M3U8 with a specific bitrate. Attributes: `stream_info` is a named tuple containing the attributes: `program_id`, `bandwidth`, `average_bandwidth`, `resolution`, `codecs` and `resolution` which is a a tuple (w, h) of integers `media` is a list of related Media entries. More info: http://tools.ietf.org/html/draft-pantos-http-live-streaming-07#section-3.3.10 ''' def __init__(self, uri, stream_info, media, base_uri): self.uri = uri self.base_uri = base_uri resolution = stream_info.get('resolution') if resolution != None: resolution = resolution.strip('"') values = resolution.split('x') resolution_pair = (int(values[0]), int(values[1])) else: resolution_pair = None self.stream_info = StreamInfo( bandwidth=stream_info['bandwidth'], average_bandwidth=stream_info.get('average_bandwidth'), program_id=stream_info.get('program_id'), resolution=resolution_pair, codecs=stream_info.get('codecs') ) self.media = [] for media_type in ('audio', 'video', 'subtitles'): group_id = stream_info.get(media_type) if not group_id: continue self.media += filter(lambda m: m.group_id == group_id, media) def __str__(self): stream_inf = [] if self.stream_info.program_id: stream_inf.append('PROGRAM-ID=%d' % self.stream_info.program_id) if self.stream_info.bandwidth: stream_inf.append('BANDWIDTH=%d' % self.stream_info.bandwidth) if self.stream_info.average_bandwidth: stream_inf.append('AVERAGE-BANDWIDTH=%d' % self.stream_info.average_bandwidth) if self.stream_info.resolution: res = str(self.stream_info.resolution[0]) + 'x' + str(self.stream_info.resolution[1]) stream_inf.append('RESOLUTION=' + res) if self.stream_info.codecs: stream_inf.append('CODECS=' + quoted(self.stream_info.codecs)) for media in self.media: media_type = media.type.upper() stream_inf.append('%s="%s"' % (media_type, media.group_id)) return '#EXT-X-STREAM-INF:' + ','.join(stream_inf) + '\n' + self.uri class IFramePlaylist(BasePathMixin): ''' IFramePlaylist object representing a link to a variant M3U8 i-frame playlist with a specific bitrate. Attributes: `iframe_stream_info` is a named tuple containing the attributes: `program_id`, `bandwidth`, `codecs` and `resolution` which is a tuple (w, h) of integers More info: http://tools.ietf.org/html/draft-pantos-http-live-streaming-07#section-3.3.13 ''' def __init__(self, base_uri, uri, iframe_stream_info): self.uri = uri self.base_uri = base_uri resolution = iframe_stream_info.get('resolution') if resolution is not None: values = resolution.split('x') resolution_pair = (int(values[0]), int(values[1])) else: resolution_pair = None self.iframe_stream_info = StreamInfo( bandwidth=iframe_stream_info.get('bandwidth'), average_bandwidth=None, program_id=iframe_stream_info.get('program_id'), resolution=resolution_pair, codecs=iframe_stream_info.get('codecs') ) def __str__(self): iframe_stream_inf = [] if self.iframe_stream_info.program_id: iframe_stream_inf.append('PROGRAM-ID=%d' % self.iframe_stream_info.program_id) if self.iframe_stream_info.bandwidth: iframe_stream_inf.append('BANDWIDTH=%d' % self.iframe_stream_info.bandwidth) if self.iframe_stream_info.resolution: res = (str(self.iframe_stream_info.resolution[0]) + 'x' + str(self.iframe_stream_info.resolution[1])) iframe_stream_inf.append('RESOLUTION=' + res) if self.iframe_stream_info.codecs: iframe_stream_inf.append('CODECS=' + quoted(self.iframe_stream_info.codecs)) if self.uri: iframe_stream_inf.append('URI=' + quoted(self.uri)) return '#EXT-X-I-FRAME-STREAM-INF:' + ','.join(iframe_stream_inf) StreamInfo = namedtuple( 'StreamInfo', ['bandwidth', 'average_bandwidth', 'program_id', 'resolution', 'codecs'] ) class Media(BasePathMixin): ''' A media object from a M3U8 playlist https://tools.ietf.org/html/draft-pantos-http-live-streaming-16#section-4.3.4.1 `uri` a string with the media uri `type` `group_id` `language` `assoc-language` `name` `default` `autoselect` `forced` `instream_id` `characteristics` attributes in the EXT-MEDIA tag `base_uri` uri the media comes from in URI hierarchy. ex.: http://example.com/path/to ''' def __init__(self, uri=None, type=None, group_id=None, language=None, name=None, default=None, autoselect=None, forced=None, characteristics=None, assoc_language=None, instream_id=None,base_uri=None, **extras): self.base_uri = base_uri self.uri = uri self.type = type self.group_id = group_id self.language = language self.name = name self.default = default self.autoselect = autoselect self.forced = forced self.assoc_language = assoc_language self.instream_id = instream_id self.characteristics = characteristics self.extras = extras def dumps(self): media_out = [] if self.uri: media_out.append('URI=' + quoted(self.uri)) if self.type: media_out.append('TYPE=' + self.type) if self.group_id: media_out.append('GROUP-ID=' + quoted(self.group_id)) if self.language: media_out.append('LANGUAGE=' + quoted(self.language)) if self.assoc_language: media_out.append('ASSOC-LANGUAGE=' + quoted(self.assoc_language)) if self.name: media_out.append('NAME=' + quoted(self.name)) if self.default: media_out.append('DEFAULT=' + self.default) if self.autoselect: media_out.append('AUTOSELECT=' + self.autoselect) if self.forced: media_out.append('FORCED=' + self.forced) if self.instream_id: media_out.append('INSTREAM-ID=' + self.instream_id) if self.characteristics: media_out.append('CHARACTERISTICS=' + quoted(self.characteristics)) return ('#EXT-X-MEDIA:' + ','.join(media_out)) def __str__(self): return self.dumps() class MediaList(list, GroupedBasePathMixin): def __str__(self): output = [str(playlist) for playlist in self] return '\n'.join(output) @property def uri(self): return [media.uri for media in self] class PlaylistList(list, GroupedBasePathMixin): def __str__(self): output = [str(playlist) for playlist in self] return '\n'.join(output) def denormalize_attribute(attribute): return attribute.replace('_','-').upper() def quoted(string): return '"%s"' % string def _urijoin(base_uri, path): if parser.is_url(base_uri): return url_parser.urljoin(base_uri, path) else: return os.path.normpath(os.path.join(base_uri, path.strip('/'))) def int_or_float_to_string(number): return str(int(number)) if number == math.floor(number) else str(number)
JaxxC/goodgame.xbmc
plugin.video.goodgame/resources/lib/m3u8/model.py
Python
gpl-2.0
22,352
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ /* * plugin-debug.c * * Debug plugin, for helping track down Conglomerate bugs * * Copyright (C) 2005 David Malcolm * * Conglomerate 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. * * Conglomerate is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * Authors: David Malcolm <david@davemalcolm.demon.co.uk> */ #include "global.h" #include "cong-plugin.h" #include "cong-primary-window.h" #include "cong-fake-plugin-hooks.h" #if ENABLE_DEBUG_PLUGIN static gboolean dump_area_tree_doc_filter (CongServiceDocTool *tool, CongDocument *doc, gpointer user_data) { /* Only available for documents using the editor widget */ CongPrimaryWindow *primary_window = cong_document_get_primary_window(doc); return primary_window->cong_editor_widget3 != NULL; } static void dump_area_tree_action_callback (CongServiceDocTool *tool, CongPrimaryWindow *primary_window, gpointer user_data) { CongEditorWidget3 *editor_widget; xmlDocPtr xml_doc; g_return_if_fail (primary_window); editor_widget = CONG_EDITOR_WIDGET3 (primary_window->cong_editor_widget3); xml_doc = cong_editor_widget_debug_dump_area_tree (editor_widget); cong_ui_new_document_from_manufactured_xml(xml_doc, cong_primary_window_get_toplevel (primary_window)); } #endif /* would be exposed as "plugin_register"? */ /** * plugin_debug_plugin_register: * @plugin: * * TODO: Write me * Returns: */ gboolean plugin_debug_plugin_register (CongPlugin *plugin) { g_return_val_if_fail (IS_CONG_PLUGIN (plugin), FALSE); #if ENABLE_DEBUG_PLUGIN cong_plugin_register_doc_tool(plugin, "Dump area tree", "Generates a debug dump of the CongEditorArea tree of the CongEditorWidget3 as another XML document.", "dump-area-tree", "Debug: _Dump Area Tree", NULL, NULL, dump_area_tree_doc_filter, dump_area_tree_action_callback, NULL); #endif return TRUE; } /* exposed as "plugin_configure"? legitimate for it not to be present */ /** * plugin_debug_plugin_configure: * @plugin: * * TODO: Write me * Returns: */ gboolean plugin_debug_plugin_configure (CongPlugin *plugin) { g_return_val_if_fail (IS_CONG_PLUGIN (plugin), FALSE); return TRUE; }
hpjansson/conglomerate
src/plugin-debug.c
C
gpl-2.0
2,892
/* Copyright (c) 2015-2016, 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. */ #include <linux/module.h> #include <linux/init.h> #include <linux/firmware.h> #include <linux/slab.h> #include <linux/platform_device.h> #include <linux/device.h> #include <linux/printk.h> #include <linux/ratelimit.h> #include <linux/debugfs.h> #include <linux/io.h> #include <linux/bitops.h> #include <linux/delay.h> #include <linux/pm_runtime.h> #include <linux/kernel.h> #include <linux/gpio.h> #include <linux/spmi.h> #include <linux/of_gpio.h> #include <linux/regulator/consumer.h> #include <linux/mfd/wcd9xxx/core.h> #include <linux/qdsp6v2/apr.h> #include <linux/timer.h> #include <linux/workqueue.h> #include <linux/sched.h> #include <sound/q6afe-v2.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/soc.h> #include <sound/soc-dapm.h> #include <sound/tlv.h> #include <sound/q6core.h> #include <soc/qcom/subsystem_notif.h> #include "msm8x16-wcd.h" #include "wcd-mbhc-v2.h" #include "msm8916-wcd-irq.h" #include "msm8x16_wcd_registers.h" #define MSM8X16_WCD_RATES (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000 |\ SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_48000) #define MSM8X16_WCD_FORMATS (SNDRV_PCM_FMTBIT_S16_LE |\ SNDRV_PCM_FMTBIT_S24_LE |\ SNDRV_PCM_FMTBIT_S24_3LE) #define NUM_INTERPOLATORS 3 #define BITS_PER_REG 8 #define MSM8X16_WCD_TX_PORT_NUMBER 4 #define MSM8X16_WCD_I2S_MASTER_MODE_MASK 0x08 #define MSM8X16_DIGITAL_CODEC_BASE_ADDR 0x771C000 #define TOMBAK_CORE_0_SPMI_ADDR 0xf000 #define TOMBAK_CORE_1_SPMI_ADDR 0xf100 #define PMIC_SLAVE_ID_0 0 #define PMIC_SLAVE_ID_1 1 #define PMIC_MBG_OK 0x2C08 #define PMIC_LDO7_EN_CTL 0x4646 #define MASK_MSB_BIT 0x80 #define CODEC_DT_MAX_PROP_SIZE 40 #define MSM8X16_DIGITAL_CODEC_REG_SIZE 0x400 #define MAX_ON_DEMAND_SUPPLY_NAME_LENGTH 64 #define MCLK_RATE_9P6MHZ 9600000 #define MCLK_RATE_12P288MHZ 12288000 #define BUS_DOWN 1 #define ADSP_STATE_READY_TIMEOUT_MS 50 #define HPHL_PA_DISABLE (0x01 << 1) #define HPHR_PA_DISABLE (0x01 << 2) #define EAR_PA_DISABLE (0x01 << 3) #define SPKR_PA_DISABLE (0x01 << 4) enum { BOOST_SWITCH = 0, BOOST_ALWAYS, BYPASS_ALWAYS, BOOST_ON_FOREVER, }; #define EAR_PMD 0 #define EAR_PMU 1 #define SPK_PMD 2 #define SPK_PMU 3 #define MICBIAS_DEFAULT_VAL 1800000 #define MICBIAS_MIN_VAL 1600000 #define MICBIAS_STEP_SIZE 50000 #define DEFAULT_BOOST_VOLTAGE 5000 #define MIN_BOOST_VOLTAGE 4000 #define MAX_BOOST_VOLTAGE 5550 #define BOOST_VOLTAGE_STEP 50 #define MSM8X16_WCD_MBHC_BTN_COARSE_ADJ 100 #define MSM8X16_WCD_MBHC_BTN_FINE_ADJ 12 #define VOLTAGE_CONVERTER(value, min_value, step_size)\ ((value - min_value)/step_size) enum { AIF1_PB = 0, AIF1_CAP, AIF2_VIFEED, NUM_CODEC_DAIS, }; enum { RX_MIX1_INP_SEL_ZERO = 0, RX_MIX1_INP_SEL_IIR1, RX_MIX1_INP_SEL_IIR2, RX_MIX1_INP_SEL_RX1, RX_MIX1_INP_SEL_RX2, RX_MIX1_INP_SEL_RX3, }; static const DECLARE_TLV_DB_SCALE(digital_gain, 0, 1, 0); static const DECLARE_TLV_DB_SCALE(analog_gain, 0, 25, 1); static struct snd_soc_dai_driver msm8x16_wcd_i2s_dai[]; static bool spkr_boost_en = true; #define MSM8X16_WCD_ACQUIRE_LOCK(x) \ mutex_lock_nested(&x, SINGLE_DEPTH_NESTING) #define MSM8X16_WCD_RELEASE_LOCK(x) mutex_unlock(&x) enum { IIR1 = 0, IIR2, IIR_MAX, }; enum { BAND1 = 0, BAND2, BAND3, BAND4, BAND5, BAND_MAX, }; struct hpf_work { struct msm8x16_wcd_priv *msm8x16_wcd; u32 decimator; u8 tx_hpf_cut_of_freq; struct delayed_work dwork; }; static struct hpf_work tx_hpf_work[NUM_DECIMATORS]; static char on_demand_supply_name[][MAX_ON_DEMAND_SUPPLY_NAME_LENGTH] = { "cdc-vdd-mic-bias", }; static unsigned long rx_digital_gain_reg[] = { MSM8X16_WCD_A_CDC_RX1_VOL_CTL_B2_CTL, MSM8X16_WCD_A_CDC_RX2_VOL_CTL_B2_CTL, MSM8X16_WCD_A_CDC_RX3_VOL_CTL_B2_CTL, }; static unsigned long tx_digital_gain_reg[] = { MSM8X16_WCD_A_CDC_TX1_VOL_CTL_GAIN, MSM8X16_WCD_A_CDC_TX2_VOL_CTL_GAIN, }; enum { MSM8X16_WCD_SPMI_DIGITAL = 0, MSM8X16_WCD_SPMI_ANALOG, MAX_MSM8X16_WCD_DEVICE }; static struct wcd_mbhc_register wcd_mbhc_registers[WCD_MBHC_REG_FUNC_MAX] = { WCD_MBHC_REGISTER("WCD_MBHC_L_DET_EN", MSM8X16_WCD_A_ANALOG_MBHC_DET_CTL_1, 0x80, 7, 0), WCD_MBHC_REGISTER("WCD_MBHC_GND_DET_EN", MSM8X16_WCD_A_ANALOG_MBHC_DET_CTL_1, 0x40, 6, 0), WCD_MBHC_REGISTER("WCD_MBHC_MECH_DETECTION_TYPE", MSM8X16_WCD_A_ANALOG_MBHC_DET_CTL_1, 0x20, 5, 0), WCD_MBHC_REGISTER("WCD_MBHC_MIC_CLAMP_CTL", MSM8X16_WCD_A_ANALOG_MBHC_DET_CTL_1, 0x18, 3, 0), WCD_MBHC_REGISTER("WCD_MBHC_ELECT_DETECTION_TYPE", MSM8X16_WCD_A_ANALOG_MBHC_DET_CTL_1, 0x01, 0, 0), WCD_MBHC_REGISTER("WCD_MBHC_HS_L_DET_PULL_UP_CTRL", MSM8X16_WCD_A_ANALOG_MBHC_DET_CTL_2, 0xC0, 6, 0), WCD_MBHC_REGISTER("WCD_MBHC_HS_L_DET_PULL_UP_COMP_CTRL", MSM8X16_WCD_A_ANALOG_MBHC_DET_CTL_2, 0x20, 5, 0), WCD_MBHC_REGISTER("WCD_MBHC_HPHL_PLUG_TYPE", MSM8X16_WCD_A_ANALOG_MBHC_DET_CTL_2, 0x10, 4, 0), WCD_MBHC_REGISTER("WCD_MBHC_GND_PLUG_TYPE", MSM8X16_WCD_A_ANALOG_MBHC_DET_CTL_2, 0x08, 3, 0), WCD_MBHC_REGISTER("WCD_MBHC_SW_HPH_LP_100K_TO_GND", MSM8X16_WCD_A_ANALOG_MBHC_DET_CTL_2, 0x01, 0, 0), WCD_MBHC_REGISTER("WCD_MBHC_ELECT_SCHMT_ISRC", MSM8X16_WCD_A_ANALOG_MBHC_DET_CTL_2, 0x06, 1, 0), WCD_MBHC_REGISTER("WCD_MBHC_FSM_EN", MSM8X16_WCD_A_ANALOG_MBHC_FSM_CTL, 0x80, 7, 0), WCD_MBHC_REGISTER("WCD_MBHC_INSREM_DBNC", MSM8X16_WCD_A_ANALOG_MBHC_DBNC_TIMER, 0xF0, 4, 0), WCD_MBHC_REGISTER("WCD_MBHC_BTN_DBNC", MSM8X16_WCD_A_ANALOG_MBHC_DBNC_TIMER, 0x0C, 2, 0), WCD_MBHC_REGISTER("WCD_MBHC_HS_VREF", MSM8X16_WCD_A_ANALOG_MBHC_BTN3_CTL, 0x03, 0, 0), WCD_MBHC_REGISTER("WCD_MBHC_HS_COMP_RESULT", MSM8X16_WCD_A_ANALOG_MBHC_ZDET_ELECT_RESULT, 0x01, 0, 0), WCD_MBHC_REGISTER("WCD_MBHC_MIC_SCHMT_RESULT", MSM8X16_WCD_A_ANALOG_MBHC_ZDET_ELECT_RESULT, 0x02, 1, 0), WCD_MBHC_REGISTER("WCD_MBHC_HPHL_SCHMT_RESULT", MSM8X16_WCD_A_ANALOG_MBHC_ZDET_ELECT_RESULT, 0x08, 3, 0), WCD_MBHC_REGISTER("WCD_MBHC_HPHR_SCHMT_RESULT", MSM8X16_WCD_A_ANALOG_MBHC_ZDET_ELECT_RESULT, 0x04, 2, 0), WCD_MBHC_REGISTER("WCD_MBHC_OCP_FSM_EN", MSM8X16_WCD_A_ANALOG_RX_COM_OCP_CTL, 0x10, 4, 0), WCD_MBHC_REGISTER("WCD_MBHC_BTN_RESULT", MSM8X16_WCD_A_ANALOG_MBHC_BTN_RESULT, 0xFF, 0, 0), WCD_MBHC_REGISTER("WCD_MBHC_BTN_ISRC_CTL", MSM8X16_WCD_A_ANALOG_MBHC_FSM_CTL, 0x70, 4, 0), WCD_MBHC_REGISTER("WCD_MBHC_ELECT_RESULT", MSM8X16_WCD_A_ANALOG_MBHC_ZDET_ELECT_RESULT, 0xFF, 0, 0), WCD_MBHC_REGISTER("WCD_MBHC_MICB_CTRL", MSM8X16_WCD_A_ANALOG_MICB_2_EN, 0xC0, 6, 0), WCD_MBHC_REGISTER("WCD_MBHC_HPH_CNP_WG_TIME", MSM8X16_WCD_A_ANALOG_RX_HPH_CNP_WG_TIME, 0xFC, 2, 0), WCD_MBHC_REGISTER("WCD_MBHC_HPHR_PA_EN", MSM8X16_WCD_A_ANALOG_RX_HPH_CNP_EN, 0x10, 4, 0), WCD_MBHC_REGISTER("WCD_MBHC_HPHL_PA_EN", MSM8X16_WCD_A_ANALOG_RX_HPH_CNP_EN, 0x20, 5, 0), WCD_MBHC_REGISTER("WCD_MBHC_HPH_PA_EN", MSM8X16_WCD_A_ANALOG_RX_HPH_CNP_EN, 0x30, 4, 0), WCD_MBHC_REGISTER("WCD_MBHC_SWCH_LEVEL_REMOVE", MSM8X16_WCD_A_ANALOG_MBHC_ZDET_ELECT_RESULT, 0x10, 4, 0), WCD_MBHC_REGISTER("WCD_MBHC_MOISTURE_VREF", 0, 0, 0, 0), WCD_MBHC_REGISTER("WCD_MBHC_PULLDOWN_CTRL", MSM8X16_WCD_A_ANALOG_MICB_2_EN, 0x20, 5, 0), }; struct msm8x16_wcd_spmi { struct spmi_device *spmi; int base; }; static const struct wcd_imped_i_ref imped_i_ref[] = { {I_h4_UA, 8, 800, 9000, 10000}, {I_pt5_UA, 10, 100, 990, 4600}, {I_14_UA, 17, 14, 1050, 700}, {I_l4_UA, 10, 4, 1165, 110}, {I_1_UA, 0, 1, 1200, 65}, }; static const struct wcd_mbhc_intr intr_ids = { .mbhc_sw_intr = MSM8X16_WCD_IRQ_MBHC_HS_DET, .mbhc_btn_press_intr = MSM8X16_WCD_IRQ_MBHC_PRESS, .mbhc_btn_release_intr = MSM8X16_WCD_IRQ_MBHC_RELEASE, .mbhc_hs_ins_intr = MSM8X16_WCD_IRQ_MBHC_INSREM_DET1, .mbhc_hs_rem_intr = MSM8X16_WCD_IRQ_MBHC_INSREM_DET, .hph_left_ocp = MSM8X16_WCD_IRQ_HPHL_OCP, .hph_right_ocp = MSM8X16_WCD_IRQ_HPHR_OCP, }; static int msm8x16_wcd_dt_parse_vreg_info(struct device *dev, struct msm8x16_wcd_regulator *vreg, const char *vreg_name, bool ondemand); static struct msm8x16_wcd_pdata *msm8x16_wcd_populate_dt_pdata( struct device *dev); static int msm8x16_wcd_enable_ext_mb_source(struct snd_soc_codec *codec, bool turn_on); static void msm8x16_trim_btn_reg(struct snd_soc_codec *codec); static void msm8x16_wcd_set_micb_v(struct snd_soc_codec *codec); static void msm8x16_wcd_set_boost_v(struct snd_soc_codec *codec); static void msm8x16_wcd_set_auto_zeroing(struct snd_soc_codec *codec, bool enable); static void msm8x16_wcd_configure_cap(struct snd_soc_codec *codec, bool micbias1, bool micbias2); static bool msm8x16_wcd_use_mb(struct snd_soc_codec *codec); struct msm8x16_wcd_spmi msm8x16_wcd_modules[MAX_MSM8X16_WCD_DEVICE]; static void *adsp_state_notifier; static struct snd_soc_codec *registered_codec; static int get_codec_version(struct msm8x16_wcd_priv *msm8x16_wcd) { if (msm8x16_wcd->codec_version == DIANGU) return DIANGU; else if (msm8x16_wcd->codec_version == CAJON_2_0) return CAJON_2_0; else if (msm8x16_wcd->codec_version == CAJON) return CAJON; else if (msm8x16_wcd->codec_version == CONGA) return CONGA; else if (msm8x16_wcd->pmic_rev == TOMBAK_2_0) return TOMBAK_2_0; else if (msm8x16_wcd->pmic_rev == TOMBAK_1_0) return TOMBAK_1_0; pr_err("%s: unsupported codec version\n", __func__); return UNSUPPORTED; } static void wcd_mbhc_meas_imped(struct snd_soc_codec *codec, s16 *impedance_l, s16 *impedance_r) { struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); if ((msm8x16_wcd->imped_det_pin == WCD_MBHC_DET_BOTH) || (msm8x16_wcd->imped_det_pin == WCD_MBHC_DET_HPHL)) { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_FSM_CTL, 0x08, 0x08); usleep_range(2000, 2100); *impedance_l = snd_soc_read(codec, MSM8X16_WCD_A_ANALOG_MBHC_BTN_RESULT); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_FSM_CTL, 0x08, 0x00); } if ((msm8x16_wcd->imped_det_pin == WCD_MBHC_DET_BOTH) || (msm8x16_wcd->imped_det_pin == WCD_MBHC_DET_HPHR)) { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_FSM_CTL, 0x04, 0x04); usleep_range(2000, 2100); *impedance_r = snd_soc_read(codec, MSM8X16_WCD_A_ANALOG_MBHC_BTN_RESULT); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_FSM_CTL, 0x04, 0x00); } } static void msm8x16_set_ref_current(struct snd_soc_codec *codec, enum wcd_curr_ref curr_ref) { struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); pr_debug("%s: curr_ref: %d\n", __func__, curr_ref); if (get_codec_version(msm8x16_wcd) < CAJON) pr_debug("%s: Setting ref current not required\n", __func__); msm8x16_wcd->imped_i_ref = imped_i_ref[curr_ref]; switch (curr_ref) { case I_h4_UA: snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MICB_2_EN, 0x07, 0x01); break; case I_pt5_UA: snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MICB_2_EN, 0x07, 0x04); break; case I_14_UA: snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MICB_2_EN, 0x07, 0x03); break; case I_l4_UA: snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MICB_2_EN, 0x07, 0x01); break; case I_1_UA: snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MICB_2_EN, 0x07, 0x00); break; default: pr_debug("%s: No ref current set\n", __func__); break; } } static bool msm8x16_adj_ref_current(struct snd_soc_codec *codec, s16 *impedance_l, s16 *impedance_r) { int i = 2; s16 compare_imp = 0; struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); if (msm8x16_wcd->imped_det_pin == WCD_MBHC_DET_HPHR) compare_imp = *impedance_r; else compare_imp = *impedance_l; if (get_codec_version(msm8x16_wcd) < CAJON) { pr_debug("%s: Reference current adjustment not required\n", __func__); return false; } while (compare_imp < imped_i_ref[i].min_val) { msm8x16_set_ref_current(codec, imped_i_ref[++i].curr_ref); wcd_mbhc_meas_imped(codec, impedance_l, impedance_r); compare_imp = (msm8x16_wcd->imped_det_pin == WCD_MBHC_DET_HPHR) ? *impedance_r : *impedance_l; if (i >= I_1_UA) break; } return true; } void msm8x16_wcd_spk_ext_pa_cb( int (*codec_spk_ext_pa)(struct snd_soc_codec *codec, int enable), struct snd_soc_codec *codec) { struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); pr_debug("%s: Enter\n", __func__); msm8x16_wcd->codec_spk_ext_pa_cb = codec_spk_ext_pa; } void msm8x16_wcd_hph_comp_cb( int (*codec_hph_comp_gpio)(bool enable), struct snd_soc_codec *codec) { struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); pr_debug("%s: Enter\n", __func__); msm8x16_wcd->codec_hph_comp_gpio = codec_hph_comp_gpio; } static void msm8x16_wcd_compute_impedance(struct snd_soc_codec *codec, s16 l, s16 r, uint32_t *zl, uint32_t *zr, bool high) { struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); uint32_t rl = 0, rr = 0; struct wcd_imped_i_ref R = msm8x16_wcd->imped_i_ref; int codec_ver = get_codec_version(msm8x16_wcd); switch (codec_ver) { case TOMBAK_1_0: case TOMBAK_2_0: case CONGA: if (high) { pr_debug("%s: This plug has high range impedance\n", __func__); rl = (uint32_t)(((100 * (l * 400 - 200))/96) - 230); rr = (uint32_t)(((100 * (r * 400 - 200))/96) - 230); } else { pr_debug("%s: This plug has low range impedance\n", __func__); rl = (uint32_t)(((1000 * (l * 2 - 1))/1165) - (13/10)); rr = (uint32_t)(((1000 * (r * 2 - 1))/1165) - (13/10)); } break; case CAJON: case CAJON_2_0: case DIANGU: if (msm8x16_wcd->imped_det_pin == WCD_MBHC_DET_HPHL) { rr = (uint32_t)(((DEFAULT_MULTIPLIER * (10 * r - 5)) - (DEFAULT_OFFSET * DEFAULT_GAIN))/DEFAULT_GAIN); rl = (uint32_t)(((10000 * (R.multiplier * (10 * l - 5))) - R.offset * R.gain_adj)/(R.gain_adj * 100)); } else if (msm8x16_wcd->imped_det_pin == WCD_MBHC_DET_HPHR) { rr = (uint32_t)(((10000 * (R.multiplier * (10 * r - 5))) - R.offset * R.gain_adj)/(R.gain_adj * 100)); rl = (uint32_t)(((DEFAULT_MULTIPLIER * (10 * l - 5))- (DEFAULT_OFFSET * DEFAULT_GAIN))/DEFAULT_GAIN); } else if (msm8x16_wcd->imped_det_pin == WCD_MBHC_DET_NONE) { rr = (uint32_t)(((DEFAULT_MULTIPLIER * (10 * r - 5)) - (DEFAULT_OFFSET * DEFAULT_GAIN))/DEFAULT_GAIN); rl = (uint32_t)(((DEFAULT_MULTIPLIER * (10 * l - 5))- (DEFAULT_OFFSET * DEFAULT_GAIN))/DEFAULT_GAIN); } else { rr = (uint32_t)(((10000 * (R.multiplier * (10 * r - 5))) - R.offset * R.gain_adj)/(R.gain_adj * 100)); rl = (uint32_t)(((10000 * (R.multiplier * (10 * l - 5))) - R.offset * R.gain_adj)/(R.gain_adj * 100)); } break; default: pr_debug("%s: No codec mentioned\n", __func__); break; } *zl = rl; *zr = rr; } static struct firmware_cal *msm8x16_wcd_get_hwdep_fw_cal( struct snd_soc_codec *codec, enum wcd_cal_type type) { struct msm8x16_wcd_priv *msm8x16_wcd; struct firmware_cal *hwdep_cal; if (!codec) { pr_err("%s: NULL codec pointer\n", __func__); return NULL; } msm8x16_wcd = snd_soc_codec_get_drvdata(codec); hwdep_cal = wcdcal_get_fw_cal(msm8x16_wcd->fw_data, type); if (!hwdep_cal) { dev_err(codec->dev, "%s: cal not sent by %d\n", __func__, type); return NULL; } return hwdep_cal; } static void wcd9xxx_spmi_irq_control(struct snd_soc_codec *codec, int irq, bool enable) { if (enable) wcd9xxx_spmi_enable_irq(irq); else wcd9xxx_spmi_disable_irq(irq); } static void msm8x16_mbhc_clk_setup(struct snd_soc_codec *codec, bool enable) { if (enable) snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 0x08, 0x08); else snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 0x08, 0x00); } static int msm8x16_mbhc_map_btn_code_to_num(struct snd_soc_codec *codec) { int btn_code; int btn; btn_code = snd_soc_read(codec, MSM8X16_WCD_A_ANALOG_MBHC_BTN_RESULT); switch (btn_code) { case 0: btn = 0; break; case 1: btn = 1; break; case 3: btn = 2; break; case 7: btn = 3; break; case 15: btn = 4; break; default: btn = -EINVAL; break; }; return btn; } static bool msm8x16_spmi_lock_sleep(struct wcd_mbhc *mbhc, bool lock) { if (lock) return wcd9xxx_spmi_lock_sleep(); wcd9xxx_spmi_unlock_sleep(); return 0; } static bool msm8x16_wcd_micb_en_status(struct wcd_mbhc *mbhc, int micb_num) { if (micb_num == MIC_BIAS_1) return (snd_soc_read(mbhc->codec, MSM8X16_WCD_A_ANALOG_MICB_1_EN) & 0x80); if (micb_num == MIC_BIAS_2) return (snd_soc_read(mbhc->codec, MSM8X16_WCD_A_ANALOG_MICB_2_EN) & 0x80); return false; } static void msm8x16_wcd_enable_master_bias(struct snd_soc_codec *codec, bool enable) { if (enable) snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MASTER_BIAS_CTL, 0x30, 0x30); else snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MASTER_BIAS_CTL, 0x30, 0x00); } static void msm8x16_wcd_mbhc_common_micb_ctrl(struct snd_soc_codec *codec, int event, bool enable) { u16 reg; u8 mask; u8 val; switch (event) { case MBHC_COMMON_MICB_PRECHARGE: reg = MSM8X16_WCD_A_ANALOG_MICB_1_CTL; mask = 0x60; val = (enable ? 0x60 : 0x00); break; case MBHC_COMMON_MICB_SET_VAL: reg = MSM8X16_WCD_A_ANALOG_MICB_1_VAL; mask = 0xFF; val = (enable ? 0xC0 : 0x00); break; case MBHC_COMMON_MICB_TAIL_CURR: reg = MSM8X16_WCD_A_ANALOG_MICB_1_EN; mask = 0x04; val = (enable ? 0x04 : 0x00); break; default: pr_err("%s: Invalid event received\n", __func__); return; }; snd_soc_update_bits(codec, reg, mask, val); } static void msm8x16_wcd_mbhc_internal_micbias_ctrl(struct snd_soc_codec *codec, int micbias_num, bool enable) { if (micbias_num == 1) { if (enable) snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MICB_1_INT_RBIAS, 0x10, 0x10); else snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MICB_1_INT_RBIAS, 0x10, 0x00); } } static bool msm8x16_wcd_mbhc_hph_pa_on_status(struct snd_soc_codec *codec) { return (snd_soc_read(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_CNP_EN) & 0x30) ? true : false; } static void msm8x16_wcd_mbhc_program_btn_thr(struct snd_soc_codec *codec, s16 *btn_low, s16 *btn_high, int num_btn, bool is_micbias) { int i; u32 course, fine, reg_val; u16 reg_addr = MSM8X16_WCD_A_ANALOG_MBHC_BTN0_ZDETL_CTL; s16 *btn_voltage; btn_voltage = ((is_micbias) ? btn_high : btn_low); for (i = 0; i < num_btn; i++) { course = (btn_voltage[i] / MSM8X16_WCD_MBHC_BTN_COARSE_ADJ); fine = ((btn_voltage[i] % MSM8X16_WCD_MBHC_BTN_COARSE_ADJ) / MSM8X16_WCD_MBHC_BTN_FINE_ADJ); reg_val = (course << 5) | (fine << 2); snd_soc_update_bits(codec, reg_addr, 0xFC, reg_val); pr_debug("%s: course: %d fine: %d reg_addr: %x reg_val: %x\n", __func__, course, fine, reg_addr, reg_val); reg_addr++; } } static void msm8x16_wcd_mbhc_calc_impedance(struct wcd_mbhc *mbhc, uint32_t *zl, uint32_t *zr) { struct snd_soc_codec *codec = mbhc->codec; struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); s16 impedance_l, impedance_r; s16 impedance_l_fixed; s16 reg0, reg1, reg2, reg3, reg4; bool high = false; bool min_range_used = false; WCD_MBHC_RSC_ASSERT_LOCKED(mbhc); reg0 = snd_soc_read(codec, MSM8X16_WCD_A_ANALOG_MBHC_DBNC_TIMER); reg1 = snd_soc_read(codec, MSM8X16_WCD_A_ANALOG_MBHC_BTN2_ZDETH_CTL); reg2 = snd_soc_read(codec, MSM8X16_WCD_A_ANALOG_MBHC_DET_CTL_2); reg3 = snd_soc_read(codec, MSM8X16_WCD_A_ANALOG_MICB_2_EN); reg4 = snd_soc_read(codec, MSM8X16_WCD_A_ANALOG_MBHC_FSM_CTL); msm8x16_wcd->imped_det_pin = WCD_MBHC_DET_BOTH; mbhc->hph_type = WCD_MBHC_HPH_NONE; snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_FSM_CTL, 0x80, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MICB_2_EN, 0xA5, 0x25); pr_debug("%s: Setup for impedance det\n", __func__); msm8x16_set_ref_current(codec, I_h4_UA); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_DET_CTL_2, 0x06, 0x02); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_DBNC_TIMER, 0x02, 0x02); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_BTN2_ZDETH_CTL, 0x02, 0x00); pr_debug("%s: Start performing impedance detection\n", __func__); wcd_mbhc_meas_imped(codec, &impedance_l, &impedance_r); if (impedance_l > 2 || impedance_r > 2) { high = true; if (!mbhc->mbhc_cfg->mono_stero_detection) { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_FSM_CTL, 0x02, 0x00); usleep_range(40000, 40100); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_BTN0_ZDETL_CTL, 0x03, 0x00); msm8x16_wcd->imped_det_pin = (impedance_l > 2 && impedance_r > 2) ? WCD_MBHC_DET_NONE : ((impedance_l > 2) ? WCD_MBHC_DET_HPHR : WCD_MBHC_DET_HPHL); if (msm8x16_wcd->imped_det_pin == WCD_MBHC_DET_NONE) goto exit; } else { if (get_codec_version(msm8x16_wcd) >= CAJON) { if (impedance_l == 63 && impedance_r == 63) { pr_debug("%s: HPHL and HPHR are floating\n", __func__); msm8x16_wcd->imped_det_pin = WCD_MBHC_DET_NONE; mbhc->hph_type = WCD_MBHC_HPH_NONE; } else if (impedance_l == 63 && impedance_r < 63) { pr_debug("%s: Mono HS with HPHL floating\n", __func__); msm8x16_wcd->imped_det_pin = WCD_MBHC_DET_HPHR; mbhc->hph_type = WCD_MBHC_HPH_MONO; } else if (impedance_r == 63 && impedance_l < 63) { pr_debug("%s: Mono HS with HPHR floating\n", __func__); msm8x16_wcd->imped_det_pin = WCD_MBHC_DET_HPHL; mbhc->hph_type = WCD_MBHC_HPH_MONO; } else if (impedance_l > 3 && impedance_r > 3 && (impedance_l == impedance_r)) { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_DET_CTL_2, 0x06, 0x06); wcd_mbhc_meas_imped(codec, &impedance_l, &impedance_r); if (impedance_r == impedance_l) pr_debug("%s: Mono Headset\n", __func__); msm8x16_wcd->imped_det_pin = WCD_MBHC_DET_NONE; mbhc->hph_type = WCD_MBHC_HPH_MONO; } else { pr_debug("%s: STEREO headset is found\n", __func__); msm8x16_wcd->imped_det_pin = WCD_MBHC_DET_BOTH; mbhc->hph_type = WCD_MBHC_HPH_STEREO; } } } } msm8x16_set_ref_current(codec, I_pt5_UA); msm8x16_set_ref_current(codec, I_14_UA); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_BTN0_ZDETL_CTL, 0x03, 0x03); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_FSM_CTL, 0x02, 0x02); usleep_range(50000, 50100); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_FSM_CTL, 0x01, 0x01); usleep_range(5000, 5100); wcd_mbhc_meas_imped(codec, &impedance_l, &impedance_r); min_range_used = msm8x16_adj_ref_current(codec, &impedance_l, &impedance_r); if (!mbhc->mbhc_cfg->mono_stero_detection) { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_FSM_CTL, 0x02, 0x00); usleep_range(40000, 40100); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_BTN0_ZDETL_CTL, 0x03, 0x00); goto exit; } if (!min_range_used || msm8x16_wcd->imped_det_pin == WCD_MBHC_DET_HPHL || msm8x16_wcd->imped_det_pin == WCD_MBHC_DET_HPHR) goto exit; snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_BTN0_ZDETL_CTL, 0x02, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_BTN1_ZDETM_CTL, 0x02, 0x02); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_FSM_CTL, 0x02, 0x00); usleep_range(40000, 40100); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_BTN0_ZDETL_CTL, 0x01, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_FSM_CTL, 0x08, 0x08); usleep_range(2000, 2100); impedance_l_fixed = snd_soc_read(codec, MSM8X16_WCD_A_ANALOG_MBHC_BTN_RESULT); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_FSM_CTL, 0x08, 0x00); if ((abs(impedance_l_fixed - impedance_l/2) * (impedance_l_fixed + impedance_l)) >= (abs(impedance_l_fixed - impedance_l) * (impedance_l_fixed + impedance_l/2))) { pr_debug("%s: STEREO plug type detected\n", __func__); mbhc->hph_type = WCD_MBHC_HPH_STEREO; } else { pr_debug("%s: MONO plug type detected\n", __func__); mbhc->hph_type = WCD_MBHC_HPH_MONO; impedance_l = impedance_l_fixed; } snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_FSM_CTL, 0x02, 0x02); usleep_range(10000, 10100); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_BTN0_ZDETL_CTL, 0x02, 0x02); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_BTN1_ZDETM_CTL, 0x02, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_FSM_CTL, 0x02, 0x00); usleep_range(40000, 40100); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MBHC_BTN0_ZDETL_CTL, 0x02, 0x00); exit: snd_soc_write(codec, MSM8X16_WCD_A_ANALOG_MBHC_FSM_CTL, reg4); snd_soc_write(codec, MSM8X16_WCD_A_ANALOG_MICB_2_EN, reg3); snd_soc_write(codec, MSM8X16_WCD_A_ANALOG_MBHC_BTN2_ZDETH_CTL, reg1); snd_soc_write(codec, MSM8X16_WCD_A_ANALOG_MBHC_DBNC_TIMER, reg0); snd_soc_write(codec, MSM8X16_WCD_A_ANALOG_MBHC_DET_CTL_2, reg2); msm8x16_wcd_compute_impedance(codec, impedance_l, impedance_r, zl, zr, high); pr_debug("%s: RL %d ohm, RR %d ohm\n", __func__, *zl, *zr); pr_debug("%s: Impedance detection completed\n", __func__); } static int msm8x16_register_notifier(struct snd_soc_codec *codec, struct notifier_block *nblock, bool enable) { struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); if (enable) return blocking_notifier_chain_register(&msm8x16_wcd->notifier, nblock); return blocking_notifier_chain_unregister( &msm8x16_wcd->notifier, nblock); } static int msm8x16_wcd_request_irq(struct snd_soc_codec *codec, int irq, irq_handler_t handler, const char *name, void *data) { return wcd9xxx_spmi_request_irq(irq, handler, name, data); } static int msm8x16_wcd_free_irq(struct snd_soc_codec *codec, int irq, void *data) { return wcd9xxx_spmi_free_irq(irq, data); } static const struct wcd_mbhc_cb mbhc_cb = { .enable_mb_source = msm8x16_wcd_enable_ext_mb_source, .trim_btn_reg = msm8x16_trim_btn_reg, .compute_impedance = msm8x16_wcd_mbhc_calc_impedance, .set_micbias_value = msm8x16_wcd_set_micb_v, .set_auto_zeroing = msm8x16_wcd_set_auto_zeroing, .get_hwdep_fw_cal = msm8x16_wcd_get_hwdep_fw_cal, .set_cap_mode = msm8x16_wcd_configure_cap, .register_notifier = msm8x16_register_notifier, .request_irq = msm8x16_wcd_request_irq, .irq_control = wcd9xxx_spmi_irq_control, .free_irq = msm8x16_wcd_free_irq, .clk_setup = msm8x16_mbhc_clk_setup, .map_btn_code_to_num = msm8x16_mbhc_map_btn_code_to_num, .lock_sleep = msm8x16_spmi_lock_sleep, .micbias_enable_status = msm8x16_wcd_micb_en_status, .mbhc_bias = msm8x16_wcd_enable_master_bias, .mbhc_common_micb_ctrl = msm8x16_wcd_mbhc_common_micb_ctrl, .micb_internal = msm8x16_wcd_mbhc_internal_micbias_ctrl, .hph_pa_on_status = msm8x16_wcd_mbhc_hph_pa_on_status, .set_btn_thr = msm8x16_wcd_mbhc_program_btn_thr, .extn_use_mb = msm8x16_wcd_use_mb, }; static const uint32_t wcd_imped_val[] = {4, 8, 12, 13, 16, 20, 24, 28, 32, 36, 40, 44, 48}; void msm8x16_notifier_call(struct snd_soc_codec *codec, const enum wcd_notify_event event) { struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); pr_debug("%s: notifier call event %d\n", __func__, event); blocking_notifier_call_chain(&msm8x16_wcd->notifier, event, &msm8x16_wcd->mbhc); } static int get_spmi_msm8x16_wcd_device_info(u16 *reg, struct msm8x16_wcd_spmi **msm8x16_wcd) { int rtn = 0; int value = ((*reg & 0x0f00) >> 8) & 0x000f; *reg = *reg - (value * 0x100); switch (value) { case 0: case 1: *msm8x16_wcd = &msm8x16_wcd_modules[value]; break; default: rtn = -EINVAL; break; } return rtn; } static int msm8x16_wcd_ahb_write_device(struct msm8x16_wcd *msm8x16_wcd, u16 reg, u8 *value, u32 bytes) { u32 temp = ((u32)(*value)) & 0x000000FF; u16 offset = (reg - 0x0200) & 0x03FF; bool q6_state = false; q6_state = q6core_is_adsp_ready(); if (q6_state != true) { pr_debug("%s: q6 not ready %d\n", __func__, q6_state); return 0; } pr_debug("%s: DSP is ready %d\n", __func__, q6_state); iowrite32(temp, msm8x16_wcd->dig_base + offset); return 0; } static int msm8x16_wcd_ahb_read_device(struct msm8x16_wcd *msm8x16_wcd, u16 reg, u32 bytes, u8 *value) { u32 temp; u16 offset = (reg - 0x0200) & 0x03FF; bool q6_state = false; q6_state = q6core_is_adsp_ready(); if (q6_state != true) { pr_debug("%s: q6 not ready %d\n", __func__, q6_state); return 0; } pr_debug("%s: DSP is ready %d\n", __func__, q6_state); temp = ioread32(msm8x16_wcd->dig_base + offset); *value = (u8)temp; return 0; } static int msm8x16_wcd_spmi_write_device(u16 reg, u8 *value, u32 bytes) { int ret; struct msm8x16_wcd_spmi *wcd = NULL; ret = get_spmi_msm8x16_wcd_device_info(&reg, &wcd); if (ret) { pr_err("%s: Invalid register address\n", __func__); return ret; } if (wcd == NULL) { pr_err("%s: Failed to get device info\n", __func__); return -ENODEV; } ret = spmi_ext_register_writel(wcd->spmi->ctrl, wcd->spmi->sid, wcd->base + reg, value, bytes); if (ret) pr_err_ratelimited("Unable to write to addr=%x, ret(%d)\n", reg, ret); if (ret != 0) { usleep_range(10, 11); ret = spmi_ext_register_writel(wcd->spmi->ctrl, wcd->spmi->sid, wcd->base + reg, value, 1); if (ret != 0) { pr_err_ratelimited("failed to write the device\n"); return ret; } } pr_debug("write sucess register = %x val = %x\n", reg, *value); return 0; } int msm8x16_wcd_spmi_read_device(u16 reg, u32 bytes, u8 *dest) { int ret = 0; struct msm8x16_wcd_spmi *wcd = NULL; ret = get_spmi_msm8x16_wcd_device_info(&reg, &wcd); if (ret) { pr_err("%s: Invalid register address\n", __func__); return ret; } if (wcd == NULL) { pr_err("%s: Failed to get device info\n", __func__); return -ENODEV; } ret = spmi_ext_register_readl(wcd->spmi->ctrl, wcd->spmi->sid, wcd->base + reg, dest, bytes); if (ret != 0) { pr_err("failed to read the device\n"); return ret; } pr_debug("%s: reg 0x%x = 0x%x\n", __func__, reg, *dest); return 0; } int msm8x16_wcd_spmi_read(unsigned short reg, int bytes, void *dest) { return msm8x16_wcd_spmi_read_device(reg, bytes, dest); } int msm8x16_wcd_spmi_write(unsigned short reg, int bytes, void *src) { return msm8x16_wcd_spmi_write_device(reg, src, bytes); } static int __msm8x16_wcd_reg_read(struct snd_soc_codec *codec, unsigned short reg) { int ret = -EINVAL; u8 temp = 0; struct msm8x16_wcd *msm8x16_wcd = codec->control_data; struct msm8916_asoc_mach_data *pdata = NULL; pr_debug("%s reg = %x\n", __func__, reg); mutex_lock(&msm8x16_wcd->io_lock); pdata = snd_soc_card_get_drvdata(codec->component.card); if (MSM8X16_WCD_IS_TOMBAK_REG(reg)) ret = msm8x16_wcd_spmi_read(reg, 1, &temp); else if (MSM8X16_WCD_IS_DIGITAL_REG(reg)) { mutex_lock(&pdata->cdc_mclk_mutex); if (atomic_read(&pdata->mclk_enabled) == false) { if (pdata->afe_clk_ver == AFE_CLK_VERSION_V1) { pdata->digital_cdc_clk.clk_val = pdata->mclk_freq; ret = afe_set_digital_codec_core_clock( AFE_PORT_ID_PRIMARY_MI2S_RX, &pdata->digital_cdc_clk); } else { pdata->digital_cdc_core_clk.enable = 1; ret = afe_set_lpass_clock_v2( AFE_PORT_ID_PRIMARY_MI2S_RX, &pdata->digital_cdc_core_clk); } if (ret < 0) { pr_err("failed to enable the MCLK\n"); goto err; } pr_debug("enabled digital codec core clk\n"); ret = msm8x16_wcd_ahb_read_device( msm8x16_wcd, reg, 1, &temp); atomic_set(&pdata->mclk_enabled, true); schedule_delayed_work(&pdata->disable_mclk_work, 50); err: mutex_unlock(&pdata->cdc_mclk_mutex); mutex_unlock(&msm8x16_wcd->io_lock); return temp; } ret = msm8x16_wcd_ahb_read_device(msm8x16_wcd, reg, 1, &temp); mutex_unlock(&pdata->cdc_mclk_mutex); } mutex_unlock(&msm8x16_wcd->io_lock); if (ret < 0) { dev_err_ratelimited(msm8x16_wcd->dev, "%s: codec read failed for reg 0x%x\n", __func__, reg); return ret; } dev_dbg(msm8x16_wcd->dev, "Read 0x%02x from 0x%x\n", temp, reg); return temp; } static int __msm8x16_wcd_reg_write(struct snd_soc_codec *codec, unsigned short reg, u8 val) { int ret = -EINVAL; struct msm8x16_wcd *msm8x16_wcd = codec->control_data; struct msm8916_asoc_mach_data *pdata = NULL; mutex_lock(&msm8x16_wcd->io_lock); pdata = snd_soc_card_get_drvdata(codec->component.card); if (MSM8X16_WCD_IS_TOMBAK_REG(reg)) ret = msm8x16_wcd_spmi_write(reg, 1, &val); else if (MSM8X16_WCD_IS_DIGITAL_REG(reg)) { mutex_lock(&pdata->cdc_mclk_mutex); if (atomic_read(&pdata->mclk_enabled) == false) { pr_debug("enable MCLK for AHB write\n"); if (pdata->afe_clk_ver == AFE_CLK_VERSION_V1) { pdata->digital_cdc_clk.clk_val = pdata->mclk_freq; ret = afe_set_digital_codec_core_clock( AFE_PORT_ID_PRIMARY_MI2S_RX, &pdata->digital_cdc_clk); } else { pdata->digital_cdc_core_clk.enable = 1; ret = afe_set_lpass_clock_v2( AFE_PORT_ID_PRIMARY_MI2S_RX, &pdata->digital_cdc_core_clk); } if (ret < 0) { pr_err("failed to enable the MCLK\n"); ret = 0; goto err; } pr_debug("enabled digital codec core clk\n"); ret = msm8x16_wcd_ahb_write_device( msm8x16_wcd, reg, &val, 1); atomic_set(&pdata->mclk_enabled, true); schedule_delayed_work(&pdata->disable_mclk_work, 50); err: mutex_unlock(&pdata->cdc_mclk_mutex); mutex_unlock(&msm8x16_wcd->io_lock); return ret; } ret = msm8x16_wcd_ahb_write_device(msm8x16_wcd, reg, &val, 1); mutex_unlock(&pdata->cdc_mclk_mutex); } mutex_unlock(&msm8x16_wcd->io_lock); return ret; } static int msm8x16_wcd_volatile(struct snd_soc_codec *codec, unsigned int reg) { dev_dbg(codec->dev, "%s: reg 0x%x\n", __func__, reg); return msm8x16_wcd_reg_readonly[reg]; } static int msm8x16_wcd_readable(struct snd_soc_codec *ssc, unsigned int reg) { return msm8x16_wcd_reg_readable[reg]; } static int msm8x16_wcd_write(struct snd_soc_codec *codec, unsigned int reg, unsigned int value) { int ret; struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s: Write from reg 0x%x val 0x%x\n", __func__, reg, value); if (reg == SND_SOC_NOPM) return 0; BUG_ON(reg > MSM8X16_WCD_MAX_REGISTER); if (!msm8x16_wcd_volatile(codec, reg)) { ret = snd_soc_cache_write(codec, reg, value); if (ret != 0) dev_err_ratelimited(codec->dev, "Cache write to %x failed: %d\n", reg, ret); } if (unlikely(test_bit(BUS_DOWN, &msm8x16_wcd->status_mask))) { pr_err_ratelimited("write 0x%02x while offline\n", reg); return -ENODEV; } return __msm8x16_wcd_reg_write(codec, reg, (u8)value); } static unsigned int msm8x16_wcd_read(struct snd_soc_codec *codec, unsigned int reg) { unsigned int val; int ret; struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); if (reg == SND_SOC_NOPM) return 0; BUG_ON(reg > MSM8X16_WCD_MAX_REGISTER); if (!msm8x16_wcd_volatile(codec, reg) && msm8x16_wcd_readable(codec, reg) && reg < codec->driver->reg_cache_size) { ret = snd_soc_cache_read(codec, reg, &val); if (ret >= 0) return val; dev_err_ratelimited(codec->dev, "Cache read from %x failed: %d\n", reg, ret); } if (unlikely(test_bit(BUS_DOWN, &msm8x16_wcd->status_mask))) { pr_err_ratelimited("write 0x%02x while offline\n", reg); return -ENODEV; } val = __msm8x16_wcd_reg_read(codec, reg); if ((reg == MSM8X16_WCD_A_DIGITAL_INT_EN_CLR) || (reg == MSM8X16_WCD_A_ANALOG_INT_EN_CLR)) val = 0; dev_dbg(codec->dev, "%s: Read from reg 0x%x val 0x%x\n", __func__, reg, val); return val; } static void msm8x16_wcd_boost_on(struct snd_soc_codec *codec) { int ret; u8 dest; struct msm8x16_wcd_spmi *wcd = &msm8x16_wcd_modules[0]; struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); ret = spmi_ext_register_readl(wcd->spmi->ctrl, PMIC_SLAVE_ID_1, PMIC_LDO7_EN_CTL, &dest, 1); if (ret != 0) { pr_err("%s: failed to read the device:%d\n", __func__, ret); return; } pr_debug("%s: LDO state: 0x%x\n", __func__, dest); if ((dest & MASK_MSB_BIT) == 0) { pr_err("LDO7 not enabled return!\n"); return; } ret = spmi_ext_register_readl(wcd->spmi->ctrl, PMIC_SLAVE_ID_0, PMIC_MBG_OK, &dest, 1); if (ret != 0) { pr_err("%s: failed to read the device:%d\n", __func__, ret); return; } pr_debug("%s: PMIC BG state: 0x%x\n", __func__, dest); if ((dest & MASK_MSB_BIT) == 0) { pr_err("PMIC MBG not ON, enable codec hw_en MB bit again\n"); snd_soc_write(codec, MSM8X16_WCD_A_ANALOG_MASTER_BIAS_CTL, 0x30); usleep_range(CODEC_DELAY_1_MS, CODEC_DELAY_1_1_MS); ret = spmi_ext_register_readl(wcd->spmi->ctrl, PMIC_SLAVE_ID_0, PMIC_MBG_OK, &dest, 1); if (ret != 0) { pr_err("%s: failed to read the device:%d\n", __func__, ret); return; } if ((dest & MASK_MSB_BIT) == 0) { pr_err("PMIC MBG still not ON after retry return!\n"); return; } } snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_PERPH_RESET_CTL3, 0x0F, 0x0F); snd_soc_write(codec, MSM8X16_WCD_A_ANALOG_SEC_ACCESS, 0xA5); snd_soc_write(codec, MSM8X16_WCD_A_ANALOG_PERPH_RESET_CTL3, 0x0F); snd_soc_write(codec, MSM8X16_WCD_A_ANALOG_MASTER_BIAS_CTL, 0x30); if (get_codec_version(msm8x16_wcd) < CAJON_2_0) { snd_soc_write(codec, MSM8X16_WCD_A_ANALOG_CURRENT_LIMIT, 0x82); } else { snd_soc_write(codec, MSM8X16_WCD_A_ANALOG_CURRENT_LIMIT, 0xA2); } snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SPKR_DRV_CTL, 0x69, 0x69); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SPKR_DRV_DBG, 0x01, 0x01); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SLOPE_COMP_IP_ZERO, 0x88, 0x88); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SPKR_DAC_CTL, 0x03, 0x03); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SPKR_OCP_CTL, 0xE1, 0xE1); if (get_codec_version(msm8x16_wcd) < CAJON_2_0) { snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 0x20, 0x20); usleep_range(CODEC_DELAY_1_MS, CODEC_DELAY_1_1_MS); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_BOOST_EN_CTL, 0xDF, 0xDF); usleep_range(CODEC_DELAY_1_MS, CODEC_DELAY_1_1_MS); } else { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_BOOST_EN_CTL, 0x40, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 0x20, 0x20); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_BOOST_EN_CTL, 0x80, 0x80); usleep_range(500, 510); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_BOOST_EN_CTL, 0x40, 0x40); usleep_range(500, 510); } } static void msm8x16_wcd_boost_off(struct snd_soc_codec *codec) { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_BOOST_EN_CTL, 0xDF, 0x5F); snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 0x20, 0x00); } static void msm8x16_wcd_bypass_on(struct snd_soc_codec *codec) { struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); if (get_codec_version(msm8x16_wcd) < CAJON_2_0) { snd_soc_write(codec, MSM8X16_WCD_A_ANALOG_SEC_ACCESS, 0xA5); snd_soc_write(codec, MSM8X16_WCD_A_ANALOG_PERPH_RESET_CTL3, 0x07); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_BYPASS_MODE, 0x02, 0x02); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_BYPASS_MODE, 0x01, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_BYPASS_MODE, 0x40, 0x40); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_BYPASS_MODE, 0x80, 0x80); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_BOOST_EN_CTL, 0xDF, 0xDF); } else { snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 0x20, 0x20); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_BYPASS_MODE, 0x20, 0x20); } } static void msm8x16_wcd_bypass_off(struct snd_soc_codec *codec) { struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); if (get_codec_version(msm8x16_wcd) < CAJON_2_0) { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_BOOST_EN_CTL, 0x80, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_BYPASS_MODE, 0x80, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_BYPASS_MODE, 0x02, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_BYPASS_MODE, 0x40, 0x00); } else { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_BYPASS_MODE, 0x20, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 0x20, 0x00); } } static void msm8x16_wcd_boost_mode_sequence(struct snd_soc_codec *codec, int flag) { struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); if (flag == EAR_PMU) { switch (msm8x16_wcd->boost_option) { case BOOST_SWITCH: if (msm8x16_wcd->ear_pa_boost_set) { msm8x16_wcd_boost_off(codec); msm8x16_wcd_bypass_on(codec); } break; case BOOST_ALWAYS: msm8x16_wcd_boost_on(codec); break; case BYPASS_ALWAYS: msm8x16_wcd_bypass_on(codec); break; case BOOST_ON_FOREVER: msm8x16_wcd_boost_on(codec); break; default: pr_err("%s: invalid boost option: %d\n", __func__, msm8x16_wcd->boost_option); break; } } else if (flag == EAR_PMD) { switch (msm8x16_wcd->boost_option) { case BOOST_SWITCH: if (msm8x16_wcd->ear_pa_boost_set) msm8x16_wcd_bypass_off(codec); break; case BOOST_ALWAYS: msm8x16_wcd_boost_off(codec); msleep(80); break; case BYPASS_ALWAYS: break; case BOOST_ON_FOREVER: break; default: pr_err("%s: invalid boost option: %d\n", __func__, msm8x16_wcd->boost_option); break; } } else if (flag == SPK_PMU) { switch (msm8x16_wcd->boost_option) { case BOOST_SWITCH: if (msm8x16_wcd->spk_boost_set) { msm8x16_wcd_bypass_off(codec); msm8x16_wcd_boost_on(codec); } break; case BOOST_ALWAYS: msm8x16_wcd_boost_on(codec); break; case BYPASS_ALWAYS: msm8x16_wcd_bypass_on(codec); break; case BOOST_ON_FOREVER: msm8x16_wcd_boost_on(codec); break; default: pr_err("%s: invalid boost option: %d\n", __func__, msm8x16_wcd->boost_option); break; } } else if (flag == SPK_PMD) { switch (msm8x16_wcd->boost_option) { case BOOST_SWITCH: if (msm8x16_wcd->spk_boost_set) { msm8x16_wcd_boost_off(codec); msleep(40); } break; case BOOST_ALWAYS: msm8x16_wcd_boost_off(codec); msleep(40); break; case BYPASS_ALWAYS: break; case BOOST_ON_FOREVER: break; default: pr_err("%s: invalid boost option: %d\n", __func__, msm8x16_wcd->boost_option); break; } } } static int msm8x16_wcd_dt_parse_vreg_info(struct device *dev, struct msm8x16_wcd_regulator *vreg, const char *vreg_name, bool ondemand) { int len, ret = 0; const __be32 *prop; char prop_name[CODEC_DT_MAX_PROP_SIZE]; struct device_node *regnode = NULL; u32 prop_val; snprintf(prop_name, CODEC_DT_MAX_PROP_SIZE, "%s-supply", vreg_name); regnode = of_parse_phandle(dev->of_node, prop_name, 0); if (!regnode) { dev_err(dev, "Looking up %s property in node %s failed\n", prop_name, dev->of_node->full_name); return -ENODEV; } dev_dbg(dev, "Looking up %s property in node %s\n", prop_name, dev->of_node->full_name); vreg->name = vreg_name; vreg->ondemand = ondemand; snprintf(prop_name, CODEC_DT_MAX_PROP_SIZE, "qcom,%s-voltage", vreg_name); prop = of_get_property(dev->of_node, prop_name, &len); if (!prop || (len != (2 * sizeof(__be32)))) { dev_err(dev, "%s %s property\n", prop ? "invalid format" : "no", prop_name); return -EINVAL; } vreg->min_uv = be32_to_cpup(&prop[0]); vreg->max_uv = be32_to_cpup(&prop[1]); snprintf(prop_name, CODEC_DT_MAX_PROP_SIZE, "qcom,%s-current", vreg_name); ret = of_property_read_u32(dev->of_node, prop_name, &prop_val); if (ret) { dev_err(dev, "Looking up %s property in node %s failed", prop_name, dev->of_node->full_name); return -EFAULT; } vreg->optimum_ua = prop_val; dev_dbg(dev, "%s: vol=[%d %d]uV, curr=[%d]uA, ond %d\n\n", vreg->name, vreg->min_uv, vreg->max_uv, vreg->optimum_ua, vreg->ondemand); return 0; } static void msm8x16_wcd_dt_parse_boost_info(struct snd_soc_codec *codec) { struct msm8x16_wcd_priv *msm8x16_wcd_priv = snd_soc_codec_get_drvdata(codec); const char *prop_name = "qcom,cdc-boost-voltage"; int boost_voltage, ret; ret = of_property_read_u32(codec->dev->of_node, prop_name, &boost_voltage); if (ret) { dev_dbg(codec->dev, "Looking up %s property in node %s failed\n", prop_name, codec->dev->of_node->full_name); boost_voltage = DEFAULT_BOOST_VOLTAGE; } if (boost_voltage < MIN_BOOST_VOLTAGE || boost_voltage > MAX_BOOST_VOLTAGE) { dev_err(codec->dev, "Incorrect boost voltage. Reverting to default\n"); boost_voltage = DEFAULT_BOOST_VOLTAGE; } msm8x16_wcd_priv->boost_voltage = VOLTAGE_CONVERTER(boost_voltage, MIN_BOOST_VOLTAGE, BOOST_VOLTAGE_STEP); dev_dbg(codec->dev, "Boost voltage value is: %d\n", boost_voltage); } static void msm8x16_wcd_dt_parse_micbias_info(struct device *dev, struct wcd9xxx_micbias_setting *micbias) { const char *prop_name = "qcom,cdc-micbias-cfilt-mv"; int ret; ret = of_property_read_u32(dev->of_node, prop_name, &micbias->cfilt1_mv); if (ret) { dev_dbg(dev, "Looking up %s property in node %s failed", prop_name, dev->of_node->full_name); micbias->cfilt1_mv = MICBIAS_DEFAULT_VAL; } } static struct msm8x16_wcd_pdata *msm8x16_wcd_populate_dt_pdata( struct device *dev) { struct msm8x16_wcd_pdata *pdata; int ret, static_cnt, ond_cnt, idx, i; const char *name = NULL; const char *static_prop_name = "qcom,cdc-static-supplies"; const char *ond_prop_name = "qcom,cdc-on-demand-supplies"; const char *addr_prop_name = "qcom,dig-cdc-base-addr"; pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL); if (!pdata) return NULL; static_cnt = of_property_count_strings(dev->of_node, static_prop_name); if (IS_ERR_VALUE(static_cnt)) { dev_err(dev, "%s: Failed to get static supplies %d\n", __func__, static_cnt); ret = -EINVAL; goto err; } ond_cnt = of_property_count_strings(dev->of_node, ond_prop_name); if (IS_ERR_VALUE(ond_cnt)) ond_cnt = 0; BUG_ON(static_cnt <= 0 || ond_cnt < 0); if ((static_cnt + ond_cnt) > ARRAY_SIZE(pdata->regulator)) { dev_err(dev, "%s: Num of supplies %u > max supported %zd\n", __func__, (static_cnt + ond_cnt), ARRAY_SIZE(pdata->regulator)); ret = -EINVAL; goto err; } for (idx = 0; idx < static_cnt; idx++) { ret = of_property_read_string_index(dev->of_node, static_prop_name, idx, &name); if (ret) { dev_err(dev, "%s: of read string %s idx %d error %d\n", __func__, static_prop_name, idx, ret); goto err; } dev_dbg(dev, "%s: Found static cdc supply %s\n", __func__, name); ret = msm8x16_wcd_dt_parse_vreg_info(dev, &pdata->regulator[idx], name, false); if (ret) { dev_err(dev, "%s:err parsing vreg for %s idx %d\n", __func__, name, idx); goto err; } } for (i = 0; i < ond_cnt; i++, idx++) { ret = of_property_read_string_index(dev->of_node, ond_prop_name, i, &name); if (ret) { dev_err(dev, "%s: err parsing on_demand for %s idx %d\n", __func__, ond_prop_name, i); goto err; } dev_dbg(dev, "%s: Found on-demand cdc supply %s\n", __func__, name); ret = msm8x16_wcd_dt_parse_vreg_info(dev, &pdata->regulator[idx], name, true); if (ret) { dev_err(dev, "%s: err parsing vreg on_demand for %s idx %d\n", __func__, name, idx); goto err; } } msm8x16_wcd_dt_parse_micbias_info(dev, &pdata->micbias); ret = of_property_read_u32(dev->of_node, addr_prop_name, &pdata->dig_cdc_addr); if (ret) { dev_dbg(dev, "%s: could not find %s entry in dt\n", __func__, addr_prop_name); pdata->dig_cdc_addr = MSM8X16_DIGITAL_CODEC_BASE_ADDR; } return pdata; err: devm_kfree(dev, pdata); dev_err(dev, "%s: Failed to populate DT data ret = %d\n", __func__, ret); return NULL; } static int msm8x16_wcd_codec_enable_on_demand_supply( struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { int ret = 0; struct snd_soc_codec *codec = w->codec; struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); struct on_demand_supply *supply; if (w->shift >= ON_DEMAND_SUPPLIES_MAX) { dev_err(codec->dev, "%s: error index > MAX Demand supplies", __func__); ret = -EINVAL; goto out; } dev_dbg(codec->dev, "%s: supply: %s event: %d ref: %d\n", __func__, on_demand_supply_name[w->shift], event, atomic_read(&msm8x16_wcd->on_demand_list[w->shift].ref)); supply = &msm8x16_wcd->on_demand_list[w->shift]; WARN_ONCE(!supply->supply, "%s isn't defined\n", on_demand_supply_name[w->shift]); if (!supply->supply) { dev_err(codec->dev, "%s: err supply not present ond for %d", __func__, w->shift); goto out; } switch (event) { case SND_SOC_DAPM_PRE_PMU: if (atomic_inc_return(&supply->ref) == 1) ret = regulator_enable(supply->supply); if (ret) dev_err(codec->dev, "%s: Failed to enable %s\n", __func__, on_demand_supply_name[w->shift]); break; case SND_SOC_DAPM_POST_PMD: if (atomic_read(&supply->ref) == 0) { dev_dbg(codec->dev, "%s: %s supply has been disabled.\n", __func__, on_demand_supply_name[w->shift]); goto out; } if (atomic_dec_return(&supply->ref) == 0) ret = regulator_disable(supply->supply); if (ret) dev_err(codec->dev, "%s: Failed to disable %s\n", __func__, on_demand_supply_name[w->shift]); break; default: break; } out: return ret; } static int msm8x16_wcd_codec_enable_clock_block(struct snd_soc_codec *codec, int enable) { struct msm8916_asoc_mach_data *pdata = NULL; pdata = snd_soc_card_get_drvdata(codec->component.card); if (enable) { snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_CLK_MCLK_CTL, 0x01, 0x01); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_CLK_PDM_CTL, 0x03, 0x03); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MASTER_BIAS_CTL, 0x30, 0x30); snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_RST_CTL, 0x80, 0x80); snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_TOP_CLK_CTL, 0x0C, 0x0C); if (pdata->mclk_freq == MCLK_RATE_12P288MHZ) snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_TOP_CTL, 0x01, 0x00); else if (pdata->mclk_freq == MCLK_RATE_9P6MHZ) snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_TOP_CTL, 0x01, 0x01); } else { snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_TOP_CLK_CTL, 0x0C, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_CLK_PDM_CTL, 0x03, 0x00); } return 0; } static int msm8x16_wcd_codec_enable_charge_pump(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s: event = %d\n", __func__, event); switch (event) { case SND_SOC_DAPM_PRE_PMU: msm8x16_wcd_codec_enable_clock_block(codec, 1); if (!(strcmp(w->name, "EAR CP"))) { snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 0x80, 0x80); msm8x16_wcd_boost_mode_sequence(codec, EAR_PMU); } else if (get_codec_version(msm8x16_wcd) == DIANGU) { snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 0x80, 0x80); } else { snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 0xC0, 0xC0); } break; case SND_SOC_DAPM_POST_PMU: usleep_range(CODEC_DELAY_1_MS, CODEC_DELAY_1_1_MS); break; case SND_SOC_DAPM_POST_PMD: usleep_range(CODEC_DELAY_1_MS, CODEC_DELAY_1_1_MS); if (!(strcmp(w->name, "EAR CP"))) { snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 0x80, 0x00); if (msm8x16_wcd->boost_option != BOOST_ALWAYS) { dev_dbg(codec->dev, "%s: boost_option:%d, tear down ear\n", __func__, msm8x16_wcd->boost_option); msm8x16_wcd_boost_mode_sequence(codec, EAR_PMD); } snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_EAR_CTL, 0x80, 0x00); } else { if (get_codec_version(msm8x16_wcd) < DIANGU) snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 0x40, 0x00); if (msm8x16_wcd->rx_bias_count == 0) snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 0x80, 0x00); dev_dbg(codec->dev, "%s: rx_bias_count = %d\n", __func__, msm8x16_wcd->rx_bias_count); } break; } return 0; } static int msm8x16_wcd_ear_pa_boost_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol); struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); ucontrol->value.integer.value[0] = (msm8x16_wcd->ear_pa_boost_set ? 1 : 0); dev_dbg(codec->dev, "%s: msm8x16_wcd->ear_pa_boost_set = %d\n", __func__, msm8x16_wcd->ear_pa_boost_set); return 0; } static int msm8x16_wcd_ear_pa_boost_set(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol); struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s: ucontrol->value.integer.value[0] = %ld\n", __func__, ucontrol->value.integer.value[0]); msm8x16_wcd->ear_pa_boost_set = (ucontrol->value.integer.value[0] ? true : false); return 0; } static int msm8x16_wcd_pa_gain_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { u8 ear_pa_gain; struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol); ear_pa_gain = snd_soc_read(codec, MSM8X16_WCD_A_ANALOG_RX_EAR_CTL); ear_pa_gain = (ear_pa_gain >> 5) & 0x1; if (ear_pa_gain == 0x00) { ucontrol->value.integer.value[0] = 0; } else if (ear_pa_gain == 0x01) { ucontrol->value.integer.value[0] = 1; } else { dev_err(codec->dev, "%s: ERROR: Unsupported Ear Gain = 0x%x\n", __func__, ear_pa_gain); return -EINVAL; } ucontrol->value.integer.value[0] = ear_pa_gain; dev_dbg(codec->dev, "%s: ear_pa_gain = 0x%x\n", __func__, ear_pa_gain); return 0; } static int msm8x16_wcd_loopback_mode_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol); struct msm8916_asoc_mach_data *pdata = NULL; pdata = snd_soc_card_get_drvdata(codec->component.card); dev_dbg(codec->dev, "%s: ucontrol->value.integer.value[0] = %ld\n", __func__, ucontrol->value.integer.value[0]); return pdata->lb_mode; } static int msm8x16_wcd_loopback_mode_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol); struct msm8916_asoc_mach_data *pdata = NULL; pdata = snd_soc_card_get_drvdata(codec->component.card); dev_dbg(codec->dev, "%s: ucontrol->value.integer.value[0] = %ld\n", __func__, ucontrol->value.integer.value[0]); switch (ucontrol->value.integer.value[0]) { case 0: pdata->lb_mode = false; break; case 1: pdata->lb_mode = true; break; default: return -EINVAL; } return 0; } static int msm8x16_wcd_pa_gain_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { u8 ear_pa_gain; struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol); dev_dbg(codec->dev, "%s: ucontrol->value.integer.value[0] = %ld\n", __func__, ucontrol->value.integer.value[0]); switch (ucontrol->value.integer.value[0]) { case 0: ear_pa_gain = 0x00; break; case 1: ear_pa_gain = 0x20; break; default: return -EINVAL; } snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_EAR_CTL, 0x20, ear_pa_gain); return 0; } static int msm8x16_wcd_hph_mode_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol); struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); if (msm8x16_wcd->hph_mode == NORMAL_MODE) { ucontrol->value.integer.value[0] = 0; } else if (msm8x16_wcd->hph_mode == HD2_MODE) { ucontrol->value.integer.value[0] = 1; } else { dev_err(codec->dev, "%s: ERROR: Default HPH Mode= %d\n", __func__, msm8x16_wcd->hph_mode); } dev_dbg(codec->dev, "%s: msm8x16_wcd->hph_mode = %d\n", __func__, msm8x16_wcd->hph_mode); return 0; } static int msm8x16_wcd_hph_mode_set(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol); struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s: ucontrol->value.integer.value[0] = %ld\n", __func__, ucontrol->value.integer.value[0]); switch (ucontrol->value.integer.value[0]) { case 0: msm8x16_wcd->hph_mode = NORMAL_MODE; break; case 1: if (get_codec_version(msm8x16_wcd) >= DIANGU) msm8x16_wcd->hph_mode = HD2_MODE; break; default: msm8x16_wcd->hph_mode = NORMAL_MODE; break; } dev_dbg(codec->dev, "%s: msm8x16_wcd->hph_mode_set = %d\n", __func__, msm8x16_wcd->hph_mode); return 0; } static int msm8x16_wcd_boost_option_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol); struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); if (msm8x16_wcd->boost_option == BOOST_SWITCH) { ucontrol->value.integer.value[0] = 0; } else if (msm8x16_wcd->boost_option == BOOST_ALWAYS) { ucontrol->value.integer.value[0] = 1; } else if (msm8x16_wcd->boost_option == BYPASS_ALWAYS) { ucontrol->value.integer.value[0] = 2; } else if (msm8x16_wcd->boost_option == BOOST_ON_FOREVER) { ucontrol->value.integer.value[0] = 3; } else { dev_err(codec->dev, "%s: ERROR: Unsupported Boost option= %d\n", __func__, msm8x16_wcd->boost_option); return -EINVAL; } dev_dbg(codec->dev, "%s: msm8x16_wcd->boost_option = %d\n", __func__, msm8x16_wcd->boost_option); return 0; } static int msm8x16_wcd_boost_option_set(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol); struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s: ucontrol->value.integer.value[0] = %ld\n", __func__, ucontrol->value.integer.value[0]); switch (ucontrol->value.integer.value[0]) { case 0: msm8x16_wcd->boost_option = BOOST_SWITCH; break; case 1: msm8x16_wcd->boost_option = BOOST_ALWAYS; break; case 2: msm8x16_wcd->boost_option = BYPASS_ALWAYS; msm8x16_wcd_bypass_on(codec); break; case 3: msm8x16_wcd->boost_option = BOOST_ON_FOREVER; msm8x16_wcd_boost_on(codec); break; default: pr_err("%s: invalid boost option: %d\n", __func__, msm8x16_wcd->boost_option); return -EINVAL; } dev_dbg(codec->dev, "%s: msm8x16_wcd->boost_option_set = %d\n", __func__, msm8x16_wcd->boost_option); return 0; } static int msm8x16_wcd_spk_boost_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol); struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); if (msm8x16_wcd->spk_boost_set == false) { ucontrol->value.integer.value[0] = 0; } else if (msm8x16_wcd->spk_boost_set == true) { ucontrol->value.integer.value[0] = 1; } else { dev_err(codec->dev, "%s: ERROR: Unsupported Speaker Boost = %d\n", __func__, msm8x16_wcd->spk_boost_set); return -EINVAL; } dev_dbg(codec->dev, "%s: msm8x16_wcd->spk_boost_set = %d\n", __func__, msm8x16_wcd->spk_boost_set); return 0; } static int msm8x16_wcd_spk_boost_set(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol); struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s: ucontrol->value.integer.value[0] = %ld\n", __func__, ucontrol->value.integer.value[0]); switch (ucontrol->value.integer.value[0]) { case 0: msm8x16_wcd->spk_boost_set = false; break; case 1: msm8x16_wcd->spk_boost_set = true; break; default: return -EINVAL; } dev_dbg(codec->dev, "%s: msm8x16_wcd->spk_boost_set = %d\n", __func__, msm8x16_wcd->spk_boost_set); return 0; } static int msm8x16_wcd_ext_spk_boost_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol); struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); if (msm8x16_wcd->ext_spk_boost_set == false) ucontrol->value.integer.value[0] = 0; else ucontrol->value.integer.value[0] = 1; dev_dbg(codec->dev, "%s: msm8x16_wcd->ext_spk_boost_set = %d\n", __func__, msm8x16_wcd->ext_spk_boost_set); return 0; } static int msm8x16_wcd_ext_spk_boost_set(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol); struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s: ucontrol->value.integer.value[0] = %ld\n", __func__, ucontrol->value.integer.value[0]); switch (ucontrol->value.integer.value[0]) { case 0: msm8x16_wcd->ext_spk_boost_set = false; break; case 1: msm8x16_wcd->ext_spk_boost_set = true; break; default: return -EINVAL; } dev_dbg(codec->dev, "%s: msm8x16_wcd->spk_boost_set = %d\n", __func__, msm8x16_wcd->spk_boost_set); return 0; } static int msm8x16_wcd_get_iir_enable_audio_mixer( struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol); int iir_idx = ((struct soc_multi_mixer_control *) kcontrol->private_value)->reg; int band_idx = ((struct soc_multi_mixer_control *) kcontrol->private_value)->shift; ucontrol->value.integer.value[0] = (snd_soc_read(codec, (MSM8X16_WCD_A_CDC_IIR1_CTL + 64 * iir_idx)) & (1 << band_idx)) != 0; dev_dbg(codec->dev, "%s: IIR #%d band #%d enable %d\n", __func__, iir_idx, band_idx, (uint32_t)ucontrol->value.integer.value[0]); return 0; } static int msm8x16_wcd_put_iir_enable_audio_mixer( struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol); int iir_idx = ((struct soc_multi_mixer_control *) kcontrol->private_value)->reg; int band_idx = ((struct soc_multi_mixer_control *) kcontrol->private_value)->shift; int value = ucontrol->value.integer.value[0]; snd_soc_update_bits(codec, (MSM8X16_WCD_A_CDC_IIR1_CTL + 64 * iir_idx), (1 << band_idx), (value << band_idx)); dev_dbg(codec->dev, "%s: IIR #%d band #%d enable %d\n", __func__, iir_idx, band_idx, ((snd_soc_read(codec, (MSM8X16_WCD_A_CDC_IIR1_CTL + 64 * iir_idx)) & (1 << band_idx)) != 0)); return 0; } static uint32_t get_iir_band_coeff(struct snd_soc_codec *codec, int iir_idx, int band_idx, int coeff_idx) { uint32_t value = 0; snd_soc_write(codec, (MSM8X16_WCD_A_CDC_IIR1_COEF_B1_CTL + 64 * iir_idx), ((band_idx * BAND_MAX + coeff_idx) * sizeof(uint32_t)) & 0x7F); value |= snd_soc_read(codec, (MSM8X16_WCD_A_CDC_IIR1_COEF_B2_CTL + 64 * iir_idx)); snd_soc_write(codec, (MSM8X16_WCD_A_CDC_IIR1_COEF_B1_CTL + 64 * iir_idx), ((band_idx * BAND_MAX + coeff_idx) * sizeof(uint32_t) + 1) & 0x7F); value |= (snd_soc_read(codec, (MSM8X16_WCD_A_CDC_IIR1_COEF_B2_CTL + 64 * iir_idx)) << 8); snd_soc_write(codec, (MSM8X16_WCD_A_CDC_IIR1_COEF_B1_CTL + 64 * iir_idx), ((band_idx * BAND_MAX + coeff_idx) * sizeof(uint32_t) + 2) & 0x7F); value |= (snd_soc_read(codec, (MSM8X16_WCD_A_CDC_IIR1_COEF_B2_CTL + 64 * iir_idx)) << 16); snd_soc_write(codec, (MSM8X16_WCD_A_CDC_IIR1_COEF_B1_CTL + 64 * iir_idx), ((band_idx * BAND_MAX + coeff_idx) * sizeof(uint32_t) + 3) & 0x7F); value |= ((snd_soc_read(codec, (MSM8X16_WCD_A_CDC_IIR1_COEF_B2_CTL + 64 * iir_idx)) & 0x3f) << 24); return value; } static int msm8x16_wcd_get_iir_band_audio_mixer( struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol); int iir_idx = ((struct soc_multi_mixer_control *) kcontrol->private_value)->reg; int band_idx = ((struct soc_multi_mixer_control *) kcontrol->private_value)->shift; ucontrol->value.integer.value[0] = get_iir_band_coeff(codec, iir_idx, band_idx, 0); ucontrol->value.integer.value[1] = get_iir_band_coeff(codec, iir_idx, band_idx, 1); ucontrol->value.integer.value[2] = get_iir_band_coeff(codec, iir_idx, band_idx, 2); ucontrol->value.integer.value[3] = get_iir_band_coeff(codec, iir_idx, band_idx, 3); ucontrol->value.integer.value[4] = get_iir_band_coeff(codec, iir_idx, band_idx, 4); dev_dbg(codec->dev, "%s: IIR #%d band #%d b0 = 0x%x\n" "%s: IIR #%d band #%d b1 = 0x%x\n" "%s: IIR #%d band #%d b2 = 0x%x\n" "%s: IIR #%d band #%d a1 = 0x%x\n" "%s: IIR #%d band #%d a2 = 0x%x\n", __func__, iir_idx, band_idx, (uint32_t)ucontrol->value.integer.value[0], __func__, iir_idx, band_idx, (uint32_t)ucontrol->value.integer.value[1], __func__, iir_idx, band_idx, (uint32_t)ucontrol->value.integer.value[2], __func__, iir_idx, band_idx, (uint32_t)ucontrol->value.integer.value[3], __func__, iir_idx, band_idx, (uint32_t)ucontrol->value.integer.value[4]); return 0; } static void set_iir_band_coeff(struct snd_soc_codec *codec, int iir_idx, int band_idx, uint32_t value) { snd_soc_write(codec, (MSM8X16_WCD_A_CDC_IIR1_COEF_B2_CTL + 64 * iir_idx), (value & 0xFF)); snd_soc_write(codec, (MSM8X16_WCD_A_CDC_IIR1_COEF_B2_CTL + 64 * iir_idx), (value >> 8) & 0xFF); snd_soc_write(codec, (MSM8X16_WCD_A_CDC_IIR1_COEF_B2_CTL + 64 * iir_idx), (value >> 16) & 0xFF); snd_soc_write(codec, (MSM8X16_WCD_A_CDC_IIR1_COEF_B2_CTL + 64 * iir_idx), (value >> 24) & 0x3F); } static int msm8x16_wcd_put_iir_band_audio_mixer( struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol); int iir_idx = ((struct soc_multi_mixer_control *) kcontrol->private_value)->reg; int band_idx = ((struct soc_multi_mixer_control *) kcontrol->private_value)->shift; snd_soc_write(codec, (MSM8X16_WCD_A_CDC_IIR1_COEF_B1_CTL + 64 * iir_idx), (band_idx * BAND_MAX * sizeof(uint32_t)) & 0x7F); set_iir_band_coeff(codec, iir_idx, band_idx, ucontrol->value.integer.value[0]); set_iir_band_coeff(codec, iir_idx, band_idx, ucontrol->value.integer.value[1]); set_iir_band_coeff(codec, iir_idx, band_idx, ucontrol->value.integer.value[2]); set_iir_band_coeff(codec, iir_idx, band_idx, ucontrol->value.integer.value[3]); set_iir_band_coeff(codec, iir_idx, band_idx, ucontrol->value.integer.value[4]); dev_dbg(codec->dev, "%s: IIR #%d band #%d b0 = 0x%x\n" "%s: IIR #%d band #%d b1 = 0x%x\n" "%s: IIR #%d band #%d b2 = 0x%x\n" "%s: IIR #%d band #%d a1 = 0x%x\n" "%s: IIR #%d band #%d a2 = 0x%x\n", __func__, iir_idx, band_idx, get_iir_band_coeff(codec, iir_idx, band_idx, 0), __func__, iir_idx, band_idx, get_iir_band_coeff(codec, iir_idx, band_idx, 1), __func__, iir_idx, band_idx, get_iir_band_coeff(codec, iir_idx, band_idx, 2), __func__, iir_idx, band_idx, get_iir_band_coeff(codec, iir_idx, band_idx, 3), __func__, iir_idx, band_idx, get_iir_band_coeff(codec, iir_idx, band_idx, 4)); return 0; } static int msm8x16_wcd_compander_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol); struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); int comp_idx = ((struct soc_multi_mixer_control *) kcontrol->private_value)->reg; int rx_idx = ((struct soc_multi_mixer_control *) kcontrol->private_value)->shift; dev_dbg(codec->dev, "%s: msm8x16_wcd->comp[%d]_enabled[%d] = %d\n", __func__, comp_idx, rx_idx, msm8x16_wcd->comp_enabled[rx_idx]); ucontrol->value.integer.value[0] = msm8x16_wcd->comp_enabled[rx_idx]; dev_dbg(codec->dev, "%s: ucontrol->value.integer.value[0] = %ld\n", __func__, ucontrol->value.integer.value[0]); return 0; } static int msm8x16_wcd_compander_set(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol); struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); int comp_idx = ((struct soc_multi_mixer_control *) kcontrol->private_value)->reg; int rx_idx = ((struct soc_multi_mixer_control *) kcontrol->private_value)->shift; int value = ucontrol->value.integer.value[0]; dev_dbg(codec->dev, "%s: ucontrol->value.integer.value[0] = %ld\n", __func__, ucontrol->value.integer.value[0]); if (get_codec_version(msm8x16_wcd) >= DIANGU) { if (!value) msm8x16_wcd->comp_enabled[rx_idx] = 0; else msm8x16_wcd->comp_enabled[rx_idx] = comp_idx; } dev_dbg(codec->dev, "%s: msm8x16_wcd->comp[%d]_enabled[%d] = %d\n", __func__, comp_idx, rx_idx, msm8x16_wcd->comp_enabled[rx_idx]); return 0; } static const char * const msm8x16_wcd_loopback_mode_ctrl_text[] = { "DISABLE", "ENABLE"}; static const struct soc_enum msm8x16_wcd_loopback_mode_ctl_enum[] = { SOC_ENUM_SINGLE_EXT(2, msm8x16_wcd_loopback_mode_ctrl_text), }; static const char * const msm8x16_wcd_ear_pa_boost_ctrl_text[] = { "DISABLE", "ENABLE"}; static const struct soc_enum msm8x16_wcd_ear_pa_boost_ctl_enum[] = { SOC_ENUM_SINGLE_EXT(2, msm8x16_wcd_ear_pa_boost_ctrl_text), }; static const char * const msm8x16_wcd_ear_pa_gain_text[] = { "POS_1P5_DB", "POS_6_DB"}; static const struct soc_enum msm8x16_wcd_ear_pa_gain_enum[] = { SOC_ENUM_SINGLE_EXT(2, msm8x16_wcd_ear_pa_gain_text), }; static const char * const msm8x16_wcd_boost_option_ctrl_text[] = { "BOOST_SWITCH", "BOOST_ALWAYS", "BYPASS_ALWAYS", "BOOST_ON_FOREVER"}; static const struct soc_enum msm8x16_wcd_boost_option_ctl_enum[] = { SOC_ENUM_SINGLE_EXT(4, msm8x16_wcd_boost_option_ctrl_text), }; static const char * const msm8x16_wcd_spk_boost_ctrl_text[] = { "DISABLE", "ENABLE"}; static const struct soc_enum msm8x16_wcd_spk_boost_ctl_enum[] = { SOC_ENUM_SINGLE_EXT(2, msm8x16_wcd_spk_boost_ctrl_text), }; static const char * const msm8x16_wcd_ext_spk_boost_ctrl_text[] = { "DISABLE", "ENABLE"}; static const struct soc_enum msm8x16_wcd_ext_spk_boost_ctl_enum[] = { SOC_ENUM_SINGLE_EXT(2, msm8x16_wcd_ext_spk_boost_ctrl_text), }; static const char * const msm8x16_wcd_hph_mode_ctrl_text[] = { "NORMAL", "HD2"}; static const struct soc_enum msm8x16_wcd_hph_mode_ctl_enum[] = { SOC_ENUM_SINGLE_EXT(ARRAY_SIZE(msm8x16_wcd_hph_mode_ctrl_text), msm8x16_wcd_hph_mode_ctrl_text), }; static const char * const cf_text[] = { "MIN_3DB_4Hz", "MIN_3DB_75Hz", "MIN_3DB_150Hz" }; static const struct soc_enum cf_dec1_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_CDC_TX1_MUX_CTL, 4, 3, cf_text); static const struct soc_enum cf_dec2_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_CDC_TX2_MUX_CTL, 4, 3, cf_text); static const struct soc_enum cf_rxmix1_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_CDC_RX1_B4_CTL, 0, 3, cf_text); static const struct soc_enum cf_rxmix2_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_CDC_RX2_B4_CTL, 0, 3, cf_text); static const struct soc_enum cf_rxmix3_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_CDC_RX3_B4_CTL, 0, 3, cf_text); static const struct snd_kcontrol_new msm8x16_wcd_snd_controls[] = { SOC_ENUM_EXT("RX HPH Mode", msm8x16_wcd_hph_mode_ctl_enum[0], msm8x16_wcd_hph_mode_get, msm8x16_wcd_hph_mode_set), SOC_ENUM_EXT("Boost Option", msm8x16_wcd_boost_option_ctl_enum[0], msm8x16_wcd_boost_option_get, msm8x16_wcd_boost_option_set), SOC_ENUM_EXT("EAR PA Boost", msm8x16_wcd_ear_pa_boost_ctl_enum[0], msm8x16_wcd_ear_pa_boost_get, msm8x16_wcd_ear_pa_boost_set), SOC_ENUM_EXT("EAR PA Gain", msm8x16_wcd_ear_pa_gain_enum[0], msm8x16_wcd_pa_gain_get, msm8x16_wcd_pa_gain_put), SOC_ENUM_EXT("Speaker Boost", msm8x16_wcd_spk_boost_ctl_enum[0], msm8x16_wcd_spk_boost_get, msm8x16_wcd_spk_boost_set), SOC_ENUM_EXT("Ext Spk Boost", msm8x16_wcd_ext_spk_boost_ctl_enum[0], msm8x16_wcd_ext_spk_boost_get, msm8x16_wcd_ext_spk_boost_set), SOC_ENUM_EXT("LOOPBACK Mode", msm8x16_wcd_loopback_mode_ctl_enum[0], msm8x16_wcd_loopback_mode_get, msm8x16_wcd_loopback_mode_put), SOC_SINGLE_TLV("ADC1 Volume", MSM8X16_WCD_A_ANALOG_TX_1_EN, 3, 8, 0, analog_gain), SOC_SINGLE_TLV("ADC2 Volume", MSM8X16_WCD_A_ANALOG_TX_2_EN, 3, 8, 0, analog_gain), SOC_SINGLE_TLV("ADC3 Volume", MSM8X16_WCD_A_ANALOG_TX_3_EN, 3, 8, 0, analog_gain), SOC_SINGLE_SX_TLV("RX1 Digital Volume", MSM8X16_WCD_A_CDC_RX1_VOL_CTL_B2_CTL, 0, -84, 40, digital_gain), SOC_SINGLE_SX_TLV("RX2 Digital Volume", MSM8X16_WCD_A_CDC_RX2_VOL_CTL_B2_CTL, 0, -84, 40, digital_gain), SOC_SINGLE_SX_TLV("RX3 Digital Volume", MSM8X16_WCD_A_CDC_RX3_VOL_CTL_B2_CTL, 0, -84, 40, digital_gain), SOC_SINGLE_SX_TLV("DEC1 Volume", MSM8X16_WCD_A_CDC_TX1_VOL_CTL_GAIN, 0, -84, 40, digital_gain), SOC_SINGLE_SX_TLV("DEC2 Volume", MSM8X16_WCD_A_CDC_TX2_VOL_CTL_GAIN, 0, -84, 40, digital_gain), SOC_SINGLE_SX_TLV("IIR1 INP1 Volume", MSM8X16_WCD_A_CDC_IIR1_GAIN_B1_CTL, 0, -84, 40, digital_gain), SOC_SINGLE_SX_TLV("IIR1 INP2 Volume", MSM8X16_WCD_A_CDC_IIR1_GAIN_B2_CTL, 0, -84, 40, digital_gain), SOC_SINGLE_SX_TLV("IIR1 INP3 Volume", MSM8X16_WCD_A_CDC_IIR1_GAIN_B3_CTL, 0, -84, 40, digital_gain), SOC_SINGLE_SX_TLV("IIR1 INP4 Volume", MSM8X16_WCD_A_CDC_IIR1_GAIN_B4_CTL, 0, -84, 40, digital_gain), SOC_SINGLE_SX_TLV("IIR2 INP1 Volume", MSM8X16_WCD_A_CDC_IIR2_GAIN_B1_CTL, 0, -84, 40, digital_gain), SOC_ENUM("TX1 HPF cut off", cf_dec1_enum), SOC_ENUM("TX2 HPF cut off", cf_dec2_enum), SOC_SINGLE("TX1 HPF Switch", MSM8X16_WCD_A_CDC_TX1_MUX_CTL, 3, 1, 0), SOC_SINGLE("TX2 HPF Switch", MSM8X16_WCD_A_CDC_TX2_MUX_CTL, 3, 1, 0), SOC_SINGLE("RX1 HPF Switch", MSM8X16_WCD_A_CDC_RX1_B5_CTL, 2, 1, 0), SOC_SINGLE("RX2 HPF Switch", MSM8X16_WCD_A_CDC_RX2_B5_CTL, 2, 1, 0), SOC_SINGLE("RX3 HPF Switch", MSM8X16_WCD_A_CDC_RX3_B5_CTL, 2, 1, 0), SOC_ENUM("RX1 HPF cut off", cf_rxmix1_enum), SOC_ENUM("RX2 HPF cut off", cf_rxmix2_enum), SOC_ENUM("RX3 HPF cut off", cf_rxmix3_enum), SOC_SINGLE_EXT("IIR1 Enable Band1", IIR1, BAND1, 1, 0, msm8x16_wcd_get_iir_enable_audio_mixer, msm8x16_wcd_put_iir_enable_audio_mixer), SOC_SINGLE_EXT("IIR1 Enable Band2", IIR1, BAND2, 1, 0, msm8x16_wcd_get_iir_enable_audio_mixer, msm8x16_wcd_put_iir_enable_audio_mixer), SOC_SINGLE_EXT("IIR1 Enable Band3", IIR1, BAND3, 1, 0, msm8x16_wcd_get_iir_enable_audio_mixer, msm8x16_wcd_put_iir_enable_audio_mixer), SOC_SINGLE_EXT("IIR1 Enable Band4", IIR1, BAND4, 1, 0, msm8x16_wcd_get_iir_enable_audio_mixer, msm8x16_wcd_put_iir_enable_audio_mixer), SOC_SINGLE_EXT("IIR1 Enable Band5", IIR1, BAND5, 1, 0, msm8x16_wcd_get_iir_enable_audio_mixer, msm8x16_wcd_put_iir_enable_audio_mixer), SOC_SINGLE_EXT("IIR2 Enable Band1", IIR2, BAND1, 1, 0, msm8x16_wcd_get_iir_enable_audio_mixer, msm8x16_wcd_put_iir_enable_audio_mixer), SOC_SINGLE_EXT("IIR2 Enable Band2", IIR2, BAND2, 1, 0, msm8x16_wcd_get_iir_enable_audio_mixer, msm8x16_wcd_put_iir_enable_audio_mixer), SOC_SINGLE_EXT("IIR2 Enable Band3", IIR2, BAND3, 1, 0, msm8x16_wcd_get_iir_enable_audio_mixer, msm8x16_wcd_put_iir_enable_audio_mixer), SOC_SINGLE_EXT("IIR2 Enable Band4", IIR2, BAND4, 1, 0, msm8x16_wcd_get_iir_enable_audio_mixer, msm8x16_wcd_put_iir_enable_audio_mixer), SOC_SINGLE_EXT("IIR2 Enable Band5", IIR2, BAND5, 1, 0, msm8x16_wcd_get_iir_enable_audio_mixer, msm8x16_wcd_put_iir_enable_audio_mixer), SOC_SINGLE_MULTI_EXT("IIR1 Band1", IIR1, BAND1, 255, 0, 5, msm8x16_wcd_get_iir_band_audio_mixer, msm8x16_wcd_put_iir_band_audio_mixer), SOC_SINGLE_MULTI_EXT("IIR1 Band2", IIR1, BAND2, 255, 0, 5, msm8x16_wcd_get_iir_band_audio_mixer, msm8x16_wcd_put_iir_band_audio_mixer), SOC_SINGLE_MULTI_EXT("IIR1 Band3", IIR1, BAND3, 255, 0, 5, msm8x16_wcd_get_iir_band_audio_mixer, msm8x16_wcd_put_iir_band_audio_mixer), SOC_SINGLE_MULTI_EXT("IIR1 Band4", IIR1, BAND4, 255, 0, 5, msm8x16_wcd_get_iir_band_audio_mixer, msm8x16_wcd_put_iir_band_audio_mixer), SOC_SINGLE_MULTI_EXT("IIR1 Band5", IIR1, BAND5, 255, 0, 5, msm8x16_wcd_get_iir_band_audio_mixer, msm8x16_wcd_put_iir_band_audio_mixer), SOC_SINGLE_MULTI_EXT("IIR2 Band1", IIR2, BAND1, 255, 0, 5, msm8x16_wcd_get_iir_band_audio_mixer, msm8x16_wcd_put_iir_band_audio_mixer), SOC_SINGLE_MULTI_EXT("IIR2 Band2", IIR2, BAND2, 255, 0, 5, msm8x16_wcd_get_iir_band_audio_mixer, msm8x16_wcd_put_iir_band_audio_mixer), SOC_SINGLE_MULTI_EXT("IIR2 Band3", IIR2, BAND3, 255, 0, 5, msm8x16_wcd_get_iir_band_audio_mixer, msm8x16_wcd_put_iir_band_audio_mixer), SOC_SINGLE_MULTI_EXT("IIR2 Band4", IIR2, BAND4, 255, 0, 5, msm8x16_wcd_get_iir_band_audio_mixer, msm8x16_wcd_put_iir_band_audio_mixer), SOC_SINGLE_MULTI_EXT("IIR2 Band5", IIR2, BAND5, 255, 0, 5, msm8x16_wcd_get_iir_band_audio_mixer, msm8x16_wcd_put_iir_band_audio_mixer), SOC_SINGLE_EXT("COMP0 RX1", COMPANDER_1, MSM8X16_WCD_RX1, 1, 0, msm8x16_wcd_compander_get, msm8x16_wcd_compander_set), SOC_SINGLE_EXT("COMP0 RX2", COMPANDER_1, MSM8X16_WCD_RX2, 1, 0, msm8x16_wcd_compander_get, msm8x16_wcd_compander_set), }; static int tombak_hph_impedance_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { int ret; uint32_t zl, zr; bool hphr; struct soc_multi_mixer_control *mc; struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol); struct msm8x16_wcd_priv *priv = snd_soc_codec_get_drvdata(codec); mc = (struct soc_multi_mixer_control *)(kcontrol->private_value); hphr = mc->shift; ret = wcd_mbhc_get_impedance(&priv->mbhc, &zl, &zr); if (ret) pr_debug("%s: Failed to get mbhc imped", __func__); pr_debug("%s: zl %u, zr %u\n", __func__, zl, zr); ucontrol->value.integer.value[0] = hphr ? zr : zl; return 0; } static const struct snd_kcontrol_new impedance_detect_controls[] = { SOC_SINGLE_EXT("HPHL Impedance", 0, 0, UINT_MAX, 0, tombak_hph_impedance_get, NULL), SOC_SINGLE_EXT("HPHR Impedance", 0, 1, UINT_MAX, 0, tombak_hph_impedance_get, NULL), }; static int tombak_get_hph_type(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol); struct msm8x16_wcd_priv *priv = snd_soc_codec_get_drvdata(codec); struct wcd_mbhc *mbhc; if (!priv) { pr_debug("%s: msm8x16-wcd private data is NULL\n", __func__); return -EINVAL; } mbhc = &priv->mbhc; if (!mbhc) { pr_debug("%s: mbhc not initialized\n", __func__); return -EINVAL; } ucontrol->value.integer.value[0] = (u32) mbhc->hph_type; pr_debug("%s: hph_type = %u\n", __func__, mbhc->hph_type); return 0; } static const struct snd_kcontrol_new hph_type_detect_controls[] = { SOC_SINGLE_EXT("HPH Type", 0, 0, UINT_MAX, 0, tombak_get_hph_type, NULL), }; static const char * const rx_mix1_text[] = { "ZERO", "IIR1", "IIR2", "RX1", "RX2", "RX3" }; static const char * const rx_mix2_text[] = { "ZERO", "IIR1", "IIR2" }; static const char * const dec_mux_text[] = { "ZERO", "ADC1", "ADC2", "ADC3", "DMIC1", "DMIC2" }; static const char * const dec3_mux_text[] = { "ZERO", "DMIC3" }; static const char * const dec4_mux_text[] = { "ZERO", "DMIC4" }; static const char * const adc2_mux_text[] = { "ZERO", "INP2", "INP3" }; static const char * const ext_spk_text[] = { "Off", "On" }; static const char * const wsa_spk_text[] = { "ZERO", "WSA" }; static const char * const rdac2_mux_text[] = { "ZERO", "RX2", "RX1" }; static const char * const iir_inp1_text[] = { "ZERO", "DEC1", "DEC2", "RX1", "RX2", "RX3" }; static const struct soc_enum adc2_enum = SOC_ENUM_SINGLE(SND_SOC_NOPM, 0, ARRAY_SIZE(adc2_mux_text), adc2_mux_text); static const struct soc_enum ext_spk_enum = SOC_ENUM_SINGLE(SND_SOC_NOPM, 0, ARRAY_SIZE(ext_spk_text), ext_spk_text); static const struct soc_enum wsa_spk_enum = SOC_ENUM_SINGLE(SND_SOC_NOPM, 0, ARRAY_SIZE(wsa_spk_text), wsa_spk_text); static const struct soc_enum rx_mix1_inp1_chain_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_CDC_CONN_RX1_B1_CTL, 0, 6, rx_mix1_text); static const struct soc_enum rx_mix1_inp2_chain_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_CDC_CONN_RX1_B1_CTL, 3, 6, rx_mix1_text); static const struct soc_enum rx_mix1_inp3_chain_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_CDC_CONN_RX1_B2_CTL, 0, 6, rx_mix1_text); static const struct soc_enum rx_mix2_inp1_chain_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_CDC_CONN_RX1_B3_CTL, 0, 3, rx_mix2_text); static const struct soc_enum rx2_mix1_inp1_chain_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_CDC_CONN_RX2_B1_CTL, 0, 6, rx_mix1_text); static const struct soc_enum rx2_mix1_inp2_chain_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_CDC_CONN_RX2_B1_CTL, 3, 6, rx_mix1_text); static const struct soc_enum rx2_mix1_inp3_chain_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_CDC_CONN_RX2_B1_CTL, 0, 6, rx_mix1_text); static const struct soc_enum rx2_mix2_inp1_chain_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_CDC_CONN_RX2_B3_CTL, 0, 3, rx_mix2_text); static const struct soc_enum rx3_mix1_inp1_chain_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_CDC_CONN_RX3_B1_CTL, 0, 6, rx_mix1_text); static const struct soc_enum rx3_mix1_inp2_chain_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_CDC_CONN_RX3_B1_CTL, 3, 6, rx_mix1_text); static const struct soc_enum rx3_mix1_inp3_chain_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_CDC_CONN_RX3_B1_CTL, 0, 6, rx_mix1_text); static const struct soc_enum dec1_mux_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_CDC_CONN_TX_B1_CTL, 0, 6, dec_mux_text); static const struct soc_enum dec2_mux_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_CDC_CONN_TX_B1_CTL, 3, 6, dec_mux_text); static const struct soc_enum dec3_mux_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_CDC_TX3_MUX_CTL, 0, ARRAY_SIZE(dec3_mux_text), dec3_mux_text); static const struct soc_enum dec4_mux_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_CDC_TX4_MUX_CTL, 0, ARRAY_SIZE(dec4_mux_text), dec4_mux_text); static const struct soc_enum rdac2_mux_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_DIGITAL_CDC_CONN_HPHR_DAC_CTL, 0, 3, rdac2_mux_text); static const struct soc_enum iir1_inp1_mux_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_CDC_CONN_EQ1_B1_CTL, 0, 6, iir_inp1_text); static const struct soc_enum iir2_inp1_mux_enum = SOC_ENUM_SINGLE(MSM8X16_WCD_A_CDC_CONN_EQ2_B1_CTL, 0, 6, iir_inp1_text); static const struct snd_kcontrol_new ext_spk_mux = SOC_DAPM_ENUM("Ext Spk Switch Mux", ext_spk_enum); static const struct snd_kcontrol_new rx_mix1_inp1_mux = SOC_DAPM_ENUM("RX1 MIX1 INP1 Mux", rx_mix1_inp1_chain_enum); static const struct snd_kcontrol_new rx_mix1_inp2_mux = SOC_DAPM_ENUM("RX1 MIX1 INP2 Mux", rx_mix1_inp2_chain_enum); static const struct snd_kcontrol_new rx_mix1_inp3_mux = SOC_DAPM_ENUM("RX1 MIX1 INP3 Mux", rx_mix1_inp3_chain_enum); static const struct snd_kcontrol_new rx2_mix1_inp1_mux = SOC_DAPM_ENUM("RX2 MIX1 INP1 Mux", rx2_mix1_inp1_chain_enum); static const struct snd_kcontrol_new rx2_mix1_inp2_mux = SOC_DAPM_ENUM("RX2 MIX1 INP2 Mux", rx2_mix1_inp2_chain_enum); static const struct snd_kcontrol_new rx2_mix1_inp3_mux = SOC_DAPM_ENUM("RX2 MIX1 INP3 Mux", rx2_mix1_inp3_chain_enum); static const struct snd_kcontrol_new rx3_mix1_inp1_mux = SOC_DAPM_ENUM("RX3 MIX1 INP1 Mux", rx3_mix1_inp1_chain_enum); static const struct snd_kcontrol_new rx3_mix1_inp2_mux = SOC_DAPM_ENUM("RX3 MIX1 INP2 Mux", rx3_mix1_inp2_chain_enum); static const struct snd_kcontrol_new rx3_mix1_inp3_mux = SOC_DAPM_ENUM("RX3 MIX1 INP3 Mux", rx3_mix1_inp3_chain_enum); static const struct snd_kcontrol_new rx1_mix2_inp1_mux = SOC_DAPM_ENUM("RX1 MIX2 INP1 Mux", rx_mix2_inp1_chain_enum); static const struct snd_kcontrol_new rx2_mix2_inp1_mux = SOC_DAPM_ENUM("RX2 MIX2 INP1 Mux", rx2_mix2_inp1_chain_enum); static const struct snd_kcontrol_new tx_adc2_mux = SOC_DAPM_ENUM("ADC2 MUX Mux", adc2_enum); static int msm8x16_wcd_put_dec_enum(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_dapm_widget_list *wlist = dapm_kcontrol_get_wlist(kcontrol); struct snd_soc_dapm_widget *w = wlist->widgets[0]; struct snd_soc_codec *codec = w->codec; struct soc_enum *e = (struct soc_enum *)kcontrol->private_value; unsigned int dec_mux, decimator; char *dec_name = NULL; char *widget_name = NULL; char *temp; u16 tx_mux_ctl_reg; u8 adc_dmic_sel = 0x0; int ret = 0; char *dec_num; if (ucontrol->value.enumerated.item[0] > e->items) { dev_err(codec->dev, "%s: Invalid enum value: %d\n", __func__, ucontrol->value.enumerated.item[0]); return -EINVAL; } dec_mux = ucontrol->value.enumerated.item[0]; widget_name = kstrndup(w->name, 15, GFP_KERNEL); if (!widget_name) { dev_err(codec->dev, "%s: failed to copy string\n", __func__); return -ENOMEM; } temp = widget_name; dec_name = strsep(&widget_name, " "); widget_name = temp; if (!dec_name) { dev_err(codec->dev, "%s: Invalid decimator = %s\n", __func__, w->name); ret = -EINVAL; goto out; } dec_num = strpbrk(dec_name, "12"); if (dec_num == NULL) { dev_err(codec->dev, "%s: Invalid DEC selected\n", __func__); ret = -EINVAL; goto out; } ret = kstrtouint(dec_num, 10, &decimator); if (ret < 0) { dev_err(codec->dev, "%s: Invalid decimator = %s\n", __func__, dec_name); ret = -EINVAL; goto out; } dev_dbg(w->dapm->dev, "%s(): widget = %s decimator = %u dec_mux = %u\n" , __func__, w->name, decimator, dec_mux); switch (decimator) { case 1: case 2: if ((dec_mux == 4) || (dec_mux == 5)) adc_dmic_sel = 0x1; else adc_dmic_sel = 0x0; break; default: dev_err(codec->dev, "%s: Invalid Decimator = %u\n", __func__, decimator); ret = -EINVAL; goto out; } tx_mux_ctl_reg = MSM8X16_WCD_A_CDC_TX1_MUX_CTL + 32 * (decimator - 1); snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x1, adc_dmic_sel); ret = snd_soc_dapm_put_enum_double(kcontrol, ucontrol); out: kfree(widget_name); return ret; } #define MSM8X16_WCD_DEC_ENUM(xname, xenum) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \ .info = snd_soc_info_enum_double, \ .get = snd_soc_dapm_get_enum_double, \ .put = msm8x16_wcd_put_dec_enum, \ .private_value = (unsigned long)&xenum } static const struct snd_kcontrol_new dec1_mux = MSM8X16_WCD_DEC_ENUM("DEC1 MUX Mux", dec1_mux_enum); static const struct snd_kcontrol_new dec2_mux = MSM8X16_WCD_DEC_ENUM("DEC2 MUX Mux", dec2_mux_enum); static const struct snd_kcontrol_new dec3_mux = SOC_DAPM_ENUM("DEC3 MUX Mux", dec3_mux_enum); static const struct snd_kcontrol_new dec4_mux = SOC_DAPM_ENUM("DEC4 MUX Mux", dec4_mux_enum); static const struct snd_kcontrol_new rdac2_mux = SOC_DAPM_ENUM("RDAC2 MUX Mux", rdac2_mux_enum); static const struct snd_kcontrol_new iir1_inp1_mux = SOC_DAPM_ENUM("IIR1 INP1 Mux", iir1_inp1_mux_enum); static const char * const ear_text[] = { "ZERO", "Switch", }; static const struct soc_enum ear_enum = SOC_ENUM_SINGLE(SND_SOC_NOPM, 0, ARRAY_SIZE(ear_text), ear_text); static const struct snd_kcontrol_new ear_pa_mux[] = { SOC_DAPM_ENUM("EAR_S", ear_enum) }; static const struct snd_kcontrol_new wsa_spk_mux[] = { SOC_DAPM_ENUM("WSA Spk Switch", wsa_spk_enum) }; static const struct snd_kcontrol_new iir2_inp1_mux = SOC_DAPM_ENUM("IIR2 INP1 Mux", iir2_inp1_mux_enum); static const char * const hph_text[] = { "ZERO", "Switch", }; static const struct soc_enum hph_enum = SOC_ENUM_SINGLE(SND_SOC_NOPM, 0, ARRAY_SIZE(hph_text), hph_text); static const struct snd_kcontrol_new hphl_mux[] = { SOC_DAPM_ENUM("HPHL", hph_enum) }; static const struct snd_kcontrol_new hphr_mux[] = { SOC_DAPM_ENUM("HPHR", hph_enum) }; static const struct snd_kcontrol_new spkr_mux[] = { SOC_DAPM_ENUM("SPK", hph_enum) }; static const char * const lo_text[] = { "ZERO", "Switch", }; static const struct soc_enum lo_enum = SOC_ENUM_SINGLE(SND_SOC_NOPM, 0, ARRAY_SIZE(hph_text), hph_text); static const struct snd_kcontrol_new lo_mux[] = { SOC_DAPM_ENUM("LINE_OUT", lo_enum) }; static void msm8x16_wcd_codec_enable_adc_block(struct snd_soc_codec *codec, int enable) { struct msm8x16_wcd_priv *wcd8x16 = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s %d\n", __func__, enable); if (enable) { wcd8x16->adc_count++; snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_ANA_CLK_CTL, 0x20, 0x20); snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 0x10, 0x10); } else { wcd8x16->adc_count--; if (!wcd8x16->adc_count) { snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 0x10, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_ANA_CLK_CTL, 0x20, 0x0); } } } static int msm8x16_wcd_codec_enable_adc(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; u16 adc_reg; u8 init_bit_shift; dev_dbg(codec->dev, "%s %d\n", __func__, event); adc_reg = MSM8X16_WCD_A_ANALOG_TX_1_2_TEST_CTL_2; if (w->reg == MSM8X16_WCD_A_ANALOG_TX_1_EN) init_bit_shift = 5; else if ((w->reg == MSM8X16_WCD_A_ANALOG_TX_2_EN) || (w->reg == MSM8X16_WCD_A_ANALOG_TX_3_EN)) init_bit_shift = 4; else { dev_err(codec->dev, "%s: Error, invalid adc register\n", __func__); return -EINVAL; } switch (event) { case SND_SOC_DAPM_PRE_PMU: msm8x16_wcd_codec_enable_adc_block(codec, 1); if (w->reg == MSM8X16_WCD_A_ANALOG_TX_2_EN) snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MICB_1_CTL, 0x02, 0x02); usleep_range(10000, 10010); snd_soc_update_bits(codec, adc_reg, 1 << init_bit_shift, 1 << init_bit_shift); if (w->reg == MSM8X16_WCD_A_ANALOG_TX_1_EN) snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_CONN_TX1_CTL, 0x03, 0x00); else if ((w->reg == MSM8X16_WCD_A_ANALOG_TX_2_EN) || (w->reg == MSM8X16_WCD_A_ANALOG_TX_3_EN)) snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_CONN_TX2_CTL, 0x03, 0x00); usleep_range(CODEC_DELAY_1_MS, CODEC_DELAY_1_1_MS); break; case SND_SOC_DAPM_POST_PMU: usleep_range(12000, 12010); snd_soc_update_bits(codec, adc_reg, 1 << init_bit_shift, 0x00); usleep_range(CODEC_DELAY_1_MS, CODEC_DELAY_1_1_MS); break; case SND_SOC_DAPM_POST_PMD: msm8x16_wcd_codec_enable_adc_block(codec, 0); if (w->reg == MSM8X16_WCD_A_ANALOG_TX_2_EN) snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MICB_1_CTL, 0x02, 0x00); if (w->reg == MSM8X16_WCD_A_ANALOG_TX_1_EN) snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_CONN_TX1_CTL, 0x03, 0x02); else if ((w->reg == MSM8X16_WCD_A_ANALOG_TX_2_EN) || (w->reg == MSM8X16_WCD_A_ANALOG_TX_3_EN)) snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_CONN_TX2_CTL, 0x03, 0x02); break; } return 0; } static int msm8x16_wcd_codec_enable_spk_pa(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); dev_dbg(w->codec->dev, "%s %d %s\n", __func__, event, w->name); switch (event) { case SND_SOC_DAPM_PRE_PMU: snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_ANA_CLK_CTL, 0x10, 0x10); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SPKR_PWRSTG_CTL, 0x01, 0x01); switch (msm8x16_wcd->boost_option) { case BOOST_SWITCH: if (!msm8x16_wcd->spk_boost_set) snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SPKR_DAC_CTL, 0x10, 0x10); break; case BOOST_ALWAYS: case BOOST_ON_FOREVER: break; case BYPASS_ALWAYS: snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SPKR_DAC_CTL, 0x10, 0x10); break; default: pr_err("%s: invalid boost option: %d\n", __func__, msm8x16_wcd->boost_option); break; } usleep_range(CODEC_DELAY_1_MS, CODEC_DELAY_1_1_MS); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SPKR_PWRSTG_CTL, 0xE0, 0xE0); if (get_codec_version(msm8x16_wcd) != TOMBAK_1_0) snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_EAR_CTL, 0x01, 0x01); break; case SND_SOC_DAPM_POST_PMU: usleep_range(CODEC_DELAY_1_MS, CODEC_DELAY_1_1_MS); switch (msm8x16_wcd->boost_option) { case BOOST_SWITCH: if (msm8x16_wcd->spk_boost_set) snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SPKR_DRV_CTL, 0xEF, 0xEF); else snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SPKR_DAC_CTL, 0x10, 0x00); break; case BOOST_ALWAYS: case BOOST_ON_FOREVER: snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SPKR_DRV_CTL, 0xEF, 0xEF); break; case BYPASS_ALWAYS: snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SPKR_DAC_CTL, 0x10, 0x00); break; default: pr_err("%s: invalid boost option: %d\n", __func__, msm8x16_wcd->boost_option); break; } snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX3_B6_CTL, 0x01, 0x00); snd_soc_update_bits(codec, w->reg, 0x80, 0x80); break; case SND_SOC_DAPM_PRE_PMD: snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX3_B6_CTL, 0x01, 0x01); msm8x16_wcd->mute_mask |= SPKR_PA_DISABLE; usleep_range(CODEC_DELAY_1_MS, CODEC_DELAY_1_1_MS); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SPKR_DAC_CTL, 0x10, 0x10); if (get_codec_version(msm8x16_wcd) < CAJON_2_0) msm8x16_wcd_boost_mode_sequence(codec, SPK_PMD); snd_soc_update_bits(codec, w->reg, 0x80, 0x00); switch (msm8x16_wcd->boost_option) { case BOOST_SWITCH: if (msm8x16_wcd->spk_boost_set) snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SPKR_DRV_CTL, 0xEF, 0x69); break; case BOOST_ALWAYS: case BOOST_ON_FOREVER: snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SPKR_DRV_CTL, 0xEF, 0x69); break; case BYPASS_ALWAYS: break; default: pr_err("%s: invalid boost option: %d\n", __func__, msm8x16_wcd->boost_option); break; } break; case SND_SOC_DAPM_POST_PMD: snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SPKR_PWRSTG_CTL, 0xE0, 0x00); usleep_range(CODEC_DELAY_1_MS, CODEC_DELAY_1_1_MS); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SPKR_PWRSTG_CTL, 0x01, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SPKR_DAC_CTL, 0x10, 0x00); if (get_codec_version(msm8x16_wcd) != TOMBAK_1_0) snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_EAR_CTL, 0x01, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_ANA_CLK_CTL, 0x10, 0x00); if (get_codec_version(msm8x16_wcd) >= CAJON_2_0) msm8x16_wcd_boost_mode_sequence(codec, SPK_PMD); break; } return 0; } static int msm8x16_wcd_codec_enable_dig_clk(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); struct msm8916_asoc_mach_data *pdata = NULL; pdata = snd_soc_card_get_drvdata(codec->component.card); dev_dbg(w->codec->dev, "%s event %d w->name %s\n", __func__, event, w->name); switch (event) { case SND_SOC_DAPM_PRE_PMU: msm8x16_wcd_codec_enable_clock_block(codec, 1); snd_soc_update_bits(codec, w->reg, 0x80, 0x80); msm8x16_wcd_boost_mode_sequence(codec, SPK_PMU); break; case SND_SOC_DAPM_POST_PMD: if (msm8x16_wcd->rx_bias_count == 0) snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 0x80, 0x00); } return 0; } static int msm8x16_wcd_codec_enable_dmic(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); u8 dmic_clk_en; u16 dmic_clk_reg; s32 *dmic_clk_cnt; unsigned int dmic; int ret; char *dec_num = strpbrk(w->name, "12"); if (dec_num == NULL) { dev_err(codec->dev, "%s: Invalid DMIC\n", __func__); return -EINVAL; } ret = kstrtouint(dec_num, 10, &dmic); if (ret < 0) { dev_err(codec->dev, "%s: Invalid DMIC line on the codec\n", __func__); return -EINVAL; } switch (dmic) { case 1: case 2: dmic_clk_en = 0x01; dmic_clk_cnt = &(msm8x16_wcd->dmic_1_2_clk_cnt); dmic_clk_reg = MSM8X16_WCD_A_CDC_CLK_DMIC_B1_CTL; dev_dbg(codec->dev, "%s() event %d DMIC%d dmic_1_2_clk_cnt %d\n", __func__, event, dmic, *dmic_clk_cnt); break; default: dev_err(codec->dev, "%s: Invalid DMIC Selection\n", __func__); return -EINVAL; } switch (event) { case SND_SOC_DAPM_PRE_PMU: (*dmic_clk_cnt)++; if (*dmic_clk_cnt == 1) { snd_soc_update_bits(codec, dmic_clk_reg, 0x0E, 0x02); snd_soc_update_bits(codec, dmic_clk_reg, dmic_clk_en, dmic_clk_en); } if (dmic == 1) snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_TX1_DMIC_CTL, 0x07, 0x01); if (dmic == 2) snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_TX2_DMIC_CTL, 0x07, 0x01); break; case SND_SOC_DAPM_POST_PMD: (*dmic_clk_cnt)--; if (*dmic_clk_cnt == 0) snd_soc_update_bits(codec, dmic_clk_reg, dmic_clk_en, 0); break; } return 0; } static bool msm8x16_wcd_use_mb(struct snd_soc_codec *codec) { struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); if (get_codec_version(msm8x16_wcd) < CAJON) return true; else return false; } static void msm8x16_wcd_set_auto_zeroing(struct snd_soc_codec *codec, bool enable) { struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); if (get_codec_version(msm8x16_wcd) < CONGA) { if (enable) snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MICB_2_EN, 0x18, 0x10); else snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MICB_2_EN, 0x18, 0x00); } else { pr_debug("%s: Auto Zeroing is not required from CONGA\n", __func__); } } static void msm8x16_trim_btn_reg(struct snd_soc_codec *codec) { struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); if (get_codec_version(msm8x16_wcd) == TOMBAK_1_0) { pr_debug("%s: This device needs to be trimmed\n", __func__); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SEC_ACCESS, 0xA5, 0xA5); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_TRIM_CTRL2, 0xFF, 0x30); } else { pr_debug("%s: This device is trimmed at ATE\n", __func__); } } static int msm8x16_wcd_enable_ext_mb_source(struct snd_soc_codec *codec, bool turn_on) { int ret = 0; static int count; dev_dbg(codec->dev, "%s turn_on: %d count: %d\n", __func__, turn_on, count); if (turn_on) { if (!count) { ret = snd_soc_dapm_force_enable_pin(&codec->dapm, "MICBIAS_REGULATOR"); snd_soc_dapm_sync(&codec->dapm); } count++; } else { if (count > 0) count--; if (!count) { ret = snd_soc_dapm_disable_pin(&codec->dapm, "MICBIAS_REGULATOR"); snd_soc_dapm_sync(&codec->dapm); } } if (ret) dev_err(codec->dev, "%s: Failed to %s external micbias source\n", __func__, turn_on ? "enable" : "disabled"); else dev_dbg(codec->dev, "%s: %s external micbias source\n", __func__, turn_on ? "Enabled" : "Disabled"); return ret; } static int msm8x16_wcd_codec_enable_micbias(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); u16 micb_int_reg; char *internal1_text = "Internal1"; char *internal2_text = "Internal2"; char *internal3_text = "Internal3"; char *external2_text = "External2"; char *external_text = "External"; bool micbias2; dev_dbg(codec->dev, "%s %d\n", __func__, event); switch (w->reg) { case MSM8X16_WCD_A_ANALOG_MICB_1_EN: case MSM8X16_WCD_A_ANALOG_MICB_2_EN: micb_int_reg = MSM8X16_WCD_A_ANALOG_MICB_1_INT_RBIAS; break; default: dev_err(codec->dev, "%s: Error, invalid micbias register 0x%x\n", __func__, w->reg); return -EINVAL; } micbias2 = (snd_soc_read(codec, MSM8X16_WCD_A_ANALOG_MICB_2_EN) & 0x80); switch (event) { case SND_SOC_DAPM_PRE_PMU: if (strnstr(w->name, internal1_text, strlen(w->name))) { if (get_codec_version(msm8x16_wcd) >= CAJON) snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_TX_1_2_ATEST_CTL_2, 0x02, 0x02); snd_soc_update_bits(codec, micb_int_reg, 0x80, 0x80); } else if (strnstr(w->name, internal2_text, strlen(w->name))) { snd_soc_update_bits(codec, micb_int_reg, 0x10, 0x10); snd_soc_update_bits(codec, w->reg, 0x60, 0x00); } else if (strnstr(w->name, internal3_text, strlen(w->name))) { snd_soc_update_bits(codec, micb_int_reg, 0x2, 0x2); } else if (!strnstr(w->name, external2_text, strlen(w->name)) && strnstr(w->name, external_text, strlen(w->name))) { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_TX_1_2_ATEST_CTL_2, 0x02, 0x02); } if (!strnstr(w->name, external_text, strlen(w->name))) snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MICB_1_EN, 0x05, 0x04); if (w->reg == MSM8X16_WCD_A_ANALOG_MICB_1_EN) msm8x16_wcd_configure_cap(codec, true, micbias2); break; case SND_SOC_DAPM_POST_PMU: if (get_codec_version(msm8x16_wcd) <= TOMBAK_2_0) usleep_range(20000, 20100); if (strnstr(w->name, internal1_text, strlen(w->name))) { snd_soc_update_bits(codec, micb_int_reg, 0x40, 0x40); } else if (strnstr(w->name, internal2_text, strlen(w->name))) { snd_soc_update_bits(codec, micb_int_reg, 0x08, 0x08); msm8x16_notifier_call(codec, WCD_EVENT_POST_MICBIAS_2_ON); } else if (strnstr(w->name, internal3_text, 30)) { snd_soc_update_bits(codec, micb_int_reg, 0x01, 0x01); } else if (strnstr(w->name, external2_text, strlen(w->name))) { msm8x16_notifier_call(codec, WCD_EVENT_POST_MICBIAS_2_ON); } break; case SND_SOC_DAPM_POST_PMD: if (strnstr(w->name, internal1_text, strlen(w->name))) { snd_soc_update_bits(codec, micb_int_reg, 0xC0, 0x40); } else if (strnstr(w->name, internal2_text, strlen(w->name))) { msm8x16_notifier_call(codec, WCD_EVENT_POST_MICBIAS_2_OFF); } else if (strnstr(w->name, internal3_text, 30)) { snd_soc_update_bits(codec, micb_int_reg, 0x2, 0x0); } else if (strnstr(w->name, external2_text, strlen(w->name))) { msm8x16_notifier_call(codec, WCD_EVENT_POST_MICBIAS_2_OFF); break; } if (w->reg == MSM8X16_WCD_A_ANALOG_MICB_1_EN) msm8x16_wcd_configure_cap(codec, false, micbias2); break; } return 0; } static void tx_hpf_corner_freq_callback(struct work_struct *work) { struct delayed_work *hpf_delayed_work; struct hpf_work *hpf_work; struct msm8x16_wcd_priv *msm8x16_wcd; struct snd_soc_codec *codec; u16 tx_mux_ctl_reg; u8 hpf_cut_of_freq; hpf_delayed_work = to_delayed_work(work); hpf_work = container_of(hpf_delayed_work, struct hpf_work, dwork); msm8x16_wcd = hpf_work->msm8x16_wcd; codec = hpf_work->msm8x16_wcd->codec; hpf_cut_of_freq = hpf_work->tx_hpf_cut_of_freq; tx_mux_ctl_reg = MSM8X16_WCD_A_CDC_TX1_MUX_CTL + (hpf_work->decimator - 1) * 32; dev_dbg(codec->dev, "%s(): decimator %u hpf_cut_of_freq 0x%x\n", __func__, hpf_work->decimator, (unsigned int)hpf_cut_of_freq); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_TX_1_2_TXFE_CLKDIV, 0xFF, 0x51); snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x30, hpf_cut_of_freq << 4); } #define TX_MUX_CTL_CUT_OFF_FREQ_MASK 0x30 #define CF_MIN_3DB_4HZ 0x0 #define CF_MIN_3DB_75HZ 0x1 #define CF_MIN_3DB_150HZ 0x2 static int msm8x16_wcd_codec_set_iir_gain(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; int value = 0, reg; switch (event) { case SND_SOC_DAPM_POST_PMU: if (w->shift == 0) reg = MSM8X16_WCD_A_CDC_IIR1_GAIN_B1_CTL; else if (w->shift == 1) reg = MSM8X16_WCD_A_CDC_IIR2_GAIN_B1_CTL; value = snd_soc_read(codec, reg); snd_soc_write(codec, reg, value); break; default: pr_err("%s: event = %d not expected\n", __func__, event); } return 0; } static int msm8x16_wcd_codec_enable_dec(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct msm8916_asoc_mach_data *pdata = NULL; unsigned int decimator; struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); char *dec_name = NULL; char *widget_name = NULL; char *temp; int ret = 0, i; u16 dec_reset_reg, tx_vol_ctl_reg, tx_mux_ctl_reg; u8 dec_hpf_cut_of_freq; int offset; char *dec_num; pdata = snd_soc_card_get_drvdata(codec->component.card); dev_dbg(codec->dev, "%s %d\n", __func__, event); widget_name = kstrndup(w->name, 15, GFP_KERNEL); if (!widget_name) return -ENOMEM; temp = widget_name; dec_name = strsep(&widget_name, " "); widget_name = temp; if (!dec_name) { dev_err(codec->dev, "%s: Invalid decimator = %s\n", __func__, w->name); ret = -EINVAL; goto out; } dec_num = strpbrk(dec_name, "1234"); if (dec_num == NULL) { dev_err(codec->dev, "%s: Invalid Decimator\n", __func__); ret = -EINVAL; goto out; } ret = kstrtouint(dec_num, 10, &decimator); if (ret < 0) { dev_err(codec->dev, "%s: Invalid decimator = %s\n", __func__, dec_name); ret = -EINVAL; goto out; } dev_dbg(codec->dev, "%s(): widget = %s dec_name = %s decimator = %u\n", __func__, w->name, dec_name, decimator); if (w->reg == MSM8X16_WCD_A_CDC_CLK_TX_CLK_EN_B1_CTL) { dec_reset_reg = MSM8X16_WCD_A_CDC_CLK_TX_RESET_B1_CTL; offset = 0; } else { dev_err(codec->dev, "%s: Error, incorrect dec\n", __func__); ret = -EINVAL; goto out; } tx_vol_ctl_reg = MSM8X16_WCD_A_CDC_TX1_VOL_CTL_CFG + 32 * (decimator - 1); tx_mux_ctl_reg = MSM8X16_WCD_A_CDC_TX1_MUX_CTL + 32 * (decimator - 1); switch (event) { case SND_SOC_DAPM_PRE_PMU: if (decimator == 3 || decimator == 4) { snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_CLK_WSA_VI_B1_CTL, 0xFF, 0x5); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_TX1_DMIC_CTL + (decimator - 1) * 0x20, 0x7, 0x2); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_TX1_DMIC_CTL + (decimator - 1) * 0x20, 0x7, 0x2); } snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, 0x01); for (i = 0; i < NUM_DECIMATORS; i++) { if (decimator == i + 1) msm8x16_wcd->dec_active[i] = true; } dec_hpf_cut_of_freq = snd_soc_read(codec, tx_mux_ctl_reg); dec_hpf_cut_of_freq = (dec_hpf_cut_of_freq & 0x30) >> 4; tx_hpf_work[decimator - 1].tx_hpf_cut_of_freq = dec_hpf_cut_of_freq; if (dec_hpf_cut_of_freq != CF_MIN_3DB_150HZ) { snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x30, CF_MIN_3DB_150HZ << 4); } snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_TX_1_2_TXFE_CLKDIV, 0xFF, 0x42); break; case SND_SOC_DAPM_POST_PMU: snd_soc_update_bits(codec, tx_mux_ctl_reg , 0x08, 0x00); if (tx_hpf_work[decimator - 1].tx_hpf_cut_of_freq != CF_MIN_3DB_150HZ) { schedule_delayed_work(&tx_hpf_work[decimator - 1].dwork, msecs_to_jiffies(300)); } if ((w->shift) < ARRAY_SIZE(tx_digital_gain_reg)) snd_soc_write(codec, tx_digital_gain_reg[w->shift + offset], snd_soc_read(codec, tx_digital_gain_reg[w->shift + offset]) ); if (pdata->lb_mode) { pr_debug("%s: loopback mode unmute the DEC\n", __func__); snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, 0x00); } break; case SND_SOC_DAPM_PRE_PMD: snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, 0x01); msleep(20); snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x08, 0x08); cancel_delayed_work_sync(&tx_hpf_work[decimator - 1].dwork); break; case SND_SOC_DAPM_POST_PMD: snd_soc_update_bits(codec, dec_reset_reg, 1 << w->shift, 1 << w->shift); snd_soc_update_bits(codec, dec_reset_reg, 1 << w->shift, 0x0); snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x08, 0x08); snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x30, (tx_hpf_work[decimator - 1].tx_hpf_cut_of_freq) << 4); snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, 0x00); for (i = 0; i < NUM_DECIMATORS; i++) { if (decimator == i + 1) msm8x16_wcd->dec_active[i] = false; } if (decimator == 3 || decimator == 4) { snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_CLK_WSA_VI_B1_CTL, 0xFF, 0x0); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_TX1_DMIC_CTL + (decimator - 1) * 0x20, 0x7, 0x0); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_TX1_DMIC_CTL + (decimator - 1) * 0x20, 0x7, 0x0); } break; } out: kfree(widget_name); return ret; } static int msm89xx_wcd_codec_enable_vdd_spkr(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); int ret = 0; if (!msm8x16_wcd->ext_spk_boost_set) { dev_dbg(codec->dev, "%s: ext_boost not supported/disabled\n", __func__); return 0; } dev_dbg(codec->dev, "%s: %s %d\n", __func__, w->name, event); switch (event) { case SND_SOC_DAPM_PRE_PMU: if (msm8x16_wcd->spkdrv_reg) { ret = regulator_enable(msm8x16_wcd->spkdrv_reg); if (ret) dev_err(codec->dev, "%s Failed to enable spkdrv reg %s\n", __func__, MSM89XX_VDD_SPKDRV_NAME); } break; case SND_SOC_DAPM_POST_PMD: if (msm8x16_wcd->spkdrv_reg) { ret = regulator_disable(msm8x16_wcd->spkdrv_reg); if (ret) dev_err(codec->dev, "%s: Failed to disable spkdrv_reg %s\n", __func__, MSM89XX_VDD_SPKDRV_NAME); } break; } return 0; } static int msm8x16_wcd_codec_config_compander(struct snd_soc_codec *codec, int interp_n, int event) { struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s: event %d shift %d, enabled %d\n", __func__, event, interp_n, msm8x16_wcd->comp_enabled[interp_n]); if (!msm8x16_wcd->comp_enabled[interp_n]) return 0; switch (msm8x16_wcd->comp_enabled[interp_n]) { case COMPANDER_1: if (SND_SOC_DAPM_EVENT_ON(event)) { snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_COMP0_B2_CTL, 0x0F, 0x09); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_CLK_RX_B2_CTL, 0x01, 0x01); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_COMP0_B1_CTL, 1 << interp_n, 1 << interp_n); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_COMP0_B3_CTL, 0xFF, 0x01); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_COMP0_B2_CTL, 0xF0, 0x50); usleep_range(1000, 1100); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_COMP0_B3_CTL, 0xFF, 0x28); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_COMP0_B2_CTL, 0xF0, 0xB0); if (msm8x16_wcd->codec_hph_comp_gpio) msm8x16_wcd->codec_hph_comp_gpio(1); } else if (SND_SOC_DAPM_EVENT_OFF(event)) { if (msm8x16_wcd->codec_hph_comp_gpio) msm8x16_wcd->codec_hph_comp_gpio(0); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_COMP0_B2_CTL, 0x0F, 0x05); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_COMP0_B1_CTL, 1 << interp_n, 0); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_CLK_RX_B2_CTL, 0x01, 0x00); } break; default: dev_dbg(codec->dev, "%s: Invalid compander %d\n", __func__, msm8x16_wcd->comp_enabled[interp_n]); break; }; return 0; } static int msm8x16_wcd_codec_enable_interpolator(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s %d %s\n", __func__, event, w->name); switch (event) { case SND_SOC_DAPM_POST_PMU: msm8x16_wcd_codec_config_compander(codec, w->shift, event); if ((w->shift) < ARRAY_SIZE(rx_digital_gain_reg)) snd_soc_write(codec, rx_digital_gain_reg[w->shift], snd_soc_read(codec, rx_digital_gain_reg[w->shift]) ); break; case SND_SOC_DAPM_POST_PMD: msm8x16_wcd_codec_config_compander(codec, w->shift, event); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_CLK_RX_RESET_CTL, 1 << w->shift, 1 << w->shift); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_CLK_RX_RESET_CTL, 1 << w->shift, 0x0); if ((w->shift == 0) && (msm8x16_wcd->mute_mask & HPHL_PA_DISABLE)) { pr_debug("disabling HPHL mute\n"); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX1_B6_CTL, 0x01, 0x00); if (get_codec_version(msm8x16_wcd) >= CAJON) snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_BIAS_CNP, 0xF0, 0x20); msm8x16_wcd->mute_mask &= ~(HPHL_PA_DISABLE); } else if ((w->shift == 1) && (msm8x16_wcd->mute_mask & HPHR_PA_DISABLE)) { pr_debug("disabling HPHR mute\n"); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX2_B6_CTL, 0x01, 0x00); if (get_codec_version(msm8x16_wcd) >= CAJON) snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_BIAS_CNP, 0xF0, 0x20); msm8x16_wcd->mute_mask &= ~(HPHR_PA_DISABLE); } else if ((w->shift == 2) && (msm8x16_wcd->mute_mask & SPKR_PA_DISABLE)) { pr_debug("disabling SPKR mute\n"); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX3_B6_CTL, 0x01, 0x00); msm8x16_wcd->mute_mask &= ~(SPKR_PA_DISABLE); } else if ((w->shift == 0) && (msm8x16_wcd->mute_mask & EAR_PA_DISABLE)) { pr_debug("disabling EAR mute\n"); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX1_B6_CTL, 0x01, 0x00); msm8x16_wcd->mute_mask &= ~(EAR_PA_DISABLE); } } return 0; } static int msm8x16_wcd_codec_enable_rx_bias(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s %d\n", __func__, event); switch (event) { case SND_SOC_DAPM_PRE_PMU: msm8x16_wcd->rx_bias_count++; if (msm8x16_wcd->rx_bias_count == 1) { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_COM_BIAS_DAC, 0x80, 0x80); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_COM_BIAS_DAC, 0x01, 0x01); } break; case SND_SOC_DAPM_POST_PMD: msm8x16_wcd->rx_bias_count--; if (msm8x16_wcd->rx_bias_count == 0) { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_COM_BIAS_DAC, 0x01, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_COM_BIAS_DAC, 0x80, 0x00); } break; } dev_dbg(codec->dev, "%s rx_bias_count = %d\n", __func__, msm8x16_wcd->rx_bias_count); return 0; } static uint32_t wcd_get_impedance_value(uint32_t imped) { int i; for (i = 0; i < ARRAY_SIZE(wcd_imped_val) - 1; i++) { if (imped >= wcd_imped_val[i] && imped < wcd_imped_val[i + 1]) break; } pr_debug("%s: selected impedance value = %d\n", __func__, wcd_imped_val[i]); return wcd_imped_val[i]; } void wcd_imped_config(struct snd_soc_codec *codec, uint32_t imped, bool set_gain) { uint32_t value; int codec_version; struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); value = wcd_get_impedance_value(imped); if (value < wcd_imped_val[0]) { pr_debug("%s, detected impedance is less than 4 Ohm\n", __func__); return; } if (value >= wcd_imped_val[ARRAY_SIZE(wcd_imped_val) - 1]) { pr_err("%s, invalid imped, greater than 48 Ohm\n = %d\n", __func__, value); return; } codec_version = get_codec_version(msm8x16_wcd); if (set_gain) { switch (codec_version) { case TOMBAK_1_0: case TOMBAK_2_0: case CONGA: if (value >= 32) snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_EAR_CTL, 0x20, 0x20); else snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_EAR_CTL, 0x20, 0x00); break; case CAJON: case CAJON_2_0: case DIANGU: if (value >= 13) { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_EAR_CTL, 0x20, 0x20); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_NCP_VCTRL, 0x07, 0x07); } else { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_EAR_CTL, 0x20, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_NCP_VCTRL, 0x07, 0x04); } break; } } else { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_EAR_CTL, 0x20, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_NCP_VCTRL, 0x07, 0x04); } pr_debug("%s: Exit\n", __func__); } static int msm8x16_wcd_hphl_dac_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { uint32_t impedl, impedr; struct snd_soc_codec *codec = w->codec; struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); int ret; dev_dbg(codec->dev, "%s %s %d\n", __func__, w->name, event); ret = wcd_mbhc_get_impedance(&msm8x16_wcd->mbhc, &impedl, &impedr); switch (event) { case SND_SOC_DAPM_PRE_PMU: if (get_codec_version(msm8x16_wcd) > CAJON) snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_CNP_EN, 0x08, 0x08); if (get_codec_version(msm8x16_wcd) == CAJON || get_codec_version(msm8x16_wcd) == CAJON_2_0) { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_L_TEST, 0x80, 0x80); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_R_TEST, 0x80, 0x80); } if (get_codec_version(msm8x16_wcd) > CAJON) snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_CNP_EN, 0x08, 0x00); if (HD2_MODE == msm8x16_wcd->hph_mode) { snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX1_B3_CTL, 0x1C, 0x14); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX1_B4_CTL, 0x18, 0x10); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX1_B3_CTL, 0x80, 0x80); } snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_L_PA_DAC_CTL, 0x02, 0x02); snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 0x01, 0x01); snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_ANA_CLK_CTL, 0x02, 0x02); if (!ret) wcd_imped_config(codec, impedl, true); else dev_dbg(codec->dev, "Failed to get mbhc impedance %d\n", ret); break; case SND_SOC_DAPM_POST_PMU: snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_L_PA_DAC_CTL, 0x02, 0x00); break; case SND_SOC_DAPM_POST_PMD: wcd_imped_config(codec, impedl, false); snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_ANA_CLK_CTL, 0x02, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 0x01, 0x00); if (HD2_MODE == msm8x16_wcd->hph_mode) { snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX1_B3_CTL, 0x1C, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX1_B4_CTL, 0x18, 0xFF); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX1_B3_CTL, 0x80, 0x00); } break; } return 0; } static int msm8x16_wcd_lo_dac_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; dev_dbg(codec->dev, "%s %s %d\n", __func__, w->name, event); switch (event) { case SND_SOC_DAPM_PRE_PMU: snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_ANA_CLK_CTL, 0x10, 0x10); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_LO_EN_CTL, 0x20, 0x20); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_LO_EN_CTL, 0x80, 0x80); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_LO_DAC_CTL, 0x08, 0x08); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_LO_DAC_CTL, 0x40, 0x40); break; case SND_SOC_DAPM_POST_PMU: snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_LO_DAC_CTL, 0x80, 0x80); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_LO_DAC_CTL, 0x08, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_LO_EN_CTL, 0x40, 0x40); break; case SND_SOC_DAPM_POST_PMD: usleep_range(20000, 20100); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_LO_DAC_CTL, 0x80, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_LO_DAC_CTL, 0x40, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_LO_DAC_CTL, 0x08, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_LO_EN_CTL, 0x80, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_LO_EN_CTL, 0x40, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_LO_EN_CTL, 0x20, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_ANA_CLK_CTL, 0x10, 0x00); break; } return 0; } static int msm8x16_wcd_hphr_dac_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s %s %d\n", __func__, w->name, event); switch (event) { case SND_SOC_DAPM_PRE_PMU: if (HD2_MODE == msm8x16_wcd->hph_mode) { snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX2_B3_CTL, 0x1C, 0x14); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX2_B4_CTL, 0x18, 0x10); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX2_B3_CTL, 0x80, 0x80); } snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_R_PA_DAC_CTL, 0x02, 0x02); snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 0x02, 0x02); snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_ANA_CLK_CTL, 0x01, 0x01); break; case SND_SOC_DAPM_POST_PMU: snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_R_PA_DAC_CTL, 0x02, 0x00); break; case SND_SOC_DAPM_POST_PMD: snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_ANA_CLK_CTL, 0x01, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 0x02, 0x00); if (HD2_MODE == msm8x16_wcd->hph_mode) { snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX2_B3_CTL, 0x1C, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX2_B4_CTL, 0x18, 0xFF); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX2_B3_CTL, 0x80, 0x00); } break; } return 0; } static int msm8x16_wcd_hph_pa_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s: %s event = %d\n", __func__, w->name, event); switch (event) { case SND_SOC_DAPM_PRE_PMU: if (w->shift == 5) msm8x16_notifier_call(codec, WCD_EVENT_PRE_HPHL_PA_ON); else if (w->shift == 4) msm8x16_notifier_call(codec, WCD_EVENT_PRE_HPHR_PA_ON); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_NCP_FBCTRL, 0x20, 0x20); break; case SND_SOC_DAPM_POST_PMU: usleep_range(7000, 7100); if (w->shift == 5) { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_L_TEST, 0x04, 0x04); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX1_B6_CTL, 0x01, 0x00); } else if (w->shift == 4) { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_R_TEST, 0x04, 0x04); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX2_B6_CTL, 0x01, 0x00); } break; case SND_SOC_DAPM_PRE_PMD: if (w->shift == 5) { snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX1_B6_CTL, 0x01, 0x01); msleep(20); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_L_TEST, 0x04, 0x00); msm8x16_wcd->mute_mask |= HPHL_PA_DISABLE; msm8x16_notifier_call(codec, WCD_EVENT_PRE_HPHL_PA_OFF); } else if (w->shift == 4) { snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX2_B6_CTL, 0x01, 0x01); msleep(20); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_R_TEST, 0x04, 0x00); msm8x16_wcd->mute_mask |= HPHR_PA_DISABLE; msm8x16_notifier_call(codec, WCD_EVENT_PRE_HPHR_PA_OFF); } if (get_codec_version(msm8x16_wcd) >= CAJON) { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_BIAS_CNP, 0xF0, 0x30); } break; case SND_SOC_DAPM_POST_PMD: if (w->shift == 5) { clear_bit(WCD_MBHC_HPHL_PA_OFF_ACK, &msm8x16_wcd->mbhc.hph_pa_dac_state); msm8x16_notifier_call(codec, WCD_EVENT_POST_HPHL_PA_OFF); } else if (w->shift == 4) { clear_bit(WCD_MBHC_HPHR_PA_OFF_ACK, &msm8x16_wcd->mbhc.hph_pa_dac_state); msm8x16_notifier_call(codec, WCD_EVENT_POST_HPHR_PA_OFF); } usleep_range(4000, 4100); usleep_range(CODEC_DELAY_1_MS, CODEC_DELAY_1_1_MS); dev_dbg(codec->dev, "%s: sleep 10 ms after %s PA disable.\n", __func__, w->name); usleep_range(10000, 10100); break; } return 0; } static const struct snd_soc_dapm_route audio_map[] = { {"RX_I2S_CLK", NULL, "CDC_CONN"}, {"I2S RX1", NULL, "RX_I2S_CLK"}, {"I2S RX2", NULL, "RX_I2S_CLK"}, {"I2S RX3", NULL, "RX_I2S_CLK"}, {"I2S TX1", NULL, "TX_I2S_CLK"}, {"I2S TX2", NULL, "TX_I2S_CLK"}, {"AIF2 VI", NULL, "TX_I2S_CLK"}, {"I2S TX1", NULL, "DEC1 MUX"}, {"I2S TX2", NULL, "DEC2 MUX"}, {"AIF2 VI", NULL, "DEC3 MUX"}, {"AIF2 VI", NULL, "DEC4 MUX"}, {"HPHR DAC", NULL, "RDAC2 MUX"}, {"RDAC2 MUX", "RX1", "RX1 CHAIN"}, {"RDAC2 MUX", "RX2", "RX2 CHAIN"}, {"WSA_SPK OUT", NULL, "WSA Spk Switch"}, {"WSA Spk Switch", "WSA", "EAR PA"}, {"EAR", NULL, "EAR_S"}, {"EAR_S", "Switch", "EAR PA"}, {"EAR PA", NULL, "RX_BIAS"}, {"EAR PA", NULL, "HPHL DAC"}, {"EAR PA", NULL, "HPHR DAC"}, {"EAR PA", NULL, "EAR CP"}, {"HEADPHONE", NULL, "HPHL PA"}, {"HEADPHONE", NULL, "HPHR PA"}, {"Ext Spk", NULL, "Ext Spk Switch"}, {"Ext Spk Switch", "On", "HPHL PA"}, {"Ext Spk Switch", "On", "HPHR PA"}, {"HPHL PA", NULL, "HPHL"}, {"HPHR PA", NULL, "HPHR"}, {"HPHL", "Switch", "HPHL DAC"}, {"HPHR", "Switch", "HPHR DAC"}, {"HPHL PA", NULL, "CP"}, {"HPHL PA", NULL, "RX_BIAS"}, {"HPHR PA", NULL, "CP"}, {"HPHR PA", NULL, "RX_BIAS"}, {"HPHL DAC", NULL, "RX1 CHAIN"}, {"SPK_OUT", NULL, "SPK PA"}, {"SPK PA", NULL, "SPK_RX_BIAS"}, {"SPK PA", NULL, "SPK"}, {"SPK", "Switch", "SPK DAC"}, {"SPK DAC", NULL, "RX3 CHAIN"}, {"SPK DAC", NULL, "VDD_SPKDRV"}, {"LINEOUT", NULL, "LINEOUT PA"}, {"LINEOUT PA", NULL, "SPK_RX_BIAS"}, {"LINEOUT PA", NULL, "LINE_OUT"}, {"LINE_OUT", "Switch", "LINEOUT DAC"}, {"LINEOUT DAC", NULL, "RX3 CHAIN"}, {"WSA_SPK OUT", NULL, "LINEOUT PA"}, {"RX1 CHAIN", NULL, "RX1 CLK"}, {"RX2 CHAIN", NULL, "RX2 CLK"}, {"RX3 CHAIN", NULL, "RX3 CLK"}, {"RX1 CHAIN", NULL, "RX1 MIX2"}, {"RX2 CHAIN", NULL, "RX2 MIX2"}, {"RX3 CHAIN", NULL, "RX3 MIX1"}, {"RX1 MIX1", NULL, "RX1 MIX1 INP1"}, {"RX1 MIX1", NULL, "RX1 MIX1 INP2"}, {"RX1 MIX1", NULL, "RX1 MIX1 INP3"}, {"RX2 MIX1", NULL, "RX2 MIX1 INP1"}, {"RX2 MIX1", NULL, "RX2 MIX1 INP2"}, {"RX3 MIX1", NULL, "RX3 MIX1 INP1"}, {"RX3 MIX1", NULL, "RX3 MIX1 INP2"}, {"RX1 MIX2", NULL, "RX1 MIX1"}, {"RX1 MIX2", NULL, "RX1 MIX2 INP1"}, {"RX2 MIX2", NULL, "RX2 MIX1"}, {"RX2 MIX2", NULL, "RX2 MIX2 INP1"}, {"RX1 MIX1 INP1", "RX1", "I2S RX1"}, {"RX1 MIX1 INP1", "RX2", "I2S RX2"}, {"RX1 MIX1 INP1", "RX3", "I2S RX3"}, {"RX1 MIX1 INP1", "IIR1", "IIR1"}, {"RX1 MIX1 INP1", "IIR2", "IIR2"}, {"RX1 MIX1 INP2", "RX1", "I2S RX1"}, {"RX1 MIX1 INP2", "RX2", "I2S RX2"}, {"RX1 MIX1 INP2", "RX3", "I2S RX3"}, {"RX1 MIX1 INP2", "IIR1", "IIR1"}, {"RX1 MIX1 INP2", "IIR2", "IIR2"}, {"RX1 MIX1 INP3", "RX1", "I2S RX1"}, {"RX1 MIX1 INP3", "RX2", "I2S RX2"}, {"RX1 MIX1 INP3", "RX3", "I2S RX3"}, {"RX2 MIX1 INP1", "RX1", "I2S RX1"}, {"RX2 MIX1 INP1", "RX2", "I2S RX2"}, {"RX2 MIX1 INP1", "RX3", "I2S RX3"}, {"RX2 MIX1 INP1", "IIR1", "IIR1"}, {"RX2 MIX1 INP1", "IIR2", "IIR2"}, {"RX2 MIX1 INP2", "RX1", "I2S RX1"}, {"RX2 MIX1 INP2", "RX2", "I2S RX2"}, {"RX2 MIX1 INP2", "RX3", "I2S RX3"}, {"RX2 MIX1 INP2", "IIR1", "IIR1"}, {"RX2 MIX1 INP2", "IIR2", "IIR2"}, {"RX3 MIX1 INP1", "RX1", "I2S RX1"}, {"RX3 MIX1 INP1", "RX2", "I2S RX2"}, {"RX3 MIX1 INP1", "RX3", "I2S RX3"}, {"RX3 MIX1 INP1", "IIR1", "IIR1"}, {"RX3 MIX1 INP1", "IIR2", "IIR2"}, {"RX3 MIX1 INP2", "RX1", "I2S RX1"}, {"RX3 MIX1 INP2", "RX2", "I2S RX2"}, {"RX3 MIX1 INP2", "RX3", "I2S RX3"}, {"RX3 MIX1 INP2", "IIR1", "IIR1"}, {"RX3 MIX1 INP2", "IIR2", "IIR2"}, {"RX1 MIX2 INP1", "IIR1", "IIR1"}, {"RX2 MIX2 INP1", "IIR1", "IIR1"}, {"RX1 MIX2 INP1", "IIR2", "IIR2"}, {"RX2 MIX2 INP1", "IIR2", "IIR2"}, {"DEC1 MUX", "DMIC1", "DMIC1"}, {"DEC1 MUX", "DMIC2", "DMIC2"}, {"DEC1 MUX", "ADC1", "ADC1"}, {"DEC1 MUX", "ADC2", "ADC2"}, {"DEC1 MUX", "ADC3", "ADC3"}, {"DEC1 MUX", NULL, "CDC_CONN"}, {"DEC2 MUX", "DMIC1", "DMIC1"}, {"DEC2 MUX", "DMIC2", "DMIC2"}, {"DEC2 MUX", "ADC1", "ADC1"}, {"DEC2 MUX", "ADC2", "ADC2"}, {"DEC2 MUX", "ADC3", "ADC3"}, {"DEC2 MUX", NULL, "CDC_CONN"}, {"DEC3 MUX", "DMIC3", "DMIC3"}, {"DEC4 MUX", "DMIC4", "DMIC4"}, {"DEC3 MUX", NULL, "CDC_CONN"}, {"DEC4 MUX", NULL, "CDC_CONN"}, {"ADC2", NULL, "ADC2 MUX"}, {"ADC3", NULL, "ADC2 MUX"}, {"ADC2 MUX", "INP2", "ADC2_INP2"}, {"ADC2 MUX", "INP3", "ADC2_INP3"}, {"ADC1", NULL, "AMIC1"}, {"ADC2_INP2", NULL, "AMIC2"}, {"ADC2_INP3", NULL, "AMIC3"}, {"IIR1", NULL, "IIR1 INP1 MUX"}, {"IIR1 INP1 MUX", "DEC1", "DEC1 MUX"}, {"IIR1 INP1 MUX", "DEC2", "DEC2 MUX"}, {"IIR2", NULL, "IIR2 INP1 MUX"}, {"IIR2 INP1 MUX", "DEC1", "DEC1 MUX"}, {"IIR2 INP1 MUX", "DEC2", "DEC2 MUX"}, {"MIC BIAS Internal1", NULL, "INT_LDO_H"}, {"MIC BIAS Internal2", NULL, "INT_LDO_H"}, {"MIC BIAS External", NULL, "INT_LDO_H"}, {"MIC BIAS External2", NULL, "INT_LDO_H"}, {"MIC BIAS Internal1", NULL, "MICBIAS_REGULATOR"}, {"MIC BIAS Internal2", NULL, "MICBIAS_REGULATOR"}, {"MIC BIAS External", NULL, "MICBIAS_REGULATOR"}, {"MIC BIAS External2", NULL, "MICBIAS_REGULATOR"}, }; static int msm8x16_wcd_startup(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(dai->codec); dev_dbg(dai->codec->dev, "%s(): substream = %s stream = %d\n", __func__, substream->name, substream->stream); if (test_bit(BUS_DOWN, &msm8x16_wcd->status_mask)) { dev_err(dai->codec->dev, "Error, Device is not up post SSR\n"); return -EINVAL; } return 0; } static void msm8x16_wcd_shutdown(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { dev_dbg(dai->codec->dev, "%s(): substream = %s stream = %d\n" , __func__, substream->name, substream->stream); } int msm8x16_wcd_mclk_enable(struct snd_soc_codec *codec, int mclk_enable, bool dapm) { struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s: mclk_enable = %u, dapm = %d\n", __func__, mclk_enable, dapm); if (mclk_enable) { msm8x16_wcd->mclk_enabled = true; msm8x16_wcd_codec_enable_clock_block(codec, 1); } else { if (!msm8x16_wcd->mclk_enabled) { dev_err(codec->dev, "Error, MCLK already diabled\n"); return -EINVAL; } msm8x16_wcd->mclk_enabled = false; msm8x16_wcd_codec_enable_clock_block(codec, 0); } return 0; } static int msm8x16_wcd_set_dai_sysclk(struct snd_soc_dai *dai, int clk_id, unsigned int freq, int dir) { dev_dbg(dai->codec->dev, "%s\n", __func__); return 0; } static int msm8x16_wcd_set_dai_fmt(struct snd_soc_dai *dai, unsigned int fmt) { dev_dbg(dai->codec->dev, "%s\n", __func__); return 0; } static int msm8x16_wcd_set_channel_map(struct snd_soc_dai *dai, unsigned int tx_num, unsigned int *tx_slot, unsigned int rx_num, unsigned int *rx_slot) { dev_dbg(dai->codec->dev, "%s\n", __func__); return 0; } static int msm8x16_wcd_get_channel_map(struct snd_soc_dai *dai, unsigned int *tx_num, unsigned int *tx_slot, unsigned int *rx_num, unsigned int *rx_slot) { dev_dbg(dai->codec->dev, "%s\n", __func__); return 0; } static int msm8x16_wcd_set_interpolator_rate(struct snd_soc_dai *dai, u8 rx_fs_rate_reg_val, u32 sample_rate) { snd_soc_update_bits(dai->codec, MSM8X16_WCD_A_CDC_RX1_B5_CTL, 0xF0, rx_fs_rate_reg_val); snd_soc_update_bits(dai->codec, MSM8X16_WCD_A_CDC_RX2_B5_CTL, 0xF0, rx_fs_rate_reg_val); return 0; } static int msm8x16_wcd_set_decimator_rate(struct snd_soc_dai *dai, u8 tx_fs_rate_reg_val, u32 sample_rate) { return 0; } static int msm8x16_wcd_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { u8 tx_fs_rate, rx_fs_rate, rx_clk_fs_rate; int ret; dev_dbg(dai->codec->dev, "%s: dai_name = %s DAI-ID %x rate %d num_ch %d format %d\n", __func__, dai->name, dai->id, params_rate(params), params_channels(params), params_format(params)); switch (params_rate(params)) { case 8000: tx_fs_rate = 0x00; rx_fs_rate = 0x00; rx_clk_fs_rate = 0x00; break; case 16000: tx_fs_rate = 0x20; rx_fs_rate = 0x20; rx_clk_fs_rate = 0x01; break; case 32000: tx_fs_rate = 0x40; rx_fs_rate = 0x40; rx_clk_fs_rate = 0x02; break; case 48000: tx_fs_rate = 0x60; rx_fs_rate = 0x60; rx_clk_fs_rate = 0x03; break; case 96000: tx_fs_rate = 0x80; rx_fs_rate = 0x80; rx_clk_fs_rate = 0x04; break; case 192000: tx_fs_rate = 0xA0; rx_fs_rate = 0xA0; rx_clk_fs_rate = 0x05; break; default: dev_err(dai->codec->dev, "%s: Invalid sampling rate %d\n", __func__, params_rate(params)); return -EINVAL; } snd_soc_update_bits(dai->codec, MSM8X16_WCD_A_CDC_CLK_RX_I2S_CTL, 0x0F, rx_clk_fs_rate); switch (substream->stream) { case SNDRV_PCM_STREAM_CAPTURE: ret = msm8x16_wcd_set_decimator_rate(dai, tx_fs_rate, params_rate(params)); if (ret < 0) { dev_err(dai->codec->dev, "%s: set decimator rate failed %d\n", __func__, ret); return ret; } break; case SNDRV_PCM_STREAM_PLAYBACK: ret = msm8x16_wcd_set_interpolator_rate(dai, rx_fs_rate, params_rate(params)); if (ret < 0) { dev_err(dai->codec->dev, "%s: set decimator rate failed %d\n", __func__, ret); return ret; } break; default: dev_err(dai->codec->dev, "%s: Invalid stream type %d\n", __func__, substream->stream); return -EINVAL; } switch (params_format(params)) { case SNDRV_PCM_FORMAT_S16_LE: snd_soc_update_bits(dai->codec, MSM8X16_WCD_A_CDC_CLK_RX_I2S_CTL, 0x20, 0x20); break; case SNDRV_PCM_FORMAT_S24_LE: case SNDRV_PCM_FORMAT_S24_3LE: snd_soc_update_bits(dai->codec, MSM8X16_WCD_A_CDC_CLK_RX_I2S_CTL, 0x20, 0x00); break; default: dev_err(dai->codec->dev, "%s: wrong format selected\n", __func__); return -EINVAL; } return 0; } int msm8x16_wcd_digital_mute(struct snd_soc_dai *dai, int mute) { struct snd_soc_codec *codec = NULL; u16 tx_vol_ctl_reg = 0; u8 decimator = 0, i; struct msm8x16_wcd_priv *msm8x16_wcd; pr_debug("%s: Digital Mute val = %d\n", __func__, mute); if (!dai || !dai->codec) { pr_err("%s: Invalid params\n", __func__); return -EINVAL; } codec = dai->codec; msm8x16_wcd = snd_soc_codec_get_drvdata(codec); if ((dai->id != AIF1_CAP) && (dai->id != AIF2_VIFEED)) { dev_dbg(codec->dev, "%s: Not capture use case skip\n", __func__); return 0; } mute = (mute) ? 1 : 0; if (!mute) { usleep_range(15000, 15010); } for (i = 0; i < NUM_DECIMATORS; i++) { if (msm8x16_wcd->dec_active[i]) decimator = i + 1; if (decimator && decimator <= NUM_DECIMATORS) { if (dai->id == AIF2_VIFEED && decimator > 2) { tx_vol_ctl_reg = MSM8X16_WCD_A_CDC_TX1_VOL_CTL_CFG + 32 * (decimator - 1); snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, mute); } else if (dai->id == AIF1_CAP && decimator < 3) { tx_vol_ctl_reg = MSM8X16_WCD_A_CDC_TX1_VOL_CTL_CFG + 32 * (decimator - 1); snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, mute); } } decimator = 0; } return 0; } static struct snd_soc_dai_ops msm8x16_wcd_dai_ops = { .startup = msm8x16_wcd_startup, .shutdown = msm8x16_wcd_shutdown, .hw_params = msm8x16_wcd_hw_params, .set_sysclk = msm8x16_wcd_set_dai_sysclk, .set_fmt = msm8x16_wcd_set_dai_fmt, .set_channel_map = msm8x16_wcd_set_channel_map, .get_channel_map = msm8x16_wcd_get_channel_map, .digital_mute = msm8x16_wcd_digital_mute, }; static struct snd_soc_dai_driver msm8x16_wcd_i2s_dai[] = { { .name = "msm8x16_wcd_i2s_rx1", .id = AIF1_PB, .playback = { .stream_name = "AIF1 Playback", .rates = MSM8X16_WCD_RATES, .formats = MSM8X16_WCD_FORMATS, .rate_max = 192000, .rate_min = 8000, .channels_min = 1, .channels_max = 3, }, .ops = &msm8x16_wcd_dai_ops, }, { .name = "msm8x16_wcd_i2s_tx1", .id = AIF1_CAP, .capture = { .stream_name = "AIF1 Capture", .rates = MSM8X16_WCD_RATES, .formats = MSM8X16_WCD_FORMATS, .rate_max = 192000, .rate_min = 8000, .channels_min = 1, .channels_max = 4, }, .ops = &msm8x16_wcd_dai_ops, }, { .name = "cajon_vifeedback", .id = AIF2_VIFEED, .capture = { .stream_name = "VIfeed", .rates = MSM8X16_WCD_RATES, .formats = MSM8X16_WCD_FORMATS, .rate_max = 48000, .rate_min = 48000, .channels_min = 2, .channels_max = 2, }, .ops = &msm8x16_wcd_dai_ops, }, }; static int msm8x16_wcd_codec_enable_rx_chain(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; switch (event) { case SND_SOC_DAPM_POST_PMU: dev_dbg(w->codec->dev, "%s: PMU:Sleeping 20ms after disabling mute\n", __func__); break; case SND_SOC_DAPM_POST_PMD: dev_dbg(w->codec->dev, "%s: PMD:Sleeping 20ms after disabling mute\n", __func__); snd_soc_update_bits(codec, w->reg, 1 << w->shift, 0x00); msleep(20); break; } return 0; } static int msm8x16_wcd_codec_enable_lo_pa(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; dev_dbg(w->codec->dev, "%s: %d %s\n", __func__, event, w->name); switch (event) { case SND_SOC_DAPM_POST_PMU: snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX3_B6_CTL, 0x01, 0x00); break; case SND_SOC_DAPM_POST_PMD: snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX3_B6_CTL, 0x01, 0x00); break; } return 0; } static int msm8x16_wcd_codec_enable_spk_ext_pa(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "%s: %s event = %d\n", __func__, w->name, event); switch (event) { case SND_SOC_DAPM_POST_PMU: dev_dbg(w->codec->dev, "%s: enable external speaker PA\n", __func__); if (msm8x16_wcd->codec_spk_ext_pa_cb) msm8x16_wcd->codec_spk_ext_pa_cb(codec, 1); break; case SND_SOC_DAPM_PRE_PMD: dev_dbg(w->codec->dev, "%s: enable external speaker PA\n", __func__); if (msm8x16_wcd->codec_spk_ext_pa_cb) msm8x16_wcd->codec_spk_ext_pa_cb(codec, 0); break; } return 0; } static int msm8x16_wcd_codec_enable_ear_pa(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); switch (event) { case SND_SOC_DAPM_PRE_PMU: dev_dbg(w->codec->dev, "%s: Sleeping 20ms after select EAR PA\n", __func__); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_EAR_CTL, 0x80, 0x80); if (get_codec_version(msm8x16_wcd) < CONGA) snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_CNP_WG_TIME, 0xFF, 0x2A); if (get_codec_version(msm8x16_wcd) >= DIANGU) { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_COM_BIAS_DAC, 0x08, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_L_TEST, 0x04, 0x04); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_R_TEST, 0x04, 0x04); } break; case SND_SOC_DAPM_POST_PMU: dev_dbg(w->codec->dev, "%s: Sleeping 20ms after enabling EAR PA\n", __func__); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_EAR_CTL, 0x40, 0x40); usleep_range(7000, 7100); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX1_B6_CTL, 0x01, 0x00); break; case SND_SOC_DAPM_PRE_PMD: snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_RX1_B6_CTL, 0x01, 0x01); msleep(20); msm8x16_wcd->mute_mask |= EAR_PA_DISABLE; if (msm8x16_wcd->boost_option == BOOST_ALWAYS) { dev_dbg(w->codec->dev, "%s: boost_option:%d, tear down ear\n", __func__, msm8x16_wcd->boost_option); msm8x16_wcd_boost_mode_sequence(codec, EAR_PMD); } if (get_codec_version(msm8x16_wcd) >= DIANGU) { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_L_TEST, 0x04, 0x0); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_R_TEST, 0x04, 0x0); } break; case SND_SOC_DAPM_POST_PMD: dev_dbg(w->codec->dev, "%s: Sleeping 7ms after disabling EAR PA\n", __func__); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_EAR_CTL, 0x40, 0x00); usleep_range(7000, 7100); if (get_codec_version(msm8x16_wcd) < CONGA) snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_CNP_WG_TIME, 0xFF, 0x16); if (get_codec_version(msm8x16_wcd) >= DIANGU) snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_COM_BIAS_DAC, 0x08, 0x08); break; } return 0; } static const struct snd_soc_dapm_widget msm8x16_wcd_dapm_widgets[] = { SND_SOC_DAPM_OUTPUT("EAR"), SND_SOC_DAPM_OUTPUT("WSA_SPK OUT"), SND_SOC_DAPM_PGA_E("EAR PA", SND_SOC_NOPM, 0, 0, NULL, 0, msm8x16_wcd_codec_enable_ear_pa, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MUX("EAR_S", SND_SOC_NOPM, 0, 0, ear_pa_mux), SND_SOC_DAPM_MUX("WSA Spk Switch", SND_SOC_NOPM, 0, 0, wsa_spk_mux), SND_SOC_DAPM_AIF_IN("I2S RX1", "AIF1 Playback", 0, SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_AIF_IN("I2S RX2", "AIF1 Playback", 0, SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_AIF_IN("I2S RX3", "AIF1 Playback", 0, SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_SUPPLY("INT_LDO_H", SND_SOC_NOPM, 1, 0, NULL, 0), SND_SOC_DAPM_SPK("Ext Spk", msm8x16_wcd_codec_enable_spk_ext_pa), SND_SOC_DAPM_OUTPUT("HEADPHONE"), SND_SOC_DAPM_PGA_E("HPHL PA", MSM8X16_WCD_A_ANALOG_RX_HPH_CNP_EN, 5, 0, NULL, 0, msm8x16_wcd_hph_pa_event, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MUX("HPHL", SND_SOC_NOPM, 0, 0, hphl_mux), SND_SOC_DAPM_MIXER_E("HPHL DAC", MSM8X16_WCD_A_ANALOG_RX_HPH_L_PA_DAC_CTL, 3, 0, NULL, 0, msm8x16_wcd_hphl_dac_event, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_PGA_E("HPHR PA", MSM8X16_WCD_A_ANALOG_RX_HPH_CNP_EN, 4, 0, NULL, 0, msm8x16_wcd_hph_pa_event, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MUX("HPHR", SND_SOC_NOPM, 0, 0, hphr_mux), SND_SOC_DAPM_MIXER_E("HPHR DAC", MSM8X16_WCD_A_ANALOG_RX_HPH_R_PA_DAC_CTL, 3, 0, NULL, 0, msm8x16_wcd_hphr_dac_event, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MUX("SPK", SND_SOC_NOPM, 0, 0, spkr_mux), SND_SOC_DAPM_DAC("SPK DAC", NULL, MSM8X16_WCD_A_ANALOG_SPKR_DAC_CTL, 7, 0), SND_SOC_DAPM_MUX("LINE_OUT", SND_SOC_NOPM, 0, 0, lo_mux), SND_SOC_DAPM_DAC_E("LINEOUT DAC", NULL, SND_SOC_NOPM, 0, 0, msm8x16_wcd_lo_dac_event, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_OUTPUT("SPK_OUT"), SND_SOC_DAPM_OUTPUT("LINEOUT"), SND_SOC_DAPM_PGA_E("SPK PA", MSM8X16_WCD_A_ANALOG_SPKR_DRV_CTL, 6, 0 , NULL, 0, msm8x16_wcd_codec_enable_spk_pa, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_PGA_E("LINEOUT PA", MSM8X16_WCD_A_ANALOG_RX_LO_EN_CTL, 5, 0 , NULL, 0, msm8x16_wcd_codec_enable_lo_pa, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_SUPPLY("VDD_SPKDRV", SND_SOC_NOPM, 0, 0, msm89xx_wcd_codec_enable_vdd_spkr, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MUX("Ext Spk Switch", SND_SOC_NOPM, 0, 0, &ext_spk_mux), SND_SOC_DAPM_MIXER("RX1 MIX1", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_MIXER("RX2 MIX1", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_MIXER_E("RX1 MIX2", MSM8X16_WCD_A_CDC_CLK_RX_B1_CTL, MSM8X16_WCD_RX1, 0, NULL, 0, msm8x16_wcd_codec_enable_interpolator, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MIXER_E("RX2 MIX2", MSM8X16_WCD_A_CDC_CLK_RX_B1_CTL, MSM8X16_WCD_RX2, 0, NULL, 0, msm8x16_wcd_codec_enable_interpolator, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MIXER_E("RX3 MIX1", MSM8X16_WCD_A_CDC_CLK_RX_B1_CTL, MSM8X16_WCD_RX3, 0, NULL, 0, msm8x16_wcd_codec_enable_interpolator, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_SUPPLY("RX1 CLK", MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 0, 0, NULL, 0), SND_SOC_DAPM_SUPPLY("RX2 CLK", MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 1, 0, NULL, 0), SND_SOC_DAPM_SUPPLY("RX3 CLK", MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 2, 0, msm8x16_wcd_codec_enable_dig_clk, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MIXER_E("RX1 CHAIN", MSM8X16_WCD_A_CDC_RX1_B6_CTL, 0, 0, NULL, 0, msm8x16_wcd_codec_enable_rx_chain, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MIXER_E("RX2 CHAIN", MSM8X16_WCD_A_CDC_RX2_B6_CTL, 0, 0, NULL, 0, msm8x16_wcd_codec_enable_rx_chain, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MIXER_E("RX3 CHAIN", MSM8X16_WCD_A_CDC_RX3_B6_CTL, 0, 0, NULL, 0, msm8x16_wcd_codec_enable_rx_chain, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MUX("RX1 MIX1 INP1", SND_SOC_NOPM, 0, 0, &rx_mix1_inp1_mux), SND_SOC_DAPM_MUX("RX1 MIX1 INP2", SND_SOC_NOPM, 0, 0, &rx_mix1_inp2_mux), SND_SOC_DAPM_MUX("RX1 MIX1 INP3", SND_SOC_NOPM, 0, 0, &rx_mix1_inp3_mux), SND_SOC_DAPM_MUX("RX2 MIX1 INP1", SND_SOC_NOPM, 0, 0, &rx2_mix1_inp1_mux), SND_SOC_DAPM_MUX("RX2 MIX1 INP2", SND_SOC_NOPM, 0, 0, &rx2_mix1_inp2_mux), SND_SOC_DAPM_MUX("RX2 MIX1 INP3", SND_SOC_NOPM, 0, 0, &rx2_mix1_inp3_mux), SND_SOC_DAPM_MUX("RX3 MIX1 INP1", SND_SOC_NOPM, 0, 0, &rx3_mix1_inp1_mux), SND_SOC_DAPM_MUX("RX3 MIX1 INP2", SND_SOC_NOPM, 0, 0, &rx3_mix1_inp2_mux), SND_SOC_DAPM_MUX("RX3 MIX1 INP3", SND_SOC_NOPM, 0, 0, &rx3_mix1_inp3_mux), SND_SOC_DAPM_MUX("RX1 MIX2 INP1", SND_SOC_NOPM, 0, 0, &rx1_mix2_inp1_mux), SND_SOC_DAPM_MUX("RX2 MIX2 INP1", SND_SOC_NOPM, 0, 0, &rx2_mix2_inp1_mux), SND_SOC_DAPM_SUPPLY("MICBIAS_REGULATOR", SND_SOC_NOPM, ON_DEMAND_MICBIAS, 0, msm8x16_wcd_codec_enable_on_demand_supply, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_SUPPLY("CP", MSM8X16_WCD_A_ANALOG_NCP_EN, 0, 0, msm8x16_wcd_codec_enable_charge_pump, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_SUPPLY("EAR CP", MSM8X16_WCD_A_ANALOG_NCP_EN, 4, 0, msm8x16_wcd_codec_enable_charge_pump, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_SUPPLY_S("RX_BIAS", 1, SND_SOC_NOPM, 0, 0, msm8x16_wcd_codec_enable_rx_bias, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_SUPPLY_S("SPK_RX_BIAS", 1, SND_SOC_NOPM, 0, 0, msm8x16_wcd_codec_enable_rx_bias, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_SUPPLY_S("CDC_CONN", -2, MSM8X16_WCD_A_CDC_CLK_OTHR_CTL, 2, 0, NULL, 0), SND_SOC_DAPM_INPUT("AMIC1"), SND_SOC_DAPM_MICBIAS_E("MIC BIAS Internal1", MSM8X16_WCD_A_ANALOG_MICB_1_EN, 7, 0, msm8x16_wcd_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MICBIAS_E("MIC BIAS Internal2", MSM8X16_WCD_A_ANALOG_MICB_2_EN, 7, 0, msm8x16_wcd_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MICBIAS_E("MIC BIAS Internal3", MSM8X16_WCD_A_ANALOG_MICB_1_EN, 7, 0, msm8x16_wcd_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_ADC_E("ADC1", NULL, MSM8X16_WCD_A_ANALOG_TX_1_EN, 7, 0, msm8x16_wcd_codec_enable_adc, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_ADC_E("ADC2_INP2", NULL, MSM8X16_WCD_A_ANALOG_TX_2_EN, 7, 0, msm8x16_wcd_codec_enable_adc, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_ADC_E("ADC2_INP3", NULL, MSM8X16_WCD_A_ANALOG_TX_3_EN, 7, 0, msm8x16_wcd_codec_enable_adc, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MIXER("ADC2", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_MIXER("ADC3", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_MUX("ADC2 MUX", SND_SOC_NOPM, 0, 0, &tx_adc2_mux), SND_SOC_DAPM_MICBIAS_E("MIC BIAS External", MSM8X16_WCD_A_ANALOG_MICB_1_EN, 7, 0, msm8x16_wcd_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MICBIAS_E("MIC BIAS External2", MSM8X16_WCD_A_ANALOG_MICB_2_EN, 7, 0, msm8x16_wcd_codec_enable_micbias, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_INPUT("AMIC3"), SND_SOC_DAPM_MUX_E("DEC1 MUX", MSM8X16_WCD_A_CDC_CLK_TX_CLK_EN_B1_CTL, 0, 0, &dec1_mux, msm8x16_wcd_codec_enable_dec, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MUX_E("DEC2 MUX", MSM8X16_WCD_A_CDC_CLK_TX_CLK_EN_B1_CTL, 1, 0, &dec2_mux, msm8x16_wcd_codec_enable_dec, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MUX_E("DEC3 MUX", MSM8X16_WCD_A_CDC_CLK_TX_CLK_EN_B1_CTL, 2, 0, &dec3_mux, msm8x16_wcd_codec_enable_dec, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MUX_E("DEC4 MUX", MSM8X16_WCD_A_CDC_CLK_TX_CLK_EN_B1_CTL, 3, 0, &dec4_mux, msm8x16_wcd_codec_enable_dec, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MUX("RDAC2 MUX", SND_SOC_NOPM, 0, 0, &rdac2_mux), SND_SOC_DAPM_INPUT("AMIC2"), SND_SOC_DAPM_AIF_OUT("I2S TX1", "AIF1 Capture", 0, SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_AIF_OUT("I2S TX2", "AIF1 Capture", 0, SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_AIF_OUT("I2S TX3", "AIF1 Capture", 0, SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_AIF_OUT("AIF2 VI", "VIfeed", 0, SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_ADC_E("DMIC1", NULL, SND_SOC_NOPM, 0, 0, msm8x16_wcd_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_ADC_E("DMIC2", NULL, SND_SOC_NOPM, 0, 0, msm8x16_wcd_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_INPUT("DMIC3"), SND_SOC_DAPM_INPUT("DMIC4"), SND_SOC_DAPM_MUX("IIR1 INP1 MUX", SND_SOC_NOPM, 0, 0, &iir1_inp1_mux), SND_SOC_DAPM_PGA_E("IIR1", MSM8X16_WCD_A_CDC_CLK_SD_CTL, 0, 0, NULL, 0, msm8x16_wcd_codec_set_iir_gain, SND_SOC_DAPM_POST_PMU), SND_SOC_DAPM_MUX("IIR2 INP1 MUX", SND_SOC_NOPM, 0, 0, &iir2_inp1_mux), SND_SOC_DAPM_PGA_E("IIR2", MSM8X16_WCD_A_CDC_CLK_SD_CTL, 1, 0, NULL, 0, msm8x16_wcd_codec_set_iir_gain, SND_SOC_DAPM_POST_PMU), SND_SOC_DAPM_SUPPLY("RX_I2S_CLK", MSM8X16_WCD_A_CDC_CLK_RX_I2S_CTL, 4, 0, NULL, 0), SND_SOC_DAPM_SUPPLY("TX_I2S_CLK", MSM8X16_WCD_A_CDC_CLK_TX_I2S_CTL, 4, 0, NULL, 0), }; static const struct msm8x16_wcd_reg_mask_val msm8x16_wcd_reg_defaults[] = { MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SPKR_DAC_CTL, 0x03), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_CURRENT_LIMIT, 0x82), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SPKR_OCP_CTL, 0xE1), }; static const struct msm8x16_wcd_reg_mask_val msm8x16_wcd_reg_defaults_2_0[] = { MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_DIGITAL_SEC_ACCESS, 0xA5), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_DIGITAL_PERPH_RESET_CTL3, 0x0F), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_TX_1_2_OPAMP_BIAS, 0x4F), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_NCP_FBCTRL, 0x28), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SPKR_DRV_CTL, 0x69), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SPKR_DRV_DBG, 0x01), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_BOOST_EN_CTL, 0x5F), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SLOPE_COMP_IP_ZERO, 0x88), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SEC_ACCESS, 0xA5), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_PERPH_RESET_CTL3, 0x0F), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_CURRENT_LIMIT, 0x82), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SPKR_DAC_CTL, 0x03), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SPKR_OCP_CTL, 0xE1), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_DIGITAL_CDC_RST_CTL, 0x80), }; static const struct msm8x16_wcd_reg_mask_val msm8909_wcd_reg_defaults[] = { MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_DIGITAL_SEC_ACCESS, 0xA5), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_DIGITAL_PERPH_RESET_CTL3, 0x0F), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SEC_ACCESS, 0xA5), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_PERPH_RESET_CTL3, 0x0F), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_TX_1_2_OPAMP_BIAS, 0x4C), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_NCP_FBCTRL, 0x28), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SPKR_DRV_CTL, 0x69), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SPKR_DRV_DBG, 0x01), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_PERPH_SUBTYPE, 0x0A), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SPKR_DAC_CTL, 0x03), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SPKR_OCP_CTL, 0xE1), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_DIGITAL_CDC_RST_CTL, 0x80), }; static const struct msm8x16_wcd_reg_mask_val cajon_wcd_reg_defaults[] = { MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_DIGITAL_SEC_ACCESS, 0xA5), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_DIGITAL_PERPH_RESET_CTL3, 0x0F), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SEC_ACCESS, 0xA5), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_PERPH_RESET_CTL3, 0x0F), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_TX_1_2_OPAMP_BIAS, 0x4C), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_CURRENT_LIMIT, 0x82), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_NCP_FBCTRL, 0xA8), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_NCP_VCTRL, 0xA4), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SPKR_ANA_BIAS_SET, 0x41), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SPKR_DRV_CTL, 0x69), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SPKR_DRV_DBG, 0x01), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SPKR_OCP_CTL, 0xE1), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SPKR_DAC_CTL, 0x03), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_RX_HPH_BIAS_PA, 0xFA), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_DIGITAL_CDC_RST_CTL, 0x80), }; static const struct msm8x16_wcd_reg_mask_val cajon2p0_wcd_reg_defaults[] = { MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_DIGITAL_SEC_ACCESS, 0xA5), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_DIGITAL_PERPH_RESET_CTL3, 0x0F), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SEC_ACCESS, 0xA5), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_PERPH_RESET_CTL3, 0x0F), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_TX_1_2_OPAMP_BIAS, 0x4C), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_CURRENT_LIMIT, 0xA2), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_NCP_FBCTRL, 0xA8), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_NCP_VCTRL, 0xA4), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SPKR_ANA_BIAS_SET, 0x41), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SPKR_DRV_CTL, 0x69), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SPKR_DRV_DBG, 0x01), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SPKR_OCP_CTL, 0xE1), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_SPKR_DAC_CTL, 0x03), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_RX_EAR_STATUS, 0x10), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_BYPASS_MODE, 0x18), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_ANALOG_RX_HPH_BIAS_PA, 0xFA), MSM8X16_WCD_REG_VAL(MSM8X16_WCD_A_DIGITAL_CDC_RST_CTL, 0x80), }; static void msm8x16_wcd_update_reg_defaults(struct snd_soc_codec *codec) { u32 i, version; struct msm8x16_wcd_priv *msm8x16_wcd = snd_soc_codec_get_drvdata(codec); version = get_codec_version(msm8x16_wcd); if (version == TOMBAK_1_0) { for (i = 0; i < ARRAY_SIZE(msm8x16_wcd_reg_defaults); i++) snd_soc_write(codec, msm8x16_wcd_reg_defaults[i].reg, msm8x16_wcd_reg_defaults[i].val); } else if (version == TOMBAK_2_0) { for (i = 0; i < ARRAY_SIZE(msm8x16_wcd_reg_defaults_2_0); i++) snd_soc_write(codec, msm8x16_wcd_reg_defaults_2_0[i].reg, msm8x16_wcd_reg_defaults_2_0[i].val); } else if (version == CONGA) { for (i = 0; i < ARRAY_SIZE(msm8909_wcd_reg_defaults); i++) snd_soc_write(codec, msm8909_wcd_reg_defaults[i].reg, msm8909_wcd_reg_defaults[i].val); } else if (version == CAJON) { for (i = 0; i < ARRAY_SIZE(cajon_wcd_reg_defaults); i++) snd_soc_write(codec, cajon_wcd_reg_defaults[i].reg, cajon_wcd_reg_defaults[i].val); } else if (version == CAJON_2_0 || version == DIANGU) { for (i = 0; i < ARRAY_SIZE(cajon2p0_wcd_reg_defaults); i++) snd_soc_write(codec, cajon2p0_wcd_reg_defaults[i].reg, cajon2p0_wcd_reg_defaults[i].val); } } static const struct msm8x16_wcd_reg_mask_val msm8x16_wcd_codec_reg_init_val[] = { {MSM8X16_WCD_A_ANALOG_RX_COM_OCP_CTL, 0xFF, 0x12}, {MSM8X16_WCD_A_ANALOG_RX_COM_OCP_COUNT, 0xFF, 0xFF}, }; static void msm8x16_wcd_codec_init_reg(struct snd_soc_codec *codec) { u32 i; for (i = 0; i < ARRAY_SIZE(msm8x16_wcd_codec_reg_init_val); i++) snd_soc_update_bits(codec, msm8x16_wcd_codec_reg_init_val[i].reg, msm8x16_wcd_codec_reg_init_val[i].mask, msm8x16_wcd_codec_reg_init_val[i].val); } static int msm8x16_wcd_bringup(struct snd_soc_codec *codec) { snd_soc_write(codec, MSM8X16_WCD_A_DIGITAL_SEC_ACCESS, 0xA5); snd_soc_write(codec, MSM8X16_WCD_A_DIGITAL_PERPH_RESET_CTL4, 0x01); snd_soc_write(codec, MSM8X16_WCD_A_ANALOG_SEC_ACCESS, 0xA5); snd_soc_write(codec, MSM8X16_WCD_A_ANALOG_PERPH_RESET_CTL4, 0x01); snd_soc_write(codec, MSM8X16_WCD_A_DIGITAL_SEC_ACCESS, 0xA5); snd_soc_write(codec, MSM8X16_WCD_A_DIGITAL_PERPH_RESET_CTL4, 0x00); snd_soc_write(codec, MSM8X16_WCD_A_ANALOG_SEC_ACCESS, 0xA5); snd_soc_write(codec, MSM8X16_WCD_A_ANALOG_PERPH_RESET_CTL4, 0x00); return 0; } static struct regulator *wcd8x16_wcd_codec_find_regulator( const struct msm8x16_wcd *msm8x16, const char *name) { int i; for (i = 0; i < msm8x16->num_of_supplies; i++) { if (msm8x16->supplies[i].supply && !strcmp(msm8x16->supplies[i].supply, name)) return msm8x16->supplies[i].consumer; } dev_err(msm8x16->dev, "Error: regulator not found:%s\n" , name); return NULL; } static int msm8x16_wcd_device_down(struct snd_soc_codec *codec) { struct msm8916_asoc_mach_data *pdata = NULL; struct msm8x16_wcd_priv *msm8x16_wcd_priv = snd_soc_codec_get_drvdata(codec); int i; pdata = snd_soc_card_get_drvdata(codec->component.card); dev_dbg(codec->dev, "%s: device down!\n", __func__); msm8x16_wcd_write(codec, MSM8X16_WCD_A_ANALOG_TX_1_EN, 0x3); msm8x16_wcd_write(codec, MSM8X16_WCD_A_ANALOG_TX_2_EN, 0x3); if (msm8x16_wcd_priv->boost_option == BOOST_ON_FOREVER) { if ((snd_soc_read(codec, MSM8X16_WCD_A_ANALOG_SPKR_DRV_CTL) & 0x80) == 0) { snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_CLK_MCLK_CTL, 0x01, 0x01); snd_soc_update_bits(codec, MSM8X16_WCD_A_CDC_CLK_PDM_CTL, 0x03, 0x03); snd_soc_write(codec, MSM8X16_WCD_A_ANALOG_MASTER_BIAS_CTL, 0x30); snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_RST_CTL, 0x80, 0x80); snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_TOP_CLK_CTL, 0x0C, 0x0C); snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_DIG_CLK_CTL, 0x84, 0x84); snd_soc_update_bits(codec, MSM8X16_WCD_A_DIGITAL_CDC_ANA_CLK_CTL, 0x10, 0x10); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SPKR_PWRSTG_CTL, 0x1F, 0x1F); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_COM_BIAS_DAC, 0x90, 0x90); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_EAR_CTL, 0xFF, 0xFF); usleep_range(20, 21); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SPKR_PWRSTG_CTL, 0xFF, 0xFF); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SPKR_DRV_CTL, 0xE9, 0xE9); } } msm8x16_wcd_boost_off(codec); msm8x16_wcd_priv->hph_mode = NORMAL_MODE; for (i = 0; i < MSM8X16_WCD_RX_MAX; i++) msm8x16_wcd_priv->comp_enabled[i] = COMPANDER_NONE; msleep(40); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_CNP_EN, 0x30, 0x00); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_SPKR_DRV_CTL, 0x80, 0x00); msm8x16_wcd_write(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_L_PA_DAC_CTL, 0x20); msm8x16_wcd_write(codec, MSM8X16_WCD_A_ANALOG_RX_HPH_R_PA_DAC_CTL, 0x20); msm8x16_wcd_write(codec, MSM8X16_WCD_A_ANALOG_RX_EAR_CTL, 0x12); msm8x16_wcd_write(codec, MSM8X16_WCD_A_ANALOG_SPKR_DAC_CTL, 0x93); msm8x16_wcd_bringup(codec); atomic_set(&pdata->mclk_enabled, false); set_bit(BUS_DOWN, &msm8x16_wcd_priv->status_mask); snd_soc_card_change_online_state(codec->component.card, 0); return 0; } static int msm8x16_wcd_device_up(struct snd_soc_codec *codec) { struct msm8x16_wcd_priv *msm8x16_wcd_priv = snd_soc_codec_get_drvdata(codec); int ret = 0; dev_dbg(codec->dev, "%s: device up!\n", __func__); mutex_lock(&codec->mutex); clear_bit(BUS_DOWN, &msm8x16_wcd_priv->status_mask); snd_soc_card_change_online_state(codec->component.card, 1); usleep_range(5000, 5100); msm8x16_wcd_codec_init_reg(codec); msm8x16_wcd_update_reg_defaults(codec); codec->cache_sync = true; snd_soc_cache_sync(codec); codec->cache_sync = false; msm8x16_wcd_write(codec, MSM8X16_WCD_A_DIGITAL_INT_EN_SET, MSM8X16_WCD_A_DIGITAL_INT_EN_SET__POR); msm8x16_wcd_write(codec, MSM8X16_WCD_A_DIGITAL_INT_EN_CLR, MSM8X16_WCD_A_DIGITAL_INT_EN_CLR__POR); msm8x16_wcd_set_boost_v(codec); msm8x16_wcd_set_micb_v(codec); if (msm8x16_wcd_priv->boost_option == BOOST_ON_FOREVER) msm8x16_wcd_boost_on(codec); else if (msm8x16_wcd_priv->boost_option == BYPASS_ALWAYS) msm8x16_wcd_bypass_on(codec); msm8x16_wcd_configure_cap(codec, false, false); wcd_mbhc_stop(&msm8x16_wcd_priv->mbhc); wcd_mbhc_deinit(&msm8x16_wcd_priv->mbhc); ret = wcd_mbhc_init(&msm8x16_wcd_priv->mbhc, codec, &mbhc_cb, &intr_ids, wcd_mbhc_registers, true); if (ret) dev_err(codec->dev, "%s: mbhc initialization failed\n", __func__); else wcd_mbhc_start(&msm8x16_wcd_priv->mbhc, msm8x16_wcd_priv->mbhc.mbhc_cfg); mutex_unlock(&codec->mutex); return 0; } static int adsp_state_callback(struct notifier_block *nb, unsigned long value, void *priv) { bool timedout; unsigned long timeout; if (value == SUBSYS_BEFORE_SHUTDOWN) msm8x16_wcd_device_down(registered_codec); else if (value == SUBSYS_AFTER_POWERUP) { dev_dbg(registered_codec->dev, "ADSP is about to power up. bring up codec\n"); if (!q6core_is_adsp_ready()) { dev_dbg(registered_codec->dev, "ADSP isn't ready\n"); timeout = jiffies + msecs_to_jiffies(ADSP_STATE_READY_TIMEOUT_MS); while (!(timedout = time_after(jiffies, timeout))) { if (!q6core_is_adsp_ready()) { dev_dbg(registered_codec->dev, "ADSP isn't ready\n"); } else { dev_dbg(registered_codec->dev, "ADSP is ready\n"); break; } } } else { dev_dbg(registered_codec->dev, "%s: DSP is ready\n", __func__); } msm8x16_wcd_device_up(registered_codec); } return NOTIFY_OK; } static struct notifier_block adsp_state_notifier_block = { .notifier_call = adsp_state_callback, .priority = -INT_MAX, }; int msm8x16_wcd_hs_detect(struct snd_soc_codec *codec, struct wcd_mbhc_config *mbhc_cfg) { struct msm8x16_wcd_priv *msm8x16_wcd_priv = snd_soc_codec_get_drvdata(codec); return wcd_mbhc_start(&msm8x16_wcd_priv->mbhc, mbhc_cfg); } EXPORT_SYMBOL(msm8x16_wcd_hs_detect); void msm8x16_wcd_hs_detect_exit(struct snd_soc_codec *codec) { struct msm8x16_wcd_priv *msm8x16_wcd_priv = snd_soc_codec_get_drvdata(codec); wcd_mbhc_stop(&msm8x16_wcd_priv->mbhc); } EXPORT_SYMBOL(msm8x16_wcd_hs_detect_exit); void msm8x16_update_int_spk_boost(bool enable) { pr_debug("%s: enable = %d\n", __func__, enable); spkr_boost_en = enable; } EXPORT_SYMBOL(msm8x16_update_int_spk_boost); static void msm8x16_wcd_set_micb_v(struct snd_soc_codec *codec) { struct msm8x16_wcd *msm8x16 = codec->control_data; struct msm8x16_wcd_pdata *pdata = msm8x16->dev->platform_data; u8 reg_val; reg_val = VOLTAGE_CONVERTER(pdata->micbias.cfilt1_mv, MICBIAS_MIN_VAL, MICBIAS_STEP_SIZE); dev_dbg(codec->dev, "cfilt1_mv %d reg_val %x\n", (u32)pdata->micbias.cfilt1_mv, reg_val); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MICB_1_VAL, 0xF8, (reg_val << 3)); } static void msm8x16_wcd_set_boost_v(struct snd_soc_codec *codec) { struct msm8x16_wcd_priv *msm8x16_wcd_priv = snd_soc_codec_get_drvdata(codec); snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_OUTPUT_VOLTAGE, 0x1F, msm8x16_wcd_priv->boost_voltage); } static void msm8x16_wcd_configure_cap(struct snd_soc_codec *codec, bool micbias1, bool micbias2) { struct msm8916_asoc_mach_data *pdata = NULL; pdata = snd_soc_card_get_drvdata(codec->component.card); pr_debug("\n %s: micbias1 %x micbias2 = %d\n", __func__, micbias1, micbias2); if (micbias1 && micbias2) { if ((pdata->micbias1_cap_mode == MICBIAS_EXT_BYP_CAP) || (pdata->micbias2_cap_mode == MICBIAS_EXT_BYP_CAP)) snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MICB_1_EN, 0x40, (MICBIAS_EXT_BYP_CAP << 6)); else snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MICB_1_EN, 0x40, (MICBIAS_NO_EXT_BYP_CAP << 6)); } else if (micbias2) { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MICB_1_EN, 0x40, (pdata->micbias2_cap_mode << 6)); } else if (micbias1) { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MICB_1_EN, 0x40, (pdata->micbias1_cap_mode << 6)); } else { snd_soc_update_bits(codec, MSM8X16_WCD_A_ANALOG_MICB_1_EN, 0x40, 0x00); } } static int msm8x16_wcd_codec_probe(struct snd_soc_codec *codec) { struct msm8x16_wcd_priv *msm8x16_wcd_priv; struct msm8x16_wcd *msm8x16_wcd; struct msm8x16_wcd_pdata *pdata; int i, ret; dev_dbg(codec->dev, "%s()\n", __func__); msm8x16_wcd_priv = kzalloc(sizeof(struct msm8x16_wcd_priv), GFP_KERNEL); if (!msm8x16_wcd_priv) return -ENOMEM; for (i = 0; i < NUM_DECIMATORS; i++) { tx_hpf_work[i].msm8x16_wcd = msm8x16_wcd_priv; tx_hpf_work[i].decimator = i + 1; INIT_DELAYED_WORK(&tx_hpf_work[i].dwork, tx_hpf_corner_freq_callback); } codec->control_data = dev_get_drvdata(codec->dev); snd_soc_codec_set_drvdata(codec, msm8x16_wcd_priv); msm8x16_wcd_priv->codec = codec; msm8x16_wcd = codec->control_data; pdata = msm8x16_wcd->dev->platform_data; msm8x16_wcd->dig_base = ioremap(pdata->dig_cdc_addr, MSM8X16_DIGITAL_CODEC_REG_SIZE); if (msm8x16_wcd->dig_base == NULL) { dev_err(codec->dev, "%s ioremap failed\n", __func__); kfree(msm8x16_wcd_priv); return -ENOMEM; } msm8x16_wcd_priv->spkdrv_reg = wcd8x16_wcd_codec_find_regulator(codec->control_data, MSM89XX_VDD_SPKDRV_NAME); msm8x16_wcd_priv->pmic_rev = snd_soc_read(codec, MSM8X16_WCD_A_DIGITAL_REVISION1); msm8x16_wcd_priv->codec_version = snd_soc_read(codec, MSM8X16_WCD_A_DIGITAL_PERPH_SUBTYPE); if (msm8x16_wcd_priv->codec_version == CONGA) { dev_dbg(codec->dev, "%s :Conga REV: %d\n", __func__, msm8x16_wcd_priv->codec_version); msm8x16_wcd_priv->ext_spk_boost_set = true; } else { dev_dbg(codec->dev, "%s :PMIC REV: %d\n", __func__, msm8x16_wcd_priv->pmic_rev); if (msm8x16_wcd_priv->pmic_rev == TOMBAK_1_0 && msm8x16_wcd_priv->codec_version == CAJON_2_0) { msm8x16_wcd_priv->codec_version = DIANGU; dev_dbg(codec->dev, "%s : Diangu detected\n", __func__); } else if (msm8x16_wcd_priv->pmic_rev == TOMBAK_1_0 && (snd_soc_read(codec, MSM8X16_WCD_A_ANALOG_NCP_FBCTRL) & 0x80)) { msm8x16_wcd_priv->codec_version = CAJON; dev_dbg(codec->dev, "%s : Cajon detected\n", __func__); } else if (msm8x16_wcd_priv->pmic_rev == TOMBAK_2_0 && (snd_soc_read(codec, MSM8X16_WCD_A_ANALOG_NCP_FBCTRL) & 0x80)) { msm8x16_wcd_priv->codec_version = CAJON_2_0; dev_dbg(codec->dev, "%s : Cajon 2.0 detected\n", __func__); } } msm8x16_wcd_priv->boost_option = BOOST_SWITCH; msm8x16_wcd_priv->hph_mode = NORMAL_MODE; for (i = 0; i < MSM8X16_WCD_RX_MAX; i++) msm8x16_wcd_priv->comp_enabled[i] = COMPANDER_NONE; msm8x16_wcd_dt_parse_boost_info(codec); msm8x16_wcd_set_boost_v(codec); snd_soc_add_codec_controls(codec, impedance_detect_controls, ARRAY_SIZE(impedance_detect_controls)); snd_soc_add_codec_controls(codec, hph_type_detect_controls, ARRAY_SIZE(hph_type_detect_controls)); msm8x16_wcd_bringup(codec); msm8x16_wcd_codec_init_reg(codec); msm8x16_wcd_update_reg_defaults(codec); wcd9xxx_spmi_set_codec(codec); msm8x16_wcd_priv->on_demand_list[ON_DEMAND_MICBIAS].supply = wcd8x16_wcd_codec_find_regulator( codec->control_data, on_demand_supply_name[ON_DEMAND_MICBIAS]); atomic_set(&msm8x16_wcd_priv->on_demand_list[ON_DEMAND_MICBIAS].ref, 0); BLOCKING_INIT_NOTIFIER_HEAD(&msm8x16_wcd_priv->notifier); msm8x16_wcd_priv->fw_data = kzalloc(sizeof(*(msm8x16_wcd_priv->fw_data)) , GFP_KERNEL); if (!msm8x16_wcd_priv->fw_data) { iounmap(msm8x16_wcd->dig_base); kfree(msm8x16_wcd_priv); return -ENOMEM; } set_bit(WCD9XXX_MBHC_CAL, msm8x16_wcd_priv->fw_data->cal_bit); ret = wcd_cal_create_hwdep(msm8x16_wcd_priv->fw_data, WCD9XXX_CODEC_HWDEP_NODE, codec); if (ret < 0) { dev_err(codec->dev, "%s hwdep failed %d\n", __func__, ret); iounmap(msm8x16_wcd->dig_base); kfree(msm8x16_wcd_priv->fw_data); kfree(msm8x16_wcd_priv); return ret; } wcd_mbhc_init(&msm8x16_wcd_priv->mbhc, codec, &mbhc_cb, &intr_ids, wcd_mbhc_registers, true); msm8x16_wcd_priv->mclk_enabled = false; msm8x16_wcd_priv->clock_active = false; msm8x16_wcd_priv->config_mode_active = false; msm8x16_wcd_priv->spk_boost_set = spkr_boost_en; pr_debug("%s: speaker boost configured = %d\n", __func__, msm8x16_wcd_priv->spk_boost_set); msm8x16_wcd_set_micb_v(codec); msm8x16_wcd_configure_cap(codec, false, false); registered_codec = codec; adsp_state_notifier = subsys_notif_register_notifier("adsp", &adsp_state_notifier_block); if (!adsp_state_notifier) { dev_err(codec->dev, "Failed to register adsp state notifier\n"); iounmap(msm8x16_wcd->dig_base); kfree(msm8x16_wcd_priv->fw_data); kfree(msm8x16_wcd_priv); registered_codec = NULL; return -ENOMEM; } return 0; } static int msm8x16_wcd_codec_remove(struct snd_soc_codec *codec) { struct msm8x16_wcd_priv *msm8x16_wcd_priv = snd_soc_codec_get_drvdata(codec); struct msm8x16_wcd *msm8x16_wcd; msm8x16_wcd = codec->control_data; msm8x16_wcd_priv->spkdrv_reg = NULL; msm8x16_wcd_priv->on_demand_list[ON_DEMAND_MICBIAS].supply = NULL; atomic_set(&msm8x16_wcd_priv->on_demand_list[ON_DEMAND_MICBIAS].ref, 0); iounmap(msm8x16_wcd->dig_base); kfree(msm8x16_wcd_priv->fw_data); kfree(msm8x16_wcd_priv); return 0; } static int msm8x16_wcd_enable_static_supplies_to_optimum( struct msm8x16_wcd *msm8x16, struct msm8x16_wcd_pdata *pdata) { int i; int ret = 0; for (i = 0; i < msm8x16->num_of_supplies; i++) { if (pdata->regulator[i].ondemand) continue; if (regulator_count_voltages(msm8x16->supplies[i].consumer) <= 0) continue; ret = regulator_set_voltage(msm8x16->supplies[i].consumer, pdata->regulator[i].min_uv, pdata->regulator[i].max_uv); if (ret) { dev_err(msm8x16->dev, "Setting volt failed for regulator %s err %d\n", msm8x16->supplies[i].supply, ret); } ret = regulator_set_optimum_mode(msm8x16->supplies[i].consumer, pdata->regulator[i].optimum_ua); dev_dbg(msm8x16->dev, "Regulator %s set optimum mode\n", msm8x16->supplies[i].supply); } return ret; } static int msm8x16_wcd_disable_static_supplies_to_optimum( struct msm8x16_wcd *msm8x16, struct msm8x16_wcd_pdata *pdata) { int i; int ret = 0; for (i = 0; i < msm8x16->num_of_supplies; i++) { if (pdata->regulator[i].ondemand) continue; if (regulator_count_voltages(msm8x16->supplies[i].consumer) <= 0) continue; regulator_set_voltage(msm8x16->supplies[i].consumer, 0, pdata->regulator[i].max_uv); regulator_set_optimum_mode(msm8x16->supplies[i].consumer, 0); dev_dbg(msm8x16->dev, "Regulator %s set optimum mode\n", msm8x16->supplies[i].supply); } return ret; } int msm8x16_wcd_suspend(struct snd_soc_codec *codec) { struct msm8916_asoc_mach_data *pdata = NULL; struct msm8x16_wcd *msm8x16 = codec->control_data; struct msm8x16_wcd_pdata *msm8x16_pdata = msm8x16->dev->platform_data; pdata = snd_soc_card_get_drvdata(codec->component.card); pr_debug("%s: mclk cnt = %d, mclk_enabled = %d\n", __func__, atomic_read(&pdata->mclk_rsc_ref), atomic_read(&pdata->mclk_enabled)); if (atomic_read(&pdata->mclk_enabled) == true) { cancel_delayed_work_sync( &pdata->disable_mclk_work); mutex_lock(&pdata->cdc_mclk_mutex); if (atomic_read(&pdata->mclk_enabled) == true) { if (pdata->afe_clk_ver == AFE_CLK_VERSION_V1) { pdata->digital_cdc_clk.clk_val = 0; afe_set_digital_codec_core_clock( AFE_PORT_ID_PRIMARY_MI2S_RX, &pdata->digital_cdc_clk); } else { pdata->digital_cdc_core_clk.enable = 0; afe_set_lpass_clock_v2( AFE_PORT_ID_PRIMARY_MI2S_RX, &pdata->digital_cdc_core_clk); } atomic_set(&pdata->mclk_enabled, false); } mutex_unlock(&pdata->cdc_mclk_mutex); } msm8x16_wcd_disable_static_supplies_to_optimum(msm8x16, msm8x16_pdata); return 0; } int msm8x16_wcd_resume(struct snd_soc_codec *codec) { struct msm8916_asoc_mach_data *pdata = NULL; struct msm8x16_wcd *msm8x16 = codec->control_data; struct msm8x16_wcd_pdata *msm8x16_pdata = msm8x16->dev->platform_data; pdata = snd_soc_card_get_drvdata(codec->component.card); msm8x16_wcd_enable_static_supplies_to_optimum(msm8x16, msm8x16_pdata); return 0; } static struct snd_soc_codec_driver soc_codec_dev_msm8x16_wcd = { .probe = msm8x16_wcd_codec_probe, .remove = msm8x16_wcd_codec_remove, .read = msm8x16_wcd_read, .write = msm8x16_wcd_write, .suspend = msm8x16_wcd_suspend, .resume = msm8x16_wcd_resume, .readable_register = msm8x16_wcd_readable, .volatile_register = msm8x16_wcd_volatile, .reg_cache_size = MSM8X16_WCD_CACHE_SIZE, .reg_cache_default = msm8x16_wcd_reset_reg_defaults, .reg_word_size = 1, .controls = msm8x16_wcd_snd_controls, .num_controls = ARRAY_SIZE(msm8x16_wcd_snd_controls), .dapm_widgets = msm8x16_wcd_dapm_widgets, .num_dapm_widgets = ARRAY_SIZE(msm8x16_wcd_dapm_widgets), .dapm_routes = audio_map, .num_dapm_routes = ARRAY_SIZE(audio_map), }; static int msm8x16_wcd_init_supplies(struct msm8x16_wcd *msm8x16, struct msm8x16_wcd_pdata *pdata) { int ret; int i; msm8x16->supplies = kzalloc(sizeof(struct regulator_bulk_data) * ARRAY_SIZE(pdata->regulator), GFP_KERNEL); if (!msm8x16->supplies) { ret = -ENOMEM; goto err; } msm8x16->num_of_supplies = 0; if (ARRAY_SIZE(pdata->regulator) > MAX_REGULATOR) { dev_err(msm8x16->dev, "%s: Array Size out of bound\n", __func__); ret = -EINVAL; goto err; } for (i = 0; i < ARRAY_SIZE(pdata->regulator); i++) { if (pdata->regulator[i].name) { msm8x16->supplies[i].supply = pdata->regulator[i].name; msm8x16->num_of_supplies++; } } ret = regulator_bulk_get(msm8x16->dev, msm8x16->num_of_supplies, msm8x16->supplies); if (ret != 0) { dev_err(msm8x16->dev, "Failed to get supplies: err = %d\n", ret); goto err_supplies; } for (i = 0; i < msm8x16->num_of_supplies; i++) { if (regulator_count_voltages(msm8x16->supplies[i].consumer) <= 0) continue; ret = regulator_set_voltage(msm8x16->supplies[i].consumer, pdata->regulator[i].min_uv, pdata->regulator[i].max_uv); if (ret) { dev_err(msm8x16->dev, "Setting regulator voltage failed for regulator %s err = %d\n", msm8x16->supplies[i].supply, ret); goto err_get; } ret = regulator_set_optimum_mode(msm8x16->supplies[i].consumer, pdata->regulator[i].optimum_ua); if (ret < 0) { dev_err(msm8x16->dev, "Setting regulator optimum mode failed for regulator %s err = %d\n", msm8x16->supplies[i].supply, ret); goto err_get; } else { ret = 0; } } return ret; err_get: regulator_bulk_free(msm8x16->num_of_supplies, msm8x16->supplies); err_supplies: kfree(msm8x16->supplies); err: return ret; } static int msm8x16_wcd_enable_static_supplies(struct msm8x16_wcd *msm8x16, struct msm8x16_wcd_pdata *pdata) { int i; int ret = 0; for (i = 0; i < msm8x16->num_of_supplies; i++) { if (pdata->regulator[i].ondemand) continue; ret = regulator_enable(msm8x16->supplies[i].consumer); if (ret) { dev_err(msm8x16->dev, "Failed to enable %s\n", msm8x16->supplies[i].supply); break; } dev_dbg(msm8x16->dev, "Enabled regulator %s\n", msm8x16->supplies[i].supply); } while (ret && --i) if (!pdata->regulator[i].ondemand) regulator_disable(msm8x16->supplies[i].consumer); return ret; } static void msm8x16_wcd_disable_supplies(struct msm8x16_wcd *msm8x16, struct msm8x16_wcd_pdata *pdata) { int i; regulator_bulk_disable(msm8x16->num_of_supplies, msm8x16->supplies); for (i = 0; i < msm8x16->num_of_supplies; i++) { if (regulator_count_voltages(msm8x16->supplies[i].consumer) <= 0) continue; regulator_set_voltage(msm8x16->supplies[i].consumer, 0, pdata->regulator[i].max_uv); regulator_set_optimum_mode(msm8x16->supplies[i].consumer, 0); } regulator_bulk_free(msm8x16->num_of_supplies, msm8x16->supplies); kfree(msm8x16->supplies); } static int msm8x16_wcd_device_init(struct msm8x16_wcd *msm8x16) { mutex_init(&msm8x16->io_lock); return 0; } static int msm8x16_wcd_spmi_probe(struct spmi_device *spmi) { int ret = 0; struct msm8x16_wcd *msm8x16 = NULL; struct msm8x16_wcd_pdata *pdata; struct resource *wcd_resource; int adsp_state; static int spmi_dev_registered_cnt; dev_dbg(&spmi->dev, "%s(%d):slave ID = 0x%x\n", __func__, __LINE__, spmi->sid); adsp_state = apr_get_subsys_state(); if (adsp_state != APR_SUBSYS_LOADED) { dev_dbg(&spmi->dev, "Adsp is not loaded yet %d\n", adsp_state); return -EPROBE_DEFER; } wcd_resource = spmi_get_resource(spmi, NULL, IORESOURCE_MEM, 0); if (!wcd_resource) { dev_err(&spmi->dev, "Unable to get Tombak base address\n"); return -ENXIO; } switch (wcd_resource->start) { case TOMBAK_CORE_0_SPMI_ADDR: msm8x16_wcd_modules[0].spmi = spmi; msm8x16_wcd_modules[0].base = (spmi->sid << 16) + wcd_resource->start; wcd9xxx_spmi_set_dev(msm8x16_wcd_modules[0].spmi, 0); device_init_wakeup(&spmi->dev, true); break; case TOMBAK_CORE_1_SPMI_ADDR: msm8x16_wcd_modules[1].spmi = spmi; msm8x16_wcd_modules[1].base = (spmi->sid << 16) + wcd_resource->start; wcd9xxx_spmi_set_dev(msm8x16_wcd_modules[1].spmi, 1); if (wcd9xxx_spmi_irq_init()) { dev_err(&spmi->dev, "%s: irq initialization failed\n", __func__); } else { dev_dbg(&spmi->dev, "%s: irq initialization passed\n", __func__); } spmi_dev_registered_cnt++; goto register_codec; default: ret = -EINVAL; goto rtn; } dev_dbg(&spmi->dev, "%s(%d):start addr = 0x%pK\n", __func__, __LINE__, &wcd_resource->start); if (wcd_resource->start != TOMBAK_CORE_0_SPMI_ADDR) goto rtn; if (spmi->dev.of_node) { dev_dbg(&spmi->dev, "%s:Platform data from device tree\n", __func__); pdata = msm8x16_wcd_populate_dt_pdata(&spmi->dev); spmi->dev.platform_data = pdata; } else { dev_dbg(&spmi->dev, "%s:Platform data from board file\n", __func__); pdata = spmi->dev.platform_data; } if (pdata == NULL) { dev_err(&spmi->dev, "%s:Platform data failed to populate\n", __func__); goto rtn; } msm8x16 = kzalloc(sizeof(struct msm8x16_wcd), GFP_KERNEL); if (msm8x16 == NULL) { ret = -ENOMEM; goto rtn; } msm8x16->dev = &spmi->dev; msm8x16->read_dev = __msm8x16_wcd_reg_read; msm8x16->write_dev = __msm8x16_wcd_reg_write; ret = msm8x16_wcd_init_supplies(msm8x16, pdata); if (ret) { dev_err(&spmi->dev, "%s: Fail to enable Codec supplies\n", __func__); goto err_codec; } ret = msm8x16_wcd_enable_static_supplies(msm8x16, pdata); if (ret) { dev_err(&spmi->dev, "%s: Fail to enable Codec pre-reset supplies\n", __func__); goto err_codec; } usleep_range(5, 6); ret = msm8x16_wcd_device_init(msm8x16); if (ret) { dev_err(&spmi->dev, "%s:msm8x16_wcd_device_init failed with error %d\n", __func__, ret); goto err_supplies; } dev_set_drvdata(&spmi->dev, msm8x16); spmi_dev_registered_cnt++; register_codec: if ((spmi_dev_registered_cnt == MAX_MSM8X16_WCD_DEVICE) && (!ret)) { if (msm8x16_wcd_modules[0].spmi) { ret = snd_soc_register_codec( &msm8x16_wcd_modules[0].spmi->dev, &soc_codec_dev_msm8x16_wcd, msm8x16_wcd_i2s_dai, ARRAY_SIZE(msm8x16_wcd_i2s_dai)); if (ret) { dev_err(&spmi->dev, "%s:snd_soc_register_codec failed with error %d\n", __func__, ret); goto err_supplies; } } } return ret; err_supplies: msm8x16_wcd_disable_supplies(msm8x16, pdata); err_codec: kfree(msm8x16); rtn: return ret; } static void msm8x16_wcd_device_exit(struct msm8x16_wcd *msm8x16) { mutex_destroy(&msm8x16->io_lock); kfree(msm8x16); } static int msm8x16_wcd_spmi_remove(struct spmi_device *spmi) { struct msm8x16_wcd *msm8x16 = dev_get_drvdata(&spmi->dev); msm8x16_wcd_device_exit(msm8x16); return 0; } #ifdef CONFIG_PM static int msm8x16_wcd_spmi_resume(struct spmi_device *spmi) { struct resource *wcd_resource; wcd_resource = spmi_get_resource(spmi, NULL, IORESOURCE_MEM, 0); if (!wcd_resource) { dev_err(&spmi->dev, "Unable to get CDC SPMI resource\n"); return -ENXIO; } if (wcd_resource->start == TOMBAK_CORE_0_SPMI_ADDR) return wcd9xxx_spmi_resume(); return 0; } static int msm8x16_wcd_spmi_suspend(struct spmi_device *spmi, pm_message_t pmesg) { struct resource *wcd_resource; wcd_resource = spmi_get_resource(spmi, NULL, IORESOURCE_MEM, 0); if (!wcd_resource) { dev_err(&spmi->dev, "Unable to get CDC SPMI resource\n"); return -ENXIO; } if (wcd_resource->start == TOMBAK_CORE_0_SPMI_ADDR) return wcd9xxx_spmi_suspend(pmesg); return 0; } #endif static struct spmi_device_id msm8x16_wcd_spmi_id_table[] = { {"wcd-spmi", MSM8X16_WCD_SPMI_DIGITAL}, {"wcd-spmi", MSM8X16_WCD_SPMI_ANALOG}, {} }; static struct of_device_id msm8x16_wcd_spmi_of_match[] = { { .compatible = "qcom,msm8x16_wcd_codec",}, { }, }; static struct spmi_driver wcd_spmi_driver = { .driver = { .owner = THIS_MODULE, .name = "wcd-spmi-core", .of_match_table = msm8x16_wcd_spmi_of_match }, #ifdef CONFIG_PM .suspend = msm8x16_wcd_spmi_suspend, .resume = msm8x16_wcd_spmi_resume, #endif .id_table = msm8x16_wcd_spmi_id_table, .probe = msm8x16_wcd_spmi_probe, .remove = msm8x16_wcd_spmi_remove, }; static int __init msm8x16_wcd_codec_init(void) { spmi_driver_register(&wcd_spmi_driver); return 0; } late_initcall(msm8x16_wcd_codec_init); static void __exit msm8x16_wcd_codec_exit(void) { spmi_driver_unregister(&wcd_spmi_driver); } module_exit(msm8x16_wcd_codec_exit); MODULE_DESCRIPTION("MSM8x16 Audio codec driver"); MODULE_LICENSE("GPL v2"); MODULE_DEVICE_TABLE(of, msm8x16_wcd_spmi_id_table);
ZeroInfinityXDA/HelixKernel_Nougat
sound/soc/codecs/msm8x16-wcd.c
C
gpl-2.0
183,679
/**************************************************************************** * (C) Copyright 2008 Samsung Electronics Co., Ltd., All rights reserved * * [File Name] :s3c-otg-oci.h * [Description] : The Header file defines the external and internal functions of OCI. * [Department] : System LSI Division/Embedded S/W Platform * [Created Date]: 2008/06/18 * [Revision History] * - Added some functions and data structure of OCI * ****************************************************************************/ /**************************************************************************** * 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 ****************************************************************************/ #ifndef _OCI_H_ #define _OCI_H_ #ifdef __cplusplus extern "C" { #endif //#include "s3c-otg-common-const.h" #include "s3c-otg-common-errorcode.h" #include "s3c-otg-common-regdef.h" #include "s3c-otg-hcdi-kal.h" #include "s3c-otg-hcdi-memory.h" #include "s3c-otg-hcdi-debug.h" #include "s3c-otg-roothub.h" #include "s3c-otg-hcdi-hcd.h" #include <mach/map.h> //virtual address for smdk extern void otg_phy_init(void); #include <plat/regs-clock.h> ///OCI interace int oci_init(void); int oci_start(void); int oci_stop(void); u8 oci_start_transfer(stransfer_t *st_t); int oci_stop_transfer(u8 ch_num); int oci_channel_init(u8 ch_num, stransfer_t *st_t); u32 oci_get_frame_num(void); u16 oci_get_frame_interval(void); void oci_set_frame_interval(u16 intervl); ///OCI Internal Functions int oci_sys_init(void); int oci_core_init(void); int oci_init_mode(void); int oci_host_init(void); int oci_dev_init(void); int oci_channel_alloc(u8 *ch_num); int oci_channel_dealloc(u8 ch_num); void oci_config_flush_fifo(u32 mode); void oci_flush_tx_fifo(u32 num); void oci_flush_rx_fifo(void); int oci_core_reset(void); void oci_set_global_interrupt(bool set); #ifdef __cplusplus } #endif #endif /* _OCI_H_ */
skeeterslint/linux-2.6.29
drivers/usb/host/s3c-otg/s3c-otg-oci.h
C
gpl-2.0
2,623
DOUBLE PRECISION FUNCTION CDFGLO(X,PARA) C*********************************************************************** C* * C* FORTRAN CODE WRITTEN FOR INCLUSION IN IBM RESEARCH REPORT RC20525, * C* 'FORTRAN ROUTINES FOR USE WITH THE METHOD OF L-MOMENTS, VERSION 3' * C* * C* J. R. M. HOSKING * C* IBM RESEARCH DIVISION * C* T. J. WATSON RESEARCH CENTER * C* YORKTOWN HEIGHTS * C* NEW YORK 10598, U.S.A. * C* * C* VERSION 3 AUGUST 1996 * C* * C*********************************************************************** C C DISTRIBUTION FUNCTION OF THE GENERALIZED LOGISTIC DISTRIBUTION C IMPLICIT DOUBLE PRECISION (A-H,O-Z) DOUBLE PRECISION PARA(3) DATA ZERO/0D0/,ONE/1D0/ C C SMALL IS USED TO TEST WHETHER X IS EFFECTIVELY AT C THE ENDPOINT OF THE DISTRIBUTION C DATA SMALL/1D-15/ C U=PARA(1) A=PARA(2) G=PARA(3) IF(A.LE.ZERO)GOTO 1000 Y=(X-U)/A IF(G.EQ.ZERO)GOTO 20 ARG=ONE-G*Y IF(ARG.GT.SMALL)GOTO 10 IF(G.LT.ZERO)CDFGLO=ZERO IF(G.GT.ZERO)CDFGLO=ONE RETURN 10 Y=-DLOG(ARG)/G 20 CDFGLO=ONE/(ONE+DEXP(-Y)) RETURN C 1000 WRITE(6,7000) CDFGLO=ZERO RETURN C 7000 FORMAT(' *** ERROR *** ROUTINE CDFGLO : PARAMETERS INVALID') END
gitpan/Statistics-Lmoments
lmoments/cdfglo.f
FORTRAN
gpl-2.0
1,815
<?php /** * Plugin installation and activation for WordPress themes. * * Please note that this is a drop-in library for a theme or plugin. * The authors of this library (Thomas, Gary and Juliette) are NOT responsible * for the support of your plugin or theme. Please contact the plugin * or theme author for support. * * @package TGM-Plugin-Activation * @version 2.5.2 * @link http://tgmpluginactivation.com/ * @author Thomas Griffin, Gary Jones, Juliette Reinders Folmer * @copyright Copyright (c) 2011, Thomas Griffin * @license GPL-2.0+ * * @wordpress-plugin * Plugin Name: TGM Plugin Activation * Plugin URI: * Description: Plugin installation and activation for WordPress themes. * Version: 2.5.2 * Author: Thomas Griffin, Gary Jones, Juliette Reinders Folmer * Author URI: http://tgmpluginactivation.com/ * Text Domain: tgmpa * Domain Path: /languages/ * Copyright: 2011, Thomas Griffin */ /* Copyright 2011 Thomas Griffin (thomasgriffinmedia.com) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 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 */ if ( ! class_exists( 'TGM_Plugin_Activation' ) ) { /** * Automatic plugin installation and activation library. * * Creates a way to automatically install and activate plugins from within themes. * The plugins can be either bundled, downloaded from the WordPress * Plugin Repository or downloaded from another external source. * * @since 1.0.0 * * @package TGM-Plugin-Activation * @author Thomas Griffin * @author Gary Jones */ class TGM_Plugin_Activation { /** * TGMPA version number. * * @since 2.5.0 * * @const string Version number. */ const TGMPA_VERSION = '2.5.2'; /** * Regular expression to test if a URL is a WP plugin repo URL. * * @const string Regex. * * @since 2.5.0 */ const WP_REPO_REGEX = '|^http[s]?://wordpress\.org/(?:extend/)?plugins/|'; /** * Arbitrary regular expression to test if a string starts with a URL. * * @const string Regex. * * @since 2.5.0 */ const IS_URL_REGEX = '|^http[s]?://|'; /** * Holds a copy of itself, so it can be referenced by the class name. * * @since 1.0.0 * * @var TGM_Plugin_Activation */ public static $instance; /** * Holds arrays of plugin details. * * @since 1.0.0 * * @since 2.5.0 the array has the plugin slug as an associative key. * * @var array */ public $plugins = array(); /** * Holds arrays of plugin names to use to sort the plugins array. * * @since 2.5.0 * * @var array */ protected $sort_order = array(); /** * Whether any plugins have the 'force_activation' setting set to true. * * @since 2.5.0 * * @var bool */ protected $has_forced_activation = false; /** * Whether any plugins have the 'force_deactivation' setting set to true. * * @since 2.5.0 * * @var bool */ protected $has_forced_deactivation = false; /** * Name of the unique ID to hash notices. * * @since 2.4.0 * * @var string */ public $id = 'tgmpa'; /** * Name of the query-string argument for the admin page. * * @since 1.0.0 * * @var string */ protected $menu = 'tgmpa-install-plugins'; /** * Parent menu file slug. * * @since 2.5.0 * * @var string */ public $parent_slug = 'themes.php'; /** * Capability needed to view the plugin installation menu item. * * @since 2.5.0 * * @var string */ public $capability = 'edit_theme_options'; /** * Default absolute path to folder containing bundled plugin zip files. * * @since 2.0.0 * * @var string Absolute path prefix to zip file location for bundled plugins. Default is empty string. */ public $default_path = ''; /** * Flag to show admin notices or not. * * @since 2.1.0 * * @var boolean */ public $has_notices = true; /** * Flag to determine if the user can dismiss the notice nag. * * @since 2.4.0 * * @var boolean */ public $dismissable = true; /** * Message to be output above nag notice if dismissable is false. * * @since 2.4.0 * * @var string */ public $dismiss_msg = ''; /** * Flag to set automatic activation of plugins. Off by default. * * @since 2.2.0 * * @var boolean */ public $is_automatic = false; /** * Optional message to display before the plugins table. * * @since 2.2.0 * * @var string Message filtered by wp_kses_post(). Default is empty string. */ public $message = ''; /** * Holds configurable array of strings. * * Default values are added in the constructor. * * @since 2.0.0 * * @var array */ public $strings = array(); /** * Holds the version of WordPress. * * @since 2.4.0 * * @var int */ public $wp_version; /** * Holds the hook name for the admin page. * * @since 2.5.0 * * @var string */ public $page_hook; /** * Adds a reference of this object to $instance, populates default strings, * does the tgmpa_init action hook, and hooks in the interactions to init. * * @internal This method should be `protected`, but as too many TGMPA implementations * haven't upgraded beyond v2.3.6 yet, this gives backward compatibility issues. * Reverted back to public for the time being. * * @since 1.0.0 * * @see TGM_Plugin_Activation::init() */ public function __construct() { // Set the current WordPress version. $this->wp_version = $GLOBALS['wp_version']; // Announce that the class is ready, and pass the object (for advanced use). do_action_ref_array( 'tgmpa_init', array( $this ) ); // When the rest of WP has loaded, kick-start the rest of the class. add_action( 'init', array( $this, 'init' ) ); } /** * Magic method to (not) set protected properties from outside of this class. * * @internal hackedihack... There is a serious bug in v2.3.2 - 2.3.6 where the `menu` property * is being assigned rather than tested in a conditional, effectively rendering it useless. * This 'hack' prevents this from happening. * * @see https://github.com/TGMPA/TGM-Plugin-Activation/blob/2.3.6/tgm-plugin-activation/class-tgm-plugin-activation.php#L1593 * * @param string $name Name of an inaccessible property. * @param mixed $value Value to assign to the property. * @return void Silently fail to set the property when this is tried from outside of this class context. * (Inside this class context, the __set() method if not used as there is direct access.) */ public function __set( $name, $value ) { return; } /** * Magic method to get the value of a protected property outside of this class context. * * @param string $name Name of an inaccessible property. * @return mixed The property value. */ public function __get( $name ) { return $this->{$name}; } /** * Initialise the interactions between this class and WordPress. * * Hooks in three new methods for the class: admin_menu, notices and styles. * * @since 2.0.0 * * @see TGM_Plugin_Activation::admin_menu() * @see TGM_Plugin_Activation::notices() * @see TGM_Plugin_Activation::styles() */ public function init() { /** * By default TGMPA only loads on the WP back-end and not in an Ajax call. Using this filter * you can overrule that behaviour. * * @since 2.5.0 * * @param bool $load Whether or not TGMPA should load. * Defaults to the return of `is_admin() && ! defined( 'DOING_AJAX' )`. */ if ( true !== apply_filters( 'tgmpa_load', ( is_admin() && ! defined( 'DOING_AJAX' ) ) ) ) { return; } // Load class strings. $this->strings = array( 'page_title' => __( 'Install Required Plugins', 'tgmpa' ), 'menu_title' => __( 'Install Plugins', 'tgmpa' ), 'installing' => __( 'Installing Plugin: %s', 'tgmpa' ), 'oops' => __( 'Something went wrong with the plugin API.', 'tgmpa' ), 'notice_can_install_required' => _n_noop( 'This theme requires the following plugin: %1$s.', 'This theme requires the following plugins: %1$s.', 'tgmpa' ), 'notice_can_install_recommended' => _n_noop( 'This theme recommends the following plugin: %1$s.', 'This theme recommends the following plugins: %1$s.', 'tgmpa' ), 'notice_cannot_install' => _n_noop( 'Sorry, but you do not have the correct permissions to install the %1$s plugin.', 'Sorry, but you do not have the correct permissions to install the %1$s plugins.', 'tgmpa' ), 'notice_ask_to_update' => _n_noop( 'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.', 'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.', 'tgmpa' ), 'notice_ask_to_update_maybe' => _n_noop( 'There is an update available for: %1$s.', 'There are updates available for the following plugins: %1$s.', 'tgmpa' ), 'notice_cannot_update' => _n_noop( 'Sorry, but you do not have the correct permissions to update the %1$s plugin.', 'Sorry, but you do not have the correct permissions to update the %1$s plugins.', 'tgmpa' ), 'notice_can_activate_required' => _n_noop( 'The following required plugin is currently inactive: %1$s.', 'The following required plugins are currently inactive: %1$s.', 'tgmpa' ), 'notice_can_activate_recommended' => _n_noop( 'The following recommended plugin is currently inactive: %1$s.', 'The following recommended plugins are currently inactive: %1$s.', 'tgmpa' ), 'notice_cannot_activate' => _n_noop( 'Sorry, but you do not have the correct permissions to activate the %1$s plugin.', 'Sorry, but you do not have the correct permissions to activate the %1$s plugins.', 'tgmpa' ), 'install_link' => _n_noop( 'Begin installing plugin', 'Begin installing plugins', 'tgmpa' ), 'update_link' => _n_noop( 'Begin updating plugin', 'Begin updating plugins', 'tgmpa' ), 'activate_link' => _n_noop( 'Begin activating plugin', 'Begin activating plugins', 'tgmpa' ), 'return' => __( 'Return to Required Plugins Installer', 'tgmpa' ), 'dashboard' => __( 'Return to the dashboard', 'tgmpa' ), 'plugin_activated' => __( 'Plugin activated successfully.', 'tgmpa' ), 'activated_successfully' => __( 'The following plugin was activated successfully:', 'tgmpa' ), 'plugin_already_active' => __( 'No action taken. Plugin %1$s was already active.', 'tgmpa' ), 'plugin_needs_higher_version' => __( 'Plugin not activated. A higher version of %s is needed for this theme. Please update the plugin.', 'tgmpa' ), 'complete' => __( 'All plugins installed and activated successfully. %1$s', 'tgmpa' ), 'dismiss' => __( 'Dismiss this notice', 'tgmpa' ), 'contact_admin' => __( 'Please contact the administrator of this site for help.', 'tgmpa' ), ); do_action( 'tgmpa_register' ); /* After this point, the plugins should be registered and the configuration set. */ // Proceed only if we have plugins to handle. if ( empty( $this->plugins ) || ! is_array( $this->plugins ) ) { return; } // Set up the menu and notices if we still have outstanding actions. if ( true !== $this->is_tgmpa_complete() ) { // Sort the plugins. array_multisort( $this->sort_order, SORT_ASC, $this->plugins ); add_action( 'admin_menu', array( $this, 'admin_menu' ) ); add_action( 'admin_head', array( $this, 'dismiss' ) ); // Prevent the normal links from showing underneath a single install/update page. add_filter( 'install_plugin_complete_actions', array( $this, 'actions' ) ); add_filter( 'update_plugin_complete_actions', array( $this, 'actions' ) ); if ( $this->has_notices ) { add_action( 'admin_notices', array( $this, 'notices' ) ); add_action( 'admin_init', array( $this, 'admin_init' ), 1 ); add_action( 'admin_enqueue_scripts', array( $this, 'thickbox' ) ); } add_action( 'load-plugins.php', array( $this, 'add_plugin_action_link_filters' ), 1 ); } // Make sure things get reset on switch theme. add_action( 'switch_theme', array( $this, 'flush_plugins_cache' ) ); if ( $this->has_notices ) { add_action( 'switch_theme', array( $this, 'update_dismiss' ) ); } // Setup the force activation hook. if ( true === $this->has_forced_activation ) { add_action( 'admin_init', array( $this, 'force_activation' ) ); } // Setup the force deactivation hook. if ( true === $this->has_forced_deactivation ) { add_action( 'switch_theme', array( $this, 'force_deactivation' ) ); } } /** * Prevent activation of plugins which don't meet the minimum version requirement from the * WP native plugins page. * * @since 2.5.0 */ public function add_plugin_action_link_filters() { foreach ( $this->plugins as $slug => $plugin ) { if ( false === $this->can_plugin_activate( $slug ) ) { add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_activate' ), 20 ); } if ( true === $plugin['force_activation'] ) { add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_deactivate' ), 20 ); } if ( false !== $this->does_plugin_require_update( $slug ) ) { add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_update' ), 20 ); } } } /** * Remove the 'Activate' link on the WP native plugins page if the plugin does not meet the * minimum version requirements. * * @since 2.5.0 * * @param array $actions Action links. * @return array */ public function filter_plugin_action_links_activate( $actions ) { unset( $actions['activate'] ); return $actions; } /** * Remove the 'Deactivate' link on the WP native plugins page if the plugin has been set to force activate. * * @since 2.5.0 * * @param array $actions Action links. * @return array */ public function filter_plugin_action_links_deactivate( $actions ) { unset( $actions['deactivate'] ); return $actions; } /** * Add a 'Requires update' link on the WP native plugins page if the plugin does not meet the * minimum version requirements. * * @since 2.5.0 * * @param array $actions Action links. * @return array */ public function filter_plugin_action_links_update( $actions ) { $actions['update'] = sprintf( '<a href="%1$s" title="%2$s" class="edit">%3$s</a>', esc_url( $this->get_tgmpa_status_url( 'update' ) ), esc_attr__( 'This plugin needs to be updated to be compatible with your theme.', 'tgmpa' ), esc_html__( 'Update Required', 'tgmpa' ) ); return $actions; } /** * Handles calls to show plugin information via links in the notices. * * We get the links in the admin notices to point to the TGMPA page, rather * than the typical plugin-install.php file, so we can prepare everything * beforehand. * * WP does not make it easy to show the plugin information in the thickbox - * here we have to require a file that includes a function that does the * main work of displaying it, enqueue some styles, set up some globals and * finally call that function before exiting. * * Down right easy once you know how... * * Returns early if not the TGMPA page. * * @since 2.1.0 * * @global string $tab Used as iframe div class names, helps with styling * @global string $body_id Used as the iframe body ID, helps with styling * * @return null Returns early if not the TGMPA page. */ public function admin_init() { if ( ! $this->is_tgmpa_page() ) { return; } if ( isset( $_REQUEST['tab'] ) && 'plugin-information' === $_REQUEST['tab'] ) { // Needed for install_plugin_information(). require_once ABSPATH . 'wp-admin/includes/plugin-install.php'; wp_enqueue_style( 'plugin-install' ); global $tab, $body_id; $body_id = 'plugin-information'; // @codingStandardsIgnoreStart $tab = 'plugin-information'; // @codingStandardsIgnoreEnd install_plugin_information(); exit; } } /** * Enqueue thickbox scripts/styles for plugin info. * * Thickbox is not automatically included on all admin pages, so we must * manually enqueue it for those pages. * * Thickbox is only loaded if the user has not dismissed the admin * notice or if there are any plugins left to install and activate. * * @since 2.1.0 */ public function thickbox() { if ( ! get_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, true ) ) { add_thickbox(); } } /** * Adds submenu page if there are plugin actions to take. * * This method adds the submenu page letting users know that a required * plugin needs to be installed. * * This page disappears once the plugin has been installed and activated. * * @since 1.0.0 * * @see TGM_Plugin_Activation::init() * @see TGM_Plugin_Activation::install_plugins_page() * * @return null Return early if user lacks capability to install a plugin. */ public function admin_menu() { // Make sure privileges are correct to see the page. if ( ! current_user_can( 'install_plugins' ) ) { return; } $args = apply_filters( 'tgmpa_admin_menu_args', array( 'parent_slug' => $this->parent_slug, // Parent Menu slug. 'page_title' => $this->strings['page_title'], // Page title. 'menu_title' => $this->strings['menu_title'], // Menu title. 'capability' => $this->capability, // Capability. 'menu_slug' => $this->menu, // Menu slug. 'function' => array( $this, 'install_plugins_page' ), // Callback. ) ); $this->add_admin_menu( $args ); } /** * Add the menu item. * * @since 2.5.0 * * @param array $args Menu item configuration. */ protected function add_admin_menu( array $args ) { if ( has_filter( 'tgmpa_admin_menu_use_add_theme_page' ) ) { _deprecated_function( 'The "tgmpa_admin_menu_use_add_theme_page" filter', '2.5.0', esc_html__( 'Set the parent_slug config variable instead.', 'tgmpa' ) ); } if ( 'themes.php' === $this->parent_slug ) { $this->page_hook = call_user_func( 'add_theme_page', $args['page_title'], $args['menu_title'], $args['capability'], $args['menu_slug'], $args['function'] ); } else { //$this->page_hook = call_user_func( 'add_submenu_page', $args['parent_slug'], $args['page_title'], $args['menu_title'], $args['capability'], $args['menu_slug'], $args['function'] ); } } /** * Echoes plugin installation form. * * This method is the callback for the admin_menu method function. * This displays the admin page and form area where the user can select to install and activate the plugin. * Aborts early if we're processing a plugin installation action. * * @since 1.0.0 * * @return null Aborts early if we're processing a plugin installation action. */ public function install_plugins_page() { // Store new instance of plugin table in object. $plugin_table = new TGMPA_List_Table; // Return early if processing a plugin installation action. if ( ( ( 'tgmpa-bulk-install' === $plugin_table->current_action() || 'tgmpa-bulk-update' === $plugin_table->current_action() ) && $plugin_table->process_bulk_actions() ) || $this->do_plugin_install() ) { return; } // Force refresh of available plugin information so we'll know about manual updates/deletes. wp_clean_plugins_cache( false ); ?> <div class="tgmpa wrap"> <h2><?php echo esc_html( get_admin_page_title() ); ?></h2> <?php $plugin_table->prepare_items(); ?> <?php if ( ! empty( $this->message ) && is_string( $this->message ) ) { echo wp_kses_post( $this->message ); } ?> <?php $plugin_table->views(); ?> <form id="tgmpa-plugins" action="" method="post"> <input type="hidden" name="tgmpa-page" value="<?php echo esc_attr( $this->menu ); ?>" /> <input type="hidden" name="plugin_status" value="<?php echo esc_attr( $plugin_table->view_context ); ?>" /> <?php $plugin_table->display(); ?> </form> </div> <?php } /** * Installs, updates or activates a plugin depending on the action link clicked by the user. * * Checks the $_GET variable to see which actions have been * passed and responds with the appropriate method. * * Uses WP_Filesystem to process and handle the plugin installation * method. * * @since 1.0.0 * * @uses WP_Filesystem * @uses WP_Error * @uses WP_Upgrader * @uses Plugin_Upgrader * @uses Plugin_Installer_Skin * @uses Plugin_Upgrader_Skin * * @return boolean True on success, false on failure. */ protected function do_plugin_install() { if ( empty( $_GET['plugin'] ) ) { return false; } // All plugin information will be stored in an array for processing. $slug = $this->sanitize_key( urldecode( $_GET['plugin'] ) ); if ( ! isset( $this->plugins[ $slug ] ) ) { return false; } // Was an install or upgrade action link clicked? if ( ( isset( $_GET['tgmpa-install'] ) && 'install-plugin' === $_GET['tgmpa-install'] ) || ( isset( $_GET['tgmpa-update'] ) && 'update-plugin' === $_GET['tgmpa-update'] ) ) { $install_type = 'install'; if ( isset( $_GET['tgmpa-update'] ) && 'update-plugin' === $_GET['tgmpa-update'] ) { $install_type = 'update'; } check_admin_referer( 'tgmpa-' . $install_type, 'tgmpa-nonce' ); // Pass necessary information via URL if WP_Filesystem is needed. $url = wp_nonce_url( add_query_arg( array( 'plugin' => urlencode( $slug ), 'tgmpa-' . $install_type => $install_type . '-plugin', ), $this->get_tgmpa_url() ), 'tgmpa-' . $install_type, 'tgmpa-nonce' ); $method = ''; // Leave blank so WP_Filesystem can populate it as necessary. if ( false === ( $creds = request_filesystem_credentials( esc_url_raw( $url ), $method, false, false, array() ) ) ) { return true; } if ( ! WP_Filesystem( $creds ) ) { request_filesystem_credentials( esc_url_raw( $url ), $method, true, false, array() ); // Setup WP_Filesystem. return true; } /* If we arrive here, we have the filesystem. */ // Prep variables for Plugin_Installer_Skin class. $extra = array(); $extra['slug'] = $slug; // Needed for potentially renaming of directory name. $source = $this->get_download_url( $slug ); $api = ( 'repo' === $this->plugins[ $slug ]['source_type'] ) ? $this->get_plugins_api( $slug ) : null; $api = ( false !== $api ) ? $api : null; $url = add_query_arg( array( 'action' => $install_type . '-plugin', 'plugin' => urlencode( $slug ), ), 'update.php' ); if ( ! class_exists( 'Plugin_Upgrader', false ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; } $skin_args = array( 'type' => ( 'bundled' !== $this->plugins[ $slug ]['source_type'] ) ? 'web' : 'upload', 'title' => sprintf( $this->strings['installing'], $this->plugins[ $slug ]['name'] ), 'url' => esc_url_raw( $url ), 'nonce' => $install_type . '-plugin_' . $slug, 'plugin' => '', 'api' => $api, 'extra' => $extra, ); if ( 'update' === $install_type ) { $skin_args['plugin'] = $this->plugins[ $slug ]['file_path']; $skin = new Plugin_Upgrader_Skin( $skin_args ); } else { $skin = new Plugin_Installer_Skin( $skin_args ); } // Create a new instance of Plugin_Upgrader. $upgrader = new Plugin_Upgrader( $skin ); // Perform the action and install the plugin from the $source urldecode(). add_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1, 3 ); if ( 'update' === $install_type ) { // Inject our info into the update transient. $to_inject = array( $slug => $this->plugins[ $slug ] ); $to_inject[ $slug ]['source'] = $source; $this->inject_update_info( $to_inject ); $upgrader->upgrade( $this->plugins[ $slug ]['file_path'] ); } else { $upgrader->install( $source ); } remove_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1, 3 ); // Make sure we have the correct file path now the plugin is installed/updated. $this->populate_file_path( $slug ); // Only activate plugins if the config option is set to true and the plugin isn't // already active (upgrade). if ( $this->is_automatic && ! $this->is_plugin_active( $slug ) ) { $plugin_activate = $upgrader->plugin_info(); // Grab the plugin info from the Plugin_Upgrader method. if ( false === $this->activate_single_plugin( $plugin_activate, $slug, true ) ) { return true; // Finish execution of the function early as we encountered an error. } } $this->show_tgmpa_version(); // Display message based on if all plugins are now active or not. if ( $this->is_tgmpa_complete() ) { echo '<p>', sprintf( esc_html( $this->strings['complete'] ), '<a href="' . esc_url( self_admin_url() ) . '">' . esc_html__( 'Return to the Dashboard', 'tgmpa' ) . '</a>' ), '</p>'; echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>'; } else { echo '<p><a href="', esc_url( $this->get_tgmpa_url() ), '" target="_parent">', esc_html( $this->strings['return'] ), '</a></p>'; } return true; } elseif ( isset( $this->plugins[ $slug ]['file_path'], $_GET['tgmpa-activate'] ) && 'activate-plugin' === $_GET['tgmpa-activate'] ) { // Activate action link was clicked. check_admin_referer( 'tgmpa-activate', 'tgmpa-nonce' ); if ( false === $this->activate_single_plugin( $this->plugins[ $slug ]['file_path'], $slug ) ) { return true; // Finish execution of the function early as we encountered an error. } } return false; } /** * Inject information into the 'update_plugins' site transient as WP checks that before running an update. * * @since 2.5.0 * * @param array $plugins The plugin information for the plugins which are to be updated. */ public function inject_update_info( $plugins ) { $repo_updates = get_site_transient( 'update_plugins' ); if ( ! is_object( $repo_updates ) ) { $repo_updates = new stdClass; } foreach ( $plugins as $slug => $plugin ) { $file_path = $plugin['file_path']; if ( empty( $repo_updates->response[ $file_path ] ) ) { $repo_updates->response[ $file_path ] = new stdClass; } // We only really need to set package, but let's do all we can in case WP changes something. $repo_updates->response[ $file_path ]->slug = $slug; $repo_updates->response[ $file_path ]->plugin = $file_path; $repo_updates->response[ $file_path ]->new_version = $plugin['version']; $repo_updates->response[ $file_path ]->package = $plugin['source']; if ( empty( $repo_updates->response[ $file_path ]->url ) && ! empty( $plugin['external_url'] ) ) { $repo_updates->response[ $file_path ]->url = $plugin['external_url']; } } set_site_transient( 'update_plugins', $repo_updates ); } /** * Adjust the plugin directory name if necessary. * * The final destination directory of a plugin is based on the subdirectory name found in the * (un)zipped source. In some cases - most notably GitHub repository plugin downloads -, this * subdirectory name is not the same as the expected slug and the plugin will not be recognized * as installed. This is fixed by adjusting the temporary unzipped source subdirectory name to * the expected plugin slug. * * @since 2.5.0 * * @param string $source Path to upgrade/zip-file-name.tmp/subdirectory/. * @param string $remote_source Path to upgrade/zip-file-name.tmp. * @param \WP_Upgrader $upgrader Instance of the upgrader which installs the plugin. * @return string $source */ public function maybe_adjust_source_dir( $source, $remote_source, $upgrader ) { if ( ! $this->is_tgmpa_page() || ! is_object( $GLOBALS['wp_filesystem'] ) ) { return $source; } // Check for single file plugins. $source_files = array_keys( $GLOBALS['wp_filesystem']->dirlist( $remote_source ) ); if ( 1 === count( $source_files ) && false === $GLOBALS['wp_filesystem']->is_dir( $source ) ) { return $source; } // Multi-file plugin, let's see if the directory is correctly named. $desired_slug = ''; // Figure out what the slug is supposed to be. if ( false === $upgrader->bulk && ! empty( $upgrader->skin->options['extra']['slug'] ) ) { $desired_slug = $upgrader->skin->options['extra']['slug']; } else { // Bulk installer contains less info, so fall back on the info registered here. foreach ( $this->plugins as $slug => $plugin ) { if ( ! empty( $upgrader->skin->plugin_names[ $upgrader->skin->i ] ) && $plugin['name'] === $upgrader->skin->plugin_names[ $upgrader->skin->i ] ) { $desired_slug = $slug; break; } } unset( $slug, $plugin ); } if ( ! empty( $desired_slug ) ) { $subdir_name = untrailingslashit( str_replace( trailingslashit( $remote_source ), '', $source ) ); if ( ! empty( $subdir_name ) && $subdir_name !== $desired_slug ) { $from = untrailingslashit( $source ); $to = trailingslashit( $remote_source ) . $desired_slug; if ( true === $GLOBALS['wp_filesystem']->move( $from, $to ) ) { return trailingslashit( $to ); } else { return new WP_Error( 'rename_failed', esc_html__( 'The remote plugin package does not contain a folder with the desired slug and renaming did not work.', 'tgmpa' ) . ' ' . esc_html__( 'Please contact the plugin provider and ask them to package their plugin according to the WordPress guidelines.', 'tgmpa' ), array( 'found' => $subdir_name, 'expected' => $desired_slug ) ); } } elseif ( empty( $subdir_name ) ) { return new WP_Error( 'packaged_wrong', esc_html__( 'The remote plugin package consists of more than one file, but the files are not packaged in a folder.', 'tgmpa' ) . ' ' . esc_html__( 'Please contact the plugin provider and ask them to package their plugin according to the WordPress guidelines.', 'tgmpa' ), array( 'found' => $subdir_name, 'expected' => $desired_slug ) ); } } return $source; } /** * Activate a single plugin and send feedback about the result to the screen. * * @since 2.5.0 * * @param string $file_path Path within wp-plugins/ to main plugin file. * @param string $slug Plugin slug. * @param bool $automatic Whether this is an automatic activation after an install. Defaults to false. * This determines the styling of the output messages. * @return bool False if an error was encountered, true otherwise. */ protected function activate_single_plugin( $file_path, $slug, $automatic = false ) { if ( $this->can_plugin_activate( $slug ) ) { $activate = activate_plugin( $file_path ); if ( is_wp_error( $activate ) ) { echo '<div id="message" class="error"><p>', wp_kses_post( $activate->get_error_message() ), '</p></div>', '<p><a href="', esc_url( $this->get_tgmpa_url() ), '" target="_parent">', esc_html( $this->strings['return'] ), '</a></p>'; return false; // End it here if there is an error with activation. } else { if ( ! $automatic ) { // Make sure message doesn't display again if bulk activation is performed // immediately after a single activation. if ( ! isset( $_POST['action'] ) ) { // WPCS: CSRF OK. echo '<div id="message" class="updated"><p>', esc_html( $this->strings['activated_successfully'] ), ' <strong>', esc_html( $this->plugins[ $slug ]['name'] ), '.</strong></p></div>'; } } else { // Simpler message layout for use on the plugin install page. echo '<p>', esc_html( $this->strings['plugin_activated'] ), '</p>'; } } } elseif ( $this->is_plugin_active( $slug ) ) { // No simpler message format provided as this message should never be encountered // on the plugin install page. echo '<div id="message" class="error"><p>', sprintf( esc_html( $this->strings['plugin_already_active'] ), '<strong>' . esc_html( $this->plugins[ $slug ]['name'] ) . '</strong>' ), '</p></div>'; } elseif ( $this->does_plugin_require_update( $slug ) ) { if ( ! $automatic ) { // Make sure message doesn't display again if bulk activation is performed // immediately after a single activation. if ( ! isset( $_POST['action'] ) ) { // WPCS: CSRF OK. echo '<div id="message" class="error"><p>', sprintf( esc_html( $this->strings['plugin_needs_higher_version'] ), '<strong>' . esc_html( $this->plugins[ $slug ]['name'] ) . '</strong>' ), '</p></div>'; } } else { // Simpler message layout for use on the plugin install page. echo '<p>', sprintf( esc_html( $this->strings['plugin_needs_higher_version'] ), esc_html( $this->plugins[ $slug ]['name'] ) ), '</p>'; } } return true; } /** * Echoes required plugin notice. * * Outputs a message telling users that a specific plugin is required for * their theme. If appropriate, it includes a link to the form page where * users can install and activate the plugin. * * Returns early if we're on the Install page. * * @since 1.0.0 * * @global object $current_screen * * @return null Returns early if we're on the Install page. */ public function notices() { // Remove nag on the install page / Return early if the nag message has been dismissed. if ( $this->is_tgmpa_page() || get_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, true ) ) { return; } // Store for the plugin slugs by message type. $message = array(); // Initialize counters used to determine plurality of action link texts. $install_link_count = 0; $update_link_count = 0; $activate_link_count = 0; foreach ( $this->plugins as $slug => $plugin ) { if ( $this->is_plugin_active( $slug ) && false === $this->does_plugin_have_update( $slug ) ) { continue; } if ( ! $this->is_plugin_installed( $slug ) ) { if ( current_user_can( 'install_plugins' ) ) { $install_link_count++; if ( true === $plugin['required'] ) { $message['notice_can_install_required'][] = $slug; } else { $message['notice_can_install_recommended'][] = $slug; } } else { // Need higher privileges to install the plugin. $message['notice_cannot_install'][] = $slug; } } else { if ( ! $this->is_plugin_active( $slug ) && $this->can_plugin_activate( $slug ) ) { if ( current_user_can( 'activate_plugins' ) ) { $activate_link_count++; if ( true === $plugin['required'] ) { $message['notice_can_activate_required'][] = $slug; } else { $message['notice_can_activate_recommended'][] = $slug; } } else { // Need higher privileges to activate the plugin. $message['notice_cannot_activate'][] = $slug; } } if ( $this->does_plugin_require_update( $slug ) || false !== $this->does_plugin_have_update( $slug ) ) { if ( current_user_can( 'install_plugins' ) ) { $update_link_count++; if ( $this->does_plugin_require_update( $slug ) ) { $message['notice_ask_to_update'][] = $slug; } elseif ( false !== $this->does_plugin_have_update( $slug ) ) { $message['notice_ask_to_update_maybe'][] = $slug; } } else { // Need higher privileges to update the plugin. $message['notice_cannot_update'][] = $slug; } } } } unset( $slug, $plugin ); // If we have notices to display, we move forward. if ( ! empty( $message ) ) { krsort( $message ); // Sort messages. $rendered = ''; // As add_settings_error() wraps the final message in a <p> and as the final message can't be // filtered, using <p>'s in our html would render invalid html output. $line_template = '<span style="display: block; margin: 0.5em 0.5em 0 0; clear: both;">%s</span>' . "\n"; // If dismissable is false and a message is set, output it now. if ( ! $this->dismissable && ! empty( $this->dismiss_msg ) ) { $rendered .= sprintf( $line_template, wp_kses_post( $this->dismiss_msg ) ); } // Render the individual message lines for the notice. foreach ( $message as $type => $plugin_group ) { $linked_plugins = array(); // Get the external info link for a plugin if one is available. foreach ( $plugin_group as $plugin_slug ) { $linked_plugins[] = $this->get_info_link( $plugin_slug ); } unset( $plugin_slug ); $count = count( $plugin_group ); $linked_plugins = array_map( array( 'TGMPA_Utils', 'wrap_in_em' ), $linked_plugins ); $last_plugin = array_pop( $linked_plugins ); // Pop off last name to prep for readability. $imploded = empty( $linked_plugins ) ? $last_plugin : ( implode( ', ', $linked_plugins ) . ' ' . esc_html_x( 'and', 'plugin A *and* plugin B', 'tgmpa' ) . ' ' . $last_plugin ); $rendered .= sprintf( $line_template, sprintf( translate_nooped_plural( $this->strings[ $type ], $count, 'tgmpa' ), $imploded, $count ) ); if ( 0 === strpos( $type, 'notice_cannot' ) ) { $rendered .= $this->strings['contact_admin']; } } unset( $type, $plugin_group, $linked_plugins, $count, $last_plugin, $imploded ); // Setup action links. $action_links = array( 'install' => '', 'update' => '', 'activate' => '', 'dismiss' => $this->dismissable ? '<a href="' . esc_url( add_query_arg( 'tgmpa-dismiss', 'dismiss_admin_notices' ) ) . '" class="dismiss-notice" target="_parent">' . esc_html( $this->strings['dismiss'] ) . '</a>' : '', ); $link_template = '<a href="%2$s">%1$s</a>'; if ( current_user_can( 'install_plugins' ) ) { if ( $install_link_count > 0 ) { $action_links['install'] = sprintf( $link_template, translate_nooped_plural( $this->strings['install_link'], $install_link_count, 'tgmpa' ), esc_url( $this->get_tgmpa_status_url( 'install' ) ) ); } if ( $update_link_count > 0 ) { $action_links['update'] = sprintf( $link_template, translate_nooped_plural( $this->strings['update_link'], $update_link_count, 'tgmpa' ), esc_url( $this->get_tgmpa_status_url( 'update' ) ) ); } } if ( current_user_can( 'activate_plugins' ) && $activate_link_count > 0 ) { $action_links['activate'] = sprintf( $link_template, translate_nooped_plural( $this->strings['activate_link'], $activate_link_count, 'tgmpa' ), esc_url( $this->get_tgmpa_status_url( 'activate' ) ) ); } $action_links = apply_filters( 'tgmpa_notice_action_links', $action_links ); $action_links = array_filter( (array) $action_links ); // Remove any empty array items. if ( ! empty( $action_links ) && is_array( $action_links ) ) { $action_links = sprintf( $line_template, implode( ' | ', $action_links ) ); $rendered .= apply_filters( 'tgmpa_notice_rendered_action_links', $action_links ); } // Register the nag messages and prepare them to be processed. if ( ! empty( $this->strings['nag_type'] ) ) { add_settings_error( 'tgmpa', 'tgmpa', $rendered, sanitize_html_class( strtolower( $this->strings['nag_type'] ) ) ); } else { $nag_class = version_compare( $this->wp_version, '3.8', '<' ) ? 'updated' : 'update-nag'; add_settings_error( 'tgmpa', 'tgmpa', $rendered, $nag_class ); } } // Admin options pages already output settings_errors, so this is to avoid duplication. if ( 'options-general' !== $GLOBALS['current_screen']->parent_base ) { $this->display_settings_errors(); } } /** * Display settings errors and remove those which have been displayed to avoid duplicate messages showing * * @since 2.5.0 */ protected function display_settings_errors() { global $wp_settings_errors; settings_errors( 'tgmpa' ); foreach ( (array) $wp_settings_errors as $key => $details ) { if ( 'tgmpa' === $details['setting'] ) { unset( $wp_settings_errors[ $key ] ); break; } } } /** * Add dismissable admin notices. * * Appends a link to the admin nag messages. If clicked, the admin notice disappears and no longer is visible to users. * * @since 2.1.0 */ public function dismiss() { if ( isset( $_GET['tgmpa-dismiss'] ) ) { update_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, 1 ); } } /** * Add individual plugin to our collection of plugins. * * If the required keys are not set or the plugin has already * been registered, the plugin is not added. * * @since 2.0.0 * * @param array|null $plugin Array of plugin arguments or null if invalid argument. * @return null Return early if incorrect argument. */ public function register( $plugin ) { if ( empty( $plugin['slug'] ) || empty( $plugin['name'] ) ) { return; } if ( empty( $plugin['slug'] ) || ! is_string( $plugin['slug'] ) || isset( $this->plugins[ $plugin['slug'] ] ) ) { return; } $defaults = array( 'name' => '', // String 'slug' => '', // String 'source' => 'repo', // String 'required' => false, // Boolean 'version' => '', // String 'force_activation' => false, // Boolean 'force_deactivation' => false, // Boolean 'external_url' => '', // String 'is_callable' => '', // String|Array. ); // Prepare the received data. $plugin = wp_parse_args( $plugin, $defaults ); // Standardize the received slug. $plugin['slug'] = $this->sanitize_key( $plugin['slug'] ); // Forgive users for using string versions of booleans or floats for version number. $plugin['version'] = (string) $plugin['version']; $plugin['source'] = empty( $plugin['source'] ) ? 'repo' : $plugin['source']; $plugin['required'] = TGMPA_Utils::validate_bool( $plugin['required'] ); $plugin['force_activation'] = TGMPA_Utils::validate_bool( $plugin['force_activation'] ); $plugin['force_deactivation'] = TGMPA_Utils::validate_bool( $plugin['force_deactivation'] ); // Enrich the received data. $plugin['file_path'] = $this->_get_plugin_basename_from_slug( $plugin['slug'] ); $plugin['source_type'] = $this->get_plugin_source_type( $plugin['source'] ); // Set the class properties. $this->plugins[ $plugin['slug'] ] = $plugin; $this->sort_order[ $plugin['slug'] ] = $plugin['name']; // Should we add the force activation hook ? if ( true === $plugin['force_activation'] ) { $this->has_forced_activation = true; } // Should we add the force deactivation hook ? if ( true === $plugin['force_deactivation'] ) { $this->has_forced_deactivation = true; } } /** * Determine what type of source the plugin comes from. * * @since 2.5.0 * * @param string $source The source of the plugin as provided, either empty (= WP repo), a file path * (= bundled) or an external URL. * @return string 'repo', 'external', or 'bundled' */ protected function get_plugin_source_type( $source ) { if ( 'repo' === $source || preg_match( self::WP_REPO_REGEX, $source ) ) { return 'repo'; } elseif ( preg_match( self::IS_URL_REGEX, $source ) ) { return 'external'; } else { return 'bundled'; } } /** * Sanitizes a string key. * * Near duplicate of WP Core `sanitize_key()`. The difference is that uppercase characters *are* * allowed, so as not to break upgrade paths from non-standard bundled plugins using uppercase * characters in the plugin directory path/slug. Silly them. * * @see https://developer.wordpress.org/reference/hooks/sanitize_key/ * * @since 2.5.0 * * @param string $key String key. * @return string Sanitized key */ public function sanitize_key( $key ) { $raw_key = $key; $key = preg_replace( '`[^A-Za-z0-9_-]`', '', $key ); /** * Filter a sanitized key string. * * @since 3.0.0 * * @param string $key Sanitized key. * @param string $raw_key The key prior to sanitization. */ return apply_filters( 'tgmpa_sanitize_key', $key, $raw_key ); } /** * Amend default configuration settings. * * @since 2.0.0 * * @param array $config Array of config options to pass as class properties. */ public function config( $config ) { $keys = array( 'id', 'default_path', 'has_notices', 'dismissable', 'dismiss_msg', 'menu', 'parent_slug', 'capability', 'is_automatic', 'message', 'strings', ); foreach ( $keys as $key ) { if ( isset( $config[ $key ] ) ) { if ( is_array( $config[ $key ] ) ) { $this->$key = array_merge( $this->$key, $config[ $key ] ); } else { $this->$key = $config[ $key ]; } } } } /** * Amend action link after plugin installation. * * @since 2.0.0 * * @param array $install_actions Existing array of actions. * @return array Amended array of actions. */ public function actions( $install_actions ) { // Remove action links on the TGMPA install page. if ( $this->is_tgmpa_page() ) { return false; } return $install_actions; } /** * Flushes the plugins cache on theme switch to prevent stale entries * from remaining in the plugin table. * * @since 2.4.0 * * @param bool $clear_update_cache Optional. Whether to clear the Plugin updates cache. * Parameter added in v2.5.0. */ public function flush_plugins_cache( $clear_update_cache = true ) { wp_clean_plugins_cache( $clear_update_cache ); } /** * Set file_path key for each installed plugin. * * @since 2.1.0 * * @param string $plugin_slug Optional. If set, only (re-)populates the file path for that specific plugin. * Parameter added in v2.5.0. */ public function populate_file_path( $plugin_slug = '' ) { if ( ! empty( $plugin_slug ) && is_string( $plugin_slug ) && isset( $this->plugins[ $plugin_slug ] ) ) { $this->plugins[ $plugin_slug ]['file_path'] = $this->_get_plugin_basename_from_slug( $plugin_slug ); } else { // Add file_path key for all plugins. foreach ( $this->plugins as $slug => $values ) { $this->plugins[ $slug ]['file_path'] = $this->_get_plugin_basename_from_slug( $slug ); } } } /** * Helper function to extract the file path of the plugin file from the * plugin slug, if the plugin is installed. * * @since 2.0.0 * * @param string $slug Plugin slug (typically folder name) as provided by the developer. * @return string Either file path for plugin if installed, or just the plugin slug. */ protected function _get_plugin_basename_from_slug( $slug ) { $keys = array_keys( $this->get_plugins() ); foreach ( $keys as $key ) { if ( preg_match( '|^' . $slug . '/|', $key ) ) { return $key; } } return $slug; } /** * Retrieve plugin data, given the plugin name. * * Loops through the registered plugins looking for $name. If it finds it, * it returns the $data from that plugin. Otherwise, returns false. * * @since 2.1.0 * * @param string $name Name of the plugin, as it was registered. * @param string $data Optional. Array key of plugin data to return. Default is slug. * @return string|boolean Plugin slug if found, false otherwise. */ public function _get_plugin_data_from_name( $name, $data = 'slug' ) { foreach ( $this->plugins as $values ) { if ( $name === $values['name'] && isset( $values[ $data ] ) ) { return $values[ $data ]; } } return false; } /** * Retrieve the download URL for a package. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return string Plugin download URL or path to local file or empty string if undetermined. */ public function get_download_url( $slug ) { $dl_source = ''; switch ( $this->plugins[ $slug ]['source_type'] ) { case 'repo': return $this->get_wp_repo_download_url( $slug ); case 'external': return $this->plugins[ $slug ]['source']; case 'bundled': return $this->default_path . $this->plugins[ $slug ]['source']; } return $dl_source; // Should never happen. } /** * Retrieve the download URL for a WP repo package. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return string Plugin download URL. */ protected function get_wp_repo_download_url( $slug ) { $source = ''; $api = $this->get_plugins_api( $slug ); if ( false !== $api && isset( $api->download_link ) ) { $source = $api->download_link; } return $source; } /** * Try to grab information from WordPress API. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return object Plugins_api response object on success, WP_Error on failure. */ protected function get_plugins_api( $slug ) { static $api = array(); // Cache received responses. if ( ! isset( $api[ $slug ] ) ) { if ( ! function_exists( 'plugins_api' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin-install.php'; } $response = plugins_api( 'plugin_information', array( 'slug' => $slug, 'fields' => array( 'sections' => false ) ) ); $api[ $slug ] = false; if ( is_wp_error( $response ) ) { wp_die( esc_html( $this->strings['oops'] ) ); } else { $api[ $slug ] = $response; } } return $api[ $slug ]; } /** * Retrieve a link to a plugin information page. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return string Fully formed html link to a plugin information page if available * or the plugin name if not. */ public function get_info_link( $slug ) { if ( ! empty( $this->plugins[ $slug ]['external_url'] ) && preg_match( self::IS_URL_REGEX, $this->plugins[ $slug ]['external_url'] ) ) { $link = sprintf( '<a href="%1$s" target="_blank">%2$s</a>', esc_url( $this->plugins[ $slug ]['external_url'] ), esc_html( $this->plugins[ $slug ]['name'] ) ); } elseif ( 'repo' === $this->plugins[ $slug ]['source_type'] ) { $url = add_query_arg( array( 'tab' => 'plugin-information', 'plugin' => urlencode( $slug ), 'TB_iframe' => 'true', 'width' => '640', 'height' => '500', ), self_admin_url( 'plugin-install.php' ) ); $link = sprintf( '<a href="%1$s" class="thickbox">%2$s</a>', esc_url( $url ), esc_html( $this->plugins[ $slug ]['name'] ) ); } else { $link = esc_html( $this->plugins[ $slug ]['name'] ); // No hyperlink. } return $link; } /** * Determine if we're on the TGMPA Install page. * * @since 2.1.0 * * @return boolean True when on the TGMPA page, false otherwise. */ protected function is_tgmpa_page() { return isset( $_GET['page'] ) && $this->menu === $_GET['page']; } /** * Retrieve the URL to the TGMPA Install page. * * I.e. depending on the config settings passed something along the lines of: * http://example.com/wp-admin/themes.php?page=tgmpa-install-plugins * * @since 2.5.0 * * @return string Properly encoded URL (not escaped). */ public function get_tgmpa_url() { static $url; if ( ! isset( $url ) ) { $parent = $this->parent_slug; if ( false === strpos( $parent, '.php' ) ) { $parent = 'admin.php'; } $url = add_query_arg( array( 'page' => urlencode( $this->menu ), ), self_admin_url( $parent ) ); } return $url; } /** * Retrieve the URL to the TGMPA Install page for a specific plugin status (view). * * I.e. depending on the config settings passed something along the lines of: * http://example.com/wp-admin/themes.php?page=tgmpa-install-plugins&plugin_status=install * * @since 2.5.0 * * @param string $status Plugin status - either 'install', 'update' or 'activate'. * @return string Properly encoded URL (not escaped). */ public function get_tgmpa_status_url( $status ) { return add_query_arg( array( 'plugin_status' => urlencode( $status ), ), $this->get_tgmpa_url() ); } /** * Determine whether there are open actions for plugins registered with TGMPA. * * @since 2.5.0 * * @return bool True if complete, i.e. no outstanding actions. False otherwise. */ public function is_tgmpa_complete() { $complete = true; foreach ( $this->plugins as $slug => $plugin ) { if ( ! $this->is_plugin_active( $slug ) || false !== $this->does_plugin_have_update( $slug ) ) { $complete = false; break; } } return $complete; } /** * Check if a plugin is installed. Does not take must-use plugins into account. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return bool True if installed, false otherwise. */ public function is_plugin_installed( $slug ) { $installed_plugins = $this->get_plugins(); // Retrieve a list of all installed plugins (WP cached). return ( ! empty( $installed_plugins[ $this->plugins[ $slug ]['file_path'] ] ) ); } /** * Check if a plugin is active. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return bool True if active, false otherwise. */ public function is_plugin_active( $slug ) { return ( ( ! empty( $this->plugins[ $slug ]['is_callable'] ) && is_callable( $this->plugins[ $slug ]['is_callable'] ) ) || is_plugin_active( $this->plugins[ $slug ]['file_path'] ) ); } /** * Check if a plugin can be updated, i.e. if we have information on the minimum WP version required * available, check whether the current install meets them. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return bool True if OK to update, false otherwise. */ public function can_plugin_update( $slug ) { // We currently can't get reliable info on non-WP-repo plugins - issue #380. if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) { return true; } $api = $this->get_plugins_api( $slug ); if ( false !== $api && isset( $api->requires ) ) { return version_compare( $GLOBALS['wp_version'], $api->requires, '>=' ); } // No usable info received from the plugins API, presume we can update. return true; } /** * Check if a plugin can be activated, i.e. is not currently active and meets the minimum * plugin version requirements set in TGMPA (if any). * * @since 2.5.0 * * @param string $slug Plugin slug. * @return bool True if OK to activate, false otherwise. */ public function can_plugin_activate( $slug ) { return ( ! $this->is_plugin_active( $slug ) && ! $this->does_plugin_require_update( $slug ) ); } /** * Retrieve the version number of an installed plugin. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return string Version number as string or an empty string if the plugin is not installed * or version unknown (plugins which don't comply with the plugin header standard). */ public function get_installed_version( $slug ) { $installed_plugins = $this->get_plugins(); // Retrieve a list of all installed plugins (WP cached). if ( ! empty( $installed_plugins[ $this->plugins[ $slug ]['file_path'] ]['Version'] ) ) { return $installed_plugins[ $this->plugins[ $slug ]['file_path'] ]['Version']; } return ''; } /** * Check whether a plugin complies with the minimum version requirements. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return bool True when a plugin needs to be updated, otherwise false. */ public function does_plugin_require_update( $slug ) { $installed_version = $this->get_installed_version( $slug ); $minimum_version = $this->plugins[ $slug ]['version']; return version_compare( $minimum_version, $installed_version, '>' ); } /** * Check whether there is an update available for a plugin. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return false|string Version number string of the available update or false if no update available. */ public function does_plugin_have_update( $slug ) { // Presume bundled and external plugins will point to a package which meets the minimum required version. if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) { if ( $this->does_plugin_require_update( $slug ) ) { return $this->plugins[ $slug ]['version']; } return false; } $repo_updates = get_site_transient( 'update_plugins' ); if ( isset( $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->new_version ) ) { return $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->new_version; } return false; } /** * Retrieve potential upgrade notice for a plugin. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return string The upgrade notice or an empty string if no message was available or provided. */ public function get_upgrade_notice( $slug ) { // We currently can't get reliable info on non-WP-repo plugins - issue #380. if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) { return ''; } $repo_updates = get_site_transient( 'update_plugins' ); if ( ! empty( $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->upgrade_notice ) ) { return $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->upgrade_notice; } return ''; } /** * Wrapper around the core WP get_plugins function, making sure it's actually available. * * @since 2.5.0 * * @param string $plugin_folder Optional. Relative path to single plugin folder. * @return array Array of installed plugins with plugin information. */ public function get_plugins( $plugin_folder = '' ) { if ( ! function_exists( 'get_plugins' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } return get_plugins( $plugin_folder ); } /** * Delete dismissable nag option when theme is switched. * * This ensures that the user(s) is/are again reminded via nag of required * and/or recommended plugins if they re-activate the theme. * * @since 2.1.1 */ public function update_dismiss() { delete_metadata( 'user', null, 'tgmpa_dismissed_notice_' . $this->id, null, true ); } /** * Forces plugin activation if the parameter 'force_activation' is * set to true. * * This allows theme authors to specify certain plugins that must be * active at all times while using the current theme. * * Please take special care when using this parameter as it has the * potential to be harmful if not used correctly. Setting this parameter * to true will not allow the specified plugin to be deactivated unless * the user switches themes. * * @since 2.2.0 */ public function force_activation() { foreach ( $this->plugins as $slug => $plugin ) { if ( true === $plugin['force_activation'] ) { if ( ! $this->is_plugin_installed( $slug ) ) { // Oops, plugin isn't there so iterate to next condition. continue; } elseif ( $this->can_plugin_activate( $slug ) ) { // There we go, activate the plugin. activate_plugin( $plugin['file_path'] ); } } } } /** * Forces plugin deactivation if the parameter 'force_deactivation' * is set to true. * * This allows theme authors to specify certain plugins that must be * deactivated upon switching from the current theme to another. * * Please take special care when using this parameter as it has the * potential to be harmful if not used correctly. * * @since 2.2.0 */ public function force_deactivation() { foreach ( $this->plugins as $slug => $plugin ) { // Only proceed forward if the parameter is set to true and plugin is active. if ( true === $plugin['force_deactivation'] && $this->is_plugin_active( $slug ) ) { deactivate_plugins( $plugin['file_path'] ); } } } /** * Echo the current TGMPA version number to the page. */ public function show_tgmpa_version() { echo '<p style="float: right; padding: 0em 1.5em 0.5em 0;"><strong><small>', esc_html( sprintf( _x( 'TGMPA v%s', '%s = version number', 'tgmpa' ), self::TGMPA_VERSION ) ), '</small></strong></p>'; } /** * Returns the singleton instance of the class. * * @since 2.4.0 * * @return object The TGM_Plugin_Activation object. */ public static function get_instance() { if ( ! isset( self::$instance ) && ! ( self::$instance instanceof self ) ) { self::$instance = new self(); } return self::$instance; } } if ( ! function_exists( 'load_tgm_plugin_activation' ) ) { /** * Ensure only one instance of the class is ever invoked. */ function load_tgm_plugin_activation() { $GLOBALS['tgmpa'] = TGM_Plugin_Activation::get_instance(); } } if ( did_action( 'plugins_loaded' ) ) { load_tgm_plugin_activation(); } else { add_action( 'plugins_loaded', 'load_tgm_plugin_activation' ); } } if ( ! function_exists( 'tgmpa' ) ) { /** * Helper function to register a collection of required plugins. * * @since 2.0.0 * @api * * @param array $plugins An array of plugin arrays. * @param array $config Optional. An array of configuration values. */ function tgmpa( $plugins, $config = array() ) { $instance = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) ); foreach ( $plugins as $plugin ) { call_user_func( array( $instance, 'register' ), $plugin ); } if ( ! empty( $config ) && is_array( $config ) ) { // Send out notices for deprecated arguments passed. if ( isset( $config['notices'] ) ) { _deprecated_argument( __FUNCTION__, '2.2.0', 'The `notices` config parameter was renamed to `has_notices` in TGMPA 2.2.0. Please adjust your configuration.' ); if ( ! isset( $config['has_notices'] ) ) { $config['has_notices'] = $config['notices']; } } if ( isset( $config['parent_menu_slug'] ) ) { _deprecated_argument( __FUNCTION__, '2.4.0', 'The `parent_menu_slug` config parameter was removed in TGMPA 2.4.0. In TGMPA 2.5.0 an alternative was (re-)introduced. Please adjust your configuration. For more information visit the website: http://tgmpluginactivation.com/configuration/#h-configuration-options.' ); } if ( isset( $config['parent_url_slug'] ) ) { _deprecated_argument( __FUNCTION__, '2.4.0', 'The `parent_url_slug` config parameter was removed in TGMPA 2.4.0. In TGMPA 2.5.0 an alternative was (re-)introduced. Please adjust your configuration. For more information visit the website: http://tgmpluginactivation.com/configuration/#h-configuration-options.' ); } call_user_func( array( $instance, 'config' ), $config ); } } } /** * WP_List_Table isn't always available. If it isn't available, * we load it here. * * @since 2.2.0 */ if ( ! class_exists( 'WP_List_Table' ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php'; } if ( ! class_exists( 'TGMPA_List_Table' ) ) { /** * List table class for handling plugins. * * Extends the WP_List_Table class to provide a future-compatible * way of listing out all required/recommended plugins. * * Gives users an interface similar to the Plugin Administration * area with similar (albeit stripped down) capabilities. * * This class also allows for the bulk install of plugins. * * @since 2.2.0 * * @package TGM-Plugin-Activation * @author Thomas Griffin * @author Gary Jones */ class TGMPA_List_Table extends WP_List_Table { /** * TGMPA instance. * * @since 2.5.0 * * @var object */ protected $tgmpa; /** * The currently chosen view. * * @since 2.5.0 * * @var string One of: 'all', 'install', 'update', 'activate' */ public $view_context = 'all'; /** * The plugin counts for the various views. * * @since 2.5.0 * * @var array */ protected $view_totals = array( 'all' => 0, 'install' => 0, 'update' => 0, 'activate' => 0, ); /** * References parent constructor and sets defaults for class. * * @since 2.2.0 */ public function __construct() { $this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) ); parent::__construct( array( 'singular' => 'plugin', 'plural' => 'plugins', 'ajax' => false, ) ); if ( isset( $_REQUEST['plugin_status'] ) && in_array( $_REQUEST['plugin_status'], array( 'install', 'update', 'activate' ), true ) ) { $this->view_context = sanitize_key( $_REQUEST['plugin_status'] ); } add_filter( 'tgmpa_table_data_items', array( $this, 'sort_table_items' ) ); } /** * Get a list of CSS classes for the <table> tag. * * Overruled to prevent the 'plural' argument from being added. * * @since 2.5.0 * * @return array CSS classnames. */ public function get_table_classes() { return array( 'widefat', 'fixed' ); } /** * Gathers and renames all of our plugin information to be used by WP_List_Table to create our table. * * @since 2.2.0 * * @return array $table_data Information for use in table. */ protected function _gather_plugin_data() { // Load thickbox for plugin links. $this->tgmpa->admin_init(); $this->tgmpa->thickbox(); // Categorize the plugins which have open actions. $plugins = $this->categorize_plugins_to_views(); // Set the counts for the view links. $this->set_view_totals( $plugins ); // Prep variables for use and grab list of all installed plugins. $table_data = array(); $i = 0; // Redirect to the 'all' view if no plugins were found for the selected view context. if ( empty( $plugins[ $this->view_context ] ) ) { $this->view_context = 'all'; } foreach ( $plugins[ $this->view_context ] as $slug => $plugin ) { $table_data[ $i ]['sanitized_plugin'] = $plugin['name']; $table_data[ $i ]['slug'] = $slug; $table_data[ $i ]['plugin'] = '<strong>' . $this->tgmpa->get_info_link( $slug ) . '</strong>'; $table_data[ $i ]['source'] = $this->get_plugin_source_type_text( $plugin['source_type'] ); $table_data[ $i ]['type'] = $this->get_plugin_advise_type_text( $plugin['required'] ); $table_data[ $i ]['status'] = $this->get_plugin_status_text( $slug ); $table_data[ $i ]['installed_version'] = $this->tgmpa->get_installed_version( $slug ); $table_data[ $i ]['minimum_version'] = $plugin['version']; $table_data[ $i ]['available_version'] = $this->tgmpa->does_plugin_have_update( $slug ); // Prep the upgrade notice info. $upgrade_notice = $this->tgmpa->get_upgrade_notice( $slug ); if ( ! empty( $upgrade_notice ) ) { $table_data[ $i ]['upgrade_notice'] = $upgrade_notice; add_action( "tgmpa_after_plugin_row_$slug", array( $this, 'wp_plugin_update_row' ), 10, 2 ); } $table_data[ $i ] = apply_filters( 'tgmpa_table_data_item', $table_data[ $i ], $plugin ); $i++; } return $table_data; } /** * Categorize the plugins which have open actions into views for the TGMPA page. * * @since 2.5.0 */ protected function categorize_plugins_to_views() { $plugins = array( 'all' => array(), // Meaning: all plugins which still have open actions. 'install' => array(), 'update' => array(), 'activate' => array(), ); foreach ( $this->tgmpa->plugins as $slug => $plugin ) { if ( $this->tgmpa->is_plugin_active( $slug ) && false === $this->tgmpa->does_plugin_have_update( $slug ) ) { // No need to display plugins if they are installed, up-to-date and active. continue; } else { $plugins['all'][ $slug ] = $plugin; if ( ! $this->tgmpa->is_plugin_installed( $slug ) ) { $plugins['install'][ $slug ] = $plugin; } else { if ( false !== $this->tgmpa->does_plugin_have_update( $slug ) ) { $plugins['update'][ $slug ] = $plugin; } if ( $this->tgmpa->can_plugin_activate( $slug ) ) { $plugins['activate'][ $slug ] = $plugin; } } } } return $plugins; } /** * Set the counts for the view links. * * @since 2.5.0 * * @param array $plugins Plugins order by view. */ protected function set_view_totals( $plugins ) { foreach ( $plugins as $type => $list ) { $this->view_totals[ $type ] = count( $list ); } } /** * Get the plugin required/recommended text string. * * @since 2.5.0 * * @param string $required Plugin required setting. * @return string */ protected function get_plugin_advise_type_text( $required ) { if ( true === $required ) { return __( 'Required', 'tgmpa' ); } return __( 'Recommended', 'tgmpa' ); } /** * Get the plugin source type text string. * * @since 2.5.0 * * @param string $type Plugin type. * @return string */ protected function get_plugin_source_type_text( $type ) { $string = ''; switch ( $type ) { case 'repo': $string = __( 'WordPress Repository', 'tgmpa' ); break; case 'external': $string = __( 'External Source', 'tgmpa' ); break; case 'bundled': $string = __( 'Pre-Packaged', 'tgmpa' ); break; } return $string; } /** * Determine the plugin status message. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return string */ protected function get_plugin_status_text( $slug ) { if ( ! $this->tgmpa->is_plugin_installed( $slug ) ) { return __( 'Not Installed', 'tgmpa' ); } if ( ! $this->tgmpa->is_plugin_active( $slug ) ) { $install_status = __( 'Installed But Not Activated', 'tgmpa' ); } else { $install_status = __( 'Active', 'tgmpa' ); } $update_status = ''; if ( $this->tgmpa->does_plugin_require_update( $slug ) && false === $this->tgmpa->does_plugin_have_update( $slug ) ) { $update_status = __( 'Required Update not Available', 'tgmpa' ); } elseif ( $this->tgmpa->does_plugin_require_update( $slug ) ) { $update_status = __( 'Requires Update', 'tgmpa' ); } elseif ( false !== $this->tgmpa->does_plugin_have_update( $slug ) ) { $update_status = __( 'Update recommended', 'tgmpa' ); } if ( '' === $update_status ) { return $install_status; } return sprintf( _x( '%1$s, %2$s', '%1$s = install status, %2$s = update status', 'tgmpa' ), $install_status, $update_status ); } /** * Sort plugins by Required/Recommended type and by alphabetical plugin name within each type. * * @since 2.5.0 * * @param array $items Prepared table items. * @return array Sorted table items. */ public function sort_table_items( $items ) { $type = array(); $name = array(); foreach ( $items as $i => $plugin ) { $type[ $i ] = $plugin['type']; // Required / recommended. $name[ $i ] = $plugin['sanitized_plugin']; } array_multisort( $type, SORT_DESC, $name, SORT_ASC, $items ); return $items; } /** * Get an associative array ( id => link ) of the views available on this table. * * @since 2.5.0 * * @return array */ public function get_views() { $status_links = array(); foreach ( $this->view_totals as $type => $count ) { if ( $count < 1 ) { continue; } switch ( $type ) { case 'all': $text = _nx( 'All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $count, 'plugins', 'tgmpa' ); break; case 'install': $text = _n( 'To Install <span class="count">(%s)</span>', 'To Install <span class="count">(%s)</span>', $count, 'tgmpa' ); break; case 'update': $text = _n( 'Update Available <span class="count">(%s)</span>', 'Update Available <span class="count">(%s)</span>', $count, 'tgmpa' ); break; case 'activate': $text = _n( 'To Activate <span class="count">(%s)</span>', 'To Activate <span class="count">(%s)</span>', $count, 'tgmpa' ); break; default: $text = ''; break; } if ( ! empty( $text ) ) { $status_links[ $type ] = sprintf( '<a href="%s"%s>%s</a>', esc_url( $this->tgmpa->get_tgmpa_status_url( $type ) ), ( $type === $this->view_context ) ? ' class="current"' : '', sprintf( $text, number_format_i18n( $count ) ) ); } } return $status_links; } /** * Create default columns to display important plugin information * like type, action and status. * * @since 2.2.0 * * @param array $item Array of item data. * @param string $column_name The name of the column. * @return string */ public function column_default( $item, $column_name ) { return $item[ $column_name ]; } /** * Required for bulk installing. * * Adds a checkbox for each plugin. * * @since 2.2.0 * * @param array $item Array of item data. * @return string The input checkbox with all necessary info. */ public function column_cb( $item ) { return sprintf( '<input type="checkbox" name="%1$s[]" value="%2$s" id="%3$s" />', esc_attr( $this->_args['singular'] ), esc_attr( $item['slug'] ), esc_attr( $item['sanitized_plugin'] ) ); } /** * Create default title column along with the action links. * * @since 2.2.0 * * @param array $item Array of item data. * @return string The plugin name and action links. */ public function column_plugin( $item ) { return sprintf( '%1$s %2$s', $item['plugin'], $this->row_actions( $this->get_row_actions( $item ), true ) ); } /** * Create version information column. * * @since 2.5.0 * * @param array $item Array of item data. * @return string HTML-formatted version information. */ public function column_version( $item ) { $output = array(); if ( $this->tgmpa->is_plugin_installed( $item['slug'] ) ) { $installed = ! empty( $item['installed_version'] ) ? $item['installed_version'] : _x( 'unknown', 'as in: "version nr unknown"', 'tgmpa' ); $color = ''; if ( ! empty( $item['minimum_version'] ) && $this->tgmpa->does_plugin_require_update( $item['slug'] ) ) { $color = ' color: #ff0000; font-weight: bold;'; } $output[] = sprintf( '<p><span style="min-width: 32px; text-align: right; float: right;%1$s">%2$s</span>' . __( 'Installed version:', 'tgmpa' ) . '</p>', $color, $installed ); } if ( ! empty( $item['minimum_version'] ) ) { $output[] = sprintf( '<p><span style="min-width: 32px; text-align: right; float: right;">%1$s</span>' . __( 'Minimum required version:', 'tgmpa' ) . '</p>', $item['minimum_version'] ); } if ( ! empty( $item['available_version'] ) ) { $color = ''; if ( ! empty( $item['minimum_version'] ) && version_compare( $item['available_version'], $item['minimum_version'], '>=' ) ) { $color = ' color: #71C671; font-weight: bold;'; } $output[] = sprintf( '<p><span style="min-width: 32px; text-align: right; float: right;%1$s">%2$s</span>' . __( 'Available version:', 'tgmpa' ) . '</p>', $color, $item['available_version'] ); } if ( empty( $output ) ) { return '&nbsp;'; // Let's not break the table layout. } else { return implode( "\n", $output ); } } /** * Sets default message within the plugins table if no plugins * are left for interaction. * * Hides the menu item to prevent the user from clicking and * getting a permissions error. * * @since 2.2.0 */ public function no_items() { printf( wp_kses_post( __( 'No plugins to install, update or activate. <a href="%1$s">Return to the Dashboard</a>', 'tgmpa' ) ), esc_url( self_admin_url() ) ); echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>'; } /** * Output all the column information within the table. * * @since 2.2.0 * * @return array $columns The column names. */ public function get_columns() { $columns = array( 'cb' => '<input type="checkbox" />', 'plugin' => __( 'Plugin', 'tgmpa' ), 'source' => __( 'Source', 'tgmpa' ), 'type' => __( 'Type', 'tgmpa' ), ); if ( 'all' === $this->view_context || 'update' === $this->view_context ) { $columns['version'] = __( 'Version', 'tgmpa' ); $columns['status'] = __( 'Status', 'tgmpa' ); } return apply_filters( 'tgmpa_table_columns', $columns ); } /** * Get name of default primary column * * @since 2.5.0 / WP 4.3+ compatibility * @access protected * * @return string */ protected function get_default_primary_column_name() { return 'plugin'; } /** * Get the name of the primary column. * * @since 2.5.0 / WP 4.3+ compatibility * @access protected * * @return string The name of the primary column. */ protected function get_primary_column_name() { if ( method_exists( 'WP_List_Table', 'get_primary_column_name' ) ) { return parent::get_primary_column_name(); } else { return $this->get_default_primary_column_name(); } } /** * Get the actions which are relevant for a specific plugin row. * * @since 2.5.0 * * @param array $item Array of item data. * @return array Array with relevant action links. */ protected function get_row_actions( $item ) { $actions = array(); $action_links = array(); // Display the 'Install' action link if the plugin is not yet available. if ( ! $this->tgmpa->is_plugin_installed( $item['slug'] ) ) { $actions['install'] = _x( 'Install %2$s', '%2$s = plugin name in screen reader markup', 'tgmpa' ); } else { // Display the 'Update' action link if an update is available and WP complies with plugin minimum. if ( false !== $this->tgmpa->does_plugin_have_update( $item['slug'] ) && $this->tgmpa->can_plugin_update( $item['slug'] ) ) { $actions['update'] = _x( 'Update %2$s', '%2$s = plugin name in screen reader markup', 'tgmpa' ); } // Display the 'Activate' action link, but only if the plugin meets the minimum version. if ( $this->tgmpa->can_plugin_activate( $item['slug'] ) ) { $actions['activate'] = _x( 'Activate %2$s', '%2$s = plugin name in screen reader markup', 'tgmpa' ); } } // Create the actual links. foreach ( $actions as $action => $text ) { $nonce_url = wp_nonce_url( add_query_arg( array( 'plugin' => urlencode( $item['slug'] ), 'tgmpa-' . $action => $action . '-plugin', ), $this->tgmpa->get_tgmpa_url() ), 'tgmpa-' . $action, 'tgmpa-nonce' ); $action_links[ $action ] = sprintf( '<a href="%1$s">' . esc_html( $text ) . '</a>', esc_url( $nonce_url ), '<span class="screen-reader-text">' . esc_html( $item['sanitized_plugin'] ) . '</span>' ); } $prefix = ( defined( 'WP_NETWORK_ADMIN' ) && WP_NETWORK_ADMIN ) ? 'network_admin_' : ''; return apply_filters( "tgmpa_{$prefix}plugin_action_links", array_filter( $action_links ), $item['slug'], $item, $this->view_context ); } /** * Generates content for a single row of the table. * * @since 2.5.0 * * @param object $item The current item. */ public function single_row( $item ) { parent::single_row( $item ); /** * Fires after each specific row in the TGMPA Plugins list table. * * The dynamic portion of the hook name, `$item['slug']`, refers to the slug * for the plugin. * * @since 2.5.0 */ do_action( "tgmpa_after_plugin_row_{$item['slug']}", $item['slug'], $item, $this->view_context ); } /** * Show the upgrade notice below a plugin row if there is one. * * @since 2.5.0 * * @see /wp-admin/includes/update.php * * @param string $slug Plugin slug. * @param array $item The information available in this table row. * @return null Return early if upgrade notice is empty. */ public function wp_plugin_update_row( $slug, $item ) { if ( empty( $item['upgrade_notice'] ) ) { return; } echo ' <tr class="plugin-update-tr"> <td colspan="', absint( $this->get_column_count() ), '" class="plugin-update colspanchange"> <div class="update-message">', esc_html__( 'Upgrade message from the plugin author:', 'tgmpa' ), ' <strong>', wp_kses_data( $item['upgrade_notice'] ), '</strong> </div> </td> </tr>'; } /** * Extra controls to be displayed between bulk actions and pagination. * * @since 2.5.0 * * @param string $which 'top' or 'bottom' table navigation. */ public function extra_tablenav( $which ) { if ( 'bottom' === $which ) { $this->tgmpa->show_tgmpa_version(); } } /** * Defines the bulk actions for handling registered plugins. * * @since 2.2.0 * * @return array $actions The bulk actions for the plugin install table. */ public function get_bulk_actions() { $actions = array(); if ( 'update' !== $this->view_context && 'activate' !== $this->view_context ) { if ( current_user_can( 'install_plugins' ) ) { $actions['tgmpa-bulk-install'] = __( 'Install', 'tgmpa' ); } } if ( 'install' !== $this->view_context ) { if ( current_user_can( 'update_plugins' ) ) { $actions['tgmpa-bulk-update'] = __( 'Update', 'tgmpa' ); } if ( current_user_can( 'activate_plugins' ) ) { $actions['tgmpa-bulk-activate'] = __( 'Activate', 'tgmpa' ); } } return $actions; } /** * Processes bulk installation and activation actions. * * The bulk installation process looks for the $_POST information and passes that * through if a user has to use WP_Filesystem to enter their credentials. * * @since 2.2.0 */ public function process_bulk_actions() { // Bulk installation process. if ( 'tgmpa-bulk-install' === $this->current_action() || 'tgmpa-bulk-update' === $this->current_action() ) { check_admin_referer( 'bulk-' . $this->_args['plural'] ); $install_type = 'install'; if ( 'tgmpa-bulk-update' === $this->current_action() ) { $install_type = 'update'; } $plugins_to_install = array(); // Did user actually select any plugins to install/update ? if ( empty( $_POST['plugin'] ) ) { if ( 'install' === $install_type ) { $message = __( 'No plugins were selected to be installed. No action taken.', 'tgmpa' ); } else { $message = __( 'No plugins were selected to be updated. No action taken.', 'tgmpa' ); } echo '<div id="message" class="error"><p>', esc_html( $message ), '</p></div>'; return false; } if ( is_array( $_POST['plugin'] ) ) { $plugins_to_install = (array) $_POST['plugin']; } elseif ( is_string( $_POST['plugin'] ) ) { // Received via Filesystem page - un-flatten array (WP bug #19643). $plugins_to_install = explode( ',', $_POST['plugin'] ); } // Sanitize the received input. $plugins_to_install = array_map( 'urldecode', $plugins_to_install ); $plugins_to_install = array_map( array( $this->tgmpa, 'sanitize_key' ), $plugins_to_install ); // Validate the received input. foreach ( $plugins_to_install as $key => $slug ) { // Check if the plugin was registered with TGMPA and remove if not. if ( ! isset( $this->tgmpa->plugins[ $slug ] ) ) { unset( $plugins_to_install[ $key ] ); continue; } // For updates: make sure this is a plugin we *can* update (update available and WP version ok). if ( 'update' === $install_type && ( $this->tgmpa->is_plugin_installed( $slug ) && ( false === $this->tgmpa->does_plugin_have_update( $slug ) || ! $this->tgmpa->can_plugin_update( $slug ) ) ) ) { unset( $plugins_to_install[ $key ] ); } } // No need to proceed further if we have no plugins to handle. if ( empty( $plugins_to_install ) ) { if ( 'install' === $install_type ) { $message = __( 'No plugins are available to be installed at this time.', 'tgmpa' ); } else { $message = __( 'No plugins are available to be updated at this time.', 'tgmpa' ); } echo '<div id="message" class="error"><p>', esc_html( $message ), '</p></div>'; return false; } // Pass all necessary information if WP_Filesystem is needed. $url = wp_nonce_url( $this->tgmpa->get_tgmpa_url(), 'bulk-' . $this->_args['plural'] ); // Give validated data back to $_POST which is the only place the filesystem looks for extra fields. $_POST['plugin'] = implode( ',', $plugins_to_install ); // Work around for WP bug #19643. $method = ''; // Leave blank so WP_Filesystem can populate it as necessary. $fields = array_keys( $_POST ); // Extra fields to pass to WP_Filesystem. if ( false === ( $creds = request_filesystem_credentials( esc_url_raw( $url ), $method, false, false, $fields ) ) ) { return true; // Stop the normal page form from displaying, credential request form will be shown. } // Now we have some credentials, setup WP_Filesystem. if ( ! WP_Filesystem( $creds ) ) { // Our credentials were no good, ask the user for them again. request_filesystem_credentials( esc_url_raw( $url ), $method, true, false, $fields ); return true; } /* If we arrive here, we have the filesystem */ // Store all information in arrays since we are processing a bulk installation. $names = array(); $sources = array(); // Needed for installs. $file_paths = array(); // Needed for upgrades. $to_inject = array(); // Information to inject into the update_plugins transient. // Prepare the data for validated plugins for the install/upgrade. foreach ( $plugins_to_install as $slug ) { $name = $this->tgmpa->plugins[ $slug ]['name']; $source = $this->tgmpa->get_download_url( $slug ); if ( ! empty( $name ) && ! empty( $source ) ) { $names[] = $name; switch ( $install_type ) { case 'install': $sources[] = $source; break; case 'update': $file_paths[] = $this->tgmpa->plugins[ $slug ]['file_path']; $to_inject[ $slug ] = $this->tgmpa->plugins[ $slug ]; $to_inject[ $slug ]['source'] = $source; break; } } } unset( $slug, $name, $source ); // Create a new instance of TGMPA_Bulk_Installer. $installer = new TGMPA_Bulk_Installer( new TGMPA_Bulk_Installer_Skin( array( 'url' => esc_url_raw( $this->tgmpa->get_tgmpa_url() ), 'nonce' => 'bulk-' . $this->_args['plural'], 'names' => $names, 'install_type' => $install_type, ) ) ); // Wrap the install process with the appropriate HTML. echo '<div class="tgmpa wrap">', '<h2>', esc_html( get_admin_page_title() ), '</h2>'; // Process the bulk installation submissions. add_filter( 'upgrader_source_selection', array( $this->tgmpa, 'maybe_adjust_source_dir' ), 1, 3 ); if ( 'tgmpa-bulk-update' === $this->current_action() ) { // Inject our info into the update transient. $this->tgmpa->inject_update_info( $to_inject ); $installer->bulk_upgrade( $file_paths ); } else { $installer->bulk_install( $sources ); } remove_filter( 'upgrader_source_selection', array( $this->tgmpa, 'maybe_adjust_source_dir' ), 1, 3 ); echo '</div>'; return true; } // Bulk activation process. if ( 'tgmpa-bulk-activate' === $this->current_action() ) { check_admin_referer( 'bulk-' . $this->_args['plural'] ); // Did user actually select any plugins to activate ? if ( empty( $_POST['plugin'] ) ) { echo '<div id="message" class="error"><p>', esc_html__( 'No plugins were selected to be activated. No action taken.', 'tgmpa' ), '</p></div>'; return false; } // Grab plugin data from $_POST. $plugins = array(); if ( isset( $_POST['plugin'] ) ) { $plugins = array_map( 'urldecode', (array) $_POST['plugin'] ); $plugins = array_map( array( $this->tgmpa, 'sanitize_key' ), $plugins ); } $plugins_to_activate = array(); $plugin_names = array(); // Grab the file paths for the selected & inactive plugins from the registration array. foreach ( $plugins as $slug ) { if ( $this->tgmpa->can_plugin_activate( $slug ) ) { $plugins_to_activate[] = $this->tgmpa->plugins[ $slug ]['file_path']; $plugin_names[] = $this->tgmpa->plugins[ $slug ]['name']; } } unset( $slug ); // Return early if there are no plugins to activate. if ( empty( $plugins_to_activate ) ) { echo '<div id="message" class="error"><p>', esc_html__( 'No plugins are available to be activated at this time.', 'tgmpa' ), '</p></div>'; return false; } // Now we are good to go - let's start activating plugins. $activate = activate_plugins( $plugins_to_activate ); if ( is_wp_error( $activate ) ) { echo '<div id="message" class="error"><p>', wp_kses_post( $activate->get_error_message() ), '</p></div>'; } else { $count = count( $plugin_names ); // Count so we can use _n function. $plugin_names = array_map( array( 'TGMPA_Utils', 'wrap_in_strong' ), $plugin_names ); $last_plugin = array_pop( $plugin_names ); // Pop off last name to prep for readability. $imploded = empty( $plugin_names ) ? $last_plugin : ( implode( ', ', $plugin_names ) . ' ' . esc_html_x( 'and', 'plugin A *and* plugin B', 'tgmpa' ) . ' ' . $last_plugin ); printf( // WPCS: xss ok. '<div id="message" class="updated"><p>%1$s %2$s.</p></div>', esc_html( _n( 'The following plugin was activated successfully:', 'The following plugins were activated successfully:', $count, 'tgmpa' ) ), $imploded ); // Update recently activated plugins option. $recent = (array) get_option( 'recently_activated' ); foreach ( $plugins_to_activate as $plugin => $time ) { if ( isset( $recent[ $plugin ] ) ) { unset( $recent[ $plugin ] ); } } update_option( 'recently_activated', $recent ); } unset( $_POST ); // Reset the $_POST variable in case user wants to perform one action after another. return true; } return false; } /** * Prepares all of our information to be outputted into a usable table. * * @since 2.2.0 */ public function prepare_items() { $columns = $this->get_columns(); // Get all necessary column information. $hidden = array(); // No columns to hide, but we must set as an array. $sortable = array(); // No reason to make sortable columns. $primary = $this->get_primary_column_name(); // Column which has the row actions. $this->_column_headers = array( $columns, $hidden, $sortable, $primary ); // Get all necessary column headers. // Process our bulk activations here. if ( 'tgmpa-bulk-activate' === $this->current_action() ) { $this->process_bulk_actions(); } // Store all of our plugin data into $items array so WP_List_Table can use it. $this->items = apply_filters( 'tgmpa_table_data_items', $this->_gather_plugin_data() ); } /* *********** DEPRECATED METHODS *********** */ /** * Retrieve plugin data, given the plugin name. * * @since 2.2.0 * @deprecated 2.5.0 use {@see TGM_Plugin_Activation::_get_plugin_data_from_name()} instead. * @see TGM_Plugin_Activation::_get_plugin_data_from_name() * * @param string $name Name of the plugin, as it was registered. * @param string $data Optional. Array key of plugin data to return. Default is slug. * @return string|boolean Plugin slug if found, false otherwise. */ protected function _get_plugin_data_from_name( $name, $data = 'slug' ) { _deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'TGM_Plugin_Activation::_get_plugin_data_from_name()' ); return $this->tgmpa->_get_plugin_data_from_name( $name, $data ); } } } if ( ! class_exists( 'TGM_Bulk_Installer' ) ) { /** * Hack: Prevent TGMPA v2.4.1- bulk installer class from being loaded if 2.4.1- is loaded after 2.5+. */ class TGM_Bulk_Installer { } } if ( ! class_exists( 'TGM_Bulk_Installer_Skin' ) ) { /** * Hack: Prevent TGMPA v2.4.1- bulk installer skin class from being loaded if 2.4.1- is loaded after 2.5+. */ class TGM_Bulk_Installer_Skin { } } /** * The WP_Upgrader file isn't always available. If it isn't available, * we load it here. * * We check to make sure no action or activation keys are set so that WordPress * does not try to re-include the class when processing upgrades or installs outside * of the class. * * @since 2.2.0 */ add_action( 'admin_init', 'tgmpa_load_bulk_installer' ); if ( ! function_exists( 'tgmpa_load_bulk_installer' ) ) { /** * Load bulk installer */ function tgmpa_load_bulk_installer() { // Silently fail if 2.5+ is loaded *after* an older version. if ( ! isset( $GLOBALS['tgmpa'] ) ) { return; } // Get TGMPA class instance. $tgmpa_instance = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) ); if ( isset( $_GET['page'] ) && $tgmpa_instance->menu === $_GET['page'] ) { if ( ! class_exists( 'Plugin_Upgrader', false ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; } if ( ! class_exists( 'TGMPA_Bulk_Installer' ) ) { /** * Installer class to handle bulk plugin installations. * * Extends WP_Upgrader and customizes to suit the installation of multiple * plugins. * * @since 2.2.0 * * @internal Since 2.5.0 the class is an extension of Plugin_Upgrader rather than WP_Upgrader * @internal Since 2.5.2 the class has been renamed from TGM_Bulk_Installer to TGMPA_Bulk_Installer. * This was done to prevent backward compatibility issues with v2.3.6. * * @package TGM-Plugin-Activation * @author Thomas Griffin * @author Gary Jones */ class TGMPA_Bulk_Installer extends Plugin_Upgrader { /** * Holds result of bulk plugin installation. * * @since 2.2.0 * * @var string */ public $result; /** * Flag to check if bulk installation is occurring or not. * * @since 2.2.0 * * @var boolean */ public $bulk = false; /** * TGMPA instance * * @since 2.5.0 * * @var object */ protected $tgmpa; /** * Whether or not the destination directory needs to be cleared ( = on update). * * @since 2.5.0 * * @var bool */ protected $clear_destination = false; /** * References parent constructor and sets defaults for class. * * @since 2.2.0 * * @param \Bulk_Upgrader_Skin|null $skin Installer skin. */ public function __construct( $skin = null ) { // Get TGMPA class instance. $this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) ); parent::__construct( $skin ); if ( isset( $this->skin->options['install_type'] ) && 'update' === $this->skin->options['install_type'] ) { $this->clear_destination = true; } if ( $this->tgmpa->is_automatic ) { $this->activate_strings(); } add_action( 'upgrader_process_complete', array( $this->tgmpa, 'populate_file_path' ) ); } /** * Sets the correct activation strings for the installer skin to use. * * @since 2.2.0 */ public function activate_strings() { $this->strings['activation_failed'] = __( 'Plugin activation failed.', 'tgmpa' ); $this->strings['activation_success'] = __( 'Plugin activated successfully.', 'tgmpa' ); } /** * Performs the actual installation of each plugin. * * @since 2.2.0 * * @see WP_Upgrader::run() * * @param array $options The installation config options. * @return null|array Return early if error, array of installation data on success. */ public function run( $options ) { $result = parent::run( $options ); // Reset the strings in case we changed one during automatic activation. if ( $this->tgmpa->is_automatic ) { if ( 'update' === $this->skin->options['install_type'] ) { $this->upgrade_strings(); } else { $this->install_strings(); } } return $result; } /** * Processes the bulk installation of plugins. * * @since 2.2.0 * * @internal This is basically a near identical copy of the WP Core Plugin_Upgrader::bulk_upgrade() * method, with minor adjustments to deal with new installs instead of upgrades. * For ease of future synchronizations, the adjustments are clearly commented, but no other * comments are added. Code style has been made to comply. * * @see Plugin_Upgrader::bulk_upgrade() * @see https://core.trac.wordpress.org/browser/tags/4.2.1/src/wp-admin/includes/class-wp-upgrader.php#L838 * * @param array $plugins The plugin sources needed for installation. * @param array $args Arbitrary passed extra arguments. * @return string|bool Install confirmation messages on success, false on failure. */ public function bulk_install( $plugins, $args = array() ) { // [TGMPA + ] Hook auto-activation in. add_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 ); $defaults = array( 'clear_update_cache' => true, ); $parsed_args = wp_parse_args( $args, $defaults ); $this->init(); $this->bulk = true; $this->install_strings(); // [TGMPA + ] adjusted. /* [TGMPA - ] $current = get_site_transient( 'update_plugins' ); */ /* [TGMPA - ] add_filter('upgrader_clear_destination', array($this, 'delete_old_plugin'), 10, 4); */ $this->skin->header(); // Connect to the Filesystem first. $res = $this->fs_connect( array( WP_CONTENT_DIR, WP_PLUGIN_DIR ) ); if ( ! $res ) { $this->skin->footer(); return false; } $this->skin->bulk_header(); // Only start maintenance mode if: // - running Multisite and there are one or more plugins specified, OR // - a plugin with an update available is currently active. // @TODO: For multisite, maintenance mode should only kick in for individual sites if at all possible. $maintenance = ( is_multisite() && ! empty( $plugins ) ); /* [TGMPA - ] foreach ( $plugins as $plugin ) $maintenance = $maintenance || ( is_plugin_active( $plugin ) && isset( $current->response[ $plugin] ) ); */ if ( $maintenance ) { $this->maintenance_mode( true ); } $results = array(); $this->update_count = count( $plugins ); $this->update_current = 0; foreach ( $plugins as $plugin ) { $this->update_current++; /* [TGMPA - ] $this->skin->plugin_info = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin, false, true); if ( !isset( $current->response[ $plugin ] ) ) { $this->skin->set_result('up_to_date'); $this->skin->before(); $this->skin->feedback('up_to_date'); $this->skin->after(); $results[$plugin] = true; continue; } // Get the URL to the zip file $r = $current->response[ $plugin ]; $this->skin->plugin_active = is_plugin_active($plugin); */ $result = $this->run( array( 'package' => $plugin, // [TGMPA + ] adjusted. 'destination' => WP_PLUGIN_DIR, 'clear_destination' => false, // [TGMPA + ] adjusted. 'clear_working' => true, 'is_multi' => true, 'hook_extra' => array( 'plugin' => $plugin, ), ) ); $results[ $plugin ] = $this->result; // Prevent credentials auth screen from displaying multiple times. if ( false === $result ) { break; } } //end foreach $plugins $this->maintenance_mode( false ); /** * Fires when the bulk upgrader process is complete. * * @since WP 3.6.0 / TGMPA 2.5.0 * * @param Plugin_Upgrader $this Plugin_Upgrader instance. In other contexts, $this, might * be a Theme_Upgrader or Core_Upgrade instance. * @param array $data { * Array of bulk item update data. * * @type string $action Type of action. Default 'update'. * @type string $type Type of update process. Accepts 'plugin', 'theme', or 'core'. * @type bool $bulk Whether the update process is a bulk update. Default true. * @type array $packages Array of plugin, theme, or core packages to update. * } */ do_action( 'upgrader_process_complete', $this, array( 'action' => 'install', // [TGMPA + ] adjusted. 'type' => 'plugin', 'bulk' => true, 'plugins' => $plugins, ) ); $this->skin->bulk_footer(); $this->skin->footer(); // Cleanup our hooks, in case something else does a upgrade on this connection. /* [TGMPA - ] remove_filter('upgrader_clear_destination', array($this, 'delete_old_plugin')); */ // [TGMPA + ] Remove our auto-activation hook. remove_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 ); // Force refresh of plugin update information. wp_clean_plugins_cache( $parsed_args['clear_update_cache'] ); return $results; } /** * Handle a bulk upgrade request. * * @since 2.5.0 * * @see Plugin_Upgrader::bulk_upgrade() * * @param array $plugins The local WP file_path's of the plugins which should be upgraded. * @param array $args Arbitrary passed extra arguments. * @return string|bool Install confirmation messages on success, false on failure. */ public function bulk_upgrade( $plugins, $args = array() ) { add_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 ); $result = parent::bulk_upgrade( $plugins, $args ); remove_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 ); return $result; } /** * Abuse a filter to auto-activate plugins after installation. * * Hooked into the 'upgrader_post_install' filter hook. * * @since 2.5.0 * * @param bool $bool The value we need to give back (true). * @return bool */ public function auto_activate( $bool ) { // Only process the activation of installed plugins if the automatic flag is set to true. if ( $this->tgmpa->is_automatic ) { // Flush plugins cache so the headers of the newly installed plugins will be read correctly. wp_clean_plugins_cache(); // Get the installed plugin file. $plugin_info = $this->plugin_info(); // Don't try to activate on upgrade of active plugin as WP will do this already. if ( ! is_plugin_active( $plugin_info ) ) { $activate = activate_plugin( $plugin_info ); // Adjust the success string based on the activation result. $this->strings['process_success'] = $this->strings['process_success'] . "<br />\n"; if ( is_wp_error( $activate ) ) { $this->skin->error( $activate ); $this->strings['process_success'] .= $this->strings['activation_failed']; } else { $this->strings['process_success'] .= $this->strings['activation_success']; } } } return $bool; } } } if ( ! class_exists( 'TGMPA_Bulk_Installer_Skin' ) ) { /** * Installer skin to set strings for the bulk plugin installations.. * * Extends Bulk_Upgrader_Skin and customizes to suit the installation of multiple * plugins. * * @since 2.2.0 * * @internal Since 2.5.2 the class has been renamed from TGM_Bulk_Installer_Skin to * TGMPA_Bulk_Installer_Skin. * This was done to prevent backward compatibility issues with v2.3.6. * * @see https://core.trac.wordpress.org/browser/trunk/src/wp-admin/includes/class-wp-upgrader-skins.php * * @package TGM-Plugin-Activation * @author Thomas Griffin * @author Gary Jones */ class TGMPA_Bulk_Installer_Skin extends Bulk_Upgrader_Skin { /** * Holds plugin info for each individual plugin installation. * * @since 2.2.0 * * @var array */ public $plugin_info = array(); /** * Holds names of plugins that are undergoing bulk installations. * * @since 2.2.0 * * @var array */ public $plugin_names = array(); /** * Integer to use for iteration through each plugin installation. * * @since 2.2.0 * * @var integer */ public $i = 0; /** * TGMPA instance * * @since 2.5.0 * * @var object */ protected $tgmpa; /** * Constructor. Parses default args with new ones and extracts them for use. * * @since 2.2.0 * * @param array $args Arguments to pass for use within the class. */ public function __construct( $args = array() ) { // Get TGMPA class instance. $this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) ); // Parse default and new args. $defaults = array( 'url' => '', 'nonce' => '', 'names' => array(), 'install_type' => 'install', ); $args = wp_parse_args( $args, $defaults ); // Set plugin names to $this->plugin_names property. $this->plugin_names = $args['names']; // Extract the new args. parent::__construct( $args ); } /** * Sets install skin strings for each individual plugin. * * Checks to see if the automatic activation flag is set and uses the * the proper strings accordingly. * * @since 2.2.0 */ public function add_strings() { if ( 'update' === $this->options['install_type'] ) { parent::add_strings(); $this->upgrader->strings['skin_before_update_header'] = __( 'Updating Plugin %1$s (%2$d/%3$d)', 'tgmpa' ); } else { $this->upgrader->strings['skin_update_failed_error'] = __( 'An error occurred while installing %1$s: <strong>%2$s</strong>.', 'tgmpa' ); $this->upgrader->strings['skin_update_failed'] = __( 'The installation of %1$s failed.', 'tgmpa' ); if ( $this->tgmpa->is_automatic ) { // Automatic activation strings. $this->upgrader->strings['skin_upgrade_start'] = __( 'The installation and activation process is starting. This process may take a while on some hosts, so please be patient.', 'tgmpa' ); $this->upgrader->strings['skin_update_successful'] = __( '%1$s installed and activated successfully.', 'tgmpa' ) . ' <a href="#" class="hide-if-no-js" onclick="%2$s"><span>' . esc_html__( 'Show Details', 'tgmpa' ) . '</span><span class="hidden">' . esc_html__( 'Hide Details', 'tgmpa' ) . '</span>.</a>'; $this->upgrader->strings['skin_upgrade_end'] = __( 'All installations and activations have been completed.', 'tgmpa' ); $this->upgrader->strings['skin_before_update_header'] = __( 'Installing and Activating Plugin %1$s (%2$d/%3$d)', 'tgmpa' ); } else { // Default installation strings. $this->upgrader->strings['skin_upgrade_start'] = __( 'The installation process is starting. This process may take a while on some hosts, so please be patient.', 'tgmpa' ); $this->upgrader->strings['skin_update_successful'] = esc_html__( '%1$s installed successfully.', 'tgmpa' ) . ' <a href="#" class="hide-if-no-js" onclick="%2$s"><span>' . esc_html__( 'Show Details', 'tgmpa' ) . '</span><span class="hidden">' . esc_html__( 'Hide Details', 'tgmpa' ) . '</span>.</a>'; $this->upgrader->strings['skin_upgrade_end'] = __( 'All installations have been completed.', 'tgmpa' ); $this->upgrader->strings['skin_before_update_header'] = __( 'Installing Plugin %1$s (%2$d/%3$d)', 'tgmpa' ); } } } /** * Outputs the header strings and necessary JS before each plugin installation. * * @since 2.2.0 * * @param string $title Unused in this implementation. */ public function before( $title = '' ) { if ( empty( $title ) ) { $title = esc_html( $this->plugin_names[ $this->i ] ); } parent::before( $title ); } /** * Outputs the footer strings and necessary JS after each plugin installation. * * Checks for any errors and outputs them if they exist, else output * success strings. * * @since 2.2.0 * * @param string $title Unused in this implementation. */ public function after( $title = '' ) { if ( empty( $title ) ) { $title = esc_html( $this->plugin_names[ $this->i ] ); } parent::after( $title ); $this->i++; } /** * Outputs links after bulk plugin installation is complete. * * @since 2.2.0 */ public function bulk_footer() { // Serve up the string to say installations (and possibly activations) are complete. parent::bulk_footer(); // Flush plugins cache so we can make sure that the installed plugins list is always up to date. wp_clean_plugins_cache(); $this->tgmpa->show_tgmpa_version(); // Display message based on if all plugins are now active or not. $update_actions = array(); if ( $this->tgmpa->is_tgmpa_complete() ) { // All plugins are active, so we display the complete string and hide the menu to protect users. echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>'; $update_actions['dashboard'] = sprintf( esc_html( $this->tgmpa->strings['complete'] ), '<a href="' . esc_url( self_admin_url() ) . '">' . esc_html__( 'Return to the Dashboard', 'tgmpa' ) . '</a>' ); } else { $update_actions['tgmpa_page'] = '<a href="' . esc_url( $this->tgmpa->get_tgmpa_url() ) . '" target="_parent">' . esc_html( $this->tgmpa->strings['return'] ) . '</a>'; } /** * Filter the list of action links available following bulk plugin installs/updates. * * @since 2.5.0 * * @param array $update_actions Array of plugin action links. * @param array $plugin_info Array of information for the last-handled plugin. */ $update_actions = apply_filters( 'tgmpa_update_bulk_plugins_complete_actions', $update_actions, $this->plugin_info ); if ( ! empty( $update_actions ) ) { $this->feedback( implode( ' | ', (array) $update_actions ) ); } } /* *********** DEPRECATED METHODS *********** */ /** * Flush header output buffer. * * @since 2.2.0 * @deprecated 2.5.0 use {@see Bulk_Upgrader_Skin::flush_output()} instead * @see Bulk_Upgrader_Skin::flush_output() */ public function before_flush_output() { _deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'Bulk_Upgrader_Skin::flush_output()' ); $this->flush_output(); } /** * Flush footer output buffer and iterate $this->i to make sure the * installation strings reference the correct plugin. * * @since 2.2.0 * @deprecated 2.5.0 use {@see Bulk_Upgrader_Skin::flush_output()} instead * @see Bulk_Upgrader_Skin::flush_output() */ public function after_flush_output() { _deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'Bulk_Upgrader_Skin::flush_output()' ); $this->flush_output(); $this->i++; } } } } } } if ( ! class_exists( 'TGMPA_Utils' ) ) { /** * Generic utilities for TGMPA. * * All methods are static, poor-dev name-spacing class wrapper. * * Class was called TGM_Utils in 2.5.0 but renamed TGMPA_Utils in 2.5.1 as this was conflicting with Soliloquy. * * @since 2.5.0 * * @package TGM-Plugin-Activation * @author Juliette Reinders Folmer */ class TGMPA_Utils { /** * Whether the PHP filter extension is enabled. * * @see http://php.net/book.filter * * @since 2.5.0 * * @static * * @var bool $has_filters True is the extension is enabled. */ public static $has_filters; /** * Wrap an arbitrary string in <em> tags. Meant to be used in combination with array_map(). * * @since 2.5.0 * * @static * * @param string $string Text to be wrapped. * @return string */ public static function wrap_in_em( $string ) { return '<em>' . wp_kses_post( $string ) . '</em>'; } /** * Wrap an arbitrary string in <strong> tags. Meant to be used in combination with array_map(). * * @since 2.5.0 * * @static * * @param string $string Text to be wrapped. * @return string */ public static function wrap_in_strong( $string ) { return '<strong>' . wp_kses_post( $string ) . '</strong>'; } /** * Helper function: Validate a value as boolean * * @since 2.5.0 * * @static * * @param mixed $value Arbitrary value. * @return bool */ public static function validate_bool( $value ) { if ( ! isset( self::$has_filters ) ) { self::$has_filters = extension_loaded( 'filter' ); } if ( self::$has_filters ) { return filter_var( $value, FILTER_VALIDATE_BOOLEAN ); } else { return self::emulate_filter_bool( $value ); } } /** * Helper function: Cast a value to bool * * @since 2.5.0 * * @static * * @param mixed $value Value to cast. * @return bool */ protected static function emulate_filter_bool( $value ) { // @codingStandardsIgnoreStart static $true = array( '1', 'true', 'True', 'TRUE', 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', ); static $false = array( '0', 'false', 'False', 'FALSE', 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF', ); // @codingStandardsIgnoreEnd if ( is_bool( $value ) ) { return $value; } else if ( is_int( $value ) && ( 0 === $value || 1 === $value ) ) { return (bool) $value; } else if ( ( is_float( $value ) && ! is_nan( $value ) ) && ( (float) 0 === $value || (float) 1 === $value ) ) { return (bool) $value; } else if ( is_string( $value ) ) { $value = trim( $value ); if ( in_array( $value, $true, true ) ) { return true; } else if ( in_array( $value, $false, true ) ) { return false; } else { return false; } } return false; } } // End of class TGMPA_Utils } // End of class_exists wrapper
idealseed123/idealseed
wp-content/themes/capitalx/includes/class-tgm-plugin-activation.php
PHP
gpl-2.0
117,889
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein * is confidential and proprietary to MediaTek Inc. and/or its licensors. * Without the prior written permission of MediaTek inc. and/or its licensors, * any reproduction, modification, use or disclosure of MediaTek Software, * and information contained herein, in whole or in part, shall be strictly prohibited. */ /* MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek Software") * have been modified by MediaTek Inc. All revisions are subject to any receiver's * applicable license agreements with MediaTek Inc. */ /* mmc328x.c - mmc328x compass driver * * * 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. * */ #include <linux/interrupt.h> #include <linux/i2c.h> #include <linux/slab.h> #include <linux/irq.h> #include <linux/miscdevice.h> #include <asm/uaccess.h> #include <asm/atomic.h> #include <linux/delay.h> #include <linux/input.h> #include <linux/workqueue.h> #include <linux/kobject.h> #include <linux/platform_device.h> #include <linux/earlysuspend.h> #include <linux/time.h> #include <linux/hrtimer.h> //#ifdef MT6573 //#include <mach/mt6573_devs.h> //#include <mach/mt6573_typedefs.h> //#include <mach/mt6573_gpio.h> //#include <mach/mt6573_pll.h> //#endif //#ifdef MT6575 //#include <mach/mt6575_devs.h> //#include <mach/mt6575_typedefs.h> //#include <mach/mt6575_gpio.h> //#include <mach/mt6575_pm_ldo.h> //#endif //#ifdef MT6577 //#include <mach/mt_devs.h> #include <mach/mt_typedefs.h> #include <mach/mt_gpio.h> #include <mach/mt_pm_ldo.h> //#endif #include <linux/hwmsensor.h> #include <linux/hwmsen_dev.h> #include <linux/sensors_io.h> #include <cust_mag.h> #include "mmc328xma_auto.h" #include <linux/hwmsen_helper.h> /*----------------------------------------------------------------------------*/ #define DEBUG 1 #define MMC328x_DEV_NAME "mmc328x" #define DRIVER_VERSION "1.0.0" /*----------------------------------------------------------------------------*/ #define MMC328x_DEBUG 1 #define MMC328x_DEBUG_MSG 1 #define MMC328x_DEBUG_FUNC 1 #define MMC328x_DEBUG_DATA 1 #define MAX_FAILURE_COUNT 3 #define MMC328x_RETRY_COUNT 10 #define MMC328x_DEFAULT_DELAY 100 #define MMC328x_BUFSIZE 0x20 #define MMC328X_DELAY_RM 10 /* ms */ #if MMC328x_DEBUG_MSG #define MMCDBG(format, ...) printk(KERN_INFO "mmc328x " format "\n", ## __VA_ARGS__) #else #define MMCDBG(format, ...) #endif #if MMC328x_DEBUG_FUNC #define MMCFUNC(func) printk(KERN_INFO "mmc328x " func " is called\n") #else #define MMCFUNC(func) #endif static struct i2c_client *this_client = NULL; // calibration msensor and orientation data static int sensor_data[CALIBRATION_DATA_SIZE]; static struct mutex sensor_data_mutex; static struct mutex read_i2c_xyz; static DECLARE_WAIT_QUEUE_HEAD(data_ready_wq); static DECLARE_WAIT_QUEUE_HEAD(open_wq); static int mmcd_delay = MMC328x_DEFAULT_DELAY; static atomic_t open_flag = ATOMIC_INIT(0); static atomic_t m_flag = ATOMIC_INIT(0); static atomic_t o_flag = ATOMIC_INIT(0); /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ static const struct i2c_device_id mmc328x_i2c_id[] = {{MMC328x_DEV_NAME,0},{}}; /*the adapter id will be available in customization*/ static struct i2c_board_info __initdata i2c_mmc328x={ I2C_BOARD_INFO("mmc328x", (0x60>>1))}; //static unsigned short mmc328x_force[] = {0x00, MMC328x_I2C_ADDR, I2C_CLIENT_END, I2C_CLIENT_END}; //static const unsigned short *const mmc328x_forces[] = { mmc328x_force, NULL }; //static struct i2c_client_address_data mmc328x_addr_data = { .forces = mmc328x_forces,}; /*----------------------------------------------------------------------------*/ static int mmc328x_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id); static int mmc328x_i2c_remove(struct i2c_client *client); static int mmc328x_i2c_detect(struct i2c_client *client, int kind, struct i2c_board_info *info); //static int mmc_probe(struct platform_device *pdev); //static int mmc_remove(struct platform_device *pdev); static int mmc328x_local_init(void); static int mmc328x_remove(void); static int mmc328x_init_flag =0; // 0<==>OK -1 <==> fail /*----------------------------------------------------------------------------*/ typedef enum { MMC_FUN_DEBUG = 0x01, MMC_DATA_DEBUG = 0X02, MMC_HWM_DEBUG = 0X04, MMC_CTR_DEBUG = 0X08, MMC_I2C_DEBUG = 0x10, } MMC_TRC; #define MMC328x_DELAY_TM 10 /* ms */ #define MMC328x_DELAY_SET 10 /* ms */ #define MMC328x_DELAY_RST 10 /* ms */ #define MMC328x_DELAY_STDN 1 /* ms */ #define MMC328x_RESET_INTV 10 static u32 read_idx = 0; static struct sensor_init_info mmc328x_init_info = { .name = "mmc328x", .init = mmc328x_local_init, .uninit = mmc328x_remove, }; /*----------------------------------------------------------------------------*/ struct mmc328x_i2c_data { struct i2c_client *client; struct mag_hw *hw; atomic_t layout; atomic_t trace; struct hwmsen_convert cvt; #if defined(CONFIG_HAS_EARLYSUSPEND) struct early_suspend early_drv; #endif }; /*----------------------------------------------------------------------------*/ static struct i2c_driver mmc328x_i2c_driver = { .driver = { // .owner = THIS_MODULE, .name = MMC328x_DEV_NAME, }, .probe = mmc328x_i2c_probe, .remove = mmc328x_i2c_remove, //.detect = mmc328x_i2c_detect, #if !defined(CONFIG_HAS_EARLYSUSPEND) .suspend = mmc328x_suspend, .resume = mmc328x_resume, #endif .id_table = mmc328x_i2c_id, //.address_data = &mmc328x_addr_data, }; /*----------------------------------------------------------------------------*/ static atomic_t dev_open_count; static int mmc328x_SetPowerMode(struct i2c_client *client, bool enable) { u8 databuf[2]; int res = 0; u8 addr = MMC328x_REG_CTRL; struct mmc328x_i2c_data *obj = i2c_get_clientdata(client); if(hwmsen_read_byte(client, addr, databuf)) { printk("mmc328x: read power ctl register err and retry!\n"); if(hwmsen_read_byte(client, addr, databuf)) { printk("mmc328x: read power ctl register retry err!\n"); return -1; } } databuf[0] &= ~MMC328x_CTRL_TM; if(enable == TRUE) { databuf[0] |= MMC328x_CTRL_TM; } else { // do nothing } databuf[1] = databuf[0]; databuf[0] = MMC328x_REG_CTRL; res = i2c_master_send(client, databuf, 0x2); if(res <= 0) { printk("mmc328x: set power mode failed!\n"); return -1; } else { printk("mmc328x: set power mode ok %x!\n", databuf[1]); } return 0; } /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ static void mmc328x_power(struct mag_hw *hw, unsigned int on) { static unsigned int power_on = 0; if(hw->power_id != MT65XX_POWER_NONE) { MMCDBG("power %s\n", on ? "on" : "off"); if(power_on == on) { MMCDBG("ignore power control: %d\n", on); } else if(on) { if(!hwPowerOn(hw->power_id, hw->power_vol, "mmc328x")) { printk(KERN_ERR "power on fails!!\n"); } } else { if(!hwPowerDown(hw->power_id, "mmc328x")) { printk(KERN_ERR "power off fail!!\n"); } } } power_on = on; } static int I2C_RxData(char *rxData, int length) { uint8_t loop_i; #if DEBUG int i; struct i2c_client *client = this_client; struct mmc328x_i2c_data *data = i2c_get_clientdata(client); char addr = rxData[0]; #endif /* Caller should check parameter validity.*/ if((rxData == NULL) || (length < 1)) { return -EINVAL; } for(loop_i = 0; loop_i < MMC328x_RETRY_COUNT; loop_i++) { this_client->addr = this_client->addr & I2C_MASK_FLAG | I2C_WR_FLAG; if(i2c_master_send(this_client, (const char*)rxData, ((length<<0X08) | 0X01))) { break; } printk("I2C_RxData delay!\n"); mdelay(10); } if(loop_i >= MMC328x_RETRY_COUNT) { printk(KERN_ERR "%s retry over %d\n", __func__, MMC328x_RETRY_COUNT); return -EIO; } #if DEBUG if(atomic_read(&data->trace) & MMC_I2C_DEBUG) { printk(KERN_INFO "RxData: len=%02x, addr=%02x\n data=", length, addr); for(i = 0; i < length; i++) { printk(KERN_INFO " %02x", rxData[i]); } printk(KERN_INFO "\n"); } #endif return 0; } static int I2C_TxData(char *txData, int length) { uint8_t loop_i; #if DEBUG int i; struct i2c_client *client = this_client; struct mmc328x_i2c_data *data = i2c_get_clientdata(client); #endif /* Caller should check parameter validity.*/ if ((txData == NULL) || (length < 2)) { return -EINVAL; } this_client->addr = this_client->addr & I2C_MASK_FLAG; for(loop_i = 0; loop_i < MMC328x_RETRY_COUNT; loop_i++) { if(i2c_master_send(this_client, (const char*)txData, length) > 0) { break; } printk("I2C_TxData delay!\n"); mdelay(10); } if(loop_i >= MMC328x_RETRY_COUNT) { printk(KERN_ERR "%s retry over %d\n", __func__, MMC328x_RETRY_COUNT); return -EIO; } #if DEBUG if(atomic_read(&data->trace) & MMC_I2C_DEBUG) { printk(KERN_INFO "TxData: len=%02x, addr=%02x\n data=", length, txData[0]); for(i = 0; i < (length-1); i++) { printk(KERN_INFO " %02x", txData[i + 1]); } printk(KERN_INFO "\n"); } #endif return 0; } // Daemon application save the data static int ECS_SaveData(int buf[12]) { #if DEBUG struct i2c_client *client = this_client; struct mmc328x_i2c_data *data = i2c_get_clientdata(client); #endif mutex_lock(&sensor_data_mutex); memcpy(sensor_data, buf, sizeof(sensor_data)); mutex_unlock(&sensor_data_mutex); #if DEBUG if(atomic_read(&data->trace) & MMC_HWM_DEBUG) { MMCDBG("Get daemon data: %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d!\n", sensor_data[0],sensor_data[1],sensor_data[2],sensor_data[3], sensor_data[4],sensor_data[5],sensor_data[6],sensor_data[7], sensor_data[8],sensor_data[9],sensor_data[10],sensor_data[11]); } #endif return 0; } static int ECS_ReadXYZData(int *vec, int size) { unsigned char data[6] = {0,0,0,0,0,0}; ktime_t expires; int wait_n=0; int MD_times = 0; static int last_data[3]; struct timespec time1, time2, time3,time4,delay,aa; #if DEBUG struct i2c_client *client = this_client; struct mmc328x_i2c_data *clientdata = i2c_get_clientdata(client); #endif //set_current_state(TASK_INTERRUPTIBLE); time1 = current_kernel_time(); if(size < 3) { return -1; } mutex_lock(&read_i2c_xyz); #if 0 /* do RESET/SET every MMC328x_RESET_INTV times read */ if (!(read_idx % MMC328x_RESET_INTV)) { /* SET */ data[0] = MMC328x_REG_CTRL; data[1] = MMC328x_CTRL_SET; /* not check return value here, assume it always OK */ I2C_TxData(data, 2); //delay.tv_sec =0; //delay.tv_nsec = MMC328x_DELAY_STDN *1000; //hrtimer_nanosleep(&delay, &aa, HRTIMER_MODE_REL, CLOCK_MONOTONIC); msleep(MMC328x_DELAY_STDN); } /* wait TM done for coming data read */ // time2 = current_kernel_time(); time3 = current_kernel_time(); /* read xyz raw data */ read_idx++; data[0] = MMC328x_REG_DATA; if(I2C_RxData(data, 6) < 0) { mutex_unlock(&read_i2c_xyz); return -EFAULT; } vec[0] = data[0] << 8 | data[1]; vec[1] = data[2] << 8 | data[3]; vec[2] = data[4] << 8 | data[5]; for(wait_n=0; wait_n<10; wait_n++) { if((vec[0]!=0) && (vec[1]!=0)&&(vec[2]!=0)) break; data[0] = MMC328x_REG_DATA; if(I2C_RxData(data, 6) < 0) { mutex_unlock(&read_i2c_xyz); return -EFAULT; } vec[0] = data[0] << 8 | data[1]; vec[1] = data[2] << 8 | data[3]; vec[2] = data[4] << 8 | data[5]; } time4 = current_kernel_time(); // printk("start time %d - %d, sleep %d - %d , stop %d !\r\n", time1.tv_sec, time1.tv_nsec, time2.tv_nsec, time3.tv_nsec, time4.tv_nsec); #if DEBUG if(atomic_read(&clientdata->trace) & MMC_DATA_DEBUG) { printk("[X - %04x] [Y - %04x] [Z - %04x]\r\n", vec[0], vec[1], vec[2]); if((vec[0]-last_data[0] > 100) ||(last_data[0]-vec[0] > 100) || (vec[1]-last_data[1] > 100) ||(last_data[1]-vec[1] > 100) || (vec[2]-last_data[2] > 100) ||(last_data[2]-vec[2] > 100)) { msleep(3000); printk("data error!\r\n"); }} #endif /* send TM cmd before read */ data[0] = MMC328x_REG_CTRL; data[1] = MMC328x_CTRL_TM; /* not check return value here, assume it always OK */ I2C_TxData(data, 2); #endif time2 = current_kernel_time(); if (!(read_idx % MMC328x_RESET_INTV)) { /* RM */ data[0] = MMC328x_REG_CTRL; data[1] = MMC328x_CTRL_RM; /* not check return value here, assume it always OK */ I2C_TxData(data, 2); /* wait external capacitor charging done for next RM */ msleep(MMC328X_DELAY_RM); } time3 = current_kernel_time(); /* send TM cmd before read */ data[0] = MMC328x_REG_CTRL; data[1] = MMC328x_CTRL_TM; /* not check return value here, assume it always OK */ I2C_TxData(data, 2); msleep(MMC328x_DELAY_TM); /* Read MD */ data[0] = MMC328x_REG_DS; I2C_RxData(data, 1); while (!(data[0] & 0x01)) { msleep(1); /* Read MD again*/ data[0] = MMC328x_REG_DS; I2C_RxData(data, 1); if (data[0] & 0x01) break; MD_times++; if (MD_times > 3) { printk("TM not work!!"); mutex_unlock(&read_i2c_xyz); return -EFAULT; } } read_idx++; data[0] = MMC328x_REG_DATA; if(I2C_RxData(data, 6) < 0) { mutex_unlock(&read_i2c_xyz); return -EFAULT; } vec[0] = data[1] << 8 | data[0]; vec[1] = data[3] << 8 | data[2]; vec[2] = data[5] << 8 | data[4]; #if DEBUG if(atomic_read(&clientdata->trace) & MMC_DATA_DEBUG) { printk("[X - %04x] [Y - %04x] [Z - %04x]\n", vec[0], vec[1], vec[2]); } #endif mutex_unlock(&read_i2c_xyz); last_data[0] = vec[0]; last_data[1] = vec[1]; last_data[2] = vec[2]; return 0; } static int ECS_GetRawData(int data[3]) { int err = 0; err = ECS_ReadXYZData(data, 3); if(err !=0 ) { printk(KERN_ERR "MMC328x_IOC_TM failed\n"); return -1; } // sensitivity 512 count = 1 Guass = 100uT data[0] = (data[0] - MMC328X_OFFSET_X) * 100 / MMC328X_SENSITIVITY_X; data[1] = (data[1] - MMC328X_OFFSET_X) * 100 / MMC328X_SENSITIVITY_X; data[2] = (data[2] - MMC328X_OFFSET_X) * 100 / MMC328X_SENSITIVITY_X; return err; } static int ECS_GetOpenStatus(void) { wait_event_interruptible(open_wq, (atomic_read(&open_flag) != 0)); return atomic_read(&open_flag); } /*----------------------------------------------------------------------------*/ static int mmc328x_ReadChipInfo(char *buf, int bufsize) { if((!buf)||(bufsize <= MMC328x_BUFSIZE -1)) { return -1; } if(!this_client) { *buf = 0; return -2; } sprintf(buf, "mmc328x Chip"); return 0; } /*----------------------------------------------------------------------------*/ static ssize_t show_chipinfo_value(struct device_driver *ddri, char *buf) { char strbuf[MMC328x_BUFSIZE]; mmc328x_ReadChipInfo(strbuf, MMC328x_BUFSIZE); return sprintf(buf, "%s\n", strbuf); } /*----------------------------------------------------------------------------*/ static ssize_t show_sensordata_value(struct device_driver *ddri, char *buf) { int sensordata[3]; char strbuf[MMC328x_BUFSIZE]; ECS_GetRawData(sensordata); sprintf(strbuf, "%d %d %d\n", sensordata[0],sensordata[1],sensordata[2]); return sprintf(buf, "%s\n", strbuf); } /*----------------------------------------------------------------------------*/ static ssize_t show_posturedata_value(struct device_driver *ddri, char *buf) { int tmp[3]; char strbuf[MMC328x_BUFSIZE]; tmp[0] = sensor_data[0] * CONVERT_O / CONVERT_O_DIV; tmp[1] = sensor_data[1] * CONVERT_O / CONVERT_O_DIV; tmp[2] = sensor_data[2] * CONVERT_O / CONVERT_O_DIV; sprintf(strbuf, "%d, %d, %d\n", tmp[0],tmp[1], tmp[2]); return sprintf(buf, "%s\n", strbuf);; } /*----------------------------------------------------------------------------*/ static ssize_t show_layout_value(struct device_driver *ddri, char *buf) { struct i2c_client *client = this_client; struct mmc328x_i2c_data *data = i2c_get_clientdata(client); return sprintf(buf, "(%d, %d)\n[%+2d %+2d %+2d]\n[%+2d %+2d %+2d]\n", data->hw->direction,atomic_read(&data->layout), data->cvt.sign[0], data->cvt.sign[1], data->cvt.sign[2],data->cvt.map[0], data->cvt.map[1], data->cvt.map[2]); } /*----------------------------------------------------------------------------*/ static ssize_t store_layout_value(struct device_driver *ddri, char *buf, size_t count) { struct i2c_client *client = this_client; struct mmc328x_i2c_data *data = i2c_get_clientdata(client); int layout = 0; if(1 == sscanf(buf, "%d", &layout)) { atomic_set(&data->layout, layout); if(!hwmsen_get_convert(layout, &data->cvt)) { printk(KERN_ERR "HWMSEN_GET_CONVERT function error!\r\n"); } else if(!hwmsen_get_convert(data->hw->direction, &data->cvt)) { printk(KERN_ERR "invalid layout: %d, restore to %d\n", layout, data->hw->direction); } else { printk(KERN_ERR "invalid layout: (%d, %d)\n", layout, data->hw->direction); hwmsen_get_convert(0, &data->cvt); } } else { printk(KERN_ERR "invalid format = '%s'\n", buf); } return count; } /*----------------------------------------------------------------------------*/ static ssize_t show_status_value(struct device_driver *ddri, char *buf) { struct i2c_client *client = this_client; struct mmc328x_i2c_data *data = i2c_get_clientdata(client); ssize_t len = 0; if(data->hw) { len += snprintf(buf+len, PAGE_SIZE-len, "CUST: %d %d (%d %d)\n", data->hw->i2c_num, data->hw->direction, data->hw->power_id, data->hw->power_vol); } else { len += snprintf(buf+len, PAGE_SIZE-len, "CUST: NULL\n"); } len += snprintf(buf+len, PAGE_SIZE-len, "OPEN: %d\n", atomic_read(&dev_open_count)); return len; } /*----------------------------------------------------------------------------*/ static ssize_t show_trace_value(struct device_driver *ddri, char *buf) { ssize_t res; struct mmc328x_i2c_data *obj = i2c_get_clientdata(this_client); if(NULL == obj) { printk(KERN_ERR "mmc328x_i2c_data is null!!\n"); return 0; } res = snprintf(buf, PAGE_SIZE, "0x%04X\n", atomic_read(&obj->trace)); return res; } /*----------------------------------------------------------------------------*/ static ssize_t store_trace_value(struct device_driver *ddri, char *buf, size_t count) { struct mmc328x_i2c_data *obj = i2c_get_clientdata(this_client); int trace; if(NULL == obj) { printk(KERN_ERR "mmc328x_i2c_data is null!!\n"); return 0; } if(1 == sscanf(buf, "0x%x", &trace)) { atomic_set(&obj->trace, trace); } else { printk(KERN_ERR "invalid content: '%s', length = %d\n", buf, count); } return count; } static ssize_t show_daemon_name(struct device_driver *ddri, char *buf) { char strbuf[MMC328x_BUFSIZE]; sprintf(strbuf, "memsicd"); return sprintf(buf, "%s", strbuf); } /*----------------------------------------------------------------------------*/ static DRIVER_ATTR(daemon, S_IRUGO, show_daemon_name, NULL); static DRIVER_ATTR(chipinfo, S_IRUGO, show_chipinfo_value, NULL); static DRIVER_ATTR(sensordata, S_IRUGO, show_sensordata_value, NULL); static DRIVER_ATTR(posturedata, S_IRUGO, show_posturedata_value, NULL); static DRIVER_ATTR(layout, S_IRUGO | S_IWUSR, show_layout_value, store_layout_value); static DRIVER_ATTR(status, S_IRUGO, show_status_value, NULL); static DRIVER_ATTR(trace, S_IRUGO | S_IWUSR, show_trace_value, store_trace_value); /*----------------------------------------------------------------------------*/ static struct driver_attribute *mmc328x_attr_list[] = { &driver_attr_daemon, &driver_attr_chipinfo, &driver_attr_sensordata, &driver_attr_posturedata, &driver_attr_layout, &driver_attr_status, &driver_attr_trace, }; /*----------------------------------------------------------------------------*/ static int mmc328x_create_attr(struct device_driver *driver) { int idx, err = 0; int num = (int)(sizeof(mmc328x_attr_list)/sizeof(mmc328x_attr_list[0])); if (driver == NULL) { return -EINVAL; } for(idx = 0; idx < num; idx++) { if(err = driver_create_file(driver, mmc328x_attr_list[idx])) { printk(KERN_ERR "driver_create_file (%s) = %d\n", mmc328x_attr_list[idx]->attr.name, err); break; } } return err; } /*----------------------------------------------------------------------------*/ static int mmc328x_delete_attr(struct device_driver *driver) { int idx; int num = (int)(sizeof(mmc328x_attr_list)/sizeof(mmc328x_attr_list[0])); if(driver == NULL) { return -EINVAL; } for(idx = 0; idx < num; idx++) { driver_remove_file(driver, mmc328x_attr_list[idx]); } return 0; } /*----------------------------------------------------------------------------*/ static int mmc328x_open(struct inode *inode, struct file *file) { struct mmc328x_i2c_data *obj = i2c_get_clientdata(this_client); int ret = -1; if(atomic_read(&obj->trace) & MMC_CTR_DEBUG) { MMCDBG("Open device node:mmc328x\n"); } ret = nonseekable_open(inode, file); return ret; } /*----------------------------------------------------------------------------*/ static int mmc328x_release(struct inode *inode, struct file *file) { struct mmc328x_i2c_data *obj = i2c_get_clientdata(this_client); atomic_dec(&dev_open_count); if(atomic_read(&obj->trace) & MMC_CTR_DEBUG) { MMCDBG("Release device node:mmc328x\n"); } return 0; } /*----------------------------------------------------------------------------*/ //static int mmc328x_ioctl(struct inode *inode, struct file *file, unsigned int cmd,unsigned long arg) static int mmc328x_unlocked_ioctl(struct file *file, unsigned int cmd,unsigned long arg) { void __user *argp = (void __user *)arg; /* NOTE: In this function the size of "char" should be 1-byte. */ char buff[MMC328x_BUFSIZE]; /* for chip information */ int value[12]; /* for SET_YPR */ int delay; /* for GET_DELAY */ int status; /* for OPEN/CLOSE_STATUS */ short sensor_status; /* for Orientation and Msensor status */ unsigned char data[16] = {0}; int vec[3] = {0}; struct i2c_client *client = this_client; struct mmc328x_i2c_data *clientdata = i2c_get_clientdata(client); hwm_sensor_data* osensor_data; uint32_t enable; switch (cmd) { case MMC31XX_IOC_TM: data[0] = MMC328x_REG_CTRL; data[1] = MMC328x_CTRL_TM; if (I2C_TxData(data, 2) < 0) { printk(KERN_ERR "MMC328x_IOC_TM failed\n"); return -EFAULT; } /* wait TM done for coming data read */ msleep(MMC328x_DELAY_TM); break; case MMC31XX_IOC_SET: data[0] = MMC328x_REG_CTRL; data[1] = MMC328x_REG_DS; if(I2C_TxData(data, 2) < 0) { printk(KERN_ERR "MMC328x_IOC_SET failed\n"); return -EFAULT; } /* wait external capacitor charging done for next SET/RESET */ msleep(MMC328x_DELAY_SET); break; case MMC31XX_IOC_RESET: data[0] = MMC328x_REG_CTRL; data[1] = MMC328x_REG_DS; if(I2C_TxData(data, 2) < 0) { printk(KERN_ERR "MMC328x_IOC_RESET failed\n"); return -EFAULT; } /* wait external capacitor charging done for next SET/RESET */ msleep(MMC328x_DELAY_RST); break; case MMC31XX_IOC_RM: data[0] = MMC328x_REG_CTRL; data[0] = MMC328x_CTRL_RM; if(I2C_RxData(data, 2) < 0) { printk(KERN_ERR "MMC328x_IOC_READ failed\n"); return -EFAULT; } /* wait external capacitor charging done for next RRM */ msleep(MMC328X_DELAY_RM); break; case MMC31XX_IOC_RRM: data[0] = MMC328x_REG_CTRL; data[0] = MMC328x_CTRL_RRM; if(I2C_RxData(data, 2) < 0) { printk(KERN_ERR "MMC328x_IOC_READ failed\n"); return -EFAULT; } /* wait external capacitor charging done for next RRM */ msleep(MMC328X_DELAY_RM); break; case MMC31XX_IOC_READ: data[0] = MMC328x_REG_DATA; if(I2C_RxData(data, 6) < 0) { printk(KERN_ERR "MMC328x_IOC_READ failed\n"); return -EFAULT; } vec[0] = data[1] << 8 | data[0]; vec[1] = data[3] << 8 | data[2]; vec[2] = data[5] << 8 | data[4]; vec[2] = 8192 - vec[2] ; #if DEBUG if(atomic_read(&clientdata->trace) & MMC_DATA_DEBUG) { printk("[X - %04x] [Y - %04x] [Z - %04x]\n", vec[0], vec[1], vec[2]); } #endif if(copy_to_user(argp, vec, sizeof(vec))) { printk(KERN_ERR "MMC328x_IOC_READ: copy to user failed\n"); return -EFAULT; } break; case MMC31XX_IOC_READXYZ: ECS_ReadXYZData(vec, 3); if(copy_to_user(argp, vec, sizeof(vec))) { printk(KERN_ERR "MMC328x_IOC_READXYZ: copy to user failed\n"); return -EFAULT; } break; case ECOMPASS_IOC_GET_DELAY: delay = mmcd_delay; if(copy_to_user(argp, &delay, sizeof(delay))) { printk(KERN_ERR "copy_to_user failed."); return -EFAULT; } break; case ECOMPASS_IOC_SET_YPR: if(argp == NULL) { MMCDBG("invalid argument."); return -EINVAL; } if(copy_from_user(value, argp, sizeof(value))) { MMCDBG("copy_from_user failed."); return -EFAULT; } ECS_SaveData(value); break; case ECOMPASS_IOC_GET_OPEN_STATUS: status = ECS_GetOpenStatus(); if(copy_to_user(argp, &status, sizeof(status))) { MMCDBG("copy_to_user failed."); return -EFAULT; } break; case ECOMPASS_IOC_GET_MFLAG: sensor_status = atomic_read(&m_flag); if(copy_to_user(argp, &sensor_status, sizeof(sensor_status))) { MMCDBG("copy_to_user failed."); return -EFAULT; } break; case ECOMPASS_IOC_GET_OFLAG: sensor_status = atomic_read(&o_flag); if(copy_to_user(argp, &sensor_status, sizeof(sensor_status))) { MMCDBG("copy_to_user failed."); return -EFAULT; } break; case MSENSOR_IOCTL_READ_CHIPINFO: if(argp == NULL) { printk(KERN_ERR "IO parameter pointer is NULL!\r\n"); break; } mmc328x_ReadChipInfo(buff, MMC328x_BUFSIZE); if(copy_to_user(argp, buff, strlen(buff)+1)) { return -EFAULT; } break; case MSENSOR_IOCTL_READ_SENSORDATA: if(argp == NULL) { printk(KERN_ERR "IO parameter pointer is NULL!\r\n"); break; } ECS_GetRawData(vec); sprintf(buff, "%x %x %x", vec[0], vec[1], vec[2]); if(copy_to_user(argp, buff, strlen(buff)+1)) { return -EFAULT; } break; case ECOMPASS_IOC_GET_LAYOUT: status = atomic_read(&clientdata->layout); if(copy_to_user(argp, &status, sizeof(status))) { MMCDBG("copy_to_user failed."); return -EFAULT; } break; case MSENSOR_IOCTL_SENSOR_ENABLE: if(argp == NULL) { printk(KERN_ERR "IO parameter pointer is NULL!\r\n"); break; } if(copy_from_user(&enable, argp, sizeof(enable))) { MMCDBG("copy_from_user failed."); return -EFAULT; } else { printk( "MSENSOR_IOCTL_SENSOR_ENABLE enable=%d!\r\n",enable); if(1 == enable) { atomic_set(&o_flag, 1); atomic_set(&open_flag, 1); } else { atomic_set(&o_flag, 0); if(atomic_read(&m_flag) == 0) { atomic_set(&open_flag, 0); } } wake_up(&open_wq); } break; case MSENSOR_IOCTL_READ_FACTORY_SENSORDATA: if(argp == NULL) { printk(KERN_ERR "IO parameter pointer is NULL!\r\n"); break; } //AKECS_GetRawData(buff, AKM8975_BUFSIZE); osensor_data = (hwm_sensor_data *)buff; mutex_lock(&sensor_data_mutex); osensor_data->values[0] = sensor_data[8] * CONVERT_O; osensor_data->values[1] = sensor_data[9] * CONVERT_O; osensor_data->values[2] = sensor_data[10] * CONVERT_O; osensor_data->status = sensor_data[11]; osensor_data->value_divide = CONVERT_O_DIV; mutex_unlock(&sensor_data_mutex); sprintf(buff, "%x %x %x %x %x", osensor_data->values[0], osensor_data->values[1], osensor_data->values[2],osensor_data->status,osensor_data->value_divide); if(copy_to_user(argp, buff, strlen(buff)+1)) { return -EFAULT; } break; default: printk(KERN_ERR "%s not supported = 0x%04x", __FUNCTION__, cmd); return -ENOIOCTLCMD; break; } return 0; } /*----------------------------------------------------------------------------*/ static struct file_operations mmc328x_fops = { //.owner = THIS_MODULE, .open = mmc328x_open, .release = mmc328x_release, .unlocked_ioctl = mmc328x_unlocked_ioctl, }; /*----------------------------------------------------------------------------*/ static struct miscdevice mmc328x_device = { .minor = MISC_DYNAMIC_MINOR, .name = "msensor", .fops = &mmc328x_fops, }; /*----------------------------------------------------------------------------*/ int mmc328x_operate(void* self, uint32_t command, void* buff_in, int size_in, void* buff_out, int size_out, int* actualout) { int err = 0; int value; hwm_sensor_data* msensor_data; #if DEBUG struct i2c_client *client = this_client; struct mmc328x_i2c_data *data = i2c_get_clientdata(client); #endif #if DEBUG if(atomic_read(&data->trace) & MMC_FUN_DEBUG) { MMCFUNC("mmc328x_operate"); } #endif switch (command) { case SENSOR_DELAY: if((buff_in == NULL) || (size_in < sizeof(int))) { printk(KERN_ERR "Set delay parameter error!\n"); err = -EINVAL; } else { value = *(int *)buff_in; if(value <= 20) { mmcd_delay = 20; } mmcd_delay = value; } break; case SENSOR_ENABLE: if((buff_in == NULL) || (size_in < sizeof(int))) { printk(KERN_ERR "Enable sensor parameter error!\n"); err = -EINVAL; } else { value = *(int *)buff_in; if(value == 1) { atomic_set(&m_flag, 1); atomic_set(&open_flag, 1); } else { atomic_set(&m_flag, 0); if(atomic_read(&o_flag) == 0) { atomic_set(&open_flag, 0); } } wake_up(&open_wq); // TODO: turn device into standby or normal mode } break; case SENSOR_GET_DATA: if((buff_out == NULL) || (size_out< sizeof(hwm_sensor_data))) { printk(KERN_ERR "get sensor data parameter error!\n"); err = -EINVAL; } else { msensor_data = (hwm_sensor_data *)buff_out; mutex_lock(&sensor_data_mutex); msensor_data->values[0] = sensor_data[4] * CONVERT_M; msensor_data->values[1] = sensor_data[5] * CONVERT_M; msensor_data->values[2] = sensor_data[6] * CONVERT_M; msensor_data->status = sensor_data[7]; msensor_data->value_divide = CONVERT_M_DIV; mutex_unlock(&sensor_data_mutex); #if DEBUG if(atomic_read(&data->trace) & MMC_HWM_DEBUG) { MMCDBG("Hwm get m-sensor data: %d, %d, %d. divide %d, status %d!\n", msensor_data->values[0],msensor_data->values[1],msensor_data->values[2], msensor_data->value_divide,msensor_data->status); } #endif } break; default: printk(KERN_ERR "msensor operate function no this parameter %d!\n", command); err = -1; break; } return err; } /*----------------------------------------------------------------------------*/ int mmc328x_orientation_operate(void* self, uint32_t command, void* buff_in, int size_in, void* buff_out, int size_out, int* actualout) { int err = 0; int value; hwm_sensor_data* osensor_data; #if DEBUG struct i2c_client *client = this_client; struct mmc328x_i2c_data *data = i2c_get_clientdata(client); #endif #if DEBUG if(atomic_read(&data->trace) & MMC_FUN_DEBUG) { MMCFUNC("mmc328x_orientation_operate"); } #endif switch (command) { case SENSOR_DELAY: if((buff_in == NULL) || (size_in < sizeof(int))) { printk(KERN_ERR "Set delay parameter error!\n"); err = -EINVAL; } else { value = *(int *)buff_in; if(value <= 20) { mmcd_delay = 20; } mmcd_delay = value; } break; case SENSOR_ENABLE: if((buff_in == NULL) || (size_in < sizeof(int))) { printk(KERN_ERR "Enable sensor parameter error!\n"); err = -EINVAL; } else { value = *(int *)buff_in; if(value == 1) { atomic_set(&o_flag, 1); atomic_set(&open_flag, 1); } else { atomic_set(&o_flag, 0); if(atomic_read(&m_flag) == 0) { atomic_set(&open_flag, 0); } } wake_up(&open_wq); } break; case SENSOR_GET_DATA: if((buff_out == NULL) || (size_out< sizeof(hwm_sensor_data))) { printk(KERN_ERR "get sensor data parameter error!\n"); err = -EINVAL; } else { osensor_data = (hwm_sensor_data *)buff_out; mutex_lock(&sensor_data_mutex); osensor_data->values[0] = sensor_data[8] * CONVERT_O; osensor_data->values[1] = sensor_data[9] * CONVERT_O; osensor_data->values[2] = sensor_data[10] * CONVERT_O; osensor_data->status = sensor_data[11]; osensor_data->value_divide = CONVERT_O_DIV; mutex_unlock(&sensor_data_mutex); #if DEBUG if(atomic_read(&data->trace) & MMC_HWM_DEBUG) { MMCDBG("Hwm get o-sensor data: %d, %d, %d. divide %d, status %d!\n", osensor_data->values[0],osensor_data->values[1],osensor_data->values[2], osensor_data->value_divide,osensor_data->status); } #endif } break; default: printk(KERN_ERR "gsensor operate function no this parameter %d!\n", command); err = -1; break; } return err; } /*----------------------------------------------------------------------------*/ #ifndef CONFIG_HAS_EARLYSUSPEND /*----------------------------------------------------------------------------*/ static int mmc328x_suspend(struct i2c_client *client, pm_message_t msg) { struct mmc328x_i2c_data *obj = i2c_get_clientdata(client) if(msg.event == PM_EVENT_SUSPEND) { mmc328x_power(obj->hw, 0); } return 0; } /*----------------------------------------------------------------------------*/ static int mmc328x_resume(struct i2c_client *client) { struct mmc328x_i2c_data *obj = i2c_get_clientdata(client) mmc328x_power(obj->hw, 1); return 0; } /*----------------------------------------------------------------------------*/ #else /*CONFIG_HAS_EARLY_SUSPEND is defined*/ /*----------------------------------------------------------------------------*/ static void mmc328x_early_suspend(struct early_suspend *h) { struct mmc328x_i2c_data *obj = container_of(h, struct mmc328x_i2c_data, early_drv); printk("mmc328x early_suspend!!\n"); //mmc328x_power(obj->hw, 0); if(NULL == obj) { printk(KERN_ERR "null pointer!!\n"); return; } if(mmc328x_SetPowerMode(obj->client, false)) { printk("mmc328x: write power control fail!!\n"); return; } } /*----------------------------------------------------------------------------*/ static void mmc328x_late_resume(struct early_suspend *h) { struct mmc328x_i2c_data *obj = container_of(h, struct mmc328x_i2c_data, early_drv); if(NULL == obj) { printk(KERN_ERR "null pointer!!\n"); return; } //mmc328x_power(obj->hw, 1); } /*----------------------------------------------------------------------------*/ #endif /*CONFIG_HAS_EARLYSUSPEND*/ /*----------------------------------------------------------------------------*/ static int mmc328x_i2c_detect(struct i2c_client *client, int kind, struct i2c_board_info *info) { strcpy(info->type, MMC328x_DEV_NAME); return 0; } /*----------------------------------------------------------------------------*/ static int mmc328x_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct i2c_client *new_client; struct mmc328x_i2c_data *data; char tmp[2]; int err = 0; struct hwmsen_object sobj_m, sobj_o; MMCDBG("%s: ++++\n", __func__); if(!(data = kmalloc(sizeof(struct mmc328x_i2c_data), GFP_KERNEL))) { err = -ENOMEM; goto exit; } memset(data, 0, sizeof(struct mmc328x_i2c_data)); data->hw = mmc328x_get_cust_mag_hw(); atomic_set(&data->layout, data->hw->direction); atomic_set(&data->trace, 0); mutex_init(&sensor_data_mutex); mutex_init(&read_i2c_xyz); init_waitqueue_head(&data_ready_wq); init_waitqueue_head(&open_wq); data->client = client; new_client = data->client; i2c_set_clientdata(new_client, data); this_client = new_client; //this_client->timing=400; /* send ST cmd to mag sensor first of all */ tmp[0] = MMC328x_REG_CTRL; tmp[1] = MMC328x_CTRL_RM; if(I2C_TxData(tmp, 2) < 0) { printk(KERN_ERR "mmc328x_device set ST cmd failed\n"); goto exit_kfree; } /* Register sysfs attribute */ if(err = mmc328x_create_attr(&(mmc328x_init_info.platform_diver_addr->driver))) { printk(KERN_ERR "create attribute err = %d\n", err); goto exit_sysfs_create_group_failed; } if(err = misc_register(&mmc328x_device)) { printk(KERN_ERR "mmc328x_device register failed\n"); goto exit_misc_device_register_failed; } sobj_m.self = data; sobj_m.polling = 1; sobj_m.sensor_operate = mmc328x_operate; if(err = hwmsen_attach(ID_MAGNETIC, &sobj_m)) { printk(KERN_ERR "attach fail = %d\n", err); goto exit_kfree; } sobj_o.self = data; sobj_o.polling = 1; sobj_o.sensor_operate = mmc328x_orientation_operate; if(err = hwmsen_attach(ID_ORIENTATION, &sobj_o)) { printk(KERN_ERR "attach fail = %d\n", err); goto exit_kfree; } #if CONFIG_HAS_EARLYSUSPEND data->early_drv.level = EARLY_SUSPEND_LEVEL_DISABLE_FB - 1, data->early_drv.suspend = mmc328x_early_suspend, data->early_drv.resume = mmc328x_late_resume, register_early_suspend(&data->early_drv); #endif MMCDBG("%s: OK\n", __func__); mmc328x_init_flag = 0; return 0; exit_sysfs_create_group_failed: exit_misc_device_register_failed: exit_kfree: kfree(data); exit: printk(KERN_ERR "%s: err = %d\n", __func__, err); mmc328x_init_flag = -1; return err; } /*----------------------------------------------------------------------------*/ static int mmc328x_i2c_remove(struct i2c_client *client) { int err; if(err = mmc328x_delete_attr(&(mmc328x_init_info.platform_diver_addr->driver))) { printk(KERN_ERR "mmc328x_delete_attr fail: %d\n", err); } this_client = NULL; i2c_unregister_device(client); kfree(i2c_get_clientdata(client)); misc_deregister(&mmc328x_device); return 0; } /*----------------------------------------------------------------------------*/ static int mmc328x_local_init(void) { struct mag_hw *hw = mmc328x_get_cust_mag_hw(); MMCFUNC("mmc328x_local_init"); mmc328x_power(hw, 1); atomic_set(&dev_open_count, 0); //mmc328x_force[0] = hw->i2c_num; if(i2c_add_driver(&mmc328x_i2c_driver)) { printk(KERN_ERR "add driver error\n"); return -1; } if(-1 == mmc328x_init_flag) { return -1; } return 0; } /*----------------------------------------------------------------------------*/ static int mmc328x_remove() { struct mag_hw *hw = mmc328x_get_cust_mag_hw(); mmc328x_power(hw, 0); atomic_set(&dev_open_count, 0); i2c_del_driver(&mmc328x_i2c_driver); return 0; } /*----------------------------------------------------------------------------*/ static int __init mmc328x_init(void) { MMCFUNC("mmc328x_init"); i2c_register_board_info(3, &i2c_mmc328x, 1); hwmsen_msensor_add(&mmc328x_init_info); return 0; } /*----------------------------------------------------------------------------*/ static void __exit mmc328x_exit(void) { MMCFUNC("mmc328x_exit"); } /*----------------------------------------------------------------------------*/ module_init(mmc328x_init); module_exit(mmc328x_exit); MODULE_AUTHOR("weiqi fu"); MODULE_DESCRIPTION("mmc328x compass driver"); MODULE_LICENSE("GPL"); MODULE_VERSION(DRIVER_VERSION);
jawad6233/android_kernel_bq_aquaris5
mediatek/custom/out/aquaris5/kernel/magnetometer/mmc328xma_auto.c
C
gpl-2.0
41,574
character (LEN=12) :: filename do i=2,36 if (i<10) then write(filename,"(A,I1,A)") "zvradio", i, ".pd " else write(filename,"(A,I2,A)") "zvradio", i, ".pd" endif open (unit=11,file=TRIM(filename)) j = 15 * i + 2 k = 206 + j k2 = 138 + j k3 = 179 + j write(11,"(A)") "#N canvas 425 466 605 321 10;" if (i<10) then write(11,"(A,I1,A)") "#X obj 301 101 vradio 15 1 0 ",i," empty empty empty 0 -8 0 10 -262144 -1 -1 0;" else write(11,"(A,I2,A)") "#X obj 301 101 vradio 15 1 0 ",i," empty empty empty 0 -8 0 10 -262144 -1 -1 0;" endif write(11,"(A,I3,A)") "#X obj 233 ", k, " outlet;" write(11,"(A)") "#X obj 196 41 inlet;" write(11,"(A,I3,A)") "#X obj 233 ", k2, " * 1;" write(11,"(A,I3,A)") "#X obj 233 ", k3, " + 1;" write(11,"(A)") "#X obj 196 74 route min stepsize;" write(11,"(A)") "#X obj 172 118 t b;" write(11,"(A)") "#X connect 0 0 3 0;" write(11,"(A)") "#X connect 2 0 5 0;" write(11,"(A)") "#X connect 3 0 4 0;" write(11,"(A)") "#X connect 4 0 1 0;" write(11,"(A)") "#X connect 5 0 4 1;" write(11,"(A)") "#X connect 5 0 6 0;" write(11,"(A)") "#X connect 5 1 3 1;" write(11,"(A)") "#X connect 5 2 0 0;" write(11,"(A)") "#X connect 6 0 0 0;" if (j<100) then write(11,"(A,I2,A)") "#X coords 0 -1 1 1 17 ", j, " 2 300 100;" else write(11,"(A,I3,A)") "#X coords 0 -1 1 1 17 ", j, " 2 300 100;" endif close(unit=11) enddo end
gilbertohasnofb/pd-abstractions-and-libraries
pd-alternative-themes/themes/default/zvradio/zvradio generator/zvradio.f95
FORTRAN
gpl-2.0
1,388
/* * Copyright 2008, Network Appliance Inc. * Author: Jason McMullan <mcmullan <at> netapp.com> * Licensed under the GPL-2 or later. */ //#define DEBUG #include <common.h> #include <malloc.h> #include <spi_flash.h> #include "spi_flash_internal.h" /* M25Pxx-specific commands */ #define CMD_W25_WREN 0x06 /* Write Enable */ #define CMD_W25_WRDI 0x04 /* Write Disable */ #define CMD_W25_RDSR 0x05 /* Read Status Register */ #define CMD_W25_WRSR 0x01 /* Write Status Register */ #define CMD_W25_READ 0x03 /* Read Data Bytes */ #define CMD_W25_FAST_READ 0x0b /* Read Data Bytes at Higher Speed */ #define CMD_W25_PP 0x02 /* Page Program */ #define CMD_W25_SE 0x20 /* Sector (4K) Erase */ #define CMD_W25_BE 0xd8 /* Block (64K) Erase */ #define CMD_W25_CE 0xc7 /* Chip Erase */ #define CMD_W25_DP 0xb9 /* Deep Power-down */ #define CMD_W25_RES 0xab /* Release from DP, and Read Signature */ #define WINBOND_ID_W25X16 0x3015 #define WINBOND_ID_W25X32 0x3016 #define WINBOND_ID_W25X64 0x3017 #define WINBOND_ID_W25Q40BV 0x3013 #define WINBOND_SR_WIP (1 << 0) /* Write-in-Progress */ struct winbond_spi_flash_params { uint16_t id; /* Log2 of page size in power-of-two mode */ uint8_t l2_page_size; uint16_t pages_per_sector; uint16_t sectors_per_block; uint8_t nr_blocks; const char *name; }; /* spi_flash needs to be first so upper layers can free() it */ struct winbond_spi_flash { struct spi_flash flash; const struct winbond_spi_flash_params *params; }; static inline struct winbond_spi_flash * to_winbond_spi_flash(struct spi_flash *flash) { return container_of(flash, struct winbond_spi_flash, flash); } static const struct winbond_spi_flash_params winbond_spi_flash_table[] = { { .id = WINBOND_ID_W25X16, .l2_page_size = 8, .pages_per_sector = 16, .sectors_per_block = 16, .nr_blocks = 32, .name = "W25X16", }, { .id = WINBOND_ID_W25X32, .l2_page_size = 8, .pages_per_sector = 16, .sectors_per_block = 16, .nr_blocks = 64, .name = "W25X32", }, { .id = WINBOND_ID_W25X64, .l2_page_size = 8, .pages_per_sector = 16, .sectors_per_block = 16, .nr_blocks = 128, .name = "W25X64", }, { .id = WINBOND_ID_W25Q40BV, .l2_page_size = 8, .pages_per_sector = 16, .sectors_per_block = 16, .nr_blocks = 8, .name = "W25Q40BV", }, }; static int winbond_wait_ready(struct spi_flash *flash, unsigned long timeout) { struct spi_slave *spi = flash->spi; unsigned long timebase; int ret; u8 status; u8 cmd[4] = { CMD_W25_RDSR, 0xff, 0xff, 0xff }; ret = spi_xfer(spi, 32, &cmd[0], NULL, SPI_XFER_BEGIN); if (ret) { debug("SF: Failed to send command %02x: %d\n", cmd, ret); return ret; } timebase = get_timer(0); do { ret = spi_xfer(spi, 8, NULL, &status, 0); if (ret) { debug("SF: Failed to get status for cmd %02x: %d\n", cmd, ret); return -1; } if ((status & WINBOND_SR_WIP) == 0) break; } while (get_timer(timebase) < timeout); spi_xfer(spi, 0, NULL, NULL, SPI_XFER_END); if ((status & WINBOND_SR_WIP) == 0) return 0; debug("SF: Timed out on command %02x: %d\n", cmd, ret); /* Timed out */ return -1; } /* * Assemble the address part of a command for Winbond devices in * non-power-of-two page size mode. */ static void winbond_build_address(struct winbond_spi_flash *stm, u8 *cmd, u32 offset) { unsigned long page_addr; unsigned long byte_addr; unsigned long page_size; unsigned int page_shift; /* * The "extra" space per page is the power-of-two page size * divided by 32. */ page_shift = stm->params->l2_page_size; page_size = (1 << page_shift); page_addr = offset / page_size; byte_addr = offset % page_size; cmd[0] = page_addr >> (16 - page_shift); cmd[1] = page_addr << (page_shift - 8) | (byte_addr >> 8); cmd[2] = byte_addr; } static int winbond_read_fast(struct spi_flash *flash, u32 offset, size_t len, void *buf) { struct winbond_spi_flash *stm = to_winbond_spi_flash(flash); u8 cmd[5]; cmd[0] = CMD_READ_ARRAY_FAST; winbond_build_address(stm, cmd + 1, offset); cmd[4] = 0x00; return spi_flash_read_common(flash, cmd, sizeof(cmd), buf, len); } static int winbond_write(struct spi_flash *flash, u32 offset, size_t len, const void *buf) { struct winbond_spi_flash *stm = to_winbond_spi_flash(flash); unsigned long page_addr; unsigned long byte_addr; unsigned long page_size; unsigned int page_shift; size_t chunk_len; size_t actual; int ret; u8 cmd[4]; page_shift = stm->params->l2_page_size; page_size = (1 << page_shift); page_addr = offset / page_size; byte_addr = offset % page_size; ret = spi_claim_bus(flash->spi); if (ret) { debug("SF: Unable to claim SPI bus\n"); return ret; } for (actual = 0; actual < len; actual += chunk_len) { chunk_len = min(len - actual, page_size - byte_addr); cmd[0] = CMD_W25_PP; cmd[1] = page_addr >> (16 - page_shift); cmd[2] = page_addr << (page_shift - 8) | (byte_addr >> 8); cmd[3] = byte_addr; debug("PP: 0x%p => cmd = { 0x%02x 0x%02x%02x%02x } chunk_len = %d\n", buf + actual, cmd[0], cmd[1], cmd[2], cmd[3], chunk_len); ret = spi_flash_cmd(flash->spi, CMD_W25_WREN, NULL, 0); if (ret < 0) { debug("SF: Enabling Write failed\n"); goto out; } ret = spi_flash_cmd_write(flash->spi, cmd, 4, buf + actual, chunk_len); if (ret < 0) { debug("SF: Winbond Page Program failed\n"); goto out; } ret = winbond_wait_ready(flash, SPI_FLASH_PROG_TIMEOUT); if (ret < 0) { debug("SF: Winbond page programming timed out\n"); goto out; } page_addr++; byte_addr = 0; } debug("SF: Winbond: Successfully programmed %u bytes @ 0x%x\n", len, offset); ret = 0; out: spi_release_bus(flash->spi); return ret; } int winbond_erase(struct spi_flash *flash, u32 offset, size_t len) { struct winbond_spi_flash *stm = to_winbond_spi_flash(flash); unsigned long sector_size; unsigned int page_shift; size_t actual; int ret; u8 cmd[4]; /* * This function currently uses sector erase only. * probably speed things up by using bulk erase * when possible. */ page_shift = stm->params->l2_page_size; sector_size = (1 << page_shift) * stm->params->pages_per_sector; if (offset % sector_size || len % sector_size) { debug("SF: Erase offset/length not multiple of sector size\n"); return -1; } len /= sector_size; cmd[0] = CMD_W25_SE; ret = spi_claim_bus(flash->spi); if (ret) { debug("SF: Unable to claim SPI bus\n"); return ret; } for (actual = 0; actual < len; actual++) { winbond_build_address(stm, &cmd[1], offset + actual * sector_size); printf("Erase: %02x %02x %02x %02x\n", cmd[0], cmd[1], cmd[2], cmd[3]); ret = spi_flash_cmd(flash->spi, CMD_W25_WREN, NULL, 0); if (ret < 0) { debug("SF: Enabling Write failed\n"); goto out; } ret = spi_flash_cmd_write(flash->spi, cmd, 4, NULL, 0); if (ret < 0) { debug("SF: Winbond sector erase failed\n"); goto out; } ret = winbond_wait_ready(flash, SPI_FLASH_PAGE_ERASE_TIMEOUT); if (ret < 0) { debug("SF: Winbond sector erase timed out\n"); goto out; } } debug("SF: Winbond: Successfully erased %u bytes @ 0x%x\n", len * sector_size, offset); ret = 0; out: spi_release_bus(flash->spi); return ret; } struct spi_flash *spi_flash_probe_winbond(struct spi_slave *spi, u8 *idcode) { const struct winbond_spi_flash_params *params; unsigned long page_size; struct winbond_spi_flash *stm; unsigned int i; for (i = 0; i < ARRAY_SIZE(winbond_spi_flash_table); i++) { params = &winbond_spi_flash_table[i]; if (params->id == ((idcode[1] << 8) | idcode[2])) break; } if (i == ARRAY_SIZE(winbond_spi_flash_table)) { debug("SF: Unsupported Winbond ID %02x%02x\n", idcode[1], idcode[2]); return NULL; } stm = malloc(sizeof(struct winbond_spi_flash)); if (!stm) { debug("SF: Failed to allocate memory\n"); return NULL; } stm->params = params; stm->flash.spi = spi; stm->flash.name = params->name; /* Assuming power-of-two page size initially. */ page_size = 1 << params->l2_page_size; stm->flash.write = winbond_write; stm->flash.erase = winbond_erase; stm->flash.read = winbond_read_fast; stm->flash.size = page_size * params->pages_per_sector * params->sectors_per_block * params->nr_blocks; debug("SF: Detected %s with page size %u, total %u bytes\n", params->name, page_size, stm->flash.size); return &stm->flash; }
uwehermann/easybox-904-lte-firmware
package/infineon-utilities/feeds/ifx_feeds_uboot/open_uboot/src/drivers/mtd/spi/winbond.c
C
gpl-2.0
8,407
# hunter-simple ## Build steps * Set `HUNTER_ROOT` environment variable.(Recommended, see [alternatives](https://github.com/hunter-packages/gate#effects)) * Generate project: `cmake -H. -B_builds -DHUNTER_STATUS_DEBUG=ON -DCMAKE_BUILD_TYPE=Debug`. * Run build: `cmake --build _builds --config Debug`. * Run test: `cd _builds && ctest -C Debug -VV`.
Akagi201/learning-cmake
hunter-simple/README.md
Markdown
gpl-2.0
350
/*- * BSD LICENSE * * Copyright(c) 2010-2016 Intel Corporation. All rights reserved. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/queue.h> #include <stdio.h> #include <errno.h> #include <stdint.h> #include <string.h> #include <unistd.h> #include <stdarg.h> #include <inttypes.h> #include <rte_byteorder.h> #include <rte_common.h> #include <rte_cycles.h> #include <rte_interrupts.h> #include <rte_log.h> #include <rte_debug.h> #include <rte_pci.h> #include <rte_atomic.h> #include <rte_branch_prediction.h> #include <rte_memory.h> #include <rte_memzone.h> #include <rte_eal.h> #include <rte_alarm.h> #include <rte_ether.h> #include <rte_ethdev.h> #include <rte_atomic.h> #include <rte_malloc.h> #include <rte_dev.h> #include "i40e_logs.h" #include "base/i40e_prototype.h" #include "base/i40e_adminq_cmd.h" #include "base/i40e_type.h" #include "i40e_rxtx.h" #include "i40e_ethdev.h" #include "i40e_pf.h" #define I40EVF_VSI_DEFAULT_MSIX_INTR 1 #define I40EVF_VSI_DEFAULT_MSIX_INTR_LNX 0 /* busy wait delay in msec */ #define I40EVF_BUSY_WAIT_DELAY 10 #define I40EVF_BUSY_WAIT_COUNT 50 #define MAX_RESET_WAIT_CNT 20 struct i40evf_arq_msg_info { enum i40e_virtchnl_ops ops; enum i40e_status_code result; uint16_t buf_len; uint16_t msg_len; uint8_t *msg; }; struct vf_cmd_info { enum i40e_virtchnl_ops ops; uint8_t *in_args; uint32_t in_args_size; uint8_t *out_buffer; /* Input & output type. pass in buffer size and pass out * actual return result */ uint32_t out_size; }; enum i40evf_aq_result { I40EVF_MSG_ERR = -1, /* Meet error when accessing admin queue */ I40EVF_MSG_NON, /* Read nothing from admin queue */ I40EVF_MSG_SYS, /* Read system msg from admin queue */ I40EVF_MSG_CMD, /* Read async command result */ }; static int i40evf_dev_configure(struct rte_eth_dev *dev); static int i40evf_dev_start(struct rte_eth_dev *dev); static void i40evf_dev_stop(struct rte_eth_dev *dev); static void i40evf_dev_info_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *dev_info); static int i40evf_dev_link_update(struct rte_eth_dev *dev, __rte_unused int wait_to_complete); static void i40evf_dev_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats); static int i40evf_dev_xstats_get(struct rte_eth_dev *dev, struct rte_eth_xstat *xstats, unsigned n); static int i40evf_dev_xstats_get_names(struct rte_eth_dev *dev, struct rte_eth_xstat_name *xstats_names, unsigned limit); static void i40evf_dev_xstats_reset(struct rte_eth_dev *dev); static int i40evf_vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on); static void i40evf_vlan_offload_set(struct rte_eth_dev *dev, int mask); static int i40evf_vlan_pvid_set(struct rte_eth_dev *dev, uint16_t pvid, int on); static void i40evf_dev_close(struct rte_eth_dev *dev); static void i40evf_dev_promiscuous_enable(struct rte_eth_dev *dev); static void i40evf_dev_promiscuous_disable(struct rte_eth_dev *dev); static void i40evf_dev_allmulticast_enable(struct rte_eth_dev *dev); static void i40evf_dev_allmulticast_disable(struct rte_eth_dev *dev); static int i40evf_init_vlan(struct rte_eth_dev *dev); static int i40evf_dev_rx_queue_start(struct rte_eth_dev *dev, uint16_t rx_queue_id); static int i40evf_dev_rx_queue_stop(struct rte_eth_dev *dev, uint16_t rx_queue_id); static int i40evf_dev_tx_queue_start(struct rte_eth_dev *dev, uint16_t tx_queue_id); static int i40evf_dev_tx_queue_stop(struct rte_eth_dev *dev, uint16_t tx_queue_id); static void i40evf_add_mac_addr(struct rte_eth_dev *dev, struct ether_addr *addr, uint32_t index, uint32_t pool); static void i40evf_del_mac_addr(struct rte_eth_dev *dev, uint32_t index); static int i40evf_dev_rss_reta_update(struct rte_eth_dev *dev, struct rte_eth_rss_reta_entry64 *reta_conf, uint16_t reta_size); static int i40evf_dev_rss_reta_query(struct rte_eth_dev *dev, struct rte_eth_rss_reta_entry64 *reta_conf, uint16_t reta_size); static int i40evf_config_rss(struct i40e_vf *vf); static int i40evf_dev_rss_hash_update(struct rte_eth_dev *dev, struct rte_eth_rss_conf *rss_conf); static int i40evf_dev_rss_hash_conf_get(struct rte_eth_dev *dev, struct rte_eth_rss_conf *rss_conf); static int i40evf_dev_mtu_set(struct rte_eth_dev *dev, uint16_t mtu); static void i40evf_set_default_mac_addr(struct rte_eth_dev *dev, struct ether_addr *mac_addr); static int i40evf_dev_rx_queue_intr_enable(struct rte_eth_dev *dev, uint16_t queue_id); static int i40evf_dev_rx_queue_intr_disable(struct rte_eth_dev *dev, uint16_t queue_id); static void i40evf_handle_pf_event(__rte_unused struct rte_eth_dev *dev, uint8_t *msg, uint16_t msglen); /* Default hash key buffer for RSS */ static uint32_t rss_key_default[I40E_VFQF_HKEY_MAX_INDEX + 1]; struct rte_i40evf_xstats_name_off { char name[RTE_ETH_XSTATS_NAME_SIZE]; unsigned offset; }; static const struct rte_i40evf_xstats_name_off rte_i40evf_stats_strings[] = { {"rx_bytes", offsetof(struct i40e_eth_stats, rx_bytes)}, {"rx_unicast_packets", offsetof(struct i40e_eth_stats, rx_unicast)}, {"rx_multicast_packets", offsetof(struct i40e_eth_stats, rx_multicast)}, {"rx_broadcast_packets", offsetof(struct i40e_eth_stats, rx_broadcast)}, {"rx_dropped_packets", offsetof(struct i40e_eth_stats, rx_discards)}, {"rx_unknown_protocol_packets", offsetof(struct i40e_eth_stats, rx_unknown_protocol)}, {"tx_bytes", offsetof(struct i40e_eth_stats, tx_bytes)}, {"tx_unicast_packets", offsetof(struct i40e_eth_stats, tx_unicast)}, {"tx_multicast_packets", offsetof(struct i40e_eth_stats, tx_multicast)}, {"tx_broadcast_packets", offsetof(struct i40e_eth_stats, tx_broadcast)}, {"tx_dropped_packets", offsetof(struct i40e_eth_stats, tx_discards)}, {"tx_error_packets", offsetof(struct i40e_eth_stats, tx_errors)}, }; #define I40EVF_NB_XSTATS (sizeof(rte_i40evf_stats_strings) / \ sizeof(rte_i40evf_stats_strings[0])) static const struct eth_dev_ops i40evf_eth_dev_ops = { .dev_configure = i40evf_dev_configure, .dev_start = i40evf_dev_start, .dev_stop = i40evf_dev_stop, .promiscuous_enable = i40evf_dev_promiscuous_enable, .promiscuous_disable = i40evf_dev_promiscuous_disable, .allmulticast_enable = i40evf_dev_allmulticast_enable, .allmulticast_disable = i40evf_dev_allmulticast_disable, .link_update = i40evf_dev_link_update, .stats_get = i40evf_dev_stats_get, .xstats_get = i40evf_dev_xstats_get, .xstats_get_names = i40evf_dev_xstats_get_names, .xstats_reset = i40evf_dev_xstats_reset, .dev_close = i40evf_dev_close, .dev_infos_get = i40evf_dev_info_get, .dev_supported_ptypes_get = i40e_dev_supported_ptypes_get, .vlan_filter_set = i40evf_vlan_filter_set, .vlan_offload_set = i40evf_vlan_offload_set, .vlan_pvid_set = i40evf_vlan_pvid_set, .rx_queue_start = i40evf_dev_rx_queue_start, .rx_queue_stop = i40evf_dev_rx_queue_stop, .tx_queue_start = i40evf_dev_tx_queue_start, .tx_queue_stop = i40evf_dev_tx_queue_stop, .rx_queue_setup = i40e_dev_rx_queue_setup, .rx_queue_release = i40e_dev_rx_queue_release, .rx_queue_intr_enable = i40evf_dev_rx_queue_intr_enable, .rx_queue_intr_disable = i40evf_dev_rx_queue_intr_disable, .rx_descriptor_done = i40e_dev_rx_descriptor_done, .tx_queue_setup = i40e_dev_tx_queue_setup, .tx_queue_release = i40e_dev_tx_queue_release, .rx_queue_count = i40e_dev_rx_queue_count, .rxq_info_get = i40e_rxq_info_get, .txq_info_get = i40e_txq_info_get, .mac_addr_add = i40evf_add_mac_addr, .mac_addr_remove = i40evf_del_mac_addr, .reta_update = i40evf_dev_rss_reta_update, .reta_query = i40evf_dev_rss_reta_query, .rss_hash_update = i40evf_dev_rss_hash_update, .rss_hash_conf_get = i40evf_dev_rss_hash_conf_get, .mtu_set = i40evf_dev_mtu_set, .mac_addr_set = i40evf_set_default_mac_addr, }; /* * Read data in admin queue to get msg from pf driver */ static enum i40evf_aq_result i40evf_read_pfmsg(struct rte_eth_dev *dev, struct i40evf_arq_msg_info *data) { struct i40e_hw *hw = I40E_DEV_PRIVATE_TO_HW(dev->data->dev_private); struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); struct i40e_arq_event_info event; enum i40e_virtchnl_ops opcode; enum i40e_status_code retval; int ret; enum i40evf_aq_result result = I40EVF_MSG_NON; event.buf_len = data->buf_len; event.msg_buf = data->msg; ret = i40e_clean_arq_element(hw, &event, NULL); /* Can't read any msg from adminQ */ if (ret) { if (ret != I40E_ERR_ADMIN_QUEUE_NO_WORK) result = I40EVF_MSG_ERR; return result; } opcode = (enum i40e_virtchnl_ops)rte_le_to_cpu_32(event.desc.cookie_high); retval = (enum i40e_status_code)rte_le_to_cpu_32(event.desc.cookie_low); /* pf sys event */ if (opcode == I40E_VIRTCHNL_OP_EVENT) { struct i40e_virtchnl_pf_event *vpe = (struct i40e_virtchnl_pf_event *)event.msg_buf; result = I40EVF_MSG_SYS; switch (vpe->event) { case I40E_VIRTCHNL_EVENT_LINK_CHANGE: vf->link_up = vpe->event_data.link_event.link_status; vf->link_speed = vpe->event_data.link_event.link_speed; vf->pend_msg |= PFMSG_LINK_CHANGE; PMD_DRV_LOG(INFO, "Link status update:%s", vf->link_up ? "up" : "down"); break; case I40E_VIRTCHNL_EVENT_RESET_IMPENDING: vf->vf_reset = true; vf->pend_msg |= PFMSG_RESET_IMPENDING; PMD_DRV_LOG(INFO, "vf is reseting"); break; case I40E_VIRTCHNL_EVENT_PF_DRIVER_CLOSE: vf->dev_closed = true; vf->pend_msg |= PFMSG_DRIVER_CLOSE; PMD_DRV_LOG(INFO, "PF driver closed"); break; default: PMD_DRV_LOG(ERR, "%s: Unknown event %d from pf", __func__, vpe->event); } } else { /* async reply msg on command issued by vf previously */ result = I40EVF_MSG_CMD; /* Actual data length read from PF */ data->msg_len = event.msg_len; } data->result = retval; data->ops = opcode; return result; } /** * clear current command. Only call in case execute * _atomic_set_cmd successfully. */ static inline void _clear_cmd(struct i40e_vf *vf) { rte_wmb(); vf->pend_cmd = I40E_VIRTCHNL_OP_UNKNOWN; } /* * Check there is pending cmd in execution. If none, set new command. */ static inline int _atomic_set_cmd(struct i40e_vf *vf, enum i40e_virtchnl_ops ops) { int ret = rte_atomic32_cmpset(&vf->pend_cmd, I40E_VIRTCHNL_OP_UNKNOWN, ops); if (!ret) PMD_DRV_LOG(ERR, "There is incomplete cmd %d", vf->pend_cmd); return !ret; } #define MAX_TRY_TIMES 200 #define ASQ_DELAY_MS 10 static int i40evf_execute_vf_cmd(struct rte_eth_dev *dev, struct vf_cmd_info *args) { struct i40e_hw *hw = I40E_DEV_PRIVATE_TO_HW(dev->data->dev_private); struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); struct i40evf_arq_msg_info info; enum i40evf_aq_result ret; int err, i = 0; if (_atomic_set_cmd(vf, args->ops)) return -1; info.msg = args->out_buffer; info.buf_len = args->out_size; info.ops = I40E_VIRTCHNL_OP_UNKNOWN; info.result = I40E_SUCCESS; err = i40e_aq_send_msg_to_pf(hw, args->ops, I40E_SUCCESS, args->in_args, args->in_args_size, NULL); if (err) { PMD_DRV_LOG(ERR, "fail to send cmd %d", args->ops); _clear_cmd(vf); return err; } switch (args->ops) { case I40E_VIRTCHNL_OP_RESET_VF: /*no need to process in this function */ err = 0; break; case I40E_VIRTCHNL_OP_VERSION: case I40E_VIRTCHNL_OP_GET_VF_RESOURCES: /* for init adminq commands, need to poll the response */ err = -1; do { ret = i40evf_read_pfmsg(dev, &info); vf->cmd_retval = info.result; if (ret == I40EVF_MSG_CMD) { err = 0; break; } else if (ret == I40EVF_MSG_ERR) break; rte_delay_ms(ASQ_DELAY_MS); /* If don't read msg or read sys event, continue */ } while (i++ < MAX_TRY_TIMES); _clear_cmd(vf); break; default: /* for other adminq in running time, waiting the cmd done flag */ err = -1; do { if (vf->pend_cmd == I40E_VIRTCHNL_OP_UNKNOWN) { err = 0; break; } rte_delay_ms(ASQ_DELAY_MS); /* If don't read msg or read sys event, continue */ } while (i++ < MAX_TRY_TIMES); break; } return err | vf->cmd_retval; } /* * Check API version with sync wait until version read or fail from admin queue */ static int i40evf_check_api_version(struct rte_eth_dev *dev) { struct i40e_virtchnl_version_info version, *pver; int err; struct vf_cmd_info args; struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); version.major = I40E_VIRTCHNL_VERSION_MAJOR; version.minor = I40E_VIRTCHNL_VERSION_MINOR; args.ops = I40E_VIRTCHNL_OP_VERSION; args.in_args = (uint8_t *)&version; args.in_args_size = sizeof(version); args.out_buffer = vf->aq_resp; args.out_size = I40E_AQ_BUF_SZ; err = i40evf_execute_vf_cmd(dev, &args); if (err) { PMD_INIT_LOG(ERR, "fail to execute command OP_VERSION"); return err; } pver = (struct i40e_virtchnl_version_info *)args.out_buffer; vf->version_major = pver->major; vf->version_minor = pver->minor; if (vf->version_major == I40E_DPDK_VERSION_MAJOR) PMD_DRV_LOG(INFO, "Peer is DPDK PF host"); else if ((vf->version_major == I40E_VIRTCHNL_VERSION_MAJOR) && (vf->version_minor <= I40E_VIRTCHNL_VERSION_MINOR)) PMD_DRV_LOG(INFO, "Peer is Linux PF host"); else { PMD_INIT_LOG(ERR, "PF/VF API version mismatch:(%u.%u)-(%u.%u)", vf->version_major, vf->version_minor, I40E_VIRTCHNL_VERSION_MAJOR, I40E_VIRTCHNL_VERSION_MINOR); return -1; } return 0; } static int i40evf_get_vf_resource(struct rte_eth_dev *dev) { struct i40e_hw *hw = I40E_DEV_PRIVATE_TO_HW(dev->data->dev_private); struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); int err; struct vf_cmd_info args; uint32_t caps, len; args.ops = I40E_VIRTCHNL_OP_GET_VF_RESOURCES; args.out_buffer = vf->aq_resp; args.out_size = I40E_AQ_BUF_SZ; if (PF_IS_V11(vf)) { caps = I40E_VIRTCHNL_VF_OFFLOAD_L2 | I40E_VIRTCHNL_VF_OFFLOAD_RSS_AQ | I40E_VIRTCHNL_VF_OFFLOAD_RSS_REG | I40E_VIRTCHNL_VF_OFFLOAD_VLAN | I40E_VIRTCHNL_VF_OFFLOAD_RX_POLLING; args.in_args = (uint8_t *)&caps; args.in_args_size = sizeof(caps); } else { args.in_args = NULL; args.in_args_size = 0; } err = i40evf_execute_vf_cmd(dev, &args); if (err) { PMD_DRV_LOG(ERR, "fail to execute command OP_GET_VF_RESOURCE"); return err; } len = sizeof(struct i40e_virtchnl_vf_resource) + I40E_MAX_VF_VSI * sizeof(struct i40e_virtchnl_vsi_resource); (void)rte_memcpy(vf->vf_res, args.out_buffer, RTE_MIN(args.out_size, len)); i40e_vf_parse_hw_config(hw, vf->vf_res); return 0; } static int i40evf_config_promisc(struct rte_eth_dev *dev, bool enable_unicast, bool enable_multicast) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); int err; struct vf_cmd_info args; struct i40e_virtchnl_promisc_info promisc; promisc.flags = 0; promisc.vsi_id = vf->vsi_res->vsi_id; if (enable_unicast) promisc.flags |= I40E_FLAG_VF_UNICAST_PROMISC; if (enable_multicast) promisc.flags |= I40E_FLAG_VF_MULTICAST_PROMISC; args.ops = I40E_VIRTCHNL_OP_CONFIG_PROMISCUOUS_MODE; args.in_args = (uint8_t *)&promisc; args.in_args_size = sizeof(promisc); args.out_buffer = vf->aq_resp; args.out_size = I40E_AQ_BUF_SZ; err = i40evf_execute_vf_cmd(dev, &args); if (err) PMD_DRV_LOG(ERR, "fail to execute command " "CONFIG_PROMISCUOUS_MODE"); return err; } /* Configure vlan and double vlan offload. Use flag to specify which part to configure */ static int i40evf_config_vlan_offload(struct rte_eth_dev *dev, bool enable_vlan_strip) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); int err; struct vf_cmd_info args; struct i40e_virtchnl_vlan_offload_info offload; offload.vsi_id = vf->vsi_res->vsi_id; offload.enable_vlan_strip = enable_vlan_strip; args.ops = (enum i40e_virtchnl_ops)I40E_VIRTCHNL_OP_CFG_VLAN_OFFLOAD; args.in_args = (uint8_t *)&offload; args.in_args_size = sizeof(offload); args.out_buffer = vf->aq_resp; args.out_size = I40E_AQ_BUF_SZ; err = i40evf_execute_vf_cmd(dev, &args); if (err) PMD_DRV_LOG(ERR, "fail to execute command CFG_VLAN_OFFLOAD"); return err; } static int i40evf_config_vlan_pvid(struct rte_eth_dev *dev, struct i40e_vsi_vlan_pvid_info *info) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); int err; struct vf_cmd_info args; struct i40e_virtchnl_pvid_info tpid_info; if (info == NULL) { PMD_DRV_LOG(ERR, "invalid parameters"); return I40E_ERR_PARAM; } memset(&tpid_info, 0, sizeof(tpid_info)); tpid_info.vsi_id = vf->vsi_res->vsi_id; (void)rte_memcpy(&tpid_info.info, info, sizeof(*info)); args.ops = (enum i40e_virtchnl_ops)I40E_VIRTCHNL_OP_CFG_VLAN_PVID; args.in_args = (uint8_t *)&tpid_info; args.in_args_size = sizeof(tpid_info); args.out_buffer = vf->aq_resp; args.out_size = I40E_AQ_BUF_SZ; err = i40evf_execute_vf_cmd(dev, &args); if (err) PMD_DRV_LOG(ERR, "fail to execute command CFG_VLAN_PVID"); return err; } static void i40evf_fill_virtchnl_vsi_txq_info(struct i40e_virtchnl_txq_info *txq_info, uint16_t vsi_id, uint16_t queue_id, uint16_t nb_txq, struct i40e_tx_queue *txq) { txq_info->vsi_id = vsi_id; txq_info->queue_id = queue_id; if (queue_id < nb_txq) { txq_info->ring_len = txq->nb_tx_desc; txq_info->dma_ring_addr = txq->tx_ring_phys_addr; } } static void i40evf_fill_virtchnl_vsi_rxq_info(struct i40e_virtchnl_rxq_info *rxq_info, uint16_t vsi_id, uint16_t queue_id, uint16_t nb_rxq, uint32_t max_pkt_size, struct i40e_rx_queue *rxq) { rxq_info->vsi_id = vsi_id; rxq_info->queue_id = queue_id; rxq_info->max_pkt_size = max_pkt_size; if (queue_id < nb_rxq) { rxq_info->ring_len = rxq->nb_rx_desc; rxq_info->dma_ring_addr = rxq->rx_ring_phys_addr; rxq_info->databuffer_size = (rte_pktmbuf_data_room_size(rxq->mp) - RTE_PKTMBUF_HEADROOM); } } /* It configures VSI queues to co-work with Linux PF host */ static int i40evf_configure_vsi_queues(struct rte_eth_dev *dev) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); struct i40e_rx_queue **rxq = (struct i40e_rx_queue **)dev->data->rx_queues; struct i40e_tx_queue **txq = (struct i40e_tx_queue **)dev->data->tx_queues; struct i40e_virtchnl_vsi_queue_config_info *vc_vqci; struct i40e_virtchnl_queue_pair_info *vc_qpi; struct vf_cmd_info args; uint16_t i, nb_qp = vf->num_queue_pairs; const uint32_t size = I40E_VIRTCHNL_CONFIG_VSI_QUEUES_SIZE(vc_vqci, nb_qp); uint8_t buff[size]; int ret; memset(buff, 0, sizeof(buff)); vc_vqci = (struct i40e_virtchnl_vsi_queue_config_info *)buff; vc_vqci->vsi_id = vf->vsi_res->vsi_id; vc_vqci->num_queue_pairs = nb_qp; for (i = 0, vc_qpi = vc_vqci->qpair; i < nb_qp; i++, vc_qpi++) { i40evf_fill_virtchnl_vsi_txq_info(&vc_qpi->txq, vc_vqci->vsi_id, i, dev->data->nb_tx_queues, txq[i]); i40evf_fill_virtchnl_vsi_rxq_info(&vc_qpi->rxq, vc_vqci->vsi_id, i, dev->data->nb_rx_queues, vf->max_pkt_len, rxq[i]); } memset(&args, 0, sizeof(args)); args.ops = I40E_VIRTCHNL_OP_CONFIG_VSI_QUEUES; args.in_args = (uint8_t *)vc_vqci; args.in_args_size = size; args.out_buffer = vf->aq_resp; args.out_size = I40E_AQ_BUF_SZ; ret = i40evf_execute_vf_cmd(dev, &args); if (ret) PMD_DRV_LOG(ERR, "Failed to execute command of " "I40E_VIRTCHNL_OP_CONFIG_VSI_QUEUES"); return ret; } /* It configures VSI queues to co-work with DPDK PF host */ static int i40evf_configure_vsi_queues_ext(struct rte_eth_dev *dev) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); struct i40e_rx_queue **rxq = (struct i40e_rx_queue **)dev->data->rx_queues; struct i40e_tx_queue **txq = (struct i40e_tx_queue **)dev->data->tx_queues; struct i40e_virtchnl_vsi_queue_config_ext_info *vc_vqcei; struct i40e_virtchnl_queue_pair_ext_info *vc_qpei; struct vf_cmd_info args; uint16_t i, nb_qp = vf->num_queue_pairs; const uint32_t size = I40E_VIRTCHNL_CONFIG_VSI_QUEUES_SIZE(vc_vqcei, nb_qp); uint8_t buff[size]; int ret; memset(buff, 0, sizeof(buff)); vc_vqcei = (struct i40e_virtchnl_vsi_queue_config_ext_info *)buff; vc_vqcei->vsi_id = vf->vsi_res->vsi_id; vc_vqcei->num_queue_pairs = nb_qp; vc_qpei = vc_vqcei->qpair; for (i = 0; i < nb_qp; i++, vc_qpei++) { i40evf_fill_virtchnl_vsi_txq_info(&vc_qpei->txq, vc_vqcei->vsi_id, i, dev->data->nb_tx_queues, txq[i]); i40evf_fill_virtchnl_vsi_rxq_info(&vc_qpei->rxq, vc_vqcei->vsi_id, i, dev->data->nb_rx_queues, vf->max_pkt_len, rxq[i]); if (i < dev->data->nb_rx_queues) /* * It adds extra info for configuring VSI queues, which * is needed to enable the configurable crc stripping * in VF. */ vc_qpei->rxq_ext.crcstrip = dev->data->dev_conf.rxmode.hw_strip_crc; } memset(&args, 0, sizeof(args)); args.ops = (enum i40e_virtchnl_ops)I40E_VIRTCHNL_OP_CONFIG_VSI_QUEUES_EXT; args.in_args = (uint8_t *)vc_vqcei; args.in_args_size = size; args.out_buffer = vf->aq_resp; args.out_size = I40E_AQ_BUF_SZ; ret = i40evf_execute_vf_cmd(dev, &args); if (ret) PMD_DRV_LOG(ERR, "Failed to execute command of " "I40E_VIRTCHNL_OP_CONFIG_VSI_QUEUES_EXT"); return ret; } static int i40evf_configure_queues(struct rte_eth_dev *dev) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); if (vf->version_major == I40E_DPDK_VERSION_MAJOR) /* To support DPDK PF host */ return i40evf_configure_vsi_queues_ext(dev); else /* To support Linux PF host */ return i40evf_configure_vsi_queues(dev); } static int i40evf_config_irq_map(struct rte_eth_dev *dev) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); struct vf_cmd_info args; uint8_t cmd_buffer[sizeof(struct i40e_virtchnl_irq_map_info) + \ sizeof(struct i40e_virtchnl_vector_map)]; struct i40e_virtchnl_irq_map_info *map_info; struct rte_pci_device *pci_dev = I40E_DEV_TO_PCI(dev); struct rte_intr_handle *intr_handle = &pci_dev->intr_handle; uint32_t vector_id; int i, err; if (rte_intr_allow_others(intr_handle)) { if (vf->version_major == I40E_DPDK_VERSION_MAJOR) vector_id = I40EVF_VSI_DEFAULT_MSIX_INTR; else vector_id = I40EVF_VSI_DEFAULT_MSIX_INTR_LNX; } else { vector_id = I40E_MISC_VEC_ID; } map_info = (struct i40e_virtchnl_irq_map_info *)cmd_buffer; map_info->num_vectors = 1; map_info->vecmap[0].rxitr_idx = I40E_ITR_INDEX_DEFAULT; map_info->vecmap[0].vsi_id = vf->vsi_res->vsi_id; /* Alway use default dynamic MSIX interrupt */ map_info->vecmap[0].vector_id = vector_id; /* Don't map any tx queue */ map_info->vecmap[0].txq_map = 0; map_info->vecmap[0].rxq_map = 0; for (i = 0; i < dev->data->nb_rx_queues; i++) { map_info->vecmap[0].rxq_map |= 1 << i; if (rte_intr_dp_is_en(intr_handle)) intr_handle->intr_vec[i] = vector_id; } args.ops = I40E_VIRTCHNL_OP_CONFIG_IRQ_MAP; args.in_args = (u8 *)cmd_buffer; args.in_args_size = sizeof(cmd_buffer); args.out_buffer = vf->aq_resp; args.out_size = I40E_AQ_BUF_SZ; err = i40evf_execute_vf_cmd(dev, &args); if (err) PMD_DRV_LOG(ERR, "fail to execute command OP_ENABLE_QUEUES"); return err; } static int i40evf_switch_queue(struct rte_eth_dev *dev, bool isrx, uint16_t qid, bool on) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); struct i40e_virtchnl_queue_select queue_select; int err; struct vf_cmd_info args; memset(&queue_select, 0, sizeof(queue_select)); queue_select.vsi_id = vf->vsi_res->vsi_id; if (isrx) queue_select.rx_queues |= 1 << qid; else queue_select.tx_queues |= 1 << qid; if (on) args.ops = I40E_VIRTCHNL_OP_ENABLE_QUEUES; else args.ops = I40E_VIRTCHNL_OP_DISABLE_QUEUES; args.in_args = (u8 *)&queue_select; args.in_args_size = sizeof(queue_select); args.out_buffer = vf->aq_resp; args.out_size = I40E_AQ_BUF_SZ; err = i40evf_execute_vf_cmd(dev, &args); if (err) PMD_DRV_LOG(ERR, "fail to switch %s %u %s", isrx ? "RX" : "TX", qid, on ? "on" : "off"); return err; } static int i40evf_start_queues(struct rte_eth_dev *dev) { struct rte_eth_dev_data *dev_data = dev->data; int i; struct i40e_rx_queue *rxq; struct i40e_tx_queue *txq; for (i = 0; i < dev->data->nb_rx_queues; i++) { rxq = dev_data->rx_queues[i]; if (rxq->rx_deferred_start) continue; if (i40evf_dev_rx_queue_start(dev, i) != 0) { PMD_DRV_LOG(ERR, "Fail to start queue %u", i); return -1; } } for (i = 0; i < dev->data->nb_tx_queues; i++) { txq = dev_data->tx_queues[i]; if (txq->tx_deferred_start) continue; if (i40evf_dev_tx_queue_start(dev, i) != 0) { PMD_DRV_LOG(ERR, "Fail to start queue %u", i); return -1; } } return 0; } static int i40evf_stop_queues(struct rte_eth_dev *dev) { int i; /* Stop TX queues first */ for (i = 0; i < dev->data->nb_tx_queues; i++) { if (i40evf_dev_tx_queue_stop(dev, i) != 0) { PMD_DRV_LOG(ERR, "Fail to stop queue %u", i); return -1; } } /* Then stop RX queues */ for (i = 0; i < dev->data->nb_rx_queues; i++) { if (i40evf_dev_rx_queue_stop(dev, i) != 0) { PMD_DRV_LOG(ERR, "Fail to stop queue %u", i); return -1; } } return 0; } static void i40evf_add_mac_addr(struct rte_eth_dev *dev, struct ether_addr *addr, __rte_unused uint32_t index, __rte_unused uint32_t pool) { struct i40e_virtchnl_ether_addr_list *list; struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); uint8_t cmd_buffer[sizeof(struct i40e_virtchnl_ether_addr_list) + \ sizeof(struct i40e_virtchnl_ether_addr)]; int err; struct vf_cmd_info args; if (i40e_validate_mac_addr(addr->addr_bytes) != I40E_SUCCESS) { PMD_DRV_LOG(ERR, "Invalid mac:%x:%x:%x:%x:%x:%x", addr->addr_bytes[0], addr->addr_bytes[1], addr->addr_bytes[2], addr->addr_bytes[3], addr->addr_bytes[4], addr->addr_bytes[5]); return; } list = (struct i40e_virtchnl_ether_addr_list *)cmd_buffer; list->vsi_id = vf->vsi_res->vsi_id; list->num_elements = 1; (void)rte_memcpy(list->list[0].addr, addr->addr_bytes, sizeof(addr->addr_bytes)); args.ops = I40E_VIRTCHNL_OP_ADD_ETHER_ADDRESS; args.in_args = cmd_buffer; args.in_args_size = sizeof(cmd_buffer); args.out_buffer = vf->aq_resp; args.out_size = I40E_AQ_BUF_SZ; err = i40evf_execute_vf_cmd(dev, &args); if (err) PMD_DRV_LOG(ERR, "fail to execute command " "OP_ADD_ETHER_ADDRESS"); return; } static void i40evf_del_mac_addr_by_addr(struct rte_eth_dev *dev, struct ether_addr *addr) { struct i40e_virtchnl_ether_addr_list *list; struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); uint8_t cmd_buffer[sizeof(struct i40e_virtchnl_ether_addr_list) + \ sizeof(struct i40e_virtchnl_ether_addr)]; int err; struct vf_cmd_info args; if (i40e_validate_mac_addr(addr->addr_bytes) != I40E_SUCCESS) { PMD_DRV_LOG(ERR, "Invalid mac:%x-%x-%x-%x-%x-%x", addr->addr_bytes[0], addr->addr_bytes[1], addr->addr_bytes[2], addr->addr_bytes[3], addr->addr_bytes[4], addr->addr_bytes[5]); return; } list = (struct i40e_virtchnl_ether_addr_list *)cmd_buffer; list->vsi_id = vf->vsi_res->vsi_id; list->num_elements = 1; (void)rte_memcpy(list->list[0].addr, addr->addr_bytes, sizeof(addr->addr_bytes)); args.ops = I40E_VIRTCHNL_OP_DEL_ETHER_ADDRESS; args.in_args = cmd_buffer; args.in_args_size = sizeof(cmd_buffer); args.out_buffer = vf->aq_resp; args.out_size = I40E_AQ_BUF_SZ; err = i40evf_execute_vf_cmd(dev, &args); if (err) PMD_DRV_LOG(ERR, "fail to execute command " "OP_DEL_ETHER_ADDRESS"); return; } static void i40evf_del_mac_addr(struct rte_eth_dev *dev, uint32_t index) { struct rte_eth_dev_data *data = dev->data; struct ether_addr *addr; addr = &data->mac_addrs[index]; i40evf_del_mac_addr_by_addr(dev, addr); } static int i40evf_update_stats(struct rte_eth_dev *dev, struct i40e_eth_stats **pstats) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); struct i40e_virtchnl_queue_select q_stats; int err; struct vf_cmd_info args; memset(&q_stats, 0, sizeof(q_stats)); q_stats.vsi_id = vf->vsi_res->vsi_id; args.ops = I40E_VIRTCHNL_OP_GET_STATS; args.in_args = (u8 *)&q_stats; args.in_args_size = sizeof(q_stats); args.out_buffer = vf->aq_resp; args.out_size = I40E_AQ_BUF_SZ; err = i40evf_execute_vf_cmd(dev, &args); if (err) { PMD_DRV_LOG(ERR, "fail to execute command OP_GET_STATS"); *pstats = NULL; return err; } *pstats = (struct i40e_eth_stats *)args.out_buffer; return 0; } static int i40evf_get_statistics(struct rte_eth_dev *dev, struct rte_eth_stats *stats) { int ret; struct i40e_eth_stats *pstats = NULL; ret = i40evf_update_stats(dev, &pstats); if (ret != 0) return 0; stats->ipackets = pstats->rx_unicast + pstats->rx_multicast + pstats->rx_broadcast; stats->opackets = pstats->tx_broadcast + pstats->tx_multicast + pstats->tx_unicast; stats->imissed = pstats->rx_discards; stats->oerrors = pstats->tx_errors + pstats->tx_discards; stats->ibytes = pstats->rx_bytes; stats->obytes = pstats->tx_bytes; return 0; } static void i40evf_dev_xstats_reset(struct rte_eth_dev *dev) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); struct i40e_eth_stats *pstats = NULL; /* read stat values to clear hardware registers */ i40evf_update_stats(dev, &pstats); /* set stats offset base on current values */ vf->vsi.eth_stats_offset = vf->vsi.eth_stats; } static int i40evf_dev_xstats_get_names(__rte_unused struct rte_eth_dev *dev, struct rte_eth_xstat_name *xstats_names, __rte_unused unsigned limit) { unsigned i; if (xstats_names != NULL) for (i = 0; i < I40EVF_NB_XSTATS; i++) { snprintf(xstats_names[i].name, sizeof(xstats_names[i].name), "%s", rte_i40evf_stats_strings[i].name); } return I40EVF_NB_XSTATS; } static int i40evf_dev_xstats_get(struct rte_eth_dev *dev, struct rte_eth_xstat *xstats, unsigned n) { int ret; unsigned i; struct i40e_eth_stats *pstats = NULL; if (n < I40EVF_NB_XSTATS) return I40EVF_NB_XSTATS; ret = i40evf_update_stats(dev, &pstats); if (ret != 0) return 0; if (!xstats) return 0; /* loop over xstats array and values from pstats */ for (i = 0; i < I40EVF_NB_XSTATS; i++) { xstats[i].id = i; xstats[i].value = *(uint64_t *)(((char *)pstats) + rte_i40evf_stats_strings[i].offset); } return I40EVF_NB_XSTATS; } static int i40evf_add_vlan(struct rte_eth_dev *dev, uint16_t vlanid) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); struct i40e_virtchnl_vlan_filter_list *vlan_list; uint8_t cmd_buffer[sizeof(struct i40e_virtchnl_vlan_filter_list) + sizeof(uint16_t)]; int err; struct vf_cmd_info args; vlan_list = (struct i40e_virtchnl_vlan_filter_list *)cmd_buffer; vlan_list->vsi_id = vf->vsi_res->vsi_id; vlan_list->num_elements = 1; vlan_list->vlan_id[0] = vlanid; args.ops = I40E_VIRTCHNL_OP_ADD_VLAN; args.in_args = (u8 *)&cmd_buffer; args.in_args_size = sizeof(cmd_buffer); args.out_buffer = vf->aq_resp; args.out_size = I40E_AQ_BUF_SZ; err = i40evf_execute_vf_cmd(dev, &args); if (err) PMD_DRV_LOG(ERR, "fail to execute command OP_ADD_VLAN"); return err; } static int i40evf_del_vlan(struct rte_eth_dev *dev, uint16_t vlanid) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); struct i40e_virtchnl_vlan_filter_list *vlan_list; uint8_t cmd_buffer[sizeof(struct i40e_virtchnl_vlan_filter_list) + sizeof(uint16_t)]; int err; struct vf_cmd_info args; vlan_list = (struct i40e_virtchnl_vlan_filter_list *)cmd_buffer; vlan_list->vsi_id = vf->vsi_res->vsi_id; vlan_list->num_elements = 1; vlan_list->vlan_id[0] = vlanid; args.ops = I40E_VIRTCHNL_OP_DEL_VLAN; args.in_args = (u8 *)&cmd_buffer; args.in_args_size = sizeof(cmd_buffer); args.out_buffer = vf->aq_resp; args.out_size = I40E_AQ_BUF_SZ; err = i40evf_execute_vf_cmd(dev, &args); if (err) PMD_DRV_LOG(ERR, "fail to execute command OP_DEL_VLAN"); return err; } static const struct rte_pci_id pci_id_i40evf_map[] = { { RTE_PCI_DEVICE(I40E_INTEL_VENDOR_ID, I40E_DEV_ID_VF) }, { RTE_PCI_DEVICE(I40E_INTEL_VENDOR_ID, I40E_DEV_ID_VF_HV) }, { RTE_PCI_DEVICE(I40E_INTEL_VENDOR_ID, I40E_DEV_ID_X722_A0_VF) }, { RTE_PCI_DEVICE(I40E_INTEL_VENDOR_ID, I40E_DEV_ID_X722_VF) }, { .vendor_id = 0, /* sentinel */ }, }; static inline int i40evf_dev_atomic_write_link_status(struct rte_eth_dev *dev, struct rte_eth_link *link) { struct rte_eth_link *dst = &(dev->data->dev_link); struct rte_eth_link *src = link; if (rte_atomic64_cmpset((uint64_t *)dst, *(uint64_t *)dst, *(uint64_t *)src) == 0) return -1; return 0; } /* Disable IRQ0 */ static inline void i40evf_disable_irq0(struct i40e_hw *hw) { /* Disable all interrupt types */ I40E_WRITE_REG(hw, I40E_VFINT_ICR0_ENA1, 0); I40E_WRITE_REG(hw, I40E_VFINT_DYN_CTL01, I40E_VFINT_DYN_CTL01_ITR_INDX_MASK); I40EVF_WRITE_FLUSH(hw); } /* Enable IRQ0 */ static inline void i40evf_enable_irq0(struct i40e_hw *hw) { /* Enable admin queue interrupt trigger */ uint32_t val; i40evf_disable_irq0(hw); val = I40E_READ_REG(hw, I40E_VFINT_ICR0_ENA1); val |= I40E_VFINT_ICR0_ENA1_ADMINQ_MASK | I40E_VFINT_ICR0_ENA1_LINK_STAT_CHANGE_MASK; I40E_WRITE_REG(hw, I40E_VFINT_ICR0_ENA1, val); I40E_WRITE_REG(hw, I40E_VFINT_DYN_CTL01, I40E_VFINT_DYN_CTL01_INTENA_MASK | I40E_VFINT_DYN_CTL01_CLEARPBA_MASK | I40E_VFINT_DYN_CTL01_ITR_INDX_MASK); I40EVF_WRITE_FLUSH(hw); } static int i40evf_reset_vf(struct i40e_hw *hw) { int i, reset; if (i40e_vf_reset(hw) != I40E_SUCCESS) { PMD_INIT_LOG(ERR, "Reset VF NIC failed"); return -1; } /** * After issuing vf reset command to pf, pf won't necessarily * reset vf, it depends on what state it exactly is. If it's not * initialized yet, it won't have vf reset since it's in a certain * state. If not, it will try to reset. Even vf is reset, pf will * set I40E_VFGEN_RSTAT to COMPLETE first, then wait 10ms and set * it to ACTIVE. In this duration, vf may not catch the moment that * COMPLETE is set. So, for vf, we'll try to wait a long time. */ rte_delay_ms(200); for (i = 0; i < MAX_RESET_WAIT_CNT; i++) { reset = rd32(hw, I40E_VFGEN_RSTAT) & I40E_VFGEN_RSTAT_VFR_STATE_MASK; reset = reset >> I40E_VFGEN_RSTAT_VFR_STATE_SHIFT; if (I40E_VFR_COMPLETED == reset || I40E_VFR_VFACTIVE == reset) break; else rte_delay_ms(50); } if (i >= MAX_RESET_WAIT_CNT) { PMD_INIT_LOG(ERR, "Reset VF NIC failed"); return -1; } return 0; } static int i40evf_init_vf(struct rte_eth_dev *dev) { int i, err, bufsz; struct i40e_hw *hw = I40E_DEV_PRIVATE_TO_HW(dev->data->dev_private); struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); uint16_t interval = i40e_calc_itr_interval(I40E_QUEUE_ITR_INTERVAL_MAX); vf->adapter = I40E_DEV_PRIVATE_TO_ADAPTER(dev->data->dev_private); vf->dev_data = dev->data; err = i40e_set_mac_type(hw); if (err) { PMD_INIT_LOG(ERR, "set_mac_type failed: %d", err); goto err; } i40e_init_adminq_parameter(hw); err = i40e_init_adminq(hw); if (err) { PMD_INIT_LOG(ERR, "init_adminq failed: %d", err); goto err; } /* Reset VF and wait until it's complete */ if (i40evf_reset_vf(hw)) { PMD_INIT_LOG(ERR, "reset NIC failed"); goto err_aq; } /* VF reset, shutdown admin queue and initialize again */ if (i40e_shutdown_adminq(hw) != I40E_SUCCESS) { PMD_INIT_LOG(ERR, "i40e_shutdown_adminq failed"); return -1; } i40e_init_adminq_parameter(hw); if (i40e_init_adminq(hw) != I40E_SUCCESS) { PMD_INIT_LOG(ERR, "init_adminq failed"); return -1; } vf->aq_resp = rte_zmalloc("vf_aq_resp", I40E_AQ_BUF_SZ, 0); if (!vf->aq_resp) { PMD_INIT_LOG(ERR, "unable to allocate vf_aq_resp memory"); goto err_aq; } if (i40evf_check_api_version(dev) != 0) { PMD_INIT_LOG(ERR, "check_api version failed"); goto err_aq; } bufsz = sizeof(struct i40e_virtchnl_vf_resource) + (I40E_MAX_VF_VSI * sizeof(struct i40e_virtchnl_vsi_resource)); vf->vf_res = rte_zmalloc("vf_res", bufsz, 0); if (!vf->vf_res) { PMD_INIT_LOG(ERR, "unable to allocate vf_res memory"); goto err_aq; } if (i40evf_get_vf_resource(dev) != 0) { PMD_INIT_LOG(ERR, "i40evf_get_vf_config failed"); goto err_alloc; } /* got VF config message back from PF, now we can parse it */ for (i = 0; i < vf->vf_res->num_vsis; i++) { if (vf->vf_res->vsi_res[i].vsi_type == I40E_VSI_SRIOV) vf->vsi_res = &vf->vf_res->vsi_res[i]; } if (!vf->vsi_res) { PMD_INIT_LOG(ERR, "no LAN VSI found"); goto err_alloc; } if (hw->mac.type == I40E_MAC_X722_VF) vf->flags = I40E_FLAG_RSS_AQ_CAPABLE; vf->vsi.vsi_id = vf->vsi_res->vsi_id; vf->vsi.type = vf->vsi_res->vsi_type; vf->vsi.nb_qps = vf->vsi_res->num_queue_pairs; vf->vsi.adapter = I40E_DEV_PRIVATE_TO_ADAPTER(dev->data->dev_private); /* Store the MAC address configured by host, or generate random one */ if (is_valid_assigned_ether_addr((struct ether_addr *)hw->mac.addr)) vf->flags |= I40E_FLAG_VF_MAC_BY_PF; else eth_random_addr(hw->mac.addr); /* Generate a random one */ /* If the PF host is not DPDK, set the interval of ITR0 to max*/ if (vf->version_major != I40E_DPDK_VERSION_MAJOR) { I40E_WRITE_REG(hw, I40E_VFINT_DYN_CTL01, (I40E_ITR_INDEX_DEFAULT << I40E_VFINT_DYN_CTL0_ITR_INDX_SHIFT) | (interval << I40E_VFINT_DYN_CTL0_INTERVAL_SHIFT)); I40EVF_WRITE_FLUSH(hw); } return 0; err_alloc: rte_free(vf->vf_res); err_aq: i40e_shutdown_adminq(hw); /* ignore error */ err: return -1; } static int i40evf_uninit_vf(struct rte_eth_dev *dev) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); struct i40e_hw *hw = I40E_DEV_PRIVATE_TO_HW(dev->data->dev_private); PMD_INIT_FUNC_TRACE(); if (hw->adapter_stopped == 0) i40evf_dev_close(dev); rte_free(vf->vf_res); vf->vf_res = NULL; rte_free(vf->aq_resp); vf->aq_resp = NULL; return 0; } static void i40evf_handle_pf_event(__rte_unused struct rte_eth_dev *dev, uint8_t *msg, __rte_unused uint16_t msglen) { struct i40e_virtchnl_pf_event *pf_msg = (struct i40e_virtchnl_pf_event *)msg; struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); switch (pf_msg->event) { case I40E_VIRTCHNL_EVENT_RESET_IMPENDING: PMD_DRV_LOG(DEBUG, "VIRTCHNL_EVENT_RESET_IMPENDING event"); _rte_eth_dev_callback_process(dev, RTE_ETH_EVENT_INTR_RESET, NULL); break; case I40E_VIRTCHNL_EVENT_LINK_CHANGE: PMD_DRV_LOG(DEBUG, "VIRTCHNL_EVENT_LINK_CHANGE event"); vf->link_up = pf_msg->event_data.link_event.link_status; vf->link_speed = pf_msg->event_data.link_event.link_speed; break; case I40E_VIRTCHNL_EVENT_PF_DRIVER_CLOSE: PMD_DRV_LOG(DEBUG, "VIRTCHNL_EVENT_PF_DRIVER_CLOSE event"); break; default: PMD_DRV_LOG(ERR, " unknown event received %u", pf_msg->event); break; } } static void i40evf_handle_aq_msg(struct rte_eth_dev *dev) { struct i40e_hw *hw = I40E_DEV_PRIVATE_TO_HW(dev->data->dev_private); struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); struct i40e_arq_event_info info; uint16_t pending, aq_opc; enum i40e_virtchnl_ops msg_opc; enum i40e_status_code msg_ret; int ret; info.buf_len = I40E_AQ_BUF_SZ; if (!vf->aq_resp) { PMD_DRV_LOG(ERR, "Buffer for adminq resp should not be NULL"); return; } info.msg_buf = vf->aq_resp; pending = 1; while (pending) { ret = i40e_clean_arq_element(hw, &info, &pending); if (ret != I40E_SUCCESS) { PMD_DRV_LOG(INFO, "Failed to read msg from AdminQ," "ret: %d", ret); break; } aq_opc = rte_le_to_cpu_16(info.desc.opcode); /* For the message sent from pf to vf, opcode is stored in * cookie_high of struct i40e_aq_desc, while return error code * are stored in cookie_low, Which is done by * i40e_aq_send_msg_to_vf in PF driver.*/ msg_opc = (enum i40e_virtchnl_ops)rte_le_to_cpu_32( info.desc.cookie_high); msg_ret = (enum i40e_status_code)rte_le_to_cpu_32( info.desc.cookie_low); switch (aq_opc) { case i40e_aqc_opc_send_msg_to_vf: if (msg_opc == I40E_VIRTCHNL_OP_EVENT) /* process event*/ i40evf_handle_pf_event(dev, info.msg_buf, info.msg_len); else { /* read message and it's expected one */ if (msg_opc == vf->pend_cmd) { vf->cmd_retval = msg_ret; /* prevent compiler reordering */ rte_compiler_barrier(); _clear_cmd(vf); } else PMD_DRV_LOG(ERR, "command mismatch," "expect %u, get %u", vf->pend_cmd, msg_opc); PMD_DRV_LOG(DEBUG, "adminq response is received," " opcode = %d", msg_opc); } break; default: PMD_DRV_LOG(ERR, "Request %u is not supported yet", aq_opc); break; } } } /** * Interrupt handler triggered by NIC for handling * specific interrupt. Only adminq interrupt is processed in VF. * * @param handle * Pointer to interrupt handle. * @param param * The address of parameter (struct rte_eth_dev *) regsitered before. * * @return * void */ static void i40evf_dev_interrupt_handler(struct rte_intr_handle *intr_handle, void *param) { struct rte_eth_dev *dev = (struct rte_eth_dev *)param; struct i40e_hw *hw = I40E_DEV_PRIVATE_TO_HW(dev->data->dev_private); uint32_t icr0; i40evf_disable_irq0(hw); /* read out interrupt causes */ icr0 = I40E_READ_REG(hw, I40E_VFINT_ICR01); /* No interrupt event indicated */ if (!(icr0 & I40E_VFINT_ICR01_INTEVENT_MASK)) { PMD_DRV_LOG(DEBUG, "No interrupt event, nothing to do"); goto done; } if (icr0 & I40E_VFINT_ICR01_ADMINQ_MASK) { PMD_DRV_LOG(DEBUG, "ICR01_ADMINQ is reported"); i40evf_handle_aq_msg(dev); } /* Link Status Change interrupt */ if (icr0 & I40E_VFINT_ICR01_LINK_STAT_CHANGE_MASK) PMD_DRV_LOG(DEBUG, "LINK_STAT_CHANGE is reported," " do nothing"); done: i40evf_enable_irq0(hw); rte_intr_enable(intr_handle); } static int i40evf_dev_init(struct rte_eth_dev *eth_dev) { struct i40e_hw *hw = I40E_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private); struct rte_pci_device *pci_dev = I40E_DEV_TO_PCI(eth_dev); PMD_INIT_FUNC_TRACE(); /* assign ops func pointer */ eth_dev->dev_ops = &i40evf_eth_dev_ops; eth_dev->rx_pkt_burst = &i40e_recv_pkts; eth_dev->tx_pkt_burst = &i40e_xmit_pkts; /* * For secondary processes, we don't initialise any further as primary * has already done this work. */ if (rte_eal_process_type() != RTE_PROC_PRIMARY){ i40e_set_rx_function(eth_dev); i40e_set_tx_function(eth_dev); return 0; } rte_eth_copy_pci_info(eth_dev, pci_dev); eth_dev->data->dev_flags |= RTE_ETH_DEV_DETACHABLE; hw->vendor_id = pci_dev->id.vendor_id; hw->device_id = pci_dev->id.device_id; hw->subsystem_vendor_id = pci_dev->id.subsystem_vendor_id; hw->subsystem_device_id = pci_dev->id.subsystem_device_id; hw->bus.device = pci_dev->addr.devid; hw->bus.func = pci_dev->addr.function; hw->hw_addr = (void *)pci_dev->mem_resource[0].addr; hw->adapter_stopped = 0; if(i40evf_init_vf(eth_dev) != 0) { PMD_INIT_LOG(ERR, "Init vf failed"); return -1; } /* register callback func to eal lib */ rte_intr_callback_register(&pci_dev->intr_handle, i40evf_dev_interrupt_handler, (void *)eth_dev); /* enable uio intr after callback register */ rte_intr_enable(&pci_dev->intr_handle); /* configure and enable device interrupt */ i40evf_enable_irq0(hw); /* copy mac addr */ eth_dev->data->mac_addrs = rte_zmalloc("i40evf_mac", ETHER_ADDR_LEN * I40E_NUM_MACADDR_MAX, 0); if (eth_dev->data->mac_addrs == NULL) { PMD_INIT_LOG(ERR, "Failed to allocate %d bytes needed to" " store MAC addresses", ETHER_ADDR_LEN * I40E_NUM_MACADDR_MAX); return -ENOMEM; } ether_addr_copy((struct ether_addr *)hw->mac.addr, &eth_dev->data->mac_addrs[0]); return 0; } static int i40evf_dev_uninit(struct rte_eth_dev *eth_dev) { PMD_INIT_FUNC_TRACE(); if (rte_eal_process_type() != RTE_PROC_PRIMARY) return -EPERM; eth_dev->dev_ops = NULL; eth_dev->rx_pkt_burst = NULL; eth_dev->tx_pkt_burst = NULL; if (i40evf_uninit_vf(eth_dev) != 0) { PMD_INIT_LOG(ERR, "i40evf_uninit_vf failed"); return -1; } rte_free(eth_dev->data->mac_addrs); eth_dev->data->mac_addrs = NULL; return 0; } /* * virtual function driver struct */ static struct eth_driver rte_i40evf_pmd = { .pci_drv = { .id_table = pci_id_i40evf_map, .drv_flags = RTE_PCI_DRV_NEED_MAPPING, .probe = rte_eth_dev_pci_probe, .remove = rte_eth_dev_pci_remove, }, .eth_dev_init = i40evf_dev_init, .eth_dev_uninit = i40evf_dev_uninit, .dev_private_size = sizeof(struct i40e_adapter), }; RTE_PMD_REGISTER_PCI(net_i40e_vf, rte_i40evf_pmd.pci_drv); RTE_PMD_REGISTER_PCI_TABLE(net_i40e_vf, pci_id_i40evf_map); RTE_PMD_REGISTER_KMOD_DEP(net_i40e_vf, "* igb_uio | vfio"); static int i40evf_dev_configure(struct rte_eth_dev *dev) { struct i40e_adapter *ad = I40E_DEV_PRIVATE_TO_ADAPTER(dev->data->dev_private); struct rte_eth_conf *conf = &dev->data->dev_conf; struct i40e_vf *vf; /* Initialize to TRUE. If any of Rx queues doesn't meet the bulk * allocation or vector Rx preconditions we will reset it. */ ad->rx_bulk_alloc_allowed = true; ad->rx_vec_allowed = true; ad->tx_simple_allowed = true; ad->tx_vec_allowed = true; /* For non-DPDK PF drivers, VF has no ability to disable HW * CRC strip, and is implicitly enabled by the PF. */ if (!conf->rxmode.hw_strip_crc) { vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); if ((vf->version_major == I40E_VIRTCHNL_VERSION_MAJOR) && (vf->version_minor <= I40E_VIRTCHNL_VERSION_MINOR)) { /* Peer is running non-DPDK PF driver. */ PMD_INIT_LOG(ERR, "VF can't disable HW CRC Strip"); return -EINVAL; } } return i40evf_init_vlan(dev); } static int i40evf_init_vlan(struct rte_eth_dev *dev) { struct rte_eth_dev_data *data = dev->data; int ret; /* Apply vlan offload setting */ i40evf_vlan_offload_set(dev, ETH_VLAN_STRIP_MASK); /* Apply pvid setting */ ret = i40evf_vlan_pvid_set(dev, data->dev_conf.txmode.pvid, data->dev_conf.txmode.hw_vlan_insert_pvid); return ret; } static void i40evf_vlan_offload_set(struct rte_eth_dev *dev, int mask) { bool enable_vlan_strip = 0; struct rte_eth_conf *dev_conf = &dev->data->dev_conf; struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); /* Linux pf host doesn't support vlan offload yet */ if (vf->version_major == I40E_DPDK_VERSION_MAJOR) { /* Vlan stripping setting */ if (mask & ETH_VLAN_STRIP_MASK) { /* Enable or disable VLAN stripping */ if (dev_conf->rxmode.hw_vlan_strip) enable_vlan_strip = 1; else enable_vlan_strip = 0; i40evf_config_vlan_offload(dev, enable_vlan_strip); } } } static int i40evf_vlan_pvid_set(struct rte_eth_dev *dev, uint16_t pvid, int on) { struct rte_eth_conf *dev_conf = &dev->data->dev_conf; struct i40e_vsi_vlan_pvid_info info; struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); memset(&info, 0, sizeof(info)); info.on = on; /* Linux pf host don't support vlan offload yet */ if (vf->version_major == I40E_DPDK_VERSION_MAJOR) { if (info.on) info.config.pvid = pvid; else { info.config.reject.tagged = dev_conf->txmode.hw_vlan_reject_tagged; info.config.reject.untagged = dev_conf->txmode.hw_vlan_reject_untagged; } return i40evf_config_vlan_pvid(dev, &info); } return 0; } static int i40evf_dev_rx_queue_start(struct rte_eth_dev *dev, uint16_t rx_queue_id) { struct i40e_rx_queue *rxq; int err = 0; struct i40e_hw *hw = I40E_DEV_PRIVATE_TO_HW(dev->data->dev_private); PMD_INIT_FUNC_TRACE(); if (rx_queue_id < dev->data->nb_rx_queues) { rxq = dev->data->rx_queues[rx_queue_id]; err = i40e_alloc_rx_queue_mbufs(rxq); if (err) { PMD_DRV_LOG(ERR, "Failed to allocate RX queue mbuf"); return err; } rte_wmb(); /* Init the RX tail register. */ I40E_PCI_REG_WRITE(rxq->qrx_tail, rxq->nb_rx_desc - 1); I40EVF_WRITE_FLUSH(hw); /* Ready to switch the queue on */ err = i40evf_switch_queue(dev, TRUE, rx_queue_id, TRUE); if (err) PMD_DRV_LOG(ERR, "Failed to switch RX queue %u on", rx_queue_id); else dev->data->rx_queue_state[rx_queue_id] = RTE_ETH_QUEUE_STATE_STARTED; } return err; } static int i40evf_dev_rx_queue_stop(struct rte_eth_dev *dev, uint16_t rx_queue_id) { struct i40e_rx_queue *rxq; int err; if (rx_queue_id < dev->data->nb_rx_queues) { rxq = dev->data->rx_queues[rx_queue_id]; err = i40evf_switch_queue(dev, TRUE, rx_queue_id, FALSE); if (err) { PMD_DRV_LOG(ERR, "Failed to switch RX queue %u off", rx_queue_id); return err; } i40e_rx_queue_release_mbufs(rxq); i40e_reset_rx_queue(rxq); dev->data->rx_queue_state[rx_queue_id] = RTE_ETH_QUEUE_STATE_STOPPED; } return 0; } static int i40evf_dev_tx_queue_start(struct rte_eth_dev *dev, uint16_t tx_queue_id) { int err = 0; PMD_INIT_FUNC_TRACE(); if (tx_queue_id < dev->data->nb_tx_queues) { /* Ready to switch the queue on */ err = i40evf_switch_queue(dev, FALSE, tx_queue_id, TRUE); if (err) PMD_DRV_LOG(ERR, "Failed to switch TX queue %u on", tx_queue_id); else dev->data->tx_queue_state[tx_queue_id] = RTE_ETH_QUEUE_STATE_STARTED; } return err; } static int i40evf_dev_tx_queue_stop(struct rte_eth_dev *dev, uint16_t tx_queue_id) { struct i40e_tx_queue *txq; int err; if (tx_queue_id < dev->data->nb_tx_queues) { txq = dev->data->tx_queues[tx_queue_id]; err = i40evf_switch_queue(dev, FALSE, tx_queue_id, FALSE); if (err) { PMD_DRV_LOG(ERR, "Failed to switch TX queue %u off", tx_queue_id); return err; } i40e_tx_queue_release_mbufs(txq); i40e_reset_tx_queue(txq); dev->data->tx_queue_state[tx_queue_id] = RTE_ETH_QUEUE_STATE_STOPPED; } return 0; } static int i40evf_vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on) { int ret; if (on) ret = i40evf_add_vlan(dev, vlan_id); else ret = i40evf_del_vlan(dev,vlan_id); return ret; } static int i40evf_rxq_init(struct rte_eth_dev *dev, struct i40e_rx_queue *rxq) { struct i40e_hw *hw = I40E_DEV_PRIVATE_TO_HW(dev->data->dev_private); struct rte_eth_dev_data *dev_data = dev->data; struct rte_pktmbuf_pool_private *mbp_priv; uint16_t buf_size, len; rxq->qrx_tail = hw->hw_addr + I40E_QRX_TAIL1(rxq->queue_id); I40E_PCI_REG_WRITE(rxq->qrx_tail, rxq->nb_rx_desc - 1); I40EVF_WRITE_FLUSH(hw); /* Calculate the maximum packet length allowed */ mbp_priv = rte_mempool_get_priv(rxq->mp); buf_size = (uint16_t)(mbp_priv->mbuf_data_room_size - RTE_PKTMBUF_HEADROOM); rxq->hs_mode = i40e_header_split_none; rxq->rx_hdr_len = 0; rxq->rx_buf_len = RTE_ALIGN(buf_size, (1 << I40E_RXQ_CTX_DBUFF_SHIFT)); len = rxq->rx_buf_len * I40E_MAX_CHAINED_RX_BUFFERS; rxq->max_pkt_len = RTE_MIN(len, dev_data->dev_conf.rxmode.max_rx_pkt_len); /** * Check if the jumbo frame and maximum packet length are set correctly */ if (dev_data->dev_conf.rxmode.jumbo_frame == 1) { if (rxq->max_pkt_len <= ETHER_MAX_LEN || rxq->max_pkt_len > I40E_FRAME_SIZE_MAX) { PMD_DRV_LOG(ERR, "maximum packet length must be " "larger than %u and smaller than %u, as jumbo " "frame is enabled", (uint32_t)ETHER_MAX_LEN, (uint32_t)I40E_FRAME_SIZE_MAX); return I40E_ERR_CONFIG; } } else { if (rxq->max_pkt_len < ETHER_MIN_LEN || rxq->max_pkt_len > ETHER_MAX_LEN) { PMD_DRV_LOG(ERR, "maximum packet length must be " "larger than %u and smaller than %u, as jumbo " "frame is disabled", (uint32_t)ETHER_MIN_LEN, (uint32_t)ETHER_MAX_LEN); return I40E_ERR_CONFIG; } } if (dev_data->dev_conf.rxmode.enable_scatter || (rxq->max_pkt_len + 2 * I40E_VLAN_TAG_SIZE) > buf_size) { dev_data->scattered_rx = 1; } return 0; } static int i40evf_rx_init(struct rte_eth_dev *dev) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); uint16_t i; int ret = I40E_SUCCESS; struct i40e_rx_queue **rxq = (struct i40e_rx_queue **)dev->data->rx_queues; i40evf_config_rss(vf); for (i = 0; i < dev->data->nb_rx_queues; i++) { if (!rxq[i] || !rxq[i]->q_set) continue; ret = i40evf_rxq_init(dev, rxq[i]); if (ret != I40E_SUCCESS) break; } if (ret == I40E_SUCCESS) i40e_set_rx_function(dev); return ret; } static void i40evf_tx_init(struct rte_eth_dev *dev) { uint16_t i; struct i40e_tx_queue **txq = (struct i40e_tx_queue **)dev->data->tx_queues; struct i40e_hw *hw = I40E_DEV_PRIVATE_TO_HW(dev->data->dev_private); for (i = 0; i < dev->data->nb_tx_queues; i++) txq[i]->qtx_tail = hw->hw_addr + I40E_QTX_TAIL1(i); i40e_set_tx_function(dev); } static inline void i40evf_enable_queues_intr(struct rte_eth_dev *dev) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); struct i40e_hw *hw = I40E_DEV_PRIVATE_TO_HW(dev->data->dev_private); struct rte_pci_device *pci_dev = I40E_DEV_TO_PCI(dev); struct rte_intr_handle *intr_handle = &pci_dev->intr_handle; if (!rte_intr_allow_others(intr_handle)) { I40E_WRITE_REG(hw, I40E_VFINT_DYN_CTL01, I40E_VFINT_DYN_CTL01_INTENA_MASK | I40E_VFINT_DYN_CTL01_CLEARPBA_MASK | I40E_VFINT_DYN_CTL01_ITR_INDX_MASK); I40EVF_WRITE_FLUSH(hw); return; } if (vf->version_major == I40E_DPDK_VERSION_MAJOR) /* To support DPDK PF host */ I40E_WRITE_REG(hw, I40E_VFINT_DYN_CTLN1(I40EVF_VSI_DEFAULT_MSIX_INTR - 1), I40E_VFINT_DYN_CTLN1_INTENA_MASK | I40E_VFINT_DYN_CTLN_CLEARPBA_MASK); /* If host driver is kernel driver, do nothing. * Interrupt 0 is used for rx packets, but don't set * I40E_VFINT_DYN_CTL01, * because it is already done in i40evf_enable_irq0. */ I40EVF_WRITE_FLUSH(hw); } static inline void i40evf_disable_queues_intr(struct rte_eth_dev *dev) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); struct i40e_hw *hw = I40E_DEV_PRIVATE_TO_HW(dev->data->dev_private); struct rte_pci_device *pci_dev = I40E_DEV_TO_PCI(dev); struct rte_intr_handle *intr_handle = &pci_dev->intr_handle; if (!rte_intr_allow_others(intr_handle)) { I40E_WRITE_REG(hw, I40E_VFINT_DYN_CTL01, I40E_VFINT_DYN_CTL01_ITR_INDX_MASK); I40EVF_WRITE_FLUSH(hw); return; } if (vf->version_major == I40E_DPDK_VERSION_MAJOR) I40E_WRITE_REG(hw, I40E_VFINT_DYN_CTLN1(I40EVF_VSI_DEFAULT_MSIX_INTR - 1), 0); /* If host driver is kernel driver, do nothing. * Interrupt 0 is used for rx packets, but don't zero * I40E_VFINT_DYN_CTL01, * because interrupt 0 is also used for adminq processing. */ I40EVF_WRITE_FLUSH(hw); } static int i40evf_dev_rx_queue_intr_enable(struct rte_eth_dev *dev, uint16_t queue_id) { struct rte_pci_device *pci_dev = I40E_DEV_TO_PCI(dev); struct rte_intr_handle *intr_handle = &pci_dev->intr_handle; struct i40e_hw *hw = I40E_DEV_PRIVATE_TO_HW(dev->data->dev_private); uint16_t interval = i40e_calc_itr_interval(RTE_LIBRTE_I40E_ITR_INTERVAL); uint16_t msix_intr; msix_intr = intr_handle->intr_vec[queue_id]; if (msix_intr == I40E_MISC_VEC_ID) I40E_WRITE_REG(hw, I40E_VFINT_DYN_CTL01, I40E_VFINT_DYN_CTL01_INTENA_MASK | I40E_VFINT_DYN_CTL01_CLEARPBA_MASK | (0 << I40E_VFINT_DYN_CTL01_ITR_INDX_SHIFT) | (interval << I40E_VFINT_DYN_CTL01_INTERVAL_SHIFT)); else I40E_WRITE_REG(hw, I40E_VFINT_DYN_CTLN1(msix_intr - I40E_RX_VEC_START), I40E_VFINT_DYN_CTLN1_INTENA_MASK | I40E_VFINT_DYN_CTLN1_CLEARPBA_MASK | (0 << I40E_VFINT_DYN_CTLN1_ITR_INDX_SHIFT) | (interval << I40E_VFINT_DYN_CTLN1_INTERVAL_SHIFT)); I40EVF_WRITE_FLUSH(hw); rte_intr_enable(&pci_dev->intr_handle); return 0; } static int i40evf_dev_rx_queue_intr_disable(struct rte_eth_dev *dev, uint16_t queue_id) { struct rte_pci_device *pci_dev = I40E_DEV_TO_PCI(dev); struct rte_intr_handle *intr_handle = &pci_dev->intr_handle; struct i40e_hw *hw = I40E_DEV_PRIVATE_TO_HW(dev->data->dev_private); uint16_t msix_intr; msix_intr = intr_handle->intr_vec[queue_id]; if (msix_intr == I40E_MISC_VEC_ID) I40E_WRITE_REG(hw, I40E_VFINT_DYN_CTL01, 0); else I40E_WRITE_REG(hw, I40E_VFINT_DYN_CTLN1(msix_intr - I40E_RX_VEC_START), 0); I40EVF_WRITE_FLUSH(hw); return 0; } static void i40evf_add_del_all_mac_addr(struct rte_eth_dev *dev, bool add) { struct i40e_virtchnl_ether_addr_list *list; struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); int err, i, j; int next_begin = 0; int begin = 0; uint32_t len; struct ether_addr *addr; struct vf_cmd_info args; do { j = 0; len = sizeof(struct i40e_virtchnl_ether_addr_list); for (i = begin; i < I40E_NUM_MACADDR_MAX; i++, next_begin++) { if (is_zero_ether_addr(&dev->data->mac_addrs[i])) continue; len += sizeof(struct i40e_virtchnl_ether_addr); if (len >= I40E_AQ_BUF_SZ) { next_begin = i + 1; break; } } list = rte_zmalloc("i40evf_del_mac_buffer", len, 0); for (i = begin; i < next_begin; i++) { addr = &dev->data->mac_addrs[i]; if (is_zero_ether_addr(addr)) continue; (void)rte_memcpy(list->list[j].addr, addr->addr_bytes, sizeof(addr->addr_bytes)); PMD_DRV_LOG(DEBUG, "add/rm mac:%x:%x:%x:%x:%x:%x", addr->addr_bytes[0], addr->addr_bytes[1], addr->addr_bytes[2], addr->addr_bytes[3], addr->addr_bytes[4], addr->addr_bytes[5]); j++; } list->vsi_id = vf->vsi_res->vsi_id; list->num_elements = j; args.ops = add ? I40E_VIRTCHNL_OP_ADD_ETHER_ADDRESS : I40E_VIRTCHNL_OP_DEL_ETHER_ADDRESS; args.in_args = (uint8_t *)list; args.in_args_size = len; args.out_buffer = vf->aq_resp; args.out_size = I40E_AQ_BUF_SZ; err = i40evf_execute_vf_cmd(dev, &args); if (err) PMD_DRV_LOG(ERR, "fail to execute command %s", add ? "OP_ADD_ETHER_ADDRESS" : "OP_DEL_ETHER_ADDRESS"); rte_free(list); begin = next_begin; } while (begin < I40E_NUM_MACADDR_MAX); } static int i40evf_dev_start(struct rte_eth_dev *dev) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); struct i40e_hw *hw = I40E_DEV_PRIVATE_TO_HW(dev->data->dev_private); struct rte_pci_device *pci_dev = I40E_DEV_TO_PCI(dev); struct rte_intr_handle *intr_handle = &pci_dev->intr_handle; uint32_t intr_vector = 0; PMD_INIT_FUNC_TRACE(); hw->adapter_stopped = 0; vf->max_pkt_len = dev->data->dev_conf.rxmode.max_rx_pkt_len; vf->num_queue_pairs = RTE_MAX(dev->data->nb_rx_queues, dev->data->nb_tx_queues); /* check and configure queue intr-vector mapping */ if (dev->data->dev_conf.intr_conf.rxq != 0) { intr_vector = dev->data->nb_rx_queues; if (rte_intr_efd_enable(intr_handle, intr_vector)) return -1; } if (rte_intr_dp_is_en(intr_handle) && !intr_handle->intr_vec) { intr_handle->intr_vec = rte_zmalloc("intr_vec", dev->data->nb_rx_queues * sizeof(int), 0); if (!intr_handle->intr_vec) { PMD_INIT_LOG(ERR, "Failed to allocate %d rx_queues" " intr_vec", dev->data->nb_rx_queues); return -ENOMEM; } } if (i40evf_rx_init(dev) != 0){ PMD_DRV_LOG(ERR, "failed to do RX init"); return -1; } i40evf_tx_init(dev); if (i40evf_configure_queues(dev) != 0) { PMD_DRV_LOG(ERR, "configure queues failed"); goto err_queue; } if (i40evf_config_irq_map(dev)) { PMD_DRV_LOG(ERR, "config_irq_map failed"); goto err_queue; } /* Set all mac addrs */ i40evf_add_del_all_mac_addr(dev, TRUE); if (i40evf_start_queues(dev) != 0) { PMD_DRV_LOG(ERR, "enable queues failed"); goto err_mac; } i40evf_enable_queues_intr(dev); return 0; err_mac: i40evf_add_del_all_mac_addr(dev, FALSE); err_queue: return -1; } static void i40evf_dev_stop(struct rte_eth_dev *dev) { struct rte_pci_device *pci_dev = I40E_DEV_TO_PCI(dev); struct rte_intr_handle *intr_handle = &pci_dev->intr_handle; PMD_INIT_FUNC_TRACE(); i40evf_stop_queues(dev); i40evf_disable_queues_intr(dev); i40e_dev_clear_queues(dev); /* Clean datapath event and queue/vec mapping */ rte_intr_efd_disable(intr_handle); if (intr_handle->intr_vec) { rte_free(intr_handle->intr_vec); intr_handle->intr_vec = NULL; } /* remove all mac addrs */ i40evf_add_del_all_mac_addr(dev, FALSE); } static int i40evf_dev_link_update(struct rte_eth_dev *dev, __rte_unused int wait_to_complete) { struct rte_eth_link new_link; struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); /* * DPDK pf host provide interfacet to acquire link status * while Linux driver does not */ /* Linux driver PF host */ switch (vf->link_speed) { case I40E_LINK_SPEED_100MB: new_link.link_speed = ETH_SPEED_NUM_100M; break; case I40E_LINK_SPEED_1GB: new_link.link_speed = ETH_SPEED_NUM_1G; break; case I40E_LINK_SPEED_10GB: new_link.link_speed = ETH_SPEED_NUM_10G; break; case I40E_LINK_SPEED_20GB: new_link.link_speed = ETH_SPEED_NUM_20G; break; case I40E_LINK_SPEED_40GB: new_link.link_speed = ETH_SPEED_NUM_40G; break; default: new_link.link_speed = ETH_SPEED_NUM_100M; break; } /* full duplex only */ new_link.link_duplex = ETH_LINK_FULL_DUPLEX; new_link.link_status = vf->link_up ? ETH_LINK_UP : ETH_LINK_DOWN; i40evf_dev_atomic_write_link_status(dev, &new_link); return 0; } static void i40evf_dev_promiscuous_enable(struct rte_eth_dev *dev) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); int ret; /* If enabled, just return */ if (vf->promisc_unicast_enabled) return; ret = i40evf_config_promisc(dev, 1, vf->promisc_multicast_enabled); if (ret == 0) vf->promisc_unicast_enabled = TRUE; } static void i40evf_dev_promiscuous_disable(struct rte_eth_dev *dev) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); int ret; /* If disabled, just return */ if (!vf->promisc_unicast_enabled) return; ret = i40evf_config_promisc(dev, 0, vf->promisc_multicast_enabled); if (ret == 0) vf->promisc_unicast_enabled = FALSE; } static void i40evf_dev_allmulticast_enable(struct rte_eth_dev *dev) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); int ret; /* If enabled, just return */ if (vf->promisc_multicast_enabled) return; ret = i40evf_config_promisc(dev, vf->promisc_unicast_enabled, 1); if (ret == 0) vf->promisc_multicast_enabled = TRUE; } static void i40evf_dev_allmulticast_disable(struct rte_eth_dev *dev) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); int ret; /* If enabled, just return */ if (!vf->promisc_multicast_enabled) return; ret = i40evf_config_promisc(dev, vf->promisc_unicast_enabled, 0); if (ret == 0) vf->promisc_multicast_enabled = FALSE; } static void i40evf_dev_info_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *dev_info) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); memset(dev_info, 0, sizeof(*dev_info)); dev_info->pci_dev = RTE_DEV_TO_PCI(dev->device); dev_info->max_rx_queues = vf->vsi_res->num_queue_pairs; dev_info->max_tx_queues = vf->vsi_res->num_queue_pairs; dev_info->min_rx_bufsize = I40E_BUF_SIZE_MIN; dev_info->max_rx_pktlen = I40E_FRAME_SIZE_MAX; dev_info->hash_key_size = (I40E_VFQF_HKEY_MAX_INDEX + 1) * sizeof(uint32_t); dev_info->reta_size = ETH_RSS_RETA_SIZE_64; dev_info->flow_type_rss_offloads = I40E_RSS_OFFLOAD_ALL; dev_info->max_mac_addrs = I40E_NUM_MACADDR_MAX; dev_info->rx_offload_capa = DEV_RX_OFFLOAD_VLAN_STRIP | DEV_RX_OFFLOAD_QINQ_STRIP | DEV_RX_OFFLOAD_IPV4_CKSUM | DEV_RX_OFFLOAD_UDP_CKSUM | DEV_RX_OFFLOAD_TCP_CKSUM; dev_info->tx_offload_capa = DEV_TX_OFFLOAD_VLAN_INSERT | DEV_TX_OFFLOAD_QINQ_INSERT | DEV_TX_OFFLOAD_IPV4_CKSUM | DEV_TX_OFFLOAD_UDP_CKSUM | DEV_TX_OFFLOAD_TCP_CKSUM | DEV_TX_OFFLOAD_SCTP_CKSUM; dev_info->default_rxconf = (struct rte_eth_rxconf) { .rx_thresh = { .pthresh = I40E_DEFAULT_RX_PTHRESH, .hthresh = I40E_DEFAULT_RX_HTHRESH, .wthresh = I40E_DEFAULT_RX_WTHRESH, }, .rx_free_thresh = I40E_DEFAULT_RX_FREE_THRESH, .rx_drop_en = 0, }; dev_info->default_txconf = (struct rte_eth_txconf) { .tx_thresh = { .pthresh = I40E_DEFAULT_TX_PTHRESH, .hthresh = I40E_DEFAULT_TX_HTHRESH, .wthresh = I40E_DEFAULT_TX_WTHRESH, }, .tx_free_thresh = I40E_DEFAULT_TX_FREE_THRESH, .tx_rs_thresh = I40E_DEFAULT_TX_RSBIT_THRESH, .txq_flags = ETH_TXQ_FLAGS_NOMULTSEGS | ETH_TXQ_FLAGS_NOOFFLOADS, }; dev_info->rx_desc_lim = (struct rte_eth_desc_lim) { .nb_max = I40E_MAX_RING_DESC, .nb_min = I40E_MIN_RING_DESC, .nb_align = I40E_ALIGN_RING_DESC, }; dev_info->tx_desc_lim = (struct rte_eth_desc_lim) { .nb_max = I40E_MAX_RING_DESC, .nb_min = I40E_MIN_RING_DESC, .nb_align = I40E_ALIGN_RING_DESC, }; } static void i40evf_dev_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats) { if (i40evf_get_statistics(dev, stats)) PMD_DRV_LOG(ERR, "Get statistics failed"); } static void i40evf_dev_close(struct rte_eth_dev *dev) { struct i40e_hw *hw = I40E_DEV_PRIVATE_TO_HW(dev->data->dev_private); struct rte_pci_device *pci_dev = I40E_DEV_TO_PCI(dev); struct rte_intr_handle *intr_handle = &pci_dev->intr_handle; i40evf_dev_stop(dev); hw->adapter_stopped = 1; i40e_dev_free_queues(dev); i40evf_reset_vf(hw); i40e_shutdown_adminq(hw); /* disable uio intr before callback unregister */ rte_intr_disable(intr_handle); /* unregister callback func from eal lib */ rte_intr_callback_unregister(intr_handle, i40evf_dev_interrupt_handler, dev); i40evf_disable_irq0(hw); } static int i40evf_get_rss_lut(struct i40e_vsi *vsi, uint8_t *lut, uint16_t lut_size) { struct i40e_vf *vf = I40E_VSI_TO_VF(vsi); struct i40e_hw *hw = I40E_VSI_TO_HW(vsi); int ret; if (!lut) return -EINVAL; if (vf->flags & I40E_FLAG_RSS_AQ_CAPABLE) { ret = i40e_aq_get_rss_lut(hw, vsi->vsi_id, FALSE, lut, lut_size); if (ret) { PMD_DRV_LOG(ERR, "Failed to get RSS lookup table"); return ret; } } else { uint32_t *lut_dw = (uint32_t *)lut; uint16_t i, lut_size_dw = lut_size / 4; for (i = 0; i < lut_size_dw; i++) lut_dw[i] = I40E_READ_REG(hw, I40E_VFQF_HLUT(i)); } return 0; } static int i40evf_set_rss_lut(struct i40e_vsi *vsi, uint8_t *lut, uint16_t lut_size) { struct i40e_vf *vf; struct i40e_hw *hw; int ret; if (!vsi || !lut) return -EINVAL; vf = I40E_VSI_TO_VF(vsi); hw = I40E_VSI_TO_HW(vsi); if (vf->flags & I40E_FLAG_RSS_AQ_CAPABLE) { ret = i40e_aq_set_rss_lut(hw, vsi->vsi_id, FALSE, lut, lut_size); if (ret) { PMD_DRV_LOG(ERR, "Failed to set RSS lookup table"); return ret; } } else { uint32_t *lut_dw = (uint32_t *)lut; uint16_t i, lut_size_dw = lut_size / 4; for (i = 0; i < lut_size_dw; i++) I40E_WRITE_REG(hw, I40E_VFQF_HLUT(i), lut_dw[i]); I40EVF_WRITE_FLUSH(hw); } return 0; } static int i40evf_dev_rss_reta_update(struct rte_eth_dev *dev, struct rte_eth_rss_reta_entry64 *reta_conf, uint16_t reta_size) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); uint8_t *lut; uint16_t i, idx, shift; int ret; if (reta_size != ETH_RSS_RETA_SIZE_64) { PMD_DRV_LOG(ERR, "The size of hash lookup table configured " "(%d) doesn't match the number of hardware can " "support (%d)", reta_size, ETH_RSS_RETA_SIZE_64); return -EINVAL; } lut = rte_zmalloc("i40e_rss_lut", reta_size, 0); if (!lut) { PMD_DRV_LOG(ERR, "No memory can be allocated"); return -ENOMEM; } ret = i40evf_get_rss_lut(&vf->vsi, lut, reta_size); if (ret) goto out; for (i = 0; i < reta_size; i++) { idx = i / RTE_RETA_GROUP_SIZE; shift = i % RTE_RETA_GROUP_SIZE; if (reta_conf[idx].mask & (1ULL << shift)) lut[i] = reta_conf[idx].reta[shift]; } ret = i40evf_set_rss_lut(&vf->vsi, lut, reta_size); out: rte_free(lut); return ret; } static int i40evf_dev_rss_reta_query(struct rte_eth_dev *dev, struct rte_eth_rss_reta_entry64 *reta_conf, uint16_t reta_size) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); uint16_t i, idx, shift; uint8_t *lut; int ret; if (reta_size != ETH_RSS_RETA_SIZE_64) { PMD_DRV_LOG(ERR, "The size of hash lookup table configured " "(%d) doesn't match the number of hardware can " "support (%d)", reta_size, ETH_RSS_RETA_SIZE_64); return -EINVAL; } lut = rte_zmalloc("i40e_rss_lut", reta_size, 0); if (!lut) { PMD_DRV_LOG(ERR, "No memory can be allocated"); return -ENOMEM; } ret = i40evf_get_rss_lut(&vf->vsi, lut, reta_size); if (ret) goto out; for (i = 0; i < reta_size; i++) { idx = i / RTE_RETA_GROUP_SIZE; shift = i % RTE_RETA_GROUP_SIZE; if (reta_conf[idx].mask & (1ULL << shift)) reta_conf[idx].reta[shift] = lut[i]; } out: rte_free(lut); return ret; } static int i40evf_set_rss_key(struct i40e_vsi *vsi, uint8_t *key, uint8_t key_len) { struct i40e_vf *vf = I40E_VSI_TO_VF(vsi); struct i40e_hw *hw = I40E_VSI_TO_HW(vsi); int ret = 0; if (!key || key_len == 0) { PMD_DRV_LOG(DEBUG, "No key to be configured"); return 0; } else if (key_len != (I40E_VFQF_HKEY_MAX_INDEX + 1) * sizeof(uint32_t)) { PMD_DRV_LOG(ERR, "Invalid key length %u", key_len); return -EINVAL; } if (vf->flags & I40E_FLAG_RSS_AQ_CAPABLE) { struct i40e_aqc_get_set_rss_key_data *key_dw = (struct i40e_aqc_get_set_rss_key_data *)key; ret = i40e_aq_set_rss_key(hw, vsi->vsi_id, key_dw); if (ret) PMD_INIT_LOG(ERR, "Failed to configure RSS key " "via AQ"); } else { uint32_t *hash_key = (uint32_t *)key; uint16_t i; for (i = 0; i <= I40E_VFQF_HKEY_MAX_INDEX; i++) i40e_write_rx_ctl(hw, I40E_VFQF_HKEY(i), hash_key[i]); I40EVF_WRITE_FLUSH(hw); } return ret; } static int i40evf_get_rss_key(struct i40e_vsi *vsi, uint8_t *key, uint8_t *key_len) { struct i40e_vf *vf = I40E_VSI_TO_VF(vsi); struct i40e_hw *hw = I40E_VSI_TO_HW(vsi); int ret; if (!key || !key_len) return -EINVAL; if (vf->flags & I40E_FLAG_RSS_AQ_CAPABLE) { ret = i40e_aq_get_rss_key(hw, vsi->vsi_id, (struct i40e_aqc_get_set_rss_key_data *)key); if (ret) { PMD_INIT_LOG(ERR, "Failed to get RSS key via AQ"); return ret; } } else { uint32_t *key_dw = (uint32_t *)key; uint16_t i; for (i = 0; i <= I40E_VFQF_HKEY_MAX_INDEX; i++) key_dw[i] = i40e_read_rx_ctl(hw, I40E_VFQF_HKEY(i)); } *key_len = (I40E_VFQF_HKEY_MAX_INDEX + 1) * sizeof(uint32_t); return 0; } static int i40evf_hw_rss_hash_set(struct i40e_vf *vf, struct rte_eth_rss_conf *rss_conf) { struct i40e_hw *hw = I40E_VF_TO_HW(vf); uint64_t rss_hf, hena; int ret; ret = i40evf_set_rss_key(&vf->vsi, rss_conf->rss_key, rss_conf->rss_key_len); if (ret) return ret; rss_hf = rss_conf->rss_hf; hena = (uint64_t)i40e_read_rx_ctl(hw, I40E_VFQF_HENA(0)); hena |= ((uint64_t)i40e_read_rx_ctl(hw, I40E_VFQF_HENA(1))) << 32; if (hw->mac.type == I40E_MAC_X722) hena &= ~I40E_RSS_HENA_ALL_X722; else hena &= ~I40E_RSS_HENA_ALL; hena |= i40e_config_hena(rss_hf, hw->mac.type); i40e_write_rx_ctl(hw, I40E_VFQF_HENA(0), (uint32_t)hena); i40e_write_rx_ctl(hw, I40E_VFQF_HENA(1), (uint32_t)(hena >> 32)); I40EVF_WRITE_FLUSH(hw); return 0; } static void i40evf_disable_rss(struct i40e_vf *vf) { struct i40e_hw *hw = I40E_VF_TO_HW(vf); uint64_t hena; hena = (uint64_t)i40e_read_rx_ctl(hw, I40E_VFQF_HENA(0)); hena |= ((uint64_t)i40e_read_rx_ctl(hw, I40E_VFQF_HENA(1))) << 32; if (hw->mac.type == I40E_MAC_X722) hena &= ~I40E_RSS_HENA_ALL_X722; else hena &= ~I40E_RSS_HENA_ALL; i40e_write_rx_ctl(hw, I40E_VFQF_HENA(0), (uint32_t)hena); i40e_write_rx_ctl(hw, I40E_VFQF_HENA(1), (uint32_t)(hena >> 32)); I40EVF_WRITE_FLUSH(hw); } static int i40evf_config_rss(struct i40e_vf *vf) { struct i40e_hw *hw = I40E_VF_TO_HW(vf); struct rte_eth_rss_conf rss_conf; uint32_t i, j, lut = 0, nb_q = (I40E_VFQF_HLUT_MAX_INDEX + 1) * 4; uint16_t num; if (vf->dev_data->dev_conf.rxmode.mq_mode != ETH_MQ_RX_RSS) { i40evf_disable_rss(vf); PMD_DRV_LOG(DEBUG, "RSS not configured"); return 0; } num = RTE_MIN(vf->dev_data->nb_rx_queues, I40E_MAX_QP_NUM_PER_VF); /* Fill out the look up table */ for (i = 0, j = 0; i < nb_q; i++, j++) { if (j >= num) j = 0; lut = (lut << 8) | j; if ((i & 3) == 3) I40E_WRITE_REG(hw, I40E_VFQF_HLUT(i >> 2), lut); } rss_conf = vf->dev_data->dev_conf.rx_adv_conf.rss_conf; if ((rss_conf.rss_hf & I40E_RSS_OFFLOAD_ALL) == 0) { i40evf_disable_rss(vf); PMD_DRV_LOG(DEBUG, "No hash flag is set"); return 0; } if (rss_conf.rss_key == NULL || rss_conf.rss_key_len < (I40E_VFQF_HKEY_MAX_INDEX + 1) * sizeof(uint32_t)) { /* Calculate the default hash key */ for (i = 0; i <= I40E_VFQF_HKEY_MAX_INDEX; i++) rss_key_default[i] = (uint32_t)rte_rand(); rss_conf.rss_key = (uint8_t *)rss_key_default; rss_conf.rss_key_len = (I40E_VFQF_HKEY_MAX_INDEX + 1) * sizeof(uint32_t); } return i40evf_hw_rss_hash_set(vf, &rss_conf); } static int i40evf_dev_rss_hash_update(struct rte_eth_dev *dev, struct rte_eth_rss_conf *rss_conf) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); struct i40e_hw *hw = I40E_DEV_PRIVATE_TO_HW(dev->data->dev_private); uint64_t rss_hf = rss_conf->rss_hf & I40E_RSS_OFFLOAD_ALL; uint64_t hena; hena = (uint64_t)i40e_read_rx_ctl(hw, I40E_VFQF_HENA(0)); hena |= ((uint64_t)i40e_read_rx_ctl(hw, I40E_VFQF_HENA(1))) << 32; if (!(hena & ((hw->mac.type == I40E_MAC_X722) ? I40E_RSS_HENA_ALL_X722 : I40E_RSS_HENA_ALL))) { /* RSS disabled */ if (rss_hf != 0) /* Enable RSS */ return -EINVAL; return 0; } /* RSS enabled */ if (rss_hf == 0) /* Disable RSS */ return -EINVAL; return i40evf_hw_rss_hash_set(vf, rss_conf); } static int i40evf_dev_rss_hash_conf_get(struct rte_eth_dev *dev, struct rte_eth_rss_conf *rss_conf) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); struct i40e_hw *hw = I40E_DEV_PRIVATE_TO_HW(dev->data->dev_private); uint64_t hena; i40evf_get_rss_key(&vf->vsi, rss_conf->rss_key, &rss_conf->rss_key_len); hena = (uint64_t)i40e_read_rx_ctl(hw, I40E_VFQF_HENA(0)); hena |= ((uint64_t)i40e_read_rx_ctl(hw, I40E_VFQF_HENA(1))) << 32; rss_conf->rss_hf = i40e_parse_hena(hena); return 0; } static int i40evf_dev_mtu_set(struct rte_eth_dev *dev, uint16_t mtu) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); struct rte_eth_dev_data *dev_data = vf->dev_data; uint32_t frame_size = mtu + ETHER_HDR_LEN + ETHER_CRC_LEN + I40E_VLAN_TAG_SIZE; int ret = 0; /* check if mtu is within the allowed range */ if ((mtu < ETHER_MIN_MTU) || (frame_size > I40E_FRAME_SIZE_MAX)) return -EINVAL; /* mtu setting is forbidden if port is start */ if (dev_data->dev_started) { PMD_DRV_LOG(ERR, "port %d must be stopped before configuration", dev_data->port_id); return -EBUSY; } if (frame_size > ETHER_MAX_LEN) dev_data->dev_conf.rxmode.jumbo_frame = 1; else dev_data->dev_conf.rxmode.jumbo_frame = 0; dev_data->dev_conf.rxmode.max_rx_pkt_len = frame_size; return ret; } static void i40evf_set_default_mac_addr(struct rte_eth_dev *dev, struct ether_addr *mac_addr) { struct i40e_vf *vf = I40EVF_DEV_PRIVATE_TO_VF(dev->data->dev_private); if (!is_valid_assigned_ether_addr(mac_addr)) { PMD_DRV_LOG(ERR, "Tried to set invalid MAC address."); return; } if (is_same_ether_addr(mac_addr, dev->data->mac_addrs)) return; if (vf->flags & I40E_FLAG_VF_MAC_BY_PF) return; i40evf_del_mac_addr_by_addr(dev, dev->data->mac_addrs); i40evf_add_mac_addr(dev, mac_addr, 0, 0); }
intersvyaz/dpdk
drivers/net/i40e/i40e_ethdev_vf.c
C
gpl-2.0
77,271
<div class="op-bsw-grey-panel-content op-bsw-grey-panel-no-sidebar"> <p class="op-micro-copy"><?php _e('Use this option if you want anyone trying to exit your page via the browser close buttons to be shown a message and redirected to a URL of your choosing',OP_SN) ?></p> <label for="<?php echo $fieldid ?>url" class="form-title"><?php _e('Redirect to URL') ?></label> <p class="op-micro-copy"><?php _e('Enter the URL that your users browser should be redirected to on exit.') ?></p> <input type="text" name="<?php echo $fieldname ?>[url]" id="<?php echo $fieldid ?>url" value="<?php op_page_attr_e($section_name,'url') ?>" /> <label for="<?php echo $fieldid ?>message" class="form-title"><?php _e('Redirect Browser Message',OP_SN) ?></label> <p class="op-micro-copy"><?php _e('Enter the message to be shown to the user in a browser pop when the user tries to exit. This would normally be a message advising if they want to close their browser or be redirected',OP_SN) ?></p> <textarea id="<?php echo $fieldid ?>message" name="<?php echo $fieldname ?>[message]"><?php stripslashes(op_page_attr_e($section_name,'message')) ?></textarea> </div>
denis-chmel/wordpress
wp-content/plugins/optimizePressPlugin/lib/modules/page/exit_redirect/tpl/settings.php
PHP
gpl-2.0
1,166
package org.anddev.andengine.engine.options; import android.os.PowerManager; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:45:23 - 10.07.2010 */ public enum WakeLockOptions { // =========================================================== // Elements // =========================================================== /** Screen is on at full brightness. Keyboard backlight is on at full brightness. Requires <b>WAKE_LOCK</b> permission! */ BRIGHT(PowerManager.FULL_WAKE_LOCK), /** Screen is on at full brightness. Keyboard backlight will be allowed to go off. Requires <b>WAKE_LOCK</b> permission!*/ SCREEN_BRIGHT(PowerManager.SCREEN_BRIGHT_WAKE_LOCK), /** Screen is on but may be dimmed. Keyboard backlight will be allowed to go off. Requires <b>WAKE_LOCK</b> permission!*/ SCREEN_DIM(PowerManager.SCREEN_DIM_WAKE_LOCK), /** Screen is on at full brightness. Does <b>not</b> require <b>WAKE_LOCK</b> permission! */ SCREEN_ON(-1); // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mFlag; // =========================================================== // Constructors // =========================================================== private WakeLockOptions(final int pFlag) { this.mFlag = pFlag; } // =========================================================== // Getter & Setter // =========================================================== public int getFlag() { return this.mFlag; } // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
ricardobaumann/android
worldofgravity-master/src/org/anddev/andengine/engine/options/WakeLockOptions.java
Java
gpl-2.0
2,193
/** schemas.js **/ schemas = { user: { id: null, name: null, password: null } } module.exports = schemas;
Zepx/Tamanegi
models/schemas.js
JavaScript
gpl-2.0
139
<div class="wphb-block-entry"> <div class="wphb-block-entry-content"> <img class="wphb-image-icon-content wphb-image-icon-content-top wphb-image-icon-content-center" src="<?php echo wphb_plugin_url() . 'admin/assets/image/icon-performance-small.png'; ?>" alt="<?php _e('Performance Report', 'wphb'); ?>"> <div class="content"> <p><?php _e( 'Hummingbird will test your website and detect what improvements you can make. We’ll give you a score out of 100 for each item, with custom recommendations on how to improve!', 'wphb' ); ?></p> <a href="<?php echo esc_url( $run_url ); ?>" class="button button-app button-content-cta" id="performance-scan-website"><?php _e( 'Test my website', 'wphb' ); ?></a> </div><!-- end content --> </div><!-- end wphb-block-entry-content --> </div><!-- end wphb-block-entry -->
golfcoastmagazine/golfcoastmagazine
wp-content/plugins/wp-hummingbird/admin/views/dashboard-performance-disabled-meta-box.php
PHP
gpl-2.0
840
<?php /** * Implements Special:UploadStash. * * 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. * http://www.gnu.org/copyleft/gpl.html * * @file * @ingroup SpecialPage * @ingroup Upload */ /** * Web access for files temporarily stored by UploadStash. * * For example -- files that were uploaded with the UploadWizard extension are stored temporarily * before committing them to the db. But we want to see their thumbnails and get other information * about them. * * Since this is based on the user's session, in effect this creates a private temporary file area. * However, the URLs for the files cannot be shared. */ class SpecialUploadStash extends UnlistedSpecialPage { // UploadStash private $stash; // Since we are directly writing the file to STDOUT, // we should not be reading in really big files and serving them out. // // We also don't want people using this as a file drop, even if they // share credentials. // // This service is really for thumbnails and other such previews while // uploading. const MAX_SERVE_BYTES = 1048576; // 1MB public function __construct() { parent::__construct( 'UploadStash', 'upload' ); try { $this->stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash(); } catch ( UploadStashNotAvailableException $e ) { } } /** * Execute page -- can output a file directly or show a listing of them. * * @param $subPage String: subpage, e.g. in http://example.com/wiki/Special:UploadStash/foo.jpg, the "foo.jpg" part * @return Boolean: success */ public function execute( $subPage ) { $this->checkPermissions(); if ( $subPage === null || $subPage === '' ) { return $this->showUploads(); } return $this->showUpload( $subPage ); } /** * If file available in stash, cats it out to the client as a simple HTTP response. * n.b. Most sanity checking done in UploadStashLocalFile, so this is straightforward. * * @param $key String: the key of a particular requested file * @throws HttpError * @return bool */ public function showUpload( $key ) { // prevent callers from doing standard HTML output -- we'll take it from here $this->getOutput()->disable(); try { $params = $this->parseKey( $key ); if ( $params['type'] === 'thumb' ) { return $this->outputThumbFromStash( $params['file'], $params['params'] ); } else { return $this->outputLocalFile( $params['file'] ); } } catch( UploadStashFileNotFoundException $e ) { $code = 404; $message = $e->getMessage(); } catch( UploadStashZeroLengthFileException $e ) { $code = 500; $message = $e->getMessage(); } catch( UploadStashBadPathException $e ) { $code = 500; $message = $e->getMessage(); } catch( SpecialUploadStashTooLargeException $e ) { $code = 500; $message = 'Cannot serve a file larger than ' . self::MAX_SERVE_BYTES . ' bytes. ' . $e->getMessage(); } catch( Exception $e ) { $code = 500; $message = $e->getMessage(); } throw new HttpError( $code, $message ); } /** * Parse the key passed to the SpecialPage. Returns an array containing * the associated file object, the type ('file' or 'thumb') and if * application the transform parameters * * @param string $key * @throws UploadStashBadPathException * @return array */ private function parseKey( $key ) { $type = strtok( $key, '/' ); if ( $type !== 'file' && $type !== 'thumb' ) { throw new UploadStashBadPathException( "Unknown type '$type'" ); } $fileName = strtok( '/' ); $thumbPart = strtok( '/' ); $file = $this->stash->getFile( $fileName ); if ( $type === 'thumb' ) { $srcNamePos = strrpos( $thumbPart, $fileName ); if ( $srcNamePos === false || $srcNamePos < 1 ) { throw new UploadStashBadPathException( 'Unrecognized thumb name' ); } $paramString = substr( $thumbPart, 0, $srcNamePos - 1 ); $handler = $file->getHandler(); $params = $handler->parseParamString( $paramString ); return array( 'file' => $file, 'type' => $type, 'params' => $params ); } return array( 'file' => $file, 'type' => $type ); } /** * Get a thumbnail for file, either generated locally or remotely, and stream it out * * @param $file * @param $params array * * @return boolean success */ private function outputThumbFromStash( $file, $params ) { // this global, if it exists, points to a "scaler", as you might find in the Wikimedia Foundation cluster. See outputRemoteScaledThumb() // this is part of our horrible NFS-based system, we create a file on a mount point here, but fetch the scaled file from somewhere else that // happens to share it over NFS global $wgUploadStashScalerBaseUrl; $flags = 0; if ( $wgUploadStashScalerBaseUrl ) { $this->outputRemoteScaledThumb( $file, $params, $flags ); } else { $this->outputLocallyScaledThumb( $file, $params, $flags ); } } /** * Scale a file (probably with a locally installed imagemagick, or similar) and output it to STDOUT. * @param $file File * @param $params array Scaling parameters ( e.g. array( width => '50' ) ); * @param $flags int Scaling flags ( see File:: constants ) * @throws MWException * @throws UploadStashFileNotFoundException * @return boolean success */ private function outputLocallyScaledThumb( $file, $params, $flags ) { // n.b. this is stupid, we insist on re-transforming the file every time we are invoked. We rely // on HTTP caching to ensure this doesn't happen. $flags |= File::RENDER_NOW; $thumbnailImage = $file->transform( $params, $flags ); if ( !$thumbnailImage ) { throw new MWException( 'Could not obtain thumbnail' ); } // we should have just generated it locally if ( !$thumbnailImage->getStoragePath() ) { throw new UploadStashFileNotFoundException( "no local path for scaled item" ); } // now we should construct a File, so we can get mime and other such info in a standard way // n.b. mimetype may be different from original (ogx original -> jpeg thumb) $thumbFile = new UnregisteredLocalFile( false, $this->stash->repo, $thumbnailImage->getStoragePath(), false ); if ( !$thumbFile ) { throw new UploadStashFileNotFoundException( "couldn't create local file object for thumbnail" ); } return $this->outputLocalFile( $thumbFile ); } /** * Scale a file with a remote "scaler", as exists on the Wikimedia Foundation cluster, and output it to STDOUT. * Note: unlike the usual thumbnail process, the web client never sees the cluster URL; we do the whole HTTP transaction to the scaler ourselves * and cat the results out. * Note: We rely on NFS to have propagated the file contents to the scaler. However, we do not rely on the thumbnail being created in NFS and then * propagated back to our filesystem. Instead we take the results of the HTTP request instead. * Note: no caching is being done here, although we are instructing the client to cache it forever. * @param $file: File object * @param $params: scaling parameters ( e.g. array( width => '50' ) ); * @param $flags: scaling flags ( see File:: constants ) * @throws MWException * @return boolean success */ private function outputRemoteScaledThumb( $file, $params, $flags ) { // this global probably looks something like 'http://upload.wikimedia.org/wikipedia/test/thumb/temp' // do not use trailing slash global $wgUploadStashScalerBaseUrl; $scalerBaseUrl = $wgUploadStashScalerBaseUrl; if( preg_match( '/^\/\//', $scalerBaseUrl ) ) { // this is apparently a protocol-relative URL, which makes no sense in this context, // since this is used for communication that's internal to the application. // default to http. $scalerBaseUrl = wfExpandUrl( $scalerBaseUrl, PROTO_CANONICAL ); } // We need to use generateThumbName() instead of thumbName(), because // the suffix needs to match the file name for the remote thumbnailer // to work $scalerThumbName = $file->generateThumbName( $file->getName(), $params ); $scalerThumbUrl = $scalerBaseUrl . '/' . $file->getUrlRel() . '/' . rawurlencode( $scalerThumbName ); // make a curl call to the scaler to create a thumbnail $httpOptions = array( 'method' => 'GET', 'timeout' => 'default' ); $req = MWHttpRequest::factory( $scalerThumbUrl, $httpOptions ); $status = $req->execute(); if ( ! $status->isOK() ) { $errors = $status->getErrorsArray(); $errorStr = "Fetching thumbnail failed: " . print_r( $errors, 1 ); $errorStr .= "\nurl = $scalerThumbUrl\n"; throw new MWException( $errorStr ); } $contentType = $req->getResponseHeader( "content-type" ); if ( ! $contentType ) { throw new MWException( "Missing content-type header" ); } return $this->outputContents( $req->getContent(), $contentType ); } /** * Output HTTP response for file * Side effect: writes HTTP response to STDOUT. * * @param $file File object with a local path (e.g. UnregisteredLocalFile, LocalFile. Oddly these don't share an ancestor!) * @throws SpecialUploadStashTooLargeException * @return bool */ private function outputLocalFile( File $file ) { if ( $file->getSize() > self::MAX_SERVE_BYTES ) { throw new SpecialUploadStashTooLargeException(); } return $file->getRepo()->streamFile( $file->getPath(), array( 'Content-Transfer-Encoding: binary', 'Expires: Sun, 17-Jan-2038 19:14:07 GMT' ) ); } /** * Output HTTP response of raw content * Side effect: writes HTTP response to STDOUT. * @param $content String content * @param $contentType String mime type * @throws SpecialUploadStashTooLargeException * @return bool */ private function outputContents( $content, $contentType ) { $size = strlen( $content ); if ( $size > self::MAX_SERVE_BYTES ) { throw new SpecialUploadStashTooLargeException(); } self::outputFileHeaders( $contentType, $size ); print $content; return true; } /** * Output headers for streaming * XXX unsure about encoding as binary; if we received from HTTP perhaps we should use that encoding, concatted with semicolon to mimeType as it usually is. * Side effect: preps PHP to write headers to STDOUT. * @param String $contentType : string suitable for content-type header * @param String $size: length in bytes */ private static function outputFileHeaders( $contentType, $size ) { header( "Content-Type: $contentType", true ); header( 'Content-Transfer-Encoding: binary', true ); header( 'Expires: Sun, 17-Jan-2038 19:14:07 GMT', true ); header( "Content-Length: $size", true ); } /** * Static callback for the HTMLForm in showUploads, to process * Note the stash has to be recreated since this is being called in a static context. * This works, because there really is only one stash per logged-in user, despite appearances. * * @return Status */ public static function tryClearStashedUploads( $formData ) { if ( isset( $formData['Clear'] ) ) { $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash(); wfDebug( "stash has: " . print_r( $stash->listFiles(), true ) ); if ( ! $stash->clear() ) { return Status::newFatal( 'uploadstash-errclear' ); } } return Status::newGood(); } /** * Default action when we don't have a subpage -- just show links to the uploads we have, * Also show a button to clear stashed files * @param $status [optional] Status: the result of processRequest * @return bool */ private function showUploads( $status = null ) { if ( $status === null ) { $status = Status::newGood(); } // sets the title, etc. $this->setHeaders(); $this->outputHeader(); // create the form, which will also be used to execute a callback to process incoming form data // this design is extremely dubious, but supposedly HTMLForm is our standard now? $form = new HTMLForm( array( 'Clear' => array( 'type' => 'hidden', 'default' => true, 'name' => 'clear', ) ), $this->getContext(), 'clearStashedUploads' ); $form->setSubmitCallback( array( __CLASS__ , 'tryClearStashedUploads' ) ); $form->setTitle( $this->getTitle() ); $form->setSubmitTextMsg( 'uploadstash-clear' ); $form->prepareForm(); $formResult = $form->tryAuthorizedSubmit(); // show the files + form, if there are any, or just say there are none $refreshHtml = Html::element( 'a', array( 'href' => $this->getTitle()->getLocalURL() ), $this->msg( 'uploadstash-refresh' )->text() ); $files = $this->stash->listFiles(); if ( $files && count( $files ) ) { sort( $files ); $fileListItemsHtml = ''; foreach ( $files as $file ) { // TODO: Use Linker::link or even construct the list in plain wikitext $fileListItemsHtml .= Html::rawElement( 'li', array(), Html::element( 'a', array( 'href' => $this->getTitle( "file/$file" )->getLocalURL() ), $file ) ); } $this->getOutput()->addHtml( Html::rawElement( 'ul', array(), $fileListItemsHtml ) ); $form->displayForm( $formResult ); $this->getOutput()->addHtml( Html::rawElement( 'p', array(), $refreshHtml ) ); } else { $this->getOutput()->addHtml( Html::rawElement( 'p', array(), Html::element( 'span', array(), $this->msg( 'uploadstash-nofiles' )->text() ) . ' ' . $refreshHtml ) ); } return true; } } class SpecialUploadStashTooLargeException extends MWException {};
1ec5/mediawiki-core
includes/specials/SpecialUploadStash.php
PHP
gpl-2.0
13,986
# coding: utf-8 import sys reload(sys) sys.setdefaultencoding('utf8') import socket import os import re import select import time import paramiko import struct import fcntl import signal import textwrap import getpass import fnmatch import readline import datetime from multiprocessing import Pool os.environ['DJANGO_SETTINGS_MODULE'] = 'jumpserver.settings' from juser.models import User from jlog.models import Log from jumpserver.api import CONF, BASE_DIR, ServerError, user_perm_group_api, user_perm_group_hosts_api, get_user_host from jumpserver.api import AssetAlias, get_connect_item try: import termios import tty except ImportError: print '\033[1;31mOnly UnixLike supported.\033[0m' time.sleep(3) sys.exit() CONF.read(os.path.join(BASE_DIR, 'jumpserver.conf')) LOG_DIR = os.path.join(BASE_DIR, 'logs') SSH_KEY_DIR = os.path.join(BASE_DIR, 'keys') SERVER_KEY_DIR = os.path.join(SSH_KEY_DIR, 'server') LOGIN_NAME = getpass.getuser() def color_print(msg, color='blue'): """Print colorful string.""" color_msg = {'blue': '\033[1;36m%s\033[0m', 'green': '\033[1;32m%s\033[0m', 'red': '\033[1;31m%s\033[0m'} print color_msg.get(color, 'blue') % msg def color_print_exit(msg, color='red'): """Print colorful string and exit.""" color_print(msg, color=color) time.sleep(2) sys.exit() def get_win_size(): """This function use to get the size of the windows!""" if 'TIOCGWINSZ' in dir(termios): TIOCGWINSZ = termios.TIOCGWINSZ else: TIOCGWINSZ = 1074295912L # Assume s = struct.pack('HHHH', 0, 0, 0, 0) x = fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ, s) return struct.unpack('HHHH', x)[0:2] def set_win_size(sig, data): """This function use to set the window size of the terminal!""" try: win_size = get_win_size() channel.resize_pty(height=win_size[0], width=win_size[1]) except: pass def log_record(username, host): """Logging user command and output.""" connect_log_dir = os.path.join(LOG_DIR, 'connect') timestamp_start = int(time.time()) today = time.strftime('%Y%m%d', time.localtime(timestamp_start)) time_now = time.strftime('%H%M%S', time.localtime(timestamp_start)) today_connect_log_dir = os.path.join(connect_log_dir, today) log_filename = '%s_%s_%s.log' % (username, host, time_now) log_file_path = os.path.join(today_connect_log_dir, log_filename) dept_name = User.objects.get(username=username).dept.name pid = os.getpid() pts = os.popen("ps axu | awk '$2==%s{ print $7 }'" % pid).read().strip() ip_list = os.popen("who | awk '$2==\"%s\"{ print $5 }'" % pts).read().strip('()\n') if not os.path.isdir(today_connect_log_dir): try: os.makedirs(today_connect_log_dir) os.chmod(today_connect_log_dir, 0777) except OSError: raise ServerError('Create %s failed, Please modify %s permission.' % (today_connect_log_dir, connect_log_dir)) try: log_file = open(log_file_path, 'a') except IOError: raise ServerError('Create logfile failed, Please modify %s permission.' % today_connect_log_dir) log = Log(user=username, host=host, remote_ip=ip_list, dept_name=dept_name, log_path=log_file_path, start_time=datetime.datetime.now(), pid=pid) log_file.write('Starttime is %s\n' % datetime.datetime.now()) log.save() return log_file, log def posix_shell(chan, username, host): """ Use paramiko channel connect server interactive. """ log_file, log = log_record(username, host) old_tty = termios.tcgetattr(sys.stdin) try: tty.setraw(sys.stdin.fileno()) tty.setcbreak(sys.stdin.fileno()) chan.settimeout(0.0) while True: try: r, w, e = select.select([chan, sys.stdin], [], []) except: pass if chan in r: try: x = chan.recv(10240) if len(x) == 0: break sys.stdout.write(x) sys.stdout.flush() log_file.write(x) log_file.flush() except socket.timeout: pass if sys.stdin in r: x = os.read(sys.stdin.fileno(), 1) if len(x) == 0: break chan.send(x) finally: termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty) log_file.write('Endtime is %s' % datetime.datetime.now()) log_file.close() log.is_finished = True log.log_finished = False log.end_time = datetime.datetime.now() log.save() print_prompt() def get_user_hostgroup(username): """Get the hostgroups of under the user control.""" groups_attr = {} group_all = user_perm_group_api(username) for group in group_all: groups_attr[group.name] = [group.id, group.comment] return groups_attr def get_user_hostgroup_host(username, gid): """Get the hostgroup hosts of under the user control.""" hosts_attr = {} user = User.objects.get(username=username) hosts = user_perm_group_hosts_api(gid) for host in hosts: alias = AssetAlias.objects.filter(user=user, host=host) if alias and alias[0].alias != '': hosts_attr[host.ip] = [host.id, host.ip, alias[0].alias] else: hosts_attr[host.ip] = [host.id, host.ip, host.comment] return hosts_attr def verify_connect(username, part_ip): ip_matched = [] try: hosts_attr = get_user_host(username) hosts = hosts_attr.values() except ServerError, e: color_print(e, 'red') return False for ip_info in hosts: if part_ip in ip_info[1:] and part_ip: ip_matched = [ip_info[1]] break for info in ip_info[1:]: if part_ip in info: ip_matched.append(ip_info[1]) ip_matched = list(set(ip_matched)) if len(ip_matched) > 1: for ip in ip_matched: print '%-15s -- %s' % (ip, hosts_attr[ip][2]) elif len(ip_matched) < 1: color_print('No Permission or No host.', 'red') else: username, password, host, port = get_connect_item(username, ip_matched[0]) connect(username, password, host, port, LOGIN_NAME) def print_prompt(): msg = """\033[1;32m### Welcome Use JumpServer To Login. ### \033[0m 1) Type \033[32mIP or Part IP, Host Alias or Comments \033[0m To Login. 2) Type \033[32mP/p\033[0m To Print The Servers You Available. 3) Type \033[32mG/g\033[0m To Print The Server Groups You Available. 4) Type \033[32mG/g(1-N)\033[0m To Print The Server Group Hosts You Available. 5) Type \033[32mE/e\033[0m To Execute Command On Several Servers. 6) Type \033[32mQ/q\033[0m To Quit. """ print textwrap.dedent(msg) def print_user_host(username): try: hosts_attr = get_user_host(username) except ServerError, e: color_print(e, 'red') return hosts = hosts_attr.keys() hosts.sort() for ip in hosts: print '%-15s -- %s' % (ip, hosts_attr[ip][2]) print '' def print_user_hostgroup(username): group_attr = get_user_hostgroup(username) groups = group_attr.keys() for g in groups: print "[%3s] %s -- %s" % (group_attr[g][0], g, group_attr[g][1]) def print_user_hostgroup_host(username, gid): pattern = re.compile(r'\d+') match = pattern.match(gid) if match: hosts_attr = get_user_hostgroup_host(username, gid) hosts = hosts_attr.keys() hosts.sort() for ip in hosts: print '%-15s -- %s' % (ip, hosts_attr[ip][2]) else: color_print('No such group id, Please check it.', 'red') def connect(username, password, host, port, login_name): """ Connect server. """ ps1 = "PS1='[\u@%s \W]\$ ' && TERM=xterm && export TERM\n" % host login_msg = "clear;echo -e '\\033[32mLogin %s done. Enjoy it.\\033[0m'\n" % host # Make a ssh connection ssh = paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect(host, port=port, username=username, password=password, compress=True) except paramiko.ssh_exception.AuthenticationException, paramiko.ssh_exception.SSHException: raise ServerError('Authentication Error.') except socket.error: raise ServerError('Connect SSH Socket Port Error, Please Correct it.') # Make a channel and set windows size global channel win_size = get_win_size() channel = ssh.invoke_shell(height=win_size[0], width=win_size[1]) try: signal.signal(signal.SIGWINCH, set_win_size) except: pass # Set PS1 and msg it channel.send(ps1) channel.send(login_msg) # Make ssh interactive tunnel posix_shell(channel, login_name, host) # Shutdown channel socket channel.close() ssh.close() def remote_exec_cmd(ip, port, username, password, cmd): try: time.sleep(5) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, port, username, password, timeout=5) stdin, stdout, stderr = ssh.exec_command("bash -l -c '%s'" % cmd) out = stdout.readlines() err = stderr.readlines() color_print('%s:' % ip, 'blue') for i in out: color_print(" " * 4 + i.strip(), 'green') for j in err: color_print(" " * 4 + j.strip(), 'red') ssh.close() except Exception as e: color_print(ip + ':', 'blue') color_print(str(e), 'red') def multi_remote_exec_cmd(hosts, username, cmd): pool = Pool(processes=5) for host in hosts: username, password, ip, port = get_connect_item(username, host) pool.apply_async(remote_exec_cmd, (ip, port, username, password, cmd)) pool.close() pool.join() def exec_cmd_servers(username): color_print("You can choose in the following IP(s), Use glob or ips split by comma. q/Q to PreLayer.", 'green') print_user_host(LOGIN_NAME) while True: hosts = [] inputs = raw_input('\033[1;32mip(s)>: \033[0m') if inputs in ['q', 'Q']: break get_hosts = get_user_host(username).keys() if ',' in inputs: ips_input = inputs.split(',') for host in ips_input: if host in get_hosts: hosts.append(host) else: for host in get_hosts: if fnmatch.fnmatch(host, inputs): hosts.append(host.strip()) if len(hosts) == 0: color_print("Check again, Not matched any ip!", 'red') continue else: print "You matched ip: %s" % hosts color_print("Input the Command , The command will be Execute on servers, q/Q to quit.", 'green') while True: cmd = raw_input('\033[1;32mCmd(s): \033[0m') if cmd in ['q', 'Q']: break exec_log_dir = os.path.join(LOG_DIR, 'exec_cmds') if not os.path.isdir(exec_log_dir): os.mkdir(exec_log_dir) os.chmod(exec_log_dir, 0777) filename = "%s/%s.log" % (exec_log_dir, time.strftime('%Y%m%d')) f = open(filename, 'a') f.write("DateTime: %s User: %s Host: %s Cmds: %s\n" % (time.strftime('%Y/%m/%d %H:%M:%S'), username, hosts, cmd)) multi_remote_exec_cmd(hosts, username, cmd) if __name__ == '__main__': print_prompt() gid_pattern = re.compile(r'^g\d+$') try: while True: try: option = raw_input("\033[1;32mOpt or IP>:\033[0m ") except EOFError: print continue except KeyboardInterrupt: sys.exit(0) if option in ['P', 'p']: print_user_host(LOGIN_NAME) continue elif option in ['G', 'g']: print_user_hostgroup(LOGIN_NAME) continue elif gid_pattern.match(option): gid = option[1:].strip() print_user_hostgroup_host(LOGIN_NAME, gid) continue elif option in ['E', 'e']: exec_cmd_servers(LOGIN_NAME) elif option in ['Q', 'q', 'exit']: sys.exit() else: try: verify_connect(LOGIN_NAME, option) except ServerError, e: color_print(e, 'red') except IndexError: pass
watchsky126/jumpserver
connect.py
Python
gpl-2.0
12,846
/* * This file is part of the UCB release of Plan 9. It is subject to the license * terms in the LICENSE file found in the top-level directory of this * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No * part of the UCB release of Plan 9, including this file, may be copied, * modified, propagated, or distributed except according to the terms contained * in the LICENSE file. */ #include "u.h" #include "lib.h" #include "dat.h" #include "fns.h" #include "error.h" #include "devip.h" void hnputl(void *p, unsigned long v); void hnputs(void *p, unsigned short v); unsigned long nhgetl(void *p); unsigned short nhgets(void *p); unsigned long parseip(char *to, char *from); void csclose(Chan*); long csread(Chan*, void*, long, vlong); long cswrite(Chan*, void*, long, vlong); void osipinit(void); enum { Qtopdir = 1, /* top level directory */ Qcs, Qprotodir, /* directory for a protocol */ Qclonus, Qconvdir, /* directory for a conversation */ Qdata, Qctl, Qstatus, Qremote, Qlocal, Qlisten, MAXPROTO = 4 }; #define TYPE(x) ((int)((x).path & 0xf)) #define CONV(x) ((int)(((x).path >> 4)&0xfff)) #define PROTO(x) ((int)(((x).path >> 16)&0xff)) #define QID(p, c, y) (((p)<<16) | ((c)<<4) | (y)) typedef struct Proto Proto; typedef struct Conv Conv; struct Conv { int x; Ref r; int sfd; int perm; char owner[KNAMELEN]; char* state; ulong laddr; ushort lport; ulong raddr; ushort rport; int restricted; char cerr[KNAMELEN]; Proto* p; }; struct Proto { Lock l; int x; int stype; char name[KNAMELEN]; int nc; int maxconv; Conv** conv; Qid qid; }; static int np; static Proto proto[MAXPROTO]; int eipfmt(Fmt*); static Conv* protoclone(Proto*, char*, int); static void setladdr(Conv*); int ipgen(Chan *c, char *nname, Dirtab *d, int nd, int s, Dir *dp) { Qid q; Conv *cv; char *p; USED(nname); q.vers = 0; q.type = 0; switch(TYPE(c->qid)) { case Qtopdir: if(s >= 1+np) return -1; if(s == 0){ q.path = QID(s, 0, Qcs); devdir(c, q, "cs", 0, "network", 0666, dp); }else{ s--; q.path = QID(s, 0, Qprotodir); q.type = QTDIR; devdir(c, q, proto[s].name, 0, "network", DMDIR|0555, dp); } return 1; case Qprotodir: if(s < proto[PROTO(c->qid)].nc) { cv = proto[PROTO(c->qid)].conv[s]; sprint(up->genbuf, "%d", s); q.path = QID(PROTO(c->qid), s, Qconvdir); q.type = QTDIR; devdir(c, q, up->genbuf, 0, cv->owner, DMDIR|0555, dp); return 1; } s -= proto[PROTO(c->qid)].nc; switch(s) { default: return -1; case 0: p = "clone"; q.path = QID(PROTO(c->qid), 0, Qclonus); break; } devdir(c, q, p, 0, "network", 0555, dp); return 1; case Qconvdir: cv = proto[PROTO(c->qid)].conv[CONV(c->qid)]; switch(s) { default: return -1; case 0: q.path = QID(PROTO(c->qid), CONV(c->qid), Qdata); devdir(c, q, "data", 0, cv->owner, cv->perm, dp); return 1; case 1: q.path = QID(PROTO(c->qid), CONV(c->qid), Qctl); devdir(c, q, "ctl", 0, cv->owner, cv->perm, dp); return 1; case 2: p = "status"; q.path = QID(PROTO(c->qid), CONV(c->qid), Qstatus); break; case 3: p = "remote"; q.path = QID(PROTO(c->qid), CONV(c->qid), Qremote); break; case 4: p = "local"; q.path = QID(PROTO(c->qid), CONV(c->qid), Qlocal); break; case 5: p = "listen"; q.path = QID(PROTO(c->qid), CONV(c->qid), Qlisten); break; } devdir(c, q, p, 0, cv->owner, 0444, dp); return 1; } return -1; } static void newproto(char *name, int type, int maxconv) { int l; Proto *p; if(np >= MAXPROTO) { print("no %s: increase MAXPROTO", name); return; } p = &proto[np]; strcpy(p->name, name); p->stype = type; p->qid.path = QID(np, 0, Qprotodir); p->qid.type = QTDIR; p->x = np++; p->maxconv = maxconv; l = sizeof(Conv*)*(p->maxconv+1); p->conv = mallocz(l, 1); if(p->conv == 0) panic("no memory"); } void ipinit(void) { osipinit(); newproto("udp", S_UDP, 10); newproto("tcp", S_TCP, 30); fmtinstall('I', eipfmt); fmtinstall('E', eipfmt); } Chan * ipattach(char *spec) { Chan *c; c = devattach('I', spec); c->qid.path = QID(0, 0, Qtopdir); c->qid.type = QTDIR; c->qid.vers = 0; return c; } static Walkqid* ipwalk(Chan *c, Chan *nc, char **name, int nname) { return devwalk(c, nc, name, nname, 0, 0, ipgen); } int ipstat(Chan *c, uchar *dp, int n) { return devstat(c, dp, n, 0, 0, ipgen); } Chan * ipopen(Chan *c, int omode) { Proto *p; ulong raddr; ushort rport; int perm, sfd; Conv *cv, *lcv; omode &= 3; perm = 0; switch(omode) { case OREAD: perm = 4; break; case OWRITE: perm = 2; break; case ORDWR: perm = 6; break; } switch(TYPE(c->qid)) { default: break; case Qtopdir: case Qprotodir: case Qconvdir: case Qstatus: case Qremote: case Qlocal: if(omode != OREAD) error(Eperm); break; case Qclonus: p = &proto[PROTO(c->qid)]; cv = protoclone(p, up->user, -1); if(cv == 0) error(Enodev); c->qid.path = QID(p->x, cv->x, Qctl); c->qid.vers = 0; break; case Qdata: case Qctl: p = &proto[PROTO(c->qid)]; lock(&p->l); cv = p->conv[CONV(c->qid)]; lock(&cv->r.lk); if((perm & (cv->perm>>6)) != perm) { if(strcmp(up->user, cv->owner) != 0 || (perm & cv->perm) != perm) { unlock(&cv->r.lk); unlock(&p->l); error(Eperm); } } cv->r.ref++; if(cv->r.ref == 1) { memmove(cv->owner, up->user, KNAMELEN); cv->perm = 0660; } unlock(&cv->r.lk); unlock(&p->l); break; case Qlisten: p = &proto[PROTO(c->qid)]; lcv = p->conv[CONV(c->qid)]; sfd = so_accept(lcv->sfd, &raddr, &rport); cv = protoclone(p, up->user, sfd); if(cv == 0) { close(sfd); error(Enodev); } cv->raddr = raddr; cv->rport = rport; setladdr(cv); cv->state = "Established"; c->qid.path = QID(p->x, cv->x, Qctl); break; } c->mode = openmode(omode); c->flag |= COPEN; c->offset = 0; return c; } void ipclose(Chan *c) { Conv *cc; switch(TYPE(c->qid)) { case Qcs: csclose(c); break; case Qdata: case Qctl: if((c->flag & COPEN) == 0) break; cc = proto[PROTO(c->qid)].conv[CONV(c->qid)]; if(decref(&cc->r) != 0) break; strcpy(cc->owner, "network"); cc->perm = 0666; cc->state = "Closed"; cc->laddr = 0; cc->raddr = 0; cc->lport = 0; cc->rport = 0; close(cc->sfd); break; } } long ipread(Chan *ch, void *a, long n, vlong offset) { int r; Conv *c; Proto *x; uchar ip[4]; char buf[128], *p; /*print("ipread %s %lux\n", c2name(ch), (long)ch->qid.path);*/ p = a; switch(TYPE(ch->qid)) { default: error(Eperm); case Qcs: return csread(ch, a, n, offset); case Qprotodir: case Qtopdir: case Qconvdir: return devdirread(ch, a, n, 0, 0, ipgen); case Qctl: sprint(buf, "%d", CONV(ch->qid)); return readstr(offset, p, n, buf); case Qremote: c = proto[PROTO(ch->qid)].conv[CONV(ch->qid)]; hnputl(ip, c->raddr); sprint(buf, "%I!%d\n", ip, c->rport); return readstr(offset, p, n, buf); case Qlocal: c = proto[PROTO(ch->qid)].conv[CONV(ch->qid)]; hnputl(ip, c->laddr); sprint(buf, "%I!%d\n", ip, c->lport); return readstr(offset, p, n, buf); case Qstatus: x = &proto[PROTO(ch->qid)]; c = x->conv[CONV(ch->qid)]; sprint(buf, "%s/%d %d %s \n", c->p->name, c->x, c->r.ref, c->state); return readstr(offset, p, n, buf); case Qdata: c = proto[PROTO(ch->qid)].conv[CONV(ch->qid)]; r = so_recv(c->sfd, a, n, 0); if(r < 0){ oserrstr(); nexterror(); } return r; } } static void setladdr(Conv *c) { so_getsockname(c->sfd, &c->laddr, &c->lport); } static void setlport(Conv *c) { if(c->restricted == 0 && c->lport == 0) return; so_bind(c->sfd, c->restricted, c->lport); } static void setladdrport(Conv *c, char *str) { char *p, addr[4]; p = strchr(str, '!'); if(p == 0) { p = str; c->laddr = 0; } else { *p++ = 0; parseip(addr, str); c->laddr = nhgetl((uchar*)addr); } if(*p == '*') c->lport = 0; else c->lport = atoi(p); setlport(c); } static char* setraddrport(Conv *c, char *str) { char *p, addr[4]; p = strchr(str, '!'); if(p == 0) return "malformed address"; *p++ = 0; parseip(addr, str); c->raddr = nhgetl((uchar*)addr); c->rport = atoi(p); p = strchr(p, '!'); if(p) { if(strcmp(p, "!r") == 0) c->restricted = 1; } return 0; } long ipwrite(Chan *ch, void *a, long n, vlong offset) { Conv *c; Proto *x; int r, nf; char *p, *fields[3], buf[128]; switch(TYPE(ch->qid)) { default: error(Eperm); case Qcs: return cswrite(ch, a, n, offset); case Qctl: x = &proto[PROTO(ch->qid)]; c = x->conv[CONV(ch->qid)]; if(n > sizeof(buf)-1) n = sizeof(buf)-1; memmove(buf, a, n); buf[n] = '\0'; nf = tokenize(buf, fields, 3); if(strcmp(fields[0], "connect") == 0){ switch(nf) { default: error("bad args to connect"); case 2: p = setraddrport(c, fields[1]); if(p != 0) error(p); break; case 3: p = setraddrport(c, fields[1]); if(p != 0) error(p); c->lport = atoi(fields[2]); setlport(c); break; } so_connect(c->sfd, c->raddr, c->rport); setladdr(c); c->state = "Established"; return n; } if(strcmp(fields[0], "announce") == 0) { switch(nf){ default: error("bad args to announce"); case 2: setladdrport(c, fields[1]); break; } so_listen(c->sfd); c->state = "Announced"; return n; } if(strcmp(fields[0], "bind") == 0){ switch(nf){ default: error("bad args to bind"); case 2: c->lport = atoi(fields[1]); break; } setlport(c); return n; } error("bad control message"); case Qdata: x = &proto[PROTO(ch->qid)]; c = x->conv[CONV(ch->qid)]; r = so_send(c->sfd, a, n, 0); if(r < 0){ oserrstr(); nexterror(); } return r; } return n; } static Conv* protoclone(Proto *p, char *user, int nfd) { Conv *c, **pp, **ep; c = 0; lock(&p->l); if(waserror()) { unlock(&p->l); nexterror(); } ep = &p->conv[p->maxconv]; for(pp = p->conv; pp < ep; pp++) { c = *pp; if(c == 0) { c = mallocz(sizeof(Conv), 1); if(c == 0) error(Enomem); lock(&c->r.lk); c->r.ref = 1; c->p = p; c->x = pp - p->conv; p->nc++; *pp = c; break; } lock(&c->r.lk); if(c->r.ref == 0) { c->r.ref++; break; } unlock(&c->r.lk); } if(pp >= ep) { unlock(&p->l); poperror(); return 0; } strcpy(c->owner, user); c->perm = 0660; c->state = "Closed"; c->restricted = 0; c->laddr = 0; c->raddr = 0; c->lport = 0; c->rport = 0; c->sfd = nfd; if(nfd == -1) c->sfd = so_socket(p->stype); unlock(&c->r.lk); unlock(&p->l); poperror(); return c; } enum { Isprefix= 16, }; uchar prefixvals[256] = { /*0x00*/ 0 | Isprefix, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*0x10*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*0x20*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*0x30*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*0x40*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*0x50*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*0x60*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*0x70*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*0x80*/ 1 | Isprefix, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*0x90*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*0xA0*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*0xB0*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*0xC0*/ 2 | Isprefix, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*0xD0*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*0xE0*/ 3 | Isprefix, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*0xF0*/ 4 | Isprefix, 0, 0, 0, 0, 0, 0, 0, /*0xF8*/ 5 | Isprefix, 0, 0, 0, /*0xFC*/ 6 | Isprefix, 0, /*0xFE*/ 7 | Isprefix, /*0xFF*/ 8 | Isprefix, }; int eipfmt(Fmt *f) { char buf[5*8]; static char *efmt = "%.2lux%.2lux%.2lux%.2lux%.2lux%.2lux"; static char *ifmt = "%d.%d.%d.%d"; uchar *p, ip[16]; ulong ul; switch(f->r) { case 'E': /* Ethernet address */ p = va_arg(f->args, uchar*); snprint(buf, sizeof buf, efmt, p[0], p[1], p[2], p[3], p[4], p[5]); return fmtstrcpy(f, buf); case 'I': ul = va_arg(f->args, ulong); hnputl(ip, ul); snprint(buf, sizeof buf, ifmt, ip[0], ip[1], ip[2], ip[3]); return fmtstrcpy(f, buf); } return fmtstrcpy(f, "(eipfmt)"); } void hnputl(void *p, unsigned long v) { unsigned char *a; a = p; a[0] = v>>24; a[1] = v>>16; a[2] = v>>8; a[3] = v; } void hnputs(void *p, unsigned short v) { unsigned char *a; a = p; a[0] = v>>8; a[1] = v; } unsigned long nhgetl(void *p) { unsigned char *a; a = p; return (a[0]<<24)|(a[1]<<16)|(a[2]<<8)|(a[3]<<0); } unsigned short nhgets(void *p) { unsigned char *a; a = p; return (a[0]<<8)|(a[1]<<0); } #define CLASS(p) ((*(unsigned char*)(p))>>6) unsigned long parseip(char *to, char *from) { int i; char *p; p = from; memset(to, 0, 4); for(i = 0; i < 4 && *p; i++){ to[i] = strtoul(p, &p, 10); if(*p != '.' && *p != 0){ memset(to, 0, 4); return 0; } if(*p == '.') p++; } switch(CLASS(to)){ case 0: /* class A - 1 byte net */ case 1: if(i == 3){ to[3] = to[2]; to[2] = to[1]; to[1] = 0; } else if (i == 2){ to[3] = to[1]; to[1] = 0; } break; case 2: /* class B - 2 byte net */ if(i == 3){ to[3] = to[2]; to[2] = 0; } break; } return nhgetl(to); } void csclose(Chan *c) { free(c->aux); } long csread(Chan *c, void *a, long n, vlong offset) { if(c->aux == nil) return 0; return readstr(offset, a, n, c->aux); } static struct { char *name; uint num; } tab[] = { "cs", 1, "echo", 7, "discard", 9, "systat", 11, "daytime", 13, "netstat", 15, "chargen", 19, "ftp-data", 20, "ftp", 21, "ssh", 22, "telnet", 23, "smtp", 25, "time", 37, "whois", 43, "dns", 53, "domain", 53, "uucp", 64, "gopher", 70, "rje", 77, "finger", 79, "http", 80, "link", 87, "supdup", 95, "hostnames", 101, "iso-tsap", 102, "x400", 103, "x400-snd", 104, "csnet-ns", 105, "pop-2", 109, "pop3", 110, "portmap", 111, "uucp-path", 117, "nntp", 119, "netbios", 139, "imap4", 143, "NeWS", 144, "print-srv", 170, "z39.50", 210, "fsb", 400, "sysmon", 401, "proxy", 402, "proxyd", 404, "https", 443, "cifs", 445, "ssmtp", 465, "rexec", 512, "login", 513, "shell", 514, "printer", 515, "courier", 530, "cscan", 531, "uucp", 540, "snntp", 563, "9fs", 564, "whoami", 565, "guard", 566, "ticket", 567, "dlsftp", 666, "fmclient", 729, "imaps", 993, "pop3s", 995, "ingreslock", 1524, "pptp", 1723, "nfs", 2049, "webster", 2627, "weather", 3000, "secstore", 5356, "Xdisplay", 6000, "styx", 6666, "mpeg", 6667, "rstyx", 6668, "infdb", 6669, "infsigner", 6671, "infcsigner", 6672, "inflogin", 6673, "bandt", 7330, "face", 32000, "dhashgate", 11978, "exportfs", 17007, "rexexec", 17009, "ncpu", 17010, "cpu", 17013, "glenglenda1", 17020, "glenglenda2", 17021, "glenglenda3", 17022, "glenglenda4", 17023, "glenglenda5", 17024, "glenglenda6", 17025, "glenglenda7", 17026, "glenglenda8", 17027, "glenglenda9", 17028, "glenglenda10", 17029, "flyboy", 17032, "dlsftp", 17033, "venti", 17034, "wiki", 17035, "vica", 17036, 0 }; static int lookupport(char *s) { int i; char buf[10], *p; i = strtol(s, &p, 0); if(*s && *p == 0) return i; i = so_getservbyname(s, "tcp", buf); if(i != -1) return atoi(buf); for(i=0; tab[i].name; i++) if(strcmp(s, tab[i].name) == 0) return tab[i].num; return 0; } static ulong lookuphost(char *s) { char to[4]; ulong ip; memset(to, 0, sizeof to); parseip(to, s); ip = nhgetl(to); if(ip != 0) return ip; if((s = hostlookup(s)) == nil) return 0; parseip(to, s); ip = nhgetl(to); free(s); return ip; } long cswrite(Chan *c, void *a, long n, vlong offset) { char *f[4]; char *s, *ns; ulong ip; int nf, port; s = malloc(n+1); if(s == nil) error(Enomem); if(waserror()){ free(s); nexterror(); } memmove(s, a, n); s[n] = 0; nf = getfields(s, f, nelem(f), 0, "!"); if(nf != 3) error("can't translate"); port = lookupport(f[2]); if(port <= 0) error("no translation for port found"); ip = lookuphost(f[1]); if(ip == 0) error("no translation for host found"); ns = smprint("/net/%s/clone %I!%d", f[0], ip, port); if(ns == nil) error(Enomem); free(c->aux); c->aux = ns; poperror(); free(s); return n; } Dev ipdevtab = { 'I', "ip", devreset, ipinit, devshutdown, ipattach, ipwalk, ipstat, ipopen, devcreate, ipclose, ipread, devbread, ipwrite, devbwrite, devremove, devwstat, };
rminnich/k9
sys/src/cmd/unix/drawterm/kern/devip.c
C
gpl-2.0
16,525
/* * COPYRIGHT (c) 1989-2007. * 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. * * $Id: act_cyc.c,v 1.2 2009/01/01 15:13:07 ralf Exp $ */ #if HAVE_CONFIG_H #include "config.h" #endif #include <rtems/itron.h> #include <rtems/score/thread.h> #include <rtems/score/tod.h> #include <rtems/itron/time.h> /* * act_cyc - Activate Cyclic Handler */ ER act_cyc( HNO cycno __attribute__((unused)), UINT cycact ) { Watchdog_Control *object; if(cycact != TCY_OFF || cycact != TCY_ON) return E_PAR; #if 0 if( object->Object_ID != cycno) return E_NOEXS; #endif _Watchdog_Activate(object); return E_OK; }
yunusdawji/rtems-at91sam9g20ek
cpukit/itron/src/act_cyc.c
C
gpl-2.0
802
#section support_code_apply int APPLY_SPECIFIC(conv_desc)(PyArrayObject *filt_shp, cudnnConvolutionDescriptor_t *desc) { cudnnStatus_t err; int pad[3] = {PAD_0, PAD_1, PAD_2}; int strides[3] = {SUB_0, SUB_1, SUB_2}; int upscale[3] = {1, 1, 1}; #if BORDER_MODE == 0 pad[0] = *(npy_int64 *)PyArray_GETPTR1(filt_shp, 2) - 1; pad[1] = *(npy_int64 *)PyArray_GETPTR1(filt_shp, 3) - 1; #if NB_DIMS > 2 pad[2] = *(npy_int64 *)PyArray_GETPTR1(filt_shp, 4) - 1; #endif #endif if (PyArray_DIM(filt_shp, 0) - 2 != NB_DIMS) { PyErr_Format(PyExc_ValueError, "Filter shape has too many dimensions: " "expected %d, got %lld.", NB_DIMS, (long long)PyArray_DIM(filt_shp, 0)); return -1; } err = cudnnCreateConvolutionDescriptor(desc); if (err != CUDNN_STATUS_SUCCESS) { PyErr_Format(PyExc_MemoryError, "could not allocate convolution " "descriptor: %s", cudnnGetErrorString(err)); return -1; } err = cudnnSetConvolutionNdDescriptor(*desc, NB_DIMS, pad, strides, upscale, CONV_MODE); return 0; }
valexandersaulys/airbnb_kaggle_contest
venv/lib/python3.4/site-packages/Theano-0.7.0-py3.4.egg/theano/sandbox/gpuarray/conv_desc.c
C
gpl-2.0
1,147
/* Copyright (c) 2012-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. */ #include <linux/module.h> #include <linux/interrupt.h> #include <linux/of.h> #include <linux/of_gpio.h> #include <linux/gpio.h> #include <linux/qpnp/pin.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/leds.h> #include <linux/qpnp/pwm.h> #include <linux/err.h> #include "mdss_dsi.h" #define DT_CMD_HDR 6 DEFINE_LED_TRIGGER(bl_led_trigger); void mdss_dsi_panel_pwm_cfg(struct mdss_dsi_ctrl_pdata *ctrl) { ctrl->pwm_bl = pwm_request(ctrl->pwm_lpg_chan, "lcd-bklt"); if (ctrl->pwm_bl == NULL || IS_ERR(ctrl->pwm_bl)) { pr_err("%s: Error: lpg_chan=%d pwm request failed", __func__, ctrl->pwm_lpg_chan); } } static void mdss_dsi_panel_bklt_pwm(struct mdss_dsi_ctrl_pdata *ctrl, int level) { int ret; u32 duty; if (ctrl->pwm_bl == NULL) { pr_err("%s: no PWM\n", __func__); return; } if (level == 0) { if (ctrl->pwm_enabled) pwm_disable(ctrl->pwm_bl); ctrl->pwm_enabled = 0; return; } duty = level * ctrl->pwm_period; duty /= ctrl->bklt_max; pr_debug("%s: bklt_ctrl=%d pwm_period=%d pwm_gpio=%d pwm_lpg_chan=%d\n", __func__, ctrl->bklt_ctrl, ctrl->pwm_period, ctrl->pwm_pmic_gpio, ctrl->pwm_lpg_chan); pr_debug("%s: ndx=%d level=%d duty=%d\n", __func__, ctrl->ndx, level, duty); if (ctrl->pwm_enabled) { pwm_disable(ctrl->pwm_bl); ctrl->pwm_enabled = 0; } ret = pwm_config_us(ctrl->pwm_bl, duty, ctrl->pwm_period); if (ret) { pr_err("%s: pwm_config_us() failed err=%d.\n", __func__, ret); return; } ret = pwm_enable(ctrl->pwm_bl); if (ret) pr_err("%s: pwm_enable() failed err=%d\n", __func__, ret); ctrl->pwm_enabled = 1; } static char dcs_cmd[2] = {0x54, 0x00}; /* DTYPE_DCS_READ */ static struct dsi_cmd_desc dcs_read_cmd = { {DTYPE_DCS_READ, 1, 0, 1, 5, sizeof(dcs_cmd)}, dcs_cmd }; u32 mdss_dsi_panel_cmd_read(struct mdss_dsi_ctrl_pdata *ctrl, char cmd0, char cmd1, void (*fxn)(int), char *rbuf, int len) { struct dcs_cmd_req cmdreq; dcs_cmd[0] = cmd0; dcs_cmd[1] = cmd1; memset(&cmdreq, 0, sizeof(cmdreq)); cmdreq.cmds = &dcs_read_cmd; cmdreq.cmds_cnt = 1; cmdreq.flags = CMD_REQ_RX | CMD_REQ_COMMIT; cmdreq.rlen = len; cmdreq.rbuf = rbuf; cmdreq.cb = fxn; /* call back */ mdss_dsi_cmdlist_put(ctrl, &cmdreq); /* * blocked here, until call back called */ return 0; } static void mdss_dsi_panel_cmds_send(struct mdss_dsi_ctrl_pdata *ctrl, struct dsi_panel_cmds *pcmds) { struct dcs_cmd_req cmdreq; memset(&cmdreq, 0, sizeof(cmdreq)); cmdreq.cmds = pcmds->cmds; cmdreq.cmds_cnt = pcmds->cmd_cnt; cmdreq.flags = CMD_REQ_COMMIT; /*Panel ON/Off commands should be sent in DSI Low Power Mode*/ if (pcmds->link_state == DSI_LP_MODE) cmdreq.flags |= CMD_REQ_LP_MODE; cmdreq.rlen = 0; cmdreq.cb = NULL; mdss_dsi_cmdlist_put(ctrl, &cmdreq); } static char led_pwm1[2] = {0x51, 0x0}; /* DTYPE_DCS_WRITE1 */ static struct dsi_cmd_desc backlight_cmd = { {DTYPE_DCS_WRITE1, 1, 0, 0, 1, sizeof(led_pwm1)}, led_pwm1 }; static void mdss_dsi_panel_bklt_dcs(struct mdss_dsi_ctrl_pdata *ctrl, int level) { struct dcs_cmd_req cmdreq; pr_debug("%s: level=%d\n", __func__, level); led_pwm1[1] = (unsigned char)level; memset(&cmdreq, 0, sizeof(cmdreq)); cmdreq.cmds = &backlight_cmd; cmdreq.cmds_cnt = 1; cmdreq.flags = CMD_REQ_COMMIT | CMD_CLK_CTRL; cmdreq.rlen = 0; cmdreq.cb = NULL; mdss_dsi_cmdlist_put(ctrl, &cmdreq); } static int mdss_dsi_request_gpios(struct mdss_dsi_ctrl_pdata *ctrl_pdata) { int rc = 0; if (gpio_is_valid(ctrl_pdata->disp_en_gpio)) { rc = gpio_request(ctrl_pdata->disp_en_gpio, "disp_enable"); if (rc) { pr_err("request disp_en gpio failed, rc=%d\n", rc); goto disp_en_gpio_err; } } rc = gpio_request(ctrl_pdata->rst_gpio, "disp_rst_n"); if (rc) { pr_err("request reset gpio failed, rc=%d\n", rc); goto rst_gpio_err; } if (gpio_is_valid(ctrl_pdata->bklt_en_gpio)) { rc = gpio_request(ctrl_pdata->bklt_en_gpio, "bklt_enable"); if (rc) { pr_err("request bklt gpio failed, rc=%d\n", rc); goto bklt_en_gpio_err; } } if (gpio_is_valid(ctrl_pdata->mode_gpio)) { rc = gpio_request(ctrl_pdata->mode_gpio, "panel_mode"); if (rc) { pr_err("request panel mode gpio failed,rc=%d\n", rc); goto mode_gpio_err; } } return rc; mode_gpio_err: if (gpio_is_valid(ctrl_pdata->bklt_en_gpio)) gpio_free(ctrl_pdata->bklt_en_gpio); bklt_en_gpio_err: gpio_free(ctrl_pdata->rst_gpio); rst_gpio_err: if (gpio_is_valid(ctrl_pdata->disp_en_gpio)) gpio_free(ctrl_pdata->disp_en_gpio); disp_en_gpio_err: return rc; } int mdss_dsi_panel_reset(struct mdss_panel_data *pdata, int enable) { struct mdss_dsi_ctrl_pdata *ctrl_pdata = NULL; struct mdss_panel_info *pinfo = NULL; int i, rc = 0; if (pdata == NULL) { pr_err("%s: Invalid input data\n", __func__); return -EINVAL; } ctrl_pdata = container_of(pdata, struct mdss_dsi_ctrl_pdata, panel_data); if (!gpio_is_valid(ctrl_pdata->disp_en_gpio)) { pr_debug("%s:%d, reset line not configured\n", __func__, __LINE__); } if (!gpio_is_valid(ctrl_pdata->rst_gpio)) { pr_debug("%s:%d, reset line not configured\n", __func__, __LINE__); return rc; } pr_debug("%s: enable = %d\n", __func__, enable); pinfo = &(ctrl_pdata->panel_data.panel_info); if (enable) { rc = mdss_dsi_request_gpios(ctrl_pdata); if (rc) { pr_err("gpio request failed\n"); return rc; } if (!pinfo->panel_power_on) { if (gpio_is_valid(ctrl_pdata->disp_en_gpio)) gpio_set_value((ctrl_pdata->disp_en_gpio), 1); for (i = 0; i < pdata->panel_info.rst_seq_len; ++i) { gpio_set_value((ctrl_pdata->rst_gpio), pdata->panel_info.rst_seq[i]); if (pdata->panel_info.rst_seq[++i]) usleep(pinfo->rst_seq[i] * 1000); } if (gpio_is_valid(ctrl_pdata->bklt_en_gpio)) gpio_set_value((ctrl_pdata->bklt_en_gpio), 1); } if (gpio_is_valid(ctrl_pdata->mode_gpio)) { if (pinfo->mode_gpio_state == MODE_GPIO_HIGH) gpio_set_value((ctrl_pdata->mode_gpio), 1); else if (pinfo->mode_gpio_state == MODE_GPIO_LOW) gpio_set_value((ctrl_pdata->mode_gpio), 0); } if (ctrl_pdata->ctrl_state & CTRL_STATE_PANEL_INIT) { pr_debug("%s: Panel Not properly turned OFF\n", __func__); ctrl_pdata->ctrl_state &= ~CTRL_STATE_PANEL_INIT; pr_debug("%s: Reset panel done\n", __func__); } } else { if (gpio_is_valid(ctrl_pdata->bklt_en_gpio)) { gpio_set_value((ctrl_pdata->bklt_en_gpio), 0); gpio_free(ctrl_pdata->bklt_en_gpio); } if (gpio_is_valid(ctrl_pdata->disp_en_gpio)) { gpio_set_value((ctrl_pdata->disp_en_gpio), 0); gpio_free(ctrl_pdata->disp_en_gpio); } gpio_set_value((ctrl_pdata->rst_gpio), 0); gpio_free(ctrl_pdata->rst_gpio); if (gpio_is_valid(ctrl_pdata->mode_gpio)) gpio_free(ctrl_pdata->mode_gpio); } return rc; } static char caset[] = {0x2a, 0x00, 0x00, 0x03, 0x00}; /* DTYPE_DCS_LWRITE */ static char paset[] = {0x2b, 0x00, 0x00, 0x05, 0x00}; /* DTYPE_DCS_LWRITE */ static struct dsi_cmd_desc partial_update_enable_cmd[] = { {{DTYPE_DCS_LWRITE, 1, 0, 0, 1, sizeof(caset)}, caset}, {{DTYPE_DCS_LWRITE, 1, 0, 0, 1, sizeof(paset)}, paset}, }; static int mdss_dsi_panel_partial_update(struct mdss_panel_data *pdata) { struct mipi_panel_info *mipi; struct mdss_dsi_ctrl_pdata *ctrl = NULL; struct dcs_cmd_req cmdreq; int rc = 0; if (pdata == NULL) { pr_err("%s: Invalid input data\n", __func__); return -EINVAL; } ctrl = container_of(pdata, struct mdss_dsi_ctrl_pdata, panel_data); mipi = &pdata->panel_info.mipi; pr_debug("%s: ctrl=%p ndx=%d\n", __func__, ctrl, ctrl->ndx); caset[1] = (((pdata->panel_info.roi_x) & 0xFF00) >> 8); caset[2] = (((pdata->panel_info.roi_x) & 0xFF)); caset[3] = (((pdata->panel_info.roi_x - 1 + pdata->panel_info.roi_w) & 0xFF00) >> 8); caset[4] = (((pdata->panel_info.roi_x - 1 + pdata->panel_info.roi_w) & 0xFF)); partial_update_enable_cmd[0].payload = caset; paset[1] = (((pdata->panel_info.roi_y) & 0xFF00) >> 8); paset[2] = (((pdata->panel_info.roi_y) & 0xFF)); paset[3] = (((pdata->panel_info.roi_y - 1 + pdata->panel_info.roi_h) & 0xFF00) >> 8); paset[4] = (((pdata->panel_info.roi_y - 1 + pdata->panel_info.roi_h) & 0xFF)); partial_update_enable_cmd[1].payload = paset; pr_debug("%s: enabling partial update\n", __func__); memset(&cmdreq, 0, sizeof(cmdreq)); cmdreq.cmds = partial_update_enable_cmd; cmdreq.cmds_cnt = 2; cmdreq.flags = CMD_REQ_COMMIT | CMD_CLK_CTRL; cmdreq.rlen = 0; cmdreq.cb = NULL; mdss_dsi_cmdlist_put(ctrl, &cmdreq); return rc; } static void mdss_dsi_panel_bl_ctrl(struct mdss_panel_data *pdata, u32 bl_level) { struct mdss_dsi_ctrl_pdata *ctrl_pdata = NULL; if (pdata == NULL) { pr_err("%s: Invalid input data\n", __func__); return; } ctrl_pdata = container_of(pdata, struct mdss_dsi_ctrl_pdata, panel_data); /* * Some backlight controllers specify a minimum duty cycle * for the backlight brightness. If the brightness is less * than it, the controller can malfunction. */ if ((bl_level < pdata->panel_info.bl_min) && (bl_level != 0)) bl_level = pdata->panel_info.bl_min; switch (ctrl_pdata->bklt_ctrl) { case BL_WLED: led_trigger_event(bl_led_trigger, bl_level); break; case BL_PWM: mdss_dsi_panel_bklt_pwm(ctrl_pdata, bl_level); break; case BL_DCS_CMD: mdss_dsi_panel_bklt_dcs(ctrl_pdata, bl_level); if (mdss_dsi_is_master_ctrl(ctrl_pdata)) { struct mdss_dsi_ctrl_pdata *sctrl = mdss_dsi_get_slave_ctrl(); if (!sctrl) { pr_err("%s: Invalid slave ctrl data\n", __func__); return; } mdss_dsi_panel_bklt_dcs(sctrl, bl_level); } break; default: pr_err("%s: Unknown bl_ctrl configuration\n", __func__); break; } } static int mdss_dsi_panel_on(struct mdss_panel_data *pdata) { struct mipi_panel_info *mipi; struct mdss_dsi_ctrl_pdata *ctrl = NULL; if (pdata == NULL) { pr_err("%s: Invalid input data\n", __func__); return -EINVAL; } ctrl = container_of(pdata, struct mdss_dsi_ctrl_pdata, panel_data); mipi = &pdata->panel_info.mipi; pr_debug("%s: ctrl=%p ndx=%d\n", __func__, ctrl, ctrl->ndx); if (ctrl->on_cmds.cmd_cnt) mdss_dsi_panel_cmds_send(ctrl, &ctrl->on_cmds); pr_debug("%s:-\n", __func__); return 0; } static int mdss_dsi_panel_off(struct mdss_panel_data *pdata) { struct mipi_panel_info *mipi; struct mdss_dsi_ctrl_pdata *ctrl = NULL; if (pdata == NULL) { pr_err("%s: Invalid input data\n", __func__); return -EINVAL; } ctrl = container_of(pdata, struct mdss_dsi_ctrl_pdata, panel_data); pr_debug("%s: ctrl=%p ndx=%d\n", __func__, ctrl, ctrl->ndx); mipi = &pdata->panel_info.mipi; if (ctrl->off_cmds.cmd_cnt) mdss_dsi_panel_cmds_send(ctrl, &ctrl->off_cmds); pr_debug("%s:-\n", __func__); return 0; } static void mdss_dsi_parse_lane_swap(struct device_node *np, char *dlane_swap) { const char *data; *dlane_swap = DSI_LANE_MAP_0123; data = of_get_property(np, "qcom,mdss-dsi-lane-map", NULL); if (data) { if (!strcmp(data, "lane_map_3012")) *dlane_swap = DSI_LANE_MAP_3012; else if (!strcmp(data, "lane_map_2301")) *dlane_swap = DSI_LANE_MAP_2301; else if (!strcmp(data, "lane_map_1230")) *dlane_swap = DSI_LANE_MAP_1230; else if (!strcmp(data, "lane_map_0321")) *dlane_swap = DSI_LANE_MAP_0321; else if (!strcmp(data, "lane_map_1032")) *dlane_swap = DSI_LANE_MAP_1032; else if (!strcmp(data, "lane_map_2103")) *dlane_swap = DSI_LANE_MAP_2103; else if (!strcmp(data, "lane_map_3210")) *dlane_swap = DSI_LANE_MAP_3210; } } static void mdss_dsi_parse_trigger(struct device_node *np, char *trigger, char *trigger_key) { const char *data; *trigger = DSI_CMD_TRIGGER_SW; data = of_get_property(np, trigger_key, NULL); if (data) { if (!strcmp(data, "none")) *trigger = DSI_CMD_TRIGGER_NONE; else if (!strcmp(data, "trigger_te")) *trigger = DSI_CMD_TRIGGER_TE; else if (!strcmp(data, "trigger_sw_seof")) *trigger = DSI_CMD_TRIGGER_SW_SEOF; else if (!strcmp(data, "trigger_sw_te")) *trigger = DSI_CMD_TRIGGER_SW_TE; } } static int mdss_dsi_parse_dcs_cmds(struct device_node *np, struct dsi_panel_cmds *pcmds, char *cmd_key, char *link_key) { const char *data; int blen = 0, len; char *buf, *bp; struct dsi_ctrl_hdr *dchdr; int i, cnt; data = of_get_property(np, cmd_key, &blen); if (!data) { pr_err("%s: failed, key=%s\n", __func__, cmd_key); return -ENOMEM; } buf = kzalloc(sizeof(char) * blen, GFP_KERNEL); if (!buf) return -ENOMEM; memcpy(buf, data, blen); /* scan dcs commands */ bp = buf; len = blen; cnt = 0; while (len >= sizeof(*dchdr)) { dchdr = (struct dsi_ctrl_hdr *)bp; dchdr->dlen = ntohs(dchdr->dlen); if (dchdr->dlen > len) { pr_err("%s: dtsi cmd=%x error, len=%d", __func__, dchdr->dtype, dchdr->dlen); goto exit_free; } bp += sizeof(*dchdr); len -= sizeof(*dchdr); bp += dchdr->dlen; len -= dchdr->dlen; cnt++; } if (len != 0) { pr_err("%s: dcs_cmd=%x len=%d error!", __func__, buf[0], blen); goto exit_free; } pcmds->cmds = kzalloc(cnt * sizeof(struct dsi_cmd_desc), GFP_KERNEL); if (!pcmds->cmds) goto exit_free; pcmds->cmd_cnt = cnt; pcmds->buf = buf; pcmds->blen = blen; bp = buf; len = blen; for (i = 0; i < cnt; i++) { dchdr = (struct dsi_ctrl_hdr *)bp; len -= sizeof(*dchdr); bp += sizeof(*dchdr); pcmds->cmds[i].dchdr = *dchdr; pcmds->cmds[i].payload = bp; bp += dchdr->dlen; len -= dchdr->dlen; } data = of_get_property(np, link_key, NULL); if (data && !strcmp(data, "dsi_hs_mode")) pcmds->link_state = DSI_HS_MODE; else pcmds->link_state = DSI_LP_MODE; pr_debug("%s: dcs_cmd=%x len=%d, cmd_cnt=%d link_state=%d\n", __func__, pcmds->buf[0], pcmds->blen, pcmds->cmd_cnt, pcmds->link_state); return 0; exit_free: kfree(buf); return -ENOMEM; } static int mdss_panel_dt_get_dst_fmt(u32 bpp, char mipi_mode, u32 pixel_packing, char *dst_format) { int rc = 0; switch (bpp) { case 3: *dst_format = DSI_CMD_DST_FORMAT_RGB111; break; case 8: *dst_format = DSI_CMD_DST_FORMAT_RGB332; break; case 12: *dst_format = DSI_CMD_DST_FORMAT_RGB444; break; case 16: switch (mipi_mode) { case DSI_VIDEO_MODE: *dst_format = DSI_VIDEO_DST_FORMAT_RGB565; break; case DSI_CMD_MODE: *dst_format = DSI_CMD_DST_FORMAT_RGB565; break; default: *dst_format = DSI_VIDEO_DST_FORMAT_RGB565; break; } break; case 18: switch (mipi_mode) { case DSI_VIDEO_MODE: if (pixel_packing == 0) *dst_format = DSI_VIDEO_DST_FORMAT_RGB666; else *dst_format = DSI_VIDEO_DST_FORMAT_RGB666_LOOSE; break; case DSI_CMD_MODE: *dst_format = DSI_CMD_DST_FORMAT_RGB666; break; default: if (pixel_packing == 0) *dst_format = DSI_VIDEO_DST_FORMAT_RGB666; else *dst_format = DSI_VIDEO_DST_FORMAT_RGB666_LOOSE; break; } break; case 24: switch (mipi_mode) { case DSI_VIDEO_MODE: *dst_format = DSI_VIDEO_DST_FORMAT_RGB888; break; case DSI_CMD_MODE: *dst_format = DSI_CMD_DST_FORMAT_RGB888; break; default: *dst_format = DSI_VIDEO_DST_FORMAT_RGB888; break; } break; default: rc = -EINVAL; break; } return rc; } static int mdss_dsi_parse_fbc_params(struct device_node *np, struct mdss_panel_info *panel_info) { int rc, fbc_enabled = 0; u32 tmp; fbc_enabled = of_property_read_bool(np, "qcom,mdss-dsi-fbc-enable"); if (fbc_enabled) { pr_debug("%s:%d FBC panel enabled.\n", __func__, __LINE__); panel_info->fbc.enabled = 1; rc = of_property_read_u32(np, "qcom,mdss-dsi-fbc-bpp", &tmp); panel_info->fbc.target_bpp = (!rc ? tmp : panel_info->bpp); rc = of_property_read_u32(np, "qcom,mdss-dsi-fbc-packing", &tmp); panel_info->fbc.comp_mode = (!rc ? tmp : 0); panel_info->fbc.qerr_enable = of_property_read_bool(np, "qcom,mdss-dsi-fbc-quant-error"); rc = of_property_read_u32(np, "qcom,mdss-dsi-fbc-bias", &tmp); panel_info->fbc.cd_bias = (!rc ? tmp : 0); panel_info->fbc.pat_enable = of_property_read_bool(np, "qcom,mdss-dsi-fbc-pat-mode"); panel_info->fbc.vlc_enable = of_property_read_bool(np, "qcom,mdss-dsi-fbc-vlc-mode"); panel_info->fbc.bflc_enable = of_property_read_bool(np, "qcom,mdss-dsi-fbc-bflc-mode"); rc = of_property_read_u32(np, "qcom,mdss-dsi-fbc-h-line-budget", &tmp); panel_info->fbc.line_x_budget = (!rc ? tmp : 0); rc = of_property_read_u32(np, "qcom,mdss-dsi-fbc-budget-ctrl", &tmp); panel_info->fbc.block_x_budget = (!rc ? tmp : 0); rc = of_property_read_u32(np, "qcom,mdss-dsi-fbc-block-budget", &tmp); panel_info->fbc.block_budget = (!rc ? tmp : 0); rc = of_property_read_u32(np, "qcom,mdss-dsi-fbc-lossless-threshold", &tmp); panel_info->fbc.lossless_mode_thd = (!rc ? tmp : 0); rc = of_property_read_u32(np, "qcom,mdss-dsi-fbc-lossy-threshold", &tmp); panel_info->fbc.lossy_mode_thd = (!rc ? tmp : 0); rc = of_property_read_u32(np, "qcom,mdss-dsi-fbc-rgb-threshold", &tmp); panel_info->fbc.lossy_rgb_thd = (!rc ? tmp : 0); rc = of_property_read_u32(np, "qcom,mdss-dsi-fbc-lossy-mode-idx", &tmp); panel_info->fbc.lossy_mode_idx = (!rc ? tmp : 0); } else { pr_debug("%s:%d Panel does not support FBC.\n", __func__, __LINE__); panel_info->fbc.enabled = 0; panel_info->fbc.target_bpp = panel_info->bpp; } return 0; } static void mdss_panel_parse_te_params(struct device_node *np, struct mdss_panel_info *panel_info) { u32 tmp; int rc = 0; /* * TE default: dsi byte clock calculated base on 70 fps; * around 14 ms to complete a kickoff cycle if te disabled; * vclk_line base on 60 fps; write is faster than read; * init == start == rdptr; */ panel_info->te.tear_check_en = !of_property_read_bool(np, "qcom,mdss-tear-check-disable"); rc = of_property_read_u32 (np, "qcom,mdss-tear-check-sync-cfg-height", &tmp); panel_info->te.sync_cfg_height = (!rc ? tmp : 0xfff0); rc = of_property_read_u32 (np, "qcom,mdss-tear-check-sync-init-val", &tmp); panel_info->te.vsync_init_val = (!rc ? tmp : panel_info->yres); rc = of_property_read_u32 (np, "qcom,mdss-tear-check-sync-threshold-start", &tmp); panel_info->te.sync_threshold_start = (!rc ? tmp : 4); rc = of_property_read_u32 (np, "qcom,mdss-tear-check-sync-threshold-continue", &tmp); panel_info->te.sync_threshold_continue = (!rc ? tmp : 4); rc = of_property_read_u32(np, "qcom,mdss-tear-check-start-pos", &tmp); panel_info->te.start_pos = (!rc ? tmp : panel_info->yres); rc = of_property_read_u32 (np, "qcom,mdss-tear-check-rd-ptr-trigger-intr", &tmp); panel_info->te.rd_ptr_irq = (!rc ? tmp : panel_info->yres + 1); rc = of_property_read_u32(np, "qcom,mdss-tear-check-frame-rate", &tmp); panel_info->te.refx100 = (!rc ? tmp : 6000); } static int mdss_dsi_parse_reset_seq(struct device_node *np, u32 rst_seq[MDSS_DSI_RST_SEQ_LEN], u32 *rst_len, const char *name) { int num = 0, i; int rc; struct property *data; u32 tmp[MDSS_DSI_RST_SEQ_LEN]; *rst_len = 0; data = of_find_property(np, name, &num); num /= sizeof(u32); if (!data || !num || num > MDSS_DSI_RST_SEQ_LEN || num % 2) { pr_debug("%s:%d, error reading %s, length found = %d\n", __func__, __LINE__, name, num); } else { rc = of_property_read_u32_array(np, name, tmp, num); if (rc) pr_debug("%s:%d, error reading %s, rc = %d\n", __func__, __LINE__, name, rc); else { for (i = 0; i < num; ++i) rst_seq[i] = tmp[i]; *rst_len = num; } } return 0; } static void mdss_dsi_parse_roi_alignment(struct device_node *np, struct mdss_panel_info *pinfo) { int len = 0; u32 value[4]; struct property *data; data = of_find_property(np, "qcom,panel-roi-alignment", &len); len /= sizeof(u32); if (!data || (len != 4)) { pr_debug("%s: Panel roi alignment not found", __func__); } else { int rc = of_property_read_u32_array(np, "qcom,panel-roi-alignment", value, len); if (rc) pr_debug("%s: Error reading panel roi alignment values", __func__); else { pinfo->xstart_pix_align = value[0]; pinfo->width_pix_align = value[1]; pinfo->ystart_pix_align = value[2]; pinfo->height_pix_align = value[3]; } pr_debug("%s: coordinate rules: [%d, %d, %d, %d]", __func__, pinfo->xstart_pix_align, pinfo->width_pix_align, pinfo->ystart_pix_align, pinfo->height_pix_align); } } static int mdss_dsi_parse_panel_features(struct device_node *np, struct mdss_dsi_ctrl_pdata *ctrl) { struct mdss_panel_info *pinfo; if (!np || !ctrl) { pr_err("%s: Invalid arguments\n", __func__); return -ENODEV; } pinfo = &ctrl->panel_data.panel_info; pinfo->cont_splash_enabled = of_property_read_bool(np, "qcom,cont-splash-enabled"); pinfo->partial_update_enabled = of_property_read_bool(np, "qcom,partial-update-enabled"); pr_info("%s:%d Partial update %s\n", __func__, __LINE__, (pinfo->partial_update_enabled ? "enabled" : "disabled")); if (pinfo->partial_update_enabled) ctrl->partial_update_fnc = mdss_dsi_panel_partial_update; pinfo->ulps_feature_enabled = of_property_read_bool(np, "qcom,ulps-enabled"); pr_info("%s: ulps feature %s", __func__, (pinfo->ulps_feature_enabled ? "enabled" : "disabled")); return 0; } static int mdss_panel_parse_dt(struct device_node *np, struct mdss_dsi_ctrl_pdata *ctrl_pdata) { u32 tmp; int rc, i, len; const char *data; static const char *pdest; struct mdss_panel_info *pinfo = &(ctrl_pdata->panel_data.panel_info); rc = of_property_read_u32(np, "qcom,mdss-dsi-panel-width", &tmp); if (rc) { pr_err("%s:%d, panel width not specified\n", __func__, __LINE__); return -EINVAL; } pinfo->xres = (!rc ? tmp : 640); rc = of_property_read_u32(np, "qcom,mdss-dsi-panel-height", &tmp); if (rc) { pr_err("%s:%d, panel height not specified\n", __func__, __LINE__); return -EINVAL; } pinfo->yres = (!rc ? tmp : 480); rc = of_property_read_u32(np, "qcom,mdss-pan-physical-width-dimension", &tmp); pinfo->physical_width = (!rc ? tmp : 0); rc = of_property_read_u32(np, "qcom,mdss-pan-physical-height-dimension", &tmp); pinfo->physical_height = (!rc ? tmp : 0); rc = of_property_read_u32(np, "qcom,mdss-dsi-h-left-border", &tmp); pinfo->lcdc.xres_pad = (!rc ? tmp : 0); rc = of_property_read_u32(np, "qcom,mdss-dsi-h-right-border", &tmp); if (!rc) pinfo->lcdc.xres_pad += tmp; rc = of_property_read_u32(np, "qcom,mdss-dsi-v-top-border", &tmp); pinfo->lcdc.yres_pad = (!rc ? tmp : 0); rc = of_property_read_u32(np, "qcom,mdss-dsi-v-bottom-border", &tmp); if (!rc) pinfo->lcdc.yres_pad += tmp; rc = of_property_read_u32(np, "qcom,mdss-dsi-bpp", &tmp); if (rc) { pr_err("%s:%d, bpp not specified\n", __func__, __LINE__); return -EINVAL; } pinfo->bpp = (!rc ? tmp : 24); pinfo->mipi.mode = DSI_VIDEO_MODE; data = of_get_property(np, "qcom,mdss-dsi-panel-type", NULL); if (data && !strncmp(data, "dsi_cmd_mode", 12)) pinfo->mipi.mode = DSI_CMD_MODE; tmp = 0; data = of_get_property(np, "qcom,mdss-dsi-pixel-packing", NULL); if (data && !strcmp(data, "loose")) tmp = 1; rc = mdss_panel_dt_get_dst_fmt(pinfo->bpp, pinfo->mipi.mode, tmp, &(pinfo->mipi.dst_format)); if (rc) { pr_debug("%s: problem determining dst format. Set Default\n", __func__); pinfo->mipi.dst_format = DSI_VIDEO_DST_FORMAT_RGB888; } pdest = of_get_property(np, "qcom,mdss-dsi-panel-destination", NULL); if (pdest) { if (strlen(pdest) != 9) { pr_err("%s: Unknown pdest specified\n", __func__); return -EINVAL; } if (!strcmp(pdest, "display_1")) pinfo->pdest = DISPLAY_1; else if (!strcmp(pdest, "display_2")) pinfo->pdest = DISPLAY_2; else { pr_debug("%s: incorrect pdest. Set Default\n", __func__); pinfo->pdest = DISPLAY_1; } } else { pr_debug("%s: pdest not specified. Set Default\n", __func__); pinfo->pdest = DISPLAY_1; } rc = of_property_read_u32(np, "qcom,mdss-dsi-h-front-porch", &tmp); pinfo->lcdc.h_front_porch = (!rc ? tmp : 6); rc = of_property_read_u32(np, "qcom,mdss-dsi-h-back-porch", &tmp); pinfo->lcdc.h_back_porch = (!rc ? tmp : 6); rc = of_property_read_u32(np, "qcom,mdss-dsi-h-pulse-width", &tmp); pinfo->lcdc.h_pulse_width = (!rc ? tmp : 2); rc = of_property_read_u32(np, "qcom,mdss-dsi-h-sync-skew", &tmp); pinfo->lcdc.hsync_skew = (!rc ? tmp : 0); rc = of_property_read_u32(np, "qcom,mdss-dsi-v-back-porch", &tmp); pinfo->lcdc.v_back_porch = (!rc ? tmp : 6); rc = of_property_read_u32(np, "qcom,mdss-dsi-v-front-porch", &tmp); pinfo->lcdc.v_front_porch = (!rc ? tmp : 6); rc = of_property_read_u32(np, "qcom,mdss-dsi-v-pulse-width", &tmp); pinfo->lcdc.v_pulse_width = (!rc ? tmp : 2); rc = of_property_read_u32(np, "qcom,mdss-dsi-underflow-color", &tmp); pinfo->lcdc.underflow_clr = (!rc ? tmp : 0xff); rc = of_property_read_u32(np, "qcom,mdss-dsi-border-color", &tmp); pinfo->lcdc.border_clr = (!rc ? tmp : 0); pinfo->bklt_ctrl = UNKNOWN_CTRL; data = of_get_property(np, "qcom,mdss-dsi-bl-pmic-control-type", NULL); if (data) { if (!strncmp(data, "bl_ctrl_wled", 12)) { led_trigger_register_simple("bkl-trigger", &bl_led_trigger); pr_debug("%s: SUCCESS-> WLED TRIGGER register\n", __func__); ctrl_pdata->bklt_ctrl = BL_WLED; } else if (!strncmp(data, "bl_ctrl_pwm", 11)) { ctrl_pdata->bklt_ctrl = BL_PWM; rc = of_property_read_u32(np, "qcom,mdss-dsi-bl-pmic-pwm-frequency", &tmp); if (rc) { pr_err("%s:%d, Error, panel pwm_period\n", __func__, __LINE__); return -EINVAL; } ctrl_pdata->pwm_period = tmp; rc = of_property_read_u32(np, "qcom,mdss-dsi-bl-pmic-bank-select", &tmp); if (rc) { pr_err("%s:%d, Error, dsi lpg channel\n", __func__, __LINE__); return -EINVAL; } ctrl_pdata->pwm_lpg_chan = tmp; tmp = of_get_named_gpio(np, "qcom,mdss-dsi-pwm-gpio", 0); ctrl_pdata->pwm_pmic_gpio = tmp; } else if (!strncmp(data, "bl_ctrl_dcs", 11)) { ctrl_pdata->bklt_ctrl = BL_DCS_CMD; } } rc = of_property_read_u32(np, "qcom,mdss-brightness-max-level", &tmp); pinfo->brightness_max = (!rc ? tmp : MDSS_MAX_BL_BRIGHTNESS); rc = of_property_read_u32(np, "qcom,mdss-dsi-bl-min-level", &tmp); pinfo->bl_min = (!rc ? tmp : 0); rc = of_property_read_u32(np, "qcom,mdss-dsi-bl-max-level", &tmp); pinfo->bl_max = (!rc ? tmp : 255); ctrl_pdata->bklt_max = pinfo->bl_max; rc = of_property_read_u32(np, "qcom,mdss-dsi-interleave-mode", &tmp); pinfo->mipi.interleave_mode = (!rc ? tmp : 0); pinfo->mipi.vsync_enable = of_property_read_bool(np, "qcom,mdss-dsi-te-check-enable"); pinfo->mipi.hw_vsync_mode = of_property_read_bool(np, "qcom,mdss-dsi-te-using-te-pin"); rc = of_property_read_u32(np, "qcom,mdss-dsi-h-sync-pulse", &tmp); pinfo->mipi.pulse_mode_hsa_he = (!rc ? tmp : false); pinfo->mipi.hfp_power_stop = of_property_read_bool(np, "qcom,mdss-dsi-hfp-power-mode"); pinfo->mipi.hsa_power_stop = of_property_read_bool(np, "qcom,mdss-dsi-hsa-power-mode"); pinfo->mipi.hbp_power_stop = of_property_read_bool(np, "qcom,mdss-dsi-hbp-power-mode"); pinfo->mipi.bllp_power_stop = of_property_read_bool(np, "qcom,mdss-dsi-bllp-power-mode"); pinfo->mipi.eof_bllp_power_stop = of_property_read_bool( np, "qcom,mdss-dsi-bllp-eof-power-mode"); pinfo->mipi.traffic_mode = DSI_NON_BURST_SYNCH_PULSE; data = of_get_property(np, "qcom,mdss-dsi-traffic-mode", NULL); if (data) { if (!strcmp(data, "non_burst_sync_event")) pinfo->mipi.traffic_mode = DSI_NON_BURST_SYNCH_EVENT; else if (!strcmp(data, "burst_mode")) pinfo->mipi.traffic_mode = DSI_BURST_MODE; } rc = of_property_read_u32(np, "qcom,mdss-dsi-te-dcs-command", &tmp); pinfo->mipi.insert_dcs_cmd = (!rc ? tmp : 1); rc = of_property_read_u32(np, "qcom,mdss-dsi-wr-mem-continue", &tmp); pinfo->mipi.wr_mem_continue = (!rc ? tmp : 0x3c); rc = of_property_read_u32(np, "qcom,mdss-dsi-wr-mem-start", &tmp); pinfo->mipi.wr_mem_start = (!rc ? tmp : 0x2c); rc = of_property_read_u32(np, "qcom,mdss-dsi-te-pin-select", &tmp); pinfo->mipi.te_sel = (!rc ? tmp : 1); rc = of_property_read_u32(np, "qcom,mdss-dsi-virtual-channel-id", &tmp); pinfo->mipi.vc = (!rc ? tmp : 0); pinfo->mipi.rgb_swap = DSI_RGB_SWAP_RGB; data = of_get_property(np, "qcom,mdss-dsi-color-order", NULL); if (data) { if (!strcmp(data, "rgb_swap_rbg")) pinfo->mipi.rgb_swap = DSI_RGB_SWAP_RBG; else if (!strcmp(data, "rgb_swap_bgr")) pinfo->mipi.rgb_swap = DSI_RGB_SWAP_BGR; else if (!strcmp(data, "rgb_swap_brg")) pinfo->mipi.rgb_swap = DSI_RGB_SWAP_BRG; else if (!strcmp(data, "rgb_swap_grb")) pinfo->mipi.rgb_swap = DSI_RGB_SWAP_GRB; else if (!strcmp(data, "rgb_swap_gbr")) pinfo->mipi.rgb_swap = DSI_RGB_SWAP_GBR; } pinfo->mipi.data_lane0 = of_property_read_bool(np, "qcom,mdss-dsi-lane-0-state"); pinfo->mipi.data_lane1 = of_property_read_bool(np, "qcom,mdss-dsi-lane-1-state"); pinfo->mipi.data_lane2 = of_property_read_bool(np, "qcom,mdss-dsi-lane-2-state"); pinfo->mipi.data_lane3 = of_property_read_bool(np, "qcom,mdss-dsi-lane-3-state"); rc = of_property_read_u32(np, "qcom,mdss-dsi-t-clk-pre", &tmp); pinfo->mipi.t_clk_pre = (!rc ? tmp : 0x24); rc = of_property_read_u32(np, "qcom,mdss-dsi-t-clk-post", &tmp); pinfo->mipi.t_clk_post = (!rc ? tmp : 0x03); pinfo->mipi.rx_eot_ignore = of_property_read_bool(np, "qcom,mdss-dsi-rx-eot-ignore"); pinfo->mipi.tx_eot_append = of_property_read_bool(np, "qcom,mdss-dsi-tx-eot-append"); rc = of_property_read_u32(np, "qcom,mdss-dsi-stream", &tmp); pinfo->mipi.stream = (!rc ? tmp : 0); data = of_get_property(np, "qcom,mdss-dsi-panel-mode-gpio-state", NULL); if (data) { if (!strcmp(data, "high")) pinfo->mode_gpio_state = MODE_GPIO_HIGH; else if (!strcmp(data, "low")) pinfo->mode_gpio_state = MODE_GPIO_LOW; } else { pinfo->mode_gpio_state = MODE_GPIO_NOT_VALID; } rc = of_property_read_u32(np, "qcom,mdss-dsi-panel-framerate", &tmp); pinfo->mipi.frame_rate = (!rc ? tmp : 60); rc = of_property_read_u32(np, "qcom,mdss-dsi-panel-clockrate", &tmp); pinfo->clk_rate = (!rc ? tmp : 0); data = of_get_property(np, "qcom,mdss-dsi-panel-timings", &len); if ((!data) || (len != 12)) { pr_err("%s:%d, Unable to read Phy timing settings", __func__, __LINE__); goto error; } for (i = 0; i < len; i++) pinfo->mipi.dsi_phy_db.timing[i] = data[i]; pinfo->mipi.lp11_init = of_property_read_bool(np, "qcom,mdss-dsi-lp11-init"); rc = of_property_read_u32(np, "qcom,mdss-dsi-init-delay-us", &tmp); pinfo->mipi.init_delay = (!rc ? tmp : 0); mdss_dsi_parse_roi_alignment(np, pinfo); mdss_dsi_parse_trigger(np, &(pinfo->mipi.mdp_trigger), "qcom,mdss-dsi-mdp-trigger"); mdss_dsi_parse_trigger(np, &(pinfo->mipi.dma_trigger), "qcom,mdss-dsi-dma-trigger"); mdss_dsi_parse_lane_swap(np, &(pinfo->mipi.dlane_swap)); mdss_dsi_parse_fbc_params(np, pinfo); mdss_panel_parse_te_params(np, pinfo); mdss_dsi_parse_reset_seq(np, pinfo->rst_seq, &(pinfo->rst_seq_len), "qcom,mdss-dsi-reset-sequence"); mdss_dsi_parse_dcs_cmds(np, &ctrl_pdata->on_cmds, "qcom,mdss-dsi-on-command", "qcom,mdss-dsi-on-command-state"); mdss_dsi_parse_dcs_cmds(np, &ctrl_pdata->off_cmds, "qcom,mdss-dsi-off-command", "qcom,mdss-dsi-off-command-state"); rc = mdss_dsi_parse_panel_features(np, ctrl_pdata); if (rc) { pr_err("%s: failed to parse panel features\n", __func__); goto error; } return 0; error: return -EINVAL; } int mdss_dsi_panel_init(struct device_node *node, struct mdss_dsi_ctrl_pdata *ctrl_pdata, bool cmd_cfg_cont_splash) { int rc = 0; static const char *panel_name; struct mdss_panel_info *pinfo; if (!node || !ctrl_pdata) { pr_err("%s: Invalid arguments\n", __func__); return -ENODEV; } pinfo = &ctrl_pdata->panel_data.panel_info; pr_debug("%s:%d\n", __func__, __LINE__); panel_name = of_get_property(node, "qcom,mdss-dsi-panel-name", NULL); if (!panel_name) pr_info("%s:%d, Panel name not specified\n", __func__, __LINE__); else pr_info("%s: Panel Name = %s\n", __func__, panel_name); rc = mdss_panel_parse_dt(node, ctrl_pdata); if (rc) { pr_err("%s:%d panel dt parse failed\n", __func__, __LINE__); return rc; } if (!cmd_cfg_cont_splash) pinfo->cont_splash_enabled = false; pr_info("%s: Continuous splash %s", __func__, pinfo->cont_splash_enabled ? "enabled" : "disabled"); ctrl_pdata->on = mdss_dsi_panel_on; ctrl_pdata->off = mdss_dsi_panel_off; ctrl_pdata->panel_data.set_backlight = mdss_dsi_panel_bl_ctrl; return 0; }
felipeizzo/sprat
drivers/video/msm/mdss/mdss_dsi_panel.c
C
gpl-2.0
32,975
# Install script for directory: /home/carlo/Dropbox/workspace/KDiamond/themes # Set the install prefix IF(NOT DEFINED CMAKE_INSTALL_PREFIX) SET(CMAKE_INSTALL_PREFIX "/usr/local") ENDIF(NOT DEFINED CMAKE_INSTALL_PREFIX) STRING(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") # Set the install configuration name. IF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) IF(BUILD_TYPE) STRING(REGEX REPLACE "^[^A-Za-z0-9_]+" "" CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}") ELSE(BUILD_TYPE) SET(CMAKE_INSTALL_CONFIG_NAME "RelWithDebInfo") ENDIF(BUILD_TYPE) MESSAGE(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"") ENDIF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) # Set the component getting installed. IF(NOT CMAKE_INSTALL_COMPONENT) IF(COMPONENT) MESSAGE(STATUS "Install component: \"${COMPONENT}\"") SET(CMAKE_INSTALL_COMPONENT "${COMPONENT}") ELSE(COMPONENT) SET(CMAKE_INSTALL_COMPONENT) ENDIF(COMPONENT) ENDIF(NOT CMAKE_INSTALL_COMPONENT) # Install shared libraries without execute permission? IF(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE) SET(CMAKE_INSTALL_SO_NO_EXE "1") ENDIF(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE) IF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified") list(APPEND CMAKE_ABSOLUTE_DESTINATION_FILES "/usr/local/share/apps/kdiamond/themes/diamonds.desktop;/usr/local/share/apps/kdiamond/themes/diamonds.svgz;/usr/local/share/apps/kdiamond/themes/diamonds.png;/usr/local/share/apps/kdiamond/themes/funny_zoo.desktop;/usr/local/share/apps/kdiamond/themes/funny_zoo.svgz;/usr/local/share/apps/kdiamond/themes/funny_zoo.png;/usr/local/share/apps/kdiamond/themes/default.desktop;/usr/local/share/apps/kdiamond/themes/egyptian.svgz;/usr/local/share/apps/kdiamond/themes/egyptian_preview.png") IF (CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION) message(WARNING "ABSOLUTE path INSTALL DESTINATION : ${CMAKE_ABSOLUTE_DESTINATION_FILES}") ENDIF (CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION) IF (CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION) message(FATAL_ERROR "ABSOLUTE path INSTALL DESTINATION forbidden (by caller): ${CMAKE_ABSOLUTE_DESTINATION_FILES}") ENDIF (CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION) FILE(INSTALL DESTINATION "/usr/local/share/apps/kdiamond/themes" TYPE FILE FILES "/home/carlo/Dropbox/workspace/KDiamond/themes/diamonds.desktop" "/home/carlo/Dropbox/workspace/KDiamond/themes/diamonds.svgz" "/home/carlo/Dropbox/workspace/KDiamond/themes/diamonds.png" "/home/carlo/Dropbox/workspace/KDiamond/themes/funny_zoo.desktop" "/home/carlo/Dropbox/workspace/KDiamond/themes/funny_zoo.svgz" "/home/carlo/Dropbox/workspace/KDiamond/themes/funny_zoo.png" "/home/carlo/Dropbox/workspace/KDiamond/themes/default.desktop" "/home/carlo/Dropbox/workspace/KDiamond/themes/egyptian.svgz" "/home/carlo/Dropbox/workspace/KDiamond/themes/egyptian_preview.png" ) ENDIF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
CarloLucibello/KDiamante
themes/cmake_install.cmake
CMake
gpl-2.0
3,018
/* * xensetup.c * * Copyright (C) 2008-2011 Samsung Electronics * Sang-bum Suh <sbuk.suh@samsung.com> * JooYoung Hwang <jooyoung.hwang@samsung.com> * Jaemin Ryu <jm77.ryu@samsung.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public version 2 of 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <xen/config.h> #include <xen/init.h> #include <xen/sched.h> #include <xen/mm.h> #include <xen/compile.h> #include <xen/string.h> #include <xen/lib.h> #include <xen/preempt.h> #include <public/version.h> #include <public/sched.h> #include <security/acm/policy_conductor.h> #include <security/acm/acm_hooks.h> #include <security/ssm-xen/sra_func.h> #include <asm/core.h> #include <asm/mmu.h> #include <asm/memmap.h> #include <asm/trap.h> #include <asm/memory.h> #include <asm/uaccess.h> #include <asm/cpu-ops.h> #include <asm/platform.h> #ifdef CONFIG_GCOV_XEN #include <xen/gcov.h> #endif #define DOM_CREATE_SUCCESS 1 #define DOM_CREATE_FAIL 0 #define BANNER "\n\rXen/ARM virtual machine monitor for %s\n\r" \ "Copyright (C) 2007 Samsung Electronics Co, Ltd. All Rights Reserved.\n" \ struct domain *idle_domain; struct domain dom_xen = { .refcnt = 1, .domain_id = DOMID_XEN, .big_lock = SPIN_LOCK_UNLOCKED, .page_alloc_lock = SPIN_LOCK_UNLOCKED, }; struct domain dom_io = { .refcnt = 1, .domain_id = DOMID_IO, .big_lock = SPIN_LOCK_UNLOCKED, .page_alloc_lock = SPIN_LOCK_UNLOCKED, }; struct meminfo system_memory = {0,}; unsigned long xenheap_phys_start; unsigned long xenheap_phys_end; struct domain_partition { unsigned long guest_memory_start; unsigned long guest_memory_size; unsigned long elf_image_address; unsigned long elf_image_size; unsigned long initrd_address; unsigned long initrd_size; unsigned long command_line_address; unsigned long stack_start; }; struct domain_partition domain_partitions[4]= { { MEMMAP_GUEST0_PARTITION_BASE, MEMMAP_GUEST0_PARTITION_SIZE, MEMMAP_GUEST0_IMAGE_BASE, MEMMAP_GUEST0_IMAGE_SIZE, 0, 0, 0, 0 }, { MEMMAP_GUEST1_PARTITION_BASE, MEMMAP_GUEST1_PARTITION_SIZE, MEMMAP_GUEST1_IMAGE_BASE, MEMMAP_GUEST1_IMAGE_SIZE, 0, 0, 0, 0 }, { MEMMAP_GUEST2_PARTITION_BASE, MEMMAP_GUEST2_PARTITION_SIZE, MEMMAP_GUEST2_IMAGE_BASE, MEMMAP_GUEST2_IMAGE_SIZE, 0, 0, 0, 0 }, { MEMMAP_GUEST3_PARTITION_BASE, MEMMAP_GUEST3_PARTITION_SIZE, MEMMAP_GUEST3_IMAGE_BASE, MEMMAP_GUEST3_IMAGE_SIZE, 0, 0, 0, 0 }, }; pte_t __attribute__((__section__(".bss.page_aligned"))) page_table[1024]; pte_t *exception_table_vector = &page_table[0]; pte_t *shared_info_vector = &page_table[256]; pte_t *mapcache_table_vector = &page_table[512]; static void prepare_console(void) { init_console(); } static void prepare_subsystems(void) { initcall_t *call; for ( call = &__initcall_start; call < &__initcall_end; call++ ) { (*call)(); } } void arch_get_xen_caps(xen_capabilities_info_t info) { char *p = info; p += snprintf(p, sizeof(32), "xen-%d.%d-arm ", XEN_VERSION, XEN_SUBVERSION); *(p-1) = 0; BUG_ON((p - info) > sizeof(xen_capabilities_info_t)); } static unsigned long find_lowest_pfn(struct meminfo *mi) { int i; unsigned long start = 0xFFFFFFFF; for(i = 0; i < mi->nr_banks; i++) { struct memory_bank *bank = &mi->banks[i]; if(bank->base < start) { start = bank->base; } } return start >> PAGE_SHIFT; } static unsigned long find_highest_pfn(struct meminfo *mi) { int i; unsigned long end = 0; for(i = 0; i < mi->nr_banks; i++) { struct memory_bank *bank = &mi->banks[i]; if(end < bank->base + bank->size) { end = bank->base + bank->size; } } return end >> PAGE_SHIFT; } static void prepare_allocator() { unsigned long nr_pages = 0; unsigned long i, s, e; unsigned long xen_pstart; unsigned long xen_pend; /* * Memory holes will be reserved during * init_boot_pages(). */ min_page = find_lowest_pfn(&system_memory); max_page = find_highest_pfn(&system_memory); xen_pstart = min_page << PAGE_SHIFT; xen_pend = max_page << PAGE_SHIFT; /* * | Xen Heap | * +------------------+ _end * | frame table | * +------------------+ * | bss section | * +------------------+ * | data section | * +------------------+ * | code section | * +------------------+ 0xFF008000 * | root trans table | */ /* Initialise boot-time allocator with all RAM situated after modules. */ frame_table = (struct page_info *)(round_pgup(((unsigned long)(&_end)))); nr_pages = PFN_UP((max_page - min_page) * sizeof(struct page_info)); memset(frame_table, 0, nr_pages << PAGE_SHIFT); xenheap_phys_start = init_boot_allocator(va_to_ma(frame_table) + (nr_pages << PAGE_SHIFT)); xenheap_phys_end = xenheap_phys_start + MEMMAP_HYPERVISOR_SIZE; /* Initialise the DOM heap, skipping RAM holes. */ nr_pages = 0; for ( i = 0; i < system_memory.nr_banks; i++ ) { nr_pages += system_memory.banks[i].size >> PAGE_SHIFT; /* Initialise boot heap, skipping Xen heap and dom0 modules. */ s = system_memory.banks[i].base; e = s + system_memory.banks[i].size; #if 0 if ( s < xenheap_phys_end ) s = xenheap_phys_end; if( e > xen_pend ) e = xen_pend; #else if ( s < (min_page << PAGE_SHIFT)) s = (min_page << PAGE_SHIFT); if ( e > MEMMAP_HYPERVISOR_BASE) e = MEMMAP_HYPERVISOR_BASE; #endif init_boot_pages(s, e); } total_pages = nr_pages; end_boot_allocator(); /* Initialise the Xen heap, skipping RAM holes. */ nr_pages = 0; for ( i = 0; i < system_memory.nr_banks; i++ ) { s = system_memory.banks[i].base; e = s + system_memory.banks[i].size; if ( s < xenheap_phys_start ) s = xenheap_phys_start; if ( e > xenheap_phys_end ) e = xenheap_phys_end; if ( s < e ) { nr_pages += (e - s) >> PAGE_SHIFT; init_xenheap_pages(s, e); } } } static void prepare_page_tables(void) { int idx; pde_t *pgd; /* Get translation table base */ pgd = (pde_t *)(ma_to_va(get_ttbr() & TTB_MASK)); /* Link page table for exception vectors table */ idx = PGD_IDX(VECTORS_BASE); pgd[idx] = MK_PDE(va_to_ma(&page_table[0]), PDE_VECTOR_TABLE); pte_sync(&pgd[idx]); /* Link page table for shared_info array */ idx = PGD_IDX(SHARED_INFO_BASE); pgd[idx] = MK_PDE(va_to_ma(&page_table[256]), PDE_GUEST_TABLE); pte_sync(&pgd[idx]); /* Link mapcache table for shared_info array */ idx = PGD_IDX(MAPCACHE_VIRT_START); pgd[idx] = MK_PDE(va_to_ma(&page_table[512]), PDE_GUEST_TABLE); pte_sync(&pgd[idx]); } /* * All platform-speficif initialization should be completed before start_xen() * */ asmlinkage void start_xen(struct platform *platform) { unsigned int boot_cpu; boot_cpu = smp_processor_id(); prepare_boot_cpu(boot_cpu); prepare_page_tables(); trap_init(); prepare_console(); printk(BANNER, platform->name); prepare_allocator(); sort_extables(); #if CONFIG_GCOV_XEN gcov_core_init(); #endif #ifdef CONFIG_VMM_SECURITY if ( sra_init() != 0 ) PANIC("Error Secure Repository Agent initialization\n"); #endif timer_init(); init_acm(); prepare_subsystems(); #ifdef UNIT_TEST /* Unit Test Example */ embunit_test_example(); #endif scheduler_init(); idle_domain = domain_create(IDLE_DOMAIN_ID, 0); BUG_ON(idle_domain == NULL); set_current(idle_domain->vcpu[0]); idle_domain->vcpu[0]->arch.ctx.ttbr0 = (get_ttbr() & TTB_MASK); local_irq_enable(); local_fiq_enable(); #ifdef CONFIG_SMP smp_prepare_cpus(NR_CPUS); #endif dom0 = domain_create(0, 0); BUG_ON(dom0 == NULL); if ( construct_domain(dom0, domain_partitions[0].guest_memory_start, domain_partitions[0].guest_memory_size, domain_partitions[0].elf_image_address, domain_partitions[0].elf_image_size, domain_partitions[0].initrd_address, domain_partitions[0].initrd_size, NULL) != 0) { PANIC("Could not set up DOM0 guest OS\n"); } domain_unpause_by_systemcontroller(dom0); start_idle_loop(); } int get_guest_domain_address( dom0_op_t * dom0_op) { unsigned int domain_id; unsigned int ret=0; dom0_op_t * op = dom0_op; domain_id = op->u.guest_image_info.domain; /* return guest domain loading physical address */ op->u.guest_image_info.guest_image_address = domain_partitions[domain_id].elf_image_address; op->u.guest_image_info.guest_image_size = domain_partitions[domain_id].elf_image_size; return ret; } int create_guest_domain( dom0_op_t * dom0_op ) { unsigned int domain_id; unsigned long guest_va; struct domain *dom; domain_id = dom0_op->u.guest_image_info.domain; guest_va = dom0_op->u.guest_image_info.guest_image_address; dom = find_domain_by_id(domain_id); if ( dom == NULL ) { PANIC("Could not find the domain structure for DOM guest OS\n"); return DOM_CREATE_FAIL; } dom->store_port = dom0_op->u.guest_image_info.store_port; dom->console_port = dom0_op->u.guest_image_info.console_port; if ( construct_domain( dom, domain_partitions[domain_id].guest_memory_start, domain_partitions[domain_id].guest_memory_size, domain_partitions[domain_id].elf_image_address, domain_partitions[domain_id].elf_image_size, domain_partitions[domain_id].initrd_address, domain_partitions[domain_id].initrd_size, NULL) != 0) // stack start { put_domain(dom); PANIC("Could not set up DOM1 guest OS\n"); return DOM_CREATE_FAIL; } dom0_op->u.guest_image_info.store_mfn = dom->store_mfn; dom0_op->u.guest_image_info.console_mfn = dom->console_mfn; printk("store mfn = 0x%x\n", dom->store_mfn); printk("console mfn = 0x%x\n", dom->console_mfn); put_domain(dom); return DOM_CREATE_SUCCESS; }
ryos36/xen-arm
xen/arch/arm/xen/xensetup.c
C
gpl-2.0
10,208
/* gsm-util.h * Copyright (C) 2008 Lucas Rocha. * * 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 * Lesser 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. */ #ifndef __GSM_UTIL_H__ #define __GSM_UTIL_H__ #include <glib.h> #ifdef __cplusplus extern "C" { #endif #define IS_STRING_EMPTY(x) ((x)==NULL||(x)[0]=='\0') char * gsm_util_find_desktop_file_for_app_name (const char *app_name, char **dirs); gchar *gsm_util_get_empty_tmp_session_dir (void); const char *gsm_util_get_saved_session_dir (void); gchar** gsm_util_get_app_dirs (void); gchar** gsm_util_get_autostart_dirs (void); gchar ** gsm_util_get_desktop_dirs (void); gboolean gsm_util_text_is_blank (const char *str); void gsm_util_init_error (gboolean fatal, const char *format, ...); char * gsm_util_generate_startup_id (void); void gsm_util_setenv (const char *variable, const char *value); #ifdef __cplusplus } #endif #endif /* __GSM_UTIL_H__ */
dnk/mate-session-manager
mate-session/gsm-util.h
C
gpl-2.0
1,886
<?php /** * @package HikaShop for Joomla! * @version 2.3.1 * @author hikashop.com * @copyright (C) 2010-2014 HIKARI SOFTWARE. All rights reserved. * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ defined('_JEXEC') or die('Restricted access'); ?><div class="hikashop_googlecheckout_end" id="hikashop_googlecheckout_end"> <span id="hikashop_googlecheckout_end_message" class="hikashop_googlecheckout_end_message"> <?php echo JText::sprintf('PLEASE_WAIT_BEFORE_REDIRECTION_TO_X',$this->payment_name).'<br/>'. JText::_('CLICK_ON_BUTTON_IF_NOT_REDIRECTED');?> </span> <span id="hikashop_googlecheckout_end_spinner" class="hikashop_googlecheckout_end_spinner"> <img src="<?php echo HIKASHOP_IMAGES.'spinner.gif';?>" /> </span> <br/> <form id="hikashop_googlecheckout_form" name="hikashop_googlecheckout_form" action="<?php echo $this->url; ?>" method="post"> <div id="hikashop_googlecheckout_end_image" class="hikashop_googlecheckout_end_image"> <input id="hikashop_googlecheckout_button" type="submit" class="btn btn-primary" value="<?php echo JText::_('PAY_NOW');?>" name="" alt="<?php echo JText::_('PAY_NOW');?>" /> </div> <?php foreach( $this->vars as $name => $value ) { echo '<input type="hidden" name="'.$name.'" value="'.htmlspecialchars((string)$value).'" />'; } $doc = JFactory::getDocument(); $doc->addScriptDeclaration("window.addEvent('domready', function() {document.getElementById('hikashop_googlecheckout_form').submit();});"); JRequest::setVar('noform',1); ?> </form> </div>
Jbouska419/craftsman
plugins/hikashoppayment/googlecheckout/googlecheckout_end.php
PHP
gpl-2.0
1,550
<?php /** * Laravel - A PHP Framework For Web Artisans * * @package Laravel * @author Taylor Otwell <taylorotwell@gmail.com> */ /* |-------------------------------------------------------------------------- | Register The Auto Loader |-------------------------------------------------------------------------- | | Composer provides a convenient, automatically generated class loader for | our application. We just need to utilize it! We'll simply require it | into the script here so that we don't have to worry about manual | loading any of our classes later on. It feels nice to relax. | */ require __DIR__.'/laraRoot/bootstrap/autoload.php'; /* |-------------------------------------------------------------------------- | Turn On The Lights |-------------------------------------------------------------------------- | | We need to illuminate PHP development, so let us turn on the lights. | This bootstraps the framework and gets it ready for use, then it | will load up this application so that we can run it and send | the responses back to the browser and delight our users. | */ $app = require_once __DIR__.'/laraRoot/bootstrap/app.php'; /* |-------------------------------------------------------------------------- | Run The Application |-------------------------------------------------------------------------- | | Once we have the application, we can handle the incoming request | through the kernel, and send the associated response back to | the client's browser allowing them to enjoy the creative | and wonderful application we have prepared for them. | */ $kernel = $app->make(Illuminate\Contracts\Http\Kernel::class); $response = $kernel->handle( $request = Illuminate\Http\Request::capture() ); $response->send(); $kernel->terminate($request, $response);
popohum/Earths-Best
index.php
PHP
gpl-2.0
1,798